agent-device 0.13.1 → 0.13.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/1974.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:fs";import t from"node:path";import{createHash as r}from"node:crypto";import{fileURLToPath as n}from"node:url";import{runCmdDetached as o,runCmdSync as i}from"./9818.js";import{readProcessCommand as a,waitForProcessExit as s,resolveRuntimeTransportHints as l,isProcessAlive as u,readProcessStartTime as c}from"./8656.js";import{normalizeBaseUrl as d,ENV_REGISTER_PATH as m,ENV_UNREGISTER_PATH as p,ENV_LOCAL_BASE_URL as h,ENV_STATE_PATH as f,ENV_SESSION as g,ENV_BEARER_TOKEN as y,METRO_COMPANION_RUN_ARG as b,buildBundleUrl as S,ENV_SERVER_BASE_URL as w,ENV_LAUNCH_URL as P,ENV_SCOPE_TENANT_ID as v,ENV_SCOPE_RUN_ID as U,ENV_SCOPE_LEASE_ID as _,REACT_DEVTOOLS_COMPANION_RUN_ARG as I,ENV_DEVICE_PORT as E}from"./320.js";import{AppError as k}from"./9152.js";import{resolveUserPath as M}from"./3267.js";import{sleep as N}from"./4829.js";let A="metro-companion";function R(e){return r("sha256").update(e).digest("hex")}function $(e){return e?.trim()?e.trim():void 0}function x(e,r,n="metro",o){let i="react-devtools"===n?{stateFile:"react-devtools-companion.json",logFile:"react-devtools-companion.log",stateDir:"react-devtools-companion"}:{stateFile:"metro-companion.json",logFile:"metro-companion.log",stateDir:A},a=o??t.join(e,".agent-device");if(!r)return{statePath:t.join(a,i.stateFile),logPath:t.join(a,i.logFile)};let s=R(r).slice(0,12),l=t.join(a,i.stateDir);return{statePath:t.join(l,`${i.stateDir}-${s}.json`),logPath:t.join(l,`${i.stateDir}-${s}.log`)}}function j(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:$("string"==typeof r.launchUrl?r.launchUrl:void 0),registerPath:$("string"==typeof r.registerPath?r.registerPath:void 0),unregisterPath:$("string"==typeof r.unregisterPath?r.unregisterPath:void 0),devicePort:Number.isInteger(r.devicePort)?Number(r.devicePort):void 0,session:$("string"==typeof r.session?r.session:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(r.bridgeScope),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function D(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
2
- `,"utf8")}function T(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function C(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{}T(n),o!==n&&T(o),t.basename(n)===A&&T(t.dirname(n))}function B(e){return e.includes(b)||e.includes(I)}function K(e){return $(e.consumerKey)??$(e.profileKey)??null}function H(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function O(e){if(!u(e.pid))return;let t=a(e.pid);if(t&&B(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await s(e.pid,1e3)}}}async function F(r){let i=K(r),s=x(r.projectRoot,r.profileKey,r.kind,r.stateDir),l=j(s.statePath);if(l&&function(e,t){var r,n;if(!u(e.pid))return!1;if(e.startTime){let t=c(e.pid);if(!t||t!==e.startTime)return!1}let o=a(e.pid);return!!o&&!!B(o)&&!!e.bridgeScope&&e.serverBaseUrl===d(t.serverBaseUrl)&&e.localBaseUrl===d(t.localBaseUrl)&&e.launchUrl===$(t.launchUrl)&&e.registerPath===$(t.registerPath)&&e.unregisterPath===$(t.unregisterPath)&&e.devicePort===t.devicePort&&e.session===$(t.session)&&(r=e.bridgeScope,n=t.bridgeScope,r.tenantId===n.tenantId&&r.runId===n.runId&&r.leaseId===n.leaseId)&&e.tokenHash===R(t.bearerToken)}(l,r)){let e=H(l,i);return e!==l&&D(s.statePath,e),{pid:l.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}l&&(await O(l),C(s));let S=function(r,i){let s=function(){let r=n(import.meta.url),o=t.extname(r)||".js",i=t.join(t.dirname(r),`metro-companion${o}`);if(!e.existsSync(i))throw Error(`Metro companion entrypoint not found at ${i}. Rebuild the package to include the companion worker entry.`);return i}(),l=s.endsWith(".ts")?["--experimental-strip-types"]:[],u="react-devtools"===r.kind?I:b;e.mkdirSync(t.dirname(i),{recursive:!0});let S=e.openSync(i,"a"),k=0;try{let e;k=o(process.execPath,[...l,s,u],{env:((e={...r.env??process.env,[w]:d(r.serverBaseUrl),[y]:r.bearerToken,[h]:d(r.localBaseUrl),[f]:x(r.projectRoot,r.profileKey,r.kind,r.stateDir).statePath})[v]=r.bridgeScope.tenantId,e[U]=r.bridgeScope.runId,e[_]=r.bridgeScope.leaseId,r.launchUrl?.trim()?e[P]=r.launchUrl.trim():delete e[P],r.registerPath?.trim()?e[m]=r.registerPath.trim():delete e[m],r.unregisterPath?.trim()?e[p]=r.unregisterPath.trim():delete e[p],void 0!==r.devicePort?e[E]=String(r.devicePort):delete e[E],r.session?.trim()?e[g]=r.session.trim():delete e[g],e),stdio:["ignore",S,S]})}finally{e.closeSync(S)}if(!Number.isInteger(k)||k<=0)throw Error("Failed to start Metro companion process.");return{pid:k,startTime:c(k)??void 0,command:a(k)??void 0,serverBaseUrl:d(r.serverBaseUrl),localBaseUrl:d(r.localBaseUrl),launchUrl:$(r.launchUrl),registerPath:$(r.registerPath),unregisterPath:$(r.unregisterPath),devicePort:r.devicePort,session:$(r.session),bridgeScope:r.bridgeScope,tokenHash:R(r.bearerToken),consumers:[]}}(r,s.logPath);return D(s.statePath,H(S,i)),{pid:S.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function L(e){let t=K(e),r=x(e.projectRoot,e.profileKey,e.kind,e.stateDir),n=j(r.statePath);if(!n)return C(r),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(D(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await O(n),C(r),{stopped:!0,statePath:r.statePath})}function G(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function J(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function V(e,t,r){return M(e,{env:t,cwd:r})}function q(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function W(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 z(e,t){if(null==e||""===e)return t;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new k("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}function X(e,t){return{platform:t,bundleUrl:S(e,t)}}function Y(e,t){return{platform:t,metroHost:J(e?.metro_host),metroPort:e?.metro_port,bundleUrl:J(e?.metro_bundle_url),launchUrl:J(e?.launch_url)}}async function Q(e){await N(e)}async function Z(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 ee(e,t){try{let r=await Z(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function et(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 s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await s(e,1e3)}}}function er(e,t){let r=Error(e);return r.retryable=t,r}function en(e,t){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(t).includes("Metro companion is not connected"))}function eo(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function ei(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({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw er(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw er(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 er(`/api/metro/bridge returned invalid JSON (${t}) from ${r}: ${o}. body=${JSON.stringify(n)}`,en(t,e))}}(await t.text(),t.status,e.baseUrl);if(!t.ok)throw er(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(o)}`,en(t.status,o));var i=o;let a=i.data??i;if(!a||"object"!=typeof a||Array.isArray(a))throw er("/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:Y(a.ios_runtime,"ios"),androidRuntime:Y(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 er(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function ea(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 es(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 ee(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await Q(o)}return!1}async function el(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await ei({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,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),!eo(e))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await Q(o)}throw Error(ea(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function eu(r={}){let n=r.env??process.env,a=process.cwd(),s=V(r.projectRoot??a,n,a),l=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!q(n))throw new k("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"}(s,r.kind??"auto"),u=z(r.metroPort??8081,8081),c=J(r.listenHost)??"0.0.0.0",d=J(r.statusHost)??"127.0.0.1",m=G(r.publicBaseUrl),p=W(r.startupTimeoutMs,18e4,3e4),h=W(r.probeTimeoutMs,1e4,1e3),f=r.reuseExisting??!0,g=r.installDependenciesIfNeeded??!0,y=r.runtimeFilePath?V(r.runtimeFilePath,n,a):null,b=V(r.logPath??t.join(s,".agent-device","metro.log"),n,a);if(!m&&!G(r.proxyBaseUrl))throw new k("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:P}=function(e,t){if(e&&!t)throw new k("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 k("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(G(r.proxyBaseUrl),J(r.proxyBearerToken)??""),v=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new k("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(r.bridgeScope):null,U=g?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=q(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:q(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return i(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},_=`http://${d}:${u}/status`,I=!1,E=!1,M=0;if(f&&await ee(_,h))E=!0;else if(I=!0,M=function(r,n,i,a,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(i)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(i)]};e.mkdirSync(t.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=o(u.command,u.installArgs,{cwd:r,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(s,l,u,c,b,n).pid,!await es(_,p,h))throw await et(M).catch(()=>{}),Error(`Metro did not become ready at ${_} within ${p}ms. Check ${b}.`);let N=m?X(m,"ios"):{platform:"ios"},A=m?X(m,"android"):{platform:"android"},R=null,$=null;if(v)try{R=await ei({baseUrl:w,bearerToken:P,scope:v,timeoutMs:h})}catch(e){if(!eo(e))throw e;$=e instanceof Error?e.message:String(e)}if(v&&(!R||!1===R.probe.reachable)){let e;try{e=(await F({projectRoot:s,serverBaseUrl:w,bearerToken:P,bridgeScope:v,localBaseUrl:`http://${d}:${u}`,launchUrl:J(r.launchUrl),profileKey:J(r.companionProfileKey),consumerKey:J(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(ea(w,e instanceof Error?e.message:String(e),R,$))}try{R=await el({baseUrl:w,bearerToken:P,scope:v,probeTimeoutMs:h,startupTimeoutMs:p,initialBridgeError:$,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}v&&function(e,t){if(!t?.iosRuntime.bundleUrl)throw Error(ea(e,"bridge descriptor is missing ios_runtime.metro_bundle_url",t))}(w,R);let x=R?.iosRuntime??N,j=R?.androidRuntime??A,D={projectRoot:s,kind:l,dependenciesInstalled:U.installed,packageManager:U.packageManager??null,started:I,reused:E,pid:M,logPath:b,statusUrl:_,runtimeFilePath:y,iosRuntime:x,androidRuntime:j,bridge:R};return y&&(e.mkdirSync(t.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(D,null,2))),D}async function ec(e={}){let t=W(e.timeoutMs,1e4,1e3),r=function(e){var t;let r,n=J(e.bundleUrl)??e.runtime?.bundleUrl,o=!!J(e.bundleUrl),i=!!J(n),a=l({metroHost:J(e.metroHost)??(o?void 0:J(e.runtime?.metroHost))??(i?void 0:"localhost"),metroPort:void 0!==e.metroPort?z(e.metroPort,8081):o?void 0:e.runtime?.metroPort??(i?void 0:8081),bundleUrl:n});if(!a)throw new k("INVALID_ARGS","Unable to resolve Metro host and port for reload.");return t=function(e){let t=J(e);if(!t)return"/reload";let r=new URL(t).pathname.replace(/\/+$/,"");return r.endsWith("/index.bundle")?`${r.slice(0,-13)}/reload`:"/reload"}(n),(r=new URL(`${a.scheme}://localhost`)).hostname=a.host,r.port=String(a.port),r.pathname=t,r.toString()}(e),n=await Z(r,t);if(!n.ok)throw new k("COMMAND_FAILED",`Metro reload failed (${n.status}).`,{reloadUrl:r,status:n.status,body:n.body,hint:"Verify Metro is running and the target React Native app is connected to this Metro instance."});return{reloaded:!0,reloadUrl:r,status:n.status,body:n.body}}export{X as buildMetroRuntimeHints,F as ensureMetroCompanion,eu as prepareMetroRuntime,ec as reloadMetro,L as stopMetroCompanion};
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{runCmdDetached as o,runCmdSync as i}from"./9818.js";import{readProcessCommand as a,waitForProcessExit as s,resolveRuntimeTransportHints as l,isProcessAlive as u,readProcessStartTime as c}from"./8656.js";import{normalizeBaseUrl as d,ENV_COMPANION_TUNNEL_BEARER_TOKEN as m,ENV_COMPANION_TUNNEL_SERVER_BASE_URL as p,ENV_COMPANION_TUNNEL_STATE_PATH as f,ENV_COMPANION_TUNNEL_LAUNCH_URL as h,ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID as g,ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID as y,ENV_COMPANION_TUNNEL_DEVICE_PORT as b,buildBundleUrl as S,METRO_COMPANION_RUN_ARG as w,ENV_COMPANION_TUNNEL_SESSION as P,ENV_COMPANION_TUNNEL_SCOPE_RUN_ID as v,ENV_COMPANION_TUNNEL_REGISTER_PATH as U,ENV_COMPANION_TUNNEL_LOCAL_BASE_URL as _,ENV_COMPANION_TUNNEL_UNREGISTER_PATH as I}from"./2301.js";import{AppError as E}from"./9152.js";import{resolveUserPath as M}from"./3267.js";import{sleep as k}from"./4829.js";function N(e){return t("sha256").update(e).digest("hex")}function A(e){return e?.trim()?e.trim():void 0}function $(e,t,n,o){let i=o??r.join(e,".agent-device");if(!n)return{statePath:r.join(i,`${t.slug}.json`),logPath:r.join(i,`${t.slug}.log`)};let a=N(n).slice(0,12),s=r.join(i,t.slug);return{statePath:r.join(s,`${t.slug}-${a}.json`),logPath:r.join(s,`${t.slug}-${a}.log`)}}function R(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:A("string"==typeof t.launchUrl?t.launchUrl:void 0),registerPath:A("string"==typeof t.registerPath?t.registerPath:void 0),unregisterPath:A("string"==typeof t.unregisterPath?t.unregisterPath:void 0),devicePort:Number.isInteger(t.devicePort)?Number(t.devicePort):void 0,session:A("string"==typeof t.session?t.session:void 0),bridgeScope:function(e){if(!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.tenantId&&"string"==typeof e.runId&&"string"==typeof e.leaseId)return{tenantId:e.tenantId,runId:e.runId,leaseId:e.leaseId}}(t.bridgeScope),tokenHash:t.tokenHash,consumers:n}}catch{return null}}function x(t,n){e.mkdirSync(r.dirname(t),{recursive:!0}),e.writeFileSync(t,`${JSON.stringify(n,null,2)}
2
+ `,"utf8")}function T(r){try{let t=e.readdirSync(r);0===t.length&&e.rmdirSync(r)}catch{}}function j(t,n){let o=r.dirname(t.statePath),i=r.dirname(t.logPath);var a=t.statePath;try{e.unlinkSync(a)}catch{}var s=t.logPath;try{e.unlinkSync(s)}catch{}T(o),i!==o&&T(i),r.basename(o)===n.slug&&T(r.dirname(o))}function C(e,r){return e.includes(r.runArg)}function B(e){return A(e.consumerKey)??A(e.profileKey)??null}function K(e,r){return!r||e.consumers.includes(r)?e:{...e,consumers:[...e.consumers,r]}}async function D(e,r){if(!u(e.pid))return;let t=a(e.pid);if(t&&C(t,r)){try{process.kill(e.pid,"SIGTERM")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}if(!await s(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e.pid,1e3)}}}async function H(t){let i=B(t),s=$(t.projectRoot,t.definition,t.profileKey,t.stateDir),l=R(s.statePath);if(l&&function(e,r){var t,n;if(!u(e.pid))return!1;if(e.startTime){let r=c(e.pid);if(!r||r!==e.startTime)return!1}let o=a(e.pid);return!!o&&!!C(o,r.definition)&&!!e.bridgeScope&&e.serverBaseUrl===d(r.serverBaseUrl)&&e.localBaseUrl===d(r.localBaseUrl)&&e.launchUrl===A(r.launchUrl)&&e.registerPath===A(r.registerPath)&&e.unregisterPath===A(r.unregisterPath)&&e.devicePort===r.devicePort&&e.session===A(r.session)&&(t=e.bridgeScope,n=r.bridgeScope,t.tenantId===n.tenantId&&t.runId===n.runId&&t.leaseId===n.leaseId)&&e.tokenHash===N(r.bearerToken)}(l,t)){let e=K(l,i);return e!==l&&x(s.statePath,e),{pid:l.pid,spawned:!1,statePath:s.statePath,logPath:s.logPath}}l&&(await D(l,t.definition),j(s,t.definition));let S=function(t,i){let s=function(t){let o=n(import.meta.url),i=r.extname(o)||".js",a=r.join(r.dirname(o),`metro-companion${i}`);if(!e.existsSync(a))throw Error(`${t.displayName} entrypoint not found at ${a}. Rebuild the package to include the companion worker entry.`);return a}(t.definition),l=s.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(r.dirname(i),{recursive:!0});let u=e.openSync(i,"a"),S=0;try{let e;S=o(process.execPath,[...l,s,t.definition.runArg],{env:((e={...t.env??process.env,[p]:d(t.serverBaseUrl),[m]:t.bearerToken,[_]:d(t.localBaseUrl),[f]:$(t.projectRoot,t.definition,t.profileKey,t.stateDir).statePath})[y]=t.bridgeScope.tenantId,e[v]=t.bridgeScope.runId,e[g]=t.bridgeScope.leaseId,t.launchUrl?.trim()?e[h]=t.launchUrl.trim():delete e[h],t.registerPath?.trim()?e[U]=t.registerPath.trim():delete e[U],t.unregisterPath?.trim()?e[I]=t.unregisterPath.trim():delete e[I],void 0!==t.devicePort?e[b]=String(t.devicePort):delete e[b],t.session?.trim()?e[P]=t.session.trim():delete e[P],e),stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(S)||S<=0)throw Error(`Failed to start ${t.definition.displayName} process.`);return{pid:S,startTime:c(S)??void 0,command:a(S)??void 0,serverBaseUrl:d(t.serverBaseUrl),localBaseUrl:d(t.localBaseUrl),launchUrl:A(t.launchUrl),registerPath:A(t.registerPath),unregisterPath:A(t.unregisterPath),devicePort:t.devicePort,session:A(t.session),bridgeScope:t.bridgeScope,tokenHash:N(t.bearerToken),consumers:[]}}(t,s.logPath);return x(s.statePath,K(S,i)),{pid:S.pid,spawned:!0,statePath:s.statePath,logPath:s.logPath}}async function O(e){let r=B(e),t=$(e.projectRoot,e.definition,e.profileKey,e.stateDir),n=R(t.statePath);if(!n)return j(t,e.definition),{stopped:!1,statePath:t.statePath};let o=r?{...n,consumers:n.consumers.filter(e=>e!==r)}:{...n,consumers:[]};return o.consumers.length>0?(x(t.statePath,o),{stopped:!1,statePath:t.statePath}):(await D(n,e.definition),j(t,e.definition),{stopped:!0,statePath:t.statePath})}let L={slug:"metro-companion",runArg:w,displayName:"Metro companion"};async function G(e){return await H({...e,definition:L,registerPath:e.registerPath??"/api/metro/companion/register"})}async function J(e){return await O({...e,definition:L})}function F(e){return"string"==typeof e&&e.trim()?d(e.trim()):""}function V(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function q(e,r,t){return M(e,{env:r,cwd:t})}function W(r){try{return e.accessSync(r,e.constants.F_OK),!0}catch{return!1}}function z(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 X(e,r){if(null==e||""===e)return r;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new E("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}function Y(e,r){return{platform:r,bundleUrl:S(e,r)}}function Q(e,r){return{platform:r,metroHost:V(e?.metro_host),metroPort:e?.metro_port,bundleUrl:V(e?.metro_bundle_url),launchUrl:V(e?.launch_url)}}async function Z(e){await k(e)}async function ee(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 er(e,r){try{let t=await ee(e,r);return t.ok&&t.body.includes("packager-status:running")}catch{return!1}}async function et(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 s(e,1e3)){try{process.kill(e,"SIGKILL")}catch(r){let e=r.code;if("ESRCH"===e||"EPERM"===e)return;throw r}await s(e,1e3)}}}function en(e,r){let t=Error(e);return t.retryable=r,t}function eo(e,r){return!!(e>=500||408===e||425===e||429===e||JSON.stringify(r).includes("Metro companion is not connected"))}function ei(e){return!!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)}async function ea(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({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw en(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw en(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(i){let n=e.slice(0,200),o=i instanceof Error?i.message:String(i);throw en(`/api/metro/bridge returned invalid JSON (${r}) from ${t}: ${o}. body=${JSON.stringify(n)}`,eo(r,e))}}(await r.text(),r.status,e.baseUrl);if(!r.ok)throw en(`/api/metro/bridge failed (${r.status}): ${JSON.stringify(o)}`,eo(r.status,o));var i=o;let a=i.data??i;if(!a||"object"!=typeof a||Array.isArray(a))throw en("/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:Q(a.ios_runtime,"ios"),androidRuntime:Q(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 en(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function es(e,r,t,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return r&&i.push(`bridgeError=${r}`),t?.probe.reachable===!1&&i.push(`bridgeProbe=${t.probe.detail||`unreachable (status ${t.probe.statusCode||0})`}`),n&&n!==r&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function el(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 er(e,r))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await Z(o)}return!1}async function eu(e){let r=Date.now()+e.startupTimeoutMs,t=null,n=null;for(;Date.now()<r;){try{let r=await ea({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,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),!ei(e))break}let o=Math.min(1e3,Math.max(r-Date.now(),0));o>0&&await Z(o)}throw Error(es(e.baseUrl,n,t,e.initialBridgeError,e.companionLogPath))}async function ec(t={}){let n=t.env??process.env,a=process.cwd(),s=q(t.projectRoot??a,n,a),l=function(t,n){if("auto"!==n)return n;let o=function(t){let n=r.join(t,"package.json");if(!W(n))throw new E("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"}(s,t.kind??"auto"),u=X(t.metroPort??8081,8081),c=V(t.listenHost)??"0.0.0.0",d=V(t.statusHost)??"127.0.0.1",m=F(t.publicBaseUrl),p=z(t.startupTimeoutMs,18e4,3e4),f=z(t.probeTimeoutMs,1e4,1e3),h=t.reuseExisting??!0,g=t.installDependenciesIfNeeded??!0,y=t.runtimeFilePath?q(t.runtimeFilePath,n,a):null,b=q(t.logPath??r.join(s,".agent-device","metro.log"),n,a);if(!m&&!F(t.proxyBaseUrl))throw new E("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:S,proxyBaseUrl:w,proxyBearerToken:P}=function(e,r){if(e&&!r)throw new E("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 E("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&r),proxyBaseUrl:e,proxyBearerToken:r}}(F(t.proxyBaseUrl),V(t.proxyBearerToken)??""),v=S?function(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new E("INVALID_ARGS","metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.");return e}(t.bridgeScope):null,U=g?function(t,n){if(function(r){try{return e.statSync(r).isDirectory()}catch{return!1}}(r.join(t,"node_modules")))return{installed:!1};let o=W(r.join(t,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:W(r.join(t,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return i(o.command,o.installArgs,{cwd:t,env:n}),{installed:!0,packageManager:o.command}}(s,n):{installed:!1},_=`http://${d}:${u}/status`,I=!1,M=!1,k=0;if(h&&await er(_,f))M=!0;else if(I=!0,k=function(t,n,i,a,s,l){let u="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(i)]}:{command:"npx",installArgs:["react-native","start","--host",a,"--port",String(i)]};e.mkdirSync(r.dirname(s),{recursive:!0});let c=e.openSync(s,"a"),d=0;try{d=o(u.command,u.installArgs,{cwd:t,env:l,stdio:["ignore",c,c]})}finally{e.closeSync(c)}if(!Number.isInteger(d)||d<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:d}}(s,l,u,c,b,n).pid,!await el(_,p,f))throw await et(k).catch(()=>{}),Error(`Metro did not become ready at ${_} within ${p}ms. Check ${b}.`);let N=m?Y(m,"ios"):{platform:"ios"},A=m?Y(m,"android"):{platform:"android"},$=null,R=null;if(v)try{$=await ea({baseUrl:w,bearerToken:P,scope:v,timeoutMs:f})}catch(e){if(!ei(e))throw e;R=e instanceof Error?e.message:String(e)}if(v&&(!$||!1===$.probe.reachable)){let e;try{e=(await G({projectRoot:s,serverBaseUrl:w,bearerToken:P,bridgeScope:v,localBaseUrl:`http://${d}:${u}`,launchUrl:V(t.launchUrl),profileKey:V(t.companionProfileKey),consumerKey:V(t.companionConsumerKey),env:n})).logPath}catch(e){throw Error(es(w,e instanceof Error?e.message:String(e),$,R))}try{$=await eu({baseUrl:w,bearerToken:P,scope:v,probeTimeoutMs:f,startupTimeoutMs:p,initialBridgeError:R,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}v&&function(e,r){if(!r?.iosRuntime.bundleUrl)throw Error(es(e,"bridge descriptor is missing ios_runtime.metro_bundle_url",r))}(w,$);let x=$?.iosRuntime??N,T=$?.androidRuntime??A,j={projectRoot:s,kind:l,dependenciesInstalled:U.installed,packageManager:U.packageManager??null,started:I,reused:M,pid:k,logPath:b,statusUrl:_,runtimeFilePath:y,iosRuntime:x,androidRuntime:T,bridge:$};return y&&(e.mkdirSync(r.dirname(y),{recursive:!0}),e.writeFileSync(y,JSON.stringify(j,null,2))),j}async function ed(e={}){let r=z(e.timeoutMs,1e4,1e3),t=function(e){var r;let t,n=V(e.bundleUrl)??e.runtime?.bundleUrl,o=!!V(e.bundleUrl),i=!!V(n),a=l({metroHost:V(e.metroHost)??(o?void 0:V(e.runtime?.metroHost))??(i?void 0:"localhost"),metroPort:void 0!==e.metroPort?X(e.metroPort,8081):o?void 0:e.runtime?.metroPort??(i?void 0:8081),bundleUrl:n});if(!a)throw new E("INVALID_ARGS","Unable to resolve Metro host and port for reload.");return r=function(e){let r=V(e);if(!r)return"/reload";let t=new URL(r).pathname.replace(/\/+$/,"");return t.endsWith("/index.bundle")?`${t.slice(0,-13)}/reload`:"/reload"}(n),(t=new URL(`${a.scheme}://localhost`)).hostname=a.host,t.port=String(a.port),t.pathname=r,t.toString()}(e),n=await ee(t,r);if(!n.ok)throw new E("COMMAND_FAILED",`Metro reload failed (${n.status}).`,{reloadUrl:t,status:n.status,body:n.body,hint:"Verify Metro is running and the target React Native app is connected to this Metro instance."});return{reloaded:!0,reloadUrl:t,status:n.status,body:n.body}}export{Y as buildMetroRuntimeHints,H as ensureCompanionTunnel,G as ensureMetroCompanion,ec as prepareMetroRuntime,ed as reloadMetro,O as stopCompanionTunnel,J as stopMetroCompanion};
@@ -0,0 +1 @@
1
+ let _="--agent-device-run-metro-companion",E="--agent-device-run-react-devtools-companion",N="AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL",O="AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN",A="AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL",T="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL",C="AGENT_DEVICE_METRO_COMPANION_STATE_PATH",I="AGENT_DEVICE_METRO_COMPANION_SCOPE_TENANT_ID",R="AGENT_DEVICE_METRO_COMPANION_SCOPE_RUN_ID",P="AGENT_DEVICE_METRO_COMPANION_SCOPE_LEASE_ID",M="AGENT_DEVICE_METRO_COMPANION_REGISTER_PATH",e="AGENT_DEVICE_METRO_COMPANION_UNREGISTER_PATH",U="AGENT_DEVICE_METRO_COMPANION_DEVICE_PORT",V="AGENT_DEVICE_METRO_COMPANION_SESSION";function L(_){let E=_.length;for(;E>0&&47===_.charCodeAt(E-1);)E-=1;return E===_.length?_:_.slice(0,E)}function S(_,E){let N=new URL(`${L(_)}/index.bundle`);return N.searchParams.set("platform",E),N.searchParams.set("dev","true"),N.searchParams.set("minify","false"),N.toString()}export{O as ENV_COMPANION_TUNNEL_BEARER_TOKEN,U as ENV_COMPANION_TUNNEL_DEVICE_PORT,T as ENV_COMPANION_TUNNEL_LAUNCH_URL,A as ENV_COMPANION_TUNNEL_LOCAL_BASE_URL,M as ENV_COMPANION_TUNNEL_REGISTER_PATH,P as ENV_COMPANION_TUNNEL_SCOPE_LEASE_ID,R as ENV_COMPANION_TUNNEL_SCOPE_RUN_ID,I as ENV_COMPANION_TUNNEL_SCOPE_TENANT_ID,N as ENV_COMPANION_TUNNEL_SERVER_BASE_URL,V as ENV_COMPANION_TUNNEL_SESSION,C as ENV_COMPANION_TUNNEL_STATE_PATH,e as ENV_COMPANION_TUNNEL_UNREGISTER_PATH,_ as METRO_COMPANION_RUN_ARG,E as REACT_DEVTOOLS_COMPANION_RUN_ARG,S as buildBundleUrl,L as normalizeBaseUrl};
@@ -0,0 +1 @@
1
+ let e=["android.shell","ios.runnerCommand","macos.desktopScreenshot"],n={"android.shell":"androidShell","ios.runnerCommand":"iosRunnerCommand","macos.desktopScreenshot":"macosDesktopScreenshot"};function o(e,n){return e.capabilities?.includes(n)??!1}function a(e,o){let a=n[o];return"function"==typeof e.escapeHatches?.[a]}export{n as BACKEND_CAPABILITY_ESCAPE_HATCH_METHODS,e as BACKEND_CAPABILITY_NAMES,o as hasBackendCapability,a as hasBackendEscapeHatch};
@@ -0,0 +1 @@
1
+ import e from"node:fs";let t=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b\\s+https?:\\/\\/","i"),r=/https?:\/\/[^\s"'<>\])]+/i,n=[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i],i="<memory>";function s(e,t,r=e.limits.maxEntries){let n=[...e.entries],i=new Set(n.map(e=>o(e)));for(let e of t.entries){let t=o(e);if(!i.has(t)&&(i.add(t),n.push(e),n.length>=r))break}return{...e,matchedLines:n.length,entries:n}}function u(t,r){let n=y(r?.maxEntries,25,1,200),i=r?.include??"summary",s=y(r?.maxPayloadChars,2048,64,16384),u=y(r?.maxScanLines,4e3,100,2e4);return e.existsSync(t)?l(e.readFileSync(t,"utf8"),{...r,path:t}):{path:t,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:i,limits:{maxEntries:n,maxPayloadChars:s,maxScanLines:u}}}function l(e,n){let s=y(n?.maxEntries,25,1,200),u=n?.backend,l=n?.include??"summary",o=y(n?.maxPayloadChars,2048,64,16384),g=y(n?.maxScanLines,4e3,100,2e4),N=e.split("\n"),T=Math.max(0,N.length-g),E=N.slice(T),I=[];for(let e=E.length-1;e>=0&&I.length<s;e-=1){let n=E[e];if(!n?.trim())continue;let i=function(e,n,i,s,u,l){let o=e[n]?.trim();if(!o)return null;let y=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let n=e.slice(t,r+1);try{let e=JSON.parse(n);return e&&"object"==typeof e?e:null}catch{return null}}(o),g=p(y,["method","httpMethod"]),N=p(y,["url","requestUrl"]),T=function(e,t){if(!e)return null;for(let r of t){let t=e[r];if("number"==typeof t&&Number.isInteger(t))return t;if("string"==typeof t&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t.trim(),10)}return null}(y,["status","statusCode","responseCode"]),E=t.exec(o),I=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(o),M=(g??I?.[1]??E?.[1])?.toUpperCase(),$=r.exec(o),L=N??$?.[0];if(!L)return null;let O=T??d(o)??void 0;if(!(g||I?.[1]||E?.[1]||void 0!==O||/\bURL["'=: ]+https?:\/\//i.test(o)||/\bheaders?["'=: ]+/i.test(o)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(o)))return null;let S={method:M,url:L,status:O,timestamp:f(o),packetId:m(o)??void 0,durationMs:c(o)??void 0,raw:x(o,l),line:i};if("android"===s&&function(e,t,r){let n=a(t,r,5),i=e.packetId??n.map(e=>m(e)).find(e=>"string"==typeof e&&e.length>0);i&&(e.packetId=i);let s=i?a(t,r,12).filter(e=>m(e)===i):n;e.timestamp||(e.timestamp=s.map(e=>f(e)).find(e=>"string"==typeof e&&e.length>0)),void 0===e.status&&(e.status=s.map(e=>d(e)).find(e=>"number"==typeof e)),void 0===e.durationMs&&(e.durationMs=s.map(e=>c(e)).find(e=>"number"==typeof e))}(S,e,n),"headers"===u||"all"===u){let e=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return b(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(o,y);e&&(S.headers=x(e,l))}if("body"===u||"all"===u){let e=h(o,y,["requestBody","body","payload","request"]),t=h(o,y,["responseBody","response"]);e&&(S.requestBody=x(e,l)),t&&(S.responseBody=x(t,l))}return S}(E,e,T+e+1,u,l,o);i&&I.push(i)}return{path:n?.path??i,exists:!0,scannedLines:E.length,matchedLines:I.length,entries:I,include:l,limits:{maxEntries:s,maxPayloadChars:o,maxScanLines:g}}}function o(e){return`${e.timestamp??""}|${e.method??""}|${e.url}|${e.status??""}|${e.raw}`}function a(e,t,r){let n=[],i=Math.max(0,t-r),s=Math.min(e.length-1,t+r);for(let t=i;t<=s;t+=1){let r=e[t]?.trim();r&&n.push(r)}return n}function d(e){for(let t of n){let r=t.exec(e);if(!r)continue;let n=Number.parseInt(r[1]??"",10);if(Number.isInteger(n))return n}return null}function f(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);if(t)return t[0];let r=/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e);return r?.[0]}function m(e){let t=/\bpacket id (\d+)\b/i.exec(e);return t?.[1]??null}function c(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);if(!t)return null;let r=Number.parseInt(t[1]??"",10);return Number.isInteger(r)?r:null}function p(e,t){if(e)for(let r of t){let t=e[r];if("string"==typeof t&&t.trim().length>0)return t.trim()}}function h(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return b(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(n?.[1])return n[1].trim()}}function b(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function x(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function y(e,t,r,n){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(n,e)):t}export{i as NETWORK_LOG_MEMORY_PATH,s as mergeNetworkDumps,u as readRecentNetworkTraffic,l as readRecentNetworkTrafficFromText};
@@ -0,0 +1 @@
1
+ let e=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i,r=/\b[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g;function t(e){var t,s;let o=!1,i=e;return{value:(t=i=(i=(i=(i=(i=i.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,r)=>(o=!0,`${String(r)}=[REDACTED]`))).replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,r,t,a)=>(o=!0,`${String(r)}[REDACTED]${String(a)}`))).replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,r)=>(o=!0,`${String(r)}[REDACTED]`))).replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;&]+)/gi,(e,r)=>(o=!0,`${String(r)}[REDACTED]`))).replaceAll(r,()=>(o=!0,"[REDACTED]")),s=()=>{o=!0},i=/(https?:\/\/|token|secret|password|authorization|cookie|api[-_]?key)/i.test(t)?t.replaceAll(/https?:\/\/[^\s"'<>)]+/gi,e=>{let r=a(e);return r?(r.redacted&&s(),r.value):e}):t),redacted:o}}function a(r){try{let t=new URL(r),a=function(r){let t=!1;for(let a of Array.from(r.searchParams.keys()))e.test(a)&&(r.searchParams.set(a,"[REDACTED]"),t=!0);return t}(t);return(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED",a=!0),{value:t.toString(),redacted:a}}catch{return}}export{t as redactNetworkLogText,a as redactNetworkUrl};
package/dist/src/8564.js CHANGED
@@ -1,3 +1,3 @@
1
- import e from"node:fs";import t from"node:path";import{fileURLToPath as n}from"node:url";import{AsyncLocalStorage as a}from"node:async_hooks";import i from"node:crypto";import r from"node:os";import{redactDiagnosticData as o,AppError as s}from"./9152.js";import{withSuccessText as l,bindCommands as d,successText as u}from"./9076.js";import{hasBackendEscapeHatch as c,hasBackendCapability as p}from"./backend.js";import{resolveUserPath as m,expandUserHomePath as f}from"./3267.js";function g(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??h(),policy:e.policy??v(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...d(t)}}function h(e=[]){let t=new Map(e.map(e=>[e.name,I(e)]));return{get:e=>I(t.get(e)),set:e=>{t.set(e.name,I(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>I(e))}}function I(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function S(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function v(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function w(e,t){if(!p(e.backend,t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} is not supported by this backend`,{capability:t});if(!e.policy.allowNamedBackendCapabilities.includes(t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} is not allowed by command policy`,{capability:t});if(!c(e.backend,t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} does not implement its escape hatch method`,{capability:t})}function b(){try{let n=y();return JSON.parse(e.readFileSync(t.join(n,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function y(){let a=t.dirname(n(import.meta.url)),i=a;for(let n=0;n<6;n+=1){let n=t.join(i,"package.json");if(e.existsSync(n))return i;i=t.dirname(i)}return a}let P=new a;function k(){return i.randomBytes(8).toString("hex")}async function _(e,t){let n={...e,diagnosticId:`${Date.now().toString(36)}-${i.randomBytes(4).toString("hex")}`,events:[]};return await P.run(n,t)}function N(){let e=P.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function D(t){let n=P.getStore();if(!n)return;let a={ts:new Date().toISOString(),level:t.level??"info",phase:t.phase,session:n.session,requestId:n.requestId,command:n.command,durationMs:t.durationMs,data:t.data?o(t.data):void 0};if(n.events.push(a),!n.debug)return;let i=`[agent-device][diag] ${JSON.stringify(a)}
1
+ import e from"node:fs";import t from"node:path";import{fileURLToPath as n}from"node:url";import{AsyncLocalStorage as a}from"node:async_hooks";import i from"node:crypto";import r from"node:os";import{redactDiagnosticData as o,AppError as s}from"./9152.js";import{withSuccessText as l,bindCommands as d,successText as u}from"./9076.js";import{hasBackendEscapeHatch as c,hasBackendCapability as p}from"./4993.js";import{resolveUserPath as m,expandUserHomePath as f}from"./3267.js";function g(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??h(),policy:e.policy??v(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,...d(t)}}function h(e=[]){let t=new Map(e.map(e=>[e.name,I(e)]));return{get:e=>I(t.get(e)),set:e=>{t.set(e.name,I(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>I(e))}}function I(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function S(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function v(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function w(e,t){if(!p(e.backend,t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} is not supported by this backend`,{capability:t});if(!e.policy.allowNamedBackendCapabilities.includes(t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} is not allowed by command policy`,{capability:t});if(!c(e.backend,t))throw new s("UNSUPPORTED_OPERATION",`Backend capability ${t} does not implement its escape hatch method`,{capability:t})}function b(){try{let n=y();return JSON.parse(e.readFileSync(t.join(n,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function y(){let a=t.dirname(n(import.meta.url)),i=a;for(let n=0;n<6;n+=1){let n=t.join(i,"package.json");if(e.existsSync(n))return i;i=t.dirname(i)}return a}let P=new a;function k(){return i.randomBytes(8).toString("hex")}async function _(e,t){let n={...e,diagnosticId:`${Date.now().toString(36)}-${i.randomBytes(4).toString("hex")}`,events:[]};return await P.run(n,t)}function N(){let e=P.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function D(t){let n=P.getStore();if(!n)return;let a={ts:new Date().toISOString(),level:t.level??"info",phase:t.phase,session:n.session,requestId:n.requestId,command:n.command,durationMs:t.durationMs,data:t.data?o(t.data):void 0};if(n.events.push(a),!n.debug)return;let i=`[agent-device][diag] ${JSON.stringify(a)}
2
2
  `;try{n.logPath&&e.appendFile(n.logPath,i,()=>{}),n.traceLogPath&&e.appendFile(n.traceLogPath,i,()=>{}),n.logPath||n.traceLogPath||process.stderr.write(i)}catch{}}async function $(e,t,n){let a=Date.now();try{let i=await t();return D({level:"info",phase:e,durationMs:Date.now()-a,data:n}),i}catch(t){throw D({level:"error",phase:e,durationMs:Date.now()-a,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function C(n={}){let a=P.getStore();if(!a||!n.force&&!a.debug||0===a.events.length)return null;try{let n=(a.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),i=new Date().toISOString().slice(0,10),s=t.join(r.homedir(),".agent-device","logs",n,i);e.mkdirSync(s,{recursive:!0});let l=new Date().toISOString().replace(/[:.]/g,"-"),d=t.join(s,`${l}-${a.diagnosticId}.ndjson`),u=a.events.map(e=>JSON.stringify(o(e)));return e.writeFileSync(d,`${u.join("\n")}
3
3
  `),a.events=[],d}catch{return null}}function j(e){let n,a=(n=(e??"").trim())?m(n):t.join(f("~"),".agent-device");return{baseDir:a,infoPath:t.join(a,"daemon.json"),lockPath:t.join(a,"daemon.lock"),logPath:t.join(a,"daemon.log"),sessionsDir:t.join(a,"sessions")}}function R(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function A(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function O(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function x(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let z=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,B=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,E=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function M(){let e=process.argv[1];return e?T(e):"unknown"}function T(n,a=y()){try{let r=t.resolve(a),o=[t.resolve(n)],s=new Set,l=[];for(;o.length>0;){let n=o.pop();if(!n||s.has(n))continue;s.add(n);let a=e.statSync(n);if(!a.isFile())continue;let i=t.relative(r,n)||n;l.push(`${i}:${a.size}:${Math.trunc(a.mtimeMs)}`);let d=e.readFileSync(n,"utf8");for(let e of function(e){let t=new Set;return L(e,z,t),L(e,B,t),[...t]}(d)){let a=function(e,n){let a=t.resolve(t.dirname(e),n),i=F(a);if(i)return i;for(let e of E){let t=F(`${a}${e}`);if(t)return t}for(let e of E){let n=F(t.join(a,`index${e}`));if(n)return n}return null}(n,e);a&&o.push(a)}}let d=l.sort().join("|"),u=i.createHash("sha1").update(d).digest("hex");return`graph:${l.length}:${u}`}catch{return"unknown"}}function L(e,t,n){t.lastIndex=0;let a=null;for(;null!==(a=t.exec(e));){let e=a[1]?.trim();e?.startsWith(".")&&n.add(e)}}function F(t){try{return e.statSync(t).isFile()?t:null}catch{return null}}function U(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function K(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function q(e,t={}){let n=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&n?{serial:e.android?.serial??e.id}:{}}}function H(e){return{name:e.name,...q(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function J(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function Z(e){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return l({udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted},`${t}: ${e.device} ${e.udid}${n}`)}function V(e){return e.bundleId??e.package??e.app}function W(e){return l({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${V(e)}`)}function G(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function Q(e){return l({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${G(e)}`)}function X(e){let t=e.appName??e.appBundleId??e.session;return l({session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?q(e.device):{}},t?`Opened: ${t}`:"Opened")}function Y(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...u(e.session?`Closed: ${e.session}`:"Closed")}}function ee(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}export{w as assertBackendCapabilityAllowed,U as buildAppIdentifiers,K as buildDeviceIdentifiers,T as computeDaemonCodeSignature,g as createAgentDevice,h as createMemorySessionStore,k as createRequestId,D as emitDiagnostic,y as findProjectRoot,C as flushDiagnosticsToSessionFile,N as getDiagnosticsMeta,S as localCommandPolicy,x as normalizeTenantId,b as readVersion,M as resolveDaemonCodeSignature,j as resolveDaemonPaths,R as resolveDaemonServerMode,A as resolveDaemonTransportPreference,V as resolveDeployResultTarget,G as resolveInstallFromSourceResultTarget,O as resolveSessionIsolationMode,v as restrictedCommandPolicy,Y as serializeCloseResult,W as serializeDeployResult,J as serializeDevice,Z as serializeEnsureSimulatorResult,Q as serializeInstallFromSourceResult,X as serializeOpenResult,H as serializeSessionListEntry,ee as serializeSnapshotResult,$ as withDiagnosticTimer,_ as withDiagnosticsScope};