@radhya/mach 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/index.js +142 -135
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Ne,b as Ze,c as
|
|
2
|
+
import{a as Ne,b as Ze,c as Ln,d as xn,e as gt,f as Mn,h as vt}from"./chunk-K7ILUOUP.js";import{a as p,b as Nn,c as we,d as Tn,e as kn,f as ei,g as We,h as v}from"./chunk-HIP5BA3H.js";import{Command as au,Option as Pt}from"commander";import{configDotenv as lu}from"dotenv";import{intro as Ae,outro as ys}from"@clack/prompts";import ye from"chalk";import{text as Un,confirm as Ss,spinner as bs,isCancel as Ui,cancel as Dt,note as Es,outro as As}from"@clack/prompts";import Ot from"chalk";async function Bn(){try{let e=await Un({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});Ui(e)&&(Dt("Operation cancelled."),process.exit(0));let t=await Un({message:"Enter Region:",initialValue:"ap-south-1"});Ui(t)&&(Dt("Operation cancelled."),process.exit(0));let i=await Ss({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Ui(i)&&(Dt("Operation cancelled."),process.exit(0));let n=bs();n.start("Setting up hosting infrastructure...");try{let r=await v.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:i});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");n.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${Ot.cyan(o.bucketName)}
|
|
3
3
|
`;s+=`Region: ${Ot.cyan(o.region)}
|
|
4
4
|
`,s+=`S3 Website URL: ${Ot.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
5
|
|
|
6
6
|
CloudFront ID: ${Ot.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
-
CloudFront URL: ${Ot.blue(o.cloudFrontUrl)}`),
|
|
7
|
+
CloudFront URL: ${Ot.blue(o.cloudFrontUrl)}`),Es(s,"Setup Complete!"),As("You are all set!")}catch(r){n.stop("Setup failed"),Dt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){Dt(`An unexpected error occurred: ${e.message}`)}}import{readdir as Is,writeFile as _s,access as ws,mkdir as $s}from"fs/promises";import{join as Fn}from"path";import{spinner as Ps,text as Hn,isCancel as jn,cancel as Bi,note as Rs,outro as vs}from"@clack/prompts";import Ds from"chalk";async function Os(){let e=["./app","./src/app"];for(let t of e)try{return await ws(t),t}catch{}return null}async function Gn(e){try{let i=await Os()||"./app",n=await Hn({message:"Enter path to your app directory:",placeholder:i,initialValue:i,validate(c){if(c.length===0)return"Path is required"}});jn(n)&&(Bi("Operation cancelled."),process.exit(0));let r=await Hn({message:"Enter your website base URL:",placeholder:"https://example.com",validate(c){if(c.length===0)return"Base URL is required";if(!c.startsWith("http"))return"URL must start with http:// or https://"}});jn(r)&&(Bi("Operation cancelled."),process.exit(0));let o=Ps();o.start("Scanning app directory for routes...");let s=await Kn(n);o.stop(`Found ${s.length} routes`);let l=Cs(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 $s(d,{recursive:!0})}catch{}await _s(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),Rs(`Routes included:
|
|
8
8
|
${s.map(c=>` \u2022 ${c.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
9
|
+
`)}`,"Sitemap Summary"),vs(`Sitemap saved to ${Ds.cyan(a)}`)}catch(t){Bi(`An error occurred: ${t.message}`)}}async function Kn(e,t=""){let i=[];try{let n=await Is(e,{withFileTypes:!0});for(let r of n){let o=Fn(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await Kn(o,Fn(t,r.name));i.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}`;i.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,"/");i.push({path:l,file:o})}}}}}catch(n){throw new Error(`Failed to scan directory ${e}: ${n.message}`)}return i}function Cs(e,t){let i=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
|
|
18
|
+
</urlset>`}import{randomUUID as jl}from"crypto";import _e from"path";import Lt from"axios";import Gl from"os";import{spinner as fn,confirm as Mr,isCancel as Ur,log as D}from"@clack/prompts";import O from"chalk";import ae from"fs";import{execSync as Br}from"child_process";import Fr from"adm-zip";import{spinner as Ms,log as ti}from"@clack/prompts";import zn from"chalk";import Wn from"fs";import Yn from"path";var Vn=`#!/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}}"
|
|
@@ -530,15 +530,15 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
530
530
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
531
531
|
sleep 5
|
|
532
532
|
sudo shutdown -h now
|
|
533
|
-
`;import
|
|
534
|
-
`):"",f;if(r){let
|
|
535
|
-
export MACH_APP_NAME="${
|
|
536
|
-
export MACH_BUILD_PROFILE="${
|
|
537
|
-
export MACH_ANDROID_RELEASE_ABIS="${
|
|
533
|
+
`;import Ns from"crypto";var Ts="mach-env-v2-js-bundle-cache",ks=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"]),Ls=["PRESIGNED_","KEYSTORE_PASSWORD_"],xs=e=>!e||ks.has(e)?!1:!Ls.some(t=>e.startsWith(t)),at=(e,t,i)=>({...e,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:i.appName||i.name||"App"}),ht=e=>{let t=Object.entries(e).filter(([i])=>xs(i)).sort(([i],[n])=>i.localeCompare(n));return Ns.createHash("sha256").update(JSON.stringify({version:Ts,entries:t})).digest("hex")};var Fi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Hi=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),Us=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),Bs=(e,t,i)=>{let n=i.MACH_ANDROID_RELEASE_ABIS||i.MACH_ANDROID_ABIS||i.MACH_PROFILE_ANDROID_RELEASE_ABIS||i.MACH_PROFILE_ANDROID_ABIS||i.MACH_PROFILE_ANDROID_ARCHITECTURES||i.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return n||(!!e.maestro||Us(t)||Hi(i.MACH_PROFILE_ANDROID_EMULATOR)||Hi(i.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||Hi(i.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Jn=async(e,t,i={},n,r)=>{let o=Ms(),s=e.buildProfile||"production",l=s==="production",a=e.apk===!0,d=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",c=e.buildCommand||(a?"assembleRelease":d),u=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(`
|
|
534
|
+
`):"",f;if(r){let L=Yn.isAbsolute(r)?r:Yn.resolve(process.cwd(),r);Wn.existsSync(L)?(f=Wn.readFileSync(L,"utf-8"),ti.info(zn.magenta(`\u2713 Loaded preBuild hook: ${r}`))):ti.warn(`preBuild script not found at ${L} \u2014 skipping`)}let m=Bs(e,s,i),b={...at(i,s,e),MACH_ANDROID_RELEASE_ABIS:m},U=ht(b),k=Vn.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,c).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
535
|
+
export MACH_APP_NAME="${Fi(b.MACH_APP_NAME)}"
|
|
536
|
+
export MACH_BUILD_PROFILE="${Fi(s)}"
|
|
537
|
+
export MACH_ANDROID_RELEASE_ABIS="${Fi(m)}"
|
|
538
538
|
export MACH_ENV_FINGERPRINT="${U}"
|
|
539
539
|
export EXPO_NO_DOTENV=1
|
|
540
540
|
{{ENV_VARS}}
|
|
541
|
-
`);if(e.dryRun){ti.info("User Data Script (dry run):"),console.log(
|
|
541
|
+
`);if(e.dryRun){ti.info("User Data Script (dry run):"),console.log(k);return}o.start("Requesting cloud build instance...");try{let L=await v.post("/builds/launch-android",{projectId:n,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:i,dryRun:e.dryRun,userDataScript:k,preBuildScriptContent:f});if(L.data.status!=="success")throw new Error(L.data.message||"Failed to launch build instance");let T=L.data.instanceId;return o.stop("Build Started"),ti.success(zn.green(`Build initiated on cloud instance (${T}).`)),{instanceId:T}}catch(L){o.stop("Android Build Failed");let T=L.response?.data?.message||L.message;throw new Error(`Failed to launch Android build: ${T}`)}};import{spinner as Fs,log as yt}from"@clack/prompts";import Qe from"chalk";import Hs from"fs";import{execSync as Ct}from"child_process";var qn=`#!/bin/bash
|
|
542
542
|
# --- Mach Cloud Build Script (iOS) ---
|
|
543
543
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
544
544
|
|
|
@@ -1022,114 +1022,160 @@ touch done
|
|
|
1022
1022
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1023
1023
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1024
1024
|
fi
|
|
1025
|
-
`;var
|
|
1026
|
-
`:
|
|
1025
|
+
`;var Xn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Zn=async(e,t,i={},n)=>{let r=Fs();e.sshHost||(e.sshHost="localhost",yt.message(Qe.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${Qe.cyan(e.sshHost)}...`);let o=e.sshUser||process.env.USER||"ubuntu",s=e.sshKey,l=`${o}@${e.sshHost}`,a=`ssh ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no ${l}`,d=`scp ${s?`-i ${s}`:""} -o StrictHostKeyChecking=no`;try{let c=o==="ubuntu"?"/home/ubuntu":`/Users/${o}`,u=(i.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),f=`${c}/${p.remoteWorkspacesDir}/${u}`;r.message(`Preparing stable workspace: ${f}...`),Ct(`${a} "mkdir -p ${f}"`,{stdio:"inherit"}),r.message("Transferring source code...");let m=`/tmp/${p.nameLower}-source-${t}.zip`;Ct(`${d} ${m} ${l}:${f}/source.zip`,{stdio:"inherit"});let b=e.iosApiKeyPath?`${f}/api_key.p8`:"",U="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Ct(`${d} ${e.iosApiKeyPath} ${l}:${b}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(U=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${b}`));let k={};if(n)try{let R=await v.post(`/builds/${n}/${t}/build-urls`,{platform:"ios"});R.data.status==="success"&&(k=R.data.urls)}catch(R){yt.warn(Qe.yellow(`Could not fetch build URLs: ${R.message}`))}let L="";if(k.credentials&&k.credentials.length>0)for(let R of k.credentials)R.type==="p12"?L+=`curl -sf -o "$CERT_DIR/${R.name}" "${R.downloadUrl}" || true
|
|
1026
|
+
`:R.type==="mobileprovision"&&(L+=`curl -sf -o "$PROV_TEMP/${R.name}" "${R.downloadUrl}" || true
|
|
1027
1027
|
`);r.message("Generating macOS build script...");let T=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1028
|
-
`:"";if(i)for(let[
|
|
1029
|
-
`}let G=e.buildProfile||"production",h=at(i,G,e),V=ht(h),_=[T,
|
|
1030
|
-
`),
|
|
1031
|
-
`):"",
|
|
1028
|
+
`:"";if(i)for(let[R,I]of Object.entries(i)){let M=I.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");T+=`export ${R}="${M}"
|
|
1029
|
+
`}let G=e.buildProfile||"production",h=at(i,G,e),V=ht(h),_=[T,k.logUpload?`export PRESIGNED_LOG_UPLOAD="${k.logUpload}"`:"",k.doneMarker?`export PRESIGNED_DONE_MARKER="${k.doneMarker}"`:"",k.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${k.cacheDerivedDataDownload}"`:"",k.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${k.cacheDerivedDataUpload}"`:"",k.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${k.cacheNodeModulesDownload}"`:"",k.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${k.cacheNodeModulesUpload}"`:"",k.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${k.cachePodsDownload}"`:"",k.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${k.cachePodsUpload}"`:"",k.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${k.artifactIpaUpload}"`:"",k.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${k.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Xn(G)}"`,`export MACH_APP_NAME="${Xn(h.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${V}"`,"export EXPO_NO_DOTENV=1",`export ${p.envPrefix}PROJECT_ID="${u}"`,i.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${i.MATCH_ENCRYPTION_PASSPHRASE}"`:"",i.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${i.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${p.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${p.keychainPassword}"`].filter(Boolean).join(`
|
|
1030
|
+
`),A=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(`
|
|
1031
|
+
`):"",C=qn,P={"{{REMOTE_DIR}}":f,"{{ENV_VARS}}":_,"{{CREDENTIAL_DOWNLOADS}}":L,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":U,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":A};Object.entries(P).forEach(([R,I])=>{C=C.split(R).join(I)});let N=`/tmp/${p.nameLower}-mac-build-${t}.sh`;if(Hs.writeFileSync(N,C),Ct(`${d} ${N} ${l}:${f}/build.sh`),r.stop("Remote script uploaded."),yt.info(Qe.cyan("Executing remote build. This might take a while...")),Ct(`${a} "bash ${f}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),n){r.start("Fetching artifact links...");try{let I=(await v.get(`/builds/${n}/${t}/artifacts`)).data.artifacts||[],M=e.simulator===!0;if(I.length===0&&!M)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),I.length>0){yt.success("Build Artifacts Ready:");for(let K of I)console.log(`
|
|
1032
1032
|
${Qe.yellow(K.name)}:
|
|
1033
1033
|
${Qe.cyan(K.downloadUrl)}`);console.log(`
|
|
1034
|
-
${Qe.dim("Note: Links are valid for 7 days.")}`)}else M&&yt.warn("Simulator build completed. No artifacts uploaded.")}catch(
|
|
1034
|
+
${Qe.dim("Note: Links are valid for 7 days.")}`)}else M&&yt.warn("Simulator build completed. No artifacts uploaded.")}catch(R){r.stop("Could not fetch artifacts"),yt.warn(Qe.yellow(`Artifact listing failed: ${R.message}`))}}}catch(c){throw r.stop("iOS Build Failed"),c}};import js from"crypto";import Te from"axios";import Qn from"fs";var Ge=6e4,Gs=12e4,ji=4,Ye=e=>encodeURIComponent(e),Ks=e=>new Promise(t=>setTimeout(t,e));async function ke(e,t){let i;for(let n=1;n<=ji;n++)try{return await t()}catch(r){if(i=r,n>=ji||!Vs(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*n*n,15e3);console.log(`[Google Play] ${e} failed (attempt ${n}/${ji}); retrying in ${Math.round(s/1e3)}s...`),await Ks(s)}throw i}function Vs(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function er(e,t){let i;try{let n=await ii(t),r=Ye(e);if(i=(await ke("create edit",()=>Te.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:Ge}))).data.id,!i)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Ye(i),l=0,d=(await ke("list tracks",()=>Te.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:Ge}))).data.tracks||[];for(let c of d)if(c.releases){for(let u of c.releases)if(u.versionCodes)for(let f of u.versionCodes){let m=parseInt(f,10);m>l&&(l=m)}}try{let u=(await ke("list bundles",()=>Te.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:Ge}))).data.bundles||[];for(let f of u)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let u=(await ke("list APKs",()=>Te.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:Ge}))).data.apks||[];for(let f of u)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}return l}catch(n){let r=n.response?.data?.error?.message||n.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(i)try{let n=await ii(t);await ke("delete edit",()=>Te.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Ye(e)}/edits/${Ye(i)}`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:Ge}))}catch{}}}async function tr(e){let{packageName:t,serviceAccount:i,aabPath:n,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let c={Authorization:`Bearer ${await ii(i)}`,Connection:"close"},u=Ye(t);if(a=(await ke("create edit",()=>Te.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits`,{},{headers:c,timeout:Ge}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let m=Ye(a),b=Qn.statSync(n),U=await ke("upload AAB",()=>Te.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${u}/edits/${m}/bundles`,Qn.createReadStream(n),{headers:{...c,"Content-Type":"application/octet-stream","Content-Length":b.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Gs})),k=Number(U.data.versionCode);if(!k)throw new Error("Google Play upload succeeded but did not return a versionCode.");let L={versionCodes:[String(k)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(L.userFraction=s),await ke("update track",()=>Te.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}/tracks/${Ye(r)}`,{releases:[L]},{headers:c,timeout:Ge})),await ke("commit edit",()=>Te.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${m}:commit`,{},{headers:c,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ge})),{editId:a,versionCode:k,track:r,releaseStatus:o,userFraction:s}}catch(d){if(a)try{let u=await ii(i);await ke("delete edit",()=>Te.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Ye(t)}/edits/${Ye(a)}`,{headers:{Authorization:`Bearer ${u}`,Connection:"close"},timeout:Ge}))}catch{}let c=d.response?.data?.error?.message||d.message;throw new Error(`Google Play API Error: ${c}`)}}async function ii(e){let t=Math.floor(Date.now()/1e3),i=t+3600,n={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:i,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(n)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=js.createSign("RSA-SHA256");a.update(l);let d=a.sign(e.private_key,"base64url"),c=`${l}.${d}`;return(await ke("OAuth token exchange",()=>Te.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:c},{headers:{Connection:"close"},timeout:Ge}))).data.access_token}import zs from"crypto";import ir from"axios";var Ki="https://api.appstoreconnect.apple.com/v1",nr=6e4,Gi=4,Ws=e=>new Promise(t=>setTimeout(t,e));function Ys(e,t,i){let n=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:n,exp:n+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=zs.createSign("SHA256");l.update(s);let a=l.sign({key:i,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Js(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function rr(e,t){let i;for(let n=1;n<=Gi;n++)try{return await t()}catch(r){if(i=r,n>=Gi||!Js(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*n*n,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${n}/${Gi}); retrying in ${Math.round(s/1e3)}s...`),await Ws(s)}throw i}function or(e){return{Authorization:`Bearer ${Ys(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function qs(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(i=>i.detail||i.title||i.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function ni(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(i=>Number(i))}function Xs(e,t){let i=ni(e),n=ni(t);if(!i&&!n)return 0;if(!i)return-1;if(!n)return 1;let r=Math.max(i.length,n.length);for(let o=0;o<r;o++){let s=i[o]||0,l=n[o]||0;if(s!==l)return s>l?1:-1}return 0}function Zs(e){let t=ni(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Qs(e,t,i){if(t)return t;if(!i)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await rr("lookup app by bundle ID",()=>ir.get(`${Ki}/apps`,{headers:or(e),params:{"filter[bundleId]":i,limit:1},timeout:nr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${i}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function sr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let i=await Qs(t,e.ascAppId,e.bundleId),n=`${Ki}/builds`,r="0",o,s=0;for(;n&&s<10;){s+=1;let l=await rr("list builds",()=>ir.get(n,{headers:or(t),params:n===`${Ki}/builds`?{"filter[app]":i,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:nr})),a=l.data?.data||[];for(let d of a){let c=String(d.attributes?.version||"").trim();ni(c)&&Xs(c,r)>0&&(r=c,o=d.attributes?.uploadedDate)}n=l.data?.links?.next}return{appId:i,latestBuildNumber:r,nextBuildNumber:Zs(r),latestUploadedDate:o}}catch(i){throw new Error(`App Store Connect API Error: ${qs(i)}`)}}import{spinner as ri,log as E,isCancel as oi,confirm as ea,select as zi}from"@clack/prompts";import y from"chalk";import g from"fs";import $ from"path";import{execFileSync as Vi,execSync as X,spawn as dr}from"child_process";import Se from"os";import ta from"crypto";var ur=(e,t)=>t.filter(i=>g.existsSync($.join(e,i))).reduce((i,n)=>i.update(g.readFileSync($.join(e,n))),ta.createHash("sha256")).digest("hex").slice(0,16),ia=e=>ur(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),na=e=>ur(e,["Podfile","Podfile.lock"]),ra=e=>{let t=$.join(e,"fingerprint.json");try{return JSON.parse(g.readFileSync(t,"utf-8"))}catch{return{}}},ar=(e,t)=>{g.mkdirSync(e,{recursive:!0}),g.writeFileSync($.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},oa=7200*1e3,sa=(e,t)=>{g.mkdirSync(e,{recursive:!0});let i=$.join(e,"build.lock");if(g.existsSync(i))try{let n=JSON.parse(g.readFileSync(i,"utf-8")),r=Date.now()-(n.timestamp||0);if(r<oa)throw new Error(`Another build is already running for this project (build ${n.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(n){if(n.message.includes("Another build"))throw n}g.writeFileSync(i,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},aa=(e,t)=>{let i=$.join(e,"build.lock");try{g.existsSync(i)&&JSON.parse(g.readFileSync(i,"utf-8")).buildId===t&&g.unlinkSync(i)}catch{}},lr=2e5,cr=(e,t)=>{let i=e+t;return i.length>lr?i.slice(-lr):i},pr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),la=(e,t,i,n)=>{let r=pr(n).replace(/\r/g,`
|
|
1035
1035
|
`).split(`
|
|
1036
1036
|
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(a=>/\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/i.test(a)),s=o.length>0?o.slice(-40):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${i}: ${e} ${t.join(" ")}`,s.length>0?`
|
|
1037
1037
|
${l}:
|
|
1038
1038
|
${s.join(`
|
|
1039
|
-
`)}`:""].join("")},
|
|
1039
|
+
`)}`:""].join("")},ca=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",da=e=>{let t=pr(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},lt=e=>{try{g.existsSync(e)&&g.rmSync(e,{recursive:!0,force:!0})}catch{}},ua=(e,t)=>{try{if(!g.existsSync(e))return;for(let i of g.readdirSync(e))t(i)&<($.join(e,i))}catch{}},fr=e=>{E.info(y.dim("Clearing Metro/Hermes JS transform caches..."));let t=Se.tmpdir();ua(t,i=>i==="metro-cache"||i.startsWith("metro-")||i.startsWith("haste-map-")||i.startsWith("react-native-packager-cache-")),lt($.join(e,".expo")),lt($.join(e,"node_modules/.cache/metro")),lt($.join(Se.homedir(),".cache/metro")),lt($.join(Se.homedir(),".cache/react-native-packager")),lt($.join(Se.homedir(),"Library/Caches/metro")),lt($.join(Se.homedir(),"Library/Caches/react-native-packager"))},Ke=(e,t,i=process.cwd(),n={},r,o)=>new Promise((s,l)=>{let a="",d=ca(e),c=Date.now(),u=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",$.join(Se.homedir(),".npm-global/bin")],m=[...(process.env.PATH||"").split(":"),...u].filter((T,G,h)=>T&&h.indexOf(T)===G).join(":");process.env[`${p.envPrefix}DEBUG`]&&console.log(y.magenta(`[${p.nameUpper}_DEBUG] Execution PATH: ${m}`));let b={...process.env,...n,PATH:m,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${p.envPrefix}DEBUG`]&&(r(y.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1040
1040
|
`)),r(y.magenta(`[ENVIRONMENT] PATH: ${m}
|
|
1041
1041
|
`)),r(y.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1042
|
-
`)));let U=e;if(["node","npm","npx","pod"].includes(e)){let T
|
|
1043
|
-
`)))}let
|
|
1042
|
+
`)));let U=e;if(["node","npm","npx","pod"].includes(e)){let T=$.dirname(process.execPath),G=$.join(T,e);g.existsSync(G)&&(U=G,r&&r(y.dim(`[EXEC] Using absolute path: ${U}
|
|
1043
|
+
`)))}let k=dr(U,t,{stdio:"pipe",cwd:i,shell:!0,env:b,detached:process.platform!=="win32"});if(o){if(o.aborted){if(k.pid)try{process.kill(-k.pid,"SIGTERM")}catch{k.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(k.pid)try{process.kill(-k.pid,"SIGTERM")}catch{k.kill()}l(new Error("Command aborted"))})}let L=(T,G)=>{if(!d){G.write(T);return}let h=T.replace(/\r/g,`
|
|
1044
1044
|
`).split(`
|
|
1045
|
-
`).filter(
|
|
1045
|
+
`).filter(da);if(h.length>0){G.write(`${h.join(`
|
|
1046
1046
|
`)}
|
|
1047
1047
|
`),c=Date.now();return}let V=Date.now();V-c>3e4&&(G.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1048
|
-
`),c=V)};
|
|
1049
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!i)throw new Error(`Could not validate iOS build number: ${
|
|
1050
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),m&&clearInterval(m))}catch{}},5e3));let
|
|
1051
|
-
`)},_=async(
|
|
1052
|
-
`);else if(n&&l==="ios"&&!e.simulator)try{let
|
|
1053
|
-
`))
|
|
1054
|
-
`)}
|
|
1055
|
-
`),
|
|
1056
|
-
`),
|
|
1057
|
-
`),
|
|
1048
|
+
`),c=V)};k.stdout.on("data",T=>{let G=T.toString();a=cr(a,G),L(G,process.stdout),r&&r(G)}),k.stderr.on("data",T=>{let G=T.toString();a=cr(a,G),L(G,process.stderr),r&&r(G)}),k.on("close",T=>{T===0?s(T):l(new Error(la(e,t,T,a)))}),k.on("error",T=>l(T))}),pa=e=>{let t=Math.floor(e/1e3%60),i=Math.floor(e/(1e3*60)%60),n=Math.floor(e/(1e3*60*60)%24),r=[];return n>0&&r.push(`${n}h`),i>0&&r.push(`${i}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},ct=(e,t)=>{let i=[];try{if(!g.existsSync(e))return i;let n=g.readdirSync(e);for(let r of n){let o=$.join(e,r);try{let s=g.statSync(o);if(t.some(a=>r.endsWith(a))){i.push($.resolve(o));continue}s.isDirectory()&&(i=i.concat(ct(o,t)))}catch{}}}catch{}return i},fa=/^\d+(?:\.\d+){0,2}$/,Wi=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:fa.test(t)?t:null},mr=(e,t)=>{let i=Wi(e);if(!i)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 i},gr=(e,t)=>Vi("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),ma=e=>{let t=$.join(e,"Info.plist");if(!g.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return mr(gr(t,"CFBundleVersion"),t)},ga=e=>{let i=Vi("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1049
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!i)throw new Error(`Could not validate iOS build number: ${$.basename(e)} has no Payload/*.app/Info.plist.`);let n=g.mkdtempSync($.join(Se.tmpdir(),`${p.nameLower}-ipa-plist-`));try{let r=$.join(n,"Info.plist"),o=Vi("unzip",["-p",e,i.trim()]);return g.writeFileSync(r,o),mr(gr(r,"CFBundleVersion"),`${$.basename(e)}:${i.trim()}`)}finally{g.rmSync(n,{recursive:!0,force:!0})}},Yi=async(e,t,i={},n,r={})=>{let o=ri(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",d=()=>at(i,a,e),c=async(A,C={})=>{if(n)for(let P=1;P<=3;P++)try{await v.patch(`/builds/${n}/${t}`,{status:A,...C});return}catch(N){let R=N?.response?.data?.message||N?.message||String(N);console.error(`[reportStatus] attempt ${P}/3 failed (status=${A}): ${R}`),P<3&&await new Promise(I=>setTimeout(I,2e3))}},u=new AbortController,{signal:f}=u,m=null;n&&(m=setInterval(async()=>{try{(await v.get(`/builds/${n}/${t}`)).data.status==="cancelled"&&(E.warn(y.yellow(`
|
|
1050
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),m&&clearInterval(m))}catch{}},5e3));let b=$.join(process.cwd(),".mach-cache"),U="setup",k="",L=null,T=async()=>{if(!k||!n)return;let A=k;k="";try{let C=A;Object.values(i).forEach(P=>{if(P&&P.length>5){let N=P.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");C=C.replace(new RegExp(N,"g"),"[SECRET]")}}),await v.post(`/builds/${n}/${t}/logs`,{log:C,step:U})}catch{}},G=async()=>{L&&(clearTimeout(L),L=null),await T(),aa(b,t),m&&(clearInterval(m),m=null);try{let A=$.join(Se.tmpdir(),`${p.buildPrefix}-${t}.keychain-db`);g.existsSync(A)&&(X(`security delete-keychain "${A}"`,{stdio:"ignore"}),E.info(y.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let A=$.join(Se.homedir(),"Library/MobileDevice/Provisioning Profiles");if(g.existsSync(A)){let C=g.readdirSync(A).filter(P=>P.includes(t)||P.startsWith(`${p.nameLower}-temp-${t}`));for(let P of C)g.unlinkSync($.join(A,P))}}catch{}},h=async A=>{n&&(k+=A,k.length>=8192?(L&&(clearTimeout(L),L=null),await T()):L||(L=setTimeout(()=>{L=null,T()},2e3)))},V=async A=>{U=A,await h(`[STEP_START:${A}] ${Math.floor(Date.now()/1e3)}
|
|
1051
|
+
`)},_=async(A,C,P,N)=>await Ke(A,C,P,N,R=>{h(R)},f);E.info(y.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{sa(b,t)}catch(A){throw await c("failed",{error:A.message}),A}if(await c("building"),await V("setup"),l==="ios"&&!e.simulator&&i.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&i.BUILD_NUMBER)E.info(y.dim(`Auto build number: ${i.BUILD_NUMBER}`)),await h(`[BUILD_NUMBER] ${i.BUILD_NUMBER}
|
|
1052
|
+
`);else if(n&&l==="ios"&&!e.simulator)try{let A=parseInt(i.BUILD_NUMBER||"0",10),C=Number.isFinite(A)?A:0,P=await v.post(`/projects/${n}/next-build-number`,{platform:"ios",startFrom:C});if(P.data.status==="success"){let N=Wi(String(P.data.buildNumber||""));if(!N)throw new Error(`Dashboard returned invalid iOS build number: "${P.data.buildNumber||""}"`);let R=parseInt(N,10),I=C>0&&Number.isFinite(R)&&R<C?String(C):N;I!==N&&(E.warn(y.yellow(`Dashboard build counter returned ${N}; using minimum ${I}.`)),await h(`[BUILD_NUMBER] Dashboard returned ${N}; using minimum ${I}
|
|
1053
|
+
`)),i.BUILD_NUMBER=I,E.info(y.dim(`Auto build number: ${i.BUILD_NUMBER}`)),await h(`[BUILD_NUMBER] ${i.BUILD_NUMBER}
|
|
1054
|
+
`)}}catch(A){E.warn(y.yellow(`Could not fetch auto build number: ${A.message}`))}await V("lock"),e.developmentClient?(E.info(y.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(E.info(y.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await V("clone"),E.info(y.dim("Preparing source...")),await V("read_config");let A=$.join(process.cwd(),p.configFileName);if(g.existsSync(A)){let B=JSON.parse(g.readFileSync(A,"utf-8"))?.build?.[a]||{};await h(`[CONFIG] Profile: ${a}, distribution: ${B.distribution||"not set"}, simulator: ${B.simulator||!1}
|
|
1055
|
+
`)}if(await V("read_package"),e.nodeVersion){let F=process.env.NVM_DIR||$.join(Se.homedir(),".nvm"),B=$.join(F,"versions","node"),q;if(g.existsSync(B)){let w=g.readdirSync(B).sort().reverse(),H=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,Z=w.find(oe=>oe===H||oe.startsWith(H+".")||oe.startsWith(`v${e.nodeVersion}.`));Z&&(q=$.join(B,Z,"bin"))}if(q&&g.existsSync(q)){let w=process.env.PATH||"";process.env.PATH=`${q}:${w}`,await h(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
|
|
1056
|
+
`),E.info(y.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await h(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1057
|
+
`),E.warn(y.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await V("deps"),o.start("Checking dependencies...");let C=ra(b),P=ia(process.cwd()),N=g.existsSync("node_modules"),R=g.existsSync("yarn.lock"),I=g.existsSync("bun.lockb");N&&C.node&&C.node!==P&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await h(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1058
|
+
`),g.rmSync($.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),N=!1);let M="npm",K=["install","--prefer-offline"];R?(M="yarn",K=["install","--prefer-offline"]):I&&(M="bun",K=["install"]),N?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(E.info(y.blue("Running pre-install hook...")),E.info(y.dim(`> ${e.preBuild}`)),await V("prebuild"),await _("bash",[e.preBuild],process.cwd(),d())),E.info(y.dim(`Running ${M} ${K.join(" ")}...`)),await _(M,K,process.cwd(),d()),C.node=P,ar(b,C);let x=JSON.parse(g.readFileSync("package.json","utf-8")),z=x.dependencies?.expo||x.devDependencies?.expo,S=e.iosBundleIdentifier||"",ne=e.name||"";if(z){o.start(`Enforcing ${p.name} configuration...`);let F=$.join(process.cwd(),"app.json"),B=null;if(g.existsSync(F)){B=g.readFileSync(F,"utf-8");let w=JSON.parse(B);w.expo=w.expo||{},ne||(ne=w.expo.name||""),l==="ios"&&!S&&(S=w.expo?.ios?.bundleIdentifier||""),e.name&&(w.expo.name=e.name),e.scheme&&(w.expo.scheme=e.scheme),l==="ios"&&e.iosBundleIdentifier?(w.expo.ios=w.expo.ios||{},w.expo.ios.bundleIdentifier=e.iosBundleIdentifier):l==="android"&&e.androidPackage&&(w.expo.android=w.expo.android||{},w.expo.android.package=e.androidPackage),g.writeFileSync(F,JSON.stringify(w,null,2))}let q=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await V("prebuild"),await _("npm",q,process.cwd(),d()),l==="ios"&&g.existsSync("ios")){await V("pods"),E.info(y.blue("Running pod install..."));try{let w=$.resolve("ios"),H=$.join(w,"Podfile");if(!g.existsSync(H))throw new Error("ios/Podfile not found. Skipping pod install.");let Z=g.readFileSync(H,"utf-8"),oe=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(E.info(y.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),Z.includes("use_expo_modules!")&&!Z.includes("exclude:"))){let st=/use_expo_modules!(\s*)$/m;st.test(Z)?Z=Z.replace(st,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):Z=Z.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let he=`
|
|
1058
1059
|
installer.generated_projects.each do |project|
|
|
1059
1060
|
project.targets.each do |target|
|
|
1060
1061
|
target.build_configurations.each do |config|
|
|
1061
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
1062
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${oe}'
|
|
1062
1063
|
end
|
|
1063
1064
|
end
|
|
1064
1065
|
end
|
|
1065
1066
|
installer.pods_project.targets.each do |target|
|
|
1066
1067
|
target.build_configurations.each do |config|
|
|
1067
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
1068
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${oe}'
|
|
1068
1069
|
end
|
|
1069
1070
|
end
|
|
1070
|
-
`,ze=/post_install\s+do\s+\|installer\|/;if(ze.test(Z))
|
|
1071
|
-
${he}`),g.writeFileSync(
|
|
1071
|
+
`,ze=/post_install\s+do\s+\|installer\|/;if(ze.test(Z))E.info(y.dim(`Injecting deployment target (${oe}) into existing post_install hook...`)),Z=Z.replace(ze,`post_install do |installer|
|
|
1072
|
+
${he}`),g.writeFileSync(H,Z);else{E.info(y.dim(`Appending new post_install hook for deployment target (${oe})...`));let st=`
|
|
1072
1073
|
post_install do |installer|
|
|
1073
1074
|
${he}
|
|
1074
1075
|
end
|
|
1075
|
-
`;g.appendFileSync(
|
|
1076
|
-
`),
|
|
1077
|
-
\u2713 Local build completed successfully in ${
|
|
1078
|
-
\u{1F4E6} Generated Artifacts:`)),J.forEach(F=>{let B
|
|
1079
|
-
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user"}),
|
|
1080
|
-
\u2717 Local build failed: ${
|
|
1081
|
-
`)[0]||"unknown"}`))}if(!
|
|
1082
|
-
`).map(Ie=>Ie.trim().replace(/^"|"$/g,"")).filter(Ie=>Ie.length>0),Zt=[
|
|
1076
|
+
`;g.appendFileSync(H,st)}let Rt="/opt/homebrew/bin/pod",Xt=g.existsSync(Rt)?Rt:"pod",Zt=na(w);g.existsSync($.join(w,"Pods"))&&C.pods&&C.pods!==Zt&&(await h(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1077
|
+
`),E.info(y.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),g.rmSync($.join(w,"Pods"),{recursive:!0,force:!0})),E.info(y.dim(`Using pod command: ${Xt} in ${w}`)),await _(Xt,["install"],w,d()),C.pods=Zt,ar(b,C)}catch(w){let H=w.message||"Unknown error";E.warn(y.yellow(`Native "pod" command failed: ${H}`)),E.info(y.dim("Falling back to npm exec pod-install...")),E.info(y.magenta(`${p.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await _("npx",["--yes","pod-install@latest","ios"],process.cwd(),d())}if(g.existsSync("ios/Pods")){E.info(y.dim("Disabling signing for Pod targets to prevent conflicts..."));try{X(`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{}}}}finally{B&&g.writeFileSync(F,B)}o.stop(`Expo prebuild complete (${p.name} config enforced).`)}let J=[];if(l==="android")await V("build"),J=await ha(e,a,i,F=>h(F),f);else if(l==="ios"){await V("signing"),E.info(y.dim("Preparing credentials..."));let F=r?.distributionType;J=await ya(e,t,a,i,n,B=>h(B),f,F,B=>V(B))}e.postBuild&&(E.info(y.blue("Running post-build hook...")),E.info(y.dim(`> ${e.postBuild}`)),await _(e.postBuild,[],process.cwd(),d()));let Re=pa(Date.now()-s);if(E.success(y.green(`
|
|
1078
|
+
\u2713 Local build completed successfully in ${Re}`)),await c("building",{...S&&{bundleId:S},...ne&&{appName:ne}}),J.length>0&&(E.info(y.cyan(`
|
|
1079
|
+
\u{1F4E6} Generated Artifacts:`)),J.forEach(F=>{let B=$.resolve(F);E.info(y.dim(` - ${F}`)),E.info(y.gray(` Path: ${B}`))}),e.interactive)){let F=await ea({message:"Install on connected device?"});if(!oi(F)&&F){if(l==="android"){let B=J.find(q=>q.endsWith(".apk"))||J[0];await ba(B,q=>h(q))}else if(l==="ios"){let B=J.find(w=>w.endsWith(".ipa"))||J.find(w=>w.endsWith(".app"))||J[0],q=Je("ios");e.simulator?await Ea(B,q||"",w=>h(w)):await Aa(B,q||"",w=>h(w))}}}await V("upload");let de=[];for(let F of J)try{let B=$.join(Se.tmpdir(),`${t}-${$.basename(F)}`);g.copyFileSync(F,B),de.push(B),E.info(y.dim(` \u{1F4CB} Preserved artifact: ${$.basename(F)}`))}catch{E.warn(y.yellow(` Failed to preserve artifact: ${$.basename(F)}`))}J=de,E.info(y.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let F=process.cwd(),B=new Set(["node_modules"]),q=g.readdirSync(F),w=0;for(let H of q)if(!B.has(H)){if(H==="ios"){let Z=$.join(F,"ios"),oe=g.readdirSync(Z);for(let he of oe)if(he!=="Pods")try{g.rmSync($.join(Z,he),{recursive:!0,force:!0}),w++}catch{}continue}try{g.rmSync($.join(F,H),{recursive:!0,force:!0}),w++}catch{}}E.info(y.dim(` Cleaned ${w} items. Cached: node_modules${g.existsSync($.join(F,"ios","Pods"))?", ios/Pods":""}`)),E.info(y.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{E.warn(y.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let B=$.join(Se.homedir(),p.workspacesDir),q=X(`df -k "${B}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),w=parseInt(q,10)*1024;if(w<53687091200&&g.existsSync(B)){E.info(y.dim(` \u26A0\uFE0F Low disk space (${(w/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let H=$.basename(process.cwd()),Z=g.readdirSync(B).filter(oe=>oe!==H).map(oe=>{let he=$.join(B,oe);try{let ze=g.statSync(he);return ze.isDirectory()?{name:oe,dir:he,mtime:ze.mtimeMs}:null}catch{return null}}).filter(Boolean);Z.sort((oe,he)=>oe.mtime-he.mtime);for(let oe of Z){if(w>=53687091200)break;try{g.rmSync(oe.dir,{recursive:!0,force:!0}),E.info(y.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${oe.name}`));let he=X(`df -k "${B}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(he,10)*1024>=53687091200)break}catch{}}}}catch{}return await G(),J}catch(A){throw await G(),A.message==="Command aborted"?(E.warn(y.yellow(`
|
|
1080
|
+
\u274C Build aborted.`)),await c("failed",{error:"Aborted by user"}),A):(E.error(y.red(`
|
|
1081
|
+
\u2717 Local build failed: ${A.message}`)),await c("failed",{error:A.message}),A)}},ha=async(e,t,i={},n,r)=>{let o=g.existsSync("android/gradlew")?"android/gradlew":g.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;E.info(y.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",d=(o.includes("android/"),"./gradlew"),c=[l],u={...i,EXPO_NO_DOTENV:"1",MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(i.ANDROID_VERSION_CODE){let m=$.join(a,"app/build.gradle");if(g.existsSync(m)){let b=i.ANDROID_VERSION_CODE,U=g.readFileSync(m,"utf-8");U=U.replace(/versionCode\s+\d+/,`versionCode ${b}`),g.writeFileSync(m,U),E.info(y.green(`\u2713 Applied Android versionCode ${b}`))}c.push(`-Pandroid.injected.version.code=${i.ANDROID_VERSION_CODE}`)}for(let m of["app/build","build",".cxx"]){let b=$.join(a,m);g.existsSync(b)&&g.rmSync(b,{recursive:!0,force:!0})}fr(process.cwd()),await Ke(d,c,a,u,n,r);let f=$.join(a,"app/build/outputs");return ct(f,[".apk",".aab"])},ya=async(e,t,i,n={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let d=$.resolve(process.cwd(),g.existsSync("ios")?"ios":"."),c=g.readdirSync(d),u=c.find(P=>P.endsWith(".xcworkspace")),f=c.find(P=>P.endsWith(".xcodeproj")),m=at(n,i,e),b=Wi(m.BUILD_NUMBER||m.CURRENT_PROJECT_VERSION);if((m.BUILD_NUMBER||m.CURRENT_PROJECT_VERSION)&&!b)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${m.BUILD_NUMBER||m.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 U=b?[`BUILD_NUMBER=${b}`,`CURRENT_PROJECT_VERSION=${b}`]:[];if(b&&(m.BUILD_NUMBER=b,m.CURRENT_PROJECT_VERSION=b,E.info(y.dim(`Using iOS build number: ${b}`))),!u&&!f)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let P=X("xcode-select -p").toString().trim();E.info(y.dim(`Using Xcode at: ${P}`))}catch{E.warn(y.dim("Could not detect Xcode path."))}E.info(y.blue("Running iOS build via xcodebuild..."));let k=u?u.replace(".xcworkspace",""):f?.replace(".xcodeproj",""),L=e.iosScheme||k||e.scheme,T=e.developmentClient?"Debug":e.iosConfiguration||"Release",G=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),h=$.join(Se.homedir(),`Library/Developer/Xcode/DerivedData/${p.nameLower}`,G);g.mkdirSync(h,{recursive:!0});let V=ht(m),_=$.join(h,".mach-env-hash"),A=$.join(h,"Build"),C=g.existsSync(_)?g.readFileSync(_,"utf-8").trim():"";if(g.existsSync(A)){let P=C&&C!==V?"Build environment changed \u2014 clearing iOS DerivedData build products.":C?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";E.info(y.dim(P)),g.rmSync(A,{recursive:!0,force:!0})}if(g.writeFileSync(_,V),fr(process.cwd()),e.simulator){E.info(y.dim(`Building for simulator (Scheme: ${L}, Config: ${T})...`)),await Ke("xcodebuild",[u?"-workspace":"-project",u||f,"-scheme",L,"-configuration",T,"-sdk","iphonesimulator","-derivedDataPath",h,...U,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],d,m,o,s);let P=$.join(h,"Build/Products",`${T}-iphonesimulator`),N=ct(P,[".app"]);if(N.length>0){let R=N[0],I=$.basename(R,".app"),M=$.join(P,`${I}_simulator.zip`);return E.info(y.dim(`Creating simulator artifact: ${M}...`)),X(`cd "${P}" && zip -r "${M}" "${$.basename(R)}"`),[M]}return[]}else{E.info(y.dim(`Archiving (Scheme: ${L}, Config: ${T})...`));let P=$.join(d,"build.xcarchive"),N=$.join(d,"export");g.rmSync(P,{recursive:!0,force:!0}),g.rmSync(N,{recursive:!0,force:!0});let R=n.IOS_DIST_P12,I=n.IOS_PROVISIONING_PROFILE,M=n.IOS_P12_PASSWORD||"",K=[],x,z,S={isAppStore:!1,isDevelopment:!1};if(R&&I){E.info(y.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let w=`${p.buildPrefix}-${t}.keychain-db`,H=$.join(Se.tmpdir(),w),Z=p.keychainPassword;X(`security create-keychain -p "${Z}" "${H}" 2>/dev/null || true`),X(`security set-keychain-settings -t 3600 -l "${H}"`),X(`security unlock-keychain -p "${Z}" "${H}"`);let oe=$.join(Se.tmpdir(),`cert-${t}.p12`),he=Buffer.from(R,"base64");g.writeFileSync(oe,he),E.info(y.dim(`P12 data size: ${he.length} bytes, first bytes: ${he.slice(0,4).toString("hex")}`)),(he.length<100||he[0]!==48)&&(E.warn(y.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),E.warn(y.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let ze=[M,"",p.keychainPassword],Rt=!1;for(let Ie of ze)try{X(`security import "${oe}" -k "${H}" -P "${Ie}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Rt=!0,E.info(y.dim(`\u2713 P12 imported successfully with password: ${Ie?"[set]":"[empty]"}`));break}catch(je){E.info(y.dim(` P12 import attempt with password ${Ie?`"${Ie.substring(0,3)}..."`:"[empty]"} failed: ${je.message?.split(`
|
|
1082
|
+
`)[0]||"unknown"}`))}if(!Rt)throw new Error("Failed to import P12.");g.unlinkSync(oe),X(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Z}" "${H}"`);let Xt=X("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1083
|
+
`).map(Ie=>Ie.trim().replace(/^"|"$/g,"")).filter(Ie=>Ie.length>0),Zt=[H,...Xt].map(Ie=>`"${Ie}"`).join(" ");X(`security list-keychains -d user -s ${Zt}`),X(`security default-keychain -s "${H}"`);let Qt=$.join(Se.homedir(),"Library/MobileDevice/Provisioning Profiles");g.mkdirSync(Qt,{recursive:!0});let st=Buffer.from(I,"base64"),Li=$.join(Qt,`${p.nameLower}-temp-${t}.mobileprovision`);g.writeFileSync(Li,st);let xi=st.toString("utf-8"),Cn=/<key>get-task-allow<\/key>\s*<true\/>/.test(xi);S={isAppStore:!xi.includes("<key>ProvisionedDevices</key>")&&!Cn,isDevelopment:Cn};try{let je=X(`security cms -D -i "${Li}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);z=je?je[1]:void 0}catch{let je=xi.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);z=je?je[1]:void 0}z||(E.warn("Could not extract UUID from provisioning profile. Using fallback."),z=`${p.nameLower}-${t}`);let Mi=$.join(Qt,`${z}.mobileprovision`);g.existsSync(Mi)&&g.unlinkSync(Mi),g.renameSync(Li,Mi);try{let je=X(`security find-identity -v -p codesigning "${H}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);je&&(x=je[1],E.info(y.blue(`Identity auto-detected from keychain: "${x}"`)))}catch{}x||(x=S.isDevelopment?"Apple Development":"Apple Distribution",E.info(y.blue(`Identity fallback (profile heuristic): "${x}"`))),E.info(y.dim(`Profile type: ${S.isDevelopment?"Development":S.isAppStore?"App Store":"Ad-Hoc"}`)),E.info(y.dim(`Identity Detection: get-task-allow=${S.isDevelopment}, Selected Identity="${x}"`)),K.push("CODE_SIGN_STYLE=Manual"),K.push(`CODE_SIGN_IDENTITY="${x}"`),K.push(`PROVISIONING_PROFILE_SPECIFIER=${z}`),e.iosTeamId&&K.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(w){throw E.error(`Signing setup failed: ${w.message}`),w}}else K.push("-allowProvisioningUpdates"),e.iosTeamId&&K.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),E.info(y.blue(`Archive detected Identity: "${x}"`)),E.info(y.blue(`Archive detected UUID: "${z}"`)),await Ke("xcodebuild",["archive",u?"-workspace":"-project",u||f,"-scheme",L,"-configuration",T,"-archivePath",P,"-derivedDataPath",h,...U,...K],d,m,o,s);let ne=ct($.join(P,"Products","Applications"),[".app"]);for(let w of ne){let H=ma(w);E.info(y.dim(`Validated iOS CFBundleVersion ${H} in ${$.basename(w)}`))}let J;z?(S.isAppStore?J="app-store":S.isDevelopment?J="development":J="ad-hoc",E.info(y.blue(`Export method from profile: "${J}"`))):(J=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",E.warn(y.yellow(`No profile UUID detected. Export method from distribution flag: "${J}"`)));let Re=e.iosExportMethod||J,de=e.iosBundleIdentifier||Je("ios"),F=$.join(d,"ExportOptions.plist"),B=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1083
1084
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1084
1085
|
<plist version="1.0">
|
|
1085
1086
|
<dict>
|
|
1086
1087
|
<key>method</key>
|
|
1087
|
-
<string>${
|
|
1088
|
+
<string>${Re}</string>
|
|
1088
1089
|
<key>destination</key>
|
|
1089
1090
|
<string>export</string>
|
|
1090
1091
|
<key>signingStyle</key>
|
|
1091
|
-
<string>${
|
|
1092
|
+
<string>${z?"manual":"automatic"}</string>
|
|
1092
1093
|
<key>thinning</key>
|
|
1093
1094
|
<string><none></string>
|
|
1094
1095
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1095
|
-
${
|
|
1096
|
+
${de&&z?`
|
|
1096
1097
|
<key>provisioningProfiles</key>
|
|
1097
1098
|
<dict>
|
|
1098
|
-
<key>${
|
|
1099
|
-
<string>${
|
|
1099
|
+
<key>${de}</key>
|
|
1100
|
+
<string>${z}</string>
|
|
1100
1101
|
</dict>`:""}
|
|
1101
1102
|
</dict>
|
|
1102
|
-
</plist>`;if(g.writeFileSync(F,B),process.env[`${p.envPrefix}DEBUG`]&&
|
|
1103
|
-
${B}`)),a&&await a("export"),
|
|
1103
|
+
</plist>`;if(g.writeFileSync(F,B),process.env[`${p.envPrefix}DEBUG`]&&E.info(y.magenta(`[${p.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1104
|
+
${B}`)),a&&await a("export"),E.info(y.blue(`Exporting with Bundle ID: "${de}"`)),E.info(y.blue(`Exporting with Method: "${Re}"`)),o){o(y.magenta(`
|
|
1104
1105
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1105
|
-
`));try{let
|
|
1106
|
-
`))}catch(
|
|
1107
|
-
`))}}await Ke("xcodebuild",["-exportArchive","-archivePath",P,"-exportPath",
|
|
1108
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1109
|
-
`)}catch(
|
|
1110
|
-
`),new Error(Z)}return
|
|
1111
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){
|
|
1112
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1113
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?q(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):q(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{b.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(n){i.stop("Installation failed."),b.error(y.red(`Failed to install APK: ${n.message}`))}},da=async(e,t,i)=>{let n=ri();try{if(!q("xcrun simctl list devices booted").toString().includes("(Booted)")){b.warn(y.yellow("No iOS Simulator is currently booted."));let o=q("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(u=>{s[u].forEach(f=>{f.isAvailable&&l.push({...f,runtime:u})})});let a=await Ki({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(oi(a))return;n.start(`Booting ${a}...`),q(`xcrun simctl boot ${a}`),q(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,c=!1;for(;d<30;){try{if(q("xcrun simctl list devices booted").toString().includes(a)){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await Ke("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),b.info(y.blue(`\u{1F680} Launching ${t}...`)),await Ke("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),b.error(y.red(`Failed to install on Simulator: ${r.message}`))}},ua=async(e,t,i)=>{let n=ri();n.start("Scanning for connected iOS devices...");try{let r=q("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 n.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){n.stop();let a=await Ki({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(oi(a))return;l=a,n.start(`Installing on ${l}...`)}else n.message(`Installing on ${s[0].model.name}...`);await Ke("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},i),n.stop("Installation complete."),b.info(y.blue(`\u{1F680} Launching ${t}...`)),await Ke("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),b.error(y.red(`Failed to install on device: ${r.message}`)),b.info(y.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Le from"fs";import pa from"os";import be from"path";import{spawnSync as Wi}from"child_process";import{randomUUID as fa}from"crypto";import{pipeline as ma}from"stream/promises";import{isCancel as zi,log as j,select as fr,spinner as Nt,text as ga}from"@clack/prompts";import mr from"axios";import W from"chalk";import gr from"adm-zip";async function hr(e){if(e.local){let i=await ya(e);i&&(process.exitCode=i.exitCode);return}let t=await Yi(e);if(t&&(j.success(W.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&j.warn(W.yellow(t.launchDeferredReason)),t.dashboardUrl&&j.info(W.dim("View test run: ")+W.white.underline(t.dashboardUrl)),e.wait)){let i=await Sa(e,t);i&&(process.exitCode=i.status==="passed"?0:1)}}var ha=new Set(["passed","failed","cancelled","interrupted"]);async function ya(e){let t=e.maestroFlows||".maestro",i=yr(e.maestroRetries);if(i===null)return null;let n=be.resolve(t);if(!Le.existsSync(n))return j.error(W.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await _a(e);if(r?.url){if(!await $a(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&&j.warn(W.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)),s.push(t);let l=i+1,a=1;for(let u=1;u<=l;u+=1){j.info(W.dim(`Running local Maestro attempt ${u}/${l}...`));let f=Wi("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(f.error){let m=f.error.message||"Failed to run Maestro";j.error(W.red(`Local Maestro failed to start: ${m}`)),j.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),a=1;break}if(a=typeof f.status=="number"?f.status:1,a===0)break}let d=a===0?"passed":"failed",c={status:d,exitCode:a,attempts:l,flows:t,platform:o};return Ca(e,c),d==="passed"?j.success(W.green("Local Maestro run passed")):j.error(W.red(`Local Maestro run failed with exit code ${a}`)),c}async function Yi(e){let t=Ne(`./${p.configFileName}`),i=e.projectId||t?.projectId,n=String(e.profile||e.buildProfile||"production").toLowerCase();if(!i)return j.error(`No projectId found. Run \`${p.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await fr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(zi(d))return null;r=d}let o=await Aa(e);if(!o)return null;if(o.kind==="latest"&&!r)return j.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return j.error("Pass --platform when using --artifact-url."),null;let s=yr(e.maestroRetries);if(s===null)return null;let l=await Ea(e,i);if(l===null)return null;let a=Nt();e.quiet||a.start("Queuing Maestro run...");try{let d=await R.post("/tests/maestro",{projectId:i,platform:r,profile:n,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:l,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let c=d.data.testRun,u={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${We}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return Ar(e,u),e.quiet||a.stop("Maestro run queued"),u}catch(d){e.quiet||a.stop("Could not queue Maestro run");let c=d.response?.data?.message||d.message||"Unknown error";return j.error(W.red(`Maestro queue failed: ${c}`)),null}}async function Sa(e,t){let i=pr(e.waitTimeout,60,"--wait-timeout"),n=pr(e.waitInterval,15,"--wait-interval");if(i===null||n===null)return null;let r=i*60*1e3,o=Math.max(5,n)*1e3,s=Date.now(),l=t.status||"queued";for(j.info(W.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await ba(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,j.info(W.dim(`Maestro status: ${l}`))),ha.has(String(a.status)))return Ar(e,a),a.status==="passed"?j.success(W.green(`Maestro run passed: ${a.testRunId}`)):(j.error(W.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&j.error(W.red(String(a.error)))),a;await Ia(o)}return j.error(W.red(`Timed out waiting for Maestro run ${t.testRunId} after ${i} minute(s).`)),{...t,status:"timeout"}}async function Ea(e,t){if(e.maestroUseBuildSource)return;let i=e.maestroFlows||".maestro",n=be.resolve(i);if(!Le.existsSync(n))return e.maestroFlows?(j.error(W.red(`Maestro flows not found: ${i}`)),null):void 0;let r=be.relative(process.cwd(),n);if(!r||r.startsWith("..")||be.isAbsolute(r))return j.error(W.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Nt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await R.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:fa()});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 gr;if(Le.statSync(n).isDirectory())l.addLocalFolder(n,r);else{let c=be.dirname(r);l.addLocalFile(n,c==="."?void 0:c,be.basename(r))}let d=l.toBuffer();return await mr.put(s.data.uploadUrl,d,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),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 j.error(W.red(`Maestro flow upload failed: ${l}`)),null}}async function ba(e,t){try{let i=await R.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(i.data.status!=="success")throw new Error(i.data.message||"Failed to fetch Maestro run");let n=i.data.testRun;return{testRunId:n.testRunId,status:n.status,projectId:e,buildId:n.buildId,platform:n.platform,dashboardUrl:n.dashboardUrl||`${We}/tests/${n.testRunId}`,launchDeferredReason:n.launchDeferredReason,...n.error?{error:n.error}:{}}}catch(i){let n=i.response?.data?.message||i.message||"Unknown error";return j.error(W.red(`Could not fetch Maestro run status: ${n}`)),null}}async function Aa(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 fr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${p.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(zi(t))return null;if(t==="latest")return{kind:"latest"};let i=await ga({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${p.name} build URL:`:"Enter artifact URL:",validate:n=>{let r=String(n||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return zi(i)?null:{kind:t,value:String(i).trim()}}function pr(e,t,i){if(e==null||e==="")return t;let n=Number(e);return!Number.isFinite(n)||n<=0?(j.error(`${i} must be a positive number.`),null):n}function Ia(e){return new Promise(t=>setTimeout(t,e))}function yr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(j.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function _a(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Ji(e.artifactUrl),name:br(e.artifactUrl)};let t=e.buildId||Oa(e.buildUrl);return t?Sr(t,e.platform):e.latest?wa(e):null}async function Sr(e,t){let i=Nt();i.start(`Resolving build ${e}...`);try{let n=await R.get(`/public/builds/${encodeURIComponent(e)}`);if(n.data.status!=="success")throw new Error(n.data.message||"Build lookup failed");let r=t||n.data.build?.platform,o=Da(n.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return i.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||Ji(o.name||o.downloadUrl),name:o.name}}catch(n){i.stop("Could not resolve build artifact");let r=n.response?.data?.message||n.message||"Unknown error";return j.error(W.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function wa(e){let t=Ne(`./${p.configFileName}`),i=e.projectId||t?.projectId,n=String(e.profile||e.buildProfile||"production").toLowerCase();if(!i)return j.error(`No projectId found. Run \`${p.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return j.error("Pass --platform when using --latest with --local."),null;let r=Nt();r.start("Resolving latest build...");try{let o=await R.get(`/builds/${i}`,{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()===n);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${n}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Sr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return j.error(W.red(`Latest build lookup failed: ${s}`)),null}}async function $a(e){let t=e.platform||Ji(e.url);if(!t)return j.error(W.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let i=Le.mkdtempSync(be.join(pa.tmpdir(),"mach-maestro-")),n=e.name||br(e.url)||(t==="android"?"app.apk":"app.zip"),r=be.join(i,n),o=Nt();o.start(`Downloading ${n}...`);try{await Pa(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),j.error(W.red(s.message||"Failed to download artifact")),!1}return t==="android"?va(r):Ra(r,i)}async function Pa(e,t){let i=await mr.get(e,{responseType:"stream"});await ma(i.data,Le.createWriteStream(t))}function va(e){if(!e.endsWith(".apk"))return j.error(W.red("Local Android Maestro runs need an APK artifact.")),!1;j.info(W.dim("Installing APK on local Android device/emulator..."));let t=Wi("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(j.error(W.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(j.error(W.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Ra(e,t){if(e.endsWith(".ipa"))return j.error(W.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let i=e;if(e.endsWith(".zip")){let r=be.join(t,"ios-app");Le.mkdirSync(r,{recursive:!0}),new gr(e).extractAllTo(r,!0);let o=Er(r);if(!o)return j.error(W.red("Could not find a .app bundle inside the downloaded zip.")),!1;i=o}if(!i.endsWith(".app"))return j.error(W.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;j.info(W.dim("Installing app on booted iOS Simulator..."));let n=Wi("xcrun",["simctl","install","booted",i],{stdio:"inherit",env:process.env});return n.error?(j.error(W.red(`xcrun failed to start: ${n.error.message}`)),!1):n.status!==0?(j.error(W.red(`iOS Simulator install failed with exit code ${n.status??1}`)),!1):!0}function Er(e){let t=Le.readdirSync(e,{withFileTypes:!0});for(let i of t){let n=be.join(e,i.name);if(i.isDirectory()&&i.name.endsWith(".app"))return n;if(i.isDirectory()){let r=Er(n);if(r)return r}}return null}function Da(e,t){let i=String(t||"").toLowerCase();return i==="android"?e.find(n=>St(n,".apk")):i==="ios"?e.find(n=>St(n,".app.zip"))||e.find(n=>St(n,".zip")):e.find(n=>St(n,".apk"))||e.find(n=>St(n,".app.zip"))||e.find(n=>St(n,".zip"))}function St(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Ji(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 br(e){if(e)try{return be.basename(new URL(e).pathname)||void 0}catch{return be.basename(e)||void 0}}function Oa(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 Ar(e,t){if(!e.jsonOutput)return;let i=be.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let r=be.dirname(i);r&&r!=="."&&Le.mkdirSync(r,{recursive:!0}),Le.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){j.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Ca(e,t){if(!e.jsonOutput)return;let i=be.resolve(e.jsonOutput),n={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=be.dirname(i);r&&r!=="."&&Le.mkdirSync(r,{recursive:!0}),Le.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){j.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}var Xi=8,ka=6,Pr=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),qi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Lr=e=>new Promise(t=>setTimeout(t,e)),La=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,i)).toFixed(i===0?0:1)} ${t[i]}`},xa=e=>{let t=e.response?.status,i=e.code||"",n=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(`${i} ${n}`):!0},si=async(e,t,i=ka)=>{let n;for(let r=1;r<=i;r++)try{return await t()}catch(o){if(n=o,!xa(o)||r>=i)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";D.warn(C.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${i})`)),await Lr(s)}throw n},Ma=async(e,t,i)=>{let n=_e.basename(e),r=ae.statSync(e).size,o=Math.round(qi/1e3);try{await si(`Upload artifact ${n}`,async()=>{let s=new AbortController,l=ae.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},qi);try{await Tt.put(t,l,{headers:{"Content-Type":i,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:qi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},Pr)}catch(s){throw new Error(`${n} (${La(r)}) failed after ${Pr} upload attempt(s): ${s.message||s}`)}return r},Ua=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},kt=e=>e.credentialId||e.id,Ba=async(e,t)=>{let i=kt(e);if(!i)return e.downloadUrl;let n=await R.get(`/credentials/${i}/download`,{params:{projectId:t,format:"raw"}});return n.data?.status==="success"&&n.data?.downloadUrl?n.data.downloadUrl:e.downloadUrl},xr=async(e,t)=>{let i=e.downloadUrl;for(let n=1;n<=Xi;n++)try{if((!i||n>1)&&(i=await Ba(e,t)),!i)throw new Error(`Credential ${e.name||kt(e)||"unknown"} has no download URL.`);let r=await Tt.get(i,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(n>=Xi||!Ua(r))throw r;let o=Math.min(1500*n*n,15e3);D.warn(C.dim(` - Temporary network error downloading ${e.name}. Retrying... (${n}/${Xi})`)),await Lr(o)}throw new Error(`Failed to download credential ${e.name||kt(e)||"unknown"}.`)},Fa=async(e,t)=>{let i=await xr(e,t);return Buffer.from(i,"base64").toString("utf8")},Ha=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,ja=(e,t,i)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[i]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,vr=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Rr=(e,t)=>{let i=e.filter(n=>n.type==="asc_api_key");if(i.length!==0){if(t){let n=i.find(o=>vr(o)===t);if(n)return n;let r=i.find(o=>vr(o)==="*");if(r)return r}return i[0]}},Ga=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Mr=(e,t,i=[])=>{if(!ae.existsSync(e))return i;let n;try{n=ae.readdirSync(e,{withFileTypes:!0})}catch{return i}for(let r of n){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=_e.join(e,r.name);r.isDirectory()?Mr(o,t,i):r.name===t&&i.push(o)}return i},Ka=(e,t,i)=>{let n=`${i} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(n.includes("development")||n.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(n.includes("staging")||n.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(n.includes("production")||n.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},Va=(e,t)=>{let i=_e.resolve(process.cwd(),ae.existsSync("ios")?"ios":"."),n=Mr(i,"project.pbxproj"),r=[];for(let o of n)try{let l=ae.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:Ka(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},ai=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),li=(e,t)=>{let i=ai(e);return t==="ios"&&(i==="internal"||i==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(i)?"internal":i},Dr=(e,t,i)=>{let n=li(e.distributionType||e.meta?.distributionType,i);return n?n===li(t,i):!0},Or=(e,t,i)=>{let n=li(e.distributionType||e.meta?.distributionType,i),r=li(t,i);return n?n===r?3:i==="android"&&r!=="store"&&n!=="store"?2:0:1},za=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},Wa=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},Ya=(e,t)=>{let i=ai(e.distribution),n=ai(e.iosExportMethod),r=ai(e.environment);return e.platform!=="ios"?i==="store"?"store":"internal":e.developmentClient||e.simulator?"development":n==="app-store"||i==="store"?"store":n==="development"||i==="development"?"development":n==="ad-hoc"||n==="adhoc"||i==="ad-hoc"||i==="adhoc"||i==="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":za(t)?"development":(Wa(t),"adhoc")},Ur=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Cr=(e,t)=>{if(!t)return!0;let i=Ur(e);return!i||i==="*"||i===t},Nr=(e,t)=>{let i=Ur(e);return!t||!i?0:i===t?2:i==="*"?1:-1},Br=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),i=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!i)return;let n=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(n&&i.startsWith(`${n}.`))return i.slice(n.length+1);let r=i.indexOf(".");return r>=0?i.slice(r+1):i}catch{return}},Ja=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let i=e.slice(0,-2);return t.startsWith(`${i}.`)}return!1},Xa=(e,t)=>{if(!t)return!0;let i=Br(e);if(i)return Ja(i,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},ci=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(D.error(C.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 R.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),D.info(C.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){D.error(C.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let t=Zi(),i=e.buildId||Na(),n=e.projectId,r=Date.now(),o=!!n,s=async l=>{if(n)try{await R.patch(`/builds/${n}/${i}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await R.get(`/builds/${n}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await Tt.get(l.data.downloadUrl,{responseType:"stream"}),d=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),c=_e.join(Ta.homedir(),p.workspacesDir,d);ae.mkdirSync(c,{recursive:!0});let u=new Set(["node_modules",`.${p.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(ae.existsSync(c)){let x=ae.readdirSync(c);for(let T of x){if(u.has(T))continue;if(T==="ios"){let h=_e.join(c,"ios");try{let V=ae.readdirSync(h);for(let _ of V)if(!f.has(_))try{ae.rmSync(_e.join(h,_),{recursive:!0,force:!0})}catch{}}catch{}continue}let G=_e.join(c,T);try{ae.rmSync(G,{recursive:!0,force:!0})}catch{}}}let m=_e.join(c,"source.zip"),A=a.data,U=ae.createWriteStream(m);await new Promise((x,T)=>{A.pipe(U),A.on("error",G=>T(G)),U.on("finish",()=>x())}),new $r(m).extractAllTo(c,!0);try{ae.unlinkSync(m)}catch{}process.chdir(c),D.info(C.green(`\u2713 Persistent workspace ready: ${c}`)),D.info(C.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ae.existsSync(_e.join(c,"node_modules"))?"\u2705":"\u274C"}, Pods=${ae.existsSync(_e.join(c,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),n&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=wr("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${C.cyan(i)}`);let a={},d={},c=Ne(`./${p.configFileName}`);if(c){n=c.projectId;let _=e.buildProfile||"production",S=Ze(c,_);!S&&e.buildProfile&&(D.error(`Build profile '${_}' not found in ${p.configFileName}`),process.exit(1));let O=S||{};process.env.MACH_DEBUG&&D.info(C.dim(`Build profile: ${_} | Platform: ${e.platform} | Distribution: ${O.distribution||"store"} | Environment: ${O.environment||_}`)),O.env&&(d=O.env,D.info(C.blue(`Use Build Profile: ${_}`)));let P=e.platform,k=O[P]||{},v=["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 $=L=>L==="androidPackage"?k.androidPackage??k.package??O.androidPackage??O.android?.package:L==="iosBundleIdentifier"?k.iosBundleIdentifier??k.bundleIdentifier??O.iosBundleIdentifier??O.ios?.bundleIdentifier:k[L]!==void 0?k[L]:O[L];for(let L of v){let H=$(L),E=L==="androidPackage"||L==="iosBundleIdentifier";H!==void 0&&(e[L]===void 0||E)&&(e[L]=H)}if(e.platform==="ios"&&!(k.iosBundleIdentifier??k.bundleIdentifier??O.iosBundleIdentifier??O.ios?.bundleIdentifier)){let H=Va(e,_);H&&H!==e.iosBundleIdentifier&&(D.warn(C.yellow(`Detected native iOS bundle identifier ${H}; using it for credential lookup. Set build.${_}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=H)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"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);let M=L=>{if(!L)return L;if(L.startsWith("scripts.")){let H=L.split(".")[1],E=c.scripts?.[H];if(E)return E;D.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&c.scheme&&(e.scheme=c.scheme);let K={...gt(c,p.envPrefix),...gt(O,`${p.envPrefix}PROFILE_`)};a={...a,...d,...K},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&&O.ios?.appleTeamId&&(e.iosTeamId=O.ios.appleTeamId),!e.iosTeamId&&c.submit?.[_]?.ios?.appleTeamId&&(e.iosTeamId=c.submit[_].ios.appleTeamId),!e.iosTeamId&&c.submit?.production?.ios?.appleTeamId&&(D.warn(C.yellow(`Check: Using 'production' Team ID for '${_}' build.`)),e.iosTeamId=c.submit.production.ios.appleTeamId),e.iosTeamId?D.info(C.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(C.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=wr("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let f="1.0.0";try{ae.existsSync("./package.json")&&(f=JSON.parse(ae.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let m=e.buildProfile||"production",A="Internal";e.developmentClient?A="DevelopmentClient":m.toLowerCase().includes("store")||m.toLowerCase()==="production"?A="Store":m.toLowerCase().includes("preview")||m.toLowerCase().includes("staging")?A="Staging":(m.toLowerCase().includes("development")||m.toLowerCase().includes("dev"))&&(A="Development");let U=e.platform==="ios"?"iOS":"Android",N=e.platform==="ios"&&e.simulator?" (Simulator)":"",x=`${U}${N} v${f} (${A})`;if(di(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:f,buildType:A,developmentClient:!!e.developmentClient,summary:x}),n){try{let _=e.buildProfile||"production",S=e.environment||_;D.info(C.blue(`Fetching managed secrets for profile: ${_} (environment: ${S})...`));let P=(await R.get(`/projects/${n}/secrets/export?env=${S}`)).data;P.status==="success"&&P.secrets&&(a={...a,...P.secrets},Object.keys(P.secrets).length>0&&D.info(C.magenta(`\u2713 Injected ${Object.keys(P.secrets).length} secrets from Dashboard.`)))}catch(_){D.warn(`Failed to load managed secrets from Dashboard: ${_.message}`)}try{D.info(C.blue("Fetching managed credentials..."));let _=Ya(e,m),S=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,O=e.platform==="ios"?"bundle":"package";D.info(C.dim(` Credential target: ${O} ${S||"not set"} (${_})`));let P=await R.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:S,distributionType:_}});if(P.data.status==="success"&&P.data.credentials){let k=P.data.credentials;D.info(C.magenta(`\u2713 Found ${k.length} relevant credentials.`));let v=k.filter(E=>e.platform==="ios"&&E.type==="ios_profile"?Dr(E,_,e.platform)?Cr(E,S):!1:e.platform==="android"&&E.type==="android_keystore"?Cr(E,S):!!Dr(E,_,e.platform)).sort((E,le)=>Nr(le,S)*10+Or(le,_,e.platform)-(Nr(E,S)*10+Or(E,_,e.platform)));D.info(C.dim(` Filtered to ${v.length} credentials for distributionType: ${_}`));let $=!1,M=!1,K=!1,L=[];for(let E of v)if(!(E.type==="ios_cert"&&$||E.type==="ios_profile"&&M||E.type==="android_keystore"&&K)&&["ios_cert","ios_profile","android_keystore"].includes(E.type)&&(E.downloadUrl||kt(E)))try{let J=await xr(E,n);if(E.type==="ios_cert"&&!$)a.IOS_DIST_P12=J,E.password?(a.IOS_P12_PASSWORD=E.password,D.info(C.dim(` - Injected ${E.name} as IOS_DIST_P12 with password from credential record`))):D.info(C.dim(` - Injected ${E.name} as IOS_DIST_P12`)),$=!0;else if(E.type==="ios_profile"&&!M){if(!Xa(J,S)){let we=Br(J)||"unknown";throw new Error(`Provisioning profile ${E.name||kt(E)||"unknown"} is for a different bundle ID. Expected ${S}, found ${we}. Upload a ${_} profile for ${S}.`)}a.IOS_PROVISIONING_PROFILE=J,D.info(C.dim(` - Injected ${E.name} as IOS_PROVISIONING_PROFILE`)),M=!0}else if(E.type==="android_keystore"&&!K){a.ANDROID_KEYSTORE_BASE64=J;let we=E.keystorePassword||E.password,se=E.keyPassword||E.keystorePassword||E.password,F=E.alias||E.meta?.alias;if(we)a.ANDROID_STORE_PASSWORD=we,D.info(C.dim(" - Injected keystore password from credential record"));else{let I=["ANDROID_STORE_PASSWORD",...[_==="store"?"PRODUCTION":_==="internal"||_==="adhoc"?"STAGING":"DEVELOPMENT",_.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(z=>`KEYSTORE_PASSWORD_${z}`),"KEYSTORE_PASSWORD"].find(z=>!!a[z]);I&&a[I]&&(a.ANDROID_STORE_PASSWORD=a[I])}if(se?(a.ANDROID_KEY_PASSWORD=se,D.info(C.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",F)a.ANDROID_KEY_ALIAS=F;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(X=>!!a[X]);B&&(a.ANDROID_KEY_ALIAS=a[B])}D.info(C.dim(` - Injected ${E.name} as ANDROID_KEYSTORE_BASE64`)),K=!0}}catch(J){L.push(`${E.name||E.type}: ${J.message}`)}let H=e.platform==="ios"?e.simulator||$&&M:K||!v.some(E=>E.type==="android_keystore");if(L.length>0&&!H)throw new Error(`Credential setup failed:
|
|
1114
|
-
${L.map(E=>`- ${E}`).join(`
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1106
|
+
`));try{let w=X("security find-identity -v -p codesigning",{encoding:"utf-8"});o(y.magenta(`${w}
|
|
1107
|
+
`))}catch(w){o(y.red(`[DIAGNOSTIC] Failed to list identities: ${w.message}
|
|
1108
|
+
`))}}await Ke("xcodebuild",["-exportArchive","-archivePath",P,"-exportPath",N,"-exportOptionsPlist",F],d,m,o,s),a&&await a("validate");let q=ct(N,[".ipa"]);for(let w of q)try{X(`unzip -t "${w}"`,{stdio:"pipe"});let H=ga(w);o&&o(`[IPA VALID] ${$.basename(w)} \u2014 archive integrity OK
|
|
1109
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${H}
|
|
1110
|
+
`)}catch(H){let Z=`IPA validation failed for ${$.basename(w)}: ${H.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${Z}
|
|
1111
|
+
`),new Error(Z)}return q}},Je=e=>{try{let t=$.join(process.cwd(),p.configFileName);if(g.existsSync(t)){let i=JSON.parse(g.readFileSync(t,"utf-8"));if(e==="android"&&i.android?.package)return i.android.package;if(e==="ios"&&i.ios?.bundleIdentifier)return i.ios.bundleIdentifier}if(e==="android"){let i=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let n of i)if(g.existsSync(n)){let o=g.readFileSync(n,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let i=$.resolve(process.cwd(),g.existsSync("ios")?"ios":"."),n=ct(i,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));n.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of n){let a=g.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=ct(i,[".xcodeproj"]);if(r.length>0){let s=$.join(r[0],"project.pbxproj");if(g.existsSync(s)){let a=g.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(g.existsSync(s)){let a=g.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},Sa=()=>{try{return X("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Se.homedir(),i=[$.join(t,"Library/Android/sdk/emulator/emulator"),$.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let n of i)if(g.existsSync(n))return n}return"emulator"},ba=async(e,t)=>{let i=ri();try{if(X("adb devices").toString().split(`
|
|
1112
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){E.warn(y.yellow("No Android devices or emulators found."));let s=Sa(),l=[];try{l=X(`${s} -list-avds`).toString().split(`
|
|
1113
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await zi({message:"Select an emulator to launch:",options:l.map(u=>({value:u,label:u}))});if(oi(a))return;i.start(`Launching emulator ${a}...`),dr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let d=0,c=!1;for(;d<60;){try{if(X("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw i.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");i.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}i.start("Installing APK on device..."),await Ke("adb",["install","-r",e],process.cwd(),{},t),i.stop("Installation complete.");let o=Je("android");if(o){E.info(y.blue(`\u{1F680} Launching ${o}...`));try{X(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1114
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?X(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):X(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{E.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(n){i.stop("Installation failed."),E.error(y.red(`Failed to install APK: ${n.message}`))}},Ea=async(e,t,i)=>{let n=ri();try{if(!X("xcrun simctl list devices booted").toString().includes("(Booted)")){E.warn(y.yellow("No iOS Simulator is currently booted."));let o=X("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(u=>{s[u].forEach(f=>{f.isAvailable&&l.push({...f,runtime:u})})});let a=await zi({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(oi(a))return;n.start(`Booting ${a}...`),X(`xcrun simctl boot ${a}`),X(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let d=0,c=!1;for(;d<30;){try{if(X("xcrun simctl list devices booted").toString().includes(a)){c=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),d++}if(!c)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await Ke("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),E.info(y.blue(`\u{1F680} Launching ${t}...`)),await Ke("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),E.error(y.red(`Failed to install on Simulator: ${r.message}`))}},Aa=async(e,t,i)=>{let n=ri();n.start("Scanning for connected iOS devices...");try{let r=X("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 n.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){n.stop();let a=await zi({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(oi(a))return;l=a,n.start(`Installing on ${l}...`)}else n.message(`Installing on ${s[0].model.name}...`);await Ke("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},i),n.stop("Installation complete."),E.info(y.blue(`\u{1F680} Launching ${t}...`)),await Ke("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},i)}catch(r){n.stop("Installation failed."),E.error(y.red(`Failed to install on device: ${r.message}`)),E.info(y.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Le from"fs";import Ia from"os";import Ee from"path";import{spawnSync as qi}from"child_process";import{randomUUID as _a}from"crypto";import{pipeline as wa}from"stream/promises";import{isCancel as Ji,log as j,select as yr,spinner as Nt,text as $a}from"@clack/prompts";import Sr from"axios";import W from"chalk";import br from"adm-zip";async function Er(e){if(e.local){let i=await Ra(e);i&&(process.exitCode=i.exitCode);return}let t=await Xi(e);if(t&&(j.success(W.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&j.warn(W.yellow(t.launchDeferredReason)),t.dashboardUrl&&j.info(W.dim("View test run: ")+W.white.underline(t.dashboardUrl)),e.wait)){let i=await va(e,t);i&&(process.exitCode=i.status==="passed"?0:1)}}var Pa=new Set(["passed","failed","cancelled","interrupted"]);async function Ra(e){let t=e.maestroFlows||".maestro",i=Ar(e.maestroRetries);if(i===null)return null;let n=Ee.resolve(t);if(!Le.existsSync(n))return j.error(W.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Ta(e);if(r?.url){if(!await La(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&&j.warn(W.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)),s.push(t);let l=i+1,a=1;for(let u=1;u<=l;u+=1){j.info(W.dim(`Running local Maestro attempt ${u}/${l}...`));let f=qi("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(f.error){let m=f.error.message||"Failed to run Maestro";j.error(W.red(`Local Maestro failed to start: ${m}`)),j.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),a=1;break}if(a=typeof f.status=="number"?f.status:1,a===0)break}let d=a===0?"passed":"failed",c={status:d,exitCode:a,attempts:l,flows:t,platform:o};return Ha(e,c),d==="passed"?j.success(W.green("Local Maestro run passed")):j.error(W.red(`Local Maestro run failed with exit code ${a}`)),c}async function Xi(e){let t=Ne(`./${p.configFileName}`),i=e.projectId||t?.projectId,n=String(e.profile||e.buildProfile||"production").toLowerCase();if(!i)return j.error(`No projectId found. Run \`${p.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await yr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(Ji(d))return null;r=d}let o=await Ca(e);if(!o)return null;if(o.kind==="latest"&&!r)return j.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return j.error("Pass --platform when using --artifact-url."),null;let s=Ar(e.maestroRetries);if(s===null)return null;let l=await Da(e,i);if(l===null)return null;let a=Nt();e.quiet||a.start("Queuing Maestro run...");try{let d=await v.post("/tests/maestro",{projectId:i,platform:r,profile:n,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:l,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let c=d.data.testRun,u={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${We}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return $r(e,u),e.quiet||a.stop("Maestro run queued"),u}catch(d){e.quiet||a.stop("Could not queue Maestro run");let c=d.response?.data?.message||d.message||"Unknown error";return j.error(W.red(`Maestro queue failed: ${c}`)),null}}async function va(e,t){let i=hr(e.waitTimeout,60,"--wait-timeout"),n=hr(e.waitInterval,15,"--wait-interval");if(i===null||n===null)return null;let r=i*60*1e3,o=Math.max(5,n)*1e3,s=Date.now(),l=t.status||"queued";for(j.info(W.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Oa(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,j.info(W.dim(`Maestro status: ${l}`))),Pa.has(String(a.status)))return $r(e,a),a.status==="passed"?j.success(W.green(`Maestro run passed: ${a.testRunId}`)):(j.error(W.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&j.error(W.red(String(a.error)))),a;await Na(o)}return j.error(W.red(`Timed out waiting for Maestro run ${t.testRunId} after ${i} minute(s).`)),{...t,status:"timeout"}}async function Da(e,t){if(e.maestroUseBuildSource)return;let i=e.maestroFlows||".maestro",n=Ee.resolve(i);if(!Le.existsSync(n))return e.maestroFlows?(j.error(W.red(`Maestro flows not found: ${i}`)),null):void 0;let r=Ee.relative(process.cwd(),n);if(!r||r.startsWith("..")||Ee.isAbsolute(r))return j.error(W.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Nt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await v.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:_a()});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 br;if(Le.statSync(n).isDirectory())l.addLocalFolder(n,r);else{let c=Ee.dirname(r);l.addLocalFile(n,c==="."?void 0:c,Ee.basename(r))}let d=l.toBuffer();return await Sr.put(s.data.uploadUrl,d,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),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 j.error(W.red(`Maestro flow upload failed: ${l}`)),null}}async function Oa(e,t){try{let i=await v.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(i.data.status!=="success")throw new Error(i.data.message||"Failed to fetch Maestro run");let n=i.data.testRun;return{testRunId:n.testRunId,status:n.status,projectId:e,buildId:n.buildId,platform:n.platform,dashboardUrl:n.dashboardUrl||`${We}/tests/${n.testRunId}`,launchDeferredReason:n.launchDeferredReason,...n.error?{error:n.error}:{}}}catch(i){let n=i.response?.data?.message||i.message||"Unknown error";return j.error(W.red(`Could not fetch Maestro run status: ${n}`)),null}}async function Ca(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 yr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${p.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(Ji(t))return null;if(t==="latest")return{kind:"latest"};let i=await $a({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${p.name} build URL:`:"Enter artifact URL:",validate:n=>{let r=String(n||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return Ji(i)?null:{kind:t,value:String(i).trim()}}function hr(e,t,i){if(e==null||e==="")return t;let n=Number(e);return!Number.isFinite(n)||n<=0?(j.error(`${i} must be a positive number.`),null):n}function Na(e){return new Promise(t=>setTimeout(t,e))}function Ar(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(j.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Ta(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||Zi(e.artifactUrl),name:wr(e.artifactUrl)};let t=e.buildId||Fa(e.buildUrl);return t?Ir(t,e.platform):e.latest?ka(e):null}async function Ir(e,t){let i=Nt();i.start(`Resolving build ${e}...`);try{let n=await v.get(`/public/builds/${encodeURIComponent(e)}`);if(n.data.status!=="success")throw new Error(n.data.message||"Build lookup failed");let r=t||n.data.build?.platform,o=Ba(n.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return i.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||Zi(o.name||o.downloadUrl),name:o.name}}catch(n){i.stop("Could not resolve build artifact");let r=n.response?.data?.message||n.message||"Unknown error";return j.error(W.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function ka(e){let t=Ne(`./${p.configFileName}`),i=e.projectId||t?.projectId,n=String(e.profile||e.buildProfile||"production").toLowerCase();if(!i)return j.error(`No projectId found. Run \`${p.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return j.error("Pass --platform when using --latest with --local."),null;let r=Nt();r.start("Resolving latest build...");try{let o=await v.get(`/builds/${i}`,{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()===n);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${n}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Ir(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return j.error(W.red(`Latest build lookup failed: ${s}`)),null}}async function La(e){let t=e.platform||Zi(e.url);if(!t)return j.error(W.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let i=Le.mkdtempSync(Ee.join(Ia.tmpdir(),"mach-maestro-")),n=e.name||wr(e.url)||(t==="android"?"app.apk":"app.zip"),r=Ee.join(i,n),o=Nt();o.start(`Downloading ${n}...`);try{await xa(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),j.error(W.red(s.message||"Failed to download artifact")),!1}return t==="android"?Ma(r):Ua(r,i)}async function xa(e,t){let i=await Sr.get(e,{responseType:"stream"});await wa(i.data,Le.createWriteStream(t))}function Ma(e){if(!e.endsWith(".apk"))return j.error(W.red("Local Android Maestro runs need an APK artifact.")),!1;j.info(W.dim("Installing APK on local Android device/emulator..."));let t=qi("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(j.error(W.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(j.error(W.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Ua(e,t){if(e.endsWith(".ipa"))return j.error(W.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let i=e;if(e.endsWith(".zip")){let r=Ee.join(t,"ios-app");Le.mkdirSync(r,{recursive:!0}),new br(e).extractAllTo(r,!0);let o=_r(r);if(!o)return j.error(W.red("Could not find a .app bundle inside the downloaded zip.")),!1;i=o}if(!i.endsWith(".app"))return j.error(W.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;j.info(W.dim("Installing app on booted iOS Simulator..."));let n=qi("xcrun",["simctl","install","booted",i],{stdio:"inherit",env:process.env});return n.error?(j.error(W.red(`xcrun failed to start: ${n.error.message}`)),!1):n.status!==0?(j.error(W.red(`iOS Simulator install failed with exit code ${n.status??1}`)),!1):!0}function _r(e){let t=Le.readdirSync(e,{withFileTypes:!0});for(let i of t){let n=Ee.join(e,i.name);if(i.isDirectory()&&i.name.endsWith(".app"))return n;if(i.isDirectory()){let r=_r(n);if(r)return r}}return null}function Ba(e,t){let i=String(t||"").toLowerCase();return i==="android"?e.find(n=>St(n,".apk")):i==="ios"?e.find(n=>St(n,".app.zip"))||e.find(n=>St(n,".zip")):e.find(n=>St(n,".apk"))||e.find(n=>St(n,".app.zip"))||e.find(n=>St(n,".zip"))}function St(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function Zi(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 wr(e){if(e)try{return Ee.basename(new URL(e).pathname)||void 0}catch{return Ee.basename(e)||void 0}}function Fa(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 $r(e,t){if(!e.jsonOutput)return;let i=Ee.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let r=Ee.dirname(i);r&&r!=="."&&Le.mkdirSync(r,{recursive:!0}),Le.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){j.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Ha(e,t){if(!e.jsonOutput)return;let i=Ee.resolve(e.jsonOutput),n={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Ee.dirname(i);r&&r!=="."&&Le.mkdirSync(r,{recursive:!0}),Le.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){j.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as tt,text as Tt,select as rn,isCancel as et,cancel as on,log as Or}from"@clack/prompts";import Q from"chalk";import ie from"fs";import be from"path";import{spawn as ja,spawnSync as dt}from"child_process";import Cr from"axios";import pt from"os";import ln from"crypto";var Ga=5e3,Ka=12,Nr=100,Qi=24,Pr=8e3,Va={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},za=e=>e?.type==="google_service_account",ai=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,Tr=e=>e.submitArgs||process.argv.slice(3).join(" ");async function li(e){let t=tt(),i=we(),n=Wa(e);if(!n){process.exitCode=1;return}let r=e.projectId||n.projectId,o=e.profile||e.buildProfile||"production";if(!r){se(`${p.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}n.projectId=r,ue(Q.dim(`Submit for project: ${n.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let I=await rn({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(et(I)){on("Operation cancelled");return}s=I}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){se(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?cl(n,o,e):null;if(s==="ios"&&!e.local&&!l){await Ya(n,o,e);return}let a=e.submitId,d=!!(e.local&&a),c=a||null,u=async(I,M={})=>{c&&await Za(r,c,{status:I,...M})},f=s==="android"?sl(n,o):void 0,m=s==="ios"?ll(n,o):void 0,b,U,k,L=!1;try{s==="android"&&(b=e.track||n.submit?.[o]?.android?.track||n.submit?.production?.android?.track||"internal",U=dl(n,o,e.releaseStatus),k=pl(n,o,e.rollout),L=fl(n,o,e.changesNotSentForReview),ml(U,k))}catch(I){se(I.message),process.exitCode=1;return}if(s==="android"&&!d&&(c=await Ja(n,r,s,o,e,{packageName:f,track:b,releaseStatus:U,rollout:k,changesNotSentForReview:L}),!c)){se("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await u("running",{platform:s,profile:o,packageName:f,track:b,releaseStatus:U,rollout:k,startTime:Date.now(),...d?el():{}});let T=null,G=null;try{G=await gl(r,s,e,i?.token),T=G?.filePath||null}catch(I){await u("failed",{error:`Failed to resolve submission artifact: ${I.message}`,endTime:Date.now()}),se(`Failed to resolve submission artifact: ${I.message}`),process.exitCode=1;return}if(!T){let I=Sl(s,e);await u("failed",{error:I,endTime:Date.now()}),se(I),process.exitCode=1;return}await u("running",{buildId:G?.buildId,artifactName:G?.artifactName,artifactSource:G?.source}),ue(`Using artifact: ${Q.green(be.basename(T))} `),t.start("Fetching submission credentials from Dashboard...");let h;try{let M=(await v.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),se("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await u("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let K=M.filter(za),x=s==="ios"?M.filter(z=>z.type==="asc_api_key"):al(K,f);if(x.length===0){if(t.stop("Credentials missing"),se(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let z=K.map(ai).filter(Boolean).join(", ");z&&ue(`Found Google Play service credential(s) for: ${z}`),ue(`Use '${p.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else ue(`Use '${p.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await u("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(h=il(x,e.credentialId),!h&&s==="ios"&&m&&(h=nl(x,m)),h||x.length===1)h=h||x[0],t.stop(`Using: ${h.name}`),s==="android"&&ai(h)==="*"&&ue(Q.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),rl()){let S=x.map(ne=>`${ne.name||"credential"} (${ne.credentialId||ne.id||"no-id"})`).join(", ");se(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${S}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let z=await rn({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:x.map(S=>({value:S.credentialId,label:S.name,hint:`${S.keyId?`ID: ${S.keyId}`:""} ${S.issuerId?`(Issuer: ${S.issuerId.substring(0,8)}...)`:""}`}))});if(et(z)){on("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}h=x.find(S=>S.credentialId===z),ue(`Using selected: ${Q.green(h.name)}`)}}catch(I){t.stop("Failed to fetch credentials"),se(`API Error: ${I.message} `),await u("failed",{error:`Failed to fetch credentials: ${I.message}`,endTime:Date.now()}),process.exitCode=1;return}let V=ie.mkdtempSync(be.join(pt.tmpdir(),`${p.nameLower}-submit-`)),_=h.keyId||h.meta?.keyId,A=h.issuerId||h.meta?.issuerId,C=h.type==="asc_api_key"?`AuthKey_${_}.p8`:"service-account.json",P=be.join(V,C);t.start("Downloading secure key...");try{let I=await v.get(`/credentials/${h.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(I.data.status!=="success"||!I.data.downloadUrl)throw new Error("Failed to get secure download URL");let M=await Cr.get(I.data.downloadUrl,{responseType:"arraybuffer"});ie.writeFileSync(P,Buffer.from(M.data)),t.stop("Key downloaded to secure temp storage")}catch(I){t.stop("Download failed"),se(`Failed to download key: ${I.message}`);try{ie.rmSync(V,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${I.message}`,endTime:Date.now()}),process.exitCode=1;return}ue(Q.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let N=!1,R;try{if(s==="ios"){if(!_){let M=await Tt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:K=>K.length>0?void 0:"Key ID is required"});if(et(M)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}_=M}if(!A||A==="undefined"){let M=await Tt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:K=>K.length>0?void 0:"Issuer ID is required"});if(et(M)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}A=M}ue(`Using ASC Key ID: ${_}`),ue(`Using ASC Issuer ID: ${A}`);let I=l?await Al(T,P,A,_,m,l):await El(T,P,A,_,m);an(`${s==="ios"?"App Store":"Google Play"} submission successful!`),N=!0}else R=await Pl(T,P,b||"internal",f,U||"completed",k,L,o),an("Google Play submission successful!"),N=!0}catch(I){se(`Submission failed: ${I.message}`),await u("failed",{error:I.message,endTime:Date.now()}),bt(e,{status:"failed",projectId:r,submitId:c,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,error:I.message,dashboardUrl:c?ut(c,r):void 0}),process.exitCode=1}finally{N&&(await u("success",{endTime:Date.now(),versionCode:R?.versionCode,track:b,releaseStatus:U}),bt(e,{status:"success",projectId:r,submitId:c,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,versionCode:R?.versionCode,track:b,releaseStatus:U,dashboardUrl:c?ut(c,r):void 0})),Hl(V),T&&T.includes(`${p.nameLower}-artifact-`)}}function Wa(e){let t=`./${p.configFileName}`;if(ie.existsSync(t))try{return JSON.parse(ie.readFileSync(t,"utf-8"))}catch(i){return se(`Failed to read ${p.configFileName}: ${i.message}`),null}return e.projectId?{projectId:e.projectId}:(se(`No ${p.configFileName} found. Run \`${p.nameLower} init\` or \`${p.nameLower} link\` first.`),null)}async function Ya(e,t,i){let n=i.projectId||e.projectId;if(!n){se(`${p.configFileName} is missing projectId.`),process.exitCode=1;return}let r=i.submitId||ln.randomUUID(),o=!!i.latest||!i.buildId,s=qa({...i,latest:o,profile:t,projectId:n,submitId:r}),l={projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,credentialId:i.credentialId,status:"pending",source:"cli",submitArgs:Tr(i),runnerArgs:s,runnerCommand:[p.nameLower,"submit",...s].map(ol).join(" "),appName:e.name,startTime:Date.now()},a=tt();a.start("Queuing iOS submit on macOS runner...");try{let d=await v.post("/submissions",l),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||ut(r,n);a.stop("iOS submit queued"),ue(`Submission ID: ${Q.cyan(r)}`),ue(`Dashboard: ${Q.blue.underline(u)}`),bt(i,{status:"pending",projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,dashboardUrl:u}),await Xa(n,r,i)}catch(d){a.stop("Could not queue iOS submit"),se(tl(d)),process.exitCode=1}}async function Ja(e,t,i,n,r,o={}){let s=r.submitId||ln.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:Tr(r),appName:e.name,startTime:Date.now(),...o};try{let d=await v.post("/submissions",a),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||c.dashboardUrl||ut(s,t);return ue(`Submission ID: ${Q.cyan(s)}`),ue(`Dashboard: ${Q.blue.underline(u)}`),bt(r,{status:"running",projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,dashboardUrl:u}),s}catch(d){let c=d.response?.data?.message||d.response?.data?.error||d.message;return ue(Q.yellow(`Could not create submission tracking record: ${c}`)),null}}function qa(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.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(i=>i!=null&&i!=="")}async function Xa(e,t,i){let n=tt(),r=0,o=0;for(i.quiet||n.start("Waiting for iOS submit runner...");;)try{let s=await v.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 c=o;c<d.length;c++){let u=d[c];u&&console.log(Q.dim(String(u)))}if(o=d.length,["success","completed","succeeded"].includes(a)){i.quiet||n.stop("iOS submit completed"),an("App Store submission successful!"),bt(i,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||ut(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){i.quiet||n.stop("iOS submit failed");let c=l?.error||l?.message||"Unknown iOS submit failure.";se(c),bt(i,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,error:c,dashboardUrl:l?.dashboardUrl||ut(t,e)}),process.exitCode=1;return}i.quiet||n.message(`iOS submit ${a}...`),await sn(Ga)}catch(s){if(r++,r>=Ka){i.quiet||n.stop("Lost connection to iOS submit status"),se(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await sn(Math.min(2e3*r,15e3))}}async function Za(e,t,i){let n;for(let r=1;r<=3;r++)try{await v.patch(`/submissions/${e}/${t}`,i);return}catch(o){if(n=o,r>=3||!Qa(o))break;await sn(1e3*r)}Or.warn(Q.dim(`Could not report submission status: ${n?.message||n}`))}function Qa(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function el(){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 tl(e){let t=e.response?.status,i=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(`
|
|
1115
|
+
`):i||e.message||String(e)}function ut(e,t){if(!e)return We;let i=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${i}`}function bt(e,t){if(!e.jsonOutput)return;let i=be.resolve(e.jsonOutput),n={...t,url:t.url||t.dashboardUrl||ut(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=be.dirname(i);r&&r!=="."&&ie.mkdirSync(r,{recursive:!0}),ie.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){Or.warn(Q.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function il(e,t){return t&&e.find(i=>i.credentialId===t||i.id===t||i.keyId===t||i.meta?.keyId===t)||null}function nl(e,t){let i=e.filter(n=>[n.bundleId,n.bundleIdentifier,n.appIdentifier,n.meta?.bundleId,n.meta?.bundleIdentifier,n.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return i.length===1?i[0]:null}function rl(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function sn(e){return new Promise(t=>setTimeout(t,e))}function ol(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function sl(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let i=Ln(e,t);if(i)return i;let n=be.join(process.cwd(),"app.json");if(ie.existsSync(n))try{return JSON.parse(ie.readFileSync(n,"utf-8")).expo?.android?.package}catch{}let r=be.join(process.cwd(),"app.config.json");if(ie.existsSync(r))try{let o=JSON.parse(ie.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function al(e,t){let i=e.filter(o=>ai(o)===t);if(i.length>0)return i;let n=e.filter(o=>{let s=ai(o);return!s||s==="*"});return e.length>0&&e.length===n.length?n:[]}function ll(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:xn(e,t)}function cl(e,t,i){let n=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=i.sshHost||n.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:i.sshUser||n.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:i.sshKey||n.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function dl(e,t,i){let n=i||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return ul(n)}function ul(e){let t=Va[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function pl(e,t,i){let n=i??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(n==null||n==="")return;let r=Number(n);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${n}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function fl(e,t,i){let n=i??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 n===!0||n==="true"||n==="1"}function ml(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 gl(e,t,i,n){let r=i.buildId?"id":i.latest?"latest":null;if(!r){let s=await rn({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${p.name})`},{value:"id",label:`Input Build ID (${p.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(et(s))return on("Operation cancelled"),null;r=s}if(r==="local"){let s=await Tt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!ie.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 et(s)?null:{filePath:s,source:"local"}}let o=tt();if(r==="latest"){let s=i.profile||i.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await v.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(),c=h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success",u=h=>d?[h.buildProfile,h.profile,h.profileName,h.buildType].filter(Boolean).some(V=>String(V).toLowerCase()===d):!0,f=a.filter(h=>c(h)&&u(h)),m=f.find(h=>h.buildType?.toLowerCase()==="store"||h.distribution?.toLowerCase()==="store")||f[0],b=a.some(h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success");if(!m)return o.stop("No suitable build found"),se(s&&b?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${m.buildId}`);let U=m.artifacts||[];if(U.length===0||U.every(h=>!(h.url||h.downloadUrl)))try{let h=await v.get(`/builds/${e}/${m.buildId}/artifacts`);h.data.status==="success"&&h.data.artifacts?.length>0?(U=h.data.artifacts.map(V=>({...V,url:V.url||V.downloadUrl})),console.log(Q.cyan(` [RECOVERY] Fetched ${U.length} artifact(s) with download URLs.`))):console.log(Q.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(h){console.log(Q.red(` [RECOVERY] /artifacts fetch failed: ${h.message}`))}let L=t==="ios",T=U.find(h=>{let V=(h.type||"").toLowerCase(),_=(h.name||"").toLowerCase();if(console.log(Q.dim(` - Checking: ${h.name} (Type: ${h.type}, HasLink: ${!!(h.url||h.downloadUrl)})`)),V)return V===(L?"ipa":"aab");let A=L?".ipa":".aab",C=(h.url||h.downloadUrl||"").toLowerCase();return _.endsWith(A)||C.includes(A)});if(!T||!(T.url||T.downloadUrl))return se("Build found but artifact URL is missing."),null;let G=T.url||T.downloadUrl;return{filePath:await en(G,L?"ios":"android"),buildId:m.buildId,artifactName:T.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),se(`API Error: ${l.message}`),null}}if(r==="id"){let s=i.buildId||await Tt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(et(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let m=await v.get(`/builds/${e}/${l}`);m.data.status==="success"&&(a=m.data.build)}catch(m){m.response?.status!==404&&console.log(Q.dim(` [RECOVERY] Project build lookup skipped: ${m.message}`))}if(!a){let m=await v.get(`/build/${l}`);if(m.data.status!=="success")throw new Error(m.data.message);a=m.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let d=t==="ios",c=si(a.artifacts);hl(c)||(c=await bl(e,l,c));let u=yl(c,t);if(!u)throw new Error(`No ${d?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a store-submission artifact.`);let f=u.url||u.downloadUrl;if(!f)throw new Error(`Artifact ${u.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 en(f,d?"ios":"android"),buildId:a.buildId||l,artifactName:u.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Tt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return et(s)?null:{filePath:await en(s,t),source:"url"}}return null}function si(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function hl(e){return e.some(t=>!!(t.url||t.downloadUrl))}function yl(e,t){let i=t==="ios",n=i?"ipa":"aab",r=i?".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===n:l.endsWith(r)||a.includes(r)})||null}function Sl(e,t){let i=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${i} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let n=t.profile||t.buildProfile;return`No latest successful ${e}${n?` ${n}`:""} build has a downloadable ${i} artifact.`}return`No downloadable ${i} artifact was selected for submission.`}async function bl(e,t,i){try{let n=await v.get(`/builds/${e}/${t}/artifacts`);if(n.data.status==="success"&&n.data.artifacts?.length>0){let r=si(n.data.artifacts);return console.log(Q.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(n){console.log(Q.dim(` [RECOVERY] Project artifact lookup skipped: ${n.message}`))}try{let n=await v.get(`/public/builds/${t}`);if(n.data.status==="success"&&n.data.artifacts?.length>0){let r=si(n.data.artifacts);return console.log(Q.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(n){console.log(Q.dim(` [RECOVERY] Public artifact lookup skipped: ${n.message}`))}return si(i)}async function en(e,t,i=3){let n=tt();n.start("Downloading artifact...");let r=ie.mkdtempSync(be.join(pt.tmpdir(),`${p.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=be.join(r,o);for(let l=1;l<=i;l++)try{l>1&&(n.message(`Downloading artifact (Retry ${l}/${i})...`),await new Promise(c=>setTimeout(c,2e3*l)));let a=ie.createWriteStream(s),d=await Cr({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((c,u)=>{d.data.pipe(a);let f=!1;d.data.on("error",m=>{f||(f=!0,a.close(),u(m))}),a.on("finish",()=>{f||c()}),a.on("error",m=>{f||(f=!0,u(m))})}),n.stop("Download complete"),s}catch(a){if(l===i)throw n.stop("Download failed"),a}throw new Error("Download failed after retries")}async function El(e,t,i,n,r){let o=tt();if(r&&ue(`Bundle ID: ${Q.green(r)}`),!i||!n)throw se(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=kr(t,i,n),l=vl();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let c=Ol(),u=ja(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});u.stdout?.on("data",f=>c.append(f,process.stdout)),u.stderr?.on("data",f=>c.append(f,process.stderr)),u.on("close",f=>{if(c.flush(),f!==0){o.stop("Pilot failed");try{ie.unlinkSync(s)}catch{}d(Cl(f,c.lines()))}else{o.stop("IPA uploaded to TestFlight");try{ie.unlinkSync(s)}catch{}a({})}}),u.on("error",f=>{c.flush();try{ie.unlinkSync(s)}catch{}o.stop("Pilot execution error");let m=Bl(f);m.logs=c.lines(),d(m)})})}async function Al(e,t,i,n,r,o){let s=tt();if(r&&ue(`Bundle ID: ${Q.green(r)}`),!i||!n)throw se(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=kr(t,i,n),a=`${o.sshUser}@${o.sshHost}`,d=Il(o),c=_l(o),u="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),u=wl("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)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..."),tn("scp",[...c,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),tn("scp",[...c,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),f=be.join(pt.tmpdir(),`${p.nameLower}-ios-submit-${Date.now()}.sh`),ie.writeFileSync(f,$l(u)),tn("scp",[...c,f,`${a}:${u}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let m=`chmod +x ${kt(`${u}/submit.sh`)} && bash ${kt(`${u}/submit.sh`)}`,b=dt("ssh",[...d,m],{stdio:"inherit"});if(b.error)throw cn("ssh",b.error);if(b.status!==0)throw new Error(`Remote iOS submit failed with exit code ${b.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(m){throw s.stop("Remote iOS submit failed"),m}finally{try{ie.unlinkSync(l)}catch{}if(f)try{ie.unlinkSync(f)}catch{}if(u)try{dt("ssh",[...d,`rm -rf ${kt(u)}`],{stdio:"ignore"})}catch{}}}function kr(e,t,i){let n=ie.readFileSync(e,"utf8"),r;try{r=ln.createPrivateKey(n).export({type:"pkcs8",format:"pem"})}catch{ue("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1116
|
+
${(n.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1117
|
+
`)}
|
|
1118
|
+
-----END PRIVATE KEY-----`}let o=be.join(pt.tmpdir(),`api_key_${i}_${Date.now()}.json`),s={key_id:i,issuer_id:t,key:r,in_house:!1};return ie.writeFileSync(o,JSON.stringify(s,null,2)),o}function Il(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 _l(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function wl(e,t){let i=dt(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(i.error)throw cn(e,i.error);if(i.status!==0)throw new Error(`${e} failed with exit code ${i.status}.`);return i.stdout||""}function tn(e,t,i){let n=dt(e,t,{stdio:"inherit"});if(n.error)throw cn(e,n.error);if(n.status!==0)throw new Error(`${i} failed with exit code ${n.status}.`)}function cn(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 kt(e){return`'${e.replace(/'/g,"'\\''")}'`}function $l(e){let t=kt(`${e}/app.ipa`),i=kt(`${e}/api_key.json`);return`#!/bin/bash
|
|
1119
|
+
set -euo pipefail
|
|
1120
|
+
|
|
1121
|
+
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
1122
|
+
export FASTLANE_SKIP_UPDATE_CHECK=1
|
|
1123
|
+
export FASTLANE_HIDE_CHANGELOG=1
|
|
1124
|
+
export CI="\${CI:-1}"
|
|
1125
|
+
|
|
1126
|
+
if ! command -v fastlane >/dev/null 2>&1; then
|
|
1127
|
+
if ! command -v gem >/dev/null 2>&1; then
|
|
1128
|
+
echo "fastlane was not found and gem is unavailable on the remote macOS runner."
|
|
1129
|
+
exit 127
|
|
1130
|
+
fi
|
|
1131
|
+
|
|
1132
|
+
FASTLANE_GEM_HOME="\${FASTLANE_GEM_HOME:-$HOME/.local/share/fastlane/3.4.0}"
|
|
1133
|
+
FASTLANE_BIN_DIR="$FASTLANE_GEM_HOME/bin"
|
|
1134
|
+
mkdir -p "$FASTLANE_BIN_DIR"
|
|
1135
|
+
export GEM_HOME="$FASTLANE_GEM_HOME"
|
|
1136
|
+
export GEM_PATH="$FASTLANE_GEM_HOME:\${GEM_PATH:-}"
|
|
1137
|
+
export PATH="$FASTLANE_BIN_DIR:$PATH"
|
|
1138
|
+
gem install fastlane -NV --install-dir "$FASTLANE_GEM_HOME" --bindir "$FASTLANE_BIN_DIR"
|
|
1139
|
+
fi
|
|
1140
|
+
|
|
1141
|
+
fastlane pilot upload \\
|
|
1142
|
+
--ipa ${t} \\
|
|
1143
|
+
--api_key_path ${i} \\
|
|
1144
|
+
--skip_submission true \\
|
|
1145
|
+
--skip_waiting_for_build_processing true
|
|
1146
|
+
`}async function Pl(e,t,i="internal",n,r="completed",o,s=!1,l="production"){let a=tt();if(!n||n==="*")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 ${i} track with ${r} release status${d}...`);try{let c=JSON.parse(ie.readFileSync(t,"utf-8"));Rl(c);let u=await tr({packageName:n,serviceAccount:c,aabPath:e,track:i,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${i} track (versionCode ${u.versionCode})`),u}catch(c){throw a.stop("Google Play upload failed"),new Error(Fl(c,i,n,l))}}function Rl(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function nn(){let e=process.env.HOME||pt.homedir(),t=process.env.FASTLANE_GEM_HOME||be.join(e,".local/share/fastlane/3.4.0"),i=[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",be.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:i,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 vl(){let e=nn(),t=Rr(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Dl(e);let i=Rr(nn());if(i)return i}return{command:"fastlane",env:nn()}}function Rr(e){let t=process.env.HOME||pt.homedir(),i=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",be.join(process.env.FASTLANE_GEM_HOME||be.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let n of i){if(n.includes("/")&&!ie.existsSync(n))continue;if(!dt(n,["--version"],{env:e,stdio:"ignore"}).error)return{command:n,env:e}}return null}function Dl(e){let t=dt("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let i=process.env.HOME||pt.homedir(),n=process.env.FASTLANE_GEM_HOME||be.join(i,".local/share/fastlane/3.4.0"),r=be.join(n,"bin");ie.mkdirSync(r,{recursive:!0}),ue(Q.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=dt("gem",["install","fastlane","-NV","--install-dir",n,"--bindir",r],{env:{...e,GEM_HOME:n,GEM_PATH:[n,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&ue(Q.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Ol(e=Nr){let t=[],i="",n=r=>{let o=xr(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),i+=s;let l=i.split(/\r?\n/);i=l.pop()||"";for(let a of l)n(a)},flush(){i.trim()&&n(i),i=""},lines(){return t.slice()}}}function Cl(e,t){let i=new Error(Nl(e,t));return i.logs=Lr(t),i.exitCode=e,i}function Nl(e,t){let i=`fastlane pilot failed with exit code ${e??"unknown"}.`,n=Tl(t);return n.length===0?i:`${i}
|
|
1147
|
+
|
|
1148
|
+
Fastlane output:
|
|
1149
|
+
${n.join(`
|
|
1150
|
+
`)}`}function Tl(e){let t=Lr(e);if(t.length===0)return[];let i=vr(t.filter(Ll)),n=kl(t);if(n)return[n,...Dr(i,Qi-1,Pr)];let r=i.length>0?i:t.slice(-Qi);return Dr(vr(r),Qi,Pr)}function kl(e){let t=e.join(`
|
|
1151
|
+
`);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 Ll(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 vr(e){let t=new Set,i=[];for(let n of e){let r=n.trim();!r||t.has(r)||(t.add(r),i.push(n))}return i}function Dr(e,t,i){let n=[],r=0;for(let o=e.length-1;o>=0&&n.length<t;o--){let s=e[o],l=r+s.length+1;if(l>i&&n.length>0)break;n.unshift(s.length>i?`${s.slice(0,i-18)}... [truncated]`:s),r=l}return n}function Lr(e){if(!Array.isArray(e))return[];let t=[];for(let i of e){let n=String(i).split(/\r?\n/);for(let r of n){let o=xr(r);o&&t.push(o)}}return t.slice(-Nr)}function xr(e){return Ml(xl(e).trimEnd()).trim()}function xl(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 Ml(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[i,n]of Object.entries(process.env))!n||n.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(i)&&(t=t.replace(new RegExp(Ul(n),"g"),"[REDACTED]"));return t}function Ul(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bl(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(`
|
|
1152
|
+
`))}function Fl(e,t,i,n="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: ${i||"unknown"} | Track: ${t}`,`Retry with: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1153
|
+
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${i||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1154
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1155
|
+
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${i||"unknown"} | Track: ${t}`,`Retry with: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t} --release-status draft`].join(`
|
|
1156
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${p.nameLower} build --platform android --profile ${n} --auto-version`,`Then: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t}`].join(`
|
|
1157
|
+
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${p.nameLower} build --platform android --profile ${n} --auto-version`].join(`
|
|
1158
|
+
`);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 Hl(e){try{ie.existsSync(e)&&ie.rmSync(e,{recursive:!0,force:!0})}catch{}}function se(e){console.log(Q.red(`\u274C ${e}`))}function ue(e){console.log(Q.gray(`\u2022 ${e}`))}function an(e){console.log(Q.green(`\u2713 ${e}`))}var dn=8,Kl=6,Hr=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),un=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),qr=e=>new Promise(t=>setTimeout(t,e)),Vl=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,i)).toFixed(i===0?0:1)} ${t[i]}`},zl=e=>{let t=e.response?.status,i=e.code||"",n=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(`${i} ${n}`):!0},ci=async(e,t,i=Kl)=>{let n;for(let r=1;r<=i;r++)try{return await t()}catch(o){if(n=o,!zl(o)||r>=i)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";D.warn(O.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${i})`)),await qr(s)}throw n},Wl=async(e,t,i)=>{let n=_e.basename(e),r=ae.statSync(e).size,o=Math.round(un/1e3);try{await ci(`Upload artifact ${n}`,async()=>{let s=new AbortController,l=ae.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},un);try{await Lt.put(t,l,{headers:{"Content-Type":i,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:un,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},Hr)}catch(s){throw new Error(`${n} (${Vl(r)}) failed after ${Hr} upload attempt(s): ${s.message||s}`)}return r},Yl=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},xt=e=>e.credentialId||e.id,Jl=async(e,t)=>{let i=xt(e);if(!i)return e.downloadUrl;let n=await v.get(`/credentials/${i}/download`,{params:{projectId:t,format:"raw"}});return n.data?.status==="success"&&n.data?.downloadUrl?n.data.downloadUrl:e.downloadUrl},Xr=async(e,t)=>{let i=e.downloadUrl;for(let n=1;n<=dn;n++)try{if((!i||n>1)&&(i=await Jl(e,t)),!i)throw new Error(`Credential ${e.name||xt(e)||"unknown"} has no download URL.`);let r=await Lt.get(i,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(n>=dn||!Yl(r))throw r;let o=Math.min(1500*n*n,15e3);D.warn(O.dim(` - Temporary network error downloading ${e.name}. Retrying... (${n}/${dn})`)),await qr(o)}throw new Error(`Failed to download credential ${e.name||xt(e)||"unknown"}.`)},ql=async(e,t)=>{let i=await Xr(e,t);return Buffer.from(i,"base64").toString("utf8")},Xl=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Zl=(e,t,i)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[i]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,jr=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Gr=(e,t)=>{let i=e.filter(n=>n.type==="asc_api_key");if(i.length!==0){if(t){let n=i.find(o=>jr(o)===t);if(n)return n;let r=i.find(o=>jr(o)==="*");if(r)return r}return i[0]}},Ql=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Zr=(e,t,i=[])=>{if(!ae.existsSync(e))return i;let n;try{n=ae.readdirSync(e,{withFileTypes:!0})}catch{return i}for(let r of n){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=_e.join(e,r.name);r.isDirectory()?Zr(o,t,i):r.name===t&&i.push(o)}return i},ec=(e,t,i)=>{let n=`${i} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(n.includes("development")||n.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(n.includes("staging")||n.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(n.includes("production")||n.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},tc=(e,t)=>{let i=_e.resolve(process.cwd(),ae.existsSync("ios")?"ios":"."),n=Zr(i,"project.pbxproj"),r=[];for(let o of n)try{let l=ae.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:ec(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},di=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),ui=(e,t)=>{let i=di(e);return t==="ios"&&(i==="internal"||i==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(i)?"internal":i},Kr=(e,t,i)=>{let n=ui(e.distributionType||e.meta?.distributionType,i);return n?n===ui(t,i):!0},Vr=(e,t,i)=>{let n=ui(e.distributionType||e.meta?.distributionType,i),r=ui(t,i);return n?n===r?3:i==="android"&&r!=="store"&&n!=="store"?2:0:1},ic=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},nc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},rc=(e,t)=>{let i=di(e.distribution),n=di(e.iosExportMethod),r=di(e.environment);return e.platform!=="ios"?i==="store"?"store":"internal":e.developmentClient||e.simulator?"development":n==="app-store"||i==="store"?"store":n==="development"||i==="development"?"development":n==="ad-hoc"||n==="adhoc"||i==="ad-hoc"||i==="adhoc"||i==="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":ic(t)?"development":(nc(t),"adhoc")},Qr=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,zr=(e,t)=>{if(!t)return!0;let i=Qr(e);return!i||i==="*"||i===t},Wr=(e,t)=>{let i=Qr(e);return!t||!i?0:i===t?2:i==="*"?1:-1},eo=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),i=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!i)return;let n=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(n&&i.startsWith(`${n}.`))return i.slice(n.length+1);let r=i.indexOf(".");return r>=0?i.slice(r+1):i}catch{return}},oc=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let i=e.slice(0,-2);return t.startsWith(`${i}.`)}return!1},sc=(e,t)=>{if(!t)return!0;let i=eo(e);if(i)return oc(i,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},pi=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(D.error(O.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 v.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),D.info(O.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){D.error(O.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(D.error(O.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&D.warn(O.yellow("--auto-submit is ignored during --dry-run."));let t=fn(),i=e.buildId||jl(),n=e.projectId,r=Date.now(),o=!!n,s=async l=>{if(n)try{await v.patch(`/builds/${n}/${i}`,{status:"failed",error:l})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let l=await v.get(`/builds/${n}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await Lt.get(l.data.downloadUrl,{responseType:"stream"}),d=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),c=_e.join(Gl.homedir(),p.workspacesDir,d);ae.mkdirSync(c,{recursive:!0});let u=new Set(["node_modules",`.${p.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(ae.existsSync(c)){let L=ae.readdirSync(c);for(let T of L){if(u.has(T))continue;if(T==="ios"){let h=_e.join(c,"ios");try{let V=ae.readdirSync(h);for(let _ of V)if(!f.has(_))try{ae.rmSync(_e.join(h,_),{recursive:!0,force:!0})}catch{}}catch{}continue}let G=_e.join(c,T);try{ae.rmSync(G,{recursive:!0,force:!0})}catch{}}}let m=_e.join(c,"source.zip"),b=a.data,U=ae.createWriteStream(m);await new Promise((L,T)=>{b.pipe(U),b.on("error",G=>T(G)),U.on("finish",()=>L())}),new Fr(m).extractAllTo(c,!0);try{ae.unlinkSync(m)}catch{}process.chdir(c),D.info(O.green(`\u2713 Persistent workspace ready: ${c}`)),D.info(O.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ae.existsSync(_e.join(c,"node_modules"))?"\u2705":"\u274C"}, Pods=${ae.existsSync(_e.join(c,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),n&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=Br("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${O.cyan(i)}`);let a={},d={},c=Ne(`./${p.configFileName}`);if(c){n=c.projectId;let _=e.buildProfile||"production",A=Ze(c,_);!A&&e.buildProfile&&(D.error(`Build profile '${_}' not found in ${p.configFileName}`),process.exit(1));let C=A||{};process.env.MACH_DEBUG&&D.info(O.dim(`Build profile: ${_} | Platform: ${e.platform} | Distribution: ${C.distribution||"store"} | Environment: ${C.environment||_}`)),C.env&&(d=C.env,D.info(O.blue(`Use Build Profile: ${_}`)));let P=e.platform,N=C[P]||{},R=["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 I=x=>x==="androidPackage"?N.androidPackage??N.package??C.androidPackage??C.android?.package:x==="iosBundleIdentifier"?N.iosBundleIdentifier??N.bundleIdentifier??C.iosBundleIdentifier??C.ios?.bundleIdentifier:N[x]!==void 0?N[x]:C[x];for(let x of R){let z=I(x),S=x==="androidPackage"||x==="iosBundleIdentifier";z!==void 0&&(e[x]===void 0||S)&&(e[x]=z)}if(e.platform==="ios"&&!(N.iosBundleIdentifier??N.bundleIdentifier??C.iosBundleIdentifier??C.ios?.bundleIdentifier)){let z=tc(e,_);z&&z!==e.iosBundleIdentifier&&(D.warn(O.yellow(`Detected native iOS bundle identifier ${z}; using it for credential lookup. Set build.${_}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=z)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"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);let M=x=>{if(!x)return x;if(x.startsWith("scripts.")){let z=x.split(".")[1],S=c.scripts?.[z];if(S)return S;D.warn(`Script reference not found: ${x}`)}return x};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&c.scheme&&(e.scheme=c.scheme);let K={...gt(c,p.envPrefix),...gt(C,`${p.envPrefix}PROFILE_`)};a={...a,...d,...K},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&&C.ios?.appleTeamId&&(e.iosTeamId=C.ios.appleTeamId),!e.iosTeamId&&c.submit?.[_]?.ios?.appleTeamId&&(e.iosTeamId=c.submit[_].ios.appleTeamId),!e.iosTeamId&&c.submit?.production?.ios?.appleTeamId&&(D.warn(O.yellow(`Check: Using 'production' Team ID for '${_}' build.`)),e.iosTeamId=c.submit.production.ios.appleTeamId),e.iosTeamId?D.info(O.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(O.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=Br("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let f="1.0.0";try{ae.existsSync("./package.json")&&(f=JSON.parse(ae.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let m=e.buildProfile||"production",b="Internal";e.developmentClient?b="DevelopmentClient":m.toLowerCase().includes("store")||m.toLowerCase()==="production"?b="Store":m.toLowerCase().includes("preview")||m.toLowerCase().includes("staging")?b="Staging":(m.toLowerCase().includes("development")||m.toLowerCase().includes("dev"))&&(b="Development");let U=e.platform==="ios"?"iOS":"Android",k=e.platform==="ios"&&e.simulator?" (Simulator)":"",L=`${U}${k} v${f} (${b})`;if(fi(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:f,buildType:b,developmentClient:!!e.developmentClient,summary:L}),n){try{let _=e.buildProfile||"production",A=e.environment||_;D.info(O.blue(`Fetching managed secrets for profile: ${_} (environment: ${A})...`));let P=(await v.get(`/projects/${n}/secrets/export?env=${A}`)).data;P.status==="success"&&P.secrets&&(a={...a,...P.secrets},Object.keys(P.secrets).length>0&&D.info(O.magenta(`\u2713 Injected ${Object.keys(P.secrets).length} secrets from Dashboard.`)))}catch(_){D.warn(`Failed to load managed secrets from Dashboard: ${_.message}`)}try{D.info(O.blue("Fetching managed credentials..."));let _=rc(e,m),A=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,C=e.platform==="ios"?"bundle":"package";D.info(O.dim(` Credential target: ${C} ${A||"not set"} (${_})`));let P=await v.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:A,distributionType:_}});if(P.data.status==="success"&&P.data.credentials){let N=P.data.credentials;D.info(O.magenta(`\u2713 Found ${N.length} relevant credentials.`));let R=N.filter(S=>e.platform==="ios"&&S.type==="ios_profile"?Kr(S,_,e.platform)?zr(S,A):!1:e.platform==="android"&&S.type==="android_keystore"?zr(S,A):!!Kr(S,_,e.platform)).sort((S,ne)=>Wr(ne,A)*10+Vr(ne,_,e.platform)-(Wr(S,A)*10+Vr(S,_,e.platform)));D.info(O.dim(` Filtered to ${R.length} credentials for distributionType: ${_}`));let I=!1,M=!1,K=!1,x=[];for(let S of R)if(!(S.type==="ios_cert"&&I||S.type==="ios_profile"&&M||S.type==="android_keystore"&&K)&&["ios_cert","ios_profile","android_keystore"].includes(S.type)&&(S.downloadUrl||xt(S)))try{let J=await Xr(S,n);if(S.type==="ios_cert"&&!I)a.IOS_DIST_P12=J,S.password?(a.IOS_P12_PASSWORD=S.password,D.info(O.dim(` - Injected ${S.name} as IOS_DIST_P12 with password from credential record`))):D.info(O.dim(` - Injected ${S.name} as IOS_DIST_P12`)),I=!0;else if(S.type==="ios_profile"&&!M){if(!sc(J,A)){let Re=eo(J)||"unknown";throw new Error(`Provisioning profile ${S.name||xt(S)||"unknown"} is for a different bundle ID. Expected ${A}, found ${Re}. Upload a ${_} profile for ${A}.`)}a.IOS_PROVISIONING_PROFILE=J,D.info(O.dim(` - Injected ${S.name} as IOS_PROVISIONING_PROFILE`)),M=!0}else if(S.type==="android_keystore"&&!K){a.ANDROID_KEYSTORE_BASE64=J;let Re=S.keystorePassword||S.password,de=S.keyPassword||S.keystorePassword||S.password,F=S.alias||S.meta?.alias;if(Re)a.ANDROID_STORE_PASSWORD=Re,D.info(O.dim(" - Injected keystore password from credential record"));else{let w=["ANDROID_STORE_PASSWORD",...[_==="store"?"PRODUCTION":_==="internal"||_==="adhoc"?"STAGING":"DEVELOPMENT",_.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(H=>`KEYSTORE_PASSWORD_${H}`),"KEYSTORE_PASSWORD"].find(H=>!!a[H]);w&&a[w]&&(a.ANDROID_STORE_PASSWORD=a[w])}if(de?(a.ANDROID_KEY_PASSWORD=de,D.info(O.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",F)a.ANDROID_KEY_ALIAS=F;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(q=>!!a[q]);B&&(a.ANDROID_KEY_ALIAS=a[B])}D.info(O.dim(` - Injected ${S.name} as ANDROID_KEYSTORE_BASE64`)),K=!0}}catch(J){x.push(`${S.name||S.type}: ${J.message}`)}let z=e.platform==="ios"?e.simulator||I&&M:K||!R.some(S=>S.type==="android_keystore");if(x.length>0&&!z)throw new Error(`Credential setup failed:
|
|
1159
|
+
${x.map(S=>`- ${S}`).join(`
|
|
1160
|
+
`)}`);x.length>0&&D.warn(O.dim(` Skipped ${x.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let N=e.buildProfile||"production",R=Ze(c,N)||{},I=Xl(c,R),M=Ql(I),K=e.distribution!==void 0?e.distribution==="store":b==="Store",x=I===void 0&&K,z=e.autoVersion||M&&K||x,S=e.autoVersion||M&&K;if(M&&!K&&D.info(O.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),z){let ne=e.iosBundleIdentifier||c.ios?.bundleIdentifier||c.expo?.ios?.bundleIdentifier,J=Zl(c,R,N),Re=P.data.credentials||[],de=Gr(Re,ne);if(!de&&(S||x)){let F=await v.get(`/credentials/${n}`);de=Gr(F.data.credentials||[],ne)}if(de){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let F=de.keyId||de.meta?.keyId,B=de.issuerId||de.meta?.issuerId;if(!F||!B)throw new Error("App Store Connect credential is missing keyId or issuerId.");let q=await ql(de,n),w=await sr({keyId:F,issuerId:B,privateKey:q,ascAppId:J,bundleId:ne}),H=/^\d+$/.test(w.latestBuildNumber);H?(a.BUILD_NUMBER=w.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=w.nextBuildNumber,a.CURRENT_PROJECT_VERSION=w.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(H?`\u2713 Latest iOS buildNumber on App Store Connect: ${O.green(w.latestBuildNumber)} (Mach will assign >= ${w.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${O.green(w.nextBuildNumber)} (Latest on App Store Connect: ${w.latestBuildNumber})`)}catch(F){t.stop("iOS buildNumber lookup failed");let B=F.response?.data?.error?.message||F.message;if(S)throw new Error(`Auto-versioning failed: ${B}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);D.warn(O.yellow(`Could not check App Store Connect buildNumber: ${B}. Falling back to Mach counter.`))}}else if(S)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${p.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let N=e.buildProfile||"production",R=Ze(c,N)||{},K=((R.android||{}).versionCode??R.androidVersionCode??c.android?.versionCode??c.expo?.android?.versionCode)==="auto",x=e.distribution!==void 0?e.distribution==="store":b==="Store",z=e.autoVersion||K&&x;if(K&&!z&&D.info(O.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),z){t.start("Resolving latest versionCode from Google Play...");try{let S=e.androidPackage||c.android?.package||c.expo?.android?.package||c.name,ne=(P.data.credentials||[]).find(q=>q.type==="google_service_account"&&(!q.bundleId||q.bundleId===S));if(!ne){let w=((await v.get(`/credentials/${n}`)).data.credentials||[]).filter(H=>H.type==="google_service_account");if(ne=w.find(H=>H.type==="google_service_account"&&H.bundleId===S),!ne&&w.length>0){let H=w.map(Z=>Z.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${S}. Found service credential(s) for: ${H}.`)}}if(!ne)throw new Error(`Google Service Account not found for package ${S}. Upload it under this package in Dashboard or run '${p.nameLower} credentials:service --platform android --package-name ${S}'.`);let J=await v.get(`/credentials/${ne.credentialId}/download`,{params:{projectId:n,format:"raw"}});if(J.data.status!=="success"||!J.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let de=(await Lt.get(J.data.downloadUrl,{headers:{Connection:"close"}})).data,F=await er(S,de);if(F==null)throw new Error("Could not retrieve any version information from Google Play.");let B=F+1;a.ANDROID_VERSION_CODE=B.toString(),t.stop(`\u2713 Resolved versionCode: ${O.green(B)} (Latest on Play Store: ${F})`)}catch(S){t.stop("Version resolution failed");let ne=S.response?.data?.error?.message||S.message;throw new Error(`Auto-versioning failed: ${ne}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let N=!!a.IOS_DIST_P12,R=!!a.IOS_PROVISIONING_PROFILE;if(!N||!R){let I=[...N?[]:["Distribution Certificate"],...R?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${I}. Expected ${_} credentials for ${A||"the selected bundle ID"}. Run \`${p.nameLower} credentials --platform ios --profile ${m}\` and select ${A||"the correct bundle ID"}.`);D.error(O.red(`Missing iOS credentials: ${I}`)),e.quiet&&process.exit(1);let M=e.yes||await Mr({message:"Would you like to generate these credentials now?",initialValue:!0});if(M&&!Ur(M))return await vt({platform:"ios",profile:m}),e.quiet||D.info(O.green("\u2713 Credentials setup complete! Restarting build phase...")),pi(e);e.quiet||D.info(O.yellow(`Run \`${p.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)){D.error(O.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let R=e.yes||await Mr({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(R&&!Ur(R))return await vt({platform:"android",profile:m}),e.quiet||D.info(O.green("\u2713 Android Keystore setup complete! Restarting build phase...")),pi(e);e.quiet||D.info(O.yellow(`Run \`${p.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(_){(String(_.message||"").startsWith("Credential download failed")||String(_.message||"").startsWith("Credential setup failed")||String(_.message||"").startsWith("Missing iOS credentials")||String(_.message||"").startsWith("Auto-versioning failed"))&&(D.error(O.red(_.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&(D.error(O.red(`Failed to resolve iOS credentials: ${_.message}`)),process.exit(1)),D.warn(`Failed to resolve credentials: ${_.message}`)}}let T=!!(e.local&&e.buildId),G=!!(e.local||e.sshHost),h=!G&&!T;if(T){D.info(O.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let _=await Yi({...e,interactive:!1},i,a,n,{branch:u,version:f,summary:L,buildType:b});await V(_),process.exit(0)}async function V(_){let A=async C=>{if(n)try{await ci("Report failed build status",()=>v.patch(`/builds/${n}/${i}`,{status:"failed",error:C,endTime:Date.now()}),3)}catch(P){D.warn(O.yellow(`Could not report failed build status: ${P.message}`))}};if(n&&_.length>0){let C=fn(),P=[];e.quiet||C.start("Uploading artifacts to Dashboard...");try{for(let N of _){let R=_e.basename(N),I=ae.statSync(N).size,M=_e.extname(R).toLowerCase(),K="application/octet-stream",x=await ci(`Create artifact upload URL for ${R}`,()=>v.post(`/builds/${n}/${i}/artifact-upload-url`,{fileName:R,fileType:K}));if(x.data.status!=="success")throw new Error(`Failed to get upload URL for ${R}`);await Wl(N,x.data.uploadUrl,K),P.push({name:R,url:x.data.downloadUrl,size:I,type:M.substring(1)})}e.quiet||C.stop("Artifacts uploaded.")}catch(N){e.quiet||C.stop("Failed to upload artifacts.");let R=`Artifact upload failed: ${N.message}`;throw D.error(O.red(R)),await A(R),new Error(R)}if(n&&P.length>0)try{D.info(O.cyan(`
|
|
1161
|
+
\u{1F517} Download Links:`));for(let N of P)D.info(O.dim(` - ${N.name}: `)+O.blue.underline(N.url));await ci("Finalize build in dashboard",()=>v.patch(`/builds/${n}/${i}`,{status:"success",artifacts:P,endTime:Date.now()})),fi(e,{status:"success",projectId:n,buildId:i,platform:e.platform,profile:m,branch:u,version:f,buildType:b,developmentClient:!!e.developmentClient,summary:L,artifacts:P}),D.success(O.green(`
|
|
1162
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!T&&await Yr(n,i,e,m),e.autoSubmit&&!T&&await pn(n,i,e,m)}catch(N){let R=`Build artifact uploaded but dashboard finalization failed: ${N.message}`;throw D.error(O.red(`
|
|
1163
|
+
${R}`)),await A(R),new Error(R)}}else if(n){let C="Build completed but produced no uploadable artifacts.";throw D.error(O.red(C)),await A(C),new Error(C)}}if(G){if(D.info(O.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),n&&!o){let _=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"building",branch:u,version:f,summary:L,startTime:r,buildType:b,buildProfile:m,buildArgs:_,simulator:!!e.simulator,developmentClient:!!e.developmentClient})}if(e.sshHost&&e.platform==="ios")await Zn(e,i,a,n),e.autoSubmit&&await pn(n,i,e,m);else{let _=await Yi({...e,interactive:!!e.local},i,a,n,{branch:u,version:f,summary:L,buildType:b});await V(_)}return}if(h&&(D.info(O.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let _=await v.post("/builds/source-upload-url",{projectId:n,buildId:i});if(_.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let A=new Fr,C=ae.readdirSync("."),P=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${p.nameLower}_cli`];for(let I of C){if(P.includes(I))continue;ae.statSync(I).isDirectory()?A.addLocalFolder(I,I):A.addLocalFile(I)}let N=A.toBuffer();e.quiet||t.message(`Uploading source (${(N.length/1024/1024).toFixed(1)} MB)...`);let R=!1;for(let I=1;I<=3;I++)try{await Lt.put(_.data.uploadUrl,N,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),R=!0;break}catch(M){if(I<3)t.message(`Upload attempt ${I} failed (${M.code||M.message}), retrying...`),await new Promise(K=>setTimeout(K,2e3*I));else throw M}if(e.quiet||t.stop("Source uploaded"),n){let I=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"pending",branch:u,version:f,summary:L,startTime:r,buildType:b,buildProfile:m,buildArgs:I,simulator:!!e.simulator,developmentClient:!!e.developmentClient}),D.info(O.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Jn(e,i,a,n,e.preBuild),e.quiet||D.info(O.cyan("\u{1F4E1} Connecting to build stream...")),await lc(n,i,e),e.maestro&&await Yr(n,i,e,m),e.autoSubmit&&await pn(n,i,e,m);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."),n&&!e.local&&await s(a),D.error(O.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function Yr(e,t,i,n){D.info(O.cyan(`
|
|
1164
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await Xi({projectId:e,buildId:t,platform:i.platform,profile:n,maestroFlows:i.maestroFlows,maestroDevice:i.maestroDevice,maestroRetries:i.maestroRetries,maestroRecord:i.maestroRecord,maestroUseBuildSource:i.maestroUseBuildSource,quiet:i.quiet})}async function pn(e,t,i,n){if(!e){D.error(O.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}D.info(O.cyan(`
|
|
1165
|
+
Auto-submit: submitting the successful build...`));try{await li({platform:i.platform,profile:n,buildProfile:n,buildId:t,projectId:e,yes:i.yes,quiet:i.quiet,track:i.submitTrack,releaseStatus:i.submitReleaseStatus,rollout:i.submitRollout,changesNotSentForReview:i.submitChangesNotSentForReview,credentialId:i.submitCredentialId,jsonOutput:i.submitJsonOutput,submitArgs:ac(i,t,n)})}catch(r){D.error(O.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function ac(e,t,i){let n=["--platform",e.platform,"--profile",i,"--build-id",t];return e.submitTrack&&n.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&n.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&n.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&n.push("--changes-not-sent-for-review"),e.submitCredentialId&&n.push("--credential-id",e.submitCredentialId),e.submitJsonOutput&&n.push("--json-output",e.submitJsonOutput),n.join(" ")}function Jr(e){return`${We}/build/${e}`}function fi(e,t){if(!e.jsonOutput)return;let i=_e.resolve(e.jsonOutput),n={...t,url:t.url||Jr(t.buildId),dashboardUrl:t.dashboardUrl||Jr(t.buildId),updatedAt:new Date().toISOString()};try{let r=_e.dirname(i);r&&r!=="."&&ae.mkdirSync(r,{recursive:!0}),ae.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){D.warn(O.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function lc(e,t,i){let n=fn(),r="pending",o=0,s=0;for(i.quiet||n.start("Connecting to build stream...");;){try{let a=(await v.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")i.quiet||n.message("Build in progress...");else if(r==="failed")i.quiet||n.stop("Build failed."),fi(i,{status:"failed",projectId:e,buildId:t,platform:i.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),D.error(O.red(`
|
|
1166
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){i.quiet||n.stop("Build successful!"),fi(i,{status:r,projectId:e,buildId:t,platform:i.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),D.success(O.green(`
|
|
1167
|
+
\u2713 Build completed successfully!`));try{i.quiet||(D.info(O.magenta(`
|
|
1168
|
+
\u{1F4F1} Installation Hub:`)),D.info(O.dim(" - View & Install Build: ")+O.white.underline(`${We}/build/${t}`)))}catch{}return}else if(r!=="pending"){i.quiet||n.stop(`Build status: ${r}`);return}}try{let c=(await v.get(`/builds/${e}/${t}/logs`)).data;if(c&&typeof c=="string"&&!i.quiet){let u=c.split(`
|
|
1169
|
+
`);if(u.length>o){for(let f=o;f<u.length;f++)u[f].trim()&&console.log(O.dim(` ${u[f]}`));o=u.length}}}catch{}s=0}catch{s++,s>10&&(n.stop("Connection lost."),D.error(O.red(`
|
|
1170
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Si from"http";import*as oo from"net";import{execFile as cc,execFileSync as bi,execSync as ft,spawn as to}from"child_process";import le from"chalk";import{log as Y}from"@clack/prompts";import dc from"axios";import pe from"fs";import xe from"os";import ee from"path";var qe=7070,Ut=`http://127.0.0.1:${qe}`,At="com.radhya.mach.agent",Et="Mach Agent",It=`${At}.service`,uc=5e3,pc=3e3,mi=null,gi=null,Me=()=>ee.join(xe.homedir(),p.configDir),so=()=>ee.join(xe.homedir(),"Library","LaunchAgents"),hi=()=>ee.join(so(),`${At}.plist`),ao=()=>ee.join(xe.homedir(),".config","systemd","user"),gn=()=>ee.join(ao(),It),hn=()=>ee.join(Me(),"agent.cmd");function yn(){return`gui/${process.getuid?.()||Number(ft("id -u").toString().trim())}`}function lo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Mt(e){return`<string>${lo(e)}</string>`}function Sn(){let e=process.argv[1]?pe.realpathSync(process.argv[1]):"";if(!e||!pe.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function bn(){let e=co(),t=process.platform==="win32"?[process.env.SystemRoot?ee.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],i={HOME:xe.homedir(),PATH:[process.env.PATH,...e.flatMap(n=>[ee.join(n,"platform-tools"),ee.join(n,"emulator"),ee.join(n,"cmdline-tools","latest","bin"),ee.join(n,"tools","bin")]),...t].filter(Boolean).join(ee.delimiter)};for(let n of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[n]&&(i[n]=process.env[n]);return i}function co(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(ee.join(xe.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(ee.join(xe.homedir(),"Android","Sdk"),ee.join(xe.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,i=process.env.USERPROFILE||xe.homedir();e.push(t?ee.join(t,"Android","Sdk"):void 0,ee.join(i,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function fc(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function uo(e,t){let i=fc(e);for(let n of co()){let r=ee.join(n,t,i);if(pe.existsSync(r))return r}return i}function po(){return uo("adb","platform-tools")}function fo(){return uo("emulator","emulator")}function mn(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function mc(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");pe.mkdirSync(Me(),{recursive:!0}),pe.mkdirSync(ao(),{recursive:!0});let e=Sn(),t=bn(),i=Object.entries(t).map(([r,o])=>`Environment=${mn(`${r}=${o}`)}`).join(`
|
|
1125
1171
|
`),n=`[Unit]
|
|
1126
1172
|
Description=Mach local device agent
|
|
1127
1173
|
After=default.target
|
|
1128
1174
|
|
|
1129
1175
|
[Service]
|
|
1130
1176
|
Type=simple
|
|
1131
|
-
ExecStart=${e.map(
|
|
1132
|
-
WorkingDirectory=${
|
|
1177
|
+
ExecStart=${e.map(mn).join(" ")}
|
|
1178
|
+
WorkingDirectory=${mn(xe.homedir())}
|
|
1133
1179
|
${i}
|
|
1134
1180
|
Restart=on-failure
|
|
1135
1181
|
RestartSec=5
|
|
@@ -1138,20 +1184,20 @@ StandardError=append:%h/${p.configDir}/agent.error.log
|
|
|
1138
1184
|
|
|
1139
1185
|
[Install]
|
|
1140
1186
|
WantedBy=default.target
|
|
1141
|
-
`;return
|
|
1187
|
+
`;return pe.writeFileSync(gn(),n),gn()}function nt(e,t={}){try{return bi("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(i){if(t.ignoreError)return!1;throw i}}function gc(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");pe.mkdirSync(Me(),{recursive:!0});let e=bn(),[t,i,...n]=Sn(),r=ee.join(Me(),"agent.log"),o=ee.join(Me(),"agent.error.log"),s=Object.entries(e).map(([d,c])=>`set "${d}=${c}"`).join(`\r
|
|
1142
1188
|
`),l=n.map(d=>`"${d.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1143
1189
|
${s}\r
|
|
1144
1190
|
cd /d "${xe.homedir()}"\r
|
|
1145
1191
|
"${t}" "${i}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1146
|
-
`;return
|
|
1147
|
-
${
|
|
1148
|
-
`),o=e.map(l=>` ${
|
|
1192
|
+
`;return pe.writeFileSync(hn(),a),hn()}function Bt(e,t={}){try{return bi("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(i){if(t.ignoreError)return!1;throw i}}function hc(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");pe.mkdirSync(Me(),{recursive:!0}),pe.mkdirSync(so(),{recursive:!0});let e=Sn(),t=bn(),i=ee.join(Me(),"agent.log"),n=ee.join(Me(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${lo(l)}</key>
|
|
1193
|
+
${Mt(a)}`).join(`
|
|
1194
|
+
`),o=e.map(l=>` ${Mt(l)}`).join(`
|
|
1149
1195
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1150
1196
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1151
1197
|
<plist version="1.0">
|
|
1152
1198
|
<dict>
|
|
1153
1199
|
<key>Label</key>
|
|
1154
|
-
${
|
|
1200
|
+
${Mt(At)}
|
|
1155
1201
|
<key>ProgramArguments</key>
|
|
1156
1202
|
<array>
|
|
1157
1203
|
${o}
|
|
@@ -1163,65 +1209,26 @@ ${r}
|
|
|
1163
1209
|
<key>RunAtLoad</key>
|
|
1164
1210
|
<true/>
|
|
1165
1211
|
<key>StandardOutPath</key>
|
|
1166
|
-
${
|
|
1212
|
+
${Mt(i)}
|
|
1167
1213
|
<key>StandardErrorPath</key>
|
|
1168
|
-
${
|
|
1214
|
+
${Mt(n)}
|
|
1169
1215
|
</dict>
|
|
1170
1216
|
</plist>
|
|
1171
|
-
`;return
|
|
1172
|
-
`).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let n=i.split(/\s+/);if(n.length<2||n[1]!=="device")return;let r=n[0],o=i.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:i.trim()})})}catch{}try{let i=(await
|
|
1173
|
-
`).filter(r=>!!r.trim()),n=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{n||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Sl(){if(process.platform!=="darwin")return[];try{let e=await mi("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),i=[];return Object.entries(t.devices||{}).forEach(([n,r])=>{r.forEach(o=>{o.isAvailable&&i.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${o.name} (${n})`})})}),i}catch{return[]}}async function El(){if(process.platform!=="darwin")return[];try{let e=await mi("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(i=>{let n=i.connectionProperties?.transportType;return n==="wired"||n==="localNetwork"}).map(i=>{let n=i.connectionProperties?.transportType,r=i.deviceProperties?.name||"iPhone";return{id:i.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${i.model?.name||i.hardwareModel||""}) - ${n}`}})}catch{return[]}}async function bl(){let[e,t,i]=await Promise.all([yl(),Sl(),El()]);return[...e,...t,...i]}async function Al(){let e=Date.now();return ui&&e-ui.updatedAt<tl?ui.targets:(pi||(pi=bl().then(t=>(ui={targets:t,updatedAt:Date.now()},t)).finally(()=>{pi=null})),pi)}async function Gr(e){let t=[];for await(let i of e)t.push(Buffer.isBuffer(i)?i:Buffer.from(i));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Il(e,t){let i=await Qa({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=ue.createWriteStream(t);i.data.pipe(n),await new Promise((r,o)=>{n.on("finish",r),n.on("error",o)})}async function _l(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=ue.mkdtempSync(Q.join(xe.tmpdir(),`${Xe}-install-`)),s=Q.join(o,n==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Il(t,s),n==="android"){hi(Xr(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");dt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=dt(`find ${JSON.stringify(Q.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=dt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{dt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{dt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{ue.rmSync(o,{recursive:!0,force:!0})}}function wl(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 dt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Fr("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Fr(qr(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function $l(){process.platform!=="darwin"&&Y.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=gi.createServer((n,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"),n.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(n.url||"/",`http://localhost:${Xe}`);if(n.method==="GET"&&o.pathname==="/local/devices"){Al().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(n.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:Xe,platform:process.platform}));return}if(n.method==="POST"&&o.pathname==="/install-local"){t(n,r);return}if(n.method==="POST"&&o.pathname==="/local/boot"){i(n,r);return}r.writeHead(404),r.end()}),t=async(n,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Gr(n);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await _l(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"}))}},i=async(n,r)=>{try{let{id:o,platform:s}=await Gr(n),l=wl(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(Xe,"127.0.0.1",()=>{Y.success(ce.green(`Local device agent running on http://localhost:${Xe}`)),Y.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Y.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Y.error(`Port ${Xe} is already in use \u2014 agent may already be running.`):Y.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}async function io(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await $l();return}if(t==="install"){await Hr();return}if(t==="status"){await hl();return}if(t==="stop"){await jr();return}if(t==="uninstall"){await gl();return}if(t==="restart"){await jr(),await Hr();return}Y.error(`Unknown agent action: ${e}`),Y.info(ce.dim(`Use: ${p.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as Bd}from"module";import{text as vl,password as Rl,spinner as Dl,isCancel as oo}from"@clack/prompts";import dn from"chalk";import Ut from"fs";import no from"path";import Pl from"os";var an=no.join(Pl.homedir(),p.configDir),ln=no.join(an,"config.json");function cn(){if(!Ut.existsSync(ln))return{};try{return JSON.parse(Ut.readFileSync(ln,"utf-8"))}catch{return{}}}function ro(e){Ut.existsSync(an)||Ut.mkdirSync(an,{recursive:!0});let i={...cn(),...e};Ut.writeFileSync(ln,JSON.stringify(i,null,2))}async function so(){let e=cn(),t=await vl({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(oo(t))return;let i=await Rl({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(oo(i))return;let n=Dl();n.start("Authenticating...");try{let o=await(await fetch(`${ei}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();o.status==="success"&&o.user.token?(vn({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ro({lastLoginEmail:t}),n.stop(dn.green("Login successful!"))):n.stop(dn.red("Login failed: "+(o.message||"Unknown error")))}catch(r){n.stop(dn.red("Network error: "+r.message))}}import{log as yi,outro as Ol}from"@clack/prompts";import Bt from"chalk";async function ao(){let e=Rn(),t=`${p.envPrefix}TOKEN`;e?yi.success(Bt.green(`Logged out. Removed saved credentials from ~/${p.configDir}/credentials.json.`)):yi.warn(Bt.yellow(`No saved ${p.name} credentials found.`)),process.env[t]&&(yi.warn(Bt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),yi.info(Bt.dim(`Run: unset ${t}`))),Ol(Bt.blue("---"))}import{outro as Cl,select as Nl,spinner as Tl,isCancel as kl}from"@clack/prompts";import Si from"chalk";import un from"fs";import Ll from"path";var lo=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",xl=()=>process.versions.node.split(".")[0]||"24";async function co(){if(!$e()){console.log(Si.red(`You are not logged in. Run \`${p.nameLower} login\` first.`));return}let t=Tl();t.start("Fetching projects...");try{let{data:i}=await R.get("/projects");if(t.stop("Projects loaded."),i.status!=="success"||!i.projects||i.projects.length===0){console.log(Si.yellow(`No projects found. Run \`${p.nameLower} init\` to create one.`));return}let n=i.projects.map(A=>({value:A.projectId,label:`${A.name} (${A.slug})`})),r=await Nl({message:"Select a project to link:",options:n});if(kl(r))return;let o=Ll.join(process.cwd(),p.configFileName),s={};if(un.existsSync(o))try{s=JSON.parse(un.readFileSync(o,"utf-8"))}catch{}let l=i.projects.find(A=>A.projectId===r),a=s.android?.package||Je("android"),d=s.ios?.bundleIdentifier||Je("ios"),c=s.android||{},u=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},m={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||xl(),scheme:l?.slug?.toLowerCase()||"app",android:{...c,package:a||"",versionCode:c.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:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:lo(f.ascAppId),appleTeamId:lo(f.appleTeamId)}}}};un.writeFileSync(o,JSON.stringify(m,null,2)),Cl(Si.green(`Linked to project ${m.name} (${m.slug})`))}catch(i){t.stop(Si.red("Error fetching projects: "+i.message))}}import{outro as Ml,text as Ei,select as Ul,spinner as Bl,isCancel as Ft}from"@clack/prompts";import Ht from"chalk";import Fl from"fs";import Hl from"path";import{randomUUID as jl}from"crypto";var Gl=()=>process.versions.node.split(".")[0]||"24";async function uo(){if(!$e()){console.log(Ht.red(`You are not logged in. Run \`${p.nameLower} login\` first.`));return}let t=await Ei({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Ft(t))return;let i=await Ei({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(Ft(i))return;let n=await Ul({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Ft(n))return;let r="";if(n==="android"||n==="all"){let l=Je("android");if(r=await Ei({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Ft(r))return}let o="";if(n==="ios"||n==="all"){let l=Je("ios");if(o=await Ei({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Ft(o))return}let s=Bl();s.start("Creating project...");try{let l=jl(),d={projectId:l,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:c}=await R.post("/projects",d);if(c.status==="success"){s.stop(Ht.green("Project created successfully!"));let u=Hl.join(process.cwd(),p.configFileName);Fl.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:i,nodeVersion:Gl(),...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)),Ml(Ht.green(`Initialized project ${t} and linked locally!`))}else s.stop(Ht.red("creation failed: "+c.message))}catch(l){s.stop(Ht.red("Network error: "+l.message))}}import{spinner as fo,log as Re}from"@clack/prompts";import bi from"chalk";import po from"fs";import Kl from"path";function mo(e,t,i,n){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=n?` ${n}`:"";return r===401?`Not logged in or token expired while trying to ${i}${s}. Run \`${p.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${i}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${p.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 ${i}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${i}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${i}${s}: ${e?.message||"Unknown error"}`}async function go(e,t){let i=$e();if(!i){Re.error(`You are not logged in. Run \`${p.nameLower} login\` first.`);return}let n=Kl.join(process.cwd(),p.configFileName);if(!po.existsSync(n)){Re.error(`No ${p.configFileName} found. Run \`${p.nameLower} init\` or \`${p.nameLower} link\` first.`);return}let r;try{r=JSON.parse(po.readFileSync(n,"utf-8"))}catch{Re.error(`Failed to parse ${p.configFileName}`);return}let{projectId:o}=r;if(!o){Re.error(`${p.configFileName} is missing projectId.`);return}e==="set"?await Vl(o,t,i):e==="list"?await zl(o,i):Re.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Vl(e,t,i){if(t.length===0){Re.error(`Usage: ${p.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=fo();n.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){Re.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let c={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:u}=await R.post(`/projects/${e}/secrets`,c);u.status==="success"?r++:(Re.error(`Failed to set ${l}: ${u.message}`),o++)}catch(c){Re.error(mo(c,e,"set",l)),o++}}n.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function zl(e,t){let i=fo();i.start("Fetching environment variables...");try{let{data:n}=await R.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let r=n.secrets||[];r.length===0?Re.info("No environment variables found for this project."):(Re.info(bi.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${bi.cyan(o.key)} = ${s} ${bi.gray(`[${o.environment}]`)}`)}))}else i.stop(bi.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),Re.error(mo(n,e,"list"))}}import{spinner as nt,text as jt,select as gn,isCancel as it,cancel as hn,log as yo}from"@clack/prompts";import oe from"chalk";import te from"fs";import Ee from"path";import{spawn as Wl,spawnSync as ut}from"child_process";import So from"axios";import ft from"os";import En from"crypto";var Yl=5e3,Jl=12,Xl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},ql=e=>e?.type==="google_service_account",Ai=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId;async function Eo(e){let t=nt(),i=$e(),n=Zl(e);if(!n){process.exitCode=1;return}let r=e.projectId||n.projectId,o=e.profile||e.buildProfile||"production";if(!r){ie(`${p.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}n.projectId=r,pe(oe.dim(`Submit for project: ${n.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let $=await gn({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(it($)){hn("Operation cancelled");return}s=$}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){ie(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?fc(n,o,e):null;if(s==="ios"&&!e.local&&!l){await Ql(n,o,e);return}let a=e.submitId,d=!!(e.local&&a),c=a||null,u=async($,M={})=>{c&&await nc(r,c,{status:$,...M})},f=s==="android"?dc(n,o):void 0,m=s==="ios"?pc(n,o):void 0,A,U,N,x=!1;try{s==="android"&&(A=e.track||n.submit?.[o]?.android?.track||n.submit?.production?.android?.track||"internal",U=mc(n,o,e.releaseStatus),N=hc(n,o,e.rollout),x=yc(n,o,e.changesNotSentForReview),Sc(U,N))}catch($){ie($.message),process.exitCode=1;return}if(s==="android"&&!d&&(c=await ec(n,r,s,o,e,{packageName:f,track:A,releaseStatus:U,rollout:N,changesNotSentForReview:x}),!c)){ie("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await u("running",{platform:s,profile:o,packageName:f,track:A,releaseStatus:U,rollout:N,startTime:Date.now()});let T=null,G=null;try{G=await Ec(r,s,e,i?.token),T=G?.filePath||null}catch($){await u("failed",{error:`Failed to resolve submission artifact: ${$.message}`,endTime:Date.now()}),ie(`Failed to resolve submission artifact: ${$.message}`),process.exitCode=1;return}if(!T){await u("failed",{error:"No suitable artifact found for submission.",endTime:Date.now()}),process.exitCode=1;return}await u("running",{buildId:G?.buildId,artifactName:G?.artifactName,artifactSource:G?.source}),pe(`Using artifact: ${oe.green(Ee.basename(T))} `),t.start("Fetching submission credentials from Dashboard...");let h;try{let M=(await R.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),ie("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await u("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let K=M.filter(ql),L=s==="ios"?M.filter(H=>H.type==="asc_api_key"):uc(K,f);if(L.length===0){if(t.stop("Credentials missing"),ie(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let H=K.map(Ai).filter(Boolean).join(", ");H&&pe(`Found Google Play service credential(s) for: ${H}`),pe(`Use '${p.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else pe(`Use '${p.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await u("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(h=sc(L,e.credentialId),!h&&s==="ios"&&m&&(h=ac(L,m)),h||L.length===1)h=h||L[0],t.stop(`Using: ${h.name}`),s==="android"&&Ai(h)==="*"&&pe(oe.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),lc()){let E=L.map(le=>`${le.name||"credential"} (${le.credentialId||le.id||"no-id"})`).join(", ");ie(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${E}`),await u("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let H=await gn({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:L.map(E=>({value:E.credentialId,label:E.name,hint:`${E.keyId?`ID: ${E.keyId}`:""} ${E.issuerId?`(Issuer: ${E.issuerId.substring(0,8)}...)`:""}`}))});if(it(H)){hn("Submission cancelled"),await u("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}h=L.find(E=>E.credentialId===H),pe(`Using selected: ${oe.green(h.name)}`)}}catch($){t.stop("Failed to fetch credentials"),ie(`API Error: ${$.message} `),await u("failed",{error:`Failed to fetch credentials: ${$.message}`,endTime:Date.now()}),process.exitCode=1;return}let V=te.mkdtempSync(Ee.join(ft.tmpdir(),`${p.nameLower}-submit-`)),_=h.keyId||h.meta?.keyId,S=h.issuerId||h.meta?.issuerId,O=h.type==="asc_api_key"?`AuthKey_${_}.p8`:"service-account.json",P=Ee.join(V,O);t.start("Downloading secure key...");try{let $=await R.get(`/credentials/${h.credentialId}/download`,{params:{projectId:r,format:"raw"}});if($.data.status!=="success"||!$.data.downloadUrl)throw new Error("Failed to get secure download URL");let M=await So.get($.data.downloadUrl,{responseType:"arraybuffer"});te.writeFileSync(P,Buffer.from(M.data)),t.stop("Key downloaded to secure temp storage")}catch($){t.stop("Download failed"),ie(`Failed to download key: ${$.message}`);try{te.rmSync(V,{recursive:!0,force:!0})}catch{}await u("failed",{error:`Failed to download credential key: ${$.message}`,endTime:Date.now()}),process.exitCode=1;return}pe(oe.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let k=!1,v;try{if(s==="ios"){if(!_){let M=await jt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:K=>K.length>0?void 0:"Key ID is required"});if(it(M)){await u("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}_=M}if(!S||S==="undefined"){let M=await jt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:K=>K.length>0?void 0:"Issuer ID is required"});if(it(M)){await u("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}S=M}pe(`Using ASC Key ID: ${_}`),pe(`Using ASC Issuer ID: ${S}`);let $=l?await Ac(T,P,S,_,m,l):await bc(T,P,S,_,m);Sn(`${s==="ios"?"App Store":"Google Play"} submission successful!`),k=!0}else v=await Pc(T,P,A||"internal",f,U||"completed",N,x,o),Sn("Google Play submission successful!"),k=!0}catch($){ie(`Submission failed: ${$.message}`),await u("failed",{error:$.message,endTime:Date.now()}),It(e,{status:"failed",projectId:r,submitId:c,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,error:$.message,dashboardUrl:c?pt(c,r):void 0}),process.exitCode=1}finally{k&&(await u("success",{endTime:Date.now(),versionCode:v?.versionCode,track:A,releaseStatus:U}),It(e,{status:"success",projectId:r,submitId:c,platform:s,profile:o,buildId:G?.buildId||e.buildId,artifactName:G?.artifactName,versionCode:v?.versionCode,track:A,releaseStatus:U,dashboardUrl:c?pt(c,r):void 0})),Nc(V),T&&T.includes(`${p.nameLower}-artifact-`)}}function Zl(e){let t=`./${p.configFileName}`;if(te.existsSync(t))try{return JSON.parse(te.readFileSync(t,"utf-8"))}catch(i){return ie(`Failed to read ${p.configFileName}: ${i.message}`),null}return e.projectId?{projectId:e.projectId}:(ie(`No ${p.configFileName} found. Run \`${p.nameLower} init\` or \`${p.nameLower} link\` first.`),null)}async function Ql(e,t,i){let n=i.projectId||e.projectId;if(!n){ie(`${p.configFileName} is missing projectId.`),process.exitCode=1;return}let r=i.submitId||En.randomUUID(),o=!!i.latest||!i.buildId,s=tc({...i,latest:o,profile:t,projectId:n,submitId:r}),l={projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,credentialId:i.credentialId,status:"pending",source:"cli",submitArgs:process.argv.slice(3).join(" "),runnerArgs:s,runnerCommand:[p.nameLower,"submit",...s].map(cc).join(" "),appName:e.name,startTime:Date.now()},a=nt();a.start("Queuing iOS submit on macOS runner...");try{let d=await R.post("/submissions",l),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||pt(r,n);a.stop("iOS submit queued"),pe(`Submission ID: ${oe.cyan(r)}`),pe(`Dashboard: ${oe.blue.underline(u)}`),It(i,{status:"pending",projectId:n,submitId:r,platform:"ios",profile:t,latest:o,buildId:i.buildId,dashboardUrl:u}),await ic(n,r,i)}catch(d){a.stop("Could not queue iOS submit"),ie(oc(d)),process.exitCode=1}}async function ec(e,t,i,n,r,o={}){let s=r.submitId||En.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:process.argv.slice(3).join(" "),appName:e.name,startTime:Date.now(),...o};try{let d=await R.post("/submissions",a),c=d.data?.submission||d.data?.submit||{},u=d.data?.dashboardUrl||c.dashboardUrl||pt(s,t);return pe(`Submission ID: ${oe.cyan(s)}`),pe(`Dashboard: ${oe.blue.underline(u)}`),It(r,{status:"running",projectId:t,submitId:s,platform:i,profile:n,latest:l,buildId:r.buildId,dashboardUrl:u}),s}catch(d){let c=d.response?.data?.message||d.response?.data?.error||d.message;return pe(oe.yellow(`Could not create submission tracking record: ${c}`)),null}}function tc(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.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(i=>i!=null&&i!=="")}async function ic(e,t,i){let n=nt(),r=0,o=0;for(i.quiet||n.start("Waiting for iOS submit runner...");;)try{let s=await R.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 c=o;c<d.length;c++){let u=d[c];u&&console.log(oe.dim(String(u)))}if(o=d.length,["success","completed","succeeded"].includes(a)){i.quiet||n.stop("iOS submit completed"),Sn("App Store submission successful!"),It(i,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||pt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){i.quiet||n.stop("iOS submit failed");let c=l?.error||l?.message||"Unknown iOS submit failure.";ie(c),It(i,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||i.profile||"production",buildId:l?.buildId||i.buildId,artifactName:l?.artifactName,error:c,dashboardUrl:l?.dashboardUrl||pt(t,e)}),process.exitCode=1;return}i.quiet||n.message(`iOS submit ${a}...`),await yn(Yl)}catch(s){if(r++,r>=Jl){i.quiet||n.stop("Lost connection to iOS submit status"),ie(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await yn(Math.min(2e3*r,15e3))}}async function nc(e,t,i){let n;for(let r=1;r<=3;r++)try{await R.patch(`/submissions/${e}/${t}`,i);return}catch(o){if(n=o,r>=3||!rc(o))break;await yn(1e3*r)}yo.warn(oe.dim(`Could not report submission status: ${n?.message||n}`))}function rc(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function oc(e){let t=e.response?.status,i=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(`
|
|
1174
|
-
`):i||e.message||String(e)}function pt(e,t){if(!e)return We;let i=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${i}`}function It(e,t){if(!e.jsonOutput)return;let i=Ee.resolve(e.jsonOutput),n={...t,url:t.url||t.dashboardUrl||pt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ee.dirname(i);r&&r!=="."&&te.mkdirSync(r,{recursive:!0}),te.writeFileSync(i,JSON.stringify(n,null,2))}catch(r){yo.warn(oe.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function sc(e,t){return t&&e.find(i=>i.credentialId===t||i.id===t||i.keyId===t||i.meta?.keyId===t)||null}function ac(e,t){let i=e.filter(n=>[n.bundleId,n.bundleIdentifier,n.appIdentifier,n.meta?.bundleId,n.meta?.bundleIdentifier,n.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return i.length===1?i[0]:null}function lc(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function yn(e){return new Promise(t=>setTimeout(t,e))}function cc(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function dc(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let i=On(e,t);if(i)return i;let n=Ee.join(process.cwd(),"app.json");if(te.existsSync(n))try{return JSON.parse(te.readFileSync(n,"utf-8")).expo?.android?.package}catch{}let r=Ee.join(process.cwd(),"app.config.json");if(te.existsSync(r))try{let o=JSON.parse(te.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function uc(e,t){let i=e.filter(o=>Ai(o)===t);if(i.length>0)return i;let n=e.filter(o=>{let s=Ai(o);return!s||s==="*"});return e.length>0&&e.length===n.length?n:[]}function pc(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Cn(e,t)}function fc(e,t,i){let n=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=i.sshHost||n.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:i.sshUser||n.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:i.sshKey||n.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function mc(e,t,i){let n=i||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return gc(n)}function gc(e){let t=Xl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function hc(e,t,i){let n=i??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(n==null||n==="")return;let r=Number(n);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${n}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function yc(e,t,i){let n=i??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 n===!0||n==="true"||n==="1"}function Sc(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 Ec(e,t,i,n){let r=i.buildId?"id":i.latest?"latest":null;if(!r){let s=await gn({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${p.name})`},{value:"id",label:`Input Build ID (${p.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(it(s))return hn("Operation cancelled"),null;r=s}if(r==="local"){let s=await jt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!te.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 it(s)?null:{filePath:s,source:"local"}}let o=nt();if(r==="latest"){let s=i.profile||i.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await R.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(),c=h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success",u=h=>d?[h.buildProfile,h.profile,h.profileName,h.buildType].filter(Boolean).some(V=>String(V).toLowerCase()===d):!0,f=a.filter(h=>c(h)&&u(h)),m=f.find(h=>h.buildType?.toLowerCase()==="store"||h.distribution?.toLowerCase()==="store")||f[0],A=a.some(h=>h.platform?.toLowerCase()===t.toLowerCase()&&h.status?.toLowerCase()==="success");if(!m)return o.stop("No suitable build found"),ie(s&&A?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${m.buildId}`);let U=m.artifacts||[];if(U.length===0||U.every(h=>!(h.url||h.downloadUrl)))try{let h=await R.get(`/builds/${e}/${m.buildId}/artifacts`);h.data.status==="success"&&h.data.artifacts?.length>0?(U=h.data.artifacts.map(V=>({...V,url:V.url||V.downloadUrl})),console.log(oe.cyan(` [RECOVERY] Fetched ${U.length} artifact(s) with download URLs.`))):console.log(oe.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(h){console.log(oe.red(` [RECOVERY] /artifacts fetch failed: ${h.message}`))}let x=t==="ios",T=U.find(h=>{let V=(h.type||"").toLowerCase(),_=(h.name||"").toLowerCase();if(console.log(oe.dim(` - Checking: ${h.name} (Type: ${h.type}, HasLink: ${!!(h.url||h.downloadUrl)})`)),V)return V===(x?"ipa":"aab");let S=x?".ipa":".aab",O=(h.url||h.downloadUrl||"").toLowerCase();return _.endsWith(S)||O.includes(S)});if(!T||!(T.url||T.downloadUrl))return ie("Build found but artifact URL is missing."),null;let G=T.url||T.downloadUrl;return{filePath:await pn(G,x?"ios":"android"),buildId:m.buildId,artifactName:T.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),ie(`API Error: ${l.message}`),null}}if(r==="id"){let s=i.buildId||await jt({message:"Enter Build ID:",validate:l=>l.length<5?"Invalid ID":void 0});if(it(s))return null;o.start("Fetching build...");try{let l=await R.get(`/build/${s}`);if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.build;if(!a)throw new Error("Build not found");let d=t==="ios",c=a.artifacts?.find(u=>{if(u.type)return u.type===(d?"ipa":"aab");let f=d?".ipa":".aab";return u.name&&u.name.endsWith(f)||u.url&&u.url.includes(f)});return!c||!c.url?(o.stop("Missing artifact"),ie("Artifact URL not found on build record."),null):(o.stop(`Found build: ${a.buildId}`),{filePath:await pn(c.url,d?"ios":"android"),buildId:a.buildId||String(s),artifactName:c.name,source:"id"})}catch(l){return o.stop("Fetch failed"),ie(l.message),null}}if(r==="url"){let s=await jt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return it(s)?null:{filePath:await pn(s,t),source:"url"}}return null}async function pn(e,t,i=3){let n=nt();n.start("Downloading artifact...");let r=te.mkdtempSync(Ee.join(ft.tmpdir(),`${p.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ee.join(r,o);for(let l=1;l<=i;l++)try{l>1&&(n.message(`Downloading artifact (Retry ${l}/${i})...`),await new Promise(c=>setTimeout(c,2e3*l)));let a=te.createWriteStream(s),d=await So({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((c,u)=>{d.data.pipe(a);let f=!1;d.data.on("error",m=>{f||(f=!0,a.close(),u(m))}),a.on("finish",()=>{f||c()}),a.on("error",m=>{f||(f=!0,u(m))})}),n.stop("Download complete"),s}catch(a){if(l===i)throw n.stop("Download failed"),a}throw new Error("Download failed after retries")}async function bc(e,t,i,n,r){let o=nt();if(r&&pe(`Bundle ID: ${oe.green(r)}`),!i||!n)throw ie(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=bo(t,i,n),l=Rc();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,d)=>{let c=Wl(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:l.env});c.on("close",u=>{if(u!==0){o.stop("Pilot failed");try{te.unlinkSync(s)}catch{}d(new Error(`fastlane pilot failed with exit code ${u??"unknown"}.`))}else{o.stop("IPA uploaded to TestFlight");try{te.unlinkSync(s)}catch{}a({})}}),c.on("error",u=>{try{te.unlinkSync(s)}catch{}o.stop("Pilot execution error"),d(Oc(u))})})}async function Ac(e,t,i,n,r,o){let s=nt();if(r&&pe(`Bundle ID: ${oe.green(r)}`),!i||!n)throw ie(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=bo(t,i,n),a=`${o.sshUser}@${o.sshHost}`,d=Ic(o),c=_c(o),u="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),u=wc("ssh",[...d,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)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..."),fn("scp",[...c,e,`${a}:${u}/app.ipa`],"IPA upload to remote runner"),fn("scp",[...c,l,`${a}:${u}/api_key.json`],"ASC key upload to remote runner"),f=Ee.join(ft.tmpdir(),`${p.nameLower}-ios-submit-${Date.now()}.sh`),te.writeFileSync(f,$c(u)),fn("scp",[...c,f,`${a}:${u}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let m=`chmod +x ${Gt(`${u}/submit.sh`)} && bash ${Gt(`${u}/submit.sh`)}`,A=ut("ssh",[...d,m],{stdio:"inherit"});if(A.error)throw bn("ssh",A.error);if(A.status!==0)throw new Error(`Remote iOS submit failed with exit code ${A.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(m){throw s.stop("Remote iOS submit failed"),m}finally{try{te.unlinkSync(l)}catch{}if(f)try{te.unlinkSync(f)}catch{}if(u)try{ut("ssh",[...d,`rm -rf ${Gt(u)}`],{stdio:"ignore"})}catch{}}}function bo(e,t,i){let n=te.readFileSync(e,"utf8"),r;try{r=En.createPrivateKey(n).export({type:"pkcs8",format:"pem"})}catch{pe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1175
|
-
${
|
|
1176
|
-
`)}
|
|
1177
|
-
-----END PRIVATE KEY-----`}let o=Ee.join(ft.tmpdir(),`api_key_${i}_${Date.now()}.json`),s={key_id:i,issuer_id:t,key:r,in_house:!1};return te.writeFileSync(o,JSON.stringify(s,null,2)),o}function Ic(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 _c(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function wc(e,t){let i=ut(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(i.error)throw bn(e,i.error);if(i.status!==0)throw new Error(`${e} failed with exit code ${i.status}.`);return i.stdout||""}function fn(e,t,i){let n=ut(e,t,{stdio:"inherit"});if(n.error)throw bn(e,n.error);if(n.status!==0)throw new Error(`${i} failed with exit code ${n.status}.`)}function bn(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 Gt(e){return`'${e.replace(/'/g,"'\\''")}'`}function $c(e){let t=Gt(`${e}/app.ipa`),i=Gt(`${e}/api_key.json`);return`#!/bin/bash
|
|
1178
|
-
set -euo pipefail
|
|
1179
|
-
|
|
1180
|
-
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
1181
|
-
export FASTLANE_SKIP_UPDATE_CHECK=1
|
|
1182
|
-
export FASTLANE_HIDE_CHANGELOG=1
|
|
1183
|
-
export CI="\${CI:-1}"
|
|
1184
|
-
|
|
1185
|
-
if ! command -v fastlane >/dev/null 2>&1; then
|
|
1186
|
-
if ! command -v gem >/dev/null 2>&1; then
|
|
1187
|
-
echo "fastlane was not found and gem is unavailable on the remote macOS runner."
|
|
1188
|
-
exit 127
|
|
1189
|
-
fi
|
|
1190
|
-
|
|
1191
|
-
FASTLANE_GEM_HOME="\${FASTLANE_GEM_HOME:-$HOME/.local/share/fastlane/3.4.0}"
|
|
1192
|
-
FASTLANE_BIN_DIR="$FASTLANE_GEM_HOME/bin"
|
|
1193
|
-
mkdir -p "$FASTLANE_BIN_DIR"
|
|
1194
|
-
export GEM_HOME="$FASTLANE_GEM_HOME"
|
|
1195
|
-
export GEM_PATH="$FASTLANE_GEM_HOME:\${GEM_PATH:-}"
|
|
1196
|
-
export PATH="$FASTLANE_BIN_DIR:$PATH"
|
|
1197
|
-
gem install fastlane -NV --install-dir "$FASTLANE_GEM_HOME" --bindir "$FASTLANE_BIN_DIR"
|
|
1198
|
-
fi
|
|
1199
|
-
|
|
1200
|
-
fastlane pilot upload \\
|
|
1201
|
-
--ipa ${t} \\
|
|
1202
|
-
--api_key_path ${i} \\
|
|
1203
|
-
--skip_submission true \\
|
|
1204
|
-
--skip_waiting_for_build_processing true
|
|
1205
|
-
`}async function Pc(e,t,i="internal",n,r="completed",o,s=!1,l="production"){let a=nt();if(!n||n==="*")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 ${i} track with ${r} release status${d}...`);try{let c=JSON.parse(te.readFileSync(t,"utf-8"));vc(c);let u=await Xn({packageName:n,serviceAccount:c,aabPath:e,track:i,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${i} track (versionCode ${u.versionCode})`),u}catch(c){throw a.stop("Google Play upload failed"),new Error(Cc(c,i,n,l))}}function vc(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function mn(){let e=process.env.HOME||ft.homedir(),t=process.env.FASTLANE_GEM_HOME||Ee.join(e,".local/share/fastlane/3.4.0"),i=[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",Ee.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:i,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 Rc(){let e=mn(),t=ho(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Dc(e);let i=ho(mn());if(i)return i}return{command:"fastlane",env:mn()}}function ho(e){let t=process.env.HOME||ft.homedir(),i=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ee.join(process.env.FASTLANE_GEM_HOME||Ee.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let n of i){if(n.includes("/")&&!te.existsSync(n))continue;if(!ut(n,["--version"],{env:e,stdio:"ignore"}).error)return{command:n,env:e}}return null}function Dc(e){let t=ut("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let i=process.env.HOME||ft.homedir(),n=process.env.FASTLANE_GEM_HOME||Ee.join(i,".local/share/fastlane/3.4.0"),r=Ee.join(n,"bin");te.mkdirSync(r,{recursive:!0}),pe(oe.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=ut("gem",["install","fastlane","-NV","--install-dir",n,"--bindir",r],{env:{...e,GEM_HOME:n,GEM_PATH:[n,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&pe(oe.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Oc(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(`
|
|
1206
|
-
`))}function Cc(e,t,i,n="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: ${i||"unknown"} | Track: ${t}`,`Retry with: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1207
|
-
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${i||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1208
|
-
`);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: ${i||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1209
|
-
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${i||"unknown"} | Track: ${t}`,`Retry with: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t} --release-status draft`].join(`
|
|
1210
|
-
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${p.nameLower} build --platform android --profile ${n} --auto-version`,`Then: ${p.nameLower} submit --latest --platform android --profile ${n} --track ${t}`].join(`
|
|
1211
|
-
`);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: ${i||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${p.nameLower} build --platform android --profile ${n} --auto-version`].join(`
|
|
1212
|
-
`);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{te.existsSync(e)&&te.rmSync(e,{recursive:!0,force:!0})}catch{}}function ie(e){console.log(oe.red(`\u274C ${e}`))}function pe(e){console.log(oe.gray(`\u2022 ${e}`))}function Sn(e){console.log(oe.green(`\u2713 ${e}`))}import{spinner as Tc,log as mt,outro as kc}from"@clack/prompts";import An from"chalk";import Ao from"fs";import Lc from"path";import{execSync as xc}from"child_process";import Mc from"adm-zip";import Uc from"axios";import{randomUUID as Bc}from"crypto";async function Io(e){mt.info(An.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Ne();(!t||!t.projectId)&&(mt.error(`No ${p.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let i=t.projectId,n=e.branch||"production",r="1.0.0";try{r=JSON.parse(Ao.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{mt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=Tc();o.start(`Compiling JavaScript bundles for OTA (Channel: ${n}, Runtime: ${r})...`);try{xc("npx expo export --platform all",{stdio:"ignore"})}catch(d){o.stop("Compilation failed."),mt.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Lc.join(process.cwd(),"dist");Ao.existsSync(s)||(o.stop("Missing dist folder."),mt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new Mc;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let d=Bc(),c=await R.post("/builds/source-upload-url",{projectId:i,buildId:d});if(c.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:f}=c.data;await Uc.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${n}...`),await R.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"android",updateId:`${d}-android`,manifestKey:f}),await R.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"ios",updateId:`${d}-ios`,manifestKey:f}),o.stop("Update Live!"),kc(An.green(`\u2713 OTA Update natively shipped to the '${n}' channel.`)),mt.info(An.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(d){o.stop("Update failed during Cloud Sync."),mt.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as Fc,outro as _o,log as _t}from"@clack/prompts";import Ve from"chalk";async function wo(){Fc(Ve.blue(`${p.name} CLI - User Profile`));let e=$e();if(!e){_t.warn(Ve.yellow("You are not logged in.")),_t.info(`Run \`${p.nameLower} login\` to authenticate.`),_o();return}_t.info(`${Ve.bold("Logged in as:")} ${Ve.green(e.email)}`);try{await R.get("/projects");let i=$e().token.split(".");if(i.length===3){let n=JSON.parse(Buffer.from(i[1],"base64").toString());if(n.exp){let r=new Date(n.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);_t.info(`${Ve.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else _t.warn(`${Ve.bold("Token status:")} ${Ve.red("Expired")} (Auto-refresh failed)`)}}}catch{_t.warn(`${Ve.bold("Token status:")} ${Ve.red("Unreachable")} (Session might be truly expired)${ei}`)}_o(Ve.blue("---"))}import{spawn as Gc}from"child_process";import{log as rt}from"@clack/prompts";import De from"chalk";import Kc from"fs";import Hc from"net";async function jc(e){return new Promise(t=>{let i=Hc.createServer();i.once("error",n=>{n.code==="EADDRINUSE"?t(!0):t(!1)}),i.once("listening",()=>{i.close(),t(!1)}),i.listen(e,"0.0.0.0")})}async function $o(e,t=20){let i=e;for(;i<e+t;){if(!await jc(i))return i;i++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var Po=async e=>{rt.info(De.blue(`Starting ${p.name} Dev Orchestrator...`));let t=Ne(),i=e.buildProfile||"development",n=t?Ze(t,i):null,r={...process.env};if(t?.projectId)try{rt.info(De.dim(`Fetching managed secrets for profile: ${i}...`));let u=await R.get(`/projects/${t.projectId}/secrets/export?env=${i}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),rt.info(De.magenta(`\u2713 Injected secrets from ${p.name} Dashboard.`)))}catch{rt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,gt(t,p.envPrefix)),n&&(Object.assign(r,gt(n,`${p.envPrefix}PROFILE_`)),n.env&&Object.assign(r,n.env));let o=!1;try{let u=JSON.parse(Kc.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{rt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||n?.port||8081),l=await $o(s);l!==s&&rt.info(De.yellow(`Port ${s} is busy. ${p.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 u=[`${De.cyan("i")} open iOS simulator`,`${De.cyan("a")} open Android emulator/device`,`${De.cyan("w")} open web`,`${De.cyan("r")} reload app`];rt.info([De.bold("Launch controls"),...u.map(f=>` ${f}`),"",De.dim("Direct launch: mach start --ios | --android | --web"),De.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1213
|
-
`))}else rt.info(De.dim(`Metro URL: http://localhost:${l}`));let c=Gc(a,d,{stdio:"inherit",env:r});return new Promise((u,f)=>{c.on("exit",m=>{m===0?u():f(new Error(`Dev server exited with code ${m}`))}),c.on("error",m=>{f(m)})})};import{log as Pe}from"@clack/prompts";import Ue from"chalk";var vo=async e=>{let t=Ne();t||(Pe.error(Ue.red(`No ${p.configFileName} found in the current directory.`)),process.exit(1));let i=e.profile||"development",n=Ze(t,i);if(e.json){console.log(JSON.stringify({project:t,resolved:n},null,2));return}Pe.info(Ue.bgBlue.white(` Resolved ${p.name} Config [${i}] `)),Pe.info(Ue.dim("----------------------------------------")),Pe.info(`${Ue.blue("Project ID:")} ${t.projectId}`),Pe.info(`${Ue.blue("Name:")} ${t.name}`),Pe.info(`${Ue.blue("Scheme:")} ${t.scheme}`),n?(Pe.info(Ue.dim(`
|
|
1214
|
-
Profile Settings:`)),Pe.info(`${Ue.cyan("Distribution:")} ${n.distribution||"none"}`),Pe.info(`${Ue.cyan("Development Client:")} ${n.developmentClient||"false"}`),n.env&&Object.keys(n.env).length>0&&(Pe.info(Ue.dim(`
|
|
1215
|
-
Environment Variables:`)),Object.entries(n.env).forEach(([r,o])=>{Pe.info(` ${r}=${o}`)}))):Pe.warn(`Profile '${i}' not found.`),Pe.info(Ue.dim("----------------------------------------"))};import{log as Be,spinner as zt,text as Ro,select as Do,confirm as Vc,isCancel as Kt,cancel as Vt,outro as Wt,note as zc}from"@clack/prompts";import ne from"chalk";import{execSync as Wc}from"child_process";async function Yc(){try{let e=Wc("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(n=>n.connectionProperties?.transportType==="wired"||n.connectionProperties?.transportType==="localNetwork").map(n=>({udid:n.identifier,name:n.deviceProperties?.name||"Unknown Device",model:n.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}async function Jc(e){let t=e.udid,i=e.name,n="";if(!t){let o=zt();o.start("Scanning for connected iOS devices...");let s=await Yc();if(o.stop(s.length>0?`Found ${s.length} device(s)`:"No devices detected"),s.length===1)t=s[0].udid,i=i||s[0].name,n=s[0].model,Be.info(`Detected: ${ne.bold(i)} (${ne.dim(t.substring(0,12)+"...")})`);else if(s.length>1){let l=await Do({message:"Select a device to register:",options:s.map(d=>({value:d.udid,label:`${d.name} (${d.model})`,hint:d.udid.substring(0,12)+"..."}))});if(Kt(l)){Vt("Cancelled");return}t=l;let a=s.find(d=>d.udid===t);i=i||a.name,n=a.model}else{Be.info(ne.dim("No connected devices found. Enter UDID manually."));let l=await Ro({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(a){if(a.length<10)return"UDID seems too short"}});if(Kt(l)){Vt("Cancelled");return}t=l}}if(!i){let o=await Ro({message:"Device name:",placeholder:"Nitesh's iPhone",validate(s){if(s.length===0)return"Name is required"}});if(Kt(o)){Vt("Cancelled");return}i=o}let r=zt();r.start("Registering device...");try{await R.post("/devices",{udid:t,name:i,platform:"ios",model:n||void 0,addedVia:"cli"}),r.stop(ne.green("Device registered!")),Be.info(` ${ne.bold("Name:")} ${i}`),Be.info(` ${ne.bold("UDID:")} ${ne.dim(t)}`)}catch(o){r.stop(ne.red("Failed to register device")),Be.error(o.response?.data?.message||o.message)}Wt(ne.blue("---"))}async function Xc(){let e=zt();e.start("Fetching registered devices...");try{let i=(await R.get("/devices")).data.devices||[];if(e.stop(`${i.length} device(s) registered`),i.length===0){Be.info(ne.dim(`No devices registered yet. Run \`${p.nameLower} device register\` to add one.`)),Wt(ne.blue("---"));return}let n=i.map(r=>{let o=new Date(r.createdAt).toLocaleDateString();return` ${ne.bold(r.name.padEnd(24))} ${ne.dim(r.udid.padEnd(28))} ${ne.cyan(r.addedVia.padEnd(10))} ${ne.dim(o)}`});zc(` ${ne.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
1217
|
+
`;return pe.writeFileSync(hi(),s),hi()}function it(e,t={}){try{return bi("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(i){if(t.ignoreError)return!1;throw i}}function yc(e){return new Promise(t=>setTimeout(t,e))}function yi(e,t,i=uc){return new Promise((n,r)=>{cc(e,t,{timeout:i,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}n(s?.toString()||"")})})}async function mo(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Ut}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,i=r=>{t||(t=!0,e(r))},n=Si.get(`${Ut}/health`,r=>{r.resume(),i(r.statusCode===200)});n.setTimeout(3e3,()=>{n.destroy(),i(!1)}),n.on("error",()=>i(!1))})}async function Sc(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await mo())return!0;await yc(250)}return!1}async function go(){return new Promise(e=>{let t=!1,i=oo.createConnection({host:"127.0.0.1",port:qe}),n=r=>{t||(t=!0,i.destroy(),e(r))};i.setTimeout(1e3),i.once("connect",()=>n(!0)),i.once("timeout",()=>n(!1)),i.once("error",()=>n(!1))})}async function En(){if(await Sc()){Y.success(le.green("Mach agent installed and started."));return}if(await go()){Y.warn(`Mach agent service is installed, but port ${qe} is held by a process that is not answering /health.`),Y.info(le.dim(`Run \`${p.nameLower} agent stop\`, close any foreground \`${p.nameLower} agent\` terminal, then run \`${p.nameLower} agent install\` again.`));return}Y.warn(`Mach agent service is installed, but it did not start listening on ${Ut}.`)}async function bc(){let e=hc(),t=yn();it(["bootout",t,e],{ignoreError:!0}),it(["bootstrap",t,e],{ignoreError:!0})||it(["load","-w",e]),it(["enable",`${t}/${At}`],{ignoreError:!0}),it(["kickstart","-k",`${t}/${At}`],{ignoreError:!0}),await En(),Y.info(le.dim(`It will start automatically when you log in. Plist: ${e}`)),Y.info(le.dim(`Logs: ${ee.join(Me(),"agent.log")}`))}async function ho(){let e=hi(),t=yn();it(["bootout",t,e],{ignoreError:!0})||it(["unload","-w",e],{ignoreError:!0})?Y.success(le.green("Mach agent service stopped.")):Y.warn("Mach agent service was not loaded.")}async function Ec(){await ho();let e=hi();pe.existsSync(e)&&pe.unlinkSync(e),Y.success(le.green("Mach agent service uninstalled."))}async function Ac(){let e=mc();nt(["daemon-reload"]),nt(["enable","--now",It]),await En(),Y.info(le.dim(`It will start automatically when you log in. Service: ${e}`)),Y.info(le.dim(`Logs: ${ee.join(Me(),"agent.log")}`))}async function Ic(){nt(["stop",It],{ignoreError:!0})?Y.success(le.green("Mach agent service stopped.")):Y.warn("Mach agent service was not running.")}async function _c(){nt(["disable","--now",It],{ignoreError:!0}),nt(["daemon-reload"],{ignoreError:!0});let e=gn();pe.existsSync(e)&&pe.unlinkSync(e),nt(["daemon-reload"],{ignoreError:!0}),Y.success(le.green("Mach agent service uninstalled."))}async function wc(){let e=gc();Bt(["/Create","/TN",Et,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Bt(["/Run","/TN",Et],{ignoreError:!0}),await En(),Y.info(le.dim(`It will start automatically when you log in. Task: ${Et}`)),Y.info(le.dim(`Logs: ${ee.join(Me(),"agent.log")}`))}async function yo(){Bt(["/End","/TN",Et],{ignoreError:!0})?Y.success(le.green("Mach agent task stopped.")):Y.warn("Mach agent task was not running.")}async function $c(){await yo(),Bt(["/Delete","/TN",Et,"/F"],{ignoreError:!0});let e=hn();pe.existsSync(e)&&pe.unlinkSync(e),Y.success(le.green("Mach agent task uninstalled."))}async function io(){if(process.platform==="darwin")return bc();if(process.platform==="linux")return Ac();if(process.platform==="win32")return wc();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function no(){if(process.platform==="darwin")return ho();if(process.platform==="linux")return Ic();if(process.platform==="win32")return yo();Y.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Pc(){if(process.platform==="darwin")return Ec();if(process.platform==="linux")return _c();if(process.platform==="win32")return $c();Y.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Rc(){let e=await mo(),t=e?!0:await go();if(e?Y.success(le.green(`Mach agent is online at ${Ut}`)):t?Y.warn(`Mach agent port is open, but /health did not respond. Run \`${p.nameLower} agent restart\` if the dashboard still shows offline.`):Y.warn(`Mach agent is not responding at ${Ut}`),process.platform==="darwin"){let i=it(["print",`${yn()}/${At}`],{ignoreError:!0});Y.info(le.dim(`Login service: ${i?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let i=nt(["is-enabled",It],{ignoreError:!0}),n=nt(["is-active",It],{ignoreError:!0});Y.info(le.dim(`Login service: ${i?"enabled":"not enabled"} / ${n?"active":"inactive"}`))}else if(process.platform==="win32"){let i=Bt(["/Query","/TN",Et],{ignoreError:!0});Y.info(le.dim(`Login task: ${i?"installed":"not installed"}`))}}async function vc(){let e=[];try{(await yi(po(),["devices","-l"])).split(`
|
|
1218
|
+
`).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let n=i.split(/\s+/);if(n.length<2||n[1]!=="device")return;let r=n[0],o=i.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:i.trim()})})}catch{}try{let i=(await yi(fo(),["-list-avds"])).split(`
|
|
1219
|
+
`).filter(r=>!!r.trim()),n=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{n||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Dc(){if(process.platform!=="darwin")return[];try{let e=await yi("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),i=[];return Object.entries(t.devices||{}).forEach(([n,r])=>{r.forEach(o=>{o.isAvailable&&i.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${o.name} (${n})`})})}),i}catch{return[]}}async function Oc(){if(process.platform!=="darwin")return[];try{let e=await yi("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(i=>{let n=i.connectionProperties?.transportType;return n==="wired"||n==="localNetwork"}).map(i=>{let n=i.connectionProperties?.transportType,r=i.deviceProperties?.name||"iPhone";return{id:i.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${i.model?.name||i.hardwareModel||""}) - ${n}`}})}catch{return[]}}async function Cc(){let[e,t,i]=await Promise.all([vc(),Dc(),Oc()]);return[...e,...t,...i]}async function Nc(){let e=Date.now();return mi&&e-mi.updatedAt<pc?mi.targets:(gi||(gi=Cc().then(t=>(mi={targets:t,updatedAt:Date.now()},t)).finally(()=>{gi=null})),gi)}async function ro(e){let t=[];for await(let i of e)t.push(Buffer.isBuffer(i)?i:Buffer.from(i));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Tc(e,t){let i=await dc({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=pe.createWriteStream(t);i.data.pipe(n),await new Promise((r,o)=>{n.on("finish",r),n.on("error",o)})}async function kc(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ee.join(xe.tmpdir(),`${qe}-install-`)),s=ee.join(o,n==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Tc(t,s),n==="android"){bi(po(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");ft(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=ft(`find ${JSON.stringify(ee.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=ft(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{ft(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{ft(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{pe.rmSync(o,{recursive:!0,force:!0})}}function Lc(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 ft(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),to("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return to(fo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function xc(){process.platform!=="darwin"&&Y.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Si.createServer((n,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"),n.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(n.url||"/",`http://localhost:${qe}`);if(n.method==="GET"&&o.pathname==="/local/devices"){Nc().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(n.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:qe,platform:process.platform}));return}if(n.method==="POST"&&o.pathname==="/install-local"){t(n,r);return}if(n.method==="POST"&&o.pathname==="/local/boot"){i(n,r);return}r.writeHead(404),r.end()}),t=async(n,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await ro(n);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await kc(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"}))}},i=async(n,r)=>{try{let{id:o,platform:s}=await ro(n),l=Lc(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(qe,"127.0.0.1",()=>{Y.success(le.green(`Local device agent running on http://localhost:${qe}`)),Y.info(le.dim("Keep this running while using the Install Hub on the dashboard.")),Y.info(le.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Y.error(`Port ${qe} is already in use \u2014 agent may already be running.`):Y.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}async function So(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await xc();return}if(t==="install"){await io();return}if(t==="status"){await Rc();return}if(t==="stop"){await no();return}if(t==="uninstall"){await Pc();return}if(t==="restart"){await no(),await io();return}Y.error(`Unknown agent action: ${e}`),Y.info(le.dim(`Use: ${p.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as du}from"module";import{text as Uc,password as Bc,spinner as Fc,isCancel as Ao}from"@clack/prompts";import wn from"chalk";import Ft from"fs";import bo from"path";import Mc from"os";var An=bo.join(Mc.homedir(),p.configDir),In=bo.join(An,"config.json");function _n(){if(!Ft.existsSync(In))return{};try{return JSON.parse(Ft.readFileSync(In,"utf-8"))}catch{return{}}}function Eo(e){Ft.existsSync(An)||Ft.mkdirSync(An,{recursive:!0});let i={..._n(),...e};Ft.writeFileSync(In,JSON.stringify(i,null,2))}async function Io(){let e=_n(),t=await Uc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(Ao(t))return;let i=await Bc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(Ao(i))return;let n=Fc();n.start("Authenticating...");try{let o=await(await fetch(`${ei}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();o.status==="success"&&o.user.token?(Nn({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),Eo({lastLoginEmail:t}),n.stop(wn.green("Login successful!"))):n.stop(wn.red("Login failed: "+(o.message||"Unknown error")))}catch(r){n.stop(wn.red("Network error: "+r.message))}}import{log as Ei,outro as Hc}from"@clack/prompts";import Ht from"chalk";async function _o(){let e=Tn(),t=`${p.envPrefix}TOKEN`;e?Ei.success(Ht.green(`Logged out. Removed saved credentials from ~/${p.configDir}/credentials.json.`)):Ei.warn(Ht.yellow(`No saved ${p.name} credentials found.`)),process.env[t]&&(Ei.warn(Ht.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Ei.info(Ht.dim(`Run: unset ${t}`))),Hc(Ht.blue("---"))}import{outro as jc,select as Gc,spinner as Kc,isCancel as Vc}from"@clack/prompts";import Ai from"chalk";import $n from"fs";import zc from"path";var wo=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",Wc=()=>process.versions.node.split(".")[0]||"24";async function $o(){if(!we()){console.log(Ai.red(`You are not logged in. Run \`${p.nameLower} login\` first.`));return}let t=Kc();t.start("Fetching projects...");try{let{data:i}=await v.get("/projects");if(t.stop("Projects loaded."),i.status!=="success"||!i.projects||i.projects.length===0){console.log(Ai.yellow(`No projects found. Run \`${p.nameLower} init\` to create one.`));return}let n=i.projects.map(b=>({value:b.projectId,label:`${b.name} (${b.slug})`})),r=await Gc({message:"Select a project to link:",options:n});if(Vc(r))return;let o=zc.join(process.cwd(),p.configFileName),s={};if($n.existsSync(o))try{s=JSON.parse($n.readFileSync(o,"utf-8"))}catch{}let l=i.projects.find(b=>b.projectId===r),a=s.android?.package||Je("android"),d=s.ios?.bundleIdentifier||Je("ios"),c=s.android||{},u=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},m={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||Wc(),scheme:l?.slug?.toLowerCase()||"app",android:{...c,package:a||"",versionCode:c.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:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:wo(f.ascAppId),appleTeamId:wo(f.appleTeamId)}}}};$n.writeFileSync(o,JSON.stringify(m,null,2)),jc(Ai.green(`Linked to project ${m.name} (${m.slug})`))}catch(i){t.stop(Ai.red("Error fetching projects: "+i.message))}}import{outro as Yc,text as Ii,select as Jc,spinner as qc,isCancel as jt}from"@clack/prompts";import Gt from"chalk";import Xc from"fs";import Zc from"path";import{randomUUID as Qc}from"crypto";var ed=()=>process.versions.node.split(".")[0]||"24";async function Po(){if(!we()){console.log(Gt.red(`You are not logged in. Run \`${p.nameLower} login\` first.`));return}let t=await Ii({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(jt(t))return;let i=await Ii({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(jt(i))return;let n=await Jc({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(jt(n))return;let r="";if(n==="android"||n==="all"){let l=Je("android");if(r=await Ii({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),jt(r))return}let o="";if(n==="ios"||n==="all"){let l=Je("ios");if(o=await Ii({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),jt(o))return}let s=qc();s.start("Creating project...");try{let l=Qc(),d={projectId:l,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:c}=await v.post("/projects",d);if(c.status==="success"){s.stop(Gt.green("Project created successfully!"));let u=Zc.join(process.cwd(),p.configFileName);Xc.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:i,nodeVersion:ed(),...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)),Yc(Gt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Gt.red("creation failed: "+c.message))}catch(l){s.stop(Gt.red("Network error: "+l.message))}}import{spinner as vo,log as ve}from"@clack/prompts";import _i from"chalk";import Ro from"fs";import td from"path";function Do(e,t,i,n){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=n?` ${n}`:"";return r===401?`Not logged in or token expired while trying to ${i}${s}. Run \`${p.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${i}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${p.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 ${i}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${i}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${i}${s}: ${e?.message||"Unknown error"}`}async function Oo(e,t){let i=we();if(!i){ve.error(`You are not logged in. Run \`${p.nameLower} login\` first.`);return}let n=td.join(process.cwd(),p.configFileName);if(!Ro.existsSync(n)){ve.error(`No ${p.configFileName} found. Run \`${p.nameLower} init\` or \`${p.nameLower} link\` first.`);return}let r;try{r=JSON.parse(Ro.readFileSync(n,"utf-8"))}catch{ve.error(`Failed to parse ${p.configFileName}`);return}let{projectId:o}=r;if(!o){ve.error(`${p.configFileName} is missing projectId.`);return}e==="set"?await id(o,t,i):e==="list"?await nd(o,i):ve.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function id(e,t,i){if(t.length===0){ve.error(`Usage: ${p.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=vo();n.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 c={key:l.trim(),value:d,type:"env",environment:"global",visibility:"secret"},{data:u}=await v.post(`/projects/${e}/secrets`,c);u.status==="success"?r++:(ve.error(`Failed to set ${l}: ${u.message}`),o++)}catch(c){ve.error(Do(c,e,"set",l)),o++}}n.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function nd(e,t){let i=vo();i.start("Fetching environment variables...");try{let{data:n}=await v.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let r=n.secrets||[];r.length===0?ve.info("No environment variables found for this project."):(ve.info(_i.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${_i.cyan(o.key)} = ${s} ${_i.gray(`[${o.environment}]`)}`)}))}else i.stop(_i.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),ve.error(Do(n,e,"list"))}}import{spinner as rd,log as mt,outro as od}from"@clack/prompts";import Pn from"chalk";import Co from"fs";import sd from"path";import{execSync as ad}from"child_process";import ld from"adm-zip";import cd from"axios";import{randomUUID as dd}from"crypto";async function No(e){mt.info(Pn.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Ne();(!t||!t.projectId)&&(mt.error(`No ${p.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let i=t.projectId,n=e.branch||"production",r="1.0.0";try{r=JSON.parse(Co.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{mt.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=rd();o.start(`Compiling JavaScript bundles for OTA (Channel: ${n}, Runtime: ${r})...`);try{ad("npx expo export --platform all",{stdio:"ignore"})}catch(d){o.stop("Compilation failed."),mt.error(`Failed to export JS bundles using Expo: ${d.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=sd.join(process.cwd(),"dist");Co.existsSync(s)||(o.stop("Missing dist folder."),mt.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new ld;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let d=dd(),c=await v.post("/builds/source-upload-url",{projectId:i,buildId:d});if(c.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:f}=c.data;await cd.put(u,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${n}...`),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"android",updateId:`${d}-android`,manifestKey:f}),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:r,platform:"ios",updateId:`${d}-ios`,manifestKey:f}),o.stop("Update Live!"),od(Pn.green(`\u2713 OTA Update natively shipped to the '${n}' channel.`)),mt.info(Pn.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(d){o.stop("Update failed during Cloud Sync."),mt.error(`Upload error: ${d.message}`),process.exit(1)}}import{intro as ud,outro as To,log as _t}from"@clack/prompts";import Ve from"chalk";async function ko(){ud(Ve.blue(`${p.name} CLI - User Profile`));let e=we();if(!e){_t.warn(Ve.yellow("You are not logged in.")),_t.info(`Run \`${p.nameLower} login\` to authenticate.`),To();return}_t.info(`${Ve.bold("Logged in as:")} ${Ve.green(e.email)}`);try{await v.get("/projects");let i=we().token.split(".");if(i.length===3){let n=JSON.parse(Buffer.from(i[1],"base64").toString());if(n.exp){let r=new Date(n.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);_t.info(`${Ve.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else _t.warn(`${Ve.bold("Token status:")} ${Ve.red("Expired")} (Auto-refresh failed)`)}}}catch{_t.warn(`${Ve.bold("Token status:")} ${Ve.red("Unreachable")} (Session might be truly expired)${ei}`)}To(Ve.blue("---"))}import{spawn as md}from"child_process";import{log as rt}from"@clack/prompts";import De from"chalk";import gd from"fs";import pd from"net";async function fd(e){return new Promise(t=>{let i=pd.createServer();i.once("error",n=>{n.code==="EADDRINUSE"?t(!0):t(!1)}),i.once("listening",()=>{i.close(),t(!1)}),i.listen(e,"0.0.0.0")})}async function Lo(e,t=20){let i=e;for(;i<e+t;){if(!await fd(i))return i;i++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var xo=async e=>{rt.info(De.blue(`Starting ${p.name} Dev Orchestrator...`));let t=Ne(),i=e.buildProfile||"development",n=t?Ze(t,i):null,r={...process.env};if(t?.projectId)try{rt.info(De.dim(`Fetching managed secrets for profile: ${i}...`));let u=await v.get(`/projects/${t.projectId}/secrets/export?env=${i}`);u.data?.status==="success"&&u.data.secrets&&(Object.assign(r,u.data.secrets),rt.info(De.magenta(`\u2713 Injected secrets from ${p.name} Dashboard.`)))}catch{rt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,gt(t,p.envPrefix)),n&&(Object.assign(r,gt(n,`${p.envPrefix}PROFILE_`)),n.env&&Object.assign(r,n.env));let o=!1;try{let u=JSON.parse(gd.readFileSync("package.json","utf-8"));o=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{rt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||n?.port||8081),l=await Lo(s);l!==s&&rt.info(De.yellow(`Port ${s} is busy. ${p.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 u=[`${De.cyan("i")} open iOS simulator`,`${De.cyan("a")} open Android emulator/device`,`${De.cyan("w")} open web`,`${De.cyan("r")} reload app`];rt.info([De.bold("Launch controls"),...u.map(f=>` ${f}`),"",De.dim("Direct launch: mach start --ios | --android | --web"),De.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1220
|
+
`))}else rt.info(De.dim(`Metro URL: http://localhost:${l}`));let c=md(a,d,{stdio:"inherit",env:r});return new Promise((u,f)=>{c.on("exit",m=>{m===0?u():f(new Error(`Dev server exited with code ${m}`))}),c.on("error",m=>{f(m)})})};import{log as $e}from"@clack/prompts";import Ue from"chalk";var Mo=async e=>{let t=Ne();t||($e.error(Ue.red(`No ${p.configFileName} found in the current directory.`)),process.exit(1));let i=e.profile||"development",n=Ze(t,i);if(e.json){console.log(JSON.stringify({project:t,resolved:n},null,2));return}$e.info(Ue.bgBlue.white(` Resolved ${p.name} Config [${i}] `)),$e.info(Ue.dim("----------------------------------------")),$e.info(`${Ue.blue("Project ID:")} ${t.projectId}`),$e.info(`${Ue.blue("Name:")} ${t.name}`),$e.info(`${Ue.blue("Scheme:")} ${t.scheme}`),n?($e.info(Ue.dim(`
|
|
1221
|
+
Profile Settings:`)),$e.info(`${Ue.cyan("Distribution:")} ${n.distribution||"none"}`),$e.info(`${Ue.cyan("Development Client:")} ${n.developmentClient||"false"}`),n.env&&Object.keys(n.env).length>0&&($e.info(Ue.dim(`
|
|
1222
|
+
Environment Variables:`)),Object.entries(n.env).forEach(([r,o])=>{$e.info(` ${r}=${o}`)}))):$e.warn(`Profile '${i}' not found.`),$e.info(Ue.dim("----------------------------------------"))};import{log as Be,spinner as zt,text as Uo,select as Bo,confirm as hd,isCancel as Kt,cancel as Vt,outro as Wt,note as yd}from"@clack/prompts";import re from"chalk";import{execSync as Sd}from"child_process";async function bd(){try{let e=Sd("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(n=>n.connectionProperties?.transportType==="wired"||n.connectionProperties?.transportType==="localNetwork").map(n=>({udid:n.identifier,name:n.deviceProperties?.name||"Unknown Device",model:n.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}async function Ed(e){let t=e.udid,i=e.name,n="";if(!t){let o=zt();o.start("Scanning for connected iOS devices...");let s=await bd();if(o.stop(s.length>0?`Found ${s.length} device(s)`:"No devices detected"),s.length===1)t=s[0].udid,i=i||s[0].name,n=s[0].model,Be.info(`Detected: ${re.bold(i)} (${re.dim(t.substring(0,12)+"...")})`);else if(s.length>1){let l=await Bo({message:"Select a device to register:",options:s.map(d=>({value:d.udid,label:`${d.name} (${d.model})`,hint:d.udid.substring(0,12)+"..."}))});if(Kt(l)){Vt("Cancelled");return}t=l;let a=s.find(d=>d.udid===t);i=i||a.name,n=a.model}else{Be.info(re.dim("No connected devices found. Enter UDID manually."));let l=await Uo({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(a){if(a.length<10)return"UDID seems too short"}});if(Kt(l)){Vt("Cancelled");return}t=l}}if(!i){let o=await Uo({message:"Device name:",placeholder:"Nitesh's iPhone",validate(s){if(s.length===0)return"Name is required"}});if(Kt(o)){Vt("Cancelled");return}i=o}let r=zt();r.start("Registering device...");try{await v.post("/devices",{udid:t,name:i,platform:"ios",model:n||void 0,addedVia:"cli"}),r.stop(re.green("Device registered!")),Be.info(` ${re.bold("Name:")} ${i}`),Be.info(` ${re.bold("UDID:")} ${re.dim(t)}`)}catch(o){r.stop(re.red("Failed to register device")),Be.error(o.response?.data?.message||o.message)}Wt(re.blue("---"))}async function Ad(){let e=zt();e.start("Fetching registered devices...");try{let i=(await v.get("/devices")).data.devices||[];if(e.stop(`${i.length} device(s) registered`),i.length===0){Be.info(re.dim(`No devices registered yet. Run \`${p.nameLower} device register\` to add one.`)),Wt(re.blue("---"));return}let n=i.map(r=>{let o=new Date(r.createdAt).toLocaleDateString();return` ${re.bold(r.name.padEnd(24))} ${re.dim(r.udid.padEnd(28))} ${re.cyan(r.addedVia.padEnd(10))} ${re.dim(o)}`});yd(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
1216
1223
|
`+n.join(`
|
|
1217
|
-
`),"Registered Devices")}catch(t){e.stop(
|
|
1218
|
-
`),d
|
|
1219
|
-
`),c
|
|
1220
|
-
`),c=
|
|
1221
|
-
`),c=
|
|
1222
|
-
`);/__DEV__/.test(
|
|
1223
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1224
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let c=
|
|
1225
|
-
`)),s.length>0){me.info(
|
|
1226
|
-
`));for(let a of s)me.error(de.red(`${de.bold(a.name)} ${de.dim(`(${a.arch})`)}`)),me.info(de.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${es})`))}return l.length>0&&(console.log(""),me.success(de.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(me.success(de.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(me.error(de.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),me.info(de.yellow("To fix this:")),me.info(de.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),me.info(de.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),me.info(de.dim(" 3. Update third-party libraries that ship prebuilt .so files")),me.info(de.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),me.info(de.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return i.stop("Analysis failed."),me.error(de.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{qe.rmSync(n,{recursive:!0,force:!0})}catch{}}}function Dd(e){let t=qe.openSync(e,"r");try{let i=Buffer.alloc(64);if(qe.readSync(t,i,0,64,0),!i.subarray(0,4).equals(Rd))return null;let n=i[4]===2,r=i[5]===1,o=(f,m)=>r?f.readUInt16LE(m):f.readUInt16BE(m),s=(f,m)=>r?f.readUInt32LE(m):f.readUInt32BE(m),l=(f,m)=>Number(r?f.readBigUInt64LE(m):f.readBigUInt64BE(m)),a,d,c;n?(a=l(i,32),d=o(i,54),c=o(i,56)):(a=s(i,28),d=o(i,42),c=o(i,44));let u=null;for(let f=0;f<c;f++){let m=Buffer.alloc(d);if(qe.readSync(t,m,0,d,a+f*d),s(m,0)!==vd)continue;let U;n?U=l(m,48):U=s(m,28),U>0&&(u===null||U<u)&&(u=U)}return u??0}catch{return null}finally{qe.closeSync(t)}}function is(e){let t=[];if(!qe.existsSync(e))return t;let i=qe.readdirSync(e,{withFileTypes:!0});for(let n of i){let r=$t.join(e,n.name);n.isDirectory()?t.push(...is(r)):n.name.endsWith(".so")&&t.push(r)}return t}function Od(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var os=async e=>{if($e()||(Ce.error(He.red(`You are not logged in. Run \`${p.nameLower} login\` first.`)),process.exit(1)),e.apk){await Td(e);return}let i=process.cwd(),n=Ni.join(i,"package.json");Xt.existsSync(n)||(Ce.error(He.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(Xt.readFileSync(n,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ce.info(He.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ce.info(He.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ce.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await qo(i,s);e.json?console.log(JSON.stringify(Qo(l,r),null,2)):Zo(l,e.severity);let a=l.some(c=>c.findings.some(u=>u.severity==="critical")),d=l.some(c=>c.findings.some(u=>u.severity==="high"));(a||d)&&process.exit(1)},ns=["16kb"];async function Td(e){let t=e.category?.toLowerCase();t&&!ns.includes(t)&&(Ce.error(He.red(`Unknown APK check category: "${t}"`)),Ce.info(He.dim(`Available APK checks: ${ns.join(", ")}`)),process.exit(1));let i=await kd(e.apk);i||process.exit(1);let n=!t,r=!1;(n||t==="16kb")&&(await ts(i)||(r=!0)),r&&process.exit(1)}async function kd(e){if(e.startsWith("build:")){let i=e.slice(6);return await Ld(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await ss(e);let t=Ni.resolve(e);return Xt.existsSync(t)?t:(Ce.error(He.red(`APK file not found: ${t}`)),null)}async function Ld(e){let t=rs();t.start(`Fetching APK from build ${e}...`);try{let i=await R.get(`/build/${e}`);if(i.data.status!=="success")throw new Error(i.data.message);let n=i.data.build;if(!n)throw new Error("Build not found");let r=n.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"),Ce.error(He.red("This build does not have an APK artifact.")),Ce.info(He.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await ss(r.url))}catch(i){return t.stop("Failed to fetch build"),Ce.error(He.red(i.message)),null}}async function ss(e){let t=rs();t.start("Downloading APK...");try{let i=Xt.mkdtempSync(Ni.join(Cd.tmpdir(),`${p.nameLower}-audit-`)),n=Ni.join(i,"app.apk"),r=await Nd.get(e,{responseType:"arraybuffer"});Xt.writeFileSync(n,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),n}catch(i){return t.stop("Download failed"),Ce.error(He.red(`Failed to download APK: ${i.message}`)),null}}var Ud=console.log;console.log=()=>{};Md();console.log=Ud;Ae(ye.bgCyan.black(p.cliTag("Production Build Orchestrator")));var Fd=Bd(import.meta.url),Hd=Fd("../package.json"),ee=new xd;ee.name(p.nameLower).description(`${p.name} CLI: Powerful Cloud Infrastructure Tools`).version(Hd.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);ee.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 io(e)});ee.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Hosting"))),await kn()});ee.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=>{Ae(ye.bgCyan.black(p.cliTag("Sitemap Generator"))),await Un(e)});ee.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)","production").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 Pt("--build-id <id>","Internal build ID").hideHelp()).addOption(new Pt("--project-id <id>","Internal project ID").hideHelp()).addOption(new Pt("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Pt("--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("--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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=ee.opts();t.yes=t.yes||i.yes,t.quiet=t.quiet||i.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||Ae(ye.bgCyan.black(p.cliTag("Cloud Build"))),await ci(t)});ee.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("--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").action(async e=>{Ae(ye.bgCyan.black(p.cliTag("Maestro Testing"))),await hr(e)});ee.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=>{Ae(ye.bgCyan.black(p.cliTag("OTA Update"))),await Io(e)});ee.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 Pt("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Pt("--project-id <id>","Internal project ID").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=ee.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,Ae(ye.bgCyan.black(p.cliTag("Store Submission"))),await Eo(e)});ee.command("login").description(`Login to ${p.name} Dashboard`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Login"))),await so()});ee.command("logout").description(`Logout from ${p.name} on this machine`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Logout"))),await ao()});ee.command("link").description(`Link local directory to a ${p.name} Project`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Link Project"))),await co()});ee.command("me").description("Display currently logged in user details").action(async()=>{await wo()});ee.command("init").description(`Create a new ${p.name} Project`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Init Project"))),await uo()});ee.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,t)=>{Ae(ye.bgCyan.black(p.cliTag("Env Manager"))),await go(e,t)});ee.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=>{Ae(ye.bgCyan.black(p.cliTag("Dev Server"))),await Po(e)});ee.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 vo(e)});ee.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-G45XNNRU.js");await t(e)});ee.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=>{Ae(ye.bgCyan.black(p.cliTag("Credentials Setup"))),await Rt(e),as(ye.green("Done!"))});ee.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=>{Ae(ye.bgCyan.black(p.cliTag("Service Credentials"))),await Nn(e),as(ye.green("Done!"))});var $n=ee.command("device").description("Manage registered iOS test devices");$n.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").action(async e=>{await Ii("register",e)});$n.command("list").description("List all registered devices").action(async()=>{await Ii("list",{})});$n.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await Ii("remove",e)});ee.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=>{Ae(ye.bgCyan.black(p.cliTag(e.apk?"APK Audit":"Security Audit"))),await os(e)});var jd=new Set(["login","logout","agent"]);ee.hook("preAction",(e,t)=>{let i=t.name(),n=t.opts?.()||{};i==="maestro"&&n.local||jd.has(i)||Dn()});ee.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1227
|
-
See --help for a list of available commands.`,
|
|
1224
|
+
`),"Registered Devices")}catch(t){e.stop(re.red("Failed to fetch devices")),Be.error(t.response?.data?.message||t.message)}Wt(re.blue("---"))}async function Id(e){let t=e.udid;if(!t){let r=zt();r.start("Fetching registered devices...");try{let s=(await v.get("/devices")).data.devices||[];if(r.stop(`${s.length} device(s) found`),s.length===0){Be.info(re.dim("No devices to remove.")),Wt(re.blue("---"));return}let l=await Bo({message:"Select device to remove:",options:s.map(a=>({value:a.udid,label:a.name,hint:a.udid.substring(0,12)+"..."}))});if(Kt(l)){Vt("Cancelled");return}t=l}catch(o){r.stop(re.red("Failed to fetch devices")),Be.error(o.response?.data?.message||o.message);return}}let i=await hd({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(Kt(i)||!i){Vt("Cancelled");return}let n=zt();n.start("Removing device...");try{await v.delete(`/devices/${encodeURIComponent(t)}`),n.stop(re.green("Device removed"))}catch(r){n.stop(re.red("Failed to remove device")),Be.error(r.response?.data?.message||r.message)}Wt(re.blue("---"))}async function wi(e,t){switch(e){case"register":await Ed(t);break;case"list":await Ad();break;case"remove":await Id(t);break;default:Be.error(`Unknown action: ${e}`)}}import{log as Ce,spinner as ms}from"@clack/prompts";import He from"chalk";import ki from"path";import qt from"fs";import iu from"os";import nu from"axios";var Oe=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Oe||{}),Fe=(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))(Fe||{});import{spinner as rs,log as Jt}from"@clack/prompts";import Pe from"chalk";import{execSync as zd}from"child_process";import os from"fs";import ss from"path";import ot from"fs";import Yt from"path";import{execSync as _d}from"child_process";var Fo={"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"}},wd={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 $d(e){try{let i=_d("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(i)}catch{}let t=Yt.join(e,"app.json");if(ot.existsSync(t))try{let i=JSON.parse(ot.readFileSync(t,"utf-8"));return i.expo||i}catch{}return null}function Pd(e){let t=[],i=Yt.join(e,"node_modules");if(!ot.existsSync(i))return t;let n=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=Yt.join(o,"android","src","main","AndroidManifest.xml");if(!ot.existsSync(l))return;let a=ot.readFileSync(l,"utf-8"),d;for(;(d=n.exec(a))!==null;)t.push({pkg:s,permission:d[1]});n.lastIndex=0}for(let o of ot.readdirSync(i)){if(o.startsWith("."))continue;let s=Yt.join(i,o);if(o.startsWith("@")){if(!ot.statSync(s).isDirectory())continue;for(let l of ot.readdirSync(s))r(Yt.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Ho(e,t){let i=[],n=1,r=$d(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let d of o){let c=Fo[d];c&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${d.split(".").pop()} declared`,description:c.description,severity:c.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Pd(e);for(let{pkg:d,permission:c}of l){let u=Fo[c];u&&(s.includes(c)||o.includes(c)||i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${c.split(".").pop()} injected by ${d}`,description:`${u.description}. Auto-injected via ${d} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${d}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${c}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[d,c]of Object.entries(wd))d in a&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`iOS: ${d} declared`,description:c.description,severity:c.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:i,durationMs:0}}import Rn from"fs";import $i from"path";var Rd=[{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"}],vd=new Set([".ts",".tsx",".js",".jsx"]),Dd=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function jo(e){let t=[],i=Rn.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Dd.has(n.name))continue;let r=$i.join(e,n.name);n.isDirectory()?t.push(...jo(r)):vd.has($i.extname(n.name))&&t.push(r)}return t}function Od(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function Cd(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Go(e,t){let i=[],n=$i.join(e,"src"),r=Rn.existsSync(n)?n:e,o=jo(r);for(let s of o){let a=Rn.readFileSync(s,"utf-8").split(`
|
|
1225
|
+
`),d=$i.relative(e,s);for(let c=0;c<a.length;c++){let u=a[c];if(!Od(u)&&!Cd(u))for(let{id:f,pattern:m,severity:b,label:U}of Rd)m.lastIndex=0,m.test(u)&&i.push({id:f,title:U,description:`Potential ${U.toLowerCase()} found in source code`,severity:b,category:"secrets",file:d,line:c+1,recommendation:`Move to environment variables or a secrets manager. Use \`${p.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:i,durationMs:0}}import{execSync as Nd}from"child_process";var Td={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function Ko(e,t){let i=[],n=1,r;try{r=Nd("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=Td[a.severity]||"info",c=Array.isArray(a.via)?a.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(a.via);i.push({id:`DEP-${String(n++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${c}. 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:i,durationMs:0}}import Pi from"fs";import Ri from"path";var kd=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,Vo=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,Ld=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,xd=new Set([".ts",".tsx",".js",".jsx"]),Md=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function zo(e){let t=[];if(!Pi.existsSync(e))return t;let i=Pi.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Md.has(n.name))continue;let r=Ri.join(e,n.name);n.isDirectory()?t.push(...zo(r)):xd.has(Ri.extname(n.name))&&t.push(r)}return t}async function Wo(e,t){let i=[],n=1,r=Ri.join(e,"src"),o=Pi.existsSync(r)?r:e,s=zo(o);for(let l of s){let a=Pi.readFileSync(l,"utf-8");if(!Ld.test(a))continue;let d=a.split(`
|
|
1226
|
+
`),c=Ri.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u];Vo.lastIndex=0;let m;for(;(m=Vo.exec(f))!==null;){let b=m[1];kd.test(b)&&i.push({id:`STOR-${String(n++).padStart(3,"0")}`,title:`AsyncStorage used for "${b}"`,description:`Sensitive data key "${b}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:c,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:i,durationMs:0}}import vi from"fs";import Di from"path";var Yo=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Ud=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Bd=new Set([".ts",".tsx",".js",".jsx"]),Fd=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Jo(e){let t=[];if(!vi.existsSync(e))return t;let i=vi.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Fd.has(n.name))continue;let r=Di.join(e,n.name);n.isDirectory()?t.push(...Jo(r)):Bd.has(Di.extname(n.name))&&t.push(r)}return t}async function qo(e,t){let i=[],n=1,r=Di.join(e,"src"),o=vi.existsSync(r)?r:e,s=Jo(o);for(let l of s){let d=vi.readFileSync(l,"utf-8").split(`
|
|
1227
|
+
`),c=Di.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u],m=f.trim();if(m.startsWith("//")||m.startsWith("*"))continue;Yo.lastIndex=0;let b;for(;(b=Yo.exec(f))!==null;){let U=b[1],k=Ud.test(U);i.push({id:`NET-${String(n++).padStart(3,"0")}`,title:`Insecure HTTP URL${k?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${U}`,severity:k?"high":"medium",category:"network",file:c,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:i,durationMs:0}}import Oi from"fs";import Ci from"path";var Xo=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,Zo=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Hd=new Set([".ts",".tsx",".js",".jsx"]),jd=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Qo(e){let t=[];if(!Oi.existsSync(e))return t;let i=Oi.readdirSync(e,{withFileTypes:!0});for(let n of i){if(jd.has(n.name))continue;let r=Ci.join(e,n.name);n.isDirectory()?t.push(...Qo(r)):Hd.has(Ci.extname(n.name))&&t.push(r)}return t}async function es(e,t){let i=[],n=1,r=Ci.join(e,"src"),o=Oi.existsSync(r)?r:e,s=Qo(o);for(let l of s){let d=Oi.readFileSync(l,"utf-8").split(`
|
|
1228
|
+
`),c=Ci.relative(e,l);for(let u=0;u<d.length;u++){let f=d[u],m=f.trim();if(!(m.startsWith("//")||m.startsWith("*"))&&(Xo.lastIndex=0,Xo.test(f)&&i.push({id:`DBG-${String(n++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:c,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),Zo.lastIndex=0,Zo.test(f))){let b=d.slice(Math.max(0,u-3),u).join(`
|
|
1229
|
+
`);/__DEV__/.test(b)||i.push({id:`DBG-${String(n++).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:c,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:i,durationMs:0}}import ts from"fs";import vn from"path";var Gd=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 Kd(e){let t=[vn.join(e,"android","app","src","main","AndroidManifest.xml"),vn.join(e,"android","AndroidManifest.xml")];for(let i of t)if(ts.existsSync(i))return i;return null}async function is(e,t){let i=[],n=1,r=Kd(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=ts.readFileSync(r,"utf-8"),s=vn.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let d=a[1],c=a[2],f=c.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Gd.has(f))continue;let m=/android:exported="true"/.test(c),b=/android:permission="/.test(c);m&&!b&&i.push({id:`MAN-${String(n++).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)&&i.push({id:`MAN-${String(n++).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)&&i.push({id:`MAN-${String(n++).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:i,durationMs:0}}import Ni from"fs";import Dn from"path";function Vd(e){let t=Dn.join(e,"ios");if(!Ni.existsSync(t))return null;let i=Ni.readdirSync(t,{withFileTypes:!0});for(let n of i){if(!n.isDirectory()||n.name==="Pods"||n.name.startsWith("."))continue;let r=Dn.join(t,n.name,"Info.plist");if(Ni.existsSync(r))return r}return null}async function ns(e,t){let i=[],n=1,r=Vd(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=Ni.readFileSync(r,"utf-8"),s=Dn.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)&&i.push({id:`ATS-${String(n++).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 c=d[1].match(/<key>([^<]+)<\/key>/g);if(c)for(let u of c){let f=u.replace(/<\/?key>/g,"");f!=="NSExceptionDomains"&&i.push({id:`ATS-${String(n++).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:i,durationMs:0}}var Wd=[{category:"permissions",label:"Permission Audit",fn:Ho,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Go,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:Ko,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:Wo,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:qo,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:es,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:is,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:ns,requiresPrebuild:!0}];async function as(e,t){let i=Wd;t.category&&(i=i.filter(s=>s.category===t.category),i.length===0&&(Jt.error(Pe.red(`Unknown category: ${t.category}`)),Jt.info(Pe.dim(`Available: ${Object.values(Fe).join(", ")}`)),process.exit(1)));let n=i.filter(s=>!s.requiresPrebuild),r=i.filter(s=>s.requiresPrebuild),o=[];for(let s of n){let l=rs();l.start(Pe.dim(`Running ${s.label}...`));try{let a=Date.now(),d=await s.fn(e,t);d.durationMs=Date.now()-a,o.push(d);let c=d.findings.length;l.stop(c>0?Pe.yellow(`${s.label} \u2014 ${c} finding(s)`):Pe.green(`${s.label} \u2014 clean`))}catch(a){l.stop(Pe.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=ss.join(e,"android"),l=ss.join(e,"ios"),a=os.existsSync(s)||os.existsSync(l);if(!a&&t.prebuild){t.json||Jt.info(Pe.dim(`
|
|
1230
|
+
Running expo prebuild for deeper analysis...`));try{zd("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return Jt.warn(Pe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||Jt.info(Pe.dim(`
|
|
1231
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let d of r){let c=rs();c.start(Pe.dim(`Running ${d.label}...`));try{let u=Date.now(),f=await d.fn(e,t);f.durationMs=Date.now()-u,o.push(f);let m=f.findings.length;c.stop(m>0?Pe.yellow(`${d.label} \u2014 ${m} finding(s)`):Pe.green(`${d.label} \u2014 clean`))}catch(u){c.stop(Pe.red(`${d.label} \u2014 error`)),o.push({category:d.category,label:d.label,findings:[],durationMs:0,error:u.message})}}}return o}import ge from"chalk";import{log as fe}from"@clack/prompts";var wt={critical:ge.bgRed.white.bold,high:ge.red.bold,medium:ge.yellow.bold,low:ge.blue,info:ge.dim},Ti={critical:0,high:1,medium:2,low:3,info:4};function Yd(e,t){if(!t)return!0;let i=Ti[t];return i===void 0?!0:Ti[e]<=i}function ls(e,t){let i=0,n={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(d=>Yd(d.severity,t));if(l.length===0&&!s.error)continue;if(fe.info(""),fe.info(ge.bold(` ${s.label}`)+ge.dim(` ${l.length} finding(s)`)),fe.info(ge.dim(" "+"\u2500".repeat(60))),s.error){fe.error(ge.red(` Error: ${s.error}`));continue}let a=[...l].sort((d,c)=>Ti[d.severity]-Ti[c.severity]);for(let d of a){let c=wt[d.severity](` ${d.severity.toUpperCase()} `);fe.info(` ${c} ${ge.bold(d.id)} ${d.title}`),fe.info(ge.dim(` ${d.description}`)),d.file&&fe.info(ge.dim(` File: ${d.file}${d.line?`:${d.line}`:""}`)),fe.info(ge.cyan(` Fix: ${d.recommendation}`)),fe.info(""),n[d.severity]++,i++}}fe.info(""),fe.info(ge.bold(" Summary")),fe.info(ge.dim(" "+"\u2500".repeat(60))),fe.info(` Total: ${ge.bold(String(i))} finding(s)`),fe.info(` ${wt.critical(` ${n.critical} Critical `)} ${wt.high(` ${n.high} High `)} ${wt.medium(` ${n.medium} Medium `)} ${wt.low(` ${n.low} Low `)} ${wt.info(` ${n.info} Info `)}`);let r=n.critical>0,o=n.high>0;r||o?(fe.info(""),fe.error(ge.red.bold(` FAIL \u2014 ${n.critical} critical, ${n.high} high issue(s) found`))):i>0?(fe.info(""),fe.warn(ge.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(fe.info(""),fe.success(ge.green.bold(" PASS \u2014 no issues found")))}function cs(e,t){let i=e.flatMap(r=>r.findings),n={};for(let r of Object.values(Oe))n[r]=i.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:i.length,...n},passed:n.critical===0&&n.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:i}}import{log as me,spinner as Jd}from"@clack/prompts";import ce from"chalk";import Xe from"fs";import qd from"os";import $t from"path";import{execSync as Xd}from"child_process";var ds=16384,Zd=1,Qd=Buffer.from([127,69,76,70]);async function us(e){me.info(ce.bold.underline("16KB Page Alignment Check")),console.log("");let t=$t.resolve(e);if(!Xe.existsSync(t))return me.error(ce.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return me.error(ce.red("The provided file is not an APK file.")),!1;let i=Jd();i.start("Extracting and analyzing native libraries...");let n=Xe.mkdtempSync($t.join(qd.tmpdir(),"mach-16kb-"));try{try{Xd(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${n}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=ps($t.join(n,"lib"));if(r.length===0)return i.stop("Analysis complete."),me.info(ce.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),me.info(ce.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let d=$t.relative(n,a),c=tu(d),u=$t.basename(a),f=eu(a);f!==null&&o.push({name:u,filePath:d,arch:c,align:f,compatible:f>=ds})}if(i.stop("Analysis complete."),o.length===0)return me.info(ce.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(me.info(ce.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1232
|
+
`)),s.length>0){me.info(ce.red.bold(`Incompatible libraries:
|
|
1233
|
+
`));for(let a of s)me.error(ce.red(`${ce.bold(a.name)} ${ce.dim(`(${a.arch})`)}`)),me.info(ce.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${ds})`))}return l.length>0&&(console.log(""),me.success(ce.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(me.success(ce.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(me.error(ce.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),me.info(ce.yellow("To fix this:")),me.info(ce.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),me.info(ce.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),me.info(ce.dim(" 3. Update third-party libraries that ship prebuilt .so files")),me.info(ce.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),me.info(ce.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return i.stop("Analysis failed."),me.error(ce.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{Xe.rmSync(n,{recursive:!0,force:!0})}catch{}}}function eu(e){let t=Xe.openSync(e,"r");try{let i=Buffer.alloc(64);if(Xe.readSync(t,i,0,64,0),!i.subarray(0,4).equals(Qd))return null;let n=i[4]===2,r=i[5]===1,o=(f,m)=>r?f.readUInt16LE(m):f.readUInt16BE(m),s=(f,m)=>r?f.readUInt32LE(m):f.readUInt32BE(m),l=(f,m)=>Number(r?f.readBigUInt64LE(m):f.readBigUInt64BE(m)),a,d,c;n?(a=l(i,32),d=o(i,54),c=o(i,56)):(a=s(i,28),d=o(i,42),c=o(i,44));let u=null;for(let f=0;f<c;f++){let m=Buffer.alloc(d);if(Xe.readSync(t,m,0,d,a+f*d),s(m,0)!==Zd)continue;let U;n?U=l(m,48):U=s(m,28),U>0&&(u===null||U<u)&&(u=U)}return u??0}catch{return null}finally{Xe.closeSync(t)}}function ps(e){let t=[];if(!Xe.existsSync(e))return t;let i=Xe.readdirSync(e,{withFileTypes:!0});for(let n of i){let r=$t.join(e,n.name);n.isDirectory()?t.push(...ps(r)):n.name.endsWith(".so")&&t.push(r)}return t}function tu(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var gs=async e=>{if(we()||(Ce.error(He.red(`You are not logged in. Run \`${p.nameLower} login\` first.`)),process.exit(1)),e.apk){await ru(e);return}let i=process.cwd(),n=ki.join(i,"package.json");qt.existsSync(n)||(Ce.error(He.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(qt.readFileSync(n,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(Ce.info(He.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),Ce.info(He.dim(`Type: ${o?"Expo":"Bare React Native"}`)),Ce.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await as(i,s);e.json?console.log(JSON.stringify(cs(l,r),null,2)):ls(l,e.severity);let a=l.some(c=>c.findings.some(u=>u.severity==="critical")),d=l.some(c=>c.findings.some(u=>u.severity==="high"));(a||d)&&process.exit(1)},fs=["16kb"];async function ru(e){let t=e.category?.toLowerCase();t&&!fs.includes(t)&&(Ce.error(He.red(`Unknown APK check category: "${t}"`)),Ce.info(He.dim(`Available APK checks: ${fs.join(", ")}`)),process.exit(1));let i=await ou(e.apk);i||process.exit(1);let n=!t,r=!1;(n||t==="16kb")&&(await us(i)||(r=!0)),r&&process.exit(1)}async function ou(e){if(e.startsWith("build:")){let i=e.slice(6);return await su(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await hs(e);let t=ki.resolve(e);return qt.existsSync(t)?t:(Ce.error(He.red(`APK file not found: ${t}`)),null)}async function su(e){let t=ms();t.start(`Fetching APK from build ${e}...`);try{let i=await v.get(`/build/${e}`);if(i.data.status!=="success")throw new Error(i.data.message);let n=i.data.build;if(!n)throw new Error("Build not found");let r=n.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"),Ce.error(He.red("This build does not have an APK artifact.")),Ce.info(He.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await hs(r.url))}catch(i){return t.stop("Failed to fetch build"),Ce.error(He.red(i.message)),null}}async function hs(e){let t=ms();t.start("Downloading APK...");try{let i=qt.mkdtempSync(ki.join(iu.tmpdir(),`${p.nameLower}-audit-`)),n=ki.join(i,"app.apk"),r=await nu.get(e,{responseType:"arraybuffer"});qt.writeFileSync(n,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),n}catch(i){return t.stop("Download failed"),Ce.error(He.red(`Failed to download APK: ${i.message}`)),null}}var cu=console.log;console.log=()=>{};lu();console.log=cu;Ae(ye.bgCyan.black(p.cliTag("Production Build Orchestrator")));var uu=du(import.meta.url),pu=uu("../package.json"),te=new au;te.name(p.nameLower).description(`${p.name} CLI: Powerful Cloud Infrastructure Tools`).version(pu.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);te.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 So(e)});te.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Hosting"))),await Bn()});te.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=>{Ae(ye.bgCyan.black(p.cliTag("Sitemap Generator"))),await Gn(e)});te.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)","production").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 Pt("--build-id <id>","Internal build ID").hideHelp()).addOption(new Pt("--project-id <id>","Internal project ID").hideHelp()).addOption(new Pt("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new Pt("--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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=te.opts();t.yes=t.yes||i.yes,t.quiet=t.quiet||i.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||Ae(ye.bgCyan.black(p.cliTag("Cloud Build"))),await pi(t)});te.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("--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").action(async e=>{Ae(ye.bgCyan.black(p.cliTag("Maestro Testing"))),await Er(e)});te.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=>{Ae(ye.bgCyan.black(p.cliTag("OTA Update"))),await No(e)});te.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 Pt("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new Pt("--project-id <id>","Internal project ID").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=te.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,Ae(ye.bgCyan.black(p.cliTag("Store Submission"))),await li(e)});te.command("login").description(`Login to ${p.name} Dashboard`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Login"))),await Io()});te.command("logout").description(`Logout from ${p.name} on this machine`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Logout"))),await _o()});te.command("link").description(`Link local directory to a ${p.name} Project`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Link Project"))),await $o()});te.command("me").description("Display currently logged in user details").action(async()=>{await ko()});te.command("init").description(`Create a new ${p.name} Project`).action(async()=>{Ae(ye.bgCyan.black(p.cliTag("Init Project"))),await Po()});te.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,t)=>{Ae(ye.bgCyan.black(p.cliTag("Env Manager"))),await Oo(e,t)});te.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=>{Ae(ye.bgCyan.black(p.cliTag("Dev Server"))),await xo(e)});te.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 Mo(e)});te.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-G45XNNRU.js");await t(e)});te.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=>{Ae(ye.bgCyan.black(p.cliTag("Credentials Setup"))),await vt(e),ys(ye.green("Done!"))});te.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=>{Ae(ye.bgCyan.black(p.cliTag("Service Credentials"))),await Mn(e),ys(ye.green("Done!"))});var On=te.command("device").description("Manage registered iOS test devices");On.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").action(async e=>{await wi("register",e)});On.command("list").description("List all registered devices").action(async()=>{await wi("list",{})});On.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await wi("remove",e)});te.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=>{Ae(ye.bgCyan.black(p.cliTag(e.apk?"APK Audit":"Security Audit"))),await gs(e)});var fu=new Set(["login","logout","agent"]);te.hook("preAction",(e,t)=>{let i=t.name(),n=t.opts?.()||{};i==="maestro"&&n.local||fu.has(i)||kn()});te.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1234
|
+
See --help for a list of available commands.`,te.args.join(" ")),process.exit(1)});process.argv.slice(2).length||te.help();te.parse(process.argv);
|