@radhya/mach 2.0.13 → 2.0.14

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/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{a as fn,b as fr,c as mr,d as gr,e as $e,f as lt,g as hr,h as Sr,i as Pt,j as yr,l as Ht}from"./chunk-YMJWGZX6.js";import{a as m,b as cr,c as Pe,d as ur,e as pr,f as vt,g as Je,h as k}from"./chunk-HIP5BA3H.js";import{Command as bf,Option as Fe}from"commander";import{configDotenv as Ef}from"dotenv";import{intro as we,outro as Oa}from"@clack/prompts";import Ee from"chalk";import{text as br,confirm as Ta,spinner as ka,isCancel as ni,cancel as jt,note as xa,outro as La}from"@clack/prompts";import Gt from"chalk";async function Er(){try{let e=await br({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});ni(e)&&(jt("Operation cancelled."),process.exit(0));let t=await br({message:"Enter Region:",initialValue:"ap-south-1"});ni(t)&&(jt("Operation cancelled."),process.exit(0));let n=await Ta({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});ni(n)&&(jt("Operation cancelled."),process.exit(0));let i=ka();i.start("Setting up hosting infrastructure...");try{let r=await k.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${Gt.cyan(o.bucketName)}
2
+ import{a as fn,b as gr,c as hr,d as Sr,e as $e,f as lt,g as yr,h as br,i as Pt,j as Er,l as Ht}from"./chunk-XW3V7PJM.js";import{a as m,b as pr,c as Pe,d as fr,e as mr,f as vt,g as Je,h as k}from"./chunk-S64YFTRR.js";import{Command as wf,Option as Fe}from"commander";import{configDotenv as _f}from"dotenv";import{intro as we,outro as Ca}from"@clack/prompts";import Ee from"chalk";import{text as Ar,confirm as La,spinner as xa,isCancel as ni,cancel as jt,note as Ma,outro as Ua}from"@clack/prompts";import Gt from"chalk";async function Ir(){try{let e=await Ar({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});ni(e)&&(jt("Operation cancelled."),process.exit(0));let t=await Ar({message:"Enter Region:",initialValue:"ap-south-1"});ni(t)&&(jt("Operation cancelled."),process.exit(0));let n=await La({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});ni(n)&&(jt("Operation cancelled."),process.exit(0));let i=xa();i.start("Setting up hosting infrastructure...");try{let r=await k.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${Gt.cyan(o.bucketName)}
3
3
  `;s+=`Region: ${Gt.cyan(o.region)}
4
4
  `,s+=`S3 Website URL: ${Gt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
5
5
 
6
6
  CloudFront ID: ${Gt.cyan(o.cloudFrontId)}`,s+=`
7
- CloudFront URL: ${Gt.blue(o.cloudFrontUrl)}`),xa(s,"Setup Complete!"),La("You are all set!")}catch(r){i.stop("Setup failed"),jt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){jt(`An unexpected error occurred: ${e.message}`)}}import{readdir as Ma,writeFile as Ua,access as Fa,mkdir as Ba}from"fs/promises";import{join as Ar}from"path";import{spinner as Ha,text as Ir,isCancel as wr,cancel as ii,note as ja,outro as Ga}from"@clack/prompts";import Ka from"chalk";async function Va(){let e=["./app","./src/app"];for(let t of e)try{return await Fa(t),t}catch{}return null}async function _r(e){try{let n=await Va()||"./app",i=await Ir({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});wr(i)&&(ii("Operation cancelled."),process.exit(0));let r=await Ir({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});wr(r)&&(ii("Operation cancelled."),process.exit(0));let o=Ha();o.start("Scanning app directory for routes...");let s=await Rr(i);o.stop(`Found ${s.length} routes`);let l=za(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let c=a.substring(0,a.lastIndexOf("/"));if(c)try{await Ba(c,{recursive:!0})}catch{}await Ua(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),ja(`Routes included:
7
+ CloudFront URL: ${Gt.blue(o.cloudFrontUrl)}`),Ma(s,"Setup Complete!"),Ua("You are all set!")}catch(r){i.stop("Setup failed"),jt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){jt(`An unexpected error occurred: ${e.message}`)}}import{readdir as Fa,writeFile as Ba,access as Ha,mkdir as ja}from"fs/promises";import{join as wr}from"path";import{spinner as Ga,text as _r,isCancel as Rr,cancel as ii,note as Ka,outro as Va}from"@clack/prompts";import za from"chalk";async function Wa(){let e=["./app","./src/app"];for(let t of e)try{return await Ha(t),t}catch{}return null}async function $r(e){try{let n=await Wa()||"./app",i=await _r({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});Rr(i)&&(ii("Operation cancelled."),process.exit(0));let r=await _r({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});Rr(r)&&(ii("Operation cancelled."),process.exit(0));let o=Ga();o.start("Scanning app directory for routes...");let s=await vr(i);o.stop(`Found ${s.length} routes`);let l=Ya(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let d=a.substring(0,a.lastIndexOf("/"));if(d)try{await ja(d,{recursive:!0})}catch{}await Ba(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),Ka(`Routes included:
8
8
  ${s.map(u=>` \u2022 ${u.path}`).join(`
9
- `)}`,"Sitemap Summary"),Ga(`Sitemap saved to ${Ka.cyan(a)}`)}catch(t){ii(`An error occurred: ${t.message}`)}}async function Rr(e,t=""){let n=[];try{let i=await Ma(e,{withFileTypes:!0});for(let r of i){let o=Ar(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await Rr(o,Ar(t,r.name));n.push(...s)}else if(r.isFile()){if(r.name==="index.tsx"||r.name==="index.ts"||r.name==="index.jsx"||r.name==="index.js"){let s=t===""?"/":`/${t}`;n.push({path:s,file:o})}else if(r.name.match(/\.(tsx|ts|jsx|js)$/)&&!r.name.includes("_layout")&&!r.name.includes("+")){let s=r.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${s}`.replace(/\/+/g,"/");n.push({path:l,file:o})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return n}function za(e,t){let n=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
9
+ `)}`,"Sitemap Summary"),Va(`Sitemap saved to ${za.cyan(a)}`)}catch(t){ii(`An error occurred: ${t.message}`)}}async function vr(e,t=""){let n=[];try{let i=await Fa(e,{withFileTypes:!0});for(let r of i){let o=wr(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await vr(o,wr(t,r.name));n.push(...s)}else if(r.isFile()){if(r.name==="index.tsx"||r.name==="index.ts"||r.name==="index.jsx"||r.name==="index.js"){let s=t===""?"/":`/${t}`;n.push({path:s,file:o})}else if(r.name.match(/\.(tsx|ts|jsx|js)$/)&&!r.name.includes("_layout")&&!r.name.includes("+")){let s=r.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${s}`.replace(/\/+/g,"/");n.push({path:l,file:o})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return n}function Ya(e,t){let n=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
10
10
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
11
11
  ${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[.*?\]/g,"/:id"),o=o.replace(/\/+/g,"/"),o===""&&(o="/"),` <url>
12
12
  <loc>${t}${o}</loc>
@@ -15,7 +15,7 @@ ${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[
15
15
  <priority>0.8</priority>
16
16
  </url>`}).join(`
17
17
  `)}
18
- </urlset>`}import{randomUUID as Tc}from"crypto";import ge from"path";import $n from"axios";import kc from"os";import{spinner as Fi,select as Mo,confirm as Uo,isCancel as vn,cancel as Fo,log as $}from"@clack/prompts";import v from"chalk";import de from"fs";import{execSync as Bo}from"child_process";import Ho from"adm-zip";import{spinner as tl,log as mn}from"@clack/prompts";import Pr from"chalk";import Or from"fs";import Dr from"path";var $r=`#!/bin/bash
18
+ </urlset>`}import{randomUUID as Ld}from"crypto";import ge from"path";import $n from"axios";import xd from"os";import{spinner as Bi,select as Fo,confirm as Bo,isCancel as vn,cancel as Ho,log as $}from"@clack/prompts";import v from"chalk";import ce from"fs";import{execSync as jo}from"child_process";import Go from"adm-zip";import{spinner as il,log as mn}from"@clack/prompts";import Dr from"chalk";import Cr from"fs";import Nr from"path";var Pr=`#!/bin/bash
19
19
  # --- Mach Cloud Build Script (Android) ---
20
20
  # All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on instance.
21
21
  BUILD_ID="{{BUILD_ID}}"
@@ -89,6 +89,25 @@ function upload_logs() {
89
89
  fi
90
90
  }
91
91
 
92
+ function log_s3_target() {
93
+ local LABEL="$1"
94
+ local URL="$2"
95
+ case "\${MACH_S3_DEBUG:-}" in
96
+ 1|true|TRUE|yes|YES|on|ON) ;;
97
+ *) return 0 ;;
98
+ esac
99
+ if [ -z "$URL" ]; then
100
+ return 0
101
+ fi
102
+ local HOST
103
+ HOST=$(printf '%s' "$URL" | sed -E 's#^https?://([^/?]+).*#\\1#')
104
+ echo "[S3_DEBUG] $LABEL host=$HOST expected_region=ap-south-1"
105
+ case "$HOST" in
106
+ *ap-south-1*) ;;
107
+ *) echo "[S3_DEBUG] WARNING: $LABEL host does not include ap-south-1" ;;
108
+ esac
109
+ }
110
+
92
111
  function report_status() {
93
112
  local STATUS=$1
94
113
  local ERROR_MSG=$2
@@ -168,6 +187,7 @@ mkdir -p /home/ubuntu/build /root/.gradle /root/.npm
168
187
  # android/ + node_modules caches are applied AFTER source extraction (so source doesn't overwrite them).
169
188
  cache_dl_pids=()
170
189
 
190
+ log_s3_target "ANDROID_SOURCE_DOWNLOAD" "$PRESIGNED_SOURCE_DOWNLOAD"
171
191
  curl -sf -o /tmp/source.zip "$PRESIGNED_SOURCE_DOWNLOAD" &
172
192
  SOURCE_DL_PID=$!
173
193
 
@@ -415,12 +435,14 @@ if [ $BUILD_EXIT_CODE -eq 0 ]; then
415
435
  if [ ! -z "$APK_FILE" ] && [ ! -z "$PRESIGNED_ARTIFACT_APK_UPLOAD" ]; then
416
436
  echo "Uploading APK: $APK_FILE as \${FINAL_BASE_NAME}.apk"
417
437
  mv "$APK_FILE" "\${FINAL_BASE_NAME}.apk"
438
+ log_s3_target "ANDROID_APK_UPLOAD" "$PRESIGNED_ARTIFACT_APK_UPLOAD"
418
439
  curl -X PUT -T "\${FINAL_BASE_NAME}.apk" "$PRESIGNED_ARTIFACT_APK_UPLOAD" --silent
419
440
  fi
420
441
 
421
442
  if [ ! -z "$AAB_FILE" ] && [ ! -z "$PRESIGNED_ARTIFACT_AAB_UPLOAD" ]; then
422
443
  echo "Uploading AAB: $AAB_FILE as \${FINAL_BASE_NAME}.aab"
423
444
  mv "$AAB_FILE" "\${FINAL_BASE_NAME}.aab"
445
+ log_s3_target "ANDROID_AAB_UPLOAD" "$PRESIGNED_ARTIFACT_AAB_UPLOAD"
424
446
  curl -X PUT -T "\${FINAL_BASE_NAME}.aab" "$PRESIGNED_ARTIFACT_AAB_UPLOAD" --silent
425
447
  fi
426
448
 
@@ -511,7 +533,7 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
511
533
  echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
512
534
  sleep 5
513
535
  sudo shutdown -h now
514
- `;import Xa from"crypto";import{log as Oe}from"@clack/prompts";import De from"chalk";import{execSync as Wa}from"child_process";import Ce from"fs";import Ot from"path";var vr={id:"expo",displayName:"Expo",applyLocalProcessEnv:e=>{e.developmentClient?(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client")},localAndroidEnv:(e,t)=>({EXPO_NO_DOTENV:"1",MACH_FRAMEWORK:"expo",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
536
+ `;import Za from"crypto";import{log as Oe}from"@clack/prompts";import De from"chalk";import{execSync as Ja}from"child_process";import Ce from"fs";import Ot from"path";var Or={id:"expo",displayName:"Expo",applyLocalProcessEnv:e=>{e.developmentClient?(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(Oe.info(De.blue("\u2139\uFE0F Configuring Expo build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client")},localAndroidEnv:(e,t)=>({EXPO_NO_DOTENV:"1",MACH_FRAMEWORK:"expo",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
515
537
  export MACH_FRAMEWORK="expo"
516
538
  echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
517
539
  export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
@@ -563,7 +585,7 @@ fi
563
585
  echo "expo.enableHermes=true" >> gradle.properties
564
586
  `,androidRemoteReleaseGradlePropertiesScript:()=>`
565
587
  echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
566
- `,prepareLocalProject:async e=>{let{platform:t,options:n,cacheMeta:i,cacheMetaDir:r,currentBuildEnv:o,reportStep:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:c,writeCacheMeta:u}=e,d=n.iosBundleIdentifier||"",f=n.name||"",p=Ot.join(process.cwd(),"app.json"),g=null;Oe.info(De.blue(`Running Expo prebuild for ${t}...`));try{if(Ce.existsSync(p)){g=Ce.readFileSync(p,"utf-8");let _=JSON.parse(g);_.expo=_.expo||{},f||(f=_.expo.name||""),t==="ios"&&!d&&(d=_.expo?.ios?.bundleIdentifier||""),n.name&&(_.expo.name=n.name),n.scheme&&(_.expo.scheme=n.scheme),t==="ios"&&n.iosBundleIdentifier?(_.expo.ios=_.expo.ios||{},_.expo.ios.bundleIdentifier=n.iosBundleIdentifier):t==="android"&&n.androidPackage&&(_.expo.android=_.expo.android||{},_.expo.android.package=n.androidPackage),Ce.writeFileSync(p,JSON.stringify(_,null,2))}let y=["exec","--","expo","prebuild","--platform",t,"--no-install"];if(await s("prebuild"),await l("npm",y,process.cwd(),o()),t!=="ios"||!Ce.existsSync("ios"))return{appName:f,bundleId:d};await s("pods"),Oe.info(De.blue("Running pod install..."));try{let _=Ot.resolve("ios"),D=Ot.join(_,"Podfile");if(!Ce.existsSync(D))throw new Error("ios/Podfile not found. Skipping pod install.");let b=o();a(_,b);let x=Ce.readFileSync(D,"utf-8"),A=n.iosDeploymentTarget||"13.4";if(!n.developmentClient&&(Oe.info(De.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),x.includes("use_expo_modules!")&&!x.includes("exclude:"))){let C=/use_expo_modules!(\s*)$/m;C.test(x)?x=x.replace(C,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):x=x.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let B=`
588
+ `,prepareLocalProject:async e=>{let{platform:t,options:n,cacheMeta:i,cacheMetaDir:r,currentBuildEnv:o,reportStep:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e,c=n.iosBundleIdentifier||"",f=n.name||"",p=Ot.join(process.cwd(),"app.json"),g=null;Oe.info(De.blue(`Running Expo prebuild for ${t}...`));try{if(Ce.existsSync(p)){g=Ce.readFileSync(p,"utf-8");let _=JSON.parse(g);_.expo=_.expo||{},f||(f=_.expo.name||""),t==="ios"&&!c&&(c=_.expo?.ios?.bundleIdentifier||""),n.name&&(_.expo.name=n.name),n.scheme&&(_.expo.scheme=n.scheme),t==="ios"&&n.iosBundleIdentifier?(_.expo.ios=_.expo.ios||{},_.expo.ios.bundleIdentifier=n.iosBundleIdentifier):t==="android"&&n.androidPackage&&(_.expo.android=_.expo.android||{},_.expo.android.package=n.androidPackage),Ce.writeFileSync(p,JSON.stringify(_,null,2))}let y=["exec","--","expo","prebuild","--platform",t,"--no-install"];if(await s("prebuild"),await l("npm",y,process.cwd(),o()),t!=="ios"||!Ce.existsSync("ios"))return{appName:f,bundleId:c};await s("pods"),Oe.info(De.blue("Running pod install..."));try{let _=Ot.resolve("ios"),D=Ot.join(_,"Podfile");if(!Ce.existsSync(D))throw new Error("ios/Podfile not found. Skipping pod install.");let b=o();a(_,b);let L=Ce.readFileSync(D,"utf-8"),A=n.iosDeploymentTarget||"13.4";if(!n.developmentClient&&(Oe.info(De.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),L.includes("use_expo_modules!")&&!L.includes("exclude:"))){let C=/use_expo_modules!(\s*)$/m;C.test(L)?L=L.replace(C,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):L=L.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let B=`
567
589
  installer.generated_projects.each do |project|
568
590
  project.targets.each do |target|
569
591
  target.build_configurations.each do |config|
@@ -576,13 +598,13 @@ echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
576
598
  config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${A}'
577
599
  end
578
600
  end
579
- `,q=/post_install\s+do\s+\|installer\|/;if(q.test(x))Oe.info(De.dim(`Injecting deployment target (${A}) into existing post_install hook...`)),x=x.replace(q,`post_install do |installer|
580
- ${B}`),Ce.writeFileSync(D,x);else{Oe.info(De.dim(`Appending new post_install hook for deployment target (${A})...`));let C=`
601
+ `,q=/post_install\s+do\s+\|installer\|/;if(q.test(L))Oe.info(De.dim(`Injecting deployment target (${A}) into existing post_install hook...`)),L=L.replace(q,`post_install do |installer|
602
+ ${B}`),Ce.writeFileSync(D,L);else{Oe.info(De.dim(`Appending new post_install hook for deployment target (${A})...`));let C=`
581
603
  post_install do |installer|
582
604
  ${B}
583
605
  end
584
- `;Ce.appendFileSync(D,C)}let P="/opt/homebrew/bin/pod",I=Ce.existsSync(P)?P:"pod",T=c(_);Ce.existsSync(Ot.join(_,"Pods"))&&i.pods&&i.pods!==T&&(await e.reportLog(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
585
- `),Oe.info(De.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),Ce.rmSync(Ot.join(_,"Pods"),{recursive:!0,force:!0})),Oe.info(De.dim(`Using pod command: ${I} in ${_}`)),await l(I,["install"],_,b),i.pods=T,u(r,i)}catch(_){let D=_.message||"Unknown error";Oe.warn(De.yellow(`Native "pod" command failed: ${D}`)),Oe.info(De.dim("Falling back to npm exec pod-install..."));let b=o();a(Ot.resolve("ios"),b),Oe.info(De.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),b)}if(Ce.existsSync("ios/Pods")){Oe.info(De.dim("Disabling signing for Pod targets to prevent conflicts..."));try{Wa(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}return{appName:f,bundleId:d}}finally{g&&Ce.writeFileSync(p,g)}}};import{log as St}from"@clack/prompts";import yt from"chalk";import Ze from"fs";import Kt from"path";var Ya=(e,t)=>!Ze.existsSync(e)||!Ze.existsSync(t)?!1:Ze.readFileSync(e,"utf-8")!==Ze.readFileSync(t,"utf-8"),ri={id:"react-native",displayName:"React Native",applyLocalProcessEnv:e=>{delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE,delete process.env.EXPO_NO_DOTENV},localAndroidEnv:(e,t)=>({MACH_FRAMEWORK:"react-native",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
606
+ `;Ce.appendFileSync(D,C)}let P="/opt/homebrew/bin/pod",I=Ce.existsSync(P)?P:"pod",T=d(_);Ce.existsSync(Ot.join(_,"Pods"))&&i.pods&&i.pods!==T&&(await e.reportLog(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
607
+ `),Oe.info(De.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),Ce.rmSync(Ot.join(_,"Pods"),{recursive:!0,force:!0})),Oe.info(De.dim(`Using pod command: ${I} in ${_}`)),await l(I,["install"],_,b),i.pods=T,u(r,i)}catch(_){let D=_.message||"Unknown error";Oe.warn(De.yellow(`Native "pod" command failed: ${D}`)),Oe.info(De.dim("Falling back to npm exec pod-install..."));let b=o();a(Ot.resolve("ios"),b),Oe.info(De.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),b)}if(Ce.existsSync("ios/Pods")){Oe.info(De.dim("Disabling signing for Pod targets to prevent conflicts..."));try{Ja(`find ios/Pods -name "project.pbxproj" -exec sed -i '' 's/buildSettings = {/buildSettings = { CODE_SIGNING_ALLOWED = NO; CODE_SIGNING_REQUIRED = NO; PROVISIONING_PROFILE_SPECIFIER = ""; EXPANDED_CODE_SIGN_IDENTITY = "";/g' {} +`,{stdio:"ignore"})}catch{}}return{appName:f,bundleId:c}}finally{g&&Ce.writeFileSync(p,g)}}};import{log as St}from"@clack/prompts";import yt from"chalk";import Ze from"fs";import Kt from"path";var Xa=(e,t)=>!Ze.existsSync(e)||!Ze.existsSync(t)?!1:Ze.readFileSync(e,"utf-8")!==Ze.readFileSync(t,"utf-8"),ri={id:"react-native",displayName:"React Native",applyLocalProcessEnv:e=>{delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE,delete process.env.EXPO_NO_DOTENV},localAndroidEnv:(e,t)=>({MACH_FRAMEWORK:"react-native",MACH_BUILD_PROFILE:t}),remoteEnvSetupScript:()=>`
586
608
  export MACH_FRAMEWORK="react-native"
587
609
  echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
588
610
  unset EXPO_NO_DOTENV
@@ -597,22 +619,21 @@ echo "[PREBUILD] React Native framework configured. Skipping Expo prebuild."
597
619
  :
598
620
  `,androidRemoteReleaseGradlePropertiesScript:()=>`
599
621
  :
600
- `,prepareLocalProject:async e=>{let{platform:t,cacheMeta:n,cacheMetaDir:i,currentBuildEnv:r,reportStep:o,reportLog:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:c,writeCacheMeta:u}=e;if(t!=="ios")return{};let d=Kt.resolve("ios"),f=Kt.join(d,"Podfile");if(!Ze.existsSync(f))throw new Error("React Native iOS build requires ios/Podfile. Commit the ios directory for vanilla React Native projects.");await o("pods"),St.info(yt.blue("Running React Native pod install..."));let p=r();a(d,p);let g=Kt.join(d,"Pods"),y=Kt.join(d,"Podfile.lock"),_=Kt.join(g,"Manifest.lock"),D=Ze.existsSync(g),b=c(d);D&&n.reactNativePods&&n.reactNativePods!==b?(await s(`[CACHE] React Native Podfile/Podfile.lock changed - wiping ios/Pods
601
- `),St.info(yt.dim("React Native Podfile fingerprint changed - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0})):D&&Ya(y,_)&&(await s(`[CACHE] React Native Pods Manifest.lock is out of sync - wiping ios/Pods
602
- `),St.info(yt.dim("React Native Pods manifest is out of sync - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0}));let x="/opt/homebrew/bin/pod",A=Ze.existsSync(x)?x:"pod";try{St.info(yt.dim(`Using pod command: ${A} in ${d}`)),await l(A,["install"],d,p)}catch(B){let q=B.message||"Unknown error";St.warn(yt.yellow(`Native "pod" command failed: ${q}`)),St.info(yt.dim("Falling back to npx pod-install..."));let P=r();a(d,P),St.info(yt.magenta(`${m.nameUpper}_DEBUG: Executing pod-install fallback via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),P)}return n.reactNativePods=c(d),u(i,n),{}}};var Ja={expo:vr,"react-native":ri};function Qe(e){if(!e)return ri;if(e!=="flutter")return Ja[e];throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.')}var qa="mach-env-v2-js-bundle-cache",Za=new Set(["BUILD_ID","BUILD_NUMBER","ANDROID_VERSION_CODE","MACH_TOKEN","MACH_DEBUG","MACH_ENV_FINGERPRINT","CODEARTIFACT_AUTH_TOKEN","EXPO_ZQRN_BB_REPO_TOKEN","SENTRY_AUTH_TOKEN","IOS_DIST_P12","IOS_PROVISIONING_PROFILE","IOS_P12_PASSWORD","MATCH_ENCRYPTION_PASSPHRASE","MATCH_PASSWORD","MATCH_KEYCHAIN_NAME","MATCH_KEYCHAIN_PASSWORD","APPLE_TEAM_ID","FASTLANE_TEAM_ID","ANDROID_KEYSTORE","ANDROID_KEYSTORE_BASE64","ANDROID_STORE_PASSWORD","ANDROID_KEY_PASSWORD","ANDROID_KEY_ALIAS","KEYSTORE_PASSWORD","KEYSTORE_ALIAS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_SECURITY_TOKEN","GITHUB_TOKEN","NPM_TOKEN"]),Qa=["PRESIGNED_","KEYSTORE_PASSWORD_"],el=e=>!e||Za.has(e)?!1:!Qa.some(t=>e.startsWith(t)),bt=(e,t,n)=>{let i=Qe(n.framework);return{...e,...i.localAndroidEnv(n,t),MACH_APP_NAME:n.appName||n.name||"App"}},Dt=e=>{let t=Object.entries(e).filter(([n])=>el(n)).sort(([n],[i])=>n.localeCompare(i));return Xa.createHash("sha256").update(JSON.stringify({version:qa,entries:t})).digest("hex")};var oi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),si=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),nl=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),il=(e,t,n)=>{let i=n.MACH_ANDROID_RELEASE_ABIS||n.MACH_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_RELEASE_ABIS||n.MACH_PROFILE_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_ARCHITECTURES||n.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return i||(!!e.maestro||nl(t)||si(n.MACH_PROFILE_ANDROID_EMULATOR)||si(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||si(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Cr=async(e,t,n={},i,r)=>{let o=tl(),s=Qe(e.framework),l=e.buildProfile||"production",a=l==="production",c=e.apk===!0,u=e.developmentClient?"assembleDebug":a?"bundleRelease":"assembleRelease",d=e.buildCommand||(c?"assembleRelease":u),f=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
603
- `):"",p;if(r){let b=Dr.isAbsolute(r)?r:Dr.resolve(process.cwd(),r);Or.existsSync(b)?(p=Or.readFileSync(b,"utf-8"),mn.info(Pr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):mn.warn(`preBuild script not found at ${b} \u2014 skipping`)}let g=il(e,l,n),y={...bt(n,l,e),MACH_ANDROID_RELEASE_ABIS:g},_=Dt(y),D=$r.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,d).replace("{{NODE_VERSION_SETUP}}",f).replace("{{ENV_VARS}}",`
622
+ `,prepareLocalProject:async e=>{let{platform:t,cacheMeta:n,cacheMetaDir:i,currentBuildEnv:r,reportStep:o,reportLog:s,loggedRun:l,configureXcodeNodeBinary:a,podsFingerprint:d,writeCacheMeta:u}=e;if(t!=="ios")return{};let c=Kt.resolve("ios"),f=Kt.join(c,"Podfile");if(!Ze.existsSync(f))throw new Error("React Native iOS build requires ios/Podfile. Commit the ios directory for vanilla React Native projects.");await o("pods"),St.info(yt.blue("Running React Native pod install..."));let p=r();a(c,p);let g=Kt.join(c,"Pods"),y=Kt.join(c,"Podfile.lock"),_=Kt.join(g,"Manifest.lock"),D=Ze.existsSync(g),b=d(c);D&&n.reactNativePods&&n.reactNativePods!==b?(await s(`[CACHE] React Native Podfile/Podfile.lock changed - wiping ios/Pods
623
+ `),St.info(yt.dim("React Native Podfile fingerprint changed - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0})):D&&Xa(y,_)&&(await s(`[CACHE] React Native Pods Manifest.lock is out of sync - wiping ios/Pods
624
+ `),St.info(yt.dim("React Native Pods manifest is out of sync - clearing Pods for clean install...")),Ze.rmSync(g,{recursive:!0,force:!0}));let L="/opt/homebrew/bin/pod",A=Ze.existsSync(L)?L:"pod";try{St.info(yt.dim(`Using pod command: ${A} in ${c}`)),await l(A,["install"],c,p)}catch(B){let q=B.message||"Unknown error";St.warn(yt.yellow(`Native "pod" command failed: ${q}`)),St.info(yt.dim("Falling back to npx pod-install..."));let P=r();a(c,P),St.info(yt.magenta(`${m.nameUpper}_DEBUG: Executing pod-install fallback via npx --yes pod-install@latest`)),await l("npx",["--yes","pod-install@latest","ios"],process.cwd(),P)}return n.reactNativePods=d(c),u(i,n),{}}};var qa={expo:Or,"react-native":ri};function Qe(e){if(!e)return ri;if(e!=="flutter")return qa[e];throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.')}var Qa="mach-env-v2-js-bundle-cache",el=new Set(["BUILD_ID","BUILD_NUMBER","ANDROID_VERSION_CODE","MACH_TOKEN","MACH_DEBUG","MACH_S3_DEBUG","MACH_ENV_FINGERPRINT","CODEARTIFACT_AUTH_TOKEN","EXPO_ZQRN_BB_REPO_TOKEN","SENTRY_AUTH_TOKEN","IOS_DIST_P12","IOS_PROVISIONING_PROFILE","IOS_P12_PASSWORD","MATCH_ENCRYPTION_PASSPHRASE","MATCH_PASSWORD","MATCH_KEYCHAIN_NAME","MATCH_KEYCHAIN_PASSWORD","APPLE_TEAM_ID","FASTLANE_TEAM_ID","ANDROID_KEYSTORE","ANDROID_KEYSTORE_BASE64","ANDROID_STORE_PASSWORD","ANDROID_KEY_PASSWORD","ANDROID_KEY_ALIAS","KEYSTORE_PASSWORD","KEYSTORE_ALIAS","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","AWS_SECURITY_TOKEN","GITHUB_TOKEN","NPM_TOKEN"]),tl=["PRESIGNED_","KEYSTORE_PASSWORD_"],nl=e=>!e||el.has(e)?!1:!tl.some(t=>e.startsWith(t)),bt=(e,t,n)=>{let i=Qe(n.framework);return{...e,...i.localAndroidEnv(n,t),MACH_APP_NAME:n.appName||n.name||"App"}},Dt=e=>{let t=Object.entries(e).filter(([n])=>nl(n)).sort(([n],[i])=>n.localeCompare(i));return Za.createHash("sha256").update(JSON.stringify({version:Qa,entries:t})).digest("hex")};var oi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),si=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),rl=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),ol=(e,t,n)=>{let i=n.MACH_ANDROID_RELEASE_ABIS||n.MACH_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_RELEASE_ABIS||n.MACH_PROFILE_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_ARCHITECTURES||n.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return i||(!!e.maestro||rl(t)||si(n.MACH_PROFILE_ANDROID_EMULATOR)||si(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||si(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Tr=async(e,t,n={},i,r)=>{let o=il(),s=Qe(e.framework),l=e.buildProfile||"production",a=l==="production",d=e.apk===!0,u=e.developmentClient?"assembleDebug":a?"bundleRelease":"assembleRelease",c=e.buildCommand||(d?"assembleRelease":u),f=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,`CURRENT_MAJOR=$(node -e "process.stdout.write(process.version.split('.')[0].replace('v',''))" 2>/dev/null || echo "0")`,`if [ "$CURRENT_MAJOR" != "${e.nodeVersion}" ]; then`,` curl -fsSL https://deb.nodesource.com/setup_${e.nodeVersion}.x | bash - 2>&1`," apt-get install -y nodejs 2>&1",' echo "[NODE] Installed Node $(node -v)"',"else",' echo "[NODE] Already on Node $(node -v) \u2014 no switch needed"',"fi"].join(`
625
+ `):"",p;if(r){let b=Nr.isAbsolute(r)?r:Nr.resolve(process.cwd(),r);Cr.existsSync(b)?(p=Cr.readFileSync(b,"utf-8"),mn.info(Dr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):mn.warn(`preBuild script not found at ${b} \u2014 skipping`)}let g=ol(e,l,n),y={...bt(n,l,e),MACH_ANDROID_RELEASE_ABIS:g},_=Dt(y),D=Pr.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,c).replace("{{NODE_VERSION_SETUP}}",f).replace("{{ENV_VARS}}",`
604
626
  export MACH_APP_NAME="${oi(y.MACH_APP_NAME)}"
605
627
  export MACH_BUILD_PROFILE="${oi(l)}"
606
628
  export MACH_ANDROID_RELEASE_ABIS="${oi(g)}"
607
629
  export MACH_ENV_FINGERPRINT="${_}"
608
630
  ${s.remoteEnvSetupScript().trim()}
609
631
  {{ENV_VARS}}
610
- `).replace("{{FRAMEWORK_ANDROID_VERSION_CODE}}",s.androidRemoteVersionCodeScript().trim()).replace("{{FRAMEWORK_ANDROID_PREBUILD}}",s.androidRemotePrebuildScript().trim()).replace("{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}",s.androidRemoteGradlePropertiesScript().trim()).replace("{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}",s.androidRemoteReleaseGradlePropertiesScript().trim());if(e.dryRun){mn.info("User Data Script (dry run):"),console.log(D);return}o.start("Requesting cloud build instance...");try{let b=await k.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:d,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:n,dryRun:e.dryRun,userDataScript:D,preBuildScriptContent:p});if(b.data.status!=="success")throw new Error(b.data.message||"Failed to launch build instance");let x=b.data.instanceId;return o.stop("Build Started"),mn.success(Pr.green(`Build initiated on cloud instance (${x}).`)),{instanceId:x}}catch(b){o.stop("Android Build Failed");let x=b.response?.data?.message||b.message;throw new Error(`Failed to launch Android build: ${x}`)}};import{spinner as rl,log as Et}from"@clack/prompts";import et from"chalk";import ol from"fs";import{execSync as Vt}from"child_process";var Nr=`#!/bin/bash
632
+ `).replace("{{FRAMEWORK_ANDROID_VERSION_CODE}}",s.androidRemoteVersionCodeScript().trim()).replace("{{FRAMEWORK_ANDROID_PREBUILD}}",s.androidRemotePrebuildScript().trim()).replace("{{FRAMEWORK_ANDROID_GRADLE_PROPERTIES}}",s.androidRemoteGradlePropertiesScript().trim()).replace("{{FRAMEWORK_ANDROID_RELEASE_GRADLE_PROPERTIES}}",s.androidRemoteReleaseGradlePropertiesScript().trim());if(e.dryRun){mn.info("User Data Script (dry run):"),console.log(D);return}o.start("Requesting cloud build instance...");try{let b=await k.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:c,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:n,dryRun:e.dryRun,userDataScript:D,preBuildScriptContent:p});if(b.data.status!=="success")throw new Error(b.data.message||"Failed to launch build instance");let L=b.data.instanceId;return o.stop("Build Started"),mn.success(Dr.green(`Build initiated on cloud instance (${L}).`)),{instanceId:L}}catch(b){o.stop("Android Build Failed");let L=b.response?.data?.message||b.message;throw new Error(`Failed to launch Android build: ${L}`)}};import{spinner as sl,log as Et}from"@clack/prompts";import et from"chalk";import al from"fs";import{execSync as Vt}from"child_process";var kr=`#!/bin/bash
611
633
  # --- Mach Cloud Build Script (iOS) ---
612
634
  # All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
613
635
 
614
636
  exec > >(tee -a "{{REMOTE_DIR}}/build-log.txt") 2>&1
615
- set -x
616
637
  set -e
617
638
  set -o pipefail
618
639
 
@@ -639,6 +660,25 @@ BUILD_ID="{{BUILD_ID}}"
639
660
  BUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
640
661
  echo "[CACHE] Build environment hash: \${BUILD_ENV_HASH:0:12}"
641
662
 
663
+ function log_s3_target() {
664
+ local LABEL="$1"
665
+ local URL="$2"
666
+ case "\${MACH_S3_DEBUG:-}" in
667
+ 1|true|TRUE|yes|YES|on|ON) ;;
668
+ *) return 0 ;;
669
+ esac
670
+ if [ -z "$URL" ]; then
671
+ return 0
672
+ fi
673
+ local HOST
674
+ HOST=$(printf '%s' "$URL" | sed -E 's#^https?://([^/?]+).*#\\1#')
675
+ echo "[S3_DEBUG] $LABEL host=$HOST expected_region=ap-south-1"
676
+ case "$HOST" in
677
+ *ap-south-1*) ;;
678
+ *) echo "[S3_DEBUG] WARNING: $LABEL host does not include ap-south-1" ;;
679
+ esac
680
+ }
681
+
642
682
  # Start log uploader (every 15s via presigned URL, only if changed)
643
683
  (
644
684
  LAST_HASH=""
@@ -1250,10 +1290,12 @@ rm derived_data.tar.gz
1250
1290
 
1251
1291
  # Upload Artifacts via presigned URLs
1252
1292
  if [ -f "build.ipa" ] && [ ! -z "$PRESIGNED_ARTIFACT_IPA_UPLOAD" ]; then
1293
+ log_s3_target "IOS_IPA_UPLOAD" "$PRESIGNED_ARTIFACT_IPA_UPLOAD"
1253
1294
  curl -X PUT -T build.ipa "$PRESIGNED_ARTIFACT_IPA_UPLOAD" --silent
1254
1295
  fi
1255
1296
 
1256
1297
  if [ -f "build.app.zip" ] && [ ! -z "$PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD" ]; then
1298
+ log_s3_target "IOS_APP_ZIP_UPLOAD" "$PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD"
1257
1299
  curl -X PUT -T build.app.zip "$PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD" --silent
1258
1300
  fi
1259
1301
 
@@ -1267,55 +1309,55 @@ touch done
1267
1309
  if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
1268
1310
  curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
1269
1311
  fi
1270
- `;var Tr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),kr=async(e,t,n={},i)=>{let r=rl(),o=Qe(e.framework);e.sshHost||(e.sshHost="localhost",Et.message(et.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${et.cyan(e.sshHost)}...`);let s=e.sshUser||process.env.USER||"ubuntu",l=e.sshKey,a=`${s}@${e.sshHost}`,c=`ssh ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no ${a}`,u=`scp ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no`;try{let d=s==="ubuntu"?"/home/ubuntu":`/Users/${s}`,f=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${m.remoteWorkspacesDir}/${f}`;r.message(`Preparing stable workspace: ${p}...`),Vt(`${c} "mkdir -p ${p}"`,{stdio:"inherit"}),r.message("Transferring source code...");let g=`/tmp/${m.nameLower}-source-${t}.zip`;Vt(`${u} ${g} ${a}:${p}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${p}/api_key.p8`:"",_="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Vt(`${u} ${e.iosApiKeyPath} ${a}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(_=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let D={};if(i)try{let h=await k.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});h.data.status==="success"&&(D=h.data.urls)}catch(h){Et.warn(et.yellow(`Could not fetch build URLs: ${h.message}`))}let b="";if(D.credentials&&D.credentials.length>0)for(let h of D.credentials)h.type==="p12"?b+=`curl -sf -o "$CERT_DIR/${h.name}" "${h.downloadUrl}" || true
1312
+ `;var Lr=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),xr=async(e,t,n={},i)=>{let r=sl(),o=Qe(e.framework);e.sshHost||(e.sshHost="localhost",Et.message(et.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${et.cyan(e.sshHost)}...`);let s=e.sshUser||process.env.USER||"ubuntu",l=e.sshKey,a=`${s}@${e.sshHost}`,d=`ssh ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no ${a}`,u=`scp ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no`;try{let c=s==="ubuntu"?"/home/ubuntu":`/Users/${s}`,f=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${c}/${m.remoteWorkspacesDir}/${f}`;r.message(`Preparing stable workspace: ${p}...`),Vt(`${d} "mkdir -p ${p}"`,{stdio:"inherit"}),r.message("Transferring source code...");let g=`/tmp/${m.nameLower}-source-${t}.zip`;Vt(`${u} ${g} ${a}:${p}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${p}/api_key.p8`:"",_="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Vt(`${u} ${e.iosApiKeyPath} ${a}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(_=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let D={};if(i)try{let h=await k.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});h.data.status==="success"&&(D=h.data.urls)}catch(h){Et.warn(et.yellow(`Could not fetch build URLs: ${h.message}`))}let b="";if(D.credentials&&D.credentials.length>0)for(let h of D.credentials)h.type==="p12"?b+=`curl -sf -o "$CERT_DIR/${h.name}" "${h.downloadUrl}" || true
1271
1313
  `:h.type==="mobileprovision"&&(b+=`curl -sf -o "$PROV_TEMP/${h.name}" "${h.downloadUrl}" || true
1272
- `);r.message("Generating macOS build script...");let x=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
1273
- `:"";if(n)for(let[h,M]of Object.entries(n)){let U=M.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");x+=`export ${h}="${U}"
1274
- `}let A=e.buildProfile||"production",B=bt(n,A,e),q=Dt(B);Et.info(et.dim(`iOS remote build config: simulator=${String(!!e.simulator)}, configuration=${e.iosConfiguration||"Release"}, scheme=${e.iosScheme||"auto"}`));let P=[x,D.logUpload?`export PRESIGNED_LOG_UPLOAD="${D.logUpload}"`:"",D.doneMarker?`export PRESIGNED_DONE_MARKER="${D.doneMarker}"`:"",D.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${D.cacheDerivedDataDownload}"`:"",D.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${D.cacheDerivedDataUpload}"`:"",D.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${D.cacheNodeModulesDownload}"`:"",D.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${D.cacheNodeModulesUpload}"`:"",D.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${D.cachePodsDownload}"`:"",D.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${D.cachePodsUpload}"`:"",D.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${D.artifactIpaUpload}"`:"",D.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${D.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Tr(A)}"`,`export MACH_APP_NAME="${Tr(B.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${q}"`,o.remoteEnvSetupScript().trim(),`export ${m.envPrefix}PROJECT_ID="${f}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
1314
+ `);r.message("Generating macOS build script...");let L=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
1315
+ `:"";if(n)for(let[h,M]of Object.entries(n)){let U=M.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");L+=`export ${h}="${U}"
1316
+ `}let A=e.buildProfile||"production",B=bt(n,A,e),q=Dt(B);Et.info(et.dim(`iOS remote build config: simulator=${String(!!e.simulator)}, configuration=${e.iosConfiguration||"Release"}, scheme=${e.iosScheme||"auto"}`));let P=[L,D.logUpload?`export PRESIGNED_LOG_UPLOAD="${D.logUpload}"`:"",D.doneMarker?`export PRESIGNED_DONE_MARKER="${D.doneMarker}"`:"",D.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${D.cacheDerivedDataDownload}"`:"",D.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${D.cacheDerivedDataUpload}"`:"",D.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${D.cacheNodeModulesDownload}"`:"",D.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${D.cacheNodeModulesUpload}"`:"",D.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${D.cachePodsDownload}"`:"",D.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${D.cachePodsUpload}"`:"",D.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${D.artifactIpaUpload}"`:"",D.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${D.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Lr(A)}"`,`export MACH_APP_NAME="${Lr(B.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${q}"`,o.remoteEnvSetupScript().trim(),`export ${m.envPrefix}PROJECT_ID="${f}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
1275
1317
  `),I=e.nodeVersion?[`echo "[NODE] Switching to Node ${e.nodeVersion}..."`,'export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" --no-use',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion} --silent`,`export PATH="$NVM_DIR/versions/node/$(nvm version ${e.nodeVersion})/bin:$PATH"`,'echo "[NODE] Now using: $(node -v) at $(which node)"'].join(`
1276
- `):"",T=Nr,w={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":P,"{{CREDENTIAL_DOWNLOADS}}":b,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":_,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":I,"{{FRAMEWORK_PREBUILD}}":o.iosRemotePrebuildScript().trim()};Object.entries(w).forEach(([h,M])=>{T=T.split(h).join(M)});let C=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(ol.writeFileSync(C,T),Vt(`${u} ${C} ${a}:${p}/build.sh`),r.stop("Remote script uploaded."),Et.info(et.cyan("Executing remote build. This might take a while...")),Vt(`${c} "bash ${p}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let M=(await k.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],U=e.simulator===!0;if(M.length===0&&!U)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),M.length>0){Et.success("Build Artifacts Ready:");for(let j of M)console.log(`
1318
+ `):"",T=kr,w={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":P,"{{CREDENTIAL_DOWNLOADS}}":b,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":_,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":I,"{{FRAMEWORK_PREBUILD}}":o.iosRemotePrebuildScript().trim()};Object.entries(w).forEach(([h,M])=>{T=T.split(h).join(M)});let C=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(al.writeFileSync(C,T),Vt(`${u} ${C} ${a}:${p}/build.sh`),r.stop("Remote script uploaded."),Et.info(et.cyan("Executing remote build. This might take a while...")),Vt(`${d} "bash ${p}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let M=(await k.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],U=e.simulator===!0;if(M.length===0&&!U)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),M.length>0){Et.success("Build Artifacts Ready:");for(let j of M)console.log(`
1277
1319
  ${et.yellow(j.name)}:
1278
1320
  ${et.cyan(j.downloadUrl)}`);console.log(`
1279
- ${et.dim("Note: Links are valid for 7 days.")}`)}else U&&Et.warn("Simulator build completed. No artifacts uploaded.")}catch(h){r.stop("Could not fetch artifacts"),Et.warn(et.yellow(`Artifact listing failed: ${h.message}`))}}}catch(d){throw r.stop("iOS Build Failed"),d}};import sl from"crypto";import He from"axios";import xr from"fs";var Xe=6e4,al=12e4,ai=4,tt=e=>encodeURIComponent(e),ll=e=>new Promise(t=>setTimeout(t,e));async function je(e,t){let n;for(let i=1;i<=ai;i++)try{return await t()}catch(r){if(n=r,i>=ai||!dl(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${ai}); retrying in ${Math.round(s/1e3)}s...`),await ll(s)}throw n}function dl(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Lr(e,t){let n;try{let i=await gn(t),r=tt(e);if(n=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=tt(n),l=0,c=(await je("list tracks",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let f of d.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}try{let d=(await je("list bundles",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.bundles||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let d=(await je("list APKs",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.apks||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await gn(t);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(e)}/edits/${tt(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))}catch{}}}async function Mr(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await gn(n)}`,Connection:"close"},d=tt(t);if(a=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Xe}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=tt(a),g=xr.statSync(i),y=await je("upload AAB",()=>He.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${p}/bundles`,xr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":g.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:al})),_=Number(y.data.versionCode);if(!_)throw new Error("Google Play upload succeeded but did not return a versionCode.");let D={versionCodes:[String(_)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(D.userFraction=s),await je("update track",()=>He.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}/tracks/${tt(r)}`,{releases:[D]},{headers:u,timeout:Xe})),await je("commit edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Xe})),{editId:a,versionCode:_,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await gn(n);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(t)}/edits/${tt(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Xe}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function gn(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=sl.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await je("OAuth token exchange",()=>He.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Xe}))).data.access_token}import cl from"crypto";import Ur from"axios";var di="https://api.appstoreconnect.apple.com/v1",Fr=6e4,li=4,ul=e=>new Promise(t=>setTimeout(t,e));function pl(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=cl.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function fl(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Br(e,t){let n;for(let i=1;i<=li;i++)try{return await t()}catch(r){if(n=r,i>=li||!fl(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${li}); retrying in ${Math.round(s/1e3)}s...`),await ul(s)}throw n}function Hr(e){return{Authorization:`Bearer ${pl(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function ml(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function hn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function gl(e,t){let n=hn(e),i=hn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function hl(e){let t=hn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Sl(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await Br("lookup app by bundle ID",()=>Ur.get(`${di}/apps`,{headers:Hr(e),params:{"filter[bundleId]":n,limit:1},timeout:Fr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function jr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Sl(t,e.ascAppId,e.bundleId),i=`${di}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await Br("list builds",()=>Ur.get(i,{headers:Hr(t),params:i===`${di}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Fr})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();hn(u)&&gl(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:hl(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${ml(n)}`)}}import{spinner as yn,log as O,isCancel as bn,confirm as yl,select as ui}from"@clack/prompts";import R from"chalk";import S from"fs";import E from"path";import{execFileSync as nt,execSync as te,spawn as Yr}from"child_process";import Ae from"os";import bl from"crypto";var Jr=(e,t)=>t.filter(n=>S.existsSync(E.join(e,n))).reduce((n,i)=>n.update(S.readFileSync(E.join(e,i))),bl.createHash("sha256")).digest("hex").slice(0,16),El=e=>Jr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Al=e=>Jr(e,["Podfile","Podfile.lock"]),Il=e=>{let t=E.join(e,"fingerprint.json");try{return JSON.parse(S.readFileSync(t,"utf-8"))}catch{return{}}},Gr=(e,t)=>{S.mkdirSync(e,{recursive:!0}),S.writeFileSync(E.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},wl=7200*1e3,_l=(e,t)=>{S.mkdirSync(e,{recursive:!0});let n=E.join(e,"build.lock");if(S.existsSync(n))try{let i=JSON.parse(S.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<wl)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}S.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Rl=(e,t)=>{let n=E.join(e,"build.lock");try{S.existsSync(n)&&JSON.parse(S.readFileSync(n,"utf-8")).buildId===t&&S.unlinkSync(n)}catch{}},Kr=15e5,Vr=(e,t)=>{let n=e+t;return n.length>Kr?n.slice(-Kr):n},Xr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),qr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),$l=e=>{let t=new Set,n=[];e.forEach((r,o)=>{qr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},vl=(e,t,n,i)=>{let r=Xr(i).replace(/\r/g,`
1321
+ ${et.dim("Note: Links are valid for 7 days.")}`)}else U&&Et.warn("Simulator build completed. No artifacts uploaded.")}catch(h){r.stop("Could not fetch artifacts"),Et.warn(et.yellow(`Artifact listing failed: ${h.message}`))}}}catch(c){throw r.stop("iOS Build Failed"),c}};import ll from"crypto";import He from"axios";import Mr from"fs";var Xe=6e4,cl=12e4,ai=4,tt=e=>encodeURIComponent(e),dl=e=>new Promise(t=>setTimeout(t,e));async function je(e,t){let n;for(let i=1;i<=ai;i++)try{return await t()}catch(r){if(n=r,i>=ai||!ul(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${ai}); retrying in ${Math.round(s/1e3)}s...`),await dl(s)}throw n}function ul(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Ur(e,t){let n;try{let i=await gn(t),r=tt(e);if(n=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=tt(n),l=0,d=(await je("list tracks",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.tracks||[];for(let u of d)if(u.releases){for(let c of u.releases)if(c.versionCodes)for(let f of c.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}try{let c=(await je("list bundles",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.bundles||[];for(let f of c)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let c=(await je("list APKs",()=>He.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))).data.apks||[];for(let f of c)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await gn(t);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(e)}/edits/${tt(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Xe}))}catch{}}}async function Fr(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await gn(n)}`,Connection:"close"},c=tt(t);if(a=(await je("create edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits`,{},{headers:u,timeout:Xe}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=tt(a),g=Mr.statSync(i),y=await je("upload AAB",()=>He.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${c}/edits/${p}/bundles`,Mr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":g.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:cl})),_=Number(y.data.versionCode);if(!_)throw new Error("Google Play upload succeeded but did not return a versionCode.");let D={versionCodes:[String(_)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(D.userFraction=s),await je("update track",()=>He.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${p}/tracks/${tt(r)}`,{releases:[D]},{headers:u,timeout:Xe})),await je("commit edit",()=>He.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${c}/edits/${p}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Xe})),{editId:a,versionCode:_,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let c=await gn(n);await je("delete edit",()=>He.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${tt(t)}/edits/${tt(a)}`,{headers:{Authorization:`Bearer ${c}`,Connection:"close"},timeout:Xe}))}catch{}let u=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${u}`)}}async function gn(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=ll.createSign("RSA-SHA256");a.update(l);let d=a.sign(e.private_key,"base64url"),u=`${l}.${d}`;return(await je("OAuth token exchange",()=>He.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Xe}))).data.access_token}import pl from"crypto";import Br from"axios";var ci="https://api.appstoreconnect.apple.com/v1",Hr=6e4,li=4,fl=e=>new Promise(t=>setTimeout(t,e));function ml(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=pl.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function gl(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function jr(e,t){let n;for(let i=1;i<=li;i++)try{return await t()}catch(r){if(n=r,i>=li||!gl(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${li}); retrying in ${Math.round(s/1e3)}s...`),await fl(s)}throw n}function Gr(e){return{Authorization:`Bearer ${ml(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function hl(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function hn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function Sl(e,t){let n=hn(e),i=hn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function yl(e){let t=hn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function bl(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await jr("lookup app by bundle ID",()=>Br.get(`${ci}/apps`,{headers:Gr(e),params:{"filter[bundleId]":n,limit:1},timeout:Hr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function Kr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await bl(t,e.ascAppId,e.bundleId),i=`${ci}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await jr("list builds",()=>Br.get(i,{headers:Gr(t),params:i===`${ci}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Hr})),a=l.data?.data||[];for(let d of a){let u=String(d.attributes?.version||"").trim();hn(u)&&Sl(u,r)>0&&(r=u,o=d.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:yl(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${hl(n)}`)}}import{spinner as yn,log as O,isCancel as bn,confirm as El,select as ui}from"@clack/prompts";import R from"chalk";import S from"fs";import E from"path";import{execFileSync as nt,execSync as te,spawn as Xr}from"child_process";import Ae from"os";import Al from"crypto";var qr=(e,t)=>t.filter(n=>S.existsSync(E.join(e,n))).reduce((n,i)=>n.update(S.readFileSync(E.join(e,i))),Al.createHash("sha256")).digest("hex").slice(0,16),Il=e=>qr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),wl=e=>qr(e,["Podfile","Podfile.lock"]),_l=e=>{let t=E.join(e,"fingerprint.json");try{return JSON.parse(S.readFileSync(t,"utf-8"))}catch{return{}}},Vr=(e,t)=>{S.mkdirSync(e,{recursive:!0}),S.writeFileSync(E.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Rl=7200*1e3,$l=(e,t)=>{S.mkdirSync(e,{recursive:!0});let n=E.join(e,"build.lock");if(S.existsSync(n))try{let i=JSON.parse(S.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<Rl)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}S.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},vl=(e,t)=>{let n=E.join(e,"build.lock");try{S.existsSync(n)&&JSON.parse(S.readFileSync(n,"utf-8")).buildId===t&&S.unlinkSync(n)}catch{}},zr=15e5,Wr=(e,t)=>{let n=e+t;return n.length>zr?n.slice(-zr):n},Zr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Qr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),Pl=e=>{let t=new Set,n=[];e.forEach((r,o)=>{Qr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},Ol=(e,t,n,i)=>{let r=Zr(i).replace(/\r/g,`
1280
1322
  `).split(`
1281
- `).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(qr),s=o.length>0?$l(r):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${n}: ${e} ${t.join(" ")}`,s.length>0?`
1323
+ `).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(Qr),s=o.length>0?Pl(r):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${n}: ${e} ${t.join(" ")}`,s.length>0?`
1282
1324
  ${l}:
1283
1325
  ${s.join(`
1284
- `)}`:""].join("")},Pl=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Ol=e=>{let t=Xr(e).trim();return t?/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|CFBundleVersion|ARCHIVE SUCCEEDED|ARCHIVE FAILED|EXPORT SUCCEEDED|EXPORT FAILED|Exported .* to:|\[IPA VALID\]/i.test(t):!1},ke=e=>{try{S.existsSync(e)&&S.rmSync(e,{recursive:!0,force:!0})}catch{}},Dl=(e,t)=>{try{if(!S.existsSync(e))return;for(let n of S.readdirSync(e))t(n)&&ke(E.join(e,n))}catch{}},ci=e=>{O.info(R.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();Dl(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),ke(E.join(e,".expo")),ke(E.join(e,"node_modules/.cache/metro")),ke(E.join(Ae.homedir(),".cache/metro")),ke(E.join(Ae.homedir(),".cache/react-native-packager")),ke(E.join(Ae.homedir(),"Library/Caches/metro")),ke(E.join(Ae.homedir(),"Library/Caches/react-native-packager"))},Cl=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),Nl=e=>{O.warn(R.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),ke(E.join(e,"Build")),ke(E.join(e,"Index.noindex")),ke(E.join(e,"ModuleCache.noindex")),ke(E.join(e,"SourcePackages"))},Tl=e=>{let t=String(e?.message||e);return/Permission denied/i.test(t)&&/Pods\/.*\.sh/i.test(t)},Zr=e=>{let t=E.join(e,"Pods"),i=[E.join(t,"Target Support Files"),t].filter(l=>S.existsSync(l)),r=new Set,o=0,s=l=>{let a=l;try{a=S.realpathSync(l)}catch{}if(r.has(a))return;r.add(a);let c;try{c=S.readdirSync(l,{withFileTypes:!0})}catch{return}for(let u of c){let d=E.join(l,u.name);if(u.isDirectory()){s(d);continue}if(!(!u.isFile()||!u.name.endsWith(".sh")))try{let f=S.statSync(d),p=f.mode|493;p!==f.mode&&(S.chmodSync(d,p),o+=1)}catch{}}};for(let l of i)s(l);return o>0&&O.info(R.dim(`Repaired executable permissions on ${o} CocoaPods script${o===1?"":"s"}.`)),o},kl=(e,t,n,i,r)=>{let o=a=>{let c=a.filter(d=>d?.id&&String(d?.platform||"").includes("iOS Simulator")&&!d?.error),u=c.find(d=>/iphone/i.test(d.name||""))||c[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let c=[],u=!1;for(let d of a.split(`
1285
- `)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let f=d.match(/\bid:([^,}]+)/)?.[1]?.trim(),p=d.match(/\bname:([^,}]+)/)?.[1]?.trim();f&&c.push({id:f,name:p,platform:"iOS Simulator"})}return o(c)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=nt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),c=JSON.parse(a),u=Array.isArray(c.destinations)?c.destinations:Array.isArray(c.availableDestinations)?c.availableDestinations:[],d=o(u);if(d)return d}catch{}try{let a=nt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},it=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",c=Pl(e),u=Date.now(),d=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",E.join(Ae.homedir(),".npm-global/bin")],p=[...(process.env.PATH||"").split(":"),...d].filter((b,x,A)=>b&&A.indexOf(b)===x).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(R.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${p}`));let g={...process.env,...i,PATH:p,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(R.magenta(`[ENVIRONMENT] node: ${process.execPath}
1326
+ `)}`:""].join("")},Dl=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",Cl=e=>{let t=Zr(e).trim();return t?/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|CFBundleVersion|ARCHIVE SUCCEEDED|ARCHIVE FAILED|EXPORT SUCCEEDED|EXPORT FAILED|Exported .* to:|\[IPA VALID\]/i.test(t):!1},ke=e=>{try{S.existsSync(e)&&S.rmSync(e,{recursive:!0,force:!0})}catch{}},Nl=(e,t)=>{try{if(!S.existsSync(e))return;for(let n of S.readdirSync(e))t(n)&&ke(E.join(e,n))}catch{}},di=e=>{O.info(R.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ae.tmpdir();Nl(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),ke(E.join(e,".expo")),ke(E.join(e,"node_modules/.cache/metro")),ke(E.join(Ae.homedir(),".cache/metro")),ke(E.join(Ae.homedir(),".cache/react-native-packager")),ke(E.join(Ae.homedir(),"Library/Caches/metro")),ke(E.join(Ae.homedir(),"Library/Caches/react-native-packager"))},Tl=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),kl=e=>{O.warn(R.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),ke(E.join(e,"Build")),ke(E.join(e,"Index.noindex")),ke(E.join(e,"ModuleCache.noindex")),ke(E.join(e,"SourcePackages"))},Ll=e=>{let t=String(e?.message||e);return/Permission denied/i.test(t)&&/Pods\/.*\.sh/i.test(t)},eo=e=>{let t=E.join(e,"Pods"),i=[E.join(t,"Target Support Files"),t].filter(l=>S.existsSync(l)),r=new Set,o=0,s=l=>{let a=l;try{a=S.realpathSync(l)}catch{}if(r.has(a))return;r.add(a);let d;try{d=S.readdirSync(l,{withFileTypes:!0})}catch{return}for(let u of d){let c=E.join(l,u.name);if(u.isDirectory()){s(c);continue}if(!(!u.isFile()||!u.name.endsWith(".sh")))try{let f=S.statSync(c),p=f.mode|493;p!==f.mode&&(S.chmodSync(c,p),o+=1)}catch{}}};for(let l of i)s(l);return o>0&&O.info(R.dim(`Repaired executable permissions on ${o} CocoaPods script${o===1?"":"s"}.`)),o},xl=(e,t,n,i,r)=>{let o=a=>{let d=a.filter(c=>c?.id&&String(c?.platform||"").includes("iOS Simulator")&&!c?.error),u=d.find(c=>/iphone/i.test(c.name||""))||d[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let d=[],u=!1;for(let c of a.split(`
1327
+ `)){if(/Ineligible destinations/i.test(c)&&(u=!0),u||!c.includes("platform:iOS Simulator")||c.includes("error:"))continue;let f=c.match(/\bid:([^,}]+)/)?.[1]?.trim(),p=c.match(/\bname:([^,}]+)/)?.[1]?.trim();f&&d.push({id:f,name:p,platform:"iOS Simulator"})}return o(d)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=nt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),d=JSON.parse(a),u=Array.isArray(d.destinations)?d.destinations:Array.isArray(d.availableDestinations)?d.availableDestinations:[],c=o(u);if(c)return c}catch{}try{let a=nt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},it=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",d=Dl(e),u=Date.now(),c=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",E.join(Ae.homedir(),".npm-global/bin")],p=[...(process.env.PATH||"").split(":"),...c].filter((b,L,A)=>b&&A.indexOf(b)===L).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(R.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${p}`));let g={...process.env,...i,PATH:p,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(R.magenta(`[ENVIRONMENT] node: ${process.execPath}
1286
1328
  `)),r(R.magenta(`[ENVIRONMENT] PATH: ${p}
1287
1329
  `)),r(R.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
1288
- `)));let y=e;if(["node","npm","npx","pod"].includes(e)){let b=E.dirname(process.execPath),x=E.join(b,e);S.existsSync(x)&&(y=x,r&&r(R.dim(`[EXEC] Using absolute path: ${y}
1289
- `)))}let _=Yr(y,t,{stdio:"pipe",cwd:n,shell:!0,env:g,detached:process.platform!=="win32"});if(o){if(o.aborted){if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}l(new Error("Command aborted"))})}let D=(b,x)=>{if(!c){x.write(b);return}let A=b.replace(/\r/g,`
1330
+ `)));let y=e;if(["node","npm","npx","pod"].includes(e)){let b=E.dirname(process.execPath),L=E.join(b,e);S.existsSync(L)&&(y=L,r&&r(R.dim(`[EXEC] Using absolute path: ${y}
1331
+ `)))}let _=Xr(y,t,{stdio:"pipe",cwd:n,shell:!0,env:g,detached:process.platform!=="win32"});if(o){if(o.aborted){if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(_.pid)try{process.kill(-_.pid,"SIGTERM")}catch{_.kill()}l(new Error("Command aborted"))})}let D=(b,L)=>{if(!d){L.write(b);return}let A=b.replace(/\r/g,`
1290
1332
  `).split(`
1291
- `).filter(Ol);if(A.length>0){x.write(`${A.join(`
1333
+ `).filter(Cl);if(A.length>0){L.write(`${A.join(`
1292
1334
  `)}
1293
- `),u=Date.now();return}let B=Date.now();B-u>3e4&&(x.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
1294
- `),u=B)};_.stdout.on("data",b=>{let x=b.toString();a=Vr(a,x),D(x,process.stdout),r&&r(x)}),_.stderr.on("data",b=>{let x=b.toString();a=Vr(a,x),D(x,process.stderr),r&&r(x)}),_.on("close",b=>{b===0?s(b):l(new Error(vl(e,t,b,a)))}),_.on("error",b=>l(b))}),Sn=async(e,t,n,i,r)=>{try{await it("xcodebuild",e,t,n,i,r)}catch(o){if(!Tl(o))throw o;O.warn(R.yellow("CocoaPods script permission denied. Repairing Pods script permissions and retrying xcodebuild once...")),Zr(t),await it("xcodebuild",e,t,n,i,r)}},xl=e=>{let t=Math.floor(e/1e3%60),n=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),r=[];return i>0&&r.push(`${i}h`),n>0&&r.push(`${n}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},At=(e,t)=>{let n=[];try{if(!S.existsSync(e))return n;let i=S.readdirSync(e);for(let r of i){let o=E.join(e,r);try{let s=S.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(E.resolve(o));continue}s.isDirectory()&&(n=n.concat(At(o,t)))}catch{}}}catch{}return n},Ll=/^\d+(?:\.\d+){0,2}$/,pi=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:Ll.test(t)?t:null},Qr=(e,t)=>{let n=pi(e);if(!n)throw new Error(`Invalid iOS CFBundleVersion from ${t}: "${e||""}". Apple requires one to three period-separated integers, for example "42" or "1.2.3". If you see "[Decryption Failed]", fix/remove the broken BUILD_NUMBER secret and rebuild.`);return n},fi=(e,t)=>nt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Ct=(e,t)=>{try{return fi(e,t)}catch{return""}},zr=e=>String(e||"").replace(/\.app$/i,"").replace(/[^a-z0-9]/gi,"").toLowerCase(),Ml=e=>{try{return S.statSync(e).isDirectory()}catch{return!1}},Ul=(e,t,n)=>{if(!S.existsSync(e))throw new Error(`iOS simulator build output directory was not found: ${e}`);let i=S.readdirSync(e).filter(c=>c.endsWith(".app")).map(c=>E.join(e,c)).filter(Ml);if(i.length===0){let u=At(e,[".app"]).map(d=>E.relative(e,d)).join(", ");throw new Error(`No top-level iOS simulator .app product was found in ${e}.`+(u?` Nested .app bundles found but ignored: ${u}`:""))}let r=new Set([t,n.iosScheme,n.scheme,n.appName].filter(Boolean).map(c=>zr(String(c))).filter(Boolean)),o=i.map(c=>{let u=E.join(c,"Info.plist"),d=S.existsSync(u)?Ct(u,"CFBundleName"):"",f=S.existsSync(u)?Ct(u,"CFBundleDisplayName"):"",p=S.existsSync(u)?Ct(u,"CFBundleExecutable"):"",g=S.existsSync(u)?Ct(u,"CFBundleIdentifier"):"",y=p?E.join(c,p):"";return{appPath:c,bundleIdentifier:g,executable:p,isValid:S.existsSync(u)&&!!p&&S.existsSync(y),names:[E.basename(c,".app"),d,f,p].map(zr).filter(Boolean)}}),s=o.filter(c=>c.isValid);if(s.length===0)throw new Error(`No valid iOS simulator .app product was found in ${e}. Candidates: `+o.map(c=>E.basename(c.appPath)).join(", "));let a=s.find(c=>c.names.some(u=>r.has(u)))||(s.length===1?s[0]:null);if(!a)throw new Error(`Multiple iOS simulator .app products were found in ${e}: `+s.map(c=>{let u=c.bundleIdentifier?` (${c.bundleIdentifier})`:"";return`${E.basename(c.appPath)}${u}`}).join(", ")+`. Set ios.scheme in ${m.configFileName} so ${m.name} can select the app target safely.`);return a.appPath},Wr=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return Qr(fi(t,"CFBundleVersion"),t)},eo=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Ct(t,"CFBundleExecutable");if(!n)throw new Error(`Could not validate iOS app executable: CFBundleExecutable missing in ${t}.`);let i=E.join(e,n);if(!S.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i},Fl=()=>process.arch==="arm64"?"arm64":"x86_64",to=e=>{let t=eo(e),n="";try{n=nt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(r){throw new Error(`Could not inspect iOS simulator executable architecture for ${E.basename(e)}: ${r.message}`)}let i=Fl();if(!new RegExp(`\\b${i}\\b`).test(n))throw new Error(`iOS simulator app ${E.basename(e)} cannot be installed on this runner because its executable does not include the required ${i} simulator architecture. lipo output: ${n}. Check the React Native iOS project ARCHS/EXCLUDED_ARCHS settings for iphonesimulator builds.`);return n},Bl=e=>{try{return nt("xcrun",["vtool","-show-build",e],{encoding:"utf-8"}).trim()}catch(t){throw new Error(`Could not inspect iOS executable build platform for ${E.basename(e)}: ${t.message}`)}},no=e=>{let t=eo(e),n=Bl(t);if(!/\bplatform\s+IOSSIMULATOR\b/i.test(n))throw new Error(`iOS simulator app ${E.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain PLATFORM IOSSIMULATOR, not an iPhone device binary. vtool output: ${n}`);return n},Hl=e=>{let n=nt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
1295
- `).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${E.basename(e)} has no Payload/*.app/Info.plist.`);let i=S.mkdtempSync(E.join(Ae.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=E.join(i,"Info.plist"),o=nt("unzip",["-p",e,n.trim()]);return S.writeFileSync(r,o),Qr(fi(r,"CFBundleVersion"),`${E.basename(e)}:${n.trim()}`)}finally{S.rmSync(i,{recursive:!0,force:!0})}},jl=e=>`'${e.replace(/'/g,"'\\''")}'`,Gl=()=>process.execPath&&S.existsSync(process.execPath)?process.execPath:nt("which",["node"],{encoding:"utf-8"}).trim(),io=(e,t,n)=>{if(!S.existsSync(e))return;let i=Gl();t.NODE_BINARY=i;let r=E.join(e,".xcode.env.local");S.writeFileSync(r,`export NODE_BINARY=${jl(i)}
1335
+ `),u=Date.now();return}let B=Date.now();B-u>3e4&&(L.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
1336
+ `),u=B)};_.stdout.on("data",b=>{let L=b.toString();a=Wr(a,L),D(L,process.stdout),r&&r(L)}),_.stderr.on("data",b=>{let L=b.toString();a=Wr(a,L),D(L,process.stderr),r&&r(L)}),_.on("close",b=>{b===0?s(b):l(new Error(Ol(e,t,b,a)))}),_.on("error",b=>l(b))}),Sn=async(e,t,n,i,r)=>{try{await it("xcodebuild",e,t,n,i,r)}catch(o){if(!Ll(o))throw o;O.warn(R.yellow("CocoaPods script permission denied. Repairing Pods script permissions and retrying xcodebuild once...")),eo(t),await it("xcodebuild",e,t,n,i,r)}},Ml=e=>{let t=Math.floor(e/1e3%60),n=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),r=[];return i>0&&r.push(`${i}h`),n>0&&r.push(`${n}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},At=(e,t)=>{let n=[];try{if(!S.existsSync(e))return n;let i=S.readdirSync(e);for(let r of i){let o=E.join(e,r);try{let s=S.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(E.resolve(o));continue}s.isDirectory()&&(n=n.concat(At(o,t)))}catch{}}}catch{}return n},Ul=/^\d+(?:\.\d+){0,2}$/,pi=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:Ul.test(t)?t:null},to=(e,t)=>{let n=pi(e);if(!n)throw new Error(`Invalid iOS CFBundleVersion from ${t}: "${e||""}". Apple requires one to three period-separated integers, for example "42" or "1.2.3". If you see "[Decryption Failed]", fix/remove the broken BUILD_NUMBER secret and rebuild.`);return n},fi=(e,t)=>nt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),Ct=(e,t)=>{try{return fi(e,t)}catch{return""}},Yr=e=>String(e||"").replace(/\.app$/i,"").replace(/[^a-z0-9]/gi,"").toLowerCase(),Fl=e=>{try{return S.statSync(e).isDirectory()}catch{return!1}},Bl=(e,t,n)=>{if(!S.existsSync(e))throw new Error(`iOS simulator build output directory was not found: ${e}`);let i=S.readdirSync(e).filter(d=>d.endsWith(".app")).map(d=>E.join(e,d)).filter(Fl);if(i.length===0){let u=At(e,[".app"]).map(c=>E.relative(e,c)).join(", ");throw new Error(`No top-level iOS simulator .app product was found in ${e}.`+(u?` Nested .app bundles found but ignored: ${u}`:""))}let r=new Set([t,n.iosScheme,n.scheme,n.appName].filter(Boolean).map(d=>Yr(String(d))).filter(Boolean)),o=i.map(d=>{let u=E.join(d,"Info.plist"),c=S.existsSync(u)?Ct(u,"CFBundleName"):"",f=S.existsSync(u)?Ct(u,"CFBundleDisplayName"):"",p=S.existsSync(u)?Ct(u,"CFBundleExecutable"):"",g=S.existsSync(u)?Ct(u,"CFBundleIdentifier"):"",y=p?E.join(d,p):"";return{appPath:d,bundleIdentifier:g,executable:p,isValid:S.existsSync(u)&&!!p&&S.existsSync(y),names:[E.basename(d,".app"),c,f,p].map(Yr).filter(Boolean)}}),s=o.filter(d=>d.isValid);if(s.length===0)throw new Error(`No valid iOS simulator .app product was found in ${e}. Candidates: `+o.map(d=>E.basename(d.appPath)).join(", "));let a=s.find(d=>d.names.some(u=>r.has(u)))||(s.length===1?s[0]:null);if(!a)throw new Error(`Multiple iOS simulator .app products were found in ${e}: `+s.map(d=>{let u=d.bundleIdentifier?` (${d.bundleIdentifier})`:"";return`${E.basename(d.appPath)}${u}`}).join(", ")+`. Set ios.scheme in ${m.configFileName} so ${m.name} can select the app target safely.`);return a.appPath},Jr=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return to(fi(t,"CFBundleVersion"),t)},no=e=>{let t=E.join(e,"Info.plist");if(!S.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Ct(t,"CFBundleExecutable");if(!n)throw new Error(`Could not validate iOS app executable: CFBundleExecutable missing in ${t}.`);let i=E.join(e,n);if(!S.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i},Hl=()=>process.arch==="arm64"?"arm64":"x86_64",io=e=>{let t=no(e),n="";try{n=nt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(r){throw new Error(`Could not inspect iOS simulator executable architecture for ${E.basename(e)}: ${r.message}`)}let i=Hl();if(!new RegExp(`\\b${i}\\b`).test(n))throw new Error(`iOS simulator app ${E.basename(e)} cannot be installed on this runner because its executable does not include the required ${i} simulator architecture. lipo output: ${n}. Check the React Native iOS project ARCHS/EXCLUDED_ARCHS settings for iphonesimulator builds.`);return n},jl=e=>{try{return nt("xcrun",["vtool","-show-build",e],{encoding:"utf-8"}).trim()}catch(t){throw new Error(`Could not inspect iOS executable build platform for ${E.basename(e)}: ${t.message}`)}},ro=e=>{let t=no(e),n=jl(t);if(!/\bplatform\s+IOSSIMULATOR\b/i.test(n))throw new Error(`iOS simulator app ${E.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain PLATFORM IOSSIMULATOR, not an iPhone device binary. vtool output: ${n}`);return n},Gl=e=>{let n=nt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
1337
+ `).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${E.basename(e)} has no Payload/*.app/Info.plist.`);let i=S.mkdtempSync(E.join(Ae.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=E.join(i,"Info.plist"),o=nt("unzip",["-p",e,n.trim()]);return S.writeFileSync(r,o),to(fi(r,"CFBundleVersion"),`${E.basename(e)}:${n.trim()}`)}finally{S.rmSync(i,{recursive:!0,force:!0})}},Kl=e=>`'${e.replace(/'/g,"'\\''")}'`,Vl=()=>process.execPath&&S.existsSync(process.execPath)?process.execPath:nt("which",["node"],{encoding:"utf-8"}).trim(),oo=(e,t,n)=>{if(!S.existsSync(e))return;let i=Vl();t.NODE_BINARY=i;let r=E.join(e,".xcode.env.local");S.writeFileSync(r,`export NODE_BINARY=${Kl(i)}
1296
1338
  `);let o=`[NODE] Xcode NODE_BINARY: ${i}
1297
- `;n&&n(R.dim(o)),O.info(R.dim(o.trim()))},mi=async(e,t,n={},i,r={})=>{let o=yn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",c=Qe(e.framework),u=()=>bt(n,a,e),d=async(I,T={})=>{if(i)for(let w=1;w<=3;w++)try{await k.patch(`/builds/${i}/${t}`,{status:I,...T});return}catch(C){let h=C?.response?.data?.message||C?.message||String(C);console.error(`[reportStatus] attempt ${w}/3 failed (status=${I}): ${h}`),w<3&&await new Promise(M=>setTimeout(M,2e3))}},f=new AbortController,{signal:p}=f,g=null;i&&(g=setInterval(async()=>{try{(await k.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(O.warn(R.yellow(`
1298
- \u{1F6D1} Build cancelled from dashboard. Terminating...`)),f.abort(),g&&clearInterval(g))}catch{}},5e3));let y=E.join(process.cwd(),".mach-cache"),_="setup",D="",b=null,x=async()=>{if(!D||!i)return;let I=D;D="";try{let T=I;Object.values(n).forEach(w=>{if(w&&w.length>5){let C=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(C,"g"),"[SECRET]")}}),await k.post(`/builds/${i}/${t}/logs`,{log:T,step:_})}catch{}},A=async()=>{b&&(clearTimeout(b),b=null),await x(),Rl(y,t),g&&(clearInterval(g),g=null);try{let I=E.join(Ae.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);S.existsSync(I)&&(te(`security delete-keychain "${I}"`,{stdio:"ignore"}),O.info(R.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let I=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(S.existsSync(I)){let T=S.readdirSync(I).filter(w=>w.includes(t)||w.startsWith(`${m.nameLower}-temp-${t}`));for(let w of T)S.unlinkSync(E.join(I,w))}}catch{}},B=async I=>{i&&(D+=I,D.length>=8192?(b&&(clearTimeout(b),b=null),await x()):b||(b=setTimeout(()=>{b=null,x()},2e3)))},q=async I=>{_=I,await B(`[STEP_START:${I}] ${Math.floor(Date.now()/1e3)}
1299
- `)},P=async(I,T,w,C)=>await it(I,T,w,C,h=>{B(h)},p);O.info(R.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{_l(y,t)}catch(I){throw await d("failed",{error:I.message,endTime:Date.now()}),I}if(await d("building"),await q("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)O.info(R.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await B(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
1339
+ `;n&&n(R.dim(o)),O.info(R.dim(o.trim()))},mi=async(e,t,n={},i,r={})=>{let o=yn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",d=Qe(e.framework),u=()=>bt(n,a,e),c=async(I,T={})=>{if(i)for(let w=1;w<=3;w++)try{await k.patch(`/builds/${i}/${t}`,{status:I,...T});return}catch(C){let h=C?.response?.data?.message||C?.message||String(C);console.error(`[reportStatus] attempt ${w}/3 failed (status=${I}): ${h}`),w<3&&await new Promise(M=>setTimeout(M,2e3))}},f=new AbortController,{signal:p}=f,g=null;i&&(g=setInterval(async()=>{try{(await k.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(O.warn(R.yellow(`
1340
+ \u{1F6D1} Build cancelled from dashboard. Terminating...`)),f.abort(),g&&clearInterval(g))}catch{}},5e3));let y=E.join(process.cwd(),".mach-cache"),_="setup",D="",b=null,L=async()=>{if(!D||!i)return;let I=D;D="";try{let T=I;Object.values(n).forEach(w=>{if(w&&w.length>5){let C=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");T=T.replace(new RegExp(C,"g"),"[SECRET]")}}),await k.post(`/builds/${i}/${t}/logs`,{log:T,step:_})}catch{}},A=async()=>{b&&(clearTimeout(b),b=null),await L(),vl(y,t),g&&(clearInterval(g),g=null);try{let I=E.join(Ae.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);S.existsSync(I)&&(te(`security delete-keychain "${I}"`,{stdio:"ignore"}),O.info(R.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let I=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");if(S.existsSync(I)){let T=S.readdirSync(I).filter(w=>w.includes(t)||w.startsWith(`${m.nameLower}-temp-${t}`));for(let w of T)S.unlinkSync(E.join(I,w))}}catch{}},B=async I=>{i&&(D+=I,D.length>=8192?(b&&(clearTimeout(b),b=null),await L()):b||(b=setTimeout(()=>{b=null,L()},2e3)))},q=async I=>{_=I,await B(`[STEP_START:${I}] ${Math.floor(Date.now()/1e3)}
1341
+ `)},P=async(I,T,w,C)=>await it(I,T,w,C,h=>{B(h)},p);O.info(R.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{$l(y,t)}catch(I){throw await c("failed",{error:I.message,endTime:Date.now()}),I}if(await c("building"),await q("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)O.info(R.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await B(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
1300
1342
  `);else if(i&&l==="ios"&&!e.simulator)try{let I=parseInt(n.BUILD_NUMBER||"0",10),T=Number.isFinite(I)?I:0,w=await k.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:T});if(w.data.status==="success"){let C=pi(String(w.data.buildNumber||""));if(!C)throw new Error(`Dashboard returned invalid iOS build number: "${w.data.buildNumber||""}"`);let h=parseInt(C,10),M=T>0&&Number.isFinite(h)&&h<T?String(T):C;M!==C&&(O.warn(R.yellow(`Dashboard build counter returned ${C}; using minimum ${M}.`)),await B(`[BUILD_NUMBER] Dashboard returned ${C}; using minimum ${M}
1301
1343
  `)),n.BUILD_NUMBER=M,O.info(R.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await B(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
1302
- `)}}catch(I){O.warn(R.yellow(`Could not fetch auto build number: ${I.message}`))}await q("lock"),c.applyLocalProcessEnv(e);try{await q("clone"),O.info(R.dim("Preparing source...")),await q("read_config");let I=E.join(process.cwd(),m.configFileName);if(S.existsSync(I)){let G=JSON.parse(S.readFileSync(I,"utf-8"))?.build?.[a]||{};await B(`[CONFIG] Profile: ${a}, distribution: ${G.distribution||"not set"}, simulator: ${G.simulator||!1}
1344
+ `)}}catch(I){O.warn(R.yellow(`Could not fetch auto build number: ${I.message}`))}await q("lock"),d.applyLocalProcessEnv(e);try{await q("clone"),O.info(R.dim("Preparing source...")),await q("read_config");let I=E.join(process.cwd(),m.configFileName);if(S.existsSync(I)){let G=JSON.parse(S.readFileSync(I,"utf-8"))?.build?.[a]||{};await B(`[CONFIG] Profile: ${a}, distribution: ${G.distribution||"not set"}, simulator: ${G.simulator||!1}
1303
1345
  `)}if(await q("read_package"),e.nodeVersion){let V=process.env.NVM_DIR||E.join(Ae.homedir(),".nvm"),G=E.join(V,"versions","node"),Q;if(S.existsSync(G)){let z=S.readdirSync(G).sort().reverse(),J=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,ae=z.find(ye=>ye===J||ye.startsWith(J+".")||ye.startsWith(`v${e.nodeVersion}.`));ae&&(Q=E.join(G,ae,"bin"))}if(Q&&S.existsSync(Q)){let z=process.env.PATH||"";process.env.PATH=`${Q}:${z}`,await B(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${Q}
1304
1346
  `),O.info(R.green(`\u2713 Node switched to ${e.nodeVersion} (${Q})`))}else await B(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
1305
- `),O.warn(R.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await q("deps"),o.start("Checking dependencies...");let T=Il(y),w=El(process.cwd()),C=S.existsSync("node_modules"),h=S.existsSync("yarn.lock"),M=S.existsSync("bun.lockb");C&&T.node&&T.node!==w&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await B(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
1306
- `),S.rmSync(E.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),C=!1);let U="npm",j=["install","--prefer-offline"];h?(U="yarn",j=["install","--prefer-offline"]):M&&(U="bun",j=["install"]),C?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(O.info(R.blue("Running pre-install hook...")),O.info(R.dim(`> ${e.preBuild}`)),await q("prebuild"),await P("bash",[e.preBuild],process.cwd(),u())),O.info(R.dim(`Running ${U} ${j.join(" ")}...`)),await P(U,j,process.cwd(),u()),T.node=w,Gr(y,T);let X=await c.prepareLocalProject({platform:l,options:e,cacheMeta:T,cacheMetaDir:y,currentBuildEnv:u,reportStep:q,reportLog:B,loggedRun:P,configureXcodeNodeBinary:io,podsFingerprint:Al,writeCacheMeta:Gr}),H=X.bundleId||e.iosBundleIdentifier||"",N=X.appName||e.name||"",W=[];if(l==="android")await q("build"),W=await Kl(e,a,n,V=>B(V),p);else if(l==="ios"){await q("signing"),O.info(R.dim("Preparing credentials..."));let V=r?.distributionType;W=await Vl(e,t,a,n,i,G=>B(G),p,V,G=>q(G))}e.postBuild&&(O.info(R.blue("Running post-build hook...")),O.info(R.dim(`> ${e.postBuild}`)),await P(e.postBuild,[],process.cwd(),u()));let ce=xl(Date.now()-s);if(O.success(R.green(`
1307
- \u2713 Local build completed successfully in ${ce}`)),await d("building",{...H&&{bundleId:H},...N&&{appName:N}}),W.length>0&&(O.info(R.cyan(`
1308
- \u{1F4E6} Generated Artifacts:`)),W.forEach(V=>{let G=E.resolve(V);O.info(R.dim(` - ${V}`)),O.info(R.gray(` Path: ${G}`))}),e.interactive)){let V=await yl({message:"Install on connected device?"});if(!bn(V)&&V){if(l==="android"){let G=W.find(Q=>Q.endsWith(".apk"))||W[0];await Wl(G,Q=>B(Q))}else if(l==="ios"){let G=W.find(z=>z.endsWith(".ipa"))||W.find(z=>z.endsWith(".app"))||W[0],Q=rt("ios");e.simulator?await Yl(G,Q||"",z=>B(z)):await Jl(G,Q||"",z=>B(z))}}}await q("upload");let ue=[];for(let V of W)try{let G=E.join(Ae.tmpdir(),`${t}-${E.basename(V)}`);S.copyFileSync(V,G),ue.push(G),O.info(R.dim(` \u{1F4CB} Preserved artifact: ${E.basename(V)}`))}catch{O.warn(R.yellow(` Failed to preserve artifact: ${E.basename(V)}`))}W=ue,O.info(R.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let V=process.cwd(),G=new Set(["node_modules"]),Q=S.readdirSync(V),z=0;for(let J of Q)if(!G.has(J)){if(J==="ios"){let ae=E.join(V,"ios"),ye=S.readdirSync(ae);for(let _e of ye)if(_e!=="Pods")try{S.rmSync(E.join(ae,_e),{recursive:!0,force:!0}),z++}catch{}continue}try{S.rmSync(E.join(V,J),{recursive:!0,force:!0}),z++}catch{}}O.info(R.dim(` Cleaned ${z} items. Cached: node_modules${S.existsSync(E.join(V,"ios","Pods"))?", ios/Pods":""}`)),O.info(R.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{O.warn(R.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let G=E.join(Ae.homedir(),m.workspacesDir),Q=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),z=parseInt(Q,10)*1024;if(z<53687091200&&S.existsSync(G)){O.info(R.dim(` \u26A0\uFE0F Low disk space (${(z/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let J=E.basename(process.cwd()),ae=S.readdirSync(G).filter(ye=>ye!==J).map(ye=>{let _e=E.join(G,ye);try{let $t=S.statSync(_e);return $t.isDirectory()?{name:ye,dir:_e,mtime:$t.mtimeMs}:null}catch{return null}}).filter(Boolean);ae.sort((ye,_e)=>ye.mtime-_e.mtime);for(let ye of ae){if(z>=53687091200)break;try{S.rmSync(ye.dir,{recursive:!0,force:!0}),O.info(R.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ye.name}`));let _e=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(_e,10)*1024>=53687091200)break}catch{}}}}catch{}return await A(),W}catch(I){throw await A(),I.message==="Command aborted"?(O.warn(R.yellow(`
1309
- \u274C Build aborted.`)),await d("failed",{error:"Aborted by user",endTime:Date.now()}),I):(O.error(R.red(`
1310
- \u2717 Local build failed: ${I.message}`)),await d("failed",{error:I.message,endTime:Date.now()}),I)}},Kl=async(e,t,n={},i,r)=>{let o=S.existsSync("android/gradlew")?"android/gradlew":S.existsSync("gradlew")?"./gradlew":null;if(!o)throw new Error("Could not find gradlew. Is this an Android project?");let s=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?s="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(s="assembleRelease");let l=e.buildCommand||s;O.info(R.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),u=[l],d=Qe(e.framework),f={...n,...d.localAndroidEnv(e,t),MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let g=E.join(a,"app/build.gradle");if(S.existsSync(g)){let y=n.ANDROID_VERSION_CODE,_=S.readFileSync(g,"utf-8");_=_.replace(/versionCode\s+\d+/,`versionCode ${y}`),S.writeFileSync(g,_),O.info(R.green(`\u2713 Applied Android versionCode ${y}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let g of["app/build","build",".cxx"]){let y=E.join(a,g);S.existsSync(y)&&S.rmSync(y,{recursive:!0,force:!0})}ci(process.cwd()),await it(c,u,a,f,i,r);let p=E.join(a,"app/build/outputs");return At(p,[".apk",".aab"])},Vl=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=E.resolve(process.cwd(),S.existsSync("ios")?"ios":".");Zr(c);let u=S.readdirSync(c),d=u.find(T=>T.endsWith(".xcworkspace")),f=u.find(T=>T.endsWith(".xcodeproj")),p=bt(i,n,e);io(c,p,o);let g=pi(p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION);if((p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION)&&!g)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let y=g?[`BUILD_NUMBER=${g}`,`CURRENT_PROJECT_VERSION=${g}`]:[];if(g&&(p.BUILD_NUMBER=g,p.CURRENT_PROJECT_VERSION=g,O.info(R.dim(`Using iOS build number: ${g}`))),!d&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let T=te("xcode-select -p").toString().trim();O.info(R.dim(`Using Xcode at: ${T}`))}catch{O.warn(R.dim("Could not detect Xcode path."))}O.info(R.blue("Running iOS build via xcodebuild..."));let _=d?d.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),D=e.iosScheme||_||e.scheme,b=e.developmentClient?"Debug":e.iosConfiguration||"Release",x=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),A=E.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,x);S.mkdirSync(A,{recursive:!0});let B=Dt(p),q=E.join(A,".mach-env-hash"),P=E.join(A,"Build"),I=S.existsSync(q)?S.readFileSync(q,"utf-8").trim():"";if(S.existsSync(P)){let T=I&&I!==B?"Build environment changed \u2014 clearing iOS DerivedData build products.":I?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";O.info(R.dim(T)),S.rmSync(P,{recursive:!0,force:!0})}if(S.writeFileSync(q,B),ci(process.cwd()),e.simulator){let T=kl(c,d,f,D,b),w=T||"generic/platform=iOS Simulator",C=["-destination",w];O.info(R.dim(T?`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`:`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`));let h=[d?"-workspace":"-project",d||f,"-scheme",D,"-configuration",b,"-sdk","iphonesimulator",...C,"-derivedDataPath",A,...y,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","ONLY_ACTIVE_ARCH=NO","EXCLUDED_ARCHS=","SUPPORTED_PLATFORMS=iphonesimulator"];try{await Sn(h,c,p,o,s)}catch(ue){if(!Cl(ue))throw ue;Nl(A),ci(process.cwd()),await Sn(h,c,p,o,s)}let M=E.join(A,"Build/Products",`${b}-iphonesimulator`),U=Ul(M,D,e),j=E.basename(U,".app"),X=Ct(E.join(U,"Info.plist"),"CFBundleIdentifier")||"unknown bundle",H=Wr(U),N=to(U),W=no(U),ce=E.join(M,`${j}_simulator.zip`);return O.info(R.dim(`Selected simulator app: ${E.relative(M,U)} (${X}, build ${H})`)),O.info(R.dim(`Simulator executable architecture: ${N}`)),O.info(R.dim(`Simulator executable platform: ${W.split(`
1311
- `).find(ue=>/\bplatform\b/i.test(ue))?.trim()||"IOSSIMULATOR"}`)),O.info(R.dim(`Creating simulator artifact: ${ce}...`)),ke(ce),nt("zip",["-r",ce,E.basename(U)],{cwd:E.dirname(U),stdio:"pipe"}),[ce]}else{O.info(R.dim(`Archiving (Scheme: ${D}, Config: ${b})...`));let T=E.join(c,"build.xcarchive"),w=E.join(c,"export");S.rmSync(T,{recursive:!0,force:!0}),S.rmSync(w,{recursive:!0,force:!0});let C=i.IOS_DIST_P12,h=i.IOS_PROVISIONING_PROFILE,M=i.IOS_P12_PASSWORD||"",U=[],j,X,H={isAppStore:!1,isDevelopment:!1};if(C&&h){O.info(R.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let z=`${m.buildPrefix}-${t}.keychain-db`,J=E.join(Ae.tmpdir(),z),ae=m.keychainPassword;te(`security create-keychain -p "${ae}" "${J}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${J}"`),te(`security unlock-keychain -p "${ae}" "${J}"`);let ye=E.join(Ae.tmpdir(),`cert-${t}.p12`),_e=Buffer.from(C,"base64");S.writeFileSync(ye,_e),O.info(R.dim(`P12 data size: ${_e.length} bytes, first bytes: ${_e.slice(0,4).toString("hex")}`)),(_e.length<100||_e[0]!==48)&&(O.warn(R.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),O.warn(R.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let $t=[M,"",m.keychainPassword],or=!1;for(let Re of $t)try{te(`security import "${ye}" -k "${J}" -P "${Re}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),or=!0,O.info(R.dim(`\u2713 P12 imported successfully with password: ${Re?"[set]":"[empty]"}`));break}catch(Be){O.info(R.dim(` P12 import attempt with password ${Re?`"${Re.substring(0,3)}..."`:"[empty]"} failed: ${Be.message?.split(`
1312
- `)[0]||"unknown"}`))}if(!or)throw new Error("Failed to import P12.");S.unlinkSync(ye),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${ae}" "${J}"`);let Ca=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
1313
- `).map(Re=>Re.trim().replace(/^"|"$/g,"")).filter(Re=>Re.length>0),Na=[J,...Ca].map(Re=>`"${Re}"`).join(" ");te(`security list-keychains -d user -s ${Na}`),te(`security default-keychain -s "${J}"`);let Zn=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");S.mkdirSync(Zn,{recursive:!0});let sr=Buffer.from(h,"base64"),Qn=E.join(Zn,`${m.nameLower}-temp-${t}.mobileprovision`);S.writeFileSync(Qn,sr);let ei=sr.toString("utf-8"),ar=/<key>get-task-allow<\/key>\s*<true\/>/.test(ei);H={isAppStore:!ei.includes("<key>ProvisionedDevices</key>")&&!ar,isDevelopment:ar};try{let Be=te(`security cms -D -i "${Qn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}catch{let Be=ei.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}X||(O.warn("Could not extract UUID from provisioning profile. Using fallback."),X=`${m.nameLower}-${t}`);let ti=E.join(Zn,`${X}.mobileprovision`);S.existsSync(ti)&&S.unlinkSync(ti),S.renameSync(Qn,ti);try{let Re=te(`security find-identity -v -p codesigning "${J}"`,{encoding:"utf-8"}),Be=Array.from(Re.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Bt=>Bt[1]),lr=H.isDevelopment?Be.find(Bt=>/\b(Development|Developer)\b/.test(Bt)):Be.find(Bt=>/\bDistribution\b/.test(Bt)),dr=Be[0];(lr||dr)&&(j=lr||dr,O.info(R.blue(`Identity auto-detected from keychain: "${j}"`)))}catch{}j||(j=H.isDevelopment?"Apple Development":"Apple Distribution",O.info(R.blue(`Identity fallback (profile heuristic): "${j}"`))),O.info(R.dim(`Profile type: ${H.isDevelopment?"Development":H.isAppStore?"App Store":"Ad-Hoc"}`)),O.info(R.dim(`Identity Detection: get-task-allow=${H.isDevelopment}, Selected Identity="${j}"`)),U.push("CODE_SIGN_STYLE=Manual"),U.push(`CODE_SIGN_IDENTITY="${j}"`),U.push(`PROVISIONING_PROFILE_SPECIFIER=${X}`),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(z){throw O.error(`Signing setup failed: ${z.message}`),z}}else U.push("-allowProvisioningUpdates"),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),O.info(R.blue(`Archive detected Identity: "${j}"`)),O.info(R.blue(`Archive detected UUID: "${X}"`)),await Sn(["archive",d?"-workspace":"-project",d||f,"-scheme",D,"-configuration",b,"-archivePath",T,"-derivedDataPath",A,...y,...U],c,p,o,s);let N=At(E.join(T,"Products","Applications"),[".app"]);for(let z of N){let J=Wr(z);O.info(R.dim(`Validated iOS CFBundleVersion ${J} in ${E.basename(z)}`))}let W;X?(H.isAppStore?W="app-store":H.isDevelopment?W="development":W="ad-hoc",O.info(R.blue(`Export method from profile: "${W}"`))):(W=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",O.warn(R.yellow(`No profile UUID detected. Export method from distribution flag: "${W}"`)));let ce=e.iosExportMethod||W,ue=e.iosBundleIdentifier||rt("ios"),V=E.join(c,"ExportOptions.plist"),G=`<?xml version="1.0" encoding="UTF-8"?>
1347
+ `),O.warn(R.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await q("deps"),o.start("Checking dependencies...");let T=_l(y),w=Il(process.cwd()),C=S.existsSync("node_modules"),h=S.existsSync("yarn.lock"),M=S.existsSync("bun.lockb");C&&T.node&&T.node!==w&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await B(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
1348
+ `),S.rmSync(E.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),C=!1);let U="npm",j=["install","--prefer-offline"];h?(U="yarn",j=["install","--prefer-offline"]):M&&(U="bun",j=["install"]),C?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(O.info(R.blue("Running pre-install hook...")),O.info(R.dim(`> ${e.preBuild}`)),await q("prebuild"),await P("bash",[e.preBuild],process.cwd(),u())),O.info(R.dim(`Running ${U} ${j.join(" ")}...`)),await P(U,j,process.cwd(),u()),T.node=w,Vr(y,T);let X=await d.prepareLocalProject({platform:l,options:e,cacheMeta:T,cacheMetaDir:y,currentBuildEnv:u,reportStep:q,reportLog:B,loggedRun:P,configureXcodeNodeBinary:oo,podsFingerprint:wl,writeCacheMeta:Vr}),H=X.bundleId||e.iosBundleIdentifier||"",N=X.appName||e.name||"",W=[];if(l==="android")await q("build"),W=await zl(e,a,n,V=>B(V),p);else if(l==="ios"){await q("signing"),O.info(R.dim("Preparing credentials..."));let V=r?.distributionType;W=await Wl(e,t,a,n,i,G=>B(G),p,V,G=>q(G))}e.postBuild&&(O.info(R.blue("Running post-build hook...")),O.info(R.dim(`> ${e.postBuild}`)),await P(e.postBuild,[],process.cwd(),u()));let de=Ml(Date.now()-s);if(O.success(R.green(`
1349
+ \u2713 Local build completed successfully in ${de}`)),await c("building",{...H&&{bundleId:H},...N&&{appName:N}}),W.length>0&&(O.info(R.cyan(`
1350
+ \u{1F4E6} Generated Artifacts:`)),W.forEach(V=>{let G=E.resolve(V);O.info(R.dim(` - ${V}`)),O.info(R.gray(` Path: ${G}`))}),e.interactive)){let V=await El({message:"Install on connected device?"});if(!bn(V)&&V){if(l==="android"){let G=W.find(Q=>Q.endsWith(".apk"))||W[0];await Jl(G,Q=>B(Q))}else if(l==="ios"){let G=W.find(z=>z.endsWith(".ipa"))||W.find(z=>z.endsWith(".app"))||W[0],Q=rt("ios");e.simulator?await Xl(G,Q||"",z=>B(z)):await ql(G,Q||"",z=>B(z))}}}await q("upload");let ue=[];for(let V of W)try{let G=E.join(Ae.tmpdir(),`${t}-${E.basename(V)}`);S.copyFileSync(V,G),ue.push(G),O.info(R.dim(` \u{1F4CB} Preserved artifact: ${E.basename(V)}`))}catch{O.warn(R.yellow(` Failed to preserve artifact: ${E.basename(V)}`))}W=ue,O.info(R.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let V=process.cwd(),G=new Set(["node_modules"]),Q=S.readdirSync(V),z=0;for(let J of Q)if(!G.has(J)){if(J==="ios"){let ae=E.join(V,"ios"),ye=S.readdirSync(ae);for(let _e of ye)if(_e!=="Pods")try{S.rmSync(E.join(ae,_e),{recursive:!0,force:!0}),z++}catch{}continue}try{S.rmSync(E.join(V,J),{recursive:!0,force:!0}),z++}catch{}}O.info(R.dim(` Cleaned ${z} items. Cached: node_modules${S.existsSync(E.join(V,"ios","Pods"))?", ios/Pods":""}`)),O.info(R.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{O.warn(R.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let G=E.join(Ae.homedir(),m.workspacesDir),Q=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),z=parseInt(Q,10)*1024;if(z<53687091200&&S.existsSync(G)){O.info(R.dim(` \u26A0\uFE0F Low disk space (${(z/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let J=E.basename(process.cwd()),ae=S.readdirSync(G).filter(ye=>ye!==J).map(ye=>{let _e=E.join(G,ye);try{let $t=S.statSync(_e);return $t.isDirectory()?{name:ye,dir:_e,mtime:$t.mtimeMs}:null}catch{return null}}).filter(Boolean);ae.sort((ye,_e)=>ye.mtime-_e.mtime);for(let ye of ae){if(z>=53687091200)break;try{S.rmSync(ye.dir,{recursive:!0,force:!0}),O.info(R.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ye.name}`));let _e=te(`df -k "${G}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(_e,10)*1024>=53687091200)break}catch{}}}}catch{}return await A(),W}catch(I){throw await A(),I.message==="Command aborted"?(O.warn(R.yellow(`
1351
+ \u274C Build aborted.`)),await c("failed",{error:"Aborted by user",endTime:Date.now()}),I):(O.error(R.red(`
1352
+ \u2717 Local build failed: ${I.message}`)),await c("failed",{error:I.message,endTime:Date.now()}),I)}},zl=async(e,t,n={},i,r)=>{let o=S.existsSync("android/gradlew")?"android/gradlew":S.existsSync("gradlew")?"./gradlew":null;if(!o)throw new Error("Could not find gradlew. Is this an Android project?");let s=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?s="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(s="assembleRelease");let l=e.buildCommand||s;O.info(R.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",d=(o.includes("android/"),"./gradlew"),u=[l],c=Qe(e.framework),f={...n,...c.localAndroidEnv(e,t),MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let g=E.join(a,"app/build.gradle");if(S.existsSync(g)){let y=n.ANDROID_VERSION_CODE,_=S.readFileSync(g,"utf-8");_=_.replace(/versionCode\s+\d+/,`versionCode ${y}`),S.writeFileSync(g,_),O.info(R.green(`\u2713 Applied Android versionCode ${y}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let g of["app/build","build",".cxx"]){let y=E.join(a,g);S.existsSync(y)&&S.rmSync(y,{recursive:!0,force:!0})}di(process.cwd()),await it(d,u,a,f,i,r);let p=E.join(a,"app/build/outputs");return At(p,[".apk",".aab"])},Wl=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let d=E.resolve(process.cwd(),S.existsSync("ios")?"ios":".");eo(d);let u=S.readdirSync(d),c=u.find(T=>T.endsWith(".xcworkspace")),f=u.find(T=>T.endsWith(".xcodeproj")),p=bt(i,n,e);oo(d,p,o);let g=pi(p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION);if((p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION)&&!g)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${p.BUILD_NUMBER||p.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let y=g?[`BUILD_NUMBER=${g}`,`CURRENT_PROJECT_VERSION=${g}`]:[];if(g&&(p.BUILD_NUMBER=g,p.CURRENT_PROJECT_VERSION=g,O.info(R.dim(`Using iOS build number: ${g}`))),!c&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let T=te("xcode-select -p").toString().trim();O.info(R.dim(`Using Xcode at: ${T}`))}catch{O.warn(R.dim("Could not detect Xcode path."))}O.info(R.blue("Running iOS build via xcodebuild..."));let _=c?c.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),D=e.iosScheme||_||e.scheme,b=e.developmentClient?"Debug":e.iosConfiguration||"Release",L=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),A=E.join(Ae.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,L);S.mkdirSync(A,{recursive:!0});let B=Dt(p),q=E.join(A,".mach-env-hash"),P=E.join(A,"Build"),I=S.existsSync(q)?S.readFileSync(q,"utf-8").trim():"";if(S.existsSync(P)){let T=I&&I!==B?"Build environment changed \u2014 clearing iOS DerivedData build products.":I?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";O.info(R.dim(T)),S.rmSync(P,{recursive:!0,force:!0})}if(S.writeFileSync(q,B),di(process.cwd()),e.simulator){let T=xl(d,c,f,D,b),w=T||"generic/platform=iOS Simulator",C=["-destination",w];O.info(R.dim(T?`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`:`Building for simulator (Scheme: ${D}, Config: ${b}, Destination: ${w})...`));let h=[c?"-workspace":"-project",c||f,"-scheme",D,"-configuration",b,"-sdk","iphonesimulator",...C,"-derivedDataPath",A,...y,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","ONLY_ACTIVE_ARCH=NO","EXCLUDED_ARCHS=","SUPPORTED_PLATFORMS=iphonesimulator"];try{await Sn(h,d,p,o,s)}catch(ue){if(!Tl(ue))throw ue;kl(A),di(process.cwd()),await Sn(h,d,p,o,s)}let M=E.join(A,"Build/Products",`${b}-iphonesimulator`),U=Bl(M,D,e),j=E.basename(U,".app"),X=Ct(E.join(U,"Info.plist"),"CFBundleIdentifier")||"unknown bundle",H=Jr(U),N=io(U),W=ro(U),de=E.join(M,`${j}_simulator.zip`);return O.info(R.dim(`Selected simulator app: ${E.relative(M,U)} (${X}, build ${H})`)),O.info(R.dim(`Simulator executable architecture: ${N}`)),O.info(R.dim(`Simulator executable platform: ${W.split(`
1353
+ `).find(ue=>/\bplatform\b/i.test(ue))?.trim()||"IOSSIMULATOR"}`)),O.info(R.dim(`Creating simulator artifact: ${de}...`)),ke(de),nt("zip",["-r",de,E.basename(U)],{cwd:E.dirname(U),stdio:"pipe"}),[de]}else{O.info(R.dim(`Archiving (Scheme: ${D}, Config: ${b})...`));let T=E.join(d,"build.xcarchive"),w=E.join(d,"export");S.rmSync(T,{recursive:!0,force:!0}),S.rmSync(w,{recursive:!0,force:!0});let C=i.IOS_DIST_P12,h=i.IOS_PROVISIONING_PROFILE,M=i.IOS_P12_PASSWORD||"",U=[],j,X,H={isAppStore:!1,isDevelopment:!1};if(C&&h){O.info(R.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let z=`${m.buildPrefix}-${t}.keychain-db`,J=E.join(Ae.tmpdir(),z),ae=m.keychainPassword;te(`security create-keychain -p "${ae}" "${J}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${J}"`),te(`security unlock-keychain -p "${ae}" "${J}"`);let ye=E.join(Ae.tmpdir(),`cert-${t}.p12`),_e=Buffer.from(C,"base64");S.writeFileSync(ye,_e),O.info(R.dim(`P12 data size: ${_e.length} bytes, first bytes: ${_e.slice(0,4).toString("hex")}`)),(_e.length<100||_e[0]!==48)&&(O.warn(R.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),O.warn(R.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let $t=[M,"",m.keychainPassword],ar=!1;for(let Re of $t)try{te(`security import "${ye}" -k "${J}" -P "${Re}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),ar=!0,O.info(R.dim(`\u2713 P12 imported successfully with password: ${Re?"[set]":"[empty]"}`));break}catch(Be){O.info(R.dim(` P12 import attempt with password ${Re?`"${Re.substring(0,3)}..."`:"[empty]"} failed: ${Be.message?.split(`
1354
+ `)[0]||"unknown"}`))}if(!ar)throw new Error("Failed to import P12.");S.unlinkSync(ye),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${ae}" "${J}"`);let Ta=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
1355
+ `).map(Re=>Re.trim().replace(/^"|"$/g,"")).filter(Re=>Re.length>0),ka=[J,...Ta].map(Re=>`"${Re}"`).join(" ");te(`security list-keychains -d user -s ${ka}`),te(`security default-keychain -s "${J}"`);let Zn=E.join(Ae.homedir(),"Library/MobileDevice/Provisioning Profiles");S.mkdirSync(Zn,{recursive:!0});let lr=Buffer.from(h,"base64"),Qn=E.join(Zn,`${m.nameLower}-temp-${t}.mobileprovision`);S.writeFileSync(Qn,lr);let ei=lr.toString("utf-8"),cr=/<key>get-task-allow<\/key>\s*<true\/>/.test(ei);H={isAppStore:!ei.includes("<key>ProvisionedDevices</key>")&&!cr,isDevelopment:cr};try{let Be=te(`security cms -D -i "${Qn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}catch{let Be=ei.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);X=Be?Be[1]:void 0}X||(O.warn("Could not extract UUID from provisioning profile. Using fallback."),X=`${m.nameLower}-${t}`);let ti=E.join(Zn,`${X}.mobileprovision`);S.existsSync(ti)&&S.unlinkSync(ti),S.renameSync(Qn,ti);try{let Re=te(`security find-identity -v -p codesigning "${J}"`,{encoding:"utf-8"}),Be=Array.from(Re.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Bt=>Bt[1]),dr=H.isDevelopment?Be.find(Bt=>/\b(Development|Developer)\b/.test(Bt)):Be.find(Bt=>/\bDistribution\b/.test(Bt)),ur=Be[0];(dr||ur)&&(j=dr||ur,O.info(R.blue(`Identity auto-detected from keychain: "${j}"`)))}catch{}j||(j=H.isDevelopment?"Apple Development":"Apple Distribution",O.info(R.blue(`Identity fallback (profile heuristic): "${j}"`))),O.info(R.dim(`Profile type: ${H.isDevelopment?"Development":H.isAppStore?"App Store":"Ad-Hoc"}`)),O.info(R.dim(`Identity Detection: get-task-allow=${H.isDevelopment}, Selected Identity="${j}"`)),U.push("CODE_SIGN_STYLE=Manual"),U.push(`CODE_SIGN_IDENTITY="${j}"`),U.push(`PROVISIONING_PROFILE_SPECIFIER=${X}`),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(z){throw O.error(`Signing setup failed: ${z.message}`),z}}else U.push("-allowProvisioningUpdates"),e.iosTeamId&&U.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),O.info(R.blue(`Archive detected Identity: "${j}"`)),O.info(R.blue(`Archive detected UUID: "${X}"`)),await Sn(["archive",c?"-workspace":"-project",c||f,"-scheme",D,"-configuration",b,"-archivePath",T,"-derivedDataPath",A,...y,...U],d,p,o,s);let N=At(E.join(T,"Products","Applications"),[".app"]);for(let z of N){let J=Jr(z);O.info(R.dim(`Validated iOS CFBundleVersion ${J} in ${E.basename(z)}`))}let W;X?(H.isAppStore?W="app-store":H.isDevelopment?W="development":W="ad-hoc",O.info(R.blue(`Export method from profile: "${W}"`))):(W=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",O.warn(R.yellow(`No profile UUID detected. Export method from distribution flag: "${W}"`)));let de=e.iosExportMethod||W,ue=e.iosBundleIdentifier||rt("ios"),V=E.join(d,"ExportOptions.plist"),G=`<?xml version="1.0" encoding="UTF-8"?>
1314
1356
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1315
1357
  <plist version="1.0">
1316
1358
  <dict>
1317
1359
  <key>method</key>
1318
- <string>${ce}</string>
1360
+ <string>${de}</string>
1319
1361
  <key>destination</key>
1320
1362
  <string>export</string>
1321
1363
  <key>signingStyle</key>
@@ -1331,63 +1373,63 @@ ${s.join(`
1331
1373
  </dict>`:""}
1332
1374
  </dict>
1333
1375
  </plist>`;if(S.writeFileSync(V,G),process.env[`${m.envPrefix}DEBUG`]&&O.info(R.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
1334
- ${G}`)),a&&await a("export"),O.info(R.blue(`Exporting with Bundle ID: "${ue}"`)),O.info(R.blue(`Exporting with Method: "${ce}"`)),o){o(R.magenta(`
1376
+ ${G}`)),a&&await a("export"),O.info(R.blue(`Exporting with Bundle ID: "${ue}"`)),O.info(R.blue(`Exporting with Method: "${de}"`)),o){o(R.magenta(`
1335
1377
  [DIAGNOSTIC] Checking available signing identities...
1336
1378
  `));try{let z=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(R.magenta(`${z}
1337
1379
  `))}catch(z){o(R.red(`[DIAGNOSTIC] Failed to list identities: ${z.message}
1338
- `))}}await Sn(["-exportArchive","-archivePath",T,"-exportPath",w,"-exportOptionsPlist",V],c,p,o,s),a&&await a("validate");let Q=At(w,[".ipa"]);for(let z of Q)try{te(`unzip -t "${z}"`,{stdio:"pipe"});let J=Hl(z);o&&o(`[IPA VALID] ${E.basename(z)} \u2014 archive integrity OK
1380
+ `))}}await Sn(["-exportArchive","-archivePath",T,"-exportPath",w,"-exportOptionsPlist",V],d,p,o,s),a&&await a("validate");let Q=At(w,[".ipa"]);for(let z of Q)try{te(`unzip -t "${z}"`,{stdio:"pipe"});let J=Gl(z);o&&o(`[IPA VALID] ${E.basename(z)} \u2014 archive integrity OK
1339
1381
  `),o&&o(`[IPA VALID] CFBundleVersion ${J}
1340
1382
  `)}catch(J){let ae=`IPA validation failed for ${E.basename(z)}: ${J.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${ae}
1341
- `),new Error(ae)}return Q}},rt=e=>{try{let t=E.join(process.cwd(),m.configFileName);if(S.existsSync(t)){let n=JSON.parse(S.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(S.existsSync(i)){let o=S.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=E.resolve(process.cwd(),S.existsSync("ios")?"ios":"."),i=At(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=S.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=At(n,[".xcodeproj"]);if(r.length>0){let s=E.join(r[0],"project.pbxproj");if(S.existsSync(s)){let a=S.readFileSync(s,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(a)return a[1]}}let o=["app.json","app.config.json","app.config.js","app.config.ts"];for(let s of o)if(S.existsSync(s)){let a=S.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},zl=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[E.join(t,"Library/Android/sdk/emulator/emulator"),E.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(S.existsSync(i))return i}return"emulator"},Wl=async(e,t)=>{let n=yn();try{if(te("adb devices").toString().split(`
1342
- `).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){O.warn(R.yellow("No Android devices or emulators found."));let s=zl(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
1343
- `).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ui({message:"Select an emulator to launch:",options:l.map(d=>({value:d,label:d}))});if(bn(a))return;n.start(`Launching emulator ${a}...`),Yr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let c=0,u=!1;for(;c<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await it("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=rt("android");if(o){O.info(R.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
1344
- `).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{O.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),O.error(R.red(`Failed to install APK: ${i.message}`))}},Yl=async(e,t,n)=>{let i=yn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){O.warn(R.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(d=>{s[d].forEach(f=>{f.isAvailable&&l.push({...f,runtime:d})})});let a=await ui({message:"Select a simulator to launch:",options:l.map(d=>({value:d.udid,label:`${d.name} (${d.runtime.split(".").pop()})`}))});if(bn(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let c=0,u=!1;for(;c<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),to(e),no(e),await it("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on Simulator: ${r.message}`))}},Jl=async(e,t,n)=>{let i=yn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let l=s[0].identifier;if(s.length>1){i.stop();let a=await ui({message:"Select a device to install on:",options:s.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(bn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await it("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on device: ${r.message}`)),O.info(R.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import L from"fs";import Tt from"os";import Y from"path";import{spawn as po,spawnSync as Ge}from"child_process";import{randomUUID as Xl}from"crypto";import{pipeline as ql}from"stream/promises";import{isCancel as yi,log as F,select as fo,spinner as Wt,text as Zl}from"@clack/prompts";import zt from"axios";import K from"chalk";import En from"adm-zip";async function mo(e){if(e.localRunner){let n=await id(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await rd(e);n&&(process.exitCode=n.exitCode);return}let t=await Ii(e);if(t&&(F.success(K.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&F.warn(K.yellow(t.launchDeferredReason)),t.dashboardUrl&&F.info(K.dim("View test run: ")+K.white.underline(t.dashboardUrl)),e.wait)){let n=await od(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var Ql=new Set(["passed","failed","cancelled","interrupted"]),ro=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),ed=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4),go=process.env.MACH_MAESTRO_FAST_FAIL_RETRY==="1";function Ai(e){let t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.flatMap(n=>String(n||"").split(",")).map(n=>n.trim()).filter(Boolean))]}function td(e){let t=Ai(e);if(t.length===0)return;let n={};for(let i of t){let r=process.env[i];r!==void 0&&(n[i]=r)}return Object.keys(n).length>0?n:void 0}function nd(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=Ai(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function id(e){let t=e.projectId,n=e.testRunId,i=e.runnerToken||process.env.MACH_RUNNER_TOKEN||process.env.MACH_TOKEN,r=(process.env.MACH_API_URL||vt).replace(/\/$/,""),o=L.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-runner-")),s=Y.join(o,"mach-maestro-output"),l=Y.join(o,"runner.log");if(L.mkdirSync(s,{recursive:!0}),!t||!n||!i)return F.error(K.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,c=null,u=null,d=p=>{L.appendFileSync(l,`${p}${p.endsWith(`
1383
+ `),new Error(ae)}return Q}},rt=e=>{try{let t=E.join(process.cwd(),m.configFileName);if(S.existsSync(t)){let n=JSON.parse(S.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(S.existsSync(i)){let o=S.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=E.resolve(process.cwd(),S.existsSync("ios")?"ios":"."),i=At(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=S.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=At(n,[".xcodeproj"]);if(r.length>0){let s=E.join(r[0],"project.pbxproj");if(S.existsSync(s)){let a=S.readFileSync(s,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(a)return a[1]}}let o=["app.json","app.config.json","app.config.js","app.config.ts"];for(let s of o)if(S.existsSync(s)){let a=S.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},Yl=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ae.homedir(),n=[E.join(t,"Library/Android/sdk/emulator/emulator"),E.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(S.existsSync(i))return i}return"emulator"},Jl=async(e,t)=>{let n=yn();try{if(te("adb devices").toString().split(`
1384
+ `).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){O.warn(R.yellow("No Android devices or emulators found."));let s=Yl(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
1385
+ `).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ui({message:"Select an emulator to launch:",options:l.map(c=>({value:c,label:c}))});if(bn(a))return;n.start(`Launching emulator ${a}...`),Xr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let d=0,u=!1;for(;d<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(c=>setTimeout(c,2e3)),d++}if(!u)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await it("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=rt("android");if(o){O.info(R.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
1386
+ `).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{O.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),O.error(R.red(`Failed to install APK: ${i.message}`))}},Xl=async(e,t,n)=>{let i=yn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){O.warn(R.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(c=>{s[c].forEach(f=>{f.isAvailable&&l.push({...f,runtime:c})})});let a=await ui({message:"Select a simulator to launch:",options:l.map(c=>({value:c.udid,label:`${c.name} (${c.runtime.split(".").pop()})`}))});if(bn(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,u=!1;for(;d<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(c=>setTimeout(c,2e3)),d++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),io(e),ro(e),await it("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on Simulator: ${r.message}`))}},ql=async(e,t,n)=>{let i=yn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let l=s[0].identifier;if(s.length>1){i.stop();let a=await ui({message:"Select a device to install on:",options:s.map(d=>({value:d.identifier,label:`${d.deviceProperties?.name||d.name||d.model?.name} (${d.model?.name||"iPhone"}) - ${d.identifier}`}))});if(bn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await it("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),O.info(R.blue(`\u{1F680} Launching ${t}...`)),await it("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),O.error(R.red(`Failed to install on device: ${r.message}`)),O.info(R.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import x from"fs";import Tt from"os";import Y from"path";import{spawn as mo,spawnSync as Ge}from"child_process";import{randomUUID as Zl}from"crypto";import{pipeline as Ql}from"stream/promises";import{isCancel as yi,log as F,select as go,spinner as Wt,text as ec}from"@clack/prompts";import zt from"axios";import K from"chalk";import En from"adm-zip";async function ho(e){if(e.localRunner){let n=await oc(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await sc(e);n&&(process.exitCode=n.exitCode);return}let t=await Ii(e);if(t&&(F.success(K.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&F.warn(K.yellow(t.launchDeferredReason)),t.dashboardUrl&&F.info(K.dim("View test run: ")+K.white.underline(t.dashboardUrl)),e.wait)){let n=await ac(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var tc=new Set(["passed","failed","cancelled","interrupted"]),so=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),nc=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4),So=process.env.MACH_MAESTRO_FAST_FAIL_RETRY==="1";function Ai(e){let t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.flatMap(n=>String(n||"").split(",")).map(n=>n.trim()).filter(Boolean))]}function ic(e){let t=Ai(e);if(t.length===0)return;let n={};for(let i of t){let r=process.env[i];r!==void 0&&(n[i]=r)}return Object.keys(n).length>0?n:void 0}function rc(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=Ai(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function oc(e){let t=e.projectId,n=e.testRunId,i=e.runnerToken||process.env.MACH_RUNNER_TOKEN||process.env.MACH_TOKEN,r=(process.env.MACH_API_URL||vt).replace(/\/$/,""),o=x.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-runner-")),s=Y.join(o,"mach-maestro-output"),l=Y.join(o,"runner.log");if(x.mkdirSync(s,{recursive:!0}),!t||!n||!i)return F.error(K.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,d=null,u=null,c=p=>{x.appendFileSync(l,`${p}${p.endsWith(`
1345
1387
  `)?"":`
1346
- `}`)},f=async(p,g)=>{try{await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:p,error:g,logPreview:fd(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(y){d(`[WARN] Could not post runner update: ${y.message||y}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let p=await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(p.data?.status!=="success"||!p.data?.payload)throw new Error(p.data?.message||"Runner payload was not returned.");a=p.data.payload;let g=Object.keys(a.env||{});d(`Using Maestro env vars: ${g.length>0?g.join(", "):"none"}`);let y={...process.env,...a.env||{}},_=md(a.env);_.length>0&&d(`Passing Maestro env vars to test command: ${g.sort().join(", ")}`),await f("running");let D=a.platform==="android"?"app.apk":"app.zip",b=Y.join(o,D),x=Y.join(o,"source.zip"),A=Y.join(o,"source");L.mkdirSync(A,{recursive:!0}),d("Downloading app artifact..."),await bi(a.artifactUrl,b),d(`Downloaded app artifact: ${D} (${so(L.statSync(b).size)})`),d("Downloading Maestro source..."),await bi(a.urls.sourceUrl,x),d(`Downloaded Maestro source: source.zip (${so(L.statSync(x).size)})`),new En(x).extractAllTo(A,!0);let B=gd(A,a.flowPath||".maestro");if(!L.existsSync(B))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${Y.relative(A,B)||"."}`),a.platform==="ios"){await Ad(a.device||"iphone_15",l);let C=Id(b,o),h=Ao(C,l);d(`Resolved iOS app bundle: ${C}`),d(`Resolved iOS bundle id: ${h||"unknown"}`),_d(C,l),Ei("xcrun",["simctl","install","booted",C],l),h&&(u={platform:a.platform,appId:h}),h&&ot("xcrun",["simctl","get_app_container","booted",h,"app"],l),gi(s,l,"ios-before-maestro.png"),a.record&&(c=wd(s,l))}else{let C=vd(b,l),h=$d(a.device,l),M=h?["-s",h]:[];d(`Resolved Android application id: ${C||"unknown"}`),Ei("adb",[...M,"install","-r",b],l),C&&(u={platform:a.platform,appId:C,deviceId:h||void 0})}let P=Math.max(0,Math.min(10,Number(a.retries??1)))+1,I=Y.join(s,"report.xml"),T=bd(l);if(!T)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let w=1;for(let C=1;C<=P;C+=1){d(`Running Maestro attempt ${C}/${P}...`);let h=["test","--platform",a.platform,..._,B,"--format","junit","--output",I,"--test-output-dir",s];if(go&&C<P?w=(await Eo(T,h,{logPath:l,env:y,fastFailOnFlowFailure:!0})).exitCode:w=ot(T,h,l,void 0,y),w===0)break}return a.platform==="ios"&&gi(s,l,"ios-after-maestro.png"),await ao(c,l),c=null,await uo(a.urls,o,s,l),w===0?(await f("passed"),F.success(K.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:P,flows:a.flowPath,platform:a.platform}):(await f("failed",`Maestro exited with code ${w}`),F.error(K.red(`Managed Maestro run failed with exit code ${w}`)),{status:"failed",exitCode:w,attempts:P,flows:a.flowPath,platform:a.platform})}catch(p){let g=p.message||String(p);return d(`MACH_MAESTRO_RUN_FAILED: ${g}`),a?.platform==="ios"&&gi(s,l,"ios-after-failure.png"),await ao(c,l),a?.urls&&await uo(a.urls,o,s,l),await f("failed",g),F.error(K.red(`Managed Maestro runner failed: ${g}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Rd(u,l)}}async function rd(e){let t=e.maestroFlows||".maestro",n=So(e.maestroRetries);if(n===null)return null;let i=Y.resolve(t);if(!L.existsSync(i))return F.error(K.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await cd(e);if(r?.url){if(!await pd(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(K.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=nd(e.maestroEnv),a=Object.keys(l);if(a.length>0){F.info(K.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,g]of Object.entries(l))s.push("-e",`${p}=${g}`)}s.push(t);let c=n+1,u=1;for(let p=1;p<=c;p+=1){if(F.info(K.dim(`Running local Maestro attempt ${p}/${c}...`)),go&&p<c){let g=await Eo("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=g.exitCode}else{let g=Ge("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof g.status=="number"?g.status:1}if(u===0)break}let d=u===0?"passed":"failed",f={status:d,exitCode:u,attempts:c,flows:t,platform:o};return kd(e,f),d==="passed"?F.success(K.green("Local Maestro run passed")):F.error(K.red(`Local Maestro run failed with exit code ${u}`)),f}async function Ii(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await fo({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(yi(d))return null;r=d}let o=await dd(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=So(e.maestroRetries);if(s===null)return null;let l=Ai(e.maestroEnv),a=td(e.maestroEnv);!e.quiet&&l.length>0&&F.info(K.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await sd(e,n);if(c===null)return null;let u=Wt();e.quiet||u.start("Queuing Maestro run...");try{let d=await k.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let f=d.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${Je}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return wo(e,p),e.quiet||u.stop("Maestro run queued"),p}catch(d){e.quiet||u.stop("Could not queue Maestro run");let f=d.response?.data?.message||d.message||"Unknown error";return F.error(K.red(`Maestro queue failed: ${f}`)),null}}async function od(e,t){let n=oo(e.waitTimeout,60,"--wait-timeout"),i=oo(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(K.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await ld(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(K.dim(`Maestro status: ${l}`))),Ql.has(String(a.status)))return wo(e,a),a.status==="passed"?F.success(K.green(`Maestro run passed: ${a.testRunId}`)):(F.error(K.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(K.red(String(a.error)))),a;await wi(o)}return F.error(K.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function sd(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Y.resolve(n);if(!L.existsSync(i))return e.maestroFlows?(F.error(K.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Y.relative(process.cwd(),i);if(!r||r.startsWith("..")||Y.isAbsolute(r))return F.error(K.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Wt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await k.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:Xl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new En;if(L.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Y.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Y.basename(r))}let c=l.toBuffer();return await ad(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return F.error(K.red(`Maestro flow upload failed: ${l}`)),null}}function ho(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function ad(e,t,n,i,r){let o;for(let s=1;s<=ro;s+=1)try{await zt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:ed});return}catch(l){if(o=l,!ho(l)||s>=ro)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await wi(a)}throw o}async function ld(e,t){try{let n=await k.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${Je}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(K.red(`Could not fetch Maestro run status: ${i}`)),null}}async function dd(e){if(e.buildId)return{kind:"build-id",value:e.buildId};if(e.buildUrl)return{kind:"build-url",value:e.buildUrl};if(e.artifactUrl)return{kind:"artifact-url",value:e.artifactUrl};if(e.latest)return{kind:"latest"};let t=await fo({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(yi(t))return null;if(t==="latest")return{kind:"latest"};let n=await Zl({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return yi(n)?null:{kind:t,value:String(n).trim()}}function oo(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function wi(e){return new Promise(t=>setTimeout(t,e))}function So(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function cd(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Ri(e.artifactUrl),name:Io(e.artifactUrl)};let t=e.buildId||Td(e.buildUrl);return t?yo(t,e.platform):e.latest?ud(e):null}async function yo(e,t){let n=Wt();n.start(`Resolving build ${e}...`);try{let i=await k.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Nd(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||Ri(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(K.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function ud(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=Wt();r.start("Resolving latest build...");try{let o=await k.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),yo(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(K.red(`Latest build lookup failed: ${s}`)),null}}async function pd(e){let t=e.platform||Ri(e.url);if(!t)return F.error(K.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=L.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-")),i=e.name||Io(e.url)||(t==="android"?"app.apk":"app.zip"),r=Y.join(n,i),o=Wt();o.start(`Downloading ${i}...`);try{await bi(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(K.red(s.message||"Failed to download artifact")),!1}return t==="android"?Dd(r):Cd(r,n)}async function bi(e,t){let n=await zt.get(e,{responseType:"stream"});await ql(n.data,L.createWriteStream(t))}function fd(e,t=12e3){try{return L.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function so(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function md(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function gd(e,t){let n=Y.resolve(e,t||".maestro"),i=Y.relative(e,n);if(i.startsWith("..")||Y.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function bo(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function hd(e){return/\[Failed\]\s+/.test(e)}function Sd(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function Eo(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&L.appendFileSync(o,`
1347
- $ ${bo(e,t)}
1348
- `),new Promise(a=>{let c=!1,u=!1,d="",f=y=>{u||(u=!0,a(y))},p=po(e,t,{cwd:i,env:r,stdio:["ignore","pipe","pipe"]}),g=y=>{d+=y;let _=d.split(/\r?\n/);d=_.pop()||"";for(let D of _)if(l&&hd(D)&&!c){c=!0;let b="Mach fast-fail: detected failed Maestro flow; stopping this attempt early to retry...";o&&L.appendFileSync(o,`
1388
+ `}`)},f=async(p,g)=>{try{await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:p,error:g,logPreview:gc(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(y){c(`[WARN] Could not post runner update: ${y.message||y}`)}};try{c(`Mach Maestro local runner starting for ${n}`);let p=await zt.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(p.data?.status!=="success"||!p.data?.payload)throw new Error(p.data?.message||"Runner payload was not returned.");a=p.data.payload;let g=Object.keys(a.env||{});c(`Using Maestro env vars: ${g.length>0?g.join(", "):"none"}`);let y={...process.env,...a.env||{}},_=hc(a.env);_.length>0&&c(`Passing Maestro env vars to test command: ${g.sort().join(", ")}`),await f("running");let D=a.platform==="android"?"app.apk":"app.zip",b=Y.join(o,D),L=Y.join(o,"source.zip"),A=Y.join(o,"source");x.mkdirSync(A,{recursive:!0}),c("Downloading app artifact..."),await bi(a.artifactUrl,b),c(`Downloaded app artifact: ${D} (${lo(x.statSync(b).size)})`),c("Downloading Maestro source..."),await bi(a.urls.sourceUrl,L),c(`Downloaded Maestro source: source.zip (${lo(x.statSync(L).size)})`),new En(L).extractAllTo(A,!0);let B=Sc(A,a.flowPath||".maestro");if(!x.existsSync(B))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(c(`Resolved Maestro flow path: ${Y.relative(A,B)||"."}`),a.platform==="ios"){await wc(a.device||"iphone_15",l);let C=_c(b,o),h=wo(C,l);c(`Resolved iOS app bundle: ${C}`),c(`Resolved iOS bundle id: ${h||"unknown"}`),$c(C,l),Ei("xcrun",["simctl","install","booted",C],l),h&&(u={platform:a.platform,appId:h}),h&&ot("xcrun",["simctl","get_app_container","booted",h,"app"],l),gi(s,l,"ios-before-maestro.png"),a.record&&(d=Rc(s,l))}else{let C=Oc(b,l),h=Pc(a.device,l),M=h?["-s",h]:[];c(`Resolved Android application id: ${C||"unknown"}`),Ei("adb",[...M,"install","-r",b],l),C&&(u={platform:a.platform,appId:C,deviceId:h||void 0})}let P=Math.max(0,Math.min(10,Number(a.retries??1)))+1,I=Y.join(s,"report.xml"),T=Ac(l);if(!T)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let w=1;for(let C=1;C<=P;C+=1){c(`Running Maestro attempt ${C}/${P}...`);let h=["test","--platform",a.platform,..._,B,"--format","junit","--output",I,"--test-output-dir",s];if(So&&C<P?w=(await Io(T,h,{logPath:l,env:y,fastFailOnFlowFailure:!0})).exitCode:w=ot(T,h,l,void 0,y),w===0)break}return a.platform==="ios"&&gi(s,l,"ios-after-maestro.png"),await co(d,l),d=null,await fo(a.urls,o,s,l),w===0?(await f("passed"),F.success(K.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:P,flows:a.flowPath,platform:a.platform}):(await f("failed",`Maestro exited with code ${w}`),F.error(K.red(`Managed Maestro run failed with exit code ${w}`)),{status:"failed",exitCode:w,attempts:P,flows:a.flowPath,platform:a.platform})}catch(p){let g=p.message||String(p);return c(`MACH_MAESTRO_RUN_FAILED: ${g}`),a?.platform==="ios"&&gi(s,l,"ios-after-failure.png"),await co(d,l),a?.urls&&await fo(a.urls,o,s,l),await f("failed",g),F.error(K.red(`Managed Maestro runner failed: ${g}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{vc(u,l)}}async function sc(e){let t=e.maestroFlows||".maestro",n=bo(e.maestroRetries);if(n===null)return null;let i=Y.resolve(t);if(!x.existsSync(i))return F.error(K.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await pc(e);if(r?.url){if(!await mc(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&F.warn(K.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=rc(e.maestroEnv),a=Object.keys(l);if(a.length>0){F.info(K.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,g]of Object.entries(l))s.push("-e",`${p}=${g}`)}s.push(t);let d=n+1,u=1;for(let p=1;p<=d;p+=1){if(F.info(K.dim(`Running local Maestro attempt ${p}/${d}...`)),So&&p<d){let g=await Io("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=g.exitCode}else{let g=Ge("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(g.error){let y=g.error.message||"Failed to run Maestro";F.error(K.red(`Local Maestro failed to start: ${y}`)),F.info(K.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof g.status=="number"?g.status:1}if(u===0)break}let c=u===0?"passed":"failed",f={status:c,exitCode:u,attempts:d,flows:t,platform:o};return xc(e,f),c==="passed"?F.success(K.green("Local Maestro run passed")):F.error(K.red(`Local Maestro run failed with exit code ${u}`)),f}async function Ii(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let c=await go({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(yi(c))return null;r=c}let o=await uc(e);if(!o)return null;if(o.kind==="latest"&&!r)return F.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return F.error("Pass --platform when using --artifact-url."),null;let s=bo(e.maestroRetries);if(s===null)return null;let l=Ai(e.maestroEnv),a=ic(e.maestroEnv);!e.quiet&&l.length>0&&F.info(K.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let d=await lc(e,n);if(d===null)return null;let u=Wt();e.quiet||u.start("Queuing Maestro run...");try{let c=await k.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:d,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(c.data.status!=="success")throw new Error(c.data.message||"Failed to queue Maestro run");let f=c.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${Je}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return Ro(e,p),e.quiet||u.stop("Maestro run queued"),p}catch(c){e.quiet||u.stop("Could not queue Maestro run");let f=c.response?.data?.message||c.message||"Unknown error";return F.error(K.red(`Maestro queue failed: ${f}`)),null}}async function ac(e,t){let n=ao(e.waitTimeout,60,"--wait-timeout"),i=ao(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(F.info(K.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await dc(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,F.info(K.dim(`Maestro status: ${l}`))),tc.has(String(a.status)))return Ro(e,a),a.status==="passed"?F.success(K.green(`Maestro run passed: ${a.testRunId}`)):(F.error(K.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&F.error(K.red(String(a.error)))),a;await wi(o)}return F.error(K.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function lc(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Y.resolve(n);if(!x.existsSync(i))return e.maestroFlows?(F.error(K.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Y.relative(process.cwd(),i);if(!r||r.startsWith("..")||Y.isAbsolute(r))return F.error(K.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Wt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await k.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:Zl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new En;if(x.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Y.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Y.basename(r))}let d=l.toBuffer();return await cc(s.data.uploadUrl,d,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return F.error(K.red(`Maestro flow upload failed: ${l}`)),null}}function yo(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function cc(e,t,n,i,r){let o;for(let s=1;s<=so;s+=1)try{await zt.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:nc});return}catch(l){if(o=l,!yo(l)||s>=so)break;let a=Math.min(2e4,2e3*s),d=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${d}), retrying...`),await wi(a)}throw o}async function dc(e,t){try{let n=await k.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${Je}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return F.error(K.red(`Could not fetch Maestro run status: ${i}`)),null}}async function uc(e){if(e.buildId)return{kind:"build-id",value:e.buildId};if(e.buildUrl)return{kind:"build-url",value:e.buildUrl};if(e.artifactUrl)return{kind:"artifact-url",value:e.artifactUrl};if(e.latest)return{kind:"latest"};let t=await go({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(yi(t))return null;if(t==="latest")return{kind:"latest"};let n=await ec({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return yi(n)?null:{kind:t,value:String(n).trim()}}function ao(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(F.error(`${n} must be a positive number.`),null):i}function wi(e){return new Promise(t=>setTimeout(t,e))}function bo(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(F.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function pc(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Ri(e.artifactUrl),name:_o(e.artifactUrl)};let t=e.buildId||Lc(e.buildUrl);return t?Eo(t,e.platform):e.latest?fc(e):null}async function Eo(e,t){let n=Wt();n.start(`Resolving build ${e}...`);try{let i=await k.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=kc(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||Ri(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return F.error(K.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function fc(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return F.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return F.error("Pass --platform when using --latest with --local."),null;let r=Wt();r.start("Resolving latest build...");try{let o=await k.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Eo(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return F.error(K.red(`Latest build lookup failed: ${s}`)),null}}async function mc(e){let t=e.platform||Ri(e.url);if(!t)return F.error(K.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=x.mkdtempSync(Y.join(Tt.tmpdir(),"mach-maestro-")),i=e.name||_o(e.url)||(t==="android"?"app.apk":"app.zip"),r=Y.join(n,i),o=Wt();o.start(`Downloading ${i}...`);try{await bi(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),F.error(K.red(s.message||"Failed to download artifact")),!1}return t==="android"?Nc(r):Tc(r,n)}async function bi(e,t){let n=await zt.get(e,{responseType:"stream"});await Ql(n.data,x.createWriteStream(t))}function gc(e,t=12e3){try{return x.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function lo(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function hc(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function Sc(e,t){let n=Y.resolve(e,t||".maestro"),i=Y.relative(e,n);if(i.startsWith("..")||Y.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Ao(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function yc(e){return/\[Failed\]\s+/.test(e)}function bc(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function Io(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&x.appendFileSync(o,`
1389
+ $ ${Ao(e,t)}
1390
+ `),new Promise(a=>{let d=!1,u=!1,c="",f=y=>{u||(u=!0,a(y))},p=mo(e,t,{cwd:i,env:r,stdio:["ignore","pipe","pipe"]}),g=y=>{c+=y;let _=c.split(/\r?\n/);c=_.pop()||"";for(let D of _)if(l&&yc(D)&&!d){d=!0;let b="Mach fast-fail: detected failed Maestro flow; stopping this attempt early to retry...";o&&x.appendFileSync(o,`
1349
1391
  ${b}
1350
1392
  `),s&&process.stderr.write(`${b}
1351
- `),Sd(p)}};p.stdout?.on("data",y=>{let _=y.toString();o&&L.appendFileSync(o,_),s&&process.stdout.write(_),g(_)}),p.stderr?.on("data",y=>{let _=y.toString();o&&L.appendFileSync(o,_),s&&process.stderr.write(_),g(_)}),p.on("error",y=>{o&&L.appendFileSync(o,`${y.message}
1352
- `),f({exitCode:1,fastFailed:c,error:y})}),p.on("close",(y,_)=>{c&&o&&L.appendFileSync(o,`Maestro attempt stopped after first failed flow${_?` (${_})`:""}.
1353
- `),f({exitCode:typeof y=="number"?y:1,fastFailed:c})})})}function ot(e,t,n,i,r=process.env){L.appendFileSync(n,`
1354
- $ ${bo(e,t)}
1355
- `);let o=Ge(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&L.appendFileSync(n,o.stdout),o.stderr&&L.appendFileSync(n,o.stderr),o.error?(L.appendFileSync(n,`${o.error.message}
1356
- `),1):typeof o.status=="number"?o.status:1}function Ei(e,t,n,i){let r=ot(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function yd(e){try{return L.accessSync(e,L.constants.X_OK),!0}catch{return!1}}function bd(e){let t=[process.env.MAESTRO_BIN,Y.join(Tt.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=Ge("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
1357
- `)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&yd(r))return e&&L.appendFileSync(e,`Using Maestro CLI at ${r}
1358
- `),r;return e&&L.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
1359
- `),null}function Ed(e){let t=String(e||"").trim();return t?t.replace(/_/g," ").replace(/\bios\b/gi,"").replace(/\biphone\b/i,"iPhone").replace(/\s+/g," ").trim():"iPhone 15"}async function Ad(e,t){if((Ge("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){L.appendFileSync(t,`Using already booted iOS Simulator.
1360
- `);return}let i=Ed(e),r=Ge("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(c=>Array.isArray(c)?c:[]).filter(c=>c?.isAvailable),l=s.find(c=>c.name===i)||s.find(c=>String(c.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(c=>String(c.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);L.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
1361
- `),ot("xcrun",["simctl","boot",l.udid],t)!==0&&L.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
1362
- `),Ei("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function Id(e,t){if(e.endsWith(".ipa"))throw new Error("iOS Maestro runs need a simulator .app.zip artifact, not an App Store .ipa.");if(e.endsWith(".zip")){let n=Y.join(t,"ios-app");L.mkdirSync(n,{recursive:!0}),new En(e).extractAllTo(n,!0);let i=_i(n);if(!i)throw new Error("Could not find a .app bundle inside the iOS artifact zip.");return i}if(e.endsWith(".app"))return e;throw new Error("iOS Maestro runs need a .app bundle or .app.zip artifact.")}function Ao(e,t){let n=Y.join(e,"Info.plist");if(!L.existsSync(n))return L.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
1363
- `),null;let i=Ge("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(L.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
1364
- `),null):r}function gi(e,t,n){let i=Y.join(e,n);ot("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&L.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
1365
- `)}function wd(e,t){let n=Y.join(e,"ios-simulator-recording.mp4");L.appendFileSync(t,`Starting iOS simulator recording: ${n}
1366
- `);let i=po("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{L.appendFileSync(t,r)}),i.stderr?.on("data",r=>{L.appendFileSync(t,r)}),i.on("error",r=>{L.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
1367
- `)}),i}async function ao(e,t){e&&await new Promise(n=>{let i=!1,r=()=>{i||(i=!0,n())};e.once("exit",r),e.once("close",r),e.killed||(L.appendFileSync(t,`Stopping iOS simulator recording...
1368
- `),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(L.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
1369
- `),e.kill("SIGKILL")),r()},5e3).unref?.()})}function _d(e,t){let n=Ao(e,t);if(!n)return;L.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
1370
- `),ot("xcrun",["simctl","uninstall","booted",n],t)!==0&&L.appendFileSync(t,`No existing app install removed for ${n}; continuing.
1371
- `)}function Rd(e,t){if(!e?.appId)return;if(L.appendFileSync(t,`Cleaning up installed app after Maestro run...
1372
- `),e.platform==="ios"){let r=ot("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?L.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
1373
- `):L.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
1374
- `);return}let n=e.deviceId?["-s",e.deviceId]:[],i=ot("adb",[...n,"uninstall",e.appId],t);i===0?L.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
1375
- `):L.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
1376
- `)}function $d(e,t){let n=Ge("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return L.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
1393
+ `),bc(p)}};p.stdout?.on("data",y=>{let _=y.toString();o&&x.appendFileSync(o,_),s&&process.stdout.write(_),g(_)}),p.stderr?.on("data",y=>{let _=y.toString();o&&x.appendFileSync(o,_),s&&process.stderr.write(_),g(_)}),p.on("error",y=>{o&&x.appendFileSync(o,`${y.message}
1394
+ `),f({exitCode:1,fastFailed:d,error:y})}),p.on("close",(y,_)=>{d&&o&&x.appendFileSync(o,`Maestro attempt stopped after first failed flow${_?` (${_})`:""}.
1395
+ `),f({exitCode:typeof y=="number"?y:1,fastFailed:d})})})}function ot(e,t,n,i,r=process.env){x.appendFileSync(n,`
1396
+ $ ${Ao(e,t)}
1397
+ `);let o=Ge(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&x.appendFileSync(n,o.stdout),o.stderr&&x.appendFileSync(n,o.stderr),o.error?(x.appendFileSync(n,`${o.error.message}
1398
+ `),1):typeof o.status=="number"?o.status:1}function Ei(e,t,n,i){let r=ot(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function Ec(e){try{return x.accessSync(e,x.constants.X_OK),!0}catch{return!1}}function Ac(e){let t=[process.env.MAESTRO_BIN,Y.join(Tt.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=Ge("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
1399
+ `)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&Ec(r))return e&&x.appendFileSync(e,`Using Maestro CLI at ${r}
1400
+ `),r;return e&&x.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
1401
+ `),null}function Ic(e){let t=String(e||"").trim();return t?t.replace(/_/g," ").replace(/\bios\b/gi,"").replace(/\biphone\b/i,"iPhone").replace(/\s+/g," ").trim():"iPhone 15"}async function wc(e,t){if((Ge("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){x.appendFileSync(t,`Using already booted iOS Simulator.
1402
+ `);return}let i=Ic(e),r=Ge("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(d=>Array.isArray(d)?d:[]).filter(d=>d?.isAvailable),l=s.find(d=>d.name===i)||s.find(d=>String(d.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(d=>String(d.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);x.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
1403
+ `),ot("xcrun",["simctl","boot",l.udid],t)!==0&&x.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
1404
+ `),Ei("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function _c(e,t){if(e.endsWith(".ipa"))throw new Error("iOS Maestro runs need a simulator .app.zip artifact, not an App Store .ipa.");if(e.endsWith(".zip")){let n=Y.join(t,"ios-app");x.mkdirSync(n,{recursive:!0}),new En(e).extractAllTo(n,!0);let i=_i(n);if(!i)throw new Error("Could not find a .app bundle inside the iOS artifact zip.");return i}if(e.endsWith(".app"))return e;throw new Error("iOS Maestro runs need a .app bundle or .app.zip artifact.")}function wo(e,t){let n=Y.join(e,"Info.plist");if(!x.existsSync(n))return x.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
1405
+ `),null;let i=Ge("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(x.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
1406
+ `),null):r}function gi(e,t,n){let i=Y.join(e,n);ot("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&x.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
1407
+ `)}function Rc(e,t){let n=Y.join(e,"ios-simulator-recording.mp4");x.appendFileSync(t,`Starting iOS simulator recording: ${n}
1408
+ `);let i=mo("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{x.appendFileSync(t,r)}),i.stderr?.on("data",r=>{x.appendFileSync(t,r)}),i.on("error",r=>{x.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
1409
+ `)}),i}async function co(e,t){e&&await new Promise(n=>{let i=!1,r=()=>{i||(i=!0,n())};e.once("exit",r),e.once("close",r),e.killed||(x.appendFileSync(t,`Stopping iOS simulator recording...
1410
+ `),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(x.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
1411
+ `),e.kill("SIGKILL")),r()},5e3).unref?.()})}function $c(e,t){let n=wo(e,t);if(!n)return;x.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
1412
+ `),ot("xcrun",["simctl","uninstall","booted",n],t)!==0&&x.appendFileSync(t,`No existing app install removed for ${n}; continuing.
1413
+ `)}function vc(e,t){if(!e?.appId)return;if(x.appendFileSync(t,`Cleaning up installed app after Maestro run...
1414
+ `),e.platform==="ios"){let r=ot("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?x.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
1415
+ `):x.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
1416
+ `);return}let n=e.deviceId?["-s",e.deviceId]:[],i=ot("adb",[...n,"uninstall",e.appId],t);i===0?x.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
1417
+ `):x.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
1418
+ `)}function Pc(e,t){let n=Ge("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return x.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
1377
1419
  `),null;let i=String(n.stdout||"").split(`
1378
- `).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(L.appendFileSync(t,`Using Android device ${e} for install and cleanup.
1379
- `),e):i.length===1?(L.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
1380
- `),i[0]):(i.length>1&&L.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
1381
- `),null)}function vd(e,t){let i=(hi("aapt",["dump","badging",e])||hi("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=hi("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(L.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
1382
- `),null)}function hi(e,t){for(let n of Pd(e)){let i=Ge(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function Pd(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of lo()){let o=Y.join(r,"build-tools");for(let s of co(o))n.push(Y.join(o,s,t))}if(e==="apkanalyzer")for(let r of lo()){n.push(Y.join(r,"cmdline-tools","latest","bin",t));let o=Y.join(r,"cmdline-tools");for(let s of co(o))n.push(Y.join(o,s,"bin",t));n.push(Y.join(r,"tools","bin",t))}let i=Od(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function lo(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(Y.join(Tt.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(Y.join(Tt.homedir(),"Android","Sdk"),Y.join(Tt.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function co(e){try{return L.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function Od(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=Ge(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
1383
- `)[0]?.trim()||null}async function Si(e,t,n){if(!L.existsSync(e))return;let i=L.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await zt.put(t,i,{headers:{"Content-Type":n,"Content-Length":String(i.length)},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4});return}catch(s){if(r=s,!ho(s)||o>=3)break;await wi(2e3*o)}throw r}async function uo(e,t,n,i){let r=Y.join(n,"report.xml"),o=Y.join(t,"artifacts.tar.gz");try{await Si(r,e.junitUploadUrl,"application/xml")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
1384
- `)}try{await Si(i,e.logUploadUrl,"text/plain")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
1385
- `)}try{ot("tar",["-czf",o,"-C",t,Y.basename(n)],i),await Si(o,e.artifactsUploadUrl,"application/gzip")}catch(s){L.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
1386
- `)}}function Dd(e){if(!e.endsWith(".apk"))return F.error(K.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(K.dim("Installing APK on local Android device/emulator..."));let t=Ge("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(K.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(K.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Cd(e,t){if(e.endsWith(".ipa"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=Y.join(t,"ios-app");L.mkdirSync(r,{recursive:!0}),new En(e).extractAllTo(r,!0);let o=_i(r);if(!o)return F.error(K.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(K.dim("Installing app on booted iOS Simulator..."));let i=Ge("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(K.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(K.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function _i(e){let t=L.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Y.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=_i(i);if(r)return r}}return null}function Nd(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>Nt(i,".apk")):n==="ios"?e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip")):e.find(i=>Nt(i,".apk"))||e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip"))}function Nt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Ri(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function Io(e){if(e)try{return Y.basename(new URL(e).pathname)||void 0}catch{return Y.basename(e)||void 0}}function Td(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function wo(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&L.mkdirSync(r,{recursive:!0}),L.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function kd(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&L.mkdirSync(r,{recursive:!0}),L.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as ut,text as Yt,select as Di,isCancel as dt,cancel as Ci,log as Do}from"@clack/prompts";import ne from"chalk";import oe from"fs";import Ie from"path";import{spawn as xd,spawnSync as It}from"child_process";import Co from"axios";import _t from"os";import ki from"crypto";var Ld=5e3,Md=12,No=100,$i=24,_o=8e3,Ud={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Fd=e=>e?.type==="google_service_account",In=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,To=e=>e.submitArgs||process.argv.slice(3).join(" ");async function wn(e){let t=ut(),n=Pe(),i=Bd(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,me(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let h=await Di({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(dt(h)){Ci("Operation cancelled");return}s=h}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?nc(i,o,e):null;if(s==="ios"&&!e.local&&!l){await Hd(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(h,M={})=>{u&&await Vd(r,u,{status:h,...M})},f=s==="android"?e.packageName||e.androidPackage||Qd(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||tc(i,o):void 0,g,y,_,D=!1;try{s==="android"&&(g=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",y=ic(i,o,e.releaseStatus),_=oc(i,o,e.rollout),D=sc(i,o,e.changesNotSentForReview),ac(y,_))}catch(h){le(h.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await jd(i,r,s,o,e,{packageName:f,track:g,releaseStatus:y,rollout:_,changesNotSentForReview:D}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:f,track:g,releaseStatus:y,rollout:_,startTime:Date.now(),...c?Wd():{}});let b=null,x=null;try{x=await lc(r,s,e,n?.token),b=x?.filePath||null}catch(h){await d("failed",{error:`Failed to resolve submission artifact: ${h.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${h.message}`),process.exitCode=1;return}if(!b){let h=cc(s,e);await d("failed",{error:h,endTime:Date.now()}),le(h),process.exitCode=1;return}await d("running",{buildId:x?.buildId,artifactName:x?.artifactName,artifactSource:x?.source}),me(`Using artifact: ${ne.green(Ie.basename(b))} `),t.start("Fetching submission credentials from Dashboard...");let A;try{let M=(await k.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let U=M.filter(Fd),j=s==="ios"?M.filter(X=>X.type==="asc_api_key"):ec(U,f);if(j.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let X=U.map(In).filter(Boolean).join(", ");X&&me(`Found Google Play service credential(s) for: ${X}`),me(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else me(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(A=Jd(j,e.credentialId),!A&&s==="ios"&&p&&(A=Xd(j,p)),A||j.length===1)A=A||j[0],t.stop(`Using: ${A.name}`),s==="android"&&In(A)==="*"&&me(ne.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),qd()){let H=j.map(N=>`${N.name||"credential"} (${N.credentialId||N.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${H}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let X=await Di({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:j.map(H=>({value:H.credentialId,label:H.name,hint:`${H.keyId?`ID: ${H.keyId}`:""} ${H.issuerId?`(Issuer: ${H.issuerId.substring(0,8)}...)`:""}`}))});if(dt(X)){Ci("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}A=j.find(H=>H.credentialId===X),me(`Using selected: ${ne.green(A.name)}`)}}catch(h){t.stop("Failed to fetch credentials"),le(`API Error: ${h.message} `),await d("failed",{error:`Failed to fetch credentials: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}let B=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-submit-`)),q=A.keyId||A.meta?.keyId,P=A.issuerId||A.meta?.issuerId,I=A.type==="asc_api_key"?`AuthKey_${q}.p8`:"service-account.json",T=Ie.join(B,I);t.start("Downloading secure key...");try{let h=await k.get(`/credentials/${A.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let M=await Co.get(h.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(T,Buffer.from(M.data)),t.stop("Key downloaded to secure temp storage")}catch(h){t.stop("Download failed"),le(`Failed to download key: ${h.message}`);try{oe.rmSync(B,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}me(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let w=!1,C;try{if(s==="ios"){if(!q){let M=await Yt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:U=>U.length>0?void 0:"Key ID is required"});if(dt(M)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}q=M}if(!P||P==="undefined"){let M=await Yt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:U=>U.length>0?void 0:"Issuer ID is required"});if(dt(M)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}P=M}me(`Using ASC Key ID: ${q}`),me(`Using ASC Issuer ID: ${P}`);let h=l?await pc(b,T,P,q,p,l):await uc(b,T,P,q,p);Ti(`${s==="ios"?"App Store":"Google Play"} submission successful!`),w=!0}else C=await Sc(b,T,g||"internal",f,y||"completed",_,D,o),Ti("Google Play submission successful!"),w=!0}catch(h){le(`Submission failed: ${h.message}`),await d("failed",{error:h.message,endTime:Date.now()}),ct(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:x?.buildId||e.buildId,artifactName:x?.artifactName,error:h.message,dashboardUrl:u?wt(u,r):void 0}),process.exitCode=1}finally{w&&(await d("success",{endTime:Date.now(),versionCode:C?.versionCode,track:g,releaseStatus:y}),ct(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:x?.buildId||e.buildId,artifactName:x?.artifactName,versionCode:C?.versionCode,track:g,releaseStatus:y,dashboardUrl:u?wt(u,r):void 0})),Nc(B),b&&b.includes(`${m.nameLower}-artifact-`)}}function Bd(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function Hd(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||ki.randomUUID(),o=!!n.latest||!n.buildId,s=Gd({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:To(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(Zd).join(" "),appName:e.name,startTime:Date.now()},a=ut();a.start("Queuing iOS submit on macOS runner...");try{let c=await k.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||wt(r,i);a.stop("iOS submit queued"),me(`Submission ID: ${ne.cyan(r)}`),me(`Dashboard: ${ne.blue.underline(d)}`),ct(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await Kd(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(Yd(c)),process.exitCode=1}}async function jd(e,t,n,i,r,o={}){let s=r.submitId||ki.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:To(r),appName:e.name,startTime:Date.now(),...o};try{let c=await k.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||wt(s,t);return me(`Submission ID: ${ne.cyan(s)}`),me(`Dashboard: ${ne.blue.underline(d)}`),ct(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return me(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function Gd(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function Kd(e,t,n){let i=ut(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await k.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(ne.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Ti("App Store submission successful!"),ct(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||wt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ct(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||wt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ni(Ld)}catch(s){if(r++,r>=Md){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Ni(Math.min(2e3*r,15e3))}}async function Vd(e,t,n){let i;for(let r=1;r<=3;r++)try{await k.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!zd(o))break;await Ni(1e3*r)}Do.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function zd(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Wd(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function Yd(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
1387
- `):n||e.message||String(e)}function wt(e,t){if(!e)return Je;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Je}/submissions/${e}${n}`}function ct(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||wt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){Do.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function Jd(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Xd(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function qd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ni(e){return new Promise(t=>setTimeout(t,e))}function Zd(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Qd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=hr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function ec(e,t){let n=e.filter(o=>In(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=In(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function tc(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Sr(e,t)}function nc(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function ic(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return rc(i)}function rc(e){let t=Ud[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function oc(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function sc(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function ac(e,t){if(e==="inProgress"&&t===void 0)throw new Error("Google Play staged rollout requires --rollout <fraction> when --release-status inProgress is used.");if(e!=="inProgress"&&e!=="halted"&&t!==void 0)throw new Error("Android rollout fraction can only be used with --release-status inProgress or halted.")}async function lc(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Di({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(dt(s))return Ci("Operation cancelled"),null;r=s}if(r==="local"){let s=await Yt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return dt(s)?null:{filePath:s,source:"local"}}let o=ut();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await k.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success",d=A=>c?[A.buildProfile,A.profile,A.profileName,A.buildType].filter(Boolean).some(B=>String(B).toLowerCase()===c):!0,f=a.filter(A=>u(A)&&d(A)),p=f.find(A=>A.buildType?.toLowerCase()==="store"||A.distribution?.toLowerCase()==="store")||f[0],g=a.some(A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&g?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let y=p.artifacts||[];if(y.length===0||y.every(A=>!(A.url||A.downloadUrl)))try{let A=await k.get(`/builds/${e}/${p.buildId}/artifacts`);A.data.status==="success"&&A.data.artifacts?.length>0?(y=A.data.artifacts.map(B=>({...B,url:B.url||B.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${y.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(A){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${A.message}`))}let D=t==="ios",b=y.find(A=>{let B=(A.type||"").toLowerCase(),q=(A.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${A.name} (Type: ${A.type}, HasLink: ${!!(A.url||A.downloadUrl)})`)),B)return B===(D?"ipa":"aab");let P=D?".ipa":".aab",I=(A.url||A.downloadUrl||"").toLowerCase();return q.endsWith(P)||I.includes(P)});if(!b||!(b.url||b.downloadUrl))return le("Build found but artifact URL is missing."),null;let x=b.url||b.downloadUrl;return{filePath:await vi(x,D?"ios":"android"),buildId:p.buildId,artifactName:b.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Yt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(dt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await k.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await k.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=An(a.artifacts);dc(u)||(u=await $o(e,l,u));let d=Ro(u,t);if(d||(u=await $o(e,l,u),d=Ro(u,t)),!d)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let f=d.url||d.downloadUrl;if(!f)throw new Error(`Artifact ${d.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await vi(f,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Yt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return dt(s)?null:{filePath:await vi(s,t),source:"url"}}return null}function An(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function dc(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Ro(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function cc(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function $o(e,t,n){try{let i=await k.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await k.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return An(n)}async function vi(e,t,n=3){let i=ut();i.start("Downloading artifact...");let r=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=oe.createWriteStream(s),c=await Co({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let f=!1;c.data.on("error",p=>{f||(f=!0,a.close(),d(p))}),a.on("finish",()=>{f||u()}),a.on("error",p=>{f||(f=!0,d(p))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function uc(e,t,n,i,r){let o=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=ko(t,n,i),l=bc();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=Ac(),d=xd(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});d.stdout?.on("data",f=>u.append(f,process.stdout)),d.stderr?.on("data",f=>u.append(f,process.stderr)),d.on("close",f=>{if(u.flush(),f!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}c(Ic(f,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),d.on("error",f=>{u.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Dc(f);p.logs=u.lines(),c(p)})})}async function pc(e,t,n,i,r,o){let s=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=ko(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=fc(o),u=mc(o),d="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=gc("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Pi("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Pi("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(_t.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(f,hc(d)),Pi("scp",[...u,f,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let p=`chmod +x ${Jt(`${d}/submit.sh`)} && bash ${Jt(`${d}/submit.sh`)}`,g=It("ssh",[...c,p],{stdio:"inherit"});if(g.error)throw xi("ssh",g.error);if(g.status!==0)throw new Error(`Remote iOS submit failed with exit code ${g.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{oe.unlinkSync(l)}catch{}if(f)try{oe.unlinkSync(f)}catch{}if(d)try{It("ssh",[...c,`rm -rf ${Jt(d)}`],{stdio:"ignore"})}catch{}}}function ko(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=ki.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{me("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
1420
+ `).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(x.appendFileSync(t,`Using Android device ${e} for install and cleanup.
1421
+ `),e):i.length===1?(x.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
1422
+ `),i[0]):(i.length>1&&x.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
1423
+ `),null)}function Oc(e,t){let i=(hi("aapt",["dump","badging",e])||hi("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=hi("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(x.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
1424
+ `),null)}function hi(e,t){for(let n of Dc(e)){let i=Ge(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function Dc(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of uo()){let o=Y.join(r,"build-tools");for(let s of po(o))n.push(Y.join(o,s,t))}if(e==="apkanalyzer")for(let r of uo()){n.push(Y.join(r,"cmdline-tools","latest","bin",t));let o=Y.join(r,"cmdline-tools");for(let s of po(o))n.push(Y.join(o,s,"bin",t));n.push(Y.join(r,"tools","bin",t))}let i=Cc(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function uo(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(Y.join(Tt.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(Y.join(Tt.homedir(),"Android","Sdk"),Y.join(Tt.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function po(e){try{return x.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function Cc(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=Ge(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
1425
+ `)[0]?.trim()||null}async function Si(e,t,n){if(!x.existsSync(e))return;let i=x.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await zt.put(t,i,{headers:{"Content-Type":n,"Content-Length":String(i.length)},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4});return}catch(s){if(r=s,!yo(s)||o>=3)break;await wi(2e3*o)}throw r}async function fo(e,t,n,i){let r=Y.join(n,"report.xml"),o=Y.join(t,"artifacts.tar.gz");try{await Si(r,e.junitUploadUrl,"application/xml")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
1426
+ `)}try{await Si(i,e.logUploadUrl,"text/plain")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
1427
+ `)}try{ot("tar",["-czf",o,"-C",t,Y.basename(n)],i),await Si(o,e.artifactsUploadUrl,"application/gzip")}catch(s){x.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
1428
+ `)}}function Nc(e){if(!e.endsWith(".apk"))return F.error(K.red("Local Android Maestro runs need an APK artifact.")),!1;F.info(K.dim("Installing APK on local Android device/emulator..."));let t=Ge("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(F.error(K.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(F.error(K.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Tc(e,t){if(e.endsWith(".ipa"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=Y.join(t,"ios-app");x.mkdirSync(r,{recursive:!0}),new En(e).extractAllTo(r,!0);let o=_i(r);if(!o)return F.error(K.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return F.error(K.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;F.info(K.dim("Installing app on booted iOS Simulator..."));let i=Ge("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(F.error(K.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(F.error(K.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function _i(e){let t=x.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Y.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=_i(i);if(r)return r}}return null}function kc(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>Nt(i,".apk")):n==="ios"?e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip")):e.find(i=>Nt(i,".apk"))||e.find(i=>Nt(i,".app.zip"))||e.find(i=>Nt(i,".zip"))}function Nt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Ri(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function _o(e){if(e)try{return Y.basename(new URL(e).pathname)||void 0}catch{return Y.basename(e)||void 0}}function Lc(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function Ro(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function xc(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&x.mkdirSync(r,{recursive:!0}),x.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){F.warn(K.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as ut,text as Yt,select as Di,isCancel as ct,cancel as Ci,log as No}from"@clack/prompts";import ne from"chalk";import oe from"fs";import Ie from"path";import{spawn as Mc,spawnSync as It}from"child_process";import To from"axios";import _t from"os";import ki from"crypto";var Uc=5e3,Fc=12,ko=100,$i=24,$o=8e3,Bc={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Hc=e=>e?.type==="google_service_account",In=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,Lo=e=>e.submitArgs||process.argv.slice(3).join(" ");async function wn(e){let t=ut(),n=Pe(),i=jc(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,me(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let h=await Di({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ct(h)){Ci("Operation cancelled");return}s=h}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?rd(i,o,e):null;if(s==="ios"&&!e.local&&!l){await Gc(i,o,e);return}let a=e.submitId,d=!!(e.local&&a),u=a||null,c=async(h,M={})=>{u&&await Wc(r,u,{status:h,...M})},f=s==="android"?e.packageName||e.androidPackage||td(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||id(i,o):void 0,g,y,_,D=!1;try{s==="android"&&(g=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",y=od(i,o,e.releaseStatus),_=ad(i,o,e.rollout),D=ld(i,o,e.changesNotSentForReview),cd(y,_))}catch(h){le(h.message),process.exitCode=1;return}if(s==="android"&&!d&&(u=await Kc(i,r,s,o,e,{packageName:f,track:g,releaseStatus:y,rollout:_,changesNotSentForReview:D}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await c("running",{platform:s,profile:o,packageName:f,track:g,releaseStatus:y,rollout:_,startTime:Date.now(),...d?Jc():{}});let b=null,L=null;try{L=await dd(r,s,e,n?.token),b=L?.filePath||null}catch(h){await c("failed",{error:`Failed to resolve submission artifact: ${h.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${h.message}`),process.exitCode=1;return}if(!b){let h=pd(s,e);await c("failed",{error:h,endTime:Date.now()}),le(h),process.exitCode=1;return}await c("running",{buildId:L?.buildId,artifactName:L?.artifactName,artifactSource:L?.source}),me(`Using artifact: ${ne.green(Ie.basename(b))} `),t.start("Fetching submission credentials from Dashboard...");let A;try{let M=(await k.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await c("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let U=M.filter(Hc),j=s==="ios"?M.filter(X=>X.type==="asc_api_key"):nd(U,f);if(j.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let X=U.map(In).filter(Boolean).join(", ");X&&me(`Found Google Play service credential(s) for: ${X}`),me(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else me(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await c("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(A=qc(j,e.credentialId),!A&&s==="ios"&&p&&(A=Zc(j,p)),A||j.length===1)A=A||j[0],t.stop(`Using: ${A.name}`),s==="android"&&In(A)==="*"&&me(ne.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),Qc()){let H=j.map(N=>`${N.name||"credential"} (${N.credentialId||N.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${H}`),await c("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let X=await Di({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:j.map(H=>({value:H.credentialId,label:H.name,hint:`${H.keyId?`ID: ${H.keyId}`:""} ${H.issuerId?`(Issuer: ${H.issuerId.substring(0,8)}...)`:""}`}))});if(ct(X)){Ci("Submission cancelled"),await c("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}A=j.find(H=>H.credentialId===X),me(`Using selected: ${ne.green(A.name)}`)}}catch(h){t.stop("Failed to fetch credentials"),le(`API Error: ${h.message} `),await c("failed",{error:`Failed to fetch credentials: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}let B=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-submit-`)),q=A.keyId||A.meta?.keyId,P=A.issuerId||A.meta?.issuerId,I=A.type==="asc_api_key"?`AuthKey_${q}.p8`:"service-account.json",T=Ie.join(B,I);t.start("Downloading secure key...");try{let h=await k.get(`/credentials/${A.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let M=await To.get(h.data.downloadUrl,{responseType:"arraybuffer"});oe.writeFileSync(T,Buffer.from(M.data)),t.stop("Key downloaded to secure temp storage")}catch(h){t.stop("Download failed"),le(`Failed to download key: ${h.message}`);try{oe.rmSync(B,{recursive:!0,force:!0})}catch{}await c("failed",{error:`Failed to download credential key: ${h.message}`,endTime:Date.now()}),process.exitCode=1;return}me(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let w=!1,C;try{if(s==="ios"){if(!q){let M=await Yt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:U=>U.length>0?void 0:"Key ID is required"});if(ct(M)){await c("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}q=M}if(!P||P==="undefined"){let M=await Yt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:U=>U.length>0?void 0:"Issuer ID is required"});if(ct(M)){await c("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}P=M}me(`Using ASC Key ID: ${q}`),me(`Using ASC Issuer ID: ${P}`);let h=l?await md(b,T,P,q,p,l):await fd(b,T,P,q,p);Ti(`${s==="ios"?"App Store":"Google Play"} submission successful!`),w=!0}else C=await bd(b,T,g||"internal",f,y||"completed",_,D,o),Ti("Google Play submission successful!"),w=!0}catch(h){le(`Submission failed: ${h.message}`),await c("failed",{error:h.message,endTime:Date.now()}),dt(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:L?.buildId||e.buildId,artifactName:L?.artifactName,error:h.message,dashboardUrl:u?wt(u,r):void 0}),process.exitCode=1}finally{w&&(await c("success",{endTime:Date.now(),versionCode:C?.versionCode,track:g,releaseStatus:y}),dt(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:L?.buildId||e.buildId,artifactName:L?.artifactName,versionCode:C?.versionCode,track:g,releaseStatus:y,dashboardUrl:u?wt(u,r):void 0})),kd(B),b&&b.includes(`${m.nameLower}-artifact-`)}}function jc(e){let t=`./${m.configFileName}`;if(oe.existsSync(t))try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function Gc(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||ki.randomUUID(),o=!!n.latest||!n.buildId,s=Vc({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:Lo(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(ed).join(" "),appName:e.name,startTime:Date.now()},a=ut();a.start("Queuing iOS submit on macOS runner...");try{let d=await k.post("/submissions",l),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||wt(r,i);a.stop("iOS submit queued"),me(`Submission ID: ${ne.cyan(r)}`),me(`Dashboard: ${ne.blue.underline(c)}`),dt(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:c}),await zc(i,r,n)}catch(d){a.stop("Could not queue iOS submit"),le(Xc(d)),process.exitCode=1}}async function Kc(e,t,n,i,r,o={}){let s=r.submitId||ki.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:Lo(r),appName:e.name,startTime:Date.now(),...o};try{let d=await k.post("/submissions",a),u=d.data?.submission||d.data?.submit||{},c=d.data?.dashboardUrl||u.dashboardUrl||wt(s,t);return me(`Submission ID: ${ne.cyan(s)}`),me(`Dashboard: ${ne.blue.underline(c)}`),dt(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:c}),s}catch(d){let u=d.response?.data?.message||d.response?.data?.error||d.message;return me(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function Vc(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function zc(e,t,n){let i=ut(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await k.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let d=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<d.length;u++){let c=d[u];c&&console.log(ne.dim(String(c)))}if(o=d.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),Ti("App Store submission successful!"),dt(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||wt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),dt(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||wt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ni(Uc)}catch(s){if(r++,r>=Fc){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Ni(Math.min(2e3*r,15e3))}}async function Wc(e,t,n){let i;for(let r=1;r<=3;r++)try{await k.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!Yc(o))break;await Ni(1e3*r)}No.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function Yc(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function Jc(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function Xc(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
1429
+ `):n||e.message||String(e)}function wt(e,t){if(!e)return Je;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${Je}/submissions/${e}${n}`}function dt(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||wt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&oe.mkdirSync(r,{recursive:!0}),oe.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){No.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function qc(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function Zc(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function Qc(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ni(e){return new Promise(t=>setTimeout(t,e))}function ed(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function td(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=yr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(oe.existsSync(i))try{return JSON.parse(oe.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(oe.existsSync(r))try{let o=JSON.parse(oe.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function nd(e,t){let n=e.filter(o=>In(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=In(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function id(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:br(e,t)}function rd(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function od(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return sd(i)}function sd(e){let t=Bc[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function ad(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function ld(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function cd(e,t){if(e==="inProgress"&&t===void 0)throw new Error("Google Play staged rollout requires --rollout <fraction> when --release-status inProgress is used.");if(e!=="inProgress"&&e!=="halted"&&t!==void 0)throw new Error("Android rollout fraction can only be used with --release-status inProgress or halted.")}async function dd(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Di({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(ct(s))return Ci("Operation cancelled"),null;r=s}if(r==="local"){let s=await Yt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!oe.existsSync(l))return"File not found";if(t==="ios"&&!l.endsWith(".ipa"))return"Must be an .ipa file";if(t==="android"&&!l.endsWith(".aab"))return"Must be an .aab file"}});return ct(s)?null:{filePath:s,source:"local"}}let o=ut();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await k.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],d=s?.toLowerCase(),u=A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success",c=A=>d?[A.buildProfile,A.profile,A.profileName,A.buildType].filter(Boolean).some(B=>String(B).toLowerCase()===d):!0,f=a.filter(A=>u(A)&&c(A)),p=f.find(A=>A.buildType?.toLowerCase()==="store"||A.distribution?.toLowerCase()==="store")||f[0],g=a.some(A=>A.platform?.toLowerCase()===t.toLowerCase()&&A.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&g?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let y=p.artifacts||[];if(y.length===0||y.every(A=>!(A.url||A.downloadUrl)))try{let A=await k.get(`/builds/${e}/${p.buildId}/artifacts`);A.data.status==="success"&&A.data.artifacts?.length>0?(y=A.data.artifacts.map(B=>({...B,url:B.url||B.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${y.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(A){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${A.message}`))}let D=t==="ios",b=y.find(A=>{let B=(A.type||"").toLowerCase(),q=(A.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${A.name} (Type: ${A.type}, HasLink: ${!!(A.url||A.downloadUrl)})`)),B)return B===(D?"ipa":"aab");let P=D?".ipa":".aab",I=(A.url||A.downloadUrl||"").toLowerCase();return q.endsWith(P)||I.includes(P)});if(!b||!(b.url||b.downloadUrl))return le("Build found but artifact URL is missing."),null;let L=b.url||b.downloadUrl;return{filePath:await vi(L,D?"ios":"android"),buildId:p.buildId,artifactName:b.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Yt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(ct(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await k.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await k.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",u=An(a.artifacts);ud(u)||(u=await Po(e,l,u));let c=vo(u,t);if(c||(u=await Po(e,l,u),c=vo(u,t)),!c)throw new Error(`No ${d?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let f=c.url||c.downloadUrl;if(!f)throw new Error(`Artifact ${c.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await vi(f,d?"ios":"android"),buildId:a.buildId||l,artifactName:c.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Yt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return ct(s)?null:{filePath:await vi(s,t),source:"url"}}return null}function An(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function ud(e){return e.some(t=>!!(t.url||t.downloadUrl))}function vo(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function pd(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function Po(e,t,n){try{let i=await k.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await k.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=An(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return An(n)}async function vi(e,t,n=3){let i=ut();i.start("Downloading artifact...");let r=oe.mkdtempSync(Ie.join(_t.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=oe.createWriteStream(s),d=await To({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,c)=>{d.data.pipe(a);let f=!1;d.data.on("error",p=>{f||(f=!0,a.close(),c(p))}),a.on("finish",()=>{f||u()}),a.on("error",p=>{f||(f=!0,c(p))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function fd(e,t,n,i,r){let o=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=xo(t,n,i),l=Ad();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let u=wd(),c=Mc(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});c.stdout?.on("data",f=>u.append(f,process.stdout)),c.stderr?.on("data",f=>u.append(f,process.stderr)),c.on("close",f=>{if(u.flush(),f!==0){o.stop("Pilot failed");try{oe.unlinkSync(s)}catch{}d(_d(f,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{oe.unlinkSync(s)}catch{}a({})}}),c.on("error",f=>{u.flush();try{oe.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Nd(f);p.logs=u.lines(),d(p)})})}async function md(e,t,n,i,r,o){let s=ut();if(r&&me(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=xo(t,n,i),a=`${o.sshUser}@${o.sshHost}`,d=gd(o),u=hd(o),c="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),c=Sd("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!c)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Pi("scp",[...u,e,`${a}:${c}/app.ipa`],"IPA upload to remote runner"),Pi("scp",[...u,l,`${a}:${c}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(_t.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),oe.writeFileSync(f,yd(c)),Pi("scp",[...u,f,`${a}:${c}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let p=`chmod +x ${Jt(`${c}/submit.sh`)} && bash ${Jt(`${c}/submit.sh`)}`,g=It("ssh",[...d,p],{stdio:"inherit"});if(g.error)throw Li("ssh",g.error);if(g.status!==0)throw new Error(`Remote iOS submit failed with exit code ${g.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{oe.unlinkSync(l)}catch{}if(f)try{oe.unlinkSync(f)}catch{}if(c)try{It("ssh",[...d,`rm -rf ${Jt(c)}`],{stdio:"ignore"})}catch{}}}function xo(e,t,n){let i=oe.readFileSync(e,"utf8"),r;try{r=ki.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{me("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
1388
1430
  ${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
1389
1431
  `)}
1390
- -----END PRIVATE KEY-----`}let o=Ie.join(_t.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return oe.writeFileSync(o,JSON.stringify(s,null,2)),o}function fc(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t.push(`${e.sshUser}@${e.sshHost}`),t}function mc(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function gc(e,t){let n=It(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw xi(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function Pi(e,t,n){let i=It(e,t,{stdio:"inherit"});if(i.error)throw xi(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function xi(e,t){return t?.code==="ENOENT"?new Error(`${e} was not found on this machine. Install OpenSSH client tools or run iOS submit directly on the macOS runner.`):t}function Jt(e){return`'${e.replace(/'/g,"'\\''")}'`}function hc(e){let t=Jt(`${e}/app.ipa`),n=Jt(`${e}/api_key.json`);return`#!/bin/bash
1432
+ -----END PRIVATE KEY-----`}let o=Ie.join(_t.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return oe.writeFileSync(o,JSON.stringify(s,null,2)),o}function gd(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t.push(`${e.sshUser}@${e.sshHost}`),t}function hd(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function Sd(e,t){let n=It(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw Li(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function Pi(e,t,n){let i=It(e,t,{stdio:"inherit"});if(i.error)throw Li(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function Li(e,t){return t?.code==="ENOENT"?new Error(`${e} was not found on this machine. Install OpenSSH client tools or run iOS submit directly on the macOS runner.`):t}function Jt(e){return`'${e.replace(/'/g,"'\\''")}'`}function yd(e){let t=Jt(`${e}/app.ipa`),n=Jt(`${e}/api_key.json`);return`#!/bin/bash
1391
1433
  set -euo pipefail
1392
1434
 
1393
1435
  export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
@@ -1415,39 +1457,39 @@ fastlane pilot upload \\
1415
1457
  --api_key_path ${n} \\
1416
1458
  --skip_submission true \\
1417
1459
  --skip_waiting_for_build_processing true
1418
- `}async function Sc(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=ut();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let c=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${c}...`);try{let u=JSON.parse(oe.readFileSync(t,"utf-8"));yc(u);let d=await Mr({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${d.versionCode})`),d}catch(u){throw a.stop("Google Play upload failed"),new Error(Cc(u,n,i,l))}}function yc(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Oi(){let e=process.env.HOME||_t.homedir(),t=process.env.FASTLANE_GEM_HOME||Ie.join(e,".local/share/fastlane/3.4.0"),n=[process.env.FASTLANE_BIN_DIR,"/usr/local/opt/ruby/bin","/opt/homebrew/opt/ruby/bin","/usr/local/bin","/opt/homebrew/bin","/usr/local/Cellar/fastlane/2.227.0/libexec/bin",Ie.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:n,GEM_HOME:t,GEM_PATH:[t,"/usr/local/Cellar/fastlane/2.227.0/libexec",process.env.GEM_PATH].filter(Boolean).join(":"),FASTLANE_INSTALLED_VIA_HOMEBREW:"true",FASTLANE_SKIP_UPDATE_CHECK:"1",FASTLANE_HIDE_CHANGELOG:"1",LANG:process.env.LANG||"en_US.UTF-8",LC_ALL:process.env.LC_ALL||"en_US.UTF-8",CI:process.env.CI||"1"}}function bc(){let e=Oi(),t=vo(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Ec(e);let n=vo(Oi());if(n)return n}return{command:"fastlane",env:Oi()}}function vo(e){let t=process.env.HOME||_t.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ie.join(process.env.FASTLANE_GEM_HOME||Ie.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!oe.existsSync(i))continue;if(!It(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function Ec(e){let t=It("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||_t.homedir(),i=process.env.FASTLANE_GEM_HOME||Ie.join(n,".local/share/fastlane/3.4.0"),r=Ie.join(i,"bin");oe.mkdirSync(r,{recursive:!0}),me(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=It("gem",["install","fastlane","-NV","--install-dir",i,"--bindir",r],{env:{...e,GEM_HOME:i,GEM_PATH:[i,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&me(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Ac(e=No){let t=[],n="",i=r=>{let o=Lo(r);if(o)for(t.push(o);t.length>e;)t.shift()};return{append(r,o){let s=Buffer.isBuffer(r)?r.toString("utf8"):String(r);o.write(s),n+=s;let l=n.split(/\r?\n/);n=l.pop()||"";for(let a of l)i(a)},flush(){n.trim()&&i(n),n=""},lines(){return t.slice()}}}function Ic(e,t){let n=new Error(wc(e,t));return n.logs=xo(t),n.exitCode=e,n}function wc(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=_c(t);return i.length===0?n:`${n}
1460
+ `}async function bd(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=ut();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let d=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${d}...`);try{let u=JSON.parse(oe.readFileSync(t,"utf-8"));Ed(u);let c=await Fr({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${c.versionCode})`),c}catch(u){throw a.stop("Google Play upload failed"),new Error(Td(u,n,i,l))}}function Ed(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Oi(){let e=process.env.HOME||_t.homedir(),t=process.env.FASTLANE_GEM_HOME||Ie.join(e,".local/share/fastlane/3.4.0"),n=[process.env.FASTLANE_BIN_DIR,"/usr/local/opt/ruby/bin","/opt/homebrew/opt/ruby/bin","/usr/local/bin","/opt/homebrew/bin","/usr/local/Cellar/fastlane/2.227.0/libexec/bin",Ie.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:n,GEM_HOME:t,GEM_PATH:[t,"/usr/local/Cellar/fastlane/2.227.0/libexec",process.env.GEM_PATH].filter(Boolean).join(":"),FASTLANE_INSTALLED_VIA_HOMEBREW:"true",FASTLANE_SKIP_UPDATE_CHECK:"1",FASTLANE_HIDE_CHANGELOG:"1",LANG:process.env.LANG||"en_US.UTF-8",LC_ALL:process.env.LC_ALL||"en_US.UTF-8",CI:process.env.CI||"1"}}function Ad(){let e=Oi(),t=Oo(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Id(e);let n=Oo(Oi());if(n)return n}return{command:"fastlane",env:Oi()}}function Oo(e){let t=process.env.HOME||_t.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ie.join(process.env.FASTLANE_GEM_HOME||Ie.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!oe.existsSync(i))continue;if(!It(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function Id(e){let t=It("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||_t.homedir(),i=process.env.FASTLANE_GEM_HOME||Ie.join(n,".local/share/fastlane/3.4.0"),r=Ie.join(i,"bin");oe.mkdirSync(r,{recursive:!0}),me(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=It("gem",["install","fastlane","-NV","--install-dir",i,"--bindir",r],{env:{...e,GEM_HOME:i,GEM_PATH:[i,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&me(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function wd(e=ko){let t=[],n="",i=r=>{let o=Uo(r);if(o)for(t.push(o);t.length>e;)t.shift()};return{append(r,o){let s=Buffer.isBuffer(r)?r.toString("utf8"):String(r);o.write(s),n+=s;let l=n.split(/\r?\n/);n=l.pop()||"";for(let a of l)i(a)},flush(){n.trim()&&i(n),n=""},lines(){return t.slice()}}}function _d(e,t){let n=new Error(Rd(e,t));return n.logs=Mo(t),n.exitCode=e,n}function Rd(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=$d(t);return i.length===0?n:`${n}
1419
1461
 
1420
1462
  Fastlane output:
1421
1463
  ${i.join(`
1422
- `)}`}function _c(e){let t=xo(e);if(t.length===0)return[];let n=Po(t.filter($c)),i=Rc(t);if(i)return[i,...Oo(n,$i-1,_o)];let r=n.length>0?n:t.slice(-$i);return Oo(Po(r),$i,_o)}function Rc(e){let t=e.join(`
1423
- `),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function $c(e){return/\[!\]|ERROR ITMS-\d+|ITMS-\d+|ENTITY_ERROR|previousBundleVersion|CFBundleVersion|Application Loader Error Output|Transporter Error|Transporter transfer failed|Asset validation failed|Validation failed|Error Domain=|The request could not be completed|No suitable application records|Could not|authentication|unauthori[sz]ed|invalid|failed|exception/i.test(e)}function Po(e){let t=new Set,n=[];for(let i of e){let r=i.trim();!r||t.has(r)||(t.add(r),n.push(i))}return n}function Oo(e,t,n){let i=[],r=0;for(let o=e.length-1;o>=0&&i.length<t;o--){let s=e[o],l=r+s.length+1;if(l>n&&i.length>0)break;i.unshift(s.length>n?`${s.slice(0,n-18)}... [truncated]`:s),r=l}return i}function xo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let i=String(n).split(/\r?\n/);for(let r of i){let o=Lo(r);o&&t.push(o)}}return t.slice(-No)}function Lo(e){return Pc(vc(e).trimEnd()).trim()}function vc(e){return e.replace(/[\u001b\u009b][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g,"")}function Pc(e){let t=e.replace(/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,"[REDACTED_PRIVATE_KEY]").replace(/(authorization:\s*bearer\s+)[A-Za-z0-9._-]+/ig,"$1[REDACTED]").replace(/((?:password|token|secret|private[_-]?key)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s,]+)/ig,"$1[REDACTED]");for(let[n,i]of Object.entries(process.env))!i||i.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(n)&&(t=t.replace(new RegExp(Oc(i),"g"),"[REDACTED]"));return t}function Oc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dc(e){return e?.code!=="ENOENT"?e:new Error(["fastlane was not found on PATH.","Mach submit uses Fastlane for iOS TestFlight/App Store uploads.","Run iOS submit on a macOS runner with Fastlane, or expose it via FASTLANE_BINARY / FASTLANE_BIN_DIR.","Example: gem install fastlane -NV"].join(`
1424
- `))}function Cc(e,t,n,i="production"){let r=e?.message||String(e);if(/changesNotSentForReview/i.test(r))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
1464
+ `)}`}function $d(e){let t=Mo(e);if(t.length===0)return[];let n=Do(t.filter(Pd)),i=vd(t);if(i)return[i,...Co(n,$i-1,$o)];let r=n.length>0?n:t.slice(-$i);return Co(Do(r),$i,$o)}function vd(e){let t=e.join(`
1465
+ `),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function Pd(e){return/\[!\]|ERROR ITMS-\d+|ITMS-\d+|ENTITY_ERROR|previousBundleVersion|CFBundleVersion|Application Loader Error Output|Transporter Error|Transporter transfer failed|Asset validation failed|Validation failed|Error Domain=|The request could not be completed|No suitable application records|Could not|authentication|unauthori[sz]ed|invalid|failed|exception/i.test(e)}function Do(e){let t=new Set,n=[];for(let i of e){let r=i.trim();!r||t.has(r)||(t.add(r),n.push(i))}return n}function Co(e,t,n){let i=[],r=0;for(let o=e.length-1;o>=0&&i.length<t;o--){let s=e[o],l=r+s.length+1;if(l>n&&i.length>0)break;i.unshift(s.length>n?`${s.slice(0,n-18)}... [truncated]`:s),r=l}return i}function Mo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let i=String(n).split(/\r?\n/);for(let r of i){let o=Uo(r);o&&t.push(o)}}return t.slice(-ko)}function Uo(e){return Dd(Od(e).trimEnd()).trim()}function Od(e){return e.replace(/[\u001b\u009b][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g,"")}function Dd(e){let t=e.replace(/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,"[REDACTED_PRIVATE_KEY]").replace(/(authorization:\s*bearer\s+)[A-Za-z0-9._-]+/ig,"$1[REDACTED]").replace(/((?:password|token|secret|private[_-]?key)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s,]+)/ig,"$1[REDACTED]");for(let[n,i]of Object.entries(process.env))!i||i.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(n)&&(t=t.replace(new RegExp(Cd(i),"g"),"[REDACTED]"));return t}function Cd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nd(e){return e?.code!=="ENOENT"?e:new Error(["fastlane was not found on PATH.","Mach submit uses Fastlane for iOS TestFlight/App Store uploads.","Run iOS submit on a macOS runner with Fastlane, or expose it via FASTLANE_BINARY / FASTLANE_BIN_DIR.","Example: gem install fastlane -NV"].join(`
1466
+ `))}function Td(e,t,n,i="production"){let r=e?.message||String(e);if(/changesNotSentForReview/i.test(r))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
1425
1467
  `);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${n||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
1426
1468
  `);if(/package.*not found|application.*not found|no application was found/i.test(r))return["Google Play could not find this package for the selected service account.",`Package: ${n||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
1427
1469
  `);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --release-status draft`].join(`
1428
1470
  `);if(r.includes("does not allow any existing users to upgrade"))return["Google Play rejected this release because the uploaded AAB is not an upgrade for existing users.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`,`Then: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t}`].join(`
1429
1471
  `);if(/version code \d+ has already been used/i.test(r))return[r.match(/version code \d+ has already been used[^\n]*/i)?.[0]||"Version code has already been used.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`].join(`
1430
- `);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function Nc(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function me(e){console.log(ne.gray(`\u2022 ${e}`))}function Ti(e){console.log(ne.green(`\u2713 ${e}`))}var Li=8,xc=6,jo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Mi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Go=new Set([".git",".gradle",".idea",".mach-cache",".expo",".turbo",".yarn/cache","build","builds","coverage","dist","node_modules",`${m.nameLower}_cli`,`.${m.nameLower}_cli`]),Lc=new Set(["android/.gradle","android/.cxx","android/app/.cxx","android/app/build","android/build","ios/Pods","ios/build","ios/DerivedData"]),Mc=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],ns=e=>new Promise(t=>setTimeout(t,e)),is=e=>e.split(ge.sep).filter(Boolean).join("/"),Uc=(e,t)=>{let n=is(e),i=n.split("/")[0];return n?!!(Go.has(n)||Go.has(i)||Lc.has(n)||t==="ios"&&i==="android"||t==="android"&&i==="ios"):!1},Fc=(e,t,n)=>{let i=0,r=new Set,o=(s,l)=>{let a=is(l);if(Uc(a,n)){r.add(a.split("/")[0]||a);return}let c=de.lstatSync(s);if(!c.isSymbolicLink()){if(c.isDirectory()){for(let u of de.readdirSync(s))o(ge.join(s,u),ge.join(l,u));return}if(c.isFile()){let u=ge.dirname(a);e.addLocalFile(s,u==="."?void 0:u,ge.basename(a)),i++}}};for(let s of de.readdirSync(t))o(ge.join(t,s),s);return{files:i,skipped:Array.from(r).sort()}},Bc=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Hc=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},jc=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Mc:n.map(i=>({value:i,label:i,hint:Hc(t[i])}))},Gc=async e=>{let t=Bc(e);if(!e.platform&&t){let n=await Mo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});vn(n)&&(Fo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=jc(),i=await Mo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});vn(i)&&(Fo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},Ko=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},rs=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},Kc=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Vc=e=>{let n=rs(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},zc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await k.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||Vc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||rs(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=Ko(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:Kc(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=Ko(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){$.warn(v.yellow(`Could not load saved build options for runner: ${t.message}`))}},Wc=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},Yc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},_n=async(e,t,n=xc)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Yc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";$.warn(v.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await ns(s)}throw i},Jc=async(e,t,n)=>{let i=ge.basename(e),r=de.statSync(e).size,o=Math.round(Mi/1e3);try{await _n(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Mi);try{await $n.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Mi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},jo)}catch(s){throw new Error(`${i} (${Wc(r)}) failed after ${jo} upload attempt(s): ${s.message||s}`)}return r},Xc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Xt=e=>e.credentialId||e.id,qc=async(e,t)=>{let n=Xt(e);if(!n)return e.downloadUrl;let i=await k.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},os=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Li;i++)try{if((!n||i>1)&&(n=await qc(e,t)),!n)throw new Error(`Credential ${e.name||Xt(e)||"unknown"} has no download URL.`);let r=await $n.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=Li||!Xc(r))throw r;let o=Math.min(1500*i*i,15e3);$.warn(v.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Li})`)),await ns(o)}throw new Error(`Failed to download credential ${e.name||Xt(e)||"unknown"}.`)},Vo=async(e,t)=>{let n=await os(e,t);return Buffer.from(n,"base64").toString("utf8")},Zc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},Qc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),eu=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,tu=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,zo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Wo=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>zo(o)===t);if(i)return i;let r=n.find(o=>zo(o)==="*");if(r)return r}return n[0]}},nu=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",ss=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ge.join(e,r.name);r.isDirectory()?ss(o,t,n):r.name===t&&n.push(o)}return n},iu=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},ru=(e,t)=>{let n=ge.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=ss(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:iu(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},Rn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),Pn=(e,t)=>{let n=Rn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Yo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n);return i?i===Pn(t,n):!0},Jo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n),r=Pn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},ou=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},su=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},au=(e,t)=>{let n=Rn(e.distribution),i=Rn(e.iosExportMethod),r=Rn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":ou(t)?"development":(su(t),"adhoc")},as=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Xo=(e,t)=>{if(!t)return!0;let n=as(e);return!n||n==="*"||n===t},qo=(e,t)=>{let n=as(e);return!t||!n?0:n===t?2:n==="*"?1:-1},ls=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},lu=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},du=(e,t)=>{if(!t)return!0;let n=ls(e);if(n)return lu(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},On=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&($.error(v.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await k.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),$.info(v.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){$.error(v.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await zc(e),await Gc(e),e.platform!=="android"&&e.platform!=="ios"&&($.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&($.error(v.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&$.warn(v.yellow("--auto-submit is ignored during --dry-run."));let t=Fi(),n=e.buildId||Tc(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await k.patch(`/builds/${i}/${n}`,{status:"failed",error:l,endTime:Date.now()})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await k.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await $n.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ge.join(kc.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(de.existsSync(u)){let D=de.readdirSync(u);for(let b of D){if(d.has(b))continue;if(b==="ios"){let A=ge.join(u,"ios");try{let B=de.readdirSync(A);for(let q of B)if(!f.has(q))try{de.rmSync(ge.join(A,q),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=ge.join(u,b);try{de.rmSync(x,{recursive:!0,force:!0})}catch{}}}let p=ge.join(u,"source.zip"),g=a.data,y=de.createWriteStream(p);await new Promise((D,b)=>{g.pipe(y),g.on("error",x=>b(x)),y.on("finish",()=>D())}),new Ho(p).extractAllTo(u,!0);try{de.unlinkSync(p)}catch{}process.chdir(u),$.info(v.green(`\u2713 Persistent workspace ready: ${u}`)),$.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ge.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ge.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=Bo("git config --get remote.origin.url").toString().trim()}catch{$.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),$.info(`Build ID: ${v.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d||($.error(v.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),d){u=d;let P=mr(d);e.framework=P,i=d.projectId;let I=e.buildProfile||"production",T=lt(d,I);!T&&e.buildProfile&&($.error(`Build profile '${I}' not found in ${m.configFileName}`),process.exit(1));let w=T||{};process.env.MACH_DEBUG&&$.info(v.dim(`Framework: ${P} | Build profile: ${I} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||I}`)),w.env&&(c=w.env,$.info(v.blue(`Use Build Profile: ${I}`)));let C=e.platform,h=w[C]||{},M=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);let U=H=>H==="androidPackage"?h.androidPackage??h.package??w.androidPackage??w.android?.package:H==="iosBundleIdentifier"?h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:h[H]!==void 0?h[H]:w[H];for(let H of M){let N=U(H),W=H==="androidPackage"||H==="iosBundleIdentifier";N!==void 0&&(e[H]===void 0||W)&&(e[H]=N)}if(e.platform==="ios"&&!(h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let N=ru(e,I);N&&N!==e.iosBundleIdentifier&&($.warn(v.yellow(`Detected native iOS bundle identifier ${N}; using it for credential lookup. Set build.${I}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=N)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1),$.info(v.dim(`Resolved build config: framework=${P}, profile=${I}, platform=${e.platform}, simulator=${e.platform==="ios"?String(!!e.simulator):"n/a"}, developmentClient=${String(!!e.developmentClient)}, distribution=${e.distribution||w.distribution||"store"}, iosConfiguration=${e.platform==="ios"?e.iosConfiguration||"Release":"n/a"}`));let j=H=>{if(!H)return H;if(H.startsWith("scripts.")){let N=H.split(".")[1],W=d.scripts?.[N];if(W)return W;$.warn(`Script reference not found: ${H}`)}return H};e.buildCommand=j(e.buildCommand),e.preBuild=j(e.preBuild),e.postBuild=j(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let X={...Pt(d,m.envPrefix),...Pt(w,`${m.envPrefix}PROFILE_`)};a={...a,...c,...X},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&w.ios?.appleTeamId&&(e.iosTeamId=w.ios.appleTeamId),!e.iosTeamId&&d.submit?.[I]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[I].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&($.warn(v.yellow(`Check: Using 'production' Team ID for '${I}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?$.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||$.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=Bo("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{$.warn("Failed to detect git branch.")}let p="1.0.0";try{de.existsSync("./package.json")&&(p=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",y="Internal";e.developmentClient?y="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?y="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?y="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(y="Development");let _=e.platform==="ios"?"iOS":"Android",D=e.platform==="ios"&&e.simulator?" (Simulator)":"",b=`${_}${D} v${p} (${y})`;if(Dn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:g,branch:f,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:b}),i){try{let P=e.buildProfile||"production",I=e.environment||P;$.info(v.blue(`Fetching managed secrets for profile: ${P} (environment: ${I})...`));let w=(await k.get(`/projects/${i}/secrets/export?env=${I}`)).data;w.status==="success"&&w.secrets&&(a={...a,...w.secrets},Object.keys(w.secrets).length>0&&$.info(v.magenta(`\u2713 Injected ${Object.keys(w.secrets).length} secrets from Dashboard.`)))}catch(P){$.warn(`Failed to load managed secrets from Dashboard: ${P.message}`)}if(e.platform==="ios"&&e.simulator)$.info(v.dim("Skipping managed iOS signing credentials for simulator build."));else try{$.info(v.blue("Fetching managed credentials..."));let P=au(e,g),I=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,T=e.platform==="ios"?"bundle":"package";$.info(v.dim(` Credential target: ${T} ${I||"not set"} (${P})`));let w=await k.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:I,distributionType:P,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(w.data.status==="success"&&w.data.credentials){let C=w.data.credentials;$.info(v.magenta(`\u2713 Found ${C.length} relevant credentials.`));let h=C.filter(N=>e.platform==="ios"&&N.type==="ios_profile"?Yo(N,P,e.platform)?Xo(N,I):!1:e.platform==="android"&&N.type==="android_keystore"?Xo(N,I):!!Yo(N,P,e.platform)).sort((N,W)=>qo(W,I)*10+Jo(W,P,e.platform)-(qo(N,I)*10+Jo(N,P,e.platform)));$.info(v.dim(` Filtered to ${h.length} credentials for distributionType: ${P}`));let M=!1,U=!1,j=!1,X=[];for(let N of h)if(!(N.type==="ios_cert"&&M||N.type==="ios_profile"&&U||N.type==="android_keystore"&&j)&&["ios_cert","ios_profile","android_keystore"].includes(N.type)&&(N.downloadUrl||Xt(N)))try{let ce=await os(N,i);if(N.type==="ios_cert"&&!M)a.IOS_DIST_P12=ce,N.password?(a.IOS_P12_PASSWORD=N.password,$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12 with password from credential record`))):$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12`)),M=!0;else if(N.type==="ios_profile"&&!U){if(!du(ce,I)){let ue=ls(ce)||"unknown";throw new Error(`Provisioning profile ${N.name||Xt(N)||"unknown"} is for a different bundle ID. Expected ${I}, found ${ue}. Upload a ${P} profile for ${I}.`)}a.IOS_PROVISIONING_PROFILE=ce,$.info(v.dim(` - Injected ${N.name} as IOS_PROVISIONING_PROFILE`)),U=!0}else if(N.type==="android_keystore"&&!j){a.ANDROID_KEYSTORE_BASE64=ce;let ue=N.keystorePassword||N.password,V=N.keyPassword||N.keystorePassword||N.password,G=N.alias||N.meta?.alias;if(ue)a.ANDROID_STORE_PASSWORD=ue,$.info(v.dim(" - Injected keystore password from credential record"));else{let J=["ANDROID_STORE_PASSWORD",...[P==="store"?"PRODUCTION":P==="internal"||P==="adhoc"?"STAGING":"DEVELOPMENT",P.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(ae=>`KEYSTORE_PASSWORD_${ae}`),"KEYSTORE_PASSWORD"].find(ae=>!!a[ae]);J&&a[J]&&(a.ANDROID_STORE_PASSWORD=a[J])}if(V?(a.ANDROID_KEY_PASSWORD=V,$.info(v.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",G)a.ANDROID_KEY_ALIAS=G;else{let Q=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(z=>!!a[z]);Q&&(a.ANDROID_KEY_ALIAS=a[Q])}$.info(v.dim(` - Injected ${N.name} as ANDROID_KEYSTORE_BASE64`)),j=!0}}catch(ce){X.push(`${N.name||N.type}: ${ce.message}`)}let H=e.platform==="ios"?e.simulator||M&&U:j||!h.some(N=>N.type==="android_keystore");if(X.length>0&&!H)throw new Error(`Credential setup failed:
1472
+ `);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function kd(e){try{oe.existsSync(e)&&oe.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function me(e){console.log(ne.gray(`\u2022 ${e}`))}function Ti(e){console.log(ne.green(`\u2713 ${e}`))}var xi=8,Md=6,Ko=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Mi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Ui="ap-south-1",Ud=`${m.envPrefix}S3_DEBUG`,Fd=()=>["1","true","yes","on"].includes(String(process.env[Ud]||"").trim().toLowerCase()),Hi=(e,t)=>{if(Fd()&&t)try{let n=new URL(t);$.info(v.dim(`[S3_DEBUG] ${e} host=${n.hostname} expectedRegion=${Ui}`)),n.hostname.includes(Ui)||$.warn(v.yellow(`[S3_DEBUG] ${e} host ${n.hostname} does not include ${Ui}`))}catch(n){$.warn(v.yellow(`[S3_DEBUG] Could not parse ${e} presigned URL host: ${n.message}`))}},Vo=new Set([".git",".gradle",".idea",".mach-cache",".expo",".turbo",".yarn/cache","build","builds","coverage","dist","node_modules",`${m.nameLower}_cli`,`.${m.nameLower}_cli`]),Bd=new Set(["android/.gradle","android/.cxx","android/app/.cxx","android/app/build","android/build","ios/Pods","ios/build","ios/DerivedData"]),Hd=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],rs=e=>new Promise(t=>setTimeout(t,e)),os=e=>e.split(ge.sep).filter(Boolean).join("/"),jd=(e,t)=>{let n=os(e),i=n.split("/")[0];return n?!!(Vo.has(n)||Vo.has(i)||Bd.has(n)||t==="ios"&&i==="android"||t==="android"&&i==="ios"):!1},Gd=(e,t,n)=>{let i=0,r=new Set,o=(s,l)=>{let a=os(l);if(jd(a,n)){r.add(a.split("/")[0]||a);return}let d=ce.lstatSync(s);if(!d.isSymbolicLink()){if(d.isDirectory()){for(let u of ce.readdirSync(s))o(ge.join(s,u),ge.join(l,u));return}if(d.isFile()){let u=ge.dirname(a);e.addLocalFile(s,u==="."?void 0:u,ge.basename(a)),i++}}};for(let s of ce.readdirSync(t))o(ge.join(t,s),s);return{files:i,skipped:Array.from(r).sort()}},Kd=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Vd=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},zd=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Hd:n.map(i=>({value:i,label:i,hint:Vd(t[i])}))},Wd=async e=>{let t=Kd(e);if(!e.platform&&t){let n=await Fo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});vn(n)&&(Ho("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=zd(),i=await Fo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});vn(i)&&(Ho("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},zo=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},ss=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},Yd=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),Jd=e=>{let n=ss(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},Xd=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await k.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||Jd(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||ss(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=zo(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:Yd(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=zo(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){$.warn(v.yellow(`Could not load saved build options for runner: ${t.message}`))}},qd=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},Zd=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},_n=async(e,t,n=Md)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!Zd(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";$.warn(v.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await rs(s)}throw i},Qd=async(e,t,n)=>{let i=ge.basename(e),r=ce.statSync(e).size,o=Math.round(Mi/1e3);Hi(`ARTIFACT_UPLOAD ${i}`,t);try{await _n(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=ce.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Mi);try{await $n.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Mi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},Ko)}catch(s){throw new Error(`${i} (${qd(r)}) failed after ${Ko} upload attempt(s): ${s.message||s}`)}return r},eu=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},Xt=e=>e.credentialId||e.id,tu=async(e,t)=>{let n=Xt(e);if(!n)return e.downloadUrl;let i=await k.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},as=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=xi;i++)try{if((!n||i>1)&&(n=await tu(e,t)),!n)throw new Error(`Credential ${e.name||Xt(e)||"unknown"} has no download URL.`);let r=await $n.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=xi||!eu(r))throw r;let o=Math.min(1500*i*i,15e3);$.warn(v.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${xi})`)),await rs(o)}throw new Error(`Failed to download credential ${e.name||Xt(e)||"unknown"}.`)},Wo=async(e,t)=>{let n=await as(e,t);return Buffer.from(n,"base64").toString("utf8")},nu=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},iu=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),ru=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,ou=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,Yo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Jo=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>Yo(o)===t);if(i)return i;let r=n.find(o=>Yo(o)==="*");if(r)return r}return n[0]}},su=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",ls=(e,t,n=[])=>{if(!ce.existsSync(e))return n;let i;try{i=ce.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ge.join(e,r.name);r.isDirectory()?ls(o,t,n):r.name===t&&n.push(o)}return n},au=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},lu=(e,t)=>{let n=ge.resolve(process.cwd(),ce.existsSync("ios")?"ios":"."),i=ls(n,"project.pbxproj"),r=[];for(let o of i)try{let l=ce.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let d=a[1]?.trim();d&&!d.includes("$")&&!d.startsWith("com.apple.")&&!r.includes(d)&&r.push(d)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:au(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},Rn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),Pn=(e,t)=>{let n=Rn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Xo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n);return i?i===Pn(t,n):!0},qo=(e,t,n)=>{let i=Pn(e.distributionType||e.meta?.distributionType,n),r=Pn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},cu=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},du=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},uu=(e,t)=>{let n=Rn(e.distribution),i=Rn(e.iosExportMethod),r=Rn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":cu(t)?"development":(du(t),"adhoc")},cs=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Zo=(e,t)=>{if(!t)return!0;let n=cs(e);return!n||n==="*"||n===t},Qo=(e,t)=>{let n=cs(e);return!t||!n?0:n===t?2:n==="*"?1:-1},ds=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},pu=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},fu=(e,t)=>{if(!t)return!0;let n=ds(e);if(n)return pu(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},On=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&($.error(v.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await k.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),$.info(v.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){$.error(v.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await Xd(e),await Wd(e),e.platform!=="android"&&e.platform!=="ios"&&($.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&($.error(v.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&$.warn(v.yellow("--auto-submit is ignored during --dry-run."));let t=Bi(),n=e.buildId||Ld(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await k.patch(`/builds/${i}/${n}`,{status:"failed",error:l,endTime:Date.now()})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await k.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");Hi("SOURCE_DOWNLOAD",l.data.downloadUrl);let a=await $n.get(l.data.downloadUrl,{responseType:"stream"}),d=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ge.join(xd.homedir(),m.workspacesDir,d);ce.mkdirSync(u,{recursive:!0});let c=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(ce.existsSync(u)){let D=ce.readdirSync(u);for(let b of D){if(c.has(b))continue;if(b==="ios"){let A=ge.join(u,"ios");try{let B=ce.readdirSync(A);for(let q of B)if(!f.has(q))try{ce.rmSync(ge.join(A,q),{recursive:!0,force:!0})}catch{}}catch{}continue}let L=ge.join(u,b);try{ce.rmSync(L,{recursive:!0,force:!0})}catch{}}}let p=ge.join(u,"source.zip"),g=a.data,y=ce.createWriteStream(p);await new Promise((D,b)=>{g.pipe(y),g.on("error",L=>b(L)),y.on("finish",()=>D())}),new Go(p).extractAllTo(u,!0);try{ce.unlinkSync(p)}catch{}process.chdir(u),$.info(v.green(`\u2713 Persistent workspace ready: ${u}`)),$.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(ge.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(ge.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=jo("git config --get remote.origin.url").toString().trim()}catch{$.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),$.info(`Build ID: ${v.cyan(n)}`);let a={},d={},u=null,c=$e(`./${m.configFileName}`);if(c||($.error(v.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),c){u=c;let P=hr(c);e.framework=P,i=c.projectId;let I=e.buildProfile||"production",T=lt(c,I);!T&&e.buildProfile&&($.error(`Build profile '${I}' not found in ${m.configFileName}`),process.exit(1));let w=T||{};process.env.MACH_DEBUG&&$.info(v.dim(`Framework: ${P} | Build profile: ${I} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||I}`)),w.env&&(d=w.env,$.info(v.blue(`Use Build Profile: ${I}`)));let C=e.platform,h=w[C]||{},M=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=c.name,e.appName=c.name,e.androidPackage=c.android?.package,e.iosBundleIdentifier=c.ios?.bundleIdentifier,e.iosScheme=c.ios?.iosScheme,!e.nodeVersion&&c.nodeVersion&&(e.nodeVersion=c.nodeVersion);let U=H=>H==="androidPackage"?h.androidPackage??h.package??w.androidPackage??w.android?.package:H==="iosBundleIdentifier"?h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:h[H]!==void 0?h[H]:w[H];for(let H of M){let N=U(H),W=H==="androidPackage"||H==="iosBundleIdentifier";N!==void 0&&(e[H]===void 0||W)&&(e[H]=N)}if(e.platform==="ios"&&!(h.iosBundleIdentifier??h.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let N=lu(e,I);N&&N!==e.iosBundleIdentifier&&($.warn(v.yellow(`Detected native iOS bundle identifier ${N}; using it for credential lookup. Set build.${I}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=N)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1),$.info(v.dim(`Resolved build config: framework=${P}, profile=${I}, platform=${e.platform}, simulator=${e.platform==="ios"?String(!!e.simulator):"n/a"}, developmentClient=${String(!!e.developmentClient)}, distribution=${e.distribution||w.distribution||"store"}, iosConfiguration=${e.platform==="ios"?e.iosConfiguration||"Release":"n/a"}`));let j=H=>{if(!H)return H;if(H.startsWith("scripts.")){let N=H.split(".")[1],W=c.scripts?.[N];if(W)return W;$.warn(`Script reference not found: ${H}`)}return H};e.buildCommand=j(e.buildCommand),e.preBuild=j(e.preBuild),e.postBuild=j(e.postBuild),!e.scheme&&c.scheme&&(e.scheme=c.scheme);let X={...Pt(c,m.envPrefix),...Pt(w,`${m.envPrefix}PROFILE_`)};a={...a,...d,...X},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&w.ios?.appleTeamId&&(e.iosTeamId=w.ios.appleTeamId),!e.iosTeamId&&c.submit?.[I]?.ios?.appleTeamId&&(e.iosTeamId=c.submit[I].ios.appleTeamId),!e.iosTeamId&&c.submit?.production?.ios?.appleTeamId&&($.warn(v.yellow(`Check: Using 'production' Team ID for '${I}' build.`)),e.iosTeamId=c.submit.production.ios.appleTeamId),e.iosTeamId?$.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||$.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=jo("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{$.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",y="Internal";e.developmentClient?y="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?y="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?y="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(y="Development");let _=e.platform==="ios"?"iOS":"Android",D=e.platform==="ios"&&e.simulator?" (Simulator)":"",b=`${_}${D} v${p} (${y})`;if(Dn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:g,branch:f,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:b}),i){try{let P=e.buildProfile||"production",I=e.environment||P;$.info(v.blue(`Fetching managed secrets for profile: ${P} (environment: ${I})...`));let w=(await k.get(`/projects/${i}/secrets/export?env=${I}`)).data;w.status==="success"&&w.secrets&&(a={...a,...w.secrets},Object.keys(w.secrets).length>0&&$.info(v.magenta(`\u2713 Injected ${Object.keys(w.secrets).length} secrets from Dashboard.`)))}catch(P){$.warn(`Failed to load managed secrets from Dashboard: ${P.message}`)}if(e.platform==="ios"&&e.simulator)$.info(v.dim("Skipping managed iOS signing credentials for simulator build."));else try{$.info(v.blue("Fetching managed credentials..."));let P=uu(e,g),I=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,T=e.platform==="ios"?"bundle":"package";$.info(v.dim(` Credential target: ${T} ${I||"not set"} (${P})`));let w=await k.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:I,distributionType:P,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(w.data.status==="success"&&w.data.credentials){let C=w.data.credentials;$.info(v.magenta(`\u2713 Found ${C.length} relevant credentials.`));let h=C.filter(N=>e.platform==="ios"&&N.type==="ios_profile"?Xo(N,P,e.platform)?Zo(N,I):!1:e.platform==="android"&&N.type==="android_keystore"?Zo(N,I):!!Xo(N,P,e.platform)).sort((N,W)=>Qo(W,I)*10+qo(W,P,e.platform)-(Qo(N,I)*10+qo(N,P,e.platform)));$.info(v.dim(` Filtered to ${h.length} credentials for distributionType: ${P}`));let M=!1,U=!1,j=!1,X=[];for(let N of h)if(!(N.type==="ios_cert"&&M||N.type==="ios_profile"&&U||N.type==="android_keystore"&&j)&&["ios_cert","ios_profile","android_keystore"].includes(N.type)&&(N.downloadUrl||Xt(N)))try{let de=await as(N,i);if(N.type==="ios_cert"&&!M)a.IOS_DIST_P12=de,N.password?(a.IOS_P12_PASSWORD=N.password,$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12 with password from credential record`))):$.info(v.dim(` - Injected ${N.name} as IOS_DIST_P12`)),M=!0;else if(N.type==="ios_profile"&&!U){if(!fu(de,I)){let ue=ds(de)||"unknown";throw new Error(`Provisioning profile ${N.name||Xt(N)||"unknown"} is for a different bundle ID. Expected ${I}, found ${ue}. Upload a ${P} profile for ${I}.`)}a.IOS_PROVISIONING_PROFILE=de,$.info(v.dim(` - Injected ${N.name} as IOS_PROVISIONING_PROFILE`)),U=!0}else if(N.type==="android_keystore"&&!j){a.ANDROID_KEYSTORE_BASE64=de;let ue=N.keystorePassword||N.password,V=N.keyPassword||N.keystorePassword||N.password,G=N.alias||N.meta?.alias;if(ue)a.ANDROID_STORE_PASSWORD=ue,$.info(v.dim(" - Injected keystore password from credential record"));else{let J=["ANDROID_STORE_PASSWORD",...[P==="store"?"PRODUCTION":P==="internal"||P==="adhoc"?"STAGING":"DEVELOPMENT",P.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(ae=>`KEYSTORE_PASSWORD_${ae}`),"KEYSTORE_PASSWORD"].find(ae=>!!a[ae]);J&&a[J]&&(a.ANDROID_STORE_PASSWORD=a[J])}if(V?(a.ANDROID_KEY_PASSWORD=V,$.info(v.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",G)a.ANDROID_KEY_ALIAS=G;else{let Q=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(z=>!!a[z]);Q&&(a.ANDROID_KEY_ALIAS=a[Q])}$.info(v.dim(` - Injected ${N.name} as ANDROID_KEYSTORE_BASE64`)),j=!0}}catch(de){X.push(`${N.name||N.type}: ${de.message}`)}let H=e.platform==="ios"?e.simulator||M&&U:j||!h.some(N=>N.type==="android_keystore");if(X.length>0&&!H)throw new Error(`Credential setup failed:
1431
1473
  ${X.map(N=>`- ${N}`).join(`
1432
- `)}`);X.length>0&&$.warn(v.dim(` Skipped ${X.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let C=e.buildProfile||"production",h=lt(d,C)||{},M=eu(d,h),U=nu(M),j=e.distribution!==void 0?e.distribution==="store":y==="Store",X=M===void 0&&j,H=e.autoVersion||U&&j||X,N=e.autoVersion||U&&j;if(U&&!j&&$.info(v.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){let W=e.iosBundleIdentifier||d.ios?.bundleIdentifier||d.expo?.ios?.bundleIdentifier,ce=tu(d,h,C),ue=w.data.credentials||[],V=Wo(ue,W);if(!V&&(N||X)){let G=await k.get(`/credentials/${i}`);V=Wo(G.data.credentials||[],W)}if(V){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let G=V.keyId||V.meta?.keyId,Q=V.issuerId||V.meta?.issuerId;if(!G||!Q)throw new Error("App Store Connect credential is missing keyId or issuerId.");let z=await Vo(V,i),J=await jr({keyId:G,issuerId:Q,privateKey:z,ascAppId:ce,bundleId:W}),ae=/^\d+$/.test(J.latestBuildNumber);ae?(a.BUILD_NUMBER=J.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=J.nextBuildNumber,a.CURRENT_PROJECT_VERSION=J.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(ae?`\u2713 Latest iOS buildNumber on App Store Connect: ${v.green(J.latestBuildNumber)} (Mach will assign >= ${J.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${v.green(J.nextBuildNumber)} (Latest on App Store Connect: ${J.latestBuildNumber})`)}catch(G){t.stop("iOS buildNumber lookup failed");let Q=G.response?.data?.error?.message||G.message;if(N)throw new Error(`Auto-versioning failed: ${Q}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);$.warn(v.yellow(`Could not check App Store Connect buildNumber: ${Q}. Falling back to Mach counter.`))}}else if(N)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let C=e.buildProfile||"production",h=lt(d,C)||{},j=((h.android||{}).versionCode??h.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",X=e.distribution!==void 0?e.distribution==="store":y==="Store",H=e.autoVersion||j&&X;if(j&&!H&&$.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){t.start("Resolving latest versionCode from Google Play...");try{let N=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,W=(w.data.credentials||[]).find(Q=>Q.type==="google_service_account"&&(!Q.bundleId||Q.bundleId===N));if(!W){let z=((await k.get(`/credentials/${i}`)).data.credentials||[]).filter(J=>J.type==="google_service_account");if(W=z.find(J=>J.type==="google_service_account"&&J.bundleId===N),!W&&z.length>0){let J=z.map(ae=>ae.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${N}. Found service credential(s) for: ${J}.`)}}if(!W)throw new Error(`Google Service Account not found for package ${N}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${N}'.`);let ce=await Vo(W,i),ue=Zc(ce,"Google Play service account");if(!ue.client_email||!ue.private_key)throw new Error("Google Play service account JSON is missing client_email or private_key.");let V=await Lr(N,ue);if(V==null)throw new Error("Could not retrieve any version information from Google Play.");let G=V+1;a.ANDROID_VERSION_CODE=G.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(G)} (Latest on Play Store: ${V})`)}catch(N){t.stop("Version resolution failed");let W=N.response?.data?.error?.message||N.message,ce=Qc(W)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${W}. ${ce}`)}}}if(e.platform==="ios"&&!e.simulator){let C=!!a.IOS_DIST_P12,h=!!a.IOS_PROVISIONING_PROFILE;if(!C||!h){let M=[...C?[]:["Distribution Certificate"],...h?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${M}. Expected ${P} credentials for ${I||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${g}\` and select ${I||"the correct bundle ID"}.`);$.error(v.red(`Missing iOS credentials: ${M}`)),e.quiet&&process.exit(1);let U=e.yes||await Uo({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!vn(U))return await Ht({platform:"ios",profile:g}),e.quiet||$.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){$.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let h=e.yes||await Uo({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(h&&!vn(h))return await Ht({platform:"android",profile:g}),e.quiet||$.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(P){(String(P.message||"").startsWith("Credential download failed")||String(P.message||"").startsWith("Credential setup failed")||String(P.message||"").startsWith("Missing iOS credentials")||String(P.message||"").startsWith("Auto-versioning failed"))&&($.error(v.red(P.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&($.error(v.red(`Failed to resolve iOS credentials: ${P.message}`)),process.exit(1)),$.warn(`Failed to resolve credentials: ${P.message}`)}}let x=!!(e.local&&e.buildId),A=!!(e.local||e.sshHost),B=!A&&!x;if(x){$.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let P=await mi({...e,interactive:!1},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P),process.exit(0)}async function q(P){let I=async T=>{if(i)try{await _n("Report failed build status",()=>k.patch(`/builds/${i}/${n}`,{status:"failed",error:T,endTime:Date.now()}),3)}catch(w){$.warn(v.yellow(`Could not report failed build status: ${w.message}`))}};if(i&&P.length>0){let T=Fi(),w=[];e.quiet||T.start("Uploading artifacts to Dashboard...");try{for(let C of P){let h=ge.basename(C),M=de.statSync(C).size,U=ge.extname(h).toLowerCase(),j="application/octet-stream",X=await _n(`Create artifact upload URL for ${h}`,()=>k.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:h,fileType:j}));if(X.data.status!=="success")throw new Error(`Failed to get upload URL for ${h}`);await Jc(C,X.data.uploadUrl,j),w.push({name:h,url:X.data.downloadUrl,size:M,type:U.substring(1)})}e.quiet||T.stop("Artifacts uploaded.")}catch(C){e.quiet||T.stop("Failed to upload artifacts.");let h=`Artifact upload failed: ${C.message}`;throw $.error(v.red(h)),await I(h),new Error(h)}if(i&&w.length>0)try{$.info(v.cyan(`
1474
+ `)}`);X.length>0&&$.warn(v.dim(` Skipped ${X.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let C=e.buildProfile||"production",h=lt(c,C)||{},M=ru(c,h),U=su(M),j=e.distribution!==void 0?e.distribution==="store":y==="Store",X=M===void 0&&j,H=e.autoVersion||U&&j||X,N=e.autoVersion||U&&j;if(U&&!j&&$.info(v.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){let W=e.iosBundleIdentifier||c.ios?.bundleIdentifier||c.expo?.ios?.bundleIdentifier,de=ou(c,h,C),ue=w.data.credentials||[],V=Jo(ue,W);if(!V&&(N||X)){let G=await k.get(`/credentials/${i}`);V=Jo(G.data.credentials||[],W)}if(V){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let G=V.keyId||V.meta?.keyId,Q=V.issuerId||V.meta?.issuerId;if(!G||!Q)throw new Error("App Store Connect credential is missing keyId or issuerId.");let z=await Wo(V,i),J=await Kr({keyId:G,issuerId:Q,privateKey:z,ascAppId:de,bundleId:W}),ae=/^\d+$/.test(J.latestBuildNumber);ae?(a.BUILD_NUMBER=J.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=J.nextBuildNumber,a.CURRENT_PROJECT_VERSION=J.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(ae?`\u2713 Latest iOS buildNumber on App Store Connect: ${v.green(J.latestBuildNumber)} (Mach will assign >= ${J.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${v.green(J.nextBuildNumber)} (Latest on App Store Connect: ${J.latestBuildNumber})`)}catch(G){t.stop("iOS buildNumber lookup failed");let Q=G.response?.data?.error?.message||G.message;if(N)throw new Error(`Auto-versioning failed: ${Q}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);$.warn(v.yellow(`Could not check App Store Connect buildNumber: ${Q}. Falling back to Mach counter.`))}}else if(N)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let C=e.buildProfile||"production",h=lt(c,C)||{},j=((h.android||{}).versionCode??h.androidVersionCode??c.android?.versionCode??c.expo?.android?.versionCode)==="auto",X=e.distribution!==void 0?e.distribution==="store":y==="Store",H=e.autoVersion||j&&X;if(j&&!H&&$.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){t.start("Resolving latest versionCode from Google Play...");try{let N=e.androidPackage||c.android?.package||c.expo?.android?.package||c.name,W=(w.data.credentials||[]).find(Q=>Q.type==="google_service_account"&&(!Q.bundleId||Q.bundleId===N));if(!W){let z=((await k.get(`/credentials/${i}`)).data.credentials||[]).filter(J=>J.type==="google_service_account");if(W=z.find(J=>J.type==="google_service_account"&&J.bundleId===N),!W&&z.length>0){let J=z.map(ae=>ae.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${N}. Found service credential(s) for: ${J}.`)}}if(!W)throw new Error(`Google Service Account not found for package ${N}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${N}'.`);let de=await Wo(W,i),ue=nu(de,"Google Play service account");if(!ue.client_email||!ue.private_key)throw new Error("Google Play service account JSON is missing client_email or private_key.");let V=await Ur(N,ue);if(V==null)throw new Error("Could not retrieve any version information from Google Play.");let G=V+1;a.ANDROID_VERSION_CODE=G.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(G)} (Latest on Play Store: ${V})`)}catch(N){t.stop("Version resolution failed");let W=N.response?.data?.error?.message||N.message,de=iu(W)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${W}. ${de}`)}}}if(e.platform==="ios"&&!e.simulator){let C=!!a.IOS_DIST_P12,h=!!a.IOS_PROVISIONING_PROFILE;if(!C||!h){let M=[...C?[]:["Distribution Certificate"],...h?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${M}. Expected ${P} credentials for ${I||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${g}\` and select ${I||"the correct bundle ID"}.`);$.error(v.red(`Missing iOS credentials: ${M}`)),e.quiet&&process.exit(1);let U=e.yes||await Bo({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!vn(U))return await Ht({platform:"ios",profile:g}),e.quiet||$.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){$.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let h=e.yes||await Bo({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(h&&!vn(h))return await Ht({platform:"android",profile:g}),e.quiet||$.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),On(e);e.quiet||$.info(v.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(P){(String(P.message||"").startsWith("Credential download failed")||String(P.message||"").startsWith("Credential setup failed")||String(P.message||"").startsWith("Missing iOS credentials")||String(P.message||"").startsWith("Auto-versioning failed"))&&($.error(v.red(P.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&($.error(v.red(`Failed to resolve iOS credentials: ${P.message}`)),process.exit(1)),$.warn(`Failed to resolve credentials: ${P.message}`)}}let L=!!(e.local&&e.buildId),A=!!(e.local||e.sshHost),B=!A&&!L;if(L){$.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let P=await mi({...e,interactive:!1},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P),process.exit(0)}async function q(P){let I=async T=>{if(i)try{await _n("Report failed build status",()=>k.patch(`/builds/${i}/${n}`,{status:"failed",error:T,endTime:Date.now()}),3)}catch(w){$.warn(v.yellow(`Could not report failed build status: ${w.message}`))}};if(i&&P.length>0){let T=Bi(),w=[];e.quiet||T.start("Uploading artifacts to Dashboard...");try{for(let C of P){let h=ge.basename(C),M=ce.statSync(C).size,U=ge.extname(h).toLowerCase(),j="application/octet-stream",X=await _n(`Create artifact upload URL for ${h}`,()=>k.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:h,fileType:j}));if(X.data.status!=="success")throw new Error(`Failed to get upload URL for ${h}`);await Qd(C,X.data.uploadUrl,j),w.push({name:h,url:X.data.downloadUrl,size:M,type:U.substring(1)})}e.quiet||T.stop("Artifacts uploaded.")}catch(C){e.quiet||T.stop("Failed to upload artifacts.");let h=`Artifact upload failed: ${C.message}`;throw $.error(v.red(h)),await I(h),new Error(h)}if(i&&w.length>0)try{$.info(v.cyan(`
1433
1475
  \u{1F517} Download Links:`));for(let C of w)$.info(v.dim(` - ${C.name}: `)+v.blue.underline(C.url));await _n("Finalize build in dashboard",()=>k.patch(`/builds/${i}/${n}`,{status:"success",artifacts:w,endTime:Date.now()})),Dn(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:g,branch:f,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:b,artifacts:w}),$.success(v.green(`
1434
- \u2713 Build completed and reported to dashboard.`)),e.maestro&&!x&&await Zo(i,n,e,g),e.autoSubmit&&!x&&await Ui(i,n,e,g)}catch(C){let h=`Build artifact uploaded but dashboard finalization failed: ${C.message}`;throw $.error(v.red(`
1435
- ${h}`)),await I(h),new Error(h)}}else if(i){let T="Build completed but produced no uploadable artifacts.";throw $.error(v.red(T)),await I(T),new Error(T)}}if(A){if($.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let P=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:P,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Qo(e,n,g,u)}),es(e)}if(e.sshHost&&e.platform==="ios")await kr(e,n,a,i),e.autoSubmit&&await Ui(i,n,e,g);else{let P=await mi({...e,interactive:!!e.local},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P)}return}if(B&&($.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let P=await k.post("/builds/source-upload-url",{projectId:i,buildId:n});if(P.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let I=new Ho,T=Fc(I,process.cwd(),e.platform),w=I.toBuffer();if(!e.quiet){let h=T.skipped.length>0?` Skipped: ${T.skipped.join(", ")}.`:"";t.message(`Prepared source (${T.files} files).${h}`)}e.quiet||t.message(`Uploading source (${(w.length/1024/1024).toFixed(1)} MB)...`);let C=!1;for(let h=1;h<=3;h++)try{await $n.put(P.data.uploadUrl,w,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),C=!0;break}catch(M){if(h<3)t.message(`Upload attempt ${h} failed (${M.code||M.message}), retrying...`),await new Promise(U=>setTimeout(U,2e3*h));else throw M}if(e.quiet||t.stop("Source uploaded"),i){let h=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:h,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...Qo(e,n,g,u)}),$.info(v.green("\u2713 Cloud build registered.")),es(e)}e.platform==="android"&&await Cr(e,n,a,i,e.preBuild),e.quiet||$.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await pu(i,n,e),e.maestro&&await Zo(i,n,e,g),e.autoSubmit&&await Ui(i,n,e,g);return}}catch(l){let a=l.message||"Build failed";l.response?.data?.message?a=l.response.data.message:l.message.includes("status code 402")?a="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(a="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&await s(a),$.error(v.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function Zo(e,t,n,i){$.info(v.cyan(`
1436
- \u{1F3BC} Queuing managed Maestro test...`)),await Ii({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,maestroEnv:n.maestroEnv,quiet:n.quiet})}async function Ui(e,t,n,i){if(!e){$.error(v.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}$.info(v.cyan(`
1437
- Auto-submit: submitting the successful build...`));try{let r=await cu(e,t);if(r?.autoSubmit){let o=r.submissionId?`${Je}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?($.info(v.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),$.info(v.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?$.warn(v.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&$.info(v.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){ct(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await wn({platform:n.platform,profile:i,buildProfile:i,buildId:t,projectId:e,yes:n.yes,quiet:n.quiet,track:n.submitTrack,releaseStatus:n.submitReleaseStatus,rollout:n.submitRollout,changesNotSentForReview:n.submitChangesNotSentForReview,credentialId:n.submitCredentialId,packageName:n.androidPackage,jsonOutput:n.submitJsonOutput,submitArgs:ds(n,t,i)})}catch(r){$.error(v.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function ds(e,t,n){let i=["--platform",e.platform,"--profile",n,"--build-id",t];return e.submitTrack&&i.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&i.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&i.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&i.push("--changes-not-sent-for-review"),e.submitCredentialId&&i.push("--credential-id",e.submitCredentialId),e.platform==="android"&&e.androidPackage&&i.push("--package-name",e.androidPackage),e.platform==="ios"&&e.iosBundleIdentifier&&i.push("--bundle-id",e.iosBundleIdentifier),e.submitJsonOutput&&i.push("--json-output",e.submitJsonOutput),i.join(" ")}async function cu(e,t){try{let i=(await k.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){$.warn(v.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function cs(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function uu(e,t,n){let i=n?.submit?.[t]?.android||{},r=n?.submit?.production?.android||{},o=e.submitTrack||i.track||r.track,s=e.submitReleaseStatus||i.releaseStatus||r.releaseStatus,l=e.submitRollout??i.rollout??i.userFraction??i.rolloutFraction??r.rollout??r.userFraction??r.rolloutFraction,a=e.submitChangesNotSentForReview??i.changesNotSentForReview??i.changes_not_sent_for_review??r.changesNotSentForReview??r.changes_not_sent_for_review;return cs({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function Qo(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?uu(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:cs({platform:e.platform,profile:n,buildId:t,latest:!1,...r,credentialId:e.submitCredentialId,packageName:e.platform==="android"?e.androidPackage:void 0,bundleId:e.platform==="ios"?e.iosBundleIdentifier:void 0,submitArgs:ds(e,t,n)})}}function es(e){!e.autoSubmit||e.dryRun||e.quiet||($.info(v.green("\u2713 Auto-submit has been registered with the build.")),$.info(v.dim(" You can close this terminal; submission will start after build success.")))}function ts(e){return`${Je}/build/${e}`}function Dn(e,t){if(!e.jsonOutput)return;let n=ge.resolve(e.jsonOutput),i={...t,url:t.url||ts(t.buildId),dashboardUrl:t.dashboardUrl||ts(t.buildId),updatedAt:new Date().toISOString()};try{let r=ge.dirname(n);r&&r!=="."&&de.mkdirSync(r,{recursive:!0}),de.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){$.warn(v.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function pu(e,t,n){let i=Fi(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await k.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),Dn(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),$.error(v.red(`
1476
+ \u2713 Build completed and reported to dashboard.`)),e.maestro&&!L&&await es(i,n,e,g),e.autoSubmit&&!L&&await Fi(i,n,e,g)}catch(C){let h=`Build artifact uploaded but dashboard finalization failed: ${C.message}`;throw $.error(v.red(`
1477
+ ${h}`)),await I(h),new Error(h)}}else if(i){let T="Build completed but produced no uploadable artifacts.";throw $.error(v.red(T)),await I(T),new Error(T)}}if(A){if($.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let P=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:P,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...ts(e,n,g,u)}),ns(e)}if(e.sshHost&&e.platform==="ios")await xr(e,n,a,i),e.autoSubmit&&await Fi(i,n,e,g);else{let P=await mi({...e,interactive:!!e.local},n,a,i,{branch:f,version:p,summary:b,buildType:y});await q(P)}return}if(B&&($.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let P=await k.post("/builds/source-upload-url",{projectId:i,buildId:n});if(P.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");Hi("SOURCE_UPLOAD",P.data.uploadUrl);let I=new Go,T=Gd(I,process.cwd(),e.platform),w=I.toBuffer();if(!e.quiet){let h=T.skipped.length>0?` Skipped: ${T.skipped.join(", ")}.`:"";t.message(`Prepared source (${T.files} files).${h}`)}e.quiet||t.message(`Uploading source (${(w.length/1024/1024).toFixed(1)} MB)...`);let C=!1;for(let h=1;h<=3;h++)try{await $n.put(P.data.uploadUrl,w,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),C=!0;break}catch(M){if(h<3)t.message(`Upload attempt ${h} failed (${M.code||M.message}), retrying...`),await new Promise(U=>setTimeout(U,2e3*h));else throw M}if(e.quiet||t.stop("Source uploaded"),i){let h=process.argv.slice(3).join(" ");await k.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:f,version:p,summary:b,startTime:r,buildType:y,buildProfile:g,buildArgs:h,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...ts(e,n,g,u)}),$.info(v.green("\u2713 Cloud build registered.")),ns(e)}e.platform==="android"&&await Tr(e,n,a,i,e.preBuild),e.quiet||$.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await hu(i,n,e),e.maestro&&await es(i,n,e,g),e.autoSubmit&&await Fi(i,n,e,g);return}}catch(l){let a=l.message||"Build failed";l.response?.data?.message?a=l.response.data.message:l.message.includes("status code 402")?a="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(a="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&await s(a),$.error(v.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function es(e,t,n,i){$.info(v.cyan(`
1478
+ \u{1F3BC} Queuing managed Maestro test...`)),await Ii({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,maestroEnv:n.maestroEnv,quiet:n.quiet})}async function Fi(e,t,n,i){if(!e){$.error(v.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}$.info(v.cyan(`
1479
+ Auto-submit: submitting the successful build...`));try{let r=await mu(e,t);if(r?.autoSubmit){let o=r.submissionId?`${Je}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?($.info(v.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),$.info(v.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?$.warn(v.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&$.info(v.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){dt(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await wn({platform:n.platform,profile:i,buildProfile:i,buildId:t,projectId:e,yes:n.yes,quiet:n.quiet,track:n.submitTrack,releaseStatus:n.submitReleaseStatus,rollout:n.submitRollout,changesNotSentForReview:n.submitChangesNotSentForReview,credentialId:n.submitCredentialId,packageName:n.androidPackage,jsonOutput:n.submitJsonOutput,submitArgs:us(n,t,i)})}catch(r){$.error(v.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function us(e,t,n){let i=["--platform",e.platform,"--profile",n,"--build-id",t];return e.submitTrack&&i.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&i.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&i.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&i.push("--changes-not-sent-for-review"),e.submitCredentialId&&i.push("--credential-id",e.submitCredentialId),e.platform==="android"&&e.androidPackage&&i.push("--package-name",e.androidPackage),e.platform==="ios"&&e.iosBundleIdentifier&&i.push("--bundle-id",e.iosBundleIdentifier),e.submitJsonOutput&&i.push("--json-output",e.submitJsonOutput),i.join(" ")}async function mu(e,t){try{let i=(await k.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){$.warn(v.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function ps(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function gu(e,t,n){let i=n?.submit?.[t]?.android||{},r=n?.submit?.production?.android||{},o=e.submitTrack||i.track||r.track,s=e.submitReleaseStatus||i.releaseStatus||r.releaseStatus,l=e.submitRollout??i.rollout??i.userFraction??i.rolloutFraction??r.rollout??r.userFraction??r.rolloutFraction,a=e.submitChangesNotSentForReview??i.changesNotSentForReview??i.changes_not_sent_for_review??r.changesNotSentForReview??r.changes_not_sent_for_review;return ps({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function ts(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?gu(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:ps({platform:e.platform,profile:n,buildId:t,latest:!1,...r,credentialId:e.submitCredentialId,packageName:e.platform==="android"?e.androidPackage:void 0,bundleId:e.platform==="ios"?e.iosBundleIdentifier:void 0,submitArgs:us(e,t,n)})}}function ns(e){!e.autoSubmit||e.dryRun||e.quiet||($.info(v.green("\u2713 Auto-submit has been registered with the build.")),$.info(v.dim(" You can close this terminal; submission will start after build success.")))}function is(e){return`${Je}/build/${e}`}function Dn(e,t){if(!e.jsonOutput)return;let n=ge.resolve(e.jsonOutput),i={...t,url:t.url||is(t.buildId),dashboardUrl:t.dashboardUrl||is(t.buildId),updatedAt:new Date().toISOString()};try{let r=ge.dirname(n);r&&r!=="."&&ce.mkdirSync(r,{recursive:!0}),ce.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){$.warn(v.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function hu(e,t,n){let i=Bi(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await k.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),Dn(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),$.error(v.red(`
1438
1480
  \u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),Dn(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),$.success(v.green(`
1439
1481
  \u2713 Build completed successfully!`));try{n.quiet||($.info(v.magenta(`
1440
- \u{1F4F1} Installation Hub:`)),$.info(v.dim(" - View & Install Build: ")+v.white.underline(`${Je}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await k.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let d=u.split(`
1441
- `);if(d.length>o){for(let f=o;f<d.length;f++)d[f].trim()&&console.log(v.dim(` ${d[f]}`));o=d.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),$.error(v.red(`
1442
- \u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Ln from"http";import*as Ss from"net";import{execFile as fu,execFileSync as mt,execSync as Tn,spawn as us}from"child_process";import pe from"chalk";import{log as ee}from"@clack/prompts";import mu from"axios";import se from"fs";import Ke from"os";import Z from"path";var st=7070,Zt=`http://127.0.0.1:${st}`,xt="com.radhya.mach.agent",kt="Mach Agent",Lt=`${xt}.service`,gu=5e3,hu=3e3,Cn=null,Nn=null,Ve=()=>Z.join(Ke.homedir(),m.configDir),ys=()=>Z.join(Ke.homedir(),"Library","LaunchAgents"),kn=()=>Z.join(ys(),`${xt}.plist`),bs=()=>Z.join(Ke.homedir(),".config","systemd","user"),Hi=()=>Z.join(bs(),Lt),ji=()=>Z.join(Ve(),"agent.cmd");function Gi(){return`gui/${process.getuid?.()||Number(Tn("id -u").toString().trim())}`}function Es(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function qt(e){return`<string>${Es(e)}</string>`}function Ki(){let e=process.argv[1]?se.realpathSync(process.argv[1]):"";if(!e||!se.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Vi(){let e=As(),t=process.platform==="win32"?[process.env.SystemRoot?Z.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:Ke.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[Z.join(i,"platform-tools"),Z.join(i,"emulator"),Z.join(i,"cmdline-tools","latest","bin"),Z.join(i,"tools","bin")]),...t].filter(Boolean).join(Z.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function As(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(Z.join(Ke.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(Z.join(Ke.homedir(),"Android","Sdk"),Z.join(Ke.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||Ke.homedir();e.push(t?Z.join(t,"Android","Sdk"):void 0,Z.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function Su(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function Is(e,t){let n=Su(e);for(let i of As()){let r=Z.join(i,t,n);if(se.existsSync(r))return r}return n}function ws(){return Is("adb","platform-tools")}function _s(){return Is("emulator","emulator")}function Bi(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function yu(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(bs(),{recursive:!0});let e=Ki(),t=Vi(),n=Object.entries(t).map(([r,o])=>`Environment=${Bi(`${r}=${o}`)}`).join(`
1482
+ \u{1F4F1} Installation Hub:`)),$.info(v.dim(" - View & Install Build: ")+v.white.underline(`${Je}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await k.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let c=u.split(`
1483
+ `);if(c.length>o){for(let f=o;f<c.length;f++)c[f].trim()&&console.log(v.dim(` ${c[f]}`));o=c.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),$.error(v.red(`
1484
+ \u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as xn from"http";import*as bs from"net";import{execFile as Su,execFileSync as mt,execSync as Tn,spawn as fs}from"child_process";import pe from"chalk";import{log as ee}from"@clack/prompts";import yu from"axios";import se from"fs";import Ke from"os";import Z from"path";var st=7070,Zt=`http://127.0.0.1:${st}`,Lt="com.radhya.mach.agent",kt="Mach Agent",xt=`${Lt}.service`,bu=5e3,Eu=3e3,Cn=null,Nn=null,Ve=()=>Z.join(Ke.homedir(),m.configDir),Es=()=>Z.join(Ke.homedir(),"Library","LaunchAgents"),kn=()=>Z.join(Es(),`${Lt}.plist`),As=()=>Z.join(Ke.homedir(),".config","systemd","user"),Gi=()=>Z.join(As(),xt),Ki=()=>Z.join(Ve(),"agent.cmd");function Vi(){return`gui/${process.getuid?.()||Number(Tn("id -u").toString().trim())}`}function Is(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function qt(e){return`<string>${Is(e)}</string>`}function zi(){let e=process.argv[1]?se.realpathSync(process.argv[1]):"";if(!e||!se.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Wi(){let e=ws(),t=process.platform==="win32"?[process.env.SystemRoot?Z.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:Ke.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[Z.join(i,"platform-tools"),Z.join(i,"emulator"),Z.join(i,"cmdline-tools","latest","bin"),Z.join(i,"tools","bin")]),...t].filter(Boolean).join(Z.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function ws(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(Z.join(Ke.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(Z.join(Ke.homedir(),"Android","Sdk"),Z.join(Ke.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||Ke.homedir();e.push(t?Z.join(t,"Android","Sdk"):void 0,Z.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function Au(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function _s(e,t){let n=Au(e);for(let i of ws()){let r=Z.join(i,t,n);if(se.existsSync(r))return r}return n}function Rs(){return _s("adb","platform-tools")}function $s(){return _s("emulator","emulator")}function ji(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function Iu(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(As(),{recursive:!0});let e=zi(),t=Wi(),n=Object.entries(t).map(([r,o])=>`Environment=${ji(`${r}=${o}`)}`).join(`
1443
1485
  `),i=`[Unit]
1444
1486
  Description=Mach local device agent
1445
1487
  After=default.target
1446
1488
 
1447
1489
  [Service]
1448
1490
  Type=simple
1449
- ExecStart=${e.map(Bi).join(" ")}
1450
- WorkingDirectory=${Bi(Ke.homedir())}
1491
+ ExecStart=${e.map(ji).join(" ")}
1492
+ WorkingDirectory=${ji(Ke.homedir())}
1451
1493
  ${n}
1452
1494
  Restart=on-failure
1453
1495
  RestartSec=5
@@ -1456,12 +1498,12 @@ StandardError=append:%h/${m.configDir}/agent.error.log
1456
1498
 
1457
1499
  [Install]
1458
1500
  WantedBy=default.target
1459
- `;return se.writeFileSync(Hi(),i),Hi()}function ft(e,t={}){try{return mt("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function bu(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");se.mkdirSync(Ve(),{recursive:!0});let e=Vi(),[t,n,...i]=Ki(),r=Z.join(Ve(),"agent.log"),o=Z.join(Ve(),"agent.error.log"),s=Object.entries(e).map(([c,u])=>`set "${c}=${u}"`).join(`\r
1460
- `),l=i.map(c=>`"${c.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
1501
+ `;return se.writeFileSync(Gi(),i),Gi()}function ft(e,t={}){try{return mt("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function wu(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");se.mkdirSync(Ve(),{recursive:!0});let e=Wi(),[t,n,...i]=zi(),r=Z.join(Ve(),"agent.log"),o=Z.join(Ve(),"agent.error.log"),s=Object.entries(e).map(([d,u])=>`set "${d}=${u}"`).join(`\r
1502
+ `),l=i.map(d=>`"${d.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
1461
1503
  ${s}\r
1462
1504
  cd /d "${Ke.homedir()}"\r
1463
1505
  "${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
1464
- `;return se.writeFileSync(ji(),a),ji()}function Qt(e,t={}){try{return mt("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Eu(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(ys(),{recursive:!0});let e=Ki(),t=Vi(),n=Z.join(Ve(),"agent.log"),i=Z.join(Ve(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Es(l)}</key>
1506
+ `;return se.writeFileSync(Ki(),a),Ki()}function Qt(e,t={}){try{return mt("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function _u(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");se.mkdirSync(Ve(),{recursive:!0}),se.mkdirSync(Es(),{recursive:!0});let e=zi(),t=Wi(),n=Z.join(Ve(),"agent.log"),i=Z.join(Ve(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Is(l)}</key>
1465
1507
  ${qt(a)}`).join(`
1466
1508
  `),o=e.map(l=>` ${qt(l)}`).join(`
1467
1509
  `),s=`<?xml version="1.0" encoding="UTF-8"?>
@@ -1469,7 +1511,7 @@ cd /d "${Ke.homedir()}"\r
1469
1511
  <plist version="1.0">
1470
1512
  <dict>
1471
1513
  <key>Label</key>
1472
- ${qt(xt)}
1514
+ ${qt(Lt)}
1473
1515
  <key>ProgramArguments</key>
1474
1516
  <array>
1475
1517
  ${o}
@@ -1486,23 +1528,23 @@ ${r}
1486
1528
  ${qt(i)}
1487
1529
  </dict>
1488
1530
  </plist>
1489
- `;return se.writeFileSync(kn(),s),kn()}function pt(e,t={}){try{return mt("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Au(e){return new Promise(t=>setTimeout(t,e))}function xn(e,t,n=gu){return new Promise((i,r)=>{fu(e,t,{timeout:n,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}i(s?.toString()||"")})})}async function Rs(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Zt}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,n=r=>{t||(t=!0,e(r))},i=Ln.get(`${Zt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function Iu(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await Rs())return!0;await Au(250)}return!1}async function $s(){return new Promise(e=>{let t=!1,n=Ss.createConnection({host:"127.0.0.1",port:st}),i=r=>{t||(t=!0,n.destroy(),e(r))};n.setTimeout(1e3),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function zi(){if(await Iu()){ee.success(pe.green("Mach agent installed and started."));return}if(await $s()){ee.warn(`Mach agent service is installed, but port ${st} is held by a process that is not answering /health.`),ee.info(pe.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}ee.warn(`Mach agent service is installed, but it did not start listening on ${Zt}.`)}async function wu(){let e=Eu(),t=Gi();pt(["bootout",t,e],{ignoreError:!0}),pt(["bootstrap",t,e],{ignoreError:!0})||pt(["load","-w",e]),pt(["enable",`${t}/${xt}`],{ignoreError:!0}),pt(["kickstart","-k",`${t}/${xt}`],{ignoreError:!0}),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Plist: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function vs(){let e=kn(),t=Gi();pt(["bootout",t,e],{ignoreError:!0})||pt(["unload","-w",e],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not loaded.")}async function _u(){await vs();let e=kn();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent service uninstalled."))}async function Ru(){let e=yu();ft(["daemon-reload"]),ft(["enable","--now",Lt]),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Service: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function $u(){ft(["stop",Lt],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not running.")}async function vu(){ft(["disable","--now",Lt],{ignoreError:!0}),ft(["daemon-reload"],{ignoreError:!0});let e=Hi();se.existsSync(e)&&se.unlinkSync(e),ft(["daemon-reload"],{ignoreError:!0}),ee.success(pe.green("Mach agent service uninstalled."))}async function Pu(){let e=bu();Qt(["/Create","/TN",kt,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Qt(["/Run","/TN",kt],{ignoreError:!0}),await zi(),ee.info(pe.dim(`It will start automatically when you log in. Task: ${kt}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function Ps(){Qt(["/End","/TN",kt],{ignoreError:!0})?ee.success(pe.green("Mach agent task stopped.")):ee.warn("Mach agent task was not running.")}async function Ou(){await Ps(),Qt(["/Delete","/TN",kt,"/F"],{ignoreError:!0});let e=ji();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent task uninstalled."))}async function ps(){if(process.platform==="darwin")return wu();if(process.platform==="linux")return Ru();if(process.platform==="win32")return Pu();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function fs(){if(process.platform==="darwin")return vs();if(process.platform==="linux")return $u();if(process.platform==="win32")return Ps();ee.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Du(){if(process.platform==="darwin")return _u();if(process.platform==="linux")return vu();if(process.platform==="win32")return Ou();ee.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Cu(){let e=await Rs(),t=e?!0:await $s();if(e?ee.success(pe.green(`Mach agent is online at ${Zt}`)):t?ee.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):ee.warn(`Mach agent is not responding at ${Zt}`),process.platform==="darwin"){let n=pt(["print",`${Gi()}/${xt}`],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=ft(["is-enabled",Lt],{ignoreError:!0}),i=ft(["is-active",Lt],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Qt(["/Query","/TN",kt],{ignoreError:!0});ee.info(pe.dim(`Login task: ${n?"installed":"not installed"}`))}}async function Nu(){let e=[];try{(await xn(ws(),["devices","-l"])).split(`
1490
- `).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await xn(_s(),["-list-avds"])).split(`
1491
- `).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Os(){if(process.platform!=="darwin")return[];try{let e=await xn("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Tu(){if(process.platform!=="darwin")return[];try{let e=await xn("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function ku(e){let t=await Os(),n=t.find(r=>r.id===e);if(n)return n;let i=t.filter(r=>r.status==="online");return i.length===1?i[0]:null}async function xu(){let[e,t,n]=await Promise.all([Nu(),Os(),Tu()]);return[...e,...t,...n]}async function Lu(){let e=Date.now();return Cn&&e-Cn.updatedAt<hu?Cn.targets:(Nn||(Nn=xu().then(t=>(Cn={targets:t,updatedAt:Date.now()},t)).finally(()=>{Nn=null})),Nn)}async function ms(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Mu(e,t){let n=await mu({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=se.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}function gs(e,t){let n=e?.stderr?.toString?.().trim();if(n)return n;let i=e?.stdout?.toString?.().trim();return i||e?.message||t}function Uu(e,t){return mt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim()}function Fu(e){let t=Z.join(e,"Info.plist");if(!se.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=Uu(t,"CFBundleExecutable"),i=Z.join(e,n);if(!se.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i}function Bu(){return process.arch==="arm64"?"arm64":"x86_64"}function Hu(e){return se.existsSync(e)?se.readdirSync(e).map(t=>Z.join(e,t)).filter(t=>t.endsWith(".app")&&se.statSync(t).isDirectory()):[]}function hs(e,t){let n=Hu(e);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple .app bundles found in ${t}: ${n.map(i=>Z.basename(i)).join(", ")}. Mach cannot safely choose which app to install.`);return""}function ju(e){let t=Fu(e),n=Bu(),i="",r="";try{i=mt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app architecture for ${Z.basename(e)}: ${o.message}`)}if(!new RegExp(`\\b${n}\\b`).test(i))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} does not include the ${n} simulator architecture. lipo output: ${i}. Rebuild the app with the latest Mach CLI and make sure the profile is a simulator build.`);try{r=mt("/usr/bin/xcrun",["vtool","-show-build",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app platform for ${Z.basename(e)}: ${o.message}`)}if(!/\bplatform\s+IOSSIMULATOR\b/i.test(r))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain platform IOSSIMULATOR. vtool output: ${r}. Rebuild the app with the latest Mach CLI.`)}async function Gu(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=se.mkdtempSync(Z.join(Ke.tmpdir(),`${st}-install-`)),s=Z.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Mu(t,s),i==="android"){mt(ws(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Tn(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l=Z.join(o,"Payload"),a=se.existsSync(l),c=r||a,u="";if(c?u=hs(l,"Payload"):u=hs(o,"the simulator artifact"),!u)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);let d=c?null:await ku(e);if(d){try{ju(u),mt("/usr/bin/xcrun",["simctl","install",d.id,u],{stdio:"pipe"})}catch(f){throw new Error(gs(f,"iOS Simulator install failed."))}return}if(!c)throw new Error("Selected iOS Simulator was not found. Refresh Install Hub devices or boot one simulator and try again.");try{Tn(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(u)}`,{stdio:"pipe"})}catch(f){throw new Error(gs(f,"iOS device install failed."))}}finally{se.rmSync(o,{recursive:!0,force:!0})}}function Ku(e,t){if(!e)throw new Error("Device id is required.");if(t==="ios"){if(process.platform!=="darwin")throw new Error("iOS Simulator launch requires macOS.");return Tn(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),us("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return us(_s(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Vu(){process.platform!=="darwin"&&ee.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Ln.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${st}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Lu().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:st,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await ms(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Gu(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await ms(i),l=Ku(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(st,"127.0.0.1",()=>{ee.success(pe.green(`Local device agent running on http://localhost:${st}`)),ee.info(pe.dim("Keep this running while using the Install Hub on the dashboard.")),ee.info(pe.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?ee.error(`Port ${st} is already in use \u2014 agent may already be running.`):ee.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ds(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Vu();return}if(t==="install"){await ps();return}if(t==="status"){await Cu();return}if(t==="stop"){await fs();return}if(t==="uninstall"){await Du();return}if(t==="restart"){await fs(),await ps();return}ee.error(`Unknown agent action: ${e}`),ee.info(pe.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as If}from"module";import{text as Wu,password as Yu,spinner as Ju,isCancel as Ts}from"@clack/prompts";import Xi from"chalk";import en from"fs";import Cs from"path";import zu from"os";var Wi=Cs.join(zu.homedir(),m.configDir),Yi=Cs.join(Wi,"config.json");function Ji(){if(!en.existsSync(Yi))return{};try{return JSON.parse(en.readFileSync(Yi,"utf-8"))}catch{return{}}}function Ns(e){en.existsSync(Wi)||en.mkdirSync(Wi,{recursive:!0});let n={...Ji(),...e};en.writeFileSync(Yi,JSON.stringify(n,null,2))}async function ks(){let e=Ji(),t=await Wu({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ts(t))return;let n=await Yu({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ts(n))return;let i=Ju();i.start("Authenticating...");try{let o=await(await fetch(`${vt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(cr({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Ns({lastLoginEmail:t}),i.stop(Xi.green("Login successful!"))):i.stop(Xi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Xi.red("Network error: "+r.message))}}import{log as Mn,outro as Xu}from"@clack/prompts";import tn from"chalk";async function xs(){let e=ur(),t=`${m.envPrefix}TOKEN`;e?Mn.success(tn.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Mn.warn(tn.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Mn.warn(tn.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Mn.info(tn.dim(`Run: unset ${t}`))),Xu(tn.blue("---"))}import{outro as qu,select as Zu,spinner as Qu,isCancel as ep}from"@clack/prompts";import Un from"chalk";import qi from"fs";import tp from"path";var Ls=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",np=()=>process.versions.node.split(".")[0]||"24";async function Ms(){if(!Pe()){console.log(Un.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Qu();t.start("Fetching projects...");try{let{data:n}=await k.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Un.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(g=>({value:g.projectId,label:`${g.name} (${g.slug})`})),r=await Zu({message:"Select a project to link:",options:i});if(ep(r))return;let o=tp.join(process.cwd(),m.configFileName),s={};if(qi.existsSync(o))try{s=JSON.parse(qi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(g=>g.projectId===r),a=s.android?.package||rt("android"),c=s.ios?.bundleIdentifier||rt("ios"),u=s.android||{},d=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,framework:fr(s.framework)||fn,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||np(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:Ls(f.ascAppId),appleTeamId:Ls(f.appleTeamId)}}}};qi.writeFileSync(o,JSON.stringify(p,null,2)),qu(Un.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(Un.red("Error fetching projects: "+n.message))}}import{outro as ip,text as Fn,select as rp,spinner as op,isCancel as nn}from"@clack/prompts";import rn from"chalk";import sp from"fs";import ap from"path";import{randomUUID as lp}from"crypto";var dp=()=>process.versions.node.split(".")[0]||"24";async function Us(){if(!Pe()){console.log(rn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Fn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(nn(t))return;let n=await Fn({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(l){if(l.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(l))return"Slug must be lowercase alphanumeric with dashes."}});if(nn(n))return;let i=await rp({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nn(i))return;let r="";if(i==="android"||i==="all"){let l=rt("android");if(r=await Fn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),nn(r))return}let o="";if(i==="ios"||i==="all"){let l=rt("ios");if(o=await Fn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),nn(o))return}let s=op();s.start("Creating project...");try{let l=lp(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await k.post("/projects",c);if(u.status==="success"){s.stop(rn.green("Project created successfully!"));let d=ap.join(process.cwd(),m.configFileName);sp.writeFileSync(d,JSON.stringify({projectId:l,framework:fn,name:t,slug:n,nodeVersion:dp(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),ip(rn.green(`Initialized project ${t} and linked locally!`))}else s.stop(rn.red("creation failed: "+u.message))}catch(l){s.stop(rn.red("Network error: "+l.message))}}import{spinner as Zi,log as ve}from"@clack/prompts";import on from"chalk";import Bn from"fs";import Fs from"path";function Qi(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function cp(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function up(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${cp(e[i])}`)].join(`
1531
+ `;return se.writeFileSync(kn(),s),kn()}function pt(e,t={}){try{return mt("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Ru(e){return new Promise(t=>setTimeout(t,e))}function Ln(e,t,n=bu){return new Promise((i,r)=>{Su(e,t,{timeout:n,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}i(s?.toString()||"")})})}async function vs(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Zt}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,n=r=>{t||(t=!0,e(r))},i=xn.get(`${Zt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function $u(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await vs())return!0;await Ru(250)}return!1}async function Ps(){return new Promise(e=>{let t=!1,n=bs.createConnection({host:"127.0.0.1",port:st}),i=r=>{t||(t=!0,n.destroy(),e(r))};n.setTimeout(1e3),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function Yi(){if(await $u()){ee.success(pe.green("Mach agent installed and started."));return}if(await Ps()){ee.warn(`Mach agent service is installed, but port ${st} is held by a process that is not answering /health.`),ee.info(pe.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}ee.warn(`Mach agent service is installed, but it did not start listening on ${Zt}.`)}async function vu(){let e=_u(),t=Vi();pt(["bootout",t,e],{ignoreError:!0}),pt(["bootstrap",t,e],{ignoreError:!0})||pt(["load","-w",e]),pt(["enable",`${t}/${Lt}`],{ignoreError:!0}),pt(["kickstart","-k",`${t}/${Lt}`],{ignoreError:!0}),await Yi(),ee.info(pe.dim(`It will start automatically when you log in. Plist: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function Os(){let e=kn(),t=Vi();pt(["bootout",t,e],{ignoreError:!0})||pt(["unload","-w",e],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not loaded.")}async function Pu(){await Os();let e=kn();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent service uninstalled."))}async function Ou(){let e=Iu();ft(["daemon-reload"]),ft(["enable","--now",xt]),await Yi(),ee.info(pe.dim(`It will start automatically when you log in. Service: ${e}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function Du(){ft(["stop",xt],{ignoreError:!0})?ee.success(pe.green("Mach agent service stopped.")):ee.warn("Mach agent service was not running.")}async function Cu(){ft(["disable","--now",xt],{ignoreError:!0}),ft(["daemon-reload"],{ignoreError:!0});let e=Gi();se.existsSync(e)&&se.unlinkSync(e),ft(["daemon-reload"],{ignoreError:!0}),ee.success(pe.green("Mach agent service uninstalled."))}async function Nu(){let e=wu();Qt(["/Create","/TN",kt,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Qt(["/Run","/TN",kt],{ignoreError:!0}),await Yi(),ee.info(pe.dim(`It will start automatically when you log in. Task: ${kt}`)),ee.info(pe.dim(`Logs: ${Z.join(Ve(),"agent.log")}`))}async function Ds(){Qt(["/End","/TN",kt],{ignoreError:!0})?ee.success(pe.green("Mach agent task stopped.")):ee.warn("Mach agent task was not running.")}async function Tu(){await Ds(),Qt(["/Delete","/TN",kt,"/F"],{ignoreError:!0});let e=Ki();se.existsSync(e)&&se.unlinkSync(e),ee.success(pe.green("Mach agent task uninstalled."))}async function ms(){if(process.platform==="darwin")return vu();if(process.platform==="linux")return Ou();if(process.platform==="win32")return Nu();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function gs(){if(process.platform==="darwin")return Os();if(process.platform==="linux")return Du();if(process.platform==="win32")return Ds();ee.warn(`Background agent service control is not supported on ${process.platform}.`)}async function ku(){if(process.platform==="darwin")return Pu();if(process.platform==="linux")return Cu();if(process.platform==="win32")return Tu();ee.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Lu(){let e=await vs(),t=e?!0:await Ps();if(e?ee.success(pe.green(`Mach agent is online at ${Zt}`)):t?ee.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):ee.warn(`Mach agent is not responding at ${Zt}`),process.platform==="darwin"){let n=pt(["print",`${Vi()}/${Lt}`],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=ft(["is-enabled",xt],{ignoreError:!0}),i=ft(["is-active",xt],{ignoreError:!0});ee.info(pe.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Qt(["/Query","/TN",kt],{ignoreError:!0});ee.info(pe.dim(`Login task: ${n?"installed":"not installed"}`))}}async function xu(){let e=[];try{(await Ln(Rs(),["devices","-l"])).split(`
1532
+ `).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await Ln($s(),["-list-avds"])).split(`
1533
+ `).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Cs(){if(process.platform!=="darwin")return[];try{let e=await Ln("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Mu(){if(process.platform!=="darwin")return[];try{let e=await Ln("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function Uu(e){let t=await Cs(),n=t.find(r=>r.id===e);if(n)return n;let i=t.filter(r=>r.status==="online");return i.length===1?i[0]:null}async function Fu(){let[e,t,n]=await Promise.all([xu(),Cs(),Mu()]);return[...e,...t,...n]}async function Bu(){let e=Date.now();return Cn&&e-Cn.updatedAt<Eu?Cn.targets:(Nn||(Nn=Fu().then(t=>(Cn={targets:t,updatedAt:Date.now()},t)).finally(()=>{Nn=null})),Nn)}async function hs(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Hu(e,t){let n=await yu({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=se.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}function Ss(e,t){let n=e?.stderr?.toString?.().trim();if(n)return n;let i=e?.stdout?.toString?.().trim();return i||e?.message||t}function ju(e,t){return mt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim()}function Gu(e){let t=Z.join(e,"Info.plist");if(!se.existsSync(t))throw new Error(`Could not validate iOS app executable: ${t} not found.`);let n=ju(t,"CFBundleExecutable"),i=Z.join(e,n);if(!se.existsSync(i))throw new Error(`Could not validate iOS app executable: ${i} not found.`);return i}function Ku(){return process.arch==="arm64"?"arm64":"x86_64"}function Vu(e){return se.existsSync(e)?se.readdirSync(e).map(t=>Z.join(e,t)).filter(t=>t.endsWith(".app")&&se.statSync(t).isDirectory()):[]}function ys(e,t){let n=Vu(e);if(n.length===1)return n[0];if(n.length>1)throw new Error(`Multiple .app bundles found in ${t}: ${n.map(i=>Z.basename(i)).join(", ")}. Mach cannot safely choose which app to install.`);return""}function zu(e){let t=Gu(e),n=Ku(),i="",r="";try{i=mt("lipo",["-info",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app architecture for ${Z.basename(e)}: ${o.message}`)}if(!new RegExp(`\\b${n}\\b`).test(i))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} does not include the ${n} simulator architecture. lipo output: ${i}. Rebuild the app with the latest Mach CLI and make sure the profile is a simulator build.`);try{r=mt("/usr/bin/xcrun",["vtool","-show-build",t],{encoding:"utf-8"}).trim()}catch(o){throw new Error(`Could not inspect iOS simulator app platform for ${Z.basename(e)}: ${o.message}`)}if(!/\bplatform\s+IOSSIMULATOR\b/i.test(r))throw new Error(`This iOS simulator artifact cannot be installed because ${Z.basename(e)} was built for the wrong Apple platform. A simulator artifact must contain platform IOSSIMULATOR. vtool output: ${r}. Rebuild the app with the latest Mach CLI.`)}async function Wu(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=se.mkdtempSync(Z.join(Ke.tmpdir(),`${st}-install-`)),s=Z.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Hu(t,s),i==="android"){mt(Rs(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Tn(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l=Z.join(o,"Payload"),a=se.existsSync(l),d=r||a,u="";if(d?u=ys(l,"Payload"):u=ys(o,"the simulator artifact"),!u)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);let c=d?null:await Uu(e);if(c){try{zu(u),mt("/usr/bin/xcrun",["simctl","install",c.id,u],{stdio:"pipe"})}catch(f){throw new Error(Ss(f,"iOS Simulator install failed."))}return}if(!d)throw new Error("Selected iOS Simulator was not found. Refresh Install Hub devices or boot one simulator and try again.");try{Tn(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(u)}`,{stdio:"pipe"})}catch(f){throw new Error(Ss(f,"iOS device install failed."))}}finally{se.rmSync(o,{recursive:!0,force:!0})}}function Yu(e,t){if(!e)throw new Error("Device id is required.");if(t==="ios"){if(process.platform!=="darwin")throw new Error("iOS Simulator launch requires macOS.");return Tn(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),fs("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return fs($s(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function Ju(){process.platform!=="darwin"&&ee.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=xn.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${st}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Bu().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:st,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await hs(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Wu(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await hs(i),l=Yu(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(st,"127.0.0.1",()=>{ee.success(pe.green(`Local device agent running on http://localhost:${st}`)),ee.info(pe.dim("Keep this running while using the Install Hub on the dashboard.")),ee.info(pe.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?ee.error(`Port ${st} is already in use \u2014 agent may already be running.`):ee.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function Ns(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await Ju();return}if(t==="install"){await ms();return}if(t==="status"){await Lu();return}if(t==="stop"){await gs();return}if(t==="uninstall"){await ku();return}if(t==="restart"){await gs(),await ms();return}ee.error(`Unknown agent action: ${e}`),ee.info(pe.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as $f}from"module";import{text as qu,password as Zu,spinner as Qu,isCancel as Ls}from"@clack/prompts";import Zi from"chalk";import en from"fs";import Ts from"path";import Xu from"os";var Ji=Ts.join(Xu.homedir(),m.configDir),Xi=Ts.join(Ji,"config.json");function qi(){if(!en.existsSync(Xi))return{};try{return JSON.parse(en.readFileSync(Xi,"utf-8"))}catch{return{}}}function ks(e){en.existsSync(Ji)||en.mkdirSync(Ji,{recursive:!0});let n={...qi(),...e};en.writeFileSync(Xi,JSON.stringify(n,null,2))}async function xs(){let e=qi(),t=await qu({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ls(t))return;let n=await Zu({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ls(n))return;let i=Qu();i.start("Authenticating...");try{let o=await(await fetch(`${vt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(pr({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ks({lastLoginEmail:t}),i.stop(Zi.green("Login successful!"))):i.stop(Zi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Zi.red("Network error: "+r.message))}}import{log as Mn,outro as ep}from"@clack/prompts";import tn from"chalk";async function Ms(){let e=fr(),t=`${m.envPrefix}TOKEN`;e?Mn.success(tn.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Mn.warn(tn.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Mn.warn(tn.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Mn.info(tn.dim(`Run: unset ${t}`))),ep(tn.blue("---"))}import{outro as tp,select as np,spinner as ip,isCancel as rp}from"@clack/prompts";import Un from"chalk";import Qi from"fs";import op from"path";var Us=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",sp=()=>process.versions.node.split(".")[0]||"24";async function Fs(){if(!Pe()){console.log(Un.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=ip();t.start("Fetching projects...");try{let{data:n}=await k.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Un.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(g=>({value:g.projectId,label:`${g.name} (${g.slug})`})),r=await np({message:"Select a project to link:",options:i});if(rp(r))return;let o=op.join(process.cwd(),m.configFileName),s={};if(Qi.existsSync(o))try{s=JSON.parse(Qi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(g=>g.projectId===r),a=s.android?.package||rt("android"),d=s.ios?.bundleIdentifier||rt("ios"),u=s.android||{},c=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,framework:gr(s.framework)||fn,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||sp(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:d||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...c,track:c.track||"internal",releaseStatus:c.releaseStatus||"completed"},ios:{ascAppId:Us(f.ascAppId),appleTeamId:Us(f.appleTeamId)}}}};Qi.writeFileSync(o,JSON.stringify(p,null,2)),tp(Un.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(Un.red("Error fetching projects: "+n.message))}}import{outro as ap,text as Fn,select as lp,spinner as cp,isCancel as nn}from"@clack/prompts";import rn from"chalk";import dp from"fs";import up from"path";import{randomUUID as pp}from"crypto";var fp=()=>process.versions.node.split(".")[0]||"24";async function Bs(){if(!Pe()){console.log(rn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Fn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(nn(t))return;let n=await Fn({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(l){if(l.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(l))return"Slug must be lowercase alphanumeric with dashes."}});if(nn(n))return;let i=await lp({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nn(i))return;let r="";if(i==="android"||i==="all"){let l=rt("android");if(r=await Fn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),nn(r))return}let o="";if(i==="ios"||i==="all"){let l=rt("ios");if(o=await Fn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),nn(o))return}let s=cp();s.start("Creating project...");try{let l=pp(),d={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await k.post("/projects",d);if(u.status==="success"){s.stop(rn.green("Project created successfully!"));let c=up.join(process.cwd(),m.configFileName);dp.writeFileSync(c,JSON.stringify({projectId:l,framework:fn,name:t,slug:n,nodeVersion:fp(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),ap(rn.green(`Initialized project ${t} and linked locally!`))}else s.stop(rn.red("creation failed: "+u.message))}catch(l){s.stop(rn.red("Network error: "+l.message))}}import{spinner as er,log as ve}from"@clack/prompts";import on from"chalk";import Bn from"fs";import Hs from"path";function tr(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function mp(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function gp(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${mp(e[i])}`)].join(`
1492
1534
  `)}
1493
- `}async function Bs(e,t,n={}){let i=Pe();if(!i){ve.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=Fs.join(process.cwd(),m.configFileName);if(!Bn.existsSync(r)){ve.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Bn.readFileSync(r,"utf-8"))}catch{ve.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){ve.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await pp(s,t,i):e==="list"?await fp(s,i):e==="pull"||e==="download"||e==="export"?await mp(s,n):ve.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function pp(e,t,n){if(t.length===0){ve.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Zi();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),c=a.join("=");if(!l||c===void 0){ve.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:d}=await k.post(`/projects/${e}/secrets`,u);d.status==="success"?r++:(ve.error(`Failed to set ${l}: ${d.message}`),o++)}catch(u){ve.error(Qi(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function fp(e,t){let n=Zi();n.start("Fetching environment variables...");try{let{data:i}=await k.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?ve.info("No environment variables found for this project."):(ve.info(on.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${on.cyan(o.key)} = ${s} ${on.gray(`[${o.environment}]`)}`)}))}else n.stop(on.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),ve.error(Qi(i,e,"list"))}}async function mp(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=Fs.resolve(process.cwd(),i);if(Bn.existsSync(r)&&!t.overwrite){ve.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Zi();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await k.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(on.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=up(l,n);Bn.writeFileSync(r,a,{encoding:"utf-8",mode:384}),o.stop(`Wrote ${Object.keys(l).length} variable(s) to ${i}.`)}catch(s){o.stop("Failed to download variables."),ve.error(Qi(s,e,"pull"))}}import{spinner as gp,log as Rt,outro as hp}from"@clack/prompts";import er from"chalk";import Hs from"fs";import Sp from"path";import{execSync as yp}from"child_process";import bp from"adm-zip";import Ep from"axios";import{randomUUID as Ap}from"crypto";async function js(e){Rt.info(er.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=$e();(!t||!t.projectId)&&(Rt.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Hs.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Rt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=gp();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{yp("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),Rt.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Sp.join(process.cwd(),"dist");Hs.existsSync(s)||(o.stop("Missing dist folder."),Rt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new bp;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=Ap(),u=await k.post("/builds/source-upload-url",{projectId:n,buildId:c});if(u.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:d,key:f}=u.data;await Ep.put(d,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:f}),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:f}),o.stop("Update Live!"),hp(er.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Rt.info(er.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),Rt.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Ip,outro as Gs,log as Mt}from"@clack/prompts";import qe from"chalk";async function Ks(){Ip(qe.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Mt.warn(qe.yellow("You are not logged in.")),Mt.info(`Run \`${m.nameLower} login\` to authenticate.`),Gs();return}Mt.info(`${qe.bold("Logged in as:")} ${qe.green(e.email)}`);try{await k.get("/projects");let n=Pe().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);Mt.info(`${qe.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Mt.warn(`${qe.bold("Token status:")} ${qe.red("Expired")} (Auto-refresh failed)`)}}}catch{Mt.warn(`${qe.bold("Token status:")} ${qe.red("Unreachable")} (Session might be truly expired)${vt}`)}Gs(qe.blue("---"))}import{spawn as Rp}from"child_process";import{log as gt}from"@clack/prompts";import xe from"chalk";import $p from"fs";import wp from"net";async function _p(e){return new Promise(t=>{let n=wp.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function Vs(e,t=20){let n=e;for(;n<e+t;){if(!await _p(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var zs=async e=>{gt.info(xe.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?lt(t,n):null,r={...process.env};if(t?.projectId)try{gt.info(xe.dim(`Fetching managed secrets for profile: ${n}...`));let d=await k.get(`/projects/${t.projectId}/secrets/export?env=${n}`);d.data?.status==="success"&&d.data.secrets&&(Object.assign(r,d.data.secrets),gt.info(xe.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{gt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,Pt(t,m.envPrefix)),i&&(Object.assign(r,Pt(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let d=JSON.parse($p.readFileSync("package.json","utf-8"));o=!!(d.dependencies?.expo||d.devDependencies?.expo)}catch{gt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await Vs(s);l!==s&&gt.info(xe.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",c=[];if(o?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),o){let d=[`${xe.cyan("i")} open iOS simulator`,`${xe.cyan("a")} open Android emulator/device`,`${xe.cyan("w")} open web`,`${xe.cyan("r")} reload app`];gt.info([xe.bold("Launch controls"),...d.map(f=>` ${f}`),"",xe.dim("Direct launch: mach start --ios | --android | --web"),xe.dim(`Metro URL: http://localhost:${l}`)].join(`
1494
- `))}else gt.info(xe.dim(`Metro URL: http://localhost:${l}`));let u=Rp(a,c,{stdio:"inherit",env:r});return new Promise((d,f)=>{u.on("exit",p=>{p===0?d():f(new Error(`Dev server exited with code ${p}`))}),u.on("error",p=>{f(p)})})};import{log as Ne}from"@clack/prompts";import ze from"chalk";var Ws=async e=>{let t=$e();t||(Ne.error(ze.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=lt(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}Ne.info(ze.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),Ne.info(ze.dim("----------------------------------------")),Ne.info(`${ze.blue("Project ID:")} ${t.projectId}`),Ne.info(`${ze.blue("Name:")} ${t.name}`),Ne.info(`${ze.blue("Scheme:")} ${t.scheme}`),i?(Ne.info(ze.dim(`
1535
+ `}async function js(e,t,n={}){let i=Pe();if(!i){ve.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=Hs.join(process.cwd(),m.configFileName);if(!Bn.existsSync(r)){ve.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Bn.readFileSync(r,"utf-8"))}catch{ve.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){ve.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await hp(s,t,i):e==="list"?await Sp(s,i):e==="pull"||e==="download"||e==="export"?await yp(s,n):ve.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function hp(e,t,n){if(t.length===0){ve.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=er();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),d=a.join("=");if(!l||d===void 0){ve.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:c}=await k.post(`/projects/${e}/secrets`,u);c.status==="success"?r++:(ve.error(`Failed to set ${l}: ${c.message}`),o++)}catch(u){ve.error(tr(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function Sp(e,t){let n=er();n.start("Fetching environment variables...");try{let{data:i}=await k.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?ve.info("No environment variables found for this project."):(ve.info(on.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${on.cyan(o.key)} = ${s} ${on.gray(`[${o.environment}]`)}`)}))}else n.stop(on.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),ve.error(tr(i,e,"list"))}}async function yp(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=Hs.resolve(process.cwd(),i);if(Bn.existsSync(r)&&!t.overwrite){ve.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=er();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await k.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(on.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=gp(l,n);Bn.writeFileSync(r,a,{encoding:"utf-8",mode:384}),o.stop(`Wrote ${Object.keys(l).length} variable(s) to ${i}.`)}catch(s){o.stop("Failed to download variables."),ve.error(tr(s,e,"pull"))}}import{spinner as bp,log as Rt,outro as Ep}from"@clack/prompts";import nr from"chalk";import Gs from"fs";import Ap from"path";import{execSync as Ip}from"child_process";import wp from"adm-zip";import _p from"axios";import{randomUUID as Rp}from"crypto";async function Ks(e){Rt.info(nr.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=$e();(!t||!t.projectId)&&(Rt.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Gs.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Rt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=bp();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{Ip("npx expo export --platform all",{stdio:"ignore"})}catch(d){o.stop("Compilation failed."),Rt.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Ap.join(process.cwd(),"dist");Gs.existsSync(s)||(o.stop("Missing dist folder."),Rt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new wp;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let d=Rp(),u=await k.post("/builds/source-upload-url",{projectId:n,buildId:d});if(u.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:c,key:f}=u.data;await _p.put(c,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${d}-android`,manifestKey:f}),await k.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${d}-ios`,manifestKey:f}),o.stop("Update Live!"),Ep(nr.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Rt.info(nr.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(d){o.stop("Update failed during Cloud Sync."),Rt.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as $p,outro as Vs,log as Mt}from"@clack/prompts";import qe from"chalk";async function zs(){$p(qe.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Mt.warn(qe.yellow("You are not logged in.")),Mt.info(`Run \`${m.nameLower} login\` to authenticate.`),Vs();return}Mt.info(`${qe.bold("Logged in as:")} ${qe.green(e.email)}`);try{await k.get("/projects");let n=Pe().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);Mt.info(`${qe.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Mt.warn(`${qe.bold("Token status:")} ${qe.red("Expired")} (Auto-refresh failed)`)}}}catch{Mt.warn(`${qe.bold("Token status:")} ${qe.red("Unreachable")} (Session might be truly expired)${vt}`)}Vs(qe.blue("---"))}import{spawn as Op}from"child_process";import{log as gt}from"@clack/prompts";import Le from"chalk";import Dp from"fs";import vp from"net";async function Pp(e){return new Promise(t=>{let n=vp.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function Ws(e,t=20){let n=e;for(;n<e+t;){if(!await Pp(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var Ys=async e=>{gt.info(Le.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?lt(t,n):null,r={...process.env};if(t?.projectId)try{gt.info(Le.dim(`Fetching managed secrets for profile: ${n}...`));let c=await k.get(`/projects/${t.projectId}/secrets/export?env=${n}`);c.data?.status==="success"&&c.data.secrets&&(Object.assign(r,c.data.secrets),gt.info(Le.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{gt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,Pt(t,m.envPrefix)),i&&(Object.assign(r,Pt(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let c=JSON.parse(Dp.readFileSync("package.json","utf-8"));o=!!(c.dependencies?.expo||c.devDependencies?.expo)}catch{gt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await Ws(s);l!==s&&gt.info(Le.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",d=[];if(o?(d=["expo","start","--port",String(l)],e.clear&&d.push("--clear"),e.tunnel&&d.push("--tunnel"),e.lan&&d.push("--lan"),e.localhost&&d.push("--localhost"),e.ios&&d.push("--ios"),e.android&&d.push("--android"),e.web&&d.push("--web")):(d=["react-native","start","--port",String(l)],e.clear&&d.push("--clear")),o){let c=[`${Le.cyan("i")} open iOS simulator`,`${Le.cyan("a")} open Android emulator/device`,`${Le.cyan("w")} open web`,`${Le.cyan("r")} reload app`];gt.info([Le.bold("Launch controls"),...c.map(f=>` ${f}`),"",Le.dim("Direct launch: mach start --ios | --android | --web"),Le.dim(`Metro URL: http://localhost:${l}`)].join(`
1536
+ `))}else gt.info(Le.dim(`Metro URL: http://localhost:${l}`));let u=Op(a,d,{stdio:"inherit",env:r});return new Promise((c,f)=>{u.on("exit",p=>{p===0?c():f(new Error(`Dev server exited with code ${p}`))}),u.on("error",p=>{f(p)})})};import{log as Ne}from"@clack/prompts";import ze from"chalk";var Js=async e=>{let t=$e();t||(Ne.error(ze.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=lt(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}Ne.info(ze.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),Ne.info(ze.dim("----------------------------------------")),Ne.info(`${ze.blue("Project ID:")} ${t.projectId}`),Ne.info(`${ze.blue("Name:")} ${t.name}`),Ne.info(`${ze.blue("Scheme:")} ${t.scheme}`),i?(Ne.info(ze.dim(`
1495
1537
  Profile Settings:`)),Ne.info(`${ze.cyan("Distribution:")} ${i.distribution||"none"}`),Ne.info(`${ze.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(Ne.info(ze.dim(`
1496
- Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Ne.info(` ${r}=${o}`)}))):Ne.warn(`Profile '${n}' not found.`),Ne.info(ze.dim("----------------------------------------"))};import{log as Le,spinner as ln,text as Ys,select as Js,confirm as vp,isCancel as sn,cancel as an,outro as dn,note as Pp}from"@clack/prompts";import ie from"chalk";import{execSync as Op}from"child_process";async function Dp(){try{let e=Op("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}var Xs=e=>e?.trim().toUpperCase()||void 0;function qs(e){let t=$e(),n=t?gr(t):{},i=Xs(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Cp(e){let t=e.udid,n=e.name,i=qs(e),r=i.teamId;if(!t){let s=ln();s.start("Scanning for connected iOS devices...");let l=await Dp();if(s.stop(l.length>0?`Found ${l.length} device(s)`:"No devices detected"),l.length===1)t=l[0].udid,n=n||l[0].name,Le.info(`Detected: ${ie.bold(n)} (${ie.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await Js({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(sn(a)){an("Cancelled");return}t=a;let c=l.find(u=>u.udid===t);n=n||c.name}else{Le.info(ie.dim("No connected devices found. Enter UDID manually."));let a=await Ys({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(c){if(c.length<10)return"UDID seems too short"}});if(sn(a)){an("Cancelled");return}t=a}}if(!n){let s=await Ys({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(sn(s)){an("Cancelled");return}n=s}let o=ln();o.start("Registering device...");try{await k.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(ie.green("Device registered!")),Le.info(` ${ie.bold("Name:")} ${n}`),Le.info(` ${ie.bold("UDID:")} ${ie.dim(t)}`),r&&Le.info(` ${ie.bold("Team:")} ${ie.dim(r)}`)}catch(s){o.stop(ie.red("Failed to register device")),Le.error(s.response?.data?.message||s.message)}dn(ie.blue("---"))}async function Np(e={}){let t=Xs(e.teamId),n=ln();n.start("Fetching registered devices...");try{let r=(await k.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){Le.info(ie.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),dn(ie.blue("---"));return}let o=r.map(s=>{let l=new Date(s.createdAt).toLocaleDateString();return` ${ie.bold(s.name.padEnd(24))} ${ie.dim(s.udid.padEnd(28))} ${ie.dim((s.teamId||"-").padEnd(12))} ${ie.cyan((s.addedVia||"-").padEnd(10))} ${ie.dim(l)}`});Pp(` ${ie.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
1538
+ Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Ne.info(` ${r}=${o}`)}))):Ne.warn(`Profile '${n}' not found.`),Ne.info(ze.dim("----------------------------------------"))};import{log as xe,spinner as ln,text as Xs,select as qs,confirm as Cp,isCancel as sn,cancel as an,outro as cn,note as Np}from"@clack/prompts";import ie from"chalk";import{execSync as Tp}from"child_process";async function kp(){try{let e=Tp("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}var Zs=e=>e?.trim().toUpperCase()||void 0;function Qs(e){let t=$e(),n=t?Sr(t):{},i=Zs(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Lp(e){let t=e.udid,n=e.name,i=Qs(e),r=i.teamId;if(!t){let s=ln();s.start("Scanning for connected iOS devices...");let l=await kp();if(s.stop(l.length>0?`Found ${l.length} device(s)`:"No devices detected"),l.length===1)t=l[0].udid,n=n||l[0].name,xe.info(`Detected: ${ie.bold(n)} (${ie.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await qs({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(sn(a)){an("Cancelled");return}t=a;let d=l.find(u=>u.udid===t);n=n||d.name}else{xe.info(ie.dim("No connected devices found. Enter UDID manually."));let a=await Xs({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(d){if(d.length<10)return"UDID seems too short"}});if(sn(a)){an("Cancelled");return}t=a}}if(!n){let s=await Xs({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(sn(s)){an("Cancelled");return}n=s}let o=ln();o.start("Registering device...");try{await k.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(ie.green("Device registered!")),xe.info(` ${ie.bold("Name:")} ${n}`),xe.info(` ${ie.bold("UDID:")} ${ie.dim(t)}`),r&&xe.info(` ${ie.bold("Team:")} ${ie.dim(r)}`)}catch(s){o.stop(ie.red("Failed to register device")),xe.error(s.response?.data?.message||s.message)}cn(ie.blue("---"))}async function xp(e={}){let t=Zs(e.teamId),n=ln();n.start("Fetching registered devices...");try{let r=(await k.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){xe.info(ie.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),cn(ie.blue("---"));return}let o=r.map(s=>{let l=new Date(s.createdAt).toLocaleDateString();return` ${ie.bold(s.name.padEnd(24))} ${ie.dim(s.udid.padEnd(28))} ${ie.dim((s.teamId||"-").padEnd(12))} ${ie.cyan((s.addedVia||"-").padEnd(10))} ${ie.dim(l)}`});Np(` ${ie.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
1497
1539
  `+o.join(`
1498
- `),"Registered Devices")}catch(i){n.stop(ie.red("Failed to fetch devices")),Le.error(i.response?.data?.message||i.message)}dn(ie.blue("---"))}async function Tp(e){let t=e.udid,n=qs(e).teamId;if(!t){let o=ln();o.start("Fetching registered devices...");try{let l=(await k.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Le.info(ie.dim("No devices to remove.")),dn(ie.blue("---"));return}let a=await Js({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(sn(a)){an("Cancelled");return}let c=l.find(u=>(u.deviceKey||u.udid)===a);t=c?.udid||a,n=c?.teamId||n}catch(s){o.stop(ie.red("Failed to fetch devices")),Le.error(s.response?.data?.message||s.message);return}}let i=await vp({message:`Remove device ${ie.dim(t.substring(0,12)+"...")}?`});if(sn(i)||!i){an("Cancelled");return}let r=ln();r.start("Removing device...");try{await k.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(ie.green("Device removed"))}catch(o){r.stop(ie.red("Failed to remove device")),Le.error(o.response?.data?.message||o.message)}dn(ie.blue("---"))}async function Hn(e,t){switch(e){case"register":await Cp(t);break;case"list":await Np(t);break;case"remove":await Tp(t);break;default:Le.error(`Unknown action: ${e}`)}}import{log as Ue,spinner as $a}from"@clack/prompts";import Ye from"chalk";import qn from"path";import pn from"fs";import mf from"os";import gf from"axios";var Me=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Me||{}),We=(a=>(a.PERMISSIONS="permissions",a.SECRETS="secrets",a.DEPENDENCIES="dependencies",a.STORAGE="storage",a.NETWORK="network",a.DEBUG="debug",a.MANIFEST="manifest",a.ATS="ats",a))(We||{});import{spinner as ha,log as un}from"@clack/prompts";import Te from"chalk";import{execSync as rf}from"child_process";import Sa from"fs";import ya from"path";import ht from"fs";import cn from"path";import{execSync as kp}from"child_process";var Zs={"android.permission.READ_PHONE_STATE":{severity:"high",description:"Can read phone number, IMEI, carrier info"},"android.permission.CALL_PHONE":{severity:"high",description:"Can make calls without user interaction"},"android.permission.SEND_SMS":{severity:"high",description:"Can send SMS without user interaction"},"android.permission.READ_SMS":{severity:"high",description:"Can read user SMS messages"},"android.permission.READ_CONTACTS":{severity:"medium",description:"Can read user contacts"},"android.permission.WRITE_CONTACTS":{severity:"medium",description:"Can modify user contacts"},"android.permission.READ_CALL_LOG":{severity:"high",description:"Can read call history"},"android.permission.CAMERA":{severity:"medium",description:"Camera access"},"android.permission.RECORD_AUDIO":{severity:"medium",description:"Microphone access"},"android.permission.ACCESS_FINE_LOCATION":{severity:"medium",description:"Precise GPS location"},"android.permission.ACCESS_COARSE_LOCATION":{severity:"medium",description:"Approximate location"},"android.permission.ACCESS_BACKGROUND_LOCATION":{severity:"high",description:"Background location tracking"},"android.permission.READ_EXTERNAL_STORAGE":{severity:"medium",description:"Read files on device"},"android.permission.WRITE_EXTERNAL_STORAGE":{severity:"medium",description:"Write files on device"},"android.permission.READ_MEDIA_IMAGES":{severity:"low",description:"Read photos"},"android.permission.READ_MEDIA_VIDEO":{severity:"low",description:"Read videos"},"android.permission.SYSTEM_ALERT_WINDOW":{severity:"high",description:"Draw overlays on other apps"},"android.permission.REQUEST_INSTALL_PACKAGES":{severity:"high",description:"Can install APKs"}},xp={NSCameraUsageDescription:{severity:"medium",description:"Camera access declared"},NSMicrophoneUsageDescription:{severity:"medium",description:"Microphone access declared"},NSLocationWhenInUseUsageDescription:{severity:"medium",description:"Location (in-use) declared"},NSLocationAlwaysUsageDescription:{severity:"high",description:"Background location declared"},NSContactsUsageDescription:{severity:"medium",description:"Contacts access declared"},NSCalendarsUsageDescription:{severity:"low",description:"Calendar access declared"},NSPhotoLibraryUsageDescription:{severity:"low",description:"Photo library access declared"}};function Lp(e){try{let n=kp("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=cn.join(e,"app.json");if(ht.existsSync(t))try{let n=JSON.parse(ht.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function Mp(e){let t=[],n=cn.join(e,"node_modules");if(!ht.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=cn.join(o,"android","src","main","AndroidManifest.xml");if(!ht.existsSync(l))return;let a=ht.readFileSync(l,"utf-8"),c;for(;(c=i.exec(a))!==null;)t.push({pkg:s,permission:c[1]});i.lastIndex=0}for(let o of ht.readdirSync(n)){if(o.startsWith("."))continue;let s=cn.join(n,o);if(o.startsWith("@")){if(!ht.statSync(s).isDirectory())continue;for(let l of ht.readdirSync(s))r(cn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Qs(e,t){let n=[],i=1,r=Lp(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let c of o){let u=Zs[c];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Mp(e);for(let{pkg:c,permission:u}of l){let d=Zs[u];d&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${c}`,description:`${d.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:d.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[c,u]of Object.entries(xp))c in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import tr from"fs";import jn from"path";var Up=[{id:"SEC-001",pattern:/(['"`])(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{20,}\1/g,severity:"critical",label:"Stripe API Key"},{id:"SEC-002",pattern:/(['"`])AIza[0-9A-Za-z\-_]{35}\1/g,severity:"high",label:"Google API Key"},{id:"SEC-003",pattern:/(['"`])AKIA[0-9A-Z]{16}\1/g,severity:"critical",label:"AWS Access Key ID"},{id:"SEC-004",pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,severity:"critical",label:"Private key in source"},{id:"SEC-005",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"high",label:"GitHub Token"},{id:"SEC-006",pattern:/xox[bpors]-[a-zA-Z0-9-]{10,}/g,severity:"high",label:"Slack Token"},{id:"SEC-007",pattern:/(?:password|secret|apikey|api_key)\s*[:=]\s*['"`][^'"`\n]{8,}['"`]/gi,severity:"high",label:"Hardcoded credential"}],Fp=new Set([".ts",".tsx",".js",".jsx"]),Bp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ea(e){let t=[],n=tr.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Bp.has(i.name))continue;let r=jn.join(e,i.name);i.isDirectory()?t.push(...ea(r)):Fp.has(jn.extname(i.name))&&t.push(r)}return t}function Hp(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function jp(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function ta(e,t){let n=[],i=jn.join(e,"src"),r=tr.existsSync(i)?i:e,o=ea(r);for(let s of o){let a=tr.readFileSync(s,"utf-8").split(`
1499
- `),c=jn.relative(e,s);for(let u=0;u<a.length;u++){let d=a[u];if(!Hp(d)&&!jp(d))for(let{id:f,pattern:p,severity:g,label:y}of Up)p.lastIndex=0,p.test(d)&&n.push({id:f,title:y,description:`Potential ${y.toLowerCase()} found in source code`,severity:g,category:"secrets",file:c,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as Gp}from"child_process";var Kp={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function na(e,t){let n=[],i=1,r;try{r=Gp("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let c=Kp[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(d=>typeof d=="string"?d:d.title||d.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity:c,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Gn from"fs";import Kn from"path";var Vp=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,ia=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,zp=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Wp=new Set([".ts",".tsx",".js",".jsx"]),Yp=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function ra(e){let t=[];if(!Gn.existsSync(e))return t;let n=Gn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Yp.has(i.name))continue;let r=Kn.join(e,i.name);i.isDirectory()?t.push(...ra(r)):Wp.has(Kn.extname(i.name))&&t.push(r)}return t}async function oa(e,t){let n=[],i=1,r=Kn.join(e,"src"),o=Gn.existsSync(r)?r:e,s=ra(o);for(let l of s){let a=Gn.readFileSync(l,"utf-8");if(!zp.test(a))continue;let c=a.split(`
1500
- `),u=Kn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d];ia.lastIndex=0;let p;for(;(p=ia.exec(f))!==null;){let g=p[1];Vp.test(g)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${g}"`,description:`Sensitive data key "${g}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:d+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Vn from"fs";import zn from"path";var sa=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Jp=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Xp=new Set([".ts",".tsx",".js",".jsx"]),qp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function aa(e){let t=[];if(!Vn.existsSync(e))return t;let n=Vn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(qp.has(i.name))continue;let r=zn.join(e,i.name);i.isDirectory()?t.push(...aa(r)):Xp.has(zn.extname(i.name))&&t.push(r)}return t}async function la(e,t){let n=[],i=1,r=zn.join(e,"src"),o=Vn.existsSync(r)?r:e,s=aa(o);for(let l of s){let c=Vn.readFileSync(l,"utf-8").split(`
1501
- `),u=zn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(p.startsWith("//")||p.startsWith("*"))continue;sa.lastIndex=0;let g;for(;(g=sa.exec(f))!==null;){let y=g[1],_=Jp.test(y);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${_?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${y}`,severity:_?"high":"medium",category:"network",file:u,line:d+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Wn from"fs";import Yn from"path";var da=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,ca=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Zp=new Set([".ts",".tsx",".js",".jsx"]),Qp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ua(e){let t=[];if(!Wn.existsSync(e))return t;let n=Wn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Qp.has(i.name))continue;let r=Yn.join(e,i.name);i.isDirectory()?t.push(...ua(r)):Zp.has(Yn.extname(i.name))&&t.push(r)}return t}async function pa(e,t){let n=[],i=1,r=Yn.join(e,"src"),o=Wn.existsSync(r)?r:e,s=ua(o);for(let l of s){let c=Wn.readFileSync(l,"utf-8").split(`
1502
- `),u=Yn.relative(e,l);for(let d=0;d<c.length;d++){let f=c[d],p=f.trim();if(!(p.startsWith("//")||p.startsWith("*"))&&(da.lastIndex=0,da.test(f)&&n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),ca.lastIndex=0,ca.test(f))){let g=c.slice(Math.max(0,d-3),d).join(`
1503
- `);/__DEV__/.test(g)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import fa from"fs";import nr from"path";var ef=new Set(["androidx.work.impl.background.systemjob.SystemJobService","androidx.work.impl.diagnostics.DiagnosticsReceiver","com.google.firebase.iid.FirebaseInstanceIdReceiver","com.google.android.gms.auth.api.signin.RevocationBoundService","androidx.profileinstaller.ProfileInstallReceiver","com.google.firebase.messaging.FirebaseMessagingService","com.google.android.gms.measurement.AppMeasurementService","com.google.android.gms.measurement.AppMeasurementJobService"]);function tf(e){let t=[nr.join(e,"android","app","src","main","AndroidManifest.xml"),nr.join(e,"android","AndroidManifest.xml")];for(let n of t)if(fa.existsSync(n))return n;return null}async function ma(e,t){let n=[],i=1,r=tf(e);if(!r)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let o=fa.readFileSync(r,"utf-8"),s=nr.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let c=a[1],u=a[2],f=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(ef.has(f))continue;let p=/android:exported="true"/.test(u),g=/android:permission="/.test(u);p&&!g&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${c}: ${f.split(".").pop()}`,description:`${f} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import Jn from"fs";import ir from"path";function nf(e){let t=ir.join(e,"ios");if(!Jn.existsSync(t))return null;let n=Jn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=ir.join(t,i.name,"Info.plist");if(Jn.existsSync(r))return r}return null}async function ga(e,t){let n=[],i=1,r=nf(e);if(!r)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let o=Jn.readFileSync(r,"utf-8"),s=ir.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let c=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let u=c[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let d of u){let f=d.replace(/<\/?key>/g,"");f!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${f}`,description:`ATS exception configured for ${f}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${f} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var of=[{category:"permissions",label:"Permission Audit",fn:Qs,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:ta,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:na,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:oa,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:la,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:pa,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:ma,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:ga,requiresPrebuild:!0}];async function ba(e,t){let n=of;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(un.error(Te.red(`Unknown category: ${t.category}`)),un.info(Te.dim(`Available: ${Object.values(We).join(", ")}`)),process.exit(1)));let i=n.filter(s=>!s.requiresPrebuild),r=n.filter(s=>s.requiresPrebuild),o=[];for(let s of i){let l=ha();l.start(Te.dim(`Running ${s.label}...`));try{let a=Date.now(),c=await s.fn(e,t);c.durationMs=Date.now()-a,o.push(c);let u=c.findings.length;l.stop(u>0?Te.yellow(`${s.label} \u2014 ${u} finding(s)`):Te.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Te.red(`${s.label} \u2014 error`)),o.push({category:s.category,label:s.label,findings:[],durationMs:0,error:a.message})}}if(r.length>0){let s=ya.join(e,"android"),l=ya.join(e,"ios"),a=Sa.existsSync(s)||Sa.existsSync(l);if(!a&&t.prebuild){t.json||un.info(Te.dim(`
1504
- Running expo prebuild for deeper analysis...`));try{rf("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return un.warn(Te.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||un.info(Te.dim(`
1505
- Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=ha();u.start(Te.dim(`Running ${c.label}...`));try{let d=Date.now(),f=await c.fn(e,t);f.durationMs=Date.now()-d,o.push(f);let p=f.findings.length;u.stop(p>0?Te.yellow(`${c.label} \u2014 ${p} finding(s)`):Te.green(`${c.label} \u2014 clean`))}catch(d){u.stop(Te.red(`${c.label} \u2014 error`)),o.push({category:c.category,label:c.label,findings:[],durationMs:0,error:d.message})}}}return o}import be from"chalk";import{log as he}from"@clack/prompts";var Ut={critical:be.bgRed.white.bold,high:be.red.bold,medium:be.yellow.bold,low:be.blue,info:be.dim},Xn={critical:0,high:1,medium:2,low:3,info:4};function sf(e,t){if(!t)return!0;let n=Xn[t];return n===void 0?!0:Xn[e]<=n}function Ea(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(c=>sf(c.severity,t));if(l.length===0&&!s.error)continue;if(he.info(""),he.info(be.bold(` ${s.label}`)+be.dim(` ${l.length} finding(s)`)),he.info(be.dim(" "+"\u2500".repeat(60))),s.error){he.error(be.red(` Error: ${s.error}`));continue}let a=[...l].sort((c,u)=>Xn[c.severity]-Xn[u.severity]);for(let c of a){let u=Ut[c.severity](` ${c.severity.toUpperCase()} `);he.info(` ${u} ${be.bold(c.id)} ${c.title}`),he.info(be.dim(` ${c.description}`)),c.file&&he.info(be.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),he.info(be.cyan(` Fix: ${c.recommendation}`)),he.info(""),i[c.severity]++,n++}}he.info(""),he.info(be.bold(" Summary")),he.info(be.dim(" "+"\u2500".repeat(60))),he.info(` Total: ${be.bold(String(n))} finding(s)`),he.info(` ${Ut.critical(` ${i.critical} Critical `)} ${Ut.high(` ${i.high} High `)} ${Ut.medium(` ${i.medium} Medium `)} ${Ut.low(` ${i.low} Low `)} ${Ut.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(he.info(""),he.error(be.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(he.info(""),he.warn(be.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(he.info(""),he.success(be.green.bold(" PASS \u2014 no issues found")))}function Aa(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(Me))i[r]=n.filter(o=>o.severity===r).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:t.name||"unknown",projectVersion:t.version||"0.0.0",summary:{total:n.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:n}}import{log as Se,spinner as af}from"@clack/prompts";import fe from"chalk";import at from"fs";import lf from"os";import Ft from"path";import{execSync as df}from"child_process";var Ia=16384,cf=1,uf=Buffer.from([127,69,76,70]);async function wa(e){Se.info(fe.bold.underline("16KB Page Alignment Check")),console.log("");let t=Ft.resolve(e);if(!at.existsSync(t))return Se.error(fe.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return Se.error(fe.red("The provided file is not an APK file.")),!1;let n=af();n.start("Extracting and analyzing native libraries...");let i=at.mkdtempSync(Ft.join(lf.tmpdir(),"mach-16kb-"));try{try{df(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=_a(Ft.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),Se.info(fe.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),Se.info(fe.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let c=Ft.relative(i,a),u=ff(c),d=Ft.basename(a),f=pf(a);f!==null&&o.push({name:d,filePath:c,arch:u,align:f,compatible:f>=Ia})}if(n.stop("Analysis complete."),o.length===0)return Se.info(fe.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(Se.info(fe.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
1540
+ `),"Registered Devices")}catch(i){n.stop(ie.red("Failed to fetch devices")),xe.error(i.response?.data?.message||i.message)}cn(ie.blue("---"))}async function Mp(e){let t=e.udid,n=Qs(e).teamId;if(!t){let o=ln();o.start("Fetching registered devices...");try{let l=(await k.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){xe.info(ie.dim("No devices to remove.")),cn(ie.blue("---"));return}let a=await qs({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(sn(a)){an("Cancelled");return}let d=l.find(u=>(u.deviceKey||u.udid)===a);t=d?.udid||a,n=d?.teamId||n}catch(s){o.stop(ie.red("Failed to fetch devices")),xe.error(s.response?.data?.message||s.message);return}}let i=await Cp({message:`Remove device ${ie.dim(t.substring(0,12)+"...")}?`});if(sn(i)||!i){an("Cancelled");return}let r=ln();r.start("Removing device...");try{await k.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(ie.green("Device removed"))}catch(o){r.stop(ie.red("Failed to remove device")),xe.error(o.response?.data?.message||o.message)}cn(ie.blue("---"))}async function Hn(e,t){switch(e){case"register":await Lp(t);break;case"list":await xp(t);break;case"remove":await Mp(t);break;default:xe.error(`Unknown action: ${e}`)}}import{log as Ue,spinner as Pa}from"@clack/prompts";import Ye from"chalk";import qn from"path";import pn from"fs";import yf from"os";import bf from"axios";var Me=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Me||{}),We=(a=>(a.PERMISSIONS="permissions",a.SECRETS="secrets",a.DEPENDENCIES="dependencies",a.STORAGE="storage",a.NETWORK="network",a.DEBUG="debug",a.MANIFEST="manifest",a.ATS="ats",a))(We||{});import{spinner as ya,log as un}from"@clack/prompts";import Te from"chalk";import{execSync as lf}from"child_process";import ba from"fs";import Ea from"path";import ht from"fs";import dn from"path";import{execSync as Up}from"child_process";var ea={"android.permission.READ_PHONE_STATE":{severity:"high",description:"Can read phone number, IMEI, carrier info"},"android.permission.CALL_PHONE":{severity:"high",description:"Can make calls without user interaction"},"android.permission.SEND_SMS":{severity:"high",description:"Can send SMS without user interaction"},"android.permission.READ_SMS":{severity:"high",description:"Can read user SMS messages"},"android.permission.READ_CONTACTS":{severity:"medium",description:"Can read user contacts"},"android.permission.WRITE_CONTACTS":{severity:"medium",description:"Can modify user contacts"},"android.permission.READ_CALL_LOG":{severity:"high",description:"Can read call history"},"android.permission.CAMERA":{severity:"medium",description:"Camera access"},"android.permission.RECORD_AUDIO":{severity:"medium",description:"Microphone access"},"android.permission.ACCESS_FINE_LOCATION":{severity:"medium",description:"Precise GPS location"},"android.permission.ACCESS_COARSE_LOCATION":{severity:"medium",description:"Approximate location"},"android.permission.ACCESS_BACKGROUND_LOCATION":{severity:"high",description:"Background location tracking"},"android.permission.READ_EXTERNAL_STORAGE":{severity:"medium",description:"Read files on device"},"android.permission.WRITE_EXTERNAL_STORAGE":{severity:"medium",description:"Write files on device"},"android.permission.READ_MEDIA_IMAGES":{severity:"low",description:"Read photos"},"android.permission.READ_MEDIA_VIDEO":{severity:"low",description:"Read videos"},"android.permission.SYSTEM_ALERT_WINDOW":{severity:"high",description:"Draw overlays on other apps"},"android.permission.REQUEST_INSTALL_PACKAGES":{severity:"high",description:"Can install APKs"}},Fp={NSCameraUsageDescription:{severity:"medium",description:"Camera access declared"},NSMicrophoneUsageDescription:{severity:"medium",description:"Microphone access declared"},NSLocationWhenInUseUsageDescription:{severity:"medium",description:"Location (in-use) declared"},NSLocationAlwaysUsageDescription:{severity:"high",description:"Background location declared"},NSContactsUsageDescription:{severity:"medium",description:"Contacts access declared"},NSCalendarsUsageDescription:{severity:"low",description:"Calendar access declared"},NSPhotoLibraryUsageDescription:{severity:"low",description:"Photo library access declared"}};function Bp(e){try{let n=Up("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=dn.join(e,"app.json");if(ht.existsSync(t))try{let n=JSON.parse(ht.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function Hp(e){let t=[],n=dn.join(e,"node_modules");if(!ht.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=dn.join(o,"android","src","main","AndroidManifest.xml");if(!ht.existsSync(l))return;let a=ht.readFileSync(l,"utf-8"),d;for(;(d=i.exec(a))!==null;)t.push({pkg:s,permission:d[1]});i.lastIndex=0}for(let o of ht.readdirSync(n)){if(o.startsWith("."))continue;let s=dn.join(n,o);if(o.startsWith("@")){if(!ht.statSync(s).isDirectory())continue;for(let l of ht.readdirSync(s))r(dn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function ta(e,t){let n=[],i=1,r=Bp(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let d of o){let u=ea[d];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Hp(e);for(let{pkg:d,permission:u}of l){let c=ea[u];c&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${d}`,description:`${c.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:c.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[d,u]of Object.entries(Fp))d in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${d} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import ir from"fs";import jn from"path";var jp=[{id:"SEC-001",pattern:/(['"`])(?:sk|pk)_(?:live|test)_[a-zA-Z0-9]{20,}\1/g,severity:"critical",label:"Stripe API Key"},{id:"SEC-002",pattern:/(['"`])AIza[0-9A-Za-z\-_]{35}\1/g,severity:"high",label:"Google API Key"},{id:"SEC-003",pattern:/(['"`])AKIA[0-9A-Z]{16}\1/g,severity:"critical",label:"AWS Access Key ID"},{id:"SEC-004",pattern:/-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/g,severity:"critical",label:"Private key in source"},{id:"SEC-005",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"high",label:"GitHub Token"},{id:"SEC-006",pattern:/xox[bpors]-[a-zA-Z0-9-]{10,}/g,severity:"high",label:"Slack Token"},{id:"SEC-007",pattern:/(?:password|secret|apikey|api_key)\s*[:=]\s*['"`][^'"`\n]{8,}['"`]/gi,severity:"high",label:"Hardcoded credential"}],Gp=new Set([".ts",".tsx",".js",".jsx"]),Kp=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function na(e){let t=[],n=ir.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Kp.has(i.name))continue;let r=jn.join(e,i.name);i.isDirectory()?t.push(...na(r)):Gp.has(jn.extname(i.name))&&t.push(r)}return t}function Vp(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function zp(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function ia(e,t){let n=[],i=jn.join(e,"src"),r=ir.existsSync(i)?i:e,o=na(r);for(let s of o){let a=ir.readFileSync(s,"utf-8").split(`
1541
+ `),d=jn.relative(e,s);for(let u=0;u<a.length;u++){let c=a[u];if(!Vp(c)&&!zp(c))for(let{id:f,pattern:p,severity:g,label:y}of jp)p.lastIndex=0,p.test(c)&&n.push({id:f,title:y,description:`Potential ${y.toLowerCase()} found in source code`,severity:g,category:"secrets",file:d,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as Wp}from"child_process";var Yp={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function ra(e,t){let n=[],i=1,r;try{r=Wp("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let d=Yp[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(c=>typeof c=="string"?c:c.title||c.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity:d,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Gn from"fs";import Kn from"path";var Jp=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,oa=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Xp=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,qp=new Set([".ts",".tsx",".js",".jsx"]),Zp=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function sa(e){let t=[];if(!Gn.existsSync(e))return t;let n=Gn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Zp.has(i.name))continue;let r=Kn.join(e,i.name);i.isDirectory()?t.push(...sa(r)):qp.has(Kn.extname(i.name))&&t.push(r)}return t}async function aa(e,t){let n=[],i=1,r=Kn.join(e,"src"),o=Gn.existsSync(r)?r:e,s=sa(o);for(let l of s){let a=Gn.readFileSync(l,"utf-8");if(!Xp.test(a))continue;let d=a.split(`
1542
+ `),u=Kn.relative(e,l);for(let c=0;c<d.length;c++){let f=d[c];oa.lastIndex=0;let p;for(;(p=oa.exec(f))!==null;){let g=p[1];Jp.test(g)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${g}"`,description:`Sensitive data key "${g}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:c+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Vn from"fs";import zn from"path";var la=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Qp=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,ef=new Set([".ts",".tsx",".js",".jsx"]),tf=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ca(e){let t=[];if(!Vn.existsSync(e))return t;let n=Vn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(tf.has(i.name))continue;let r=zn.join(e,i.name);i.isDirectory()?t.push(...ca(r)):ef.has(zn.extname(i.name))&&t.push(r)}return t}async function da(e,t){let n=[],i=1,r=zn.join(e,"src"),o=Vn.existsSync(r)?r:e,s=ca(o);for(let l of s){let d=Vn.readFileSync(l,"utf-8").split(`
1543
+ `),u=zn.relative(e,l);for(let c=0;c<d.length;c++){let f=d[c],p=f.trim();if(p.startsWith("//")||p.startsWith("*"))continue;la.lastIndex=0;let g;for(;(g=la.exec(f))!==null;){let y=g[1],_=Qp.test(y);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${_?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${y}`,severity:_?"high":"medium",category:"network",file:u,line:c+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import Wn from"fs";import Yn from"path";var ua=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,pa=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,nf=new Set([".ts",".tsx",".js",".jsx"]),rf=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function fa(e){let t=[];if(!Wn.existsSync(e))return t;let n=Wn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(rf.has(i.name))continue;let r=Yn.join(e,i.name);i.isDirectory()?t.push(...fa(r)):nf.has(Yn.extname(i.name))&&t.push(r)}return t}async function ma(e,t){let n=[],i=1,r=Yn.join(e,"src"),o=Wn.existsSync(r)?r:e,s=fa(o);for(let l of s){let d=Wn.readFileSync(l,"utf-8").split(`
1544
+ `),u=Yn.relative(e,l);for(let c=0;c<d.length;c++){let f=d[c],p=f.trim();if(!(p.startsWith("//")||p.startsWith("*"))&&(ua.lastIndex=0,ua.test(f)&&n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:u,line:c+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),pa.lastIndex=0,pa.test(f))){let g=d.slice(Math.max(0,c-3),c).join(`
1545
+ `);/__DEV__/.test(g)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:c+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import ga from"fs";import rr from"path";var of=new Set(["androidx.work.impl.background.systemjob.SystemJobService","androidx.work.impl.diagnostics.DiagnosticsReceiver","com.google.firebase.iid.FirebaseInstanceIdReceiver","com.google.android.gms.auth.api.signin.RevocationBoundService","androidx.profileinstaller.ProfileInstallReceiver","com.google.firebase.messaging.FirebaseMessagingService","com.google.android.gms.measurement.AppMeasurementService","com.google.android.gms.measurement.AppMeasurementJobService"]);function sf(e){let t=[rr.join(e,"android","app","src","main","AndroidManifest.xml"),rr.join(e,"android","AndroidManifest.xml")];for(let n of t)if(ga.existsSync(n))return n;return null}async function ha(e,t){let n=[],i=1,r=sf(e);if(!r)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let o=ga.readFileSync(r,"utf-8"),s=rr.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let d=a[1],u=a[2],f=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(of.has(f))continue;let p=/android:exported="true"/.test(u),g=/android:permission="/.test(u);p&&!g&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${d}: ${f.split(".").pop()}`,description:`${f} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import Jn from"fs";import or from"path";function af(e){let t=or.join(e,"ios");if(!Jn.existsSync(t))return null;let n=Jn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=or.join(t,i.name,"Info.plist");if(Jn.existsSync(r))return r}return null}async function Sa(e,t){let n=[],i=1,r=af(e);if(!r)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let o=Jn.readFileSync(r,"utf-8"),s=or.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let d=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(d){let u=d[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let c of u){let f=c.replace(/<\/?key>/g,"");f!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${f}`,description:`ATS exception configured for ${f}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${f} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var cf=[{category:"permissions",label:"Permission Audit",fn:ta,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:ia,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:ra,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:aa,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:da,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:ma,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:ha,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:Sa,requiresPrebuild:!0}];async function Aa(e,t){let n=cf;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(un.error(Te.red(`Unknown category: ${t.category}`)),un.info(Te.dim(`Available: ${Object.values(We).join(", ")}`)),process.exit(1)));let i=n.filter(s=>!s.requiresPrebuild),r=n.filter(s=>s.requiresPrebuild),o=[];for(let s of i){let l=ya();l.start(Te.dim(`Running ${s.label}...`));try{let a=Date.now(),d=await s.fn(e,t);d.durationMs=Date.now()-a,o.push(d);let u=d.findings.length;l.stop(u>0?Te.yellow(`${s.label} \u2014 ${u} finding(s)`):Te.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Te.red(`${s.label} \u2014 error`)),o.push({category:s.category,label:s.label,findings:[],durationMs:0,error:a.message})}}if(r.length>0){let s=Ea.join(e,"android"),l=Ea.join(e,"ios"),a=ba.existsSync(s)||ba.existsSync(l);if(!a&&t.prebuild){t.json||un.info(Te.dim(`
1546
+ Running expo prebuild for deeper analysis...`));try{lf("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return un.warn(Te.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||un.info(Te.dim(`
1547
+ Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let u=ya();u.start(Te.dim(`Running ${d.label}...`));try{let c=Date.now(),f=await d.fn(e,t);f.durationMs=Date.now()-c,o.push(f);let p=f.findings.length;u.stop(p>0?Te.yellow(`${d.label} \u2014 ${p} finding(s)`):Te.green(`${d.label} \u2014 clean`))}catch(c){u.stop(Te.red(`${d.label} \u2014 error`)),o.push({category:d.category,label:d.label,findings:[],durationMs:0,error:c.message})}}}return o}import be from"chalk";import{log as he}from"@clack/prompts";var Ut={critical:be.bgRed.white.bold,high:be.red.bold,medium:be.yellow.bold,low:be.blue,info:be.dim},Xn={critical:0,high:1,medium:2,low:3,info:4};function df(e,t){if(!t)return!0;let n=Xn[t];return n===void 0?!0:Xn[e]<=n}function Ia(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(d=>df(d.severity,t));if(l.length===0&&!s.error)continue;if(he.info(""),he.info(be.bold(` ${s.label}`)+be.dim(` ${l.length} finding(s)`)),he.info(be.dim(" "+"\u2500".repeat(60))),s.error){he.error(be.red(` Error: ${s.error}`));continue}let a=[...l].sort((d,u)=>Xn[d.severity]-Xn[u.severity]);for(let d of a){let u=Ut[d.severity](` ${d.severity.toUpperCase()} `);he.info(` ${u} ${be.bold(d.id)} ${d.title}`),he.info(be.dim(` ${d.description}`)),d.file&&he.info(be.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),he.info(be.cyan(` Fix: ${d.recommendation}`)),he.info(""),i[d.severity]++,n++}}he.info(""),he.info(be.bold(" Summary")),he.info(be.dim(" "+"\u2500".repeat(60))),he.info(` Total: ${be.bold(String(n))} finding(s)`),he.info(` ${Ut.critical(` ${i.critical} Critical `)} ${Ut.high(` ${i.high} High `)} ${Ut.medium(` ${i.medium} Medium `)} ${Ut.low(` ${i.low} Low `)} ${Ut.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(he.info(""),he.error(be.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(he.info(""),he.warn(be.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(he.info(""),he.success(be.green.bold(" PASS \u2014 no issues found")))}function wa(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(Me))i[r]=n.filter(o=>o.severity===r).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:t.name||"unknown",projectVersion:t.version||"0.0.0",summary:{total:n.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:n}}import{log as Se,spinner as uf}from"@clack/prompts";import fe from"chalk";import at from"fs";import pf from"os";import Ft from"path";import{execSync as ff}from"child_process";var _a=16384,mf=1,gf=Buffer.from([127,69,76,70]);async function Ra(e){Se.info(fe.bold.underline("16KB Page Alignment Check")),console.log("");let t=Ft.resolve(e);if(!at.existsSync(t))return Se.error(fe.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return Se.error(fe.red("The provided file is not an APK file.")),!1;let n=uf();n.start("Extracting and analyzing native libraries...");let i=at.mkdtempSync(Ft.join(pf.tmpdir(),"mach-16kb-"));try{try{ff(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=$a(Ft.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),Se.info(fe.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),Se.info(fe.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let d=Ft.relative(i,a),u=Sf(d),c=Ft.basename(a),f=hf(a);f!==null&&o.push({name:c,filePath:d,arch:u,align:f,compatible:f>=_a})}if(n.stop("Analysis complete."),o.length===0)return Se.info(fe.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(Se.info(fe.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
1506
1548
  `)),s.length>0){Se.info(fe.red.bold(`Incompatible libraries:
1507
- `));for(let a of s)Se.error(fe.red(`${fe.bold(a.name)} ${fe.dim(`(${a.arch})`)}`)),Se.info(fe.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Ia})`))}return l.length>0&&(console.log(""),Se.success(fe.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(Se.success(fe.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(Se.error(fe.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),Se.info(fe.yellow("To fix this:")),Se.info(fe.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),Se.info(fe.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),Se.info(fe.dim(" 3. Update third-party libraries that ship prebuilt .so files")),Se.info(fe.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),Se.info(fe.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),Se.error(fe.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{at.rmSync(i,{recursive:!0,force:!0})}catch{}}}function pf(e){let t=at.openSync(e,"r");try{let n=Buffer.alloc(64);if(at.readSync(t,n,0,64,0),!n.subarray(0,4).equals(uf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let f=0;f<u;f++){let p=Buffer.alloc(c);if(at.readSync(t,p,0,c,a+f*c),s(p,0)!==cf)continue;let y;i?y=l(p,48):y=s(p,28),y>0&&(d===null||y<d)&&(d=y)}return d??0}catch{return null}finally{at.closeSync(t)}}function _a(e){let t=[];if(!at.existsSync(e))return t;let n=at.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Ft.join(e,i.name);i.isDirectory()?t.push(..._a(r)):i.name.endsWith(".so")&&t.push(r)}return t}function ff(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var va=async e=>{if(Pe()||(Ue.error(Ye.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await hf(e);return}let n=process.cwd(),i=qn.join(n,"package.json");pn.existsSync(i)||(Ue.error(Ye.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(pn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ue.info(Ye.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ue.info(Ye.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ue.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await ba(n,s);e.json?console.log(JSON.stringify(Aa(l,r),null,2)):Ea(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},Ra=["16kb"];async function hf(e){let t=e.category?.toLowerCase();t&&!Ra.includes(t)&&(Ue.error(Ye.red(`Unknown APK check category: "${t}"`)),Ue.info(Ye.dim(`Available APK checks: ${Ra.join(", ")}`)),process.exit(1));let n=await Sf(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await wa(n)||(r=!0)),r&&process.exit(1)}async function Sf(e){if(e.startsWith("build:")){let n=e.slice(6);return await yf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Pa(e);let t=qn.resolve(e);return pn.existsSync(t)?t:(Ue.error(Ye.red(`APK file not found: ${t}`)),null)}async function yf(e){let t=$a();t.start(`Fetching APK from build ${e}...`);try{let n=await k.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),Ue.error(Ye.red("This build does not have an APK artifact.")),Ue.info(Ye.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Pa(r.url))}catch(n){return t.stop("Failed to fetch build"),Ue.error(Ye.red(n.message)),null}}async function Pa(e){let t=$a();t.start("Downloading APK...");try{let n=pn.mkdtempSync(qn.join(mf.tmpdir(),`${m.nameLower}-audit-`)),i=qn.join(n,"app.apk"),r=await gf.get(e,{responseType:"arraybuffer"});pn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),Ue.error(Ye.red(`Failed to download APK: ${n.message}`)),null}}var Af=console.log;console.log=()=>{};Ef();console.log=Af;we(Ee.bgCyan.black(m.cliTag("Production Build Orchestrator")));var wf=If(import.meta.url),_f=wf("../package.json"),Da=(e,t=[])=>t.concat(e),re=new bf;re.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(_f.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);re.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await Ds(e)});re.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(Ee.bgCyan.black(m.cliTag("Hosting"))),await Er()});re.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Sitemap Generator"))),await _r(e)});re.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Fe("--build-id <id>","Internal build ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Fe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Da,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=re.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(Ee.bgCyan.black(m.cliTag("Cloud Build"))),await On(t)});re.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Da,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new Fe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Fe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Maestro Testing"))),await mo(e)});re.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(Ee.bgCyan.black(m.cliTag("OTA Update"))),await js(e)});re.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new Fe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Fe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=re.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(Ee.bgCyan.black(m.cliTag("Store Submission"))),await wn(e)});re.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Login"))),await ks()});re.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Logout"))),await xs()});re.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Link Project"))),await Ms()});re.command("me").description("Display currently logged in user details").action(async()=>{await Ks()});re.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Init Project"))),await Us()});re.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(Ee.bgCyan.black(m.cliTag("Env Manager"))),await Bs(e,t,n)});re.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Dev Server"))),await zs(e)});re.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await Ws(e)});re.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:t}=await import("./credentials-3MYGMYJK.js");await t(e)});re.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Credentials Setup"))),await Ht(e),Oa(Ee.green("Done!"))});re.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Service Credentials"))),await yr(e),Oa(Ee.green("Done!"))});var rr=re.command("device").description("Manage registered iOS test devices");rr.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("register",e)});rr.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Hn("list",e)});rr.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("remove",e)});re.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(Ee.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await va(e)});var Rf=new Set(["login","logout","agent"]);re.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Rf.has(n)||pr()});re.on("command:*",()=>{console.error(`Invalid command: %s
1549
+ `));for(let a of s)Se.error(fe.red(`${fe.bold(a.name)} ${fe.dim(`(${a.arch})`)}`)),Se.info(fe.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${_a})`))}return l.length>0&&(console.log(""),Se.success(fe.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(Se.success(fe.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(Se.error(fe.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),Se.info(fe.yellow("To fix this:")),Se.info(fe.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),Se.info(fe.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),Se.info(fe.dim(" 3. Update third-party libraries that ship prebuilt .so files")),Se.info(fe.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),Se.info(fe.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),Se.error(fe.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{at.rmSync(i,{recursive:!0,force:!0})}catch{}}}function hf(e){let t=at.openSync(e,"r");try{let n=Buffer.alloc(64);if(at.readSync(t,n,0,64,0),!n.subarray(0,4).equals(gf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),a,d,u;i?(a=l(n,32),d=o(n,54),u=o(n,56)):(a=s(n,28),d=o(n,42),u=o(n,44));let c=null;for(let f=0;f<u;f++){let p=Buffer.alloc(d);if(at.readSync(t,p,0,d,a+f*d),s(p,0)!==mf)continue;let y;i?y=l(p,48):y=s(p,28),y>0&&(c===null||y<c)&&(c=y)}return c??0}catch{return null}finally{at.closeSync(t)}}function $a(e){let t=[];if(!at.existsSync(e))return t;let n=at.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Ft.join(e,i.name);i.isDirectory()?t.push(...$a(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Sf(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Oa=async e=>{if(Pe()||(Ue.error(Ye.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Ef(e);return}let n=process.cwd(),i=qn.join(n,"package.json");pn.existsSync(i)||(Ue.error(Ye.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(pn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ue.info(Ye.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ue.info(Ye.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ue.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await Aa(n,s);e.json?console.log(JSON.stringify(wa(l,r),null,2)):Ia(l,e.severity);let a=l.some(u=>u.findings.some(c=>c.severity==="critical")),d=l.some(u=>u.findings.some(c=>c.severity==="high"));(a||d)&&process.exit(1)},va=["16kb"];async function Ef(e){let t=e.category?.toLowerCase();t&&!va.includes(t)&&(Ue.error(Ye.red(`Unknown APK check category: "${t}"`)),Ue.info(Ye.dim(`Available APK checks: ${va.join(", ")}`)),process.exit(1));let n=await Af(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await Ra(n)||(r=!0)),r&&process.exit(1)}async function Af(e){if(e.startsWith("build:")){let n=e.slice(6);return await If(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Da(e);let t=qn.resolve(e);return pn.existsSync(t)?t:(Ue.error(Ye.red(`APK file not found: ${t}`)),null)}async function If(e){let t=Pa();t.start(`Fetching APK from build ${e}...`);try{let n=await k.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),Ue.error(Ye.red("This build does not have an APK artifact.")),Ue.info(Ye.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Da(r.url))}catch(n){return t.stop("Failed to fetch build"),Ue.error(Ye.red(n.message)),null}}async function Da(e){let t=Pa();t.start("Downloading APK...");try{let n=pn.mkdtempSync(qn.join(yf.tmpdir(),`${m.nameLower}-audit-`)),i=qn.join(n,"app.apk"),r=await bf.get(e,{responseType:"arraybuffer"});pn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),Ue.error(Ye.red(`Failed to download APK: ${n.message}`)),null}}var Rf=console.log;console.log=()=>{};_f();console.log=Rf;we(Ee.bgCyan.black(m.cliTag("Production Build Orchestrator")));var vf=$f(import.meta.url),Pf=vf("../package.json"),Na=(e,t=[])=>t.concat(e),re=new wf;re.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Pf.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);re.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await Ns(e)});re.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(Ee.bgCyan.black(m.cliTag("Hosting"))),await Ir()});re.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Sitemap Generator"))),await $r(e)});re.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Fe("--build-id <id>","Internal build ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Fe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Na,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=re.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(Ee.bgCyan.black(m.cliTag("Cloud Build"))),await On(t)});re.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",Na,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new Fe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new Fe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Maestro Testing"))),await ho(e)});re.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(Ee.bgCyan.black(m.cliTag("OTA Update"))),await Ks(e)});re.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new Fe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Fe("--project-id <id>","Internal project ID").hideHelp()).addOption(new Fe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new Fe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=re.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(Ee.bgCyan.black(m.cliTag("Store Submission"))),await wn(e)});re.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Login"))),await xs()});re.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Logout"))),await Ms()});re.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Link Project"))),await Fs()});re.command("me").description("Display currently logged in user details").action(async()=>{await zs()});re.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(Ee.bgCyan.black(m.cliTag("Init Project"))),await Bs()});re.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(Ee.bgCyan.black(m.cliTag("Env Manager"))),await js(e,t,n)});re.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Dev Server"))),await Ys(e)});re.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await Js(e)});re.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:t}=await import("./credentials-CT2WW52S.js");await t(e)});re.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(Ee.bgCyan.black(m.cliTag("Credentials Setup"))),await Ht(e),Ca(Ee.green("Done!"))});re.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(Ee.bgCyan.black(m.cliTag("Service Credentials"))),await Er(e),Ca(Ee.green("Done!"))});var sr=re.command("device").description("Manage registered iOS test devices");sr.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("register",e)});sr.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Hn("list",e)});sr.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Hn("remove",e)});re.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(Ee.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await Oa(e)});var Of=new Set(["login","logout","agent"]);re.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Of.has(n)||mr()});re.on("command:*",()=>{console.error(`Invalid command: %s
1508
1550
  See --help for a list of available commands.`,re.args.join(" ")),process.exit(1)});process.argv.slice(2).length||re.help();re.parse(process.argv);