@appetize/cli 0.18.0 → 0.19.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 +7 -0
- package/cli.js +10 -3
- package/config-D0ukqfLN.js +3 -0
- package/daemon.js +2 -2
- package/package.json +4 -3
- package/skills/appetize/SKILL.md +10 -6
- package/skills/appetize/references/commands.md +37 -21
- package/viewer.html +1 -1
- package/config-CmsJj7_W.js +0 -2
package/CHANGELOG.md
CHANGED
package/cli.js
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`}const yt=async({device:e,positionals:[t]})=>(await e.open(vt(t)),{opened:!0});function vt(e){if(typeof e=="string")try{return new URL(e),e}catch{throw new Error("<url> expects a URL, e.g., myapp://orders/42")}throw new Error("<url> expects a URL, e.g., myapp://orders/42")}const xt=new Set(J),St=async({device:e,positionals:[t]})=>{if(!Et(t))throw new Error(`Button must be one of: ${J.join(", ")}`);return await e.press(t),{pressed:!0}};function Et(e){return typeof e=="string"&&xt.has(e)}const bt=async({control:e,options:t,positionals:[o]})=>{const{path:n}=await e.recordStart({force:t.force===!0,path:It(o)});return{path:n,recording:!0}},Ot=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t,recording:!1}};function It(e){const t=q(T(e,{extension:".mp4",strict:!0})),o=Ce(t);if(!G(o))throw new Error(`No such directory: ${o}`);return t}const ce={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},Pt=async({device:e,positionals:[t]})=>{if(!$t(t))throw new Error(`Orientation must be one of: ${Object.keys(ce).join(", ")}`);return await e.rotate(t)};function $t(e){return typeof e=="string"&&Object.hasOwn(ce,e)}const At=async({device:e,positionals:[t]})=>{const o=await e.screenshot(),n=Lt(o.mimeType,t);return await X(n,o.data),{bytes:o.data.byteLength,mimeType:o.mimeType,output:n}};function Tt(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function Lt(e,t="screenshot"){return T(t,{extension:Tt(e)})}function Nt(e){const t=Z(new URL("./daemon.js",import.meta.url)),o=ze(be(e.sessionId),"a"),n=qe(process.execPath,[t],{detached:!0,env:{...process.env,[Oe]:Ie(e),DEBUG:kt(process.env.DEBUG)},stdio:["ignore",o,o]});if(Fe(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 Dt=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function _t(){return Xe({capitalize:!1,separator:"-"})}function Rt(e){if(!Dt.test(e))throw new Error('--session-id must use letters, digits, ".", "-" or "_"');return e}const Ut=["device-os-version","open","proxy"],zt=150;async function Ft(e,{onPhase:t,signal:o}){let n;for(;;){const i=B(e),r=i?.state?.phase;if(r&&r!==n&&(n=r,t?.(r)),i&&r==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(r==="error")throw new Error(i?.endedReason??"The session failed to start");if(r==="ended")throw new Error(i?.endedReason??"The session ended");await C(zt,o)}}function jt(e){const t=f(e,"--open");if(t!==void 0){try{new URL(t)}catch{throw new Error("--open expects a URL, e.g., myapp://orders/42")}return t}}function Ct(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Bt(e))throw new Error("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function Mt({options:e,positionals:[t,o],signal:n}){const i=f(e["device-os-version"],"--device-os-version"),r=f(e["session-id"],"--session-id"),s=r===void 0?_t():Rt(r);if(B(s)!==void 0)throw new Error(`Session ${s} already exists`);const x={device:i===void 0?{id:t}:{id:t,osVersion:i},endpoint:$e(e),featureFlags:Pe(),open:jt(e.open),proxy:Ct(e.proxy),sessionId:s,target:o};Nt(x),console.error(`session started with id: ${s}`);const m=Ae(s,x.proxy);if(e.wait===!1)return{logs:m,sessionId:s};const S=await Ft(s,{onPhase:ge=>{console.error(ge)},signal:n});return{adbSerial:S.adbSerial,baseUrl:S.baseUrl,controlSocket:S.controlSocket,logs:m,sessionId:s,viewerUrl:S.viewerUrl}}function Bt(e){return e.startsWith("http://")}const Gt=async({record:{pid:e,sessionId:t}})=>(Te(e)&&process.kill(e,"SIGTERM"),{ended:!0,sessionId:t}),pe="appetize",Kt=Z(new URL(`./skills/${pe}/`,import.meta.url)),U=["agents","claude","codex","copilot","cursor"],de=["project","user"],qt={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},Xt=w(".agents","skills"),Zt=["claude","agents"];function Vt(e){return U.some(t=>t===e)}function Wt(e){return de.some(t=>t===e)}async function Jt(e){const t=e.agents??await Ht(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,Xt);return t.scope==="project"?[n]:await me(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 q(o)}return w(t.root,qt[e])}async function Ht(e){const o=(await Promise.all(U.map(async n=>await Yt(n,e)?n:void 0))).filter(n=>n!==void 0);return o.length>0?o:Zt}async function Yt(e,t){const o=[ue(e,t),...await le(e,t)];return(await Promise.all(o.map(i=>me(i)))).includes(!0)}async function me(e){try{return(await Be(e)).isDirectory()}catch{return!1}}const Qt=["agent","scope"];async function eo({options:e,signal:t}){const o=no(e.scope),n=oo(e.agent),i=o==="user"?Ze():process.cwd(),r=await Jt({agents:n,root:i,scope:o}),s=[];for(const x of r){t.throwIfAborted();const m=w(x,pe);await Ge(m,{force:!0,recursive:!0}),await Ke(Kt,m,{recursive:!0}),s.push(o==="user"?m:Me(i,m))}return{installed:s}}function to(e){const t=E(e,"--agent");if(!Vt(t))throw new Error(`--agent expects one of ${U.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=E(e,"--scope");if(!Wt(t))throw new Error(`--scope expects one of ${de.join(", ")}`);return t}const d="from",l="to",io=[..._({prefix:d}),..._({prefix:l})],ro=async({device:e,options:t})=>(await e.swipe(po(t),uo(t)),{swiped:!0});function so(e){return $.some(t=>t===e)}function ao(e){if(e===void 0)return;const t=E(e,"--direction");if(!so(t))throw new Error(`--direction expects one of ${$.join(", ")}`);return t}function co(e,t){const o=Le(e.distance,"--distance");if(O(e,{prefix:l})!==void 0)throw new Error(`--direction may not be combined with --${l}-*`);return{direction:t,distance:o,from:O(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:fe(O(e,{prefix:d}),d),to:fe(O(e,{prefix:l}),l)}}function uo(e){const t=c(e.duration,"--duration"),o=c(e.timeout,"--timeout");return t===void 0&&o===void 0?void 0:{duration:t,timeout:o}}function fe(e,t){if(e===void 0)throw new Error(`A swipe needs --direction, or both endpoints: pass one of ${v({prefix:t})}`);return e}const mo=_(),fo=async({device:e,options:t})=>{const o=oe(t);return await e.tap(o,te(t)),{tapped:!0}},wo=async({device:e,options:t,positionals:[o]})=>(await e.type(o,ho(t)),{typed:!0});function ho(e){const t=c(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 j(e.controlSocket,{signal:t}),{client:n}=Ne(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 vo(e){return async({options:t,positionals:o,signal:n})=>{const i=t["session-id"],r=ke(typeof i=="string"?i:void 0);return await e({options:t,positionals:o,record:r,signal:AbortSignal.any([n,De(r.pid)])})}}function xo(e){return async({options:t,positionals:o,record:n,signal:i})=>{const r=await go(n,i);try{return await e({device:r,options:t,positionals:o,signal:i})}finally{r.close()}}}function So(e){return async({options:t,positionals:o,record:n,signal:i})=>{const r=await yo(n,i);try{return await e({control:r,options:t,positionals:o,signal:i})}finally{r.close()}}}const Eo=["session-id",...Je,...Qe,...at,...ft,...Qt,...Ut,...io,...mo],bo=["json"];function Oo(e){const t=ye("appetize").version(e).option("--json","Print the result as JSON");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("--open","URL opened once the session is 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").example("session start iphone15pro app_a1b2c3 --open myapp://orders/42"),Mt),F(t.command("session stop").describe("Stop a running device session"),Gt),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 (${A.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(Y)})`).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"),ct),u(t.command("press <button>").describe(`Press a device button: ${W.join(", ")}; Android only: ${V.join(", ")}`).example("press home").example("press volumeUp"),St),u(t.command("rotate <orientation>").describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),Pt),u(t.command("open <url>").describe("Open a URL or deep link on the device").example("open myapp://orders/42").example("open https://example.com"),yt),u(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),u(D(t.command("tap").describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${v()}`])).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),u(D(D(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 --${l}-* point to form a path`,"",`Pick one per point: ${v({prefix:d})}`,` ${v({prefix:l})}`]).option("--direction",`Direction to travel: ${$.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:d}),{prefix:l}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${d}/--${l} 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"),ro),u(Q(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"),wt),u(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"),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"),vo(t))}function u(e,t){return F(e,xo(t))}function we(e,t){return F(e,So(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{const n=await e(Re(t));n!==void 0&&process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
4
|
-
`),
|
|
2
|
+
import Ue from"sade";import{d as X,D as je,p as v,a as m,f as L,U as c,b as V,c as ze,i as Fe,e as Ce,r as H,g as k,h as Me,j as Be,s as qe,k as J,l as Ge,m as Ke,n as Ze,S as Y,o as Q,q as We,t as Xe,u as ee,v as Ve,w as He,x as Je,y as Ye,z as Qe,A as et}from"./config-D0ukqfLN.js";import{existsSync as te,openAsBlob as tt,openSync as nt,closeSync as ot}from"node:fs";import{basename as D,extname as it,resolve as ne,dirname as rt,join as S,relative as st}from"node:path";import{writeFile as oe,stat as at,rm as ct,cp as pt}from"node:fs/promises";import{spawn as dt}from"node:child_process";import{fileURLToPath as ie}from"node:url";import{humanId as lt}from"human-id";import{homedir as ut}from"node:os";import ft from"debug";import mt from"yocto-spinner";import ht from"cli-table3";import"stream";import"module";import"node:net";import"json-rpc-2.0";const re=["back","menu","unlock","volumeDown","volumeUp"],se=["home","lock"],ae=[...se,...re],N=["down","left","right","up"];async function wt(e,t={}){const n=await X(e,{signal:t.signal});return new je(n,{...t,onClose:()=>{n.close(),t.onClose?.()}})}const ce=[{header:"Target",key:"id"},{header:"App",key:"appId"},{header:"Platform",key:"platform"},{header:"Version",key:"versionName"},{header:"Build",key:"buildNumber"},{header:"Uploaded",key:"created"}];function _({appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:r}){return{appId:e,buildNumber:t,created:n,id:o,platform:i,versionName:r}}const gt=["app"],yt=10,vt=[{fields:ce,key:"builds"},{header:"Total",key:"total"},{header:"Next page",key:"nextPage"}];async function St({options:e,signal:t}){const n=v(e.app,"--app"),o=m(e.limit,"--limit")??yt,i=m(e.page,"--page"),r={limit:String(o)};n!==void 0&&(r.appId=n),i!==void 0&&(r.page=String(i));const s=await L("/api/v2/builds",{commandOptions:e,query:r,signal:t});return{builds:s.builds.map(_),nextPage:s.nextPage,total:s.total}}const bt=["note","tags"],pe=12e4,xt=2e3,R=[".apk",".apks",".zip",".tar.gz",".tgz"],Et={".apk":"android",".apks":"android",".tar.gz":"ios",".tgz":"ios",".zip":"ios"},Ot=ce;async function kt({options:e,positionals:[t],progress:n,signal:o}){const i=$t(t),r=D(t);n.status(`Uploading ${r}`);const s=await At(t,i,e,o);if(e.wait!==!0)return n.status(`Uploaded ${r}`),_(s);n.step(`Uploaded ${r}`),n.status("Waiting for build metadata");const a=await Pt(s.id,e,o);return n.status(`Processed ${r}`),_(a)}async function Pt(e,t,n){const o=m(t.timeout,"--timeout")??pe,i=Date.now()+o;for(;;){const r=await L(`/api/v2/builds/${e}`,{commandOptions:t,signal:n});if(r.appId!==void 0)return r;if(Date.now()>=i)throw new Error(`Build ${e} is still being processed after ${String(o)}ms; find it with 'appetize build list'`);await V(xt,n)}}async function It(e){if(!te(e))throw new Error(`No build file at ${e}`);return await tt(e)}function $t(e){const t=e.toLowerCase(),n=R.find(o=>t.endsWith(o));if(n===void 0)throw new c(`Cannot tell the platform of ${D(e)}; upload a ${R.join(", ")} file`);return Et[n]}async function At(e,t,n,o){const i=new FormData;i.set("platform",t);const r=v(n.note,"--note");r!==void 0&&i.set("note",r);const s=v(n.tags,"--tags");return s!==void 0&&i.set("tags",s),i.set("file",await It(e),D(e)),await L("/api/v2/builds",{body:i,commandOptions:n,method:"POST",signal:o})}const Tt=["platform"],Lt=[{fields:[{header:"ID",key:"id"},{header:"Name",key:"name"},{header:"Platform",key:"platform"},{header:"OS versions",key:"osVersions"}],key:"devices"}];async function Dt({options:e,signal:t}){const n=Nt(e.platform);return{devices:(await ze(e,t)).filter(i=>n===void 0||i.platform===n).map(_t)}}function Nt(e){const t=v(e,"--platform");if(t!==void 0){if(!Fe(t))throw new c(`--platform expects one of: ${Ce.join(", ")}`);return t}}function _t({id:e,name:t,osVersions:n,platform:o}){return{id:e,name:t,osVersions:n,platform:o}}const Rt="APPETIZE_OUTPUT";function Ut(e,t,n){return{format:jt(e,t),progress:zt(e,n)}}function U(e,{extension:t,strict:n=!1}){const o=it(e);if(o==="")return`${e}${t}`;if(n&&o!==t)throw new c(`The output must be a path ending in ${t}`);return e}function jt(e,t){if(e.json===!0)return"json";if(e.json===!1)return"text";const n=process.env[Rt]?.trim();return n==="json"||n==="text"?n:t.isTTY===!0?"text":"json"}function zt(e,t){return e.quiet===!0?"silent":t.isTTY===!0&&process.env.TERM!=="dumb"&&!("CI"in process.env)?"interactive":"silent"}const b=["text","testId"],h="select",E={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"}},j="index",P="position",z="x",F="y";function de(e,{prefix:t=h}={}){return b.reduce((n,o)=>{const{help:i,suffix:r}=E[o];return n.option(`--${p(t,r)}`,i)},e).option(`--${p(t,j)}`,"Which match when multiple (0-based)")}function C(e,t={}){const{prefix:n=h}=t;return de(e,t).option(`--${p(n,P)}`,"Screen position to use as x,y (0-1), e.g., 0.5,0.75").option(`--${p(n,z)}`,"Horizontal position within the element (0-1, outside allowed)").option(`--${p(n,F)}`,"Vertical position within the element (0-1, outside allowed)")}function le(e,{prefix:t=h}={}){const n=B(e,t);if(n.length===0)throw new c(`A selector is required: pass one of ${$(b,t)}`);if(n.length>1)throw new c(`Only one selector may be given, got ${$(n,t)}`);const[o]=n,i=ge(e,p(t,E[o].suffix)),r=m(e[p(t,j)],`--${p(t,j)}`);switch(o){case"testId":return{by:"testId",index:r,testId:i};case"text":return{by:"text",index:r,text:Mt(i)}}}function ue(e){const t=m(e.timeout,"--timeout");return t===void 0?void 0:{timeout:t}}function Ft(e,{prefix:t=h}={}){return he(e,t)?le(e,{prefix:t}):void 0}function I(e,{prefix:t=h}={}){return he(e,t)?fe(e,{prefix:t}):void 0}function fe(e,{prefix:t=h}={}){const n=p(t,P),o=e[n],i=we(e,p(t,z)),r=we(e,p(t,F));if(o===void 0){if(B(e,t).length===0)throw new c(`A selector is required: pass one of ${O({prefix:t})}`);return{...le(e,{prefix:t}),x:i,y:r}}if(B(e,t).length>0)throw new c(`--${n} may not be combined with ${$(b,t)}`);if(i!==void 0||r!==void 0)throw new c(`--${n} may not be combined with --${p(t,z)} or --${p(t,F)}`);return Ct(ge(e,n),n)}function O(e={}){const{prefix:t=h}=e;return`${$(b,t)}, --${p(t,P)}`}function M(e={}){const{prefix:t=h}=e;return[...me(e),p(t,P)]}function me({prefix:e=h}={}){return b.map(t=>p(e,E[t].suffix))}function B(e,t){return b.filter(n=>e[p(t,E[n].suffix)]!==void 0)}function p(...e){return e.filter(Boolean).join("-")}function $(e,t){return e.map(n=>`--${p(t,E[n].suffix)}`).join(", ")}function he(e,t){return Object.entries(e).some(([n,o])=>o!==void 0&&n.startsWith(`${t}-`))}function we(e,t){return m(e[t],`--${t}`)}function Ct(e,t){const n=e.split(",");if(n.length!==2)throw new c(`--${t} expects x,y (0-1), e.g., 0.5,0.75`);const[o,i]=n.map(r=>Number(r.trim()));return{by:"position",x:H(o,`--${t}`),y:H(i,`--${t}`)}}function Mt(e){const t=/^\/(.*)\/([a-z]*)$/s.exec(e);return t?new RegExp(t[1],t[2]):e}function ge(e,t){return k(e[t],`--${t}`)}const Bt=me(),qt=async({device:e,options:t,positionals:[n]})=>{const o=Gt(n),i=Ft(t),r=await e.inspect(i,ue(t)),s=Kt(r,t.pretty===!0);return await oe(o,s),{bytes:Buffer.byteLength(s),nodes:ye(r.root),output:o}};function ye(e){return e.children.reduce((t,n)=>t+ye(n),1)}function Gt(e="inspect"){return U(e,{extension:".json"})}function Kt(e,t){return`${JSON.stringify(e,null,t?2:void 0)}
|
|
3
|
+
`}const Zt=async({device:e})=>{await e.clearKeychain()},Wt=async({device:e,positionals:[t]})=>{await e.open(Xt(t))};function Xt(e){if(typeof e=="string")try{return new URL(e),e}catch{throw new c("<url> expects a URL, e.g., myapp://orders/42")}throw new c("<url> expects a URL, e.g., myapp://orders/42")}const Vt=new Set(ae),Ht=async({device:e,positionals:[t]})=>{if(!Jt(t))throw new c(`Button must be one of: ${ae.join(", ")}`);await e.press(t)};function Jt(e){return typeof e=="string"&&Vt.has(e)}const Yt=async({control:e,options:t,positionals:[n]})=>{const{path:o}=await e.recordStart({force:t.force===!0,path:en(n)});return{path:o}},Qt=async({control:e})=>{const{path:t}=await e.recordStop();return{path:t}};function en(e){const t=ne(U(e,{extension:".mp4",strict:!0})),n=rt(t);if(!te(n))throw new c(`No such directory: ${n}`);return t}const ve={landscapeLeft:!0,landscapeRight:!0,portrait:!0,upsideDown:!0},tn=async({device:e,positionals:[t]})=>{if(!nn(t))throw new c(`Orientation must be one of: ${Object.keys(ve).join(", ")}`);await e.rotate(t)};function nn(e){return typeof e=="string"&&Object.hasOwn(ve,e)}const on=async({device:e,positionals:[t]})=>{const n=await e.screenshot(),o=sn(n.mimeType,t);return await oe(o,n.data),{bytes:n.data.byteLength,output:o}};function rn(e){const t=e.split("/").at(1);return`.${t==="jpeg"?"jpg":t??"png"}`}function sn(e,t="screenshot"){return U(t,{extension:rn(e)})}function an(e){const t=ie(new URL("./daemon.js",import.meta.url)),n=nt(Me(e.sessionId),"a"),o=dt(process.execPath,[t],{detached:!0,env:{...process.env,[Be]:qe(e),DEBUG:cn(process.env.DEBUG)},stdio:["ignore",n,n]});if(ot(n),o.unref(),o.pid===void 0)throw new Error("Failed to spawn the session daemon");return o.pid}function cn(e){return e?`${e},appetize:daemon`:"appetize:daemon"}const pn=/^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/i;function dn(){return lt({capitalize:!1,separator:"-"})}function ln(e){if(!pn.test(e))throw new c('--session-id must use letters, digits, ".", "-" or "_"');return e}const un=["device-os-version","open","proxy"],fn=150,mn={downloadingApp:"Downloading the app",installingApp:"Installing the app",launchingApp:"Launching the app",queued:"Queued",ready:"Device ready",requesting:"Requesting a device",starting:"Starting the device"},hn=[{header:"Session ID",key:"sessionId"},{header:"Web view",key:"viewerUrl"},{format:e=>`adb connect ${e}`,header:"adb",key:"adbSerial"},{header:"Host",key:"baseUrl"},{fields:[{header:"Device",key:"device"},{header:"Daemon",key:"daemon"},{header:"Network",key:"network"}],header:"Logs",key:"logs"},{hidden:!0,key:"controlSocket"}];async function wn(e,{onPhase:t,signal:n}){let o;for(;;){const i=J(e),r=i?.state?.phase;if(r&&r!==o&&(o=r,t?.(r)),i&&r==="ready"&&i.controlSocket!==void 0)return{...i,controlSocket:i.controlSocket};if(r==="error")throw new Error(i?.endedReason??"The session failed to start");if(r==="ended")throw new Error(i?.endedReason??"The session ended");await V(fn,n)}}function gn(e){const t=v(e,"--open");if(t!==void 0){try{new URL(t)}catch{throw new c("--open expects a URL, e.g., myapp://orders/42")}return t}}function yn(e){if(!(e===void 0||e===!1)){if(e===""||e==="intercept")return"intercept";if(typeof e!="string"||!Sn(e))throw new c("--proxy expects 'intercept' or an http:// url, e.g., http://proxy:8080");return e}}async function vn({options:e,positionals:[t,n],progress:o,signal:i}){const r=v(e["device-os-version"],"--device-os-version"),s=v(e["session-id"],"--session-id"),a=s===void 0?dn():ln(s);if(J(a)!==void 0)throw new Error(`Session ${a} already exists`);const d={device:r===void 0?{id:t}:{id:t,osVersion:r},endpoint:Ke(e),featureFlags:Ge(),open:gn(e.open),proxy:yn(e.proxy),sessionId:a,target:n};an(d),o.step(`Session ${a}`);const l=Ze(a,d.proxy);if(e.wait===!1)return{logs:l,sessionId:a};const u=await wn(a,{onPhase:f=>{bn(f)&&o.status(mn[f]??"Starting the session")},signal:i}).catch(f=>{throw Y.wrap(f,Q(a))});return{adbSerial:u.adbSerial,baseUrl:u.baseUrl,controlSocket:u.controlSocket,logs:l,sessionId:a,viewerUrl:u.viewerUrl}}function Sn(e){return e.startsWith("http://")}function bn(e){return e!=="ended"&&e!=="error"}const xn=async({record:{pid:e,sessionId:t}})=>(We(e)&&process.kill(e,"SIGTERM"),{sessionId:t}),Se="appetize",En=ie(new URL(`./skills/${Se}/`,import.meta.url)),q=["agents","claude","codex","copilot","cursor"],be=["project","user"],On={agents:".agents",claude:".claude",codex:".codex",copilot:".copilot",cursor:".cursor"},kn=S(".agents","skills"),Pn=["claude","agents"];function In(e){return q.some(t=>t===e)}function $n(e){return be.some(t=>t===e)}async function An(e){const t=e.agents??await Tn(e),n=await Promise.all(t.map(o=>xe(o,e)));return[...new Set(n.flat())]}async function xe(e,t){const n=Ee(e,t);if(e==="claude")return[S(n,"skills")];const o=S(t.root,kn);return t.scope==="project"?[o]:await Oe(n)?[o,S(n,"skills")]:[o]}function Ee(e,t){if(e==="claude"&&t.scope==="user"){const n=process.env.CLAUDE_CONFIG_DIR?.trim();if(n)return ne(n)}return S(t.root,On[e])}async function Tn(e){const n=(await Promise.all(q.map(async o=>await Ln(o,e)?o:void 0))).filter(o=>o!==void 0);return n.length>0?n:Pn}async function Ln(e,t){const n=[Ee(e,t),...await xe(e,t)];return(await Promise.all(n.map(i=>Oe(i)))).includes(!0)}async function Oe(e){try{return(await at(e)).isDirectory()}catch{return!1}}const Dn=["agent","scope"];async function Nn({options:e,signal:t}){const n=Un(e.scope),o=Rn(e.agent),i=n==="user"?ut():process.cwd(),r=await An({agents:o,root:i,scope:n}),s=[];for(const a of r){t.throwIfAborted();const d=S(a,Se);await ct(d,{force:!0,recursive:!0}),await pt(En,d,{recursive:!0}),s.push(n==="user"?d:st(i,d))}return{installed:s}}function _n(e){const t=k(e,"--agent");if(!In(t))throw new c(`--agent expects one of ${q.join(", ")}`);return t}function Rn(e){return e===void 0?void 0:(Array.isArray(e)?e:[e]).map(n=>_n(n))}function Un(e){if(e===void 0)return"project";const t=k(e,"--scope");if(!$n(t))throw new c(`--scope expects one of ${be.join(", ")}`);return t}const w="from",g="to",jn=[...M({prefix:w}),...M({prefix:g})],zn=async({device:e,options:t})=>{await e.swipe(Bn(t),Gn(t))};function Fn(e){return N.some(t=>t===e)}function Cn(e){if(e===void 0)return;const t=k(e,"--direction");if(!Fn(t))throw new c(`--direction expects one of ${N.join(", ")}`);return t}function Mn(e,t){const n=Xe(e.distance,"--distance");if(I(e,{prefix:g})!==void 0)throw new c(`--direction may not be combined with --${g}-*`);return{direction:t,distance:n,from:I(e,{prefix:w})}}function Bn(e){const t=Cn(e.direction);return t===void 0?qn(e):Mn(e,t)}function qn(e){if(e.distance!==void 0)throw new c("--distance is only valid with --direction");return{from:ke(I(e,{prefix:w}),w),to:ke(I(e,{prefix:g}),g)}}function Gn(e){const t=m(e.duration,"--duration"),n=m(e.timeout,"--timeout");return t===void 0&&n===void 0?void 0:{duration:t,timeout:n}}function ke(e,t){if(e===void 0)throw new c(`A swipe needs --direction, or both endpoints: pass one of ${O({prefix:t})}`);return e}const Kn=M(),Zn=async({device:e,options:t})=>{const n=fe(t);await e.tap(n,ue(t))},Wn=async({device:e,options:t,positionals:[n]})=>{await e.type(n,Xn(t))};function Xn(e){const t=m(e.delay,"--delay");return t===void 0?void 0:{delay:t}}const G=ft("appetize:cli"),Vn={fail:()=>{},status:()=>{},step:()=>{},succeed:()=>{}};function Hn(e,t,n){return e==="interactive"?Jn(t,n):Vn}function Jn(e,t){const n=mt({handleSignals:!1,stream:e});let o=0;const i=()=>{n.stop()};t.addEventListener("abort",i,{once:!0});const r=()=>(process.off("exit",i),n.isSpinning);return{fail:()=>{r()&&n.stop()},status:s=>{if(!t.aborted){if(n.isSpinning){n.text=s;return}o=Date.now(),process.once("exit",i),n.start(s)}},step:s=>{e.write(`\u25B8 ${s}
|
|
4
|
+
`)},succeed:()=>{if(!r())return;const s=Math.round((Date.now()-o)/1e3);n.success(`${n.text} (${String(s)}s)`)}}}const Yn=new Set(["adb","api","apk","id","os","url"]),Qn={bottom:"","bottom-left":"","bottom-mid":"","bottom-right":"",left:"","left-mid":"",mid:"","mid-mid":"",middle:" ",right:"","right-mid":"",top:"","top-left":"","top-mid":"","top-right":""},Pe=2,eo=10;function to(e){return e.split(/(?=[A-Z])/).map((t,n)=>{const o=t.toLowerCase();return Yn.has(o)?o.toUpperCase():n===0?o.charAt(0).toUpperCase()+o.slice(1):o}).join(" ")}function no(e,t,n){return Z(e)?De(e,t,n):A(e,{fields:t,key:""},n)}function oo(e,t){const n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n.length===0?[e]:n}function Ie(e){return new ht({chars:Qn,head:e,style:{border:[],head:[],"padding-left":0,"padding-right":Pe}})}function $e(e,t){return e.find(n=>n.key===t)}function Ae(e,t){return t?.header??to(e)}function K(e){return e!=null}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Te(e){return["boolean","number","string"].includes(typeof e)}function Le(e,t){const n=new Set(t),o=e.map(r=>r.key).filter(r=>n.has(r)),i=new Set(e.filter(r=>r.hidden).map(r=>r.key));return[...new Set([...o,...t])].filter(r=>!i.has(r))}function De(e,t,n){const o=new Map(Object.entries(e)),i=Le(t,[...o.keys()]).filter(u=>K(o.get(u))),r=i.map(u=>$e(t,u)),s=i.map((u,f)=>Ae(u,r[f])),a=Math.max(0,...s.map(u=>u.length))+Pe,d=n===void 0?void 0:n-a-1,l=Ie();return l.push(...i.map((u,f)=>[s[f],A(o.get(u),r[f],d)])),Ne(l.toString())}function io(e,t){const n=e.map(s=>new Map(Object.entries(s))),o=Le(t,n.flatMap(s=>[...s.keys()])),i=o.map(s=>$e(t,s)),r=Ie(o.map((s,a)=>Ae(s,i[a])));for(const s of n)r.push(o.map((a,d)=>{const l=s.get(a);return K(l)?A(l,i[d]):""}));return Ne(r.toString())}function A(e,t,n){if(t?.format)return T(t.format(e),n);if(Te(e))return T(ee(e),n);if(Array.isArray(e)){const o=e.filter(K);return o.every(Te)?T(ee(o),n):o.every(Z)?io(o,t?.fields??[]):o.map(i=>A(i,t,n)).join(`
|
|
5
|
+
`)}return Z(e)?De(e,t?.fields??[],n):T(String(e),n)}function Ne(e){return e.split(`
|
|
6
|
+
`).map(t=>t.trimEnd()).join(`
|
|
7
|
+
`)}function T(e,t){return t===void 0||t<eo?e:e.split(`
|
|
8
|
+
`).flatMap(n=>ro(n,t)).join(`
|
|
9
|
+
`)}function ro(e,t){const n=[];let o="";for(const i of e.split(" ").flatMap(r=>oo(r,t)))o===""?o=i:o.length+1+i.length<=t?o=`${o} ${i}`:(n.push(o),o=i);return n.push(o),n}function so(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");return wt(e.controlSocket,{baseUrl:e.baseUrl,signal:t})}async function ao(e,t){if(e.controlSocket===void 0)throw new Error("Session is not ready");const n=await X(e.controlSocket,{signal:t}),{client:o}=Ve(n,{});return{close:()=>{n.close()},recordStart:async i=>await o.request("appetizeio.cli.record.start",i),recordStop:async()=>await o.request("appetizeio.cli.record.stop")}}function co(e){return async({options:t,positionals:n,progress:o,signal:i})=>{const r=t["session-id"],s=He(typeof r=="string"?r:void 0);try{return await e({options:t,positionals:n,progress:o,record:s,signal:AbortSignal.any([i,Je(s.pid)])})}catch(a){throw Y.wrap(a,Q(s.sessionId))}}}function po(e){return async({options:t,positionals:n,progress:o,record:i,signal:r})=>{const s=await so(i,r);try{return await e({device:s,options:t,positionals:n,progress:o,signal:r})}finally{s.close()}}}function lo(e){return async({options:t,positionals:n,progress:o,record:i,signal:r})=>{const s=await ao(i,r);try{return await e({control:s,options:t,positionals:n,progress:o,signal:r})}finally{s.close()}}}const uo=["session-id",...gt,...bt,...Tt,...Bt,...Dn,...un,...jn,...Kn],fo=["json","quiet"];function mo(e){const t=Ue("appetize").version(e).option("--json","Print the result as JSON").option("--quiet","Hide progress");return x(t,"session start <device-id> <target>",n=>n.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("--open","URL opened once the session is 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").example("session start iphone15pro app_a1b2c3 --open myapp://orders/42"),vn,{fields:hn}),W(t,"session stop",n=>n.describe("Stop a running device session"),xn),x(t,"build list",n=>n.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"),St,{fields:vt}),x(t,"build upload <file>",n=>n.describe([`Upload a build (${R.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(pe)})`).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"'),kt,{fields:Ot}),x(t,"device list",n=>n.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"),Dt,{fields:Lt}),y(t,"press <button>",n=>n.describe(`Press a device button: ${se.join(", ")}; Android only: ${re.join(", ")}`).example("press home").example("press volumeUp"),Ht),y(t,"rotate <orientation>",n=>n.describe("Rotate the device to an orientation: portrait, landscapeLeft, landscapeRight or upsideDown").example("rotate portrait").example("rotate landscapeLeft"),tn),y(t,"open <url>",n=>n.describe("Open a URL or deep link on the device").example("open myapp://orders/42").example("open https://example.com"),Wt),y(t,"keychain clear",n=>n.describe("Clear the entire device keychain (iOS only)").example("keychain clear"),Zt),y(t,"screenshot [output]",n=>n.describe("Take a screenshot of the current device screen").example("screenshot").example("screenshot home-screen").example("screenshot ./shots/checkout.png"),on),y(t,"tap",n=>C(n.describe(["Tap an element matched by a selector, or a screen position","",`Pick one of: ${O()}`])).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"),Zn),y(t,"swipe",n=>C(C(n.describe(["Swipe in a direction, or along a path between two points","",`Pick a --direction with an optional --${w} starting point,`,`or both a --${w}-* and a --${g}-* point to form a path`,"",`Pick one per point: ${O({prefix:w})}`,` ${O({prefix:g})}`]).option("--direction",`Direction to travel: ${N.join(", ")}`).option("--distance","Travel as a fraction of the screen (0-1)"),{prefix:w}),{prefix:g}).option("--duration","Milliseconds the gesture travels for").option("--timeout",`Milliseconds to wait for any --${w}/--${g} 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"),zn),y(t,"inspect [output]",n=>de(n.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"),qt),y(t,"type <text>",n=>n.describe(`Type text; {...} presses a named key: ${et.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"),Wn),_e(t,"recording start <output>",n=>n.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"),Yt),_e(t,"recording stop",n=>n.describe("Stop recording the device video and close the file").example("recording stop"),Qt),x(t,"skill install",n=>n.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"),Nn),t}function x(e,t,n,o,{fields:i}={}){const r=t.split(" ").filter(s=>!/^[<[]/.test(s)).join(" ");return n(e.command(t)).action(go({action:o,fields:i,name:r}))}function W(e,t,n,o){return x(e,t,i=>n(i).option("--session-id","Target session id; defaults to the sole active session"),co(o))}function y(e,t,n,o){return W(e,t,n,po(o))}function _e(e,t,n,o){return W(e,t,n,lo(o))}function Re(e){return`${String(Date.now()-e)}ms`}function ho(e,t,n){if(e==="json")return JSON.stringify(t===void 0?{}:t,null,2);const o=t===void 0?"":no(t,n,process.stdout.columns);return o===""?void 0:o}async function wo({action:e,fields:t=[],name:n},o){const i=Date.now();G(`invoked: ${process.argv.slice(2).join(" ")}`);const r=Ye(o),{format:s,progress:a}=Ut(r.options,process.stdout,process.stderr),d=Hn(a,process.stderr,r.signal);try{const l=ho(s,await e({...r,progress:d}),t);d.succeed(),l!==void 0&&process.stdout.write(`${l}
|
|
10
|
+
`),G(`ok in ${Re(i)}`)}catch(l){d.fail(),process.stderr.write(`${Qe(s,l,{command:n})}
|
|
11
|
+
`),G(`failed after ${Re(i)}:`,l),process.exitCode=1}}function go(e){return(...t)=>{wo(e,t)}}mo("0.19.0").parse(process.argv,{boolean:fo,string:uo});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Transform as ar}from"stream";import{createRequire as lr}from"module";import{connect as cr}from"node:net";import Fe from"debug";import{JSONRPCServerAndClient as fr,JSONRPCServer as ur,JSONRPCClient as dr,JSONRPC as hr}from"json-rpc-2.0";import{homedir as bt}from"node:os";import{sep as pr,join as te}from"node:path";import{writeFileSync as yr,renameSync as wr,mkdirSync as gt,readFileSync as mr,readdirSync as br}from"node:fs";let ze;try{ze=new TextDecoder}catch{}let p,V,c=0;const je=[],gr=105,Er=57342,Sr=57343,Et=57337,St=6,fe={};let me=11281e4,Y=1681e4,re=je,be=0,k={},_,ge,Ee=0,se=0,N,q,D=[],Ve=[],K,j,Se,vt={useRecords:!1,mapsAsObjects:!0},ve=!1,At=2;try{new Function("")}catch{At=1/0}class pe{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 Tt(()=>(Je(),this?this.decode(e,r):pe.prototype.decode.call(vt,e,r)));V=r>-1?r:e.length,c=0,be=0,se=0,ge=null,re=je,N=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 pe){if(k=this,K=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return _=this.structures,Ie();(!_||_.length>0)&&(_=[])}else k=vt,(!_||_.length>0)&&(_=[]),K=null;return Ie()}decodeMultiple(e,r){let s,n=0;try{let o=e.length;ve=!0;let f=this?this.decode(e,o):Ge.decode(e,o);if(r){if(r(f)===!1)return;for(;c<o;)if(n=c,r(Ie())===!1)return}else{for(s=[f];c<o;)n=c,s.push(Ie());return s}}catch(o){throw o.lastPosition=n,o.values=s,o}finally{ve=!1,Je()}}}function Ie(){try{let t=I();if(N){if(c>=N.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}c=N.postBundlePosition,N=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(!ve)throw new Error("Data read, but end of buffer not reached");return t}catch(t){throw Je(),(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 kr();t=j.getUint16(c),c+=2;break;case 26:if(e==7){let r=j.getFloat32(c);if(k.useFloat32>2){let s=We[(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 k.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>=me)throw new Error(`Array length exceeds ${me}`);r[n++]=s}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let o;if(k.mapsAsObjects){let f={},m=0;if(k.keyMap)for(;(o=I())!=fe;){if(m++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(k.decodeKey(o))]=I()}else for(;(o=I())!=fe;){if(m++>=Y)throw new Error(`Property count exceeds ${Y}`);f[J(o)]=I()}return f}else{Se&&(k.mapsAsObjects=!0,Se=!1);let f=new Map;if(k.keyMap){let m=0;for(;(o=I())!=fe;){if(m++>=Y)throw new Error(`Map size exceeds ${Y}`);f.set(k.decodeKey(o),I())}}else{let m=0;for(;(o=I())!=fe;){if(m++>=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 Or(t);case 3:if(se>=c)return ge.slice(c-Ee,(c+=t)-Ee);if(se==0&&V<140&&t<32){let n=t<16?It(t):Ar(t);if(n!=null)return n}return kt(t);case 4:if(t>=me)throw new Error(`Array length exceeds ${me}`);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 ${me}`);if(t>(V-c)/2)throw ne();if(k.mapsAsObjects){let n={};if(k.keyMap)for(let o=0;o<t;o++)n[J(k.decodeKey(I()))]=I();else for(let o=0;o<t;o++)n[J(I())]=I();return n}else{Se&&(k.mapsAsObjects=!0,Se=!1);let n=new Map;if(k.keyMap)for(let o=0;o<t;o++)n.set(k.decodeKey(I()),I());else for(let o=0;o<t;o++)n.set(I(),I());return n}case 6:if(t>=Et){let n=_[t&8191];if(n)return n.read||(n.read=Ke(n)),n.read();if(t<65536){if(t==Sr){let o=de(),f=I(),m=I();$e(f,m);let y={};if(k.keyMap)for(let v=2;v<o;v++){let g=k.decodeKey(m[v-2]);y[J(g)]=I()}else for(let v=2;v<o;v++){let g=m[v-2];y[J(g)]=I()}return y}else if(t==Er){let o=de(),f=I();for(let m=2;m<o;m++)$e(f++,I());return I()}else if(t==Et)return Cr();if(k.getShared&&(qe(),n=_[t&8191],n))return n.read||(n.read=Ke(n)),n.read()}}let s=D[t];if(s)return s.handlesRead?s(I):s(I());{let n=I();for(let o=0;o<Ve.length;o++){let f=Ve[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 Ot=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ke(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++>=At){let o=this.length==r?this:this.slice(0,r);return s=k.keyMap?new Function("r","return {"+o.map(f=>k.decodeKey(f)).map(f=>Ot.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"):new Function("r","return {"+o.map(f=>Ot.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(k.keyMap)for(let o=0;o<r;o++)n[J(k.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 kt=xe;function vr(t){kt=e();function e(r){return function(n){let o=re[be++];if(o==null){if(N)return xe(n);let m=t(c,V,n,p);if(typeof m=="string")o=m,re=je;else if(re=m,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,Ee=c,se=c+f,c+=n,o.slice(0,n))}}}function xe(t){let e;if(t<16&&(e=It(t)))return e;if(t>64&&ze)return ze.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 m=p[c++]&63;let y=(n&7)<<18|(o&63)<<12|f<<6|m;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 Ar(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 It(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 m=p[c++];if((m&128)>0){c-=7;return}return F(e,r,s,n,o,f,m)}else{let o=p[c++],f=p[c++],m=p[c++],y=p[c++];if((o&128)>0||(f&128)>0||(m&128)>0||(y&128)>0){c-=8;return}if(t<10){if(t===8)return F(e,r,s,n,o,f,m,y);{let v=p[c++];if((v&128)>0){c-=9;return}return F(e,r,s,n,o,f,m,y,v)}}else if(t<12){let v=p[c++],g=p[c++];if((v&128)>0||(g&128)>0){c-=10;return}if(t<11)return F(e,r,s,n,o,f,m,y,v,g);let M=p[c++];if((M&128)>0){c-=11;return}return F(e,r,s,n,o,f,m,y,v,g,M)}else{let v=p[c++],g=p[c++],M=p[c++],R=p[c++];if((v&128)>0||(g&128)>0||(M&128)>0||(R&128)>0){c-=12;return}if(t<14){if(t===12)return F(e,r,s,n,o,f,m,y,v,g,M,R);{let L=p[c++];if((L&128)>0){c-=13;return}return F(e,r,s,n,o,f,m,y,v,g,M,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,m,y,v,g,M,R,L,U);let P=p[c++];if((P&128)>0){c-=15;return}return F(e,r,s,n,o,f,m,y,v,g,M,R,L,U,P)}}}}}function Or(t){return k.copyBuffers?Uint8Array.prototype.slice.call(p,c,c+=t):p.subarray(c,c+=t)}let xt=new Float32Array(1),Me=new Uint8Array(xt.buffer,0,4);function kr(){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,xt[0]}new Array(4096);class ie{constructor(e,r){this.value=e,this.tag=r}}D[0]=t=>new Date(t),D[1]=t=>new Date(Math.round(t*1e3)),D[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},D[3]=t=>BigInt(-1)-D[2](t),D[4]=t=>+(t[1]+"e"+t[0]),D[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const $e=(t,e)=>{t=t-57344;let r=_[t];r&&r.isShared&&((_.restoreStructures||(_.restoreStructures=[]))[t]=r),_[t]=e,e.read=Ke(e)};D[gr]=t=>{let e=t.length,r=t[1];$e(t[0],r);let s={};for(let n=2;n<e;n++){let o=r[n-2];s[J(o)]=t[n]}return s},D[14]=t=>N?N[0].slice(N.position0,N.position0+=t):new ie(t,14),D[15]=t=>N?N[1].slice(N.position1,N.position1+=t):new ie(t,15);let Ir={Error,RegExp};D[27]=t=>(Ir[t[0]]||Error)(t[1],t[2]);const Mt=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()};Mt.handlesRead=!0,D[51]=Mt,D[St]=t=>{if(!K)if(k.getShared)qe();else return new ie(t,St);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},D[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)},D[28].handlesRead=!0,D[29]=t=>{let e=q.get(t);return e.used=!0,e.target},D[258]=t=>new Set(t),(D[259]=t=>(k.mapsAsObjects&&(k.mapsAsObjects=!1,Se=!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(k.getShared)qe();else throw new Error("No packed values available");return K}const xr=1399353956;Ve.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==xr)return{packedValues:K,structures:_.slice(0),version:e};if(t==55799)return e});const Mr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Rt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],Rr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Rt.length;t++)Tr(Rt[t],Rr[t]);function Tr(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;D[n?e:e-4]=s==1||n==Mr?f=>{if(!t)throw new Error("Could not find typed array for code "+e);return!k.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 m=new DataView(f.buffer,f.byteOffset,f.byteLength),y=f.length>>o,v=new t(y),g=m[r];for(let M=0;M<y;M++)v[M]=g.call(m,M<<o,n);return v}}}function Cr(){let t=de(),e=c+I();for(let s=2;s<t;s++){let n=de();c+=n}let r=c;return c=e,N=[xe(de()),xe(de())],N.position0=0,N.position1=0,N.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 qe(){if(k.getShared){let t=Tt(()=>(p=null,k.getShared()))||{},e=t.structures||[];k.sharedVersion=t.version,K=k.sharedValues=t.packedValues,_===!0?k.structures=_=e:_.splice.apply(_,[0,e.length].concat(e))}}function Tt(t){let e=V,r=c,s=be,n=Ee,o=se,f=ge,m=re,y=q,v=N,g=new Uint8Array(p.slice(0,V)),M=_,R=k,L=ve,U=t();return V=e,c=r,be=s,Ee=n,se=o,ge=f,re=m,q=y,N=v,p=g,ve=L,_=M,k=R,j=new DataView(p.buffer,p.byteOffset,p.byteLength),U}function Je(){p=null,q=null,_=null}const We=new Array(147);for(let t=0;t<256;t++)We[t]=+("1e"+Math.floor(45.15-t*.30103));let Ge=new pe({useRecords:!1});const Pr=Ge.decode;Ge.decodeMultiple;let Re;try{Re=new TextEncoder}catch{}let He,Ct;const Te=typeof globalThis=="object"&&globalThis.Buffer,Ae=typeof Te<"u",Ze=Ae?Te.allocUnsafeSlow:Uint8Array,Pt=Ae?Te:Uint8Array,Ut=256,Lt=Ae?4294967296:2144337920;let Ye,l,C,i=0,Q,B=null;const Ur=61440,Lr=/[\u0080-\uFFFF]/,$=Symbol("record-id");class _t extends pe{constructor(e){super(e),this.offset=0;let r,s,n,o,f;e=e||{};let m=Pt.prototype.utf8Write?function(a,w){return l.utf8Write(a,w,l.byteLength-w)}:Re&&Re.encodeInto?function(a,w){return Re.encodeInto(a,l.subarray(w)).written}:!1,y=this,v=e.structures||e.saveStructures,g=e.maxSharedStructures;if(g==null&&(g=v?128:0),g>8190)throw new Error("Maximum maxSharedStructure is 8190");let M=e.sequential;M&&(g=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=[],ye=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 Ze(8192),C=new DataView(l.buffer,0,8192),i=0),Q=l.length-10,Q-i<2048?(l=new Ze(l.length),C=new DataView(l.buffer,0,l.length),Q=l.length-10,i=0):w===Ft&&(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"?(B=[],B.size=1/0):B=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 b=0,E=u.length;b<E;b++)P[u[b]]=b}}let d=s.length;if(d>g&&!M&&(d=g),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let b,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[$]===void 0&&(E[$]=h);let x=u[S];b=E[x],b||(b=E[x]=Object.create(null)),E=b}E[$]=h|1048576}}M||(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,Ce(a,d),d.values.length>0){l[i++]=216,l[i++]=51,H(4);let h=d.values;O(h),H(0),H(0),L=Object.create(P||null);for(let u=0,b=h.length;u<b;u++)L[h[u]]=u}}Ye=w&tt;try{if(Ye)return;if(O(a),B&&Bt(r,O),y.offset=i,f&&f.idsToInsert){i+=f.idsToInsert.length*2,i>Q&&le(i),y.offset=i;let d=Dr(l.subarray(r,i),f.idsToInsert);return f=null,d}return w&Ft?(l.start=r,l.end=i,l):l.subarray(r,i)}finally{if(s){if(G<10&&G++,s.length>g&&(s.length=g),ye>1e4)s.transitions=null,G=0,ye=0,W.length>0&&(W=[]);else if(W.length>0&&!M){for(let d=0,h=W.length;d<h;d++)W[d][$]=void 0;W=[]}}if(n&&y.saveShared){y.structures.length>g&&(y.structures=y.structures.slice(0,g));let d=l.subarray(r,i);return y.updateSharedData()===!1?y.encode(a):d}w&Fr&&(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 O=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?O(15-E>>1):O(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(B&&h>=4&&h<1024){if((B.size+=h)>Ur){let S,A=(B[0]?B[0].length*3+B[1].length:0)+10;i+A>Q&&(l=le(i+A)),l[i++]=217,l[i++]=223,l[i++]=249,l[i++]=B.position?132:130,l[i++]=26,S=i-r,i+=4,B.position&&Bt(r,O),B=["",""],B.size=0,B.position=S}let E=Lr.test(a);B[E?0:1]+=a,l[i++]=E?206:207,O(h);return}let u;h<32?u=1:h<256?u=2:h<65536?u=3:u=5;let b=h*3;if(i+b>Q&&(l=le(i+b)),h<64||!m){let E,S,A,x=i+u;for(E=0;E<h;E++)S=a.charCodeAt(E),S<128?l[x++]=S:S<2048?(l[x++]=S>>6|192,l[x++]=S&63|128):(S&64512)===55296&&((A=a.charCodeAt(E+1))&64512)===56320?(S=65536+((S&1023)<<10)+(A&1023),E++,l[x++]=S>>18|240,l[x++]=S>>12&63|128,l[x++]=S>>6&63|128,l[x++]=S&63|128):(l[x++]=S>>12|224,l[x++]=S>>6&63|128,l[x++]=S&63|128);d=x-i-u}else d=m(a,i+u,b);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*We[(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 b=f.idsToInsert||(f.idsToInsert=[]);u.references=[],b.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++)O(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,b]of a)O(y.encodeKey(u)),O(b);else for(let[u,b]of a)O(u),O(b);else{for(let u=0,b=He.length;u<b;u++){let E=Ct[u];if(a instanceof E){let S=He[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,O,le);return}}if(a[Symbol.iterator]){if(Ye){let u=new Error("Iterable should be serialized as iterator");throw u.iteratorNotHandled=!0,u}l[i++]=159;for(let u of a)O(u);l[i++]=255;return}if(a[Symbol.asyncIterator]||Xe(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 O(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);Qe(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++)O(y.encodeKey(w[u])),O(d[u]);else for(let u=0;u<h;u++)O(w[u]),O(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))&&(O(y.encodeKey(h)),O(a[h]),d++);else for(let h in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(h))&&(O(h),O(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,b=0,E,S;if(this.keyMap){S=Object.keys(a).map(x=>this.encodeKey(x)),b=S.length;for(let x=0;x<b;x++){let mt=S[x];d=h[mt],d||(d=h[mt]=Object.create(null),u++),h=d}}else for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&(d=h[x],d||(h[$]&1048576&&(E=h[$]&65535),d=h[x]=Object.create(null),u++),h=d,b++);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>=Ut&&(o.nextId=(A=g)+1)):A=E,o[A]=S,A<g){l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255,h=o.transitions;for(let x=0;x<b;x++)(h[$]===void 0||h[$]&1048576)&&(h[$]=A),h=h[S[x]];h[$]=A|1048576,n=!0}else{if(h[$]=A,C.setUint32(i,3655335680),i+=3,u&&(ye+=G*u),W.length>=Ut-g&&(W.shift()[$]=void 0),W.push(h),H(b+2),O(57344+A),O(S),w)return;for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&O(a[x]);return}if(b<24?l[i++]=128|b:H(b),!w)for(let x in a)(typeof a.hasOwnProperty!="function"||a.hasOwnProperty(x))&&O(a[x])},le=a=>{let w;if(a>16777216){if(a-r>Lt)throw new Error("Encoded buffer would be larger than maximum buffer size");w=Math.min(Lt,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 Ze(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,pt=1e3;this.encodeAsIterable=function(a,w){return yt(a,w,ce)},this.encodeAsAsyncIterable=function(a,w){return yt(a,w,wt)};function*ce(a,w,d){let h=a.constructor;if(h===Object){let u=y.useRecords!==!1;u?z(a,!0):Nt(Object.keys(a).length,160);for(let b in a){let E=a[b];u||O(b),E&&typeof E=="object"?w[b]?yield*ce(E,w[b]):yield*Be(E,w,b):O(E)}}else if(h===Array){let u=a.length;H(u);for(let b=0;b<u;b++){let E=a[b];E&&(typeof E=="object"||i-r>ee)?w.element?yield*ce(E,w.element):yield*Be(E,w,"element"):O(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*Be(u,w,"element"):O(u);l[i++]=255}else Xe(a)?(Nt(a.size,64),yield l.subarray(r,i),yield a,we()):a[Symbol.asyncIterator]?(l[i++]=159,yield l.subarray(r,i),yield a,we(),l[i++]=255):O(a);d&&i>r?yield l.subarray(r,i):i-r>ee&&(yield l.subarray(r,i),we())}function*Be(a,w,d){let h=i-r;try{O(a),i-r>ee&&(yield l.subarray(r,i),we())}catch(u){if(u.iteratorNotHandled)w[d]={},i=r+h,yield*ce.call(this,a,w[d]);else throw u}}function we(){ee=pt,y.encode(null,tt)}function yt(a,w,d){return w&&w.chunkThreshold?ee=pt=w.chunkThreshold:ee=100,a&&typeof a=="object"?(y.encode(null,tt),d(a,y.iterateProperties||(y.iterateProperties={}),!0)):[y.encode(a)]}async function*wt(a,w){for(let d of ce(a,w,!0)){let h=d.constructor;if(h===Pt||h===Uint8Array)yield d;else if(Xe(d)){let u=d.stream().getReader(),b;for(;!(b=await u.read()).done;)yield b.value}else if(d[Symbol.asyncIterator])for await(let u of d)we(),u?yield*wt(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 Dt(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 Nt(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 Dt{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,C.setUint32(i,t),i+=4)}const _r=typeof Blob>"u"?function(){}:Blob;function Xe(t){if(t instanceof _r)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function Ce(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++)Ce(t[s],e);else{let s=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(s&&Ce(r,e),Ce(t[r],e))}break;case"function":console.log(t)}}const Nr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Ct=[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,Dt],He=[{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){Qe(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Ae&&this.tagUint8Array!==!1))return 64},encode(t,e,r){Qe(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){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!Nr&&e>1&&(t-=4),{tag:t,encode:function(s,n){let o=s.byteLength,f=s.byteOffset||0,m=s.buffer||s;n(Ae?Te.from(m,f,o):new Uint8Array(m,f,o))}}}function Qe(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 Dr(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 m of f.references)t[m++]=o>>8,t[m]=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 Bt(t,e){C.setUint32(B.position+t,i-B.position-t+1);let r=B;B=null,e(r[0]),e(r[1])}let et=new _t({useRecords:!1});const Br=et.encode;et.encodeAsIterable,et.encodeAsAsyncIterable;const Ft=512,Fr=1024,tt=2048;class zr extends ar{constructor(e){e||(e={}),e.objectMode=!0,super(e),e.structures=[],this.decoder=e.decoder||new pe(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 jr=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!jr){let t;try{typeof require=="function"?t=require("cbor-extract"):t=lr(import.meta.url)("cbor-extract"),t&&vr(t.extractStrings)}catch{}}class Vr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Kr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Vr;return new r(t,e)}class $r{#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 qr extends $r{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Kr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function rt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function Jr(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}class Oe{closed=!1;[T];#e;constructor(e,{signal:r}={}){this[T]=new qr(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[T].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const zt={useRecords:!1},Wr=new _t(zt);class jt extends Oe{#e=[];#r;constructor(e,{signal:r}={}){super(async f=>{this.#r.write(Wr.encode(f))},{signal:r}),this.#r=e;const s=new zr(zt);s.on("data",f=>{rt(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 Gr(t,e){const{promise:r,reject:s,resolve:n}=Jr(),o=cr(t),f=e?.signal,m=()=>{o.off("connect",g),o.off("error",M),f?.removeEventListener("abort",v)},y=R=>{m(),o.destroy(),s(R)},v=()=>{y(new Error("The connection was aborted"))},g=()=>{m();const R=new jt(o,e);R[T].addEventListener("close",()=>{o.destroy()},{once:!0}),n(R)},M=R=>{y(R)};return f?.aborted?(y(new Error("The connection was aborted")),r):(o.once("connect",g),o.once("error",M),f?.addEventListener("abort",v,{once:!0}),r)}const Vt=Fe("appetize.io:error:rpc");function st(t,e){const r=new fr(new ur({errorListener:Vt}),Hr(t),{errorListener:Vt}),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 Kt(t,e){const{rpc:r,unsub:s}=st(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 Hr(t){return new dr(t[T].send.bind(t[T]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}function nt(t,e,{leftEffects:r=()=>({}),notifiesLeft:s,notifiesRight:n,rightEffects:o=()=>({})}={}){const f=st(t,{}),m=st(e,{}),y=[()=>{f.unsub(),m.unsub()}],v=()=>{for(const U of y)try{U()}catch{}},g=m.rpc.client,M=f.rpc.client;y.push(t[T].addEventListener("close",()=>{v()},{once:!0}),e[T].addEventListener("close",()=>{v()},{once:!0}));const R=r(g,M);for(const U in R){const P=R[U];P&&f.rpc.addMethod(U,P)}const L=o(M,g);for(const U in L){const P=L[U];P&&m.rpc.addMethod(U,P)}return $t(f.rpc,m.rpc,{notifies:s}),$t(m.rpc,f.rpc,{notifies:n}),v}function $t(t,e,{notifies:r}={}){t.applyServerMiddleware(async(s,n)=>{const o=r?.();if(o){const{id:m,...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:hr,result:f}})}function X(t,...e){t.notify(e[0],e[1],e[2])}const Zr=(...t)=>Kt(...t),it=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"];function ot(){const t=new Oe(async r=>{e[T].dispatchMessage(r)}),e=new Oe(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 qt(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=Fe("appetize.io:trace:transport:iframe");class Jt extends Oe{onmessage;#e;#r;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#r.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ae("handleMessage()",e),e.source!==this.#r||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!rt(r)){ae("handleMessage() -> legacy"),this.onmessage?.(e);return}ae("handleMessage() -> jsonrpc"),this[T].dispatchMessage(r)}}function Ue(){let t,e;return{promise:new Promise((s,n)=>{e=s,t=n}),reject:t,resolve:e}}const Yr=2*1024*1024,Wt=Fe("appetize:client:acked-writable-stream");class Xr{unacked=0;#e;#r;#t;#s;#n=[];#i;constructor(e){this.#t=e,this.#i=e.window??Yr}abort(e){this.#a(e),this.#t.onAbort?.(e)}async close(){await this.#l(()=>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.#s&&(this.#s.acked+=r),this.#o()},s=>{this.fail(s)}),this.unacked>=this.#i&&!this.#s&&(this.#s={acked:0,at:performance.now()},Wt("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;Wt("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.#r)return!1;this.#r={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#l(e){if(e())return Promise.resolve();const r={...Ue(),until:e};return this.#n.push(r),r.promise}}class Qr extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new Xr(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 es=1024*1024;class ts{#e;#r=!1;#t;#s;constructor(e){this.#t=e}cancel(e){this.#n(),this.#t?.(e)}close(){this.#n()&&this.#e.close()}error(e){this.#n()&&this.#e.error(e)}pull(){const e=this.#s;this.#s=void 0,e?.resolve(void 0)}async push(e){if(this.#r)return;this.#s??=Ue();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class rs extends ReadableStream{#e;constructor({highWaterMark:e=es,onCancel:r}={}){const s=new ts(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 ss{closed;readable;writable;#e=[];#r;#t;#s;#n;#i;#o="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:o}){if(this.#i=e,this.#r=Ue(),this.closed=this.#r.promise,this.closed.catch(ns),this.#s=new rs({highWaterMark:s,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#s,this.#n=new Qr({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.#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&&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.#r.reject(e):this.#r.resolve(void 0)}}}function ns(){}class is{readable;ready;#e=[];#r=!1;#t;#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.#t=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.#t.enqueue(e)}markReady(){if(!this.#n)return;const{resolve:e}=this.#n;this.#n=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#i(e){this.#r||(this.#t.close(),this.#o(e))}#o(e){this.#r=!0;for(const r of this.#e)r();this.#n?.reject(e??new Error(`${this.#s} closed before it started`)),this.#n=void 0}}class os{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 Gt extends os{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new is({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 as{#e;#r;#t;#s;constructor(e){this.#s=e,this.#r=new Gt({label:"Log stream",start:()=>e.request("appetizeio.device.server.debug.log.start"),stop:()=>{X(e,"appetizeio.device.server.debug.log.stop",void 0)}}),this.#t=new Gt({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.#r.close(),this.#t.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new ss(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#r.createStream(e)}async createProxyInterceptStream(e){return await this.#t.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#r.handleNotification(e)}handleProxyInterceptEvent(e){this.#t.handleNotification(e)}}function at(t){return{...ls(t),index:t.index,within:t.within?at(t.within):void 0}}function ls(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:cs(t.text)}}}function cs(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function fs(t){return{press:e=>{X(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function us({onRequest:t,parent:e,proxyInlet:r,signal:s}){const n=new Jt(e,{signal:s}),o=[()=>{n.close()}];return qt(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 ds="@appetizeio/rpc:playwrightAdapter",Le=Symbol.for(ds);function hs(t){window[Le]&&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[Le]=e,()=>{window[Le]===e&&delete window[Le]}}function ps({onRequest:t,proxyInlet:e}){const[r,s]=ot(),o=[hs(s),()=>{r.close()}];return qt(r,e),t&&o.push(Pe(r,f=>{t(f,{source:"parent"})})),{cleanup:()=>{for(const f of o)f()},notifies:()=>r}}function _e(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...at(t),x:t.x,y:t.y}}function ys(t){return"to"in t?{from:_e(t.from),kind:"path",to:_e(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?_e(t.from):void 0,kind:"direction"}}function ws(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 ms=new Set(it),bs=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,gs=/(\{\{|\{[^{}]*\})/u;function Es(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,o]of t.split(gs).entries())if(n%2===0){if(o.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=o}else o==="{{"?r+="{":(s(),e.push(vs(o.slice(1,-1))));return s(),e}function Ss(t,e){if(!ms.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: ${it.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function vs(t){const e=bs.exec(t)?.groups,r=e?.key??t;if(Ss(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 As=Symbol("@appetizeio/client:v1Compat");function Ht(t){return t?.[As]}class Os{readable;ready;get dimensions(){return this.#s}#e=[];#r=!1;#t;#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.#t=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.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||this.#n()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#r||(this.#t.close(),this.#a(e))}#a(e){this.#r=!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 ks{#e=!1;#r;#t;#s=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Os({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.#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)}#i(e){this.#s.delete(e),!(this.#s.size>0||!this.#t)&&(this.#t=void 0,X(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,X(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Is{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const s=Ht(r)??{},{baseUrl:n,onClose:o,signal:f}=r;this.#e=n?xs(n):void 0;const{onRequest:m,parent:y,proxyRequest:v}=s,g=Ms(m);f?.addEventListener("abort",this.close);const[M,R]=ot(),[L,U]=ot();this.#r.push(()=>{M.close(),R.close(),L.close(),U.close()}),this.#r.push(nt(U,e,{leftEffects:v}));const P=y==="playwright"?ps({onRequest:g,proxyInlet:L}):y?us({onRequest:g,parent:y,proxyInlet:L,signal:f}):void 0;P&&this.#r.push(P.cleanup),this.#r.push(nt(R,L,{notifiesLeft:P?.notifies}));const{client:W,unsub:ye}=Zr(M,{"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=>{O.handleChunk(z)}});this.#t=W,this.#r.push(ye);const G=new as(this.#t);this.#r.push(()=>{G.close()});const O=new ks(this.#t);this.#r.push(()=>{O.close()}),this.debug=G,this.keyboard=fs(this.#t),this.touch=ws(this.#t),this.video=O,g&&(this.#r.push(Pe(R,z=>{g(z,{source:"self"})})),e instanceof Jt&&this.#r.push(Pe(e,z=>{g(z,{source:"iframe"})}))),this.#r.push(()=>o?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}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?at(e):void 0})}async open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){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,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.#t.request("appetizeio.device.server.swipe",{gesture:ys(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:_e(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:Es(e)})}}function xs(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Ms=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}},Rs={dateStyle:"medium",timeStyle:"short"},Ts=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;function lt(t){return Array.isArray(t)?t.map(lt).join(", "):typeof t=="boolean"?t?"yes":"no":typeof t=="number"?t.toLocaleString():Cs(t)}function Cs(t){if(Ts.test(t)){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.toLocaleString(void 0,Rs)}const e=bt();return t===e?"~":t.startsWith(`${e}${pr}`)?`~${t.slice(e.length)}`:t}class Ne extends Error{details;constructor(e,r={},s){super(e,s===void 0?void 0:{cause:s}),this.name="CommandError",this.details=r}hints(e){return[]}}class De extends Ne{sessionDir;constructor(e,r,s={},n){super(e,Object.assign({sessionDir:r},s),n),this.name="SessionError",this.sessionDir=r}static wrap(e,r){if(e instanceof De||e instanceof he)return e;const s=e instanceof Error?e.message:String(e),n=e instanceof Ne?e.details:{};return new De(s,r,n,e)}hints(){return[`Check the session logs for details: ${lt(this.sessionDir)}`]}}class he extends Ne{constructor(e){super(e),this.name="UsageError"}hints({command:e}){return[`Run 'appetize ${e} --help' for usage`]}}function Ps(t,e,r){const s=e instanceof Error?e.message:String(e);return e instanceof Ne?t==="json"?JSON.stringify({error:{message:s,...e.details}},null,2):[`\u2716 ${s}`,...e.hints(r).map(n=>` ${n}`)].join(`
|
|
2
|
+
`):t==="json"?JSON.stringify({error:{message:s}},null,2):`\u2716 ${s}`}function ct(t){try{return process.kill(t,0),!0}catch{return!1}}const Us=["SIGINT","SIGTERM"],Ls=150;function _s(t){const e=new AbortController,r=setInterval(()=>{ct(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},Ls);return r.unref(),e.signal}function Zt(){const t=new AbortController;for(const e of Us)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Ns(t,e){return new Promise((r,s)=>{if(e.aborted){s(Yt(e.reason));return}const n=()=>{clearTimeout(o),s(Yt(e.reason))},o=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function Yt(t){return t instanceof Error?t:new Error(String(t))}function Ds(t){const e=t.at(-1);return{options:zs(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:Zt()}}function Bs(t,e){const r=Xt(t,e);return r===void 0?void 0:Qt(r,e)}function Xt(t,e){if(t===void 0)return;const r=typeof t=="boolean"?Number.NaN:Number(t);if(!Number.isFinite(r))throw new he(`${e} expects a number, e.g., ${e}=-0.1`);return r}function ft(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new he(`${e} needs a value`);return t}}function Qt(t,e){if(!(t>=0&&t<=1))throw new he(`${e} expects a number between 0 and 1`);return t}function Fs(t,e){const r=ft(t,e);if(r===void 0)throw new he(`${e} needs a value`);return r}function zs(t){return typeof t=="object"&&t!==null}const js="APPETIZEIO_FEATURE_FLAGS";function Vs(){const t={};for(const e of(process.env[js]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function Ks(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function er(t){return ft(t.endpoint,"--endpoint")??$s()}function $s(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const qs="https://appetize.io";async function tr(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const o=new URL(t,er(r)??qs);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",Ks());const m=await fetch(o,{...n,headers:f});if(!m.ok)throw new Error(`The webserver rejected the request (${String(m.status)})`);return await m.json()}const rr=["android","ios"];function sr(t={},e){return tr("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function Js(t){return rr.includes(t)}async function Ws(t,e={}){return(await sr(e)).find(s=>s.id===t)?.platform}function Gs(t){let e={...t,updatedAt:new Date().toISOString()};return{path:dt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},rn(e),e)}}function Hs(){const t=ir();return gt(t,{recursive:!0}),br(t).map(e=>ut(e)).filter(e=>e!==void 0)}function Zs(t){if(t!==void 0){const r=ut(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Hs().filter(tn);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 ut(t){try{return JSON.parse(mr(dt(t),"utf8"))}catch{return}}function Ys(t){return te(ke(t),"control.sock")}function nr(t){return te(ke(t),"daemon.log")}function Xs(t){return te(ke(t),"device.log.jsonl")}function Qs(t,e){return{daemon:nr(t),device:Xs(t),...e==="intercept"?{network:en(t)}:void 0}}function en(t){return te(ke(t),"network.jsonl")}function ke(t){const e=or(t);return gt(e,{recursive:!0}),e}function dt(t){return te(ke(t),"state.json")}function ir(){return process.env.APPETIZE_CLI_HOME??te(bt(),".appetize","cli","sessions")}function or(t){return te(ir(),t)}function tn(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:ct(t.pid)}function rn(t){const e=dt(t.sessionId),r=`${e}.tmp`;yr(r,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),wr(r,e)}const ht="APPETIZE_DAEMON_CONFIG";function sn(){const t=process.env[ht];if(!t)throw new Error(`${ht} is not set`);return JSON.parse(t)}function nn(t){return JSON.stringify(t)}export{it as A,Br as B,T as C,Is as D,Pr as E,rt as F,Ht as G,Ue as H,sn as I,Gs as J,Ws as K,jt as L,nt as M,Ys as N,Zt as O,De as S,Oe as T,he as U,Xt as a,Ns as b,sr as c,Gr as d,rr as e,tr as f,Fs as g,nr as h,Js as i,ht as j,ut as k,Vs as l,er as m,Qs as n,or as o,ft as p,ct as q,Qt as r,nn as s,Bs as t,lt as u,Kt as v,Zs as w,_s as x,Ds as y,Ps as z};
|
package/daemon.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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,n as j,G as H,H as J,S as Q,I as k,J as G,K}from"./config-CmsJj7_W.js";import S from"debug";import{createServer as A}from"node:net";import{pipeline as $}from"node:stream";import{rm as B}from"node:fs/promises";import{readFileSync as Z,createWriteStream as X,existsSync as Y,rmSync as ee}from"node:fs";import{createServer as te}from"node:http";import{WebSocketServer as ne}from"ws";import{pipeline as re}from"node:stream/promises";import{EncodedVideoPacketSource as oe,Output as se,FilePathTarget as ie,Mp4OutputFormat as ae,EncodedPacket as ce}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:os";import"node:path";const de=S("appetize.io:transport:ws-ping"),ue=3e4;function le(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),de("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},ue);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}=le(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 fe(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 pe(r,o,t),o}function pe(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 he(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=we(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 we(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 ve(){return typeof process>"u"?void 0:process}function ge(e){return{deviceType:e.id,osVersion:e.osVersion}}function ye(e){return e==="intercept"?"interceptOnDemand":e}class g extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function me(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=>{be(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 be(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 Se(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=V();ke(s.reject,o);const i=await me(Ae(e),{onClose:()=>{s.reject(Ee())},onEvent:(c,a)=>{Te(c,a,s,r)},signal:o});return Le(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ee(){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 Te(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Re(t):Pe(t);o&&r?.(o)}else e==="newSession"?$e(n,t):e==="userError"&&n.reject(new g("denied",Ce(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 Le(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 ke(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ae(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function $e(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 Re(e){const t=I(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Pe(e){const t=I(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ce(e){return m(e,"message")??"The session request was denied"}async function Ie({apiToken:e=Ue(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,open:s,proxy:i,signal:c,target:a}){if(c?.throwIfAborted(),!a)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const d=await Se(r,{codec:t,launchUrl:s,noVideo:!0,proxy:ye(i),publicKey:a,...ge(n)},{apiToken:e,onQueue:p=>{o?.({phase:"queued",queue:p})},signal:c});return{baseUrl:new URL(d.path).origin,url:We(d)}}function Ue(){return ve()?.env.APPETIZE_API_TOKEN}function We(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 xe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},Me=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&U("Object expected");var r,o;r===void 0&&(r=t[xe("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},Oe=(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 ze=1e4;async function _e(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=Me(o,qe(ze,{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 Ie({device:e.device,endpoint:e.endpoint,onStateChange:d,open:e.open,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:p});const l=new E(u,{signal:a});return await he(l,{device:e.device,onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await fe(l,{baseUrl:p,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{Oe(o,s,i)}}function Fe(){const e=N(),t=j(e.sessionId,e.proxy),n=H({device:e.device,endpoint:e.endpoint,open:e.open,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 Ve(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)}),Ne(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 je(a,t,r);return{close:d,url:new URL(`adb://${p.address}:${String(p.port)}`)}}function Ne(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 je(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 He(e,t,n,{signal:r}={}){try{if(!await Je(t))return;const o=await Ve(e,{onError:s=>{f(`adb endpoint error: ${D(s)}`)},signal:r});n.save({adbSerial:o.url.host}),f(`adb endpoint listening at ${o.url.host}`)}catch(o){f(`adb endpoint unavailable: ${D(o)}`)}}async function Je(e){return await J(e.device.id,{endpoint:e.endpoint})==="android"}function D(e){return e instanceof Error?e.message:String(e)}async function Qe(e,t,{methods:n={},signal:r}={}){await B(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 Ge(e,t,n,{recorder:r,signal:o}){const s=G(n);return await Qe(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 q="127.0.0.1";async function Ke(e,t,n={}){try{const r=await Be(e,n);return t.save({viewerUrl:r.url.href}),f(`web endpoint listening at ${r.url.href}`),r}catch(r){f(`web endpoint unavailable: ${tt(r)}`);return}}async function Be(e,{port:t=0,signal:n,viewerHtml:r=Z(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const o=te((u,l)=>{Xe(u,l,r)}),s=new Set,i=new ne({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)=>{Ye(i,u,l,h)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const h of s)Ze(h);i.close(),o.close(h=>{h?l(h):u()})}),c),d=()=>{a()};await et(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://${q}:${String(p.port)}/`)}}function Ze(e){e.close(1001)}function Xe(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 Ye(e,t,n,r){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,r,o=>{e.emit("connection",o,t)})}function et(e,t){return new Promise((n,r)=>{const o=s=>{r(s)};e.once("error",o),e.listen(t,q,()=>{e.removeListener("error",o),n()})})}function tt(e){return e instanceof Error?e.message:String(e)}function nt(e){const t=new AbortController,n=rt(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 rt(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 x(e,t,{label:n,signal:r}){try{const o=await e();await re(o.readable.pipeThrough(ot()),X(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 ot(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
|
|
2
|
-
`)}})}async function st(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function it(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const T=30;async function at(e,t){await e.pipeTo(dt(t))}function ct(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function dt(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 ut(ft(r),e),lt(t,r),await pt(t,r))}})}async function ut(e,t){const n=new oe("avc"),r=new se({format:new ae({fastStart:"fragmented"}),target:new ie(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 lt(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 ft(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function pt(e,t){const n=new ce(t.data,t.type,e.frame/T,1/T);e.frame+=1,await e.source.add(n,ct(e.size))}function ht(e,t,{signal:n}={}){let r,o;const s=async(a,{force:d=!1}={})=>{if(Y(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);ee(a)}const p=await e.video.createStream({signal:n});return r={done:wt(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 wt(e,t){try{await at(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function vt(){const{config:e,logs:t,store:n}=Fe();f(`recording to ${n.path}`);const{shutdown:r,signal:o}=nt(n);try{const{device:s,transport:i}=await
|
|
1
|
+
import{T as M,B as L,C as O,E as b,F as _,D as z,G as F,H as V,I as N,n as j,J as H,K as J,L as Q,M as k,N as G,O as K}from"./config-D0ukqfLN.js";import S from"debug";import{createServer as A}from"node:net";import{pipeline as $}from"node:stream";import{rm as B}from"node:fs/promises";import{readFileSync as Z,createWriteStream as X,existsSync as Y,rmSync as ee}from"node:fs";import{createServer as te}from"node:http";import{WebSocketServer as ne}from"ws";import{pipeline as re}from"node:stream/promises";import{EncodedVideoPacketSource as oe,Output as se,FilePathTarget as ie,Mp4OutputFormat as ae,EncodedPacket as ce}from"mediabunny";import"stream";import"module";import"json-rpc-2.0";import"node:os";import"node:path";const de=S("appetize.io:transport:ws-ping"),ue=3e4;function le(e){let t=!0;const n=()=>{t=!0};e.on("pong",n);const r=setInterval(()=>{if(!t){clearInterval(r),de("liveness ping went unanswered, terminating"),e.terminate();return}e.readyState===e.OPEN&&(t=!1,e.ping())},ue);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}=le(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 _(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 fe(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 z(r,{...t,baseUrl:n});return typeof e=="string"&&await pe(r,o,t),o}function pe(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 he(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=we(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 we(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 ve(){return typeof process>"u"?void 0:process}function ge(e){return{deviceType:e.id,osVersion:e.osVersion}}function ye(e){return e==="intercept"?"interceptOnDemand":e}class g extends Error{code;constructor(t,n){super(n),this.name="SessionRequestError",this.code=t}}function me(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=>{be(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 be(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 Se(e,t,{apiToken:n,onQueue:r,signal:o}={}){const s=V();ke(s.reject,o);const i=await me(Ae(e),{onClose:()=>{s.reject(Ee())},onEvent:(c,a)=>{Te(c,a,s,r)},signal:o});return Le(e,{apiToken:n,data:t,socketid:i.id},o).catch(s.reject),await s.promise.finally(()=>{i.close()})}function Ee(){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 Te(e,t,n,r){if(e==="queue"||e==="concurrentQueue"){const o=e==="queue"?Re(t):Pe(t);o&&r?.(o)}else e==="newSession"?$e(n,t):e==="userError"&&n.reject(new g("denied",Ce(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 Le(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 ke(e,t){t?.addEventListener("abort",()=>{e(t.reason)},{once:!0})}function Ae(e){const t=new URL("/client",e);return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.href}function $e(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 Re(e){const t=I(e,"position");return t===void 0?void 0:{position:t,reason:"capacity"}}function Pe(e){const t=I(e,"position");if(t!==void 0)return{limit:m(e,"name")??"Queue",position:t,reason:"concurrency"}}function Ce(e){return m(e,"message")??"The session request was denied"}async function Ie({apiToken:e=Ue(),codec:t="h264",device:n,endpoint:r="https://appetize.io",onStateChange:o,open:s,proxy:i,signal:c,target:a}){if(c?.throwIfAborted(),!a)throw new TypeError("target is required");if(!n.id)throw new TypeError("device.id is required");o?.({phase:"requesting"});const d=await Se(r,{codec:t,launchUrl:s,noVideo:!0,proxy:ye(i),publicKey:a,...ge(n)},{apiToken:e,onQueue:p=>{o?.({phase:"queued",queue:p})},signal:c});return{baseUrl:new URL(d.path).origin,url:We(d)}}function Ue(){return ve()?.env.APPETIZE_API_TOKEN}function We(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 xe=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},Me=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&U("Object expected");var r,o;r===void 0&&(r=t[xe("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},Oe=(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 ze(e,t,{onClose:n,signal:r}={}){var o=[];try{const c=Me(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 Ie({device:e.device,endpoint:e.endpoint,onStateChange:d,open:e.open,proxy:e.proxy,signal:a,target:e.target});t.save({baseUrl:p});const l=new E(u,{signal:a});return await he(l,{device:e.device,onStateChange:d,signal:a}),l.onclose=()=>{n?.("The device connection closed")},{device:await fe(l,{baseUrl:p,signal:a}),transport:l}}catch(c){var s=c,i=!0}finally{Oe(o,s,i)}}function Fe(){const e=N(),t=j(e.sessionId,e.proxy),n=H({device:e.device,endpoint:e.endpoint,open:e.open,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 Ve(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)}),Ne(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 je(a,t,r);return{close:d,url:new URL(`adb://${p.address}:${String(p.port)}`)}}function Ne(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 je(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 He(e,t,n,{signal:r}={}){try{if(!await Je(t))return;const o=await Ve(e,{onError:s=>{f(`adb endpoint error: ${D(s)}`)},signal:r});n.save({adbSerial:o.url.host}),f(`adb endpoint listening at ${o.url.host}`)}catch(o){f(`adb endpoint unavailable: ${D(o)}`)}}async function Je(e){return await J(e.device.id,{endpoint:e.endpoint})==="android"}function D(e){return e instanceof Error?e.message:String(e)}async function Qe(e,t,{methods:n={},signal:r}={}){await B(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 Ge(e,t,n,{recorder:r,signal:o}){const s=G(n);return await Qe(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 q="127.0.0.1";async function Ke(e,t,n={}){try{const r=await Be(e,n);return t.save({viewerUrl:r.url.href}),f(`web endpoint listening at ${r.url.href}`),r}catch(r){f(`web endpoint unavailable: ${tt(r)}`);return}}async function Be(e,{port:t=0,signal:n,viewerHtml:r=Z(new URL("./viewer.html",import.meta.url),"utf8")}){n?.throwIfAborted();const o=te((u,l)=>{Xe(u,l,r)}),s=new Set,i=new ne({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)=>{Ye(i,u,l,h)});const a=()=>(c??=new Promise((u,l)=>{n?.removeEventListener("abort",d);for(const h of s)Ze(h);i.close(),o.close(h=>{h?l(h):u()})}),c),d=()=>{a()};await et(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://${q}:${String(p.port)}/`)}}function Ze(e){e.close(1001)}function Xe(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 Ye(e,t,n,r){if(t.url!=="/ws"){n.destroy();return}e.handleUpgrade(t,n,r,o=>{e.emit("connection",o,t)})}function et(e,t){return new Promise((n,r)=>{const o=s=>{r(s)};e.once("error",o),e.listen(t,q,()=>{e.removeListener("error",o),n()})})}function tt(e){return e instanceof Error?e.message:String(e)}function nt(e){const t=new AbortController,n=rt(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 rt(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 x(e,t,{label:n,signal:r}){try{const o=await e();await re(o.readable.pipeThrough(ot()),X(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 ot(){return new TransformStream({transform:(e,t)=>{t.enqueue(`${JSON.stringify(e)}
|
|
2
|
+
`)}})}async function st(e,t,{signal:n}={}){await x(async()=>await e.debug.createLogStream({signal:n}),t,{label:"log capture",signal:n})}async function it(e,t,{signal:n}={}){await x(async()=>await e.debug.createProxyInterceptStream({signal:n}),t,{label:"network capture",signal:n})}const T=30;async function at(e,t){await e.pipeTo(dt(t))}function ct(e){return{decoderConfig:{codec:"avc1.640028",codedHeight:e.height,codedWidth:e.width}}}function dt(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 ut(ft(r),e),lt(t,r),await pt(t,r))}})}async function ut(e,t){const n=new oe("avc"),r=new se({format:new ae({fastStart:"fragmented"}),target:new ie(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 lt(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 ft(e){if(e.type!=="key")throw new Error("Video stream started without a key chunk");return e}async function pt(e,t){const n=new ce(t.data,t.type,e.frame/T,1/T);e.frame+=1,await e.source.add(n,ct(e.size))}function ht(e,t,{signal:n}={}){let r,o;const s=async(a,{force:d=!1}={})=>{if(Y(a)){if(!d)throw new Error(`A recording already exists at ${a}; pass --force to overwrite`);ee(a)}const p=await e.video.createStream({signal:n});return r={done:wt(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 wt(e,t){try{await at(e.readable,t)}catch(n){f(`video capture ended with an error: ${String(n)}`)}}async function vt(){const{config:e,logs:t,store:n}=Fe();f(`recording to ${n.path}`);const{shutdown:r,signal:o}=nt(n);try{const{device:s,transport:i}=await ze(e,n,{onClose:r,signal:o}),c=ht(s,n,{signal:o});await He(s,e,n,{signal:o}),await Ke(i,n,{signal:o});const a=await Ge(i,n,e.sessionId,{recorder:c,signal:o});f(`control socket listening at ${a}`),st(s,t.device,{signal:o}),f(`recording device logs to ${t.device}`),t.network&&(it(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}}vt();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appetize/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.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",
|
|
@@ -28,10 +28,11 @@
|
|
|
28
28
|
"appetize": "cli.js"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
+
"cli-table3": "^0.6.5",
|
|
31
32
|
"debug": "^4.4.3",
|
|
32
33
|
"human-id": "^4.2.1",
|
|
33
|
-
"json-rpc-2.0": "^1.8.
|
|
34
|
-
"mediabunny": "^1.58.
|
|
34
|
+
"json-rpc-2.0": "^1.8.1",
|
|
35
|
+
"mediabunny": "^1.58.1",
|
|
35
36
|
"sade": "^1.8.1",
|
|
36
37
|
"ws": "^8.21.3",
|
|
37
38
|
"yocto-spinner": "^1.2.2"
|
package/skills/appetize/SKILL.md
CHANGED
|
@@ -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.
|
|
13
|
+
cli-version: '0.19.0'
|
|
14
14
|
---
|
|
15
15
|
|
|
16
16
|
# Appetize
|
|
@@ -31,7 +31,8 @@ Confirm the CLI is installed and note the version:
|
|
|
31
31
|
appetize --version
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
-
End every command with `--json`, so its result is always JSON.
|
|
34
|
+
End every command with `--json`, so its result is always JSON. If your tool runs
|
|
35
|
+
commands in a terminal, add `--quiet` too.
|
|
35
36
|
|
|
36
37
|
`APPETIZE_API_TOKEN` must be set for private APIs and session targets. A target
|
|
37
38
|
is an uploaded build's public key, e.g. `app_a1b2c3`. Discover one with
|
|
@@ -278,10 +279,8 @@ transcript is the record — never commit screenshots or recordings to the repo.
|
|
|
278
279
|
| Element not found | Re-inspect. It is off screen, covered, or the screen changed. |
|
|
279
280
|
| App fails only on network calls | If you started with `--proxy`, retry without it. |
|
|
280
281
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
`session start` is taking a while, that sequence tells you whether you are
|
|
284
|
-
queued for capacity or waiting on an install.
|
|
282
|
+
If `session start` is taking a while, `state.phase` in its `state.json` tells
|
|
283
|
+
you whether you are queued for capacity or waiting on an install.
|
|
285
284
|
|
|
286
285
|
## Dismissing the soft keyboard
|
|
287
286
|
|
|
@@ -326,6 +325,11 @@ appetize inspect --select-test-id order-42 --timeout 5000 --json
|
|
|
326
325
|
screen with `inspect --timeout`. A custom scheme needs its app installed on the
|
|
327
326
|
device. iOS caps URLs at 2048 characters.
|
|
328
327
|
|
|
328
|
+
## Logged-out state
|
|
329
|
+
|
|
330
|
+
On iOS, `appetize keychain clear` clears the entire keychain without restarting
|
|
331
|
+
the session. It has no effect on Android.
|
|
332
|
+
|
|
329
333
|
## Full command reference
|
|
330
334
|
|
|
331
335
|
`references/commands.md` has every command, flag, output shape and exit
|
|
@@ -16,6 +16,7 @@ same flags at the terminal.
|
|
|
16
16
|
- [press](#press)
|
|
17
17
|
- [rotate](#rotate)
|
|
18
18
|
- [open](#open)
|
|
19
|
+
- [keychain clear](#keychain-clear)
|
|
19
20
|
- [screenshot](#screenshot)
|
|
20
21
|
- [recording start](#recording-start)
|
|
21
22
|
- [recording stop](#recording-stop)
|
|
@@ -26,7 +27,10 @@ same flags at the terminal.
|
|
|
26
27
|
|
|
27
28
|
## Global
|
|
28
29
|
|
|
29
|
-
`--json` prints the result as JSON. End every command with it.
|
|
30
|
+
`--json` prints the result as JSON. End every command with it. `--no-json`
|
|
31
|
+
prints text.
|
|
32
|
+
|
|
33
|
+
`--quiet` hides the progress spinner shown on an interactive terminal.
|
|
30
34
|
|
|
31
35
|
`--session-id <id>` is accepted by every command except those marked "Takes
|
|
32
36
|
no session". On
|
|
@@ -57,9 +61,7 @@ once the device is ready; `--no-wait` prints `{ logs, sessionId }` immediately.
|
|
|
57
61
|
available to it: `adb connect <adbSerial>` attaches to the device until the
|
|
58
62
|
session ends. `viewerUrl` opens the local browser viewer. `logs`
|
|
59
63
|
carries a `device` and a `daemon` path, plus a `network` path — the JSONL capture
|
|
60
|
-
of the app's traffic — when started with `--proxy` (or `--proxy intercept`).
|
|
61
|
-
`requesting`, `queued`, `starting`, `downloadingApp`, `installingApp`,
|
|
62
|
-
`launchingApp`, `ready`.
|
|
64
|
+
of the app's traffic — when started with `--proxy` (or `--proxy intercept`).
|
|
63
65
|
|
|
64
66
|
Network traffic can be proxied or intercepted for debugging. `--proxy` (or
|
|
65
67
|
`--proxy intercept`) provisions the intercepting proxy so traffic can be
|
|
@@ -77,7 +79,7 @@ and starting a session with an id already in use fails.
|
|
|
77
79
|
appetize session stop
|
|
78
80
|
```
|
|
79
81
|
|
|
80
|
-
Signals the daemon to shut down and prints `{
|
|
82
|
+
Signals the daemon to shut down and prints `{ sessionId }`. Reports
|
|
81
83
|
the id even if the daemon had already exited, so it is safe to call twice.
|
|
82
84
|
|
|
83
85
|
## build list
|
|
@@ -115,7 +117,7 @@ appetize build upload <file> [options]
|
|
|
115
117
|
|
|
116
118
|
Uploads a `.apk`, `.apks`, `.zip` or `.tar.gz` and prints
|
|
117
119
|
`{ created, id, platform }` on stdout, where `id` is a target `session start`
|
|
118
|
-
takes.
|
|
120
|
+
takes.
|
|
119
121
|
|
|
120
122
|
The extension decides the platform — `.apk` and `.apks` are Android, `.zip`,
|
|
121
123
|
`.tar.gz` and `.tgz` are iOS — and any other file is refused before uploading.
|
|
@@ -174,7 +176,7 @@ appetize tap [options]
|
|
|
174
176
|
| `--select-*` | Element or position to tap — see [Selectors](#selectors) |
|
|
175
177
|
| `--timeout` | Milliseconds to wait for the element |
|
|
176
178
|
|
|
177
|
-
Prints `{
|
|
179
|
+
Prints `{}`. Combining an element selector with `--select-x` /
|
|
178
180
|
`--select-y` taps a point within that element, and values outside `0-1` are
|
|
179
181
|
allowed to reach just beyond its edge (e.g. `--select-x=-0.1`).
|
|
180
182
|
|
|
@@ -193,7 +195,7 @@ appetize swipe [options]
|
|
|
193
195
|
| `--duration` | Milliseconds the gesture travels for |
|
|
194
196
|
| `--timeout` | Milliseconds to wait for any `--from`/`--to` elements |
|
|
195
197
|
|
|
196
|
-
Prints `{
|
|
198
|
+
Prints `{}`. Two shapes are valid: a `--direction` with an
|
|
197
199
|
optional `--from-*` starting point, or both a `--from-*` and a `--to-*` point to
|
|
198
200
|
form a path. Mixing `--direction` with `--to-*` is an error, as is `--distance`
|
|
199
201
|
without `--direction`.
|
|
@@ -208,7 +210,7 @@ appetize type <text> [options]
|
|
|
208
210
|
| --------- | ---------------------------------- |
|
|
209
211
|
| `--delay` | Milliseconds to wait between steps |
|
|
210
212
|
|
|
211
|
-
Prints `{
|
|
213
|
+
Prints `{}`. Bare text is delivered as a string; `{...}` names a
|
|
212
214
|
key delivered as a keystroke. Supported keys: `ArrowDown`, `ArrowLeft`,
|
|
213
215
|
`ArrowRight`, `ArrowUp`, `Backspace`, `Enter`, `Tab`. A token may carry a repeat
|
|
214
216
|
count as in `{Backspace>16/}`, and `{{` types a literal `{`. An unclosed token
|
|
@@ -222,7 +224,7 @@ Typing does not focus a field — tap it first.
|
|
|
222
224
|
appetize press <button>
|
|
223
225
|
```
|
|
224
226
|
|
|
225
|
-
Prints `{
|
|
227
|
+
Prints `{}`. Buttons: `home` and `lock` on both platforms;
|
|
226
228
|
`back`, `menu`, `unlock`, `volumeUp` and `volumeDown` on Android only. Calling
|
|
227
229
|
an Android-only button on iOS fails.
|
|
228
230
|
|
|
@@ -235,7 +237,7 @@ main page.
|
|
|
235
237
|
appetize rotate <orientation>
|
|
236
238
|
```
|
|
237
239
|
|
|
238
|
-
Prints
|
|
240
|
+
Prints `{}`. Orientations: `portrait`, `landscapeLeft`,
|
|
239
241
|
`landscapeRight`, `upsideDown`.
|
|
240
242
|
|
|
241
243
|
## open
|
|
@@ -244,9 +246,18 @@ Prints the resulting orientation. Orientations: `portrait`, `landscapeLeft`,
|
|
|
244
246
|
appetize open <url>
|
|
245
247
|
```
|
|
246
248
|
|
|
247
|
-
Prints `{
|
|
249
|
+
Prints `{}`. `<url>` is a deep link (`myapp://orders/42`) or an
|
|
248
250
|
http(s) URL. A malformed or scheme-less value is refused.
|
|
249
251
|
|
|
252
|
+
## keychain clear
|
|
253
|
+
|
|
254
|
+
```
|
|
255
|
+
appetize keychain clear
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Prints `{}`. iOS only: clears the entire keychain. No effect on
|
|
259
|
+
Android.
|
|
260
|
+
|
|
250
261
|
## screenshot
|
|
251
262
|
|
|
252
263
|
```
|
|
@@ -254,7 +265,7 @@ appetize screenshot [output]
|
|
|
254
265
|
```
|
|
255
266
|
|
|
256
267
|
`output` defaults to `screenshot`, and an extension matching the image is added
|
|
257
|
-
if you omit one. Writes a PNG and prints `{ bytes,
|
|
268
|
+
if you omit one. Writes a PNG and prints `{ bytes, output }`.
|
|
258
269
|
|
|
259
270
|
## recording start
|
|
260
271
|
|
|
@@ -267,7 +278,7 @@ appetize recording start <output> [options]
|
|
|
267
278
|
| `--force` | Overwrite the file if it already exists |
|
|
268
279
|
|
|
269
280
|
Asks the daemon to open the device video stream and capture it to `output`,
|
|
270
|
-
printing `{ path
|
|
281
|
+
printing `{ path }`. Capture is opt-in — video is lazy
|
|
271
282
|
device-side, so nothing streams until this runs.
|
|
272
283
|
|
|
273
284
|
`output` is required. `.mp4` is added if you omit an extension, any other
|
|
@@ -286,7 +297,7 @@ capture is running.
|
|
|
286
297
|
appetize recording stop
|
|
287
298
|
```
|
|
288
299
|
|
|
289
|
-
Closes the stream and the file, printing `{ path
|
|
300
|
+
Closes the stream and the file, printing `{ path }`. Fails
|
|
290
301
|
with `No video recording in progress` when nothing is recording. Ending the
|
|
291
302
|
session while recording closes the file too, noting it in `daemon.log`.
|
|
292
303
|
|
|
@@ -357,6 +368,7 @@ slider track.
|
|
|
357
368
|
| `APPETIZE_API_TOKEN` | Authorizes private APIs and session targets |
|
|
358
369
|
| `APPETIZE_ENDPOINT` | Appetize URL used when `--endpoint` is omitted |
|
|
359
370
|
| `APPETIZE_CLI_HOME` | Overrides the session state directory |
|
|
371
|
+
| `APPETIZE_OUTPUT` | `json` or `text` when neither flag is passed |
|
|
360
372
|
|
|
361
373
|
Session state is written to `~/.appetize/cli/sessions/<session-id>/state.json`.
|
|
362
374
|
Device logs stream as JSONL to `device.log.jsonl` beside it, and the daemon's
|
|
@@ -364,12 +376,16 @@ own output goes to `daemon.log`.
|
|
|
364
376
|
|
|
365
377
|
## Exit codes and output streams
|
|
366
378
|
|
|
367
|
-
Commands exit `0` on success and non-zero on failure, printing
|
|
368
|
-
|
|
369
|
-
|
|
379
|
+
Commands exit `0` on success and non-zero on failure, printing
|
|
380
|
+
`{ "error": { "message": "…" } }` to stderr (text on a terminal, unless
|
|
381
|
+
`--json`), plus `sessionDir` (the session's
|
|
382
|
+
logs and `state.json`) once a session is found, unless the command was misused.
|
|
383
|
+
A selector `--timeout` that expires is a failure, which is what makes it usable
|
|
384
|
+
as a wait.
|
|
370
385
|
|
|
371
|
-
|
|
372
|
-
stderr
|
|
386
|
+
Results go to stdout as JSON (text on a terminal, unless `--json`) and hold
|
|
387
|
+
only what you could not know beforehand; `{}` means the command ran. stderr
|
|
388
|
+
carries only errors, plus a progress spinner on an interactive terminal.
|
|
373
389
|
|
|
374
390
|
Common failures:
|
|
375
391
|
|
|
@@ -377,4 +393,4 @@ Common failures:
|
|
|
377
393
|
| --------------------------- | --------------------------------------------------------------------------------- |
|
|
378
394
|
| `No active sessions` | `session start` first; if one should be live, its `daemon.log` says why it exited |
|
|
379
395
|
| `No session found for id X` | `endedReason` in the session's `state.json` |
|
|
380
|
-
| `Session is not ready` | `state.phase` in `state.json` says how far it got
|
|
396
|
+
| `Session is not ready` | `state.phase` in `state.json` under `error.sessionDir` says how far it got |
|
package/viewer.html
CHANGED
|
@@ -1,2 +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,b;function N(...O){if(!N.enabled)return;const m=N,g=Number(new Date),I=g-(v||g);m.diff=I,m.prev=v,m.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(m,L),O.splice(_,1),_--}return q}),n.formatArgs.call(m,O),(m.log||n.log).apply(m,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,b=n.enabled(p)),b),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,b=-1,N=0;for(;f<p.length;)if(C<v.length&&(v[C]===p[f]||v[C]==="*"))v[C]==="*"?(b=C,N=f,C++):(f++,C++);else if(b!==-1)C=b+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={},bt;function _e(){return bt||(bt=1,(function(t){var e=Ce&&Ce.__extends||(function(){var f=function(C,b){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(N,O){N.__proto__=O}||function(N,O){for(var m in O)Object.prototype.hasOwnProperty.call(O,m)&&(N[m]=O[m])},f(C,b)};return function(C,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");f(C,b);function N(){this.constructor=C}C.prototype=b===null?Object.create(b):(N.prototype=b.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,b){var N={code:f,message:C};return b!=null&&(N.data=b),N},c=(function(f){e(C,f);function C(b,N,O){var m=f.call(this,b)||this;return Object.setPrototypeOf(m,C.prototype),m.code=N,m.data=O,m}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,b,N){return{jsonrpc:t.JSONRPC,id:f,error:y(C,b,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,b){return{jsonrpc:t.JSONRPC,id:f,method:C,params:b}};t.createJSONRPCRequest=p;var v=function(f,C){return{jsonrpc:t.JSONRPC,method:f,params:C}};t.createJSONRPCNotification=v})(Ce)),Ce}var Ee={},mt;function St(){return mt||(mt=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{b(h.next(N))}catch(O){v(O)}}function C(N){try{b(h.throw(N))}catch(O){v(O)}}function b(N){N.done?p(N.value):w(N.value).then(f,C)}b((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(b){return function(N){return C([b,N])}}function C(b){if(h)throw new TypeError("Generator is already executing.");for(;v&&(v=0,b[0]&&(c=0)),c;)try{if(h=1,w&&(p=b[0]&2?w.return:b[0]?w.throw||((p=w.return)&&p.call(w),0):w.next)&&!(p=p.call(w,b[1])).done)return p;switch(w=0,p&&(b=[b[0]&2,p.value]),b[0]){case 0:case 1:p=b;break;case 4:return c.label++,{value:b[1],done:!1};case 5:c.label++,w=b[1],b=[0];continue;case 7:b=c.ops.pop(),c.trys.pop();continue;default:if(p=c.trys,!(p=p.length>0&&p[p.length-1])&&(b[0]===6||b[0]===2)){c=0;continue}if(b[0]===3&&(!p||b[1]>p[0]&&b[1]<p[3])){c.label=b[1];break}if(b[0]===6&&c.label<p[1]){c.label=p[1],p=b;break}if(p&&c.label<p[2]){c.label=p[2],c.ops.push(b);break}p[2]&&c.ops.pop(),c.trys.pop();continue}b=y.call(o,c)}catch(N){b=[6,N],w=0}finally{h=p=0}if(b[0]&5)throw b[1];return{value:b[0]?b[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(b){var N=h.idToResolveMap.get(b);N&&(h.idToResolveMap.delete(b),N(c(b)))})},y);return f().then(function(b){return clearTimeout(C),b},function(b){return clearTimeout(C),Promise.reject(b)})},p=function(v,f){var C=(Array.isArray(v)?v:[v]).map(function(b){return b.id}).filter(i);return w(C,function(){return h.requestAdvanced(v,f)})};return{request:function(v,f,C){var b=h._createID();return w([b],function(){return h.requestWithID(v,f,C,b)})},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(b){return h.idToResolveMap.set(C.id,b)})}),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(b){h.receive((0,r.createJSONRPCErrorResponse)(b.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 m,g=1,I=arguments.length;g<I;g++){m=arguments[g];for(var _ in m)Object.prototype.hasOwnProperty.call(m,_)&&(O[_]=m[_])}return O},e.apply(this,arguments)},r=ne&&ne.__awaiter||function(O,m,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,m||[])).next())})},n=ne&&ne.__generator||function(O,m){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=m.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,m,g){if(g||arguments.length===2)for(var I=0,_=m.length,M;I<_;I++)(M||!(I in m))&&(M||(M=Array.prototype.slice.call(m,0,I)),M[I]=m[I]);return O.concat(M||Array.prototype.slice.call(m))};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(m){m===void 0&&(m={});var g;this.mapErrorToJSONRPCErrorResponse=C,this.handleMethodNotFound=b,this.nameToMethodDictionary={},this.middleware=null,this.errorListener=(g=m.errorListener)!==null&&g!==void 0?g:console.warn}return O.prototype.hasMethod=function(m){return!!this.nameToMethodDictionary[m]},O.prototype.addMethod=function(m,g){this.addMethodAdvanced(m,this.toJSONRPCMethod(g))},O.prototype.removeMethod=function(m){delete this.nameToMethodDictionary[m]},O.prototype.toJSONRPCMethod=function(m){return function(g,I){var _=m(g.params,I);return Promise.resolve(_).then(function(M){return f(g.id,M)})}},O.prototype.addMethodAdvanced=function(m,g){var I;this.nameToMethodDictionary=e(e({},this.nameToMethodDictionary),(I={},I[m]=g,I))},O.prototype.receiveJSON=function(m,g){var I=this.tryParseRequestJSON(m);return I?this.receive(I,g):Promise.resolve(y())},O.prototype.tryParseRequestJSON=function(m){try{return JSON.parse(m)}catch{return null}},O.prototype.receive=function(m,g){return Array.isArray(m)?this.receiveMultiple(m,g):this.receiveSingle(m,g)},O.prototype.receiveMultiple=function(m,g){return r(this,void 0,void 0,function(){var I,_=this;return n(this,function(M){switch(M.label){case 0:return m.length===0?[2,(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")]:[4,Promise.all(m.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(m,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[m.method],(0,i.isJSONRPCRequest)(m)?[3,1]:[2,(0,t.createInvalidRequestResponse)(m)];case 1:return[4,this.callMethod(I,m,g)];case 2:return _=M.sent(),[2,N(m,_)]}})})},O.prototype.applyMiddleware=function(){for(var m=[],g=0;g<arguments.length;g++)m[g]=arguments[g];this.middleware?this.middleware=this.combineMiddlewares(s([this.middleware],m,!0)):this.middleware=this.combineMiddlewares(m)},O.prototype.combineMiddlewares=function(m){return m.length?m.reduce(this.middlewareReducer):null},O.prototype.middlewareReducer=function(m,g){return function(I,_,M){return m(function(q,z){return g(I,q,z)},_,M)}},O.prototype.callMethod=function(m,g,I){var _=this,M=function(z,X){return m?m(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(m,g){return m!==void 0?this.mapErrorToJSONRPCErrorResponse(m,g):null},O})();t.JSONRPCServer=w;var p=function(O){return O!==null},v=function(O,m,g){return O(m,g)},f=function(O,m){return O!==void 0?(0,i.createJSONRPCSuccessResponse)(O,m):null},C=function(O,m){var g,I=(g=m?.message)!==null&&g!==void 0?g:"An unexpected error occurred",_=o.DefaultErrorCode,M;return m instanceof i.JSONRPCErrorException&&(_=m.code,M=m.data),(0,i.createJSONRPCErrorResponse)(O,_,I,M)},b=function(O){return r(void 0,void 0,void 0,function(){return n(this,function(m){return O.id!==void 0?[2,(0,t.createMethodNotFoundResponse)(O.id)]:[2,null]})})},N=function(O,m){return m||(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(b){w(b)}}function v(C){try{f(y.throw(C))}catch(b){w(b)}}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 extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function pr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:hr;return new r(t,e)}class yr{#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 wr extends yr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(pr("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}),gr(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 vr(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 gr(t){return new ke.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const br=(...t)=>vr(...t),He=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],mr=33333,Sr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Er=new Set(He);class Rr{#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=Pr(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+=mr}}}}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 Or(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=i=>{i.altKey||i.ctrlKey||i.metaKey||!Ir(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 Ar(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 Mr(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 Rr({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 Pr(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),s=Sr.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 Ir(t){return Array.from(Cr.segment(t)).length===1||Er.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 Nr=105,_r=57342,kr=57343,Nt=57337,_t=6,ge={};let Re=11281e4,ce=1681e4,U={},K,Le,Te=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(U=this,Y=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return K=this.structures,xe();(!K||K.length>0)&&(K=[])}else U=kt,(!K||K.length>0)&&(K=[]),Y=null;return xe()}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(xe())===!1)return}else{for(n=[o];d<i;)s=d,n.push(xe());return n}}catch(i){throw i.lastPosition=s,i.values=n,i}finally{Me=!1,rt()}}}function xe(){try{let t=J();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 J(){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 xr();t=G.getUint16(d),d+=2;break;case 26:if(e==7){let r=G.getFloat32(d);if(U.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 U.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=J())!=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(U.mapsAsObjects){let o={},y=0;if(U.keyMap)for(;(i=J())!=ge;){if(y++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(U.decodeKey(i))]=J()}else for(;(i=J())!=ge;){if(y++>=ce)throw new Error(`Property count exceeds ${ce}`);o[re(i)]=J()}return o}else{Ae&&(U.mapsAsObjects=!0,Ae=!1);let o=new Map;if(U.keyMap){let y=0;for(;(i=J())!=ge;){if(y++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(U.decodeKey(i),J())}}else{let y=0;for(;(i=J())!=ge;){if(y++>=ce)throw new Error(`Map size exceeds ${ce}`);o.set(i,J())}}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 Tr(t);case 3:if(Oe>=d)return Le.slice(d-Te,(d+=t)-Te);if(Oe==0&&Q<140&&t<32){let s=t<16?Tt(t):Lr(t);if(s!=null)return s}return Fr(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]=J();return r;case 5:if(t>=ce)throw new Error(`Map size exceeds ${Re}`);if(t>(Q-d)/2)throw de();if(U.mapsAsObjects){let s={};if(U.keyMap)for(let i=0;i<t;i++)s[re(U.decodeKey(J()))]=J();else for(let i=0;i<t;i++)s[re(J())]=J();return s}else{Ae&&(U.mapsAsObjects=!0,Ae=!1);let s=new Map;if(U.keyMap)for(let i=0;i<t;i++)s.set(U.decodeKey(J()),J());else for(let i=0;i<t;i++)s.set(J(),J());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==kr){let i=me(),o=J(),y=J();et(o,y);let c={};if(U.keyMap)for(let h=2;h<i;h++){let w=U.decodeKey(y[h-2]);c[re(w)]=J()}else for(let h=2;h<i;h++){let w=y[h-2];c[re(w)]=J()}return c}else if(t==_r){let i=me(),o=J();for(let y=2;y<i;y++)et(o++,J());return J()}else if(t==Nt)return qr();if(U.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(J):n(J());{let s=J();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(J);n=n.next}if(this.slowReads++>=Ft){let i=this.length==r?this:this.slice(0,r);return n=U.keyMap?new Function("r","return {"+i.map(o=>U.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(J)}let s={};if(U.keyMap)for(let i=0;i<r;i++)s[re(U.decodeKey(this[i]))]=J();else for(let i=0;i<r;i++)s[re(this[i])]=J();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 Fr=Qe;function Qe(t){let e;if(t<16&&(e=Tt(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 Lr(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 Tt(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 b=A[d++];if((b&128)>0){d-=15;return}return H(e,r,n,s,i,o,y,c,h,w,p,v,f,C,b)}}}}}function Tr(t){return U.copyBuffers?Uint8Array.prototype.slice.call(A,d,d+=t):A.subarray(d,d+=t)}let xt=new Float32Array(1),Ue=new Uint8Array(xt.buffer,0,4);function xr(){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 Ue[3]=t&128|(r>>1)+56,Ue[2]=(t&7)<<5|e>>3,Ue[1]=e<<5,Ue[0]=0,xt[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[Nr]=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 Ur={Error,RegExp};V[27]=t=>(Ur[t[0]]||Error)(t[1],t[2]);const Ut=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()};Ut.handlesRead=!0,V[51]=Ut,V[_t]=t=>{if(!Y)if(U.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=>(U.mapsAsObjects&&(U.mapsAsObjects=!1,Ae=!0),t())).handlesRead=!0;function be(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function pe(){if(!Y)if(U.getShared)tt();else throw new Error("No packed values available");return Y}const Jr=1399353956;Ye.push((t,e)=>{if(t>=225&&t<=255)return be(pe().prefixes[t-224],e);if(t>=28704&&t<=32767)return be(pe().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return be(pe().prefixes[t-1879048192],e);if(t>=216&&t<=223)return be(e,pe().suffixes[t-216]);if(t>=27647&&t<=28671)return be(e,pe().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return be(e,pe().suffixes[t-1811939328]);if(t==Jr)return{packedValues:Y,structures:K.slice(0),version:e};if(t==55799)return e});const Dr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Jt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],jr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Jt.length;t++)Br(Jt[t],jr[t]);function Br(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==Dr?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!U.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 qr(){let t=me(),e=d+J();for(let n=2;n<t;n++){let s=me();d+=s}let r=d;return d=e,W=[Qe(me()),Qe(me())],W.position0=0,W.position1=0,W.postBundlePosition=d,d=r,J()}function me(){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(U.getShared){let t=Dt(()=>(A=null,U.getShared()))||{},e=t.structures||[];U.sharedVersion=t.version,Y=U.sharedValues=t.packedValues,K===!0?U.structures=K=e:K.splice.apply(K,[0,e.length].concat(e))}}function Dt(t){let e=Q,r=d,n=Te,s=Oe,i=Le,o=te,y=W,c=new Uint8Array(A.slice(0,Q)),h=K,w=U,p=Me,v=t();return Q=e,d=r,Te=n,Oe=s,Le=i,te=o,W=y,A=c,Me=p,K=h,U=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 Je;try{Je=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 zr=61440,Kr=/[\u0080-\uFFFF]/,ee=Symbol("record-id");class Vr 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)}:Je&&Je.encodeInto?function(l,P){return Je.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,b;if(C){b=Object.create(null);for(let l=0,P=C.length;l<P;l++)b[C[l]]=l}let N=[],O=0,m=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){b={};for(let k=0,F=S.length;k<F;k++)b[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 T=0,x=S.length;T<x;T++){F[ee]===void 0&&(F[ee]=R);let D=S[T];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=b,e.pack){let E=new Map;if(E.values=[],E.encoder=c,E.maxValues=e.maxPrivatePackedValues||(b?16:1/0),E.objectMap=b||!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(b||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=Hr(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(m<10&&m++,n.length>w&&(n.length=w),O>1e4)n.transitions=null,m=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&Zr&&(a=r)}},this.findCommonStringsToPack=()=>(v=new Map,b||(b=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&&(b[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 T=v.get(l);T?T.count++:v.set(l,{count:1})}}let R=l.length;if($&&R>=4&&R<1024){if(($.size+=R)>zr){let T,x=($[0]?$[0].length*3+$[1].length:0)+10;a+x>ue&&(u=_(a+x)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=$.position?132:130,u[a++]=26,T=a-r,a+=4,$.position&&$t(r,g),$=["",""],$.size=0,$.position=T}let F=Kr.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,T,x,D=a+S;for(F=0;F<R;F++)T=l.charCodeAt(F),T<128?u[D++]=T:T<2048?(u[D++]=T>>6|192,u[D++]=T&63|128):(T&64512)===55296&&((x=l.charCodeAt(F+1))&64512)===56320?(T=65536+((T&1023)<<10)+(x&1023),F++,u[D++]=T>>18|240,u[D++]=T>>12&63|128,u[D++]=T>>6&63|128,u[D++]=T&63|128):(u[D++]=T>>12|224,u[D++]=T>>6&63|128,u[D++]=T&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 T=st[S],x=T.tag;x==null&&(x=T.getTag&&T.getTag.call(this,l)),x<24?u[a++]=192|x:x<256?(u[a++]=216,u[a++]=x):x<65536?(u[a++]=217,u[a++]=x>>8,u[a++]=x&255):x>-1&&(u[a++]=218,B.setUint32(a,x),a+=4),T.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,T;if(this.keyMap){T=Object.keys(l).map(D=>this.encodeKey(D)),k=T.length;for(let D=0;D<k;D++){let yt=T[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 x=R[ee];if(x!==void 0)x&=65535,u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255;else if(T||(T=R.__keys__||(R.__keys__=Object.keys(l))),F===void 0?(x=i.nextId++,x||(x=0,i.nextId=1),x>=zt&&(i.nextId=(x=w)+1)):x=F,i[x]=T,x<w){u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255,R=i.transitions;for(let D=0;D<k;D++)(R[ee]===void 0||R[ee]&1048576)&&(R[ee]=x),R=R[T[D]];R[ee]=x|1048576,s=!0}else{if(R[ee]=x,B.setUint32(a,3655335680),a+=3,S&&(O+=m*S),N.length>=zt-w&&(N.shift()[ee]=void 0),N.push(R),ie(k+2),g(57344+x),g(T),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 Wr=typeof Blob>"u"?function(){}:Blob;function ct(t){if(t instanceof Wr)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 $r=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!$r&&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 Hr(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 Vr({useRecords:!1});const Gr=ut.encode;ut.encodeAsIterable,ut.encodeAsAsyncIterable;const Ht=512,Zr=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 wr(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 Yr=Se("appetize.io:transport:ws-ping"),Xr=3e4;function Qr(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),Yr("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},Xr);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const ye=Se("appetize.io:trace:transport:websocket");class en extends Be{constructor(e,{signal:r}={}){super(async s=>{this.#i.send(Gr(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}=Qr(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 b=v[C];b&&o.rpc.addMethod(C,b)}const f=i(p,w);for(const C in f){const b=f[C];b&&y.rpc.addMethod(C,b)}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 tn=2*1024*1024,er=Se("appetize:client:acked-writable-stream");class rn{unacked=0;#e;#r;#t;#n;#i=[];#s;constructor(e){this.#t=e,this.#s=e.window??tn}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 nn extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new rn(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 sn=1024*1024;class on{#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 an extends ReadableStream{#e;constructor({highWaterMark:e=sn,onCancel:r}={}){const n=new on(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 cn{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(ln),this.#n=new an({highWaterMark:n,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#n,this.#i=new nn({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 ln(){}class un{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 fn{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 fn{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new un({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 dn{#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 cn(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{...hn(t),index:t.index,within:t.within?pt(t.within):void 0}}function hn(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:pn(t.text)}}}function pn(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function yn(t){return{press:e=>{le(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function wn({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 vn="@appetizeio/rpc:playwrightAdapter",qe=Symbol.for(vn);function gn(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 bn({onRequest:t,proxyInlet:e}){const[r,n]=dt(),i=[gn(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 mn(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 Sn(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 Cn=new Set(He),En=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Rn=/(\{\{|\{[^{}]*\})/u;function On(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[s,i]of t.split(Rn).entries())if(s%2===0){if(i.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=i}else i==="{{"?r+="{":(n(),e.push(Mn(i.slice(1,-1))));return n(),e}function An(t,e){if(!Cn.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 Mn(t){const e=En.exec(t)?.groups,r=e?.key??t;if(An(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 Pn=Symbol("@appetizeio/client:v1Compat");function rr(t){return t?.[Pn]}class In{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 Nn{#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 In({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 _n{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const n=rr(r)??{},{baseUrl:s,onClose:i,signal:o}=r;this.#e=s?kn(s):void 0;const{onRequest:y,parent:c,proxyRequest:h}=n,w=Fn(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 b=c==="playwright"?bn({onRequest:w,proxyInlet:f}):c?wn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;b&&this.#r.push(b.cleanup),this.#r.push(Zt(v,f,{notifiesLeft:b?.notifies}));const{client:N,unsub:O}=br(p,{"appetizeio.device.client.debug.adbTunnel.data":I=>m.handleAdbTunnelData(I),"appetizeio.device.client.debug.adbTunnel.stopped":async I=>{m.handleAdbTunnelStopped(I)},"appetizeio.device.client.debug.log.entry":async I=>{m.handleLogEntry(I)},"appetizeio.device.client.debug.proxyIntercept.event":async I=>{m.handleProxyInterceptEvent(I)},"appetizeio.device.client.video.chunk":async I=>{g.handleChunk(I)}});this.#t=N,this.#r.push(O);const m=new dn(this.#t);this.#r.push(()=>{m.close()});const g=new Nn(this.#t);this.#r.push(()=>{g.close()}),this.debug=m,this.keyboard=yn(this.#t),this.touch=Sn(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?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}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 open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){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:mn(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:On(e)})}}function kn(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Fn=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function Ln(t){return typeof t=="object"&&t!==null}function Tn(t){try{const e=jt(new Uint8Array(t.data));if(Ln(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function xn(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new en(t,{signal:e.signal}):t,s=new _n(n,{...e,baseUrl:r});return typeof t=="string"&&await Un(n,s,e),s}function Un(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=Tn(o);y&&n?.(y)}})}async function Jn(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 xn(`${n}//${e.host}/ws`);Or(s,r),Ar(s,r),await Mr(s,r)}await Jn(document,location);
|
|
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 Ie={exports:{}},ze,wt;function ir(){if(wt)return ze;wt=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;ze=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*s;case"weeks":case"week":case"w":return v*i;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 S=p>=v*1.5;return Math.round(w/v)+" "+f+(S?"s":"")}return ze}var Ke,vt;function sr(){if(vt)return Ke;vt=1;function t(e){n.debug=n,n.default=n,n.coerce=h,n.disable=y,n.enable=s,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,S,g;function C(...b){if(!C.enabled)return;const E=C,M=Number(new Date),N=M-(v||M);E.diff=N,E.prev=v,E.curr=M,v=M,b[0]=n.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let P=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(q,G)=>{if(q==="%%")return"%";P++;const F=n.formatters[G];if(typeof F=="function"){const V=b[P];q=F.call(E,V),b.splice(P,1),P--}return q}),n.formatArgs.call(E,b),(E.log||n.log).apply(E,b)}return C.namespace=p,C.useColors=n.useColors(),C.color=n.selectColor(p),C.extend=i,C.destroy=n.destroy,Object.defineProperty(C,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(S!==n.namespaces&&(S=n.namespaces,g=n.enabled(p)),g),set:b=>{f=b}}),typeof n.init=="function"&&n.init(C),C}function i(p,v){const f=n(this.namespace+(typeof v>"u"?":":v)+p);return f.log=this.log,f}function s(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,S=0,g=-1,C=0;for(;f<p.length;)if(S<v.length&&(v[S]===p[f]||v[S]==="*"))v[S]==="*"?(g=S,C=f,S++):(f++,S++);else if(g!==-1)S=g+1,C++,f=C;else return!1;for(;S<v.length&&v[S]==="*";)S++;return S===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 Ke=t,Ke}var gt;function or(){return gt||(gt=1,(function(t,e){e.formatArgs=n,e.save=i,e.load=s,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 i(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function s(){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}}})(Ie,Ie.exports)),Ie.exports}var ar=or(),me=nr(ar),ue={},ie={},Se={},bt;function Ne(){return bt||(bt=1,(function(t){var e=Se&&Se.__extends||(function(){var f=function(S,g){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,b){C.__proto__=b}||function(C,b){for(var E in b)Object.prototype.hasOwnProperty.call(b,E)&&(C[E]=b[E])},f(S,g)};return function(S,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");f(S,g);function C(){this.constructor=S}S.prototype=g===null?Object.create(g):(C.prototype=g.prototype,new C)}})();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 i=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCRequest)};t.isJSONRPCRequests=i;var s=function(f){return f.jsonrpc===t.JSONRPC&&f.id!==void 0&&(f.result!==void 0||f.error!==void 0)};t.isJSONRPCResponse=s;var o=function(f){return Array.isArray(f)&&f.every(t.isJSONRPCResponse)};t.isJSONRPCResponses=o;var y=function(f,S,g){var C={code:f,message:S};return g!=null&&(C.data=g),C},c=(function(f){e(S,f);function S(g,C,b){var E=f.call(this,g)||this;return Object.setPrototypeOf(E,S.prototype),E.code=C,E.data=b,E}return S.prototype.toObject=function(){return y(this.code,this.message,this.data)},S})(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,S,g,C){return{jsonrpc:t.JSONRPC,id:f,error:y(S,g,C)}};t.createJSONRPCErrorResponse=h;var w=function(f,S){return{jsonrpc:t.JSONRPC,id:f,result:S??null}};t.createJSONRPCSuccessResponse=w;var p=function(f,S,g){return{jsonrpc:t.JSONRPC,id:f,method:S,params:g}};t.createJSONRPCRequest=p;var v=function(f,S){return{jsonrpc:t.JSONRPC,method:f,params:S}};t.createJSONRPCNotification=v})(Se)),Se}var Ce={},mt;function St(){return mt||(mt=1,Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.DefaultErrorCode=void 0,Ce.DefaultErrorCode=0),Ce}var Ct;function cr(){if(Ct)return ie;Ct=1;var t=ie&&ie.__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(C){try{g(h.next(C))}catch(b){v(b)}}function S(C){try{g(h.throw(C))}catch(b){v(b)}}function g(C){C.done?p(C.value):w(C.value).then(f,S)}g((h=h.apply(o,y||[])).next())})},e=ie&&ie.__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(g){return function(C){return S([g,C])}}function S(g){if(h)throw new TypeError("Generator is already executing.");for(;v&&(v=0,g[0]&&(c=0)),c;)try{if(h=1,w&&(p=g[0]&2?w.return:g[0]?w.throw||((p=w.return)&&p.call(w),0):w.next)&&!(p=p.call(w,g[1])).done)return p;switch(w=0,p&&(g=[g[0]&2,p.value]),g[0]){case 0:case 1:p=g;break;case 4:return c.label++,{value:g[1],done:!1};case 5:c.label++,w=g[1],g=[0];continue;case 7:g=c.ops.pop(),c.trys.pop();continue;default:if(p=c.trys,!(p=p.length>0&&p[p.length-1])&&(g[0]===6||g[0]===2)){c=0;continue}if(g[0]===3&&(!p||g[1]>p[0]&&g[1]<p[3])){c.label=g[1];break}if(g[0]===6&&c.label<p[1]){c.label=p[1],p=g;break}if(p&&c.label<p[2]){c.label=p[2],c.ops.push(g);break}p[2]&&c.ops.pop(),c.trys.pop();continue}g=y.call(o,c)}catch(C){g=[6,C],w=0}finally{h=p=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}};Object.defineProperty(ie,"__esModule",{value:!0}),ie.JSONRPCClient=void 0;var r=Ne(),n=St(),i=(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 S=setTimeout(function(){v.forEach(function(g){var C=h.idToResolveMap.get(g);C&&(h.idToResolveMap.delete(g),C(c(g)))})},y);return f().then(function(g){return clearTimeout(S),g},function(g){return clearTimeout(S),Promise.reject(g)})},p=function(v,f){var S=(Array.isArray(v)?v:[v]).map(function(g){return g.id}).filter(s);return w(S,function(){return h.requestAdvanced(v,f)})};return{request:function(v,f,S){var g=h._createID();return w([g],function(){return h.requestWithID(v,f,S,g)})},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(S){return s(S.id)}),v=p.map(function(S){return new Promise(function(g){return h.idToResolveMap.set(S.id,g)})}),f=Promise.all(v).then(function(S){return w||!S.length?S:S[0]});return this.send(w?y:y[0],c).then(function(){return f},function(S){return p.forEach(function(g){h.receive((0,r.createJSONRPCErrorResponse)(g.id,n.DefaultErrorCode,S&&S.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})();ie.JSONRPCClient=i;var s=function(o){return o!=null};return ie}var Ve={},Et;function lr(){return Et||(Et=1,Object.defineProperty(Ve,"__esModule",{value:!0})),Ve}var se={},Rt;function ur(){return Rt||(Rt=1,(function(t){var e=se&&se.__awaiter||function(C,b,E,M){function N(P){return P instanceof E?P:new E(function(D){D(P)})}return new(E||(E=Promise))(function(P,D){function q(V){try{F(M.next(V))}catch(we){D(we)}}function G(V){try{F(M.throw(V))}catch(we){D(we)}}function F(V){V.done?P(V.value):N(V.value).then(q,G)}F((M=M.apply(C,b||[])).next())})},r=se&&se.__generator||function(C,b){var E={label:0,sent:function(){if(P[0]&1)throw P[1];return P[1]},trys:[],ops:[]},M,N,P,D;return D={next:q(0),throw:q(1),return:q(2)},typeof Symbol=="function"&&(D[Symbol.iterator]=function(){return this}),D;function q(F){return function(V){return G([F,V])}}function G(F){if(M)throw new TypeError("Generator is already executing.");for(;D&&(D=0,F[0]&&(E=0)),E;)try{if(M=1,N&&(P=F[0]&2?N.return:F[0]?N.throw||((P=N.return)&&P.call(N),0):N.next)&&!(P=P.call(N,F[1])).done)return P;switch(N=0,P&&(F=[F[0]&2,P.value]),F[0]){case 0:case 1:P=F;break;case 4:return E.label++,{value:F[1],done:!1};case 5:E.label++,N=F[1],F=[0];continue;case 7:F=E.ops.pop(),E.trys.pop();continue;default:if(P=E.trys,!(P=P.length>0&&P[P.length-1])&&(F[0]===6||F[0]===2)){E=0;continue}if(F[0]===3&&(!P||F[1]>P[0]&&F[1]<P[3])){E.label=F[1];break}if(F[0]===6&&E.label<P[1]){E.label=P[1],P=F;break}if(P&&E.label<P[2]){E.label=P[2],E.ops.push(F);break}P[2]&&E.ops.pop(),E.trys.pop();continue}F=b.call(C,E)}catch(V){F=[6,V],N=0}finally{M=P=0}if(F[0]&5)throw F[1];return{value:F[0]?F[1]:void 0,done:!0}}},n=se&&se.__spreadArray||function(C,b,E){if(E||arguments.length===2)for(var M=0,N=b.length,P;M<N;M++)(P||!(M in b))&&(P||(P=Array.prototype.slice.call(b,0,M)),P[M]=b[M]);return C.concat(P||Array.prototype.slice.call(b))};Object.defineProperty(t,"__esModule",{value:!0}),t.JSONRPCServer=t.createMethodNotFoundResponse=t.createInvalidRequestResponse=void 0;var i=Ne(),s=St(),o=function(){return(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.ParseError,"Parse error")},y=function(C){return(0,i.createJSONRPCErrorResponse)((0,i.isJSONRPCID)(C.id)?C.id:null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")};t.createInvalidRequestResponse=y;var c=function(C){return(0,i.createJSONRPCErrorResponse)(C,i.JSONRPCErrorCode.MethodNotFound,"Method not found")};t.createMethodNotFoundResponse=c;var h=(function(){function C(b){b===void 0&&(b={});var E;this.mapErrorToJSONRPCErrorResponse=f,this.handleMethodNotFound=S,this.nameToMethodMap=new Map,this.middleware=null,this.errorListener=(E=b.errorListener)!==null&&E!==void 0?E:console.warn}return C.prototype.hasMethod=function(b){return this.nameToMethodMap.has(b)},C.prototype.addMethod=function(b,E){this.addMethodAdvanced(b,this.toJSONRPCMethod(E))},C.prototype.removeMethod=function(b){this.nameToMethodMap.delete(b)},C.prototype.toJSONRPCMethod=function(b){return function(E,M){var N=b(E.params,M);return Promise.resolve(N).then(function(P){return v(E.id,P)})}},C.prototype.addMethodAdvanced=function(b,E){this.nameToMethodMap.set(b,E)},C.prototype.receiveJSON=function(b,E){var M=this.tryParseRequestJSON(b);return M?this.receive(M,E):Promise.resolve(o())},C.prototype.tryParseRequestJSON=function(b){try{return JSON.parse(b)}catch{return null}},C.prototype.receive=function(b,E){return Array.isArray(b)?this.receiveMultiple(b,E):this.receiveSingle(b,E)},C.prototype.receiveMultiple=function(b,E){return e(this,void 0,void 0,function(){var M,N=this;return r(this,function(P){switch(P.label){case 0:return b.length===0?[2,(0,i.createJSONRPCErrorResponse)(null,i.JSONRPCErrorCode.InvalidRequest,"Invalid Request")]:[4,Promise.all(b.map(function(D){return N.receiveSingle(D,E)}))];case 1:return M=P.sent().filter(w),M.length===1?[2,M[0]]:M.length?[2,M]:[2,null]}})})},C.prototype.receiveSingle=function(b,E){return e(this,void 0,void 0,function(){var M,N;return r(this,function(P){switch(P.label){case 0:return M=this.nameToMethodMap.get(b.method),(0,i.isJSONRPCRequest)(b)?[3,1]:[2,(0,t.createInvalidRequestResponse)(b)];case 1:return[4,this.callMethod(M,b,E)];case 2:return N=P.sent(),[2,g(b,N)]}})})},C.prototype.applyMiddleware=function(){for(var b=[],E=0;E<arguments.length;E++)b[E]=arguments[E];this.middleware?this.middleware=this.combineMiddlewares(n([this.middleware],b,!0)):this.middleware=this.combineMiddlewares(b)},C.prototype.combineMiddlewares=function(b){return b.length?b.reduce(this.middlewareReducer):null},C.prototype.middlewareReducer=function(b,E){return function(M,N,P){return b(function(D,q){return E(M,D,q)},N,P)}},C.prototype.callMethod=function(b,E,M){var N=this,P=function(q,G){return b?b(q,G):N.handleMethodNotFound(q,G)},D=function(q){return N.errorListener('An unexpected error occurred while executing "'.concat(E.method,'" JSON-RPC method:'),q),Promise.resolve(N.mapErrorToJSONRPCErrorResponseIfNecessary(E.id,q))};try{return(this.middleware||p)(P,E,M).then(void 0,D)}catch(q){return D(q)}},C.prototype.mapErrorToJSONRPCErrorResponseIfNecessary=function(b,E){return b!==void 0?this.mapErrorToJSONRPCErrorResponse(b,E):null},C})();t.JSONRPCServer=h;var w=function(C){return C!==null},p=function(C,b,E){return C(b,E)},v=function(C,b){return C!==void 0?(0,i.createJSONRPCSuccessResponse)(C,b):null},f=function(C,b){var E,M=(E=b?.message)!==null&&E!==void 0?E:"An unexpected error occurred",N=s.DefaultErrorCode,P;return b instanceof i.JSONRPCErrorException&&(N=b.code,P=b.data),(0,i.createJSONRPCErrorResponse)(C,N,M,P)},S=function(C){return e(void 0,void 0,void 0,function(){return r(this,function(b){return C.id!==void 0?[2,(0,t.createMethodNotFoundResponse)(C.id)]:[2,null]})})},g=function(C,b){return b||(C.id!==void 0?(0,i.createJSONRPCErrorResponse)(C.id,i.JSONRPCErrorCode.InternalError,"Internal error"):null)}})(se)),se}var oe={},Ot;function fr(){if(Ot)return oe;Ot=1;var t=oe&&oe.__awaiter||function(i,s,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(S){try{f(y.next(S))}catch(g){w(g)}}function v(S){try{f(y.throw(S))}catch(g){w(g)}}function f(S){S.done?h(S.value):c(S.value).then(p,v)}f((y=y.apply(i,s||[])).next())})},e=oe&&oe.__generator||function(i,s){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(S){return v([f,S])}}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=s.call(i,o)}catch(S){f=[6,S],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(oe,"__esModule",{value:!0}),oe.JSONRPCServerAndClient=void 0;var r=Ne(),n=(function(){function i(s,o,y){y===void 0&&(y={});var c;this.server=s,this.client=o,this.errorListener=(c=y.errorListener)!==null&&c!==void 0?c:console.warn}return i.prototype.applyServerMiddleware=function(){for(var s,o=[],y=0;y<arguments.length;y++)o[y]=arguments[y];(s=this.server).applyMiddleware.apply(s,o)},i.prototype.hasMethod=function(s){return this.server.hasMethod(s)},i.prototype.addMethod=function(s,o){this.server.addMethod(s,o)},i.prototype.addMethodAdvanced=function(s,o){this.server.addMethodAdvanced(s,o)},i.prototype.removeMethod=function(s){this.server.removeMethod(s)},i.prototype.timeout=function(s){return this.client.timeout(s)},i.prototype.request=function(s,o,y){return this.client.request(s,o,y)},i.prototype.requestAdvanced=function(s,o){return this.client.requestAdvanced(s,o)},i.prototype.notify=function(s,o,y){this.client.notify(s,o,y)},i.prototype.rejectAllPendingRequests=function(s){this.client.rejectAllPendingRequests(s)},i.prototype.receiveAndSend=function(s,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)(s)||(0,r.isJSONRPCResponses)(s)?(this.client.receive(s),[3,4]):[3,1];case 1:return(0,r.isJSONRPCRequest)(s)||(0,r.isJSONRPCRequests)(s)?[4,this.server.receive(s,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,s),[2,Promise.reject(new Error(h))];case 4:return[2]}})})},i})();return oe.JSONRPCServerAndClient=n,oe}var Mt;function dr(){return Mt||(Mt=1,(function(t){var e=ue&&ue.__createBinding||(Object.create?(function(n,i,s,o){o===void 0&&(o=s);var y=Object.getOwnPropertyDescriptor(i,s);(!y||("get"in y?!i.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(n,o,y)}):(function(n,i,s,o){o===void 0&&(o=s),n[o]=i[s]})),r=ue&&ue.__exportStar||function(n,i){for(var s in n)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,n,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(cr(),t),r(lr(),t),r(Ne(),t),r(ur(),t),r(fr(),t)})(ue)),ue}var ke=dr();class hr extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function pr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:hr;return new r(t,e)}class yr{#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 wr extends yr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(pr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}const At=me("appetize.io:error:rpc");function We(t,e){const r=new ke.JSONRPCServerAndClient(new ke.JSONRPCServer({errorListener:At}),gr(t),{errorListener:At}),n=t[j].addEventListener("message",({detail:s})=>{r.receiveAndSend(s)}),i=t[j].addEventListener("close",()=>{n(),r.rejectAllPendingRequests("Transport closed")},{once:!0});for(const s in e){const o=e[s];o&&r.addMethod(s,o.bind(e))}return{rpc:r,unsub:()=>{n(),i()}}}function vr(t,e){const{rpc:r,unsub:n}=We(t,e);return{client:r.client,unsub:n}}function _e(t,e){const r=t[j].addEventListener("message",({detail:i})=>{if("method"in i)try{e({method:i.method,param:i.params})}catch{}}),n=t[j].addEventListener("close",r,{once:!0});return()=>{r(),n()}}function gr(t){return new ke.JSONRPCClient(t[j].send.bind(t[j]),()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)+1)}const br=(...t)=>vr(...t),$e=["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","Backspace","Enter","Tab"],mr=33333,Sr=[[99,10],[396,11],[792,21],[1620,22],[3600,31],[5120,32],[8192,40],[8704,42],[22080,50],[36864,51],[139264,60]],Cr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Er=new Set($e);class Rr{#e;#r=!1;#t;#n;#i;#s;#o;#a;#c;#l=0;#u=!1;constructor({canvas:e,context:r,onClose:n,onError:i,signal:s,stream:o}){this.#e=e,this.#t=r,this.#s=n,this.#o=i,this.#a=s,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=Pr(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:i=>{this.#t.drawImage(i,0,0,this.#e.width,this.#e.height),i.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+=mr}}}}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 Or(t,e,{signal:r}={}){if(r?.aborted)return()=>{};const n=s=>{s.altKey||s.ctrlKey||s.metaKey||!Ir(s.key)||(s.preventDefault(),t.keyboard.press(s.key))},i=()=>{e.removeEventListener("keydown",n),r?.removeEventListener("abort",i)};return e.addEventListener("keydown",n),r?.addEventListener("abort",i,{once:!0}),i}function Mr(t,e,{signal:r}={}){let n,i;const s=h=>{n===void 0&&(h.preventDefault(),n=h.pointerId,i=He(e,h),e.focus(),e.setPointerCapture(h.pointerId),t.touch.down(i.x,i.y))},o=h=>{h.pointerId===n&&(h.preventDefault(),i=He(e,h),t.touch.move(i.x,i.y))},y=h=>{if(h.pointerId!==n)return;h.preventDefault();const w=He(e,h);t.touch.up(w.x,w.y),It(e,h.pointerId),n=void 0,i=void 0},c=()=>{n!==void 0&&It(e,n),i&&t.touch.up(i.x,i.y),n=void 0,i=void 0,e.removeEventListener("pointercancel",y),e.removeEventListener("pointerdown",s),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",y),r?.removeEventListener("abort",c)};return r?.aborted||(e.addEventListener("pointercancel",y),e.addEventListener("pointerdown",s),e.addEventListener("pointermove",o),e.addEventListener("pointerup",y),r?.addEventListener("abort",c,{once:!0})),c}async function Ar(t,e,{onClose:r,onError:n,signal:i}={}){const s=e.getContext("2d");if(!s)throw new Error("Canvas context unavailable");i?.throwIfAborted();const o=await t.video.createStream({signal:i});return{close:new Rr({canvas:e,context:s,onClose:r,onError:n,signal:i,stream:o}).close}}function Pt(t){return Math.max(0,Math.min(1,t))}function Pr(t,e,r){const n=Math.ceil(e/16)*Math.ceil(r/16),i=Sr.find(([s])=>n<=s)?.[1]??62;for(let s=0;s<t.length-7;s+=1){const o=t[s]===0&&t[s+1]===0&&t[s+2]===1,y=t[s]===0&&t[s+1]===0&&t[s+2]===0&&t[s+3]===1,c=o?s+3:y?s+4:-1;if(c>=0&&(t[c]&31)===7)return`avc1.${[t[c+1],t[c+2],Math.max(t[c+3],i)].map(h=>h.toString(16).padStart(2,"0")).join("")}`}return"avc1.42e01e"}function Ir(t){return Array.from(Cr.segment(t)).length===1||Er.has(t)}function He(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 Ge;try{Ge=new TextDecoder}catch{}let A,X,d=0;const Nr=105,kr=57342,_r=57343,Nt=57337,kt=6,ve={};let Ee=11281e4,ae=1681e4,T={},z,Fe,Le=0,Re=0,W,ee,K=[],Ze=[],Y,Z,Oe,_t={useRecords:!1,mapsAsObjects:!0},Me=!1,Ft=2;try{new Function("")}catch{Ft=1/0}class Pe{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,i]of Object.entries(e))r.set(this._keyMap.hasOwnProperty(n)?this._keyMap[n]:n,i);return r}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[n,i]of Object.entries(this._keyMap))this._mapKey.set(i,n)}let r={};return e.forEach((n,i)=>r[te(this._mapKey.has(i)?this._mapKey.get(i):i)]=n),r}mapDecode(e,r){let n=this.decode(e);return this._keyMap&&n.constructor.name==="Array"?n.map(i=>this.decodeKeys(i)):n}decode(e,r){if(A)return Dt(()=>(tt(),this?this.decode(e,r):Pe.prototype.decode.call(_t,e,r)));X=r>-1?r:e.length,d=0,Re=0,Fe=null,W=null,A=e;try{Z=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 Pe){if(T=this,Y=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return z=this.structures,xe();(!z||z.length>0)&&(z=[])}else T=_t,(!z||z.length>0)&&(z=[]),Y=null;return xe()}decodeMultiple(e,r){let n,i=0;try{let s=e.length;Me=!0;let o=this?this.decode(e,s):nt.decode(e,s);if(r){if(r(o)===!1)return;for(;d<s;)if(i=d,r(xe())===!1)return}else{for(n=[o];d<s;)i=d,n.push(xe());return n}}catch(s){throw s.lastPosition=i,s.values=n,s}finally{Me=!1,tt()}}}function xe(){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==X)z=null,A=null,ee&&(ee=null);else if(d>X){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 tt(),(t instanceof RangeError||t.message.startsWith("Unexpected end of buffer"))&&(t.incomplete=!0),t}}function fe(){let t=new Error("Unexpected end of CBOR data");return t.incomplete=!0,t}function U(){if(!(d<X))throw fe();let t=A[d++],e=t>>5;if(t=t&31,t>23)switch(t){case 24:if(d>=X)throw fe();t=A[d++];break;case 25:if(e==7)return Tr();t=Z.getUint16(d),d+=2;break;case 26:if(e==7){let r=Z.getFloat32(d);if(T.useFloat32>2){let n=rt[(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=Z.getUint32(d),d+=4,e===1)return-1-t;break;case 27:if(e==7){let r=Z.getFloat64(d);return d+=8,r}if(e>1){if(Z.getUint32(d)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");t=Z.getUint32(d+4)}else T.int64AsNumber?(t=Z.getUint32(d)*4294967296,t+=Z.getUint32(d+4)):t=Z.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,i=0;for(;(n=U())!=ve;){if(i>=Ee)throw new Error(`Array length exceeds ${Ee}`);r[i++]=n}return e==4?r:e==3?r.join(""):Buffer.concat(r);case 5:let s;if(T.mapsAsObjects){let o={},y=0;if(T.keyMap)for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Property count exceeds ${ae}`);o[te(T.decodeKey(s))]=U()}else for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Property count exceeds ${ae}`);o[te(s)]=U()}return o}else{Oe&&(T.mapsAsObjects=!0,Oe=!1);let o=new Map;if(T.keyMap){let y=0;for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Map size exceeds ${ae}`);o.set(T.decodeKey(s),U())}}else{let y=0;for(;(s=U())!=ve;){if(y++>=ae)throw new Error(`Map size exceeds ${ae}`);o.set(s,U())}}return o}case 7:return ve;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 xr(t);case 3:if(Re>=d)return Fe.slice(d-Le,(d+=t)-Le);if(Re==0&&X<140&&t<32){let i=t<16?xt(t):Lr(t);if(i!=null)return i}return Fr(t);case 4:if(t>=Ee)throw new Error(`Array length exceeds ${Ee}`);if(t>X-d)throw fe();let r=new Array(t);for(let i=0;i<t;i++)r[i]=U();return r;case 5:if(t>=ae)throw new Error(`Map size exceeds ${Ee}`);if(t>(X-d)/2)throw fe();if(T.mapsAsObjects){let i={};if(T.keyMap)for(let s=0;s<t;s++)i[te(T.decodeKey(U()))]=U();else for(let s=0;s<t;s++)i[te(U())]=U();return i}else{Oe&&(T.mapsAsObjects=!0,Oe=!1);let i=new Map;if(T.keyMap)for(let s=0;s<t;s++)i.set(T.decodeKey(U()),U());else for(let s=0;s<t;s++)i.set(U(),U());return i}case 6:if(t>=Nt){let i=z[t&8191];if(i)return i.read||(i.read=Ye(i)),i.read();if(t<65536){if(t==_r){let s=be(),o=U(),y=U();Qe(o,y);let c={};if(T.keyMap)for(let h=2;h<s;h++){let w=T.decodeKey(y[h-2]);c[te(w)]=U()}else for(let h=2;h<s;h++){let w=y[h-2];c[te(w)]=U()}return c}else if(t==kr){let s=be(),o=U();for(let y=2;y<s;y++)Qe(o++,U());return U()}else if(t==Nt)return qr();if(T.getShared&&(et(),i=z[t&8191],i))return i.read||(i.read=Ye(i)),i.read()}}let n=K[t];if(n)return n.handlesRead?n(U):n(U());{let i=U();for(let s=0;s<Ze.length;s++){let o=Ze[s](t,i);if(o!==void 0)return o}return new de(i,t)}case 7:switch(t){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let i=(Y||he())[t];if(i!==void 0)return i;throw new Error("Unknown token "+t)}default:throw isNaN(t)?fe():new Error("Unknown CBOR token "+t)}}const Lt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Ye(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=Z.getUint16(d),d+=2;break;case 26:r=Z.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 s=this.length==r?this:this.slice(0,r);return n=T.keyMap?new Function("r","return {"+s.map(o=>T.decodeKey(o)).map(o=>Lt.test(o)?te(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"):new Function("r","return {"+s.map(o=>Lt.test(o)?te(o)+":r()":"["+JSON.stringify(o)+"]:r()").join(",")+"}"),this.compiledReader&&(n.next=this.compiledReader),n.propertyCount=r,this.compiledReader=n,n(U)}let i={};if(T.keyMap)for(let s=0;s<r;s++)i[te(T.decodeKey(this[s]))]=U();else for(let s=0;s<r;s++)i[te(this[s])]=U();return i}return t.slowReads=0,e}function te(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 Fr=Xe;function Xe(t){let e;if(t<16&&(e=xt(t)))return e;if(t>64&&Ge)return Ge.decode(A.subarray(d,d+=t));const r=d+t,n=[];for(e="";d<r;){const i=A[d++];if((i&128)===0)n.push(i);else if((i&224)===192)if(i<194||d>=r||(A[d]&192)!==128)n.push(65533);else{const s=A[d++]&63;n.push((i&31)<<6|s)}else if((i&240)===224){const s=d<r?A[d]:0;if(d>=r||(s&192)!==128||i===224&&s<160||i===237&&s>=160)n.push(65533);else if(d++,d>=r||(A[d]&192)!==128)n.push(65533);else{const o=A[d++]&63;n.push((i&31)<<12|(s&63)<<6|o)}}else if((i&248)===240){const s=d<r?A[d]:0;if(i>244||d>=r||(s&192)!==128||i===240&&s<144||i===244&&s>=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=(i&7)<<18|(s&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 Lr(t){let e=d,r=new Array(t);for(let n=0;n<t;n++){const i=A[d++];if((i&128)>0){d=e;return}r[n]=i}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++],i=A[d++];if((e&128)>0||(r&128)>0||(n&128)>0||(i&128)>0){d-=4;return}if(t<6){if(t===4)return H(e,r,n,i);{let s=A[d++];if((s&128)>0){d-=5;return}return H(e,r,n,i,s)}}else if(t<8){let s=A[d++],o=A[d++];if((s&128)>0||(o&128)>0){d-=6;return}if(t<7)return H(e,r,n,i,s,o);let y=A[d++];if((y&128)>0){d-=7;return}return H(e,r,n,i,s,o,y)}else{let s=A[d++],o=A[d++],y=A[d++],c=A[d++];if((s&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,i,s,o,y,c);{let h=A[d++];if((h&128)>0){d-=9;return}return H(e,r,n,i,s,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,i,s,o,y,c,h,w);let p=A[d++];if((p&128)>0){d-=11;return}return H(e,r,n,i,s,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,i,s,o,y,c,h,w,p,v);{let f=A[d++];if((f&128)>0){d-=13;return}return H(e,r,n,i,s,o,y,c,h,w,p,v,f)}}else{let f=A[d++],S=A[d++];if((f&128)>0||(S&128)>0){d-=14;return}if(t<15)return H(e,r,n,i,s,o,y,c,h,w,p,v,f,S);let g=A[d++];if((g&128)>0){d-=15;return}return H(e,r,n,i,s,o,y,c,h,w,p,v,f,S,g)}}}}}function xr(t){return T.copyBuffers?Uint8Array.prototype.slice.call(A,d,d+=t):A.subarray(d,d+=t)}let Tt=new Float32Array(1),Te=new Uint8Array(Tt.buffer,0,4);function Tr(){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 Te[3]=t&128|(r>>1)+56,Te[2]=(t&7)<<5|e>>3,Te[1]=e<<5,Te[0]=0,Tt[0]}new Array(4096);class de{constructor(e,r){this.value=e,this.tag=r}}K[0]=t=>new Date(t),K[1]=t=>new Date(Math.round(t*1e3)),K[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},K[3]=t=>BigInt(-1)-K[2](t),K[4]=t=>+(t[1]+"e"+t[0]),K[5]=t=>t[1]*Math.exp(t[0]*Math.log(2));const Qe=(t,e)=>{t=t-57344;let r=z[t];r&&r.isShared&&((z.restoreStructures||(z.restoreStructures=[]))[t]=r),z[t]=e,e.read=Ye(e)};K[Nr]=t=>{let e=t.length,r=t[1];Qe(t[0],r);let n={};for(let i=2;i<e;i++){let s=r[i-2];n[te(s)]=t[i]}return n},K[14]=t=>W?W[0].slice(W.position0,W.position0+=t):new de(t,14),K[15]=t=>W?W[1].slice(W.position1,W.position1+=t):new de(t,15);let Ur={Error,RegExp};K[27]=t=>(Ur[t[0]]||Error)(t[1],t[2]);const Ut=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()};Ut.handlesRead=!0,K[51]=Ut,K[kt]=t=>{if(!Y)if(T.getShared)et();else return new de(t,kt);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},K[28]=t=>{ee||(ee=new Map,ee.id=0);let e=ee.id++,r=d,n=A[d],i;n>>5==4?i=[]:i={};let s={target:i};ee.set(e,s);let o=t();return s.used?(Object.getPrototypeOf(i)!==Object.getPrototypeOf(o)&&(d=r,i=o,ee.set(e,{target:i}),o=t()),Object.assign(i,o)):(s.target=o,o)},K[28].handlesRead=!0,K[29]=t=>{let e=ee.get(t);return e.used=!0,e.target},K[258]=t=>new Set(t),(K[259]=t=>(T.mapsAsObjects&&(T.mapsAsObjects=!1,Oe=!0),t())).handlesRead=!0;function ge(t,e){return typeof t=="string"?t+e:t instanceof Array?t.concat(e):Object.assign({},t,e)}function he(){if(!Y)if(T.getShared)et();else throw new Error("No packed values available");return Y}const Jr=1399353956;Ze.push((t,e)=>{if(t>=225&&t<=255)return ge(he().prefixes[t-224],e);if(t>=28704&&t<=32767)return ge(he().prefixes[t-28672],e);if(t>=1879052288&&t<=2147483647)return ge(he().prefixes[t-1879048192],e);if(t>=216&&t<=223)return ge(e,he().suffixes[t-216]);if(t>=27647&&t<=28671)return ge(e,he().suffixes[t-27639]);if(t>=1811940352&&t<=1879048191)return ge(e,he().suffixes[t-1811939328]);if(t==Jr)return{packedValues:Y,structures:z.slice(0),version:e};if(t==55799)return e});const Dr=new Uint8Array(new Uint16Array([1]).buffer)[0]==1,Jt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],jr=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<Jt.length;t++)Br(Jt[t],jr[t]);function Br(t,e){let r="get"+t.name.slice(0,-5),n;typeof t=="function"?n=t.BYTES_PER_ELEMENT:t=null;for(let i=0;i<2;i++){if(!i&&n==1)continue;let s=n==2?1:n==4?2:n==8?3:0;K[i?e:e-4]=n==1||i==Dr?o=>{if(!t)throw new Error("Could not find typed array for code "+e);return!T.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>>s):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>>s,h=new t(c),w=y[r];for(let p=0;p<c;p++)h[p]=w.call(y,p<<s,i);return h}}}function qr(){let t=be(),e=d+U();for(let n=2;n<t;n++){let i=be();d+=i}let r=d;return d=e,W=[Xe(be()),Xe(be())],W.position0=0,W.position1=0,W.postBundlePosition=d,d=r,U()}function be(){if(!(d<X))throw fe();let t=A[d++]&31;if(t>23)switch(t){case 24:if(d>=X)throw fe();t=A[d++];break;case 25:t=Z.getUint16(d),d+=2;break;case 26:t=Z.getUint32(d),d+=4;break}return t}function et(){if(T.getShared){let t=Dt(()=>(A=null,T.getShared()))||{},e=t.structures||[];T.sharedVersion=t.version,Y=T.sharedValues=t.packedValues,z===!0?T.structures=z=e:z.splice.apply(z,[0,e.length].concat(e))}}function Dt(t){let e=X,r=d,n=Le,i=Re,s=Fe,o=ee,y=W,c=new Uint8Array(A.slice(0,X)),h=z,w=T,p=Me,v=t();return X=e,d=r,Le=n,Re=i,Fe=s,ee=o,W=y,A=c,Me=p,z=h,T=w,Z=new DataView(A.buffer,A.byteOffset,A.byteLength),v}function tt(){A=null,ee=null,z=null}const rt=new Array(147);for(let t=0;t<256;t++)rt[t]=+("1e"+Math.floor(45.15-t*.30103));let nt=new Pe({useRecords:!1});const jt=nt.decode;nt.decodeMultiple;let Ue;try{Ue=new TextEncoder}catch{}let it,Bt;const Je=typeof globalThis=="object"&&globalThis.Buffer,Ae=typeof Je<"u",st=Ae?Je.allocUnsafeSlow:Uint8Array,qt=Ae?Je:Uint8Array,zt=256,Kt=Ae?4294967296:2144337920;let ot,u,B,a=0,le,$=null;const zr=61440,Kr=/[\u0080-\uFFFF]/,Q=Symbol("record-id");class Vr extends Pe{constructor(e){super(e),this.offset=0;let r,n,i,s,o;e=e||{};let y=qt.prototype.utf8Write?function(l,I){return u.utf8Write(l,I,u.byteLength-I)}:Ue&&Ue.encodeInto?function(l,I){return Ue.encodeInto(l,u.subarray(I)).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,S=e.sharedValues,g;if(S){g=Object.create(null);for(let l=0,I=S.length;l<I;l++)g[S[l]]=l}let C=[],b=0,E=0;this.mapEncode=function(l,I){return this._keyMap&&!this._mapped&&l.constructor.name==="Array"&&(l=l.map(R=>this.encodeKeys(R))),this.encode(l,I)},this.encode=function(l,I){if(u||(u=new st(8192),B=new DataView(u.buffer,0,8192),a=0),le=u.length-10,le-a<2048?(u=new st(u.length),B=new DataView(u.buffer,0,u.length),le=u.length-10,a=0):I===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 O=c.getShared()||{};c.structures=n=O.structures||[],c.sharedVersion=O.version;let m=c.sharedValues=O.packedValues;if(m){g={};for(let k=0,_=m.length;k<_;k++)g[m[k]]=k}}let R=n.length;if(R>w&&!p&&(R=w),!n.transitions){n.transitions=Object.create(null);for(let O=0;O<R;O++){let m=n[O];if(!m)continue;let k,_=n.transitions;for(let L=0,x=m.length;L<x;L++){_[Q]===void 0&&(_[Q]=O);let J=m[L];k=_[J],k||(k=_[J]=Object.create(null)),_=k}_[Q]=O|1048576}}p||(n.nextId=R)}if(i&&(i=!1),s=n||[],f=g,e.pack){let R=new Map;if(R.values=[],R.encoder=c,R.maxValues=e.maxPrivatePackedValues||(g?16:1/0),R.objectMap=g||!1,R.samplingPackedValues=v,De(l,R),R.values.length>0){u[a++]=216,u[a++]=51,re(4);let O=R.values;M(O),re(0),re(0),f=Object.create(g||null);for(let m=0,k=O.length;m<k;m++)f[O[m]]=m}}ot=I&ut;try{if(ot)return;if(M(l),$&&$t(r,M),c.offset=a,o&&o.idsToInsert){a+=o.idsToInsert.length*2,a>le&&P(a),c.offset=a;let R=Hr(u.subarray(r,a),o.idsToInsert);return o=null,R}return I&Ht?(u.start=r,u.end=a,u):u.subarray(r,a)}finally{if(n){if(E<10&&E++,n.length>w&&(n.length=w),b>1e4)n.transitions=null,E=0,b=0,C.length>0&&(C=[]);else if(C.length>0&&!p){for(let R=0,O=C.length;R<O;R++)C[R][Q]=void 0;C=[]}}if(i&&c.saveShared){c.structures.length>w&&(c.structures=c.structures.slice(0,w));let R=u.subarray(r,a);return c.updateSharedData()===!1?c.encode(l):R}I&Zr&&(a=r)}},this.findCommonStringsToPack=()=>(v=new Map,g||(g=Object.create(null)),l=>{let I=l&&l.threshold||4,R=this.pack?l.maxPrivatePackedValues||16:0;S||(S=this.sharedValues=[]);for(let[O,m]of v)m.count>I&&(g[O]=R++,S.push(O),i=!0);for(;this.saveShared&&this.updateSharedData()===!1;);v=null});const M=l=>{a>le&&(u=P(a));var I=typeof l,R;if(I==="string"){if(f){let _=f[l];if(_>=0){_<16?u[a++]=_+224:(u[a++]=198,_&1?M(15-_>>1):M(_-16>>1));return}else if(v&&!e.pack){let L=v.get(l);L?L.count++:v.set(l,{count:1})}}let O=l.length;if($&&O>=4&&O<1024){if(($.size+=O)>zr){let L,x=($[0]?$[0].length*3+$[1].length:0)+10;a+x>le&&(u=P(a+x)),u[a++]=217,u[a++]=223,u[a++]=249,u[a++]=$.position?132:130,u[a++]=26,L=a-r,a+=4,$.position&&$t(r,M),$=["",""],$.size=0,$.position=L}let _=Kr.test(l);$[_?0:1]+=l,u[a++]=_?206:207,M(O);return}let m;O<32?m=1:O<256?m=2:O<65536?m=3:m=5;let k=O*3;if(a+k>le&&(u=P(a+k)),O<64||!y){let _,L,x,J=a+m;for(_=0;_<O;_++)L=l.charCodeAt(_),L<128?u[J++]=L:L<2048?(u[J++]=L>>6|192,u[J++]=L&63|128):(L&64512)===55296&&((x=l.charCodeAt(_+1))&64512)===56320?(L=65536+((L&1023)<<10)+(x&1023),_++,u[J++]=L>>18|240,u[J++]=L>>12&63|128,u[J++]=L>>6&63|128,u[J++]=L&63|128):(u[J++]=L>>12|224,u[J++]=L>>6&63|128,u[J++]=L&63|128);R=J-a-m}else R=y(l,a+m,k);R<24?u[a++]=96|R:R<256?(m<2&&u.copyWithin(a+2,a+1,a+1+R),u[a++]=120,u[a++]=R):R<65536?(m<3&&u.copyWithin(a+3,a+2,a+2+R),u[a++]=121,u[a++]=R>>8,u[a++]=R&255):(m<5&&u.copyWithin(a+5,a+3,a+3+R),u[a++]=122,B.setUint32(a,R),a+=4),a+=R}else if(I==="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 O;if((O=this.useFloat32)>0&&l<4294967296&&l>=-2147483648){u[a++]=250,B.setFloat32(a,l);let m;if(O<4||(m=l*rt[(u[a]&127)<<1|u[a+1]>>7])>>0===m){a+=4;return}else a--}u[a++]=251,B.setFloat64(a,l),a+=8}else if(I==="object")if(!l)u[a++]=246;else{if(o){let m=o.get(l);if(m){if(u[a++]=216,u[a++]=29,u[a++]=25,!m.references){let k=o.idsToInsert||(o.idsToInsert=[]);m.references=[],k.push(m)}m.references.push(a-r),a+=2;return}else o.set(l,{offset:a-r})}let O=l.constructor;if(O===Object)this.skipFunction===!0&&(l=Object.fromEntries([...Object.keys(l).filter(m=>typeof l[m]!="function").map(m=>[m,l[m]])])),N(l);else if(O===Array){R=l.length,R<24?u[a++]=128|R:re(R);for(let m=0;m<R;m++)M(l[m])}else if(O===Map)if((this.mapsAsObjects?this.useTag259ForMaps!==!1:this.useTag259ForMaps)&&(u[a++]=217,u[a++]=1,u[a++]=3),R=l.size,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[m,k]of l)M(c.encodeKey(m)),M(k);else for(let[m,k]of l)M(m),M(k);else{for(let m=0,k=it.length;m<k;m++){let _=Bt[m];if(l instanceof _){let L=it[m],x=L.tag;x==null&&(x=L.getTag&&L.getTag.call(this,l)),x<24?u[a++]=192|x:x<256?(u[a++]=216,u[a++]=x):x<65536?(u[a++]=217,u[a++]=x>>8,u[a++]=x&255):x>-1&&(u[a++]=218,B.setUint32(a,x),a+=4),L.encode.call(this,l,M,P);return}}if(l[Symbol.iterator]){if(ot){let m=new Error("Iterable should be serialized as iterator");throw m.iteratorNotHandled=!0,m}u[a++]=159;for(let m of l)M(m);u[a++]=255;return}if(l[Symbol.asyncIterator]||at(l)){let m=new Error("Iterable/blob should be serialized as iterator");throw m.iteratorNotHandled=!0,m}if(this.useToJSON&&l.toJSON){const m=l.toJSON();if(m!==l)return M(m)}N(l)}}else if(I==="boolean")u[a++]=l?245:244;else if(I==="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 O=[];for(;l;)O.push(Number(l&BigInt(255))),l>>=BigInt(8);ct(new Uint8Array(O.reverse()),P);return}a+=8}else if(I==="undefined")u[a++]=247;else throw new Error("Unknown type: "+I)},N=this.useRecords===!1?this.variableMapSize?l=>{let I=Object.keys(l),R=Object.values(l),O=I.length;if(O<24?u[a++]=160|O:O<256?(u[a++]=184,u[a++]=O):O<65536?(u[a++]=185,u[a++]=O>>8,u[a++]=O&255):(u[a++]=186,B.setUint32(a,O),a+=4),c.keyMap)for(let m=0;m<O;m++)M(c.encodeKey(I[m])),M(R[m]);else for(let m=0;m<O;m++)M(I[m]),M(R[m])}:l=>{u[a++]=185;let I=a-r;a+=2;let R=0;if(c.keyMap)for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(M(c.encodeKey(O)),M(l[O]),R++);else for(let O in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(O))&&(M(O),M(l[O]),R++);u[I+++r]=R>>8,u[I+r]=R&255}:(l,I)=>{let R,O=s.transitions||(s.transitions=Object.create(null)),m=0,k=0,_,L;if(this.keyMap){L=Object.keys(l).map(J=>this.encodeKey(J)),k=L.length;for(let J=0;J<k;J++){let yt=L[J];R=O[yt],R||(R=O[yt]=Object.create(null),m++),O=R}}else for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&(R=O[J],R||(O[Q]&1048576&&(_=O[Q]&65535),R=O[J]=Object.create(null),m++),O=R,k++);let x=O[Q];if(x!==void 0)x&=65535,u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255;else if(L||(L=O.__keys__||(O.__keys__=Object.keys(l))),_===void 0?(x=s.nextId++,x||(x=0,s.nextId=1),x>=zt&&(s.nextId=(x=w)+1)):x=_,s[x]=L,x<w){u[a++]=217,u[a++]=x>>8|224,u[a++]=x&255,O=s.transitions;for(let J=0;J<k;J++)(O[Q]===void 0||O[Q]&1048576)&&(O[Q]=x),O=O[L[J]];O[Q]=x|1048576,i=!0}else{if(O[Q]=x,B.setUint32(a,3655335680),a+=3,m&&(b+=E*m),C.length>=zt-w&&(C.shift()[Q]=void 0),C.push(O),re(k+2),M(57344+x),M(L),I)return;for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&M(l[J]);return}if(k<24?u[a++]=128|k:re(k),!I)for(let J in l)(typeof l.hasOwnProperty!="function"||l.hasOwnProperty(J))&&M(l[J])},P=l=>{let I;if(l>16777216){if(l-r>Kt)throw new Error("Encoded buffer would be larger than maximum buffer size");I=Math.min(Kt,Math.round(Math.max((l-r)*(l>67108864?1.25:2),4194304)/4096)*4096)}else I=(Math.max(l-r<<2,u.length-1)>>12)+1<<12;let R=new st(I);return B=new DataView(R.buffer,0,I),u.copy?u.copy(R,0,r,l):R.set(u.slice(r,l)),a-=r,r=0,le=R.length-10,u=R};let D=100,q=1e3;this.encodeAsIterable=function(l,I){return we(l,I,G)},this.encodeAsAsyncIterable=function(l,I){return we(l,I,pt)};function*G(l,I,R){let O=l.constructor;if(O===Object){let m=c.useRecords!==!1;m?N(l,!0):Vt(Object.keys(l).length,160);for(let k in l){let _=l[k];m||M(k),_&&typeof _=="object"?I[k]?yield*G(_,I[k]):yield*F(_,I,k):M(_)}}else if(O===Array){let m=l.length;re(m);for(let k=0;k<m;k++){let _=l[k];_&&(typeof _=="object"||a-r>D)?I.element?yield*G(_,I.element):yield*F(_,I,"element"):M(_)}}else if(l[Symbol.iterator]&&!l.buffer){u[a++]=159;for(let m of l)m&&(typeof m=="object"||a-r>D)?I.element?yield*G(m,I.element):yield*F(m,I,"element"):M(m);u[a++]=255}else at(l)?(Vt(l.size,64),yield u.subarray(r,a),yield l,V()):l[Symbol.asyncIterator]?(u[a++]=159,yield u.subarray(r,a),yield l,V(),u[a++]=255):M(l);R&&a>r?yield u.subarray(r,a):a-r>D&&(yield u.subarray(r,a),V())}function*F(l,I,R){let O=a-r;try{M(l),a-r>D&&(yield u.subarray(r,a),V())}catch(m){if(m.iteratorNotHandled)I[R]={},a=r+O,yield*G.call(this,l,I[R]);else throw m}}function V(){D=q,c.encode(null,ut)}function we(l,I,R){return I&&I.chunkThreshold?D=q=I.chunkThreshold:D=100,l&&typeof l=="object"?(c.encode(null,ut),R(l,c.iterateProperties||(c.iterateProperties={}),!0)):[c.encode(l)]}async function*pt(l,I){for(let R of G(l,I,!0)){let O=R.constructor;if(O===qt||O===Uint8Array)yield R;else if(at(R)){let m=R.stream().getReader(),k;for(;!(k=await m.read()).done;)yield k.value}else if(R[Symbol.asyncIterator])for await(let m of R)V(),m?yield*pt(m,I.async||(I.async={})):yield c.encode(m);else yield R}}}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),i=this.saveShared(n,s=>(s&&s.version||0)==e);return i===!1?(n=this.getShared()||{},this.structures=n.structures||[],this.sharedValues=n.packedValues,this.sharedVersion=n.version,this.structures.nextId=this.structures.length):r.forEach((s,o)=>this.structures[o]=s),i}}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 re(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 Wr=typeof Blob>"u"?function(){}:Blob;function at(t){if(t instanceof Wr)return!0;let e=t[Symbol.toStringTag];return e==="Blob"||e==="File"}function De(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 i=e.samplingPackedValues.get(t);i?i.count++:e.samplingPackedValues.set(t,{count:1})}}break;case"object":if(t)if(t instanceof Array)for(let n=0,i=t.length;n<i;n++)De(t[n],e);else{let n=!e.encoder.useRecords;for(var r in t)t.hasOwnProperty(r)&&(n&&De(r,e),De(t[r],e))}break;case"function":console.log(t)}}const $r=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;Bt=[Date,Set,Error,RegExp,de,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array>"u"?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array>"u"?function(){}:BigInt64Array,Float32Array,Float64Array,Wt],it=[{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){ct(t,r)}},{getTag(t){if(t.constructor===Uint8Array&&(this.tagUint8Array||Ae&&this.tagUint8Array!==!1))return 64},encode(t,e,r){ct(t,r)}},ne(68,1),ne(69,2),ne(70,4),ne(71,8),ne(72,1),ne(77,2),ne(78,4),ne(79,8),ne(85,4),ne(86,8),{encode(t,e){let r=t.packedValues||[],n=t.structures||[];if(r.values.length>0){u[a++]=216,u[a++]=51,re(4);let i=r.values;e(i),re(0),re(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let s=0,o=i.length;s<o;s++)packedObjectMap[i[s]]=s}if(n){B.setUint32(a,3655335424),a+=3;let i=n.slice(0);i.unshift(57344),i.push(new de(t.version,1399353956)),e(i)}else e(new de(t.version,1399353956))}}];function ne(t,e){return!$r&&e>1&&(t-=4),{tag:t,encode:function(n,i){let s=n.byteLength,o=n.byteOffset||0,y=n.buffer||n;i(Ae?Je.from(y,o,s):new Uint8Array(y,o,s))}}}function ct(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 Hr(t,e){let r,n=e.length*2,i=t.length-n;e.sort((s,o)=>s.offset>o.offset?1:-1);for(let s=0;s<e.length;s++){let o=e[s];o.id=s;for(let y of o.references)t[y++]=s>>8,t[y]=s&255}for(;r=e.pop();){let s=r.offset;t.copyWithin(s+n,s,i),n-=2;let o=s+n;t[o++]=216,t[o++]=28,i=s}return t}function $t(t,e){B.setUint32($.position+t,a-$.position-t+1);let r=$;$=null,e(r[0]),e(r[1])}let lt=new Vr({useRecords:!1});const Gr=lt.encode;lt.encodeAsIterable,lt.encodeAsAsyncIterable;const Ht=512,Zr=1024,ut=2048;function Gt(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}class je{closed=!1;[j];#e;constructor(e,{signal:r}={}){this[j]=new wr(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 Yr=me("appetize.io:transport:ws-ping"),Xr=3e4;function Qr(t){let e=!0;const r=()=>{e=!0};t.on("pong",r);const n=setInterval(()=>{if(!e){clearInterval(n),Yr("liveness ping went unanswered, terminating"),t.terminate();return}t.readyState===t.OPEN&&(e=!1,t.ping())},Xr);return{destroy(){clearInterval(n),t.off("pong",r)},pong:r}}const pe=me("appetize.io:trace:transport:websocket");class en extends je{constructor(e,{signal:r}={}){super(async i=>{this.#i.send(Gr(i))},{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:i,pong:s}=Qr(n);this.#n=s,this.#e.push(i)}}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){pe("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=>{pe("handleWebSocketClose()",e);try{this.#s(e)}finally{this.close()}};#a=e=>{pe("handleWebSocketError()",e),this.onerror?.(e)};#c=async e=>{pe("handleWebSocketMessage()",e),this.#n?.();const r=this.#u(e);if(!r){pe("handleWebSocketMessage() -> legacy"),this.onmessage?.(e);return}pe("handleWebSocketMessage() -> jsonrpc",r),this[j].dispatchMessage(r)};#l=e=>{pe("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:i,rightEffects:s=()=>({})}={}){const o=We(t,{}),y=We(e,{}),c=[()=>{o.unsub(),y.unsub()}],h=()=>{for(const S of c)try{S()}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 S in v){const g=v[S];g&&o.rpc.addMethod(S,g)}const f=s(p,w);for(const S in f){const g=f[S];g&&y.rpc.addMethod(S,g)}return Yt(o.rpc,y.rpc,{notifies:n}),Yt(y.rpc,o.rpc,{notifies:i}),h}function Yt(t,e,{notifies:r}={}){t.applyServerMiddleware(async(n,i)=>{const s=r?.();if(s){const{id:y,...c}=i;s[j].send(c)}if(t.hasMethod(i.method))return await n(i);if(!i.id)return e.notify(i.method,i.params),null;const o=await e.request(i.method,i.params);return{id:i.id,jsonrpc:ke.JSONRPC,result:o}})}function ce(t,...e){t.notify(e[0],e[1],e[2])}function ft(){const t=new je(async r=>{e[j].dispatchMessage(r)}),e=new je(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 i of r)i()};r.push(t[j].addEventListener("message",i=>e[j].send(i.detail))),r.push(t[j].addEventListener("close",n,{once:!0})),r.push(e[j].addEventListener("message",i=>t[j].send(i.detail))),r.push(e[j].addEventListener("close",n,{once:!0}))}const ye=me("appetize.io:trace:transport:iframe");class Qt extends je{onmessage;#e;#r;constructor(e,{origin:r="*",signal:n}={}){super(async i=>{e.postMessage(i,this.#e)},{signal:n}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,n){ye("postMessage(legacy)",{message:e,targetOrigin:r,transfer:n}),this.#r.postMessage(e,r??this.#e,n)}handleClose(e){ye("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ye("handleMessage()",e),e.source!==this.#r||(ye("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ye("handleMessage() -> origin ok");const r=e.data;if(!Gt(r)){ye("handleMessage() -> legacy"),this.onmessage?.(e);return}ye("handleMessage() -> jsonrpc"),this[j].dispatchMessage(r)}}function dt(){let t,e;return{promise:new Promise((n,i)=>{e=n,t=i}),reject:t,resolve:e}}const tn=2*1024*1024,er=me("appetize:client:acked-writable-stream");class rn{unacked=0;#e;#r;#t;#n;#i=[];#s;constructor(e){this.#t=e,this.#s=e.window??tn}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={...dt(),until:e};return this.#i.push(r),r.promise}}class nn extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new rn(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 sn=1024*1024;class on{#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??=dt();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 an extends ReadableStream{#e;constructor({highWaterMark:e=sn,onCancel:r}={}){const n=new on(r);super({cancel:i=>{n.cancel(i)},pull:()=>{n.pull()},start:i=>{n.start(i)}},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 cn{closed;readable;writable;#e=[];#r;#t;#n;#i;#s;#o="starting";constructor(e,{onClose:r,receiveBuffer:n,sendWindow:i,signal:s}){if(this.#s=e,this.#r=dt(),this.closed=this.#r.promise,this.closed.catch(ln),this.#n=new an({highWaterMark:n,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#n,this.#i=new nn({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:i}),this.writable=this.#i,s){const o=()=>{this.#a(s.reason)};s.addEventListener("abort",o,{once:!0}),this.#e.push(()=>{s.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&&ce(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 ln(){}class un{readable;ready;#e=[];#r=!1;#t;#n;#i;constructor({label:e,onClose:r,signal:n}){this.#n=e,this.ready=new Promise((s,o)=>{this.#i={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#o()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#t=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}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 fn{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 fn{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new un({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 dn{#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:()=>{ce(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:()=>{ce(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 cn(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 ht(t){return{...hn(t),index:t.index,within:t.within?ht(t.within):void 0}}function hn(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:pn(t.text)}}}function pn(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function yn(t){return{press:e=>{ce(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function wn({onRequest:t,parent:e,proxyInlet:r,signal:n}){const i=new Qt(e,{signal:n}),s=[()=>{i.close()}];return Xt(i,r),t&&s.push(_e(i,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>e===globalThis.window?void 0:i}}const vn="@appetizeio/rpc:playwrightAdapter",Be=Symbol.for(vn);function gn(t){window[Be]&&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[Be]=e,()=>{window[Be]===e&&delete window[Be]}}function bn({onRequest:t,proxyInlet:e}){const[r,n]=ft(),s=[gn(n),()=>{r.close()}];return Xt(r,e),t&&s.push(_e(r,o=>{t(o,{source:"parent"})})),{cleanup:()=>{for(const o of s)o()},notifies:()=>r}}function qe(t){return t.by==="position"?{by:"position",x:t.x,y:t.y}:{...ht(t),x:t.x,y:t.y}}function mn(t){return"to"in t?{from:qe(t.from),kind:"path",to:qe(t.to)}:{direction:t.direction,distance:t.distance,from:t.from?qe(t.from):void 0,kind:"direction"}}function Sn(t){return{down:(e,r)=>{ce(t,"appetizeio.device.server.touch.down",{x:e,y:r})},move:(e,r)=>{ce(t,"appetizeio.device.server.touch.move",{x:e,y:r})},up:(e,r)=>{ce(t,"appetizeio.device.server.touch.up",{x:e,y:r})}}}const Cn=new Set($e),En=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,Rn=/(\{\{|\{[^{}]*\})/u;function On(t){const e=[];let r="";function n(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[i,s]of t.split(Rn).entries())if(i%2===0){if(s.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=s}else s==="{{"?r+="{":(n(),e.push(An(s.slice(1,-1))));return n(),e}function Mn(t,e){if(!Cn.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: ${$e.join(", ")}. Type characters as text, and escape a literal "{" as "{{".`)}function An(t){const e=En.exec(t)?.groups,r=e?.key??t;if(Mn(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 Pn=Symbol("@appetizeio/client:v1Compat");function rr(t){return t?.[Pn]}class In{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((s,o)=>{this.#s={reject:o,resolve:s}});let i;if(this.readable=new ReadableStream({cancel:()=>{this.#a()},start:s=>{i=s}}),!i)throw new Error("ReadableStream controller was not initialized");if(this.#t=i,n){const s=()=>{this.fail(n.reason)};n.addEventListener("abort",s,{once:!0}),this.#e.push(()=>{n.removeEventListener("abort",s)})}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 Nn{#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 In({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,ce(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,ce(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class kn{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const n=rr(r)??{},{baseUrl:i,onClose:s,signal:o}=r;this.#e=i?_n(i):void 0;const{onRequest:y,parent:c,proxyRequest:h}=n,w=Fn(y);o?.addEventListener("abort",this.close);const[p,v]=ft(),[f,S]=ft();this.#r.push(()=>{p.close(),v.close(),f.close(),S.close()}),this.#r.push(Zt(S,e,{leftEffects:h}));const g=c==="playwright"?bn({onRequest:w,proxyInlet:f}):c?wn({onRequest:w,parent:c,proxyInlet:f,signal:o}):void 0;g&&this.#r.push(g.cleanup),this.#r.push(Zt(v,f,{notifiesLeft:g?.notifies}));const{client:C,unsub:b}=br(p,{"appetizeio.device.client.debug.adbTunnel.data":N=>E.handleAdbTunnelData(N),"appetizeio.device.client.debug.adbTunnel.stopped":async N=>{E.handleAdbTunnelStopped(N)},"appetizeio.device.client.debug.log.entry":async N=>{E.handleLogEntry(N)},"appetizeio.device.client.debug.proxyIntercept.event":async N=>{E.handleProxyInterceptEvent(N)},"appetizeio.device.client.video.chunk":async N=>{M.handleChunk(N)}});this.#t=C,this.#r.push(b);const E=new dn(this.#t);this.#r.push(()=>{E.close()});const M=new Nn(this.#t);this.#r.push(()=>{M.close()}),this.debug=E,this.keyboard=yn(this.#t),this.touch=Sn(this.#t),this.video=M,w&&(this.#r.push(_e(v,N=>{w(N,{source:"self"})})),e instanceof Qt&&this.#r.push(_e(e,N=>{w(N,{source:"iframe"})}))),this.#r.push(()=>s?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}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?ht(e):void 0})}async open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){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 i=n.headers.get("content-type")??"application/octet-stream";return{data:new Uint8Array(await n.arrayBuffer()),mimeType:i}}async swipe(e,r){await this.#t.request("appetizeio.device.server.swipe",{gesture:mn(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:qe(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:On(e)})}}function _n(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const Fn=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function Ln(t){return typeof t=="object"&&t!==null}function xn(t){try{const e=jt(new Uint8Array(t.data));if(Ln(e)&&typeof e.name=="string")return{name:e.name,payload:"payload"in e?e.payload:void 0}}catch{}}async function Tn(t,e={}){const r=e.baseUrl??(typeof t=="string"?new URL(t).origin:void 0),n=typeof t=="string"?new en(t,{signal:e.signal}):t,i=new kn(n,{...e,baseUrl:r});return typeof t=="string"&&await Un(n,i,e),i}function Un(t,e,r){const n=rr(r)?.onLegacyMessage;return new Promise((i,s)=>{t.onopen=()=>{i()},t.onclose=()=>{e.close(),r.signal?.aborted?s(r.signal.reason):s(new Error("The websocket was closed before the device connection was established"))},t.onerror=s,t.onmessage=o=>{const y=xn(o);y&&n?.(y)}})}async function Jn(t,e){const r=t.querySelector("canvas");if(!(r instanceof HTMLCanvasElement))throw new Error("Canvas unavailable");const n=e.protocol==="https:"?"wss:":"ws:",i=await Tn(`${n}//${e.host}/ws`);Or(i,r),Mr(i,r),await Ar(i,r)}await Jn(document,location);
|
|
2
2
|
</script></body></html>
|
package/config-CmsJj7_W.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Transform as tr}from"stream";import{createRequire as rr}from"module";import{connect as sr}from"node:net";import Be from"debug";import{JSONRPCServerAndClient as nr,JSONRPCServer as ir,JSONRPCClient as or,JSONRPC as ar}from"json-rpc-2.0";import{writeFileSync as lr,renameSync as cr,mkdirSync as pt,readFileSync as fr,readdirSync as ur}from"node:fs";import{homedir as dr}from"node:os";import{join as te}from"node:path";let Ne;try{Ne=new TextDecoder}catch{}let p,V,c=0;const De=[],hr=105,pr=57342,yr=57343,yt=57337,wt=6,fe={};let we=11281e4,Y=1681e4,re=De,be=0,O={},_,me,ge=0,se=0,B,q,N=[],Fe=[],K,j,Ee,bt={useRecords:!1,mapsAsObjects:!0},Se=!1,mt=2;try{new Function("")}catch{mt=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,me=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 gr();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 mr(t);case 3:if(se>=c)return me.slice(c-ge,(c+=t)-ge);if(se==0&&V<140&&t<32){let n=t<16?St(t):br(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==yr){let o=de(),f=I(),b=I();je(f,b);let y={};if(O.keyMap)for(let v=2;v<o;v++){let g=O.decodeKey(b[v-2]);y[J(g)]=I()}else for(let v=2;v<o;v++){let g=b[v-2];y[J(g)]=I()}return y}else if(t==pr){let o=de(),f=I();for(let b=2;b<o;b++)je(f++,I());return I()}else if(t==yt)return Or();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 gt=/^[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++>=mt){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=>gt.test(f)?J(f)+":r()":"["+JSON.stringify(f)+"]:r()").join(",")+"}"):new Function("r","return {"+o.map(f=>gt.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 wr(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):(me=o,ge=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 br(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++],g=p[c++];if((v&128)>0||(g&128)>0){c-=10;return}if(t<11)return F(e,r,s,n,o,f,b,y,v,g);let x=p[c++];if((x&128)>0){c-=11;return}return F(e,r,s,n,o,f,b,y,v,g,x)}else{let v=p[c++],g=p[c++],x=p[c++],R=p[c++];if((v&128)>0||(g&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,g,x,R);{let L=p[c++];if((L&128)>0){c-=13;return}return F(e,r,s,n,o,f,b,y,v,g,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,g,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,g,x,R,L,U,P)}}}}}function mr(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 gr(){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[hr]=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 Er={Error,RegExp};N[27]=t=>(Er[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 Sr=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==Sr)return{packedValues:K,structures:_.slice(0),version:e};if(t==55799)return e});const vr=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],Ar=[64,68,69,70,71,72,77,78,79,85,86];for(let t=0;t<kt.length;t++)kr(kt[t],Ar[t]);function kr(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==vr?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),g=b[r];for(let x=0;x<y;x++)v[x]=g.call(b,x<<o,n);return v}}}function Or(){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=ge,o=se,f=me,b=re,y=q,v=B,g=new Uint8Array(p.slice(0,V)),x=_,R=O,L=Se,U=t();return V=e,c=r,be=s,ge=n,se=o,me=f,re=b,q=y,B=v,p=g,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 Ir=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,C,i=0,Q,D=null;const Mr=61440,xr=/[\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,g=e.maxSharedStructures;if(g==null&&(g=v?128:0),g>8190)throw new Error("Maximum maxSharedStructure is 8190");let x=e.sequential;x&&(g=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,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),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 m=0,E=u.length;m<E;m++)P[u[m]]=m}}let d=s.length;if(d>g&&!x&&(d=g),!s.transitions){s.transitions=Object.create(null);for(let h=0;h<d;h++){let u=s[h];if(!u)continue;let m,E=s.transitions;for(let S=0,A=u.length;S<A;S++){E[$]===void 0&&(E[$]=h);let M=u[S];m=E[M],m||(m=E[M]=Object.create(null)),E=m}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,H(4);let h=d.values;k(h),H(0),H(0),L=Object.create(P||null);for(let u=0,m=h.length;u<m;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=Cr(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>g&&(s.length=g),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>g&&(y.structures=y.structures.slice(0,g));let d=l.subarray(r,i);return y.updateSharedData()===!1?y.encode(a):d}w&Ur&&(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)>Mr){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=xr.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 m=h*3;if(i+m>Q&&(l=le(i+m)),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,m);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 m=f.idsToInsert||(f.idsToInsert=[]);u.references=[],m.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,C.setUint32(i,d),i+=4),y.keyMap)for(let[u,m]of a)k(y.encodeKey(u)),k(m);else for(let[u,m]of a)k(u),k(m);else{for(let u=0,m=Je.length;u<m;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(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,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,m=0,E,S;if(this.keyMap){S=Object.keys(a).map(M=>this.encodeKey(M)),m=S.length;for(let M=0;M<m;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,m++);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=g)+1)):A=E,o[A]=S,A<g){l[i++]=217,l[i++]=A>>8|224,l[i++]=A&255,h=o.transitions;for(let M=0;M<m;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+=G*u),W.length>=xt-g&&(W.shift()[$]=void 0),W.push(h),H(m+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(m<24?l[i++]=128|m:H(m),!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 m in a){let E=a[m];u||k(m),E&&typeof E=="object"?w[m]?yield*ce(E,w[m]):yield*_e(E,w,m):k(E)}}else if(h===Array){let u=a.length;H(u);for(let m=0;m<u;m++){let E=a[m];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)?(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(He(d)){let u=d.stream().getReader(),m;for(;!(m=await u.read()).done;)yield m.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 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,C.setUint32(i,t),i+=4)}const Rr=typeof Blob>"u"?function(){}:Blob;function He(t){if(t instanceof Rr)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 Tr=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,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){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!Tr&&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 Cr(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 Pr=Ye.encode;Ye.encodeAsIterable,Ye.encodeAsAsyncIterable;const Lt=512,Ur=1024,Xe=2048;class Lr extends tr{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 _r=process.env.CBOR_NATIVE_ACCELERATION_DISABLED!==void 0&&process.env.CBOR_NATIVE_ACCELERATION_DISABLED.toLowerCase()==="true";if(!_r){let t;try{typeof require=="function"?t=require("cbor-extract"):t=rr(import.meta.url)("cbor-extract"),t&&wr(t.extractStrings)}catch{}}class Br extends Event{code;reason;wasClean;constructor(e,r={}){super(e,r),this.code=r.code??0,this.reason=r.reason??"",this.wasClean=r.wasClean??!1}}function Nr(t,e){const r="CloseEvent"in globalThis?globalThis.CloseEvent:Br;return new r(t,e)}class Dr{#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 Fr extends Dr{send;constructor(e){super(),this.send=e}dispatchClose(e){return this.dispatchEvent(Nr("close",e))}dispatchMessage(e){return this.dispatchEvent(new CustomEvent("message",{detail:e}))}}function Qe(t){return!!t&&typeof t=="object"&&"jsonrpc"in t}function zr(){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 Fr(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[T].dispatchClose(e)}#r=()=>{this.close({code:1e3,reason:String(this.#e?.reason)})}}const _t={useRecords:!1},jr=new Tt(_t);class Bt extends Ae{#e=[];#r;constructor(e,{signal:r}={}){super(async f=>{this.#r.write(jr.encode(f))},{signal:r}),this.#r=e;const s=new Lr(_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 Vr(t,e){const{promise:r,reject:s,resolve:n}=zr(),o=sr(t),f=e?.signal,b=()=>{o.off("connect",g),o.off("error",x),f?.removeEventListener("abort",v)},y=R=>{b(),o.destroy(),s(R)},v=()=>{y(new Error("The connection was aborted"))},g=()=>{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",g),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 nr(new ir({errorListener:Nt}),Kr(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 Kr(t){return new or(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{}},g=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(g,x);for(const U in R){const P=R[U];P&&f.rpc.addMethod(U,P)}const L=o(x,g);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:ar,result:f}})}function X(t,...e){t.notify(e[0],e[1],e[2])}const $r=(...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;#r;constructor(e,{origin:r="*",signal:s}={}){super(async n=>{e.postMessage(n,this.#e)},{signal:s}),this.#r=e,this.#e=r,window.addEventListener("message",this.#t)}postMessage(e,r,s){ae("postMessage(legacy)",{message:e,targetOrigin:r,transfer:s}),this.#r.postMessage(e,r??this.#e,s)}handleClose(e){ae("close()"),window.removeEventListener("message",this.#t),super.handleClose(e)}#t=async e=>{if(ae("handleMessage()",e),e.source!==this.#r||(ae("handleMessage() -> source ok"),this.#e!=="*"&&e.origin!==this.#e))return;ae("handleMessage() -> origin ok");const r=e.data;if(!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 qr=2*1024*1024,Vt=Be("appetize:client:acked-writable-stream");class Jr{unacked=0;#e;#r;#t;#s;#n=[];#i;constructor(e){this.#t=e,this.#i=e.window??qr}abort(e){this.#a(e),this.#t.onAbort?.(e)}async close(){await this.#l(()=>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.#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.#r)return!1;this.#r={reason:e},this.#e.error(e);const r=this.#n;this.#n=[];for(const s of r)s.reject(e);return!0}#l(e){if(e())return Promise.resolve();const r={...Pe(),until:e};return this.#n.push(r),r.promise}}class Wr extends WritableStream{get unacked(){return this.#e.unacked}#e;constructor(e){const r=new Jr(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 Gr=1024*1024;class Hr{#e;#r=!1;#t;#s;constructor(e){this.#t=e}cancel(e){this.#n(),this.#t?.(e)}close(){this.#n()&&this.#e.close()}error(e){this.#n()&&this.#e.error(e)}pull(){const e=this.#s;this.#s=void 0,e?.resolve(void 0)}async push(e){if(this.#r)return;this.#s??=Pe();const{promise:r}=this.#s;this.#e.enqueue(e),await r}start(e){this.#e=e}#n(){return this.#r?!1:(this.#r=!0,this.pull(),!0)}}class Zr extends ReadableStream{#e;constructor({highWaterMark:e=Gr,onCancel:r}={}){const s=new Hr(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 Yr{closed;readable;writable;#e=[];#r;#t;#s;#n;#i;#o="starting";constructor(e,{onClose:r,receiveBuffer:s,sendWindow:n,signal:o}){if(this.#i=e,this.#r=Pe(),this.closed=this.#r.promise,this.closed.catch(Xr),this.#s=new Zr({highWaterMark:s,onCancel:()=>{this.#a(void 0)}}),this.readable=this.#s,this.#n=new Wr({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.#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&&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.#r.reject(e):this.#r.resolve(void 0)}}}function Xr(){}class Qr{readable;ready;#e=[];#r=!1;#t;#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.#t=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.#t.enqueue(e)}markReady(){if(!this.#n)return;const{resolve:e}=this.#n;this.#n=void 0,e(this)}async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#i(e){this.#r||(this.#t.close(),this.#o(e))}#o(e){this.#r=!0;for(const r of this.#e)r();this.#n?.reject(e??new Error(`${this.#s} closed before it started`)),this.#n=void 0}}class es{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 Kt extends es{#e;constructor(e){super({start:e.start,stop:e.stop}),this.#e=e.label}async createStream({signal:e}={}){e?.throwIfAborted();const r=new Qr({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 ts{#e;#r;#t;#s;constructor(e){this.#s=e,this.#r=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.#t=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.#r.close(),this.#t.close()}async createAdbTunnel({signal:e}={}){e?.throwIfAborted(),this.#e?.close();const r=new Yr(this.#s,{onClose:()=>{this.#e=void 0},signal:e});return this.#e=r,await r.start(),r}async createLogStream(e){return await this.#r.createStream(e)}async createProxyInterceptStream(e){return await this.#t.createStream(e)}async handleAdbTunnelData({data:e}){await this.#e?.handleData(e)}handleAdbTunnelStopped(e){this.#e?.handleStopped(e)}handleLogEntry(e){this.#r.handleNotification(e)}handleProxyInterceptEvent(e){this.#t.handleNotification(e)}}function nt(t){return{...rs(t),index:t.index,within:t.within?nt(t.within):void 0}}function rs(t){switch(t.by){case"testId":return{by:"testId",testId:t.testId};case"text":return{by:"text",text:ss(t.text)}}}function ss(t){return typeof t=="string"?{kind:"exact",value:t}:{flags:t.flags,kind:"regex",source:t.source}}function ns(t){return{press:e=>{X(t,"appetizeio.device.server.keyboard.press",{key:e})}}}function is({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 os="@appetizeio/rpc:playwrightAdapter",Ue=Symbol.for(os);function as(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 ls({onRequest:t,proxyInlet:e}){const[r,s]=st(),o=[as(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 cs(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 fs(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 us=new Set(rt),ds=/^(?<key>[A-Za-z]+)>(?<repeat>\d+)\/$/u,hs=/(\{\{|\{[^{}]*\})/u;function ps(t){const e=[];let r="";function s(){r.length>0&&(e.push({kind:"text",text:r}),r="")}for(const[n,o]of t.split(hs).entries())if(n%2===0){if(o.includes("{"))throw new Error(`Unclosed "{" in ${JSON.stringify(t)}`);r+=o}else o==="{{"?r+="{":(s(),e.push(ws(o.slice(1,-1))));return s(),e}function ys(t,e){if(!us.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 ws(t){const e=ds.exec(t)?.groups,r=e?.key??t;if(ys(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 bs=Symbol("@appetizeio/client:v1Compat");function $t(t){return t?.[bs]}class ms{readable;ready;get dimensions(){return this.#s}#e=[];#r=!1;#t;#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.#t=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.#t.enqueue(e)}requestKeyFrame=()=>{this.#r||this.#n()};async*[Symbol.asyncIterator](){const e=this.readable.getReader();try{for(let r=await e.read();!r.done;r=await e.read())yield r.value}finally{await e.cancel()}}#o(e){this.#r||(this.#t.close(),this.#a(e))}#a(e){this.#r=!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 gs{#e=!1;#r;#t;#s=new Set;constructor(e){this.#r=e}close(){this.#t=void 0;for(const e of[...this.#s])e.close()}async createStream({signal:e}={}){e?.throwIfAborted();const r=new ms({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.#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)}#i(e){this.#s.delete(e),!(this.#s.size>0||!this.#t)&&(this.#t=void 0,X(this.#r,"appetizeio.device.server.video.stop",void 0))}#o(){this.#e||(this.#e=!0,X(this.#r,"appetizeio.device.server.video.requestKeyFrame",void 0))}}class Es{debug;keyboard;touch;video;#e;#r=[];#t;constructor(e,r={}){const s=$t(r)??{},{baseUrl:n,onClose:o,signal:f}=r;this.#e=n?Ss(n):void 0;const{onRequest:b,parent:y,proxyRequest:v}=s,g=vs(b);f?.addEventListener("abort",this.close);const[x,R]=st(),[L,U]=st();this.#r.push(()=>{x.close(),R.close(),L.close(),U.close()}),this.#r.push(tt(U,e,{leftEffects:v}));const P=y==="playwright"?ls({onRequest:g,proxyInlet:L}):y?is({onRequest:g,parent:y,proxyInlet:L,signal:f}):void 0;P&&this.#r.push(P.cleanup),this.#r.push(tt(R,L,{notifiesLeft:P?.notifies}));const{client:W,unsub:pe}=$r(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.#t=W,this.#r.push(pe);const G=new ts(this.#t);this.#r.push(()=>{G.close()});const k=new gs(this.#t);this.#r.push(()=>{k.close()}),this.debug=G,this.keyboard=ns(this.#t),this.touch=fs(this.#t),this.video=k,g&&(this.#r.push(Ce(R,z=>{g(z,{source:"self"})})),e instanceof jt&&this.#r.push(Ce(e,z=>{g(z,{source:"iframe"})}))),this.#r.push(()=>o?.())}async clearKeychain(){await this.#t.request("appetizeio.device.server.clearKeychain")}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?nt(e):void 0})}async open(e){new URL(e),await this.#t.request("appetizeio.device.server.open",{url:e})}async press(e){await this.#t.request("appetizeio.device.server.press",{action:e})}async rotate(e){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,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.#t.request("appetizeio.device.server.swipe",{gesture:cs(e),options:r})}async tap(e,r){await this.#t.request("appetizeio.device.server.tap",{options:r,selector:Le(e)})}async type(e,r){await this.#t.request("appetizeio.device.server.type",{options:r,steps:ps(e)})}}function Ss(t){const e=new URL(t);return e.protocol==="ws:"?e.protocol="http:":e.protocol==="wss:"&&(e.protocol="https:"),e.href}const vs=t=>{if(t)return(e,r)=>{e.method.startsWith("appetizeio.device.server.")&&t(e,r)}};function it(t){try{return process.kill(t,0),!0}catch{return!1}}const As=["SIGINT","SIGTERM"],ks=150;function Os(t){const e=new AbortController,r=setInterval(()=>{it(t)||(clearInterval(r),e.abort(new Error("The device session exited")))},ks);return r.unref(),e.signal}function qt(){const t=new AbortController;for(const e of As)process.once(e,()=>{t.abort(new Error(`Received ${e}`))});return t.signal}function Is(t,e){return new Promise((r,s)=>{if(e.aborted){s(Jt(e.reason));return}const n=()=>{clearTimeout(o),s(Jt(e.reason))},o=setTimeout(()=>{e.removeEventListener("abort",n),r()},t);e.addEventListener("abort",n,{once:!0})})}function Jt(t){return t instanceof Error?t:new Error(String(t))}function Ms(t){const e=t.at(-1);return{options:Ts(e)?e:{},positionals:t.slice(0,-1).filter(r=>typeof r=="string"),signal:qt()}}function xs(t,e){const r=Wt(t,e);return r===void 0?void 0:Gt(r,e)}function Wt(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 ot(t,e){if(t!==void 0){if(typeof t!="string"||t==="")throw new Error(`${e} needs a value`);return t}}function Gt(t,e){if(!(t>=0&&t<=1))throw new Error(`${e} expects a number between 0 and 1`);return t}function Rs(t,e){const r=ot(t,e);if(r===void 0)throw new Error(`${e} needs a value`);return r}function Ts(t){return typeof t=="object"&&t!==null}const Cs="APPETIZEIO_FEATURE_FLAGS";function Ps(){const t={};for(const e of(process.env[Cs]??"").split(",")){const r=e.trim();r!==""&&(t[r]=!0)}return t}function Us(){const t=process.env.APPETIZE_API_TOKEN;if(!t)throw new Error("APPETIZE_API_TOKEN must be set");return t}function Ht(t){return ot(t.endpoint,"--endpoint")??Ls()}function Ls(){const t=process.env.APPETIZE_ENDPOINT?.trim();return t===""?void 0:t}const _s="https://appetize.io";async function Zt(t,{authorize:e=!0,commandOptions:r={},query:s={},...n}={}){const o=new URL(t,Ht(r)??_s);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",Us());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 Yt=["android","ios"];function Xt(t={},e){return Zt("/api/v2/service/devices",{authorize:!1,commandOptions:t,signal:e})}function Bs(t){return Yt.includes(t)}async function Ns(t,e={}){return(await Xt(e)).find(s=>s.id===t)?.platform}function Ds(t){let e={...t,updatedAt:new Date().toISOString()};return{path:lt(e.sessionId),save:r=>(e={...e,...r,updatedAt:new Date().toISOString()},Js(e),e)}}function Fs(){const t=er();return pt(t,{recursive:!0}),ur(t).map(e=>at(e)).filter(e=>e!==void 0)}function zs(t){if(t!==void 0){const r=at(t);if(!r)throw new Error(`No session found for id ${t}`);return r}const e=Fs().filter(qs);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(fr(lt(t),"utf8"))}catch{return}}function js(t){return te(ke(t),"control.sock")}function Qt(t){return te(ke(t),"daemon.log")}function Vs(t){return te(ke(t),"device.log.jsonl")}function Ks(t,e){return{daemon:Qt(t),device:Vs(t),...e==="intercept"?{network:$s(t)}:void 0}}function $s(t){return te(ke(t),"network.jsonl")}function ke(t){const e=te(er(),t);return pt(e,{recursive:!0}),e}function lt(t){return te(ke(t),"state.json")}function er(){return process.env.APPETIZE_CLI_HOME??te(dr(),".appetize","cli","sessions")}function qs(t){const e=t.state?.phase;return e==="ended"||e==="error"?!1:it(t.pid)}function Js(t){const e=lt(t.sessionId),r=`${e}.tmp`;lr(r,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`),cr(r,e)}const ct="APPETIZE_DAEMON_CONFIG";function Ws(){const t=process.env[ct];if(!t)throw new Error(`${ct} is not set`);return JSON.parse(t)}function Gs(t){return JSON.stringify(t)}export{Ir as A,Qe as B,$t as C,Es as D,Pe as E,Ws as F,Ds as G,Ns as H,tt as I,js as J,qt as K,Bt as S,Ae as T,Wt as a,Is as b,Xt as c,Vr as d,Yt as e,Zt as f,Rs as g,Qt as h,Bs as i,ct as j,at as k,Ps as l,Ht as m,Ks as n,it as o,ot as p,xs as q,Gt as r,Gs as s,Dt as t,zs as u,Os as v,rt as w,Ms as x,Pr as y,T as z};
|