agent-device 0.11.15 → 0.12.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/README.md +2 -2
- package/dist/src/152.js +1 -0
- package/dist/src/155.js +38 -0
- package/dist/src/267.js +1 -0
- package/dist/src/57.js +1 -0
- package/dist/src/818.js +1 -3
- package/dist/src/924.js +1 -1
- package/dist/src/974.js +2 -2
- package/dist/src/bin.js +36 -37
- package/dist/src/contracts.d.ts +59 -0
- package/dist/src/contracts.js +1 -1
- package/dist/src/daemon.js +15 -18
- package/dist/src/index.d.ts +15 -172
- package/dist/src/index.js +3 -2
- package/dist/src/metro.d.ts +6 -0
- package/dist/src/metro.js +1 -1
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +1 -1
- package/skills/agent-device/references/exploration.md +19 -5
- package/skills/agent-device/references/macos-desktop.md +1 -0
- package/dist/src/760.js +0 -33
- package/dist/src/957.js +0 -2
package/dist/src/267.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"node:os";import r from"node:path";function o(r){return r?.HOME?.trim()||e.homedir()}function t(e,n={}){return"~"===e?o(n.env):e.startsWith("~/")?r.join(o(n.env),e.slice(2)):e}function n(e,o={}){let s=t(e,o);return r.isAbsolute(s)?s:r.resolve(o.cwd??process.cwd(),s)}export{t as expandUserHomePath,n as resolveUserPath};
|
package/dist/src/57.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(t){return{x:Math.round(t.x+t.width/2),y:Math.round(t.y+t.height/2)}}export{t as centerOfRect};
|
package/dist/src/818.js
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function w(e,t,r){let n=Date.now();try{let o=await t();return h({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw h({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function E(e={}){let t=l.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),s=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(s,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,"-"),d=i.join(s,`${a}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(S(e)));return r.writeFileSync(d,`${u.join("\n")}
|
|
3
|
-
`),t.events=[],d}catch{return null}}function S(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&c.test(i)||f.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let s={};for(let[n,o]of Object.entries(t)){if(c.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class D extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function A(e){return e instanceof D?e:e instanceof Error?new D("UNKNOWN",e.message,void 0,e):new D("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=A(e),n=r.details?S(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),d=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),u=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:u,hint:a,diagnosticId:i,logPath:s,details:d}}let v=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,O=[".com",".exe",".bat",".cmd"];async function y(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),a="",u=r.binaryStdout?Buffer.alloc(0):void 0,l="",c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{r.binaryStdout?u=Buffer.concat([u??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{l+=e}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:l,exitCode:d,stdoutBuffer:u}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:d,processExitError:!0}))})})}async function N(e){let t=C(e,{allowRelativePath:!1});if(!t)return!1;if(i.isAbsolute(t))return F(t);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return O;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:O}();for(let e of r.split(i.delimiter)){let r=e.trim();if(r){for(let e of function(e,t){if("win32"!==process.platform)return[e];let r=e.toLowerCase();return t.some(e=>r.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,n))if(await F(i.join(r,e)))return!0}}return!1}function M(e,t,r={}){let n=L(e),o=u(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:b(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new D("COMMAND_FAILED",`${n} timed out after ${b(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:b(r.timeoutMs)},o.error);if("ENOENT"===i)throw new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},o.error);throw new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},o.error)}let i=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),a="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),d=o.status??1;if(0!==d&&!r.allowFailure)throw new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:d,processExitError:!0});return{stdout:s,stderr:a,exitCode:d,stdoutBuffer:i}}function T(e,t,r={}){let n=d(L(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function _(e,t,r={}){let n=L(e);return new Promise((o,i)=>{let s=d(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(s);let a="",u="",l=r.binaryStdout?Buffer.alloc(0):void 0,c=!1,f=b(r.timeoutMs),p=f?setTimeout(()=>{c=!0,s.kill("SIGKILL")},f):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),s.stderr.on("data",e=>{let t=String(e);u+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{(p&&clearTimeout(p),"ENOENT"===r.code)?i(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):i(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),s.on("close",s=>{p&&clearTimeout(p);let d=s??1;c&&f?i(new D("COMMAND_FAILED",`${n} timed out after ${f}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,timeoutMs:f})):0===d||r.allowFailure?o({stdout:a,stderr:u,exitCode:d,stdoutBuffer:l}):i(new D("COMMAND_FAILED",`${n} exited with code ${d}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:d,processExitError:!0}))})})}function $(e,t,r={}){let n=L(e),o=d(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),i="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",e=>{i+=e}),o.stderr.on("data",e=>{s+=e});let a=new Promise((a,d)=>{o.on("error",r=>{"ENOENT"===r.code?d(new D("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):d(new D("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),o.on("close",o=>{let u=o??1;0===u||r.allowFailure?a({stdout:i,stderr:s,exitCode:u}):d(new D("COMMAND_FAILED",`${n} exited with code ${u}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:u,processExitError:!0}))})});return{child:o,wait:a}}function L(e){let t=C(e,{allowRelativePath:!0});if(!t)throw new D("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return t}function C(e,t){let r=e.trim();return!r||r.includes("\0")?null:i.isAbsolute(r)?r:r.includes("/")||r.includes("\\")?t.allowRelativePath?r:null:v.test(r)?r:null}async function F(e){try{if(!(await a(e)).isFile())return!1;return await s(e,"win32"===process.platform?n.F_OK:n.X_OK),!0}catch{return!1}}function b(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{D as AppError,A as asAppError,p as createRequestId,h as emitDiagnostic,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,I as normalizeError,y as runCmd,$ as runCmdBackground,T as runCmdDetached,_ as runCmdStreaming,M as runCmdSync,N as whichCmd,w as withDiagnosticTimer,m as withDiagnosticsScope};
|
|
1
|
+
import{constants as e}from"node:fs";import{access as t,stat as r}from"node:fs/promises";import n from"node:path";import{spawn as o,spawnSync as i}from"node:child_process";let s=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,a=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function u(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&s.test(i)||a.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let u={};for(let[n,o]of Object.entries(t)){if(s.test(n)){u[n]="[REDACTED]";continue}u[n]=e(o,r,n)}return u}(e,new WeakSet)}class d extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function l(e){return e instanceof d?e:e instanceof Error?new d("UNKNOWN",e.message,void 0,e):new d("UNKNOWN","Unknown error",{err:e})}function c(e,t={}){let r=l(e),n=r.details?u(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"APP_NOT_INSTALLED":return"Run apps to discover the exact installed package or bundle id, or install the app before open.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),d=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),f=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:f,hint:a,diagnosticId:i,logPath:s,details:d}}let f=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,p=[".com",".exe",".bat",".cmd"];async function m(e,t,r={}){let n=D(e);return new Promise((i,s)=>{let a=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1}),u="",l=r.binaryStdout?Buffer.alloc(0):void 0,c="",f=!1,p=T(r.timeoutMs),m=p?setTimeout(()=>{f=!0,a.kill("SIGKILL")},p):null;r.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==r.stdin&&a.stdin.write(r.stdin),a.stdin.end(),a.stdout.on("data",e=>{r.binaryStdout?l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):u+=e}),a.stderr.on("data",e=>{c+=e}),a.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?s(new d("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):s(new d("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),a.on("close",o=>{m&&clearTimeout(m);let a=o??1;f&&p?s(new d("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:u,stderr:c,exitCode:a,timeoutMs:p})):0===a||r.allowFailure?i({stdout:u,stderr:c,exitCode:a,stdoutBuffer:l}):s(new d("COMMAND_FAILED",`${n} exited with code ${a}`,{cmd:e,args:t,stdout:u,stderr:c,exitCode:a,processExitError:!0}))})})}async function h(e){let t=S(e);if(!t)return!1;if(n.isAbsolute(t))return y(t);let r=process.env.PATH;if(!r)return!1;let o=function(){if("win32"!==process.platform)return[""];let e=process.env.PATHEXT;if(!e)return p;let t=e.split(";").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0);return t.length>0?t:p}();for(let e of r.split(n.delimiter)){let r=e.trim();if(r){for(let e of function(e,t){if("win32"!==process.platform)return[e];let r=e.toLowerCase();return t.some(e=>r.endsWith(e))?[e]:t.map(t=>`${e}${t}`)}(t,o))if(await y(n.join(r,e)))return!0}}return!1}async function w(e,t){let r=I(e,t,"executable");if(r){if(!await y(r))throw new d("TOOL_MISSING",`${t} points to a missing or non-executable file: ${r}`,{envName:t,path:r});return r}}async function E(e,t){let r=I(e,t,"file");if(r){if(!await M(r))throw new d("TOOL_MISSING",`${t} points to a missing or non-file path: ${r}`,{envName:t,path:r});return r}}function A(e,t,r={}){let n=D(e),o=i(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:T(r.timeoutMs),shell:!1});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new d("COMMAND_FAILED",`${n} timed out after ${T(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:T(r.timeoutMs)},o.error);if("ENOENT"===i)throw new d("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},o.error);throw new d("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},o.error)}let s=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,a=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),u="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),l=o.status??1;if(0!==l&&!r.allowFailure)throw new d("COMMAND_FAILED",`${n} exited with code ${l}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:l,processExitError:!0});return{stdout:a,stderr:u,exitCode:l,stdoutBuffer:s}}function g(e,t,r={}){let n=o(D(e),t,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,shell:!1});return n.unref(),n.pid??0}async function O(e,t,r={}){let n=D(e);return new Promise((i,s)=>{let a=o(n,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,shell:!1});r.onSpawn?.(a);let u="",l="",c=r.binaryStdout?Buffer.alloc(0):void 0,f=!1,p=T(r.timeoutMs),m=p?setTimeout(()=>{f=!0,a.kill("SIGKILL")},p):null;r.binaryStdout||a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),void 0!==r.stdin&&a.stdin.write(r.stdin),a.stdin.end(),a.stdout.on("data",e=>{if(r.binaryStdout){c=Buffer.concat([c??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);u+=t,r.onStdoutChunk?.(t)}),a.stderr.on("data",e=>{let t=String(e);l+=t,r.onStderrChunk?.(t)}),a.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?s(new d("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):s(new d("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),a.on("close",o=>{m&&clearTimeout(m);let a=o??1;f&&p?s(new d("COMMAND_FAILED",`${n} timed out after ${p}ms`,{cmd:e,args:t,stdout:u,stderr:l,exitCode:a,timeoutMs:p})):0===a||r.allowFailure?i({stdout:u,stderr:l,exitCode:a,stdoutBuffer:c}):s(new d("COMMAND_FAILED",`${n} exited with code ${a}`,{cmd:e,args:t,stdout:u,stderr:l,exitCode:a,processExitError:!0}))})})}function N(e,t,r={}){let n=D(e),i=o(n,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached,shell:!1}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",e=>{s+=e}),i.stderr.on("data",e=>{a+=e});let u=new Promise((o,u)=>{i.on("error",r=>{"ENOENT"===r.code?u(new d("TOOL_MISSING",`${n} not found in PATH`,{cmd:e},r)):u(new d("COMMAND_FAILED",`Failed to run ${n}`,{cmd:e,args:t},r))}),i.on("close",i=>{let l=i??1;0===l||r.allowFailure?o({stdout:s,stderr:a,exitCode:l}):u(new d("COMMAND_FAILED",`${n} exited with code ${l}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:l,processExitError:!0}))})});return{child:i,wait:u}}function D(e){let t=S(e);if(!t)throw new d("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:"Use a bare command name from PATH or an absolute executable path."});return t}function I(e,t,r){let o=e?.trim();if(o){if(!n.isAbsolute(o)||o.includes("\0"))throw new d("INVALID_ARGS",`${t} must be an absolute ${r} path, not ${JSON.stringify(e)}`,{envName:t,path:e});return o}}function S(e){let t=e.trim();return!t||t.includes("\0")?null:n.isAbsolute(t)?t:t.includes("/")||t.includes("\\")?null:f.test(t)?t:null}async function y(r){try{if(!await M(r))return!1;return await t(r,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}async function M(e){try{return(await r(e)).isFile()}catch{return!1}}function T(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}export{d as AppError,l as asAppError,y as isExecutablePath,c as normalizeError,u as redactDiagnosticData,w as resolveExecutableOverridePath,E as resolveFileOverridePath,m as runCmd,N as runCmdBackground,g as runCmdDetached,O as runCmdStreaming,A as runCmdSync,h as whichCmd};
|
package/dist/src/924.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:fs";import t from"node:path";import{
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{AppError as r}from"./152.js";import{resolveUserPath as n}from"./267.js";let o=new Set(["1","true","yes","on"]),i=new Set(["0","false","no","off"]);function a(e,t,n,o){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>a({...e,multiple:!1},t,n,o));if("boolean"===e.type){var i=t,l=n,m=o;if("boolean"==typeof i)return i;if("string"==typeof i){let e=s(i);if(void 0!==e)return e}throw new r("INVALID_ARGS",`Invalid value for "${m}" in ${l}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==s(t))return s(t);if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var u=e,f=t,p=n,y=o;let i=u.setValue;if(f===i)return i;if("string"==typeof f){let e=f.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===f)return i;if(!1!==f)throw new r("INVALID_ARGS",`Invalid value for "${y}" in ${p}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let g="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(g)||!Number.isInteger(g))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected integer.`);if("number"==typeof e.min&&g<e.min)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be >= ${e.min}.`);if("number"==typeof e.max&&g>e.max)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be <= ${e.max}.`);return g}function s(e){let t=e.trim().toLowerCase();return!!o.has(t)||!i.has(t)&&void 0}let l=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,legacyEnvNames:["IOS_SIMULATOR_DEVICE_SET"]},{key:"androidDeviceAllowlist",type:"string",legacyEnvNames:["ANDROID_DEVICE_ALLOWLIST"]},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string",legacyEnvNames:["AGENT_DEVICE_PROXY_TOKEN"]},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],m=["session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],u=new Map(l.map(e=>[e.key,e]));function f(e){let t=e.env??process.env;return n(e.configPath,{cwd:e.cwd,env:t})}function p(o){let i=function(o){let i,s,l=o.env??process.env,m=f(o);if(!e.existsSync(m))throw new r("INVALID_ARGS",`Remote config file not found: ${m}`);try{i=e.readFileSync(m,"utf8")}catch(e){throw new r("INVALID_ARGS",`Failed to read remote config file: ${m}`,{cause:e instanceof Error?e.message:String(e)})}try{s=JSON.parse(i)}catch(e){throw new r("INVALID_ARGS",`Invalid JSON in remote config file: ${m}`,{cause:e instanceof Error?e.message:String(e)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new r("INVALID_ARGS",`Remote config file must contain a JSON object: ${m}`);let p={},y=s,g=t.dirname(m);for(let[e,t]of Object.entries(y)){let o=u.get(e);if(!o)throw new r("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${m}.`);let i=a(o,t,`remote config file ${m}`,e);p[o.key]="string"==typeof i&&"path"in o&&o.path?n(i,{cwd:g,env:l}):i}return{resolvedPath:m,profile:p}}(o);return{resolvedPath:i.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of l){let n=r[e.key];void 0!==n&&(t[e.key]=n)}return t}(function(e=process.env){let t={};for(let r of l){let n=(function(e){let t=u.get(e);return[`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`,...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);n&&(t[r.key]=a(r,n.value,`environment variable ${n.name}`,n.name))}return t}(o.env),i.profile)}}export{l as REMOTE_CONFIG_FIELD_SPECS,m as REMOTE_OPEN_PROFILE_KEYS,f as resolveRemoteConfigPath,p as resolveRemoteConfigProfile};
|
package/dist/src/974.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import"node:fs/promises";import t from"node:path";import{spawn as r,spawnSync as n}from"node:child_process";import{createHash as o}from"node:crypto";import{fileURLToPath as i}from"node:url";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)===U&&k(t.dirname(n))}function $(e){return e.includes(S)}function O(e){return v(e.consumerKey)??v(e.profileKey)??null}function C(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function D(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 x(r){let n=O(r),o=N(r.projectRoot,r.profileKey),a=T(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===v(t.launchUrl)&&e.tokenHash===A(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 D(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:N(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:v(r.launchUrl),tokenHash:A(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=N(e.projectRoot,e.profileKey),n=T(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 D(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 F(e,t,r){return a(e,{env:t,cwd:r})}function G(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function H(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 K(e,t){return{platform:t,bundleUrl:P(e,t)}}function V(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 J(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}}function Z(e,t){let r=Error(e);return r.retryable=t,r}async function W(e){var t,r,n,o;let i;try{i=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"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(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Z(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw Z(t instanceof Error?t.message:String(t),!0)}let a=await i.text(),s=a?JSON.parse(a):{};if(!i.ok)throw Z(`/api/metro/bridge failed (${i.status}): ${JSON.stringify(s)}`,(n=i.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:V(o.ios_runtime,"ios"),androidRuntime:V(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function X(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 Y(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 J(o)}return!1}async function Q(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await W({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 J(o)}throw Error(X(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function ee(r={}){let n=r.env??process.env,o=process.cwd(),i=F(r.projectRoot??o,n,o),a=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!G(n))throw new s("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 s("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=H(r.startupTimeoutMs,18e4,3e4),h=H(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?F(r.runtimeFilePath,n,o):null,w=F(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new s("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new s("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 s("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`,U=!1,A=!1,v=0;if(g&&await z(P,h))A=!0;else if(U=!0,v=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,a,l,m,w,n).pid,!await Y(P,f,h))throw Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let N=K(p,"ios"),T=K(p,"android"),I=null,k=null;if(E)try{I=await W({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.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 x({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(X(S,e instanceof Error?e.message:String(e),I,k))}try{I=await Q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:k,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=I?.iosRuntime??N,$=I?.androidRuntime??T,O={projectRoot:i,kind:a,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:U,reused:A,pid:v,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,K as buildMetroRuntimeHints,x as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,M as normalizeBaseUrl,ee as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,B as stopMetroCompanion,E as stopProcessForTakeover};
|
|
1
|
+
import e from"node:fs";import"node:fs/promises";import t from"node:path";import{spawn as r,spawnSync as n}from"node:child_process";import{createHash as o}from"node:crypto";import{fileURLToPath as i}from"node:url";import{AppError as a}from"./152.js";import{resolveUserPath as s}from"./267.js";let l=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/;function u(e,t,r={}){let o=m(e),i=n(o,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:d(r.timeoutMs),shell:!1});if(i.error){let n=i.error.code;if("ETIMEDOUT"===n)throw new a("COMMAND_FAILED",`${o} timed out after ${d(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:d(r.timeoutMs)},i.error);if("ENOENT"===n)throw new a("TOOL_MISSING",`${o} not found in PATH`,{cmd:e},i.error);throw new a("COMMAND_FAILED",`Failed to run ${o}`,{cmd:e,args:t},i.error)}let s=r.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,l=r.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),c="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),p=i.status??1;if(0!==p&&!r.allowFailure)throw new a("COMMAND_FAILED",`${o} exited with code ${p}`,{cmd:e,args:t,stdout:l,stderr:c,exitCode:p,processExitError:!0});return{stdout:l,stderr:c,exitCode:p,stdoutBuffer:s}}function c(e,t,n={}){let o=r(m(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??"ignore",detached:!0,shell:!1});return o.unref(),o.pid??0}function m(e){let r,n=!(r=e.trim())||r.includes("\0")?null:t.isAbsolute(r)?r:r.includes("/")||r.includes("\\")?null:l.test(r)?r:null;if(!n)throw new a("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e,hint:"Use a bare command name from PATH or an absolute executable path."});return n}function d(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let p=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function f(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function h(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function g(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function y(e,t){let r;if(!f(e))return!1;if(t){let r=h(e);if(!r||r!==t)return!1}let n=g(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&p.some(e=>e.test(r))}function b(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function w(e,t){if(!f(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!f(e))return!0;return!f(e)}async function E(e,t){!y(e,t.expectedStartTime)||!b(e,"SIGTERM")||await w(e,t.termTimeoutMs)||b(e,"SIGKILL")&&await w(e,t.killTimeoutMs)}let S="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function M(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)}function P(e,t){let r=new URL(`${M(e)}/index.bundle`);return r.searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString()}let A="metro-companion";function U(e){return o("sha256").update(e).digest("hex")}function N(e){return e?.trim()?e.trim():void 0}function T(e,r){let n=t.join(e,".agent-device");if(!r)return{statePath:t.join(n,"metro-companion.json"),logPath:t.join(n,"metro-companion.log")};let o=U(r).slice(0,12),i=t.join(n,A);return{statePath:t.join(i,`metro-companion-${o}.json`),logPath:t.join(i,`metro-companion-${o}.log`)}}function v(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:N("string"==typeof r.launchUrl?r.launchUrl:void 0),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function I(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
|
|
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};
|