UNPKG

agent-device

Version:

Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.

104 lines (95 loc) • 47.2 kB
import{a as e,r as t,t as n}from"./rolldown-runtime.js";import{t as r}from"./yauzl.js";import{a as i,c as a,f as o,l as s,n as c,o as l,r as u,s as d,t as f,u as p,v as m}from"./log-stream.js";import{g as h,n as ee,r as te,u as ne,v as g}from"./destination-tunnel-dialer.js";import{EventEmitter as _}from"events";import v from"fs";import{promisify as y}from"util";import{pipeline as b}from"stream";import x from"os";import S from"http";import C from"https";import w from"path";import re from"crypto";import{pipeline as T}from"stream/promises";import{execFile as E}from"child_process";var D=e(r(),1);const O=e=>new Promise(t=>setTimeout(t,e));var k=e(n(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),ee=e=>e.startsWith(`!`)||e.startsWith(`\\^`)?`^${e.slice(e[0]===`!`?1:2)}`:e,te=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ne=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*(?:\\\*\\\*\\\/)+/,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${te(r)}${i}`:i===`]`&&r.length%2==0?`[${ee(h(n))}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],g=/(^|\\\/)?\\\*$/,_=`regex`,v=`checkRegex`,y={[_](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[v](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},b=e=>ne.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),x=e=>typeof e==`string`,S=e=>e&&x(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,C=e=>e.split(s).filter(Boolean);var w=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_regex`;return this[e]?this[e]:this._make(_,e)}get checkRegex(){let e=`_checkRegex`;return this[e]?this[e]:this._make(v,e)}_make(e,t){let n=this.regexPrefix.replace(g,y[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let re=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=b(i);return new w(e,t,i,n,r,s)};var T=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(x(e)&&(e={pattern:e}),S(e.pattern)){let t=re(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(x(e)?C(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let E=(e,t)=>{throw new t(e)},D=(e,t,n)=>x(e)?e?!D.isNotRelative(e)||n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),O=e=>c.test(e);D.isNotRelative=O,D.convert=e=>e;var k=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new T(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&D.convert(e);return D(i,e,this._strictPathCheck?E:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,v)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,_);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,_)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let A=e=>new k(e),j=e=>D(e&&D.convert(e),e,m),M=()=>{D.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;D.isNotRelative=t=>e.test(t)||O(t)};typeof process<`u`&&process.platform===`win32`&&M(),t.exports=A,A.default=A,t.exports.isPathValid=j,f(t.exports,Symbol.for(`setupWindows`),M)}))(),1);const A=y(E);function j(e){return e.split(w.sep).join(`/`).replace(/^\.\/+/,``).replace(/\/+/g,`/`)}function M(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)t--;return t===e.length?e:e.slice(0,t)}async function N(e){try{let{stdout:t}=await A(`git`,[`ls-files`,`-z`],{cwd:e,maxBuffer:268435456}),n=new Set,r=new Set;for(let e of t.split(`\0`)){if(!e)continue;n.add(e);let t=e.lastIndexOf(`/`);for(;t>0;)r.add(e.substring(0,t)),t=e.lastIndexOf(`/`,t-1)}return{tracked:n,prefixes:r}}catch{return null}}const P=[`build/`,`.build/`,`DerivedData/`,`Index.noindex/`,`ModuleCache.noindex/`,`.index-build/`,`.swiftpm/`,`Pods/`,`Carthage/Build/`];async function ie(e,t){let n=w.resolve(e),r=new Map,i=e=>{let t=r.get(e);if(t!==void 0)return t;try{let r=v.readFileSync(w.join(n,e.split(`/`).join(w.sep),`.gitignore`),`utf-8`);t=(0,k.default)({ignorecase:!1,allowRelativePaths:!0}).add(r)}catch{t=null}return r.set(e,t),t},a=t.nestedGitignore??!!t.xcodeDefaults,o=e=>{let t=M(e),n=e.endsWith(`/`)?`/`:``,r=t.split(`/`),o,s=a?r.length:1;for(let e=0;e<s;e++){let t=i(r.slice(0,e).join(`/`));if(!t)continue;let a=t.test(r.slice(e).join(`/`)+n);if(a.ignored||a.unignored){o={ignored:a.ignored};let e=a.rule?.pattern;e!==void 0&&(o.rule=e)}}return o},s=M(j(w.relative(n,t.basisCacheDir))),c=s&&s!==`.`&&s!==`..`&&!s.startsWith(`../`),l=await N(n),u=t.log,d=new Set;return e=>{let n=j(e);if(!n)return!1;let r=M(n);if(c&&(r===s||r.startsWith(`${s}/`)))return!0;if(t.include?.(n))return!1;if(t.additional?.(n)||r===`.git`||r.startsWith(`.git/`)||r.endsWith(`/.git`)||r.includes(`/.git/`)||r===`.DS_Store`||r.endsWith(`/.DS_Store`))return!0;if(t.xcodeDefaults){for(let e of P)if(n.startsWith(e))return!0;if(n.includes(`/xcuserdata/`)||n.includes(`.dSYM/`))return!0}if(r.endsWith(`.xcconfig`))return!1;let i=r.slice(r.lastIndexOf(`/`)+1);if(i.endsWith(`.env`)||i.startsWith(`.env.`))return!1;let a=o(n);if(a?.ignored){if(l&&(l.tracked.has(r)||l.prefixes.has(r))){let e=a.rule??`<unknown>`;if(!d.has(e)){d.add(e);let t=`.gitignore rule '${e}' is dropping '${r}', which is tracked in git. The remote build will not see this path. Remove or scope the rule, or pass --include, if you need it synced.`;u?u(`warn`,t):console.warn(`[FolderSync]`,t)}}return!0}return!1}}const F=()=>{};function I(e){return new Promise(t=>setTimeout(t,e))}function L(e){let t=w.resolve(e),n=re.createHash(`sha1`).update(t).digest(`hex`).slice(0,12),r=w.basename(t,w.extname(t)).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``),i=r===``?`app`:r;return w.join(x.tmpdir(),`limrun-sync-app-${i}-${n}`)}function R(e){return w.join(L(e),`Extracted.app`)}function z(e){return e.replace(/\\/g,`/`)}function B(e){return e.includes(`\0`)||w.posix.isAbsolute(e)?!0:e.split(`/`).some(e=>e===`..`)}function V(e){return e.externalFileAttributes>>>16&65535}function ae(e){return(V(e)&61440)==40960}function H(e){return e.fileName.endsWith(`/`)}function U(e,t){return V(e)&4095||t}async function W(e){try{return await D.openPromise(e,{autoClose:!1,lazyEntries:!0,strictFileNames:!0,validateEntrySizes:!0})}catch(t){let n=t instanceof Error?`: ${t.message}`:``;throw Error(`The path is not a valid app bundle directory or ZIP/IPA archive: ${e}${n}`)}}async function G(e){let t=[];for await(let n of e.eachEntry())t.push(n);return t}async function oe(e){let t=await v.promises.lstat(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e});t&&(!t.isDirectory()||t.isSymbolicLink())&&await v.promises.rm(e,{recursive:!0,force:!0}),await v.promises.mkdir(e,{recursive:!0})}function K(e,t){let n=new Set,r=new Set;for(let t of e){let e=z(t.fileName);if(B(e))throw Error(`ZIP entry has an unsafe path: ${t.fileName}`);if(H(t))continue;let i=e.startsWith(`Payload/`)?e.slice(8):``;if(i===``)continue;let[a,...o]=i.split(`/`);a?.endsWith(`.app`)&&(n.add(a),o.join(`/`)===`Info.plist`&&r.add(a))}if(n.size===0)throw Error(`ZIP/IPA archive contains no Payload/*.app bundle: ${t}`);if(n.size>1)throw Error(`ZIP/IPA archive contains more than one Payload/*.app bundle (${[...n].join(`, `)}); expected exactly one`);let i=[...n][0];if(!r.has(i))throw Error(`ZIP/IPA archive app bundle is missing Info.plist: Payload/${i}/Info.plist`);return i}async function se(e,t,n,r){if(H(t)){await v.promises.mkdir(n,{recursive:!0,mode:U(t,493)});return}if(await v.promises.mkdir(w.dirname(n),{recursive:!0}),ae(t)){let i=await e.openReadStreamPromise(t),a=[];for await(let e of i)a.push(Buffer.isBuffer(e)?e:Buffer.from(e));let o=Buffer.concat(a).toString(`utf8`),s=w.resolve(w.dirname(n),o),c=w.resolve(r);if(s!==c&&!s.startsWith(c+w.sep))throw Error(`ZIP/IPA symlink escapes app bundle: ${t.fileName} -> ${o}`);await v.promises.rm(n,{force:!0}),await v.promises.symlink(o,n);return}let i=await e.openReadStreamPromise(t);await T(i,v.createWriteStream(n,{mode:U(t,420)})),await v.promises.chmod(n,U(t,420))}async function q(e){let t=w.resolve(e),n=R(t);await oe(w.dirname(n));let r=await W(t);try{let e=await G(r),i=K(e,t),a=`Payload/${i}/`;await v.promises.rm(n,{recursive:!0,force:!0}),await oe(n);for(let t of e){let e=z(t.fileName);if(e!==`Payload/${i}`&&!e.startsWith(a))continue;let o=e===`Payload/${i}`?``:e.slice(a.length);if(o===``){await v.promises.mkdir(n,{recursive:!0});continue}if(B(o))throw Error(`ZIP entry has an unsafe app-relative path: ${t.fileName}`);let s=w.join(n,o.split(`/`).join(w.sep)),c=w.resolve(n),l=w.resolve(s);if(l!==c&&!l.startsWith(c+w.sep))throw Error(`ZIP entry escapes app bundle: ${t.fileName}`);await se(r,t,s,n)}return{appPath:n,cacheIdentityPath:t,isArchive:!0,archivePath:t}}finally{r.close()}}async function ce(e){let t=w.resolve(e),n=await v.promises.stat(t);if(n.isDirectory())return{appPath:t,cacheIdentityPath:t,isArchive:!1};if(!n.isFile())throw Error(`The path is neither an app bundle directory nor a ZIP/IPA archive: ${e}`);return await q(t)}async function le(e,t){let n=Date.now()+1e4,r;for(;!t()&&Date.now()<n;){let t=await v.promises.stat(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(t?.isFile()){let e={size:t.size,mtimeMs:t.mtimeMs};if(r&&r.size===e.size&&r.mtimeMs===e.mtimeMs)return!0;r=e}else r=void 0;await I(100)}return!1}function ue(e){let t=w.resolve(e.archivePath),n=e.log??F,r=w.dirname(t),i=w.basename(t),a,o=!1,s=!1,c=!1,l,u=async()=>{o=!0;try{if(!await le(t,()=>c)){c||n(`warn`,`ZIP/IPA archive did not become readable after change: ${t}`);return}await q(t),n(`debug`,`re-extracted ZIP/IPA archive: ${t}`),await e.onExtracted?.()}catch(e){n(`error`,`failed to re-extract ZIP/IPA archive ${t}: ${e instanceof Error?e.message:e}`)}finally{o=!1,s&&!c&&(s=!1,d())}},d=()=>{if(c)return;if(o){s=!0;return}let e=u();l=e,e.finally(()=>{l===e&&(l=void 0)})},f=()=>{c||(a&&clearTimeout(a),a=setTimeout(()=>{a=void 0,d()},500))},p=v.watch(r,(e,t)=>{t?.toString()===i&&f()});return n(`debug`,`watchAppArchive: ${t}`),{close:async()=>{c=!0,s=!1,a&&=(clearTimeout(a),void 0),p.close(),await l}}}async function de({localPort:e=0,remoteBaseUrl:t,headers:n={}}){let r=he(t),i=S.createServer((e,t)=>{let i=e.url||`/`,a=new URL(`${r}${i.startsWith(`/`)?i:`/${i}`}`),o=(a.protocol===`https:`?C:S).request(a,{method:e.method,headers:{...e.headers,host:a.host,...n}},e=>{t.writeHead(e.statusCode??502,e.headers),e.pipe(t)});o.on(`error`,e=>{t.headersSent||t.writeHead(502,{"content-type":`text/plain`}),t.end(e.message)}),e.pipe(o)});await ge(i,e);let a=i.address();if(!a||typeof a==`string`)throw Error(`Failed to start HTTP proxy.`);return{port:a.port,close:()=>Y(i)}}const J=new Set([`connection`,`proxy-connection`,`keep-alive`,`proxy-authorization`,`proxy-authenticate`,`te`,`trailer`,`upgrade`]);function fe(e){return Object.fromEntries(Object.entries(e).filter(([e])=>!J.has(e)))}async function pe({matchPort:e,remoteBaseUrl:t,headers:n={}}){let r=he(t),i={"http:":new S.Agent({keepAlive:!0}),"https:":new C.Agent({keepAlive:!0})},a=S.createServer((t,a)=>{let o;try{o=new URL(t.url??``)}catch{}if(!o||o.protocol!==`http:`&&o.protocol!==`https:`){a.writeHead(400,{"content-type":`text/plain`}),a.end(`Limrun forward proxy only accepts absolute-form request targets.`);return}if(!me(o.hostname)||Number(o.port)!==e){a.writeHead(403,{"content-type":`text/plain`}),a.end(`Limrun forward proxy only forwards 127.0.0.1:${e}.`);return}let s=new URL(`${r}${o.pathname}${o.search}`),c=(s.protocol===`https:`?C:S).request(s,{agent:i[s.protocol],method:t.method,headers:{...fe(t.headers),host:s.host,...n}},e=>{a.writeHead(e.statusCode??502,fe(e.headers)),b(e,a,()=>{})});c.on(`error`,e=>{if(a.headersSent){a.destroy(e);return}a.writeHead(502,{"content-type":`text/plain`}),a.end(e.message)}),a.on(`close`,()=>{a.writableFinished||c.destroy()}),b(t,c,()=>{})});a.on(`connect`,(e,t)=>{t.end(`HTTP/1.1 501 Not Implemented\r \r Limrun forward proxy does not tunnel CONNECT.\r `)}),await ge(a,0);let o=a.address();if(!o||typeof o==`string`)throw Error(`Failed to start HTTP forward proxy.`);return{port:o.port,close:async()=>{await Y(a),i[`http:`].destroy(),i[`https:`].destroy()}}}function me(e){return e===`localhost`||e===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(e)}function he(e){return e.replace(/\/+$/,``)}function ge(e,t){return new Promise((n,r)=>{e.once(`error`,r),e.listen(t,`127.0.0.1`,()=>{e.off(`error`,r),n()})})}function Y(e){return new Promise((t,n)=>{e.close(e=>{e?n(e):t()})})}const _e=new Set([`openurl`,`launch`,`terminate`,`uninstall`,`privacy`,`location`,`status_bar`]);async function ve(e){let t=await ye({client:e,udid:e.deviceInfo.udid});try{let n=await be({shimUrl:t.url,udid:e.deviceInfo.udid});return{dir:n,close:async()=>{await t.close(),v.rmSync(n,{recursive:!0,force:!0})}}}catch(e){throw await t.close().catch(()=>{}),e}}async function ye({client:e,udid:t}){let n=S.createServer(async(n,r)=>{if(n.method!==`POST`||n.url!==`/xcrun`){X(r,404,{code:127,stdout:``,stderr:`not found`});return}try{X(r,200,await xe(e,t,(await Me(n)).args??[]))}catch{X(r,200,{code:1,stdout:``,stderr:`limrun xcrun shim failed to execute the requested command.`})}});await Ae(n,0);let r=n.address();if(!r||typeof r==`string`)throw Error(`Failed to start Limrun xcrun shim server.`);return{url:`http://127.0.0.1:${r.port}/xcrun`,close:()=>je(n)}}async function be(e){let t=v.mkdtempSync(w.join(x.tmpdir(),`limrun-xcrun-shim-`)),n=w.join(t,`xcrun`);return v.writeFileSync(n,ke(e),`utf8`),v.chmodSync(n,493),t}async function xe(e,t,n){if(n[0]===`devicectl`)return Se(n);if(n[0]!==`simctl`)return{code:127,stdout:``,stderr:`unsupported xcrun command: ${n.join(` `)}`};let r=n.slice(1),i=r[0],a=Ee(i,r);if(i===`list`)return Ce(e.deviceInfo.udid,r);if(!Te(a,t))return{code:64,stdout:``,stderr:`unsupported non-Limrun simctl target '${a??``}'.`};if(i===`listapps`){let t=await e.listApps();return{code:0,stdout:`${JSON.stringify(Oe(t))}\n`,stderr:``}}if(i===`install`){let t=r[2];return t?(await e.syncApp(t,{install:!0,watch:!1}),{code:0,stdout:``,stderr:``}):{code:64,stdout:``,stderr:`simctl install requires a local .app path.`}}return we(i)||(!i||!_e.has(i)?{code:64,stdout:``,stderr:`limrun xcrun shim does not support simctl ${i??``}.`}:await e.simctl(r).wait())}function Se(e){let t=[];for(let n=1;n<e.length;n++){if(e[n]===`--json-output`){n++;continue}e[n].startsWith(`-`)||t.push(e[n])}if(t[0]!==`list`||t[1]!==`devices`)return{code:127,stdout:``,stderr:`unsupported devicectl command: ${e.join(` `)}`};let n=JSON.stringify({result:{devices:[]}}),r=e.indexOf(`--json-output`),i=r===-1?void 0:e[r+1];if(i&&i!==`-`){try{v.writeFileSync(i,n)}catch(e){return{code:1,stdout:``,stderr:`could not write devicectl output to ${i}: ${e instanceof Error?e.message:String(e)}`}}return{code:0,stdout:``,stderr:``}}return{code:0,stdout:`${n}\n`,stderr:``}}function Ce(e,t){return t.includes(`-j`)?{code:0,stdout:`${JSON.stringify(De(e))}\n`,stderr:``}:{code:64,stdout:``,stderr:"limrun xcrun shim only supports `xcrun simctl list -j`."}}function we(e){if(e===`get_app_container`)return{code:64,stdout:``,stderr:`limrun xcrun shim does not support get_app_container because upstream tools expect a local filesystem path.`};if(e===`keychain`)return{code:64,stdout:``,stderr:`limrun xcrun shim does not support simctl keychain in v1.`};if(e===`io`)return{code:64,stdout:``,stderr:`limrun xcrun shim does not support simctl io recordVideo in v1.`};if(e===`push`||e===`addmedia`)return{code:64,stdout:``,stderr:`limrun xcrun shim does not support path-bearing simctl ${e} in v1.`}}function Te(e,t){return e===t||e===`booted`}function Ee(e,t){return e===`launch`?t.slice(1).find(e=>!e.startsWith(`-`)):t[1]}function De(e){let t=`com.apple.CoreSimulator.SimRuntime.iOS-18-0`,n=`com.apple.CoreSimulator.SimDeviceType.iPhone-16-Pro`;return{devices:{[t]:[{availability:`(available)`,dataPath:`/tmp/limrun-sim/${e}/data`,logPath:`/tmp/limrun-sim/${e}/logs`,isAvailable:!0,name:process.env.LIMRUN_IOS_DEVICE_NAME||`Limrun iPhone`,state:`Booted`,udid:e,deviceTypeIdentifier:n,availabilityError:null}]},devicetypes:[{bundlePath:``,identifier:n,maxRuntimeVersion:999999,maxRuntimeVersionString:null,minRuntimeVersion:0,minRuntimeVersionString:null,modelIdentifier:`iPhone17,1`,name:`iPhone 16 Pro`,productFamily:`iPhone`}],pairs:{},runtimes:[{availability:`(available)`,bundlePath:``,buildversion:`22A000`,identifier:t,isInternal:!1,isAvailable:!0,name:process.env.LIMRUN_IOS_RUNTIME_NAME||`iOS 18.0`,platform:`iOS`,runtimeRoot:``,supportedDeviceTypes:[],version:`18.0`}]}}function Oe(e){return Object.fromEntries(e.map(e=>[e.bundleId,{CFBundleIdentifier:e.bundleId,...e.name?{CFBundleName:e.name}:{}}]))}function ke(e){return`#!/usr/bin/env node const http = require('node:http'); const { spawnSync } = require('node:child_process'); const args = process.argv.slice(2); const realXcrun = process.env.LIMRUN_REAL_XCRUN || '/usr/bin/xcrun'; function delegate() { const result = spawnSync(realXcrun, args, { stdio: 'inherit' }); if (result.error) { process.stderr.write(String(result.error.message || result.error) + '\\n'); process.exit(127); } process.exit(result.status ?? 1); } function fail(message) { process.stderr.write('limrun xcrun shim: ' + message + '\\n'); process.exit(64); } // Physical-device enumeration (e.g. Maestro's device picker) is answered by // the shim server; real devicectl does not exist off macOS. Every other // devicectl subcommand delegates. Flags can precede the subcommand // (devicectl --json-output <path> list devices), so match on positionals. function devicectlPositionals(args) { const positionals = []; for (let i = 1; i < args.length; i++) { if (args[i] === '--json-output') { i++; continue; } if (args[i].startsWith('-')) continue; positionals.push(args[i]); } return positionals; } const devicectlSubcommand = args[0] === 'devicectl' ? devicectlPositionals(args) : []; const isDevicectlListDevices = devicectlSubcommand[0] === 'list' && devicectlSubcommand[1] === 'devices'; if (args[0] !== 'simctl' && !isDevicectlListDevices) { delegate(); } const shimUrl = ${e?JSON.stringify(e.shimUrl):`process.env.LIMRUN_XCRUN_SHIM_URL`}; const udid = ${e?JSON.stringify(e.udid):`process.env.LIMRUN_IOS_UDID`}; if (!shimUrl || !udid) { fail('LIMRUN_XCRUN_SHIM_URL and LIMRUN_IOS_UDID are required.'); } function simctlTarget(command, simctlArgs) { if (command === 'launch') { return simctlArgs.slice(1).find((arg) => !arg.startsWith('-')); } return simctlArgs[1]; } function isLimrunTarget(value) { return value === udid || value === 'booted'; } if (args[0] === 'simctl') { const simctlArgs = args.slice(1); const command = simctlArgs[0]; const target = simctlTarget(command, simctlArgs); if (command !== 'list' && !isLimrunTarget(target)) { delegate(); } } const parsed = new URL(shimUrl); const body = JSON.stringify({ args }); const req = http.request(parsed, { method: 'POST', headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body), }, }, (res) => { const chunks = []; res.on('data', (chunk) => chunks.push(chunk)); res.on('end', () => { let payload; try { payload = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch (error) { process.stderr.write('limrun xcrun shim: invalid shim response\\n'); process.exit(1); } if (payload.stdout) process.stdout.write(payload.stdout); if (payload.stderr) process.stderr.write(payload.stderr); process.exit(typeof payload.code === 'number' ? payload.code : 1); }); }); req.on('error', (error) => { process.stderr.write('limrun xcrun shim: ' + error.message + '\\n'); process.exit(1); }); req.end(body); `}function Ae(e,t){return new Promise((n,r)=>{e.once(`error`,r),e.listen(t,`127.0.0.1`,()=>{e.off(`error`,r),n()})})}function je(e){return new Promise((t,n)=>{e.close(e=>{e?n(e):t()})})}function Me(e){return new Promise((t,n)=>{let r=[];e.on(`data`,e=>r.push(Buffer.from(e))),e.on(`end`,()=>{try{t(JSON.parse(Buffer.concat(r).toString(`utf8`)||`{}`))}catch(e){n(e)}}),e.on(`error`,n)})}function X(e,t,n){let r=JSON.stringify(n);e.writeHead(t,{"content-type":`application/json`,"content-length":Buffer.byteLength(r)}),e.end(r)}var Ne=t({REVERSE_TUNNEL_REMOTE_PORT_MAX:()=>Fe,REVERSE_TUNNEL_REMOTE_PORT_MIN:()=>Pe,RecordingQuality:()=>Be,SimctlExecution:()=>Ve,TAP_ELEMENT_TIMEOUT_MS:()=>Ie,createInstanceClient:()=>He,deriveReverseTunnelUrl:()=>Re,parseElementTree:()=>ze});const Pe=57090,Fe=57099,Ie=9e4;function Le(e,t){let n=t?`recording_${t}.mp4`:`recording.mp4`;return`${e}/files?name=${encodeURIComponent(n)}`}function Z(e){if(/^[a-z0-9][a-z0-9_-]{0,63}$/.exec(e)?.[0]!==e)throw Error(`recordingId must be 1–64 lowercase letters, digits, underscores or hyphens, start with a letter or digit`)}function Re(e,t){let n=new URL(e);if(n.protocol===`https:`)n.protocol=`wss:`;else if(n.protocol===`http:`)n.protocol=`ws:`;else throw Error(`Unsupported apiUrl protocol for reverse tunnel: ${n.protocol}`);return n.pathname=`${n.pathname.replace(/\/+$/,``)}/reverse-tunnel`,n.search=``,n.hash=``,n.searchParams.set(`remotePort`,String(t)),n.toString()}function ze(e){return JSON.parse(e)}var Be;(function(e){e[e.Q5=5]=`Q5`,e[e.Q6=6]=`Q6`,e[e.Q7=7]=`Q7`,e[e.Q8=8]=`Q8`,e[e.Q9=9]=`Q9`,e[e.Q10=10]=`Q10`})(Be||={});var Ve=class extends _{get isRunning(){return!this.completed}constructor(e,{encoding:t=`utf-8`}={}){super(),this.stdoutChunks=[],this.stderrChunks=[],this.stdoutLineBuffer=``,this.stderrLineBuffer=``,this.exitCodeValue=null,this.completed=!1,this.waitPromise=null,this.stopCallback=null,this.stopCallback=e,this.encoding=t}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}off(e,t){return super.off(e,t)}wait(){return this.waitPromise||=new Promise((e,t)=>{if(this.completed){e({code:this.exitCodeValue,stdout:Buffer.concat(this.stdoutChunks).toString(this.encoding),stderr:Buffer.concat(this.stderrChunks).toString(this.encoding)});return}this.once(`exit`,t=>{e({code:t,stdout:Buffer.concat(this.stdoutChunks).toString(this.encoding),stderr:Buffer.concat(this.stderrChunks).toString(this.encoding)})}),this.once(`error`,e=>{t(e)})}),this.waitPromise}stop(){this.stopCallback&&this.stopCallback()}_handleStdout(e){this.stdoutChunks.push(e),this.emit(`stdout`,e),this.stdoutLineBuffer+=e.toString(this.encoding);let t=this.stdoutLineBuffer.split(` `);this.stdoutLineBuffer=t.pop()||``;for(let e of t)this.emit(`line-stdout`,e)}_handleStderr(e){this.stderrChunks.push(e),this.emit(`stderr`,e),this.stderrLineBuffer+=e.toString(this.encoding);let t=this.stderrLineBuffer.split(` `);this.stderrLineBuffer=t.pop()||``;for(let e of t)this.emit(`line-stderr`,e)}_handleExit(e){this.stdoutLineBuffer&&=(this.emit(`line-stdout`,this.stdoutLineBuffer),``),this.stderrLineBuffer&&=(this.emit(`line-stderr`,this.stderrLineBuffer),``),this.exitCodeValue=e,this.completed=!0,this.emit(`exit`,e)}_handleError(e){this.completed=!0,this.emit(`error`,e)}};async function He(e){let t=`${e.apiUrl.replace(`https://`,`wss://`).replace(`http://`,`ws://`)}/signaling?token=${e.token}`,n=e.logLevel??`info`,r=e.maxReconnectAttempts??6,_=e.reconnectDelay??1e3,y=e.maxReconnectDelay??3e4,b,S=`connecting`,C=0,T,E=!1,D,k=new Map,A=new Map,j=new Map,M=[],N=[],P=new Set,F={debug:(...e)=>{n===`debug`&&console.log(...e)},info:(...e)=>{(n===`info`||n===`debug`)&&console.log(...e)},warn:(...e)=>{(n===`warn`||n===`info`||n===`debug`)&&console.warn(...e)},error:(...e)=>{n!==`none`&&console.error(...e)}},I=e=>{S!==e&&(S=e,F.debug(`Connection state changed to: ${e}`),P.forEach(t=>{try{t(e)}catch(e){F.error(`Error in connection state callback:`,e)}}))},L=e=>{k.forEach(t=>{clearTimeout(t.timeout),t.reject(Error(e))}),k.clear(),A.forEach(t=>t._handleError(Error(e))),A.clear()},R=()=>{T&&=(clearTimeout(T),void 0),G&&=(clearInterval(G),void 0),b&&=(b.removeAllListeners(),b.on(`error`,()=>{}),(b.readyState===h.default.OPEN||b.readyState===h.default.CONNECTING)&&b.close(),void 0)},z=()=>{let e=M.splice(0);for(let t of e)t().catch(e=>F.warn(`Failed to close xcrun shim:`,e));let t=N.splice(0);for(let e of t)e().catch(e=>F.warn(`Failed to close HTTP proxy:`,e))},B=()=>{R(),z()},V=(e,t,n)=>{let r=j.get(e)??new Map;r.set(t,n),j.set(e,r)},ae=(e,t)=>{let n=j.get(e);if(!n)return;let r=n.get(t);if(r)return n.delete(t),n.size===0&&j.delete(e),r},H=(e,t)=>j.get(e)?.get(t),U=(e,t)=>{let n=j.get(e);n&&(n.delete(t),n.size===0&&j.delete(e))},W=()=>{j.clear()},G,oe=Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15);return new Promise((j,z)=>{let K=!1,se=()=>{if(E){F.debug(`Skipping reconnection (intentional disconnect)`);return}if(s(D??``)){F.error(`Skipping reconnection (non-retryable error): ${D}`),I(`disconnected`),W();return}if(C>=r){F.error(`Max reconnection attempts (${r}) reached. Giving up.`),I(`disconnected`),W();return}let e=Math.min(_*2**C,y);C++,F.debug(`Scheduling reconnection attempt ${C} in ${e}ms...`),I(`reconnecting`),T=setTimeout(()=>{F.debug(`Attempting to reconnect (attempt ${C})...`),Y()},e)},q=()=>`ts-client-${Date.now()}-${Math.random().toString(36).substring(7)}`,le=e=>{if(e.type!==`launchApp`)return e;let t=e.runtime;return{type:e.type,id:e.id,execId:e.execId,bundleId:e.bundleId,mode:e.mode,runtime:t?{kind:t.kind,version:t.version}:void 0}},J=(e,t={},n,r=3e4)=>new Promise((i,a)=>{if(!b||b.readyState!==h.default.OPEN){a(Error(`WebSocket is not connected or connection is not open.`));return}let o=q(),s=setTimeout(()=>{k.delete(o),a(Error(`Request ${e} timed out`))},r);k.set(o,n?{resolve:i,reject:a,timeout:s,transform:n}:{resolve:i,reject:a,timeout:s});let c={type:e,id:o,...t};F.debug(`Sending request:`,le(c)),b.send(JSON.stringify(c),t=>{t&&(clearTimeout(s),k.delete(o),F.error(`Failed to send ${e} request:`,t),a(t))})}),fe=e=>e.length===0?[]:e.split(/\r?\n/),me=e=>{if(e.type!==`appExit`)return!1;let{execId:t,bundleId:n}=e;if(typeof t!=`string`||typeof n!=`string`)return F.warn(`Received malformed appExit message:`,e),!0;let r=ae(`appExit`,t)??H(`monitorExit`,t);return r?(r(e).catch(e=>{F.error(`Error processing appExit notification for execId ${t}:`,e)}),!0):(F.debug(`Received appExit for unknown or already handled execId: ${t}`),!0)},he=e=>{if(e.type!==`appHang`)return!1;let{execId:t,bundleId:n,hang:r}=e;if(typeof t!=`string`||typeof n!=`string`||typeof r!=`object`||!r)return F.warn(`Received malformed appHang message:`,e),!0;let i=H(`appHang`,t);return i?(i(e).catch(e=>{F.error(`Error processing appHang notification for execId ${t}:`,e)}),!0):(F.debug(`Received appHang for unknown or stopped execId: ${t}`),!0)},ge={screenshotResult:e=>({base64:e.base64,width:e.width,height:e.height}),elementTreeResult:e=>ze(e.json??`[]`),tapResult:()=>void 0,tapElementResult:e=>({elementLabel:e.elementLabel,elementType:e.elementType,method:e.method}),incrementElementResult:e=>({elementLabel:e.elementLabel}),decrementElementResult:e=>({elementLabel:e.elementLabel}),setElementValueResult:e=>({elementLabel:e.elementLabel}),typeTextResult:()=>void 0,pressKeyResult:()=>void 0,toggleKeyboardResult:()=>void 0,launchAppResult:()=>void 0,terminateAppResult:()=>void 0,watchAppResult:()=>void 0,monitorAppResult:()=>void 0,unwatchAppResult:()=>void 0,appLogTailResult:e=>e.logs??``,listAppsResult:e=>JSON.parse(e.apps||`[]`),listOpenFilesResult:e=>e.files||[],deviceInfoResult:e=>({udid:e.udid,screenWidth:e.screenWidth,screenHeight:e.screenHeight,model:e.model,osVersion:e.osVersion}),openUrlResult:()=>void 0,appInstallationResult:e=>({url:e.url||``,bundleId:e.bundleId||``}),keychainExportResult:()=>void 0,keychainImportResult:e=>({durationMs:e.durationMs??0}),startVideoRecordingResult:()=>void 0,startVideoRecordingSessionResult:e=>({recordingId:e.recordingId}),stopVideoRecordingSessionResult:e=>({recordingId:e.recordingId}),stopVideoRecordingResult:()=>void 0,startAppLogCaptureResult:()=>void 0,stopAppLogCaptureResult:()=>void 0,startEventCaptureResult:()=>void 0,stopEventCaptureResult:()=>void 0,cameraControlResult:()=>void 0,playOnMicrophoneResult:e=>({duration:e.duration??0,once:e.once??!1}),stopMicrophonePlaybackResult:()=>void 0,microphoneStatusResult:e=>e.status??{source:`silence`},setOrientationResult:()=>void 0,foldStateResult:e=>e.state??null,scrollResult:()=>void 0,performActionsResult:e=>({results:e.results??[]}),xcrunResult:e=>({stdout:e.stdout?Buffer.from(e.stdout,`base64`).toString(`utf-8`):``,stderr:e.stderr?Buffer.from(e.stderr,`base64`).toString(`utf-8`):``,exitCode:e.exitCode??-1}),xcodebuildResult:e=>({stdout:e.stdout?Buffer.from(e.stdout,`base64`).toString(`utf-8`):``,stderr:e.stderr?Buffer.from(e.stderr,`base64`).toString(`utf-8`):``,exitCode:e.exitCode??-1})},Y=()=>{R(),I(`connecting`);let e=g.getWebSocketAgent(t);b=new h.default(t,e?{agent:e}:{}),b.on(`message`,e=>{let t;try{t=JSON.parse(e.toString())}catch(t){F.error({data:e,error:t},`Failed to parse JSON message`);return}if(me(t)||he(t))return;if(t.type===`simctlStream`){let e=A.get(t.id);if(!e){F.debug(`Received simctl stream for unknown execution: ${t.id}`);return}if(t.stdout)try{e._handleStdout(Buffer.from(t.stdout,`base64`))}catch(e){F.error(`Failed to decode stdout data:`,e)}if(t.stderr)try{e._handleStderr(Buffer.from(t.stderr,`base64`))}catch(e){F.error(`Failed to decode stderr data:`,e)}t.exitCode!==void 0&&(F.debug(`Simctl execution ${t.id} completed with exit code ${t.exitCode}`),e._handleExit(t.exitCode),A.delete(t.id));return}let n=k.get(t.id);if(!n){F.debug(`Received response for unknown or already handled request: ${t.id}`);return}if(clearTimeout(n.timeout),k.delete(t.id),t.error){F.debug(`Server error for ${t.type}: ${t.error}`),n.reject(Error(t.error));return}let r=n.transform??ge[t.type];if(r)try{n.resolve(r(t))}catch(e){n.reject(e)}else F.warn(`Received unexpected message type:`,t.type),n.resolve(t)}),b.on(`error`,e=>{D=e.message,F.error(`WebSocket error:`,e.message),!K&&(b?.readyState===h.default.CONNECTING||b?.readyState===h.default.OPEN)&&z(e)}),b.on(`close`,()=>{G&&=(clearInterval(G),void 0);let e=!E&&!s(D??``)&&S!==`disconnected`;I(`disconnected`),F.debug(`Disconnected from server.`),L(`Connection closed`),e?se():s(D??``)&&(F.error(`Closing connection due to non-retryable error: ${D}`),B(),I(`disconnected`),L(`Non-retryable error`),W(),F.debug(`Non-retryable error. Closing connection.`))}),b.on(`open`,async()=>{if(F.debug(`Connected to ${t}`),C=0,D=void 0,I(`connected`),G=setInterval(()=>{b&&b.readyState===h.default.OPEN&&b.ping()},3e4),!K){try{Q=await Tt(),F.debug(`Device info fetched:`,Q)}catch(e){F.error(`Failed to fetch device info:`,e),z(e);return}K=!0,j({screenshot:_e,elementTree:ye,elementTreeRaw:be,tap:xe,tapWithScreenSize:Se,tapElement:Te,incrementElement:Ee,decrementElement:De,setElementValue:Oe,typeText:ke,pressKey:Ae,toggleKeyboard:je,launchApp:Me,terminateApp:He,watchApp:Ne,monitorApp:Be,appLogTail:Ue,streamAppLog:We,streamSyslog:Ge,listApps:Ke,openUrl:qe,installApp:Je,saveKeychain:Ye,restoreKeychain:Xe,setOrientation:nt,getFoldState:et,screenshotDisplay:Qe,tapDisplay:$e,setDuoOrientation:Ze,setHingeAngle:tt,scroll:rt,performActions:it,startRecording:ot,stopRecording:ht,startRecordingSession:st,stopRecordingSession:ct,startAppLogCapture:lt,stopAppLogCapture:ut,startEventCapture:dt,stopEventCapture:ft,streamAppLogCapture:pt,streamEventCapture:mt,playOnMicrophone:gt,stopMicrophonePlayback:_t,microphoneStatus:vt,keepAlive:yt,syncApp:bt,setStoreKitConfig:Pt,addCaCertificate:Ft,clearStoreKitConfig:It,discoverStoreKitConfig:Lt,softReset:Rt,startReverseTunnel:zt,startTunnel:Bt,getTunnelStatus:Vt,stopTunnel:Ht,startHttpProxy:Ut,startForwardHttpProxy:Wt,disconnect:$,getConnectionState:Gt,onConnectionStateChange:Kt,simctl:Et,xcrun:St,startXcrunShim:Ct,xcodebuild:wt,pushFile:Ot,pullFile:kt,listFiles:At,deleteFile:jt,setCameraVideo:Mt,clearCameraVideo:Nt,lsof:xt,deviceInfo:Q})}})},_e=(e={})=>J(`screenshot`,e),ye=e=>J(`elementTree`,{point:e}),be=e=>J(`elementTree`,{point:e},e=>e.json??``),xe=(e,t)=>J(`tap`,{x:e,y:t}),Se=(e,t,n,r)=>J(`tap`,{x:e,y:t,screenWidth:n,screenHeight:r}),Ce=(e,t)=>J(`tapElement`,{selector:e,activate:t?.activate},void 0,t?.timeoutMs??9e4),we=e=>{let t=e instanceof Error?e.message:String(e);return/matched nothing in the accessibility tree|was not found on screen after scrolling|Accessibility element not found for selector/.test(t)},Te=async(e,t)=>{if(!t?.scrollSearch)return Ce(e,t);if(!Q)throw Error(`Device info not available yet; wait for client connection to be established.`);let n=Date.now()+(t.timeoutMs??9e4),r=()=>Ce(e,{...t,timeoutMs:Math.max(1,n-Date.now())}),i;try{return await r()}catch(e){if(!we(e))throw e;i=e}let a=Q.screenHeight,o;if(Q.model===`iPhone Duo`){let e=(await et())?.displays.filter(e=>e.active)??[];if(e.length!==1)throw Error(`Scroll search requires exactly one active Duo display; retry after the fold settles.`);let t=e[0];o=t.id,a=(t.orientation===3||t.orientation===4?t.width:t.height)/t.scale}let s=Math.round(a*.6);for(let[e,t]of[[`down`,3],[`up`,6]])for(let a=0;a<t&&!(Date.now()>=n);a+=1){await rt(e,s,o?{display:o}:void 0),await O(300);try{return await r()}catch(e){if(!we(e))throw e;i=e}}let c=i instanceof Error?i.message:String(i);throw Error(`${c} (after client-side scroll search)`)},Ee=e=>J(`incrementElement`,{selector:e}),De=e=>J(`decrementElement`,{selector:e}),Oe=(e,t)=>{let n=t??void 0;return J(`setElementValue`,{text:e,selector:n,focused:!n||void 0})},ke=(e,t,n)=>{let r=n?.requireFocus!==!1&&void 0;return J(`typeText`,{text:e,pressEnter:t,requireFocus:r})},Ae=(e,t)=>J(`pressKey`,{key:e,modifiers:t}),je=()=>J(`toggleKeyboard`),Me=async(e,t)=>{let n=typeof t==`string`?{mode:t}:t??{},r=typeof t==`object`?t.mode:n.mode;if(n.runtime&&r===`ForegroundIfRunning`)throw Error(`launchApp runtime launches require RelaunchIfRunning so runtime injection is applied.`);let i=Object.keys(n.env??{}).length>0,a=n.runtime?`RelaunchIfRunning`:n.mode??(i?`RelaunchIfRunning`:void 0),{onExit:o,onHang:s}=n,c=o||s?q():void 0;if(c){let e=o?X(c,o):void 0;s&&V(`appHang`,c,Ie(c,s)),V(`appExit`,c,async t=>{U(`appHang`,c),await e?.(t)})}try{await J(`launchApp`,{bundleId:e,mode:a,runtime:n.runtime,env:n.env,execId:c,hangs:s?!0:void 0})}catch(e){throw c&&(U(`appExit`,c),U(`appHang`,c)),e}},X=(e,t)=>async n=>{let r=n,i=[];if(Array.isArray(r.logs))i=r.logs.map(String);else if(Number.isInteger(r.logLineCount)&&(r.logLineCount??0)>0)try{i=fe(await J(`appLogTail`,{bundleId:r.bundleId,lines:r.logLineCount}))}catch(t){F.error(`Failed to fetch app logs for exit execId ${e}:`,t)}let a={bundleId:r.bundleId,reason:r.reason??`exit`,...r.crash?{crash:r.crash}:{}};try{await t(i,a)}catch(t){F.error(`Error in onExit callback for execId ${e}:`,t)}},Ne=async(e,t)=>{let n=q();V(`appExit`,n,X(n,t));try{await J(`watchApp`,{bundleId:e,execId:n})}catch(e){throw U(`appExit`,n),e}return{execId:n,stop:async()=>{U(`appExit`,n),await J(`unwatchApp`,{execId:n})}}},Ie=(e,t)=>async n=>{let{hang:r,bundleId:i}=n;try{await t({...r,bundleId:i})}catch(t){F.error(`Error in onHang callback for execId ${e}:`,t)}},Be=async(e,{onExit:t,onHang:n})=>{let r=q(),i=()=>{U(`monitorExit`,r),U(`appHang`,r)};t&&V(`monitorExit`,r,X(r,t)),n&&V(`appHang`,r,Ie(r,n));try{await J(`monitorApp`,{bundleId:e,execId:r},void 0,1e4)}catch(e){throw i(),e}return{execId:r,stop:async()=>{i(),await J(`unwatchApp`,{execId:r})}}},He=e=>J(`terminateApp`,{bundleId:e}),Ue=(e,t)=>J(`appLogTail`,{bundleId:e,lines:t}),We=e=>{let n=q();return new f(t,{type:`streamAppLog`,id:n,bundleId:e},`streamAppLogTerminate`,n)},Ge=()=>{let e=q();return new f(t,{type:`streamSyslog`,id:e},`streamSyslogTerminate`,e)},Ke=()=>J(`listApps`),qe=e=>J(`openUrl`,{url:e}),Je=(e,t)=>J(`appInstallation`,{url:e,md5:t?.md5,launchMode:t?.launchMode},void 0,t?.timeoutMs??12e4),Ye=async e=>{if(`encryptionKey`in e)throw Error(`Keychain encryption is no longer supported. Omit encryptionKey.`);await J(`exportKeychain`,{url:e.url},void 0,12e4)},Xe=async e=>{if(`encryptionKey`in e)throw Error(`Keychain encryption is no longer supported. Omit encryptionKey.`);return J(`importKeychain`,{url:e.url},void 0,12e4)},Ze=e=>[`portrait`,`pud`,`landscape-left`,`landscape-right`].includes(e)?J(`setDuoOrientation`,{orientation:e}):Promise.reject(RangeError(`Invalid iPhone Duo orientation`)),Qe=(e,t)=>J(`screenshotDisplay`,{display:e,...t}),$e=(e,t,n)=>J(`tapDisplay`,{display:e,x:t,y:n}),et=()=>J(`getFoldState`),tt=e=>!Number.isFinite(e)||e<0||e>180?Promise.reject(RangeError(`Hinge angle must be between 0 and 180 degrees`)):J(`setHingeAngle`,{angleDegrees:e}),nt=e=>J(`setOrientation`,{orientation:e}),rt=(e,t,n)=>J(`scroll`,{direction:e,pixels:t,coordinate:n?.coordinate,momentum:n?.momentum,display:n?.display}),it=(e,t)=>{let n=e.reduce((e,t)=>e+(t.type===`wait`?Math.max(0,t.durationMs):0),0),r=t?.timeoutMs??3e4+n+e.length*2e3;return J(`performActions`,{actions:e,display:t?.display},void 0,r)},at=e=>{if(e?.quality!==void 0&&(!Number.isInteger(e.quality)||e.quality<5||e.quality>10))throw Error(`quality must be one of: 5, 6, 7, 8, 9, 10`);return{...u(e?.persist),quality:e?.quality,display:e?.display,touchIndicators:e?.touchIndicators}},ot=async e=>{await J(`startVideoRecording`,at(e))},st=async e=>{e?.recordingId!==void 0&&Z(e.recordingId);let t=await J(`startVideoRecordingSession`,{...at(e),recordingId:e?.recordingId});return Z(t.recordingId),t.recordingId},ct=async(t,n={})=>{t!==void 0&&Z(t);let r=(await J(`stopVideoRecordingSession`,{recordingId:t,upload:n.presignedUrl?{presignedUrl:n.presignedUrl}:void 0},void 0,18e4)).recordingId??t;if(r===void 0)throw Error(`Runtime did not return the stopped recordingId`);let i=t===void 0&&r===`legacy:recording`;i||Z(r);let a=Le(e.apiUrl,i?void 0:r);return n.localPath&&await m(a,e.token,n.localPath),a},lt=async e=>{if(!e.bundleId)throw Error(`bundleId must be a non-empty string`);await J(`startAppLogCapture`,{bundleId:e.bundleId,...u(e.persist)})},ut=async()=>{await J(`stopAppLogCapture`)},dt=async e=>{await J(`startEventCapture`,{...u(e?.persist)})},ft=async()=>{await J(`stopEventCapture`)},pt=t=>c({url:`${e.apiUrl}/session/applogs/events`,token:e.token,onEntry:t.onLine,onError:t.onError}),mt=t=>c({url:`${e.apiUrl}/session/events/events`,token:e.token,onEntry:t.onEvent,onError:t.onError}),ht=async t=>{await J(`stopVideoRecording`,{upload:t.presignedUrl?{presignedUrl:t.presignedUrl}:void 0});let n=Le(e.apiUrl);return t.localPath&&await m(n,e.token,t.localPath),n},gt=async(e,t)=>{if(!e)throw Error(`path must be a non-empty string`);return J(`playOnMicrophone`,{path:e,once:t?.once})},_t=async()=>{await J(`stopMicrophonePlayback`)},vt=async()=>J(`microphoneStatus`),yt=()=>{!b||b.readyState!==h.default.OPEN||b.send(JSON.stringify({type:`keepAlive`,sessionId:oe}))},bt=async(t,n)=>{let r=await ce(t),i=r.appPath,a=w.join(i,`Info.plist`);if(!(await v.promises.stat(a).catch(()=>null))?.isFile())throw Error(`The folder is not a valid app bundle: missing Info.plist at ${a}`);if(!Q)throw Error(`Device info not available yet; wait for client connection to be established.`);let s=w.resolve(r.cacheIdentityPath),c=`limsync-cache-${w.basename(s)}-${re.createHash(`sha1`).update(s).digest(`hex`).slice(0,8)}`,l=n?.basisCacheDir??w.join(x.tmpdir(),c),u=n?.watch??!0,d=(e,t)=>{switch(e){case`debug`:F.debug(t);break;case`info`:F.info(t);break;case`warn`:F.warn(t);break;case`error`:F.error(t);break;default:F.info(t)}},f={apiUrl:e.apiUrl,token:e.token,udid:c,ignoreFn:await ie(i,{basisCacheDir:l,log:d}),basisCacheDir:l,log:d,install:n?.install??!0,launchMode:n?.launchMode??`ForegroundIfRunning`,watch:!r.isArchive&&u,...n?.onSyncComplete?{onSyncComplete:n.onSyncComplete}:{}},p=await o(i,f);if(!r.isArchive||!r.archivePath||!u)return p;let m=ue({archivePath:r.archivePath,log:d,onExtracted:async()=>{await o(i,f)}});return{...p,stopWatching:async()=>{await m.close()}}},xt=()=>J(`listOpenFiles`,{kind:`unix`}),St=e=>J(`xcrun`,{args:e}),Ct=async()=>{let e=await ve({deviceInfo:Q,listApps:Ke,simctl:Et,syncApp:bt});return M.push(e.close),e.dir},wt=e=>J(`xcodebuild`,{args:e}),Tt=()=>J(`deviceInfo`),Q,Et=(e,t={})=>{let n=q(),r=new Ve(()=>{A.delete(n),t.disconnectOnExit&&(F.debug(`Simctl execution ${n} cancelled, disconnecting due to disconnectOnExit`),$()),F.debug(`Simctl execution ${n} cancelled`)});if(A.set(n,r),t.disconnectOnExit&&(r.once(`exit`,()=>{F.debug(`Simctl execution ${n} finished, disconnecting due to disconnectOnExit`),$()}),r.once(`error`,()=>{F.debug(`Simctl execution ${n} errored, disconnecting due to disconnectOnExit`),$()})),!b||b.readyState!==h.default.OPEN)return process.nextTick(()=>{r._handleError(Error(`WebSocket is not connected or connection is not open.`)),A.delete(n)}),r;let i={type:`simctl`,id:n,args:e,...t.stdin!==void 0&&{stdin:Buffer.from(t.stdin).toString(`base64`)}};return F.debug(`Sending simctl request:`,{...i,stdin:void 0}),b.send(JSON.stringify(i),e=>{e&&(F.error(`Failed to send simctl request:`,e),r._handleError(e),A.delete(n))}),r},Dt=(t,n)=>{let r=new URLSearchParams({name:t});return n?.bundleId&&(r.set(`bundleId`,n.bundleId),n.containerType&&r.set(`containerType`,n.containerType)),`${e.apiUrl}/files?${r.toString()}`},Ot=async(t,n,r)=>{let i=v.createReadStream(t),a=Dt(n,r);try{let n=await g.fetch(a,{method:`PUT`,headers:{"Content-Type":`application/octet-stream`,"Content-Length":v.statSync(t).size.toString(),Authorization:`Bearer ${e.token}`},body:i,duplex:`half`});if(!n.ok){let e=await n.text();throw F.debug(`Upload failed: ${n.status} ${e}`),Error(`Upload failed: ${n.status} ${e}`)}return(await n.json()).path}catch(e){throw F.debug(`Failed to upload file ${t}:`,e),e}},kt=async(t,n)=>{let r=await g.fetch(Dt(t,n),{method:`GET`,headers:{Authorization:`Bearer ${e.token}`}});if(!r.ok){let e=await r.text();throw Error(`Download of '${t}' failed: ${r.status} ${e}`)}return Buffer.from(await r.arrayBuffer())},At=async(t=`.`,n)=>{let r=new URLSearchParams;t&&t!==`.`&&r.set(`path`,t),n?.bundleId&&(r.set(`bundleId`,n.bundleId),n.containerType&&r.set(`containerType`,n.containerType));let i=r.toString(),a=`${e.apiUrl}/files/list${i?`?${i}`:``}`,o=await g.fetch(a,{method:`GET`,headers:{Authorization:`Bearer ${e.token}`}});if(!o.ok){let e=await o.text();throw Error(`Listing of '${t}' failed: ${o.status} ${e}`)}return(await o.json()).entries},jt=async(t,n)=>{let r=await g.fetch(Dt(t,n),{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!r.ok){let e=await r.text();throw Error(`Deletion of '${t}' failed: ${r.status} ${e}`)}},Mt=async(e,t)=>{let n=`limrun-camera-${w.basename(e)}`,r=await Ot(e,n);await J(`cameraControl`,{action:`setSource`,source:`video`,arg:r,loop:t?.loop??!0})},Nt=()=>J(`cameraControl`,{action:`reset`}),Pt=async(t,n)=>{let r=Buffer.isBuffer(n)?n:Buffer.from(n),i=`${e.apiUrl}/payments/storeKitConfigs/${encodeURIComponent(t)}`,a=await g.fetch(i,{method:`PUT`,headers:{"Content-Type":`application/octet-stream`,Authorization:`Bearer ${e.token}`},body:r});if(!a.ok){let e=await a.text();throw Error(`setStoreKitConfig failed: ${a.status} ${e}`)}},Ft=t=>i(`${e.apiUrl}/trusted-cas`,e.token,t),It=async t=>{let n=`${e.apiUrl}/payments/storeKitConfigs/${encodeURIComponent(t)}`,r=await g.fetch(n,{method:`DELETE`,headers:{Authorization:`Bearer ${e.token}`}});if(!r.ok){let e=await r.text();throw Error(`clearStoreKitConfig failed: ${r.status} ${e}`)}},Lt=async(t,n)=>{let r=n?.timeoutSeconds??120,i=`${e.apiUrl}/payments/storeKitConfigs/${encodeURIComponent(t)}/discover`,a=new AbortController,o=setTimeout(()=>a.abort(),(r+10)*1e3);try{let t=await g.fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.token}`},body:JSON.stringify({timeoutSeconds:r}),signal:a.signal});if(!t.ok){let e=await t.text();throw Error(`discoverStoreKitConfig failed: ${t.status} ${e}`)}let n=await t.json();return{itemsFound:n.itemsFound,productsCount:n.productsCount,subscriptionsCount:n.subscriptionsCount,subscriptionGroupsCount:n.subscriptionGroupsCount}}finally{clearTimeout(o)}},Rt=async(t,n)=>{let r={bundleId:t};n?.strategy&&(r.strategy=n.strategy);let i=`${e.apiUrl}/softReset`,a=await g.fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.token}`},body:JSON.stringify(r)});if(!a.ok){let e=await a.text();throw Error(`softReset failed: ${a.status} ${e}`)}let o=await a.json(),s={strategy:o.strategy,bundleId:o.bundleId,durationMs:o.durationMs};return o.itemsCleared!==void 0&&(s.itemsCleared=o.itemsCleared),s},zt=async t=>{a(t.remotePort,`remotePort`,Pe,Fe);let r=t.localPort??t.remotePort;a(r,`localPort`,1,65535);let i=Re(e.apiUrl,t.remotePort);return p(i,e.token,{localHost:t.localHost??`127.0.0.1`,localPort:r,logLevel:t.logLevel??n})},Bt=async t=>te(ne(e.apiUrl),e.token,ee(t,n)),Vt=async()=>l(e.apiUrl,e.token),Ht=async t=>{await d(e.apiUrl,e.token,t)},Ut=async t=>{a(t.localPort,`localPort`,1,65535);let n=await de({localPort:t.localPort,remoteBaseUrl:t.remoteBaseUrl,headers:{authorization:`Bearer ${e.token}`}});return N.push(n.close),n.port},Wt=async t=>{a(t.matchPort,`matchPort`,1,65535);let n=await pe({matchPort:t.matchPort,remoteBaseUrl:t.remoteBaseUrl,headers:{authorization:`Bearer ${e.token}`}});return N.push(n.close),n.port},$=()=>{E=!0,B(),I(`disconnected`),L(`Intentional disconnect`),W(),F.debug(`Intentionally disconnected from WebSocket.`)},Gt=()=>S,Kt=e=>(P.add(e),()=>{P.delete(e)});Y()})}export{O as i,Ne as n,ie as r,He as t};