agent-device 0.12.0 → 0.12.2
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/dist/src/164.js +1 -0
- package/dist/src/556.js +1 -0
- package/dist/src/940.js +1 -0
- package/dist/src/974.js +2 -2
- package/dist/src/artifacts.d.ts +3 -0
- package/dist/src/artifacts.js +1 -0
- package/dist/src/bin.js +63 -63
- package/dist/src/finders.d.ts +79 -0
- package/dist/src/finders.js +1 -0
- package/dist/src/index.js +3 -3
- package/dist/src/install-source.d.ts +40 -0
- package/dist/src/install-source.js +1 -0
- package/dist/src/metro.js +1 -1
- package/dist/src/selectors.d.ts +110 -0
- package/dist/src/selectors.js +1 -0
- package/package.json +17 -1
- package/skills/agent-device/references/verification.md +17 -1
package/dist/src/164.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:fs";import o from"node:os";import t from"node:path";function e(n=process.env){let r=n.ANDROID_SDK_ROOT?.trim(),i=n.ANDROID_HOME?.trim(),d=n.HOME?.trim()||o.homedir();return function(o){let t=new Set,e=[];for(let n of o){let o=n.trim();!o||t.has(o)||(t.add(o),e.push(o))}return e}([r??"",i??"",d?t.join(d,"Android","Sdk"):""])}t.join("cmdline-tools","latest","bin"),t.join("cmdline-tools","tools","bin");export{e as resolveAndroidSdkRoots};
|
package/dist/src/556.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./152.js";function t(e,l,o,u={}){let c=i(o);if(!c)return{matches:[],score:0};let a=0,s=[];for(let t of e){if(u.requireRect&&!t.rect)continue;let e=function(e,t,i){switch(t){case"role":return function(e,t){let r=n(e??"");return r?r===t?2:+!!r.includes(t):0}(e.type,i);case"label":return r(e.label,i);case"value":return r(e.value,i);case"id":return r(e.identifier,i);default:return Math.max(r(e.label,i),r(e.value,i),r(e.identifier,i))}}(t,l,c);if(!(e<=0)){if(e>a){a=e,s.length=0,s.push(t);continue}e===a&&s.push(t)}}return{matches:s,score:a}}function r(e,t){let r=i(e??"");return r?r===t?2:+!!r.includes(t):0}function i(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function n(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}function l(t){let r="any",i=0;["text","label","value","role","id"].includes(t[0])&&(r=t[0],i=1);let n=t[i]??"",l=t.slice(i+1);if(0===l.length)return{locator:r,query:n,action:"click"};let o=l[0].toLowerCase();if("get"===o){let t=l[1]?.toLowerCase();if("text"===t)return{locator:r,query:n,action:"get_text"};if("attrs"===t)return{locator:r,query:n,action:"get_attrs"};throw new e("INVALID_ARGS","find get only supports text or attrs")}if("wait"===o)return{locator:r,query:n,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(l[1])??void 0};if("exists"===o)return{locator:r,query:n,action:"exists"};if("click"===o)return{locator:r,query:n,action:"click"};if("focus"===o)return{locator:r,query:n,action:"focus"};if("fill"===o)return{locator:r,query:n,action:"fill",value:l.slice(1).join(" ")};if("type"===o)return{locator:r,query:n,action:"type",value:l.slice(1).join(" ")};throw new e("INVALID_ARGS",`Unsupported find action: ${l[0]}`)}export{t as findBestMatchesByLocator,n as normalizeRole,i as normalizeText,l as parseFindArgs};
|
package/dist/src/940.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./152.js";import{normalizeText as t}from"./556.js";let r=new Set(["id","role","text","label","value","appname","windowtitle"]),n=new Set(["visible","hidden","editable","selected","enabled","hittable"]),l=new Set([...r,...n]);function i(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Selector expression cannot be empty");let n=function(t){let r=[],n="",l=null;for(let i=0;i<t.length;i+=1){let u=t[i];if(('"'===u||"'"===u)&&!f(t,i)){l=c(l,u),n+=u;continue}if(!l&&"|"===u&&"|"===t[i+1]){let l=n.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);r.push(l),n="",i+=1;continue}n+=u}let i=n.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return r.push(i),r}(r);if(0===n.length)throw new e("INVALID_ARGS","Selector expression cannot be empty");return{raw:r,selectors:n.map(t=>(function(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Selector segment cannot be empty");let n=function(t){let r=[],n="",l=null;for(let e=0;e<t.length;e+=1){let i=t[e];if(('"'===i||"'"===i)&&!f(t,e)){l=c(l,i),n+=i;continue}if(!l&&/\s/.test(i)){n.trim()&&r.push(n.trim()),n="";continue}n+=i}if(l)throw new e("INVALID_ARGS",`Unclosed quote in selector: ${t}`);return n.trim()&&r.push(n.trim()),r}(r);if(0===n.length)throw new e("INVALID_ARGS",`Invalid selector segment: ${t}`);return{raw:r,terms:n.map(a)}})(t))}}function u(e){try{return i(e)}catch{return null}}function o(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let r=t.indexOf("=");if(-1!==r){let e=t.slice(0,r).trim().toLowerCase();return l.has(e)}return l.has(t.toLowerCase())}function a(t){let r=t.trim();if(!r)throw new e("INVALID_ARGS","Empty selector term");let i=r.indexOf("=");if(-1===i){let l=r.toLowerCase();if(!n.has(l))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:l,value:!0}}let u=r.slice(0,i).trim().toLowerCase(),o=r.slice(i+1).trim();if(!l.has(u))throw new e("INVALID_ARGS",`Unknown selector key: ${u}`);if(!o)throw new e("INVALID_ARGS",`Missing selector value for key: ${u}`);if(n.has(u)){let t,r="true"===(t=s(o).toLowerCase())||"false"!==t&&null;if(null===r)throw new e("INVALID_ARGS",`Invalid boolean value for ${u}: ${o}`);return{key:u,value:r}}return{key:u,value:s(o)}}function c(e,t){return e?e===t?null:e:t}function s(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function f(e,t){let r=0;for(let n=t-1;n>=0&&"\\"===e[n];n-=1)r+=1;return r%2==1}function d(e){let t=e.trim().replace(/XCUIElementType/gi,"");t.startsWith("AX")&&(t=t.slice(2));let r=Math.max((t=t.toLowerCase()).lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function h(e,t,r){return t.terms.every(t=>(function(e,t,r){switch(t.key){case"id":return p(e.identifier,String(t.value));case"role":return p(d(e.type??""),String(t.value));case"label":return p(e.label,String(t.value));case"value":return p(e.value,String(t.value));case"text":return p([e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??"",String(t.value));case"appname":return p(e.appName,String(t.value));case"windowtitle":return p(e.windowTitle,String(t.value));case"visible":return m(e)===!!t.value;case"hidden":return!m(e)==!!t.value;case"editable":return w(e,r)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,r))}function m(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function w(e,t){var r;let n;return r=e.type??"",(!(n=d(r))||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n))&&!1!==e.enabled}function p(e,r){return t(e??"")===t(r)}function S(e,t,r){let n=r.requireRect??!1,l=r.requireUnique??!0,i=[];for(let u=0;u<t.selectors.length;u+=1){let o=t.selectors[u],a=function(e,t,r,n){let l=0,i=null,u=null,o=!1;for(let a of e){if(n&&!a.rect||!h(a,t,r))continue;if(l+=1,i??=a,!u){u=a;continue}let e=function(e,t){let r=e.depth??0,n=t.depth??0;if(r!==n)return r>n?1:-1;let l=b(e),i=b(t);return l!==i?l<i?1:-1:0}(a,u);e>0?(u=a,o=!1):0===e&&(o=!0)}return{count:l,firstNode:i,disambiguated:o?null:u}}(e,o,r.platform,n);if(i.push({selector:o.raw,matches:a.count}),0!==a.count&&a.firstNode){if(l&&1!==a.count){if(!r.disambiguateAmbiguous||!a.disambiguated)continue;return{node:a.disambiguated,selector:o,selectorIndex:u,matches:a.count,diagnostics:i}}return{node:a.firstNode,selector:o,selectorIndex:u,matches:a.count,diagnostics:i}}}return null}function v(e,t,r){let n=r.requireRect??!1,l=[];for(let i=0;i<t.selectors.length;i+=1){let u=t.selectors[i],o=function(e,t,r,n){let l=0;for(let i of e)(!n||i.rect)&&h(i,t,r)&&(l+=1);return l}(e,u,r.platform,n);if(l.push({selector:u.raw,matches:o}),o>0)return{selectorIndex:i,selector:u,matches:o,diagnostics:l}}return null}function I(e,t,r){if(0===t.length)return`Selector did not match: ${e.raw}`;let n=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return r.unique??!0?`Selector did not resolve uniquely (${n})`:`Selector did not match (${n})`}function b(e){return e.rect?e.rect.width*e.rect.height:1/0}export{v as findSelectorChainMatch,I as formatSelectorFailure,w as isNodeEditable,o as isSelectorToken,i as parseSelectorChain,S as resolveSelectorChain,m as isNodeVisible,u as tryParseSelectorChain};
|
package/dist/src/974.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import
|
|
2
|
-
`,"utf8")}function k(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function R(r){let n=t.dirname(r.statePath),o=t.dirname(r.logPath);var i=r.statePath;try{e.unlinkSync(i)}catch{}var a=r.logPath;try{e.unlinkSync(a)}catch{}k(n),o!==n&&k(o),t.basename(n)===A&&k(t.dirname(n))}function $(e){return e.includes(S)}function O(e){return N(e.consumerKey)??N(e.profileKey)??null}function C(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function x(e){if(!f(e.pid))return;let t=g(e.pid);if(t&&$(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e.pid,1e3)}}}async function D(r){let n=O(r),o=T(r.projectRoot,r.profileKey),a=v(o.statePath);if(a&&function(e,t){if(!f(e.pid))return!1;if(e.startTime){let t=h(e.pid);if(!t||t!==e.startTime)return!1}let r=g(e.pid);return!!r&&!!$(r)&&e.serverBaseUrl===M(t.serverBaseUrl)&&e.localBaseUrl===M(t.localBaseUrl)&&e.launchUrl===N(t.launchUrl)&&e.tokenHash===U(t.bearerToken)}(a,r)){let e=C(a,n);return e!==a&&I(o.statePath,e),{pid:a.pid,spawned:!1,statePath:o.statePath,logPath:o.logPath}}a&&(await x(a),R(o));let s=function(r,n){let o=function(){let r=i(import.meta.url),n=t.extname(r)||".js",o=t.join(t.dirname(r),`metro-companion${n}`);if(!e.existsSync(o))throw Error(`Metro companion entrypoint not found at ${o}. Rebuild the package to include the companion worker entry.`);return o}(),a=o.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(n),{recursive:!0});let s=e.openSync(n,"a"),l=0;try{let e;l=c(process.execPath,[...a,o,S],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:M(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:M(r.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:T(r.projectRoot,r.profileKey).statePath},r.launchUrl?.trim()?e[_]=r.launchUrl.trim():delete e[_],e),stdio:["ignore",s,s]})}finally{e.closeSync(s)}if(!Number.isInteger(l)||l<=0)throw Error("Failed to start Metro companion process.");return{pid:l,startTime:h(l)??void 0,command:g(l)??void 0,serverBaseUrl:M(r.serverBaseUrl),localBaseUrl:M(r.localBaseUrl),launchUrl:N(r.launchUrl),tokenHash:U(r.bearerToken),consumers:[]}}(r,o.logPath);return I(o.statePath,C(s,n)),{pid:s.pid,spawned:!0,statePath:o.statePath,logPath:o.logPath}}async function B(e){let t=O(e),r=T(e.projectRoot,e.profileKey),n=v(r.statePath);if(!n)return R(r),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(I(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await x(n),R(r),{stopped:!0,statePath:r.statePath})}function j(e){return"string"==typeof e&&e.trim()?M(e.trim()):""}function L(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function H(e,t,r){return s(e,{env:t,cwd:r})}function G(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function K(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function F(e,t){return{platform:t,bundleUrl:P(e,t)}}function J(e,t){return{platform:t,metroHost:L(e?.metro_host),metroPort:e?.metro_port,bundleUrl:L(e?.metro_bundle_url),launchUrl:L(e?.launch_url)}}async function V(e){await new Promise(t=>setTimeout(t,e))}async function q(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function z(e,t){try{let r=await q(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function Z(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e,1e3)){try{process.kill(e,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e,1e3)}}}function W(e,t){let r=Error(e);return r.retryable=t,r}function X(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}async function Y(e){let t;try{var r,n;t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(r=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...r.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw W(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw W(t instanceof Error?t.message:String(t),!0)}let o=function(e,t,r){if(!e)return{};try{let t=JSON.parse(e);if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Expected a JSON object");return t}catch(i){let n=e.slice(0,200),o=i instanceof Error?i.message:String(i);throw W(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${o}. body=${JSON.stringify(n)}`,X(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw W(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(o)}`,X(t.status,o));var i=o;let a=i.data??i;if(!a||"object"!=typeof a||Array.isArray(a))throw W("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:a.enabled,baseUrl:a.base_url,statusUrl:a.status_url??"",bundleUrl:a.bundle_url??"",iosRuntime:J(a.ios_runtime,"ios"),androidRuntime:J(a.android_runtime,"android"),upstream:{bundleUrl:a.upstream.bundle_url??"",host:a.upstream.host??"",port:a.upstream.port??0,statusUrl:a.upstream.status_url??""},probe:{reachable:a.probe.reachable,statusCode:a.probe.status_code,latencyMs:a.probe.latency_ms,detail:a.probe.detail}}}catch(e){throw W(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function Q(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function ee(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await z(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await V(o)}return!1}async function et(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await Y({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await V(o)}throw Error(Q(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function er(r={}){let n=r.env??process.env,o=process.cwd(),i=H(r.projectRoot??o,n,o),s=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!G(n))throw new a("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),l=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new a("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=L(r.listenHost)??"0.0.0.0",d=L(r.statusHost)??"127.0.0.1",p=j(r.publicBaseUrl),f=K(r.startupTimeoutMs,18e4,3e4),h=K(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?H(r.runtimeFilePath,n,o):null,w=H(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new a("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new a("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new a("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(j(r.proxyBaseUrl),L(r.proxyBearerToken)??""),M=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=G(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:G(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return u(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(i,n):{installed:!1},P=`http://${d}:${l}/status`,A=!1,U=!1,N=0;if(g&&await z(P,h))U=!0;else if(A=!0,N=function(r,n,o,i,a,s){let l="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(a),{recursive:!0});let u=e.openSync(a,"a"),m=0;try{m=c(l.command,l.installArgs,{cwd:r,env:s,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(i,s,l,m,w,n).pid,!await ee(P,f,h))throw await Z(N).catch(()=>{}),Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let T=F(p,"ios"),v=F(p,"android"),I=null,k=null;if(E)try{I=await Y({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:T.bundleUrl},timeoutMs:h})}catch(e){k=e instanceof Error?e.message:String(e)}if(E&&(!I||!1===I.probe.reachable)){let e;try{e=(await D({projectRoot:i,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${l}`,launchUrl:L(r.launchUrl),profileKey:L(r.companionProfileKey),consumerKey:L(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(Q(S,e instanceof Error?e.message:String(e),I,k))}try{I=await et({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:T.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:k,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=I?.iosRuntime??T,$=I?.androidRuntime??v,O={projectRoot:i,kind:s,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:A,reused:U,pid:N,logPath:w,statusUrl:P,runtimeFilePath:b,iosRuntime:R,androidRuntime:$,bridge:I};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(O,null,2))),O}export{P as buildBundleUrl,F as buildMetroRuntimeHints,D as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,M as normalizeBaseUrl,er as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,B as stopMetroCompanion,E as stopProcessForTakeover};
|
|
1
|
+
import e from"node:fs";import r from"node:path";import{createHash as t}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdSync as o,runCmdDetached as a}from"./818.js";import{AppError as i}from"./152.js";import{resolveUserPath as s}from"./267.js";let l=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function u(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function c(e){if(!Number.isInteger(e)||e<=0)return null;try{let r=o("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let t=r.stdout.trim();return t.length>0?t:null}catch{return null}}function m(e){if(!Number.isInteger(e)||e<=0)return null;try{let r=o("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==r.exitCode)return null;let t=r.stdout.trim();return t.length>0?t:null}catch{return null}}function d(e,r){let t;if(!u(e))return!1;if(r){let t=c(e);if(!t||t!==r)return!1}let n=m(e);return!!n&&!!(t=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&l.some(e=>e.test(t))}function p(e,r){try{return process.kill(e,r),!0}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return!1;throw r}}async function f(e,r){if(!u(e))return!0;let t=Date.now();for(;Date.now()-t<r;)if(await new Promise(e=>setTimeout(e,50)),!u(e))return!0;return!u(e)}async function h(e,r){!d(e,r.expectedStartTime)||!p(e,"SIGTERM")||await f(e,r.termTimeoutMs)||p(e,"SIGKILL")&&await f(e,r.killTimeoutMs)}let g="--agent-device-run-metro-companion",y="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function b(e){let r=e.length;for(;r>0&&47===e.charCodeAt(r-1);)r-=1;return r===e.length?e:e.slice(0,r)}function w(e,r){let t=new URL(`${b(e)}/index.bundle`);return t.searchParams.set("platform",r),t.searchParams.set("dev","true"),t.searchParams.set("minify","false"),t.toString()}let E="metro-companion";function S(e){return t("sha256").update(e).digest("hex")}function _(e){return e?.trim()?e.trim():void 0}function P(e,t){let n=r.join(e,".agent-device");if(!t)return{statePath:r.join(n,"metro-companion.json"),logPath:r.join(n,"metro-companion.log")};let o=S(t).slice(0,12),a=r.join(n,E);return{statePath:r.join(a,`metro-companion-${o}.json`),logPath:r.join(a,`metro-companion-${o}.log`)}}function U(r){try{let t=JSON.parse(e.readFileSync(r,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let n=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:_("string"==typeof t.launchUrl?t.launchUrl:void 0),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function M(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
|
|
2
|
+
`,"utf8")}function N(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function k(t){let n=r.dirname(t.statePath),o=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var i=t.logPath;try{e.unlinkSync(i)}catch{}N(n),o!==n&&N(o),r.basename(n)===E&&N(r.dirname(n))}function A(e){return e.includes(g)}function T(e){return _(e.consumerKey)??_(e.profileKey)??null}function v(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function R(e){if(!u(e.pid))return;let r=m(e.pid);if(r&&A(r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await f(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await f(e.pid,1e3)}}}async function I(t){let o=T(t),i=P(t.projectRoot,t.profileKey),s=U(i.statePath);if(s&&function(e,r){if(!u(e.pid))return!1;if(e.startTime){let r=c(e.pid);if(!r||r!==e.startTime)return!1}let t=m(e.pid);return!!t&&!!A(t)&&e.serverBaseUrl===b(r.serverBaseUrl)&&e.localBaseUrl===b(r.localBaseUrl)&&e.launchUrl===_(r.launchUrl)&&e.tokenHash===S(r.bearerToken)}(s,t)){let e=v(s,o);return e!==s&&M(i.statePath,e),{pid:s.pid,spawned:!1,statePath:i.statePath,logPath:i.logPath}}s&&(await R(s),k(i));let l=function(t,o){let i=function(){let t=n(import.meta.url),o=r.extname(t)||".js",a=r.join(r.dirname(t),`metro-companion${o}`);if(!e.existsSync(a))throw Error(`Metro companion entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(),s=i.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(o),{recursive:!0});let l=e.openSync(o,"a"),u=0;try{let e;u=a(process.execPath,[...s,i,g],{env:(e={...t.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:b(t.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:t.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:b(t.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:P(t.projectRoot,t.profileKey).statePath},t.launchUrl?.trim()?e[y]=t.launchUrl.trim():delete e[y],e),stdio:["ignore",l,l]})}finally{e.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro companion process.");return{pid:u,startTime:c(u)??void 0,command:m(u)??void 0,serverBaseUrl:b(t.serverBaseUrl),localBaseUrl:b(t.localBaseUrl),launchUrl:_(t.launchUrl),tokenHash:S(t.bearerToken),consumers:[]}}(t,i.logPath);return M(i.statePath,v(l,o)),{pid:l.pid,spawned:!0,statePath:i.statePath,logPath:i.logPath}}async function C(e){let r=T(e),t=P(e.projectRoot,e.profileKey),n=U(t.statePath);if(!n)return k(t),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(M(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await R(n),k(t),{stopped:!0,statePath:t.statePath})}function $(e){return"string"==typeof e&&e.trim()?b(e.trim()):""}function x(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function O(e,r,t){return s(e,{env:r,cwd:t})}function j(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function B(e,r,t){if(null==e||""===e)return r;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,t):r}function D(e,r){return{platform:r,bundleUrl:w(e,r)}}function K(e,r){return{platform:r,metroHost:x(e?.metro_host),metroPort:e?.metro_port,bundleUrl:x(e?.metro_bundle_url),launchUrl:x(e?.launch_url)}}async function L(e){await new Promise(r=>setTimeout(r,e))}async function H(e,r,t={}){try{let n=await fetch(e,{headers:t,signal:AbortSignal.timeout(r)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Error(`Timed out fetching ${e} after ${r}ms`);throw t}}async function G(e,r){try{let t=await H(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function F(e){if(Number.isInteger(e)&&!(e<=0)){try{process.kill(e,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await f(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await f(e,1e3)}}}function J(e,r){let t=Error(e);return t.retryable=r,t}function V(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}async function q(e){let r;try{var t,n;r=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,n=e.bearerToken,{Authorization:`Bearer ${n}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw J(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw J(r instanceof Error?r.message:String(r),!0)}let o=function(e,r,t){if(!e)return{};try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw Error("Expected a JSON object");return r}catch(a){let n=e.slice(0,200),o=a instanceof Error?a.message:String(a);throw J(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,V(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw J(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,V(r.status,o));var a=o;let i=a.data??a;if(!i||"object"!=typeof i||Array.isArray(i))throw J("/api/metro/bridge returned malformed descriptor: Expected a JSON object.",!1);try{return{enabled:i.enabled,baseUrl:i.base_url,statusUrl:i.status_url??"",bundleUrl:i.bundle_url??"",iosRuntime:K(i.ios_runtime,"ios"),androidRuntime:K(i.android_runtime,"android"),upstream:{bundleUrl:i.upstream.bundle_url??"",host:i.upstream.host??"",port:i.upstream.port??0,statusUrl:i.upstream.status_url??""},probe:{reachable:i.probe.reachable,statusCode:i.probe.status_code,latencyMs:i.probe.latency_ms,detail:i.probe.detail}}}catch(e){throw J(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function z(e,r,t,n,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&a.push(`bridgeError=${r}`),t?.probe.reachable===!1&&a.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&a.push(`initialBridgeError=${n}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function W(e,r,t){let n=Date.now()+r;for(;Date.now()<n;){let r=Math.min(t,Math.max(n-Date.now(),1));if(await G(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await L(o)}return!1}async function X(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await q({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==r.probe.reachable)return r;t=r,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await L(o)}throw Error(z(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function Y(t={}){let n=t.env??process.env,s=process.cwd(),l=O(t.projectRoot??s,n,s),u=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!j(n))throw new i("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(t);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(l,t.kind??"auto"),c=function(e){if(null==e||""===e)return 8081;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new i("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(t.metroPort??8081),m=x(t.listenHost)??"0.0.0.0",d=x(t.statusHost)??"127.0.0.1",p=$(t.publicBaseUrl),f=B(t.startupTimeoutMs,18e4,3e4),h=B(t.probeTimeoutMs,1e4,1e3),g=t.reuseExisting??!0,y=t.installDependenciesIfNeeded??!0,b=t.runtimeFilePath?O(t.runtimeFilePath,n,s):null,w=O(t.logPath??r.join(l,".agent-device","metro.log"),n,s);if(!p)throw new i("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,r){if(e&&!r)throw new i("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&r)throw new i("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}($(t.proxyBaseUrl),x(t.proxyBearerToken)??""),P=y?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let a=j(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:j(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return o(a.command,a.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:a.command}}(l,n):{installed:!1},U=`http://${d}:${c}/status`,M=!1,N=!1,k=0;if(g&&await G(U,h))N=!0;else if(M=!0,k=function(t,n,o,i,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(r.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),m=0;try{m=a(u.command,u.installArgs,{cwd:t,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(l,u,c,m,w,n).pid,!await W(U,f,h))throw await F(k).catch(()=>{}),Error(`Metro did not become ready at ${U} within ${f}ms. Check ${w}.`);let A=D(p,"ios"),T=D(p,"android"),v=null,R=null;if(E)try{v=await q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:A.bundleUrl},timeoutMs:h})}catch(e){R=e instanceof Error?e.message:String(e)}if(E&&(!v||!1===v.probe.reachable)){let e;try{e=(await I({projectRoot:l,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${c}`,launchUrl:x(t.launchUrl),profileKey:x(t.companionProfileKey),consumerKey:x(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(z(S,e instanceof Error?e.message:String(e),v,R))}try{v=await X({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:A.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:R,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let C=v?.iosRuntime??A,K=v?.androidRuntime??T,L={projectRoot:l,kind:u,dependenciesInstalled:P.installed,packageManager:P.packageManager??null,started:M,reused:N,pid:k,logPath:w,statusUrl:U,runtimeFilePath:b,iosRuntime:C,androidRuntime:K,bridge:v};return b&&(e.mkdirSync(r.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(L,null,2))),L}export{w as buildBundleUrl,D as buildMetroRuntimeHints,I as ensureMetroCompanion,d as isAgentDeviceDaemonProcess,b as normalizeBaseUrl,Y as prepareMetroRuntime,C as stopMetroCompanion,h as stopProcessForTakeover};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let t;import e from"node:fs/promises";import r from"node:path";import{TextDecoder as n}from"node:util";import{isExecutablePath as a,runCmd as i}from"./818.js";import{resolveAndroidSdkRoots as f}from"./164.js";let o=new n("utf-16le");async function u(t){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var e;let n=await l(t,r);if(!n)continue;let a=(e=n).subarray(0,Math.min(e.length,128)).toString("utf8").trimStart().startsWith("<")?function(t){let e=t.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return e?.[1]}(e.toString("utf8")):function(t){let e;if(!(t.length<8)&&3===t.readUInt16LE(0))for(let r=t.readUInt16LE(2);r+8<=t.length;){let n=t.readUInt16LE(r),a=t.readUInt16LE(r+2),i=t.readUInt32LE(r+4);if(i<=0||r+i>t.length)break;if(1===n)e=function(t){if(t.length<28)return[];let e=t.readUInt32LE(8),r=t.readUInt32LE(16),n=t.readUInt32LE(20),a=(256&r)!=0,i=[];for(let r=0;r<e;r+=1){let e=28+4*r;if(e+4>t.length)break;let f=n+t.readUInt32LE(e);i.push(a?function(t,e){let[,r]=d(t,e),[n,a]=d(t,e+r),i=e+r+a;return t.subarray(i,i+n).toString("utf8")}(t,f):function(t,e){let[r,n]=function(t,e){let r=t.readUInt16LE(e);return(32768&r)==0?[r,2]:[(32767&r)<<16|t.readUInt16LE(e+2),4]}(t,e),a=e+n;return o.decode(t.subarray(a,a+2*r))}(t,f))}return i}(t.subarray(r,r+i));else if(258===n&&e){let n=function(t,e,r,n){if(r<36||e+r>t.length||"manifest"!==n[t.readUInt32LE(e+20)])return;let a=t.readUInt16LE(e+24),i=t.readUInt16LE(e+26),f=t.readUInt16LE(e+28),o=e+a;for(let e=0;e<f;e+=1){let r=o+e*i;if(r+20>t.length)break;if("package"!==n[t.readUInt32LE(r+4)])continue;let a=t.readUInt32LE(r+8);if(0xffffffff!==a)return n[a];let f=t.readUInt8(r+15),u=t.readUInt32LE(r+16);if(3===f)return n[u];break}}(t,r,a,e);if(n)return n}r+=i}}(e);if(a)return a}return await c(t)}async function l(t,e){try{let r=await i("unzip",["-p",t,e],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function d(t,e){let r=t.readUInt8(e);return(128&r)==0?[r,1]:[(127&r)<<8|t.readUInt8(e+1),2]}async function c(t){let e=await s();if(!e)return;let r=await i(e,["dump","badging",t],{allowFailure:!0});if(0!==r.exitCode)return;let n=r.stdout.match(/package:\s+name='([^']+)'/);return n?.[1]}async function s(){if(void 0!==t)return t??void 0;try{for(let n of f()){let i=r.join(n,"build-tools");try{for(let n of(await e.readdir(i)).sort((t,e)=>e.localeCompare(t,void 0,{numeric:!0}))){let e=r.join(i,n,"aapt");if(r.isAbsolute(e)&&await a(e))return t=e,e}}catch{}}}catch{}t=null}export{u as resolveAndroidArchivePackageName};
|