@radhya/mach 1.8.3 → 1.8.5
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 +83 -57
- package/dist/index.js +174 -97
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
`;
|
|
4
|
-
`,
|
|
5
|
-
|
|
6
|
-
CloudFront ID: ${
|
|
7
|
-
CloudFront URL: ${
|
|
8
|
-
${
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
2
|
+
import{a as Te,b as We,c as wi,d as Oi,e as et,f as Ci,h as pt}from"./chunk-NIGYNUTS.js";import{a as m,b as Ri,c as ge,d as vi,e as Nt,f as ut,g as v}from"./chunk-YBL2LBMW.js";import{Command as ga,Option as yo}from"commander";import{configDotenv as ha}from"dotenv";import{intro as ue,outro as So}from"@clack/prompts";import se from"chalk";import{text as Ni,confirm as Eo,spinner as Ao,isCancel as ei,cancel as ft,note as bo,outro as _o}from"@clack/prompts";import mt from"chalk";async function Ti(){try{let e=await Ni({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(o){if(o.length===0)return"Bucket name is required"}});ei(e)&&(ft("Operation cancelled."),process.exit(0));let t=await Ni({message:"Enter Region:",initialValue:"ap-south-1"});ei(t)&&(ft("Operation cancelled."),process.exit(0));let i=await Eo({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});ei(i)&&(ft("Operation cancelled."),process.exit(0));let n=Ao();n.start("Setting up hosting infrastructure...");try{let o=await v.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:i});if(o.data.status!=="success")throw new Error(o.data.message||"Hosting setup failed");n.stop("Hosting setup complete!");let r=o.data,a=`Bucket Name: ${mt.cyan(r.bucketName)}
|
|
3
|
+
`;a+=`Region: ${mt.cyan(r.region)}
|
|
4
|
+
`,a+=`S3 Website URL: ${mt.blue(r.s3WebsiteUrl)}`,r.cloudFrontId&&(a+=`
|
|
5
|
+
|
|
6
|
+
CloudFront ID: ${mt.cyan(r.cloudFrontId)}`,a+=`
|
|
7
|
+
CloudFront URL: ${mt.blue(r.cloudFrontUrl)}`),bo(a,"Setup Complete!"),_o("You are all set!")}catch(o){n.stop("Setup failed"),ft(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){ft(`An unexpected error occurred: ${e.message}`)}}import{readdir as Io,writeFile as Po,access as $o,mkdir as Do}from"fs/promises";import{join as ki}from"path";import{spinner as Ro,text as xi,isCancel as Li,cancel as ti,note as vo,outro as wo}from"@clack/prompts";import Oo from"chalk";async function Co(){let e=["./app","./src/app"];for(let t of e)try{return await $o(t),t}catch{}return null}async function Mi(e){try{let i=await Co()||"./app",n=await xi({message:"Enter path to your app directory:",placeholder:i,initialValue:i,validate(d){if(d.length===0)return"Path is required"}});Li(n)&&(ti("Operation cancelled."),process.exit(0));let o=await xi({message:"Enter your website base URL:",placeholder:"https://example.com",validate(d){if(d.length===0)return"Base URL is required";if(!d.startsWith("http"))return"URL must start with http:// or https://"}});Li(o)&&(ti("Operation cancelled."),process.exit(0));let r=Ro();r.start("Scanning app directory for routes...");let a=await Ui(n);r.stop(`Found ${a.length} routes`);let l=No(a,o),s=e.output||"./public/sitemap.xml";r.start(`Writing sitemap to ${s}...`);let c=s.substring(0,s.lastIndexOf("/"));if(c)try{await Do(c,{recursive:!0})}catch{}await Po(s,l,"utf-8"),r.stop("Sitemap generated successfully!"),vo(`Routes included:
|
|
8
|
+
${a.map(d=>` \u2022 ${d.path}`).join(`
|
|
9
|
+
`)}`,"Sitemap Summary"),wo(`Sitemap saved to ${Oo.cyan(s)}`)}catch(t){ti(`An error occurred: ${t.message}`)}}async function Ui(e,t=""){let i=[];try{let n=await Io(e,{withFileTypes:!0});for(let o of n){let r=ki(e,o.name);if(!(o.name.startsWith("_")||o.name.startsWith("."))){if(o.isDirectory()){let a=await Ui(r,ki(t,o.name));i.push(...a)}else if(o.isFile()){if(o.name==="index.tsx"||o.name==="index.ts"||o.name==="index.jsx"||o.name==="index.js"){let a=t===""?"/":`/${t}`;i.push({path:a,file:r})}else if(o.name.match(/\.(tsx|ts|jsx|js)$/)&&!o.name.includes("_layout")&&!o.name.includes("+")){let a=o.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${a}`.replace(/\/+/g,"/");i.push({path:l,file:r})}}}}}catch(n){throw new Error(`Failed to scan directory ${e}: ${n.message}`)}return i}function No(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(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[.*?\]/g,"/:id"),r=r.replace(/\/+/g,"/"),r===""&&(r="/"),` <url>
|
|
12
12
|
<loc>${t}${r}</loc>
|
|
@@ -15,7 +15,7 @@ ${e.map(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[
|
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as dr}from"crypto";import Se from"path";import ht from"axios";import ur from"os";import{spinner as ai,confirm as rn,isCancel as sn,log as w}from"@clack/prompts";import N from"chalk";import re from"fs";import{execSync as an}from"child_process";import ln from"adm-zip";import{spinner as Mo,log as Tt}from"@clack/prompts";import Hi from"chalk";import Bi from"fs";import Gi from"path";var Fi=`#!/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}}"
|
|
@@ -196,6 +196,13 @@ if [ -f /tmp/android-cache.tar.gz ]; then
|
|
|
196
196
|
tar $TAR_COMPRESS -xf /tmp/android-cache.tar.gz -C /home/ubuntu/build && rm -f /tmp/android-cache.tar.gz && echo "android/ cache restored."
|
|
197
197
|
fi
|
|
198
198
|
|
|
199
|
+
# Older android/ caches may include Gradle outputs and pre-bundled JS from a
|
|
200
|
+
# different build profile. Keep the native project, but force fresh outputs.
|
|
201
|
+
if [ -d "/home/ubuntu/build/android" ]; then
|
|
202
|
+
echo "[CACHE] Pruning restored android build outputs..."
|
|
203
|
+
find /home/ubuntu/build/android -type d \\( -name build -o -name .cxx \\) -prune -exec rm -rf {} + 2>/dev/null || true
|
|
204
|
+
fi
|
|
205
|
+
|
|
199
206
|
echo "Cache restore complete."
|
|
200
207
|
|
|
201
208
|
# CodeArtifact Logic \u2014 use env var if already set (pass as project secret)
|
|
@@ -246,12 +253,20 @@ if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
|
246
253
|
fi
|
|
247
254
|
|
|
248
255
|
# --- Prebuild (expo only) ---
|
|
249
|
-
# Compute a hash of native-affecting files
|
|
250
|
-
#
|
|
256
|
+
# Compute a hash of native-affecting files and the Mach-injected app env to
|
|
257
|
+
# decide if android/ cache is still valid. Env names are project-defined, so the
|
|
258
|
+
# CLI precomputes MACH_ENV_FINGERPRINT from all relevant managed values.
|
|
251
259
|
if grep -q '"expo"' package.json 2>/dev/null; then
|
|
252
260
|
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
253
261
|
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
254
|
-
|
|
262
|
+
PREBUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
263
|
+
PREBUILD_CURRENT_HASH=$(
|
|
264
|
+
{
|
|
265
|
+
cat app.json app.config.ts app.config.js 2>/dev/null
|
|
266
|
+
node -e "try{const p=require('./package.json');const keys=Object.keys({...p.dependencies,...p.devDependencies}).filter(k=>k.startsWith('expo-')||k.startsWith('@expo/')||k.startsWith('@react-native'));console.log(keys.join(','))}catch(e){}" 2>/dev/null
|
|
267
|
+
printf '%s\\n' "$PREBUILD_ENV_HASH"
|
|
268
|
+
} | md5sum | cut -d' ' -f1
|
|
269
|
+
)
|
|
255
270
|
|
|
256
271
|
ANDROID_CACHE_VALID=false
|
|
257
272
|
if [ -f "$PREBUILD_HASH_FILE" ] && [ -d "android" ] && [ -f "android/gradlew" ]; then
|
|
@@ -468,7 +483,7 @@ if [ -d "/home/ubuntu/build/node_modules" ] && [ ! -z "$PRESIGNED_CACHE_NODE_MOD
|
|
|
468
483
|
fi
|
|
469
484
|
|
|
470
485
|
if [ -d "/home/ubuntu/build/android" ] && [ ! -z "$PRESIGNED_CACHE_ANDROID_UPLOAD" ]; then
|
|
471
|
-
(tar $TAR_COMPRESS -cf /tmp/android-cache.tar.gz -C /home/ubuntu/build
|
|
486
|
+
(find /home/ubuntu/build/android -type d \\( -name build -o -name .cxx \\) -prune -exec rm -rf {} + 2>/dev/null || true; tar $TAR_COMPRESS -cf /tmp/android-cache.tar.gz -C /home/ubuntu/build --exclude='android/.gradle' --exclude='android/**/build' --exclude='android/**/.cxx' android && curl -X PUT -T /tmp/android-cache.tar.gz "$PRESIGNED_CACHE_ANDROID_UPLOAD" --silent && rm -f /tmp/android-cache.tar.gz && echo "android/ cache saved.") &
|
|
472
487
|
cache_pids+=($!)
|
|
473
488
|
fi
|
|
474
489
|
|
|
@@ -487,12 +502,13 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
487
502
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
488
503
|
sleep 5
|
|
489
504
|
sudo shutdown -h now
|
|
490
|
-
`;var
|
|
491
|
-
`):"",p;if(o){let
|
|
492
|
-
export MACH_APP_NAME="${
|
|
493
|
-
export MACH_BUILD_PROFILE="${
|
|
505
|
+
`;import To from"crypto";var ko=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"]),xo=["PRESIGNED_","KEYSTORE_PASSWORD_"],Lo=e=>!e||ko.has(e)?!1:!xo.some(t=>e.startsWith(t)),Ye=(e,t,i)=>({...e,MACH_BUILD_PROFILE:t,MACH_APP_NAME:i.appName||i.name||"App"}),tt=e=>{let t=Object.entries(e).filter(([i])=>Lo(i)).sort(([i],[n])=>i.localeCompare(n));return To.createHash("sha256").update(JSON.stringify(t)).digest("hex")};var ji=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Ki=async(e,t,i={},n,o)=>{let r=Mo(),a=e.buildProfile||"production",l=a==="production",s=e.apk===!0,c=e.developmentClient?"assembleDebug":l?"bundleRelease":"assembleRelease",d=e.buildCommand||(s?"assembleRelease":c),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(`
|
|
506
|
+
`):"",p;if(o){let $=Gi.isAbsolute(o)?o:Gi.resolve(process.cwd(),o);Bi.existsSync($)?(p=Bi.readFileSync($,"utf-8"),Tt.info(Hi.magenta(`\u2713 Loaded preBuild hook: ${o}`))):Tt.warn(`preBuild script not found at ${$} \u2014 skipping`)}let f=Ye(i,a,e),y=tt(f),D=Fi.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,d).replace("{{NODE_VERSION_SETUP}}",u).replace("{{ENV_VARS}}",`
|
|
507
|
+
export MACH_APP_NAME="${ji(f.MACH_APP_NAME)}"
|
|
508
|
+
export MACH_BUILD_PROFILE="${ji(a)}"
|
|
509
|
+
export MACH_ENV_FINGERPRINT="${y}"
|
|
494
510
|
{{ENV_VARS}}
|
|
495
|
-
`);if(e.dryRun){
|
|
511
|
+
`);if(e.dryRun){Tt.info("User Data Script (dry run):"),console.log(D);return}r.start("Requesting cloud build instance...");try{let $=await v.post("/builds/launch-android",{projectId:n,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:d,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:i,dryRun:e.dryRun,userDataScript:D,preBuildScriptContent:p});if($.data.status!=="success")throw new Error($.data.message||"Failed to launch build instance");let L=$.data.instanceId;return r.stop("Build Started"),Tt.success(Hi.green(`Build initiated on cloud instance (${L}).`)),{instanceId:L}}catch($){r.stop("Android Build Failed");let L=$.response?.data?.message||$.message;throw new Error(`Failed to launch Android build: ${L}`)}};import{spinner as Uo,log as it}from"@clack/prompts";import Ge from"chalk";import Fo from"fs";import{execSync as gt}from"child_process";var Vi=`#!/bin/bash
|
|
496
512
|
# --- Mach Cloud Build Script (iOS) ---
|
|
497
513
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
498
514
|
|
|
@@ -521,6 +537,8 @@ set -e
|
|
|
521
537
|
{{ENV_VARS}}
|
|
522
538
|
|
|
523
539
|
BUILD_ID="{{BUILD_ID}}"
|
|
540
|
+
BUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
541
|
+
echo "[CACHE] Build environment hash: \${BUILD_ENV_HASH:0:12}"
|
|
524
542
|
|
|
525
543
|
# Start log uploader (every 15s via presigned URL, only if changed)
|
|
526
544
|
(
|
|
@@ -576,6 +594,27 @@ else
|
|
|
576
594
|
echo "DerivedData found locally. Skipping download (Persistent Worker Optimization)."
|
|
577
595
|
fi
|
|
578
596
|
|
|
597
|
+
# DerivedData can contain the app bundle and React Native JS generated by a
|
|
598
|
+
# previous profile. Keep compiler/module caches for speed, but drop build
|
|
599
|
+
# products whenever the env fingerprint changes (or old caches have no stamp).
|
|
600
|
+
DD_ENV_HASH_FILE="$DERIVED_DATA_PATH/.mach-env-hash"
|
|
601
|
+
DD_PREVIOUS_ENV_HASH=""
|
|
602
|
+
if [ -f "$DD_ENV_HASH_FILE" ]; then
|
|
603
|
+
DD_PREVIOUS_ENV_HASH=$(cat "$DD_ENV_HASH_FILE" 2>/dev/null || true)
|
|
604
|
+
fi
|
|
605
|
+
if [ -d "$DERIVED_DATA_PATH/Build" ]; then
|
|
606
|
+
if [ -z "$DD_PREVIOUS_ENV_HASH" ]; then
|
|
607
|
+
echo "[CACHE] DerivedData has no env stamp. Pruning stale iOS build products..."
|
|
608
|
+
rm -rf "$DERIVED_DATA_PATH/Build"
|
|
609
|
+
elif [ "$DD_PREVIOUS_ENV_HASH" != "$BUILD_ENV_HASH" ]; then
|
|
610
|
+
echo "[CACHE] Build env changed. Pruning iOS build products..."
|
|
611
|
+
rm -rf "$DERIVED_DATA_PATH/Build"
|
|
612
|
+
else
|
|
613
|
+
echo "[CACHE] DerivedData env stamp matches. Reusing Xcode build products."
|
|
614
|
+
fi
|
|
615
|
+
fi
|
|
616
|
+
echo "$BUILD_ENV_HASH" > "$DD_ENV_HASH_FILE"
|
|
617
|
+
|
|
579
618
|
# 1. Node Modules Cache \u2014 download via presigned URL
|
|
580
619
|
if [ ! -d "node_modules" ] || [ -z "$(ls -A node_modules 2>/dev/null)" ]; then
|
|
581
620
|
echo "Checking node_modules cache..."
|
|
@@ -686,6 +725,9 @@ if [ -f "ios/Podfile" ]; then
|
|
|
686
725
|
cd ..
|
|
687
726
|
fi
|
|
688
727
|
|
|
728
|
+
# Remove stale artifacts from persistent workspaces before archiving.
|
|
729
|
+
rm -rf build.xcarchive build.ipa build.app.zip export ios/build
|
|
730
|
+
|
|
689
731
|
# 6. EAS-Style Automatic Signing (Temporary Keychain)
|
|
690
732
|
echo "[STEP_START:signing] $(date +%s)"
|
|
691
733
|
|
|
@@ -905,6 +947,7 @@ echo "[STEP_START:upload] $(date +%s)"
|
|
|
905
947
|
|
|
906
948
|
# Upload DerivedData Cache via presigned URL
|
|
907
949
|
echo "Uploading DerivedData cache..."
|
|
950
|
+
echo "$BUILD_ENV_HASH" > "$DD_ENV_HASH_FILE"
|
|
908
951
|
tar -czf derived_data.tar.gz -C "$DERIVED_DATA_PATH" .
|
|
909
952
|
if [ ! -z "$PRESIGNED_CACHE_DD_UPLOAD" ]; then
|
|
910
953
|
curl -X PUT -T derived_data.tar.gz "$PRESIGNED_CACHE_DD_UPLOAD" --silent || true
|
|
@@ -930,27 +973,27 @@ touch done
|
|
|
930
973
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
931
974
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
932
975
|
fi
|
|
933
|
-
`;var
|
|
934
|
-
`:
|
|
935
|
-
`);o.message("Generating macOS build script...");let
|
|
936
|
-
`:"";if(i)for(let[
|
|
937
|
-
`}let
|
|
938
|
-
`),
|
|
939
|
-
`):"",
|
|
940
|
-
${
|
|
941
|
-
${
|
|
942
|
-
${
|
|
943
|
-
`)),o(
|
|
944
|
-
`)),o(
|
|
945
|
-
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let
|
|
946
|
-
`)))}let
|
|
947
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),
|
|
948
|
-
`)},
|
|
949
|
-
`))}catch(
|
|
950
|
-
`)}if(await
|
|
951
|
-
`),
|
|
952
|
-
`),
|
|
953
|
-
`),
|
|
976
|
+
`;var zi=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Wi=async(e,t,i={},n)=>{let o=Uo();e.sshHost||(e.sshHost="localhost",it.message(Ge.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Ge.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",a=e.sshKey,l=`${r}@${e.sshHost}`,s=`ssh ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no ${l}`,c=`scp ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no`;try{let d=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(i.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${m.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),gt(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let f=`/tmp/${m.nameLower}-source-${t}.zip`;gt(`${c} ${f} ${l}:${p}/source.zip`,{stdio:"inherit"});let y=e.iosApiKeyPath?`${p}/api_key.p8`:"",D="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),gt(`${c} ${e.iosApiKeyPath} ${l}:${y}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(D=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${y}`));let $={};if(n)try{let U=await v.post(`/builds/${n}/${t}/build-urls`,{platform:"ios"});U.data.status==="success"&&($=U.data.urls)}catch(U){it.warn(Ge.yellow(`Could not fetch build URLs: ${U.message}`))}let L="";if($.credentials&&$.credentials.length>0)for(let U of $.credentials)U.type==="p12"?L+=`curl -sf -o "$CERT_DIR/${U.name}" "${U.downloadUrl}" || true
|
|
977
|
+
`:U.type==="mobileprovision"&&(L+=`curl -sf -o "$PROV_TEMP/${U.name}" "${U.downloadUrl}" || true
|
|
978
|
+
`);o.message("Generating macOS build script...");let B=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
979
|
+
`:"";if(i)for(let[U,F]of Object.entries(i)){let R=F.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");B+=`export ${U}="${R}"
|
|
980
|
+
`}let te=e.buildProfile||"production",E=Ye(i,te,e),H=tt(E),_=[B,$.logUpload?`export PRESIGNED_LOG_UPLOAD="${$.logUpload}"`:"",$.doneMarker?`export PRESIGNED_DONE_MARKER="${$.doneMarker}"`:"",$.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${$.cacheDerivedDataDownload}"`:"",$.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${$.cacheDerivedDataUpload}"`:"",$.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${$.cacheNodeModulesDownload}"`:"",$.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${$.cacheNodeModulesUpload}"`:"",$.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${$.cachePodsDownload}"`:"",$.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${$.cachePodsUpload}"`:"",$.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${$.artifactIpaUpload}"`:"",$.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${$.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${zi(te)}"`,`export MACH_APP_NAME="${zi(E.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${H}"`,`export ${m.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="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
|
|
981
|
+
`),g=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(`
|
|
982
|
+
`):"",A=Vi,I={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":_,"{{CREDENTIAL_DOWNLOADS}}":L,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":D,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":g};Object.entries(I).forEach(([U,F])=>{A=A.split(U).join(F)});let M=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(Fo.writeFileSync(M,A),gt(`${c} ${M} ${l}:${p}/build.sh`),o.stop("Remote script uploaded."),it.info(Ge.cyan("Executing remote build. This might take a while...")),gt(`${s} "bash ${p}/build.sh"`,{stdio:"inherit"}),o.stop("Remote build finished!"),n){o.start("Fetching artifact links...");try{let F=(await v.get(`/builds/${n}/${t}/artifacts`)).data.artifacts||[],R=e.simulator===!0;if(F.length===0&&!R)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),F.length>0){it.success("Build Artifacts Ready:");for(let k of F)console.log(`
|
|
983
|
+
${Ge.yellow(k.name)}:
|
|
984
|
+
${Ge.cyan(k.downloadUrl)}`);console.log(`
|
|
985
|
+
${Ge.dim("Note: Links are valid for 7 days.")}`)}else R&&it.warn("Simulator build completed. No artifacts uploaded.")}catch(U){o.stop("Could not fetch artifacts"),it.warn(Ge.yellow(`Artifact listing failed: ${U.message}`))}}}catch(d){throw o.stop("iOS Build Failed"),d}};import Ho from"crypto";import Ie from"axios";import Yi from"fs";var ke=6e4,Bo=12e4,ii=4,Ue=e=>encodeURIComponent(e),Go=e=>new Promise(t=>setTimeout(t,e));async function Pe(e,t){let i;for(let n=1;n<=ii;n++)try{return await t()}catch(o){if(i=o,n>=ii||!jo(o))throw o;let r=Number(o.response?.headers?.["retry-after"]),a=Number.isFinite(r)&&r>0?r*1e3:Math.min(2e3*n*n,15e3);console.log(`[Google Play] ${e} failed (attempt ${n}/${ii}); retrying in ${Math.round(a/1e3)}s...`),await Go(a)}throw i}function jo(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Ji(e,t){let i;try{let n=await kt(t),o=Ue(e);if(i=(await Pe("create edit",()=>Ie.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${o}/edits`,{},{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.id,!i)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let a=Ue(i),l=0,c=(await Pe("list tracks",()=>Ie.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${o}/edits/${a}/tracks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.tracks||[];for(let d of c)if(d.releases){for(let u of d.releases)if(u.versionCodes)for(let p of u.versionCodes){let f=parseInt(p,10);f>l&&(l=f)}}try{let u=(await Pe("list bundles",()=>Ie.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${o}/edits/${a}/bundles`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.bundles||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}try{let u=(await Pe("list APKs",()=>Ie.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${o}/edits/${a}/apks`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))).data.apks||[];for(let p of u)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}return l}catch(n){let o=n.response?.data?.error?.message||n.message;throw new Error(`Google Play API Error: ${o}`)}finally{if(i)try{let n=await kt(t);await Pe("delete edit",()=>Ie.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Ue(e)}/edits/${Ue(i)}`,{headers:{Authorization:`Bearer ${n}`,Connection:"close"},timeout:ke}))}catch{}}}async function Xi(e){let{packageName:t,serviceAccount:i,aabPath:n,track:o,releaseStatus:r,userFraction:a,changesNotSentForReview:l}=e,s;try{let d={Authorization:`Bearer ${await kt(i)}`,Connection:"close"},u=Ue(t);if(s=(await Pe("create edit",()=>Ie.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits`,{},{headers:d,timeout:ke}))).data.id,!s)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let f=Ue(s),y=Yi.statSync(n),D=await Pe("upload AAB",()=>Ie.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${u}/edits/${f}/bundles`,Yi.createReadStream(n),{headers:{...d,"Content-Type":"application/octet-stream","Content-Length":y.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Bo})),$=Number(D.data.versionCode);if(!$)throw new Error("Google Play upload succeeded but did not return a versionCode.");let L={versionCodes:[String($)],status:r};return(r==="inProgress"||r==="halted")&&typeof a=="number"&&(L.userFraction=a),await Pe("update track",()=>Ie.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${f}/tracks/${Ue(o)}`,{releases:[L]},{headers:d,timeout:ke})),await Pe("commit edit",()=>Ie.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${u}/edits/${f}:commit`,{},{headers:d,params:l?{changesNotSentForReview:!0}:void 0,timeout:ke})),{editId:s,versionCode:$,track:o,releaseStatus:r,userFraction:a}}catch(c){if(s)try{let u=await kt(i);await Pe("delete edit",()=>Ie.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Ue(t)}/edits/${Ue(s)}`,{headers:{Authorization:`Bearer ${u}`,Connection:"close"},timeout:ke}))}catch{}let d=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${d}`)}}async function kt(e){let t=Math.floor(Date.now()/1e3),i=t+3600,n={alg:"RS256",typ:"JWT"},o={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"},r=Buffer.from(JSON.stringify(n)).toString("base64url"),a=Buffer.from(JSON.stringify(o)).toString("base64url"),l=`${r}.${a}`,s=Ho.createSign("RSA-SHA256");s.update(l);let c=s.sign(e.private_key,"base64url"),d=`${l}.${c}`;return(await Pe("OAuth token exchange",()=>Ie.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"},timeout:ke}))).data.access_token}import{spinner as xt,log as b,isCancel as Lt,confirm as Ko,select as ni}from"@clack/prompts";import S from"chalk";import h from"fs";import P from"path";import{execSync as j,spawn as Zi}from"child_process";import $e from"os";import Vo from"crypto";var Qi=(e,t)=>t.filter(i=>h.existsSync(P.join(e,i))).reduce((i,n)=>i.update(h.readFileSync(P.join(e,n))),Vo.createHash("sha256")).digest("hex").slice(0,16),zo=e=>Qi(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Wo=e=>Qi(e,["Podfile","Podfile.lock"]),Yo=e=>{let t=P.join(e,"fingerprint.json");try{return JSON.parse(h.readFileSync(t,"utf-8"))}catch{return{}}},qi=(e,t)=>{h.mkdirSync(e,{recursive:!0}),h.writeFileSync(P.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Jo=7200*1e3,Xo=(e,t)=>{h.mkdirSync(e,{recursive:!0});let i=P.join(e,"build.lock");if(h.existsSync(i))try{let n=JSON.parse(h.readFileSync(i,"utf-8")),o=Date.now()-(n.timestamp||0);if(o<Jo)throw new Error(`Another build is already running for this project (build ${n.buildId}, started ${Math.round(o/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}h.writeFileSync(i,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},qo=(e,t)=>{let i=P.join(e,"build.lock");try{h.existsSync(i)&&JSON.parse(h.readFileSync(i,"utf-8")).buildId===t&&h.unlinkSync(i)}catch{}},xe=(e,t,i=process.cwd(),n={},o,r)=>new Promise((a,l)=>{let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",P.join($e.homedir(),".npm-global/bin")],d=[...(process.env.PATH||"").split(":"),...s].filter((y,D,$)=>y&&$.indexOf(y)===D).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(S.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${d}`));let u={...process.env,...n,PATH:d,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${m.envPrefix}DEBUG`]&&(o(S.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
986
|
+
`)),o(S.magenta(`[ENVIRONMENT] PATH: ${d}
|
|
987
|
+
`)),o(S.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
988
|
+
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let y=P.dirname(process.execPath),D=P.join(y,e);h.existsSync(D)&&(p=D,o&&o(S.dim(`[EXEC] Using absolute path: ${p}
|
|
989
|
+
`)))}let f=Zi(p,t,{stdio:"pipe",cwd:i,shell:!0,env:u,detached:process.platform!=="win32"});if(r){if(r.aborted){if(f.pid)try{process.kill(-f.pid,"SIGTERM")}catch{f.kill()}return l(new Error("Command aborted"))}r.addEventListener("abort",()=>{if(f.pid)try{process.kill(-f.pid,"SIGTERM")}catch{f.kill()}l(new Error("Command aborted"))})}f.stdout.on("data",y=>{let D=y.toString();process.stdout.write(D),o&&o(D)}),f.stderr.on("data",y=>{let D=y.toString();process.stderr.write(D),o&&o(D)}),f.on("close",y=>{y===0?a(y):l(new Error(`Command failed with code ${y}: ${e} ${t.join(" ")}`))}),f.on("error",y=>l(y))}),Zo=e=>{let t=Math.floor(e/1e3%60),i=Math.floor(e/(1e3*60)%60),n=Math.floor(e/(1e3*60*60)%24),o=[];return n>0&&o.push(`${n}h`),i>0&&o.push(`${i}m`),(t>0||o.length===0)&&o.push(`${t}s`),o.join(" ")},nt=(e,t)=>{let i=[];try{if(!h.existsSync(e))return i;let n=h.readdirSync(e);for(let o of n){let r=P.join(e,o);try{let a=h.statSync(r);if(t.some(s=>o.endsWith(s))){i.push(P.resolve(r));continue}a.isDirectory()&&(i=i.concat(nt(r,t)))}catch{}}}catch{}return i},oi=async(e,t,i={},n,o={})=>{let r=xt(),a=Date.now(),l=e.platform,s=e.buildProfile||"production",c=()=>Ye(i,s,e),d=async(g,A={})=>{if(n)for(let I=1;I<=3;I++)try{await v.patch(`/builds/${n}/${t}`,{status:g,...A});return}catch(M){let U=M?.response?.data?.message||M?.message||String(M);console.error(`[reportStatus] attempt ${I}/3 failed (status=${g}): ${U}`),I<3&&await new Promise(F=>setTimeout(F,2e3))}},u=new AbortController,{signal:p}=u,f=null;n&&(f=setInterval(async()=>{try{(await v.get(`/builds/${n}/${t}`)).data.status==="cancelled"&&(b.warn(S.yellow(`
|
|
990
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),u.abort(),f&&clearInterval(f))}catch{}},5e3));let y=P.join(process.cwd(),".mach-cache"),D="setup",$="",L=null,B=async()=>{if(!$||!n)return;let g=$;$="";try{let A=g;Object.values(i).forEach(I=>{if(I&&I.length>5){let M=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");A=A.replace(new RegExp(M,"g"),"[SECRET]")}}),await v.post(`/builds/${n}/${t}/logs`,{log:A,step:D})}catch{}},te=async()=>{L&&(clearTimeout(L),L=null),await B(),qo(y,t),f&&(clearInterval(f),f=null);try{let g=P.join($e.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);h.existsSync(g)&&(j(`security delete-keychain "${g}"`,{stdio:"ignore"}),b.info(S.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let g=P.join($e.homedir(),"Library/MobileDevice/Provisioning Profiles");if(h.existsSync(g)){let A=h.readdirSync(g).filter(I=>I.includes(t)||I.startsWith(`${m.nameLower}-temp-${t}`));for(let I of A)h.unlinkSync(P.join(g,I))}}catch{}},E=async g=>{n&&($+=g,$.length>=8192?(L&&(clearTimeout(L),L=null),await B()):L||(L=setTimeout(()=>{L=null,B()},2e3)))},H=async g=>{D=g,await E(`[STEP_START:${g}] ${Math.floor(Date.now()/1e3)}
|
|
991
|
+
`)},_=async(g,A,I,M)=>await xe(g,A,I,M,U=>{E(U)},p);b.info(S.blue(`\u{1F680} Starting local build for ${l} (${s})...`));try{Xo(y,t)}catch(g){throw await d("failed",{error:g.message}),g}if(await d("building"),await H("setup"),n&&l==="ios"&&!e.simulator)try{let g=parseInt(i.BUILD_NUMBER||"0",10),A=await v.post(`/projects/${n}/next-build-number`,{platform:"ios",startFrom:g});A.data.status==="success"&&(i.BUILD_NUMBER=String(A.data.buildNumber),b.info(S.dim(`Auto build number: ${i.BUILD_NUMBER}`)),await E(`[BUILD_NUMBER] ${i.BUILD_NUMBER}
|
|
992
|
+
`))}catch(g){b.warn(S.yellow(`Could not fetch auto build number: ${g.message}`))}await H("lock"),e.developmentClient?(b.info(S.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):(b.info(S.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 H("clone"),b.info(S.dim("Preparing source...")),await H("read_config");let g=P.join(process.cwd(),m.configFileName);if(h.existsSync(g)){let C=JSON.parse(h.readFileSync(g,"utf-8"))?.build?.[s]||{};await E(`[CONFIG] Profile: ${s}, distribution: ${C.distribution||"not set"}, simulator: ${C.simulator||!1}
|
|
993
|
+
`)}if(await H("read_package"),e.nodeVersion){let O=process.env.NVM_DIR||P.join($e.homedir(),".nvm"),C=P.join(O,"versions","node"),K;if(h.existsSync(C)){let T=h.readdirSync(C).sort().reverse(),Q=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,J=T.find(X=>X===Q||X.startsWith(Q+".")||X.startsWith(`v${e.nodeVersion}.`));J&&(K=P.join(C,J,"bin"))}if(K&&h.existsSync(K)){let T=process.env.PATH||"";process.env.PATH=`${K}:${T}`,await E(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${K}
|
|
994
|
+
`),b.info(S.green(`\u2713 Node switched to ${e.nodeVersion} (${K})`))}else await E(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
995
|
+
`),b.warn(S.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await H("deps"),r.start("Checking dependencies...");let A=Yo(y),I=zo(process.cwd()),M=h.existsSync("node_modules"),U=h.existsSync("yarn.lock"),F=h.existsSync("bun.lockb");M&&A.node&&A.node!==I&&(r.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await E(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
996
|
+
`),h.rmSync(P.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),M=!1);let R="npm",k=["install","--prefer-offline"];U?(R="yarn",k=["install","--prefer-offline"]):F&&(R="bun",k=["install"]),M?r.stop("Cached node_modules found. Syncing dependencies..."):r.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(b.info(S.blue("Running pre-install hook...")),b.info(S.dim(`> ${e.preBuild}`)),await H("prebuild"),await _("bash",[e.preBuild],process.cwd(),c())),b.info(S.dim(`Running ${R} ${k.join(" ")}...`)),await _(R,k,process.cwd(),c()),A.node=I,qi(y,A);let x=JSON.parse(h.readFileSync("package.json","utf-8")),G=x.dependencies?.expo||x.devDependencies?.expo,q=e.iosBundleIdentifier||"",ce=e.name||"";if(G){r.start(`Enforcing ${m.name} configuration...`);let O=P.join(process.cwd(),"app.json"),C=null;if(h.existsSync(O)){C=h.readFileSync(O,"utf-8");let T=JSON.parse(C);T.expo=T.expo||{},ce||(ce=T.expo.name||""),l==="ios"&&!q&&(q=T.expo?.ios?.bundleIdentifier||""),e.name&&(T.expo.name=e.name),e.scheme&&(T.expo.scheme=e.scheme),l==="ios"&&e.iosBundleIdentifier?(T.expo.ios=T.expo.ios||{},T.expo.ios.bundleIdentifier=e.iosBundleIdentifier):l==="android"&&e.androidPackage&&(T.expo.android=T.expo.android||{},T.expo.android.package=e.androidPackage),h.writeFileSync(O,JSON.stringify(T,null,2))}let K=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await H("prebuild"),await _("npm",K,process.cwd(),c()),l==="ios"&&h.existsSync("ios")){await H("pods"),b.info(S.blue("Running pod install..."));try{let T=P.resolve("ios"),Q=P.join(T,"Podfile");if(!h.existsSync(Q))throw new Error("ios/Podfile not found. Skipping pod install.");let J=h.readFileSync(Q,"utf-8"),X=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(b.info(S.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),J.includes("use_expo_modules!")&&!J.includes("exclude:"))){let ze=/use_expo_modules!(\s*)$/m;ze.test(J)?J=J.replace(ze,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):J=J.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let fe=`
|
|
954
997
|
installer.generated_projects.each do |project|
|
|
955
998
|
project.targets.each do |target|
|
|
956
999
|
target.build_configurations.each do |config|
|
|
@@ -963,80 +1006,114 @@ ${Le.dim("Note: Links are valid for 7 days.")}`)}else x&&ze.warn("Simulator buil
|
|
|
963
1006
|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${X}'
|
|
964
1007
|
end
|
|
965
1008
|
end
|
|
966
|
-
`,
|
|
967
|
-
${
|
|
1009
|
+
`,Me=/post_install\s+do\s+\|installer\|/;if(Me.test(J))b.info(S.dim(`Injecting deployment target (${X}) into existing post_install hook...`)),J=J.replace(Me,`post_install do |installer|
|
|
1010
|
+
${fe}`),h.writeFileSync(Q,J);else{b.info(S.dim(`Appending new post_install hook for deployment target (${X})...`));let ze=`
|
|
968
1011
|
post_install do |installer|
|
|
969
|
-
${
|
|
1012
|
+
${fe}
|
|
970
1013
|
end
|
|
971
|
-
`;
|
|
972
|
-
`),
|
|
973
|
-
\u2713 Local build completed successfully in ${
|
|
974
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
975
|
-
\u274C Build aborted.`)),await
|
|
976
|
-
\u2717 Local build failed: ${
|
|
977
|
-
`)[0]||"unknown"}`))}if(!
|
|
978
|
-
`).map(
|
|
1014
|
+
`;h.appendFileSync(Q,ze)}let Ze="/opt/homebrew/bin/pod",dt=h.existsSync(Ze)?Ze:"pod",Qe=Wo(T);h.existsSync(P.join(T,"Pods"))&&A.pods&&A.pods!==Qe&&(await E(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1015
|
+
`),b.info(S.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),h.rmSync(P.join(T,"Pods"),{recursive:!0,force:!0})),b.info(S.dim(`Using pod command: ${dt} in ${T}`)),await _(dt,["install"],T,c()),A.pods=Qe,qi(y,A)}catch(T){let Q=T.message||"Unknown error";b.warn(S.yellow(`Native "pod" command failed: ${Q}`)),b.info(S.dim("Falling back to npm exec pod-install...")),b.info(S.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await _("npx",["--yes","pod-install@latest","ios"],process.cwd(),c())}if(h.existsSync("ios/Pods")){b.info(S.dim("Disabling signing for Pod targets to prevent conflicts..."));try{j(`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{C&&h.writeFileSync(O,C)}r.stop(`Expo prebuild complete (${m.name} config enforced).`)}let W=[];if(l==="android")await H("build"),W=await Qo(e,s,i,O=>E(O),p);else if(l==="ios"){await H("signing"),b.info(S.dim("Preparing credentials..."));let O=o?.distributionType;W=await er(e,t,s,i,n,C=>E(C),p,O,C=>H(C))}e.postBuild&&(b.info(S.blue("Running post-build hook...")),b.info(S.dim(`> ${e.postBuild}`)),await _(e.postBuild,[],process.cwd(),c()));let Ce=Zo(Date.now()-a);if(b.success(S.green(`
|
|
1016
|
+
\u2713 Local build completed successfully in ${Ce}`)),await d("building",{...q&&{bundleId:q},...ce&&{appName:ce}}),W.length>0&&(b.info(S.cyan(`
|
|
1017
|
+
\u{1F4E6} Generated Artifacts:`)),W.forEach(O=>{let C=P.resolve(O);b.info(S.dim(` - ${O}`)),b.info(S.gray(` Path: ${C}`))}),e.interactive)){let O=await Ko({message:"Install on connected device?"});if(!Lt(O)&&O){if(l==="android"){let C=W.find(K=>K.endsWith(".apk"))||W[0];await ir(C,K=>E(K))}else if(l==="ios"){let C=W.find(T=>T.endsWith(".ipa"))||W.find(T=>T.endsWith(".app"))||W[0],K=Fe("ios");e.simulator?await nr(C,K||"",T=>E(T)):await or(C,K||"",T=>E(T))}}}await H("upload");let pe=[];for(let O of W)try{let C=P.join($e.tmpdir(),`${t}-${P.basename(O)}`);h.copyFileSync(O,C),pe.push(C),b.info(S.dim(` \u{1F4CB} Preserved artifact: ${P.basename(O)}`))}catch{b.warn(S.yellow(` Failed to preserve artifact: ${P.basename(O)}`))}W=pe,b.info(S.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let O=process.cwd(),C=new Set(["node_modules"]),K=h.readdirSync(O),T=0;for(let Q of K)if(!C.has(Q)){if(Q==="ios"){let J=P.join(O,"ios"),X=h.readdirSync(J);for(let fe of X)if(fe!=="Pods")try{h.rmSync(P.join(J,fe),{recursive:!0,force:!0}),T++}catch{}continue}try{h.rmSync(P.join(O,Q),{recursive:!0,force:!0}),T++}catch{}}b.info(S.dim(` Cleaned ${T} items. Cached: node_modules${h.existsSync(P.join(O,"ios","Pods"))?", ios/Pods":""}`)),b.info(S.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{b.warn(S.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let C=P.join($e.homedir(),m.workspacesDir),K=j(`df -k "${C}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),T=parseInt(K,10)*1024;if(T<53687091200&&h.existsSync(C)){b.info(S.dim(` \u26A0\uFE0F Low disk space (${(T/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let Q=P.basename(process.cwd()),J=h.readdirSync(C).filter(X=>X!==Q).map(X=>{let fe=P.join(C,X);try{let Me=h.statSync(fe);return Me.isDirectory()?{name:X,dir:fe,mtime:Me.mtimeMs}:null}catch{return null}}).filter(Boolean);J.sort((X,fe)=>X.mtime-fe.mtime);for(let X of J){if(T>=53687091200)break;try{h.rmSync(X.dir,{recursive:!0,force:!0}),b.info(S.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${X.name}`));let fe=j(`df -k "${C}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(fe,10)*1024>=53687091200)break}catch{}}}}catch{}return await te(),W}catch(g){throw await te(),g.message==="Command aborted"?(b.warn(S.yellow(`
|
|
1018
|
+
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user"}),g):(b.error(S.red(`
|
|
1019
|
+
\u2717 Local build failed: ${g.message}`)),await d("failed",{error:g.message}),g)}},Qo=async(e,t,i={},n,o)=>{let r=h.existsSync("android/gradlew")?"android/gradlew":h.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let a=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?a="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(a="assembleRelease");let l=e.buildCommand||a;b.info(S.blue(`Running Android build: ${l}...`));let s=r.includes("android/")?"android":".",c=(r.includes("android/"),"./gradlew"),d=[l],u={...i,MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(i.ANDROID_VERSION_CODE){let f=P.join(s,"app/build.gradle");if(h.existsSync(f)){let y=i.ANDROID_VERSION_CODE,D=h.readFileSync(f,"utf-8");D=D.replace(/versionCode\s+\d+/,`versionCode ${y}`),h.writeFileSync(f,D),b.info(S.green(`\u2713 Applied Android versionCode ${y}`))}d.push(`-Pandroid.injected.version.code=${i.ANDROID_VERSION_CODE}`)}for(let f of["app/build","build",".cxx"]){let y=P.join(s,f);h.existsSync(y)&&h.rmSync(y,{recursive:!0,force:!0})}await xe(c,d,s,u,n,o);let p=P.join(s,"app/build/outputs");return nt(p,[".apk",".aab"])},er=async(e,t,i,n={},o,r,a,l,s)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=P.resolve(process.cwd(),h.existsSync("ios")?"ios":"."),d=h.readdirSync(c),u=d.find(g=>g.endsWith(".xcworkspace")),p=d.find(g=>g.endsWith(".xcodeproj")),f=Ye(n,i,e);if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let g=j("xcode-select -p").toString().trim();b.info(S.dim(`Using Xcode at: ${g}`))}catch{b.warn(S.dim("Could not detect Xcode path."))}b.info(S.blue("Running iOS build via xcodebuild..."));let y=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),D=e.iosScheme||y||e.scheme,$=e.developmentClient?"Debug":e.iosConfiguration||"Release",L=(o||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),B=P.join($e.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,L);h.mkdirSync(B,{recursive:!0});let te=tt(f),E=P.join(B,".mach-env-hash"),H=P.join(B,"Build"),_=h.existsSync(E)?h.readFileSync(E,"utf-8").trim():"";if(h.existsSync(H)&&_!==te&&(b.info(S.dim(_?"Build environment changed \u2014 clearing iOS DerivedData build products.":"DerivedData has no environment stamp \u2014 clearing iOS build products.")),h.rmSync(H,{recursive:!0,force:!0})),h.writeFileSync(E,te),e.simulator){b.info(S.dim(`Building for simulator (Scheme: ${D}, Config: ${$})...`)),await xe("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",D,"-configuration",$,"-sdk","iphonesimulator","-derivedDataPath",B,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],c,f,r,a);let g=P.join(B,"Build/Products",`${$}-iphonesimulator`),A=nt(g,[".app"]);if(A.length>0){let I=A[0],M=P.basename(I,".app"),U=P.join(g,`${M}_simulator.zip`);return b.info(S.dim(`Creating simulator artifact: ${U}...`)),j(`cd "${g}" && zip -r "${U}" "${P.basename(I)}"`),[U]}return[]}else{b.info(S.dim(`Archiving (Scheme: ${D}, Config: ${$})...`));let g=P.join(c,"build.xcarchive"),A=P.join(c,"export");h.rmSync(g,{recursive:!0,force:!0}),h.rmSync(A,{recursive:!0,force:!0}),h.rmSync(P.join(c,"build"),{recursive:!0,force:!0});let I=n.IOS_DIST_P12,M=n.IOS_PROVISIONING_PROFILE,U=n.IOS_P12_PASSWORD||"",F=[],R,k,x={isAppStore:!1,isDevelopment:!1};if(I&&M){b.info(S.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let O=`${m.buildPrefix}-${t}.keychain-db`,C=P.join($e.tmpdir(),O),K=m.keychainPassword;j(`security create-keychain -p "${K}" "${C}" 2>/dev/null || true`),j(`security set-keychain-settings -t 3600 -l "${C}"`),j(`security unlock-keychain -p "${K}" "${C}"`);let T=P.join($e.tmpdir(),`cert-${t}.p12`),Q=Buffer.from(I,"base64");h.writeFileSync(T,Q),b.info(S.dim(`P12 data size: ${Q.length} bytes, first bytes: ${Q.slice(0,4).toString("hex")}`)),(Q.length<100||Q[0]!==48)&&(b.warn(S.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),b.warn(S.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let J=[U,"",m.keychainPassword],X=!1;for(let me of J)try{j(`security import "${T}" -k "${C}" -P "${me}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),X=!0,b.info(S.dim(`\u2713 P12 imported successfully with password: ${me?"[set]":"[empty]"}`));break}catch(Ne){b.info(S.dim(` P12 import attempt with password ${me?`"${me.substring(0,3)}..."`:"[empty]"} failed: ${Ne.message?.split(`
|
|
1020
|
+
`)[0]||"unknown"}`))}if(!X)throw new Error("Failed to import P12.");h.unlinkSync(T),j(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${K}" "${C}"`);let fe=j("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1021
|
+
`).map(me=>me.trim().replace(/^"|"$/g,"")).filter(me=>me.length>0),Me=[C,...fe].map(me=>`"${me}"`).join(" ");j(`security list-keychains -d user -s ${Me}`),j(`security default-keychain -s "${C}"`);let Ze=P.join($e.homedir(),"Library/MobileDevice/Provisioning Profiles");h.mkdirSync(Ze,{recursive:!0});let dt=Buffer.from(M,"base64"),Qe=P.join(Ze,`${m.nameLower}-temp-${t}.mobileprovision`);h.writeFileSync(Qe,dt);let Ct=dt.toString("utf-8"),ze=/<key>get-task-allow<\/key>\s*<true\/>/.test(Ct);x={isAppStore:!Ct.includes("<key>ProvisionedDevices</key>")&&!ze,isDevelopment:ze};try{let Ne=j(`security cms -D -i "${Qe}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);k=Ne?Ne[1]:void 0}catch{let Ne=Ct.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);k=Ne?Ne[1]:void 0}k||(b.warn("Could not extract UUID from provisioning profile. Using fallback."),k=`${m.nameLower}-${t}`);let Qt=P.join(Ze,`${k}.mobileprovision`);h.existsSync(Qt)&&h.unlinkSync(Qt),h.renameSync(Qe,Qt);try{let Ne=j(`security find-identity -v -p codesigning "${C}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);Ne&&(R=Ne[1],b.info(S.blue(`Identity auto-detected from keychain: "${R}"`)))}catch{}R||(R=x.isDevelopment?"Apple Development":"Apple Distribution",b.info(S.blue(`Identity fallback (profile heuristic): "${R}"`))),b.info(S.dim(`Profile type: ${x.isDevelopment?"Development":x.isAppStore?"App Store":"Ad-Hoc"}`)),b.info(S.dim(`Identity Detection: get-task-allow=${x.isDevelopment}, Selected Identity="${R}"`)),F.push("CODE_SIGN_STYLE=Manual"),F.push(`CODE_SIGN_IDENTITY="${R}"`),F.push(`PROVISIONING_PROFILE_SPECIFIER=${k}`),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(O){throw b.error(`Signing setup failed: ${O.message}`),O}}else F.push("-allowProvisioningUpdates"),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);s&&await s("archive"),b.info(S.blue(`Archive detected Identity: "${R}"`)),b.info(S.blue(`Archive detected UUID: "${k}"`)),await xe("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",D,"-configuration",$,"-archivePath",g,"-derivedDataPath",B,...F],c,f,r,a);let G;k?(x.isAppStore?G="app-store":x.isDevelopment?G="development":G="ad-hoc",b.info(S.blue(`Export method from profile: "${G}"`))):(G=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",b.warn(S.yellow(`No profile UUID detected. Export method from distribution flag: "${G}"`)));let q=e.iosExportMethod||G,ce=Fe("ios"),W=P.join(c,"ExportOptions.plist"),Ce=`<?xml version="1.0" encoding="UTF-8"?>
|
|
979
1022
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
980
1023
|
<plist version="1.0">
|
|
981
1024
|
<dict>
|
|
982
1025
|
<key>method</key>
|
|
983
|
-
<string>${
|
|
1026
|
+
<string>${q}</string>
|
|
984
1027
|
<key>destination</key>
|
|
985
1028
|
<string>export</string>
|
|
986
1029
|
<key>signingStyle</key>
|
|
987
|
-
<string>${
|
|
1030
|
+
<string>${k?"manual":"automatic"}</string>
|
|
988
1031
|
<key>thinning</key>
|
|
989
1032
|
<string><none></string>
|
|
990
1033
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
991
|
-
${
|
|
1034
|
+
${ce&&k?`
|
|
992
1035
|
<key>provisioningProfiles</key>
|
|
993
1036
|
<dict>
|
|
994
|
-
<key>${
|
|
995
|
-
<string>${
|
|
1037
|
+
<key>${ce}</key>
|
|
1038
|
+
<string>${k}</string>
|
|
996
1039
|
</dict>`:""}
|
|
997
1040
|
</dict>
|
|
998
|
-
</plist>`;if(
|
|
999
|
-
${
|
|
1041
|
+
</plist>`;if(h.writeFileSync(W,Ce),process.env[`${m.envPrefix}DEBUG`]&&b.info(S.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1042
|
+
${Ce}`)),s&&await s("export"),b.info(S.blue(`Exporting with Bundle ID: "${ce}"`)),b.info(S.blue(`Exporting with Method: "${q}"`)),r){r(S.magenta(`
|
|
1000
1043
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1001
|
-
`));try{let
|
|
1002
|
-
`))}catch(
|
|
1003
|
-
`))}}await
|
|
1004
|
-
`)}catch{let
|
|
1005
|
-
`),new Error(
|
|
1006
|
-
`).slice(1).map(
|
|
1007
|
-
`).filter(s=>s.trim().length>0)}catch{}if(
|
|
1008
|
-
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):G(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(n){i.stop("Installation failed."),A.error(h.red(`Failed to install APK: ${n.message}`))}},wo=async(e,t,i)=>{let n=It();try{if(!G("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(h.yellow("No iOS Simulator is currently booted."));let r=G("xcrun simctl list devices --json").toString(),l=JSON.parse(r).devices,a=[];Object.keys(l).forEach(u=>{l[u].forEach(p=>{p.isAvailable&&a.push({...p,runtime:u})})});let s=await jt({message:"Select a simulator to launch:",options:a.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(_t(s))return;n.start(`Booting ${s}...`),G(`xcrun simctl boot ${s}`),G(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let c=0,d=!1;for(;c<30;){try{if(G("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await Oe("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),A.info(h.blue(`\u{1F680} Launching ${t}...`)),await Oe("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),A.error(h.red(`Failed to install on Simulator: ${o.message}`))}},vo=async(e,t,i)=>{let n=It();n.start("Scanning for connected iOS devices...");try{let o=G("xcrun devicectl list devices --json-output -").toString(),l=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(l.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 a=l[0].identifier;if(l.length>1){n.stop();let s=await jt({message:"Select a device to install on:",options:l.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(_t(s))return;a=s,n.start(`Installing on ${a}...`)}else n.message(`Installing on ${l[0].model.name}...`);await Oe("xcrun",["devicectl","device","install","app","--device",a,e],process.cwd(),{},i),n.stop("Installation complete."),A.info(h.blue(`\u{1F680} Launching ${t}...`)),await Oe("xcrun",["devicectl","device","launch","app","--device",a,t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),A.error(h.red(`Failed to install on device: ${o.message}`)),A.info(h.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import Ti from"fs";import ki from"path";import{isCancel as Kt,log as ke,select as xi,spinner as Oo,text as Co}from"@clack/prompts";import We from"chalk";async function Li(e){let t=await zt(e);t&&(ke.success(We.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&ke.warn(We.yellow(t.launchDeferredReason)),t.dashboardUrl&&ke.info(We.dim("View test run: ")+We.white.underline(t.dashboardUrl)))}async function zt(e){let t=ve(`./${f.configFileName}`),i=e.projectId||t?.projectId,n=e.profile||e.buildProfile||"production";if(!i)return ke.error(`No projectId found. Run \`${f.nameLower} link\` first or pass an internal project id.`),null;let o=e.platform;if(!o&&e.latest){let s=await xi({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(Kt(s))return null;o=s}let r=await No(e);if(!r)return null;if(r.kind==="latest"&&!o)return ke.error("Pass --platform when using --latest."),null;if(r.kind==="artifact-url"&&!o)return ke.error("Pass --platform when using --artifact-url."),null;let l=To(e.maestroRetries);if(l===null)return null;let a=Oo();e.quiet||a.start("Queuing Maestro run...");try{let s=await $.post("/tests/maestro",{projectId:i,platform:o,profile:n,latest:r.kind==="latest",buildId:r.kind==="build-id"?r.value:e.buildId,buildUrl:r.kind==="build-url"?r.value:e.buildUrl,artifactUrl:r.kind==="artifact-url"?r.value:e.artifactUrl,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(o==="ios"?"iphone_15":"pixel_6"),retries:l,record:!!e.maestroRecord});if(s.data.status!=="success")throw new Error(s.data.message||"Failed to queue Maestro run");let c=s.data.testRun,d={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${Qe}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return ko(e,d),e.quiet||a.stop("Maestro run queued"),d}catch(s){e.quiet||a.stop("Could not queue Maestro run");let c=s.response?.data?.message||s.message||"Unknown error";return ke.error(We.red(`Maestro queue failed: ${c}`)),null}}async function No(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 xi({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${f.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(Kt(t))return null;if(t==="latest")return{kind:"latest"};let i=await Co({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${f.name} build URL:`:"Enter artifact URL:",validate:n=>{let o=String(n||"").trim();if(!o)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!o.startsWith("http"))return"Must be a URL"}});return Kt(i)?null:{kind:t,value:String(i).trim()}}function To(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(ke.error("--maestro-retries must be an integer between 0 and 10."),null):t}function ko(e,t){if(!e.jsonOutput)return;let i=ki.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let o=ki.dirname(i);o&&o!=="."&&Ti.mkdirSync(o,{recursive:!0}),Ti.writeFileSync(i,JSON.stringify(n,null,2))}catch(o){ke.warn(We.yellow(`Could not write Maestro metadata JSON: ${o.message}`))}}var Pt=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(R.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let t=Vt(),i=e.buildId||xo(),n=e.projectId,o=Date.now(),r=!!n,l=async a=>{if(n)try{await $.patch(`/builds/${n}/${i}`,{status:"failed",error:a})}catch{}};if(e.local&&e.buildId){e.quiet||t.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let a=await $.get(`/builds/${n}/${e.buildId}/source-url`);if(a.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await rt.get(a.data.downloadUrl,{responseType:"stream"}),c=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=ye.join(Lo.homedir(),f.workspacesDir,c);re.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(re.existsSync(d)){let B=re.readdirSync(d);for(let w of B){if(u.has(w))continue;if(w==="ios"){let b=ye.join(d,"ios");try{let L=re.readdirSync(b);for(let m of L)if(!p.has(m))try{re.rmSync(ye.join(b,m),{recursive:!0,force:!0})}catch{}}catch{}continue}let U=ye.join(d,w);try{re.rmSync(U,{recursive:!0,force:!0})}catch{}}}let g=ye.join(d,"source.zip"),E=s.data,P=re.createWriteStream(g);await new Promise((B,w)=>{E.pipe(P),E.on("error",U=>w(U)),P.on("finish",()=>B())}),new Hi(g).extractAllTo(d,!0);try{re.unlinkSync(g)}catch{}process.chdir(d),R.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),R.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${re.existsSync(ye.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${re.existsSync(ye.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(a){t.stop(`Failed to prepare isolated workspace: ${a.message}`),n&&await l(`Setup Error: ${a.message}`),process.exit(1)}}try{let a=e.repo;if(!a)try{a=Fi("git config --get remote.origin.url").toString().trim()}catch{R.warn("Could not detect git repository URL.")}!a&&e.dryRun,a||(a="https://github.com/placeholder/repo.git"),R.info(`Build ID: ${v.cyan(i)}`);let s={},c={},d=ve(`./${f.configFileName}`);if(d){n=d.projectId;let m=e.buildProfile||"production",D=Be(d,m);!D&&e.buildProfile&&(R.error(`Build profile '${m}' not found in ${f.configFileName}`),process.exit(1));let y=D||{};process.env.MACH_DEBUG&&R.info(v.dim(`Build profile: ${m} | Platform: ${e.platform} | Distribution: ${y.distribution||"store"} | Environment: ${y.environment||m}`)),y.env&&(c=y.env,R.info(v.blue(`Use Build Profile: ${m}`)));let I=e.platform,x=y[I]||{},W=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);let j=M=>M==="androidPackage"?x.androidPackage??x.package??y.androidPackage??y.android?.package:M==="iosBundleIdentifier"?x.iosBundleIdentifier??x.bundleIdentifier??y.iosBundleIdentifier??y.ios?.bundleIdentifier:x[M]!==void 0?x[M]:y[M];for(let M of W){let K=j(M),H=M==="androidPackage"||M==="iosBundleIdentifier";K!==void 0&&(e[M]===void 0||H)&&(e[M]=K)}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 O=M=>{if(!M)return M;if(M.startsWith("scripts.")){let K=M.split(".")[1],H=d.scripts?.[K];if(H)return H;R.warn(`Script reference not found: ${M}`)}return M};e.buildCommand=O(e.buildCommand),e.preBuild=O(e.preBuild),e.postBuild=O(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let F={...Ke(d,f.envPrefix),...Ke(y,`${f.envPrefix}PROFILE_`)};s={...s,...c,...F},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&y.ios?.appleTeamId&&(e.iosTeamId=y.ios.appleTeamId),!e.iosTeamId&&d.submit?.[m]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[m].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(R.warn(v.yellow(`Check: Using 'production' Team ID for '${m}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?R.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):R.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=Fi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{R.warn("Failed to detect git branch.")}let p="1.0.0";try{re.existsSync("./package.json")&&(p=JSON.parse(re.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",E="Internal";e.developmentClient?E="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?E="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?E="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(E="Development");let P=e.platform==="ios"?"iOS":"Android",C=e.platform==="ios"&&e.simulator?" (Simulator)":"",B=`${P}${C} v${p} (${E})`;if(st(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:g,branch:u,version:p,buildType:E,developmentClient:!!e.developmentClient,summary:B}),n){try{let m=e.buildProfile||"production";R.info(v.blue(`Fetching managed secrets for profile: ${m}...`));let D=e.environment||m,I=(await $.get(`/projects/${n}/secrets/export?env=${D}`)).data;I.status==="success"&&I.secrets&&(s={...s,...I.secrets},Object.keys(I.secrets).length>0&&R.info(v.magenta(`\u2713 Injected ${Object.keys(I.secrets).length} secrets from Dashboard.`)))}catch(m){R.warn(`Failed to load managed secrets from Dashboard: ${m.message}`)}try{R.info(v.blue("Fetching managed credentials..."));let m="development";e.distribution==="store"?m="store":e.distribution==="internal"&&(m=e.platform==="ios"?"adhoc":"internal"),e.developmentClient&&(m="development");let D=await $.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:m}});if(D.data.status==="success"&&D.data.credentials){let y=D.data.credentials;R.info(v.magenta(`\u2713 Found ${y.length} relevant credentials.`));let I=y.filter(O=>{if(O.distributionType){let F=m==="internal"?"adhoc":m;return O.distributionType===F||O.distributionType===m}return!0});R.info(v.dim(` Filtered to ${I.length} credentials for distributionType: ${m}`));let x=!1,W=!1,j=!1;for(let O of I)if(O.downloadUrl)try{let F="",M=5;for(;M>0;)try{let K=await rt.get(O.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});F=Buffer.from(K.data).toString("base64");break}catch(K){if(M--,M===0)throw K;R.warn(v.dim(` - Temporary network error downloading ${O.name}. Retrying... (${5-M}/5)`)),await new Promise(H=>setTimeout(H,2e3))}if(O.type==="ios_cert"&&!x)s.IOS_DIST_P12=F,O.password?(s.IOS_P12_PASSWORD=O.password,R.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12 with password from credential record`))):R.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12`)),x=!0;else if(O.type==="ios_profile"&&!W)s.IOS_PROVISIONING_PROFILE=F,R.info(v.dim(` - Injected ${O.name} as IOS_PROVISIONING_PROFILE`)),W=!0;else if(O.type==="android_keystore"&&!j){s.ANDROID_KEYSTORE_BASE64=F;let K=O.keystorePassword||O.password,H=O.keyPassword||O.keystorePassword||O.password,z=O.alias||O.meta?.alias;if(K)s.ANDROID_STORE_PASSWORD=K,R.info(v.dim(" - Injected keystore password from credential record"));else{let T=["ANDROID_STORE_PASSWORD",...[m==="store"?"PRODUCTION":m==="internal"?"STAGING":"DEVELOPMENT",m.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(k=>`KEYSTORE_PASSWORD_${k}`),"KEYSTORE_PASSWORD"].find(k=>!!s[k]);T&&s[T]&&(s.ANDROID_STORE_PASSWORD=s[T])}if(H?(s.ANDROID_KEY_PASSWORD=H,R.info(v.dim(" - Injected key password from credential record"))):s.ANDROID_KEY_PASSWORD=s.ANDROID_STORE_PASSWORD||"",z)s.ANDROID_KEY_ALIAS=z;else{let ne=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(he=>!!s[he]);ne&&(s.ANDROID_KEY_ALIAS=s[ne])}R.info(v.dim(` - Injected ${O.name} as ANDROID_KEYSTORE_BASE64`)),j=!0}}catch(F){R.warn(`Failed to download credential ${O.name}: ${F.message}`)}}if(e.platform==="android"){let y=e.buildProfile||"production",I=Be(d,y)||{},j=((I.android||{}).versionCode??I.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",O=e.autoVersion||j&&e.distribution==="store";if(j&&!O&&R.info(v.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),O){t.start("Resolving latest versionCode from Google Play...");try{let F=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,M=(D.data.credentials||[]).find(T=>T.type==="google_service_account"&&(!T.bundleId||T.bundleId===F));if(!M){let k=((await $.get(`/credentials/${n}`)).data.credentials||[]).filter(V=>V.type==="google_service_account");if(M=k.find(V=>V.type==="google_service_account"&&V.bundleId===F),!M&&k.length>0){let V=k.map(N=>N.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${F}. Found service credential(s) for: ${V}.`)}}if(!M)throw new Error(`Google Service Account not found for package ${F}. Upload it under this package in Dashboard or run '${f.nameLower} credentials:service --platform android --package-name ${F}'.`);let K=await $.get(`/credentials/${M.credentialId}/download`,{params:{projectId:n}});if(K.data.status!=="success"||!K.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let z=(await rt.get(K.data.downloadUrl,{headers:{Connection:"close"}})).data,ne=await vi(F,z);if(ne==null)throw new Error("Could not retrieve any version information from Google Play.");let he=ne+1;s.ANDROID_VERSION_CODE=he.toString(),t.stop(`\u2713 Resolved versionCode: ${v.green(he)} (Latest on Play Store: ${ne})`)}catch(F){t.stop("Version resolution failed");let M=F.response?.data?.error?.message||F.message;throw new Error(`Auto-versioning failed: ${M}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let y=!!s.IOS_DIST_P12,I=!!s.IOS_PROVISIONING_PROFILE;if(!y||!I){let x=[...y?[]:["Distribution Certificate"],...I?[]:["Provisioning Profile"]].join(" and ");R.error(v.red(`Missing iOS credentials: ${x}`)),e.quiet&&process.exit(1);let W=e.yes||await Ui({message:"Would you like to generate these credentials now?",initialValue:!0});if(W&&!Mi(W))return await et({platform:"ios",profile:g}),e.quiet||R.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),Pt(e);e.quiet||R.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){R.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let I=e.yes||await Ui({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(I&&!Mi(I))return await et({platform:"android",profile:g}),e.quiet||R.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),Pt(e);e.quiet||R.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(m){R.warn(`Failed to resolve credentials: ${m.message}`)}}let w=!!(e.local&&e.buildId),U=!!(e.local||e.sshHost),b=!U&&!w;if(w){R.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let m=await Gt({...e,interactive:!1},i,s,n,{branch:u,version:p,summary:B,buildType:E});await L(m),process.exit(0)}async function L(m){if(n&&m.length>0){let D=Vt(),y=[];e.quiet||D.start("Uploading artifacts to Dashboard...");try{for(let I of m){let x=ye.basename(I),W=re.readFileSync(I),j=ye.extname(x).toLowerCase(),O="application/octet-stream",F=await $.post(`/builds/${n}/${i}/artifact-upload-url`,{fileName:x,fileType:O});if(F.data.status!=="success")throw new Error(`Failed to get upload URL for ${x}`);let M=!1;for(let K=1;K<=3;K++)try{await rt.put(F.data.uploadUrl,W,{headers:{"Content-Type":O},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),M=!0;break}catch(H){if(R.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${H.code||H.message})`)),K<3)await new Promise(z=>setTimeout(z,3e3*K));else throw H}M&&y.push({name:x,url:F.data.downloadUrl,size:W.length,type:j.substring(1)})}e.quiet||D.stop("Artifacts uploaded.")}catch(I){e.quiet||D.stop("Failed to upload artifacts."),R.error(v.red(`Upload error: ${I.message}`));try{await $.patch(`/builds/${n}/${i}`,{status:"completed",artifacts:m.map(x=>ye.basename(x)),endTime:Date.now()})}catch(x){R.warn(v.yellow(`Could not set fallback build status: ${x.message}`))}return}if(n&&y.length>0)try{R.info(v.cyan(`
|
|
1009
|
-
\u{1F517} Download Links:`));for(let I of
|
|
1010
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1011
|
-
\u26A0\uFE0F Could not report to dashboard: ${I.message}`))}}else if(n)try{await
|
|
1012
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1013
|
-
\u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){i.quiet||n.stop("Build successful!"),
|
|
1014
|
-
\u2713 Build completed successfully!`));try{i.quiet||(
|
|
1015
|
-
\u{1F4F1} Installation Hub:`)),
|
|
1016
|
-
`);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(
|
|
1017
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(
|
|
1018
|
-
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let o=n.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];i.add(r);let
|
|
1019
|
-
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let t=Pe("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),i=JSON.parse(t);Object.entries(i.devices).forEach(([n,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${r.name} (${n})`})})})}catch{}try{let t=Pe("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(t).result?.devices||[]).forEach(n=>{let o=n.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:n.identifier,platform:"ios",type:"physical",name:n.deviceProperties?.name||"iPhone",status:"online",details:`${n.deviceProperties?.name||"iPhone"} (${n.model?.name||n.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ki(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 jo(e,t){let i=await Fo({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=Jt.createWriteStream(t);i.data.pipe(n),await new Promise((o,r)=>{n.on("finish",o),n.on("error",r)})}async function Go(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),o=t.toLowerCase().includes(".ipa"),r=Jt.mkdtempSync(Yt.join(Ho.tmpdir(),`${at}-install-`)),l=Yt.join(r,n==="android"?"install.apk":o?"install.ipa":"install.zip");try{if(await jo(t,l),n==="android"){Pe(`adb -s ${JSON.stringify(e)} install -r ${JSON.stringify(l)}`,{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");Pe(`unzip -o ${JSON.stringify(l)} -d ${JSON.stringify(r)}`,{stdio:"pipe"});let a="";try{a=Pe(`find ${JSON.stringify(Yt.join(r,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(a||(a=Pe(`find ${JSON.stringify(r)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!a)throw new Error(`No .app bundle found inside the ${o?"IPA":"archive"}.`);try{Pe(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(a)}`,{stdio:"pipe"})}catch(s){try{Pe(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(a)}`,{stdio:"pipe"})}catch{throw new Error(s.stderr?.toString().trim()||s.message||"iOS install failed.")}}}finally{Jt.rmSync(r,{recursive:!0,force:!0})}}function Ko(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 Pe(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Gi("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android"){let i=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`;return Gi(i,["-avd",e],{detached:!0,stdio:"ignore"}).unref(),"Emulator booting in background..."}throw new Error("Invalid platform.")}async function zi(){process.platform!=="darwin"&&Ye.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Mo.createServer((n,o)=>{if(o.setHeader("Access-Control-Allow-Origin","*"),o.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){o.writeHead(204),o.end();return}let r=new URL(n.url||"/",`http://localhost:${at}`);if(n.method==="GET"&&r.pathname==="/local/devices"){try{let l=Bo();o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",targets:l}))}catch(l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:l.message}))}return}if(n.method==="POST"&&r.pathname==="/install-local"){t(n,o);return}if(n.method==="POST"&&r.pathname==="/local/boot"){i(n,o);return}o.writeHead(404),o.end()}),t=async(n,o)=>{try{let{deviceId:r,artifactUrl:l,platform:a}=await Ki(n);if(!r||!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Go(r,l,a),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:`Installed on ${r}`}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local install failed"}))}},i=async(n,o)=>{try{let{id:r,platform:l}=await Ki(n),a=Ko(r,l);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:a}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local device launch failed"}))}};e.listen(at,"127.0.0.1",()=>{Ye.success(Wt.green(`Local device agent running on http://localhost:${at}`)),Ye.info(Wt.dim("Keep this running while using the Install Hub on the dashboard.")),Ye.info(Wt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Ye.error(`Port ${at} is already in use \u2014 agent may already be running.`):Ye.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Ps}from"module";import{text as Vo,password as Wo,spinner as Yo,isCancel as Yi}from"@clack/prompts";import Qt from"chalk";import lt from"fs";import Vi from"path";import zo from"os";var qt=Vi.join(zo.homedir(),f.configDir),Xt=Vi.join(qt,"config.json");function Zt(){if(!lt.existsSync(Xt))return{};try{return JSON.parse(lt.readFileSync(Xt,"utf-8"))}catch{return{}}}function Wi(e){lt.existsSync(qt)||lt.mkdirSync(qt,{recursive:!0});let i={...Zt(),...e};lt.writeFileSync(Xt,JSON.stringify(i,null,2))}async function Ji(){let e=Zt(),t=await Vo({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Yi(t))return;let i=await Wo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Yi(i))return;let n=Yo();n.start("Authenticating...");try{let r=await(await fetch(`${At}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();r.status==="success"&&r.user.token?(di({id:r.user.id,email:t,token:r.user.token,refreshToken:r.user.refreshToken}),Wi({lastLoginEmail:t}),n.stop(Qt.green("Login successful!"))):n.stop(Qt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){n.stop(Qt.red("Network error: "+o.message))}}import{outro as Jo,select as qo,spinner as Xo,isCancel as Zo}from"@clack/prompts";import $t from"chalk";import ei from"fs";import Qo from"path";async function qi(){if(!fe()){console.log($t.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=Xo();t.start("Fetching projects...");try{let{data:i}=await $.get("/projects");if(t.stop("Projects loaded."),i.status!=="success"||!i.projects||i.projects.length===0){console.log($t.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let n=i.projects.map(p=>({value:p.projectId,label:`${p.name} (${p.slug})`})),o=await qo({message:"Select a project to link:",options:n});if(Zo(o))return;let r=Qo.join(process.cwd(),f.configFileName),l={};if(ei.existsSync(r))try{l=JSON.parse(ei.readFileSync(r,"utf-8"))}catch{}let a=i.projects.find(p=>p.projectId===o),s=l.android?.package||Te("android"),c=l.ios?.bundleIdentifier||Te("ios"),d=l.submit?.production?.android||{},u={projectId:o,name:a?.name,slug:a?.slug,scheme:a?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:c||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:l.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:l.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};ei.writeFileSync(r,JSON.stringify(u,null,2)),Jo($t.green(`Linked to project ${u.name} (${u.slug})`))}catch(i){t.stop($t.red("Error fetching projects: "+i.message))}}import{outro as er,text as Dt,select as tr,spinner as ir,isCancel as ct}from"@clack/prompts";import dt from"chalk";import nr from"fs";import or from"path";import{randomUUID as rr}from"crypto";async function Xi(){if(!fe()){console.log(dt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let t=await Dt({message:"Project Name:",placeholder:"My Awesome App",validate(a){if(a.length===0)return"Name is required!"}});if(ct(t))return;let i=await Dt({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(a){if(a.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(a))return"Slug must be lowercase alphanumeric with dashes."}});if(ct(i))return;let n=await tr({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(ct(n))return;let o="";if(n==="android"||n==="all"){let a=Te("android");if(o=await Dt({message:"Android Package Name:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),ct(o))return}let r="";if(n==="ios"||n==="all"){let a=Te("ios");if(r=await Dt({message:"iOS Bundle Identifier:",initialValue:a||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),ct(r))return}let l=ir();l.start("Creating project...");try{let a=rr(),c={projectId:a,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:d}=await $.post("/projects",c);if(d.status==="success"){l.stop(dt.green("Project created successfully!"));let u=or.join(process.cwd(),f.configFileName);nr.writeFileSync(u,JSON.stringify({projectId:a,name:t,slug:i,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),er(dt.green(`Initialized project ${t} and linked locally!`))}else l.stop(dt.red("creation failed: "+d.message))}catch(a){l.stop(dt.red("Network error: "+a.message))}}import{spinner as Qi,log as Se}from"@clack/prompts";import Rt from"chalk";import Zi from"fs";import sr from"path";async function en(e,t){let i=fe();if(!i){Se.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let n=sr.join(process.cwd(),f.configFileName);if(!Zi.existsSync(n)){Se.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Zi.readFileSync(n,"utf-8"))}catch{Se.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){Se.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await ar(r,t,i):e==="list"?await lr(r,i):Se.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function ar(e,t,i){if(t.length===0){Se.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=Qi();n.start("Setting environment variables...");let o=0,r=0;for(let l of t){let[a,...s]=l.split("="),c=s.join("=");if(!a||c===void 0){Se.warn(`Invalid format for argument: ${l}. Expected KEY=VALUE.`),r++;continue}try{let d={key:a.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:u}=await $.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(Se.error(`Failed to set ${a}: ${u.message}`),r++)}catch(d){Se.error(`Network error setting ${a}: ${d.message}`),r++}}n.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function lr(e,t){let i=Qi();i.start("Fetching environment variables...");try{let{data:n}=await $.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let o=n.secrets||[];o.length===0?Se.info("No environment variables found for this project."):(Se.info(Rt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let l=r.visibility==="plain"?r.value:"********";console.log(` ${Rt.cyan(r.key)} = ${l} ${Rt.gray(`[${r.environment}]`)}`)}))}else i.stop(Rt.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),Se.error(`Network error: ${n.message}`)}}import{spinner as pt,text as ut,select as ii,isCancel as Ue,cancel as ni}from"@clack/prompts";import se from"chalk";import ie from"fs";import Me from"path";import{spawn as nn}from"child_process";import on from"axios";import oi from"os";import cr from"crypto";async function rn(e){let t=pt(),i=fe(),n=`./${f.configFileName}`;if(!ie.existsSync(n)){pe(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(ie.readFileSync(n,"utf-8")),{projectId:r}=o,l=e.profile||e.buildProfile||"production";if(!r){pe(`${f.configFileName} is missing projectId.`);return}Ce(se.dim(`Submit for project: ${o.name||r} | Profile: ${l}`));let a=e.platform;if(!a){let w=await ii({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(Ue(w)){ni("Operation cancelled");return}a=w}let s=await fr(r,a,e,i?.token);if(!s)return;Ce(`Using artifact: ${se.green(Me.basename(s))} `);let c=a==="android"?dr(o,l):void 0;t.start("Fetching submission credentials from Dashboard...");let d;try{let U=(await $.get(`/credentials/${r}`)).data.credentials||[];if(a==="android"&&!c){t.stop("Package name missing"),pe("Could not resolve Android package name. Set android.package in mach.config.json/app.json.");return}let b=U.filter(L=>a==="ios"?L.type==="asc_api_key":L.type==="google_service_account"&&L.bundleId===c);if(b.length===0){t.stop("Credentials missing"),pe(a==="android"?`No Google Play service credential found for package ${c}.`:`No Service Credentials found for ${a}.`),Ce(a==="android"?`Use '${f.nameLower} credentials:service --platform android --package-name ${c}' or upload it under that package in the Dashboard.`:`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(b.length===1)d=b[0],t.stop(`Using: ${d.name}`);else{t.stop("Multiple credentials found");let L=await ii({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:b.map(m=>({value:m.credentialId,label:m.name,hint:`${m.keyId?`ID: ${m.keyId}`:""} ${m.issuerId?`(Issuer: ${m.issuerId.substring(0,8)}...)`:""}`}))});if(Ue(L)){ni("Submission cancelled");return}d=b.find(m=>m.credentialId===L),Ce(`Using selected: ${se.green(d.name)}`)}}catch(w){t.stop("Failed to fetch credentials"),pe(`API Error: ${w.message} `);return}let u=ie.mkdtempSync(Me.join(oi.tmpdir(),`${f.nameLower}-submit-`)),p=d.keyId||d.meta?.keyId,g=d.issuerId||d.meta?.issuerId,E=d.type==="asc_api_key"?`AuthKey_${p}.p8`:"service-account.json",P=Me.join(u,E);t.start("Downloading secure key...");try{let w=await $.get(`/credentials/${d.credentialId}/download`,{params:{projectId:r}});if(w.data.status!=="success"||!w.data.downloadUrl)throw new Error("Failed to get secure download URL");let U=await on.get(w.data.downloadUrl,{responseType:"arraybuffer"});ie.writeFileSync(P,Buffer.from(U.data)),t.stop("Key downloaded to secure temp storage")}catch(w){t.stop("Download failed"),pe(`Failed to download key: ${w.message}`);try{ie.rmSync(u,{recursive:!0,force:!0})}catch{}return}Ce(se.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let C=a==="android"?e.track||o.submit?.[l]?.android?.track||o.submit?.production?.android?.track||"internal":void 0,B=a==="android"?pr(o,l,e.releaseStatus):void 0;try{if(a==="ios"){if(!p){let b=await ut({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:L=>L.length>0?void 0:"Key ID is required"});if(Ue(b))return;p=b}if(!g||g==="undefined"){let b=await ut({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:L=>L.length>0?void 0:"Issuer ID is required"});if(Ue(b))return;g=b}Ce(`Using ASC Key ID: ${p}`),Ce(`Using ASC Issuer ID: ${g}`);let w=ur(o,l),U=await mr(s,P,g,p,w);if(U&&U.apiKeyJsonPath)throw Ce(se.cyan(`
|
|
1020
|
-
[DIAGNOSTIC] API key written to: ${
|
|
1021
|
-
`)),new Error("fastlane pilot execution failed");
|
|
1022
|
-
${(
|
|
1044
|
+
`));try{let O=j("security find-identity -v -p codesigning",{encoding:"utf-8"});r(S.magenta(`${O}
|
|
1045
|
+
`))}catch(O){r(S.red(`[DIAGNOSTIC] Failed to list identities: ${O.message}
|
|
1046
|
+
`))}}await xe("xcodebuild",["-exportArchive","-archivePath",g,"-exportPath",A,"-exportOptionsPlist",W],c,f,r,a),s&&await s("validate");let pe=nt(A,[".ipa"]);for(let O of pe)try{j(`unzip -t "${O}"`,{stdio:"pipe"}),r&&r(`[IPA VALID] ${P.basename(O)} \u2014 archive integrity OK
|
|
1047
|
+
`)}catch{let K=`IPA validation failed for ${P.basename(O)}: archive may be corrupt`;throw r&&r(`[IPA CORRUPT] ${K}
|
|
1048
|
+
`),new Error(K)}return pe}},Fe=e=>{try{let t=P.join(process.cwd(),m.configFileName);if(h.existsSync(t)){let i=JSON.parse(h.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(h.existsSync(n)){let r=h.readFileSync(n,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(r)return r[1]}}else{let i=P.resolve(process.cwd(),h.existsSync("ios")?"ios":"."),n=nt(i,["Info.plist"]).filter(a=>!a.includes("/Pods/")&&!a.includes("/build/")&&!a.includes("/DerivedData/"));n.sort((a,l)=>l.split("/").length-a.split("/").length);for(let a of n){let s=h.readFileSync(a,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(s&&!s[1].includes("$"))return s[1]}let o=nt(i,[".xcodeproj"]);if(o.length>0){let a=P.join(o[0],"project.pbxproj");if(h.existsSync(a)){let s=h.readFileSync(a,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(s)return s[1]}}let r=["app.json","app.config.json","app.config.js","app.config.ts"];for(let a of r)if(h.existsSync(a)){let s=h.readFileSync(a,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(s)return s[1]}}}catch{return null}return null},tr=()=>{try{return j("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=$e.homedir(),i=[P.join(t,"Library/Android/sdk/emulator/emulator"),P.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let n of i)if(h.existsSync(n))return n}return"emulator"},ir=async(e,t)=>{let i=xt();try{if(j("adb devices").toString().split(`
|
|
1049
|
+
`).slice(1).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("*")).map(a=>a.split(" ")[0]).length===0){b.warn(S.yellow("No Android devices or emulators found."));let a=tr(),l=[];try{l=j(`${a} -list-avds`).toString().split(`
|
|
1050
|
+
`).filter(s=>s.trim().length>0)}catch{}if(l.length>0){let s=await ni({message:"Select an emulator to launch:",options:l.map(u=>({value:u,label:u}))});if(Lt(s))return;i.start(`Launching emulator ${s}...`),Zi(a,["-avd",s],{detached:!0,stdio:"ignore"}).unref();let c=0,d=!1;for(;c<60;){try{if(j("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)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 xe("adb",["install","-r",e],process.cwd(),{},t),i.stop("Installation complete.");let r=Fe("android");if(r){b.info(S.blue(`\u{1F680} Launching ${r}...`));try{j(`adb shell dumpsys package ${r}`).toString().split(`
|
|
1051
|
+
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?j(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):j(`adb shell monkey -p ${r} -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(S.red(`Failed to install APK: ${n.message}`))}},nr=async(e,t,i)=>{let n=xt();try{if(!j("xcrun simctl list devices booted").toString().includes("(Booted)")){b.warn(S.yellow("No iOS Simulator is currently booted."));let r=j("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,l=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&l.push({...p,runtime:u})})});let s=await ni({message:"Select a simulator to launch:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(Lt(s))return;n.start(`Booting ${s}...`),j(`xcrun simctl boot ${s}`),j(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let c=0,d=!1;for(;c<30;){try{if(j("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),c++}if(!d)throw n.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");n.stop("Simulator booted.")}n.start("Installing on iOS Simulator..."),await xe("xcrun",["simctl","install","booted",e],process.cwd(),{},i),n.stop("Installation complete."),b.info(S.blue(`\u{1F680} Launching ${t}...`)),await xe("xcrun",["simctl","launch","booted",t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),b.error(S.red(`Failed to install on Simulator: ${o.message}`))}},or=async(e,t,i)=>{let n=xt();n.start("Scanning for connected iOS devices...");try{let o=j("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.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=a[0].identifier;if(a.length>1){n.stop();let s=await ni({message:"Select a device to install on:",options:a.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(Lt(s))return;l=s,n.start(`Installing on ${l}...`)}else n.message(`Installing on ${a[0].model.name}...`);await xe("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},i),n.stop("Installation complete."),b.info(S.blue(`\u{1F680} Launching ${t}...`)),await xe("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},i)}catch(o){n.stop("Installation failed."),b.error(S.red(`Failed to install on device: ${o.message}`)),b.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import en from"fs";import tn from"path";import{isCancel as ri,log as He,select as nn,spinner as rr,text as sr}from"@clack/prompts";import ot from"chalk";async function on(e){let t=await si(e);t&&(He.success(ot.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&He.warn(ot.yellow(t.launchDeferredReason)),t.dashboardUrl&&He.info(ot.dim("View test run: ")+ot.white.underline(t.dashboardUrl)))}async function si(e){let t=Te(`./${m.configFileName}`),i=e.projectId||t?.projectId,n=e.profile||e.buildProfile||"production";if(!i)return He.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let o=e.platform;if(!o&&e.latest){let s=await nn({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ri(s))return null;o=s}let r=await ar(e);if(!r)return null;if(r.kind==="latest"&&!o)return He.error("Pass --platform when using --latest."),null;if(r.kind==="artifact-url"&&!o)return He.error("Pass --platform when using --artifact-url."),null;let a=lr(e.maestroRetries);if(a===null)return null;let l=rr();e.quiet||l.start("Queuing Maestro run...");try{let s=await v.post("/tests/maestro",{projectId:i,platform:o,profile:n,latest:r.kind==="latest",buildId:r.kind==="build-id"?r.value:e.buildId,buildUrl:r.kind==="build-url"?r.value:e.buildUrl,artifactUrl:r.kind==="artifact-url"?r.value:e.artifactUrl,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(o==="ios"?"iphone_15":"pixel_6"),retries:a,record:!!e.maestroRecord});if(s.data.status!=="success")throw new Error(s.data.message||"Failed to queue Maestro run");let c=s.data.testRun,d={testRunId:c.testRunId,status:c.status,projectId:i,buildId:c.buildId,platform:c.platform,dashboardUrl:c.dashboardUrl||`${ut}/tests/${c.testRunId}`,launchDeferredReason:c.launchDeferredReason};return cr(e,d),e.quiet||l.stop("Maestro run queued"),d}catch(s){e.quiet||l.stop("Could not queue Maestro run");let c=s.response?.data?.message||s.message||"Unknown error";return He.error(ot.red(`Maestro queue failed: ${c}`)),null}}async function ar(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 nn({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ri(t))return null;if(t==="latest")return{kind:"latest"};let i=await sr({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:n=>{let o=String(n||"").trim();if(!o)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!o.startsWith("http"))return"Must be a URL"}});return ri(i)?null:{kind:t,value:String(i).trim()}}function lr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(He.error("--maestro-retries must be an integer between 0 and 10."),null):t}function cr(e,t){if(!e.jsonOutput)return;let i=tn.resolve(e.jsonOutput),n={...t,updatedAt:new Date().toISOString()};try{let o=tn.dirname(i);o&&o!=="."&&en.mkdirSync(o,{recursive:!0}),en.writeFileSync(i,JSON.stringify(n,null,2))}catch(o){He.warn(ot.yellow(`Could not write Maestro metadata JSON: ${o.message}`))}}var Mt=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(w.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let t=ai(),i=e.buildId||dr(),n=e.projectId,o=Date.now(),r=!!n,a=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 s=await ht.get(l.data.downloadUrl,{responseType:"stream"}),c=(n||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=Se.join(ur.homedir(),m.workspacesDir,c);re.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(re.existsSync(d)){let L=re.readdirSync(d);for(let B of L){if(u.has(B))continue;if(B==="ios"){let E=Se.join(d,"ios");try{let H=re.readdirSync(E);for(let _ of H)if(!p.has(_))try{re.rmSync(Se.join(E,_),{recursive:!0,force:!0})}catch{}}catch{}continue}let te=Se.join(d,B);try{re.rmSync(te,{recursive:!0,force:!0})}catch{}}}let f=Se.join(d,"source.zip"),y=s.data,D=re.createWriteStream(f);await new Promise((L,B)=>{y.pipe(D),y.on("error",te=>B(te)),D.on("finish",()=>L())}),new ln(f).extractAllTo(d,!0);try{re.unlinkSync(f)}catch{}process.chdir(d),w.info(N.green(`\u2713 Persistent workspace ready: ${d}`)),w.info(N.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${re.existsSync(Se.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${re.existsSync(Se.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),n&&await a(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=an("git config --get remote.origin.url").toString().trim()}catch{w.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),w.info(`Build ID: ${N.cyan(i)}`);let s={},c={},d=Te(`./${m.configFileName}`);if(d){n=d.projectId;let _=e.buildProfile||"production",g=We(d,_);!g&&e.buildProfile&&(w.error(`Build profile '${_}' not found in ${m.configFileName}`),process.exit(1));let A=g||{};process.env.MACH_DEBUG&&w.info(N.dim(`Build profile: ${_} | Platform: ${e.platform} | Distribution: ${A.distribution||"store"} | Environment: ${A.environment||_}`)),A.env&&(c=A.env,w.info(N.blue(`Use Build Profile: ${_}`)));let I=e.platform,M=A[I]||{},U=["developmentClient","simulator","distribution","buildCommand","apk","iosScheme","preBuild","postBuild","scheme","environment","androidPackage","iosBundleIdentifier","name","iosDeploymentTarget","iosApiKeyId","iosApiKeyIssuer","iosApiKeyPath","iosTeamId","iosConfiguration","iosExportMethod","branch","repo","instanceType","ami","bucket","region","nodeVersion"];e.name=d.name,e.appName=d.name,e.androidPackage=d.android?.package,e.iosBundleIdentifier=d.ios?.bundleIdentifier,e.iosScheme=d.ios?.iosScheme,!e.nodeVersion&&d.nodeVersion&&(e.nodeVersion=d.nodeVersion);let F=x=>x==="androidPackage"?M.androidPackage??M.package??A.androidPackage??A.android?.package:x==="iosBundleIdentifier"?M.iosBundleIdentifier??M.bundleIdentifier??A.iosBundleIdentifier??A.ios?.bundleIdentifier:M[x]!==void 0?M[x]:A[x];for(let x of U){let G=F(x),q=x==="androidPackage"||x==="iosBundleIdentifier";G!==void 0&&(e[x]===void 0||q)&&(e[x]=G)}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 R=x=>{if(!x)return x;if(x.startsWith("scripts.")){let G=x.split(".")[1],q=d.scripts?.[G];if(q)return q;w.warn(`Script reference not found: ${x}`)}return x};e.buildCommand=R(e.buildCommand),e.preBuild=R(e.preBuild),e.postBuild=R(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let k={...et(d,m.envPrefix),...et(A,`${m.envPrefix}PROFILE_`)};s={...s,...c,...k},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&A.ios?.appleTeamId&&(e.iosTeamId=A.ios.appleTeamId),!e.iosTeamId&&d.submit?.[_]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[_].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(w.warn(N.yellow(`Check: Using 'production' Team ID for '${_}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?w.info(N.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):w.warn(N.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=an("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{w.warn("Failed to detect git branch.")}let p="1.0.0";try{re.existsSync("./package.json")&&(p=JSON.parse(re.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let f=e.buildProfile||"production",y="Internal";e.developmentClient?y="DevelopmentClient":f.toLowerCase().includes("store")||f.toLowerCase()==="production"?y="Store":f.toLowerCase().includes("preview")||f.toLowerCase().includes("staging")?y="Staging":(f.toLowerCase().includes("development")||f.toLowerCase().includes("dev"))&&(y="Development");let D=e.platform==="ios"?"iOS":"Android",$=e.platform==="ios"&&e.simulator?" (Simulator)":"",L=`${D}${$} v${p} (${y})`;if(yt(e,{status:"created",projectId:n,buildId:i,platform:e.platform,profile:f,branch:u,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:L}),n){try{let _=e.buildProfile||"production",g=e.environment||_;w.info(N.blue(`Fetching managed secrets for profile: ${_} (environment: ${g})...`));let I=(await v.get(`/projects/${n}/secrets/export?env=${g}`)).data;I.status==="success"&&I.secrets&&(s={...s,...I.secrets},Object.keys(I.secrets).length>0&&w.info(N.magenta(`\u2713 Injected ${Object.keys(I.secrets).length} secrets from Dashboard.`)))}catch(_){w.warn(`Failed to load managed secrets from Dashboard: ${_.message}`)}try{w.info(N.blue("Fetching managed credentials..."));let _="development";e.distribution==="store"?_="store":e.distribution==="internal"&&(_=e.platform==="ios"?"adhoc":"internal"),e.developmentClient&&(_="development");let g=await v.get("/credentials/resolve",{params:{projectId:n,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:_}});if(g.data.status==="success"&&g.data.credentials){let A=g.data.credentials;w.info(N.magenta(`\u2713 Found ${A.length} relevant credentials.`));let I=A.filter(R=>{if(R.distributionType){let k=_==="internal"?"adhoc":_;return R.distributionType===k||R.distributionType===_}return!0});w.info(N.dim(` Filtered to ${I.length} credentials for distributionType: ${_}`));let M=!1,U=!1,F=!1;for(let R of I)if(R.downloadUrl)try{let k="",x=5;for(;x>0;)try{let G=await ht.get(R.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});k=Buffer.from(G.data).toString("base64");break}catch(G){if(x--,x===0)throw G;w.warn(N.dim(` - Temporary network error downloading ${R.name}. Retrying... (${5-x}/5)`)),await new Promise(q=>setTimeout(q,2e3))}if(R.type==="ios_cert"&&!M)s.IOS_DIST_P12=k,R.password?(s.IOS_P12_PASSWORD=R.password,w.info(N.dim(` - Injected ${R.name} as IOS_DIST_P12 with password from credential record`))):w.info(N.dim(` - Injected ${R.name} as IOS_DIST_P12`)),M=!0;else if(R.type==="ios_profile"&&!U)s.IOS_PROVISIONING_PROFILE=k,w.info(N.dim(` - Injected ${R.name} as IOS_PROVISIONING_PROFILE`)),U=!0;else if(R.type==="android_keystore"&&!F){s.ANDROID_KEYSTORE_BASE64=k;let G=R.keystorePassword||R.password,q=R.keyPassword||R.keystorePassword||R.password,ce=R.alias||R.meta?.alias;if(G)s.ANDROID_STORE_PASSWORD=G,w.info(N.dim(" - Injected keystore password from credential record"));else{let pe=["ANDROID_STORE_PASSWORD",...[_==="store"?"PRODUCTION":_==="internal"?"STAGING":"DEVELOPMENT",_.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(O=>`KEYSTORE_PASSWORD_${O}`),"KEYSTORE_PASSWORD"].find(O=>!!s[O]);pe&&s[pe]&&(s.ANDROID_STORE_PASSWORD=s[pe])}if(q?(s.ANDROID_KEY_PASSWORD=q,w.info(N.dim(" - Injected key password from credential record"))):s.ANDROID_KEY_PASSWORD=s.ANDROID_STORE_PASSWORD||"",ce)s.ANDROID_KEY_ALIAS=ce;else{let W=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Ce=>!!s[Ce]);W&&(s.ANDROID_KEY_ALIAS=s[W])}w.info(N.dim(` - Injected ${R.name} as ANDROID_KEYSTORE_BASE64`)),F=!0}}catch(k){w.warn(`Failed to download credential ${R.name}: ${k.message}`)}}if(e.platform==="android"){let A=e.buildProfile||"production",I=We(d,A)||{},F=((I.android||{}).versionCode??I.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",R=e.autoVersion||F&&e.distribution==="store";if(F&&!R&&w.info(N.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),R){t.start("Resolving latest versionCode from Google Play...");try{let k=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,x=(g.data.credentials||[]).find(pe=>pe.type==="google_service_account"&&(!pe.bundleId||pe.bundleId===k));if(!x){let O=((await v.get(`/credentials/${n}`)).data.credentials||[]).filter(C=>C.type==="google_service_account");if(x=O.find(C=>C.type==="google_service_account"&&C.bundleId===k),!x&&O.length>0){let C=O.map(K=>K.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${k}. Found service credential(s) for: ${C}.`)}}if(!x)throw new Error(`Google Service Account not found for package ${k}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${k}'.`);let G=await v.get(`/credentials/${x.credentialId}/download`,{params:{projectId:n}});if(G.data.status!=="success"||!G.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let ce=(await ht.get(G.data.downloadUrl,{headers:{Connection:"close"}})).data,W=await Ji(k,ce);if(W==null)throw new Error("Could not retrieve any version information from Google Play.");let Ce=W+1;s.ANDROID_VERSION_CODE=Ce.toString(),t.stop(`\u2713 Resolved versionCode: ${N.green(Ce)} (Latest on Play Store: ${W})`)}catch(k){t.stop("Version resolution failed");let x=k.response?.data?.error?.message||k.message;throw new Error(`Auto-versioning failed: ${x}. Fix Google Play service account permissions or remove android.versionCode="auto".`)}}}if(e.platform==="ios"&&!e.simulator){let A=!!s.IOS_DIST_P12,I=!!s.IOS_PROVISIONING_PROFILE;if(!A||!I){let M=[...A?[]:["Distribution Certificate"],...I?[]:["Provisioning Profile"]].join(" and ");w.error(N.red(`Missing iOS credentials: ${M}`)),e.quiet&&process.exit(1);let U=e.yes||await rn({message:"Would you like to generate these credentials now?",initialValue:!0});if(U&&!sn(U))return await pt({platform:"ios",profile:f}),e.quiet||w.info(N.green("\u2713 Credentials setup complete! Restarting build phase...")),Mt(e);e.quiet||w.info(N.yellow(`Run \`${m.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){w.error(N.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let I=e.yes||await rn({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(I&&!sn(I))return await pt({platform:"android",profile:f}),e.quiet||w.info(N.green("\u2713 Android Keystore setup complete! Restarting build phase...")),Mt(e);e.quiet||w.info(N.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(_){w.warn(`Failed to resolve credentials: ${_.message}`)}}let B=!!(e.local&&e.buildId),te=!!(e.local||e.sshHost),E=!te&&!B;if(B){w.info(N.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let _=await oi({...e,interactive:!1},i,s,n,{branch:u,version:p,summary:L,buildType:y});await H(_),process.exit(0)}async function H(_){if(n&&_.length>0){let g=ai(),A=[];e.quiet||g.start("Uploading artifacts to Dashboard...");try{for(let I of _){let M=Se.basename(I),U=re.readFileSync(I),F=Se.extname(M).toLowerCase(),R="application/octet-stream",k=await v.post(`/builds/${n}/${i}/artifact-upload-url`,{fileName:M,fileType:R});if(k.data.status!=="success")throw new Error(`Failed to get upload URL for ${M}`);let x=!1;for(let G=1;G<=3;G++)try{await ht.put(k.data.uploadUrl,U,{headers:{"Content-Type":R},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),x=!0;break}catch(q){if(w.warn(N.yellow(`Artifact upload attempt ${G}/3 failed (${q.code||q.message})`)),G<3)await new Promise(ce=>setTimeout(ce,3e3*G));else throw q}x&&A.push({name:M,url:k.data.downloadUrl,size:U.length,type:F.substring(1)})}e.quiet||g.stop("Artifacts uploaded.")}catch(I){e.quiet||g.stop("Failed to upload artifacts."),w.error(N.red(`Upload error: ${I.message}`));try{await v.patch(`/builds/${n}/${i}`,{status:"completed",artifacts:_.map(M=>Se.basename(M)),endTime:Date.now()})}catch(M){w.warn(N.yellow(`Could not set fallback build status: ${M.message}`))}return}if(n&&A.length>0)try{w.info(N.cyan(`
|
|
1052
|
+
\u{1F517} Download Links:`));for(let I of A)w.info(N.dim(` - ${I.name}: `)+N.blue.underline(I.url));await v.patch(`/builds/${n}/${i}`,{status:"success",artifacts:A,endTime:Date.now()}),yt(e,{status:"success",projectId:n,buildId:i,platform:e.platform,profile:f,branch:u,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:L,artifacts:A}),w.success(N.green(`
|
|
1053
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!B&&await cn(n,i,e,f)}catch(I){w.warn(N.yellow(`
|
|
1054
|
+
\u26A0\uFE0F Could not report to dashboard: ${I.message}`))}}else if(n)try{await v.patch(`/builds/${n}/${i}`,{status:"completed",endTime:Date.now()}),yt(e,{status:"completed",projectId:n,buildId:i,platform:e.platform,profile:f,branch:u,version:p,buildType:y,developmentClient:!!e.developmentClient,summary:L})}catch{}}if(te){if(w.info(N.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),n&&!r){let _=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"building",branch:u,version:p,summary:L,startTime:o,buildType:y,buildProfile:f,buildArgs:_,simulator:!!e.simulator,developmentClient:!!e.developmentClient})}if(e.sshHost&&e.platform==="ios"){let _=await Wi(e,i,s,n)}else{let _=await oi({...e,interactive:!!e.local},i,s,n,{branch:u,version:p,summary:L,buildType:y});await H(_)}return}if(E&&(w.info(N.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 g=new ln,A=re.readdirSync("."),I=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${m.nameLower}_cli`];for(let F of A){if(I.includes(F))continue;re.statSync(F).isDirectory()?g.addLocalFolder(F,F):g.addLocalFile(F)}let M=g.toBuffer();e.quiet||t.message(`Uploading source (${(M.length/1024/1024).toFixed(1)} MB)...`);let U=!1;for(let F=1;F<=3;F++)try{await ht.put(_.data.uploadUrl,M,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),U=!0;break}catch(R){if(F<3)t.message(`Upload attempt ${F} failed (${R.code||R.message}), retrying...`),await new Promise(k=>setTimeout(k,2e3*F));else throw R}if(e.quiet||t.stop("Source uploaded"),n){let F=process.argv.slice(3).join(" ");await v.post("/builds",{projectId:n,buildId:i,platform:e.platform,status:"pending",branch:u,version:p,summary:L,startTime:o,buildType:y,buildProfile:f,buildArgs:F,simulator:!!e.simulator,developmentClient:!!e.developmentClient}),w.info(N.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Ki(e,i,s,n,e.preBuild),e.quiet||w.info(N.cyan("\u{1F4E1} Connecting to build stream...")),await pr(n,i,e),e.maestro&&await cn(n,i,e,f);return}}catch(l){let s=l.message||"Build failed";l.response?.data?.message?s=l.response.data.message:l.message.includes("status code 402")?s="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(s="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),n&&!e.local&&await a(s),w.error(N.red(`\u2717 Build failed: ${s}`)),process.exit(1)}};async function cn(e,t,i,n){w.info(N.cyan(`
|
|
1055
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await si({projectId:e,buildId:t,platform:i.platform,profile:n,maestroFlows:i.maestroFlows,maestroDevice:i.maestroDevice,maestroRetries:i.maestroRetries,maestroRecord:i.maestroRecord,quiet:i.quiet})}function dn(e){return`${ut}/build/${e}`}function yt(e,t){if(!e.jsonOutput)return;let i=Se.resolve(e.jsonOutput),n={...t,url:t.url||dn(t.buildId),dashboardUrl:t.dashboardUrl||dn(t.buildId),updatedAt:new Date().toISOString()};try{let o=Se.dirname(i);o&&o!=="."&&re.mkdirSync(o,{recursive:!0}),re.writeFileSync(i,JSON.stringify(n,null,2))}catch(o){w.warn(N.yellow(`Could not write build metadata JSON: ${o.message}`))}}async function pr(e,t,i){let n=ai(),o="pending",r=0,a=0;for(i.quiet||n.start("Connecting to build stream...");;){try{let s=(await v.get(`/builds/${e}/${t}`)).data.build;if(s){if(o=s.status,o==="building")i.quiet||n.message("Build in progress...");else if(o==="failed")i.quiet||n.stop("Build failed."),yt(i,{status:"failed",projectId:e,buildId:t,platform:i.platform,profile:s.buildProfile,buildType:s.buildType,developmentClient:!!s.developmentClient,version:s.version,summary:s.summary,error:s.error||"Unknown error",artifacts:s.artifacts||[]}),w.error(N.red(`
|
|
1056
|
+
\u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){i.quiet||n.stop("Build successful!"),yt(i,{status:o,projectId:e,buildId:t,platform:i.platform,profile:s.buildProfile,buildType:s.buildType,developmentClient:!!s.developmentClient,version:s.version,summary:s.summary,artifacts:s.artifacts||[]}),w.success(N.green(`
|
|
1057
|
+
\u2713 Build completed successfully!`));try{i.quiet||(w.info(N.magenta(`
|
|
1058
|
+
\u{1F4F1} Installation Hub:`)),w.info(N.dim(" - View & Install Build: ")+N.white.underline(`${ut}/build/${t}`)))}catch{}return}else if(o!=="pending"){i.quiet||n.stop(`Build status: ${o}`);return}}try{let d=(await v.get(`/builds/${e}/${t}/logs`)).data;if(d&&typeof d=="string"&&!i.quiet){let u=d.split(`
|
|
1059
|
+
`);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(N.dim(` ${u[p]}`));r=u.length}}}catch{}a=0}catch{a++,a>10&&(n.stop("Connection lost."),w.error(N.red(`
|
|
1060
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import fr from"http";import{execSync as De,spawn as un}from"child_process";import li from"chalk";import{log as rt}from"@clack/prompts";import mr from"axios";import di from"fs";import gr from"os";import ci from"path";var St=7070;function hr(){let e=[];try{let t=De("adb devices -l",{stdio:"pipe"}).toString(),i=new Set;t.split(`
|
|
1061
|
+
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let o=n.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];i.add(r);let a=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:a?a[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let t=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,n=De(`${t} -list-avds`,{stdio:"pipe"}).toString().split(`
|
|
1062
|
+
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let t=De("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),i=JSON.parse(t);Object.entries(i.devices).forEach(([n,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:n,details:`${r.name} (${n})`})})})}catch{}try{let t=De("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(t).result?.devices||[]).forEach(n=>{let o=n.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:n.identifier,platform:"ios",type:"physical",name:n.deviceProperties?.name||"iPhone",status:"online",details:`${n.deviceProperties?.name||"iPhone"} (${n.model?.name||n.hardwareModel||""}) - ${o}`})})}catch{}return e}async function pn(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 yr(e,t){let i=await mr({method:"GET",url:e,responseType:"stream",timeout:12e4}),n=di.createWriteStream(t);i.data.pipe(n),await new Promise((o,r)=>{n.on("finish",o),n.on("error",r)})}async function Sr(e,t,i){let n=i||(t.toLowerCase().includes(".apk")?"android":"ios"),o=t.toLowerCase().includes(".ipa"),r=di.mkdtempSync(ci.join(gr.tmpdir(),`${St}-install-`)),a=ci.join(r,n==="android"?"install.apk":o?"install.ipa":"install.zip");try{if(await yr(t,a),n==="android"){De(`adb -s ${JSON.stringify(e)} install -r ${JSON.stringify(a)}`,{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");De(`unzip -o ${JSON.stringify(a)} -d ${JSON.stringify(r)}`,{stdio:"pipe"});let l="";try{l=De(`find ${JSON.stringify(ci.join(r,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=De(`find ${JSON.stringify(r)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${o?"IPA":"archive"}.`);try{De(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(s){try{De(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(s.stderr?.toString().trim()||s.message||"iOS install failed.")}}}finally{di.rmSync(r,{recursive:!0,force:!0})}}function Er(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 De(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),un("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android"){let i=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`;return un(i,["-avd",e],{detached:!0,stdio:"ignore"}).unref(),"Emulator booting in background..."}throw new Error("Invalid platform.")}async function fn(){process.platform!=="darwin"&&rt.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=fr.createServer((n,o)=>{if(o.setHeader("Access-Control-Allow-Origin","*"),o.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),o.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){o.writeHead(204),o.end();return}let r=new URL(n.url||"/",`http://localhost:${St}`);if(n.method==="GET"&&r.pathname==="/local/devices"){try{let a=hr();o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",targets:a}))}catch(a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:a.message}))}return}if(n.method==="POST"&&r.pathname==="/install-local"){t(n,o);return}if(n.method==="POST"&&r.pathname==="/local/boot"){i(n,o);return}o.writeHead(404),o.end()}),t=async(n,o)=>{try{let{deviceId:r,artifactUrl:a,platform:l}=await pn(n);if(!r||!a){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Sr(r,a,l),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:`Installed on ${r}`}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local install failed"}))}},i=async(n,o)=>{try{let{id:r,platform:a}=await pn(n),l=Er(r,a);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"success",message:l}))}catch(r){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({status:"error",message:r.message||"Local device launch failed"}))}};e.listen(St,"127.0.0.1",()=>{rt.success(li.green(`Local device agent running on http://localhost:${St}`)),rt.info(li.dim("Keep this running while using the Install Hub on the dashboard.")),rt.info(li.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?rt.error(`Port ${St} is already in use \u2014 agent may already be running.`):rt.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Sa}from"module";import{text as br,password as _r,spinner as Ir,isCancel as hn}from"@clack/prompts";import mi from"chalk";import Et from"fs";import mn from"path";import Ar from"os";var ui=mn.join(Ar.homedir(),m.configDir),pi=mn.join(ui,"config.json");function fi(){if(!Et.existsSync(pi))return{};try{return JSON.parse(Et.readFileSync(pi,"utf-8"))}catch{return{}}}function gn(e){Et.existsSync(ui)||Et.mkdirSync(ui,{recursive:!0});let i={...fi(),...e};Et.writeFileSync(pi,JSON.stringify(i,null,2))}async function yn(){let e=fi(),t=await br({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(hn(t))return;let i=await _r({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(hn(i))return;let n=Ir();n.start("Authenticating...");try{let r=await(await fetch(`${Nt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:i})})).json();r.status==="success"&&r.user.token?(Ri({id:r.user.id,email:t,token:r.user.token,refreshToken:r.user.refreshToken}),gn({lastLoginEmail:t}),n.stop(mi.green("Login successful!"))):n.stop(mi.red("Login failed: "+(r.message||"Unknown error")))}catch(o){n.stop(mi.red("Network error: "+o.message))}}import{outro as Pr,select as $r,spinner as Dr,isCancel as Rr}from"@clack/prompts";import Ut from"chalk";import gi from"fs";import vr from"path";var Sn=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",wr=()=>process.versions.node.split(".")[0]||"24";async function En(){if(!ge()){console.log(Ut.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=Dr();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(Ut.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let n=i.projects.map(y=>({value:y.projectId,label:`${y.name} (${y.slug})`})),o=await $r({message:"Select a project to link:",options:n});if(Rr(o))return;let r=vr.join(process.cwd(),m.configFileName),a={};if(gi.existsSync(r))try{a=JSON.parse(gi.readFileSync(r,"utf-8"))}catch{}let l=i.projects.find(y=>y.projectId===o),s=a.android?.package||Fe("android"),c=a.ios?.bundleIdentifier||Fe("ios"),d=a.android||{},u=a.submit?.production?.android||{},p=a.submit?.production?.ios||{},f={projectId:o,name:l?.name,slug:l?.slug,nodeVersion:a.nodeVersion||wr(),scheme:l?.slug?.toLowerCase()||"app",android:{...d,package:s||"",versionCode:d.versionCode||"auto"},ios:{bundleIdentifier:c||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...u,track:u.track||"internal",releaseStatus:u.releaseStatus||"completed"},ios:{ascAppId:Sn(p.ascAppId),appleTeamId:Sn(p.appleTeamId)}}}};gi.writeFileSync(r,JSON.stringify(f,null,2)),Pr(Ut.green(`Linked to project ${f.name} (${f.slug})`))}catch(i){t.stop(Ut.red("Error fetching projects: "+i.message))}}import{outro as Or,text as Ft,select as Cr,spinner as Nr,isCancel as At}from"@clack/prompts";import bt from"chalk";import Tr from"fs";import kr from"path";import{randomUUID as xr}from"crypto";var Lr=()=>process.versions.node.split(".")[0]||"24";async function An(){if(!ge()){console.log(bt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Ft({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(At(t))return;let i=await Ft({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(At(i))return;let n=await Cr({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(At(n))return;let o="";if(n==="android"||n==="all"){let l=Fe("android");if(o=await Ft({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),At(o))return}let r="";if(n==="ios"||n==="all"){let l=Fe("ios");if(r=await Ft({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),At(r))return}let a=Nr();a.start("Creating project...");try{let l=xr(),c={projectId:l,name:t,slug:i,storageType:"managed",platforms:n==="all"?["android","ios","web"]:[n]},{data:d}=await v.post("/projects",c);if(d.status==="success"){a.stop(bt.green("Project created successfully!"));let u=kr.join(process.cwd(),m.configFileName);Tr.writeFileSync(u,JSON.stringify({projectId:l,name:t,slug:i,nodeVersion:Lr(),...o?{android:{package:o,versionCode:"auto"}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),Or(bt.green(`Initialized project ${t} and linked locally!`))}else a.stop(bt.red("creation failed: "+d.message))}catch(l){a.stop(bt.red("Network error: "+l.message))}}import{spinner as _n,log as Ee}from"@clack/prompts";import Ht from"chalk";import bn from"fs";import Mr from"path";async function In(e,t){let i=ge();if(!i){Ee.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let n=Mr.join(process.cwd(),m.configFileName);if(!bn.existsSync(n)){Ee.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(bn.readFileSync(n,"utf-8"))}catch{Ee.error(`Failed to parse ${m.configFileName}`);return}let{projectId:r}=o;if(!r){Ee.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await Ur(r,t,i):e==="list"?await Fr(r,i):Ee.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Ur(e,t,i){if(t.length===0){Ee.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let n=_n();n.start("Setting environment variables...");let o=0,r=0;for(let a of t){let[l,...s]=a.split("="),c=s.join("=");if(!l||c===void 0){Ee.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:u}=await v.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(Ee.error(`Failed to set ${l}: ${u.message}`),r++)}catch(d){Ee.error(`Network error setting ${l}: ${d.message}`),r++}}n.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Fr(e,t){let i=_n();i.start("Fetching environment variables...");try{let{data:n}=await v.get(`/projects/${e}/secrets`);if(n.status==="success"){i.stop("Fetched variables.");let o=n.secrets||[];o.length===0?Ee.info("No environment variables found for this project."):(Ee.info(Ht.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${Ht.cyan(r.key)} = ${a} ${Ht.gray(`[${r.environment}]`)}`)}))}else i.stop(Ht.red(`Failed to fetch variables: ${n.message}`))}catch(n){i.stop("Failed to fetch variables."),Ee.error(`Network error: ${n.message}`)}}import{spinner as st,text as _t,select as Ei,isCancel as je,cancel as Ai}from"@clack/prompts";import ee from"chalk";import Y from"fs";import de from"path";import{spawn as Hr,spawnSync as Je}from"child_process";import Rn from"axios";import Xe from"os";import Br from"crypto";var Gr={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},jr=e=>e?.type==="google_service_account",Bt=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId;async function vn(e){let t=st(),i=ge(),n=`./${m.configFileName}`;if(!Y.existsSync(n)){le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o=JSON.parse(Y.readFileSync(n,"utf-8")),{projectId:r}=o,a=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId.`);return}ae(ee.dim(`Submit for project: ${o.name||r} | Profile: ${a}`));let l=e.platform;if(!l){let E=await Ei({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(je(E)){Ai("Operation cancelled");return}l=E}let s=await Qr(r,l,e,i?.token);if(!s)return;ae(`Using artifact: ${ee.green(de.basename(s))} `);let c=l==="android"?Kr(o,a):void 0;t.start("Fetching submission credentials from Dashboard...");let d;try{let H=(await v.get(`/credentials/${r}`)).data.credentials||[];if(l==="android"&&!c){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json.");return}let _=H.filter(jr),g=l==="ios"?H.filter(A=>A.type==="asc_api_key"):Vr(_,c);if(g.length===0){if(t.stop("Credentials missing"),le(l==="android"?`No Google Play service credential found for package ${c}.`:`No Service Credentials found for ${l}.`),l==="android"){let A=_.map(Bt).filter(Boolean).join(", ");A&&ae(`Found Google Play service credential(s) for: ${A}`),ae(`Use '${m.nameLower} credentials:service --platform android --package-name ${c}' or upload it under that package in the Dashboard.`)}else ae(`Use '${m.nameLower} credentials:service --platform ${l}' or use the Dashboard to upload them.`);return}if(g.length===1)d=g[0],t.stop(`Using: ${d.name}`),l==="android"&&Bt(d)==="*"&&ae(ee.yellow(`Using legacy wildcard Google Play credential for ${c}. Upload a package-scoped credential when possible.`));else{t.stop("Multiple credentials found");let A=await Ei({message:`Choose a ${l==="ios"?"App Store Connect":"Google Play"} credential:`,options:g.map(I=>({value:I.credentialId,label:I.name,hint:`${I.keyId?`ID: ${I.keyId}`:""} ${I.issuerId?`(Issuer: ${I.issuerId.substring(0,8)}...)`:""}`}))});if(je(A)){Ai("Submission cancelled");return}d=g.find(I=>I.credentialId===A),ae(`Using selected: ${ee.green(d.name)}`)}}catch(E){t.stop("Failed to fetch credentials"),le(`API Error: ${E.message} `);return}let u=Y.mkdtempSync(de.join(Xe.tmpdir(),`${m.nameLower}-submit-`)),p=d.keyId||d.meta?.keyId,f=d.issuerId||d.meta?.issuerId,y=d.type==="asc_api_key"?`AuthKey_${p}.p8`:"service-account.json",D=de.join(u,y);t.start("Downloading secure key...");try{let E=await v.get(`/credentials/${d.credentialId}/download`,{params:{projectId:r}});if(E.data.status!=="success"||!E.data.downloadUrl)throw new Error("Failed to get secure download URL");let H=await Rn.get(E.data.downloadUrl,{responseType:"arraybuffer"});Y.writeFileSync(D,Buffer.from(H.data)),t.stop("Key downloaded to secure temp storage")}catch(E){t.stop("Download failed"),le(`Failed to download key: ${E.message}`);try{Y.rmSync(u,{recursive:!0,force:!0})}catch{}return}ae(ee.blue(`Initiating ${l==="ios"?"TestFlight":"Google Play"} submission...`));let $,L,B,te=!1;try{l==="android"&&($=e.track||o.submit?.[a]?.android?.track||o.submit?.production?.android?.track||"internal",L=Yr(o,a,e.releaseStatus),B=Xr(o,a,e.rollout),te=qr(o,a,e.changesNotSentForReview),Zr(L,B))}catch(E){le(E.message),$n(u);return}try{if(l==="ios"){if(!p){let g=await _t({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:A=>A.length>0?void 0:"Key ID is required"});if(je(g))return;p=g}if(!f||f==="undefined"){let g=await _t({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:A=>A.length>0?void 0:"Issuer ID is required"});if(je(g))return;f=g}ae(`Using ASC Key ID: ${p}`),ae(`Using ASC Issuer ID: ${f}`);let E=zr(o,a),H=Wr(o,a,e),_=H?await ts(s,D,f,p,E,H):await es(s,D,f,p,E);if(_&&_.apiKeyJsonPath)throw ae(ee.cyan(`
|
|
1063
|
+
[DIAGNOSTIC] API key written to: ${_.apiKeyJsonPath}
|
|
1064
|
+
`)),new Error("fastlane pilot execution failed");Dn(`${l==="ios"?"App Store":"Google Play"} submission successful!`)}else await ss(s,D,$||"internal",c,L||"completed",B,te,a),Dn("Google Play submission successful!")}catch(E){le(`Submission failed: ${E.message}`)}finally{$n(u),s.includes(`${m.nameLower}-artifact-`)}}function Kr(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let i=wi(e,t);if(i)return i;let n=de.join(process.cwd(),"app.json");if(Y.existsSync(n))try{return JSON.parse(Y.readFileSync(n,"utf-8")).expo?.android?.package}catch{}let o=de.join(process.cwd(),"app.config.json");if(Y.existsSync(o))try{let r=JSON.parse(Y.readFileSync(o,"utf-8"));return r.expo?.android?.package||r.android?.package}catch{}}function Vr(e,t){let i=e.filter(r=>Bt(r)===t);if(i.length>0)return i;let n=e.filter(r=>{let a=Bt(r);return!a||a==="*"});return e.length>0&&e.length===n.length?n:[]}function zr(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:Oi(e,t)}function Wr(e,t,i){let n=e.submit?.[t]?.ios||{},o=e.submit?.production?.ios||{},r=i.sshHost||n.sshHost||o.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return r?{sshHost:r,sshUser:i.sshUser||n.sshUser||o.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:i.sshKey||n.sshKey||o.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function Yr(e,t,i){let n=i||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return Jr(n)}function Jr(e){let t=Gr[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Xr(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 o=Number(n);if(!Number.isFinite(o)||o<=0||o>=1)throw new Error(`Invalid Android rollout fraction "${n}". Use a number greater than 0 and less than 1, for example 0.1.`);return o}function qr(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 Zr(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 Qr(e,t,i,n){let o=i.buildId?"id":i.latest?"latest":null;if(!o){let a=await Ei({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${m.name})`},{value:"id",label:`Input Build ID (${m.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]});if(je(a))return Ai("Operation cancelled"),null;o=a}if(o==="local"){let a=await _t({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!Y.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 je(a)?null:a}let r=st();if(o==="latest"){let a=i.profile||i.buildProfile;r.start(`Fetching latest${a?` ${a}`:""} build...`);try{let l=await v.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let s=l.data.builds||[],c=a?.toLowerCase(),d=E=>E.platform?.toLowerCase()===t.toLowerCase()&&E.status?.toLowerCase()==="success",u=E=>c?[E.buildProfile,E.profile,E.profileName,E.buildType].filter(Boolean).some(H=>String(H).toLowerCase()===c):!0,p=s.filter(E=>d(E)&&u(E)),f=p.find(E=>E.buildType?.toLowerCase()==="store"||E.distribution?.toLowerCase()==="store")||p[0],y=s.some(E=>E.platform?.toLowerCase()===t.toLowerCase()&&E.status?.toLowerCase()==="success");if(!f)return r.stop("No suitable build found"),le(a&&y?`No successful ${t} builds found for profile "${a}".`:"No successful builds found for this platform."),null;r.stop(`Found build: ${f.buildId}`);let D=f.artifacts||[];if(D.length===0||D.every(E=>!(E.url||E.downloadUrl)))try{let E=await v.get(`/builds/${e}/${f.buildId}/artifacts`);E.data.status==="success"&&E.data.artifacts?.length>0?(D=E.data.artifacts.map(H=>({...H,url:H.url||H.downloadUrl})),console.log(ee.cyan(` [RECOVERY] Fetched ${D.length} artifact(s) with download URLs.`))):console.log(ee.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(E){console.log(ee.red(` [RECOVERY] /artifacts fetch failed: ${E.message}`))}let L=t==="ios",B=D.find(E=>{let H=(E.type||"").toLowerCase(),_=(E.name||"").toLowerCase();if(console.log(ee.dim(` - Checking: ${E.name} (Type: ${E.type}, HasLink: ${!!(E.url||E.downloadUrl)})`)),H)return H===(L?"ipa":"aab");let g=L?".ipa":".aab",A=(E.url||E.downloadUrl||"").toLowerCase();return _.endsWith(g)||A.includes(g)});if(!B||!(B.url||B.downloadUrl))return le("Build found but artifact URL is missing."),null;let te=B.url||B.downloadUrl;return await hi(te,L?"ios":"android")}catch(l){return r.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(o==="id"){let a=i.buildId||await _t({message:"Enter Build ID:",validate:l=>l.length<5?"Invalid ID":void 0});if(je(a))return null;r.start("Fetching build...");try{let l=await v.get(`/build/${a}`);if(l.data.status!=="success")throw new Error(l.data.message);let s=l.data.build;if(!s)throw new Error("Build not found");let c=t==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(c?"ipa":"aab");let p=c?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),le("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await hi(d.url,c?"ios":"android"))}catch(l){return r.stop("Fetch failed"),le(l.message),null}}if(o==="url"){let a=await _t({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return je(a)?null:await hi(a,t)}return null}async function hi(e,t,i=3){let n=st();n.start("Downloading artifact...");let o=Y.mkdtempSync(de.join(Xe.tmpdir(),`${m.nameLower}-artifact-`)),r=`app.${t==="ios"?"ipa":"aab"}`,a=de.join(o,r);for(let l=1;l<=i;l++)try{l>1&&(n.message(`Downloading artifact (Retry ${l}/${i})...`),await new Promise(d=>setTimeout(d,2e3*l)));let s=Y.createWriteStream(a),c=await Rn({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{c.data.pipe(s);let p=!1;c.data.on("error",f=>{p||(p=!0,s.close(),u(f))}),s.on("finish",()=>{p||d()}),s.on("error",f=>{p||(p=!0,u(f))})}),n.stop("Download complete"),a}catch(s){if(l===i)throw n.stop("Download failed"),s}throw new Error("Download failed after retries")}async function es(e,t,i,n,o){let r=st();if(o&&ae(`Bundle ID: ${ee.green(o)}`),!i||!n)throw le(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let a=wn(t,i,n),l=ls();return r.start("Uploading to TestFlight (pilot)..."),new Promise((s,c)=>{let d=Hr(l.command,["pilot","upload","--ipa",e,"--api_key_path",a,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:l.env});d.on("close",u=>{if(u!==0)r.stop("Pilot failed"),s({apiKeyJsonPath:a});else{r.stop("IPA uploaded to TestFlight");try{Y.unlinkSync(a)}catch{}s({apiKeyJsonPath:null})}}),d.on("error",u=>{try{Y.unlinkSync(a)}catch{}r.stop("Pilot execution error"),c(ds(u))})})}async function ts(e,t,i,n,o,r){let a=st();if(o&&ae(`Bundle ID: ${ee.green(o)}`),!i||!n)throw le(`Missing credentials: issuerId=${i}, keyId=${n}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=wn(t,i,n),s=`${r.sshUser}@${r.sshHost}`,c=is(r),d=ns(r),u="",p="";try{if(a.start(`Preparing remote iOS submit runner (${s})...`),u=os("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!u)throw new Error("Remote runner did not return a temp directory.");a.stop(`Remote runner ready: ${s}`),a.start("Uploading IPA and App Store Connect key to remote runner..."),yi("scp",[...d,e,`${s}:${u}/app.ipa`],"IPA upload to remote runner"),yi("scp",[...d,l,`${s}:${u}/api_key.json`],"ASC key upload to remote runner"),p=de.join(Xe.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),Y.writeFileSync(p,rs(u)),yi("scp",[...d,p,`${s}:${u}/submit.sh`],"submit script upload to remote runner"),a.stop("Remote submit inputs uploaded"),a.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${It(`${u}/submit.sh`)} && bash ${It(`${u}/submit.sh`)}`,y=Je("ssh",[...c,f],{stdio:"inherit"});if(y.error)throw bi("ssh",y.error);if(y.status!==0)throw new Error(`Remote iOS submit failed with exit code ${y.status}.`);return a.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw a.stop("Remote iOS submit failed"),f}finally{try{Y.unlinkSync(l)}catch{}if(p)try{Y.unlinkSync(p)}catch{}if(u)try{Je("ssh",[...c,`rm -rf ${It(u)}`],{stdio:"ignore"})}catch{}}}function wn(e,t,i){let n=Y.readFileSync(e,"utf8"),o;try{o=Br.createPrivateKey(n).export({type:"pkcs8",format:"pem"})}catch{ae("Key normalization failed, falling back to manual re-wrapping..."),o=`-----BEGIN PRIVATE KEY-----
|
|
1065
|
+
${(n.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1023
1066
|
`)}
|
|
1024
|
-
-----END PRIVATE KEY-----`}console.log(
|
|
1025
|
-
[DIAGNOSTIC] Key ID: ${
|
|
1026
|
-
`))
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1067
|
+
-----END PRIVATE KEY-----`}console.log(ee.yellow(`
|
|
1068
|
+
[DIAGNOSTIC] Key ID: ${i}`)),console.log(ee.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(ee.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${o.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(ee.yellow(`[DIAGNOSTIC] Key Checksum (End): ${o.substring(o.length-28).replace(/\n/g,"\\n")}
|
|
1069
|
+
`));let r=de.join(Xe.tmpdir(),`api_key_${i}_${Date.now()}.json`),a={key_id:i,issuer_id:t,key:o,in_house:!1};return Y.writeFileSync(r,JSON.stringify(a,null,2)),r}function is(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 ns(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function os(e,t){let i=Je(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(i.error)throw bi(e,i.error);if(i.status!==0)throw new Error(`${e} failed with exit code ${i.status}.`);return i.stdout||""}function yi(e,t,i){let n=Je(e,t,{stdio:"inherit"});if(n.error)throw bi(e,n.error);if(n.status!==0)throw new Error(`${i} failed with exit code ${n.status}.`)}function bi(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 It(e){return`'${e.replace(/'/g,"'\\''")}'`}function rs(e){let t=It(`${e}/app.ipa`),i=It(`${e}/api_key.json`);return`#!/bin/bash
|
|
1070
|
+
set -euo pipefail
|
|
1071
|
+
|
|
1072
|
+
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
1073
|
+
export FASTLANE_SKIP_UPDATE_CHECK=1
|
|
1074
|
+
export FASTLANE_HIDE_CHANGELOG=1
|
|
1075
|
+
export CI="\${CI:-1}"
|
|
1076
|
+
|
|
1077
|
+
if ! command -v fastlane >/dev/null 2>&1; then
|
|
1078
|
+
if ! command -v gem >/dev/null 2>&1; then
|
|
1079
|
+
echo "fastlane was not found and gem is unavailable on the remote macOS runner."
|
|
1080
|
+
exit 127
|
|
1081
|
+
fi
|
|
1082
|
+
|
|
1083
|
+
FASTLANE_GEM_HOME="\${FASTLANE_GEM_HOME:-$HOME/.local/share/fastlane/3.4.0}"
|
|
1084
|
+
FASTLANE_BIN_DIR="$FASTLANE_GEM_HOME/bin"
|
|
1085
|
+
mkdir -p "$FASTLANE_BIN_DIR"
|
|
1086
|
+
export GEM_HOME="$FASTLANE_GEM_HOME"
|
|
1087
|
+
export GEM_PATH="$FASTLANE_GEM_HOME:\${GEM_PATH:-}"
|
|
1088
|
+
export PATH="$FASTLANE_BIN_DIR:$PATH"
|
|
1089
|
+
gem install fastlane -NV --install-dir "$FASTLANE_GEM_HOME" --bindir "$FASTLANE_BIN_DIR"
|
|
1090
|
+
fi
|
|
1091
|
+
|
|
1092
|
+
fastlane pilot upload \\
|
|
1093
|
+
--ipa ${t} \\
|
|
1094
|
+
--api_key_path ${i} \\
|
|
1095
|
+
--skip_submission true \\
|
|
1096
|
+
--skip_waiting_for_build_processing true
|
|
1097
|
+
`}async function ss(e,t,i="internal",n,o="completed",r,a=!1,l="production"){let s=st();if(!n||n==="*")throw new Error("Android package name is required for Google Play submission.");let c=r!==void 0?` (${r} rollout)`:"";s.start(`Uploading to Google Play ${i} track with ${o} release status${c}...`);try{let d=JSON.parse(Y.readFileSync(t,"utf-8"));as(d);let u=await Xi({packageName:n,serviceAccount:d,aabPath:e,track:i,releaseStatus:o,userFraction:r,changesNotSentForReview:a});s.stop(`AAB uploaded to ${i} track (versionCode ${u.versionCode})`)}catch(d){throw s.stop("Google Play upload failed"),new Error(us(d,i,n,l))}}function as(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Si(){let e=process.env.HOME||Xe.homedir(),t=process.env.FASTLANE_GEM_HOME||de.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",de.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",CI:process.env.CI||"1"}}function ls(){let e=Si(),t=Pn(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){cs(e);let i=Pn(Si());if(i)return i}return{command:"fastlane",env:Si()}}function Pn(e){let t=process.env.HOME||Xe.homedir(),i=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",de.join(process.env.FASTLANE_GEM_HOME||de.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let n of i){if(n.includes("/")&&!Y.existsSync(n))continue;if(!Je(n,["--version"],{env:e,stdio:"ignore"}).error)return{command:n,env:e}}return null}function cs(e){let t=Je("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let i=process.env.HOME||Xe.homedir(),n=process.env.FASTLANE_GEM_HOME||de.join(i,".local/share/fastlane/3.4.0"),o=de.join(n,"bin");Y.mkdirSync(o,{recursive:!0}),ae(ee.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let r=Je("gem",["install","fastlane","-NV","--install-dir",n,"--bindir",o],{env:{...e,GEM_HOME:n,GEM_PATH:[n,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(r.error||r.status!==0)&&ae(ee.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function ds(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(`
|
|
1098
|
+
`))}function us(e,t,i,n="production"){let o=e?.message||String(e);if(/changesNotSentForReview/i.test(o))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${i||"unknown"} | Track: ${t}`,`Retry with: ${m.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(`
|
|
1099
|
+
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(o))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(`
|
|
1100
|
+
`);if(/package.*not found|application.*not found|no application was found/i.test(o))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(`
|
|
1101
|
+
`);if(/only releases with status draft|draft app/i.test(o))return["Google Play requires a draft release for this app state.",`Package: ${i||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${n} --track ${t} --release-status draft`].join(`
|
|
1102
|
+
`);if(o.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: ${m.nameLower} build --platform android --profile ${n} --auto-version`,`Then: ${m.nameLower} submit --latest --platform android --profile ${n} --track ${t}`].join(`
|
|
1103
|
+
`);if(/version code \d+ has already been used/i.test(o))return[o.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: ${m.nameLower} build --platform android --profile ${n} --auto-version`].join(`
|
|
1104
|
+
`);let r=o.match(/Google Api Error:[^\n]+/)||o.match(/Google Play API Error:[^\n]+/);return r?r[0]:o||"Google Play submission failed"}function $n(e){try{Y.existsSync(e)&&Y.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ee.red(`\u274C ${e}`))}function ae(e){console.log(ee.gray(`\u2022 ${e}`))}function Dn(e){console.log(ee.green(`\u2713 ${e}`))}import{spinner as ps,log as qe,outro as fs}from"@clack/prompts";import _i from"chalk";import On from"fs";import ms from"path";import{execSync as gs}from"child_process";import hs from"adm-zip";import ys from"axios";import{randomUUID as Ss}from"crypto";async function Cn(e){qe.info(_i.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=Te();(!t||!t.projectId)&&(qe.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let i=t.projectId,n=e.branch||"production",o="1.0.0";try{o=JSON.parse(On.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{qe.warn("Could not read package.json version. Defaulting to 1.0.0")}let r=ps();r.start(`Compiling JavaScript bundles for OTA (Channel: ${n}, Runtime: ${o})...`);try{gs("npx expo export --platform all",{stdio:"ignore"})}catch(c){r.stop("Compilation failed."),qe.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}r.message("Zipping artifact payload...");let a=ms.join(process.cwd(),"dist");On.existsSync(a)||(r.stop("Missing dist folder."),qe.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new hs;l.addLocalFolder(a,"dist");let s=l.toBuffer();r.message("Uploading payload to Mach Cloud...");try{let c=Ss(),d=await v.post("/builds/source-upload-url",{projectId:i,buildId:c});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await ys.put(u,s,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),r.message(`Promoting Update to ${n}...`),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:o,platform:"android",updateId:`${c}-android`,manifestKey:p}),await v.post("/updates/publish",{projectId:i,channelName:n,runtimeVersion:o,platform:"ios",updateId:`${c}-ios`,manifestKey:p}),r.stop("Update Live!"),fs(_i.green(`\u2713 OTA Update natively shipped to the '${n}' channel.`)),qe.info(_i.dim(`Any app running runtime '${o}' will download this bundle smoothly.`))}catch(c){r.stop("Update failed during Cloud Sync."),qe.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as Es,outro as Nn,log as at}from"@clack/prompts";import Le from"chalk";async function Tn(){Es(Le.blue(`${m.name} CLI - User Profile`));let e=ge();if(!e){at.warn(Le.yellow("You are not logged in.")),at.info(`Run \`${m.nameLower} login\` to authenticate.`),Nn();return}at.info(`${Le.bold("Logged in as:")} ${Le.green(e.email)}`);try{await v.get("/projects");let i=ge().token.split(".");if(i.length===3){let n=JSON.parse(Buffer.from(i[1],"base64").toString());if(n.exp){let o=new Date(n.exp*1e3),r=new Date,a=o.getTime()-r.getTime();if(a>0){let l=Math.round(a/6e4),s=(l/60).toFixed(1);at.info(`${Le.bold("Token status:")} Valid (Expires in ~${s}h / ${l}m)`)}else at.warn(`${Le.bold("Token status:")} ${Le.red("Expired")} (Auto-refresh failed)`)}}}catch{at.warn(`${Le.bold("Token status:")} ${Le.red("Unreachable")} (Session might be truly expired)${Nt}`)}Nn(Le.blue("---"))}import{spawn as _s}from"child_process";import{log as Ke}from"@clack/prompts";import Ae from"chalk";import Is from"fs";import As from"net";async function bs(e){return new Promise(t=>{let i=As.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 kn(e,t=20){let i=e;for(;i<e+t;){if(!await bs(i))return i;i++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var xn=async e=>{Ke.info(Ae.blue(`Starting ${m.name} Dev Orchestrator...`));let t=Te(),i=e.buildProfile||"development",n=t?We(t,i):null,o={...process.env};if(t?.projectId)try{Ke.info(Ae.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(o,u.data.secrets),Ke.info(Ae.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{Ke.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(o,et(t,m.envPrefix)),n&&(Object.assign(o,et(n,`${m.envPrefix}PROFILE_`)),n.env&&Object.assign(o,n.env));let r=!1;try{let u=JSON.parse(Is.readFileSync("package.json","utf-8"));r=!!(u.dependencies?.expo||u.devDependencies?.expo)}catch{Ke.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let a=Number(e.port||n?.port||8081),l=await kn(a);l!==a&&Ke.info(Ae.yellow(`Port ${a} is busy. ${m.name} is using ${l} instead.`));let s=process.platform==="win32"?"npx.cmd":"npx",c=[];if(r?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),r){let u=[`${Ae.cyan("i")} open iOS simulator`,`${Ae.cyan("a")} open Android emulator/device`,`${Ae.cyan("w")} open web`,`${Ae.cyan("r")} reload app`];Ke.info([Ae.bold("Launch controls"),...u.map(p=>` ${p}`),"",Ae.dim("Direct launch: mach start --ios | --android | --web"),Ae.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1105
|
+
`))}else Ke.info(Ae.dim(`Metro URL: http://localhost:${l}`));let d=_s(s,c,{stdio:"inherit",env:o});return new Promise((u,p)=>{d.on("exit",f=>{f===0?u():p(new Error(`Dev server exited with code ${f}`))}),d.on("error",f=>{p(f)})})};import{log as he}from"@clack/prompts";import Re from"chalk";var Ln=async e=>{let t=Te();t||(he.error(Re.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let i=e.profile||"development",n=We(t,i);if(e.json){console.log(JSON.stringify({project:t,resolved:n},null,2));return}he.info(Re.bgBlue.white(` Resolved ${m.name} Config [${i}] `)),he.info(Re.dim("----------------------------------------")),he.info(`${Re.blue("Project ID:")} ${t.projectId}`),he.info(`${Re.blue("Name:")} ${t.name}`),he.info(`${Re.blue("Scheme:")} ${t.scheme}`),n?(he.info(Re.dim(`
|
|
1106
|
+
Profile Settings:`)),he.info(`${Re.cyan("Distribution:")} ${n.distribution||"none"}`),he.info(`${Re.cyan("Development Client:")} ${n.developmentClient||"false"}`),n.env&&Object.keys(n.env).length>0&&(he.info(Re.dim(`
|
|
1107
|
+
Environment Variables:`)),Object.entries(n.env).forEach(([o,r])=>{he.info(` ${o}=${r}`)}))):he.warn(`Profile '${i}' not found.`),he.info(Re.dim("----------------------------------------"))};import{log as ve,spinner as Dt,text as Mn,select as Un,confirm as Ps,isCancel as Pt,cancel as $t,outro as Rt,note as $s}from"@clack/prompts";import z from"chalk";import{execSync as Ds}from"child_process";async function Rs(){try{let e=Ds("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 vs(e){let t=e.udid,i=e.name,n="";if(!t){let r=Dt();r.start("Scanning for connected iOS devices...");let a=await Rs();if(r.stop(a.length>0?`Found ${a.length} device(s)`:"No devices detected"),a.length===1)t=a[0].udid,i=i||a[0].name,n=a[0].model,ve.info(`Detected: ${z.bold(i)} (${z.dim(t.substring(0,12)+"...")})`);else if(a.length>1){let l=await Un({message:"Select a device to register:",options:a.map(c=>({value:c.udid,label:`${c.name} (${c.model})`,hint:c.udid.substring(0,12)+"..."}))});if(Pt(l)){$t("Cancelled");return}t=l;let s=a.find(c=>c.udid===t);i=i||s.name,n=s.model}else{ve.info(z.dim("No connected devices found. Enter UDID manually."));let l=await Mn({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(s){if(s.length<10)return"UDID seems too short"}});if(Pt(l)){$t("Cancelled");return}t=l}}if(!i){let r=await Mn({message:"Device name:",placeholder:"Nitesh's iPhone",validate(a){if(a.length===0)return"Name is required"}});if(Pt(r)){$t("Cancelled");return}i=r}let o=Dt();o.start("Registering device...");try{await v.post("/devices",{udid:t,name:i,platform:"ios",model:n||void 0,addedVia:"cli"}),o.stop(z.green("Device registered!")),ve.info(` ${z.bold("Name:")} ${i}`),ve.info(` ${z.bold("UDID:")} ${z.dim(t)}`)}catch(r){o.stop(z.red("Failed to register device")),ve.error(r.response?.data?.message||r.message)}Rt(z.blue("---"))}async function ws(){let e=Dt();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){ve.info(z.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),Rt(z.blue("---"));return}let n=i.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${z.bold(o.name.padEnd(24))} ${z.dim(o.udid.padEnd(28))} ${z.cyan(o.addedVia.padEnd(10))} ${z.dim(r)}`});$s(` ${z.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
1031
1108
|
`+n.join(`
|
|
1032
|
-
`),"Registered Devices")}catch(t){e.stop(
|
|
1033
|
-
`),c=
|
|
1034
|
-
`),d=
|
|
1035
|
-
`),d=
|
|
1036
|
-
`),d=
|
|
1037
|
-
`);/__DEV__/.test(
|
|
1038
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1039
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let c of o){let d=
|
|
1040
|
-
`)),
|
|
1041
|
-
`));for(let s of l)ee.error(Z.red(`${Z.bold(s.name)} ${Z.dim(`(${s.arch})`)}`)),ee.info(Z.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${Hn})`))}return a.length>0&&(console.log(""),ee.success(Z.green(`${a.length} librar${a.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),l.length===0?(ee.success(Z.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ee.error(Z.red.bold(`Found ${l.length} unaligned lib${l.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ee.info(Z.yellow("To fix this:")),ee.info(Z.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ee.info(Z.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ee.info(Z.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ee.info(Z.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ee.info(Z.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return i.stop("Analysis failed."),ee.error(Z.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{xe.rmSync(n,{recursive:!0,force:!0})}catch{}}}function ms(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(fs))return null;let n=i[4]===2,o=i[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),l=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),a=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,c,d;n?(s=a(i,32),c=r(i,54),d=r(i,56)):(s=l(i,28),c=r(i,42),d=r(i,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(c);if(xe.readSync(t,g,0,c,s+p*c),l(g,0)!==ps)continue;let P;n?P=a(g,48):P=l(g,28),P>0&&(u===null||P<u)&&(u=P)}return u??0}catch{return null}finally{xe.closeSync(t)}}function jn(e){let t=[];if(!xe.existsSync(e))return t;let i=xe.readdirSync(e,{withFileTypes:!0});for(let n of i){let o=Xe.join(e,n.name);n.isDirectory()?t.push(...jn(o)):n.name.endsWith(".so")&&t.push(o)}return t}function gs(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var zn=async e=>{if(fe()||(be.error(we.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await Ss(e);return}let i=process.cwd(),n=Mt.join(i,"package.json");Et.existsSync(n)||(be.error(we.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(Et.readFileSync(n,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(be.info(we.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),be.info(we.dim(`Type: ${r?"Expo":"Bare React Native"}`)),be.info(""));let l={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},a=await Un(i,l);e.json?console.log(JSON.stringify(Fn(a,o),null,2)):Mn(a,e.severity);let s=a.some(d=>d.findings.some(u=>u.severity==="critical")),c=a.some(d=>d.findings.some(u=>u.severity==="high"));(s||c)&&process.exit(1)},Gn=["16kb"];async function Ss(e){let t=e.category?.toLowerCase();t&&!Gn.includes(t)&&(be.error(we.red(`Unknown APK check category: "${t}"`)),be.info(we.dim(`Available APK checks: ${Gn.join(", ")}`)),process.exit(1));let i=await Es(e.apk);i||process.exit(1);let n=!t,o=!1;(n||t==="16kb")&&(await Bn(i)||(o=!0)),o&&process.exit(1)}async function Es(e){if(e.startsWith("build:")){let i=e.slice(6);return await As(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await Vn(e);let t=Mt.resolve(e);return Et.existsSync(t)?t:(be.error(we.red(`APK file not found: ${t}`)),null)}async function As(e){let t=Kn();t.start(`Fetching APK from build ${e}...`);try{let i=await $.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 o=n.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(t.stop("No APK artifact found"),be.error(we.red("This build does not have an APK artifact.")),be.info(we.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await Vn(o.url))}catch(i){return t.stop("Failed to fetch build"),be.error(we.red(i.message)),null}}async function Vn(e){let t=Kn();t.start("Downloading APK...");try{let i=Et.mkdtempSync(Mt.join(hs.tmpdir(),`${f.nameLower}-audit-`)),n=Mt.join(i,"app.apk"),o=await ys.get(e,{responseType:"arraybuffer"});Et.writeFileSync(n,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${r} MB)`),n}catch(i){return t.stop("Download failed"),be.error(we.red(`Failed to download APK: ${i.message}`)),null}}var _s=console.log;console.log=()=>{};Is();console.log=_s;ue(ae.bgCyan.black(f.cliTag("Production Build Orchestrator")));var $s=Ps(import.meta.url),Ds=$s("../package.json"),Y=new bs;Y.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(Ds.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);Y.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await zi()});Y.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ue(ae.bgCyan.black(f.cliTag("Hosting"))),await hi()});Y.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=>{ue(ae.bgCyan.black(f.cliTag("Sitemap Generator"))),await Ai(e)});Y.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 Wn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Wn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=Y.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||ue(ae.bgCyan.black(f.cliTag("Cloud Build"))),await Pt(t)});Y.command("maestro").description("Run managed Maestro tests for an existing Mach build or artifact").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("--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("--json-output <path>","Write test run metadata JSON to a file for CI/CD").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Maestro Testing"))),await Li(e)});Y.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=>{ue(ae.bgCyan.black(f.cliTag("OTA Update"))),await ln(e)});Y.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("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{ue(ae.bgCyan.black(f.cliTag("Store Submission"))),await rn(e)});Y.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Login"))),await Ji()});Y.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Link Project"))),await qi()});Y.command("me").description("Display currently logged in user details").action(async()=>{await dn()});Y.command("init").description(`Create a new ${f.name} Project`).action(async()=>{ue(ae.bgCyan.black(f.cliTag("Init Project"))),await Xi()});Y.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)=>{ue(ae.bgCyan.black(f.cliTag("Env Manager"))),await en(e,t)});Y.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=>{ue(ae.bgCyan.black(f.cliTag("Dev Server"))),await pn(e)});Y.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 fn(e)});Y.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-UTJERDGT.js");await t(e)});Y.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=>{ue(ae.bgCyan.black(f.cliTag("Credentials Setup"))),await et(e),Yn(ae.green("Done!"))});Y.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=>{ue(ae.bgCyan.black(f.cliTag("Service Credentials"))),await mi(e),Yn(ae.green("Done!"))});var ci=Y.command("device").description("Manage registered iOS test devices");ci.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 wt("register",e)});ci.command("list").description("List all registered devices").action(async()=>{await wt("list",{})});ci.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await wt("remove",e)});Y.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=>{ue(ae.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await zn(e)});var Rs=new Set(["login"]);Y.hook("preAction",(e,t)=>{let i=t.name();Rs.has(i)||ui()});Y.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1042
|
-
See --help for a list of available commands.`,
|
|
1109
|
+
`),"Registered Devices")}catch(t){e.stop(z.red("Failed to fetch devices")),ve.error(t.response?.data?.message||t.message)}Rt(z.blue("---"))}async function Os(e){let t=e.udid;if(!t){let o=Dt();o.start("Fetching registered devices...");try{let a=(await v.get("/devices")).data.devices||[];if(o.stop(`${a.length} device(s) found`),a.length===0){ve.info(z.dim("No devices to remove.")),Rt(z.blue("---"));return}let l=await Un({message:"Select device to remove:",options:a.map(s=>({value:s.udid,label:s.name,hint:s.udid.substring(0,12)+"..."}))});if(Pt(l)){$t("Cancelled");return}t=l}catch(r){o.stop(z.red("Failed to fetch devices")),ve.error(r.response?.data?.message||r.message);return}}let i=await Ps({message:`Remove device ${z.dim(t.substring(0,12)+"...")}?`});if(Pt(i)||!i){$t("Cancelled");return}let n=Dt();n.start("Removing device...");try{await v.delete(`/devices/${encodeURIComponent(t)}`),n.stop(z.green("Device removed"))}catch(o){n.stop(z.red("Failed to remove device")),ve.error(o.response?.data?.message||o.message)}Rt(z.blue("---"))}async function Gt(e,t){switch(e){case"register":await vs(t);break;case"list":await ws();break;case"remove":await Os(t);break;default:ve.error(`Unknown action: ${e}`)}}import{log as _e,spinner as mo}from"@clack/prompts";import Oe from"chalk";import Zt from"path";import Ot from"fs";import da from"os";import ua from"axios";var be=(r=>(r.CRITICAL="critical",r.HIGH="high",r.MEDIUM="medium",r.LOW="low",r.INFO="info",r))(be||{}),we=(s=>(s.PERMISSIONS="permissions",s.SECRETS="secrets",s.DEPENDENCIES="dependencies",s.STORAGE="storage",s.NETWORK="network",s.DEBUG="debug",s.MANIFEST="manifest",s.ATS="ats",s))(we||{});import{spinner as no,log as wt}from"@clack/prompts";import ye from"chalk";import{execSync as ea}from"child_process";import oo from"fs";import ro from"path";import Ve from"fs";import vt from"path";import{execSync as Cs}from"child_process";var Fn={"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"}},Ns={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 Ts(e){try{let i=Cs("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(i)}catch{}let t=vt.join(e,"app.json");if(Ve.existsSync(t))try{let i=JSON.parse(Ve.readFileSync(t,"utf-8"));return i.expo||i}catch{}return null}function ks(e){let t=[],i=vt.join(e,"node_modules");if(!Ve.existsSync(i))return t;let n=/<uses-permission\s+android:name="([^"]+)"/g;function o(r,a){let l=vt.join(r,"android","src","main","AndroidManifest.xml");if(!Ve.existsSync(l))return;let s=Ve.readFileSync(l,"utf-8"),c;for(;(c=n.exec(s))!==null;)t.push({pkg:a,permission:c[1]});n.lastIndex=0}for(let r of Ve.readdirSync(i)){if(r.startsWith("."))continue;let a=vt.join(i,r);if(r.startsWith("@")){if(!Ve.statSync(a).isDirectory())continue;for(let l of Ve.readdirSync(a))o(vt.join(a,l),`${r}/${l}`)}else o(a,r)}return t}async function Hn(e,t){let i=[],n=1,o=Ts(e),r=o?.android?.permissions||[],a=o?.android?.blockedPermissions||[];for(let c of r){let d=Fn[c];d&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=ks(e);for(let{pkg:c,permission:d}of l){let u=Fn[d];u&&(a.includes(d)||r.includes(d)||i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`${d.split(".").pop()} injected by ${c}`,description:`${u.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${d}" to blockedPermissions if not needed.`,autoFixable:!0}))}let s=o?.ios?.infoPlist||{};for(let[c,d]of Object.entries(Ns))c in s&&i.push({id:`PERM-${String(n++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:i,durationMs:0}}import Ii from"fs";import jt from"path";var xs=[{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"}],Ls=new Set([".ts",".tsx",".js",".jsx"]),Ms=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Bn(e){let t=[],i=Ii.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Ms.has(n.name))continue;let o=jt.join(e,n.name);n.isDirectory()?t.push(...Bn(o)):Ls.has(jt.extname(n.name))&&t.push(o)}return t}function Us(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function Fs(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Gn(e,t){let i=[],n=jt.join(e,"src"),o=Ii.existsSync(n)?n:e,r=Bn(o);for(let a of r){let s=Ii.readFileSync(a,"utf-8").split(`
|
|
1110
|
+
`),c=jt.relative(e,a);for(let d=0;d<s.length;d++){let u=s[d];if(!Us(u)&&!Fs(u))for(let{id:p,pattern:f,severity:y,label:D}of xs)f.lastIndex=0,f.test(u)&&i.push({id:p,title:D,description:`Potential ${D.toLowerCase()} found in source code`,severity:y,category:"secrets",file:c,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:i,durationMs:0}}import{execSync as Hs}from"child_process";var Bs={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function jn(e,t){let i=[],n=1,o;try{o=Hs("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(o=l.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let a=r.vulnerabilities||{};for(let[l,s]of Object.entries(a)){let c=Bs[s.severity]||"info",d=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);i.push({id:`DEP-${String(n++).padStart(3,"0")}`,title:`${l} \u2014 ${s.severity}`,description:`Via: ${d}. Range: ${s.range||"unknown"}`,severity:c,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:i,durationMs:0}}import Kt from"fs";import Vt from"path";var Gs=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,Kn=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,js=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Ks=new Set([".ts",".tsx",".js",".jsx"]),Vs=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function Vn(e){let t=[];if(!Kt.existsSync(e))return t;let i=Kt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Vs.has(n.name))continue;let o=Vt.join(e,n.name);n.isDirectory()?t.push(...Vn(o)):Ks.has(Vt.extname(n.name))&&t.push(o)}return t}async function zn(e,t){let i=[],n=1,o=Vt.join(e,"src"),r=Kt.existsSync(o)?o:e,a=Vn(r);for(let l of a){let s=Kt.readFileSync(l,"utf-8");if(!js.test(s))continue;let c=s.split(`
|
|
1111
|
+
`),d=Vt.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u];Kn.lastIndex=0;let f;for(;(f=Kn.exec(p))!==null;){let y=f[1];Gs.test(y)&&i.push({id:`STOR-${String(n++).padStart(3,"0")}`,title:`AsyncStorage used for "${y}"`,description:`Sensitive data key "${y}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:d,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 zt from"fs";import Wt from"path";var Wn=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,zs=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,Ws=new Set([".ts",".tsx",".js",".jsx"]),Ys=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Yn(e){let t=[];if(!zt.existsSync(e))return t;let i=zt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Ys.has(n.name))continue;let o=Wt.join(e,n.name);n.isDirectory()?t.push(...Yn(o)):Ws.has(Wt.extname(n.name))&&t.push(o)}return t}async function Jn(e,t){let i=[],n=1,o=Wt.join(e,"src"),r=zt.existsSync(o)?o:e,a=Yn(r);for(let l of a){let c=zt.readFileSync(l,"utf-8").split(`
|
|
1112
|
+
`),d=Wt.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u],f=p.trim();if(f.startsWith("//")||f.startsWith("*"))continue;Wn.lastIndex=0;let y;for(;(y=Wn.exec(p))!==null;){let D=y[1],$=zs.test(D);i.push({id:`NET-${String(n++).padStart(3,"0")}`,title:`Insecure HTTP URL${$?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${D}`,severity:$?"high":"medium",category:"network",file:d,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:i,durationMs:0}}import Yt from"fs";import Jt from"path";var Xn=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,qn=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Js=new Set([".ts",".tsx",".js",".jsx"]),Xs=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Zn(e){let t=[];if(!Yt.existsSync(e))return t;let i=Yt.readdirSync(e,{withFileTypes:!0});for(let n of i){if(Xs.has(n.name))continue;let o=Jt.join(e,n.name);n.isDirectory()?t.push(...Zn(o)):Js.has(Jt.extname(n.name))&&t.push(o)}return t}async function Qn(e,t){let i=[],n=1,o=Jt.join(e,"src"),r=Yt.existsSync(o)?o:e,a=Zn(r);for(let l of a){let c=Yt.readFileSync(l,"utf-8").split(`
|
|
1113
|
+
`),d=Jt.relative(e,l);for(let u=0;u<c.length;u++){let p=c[u],f=p.trim();if(!(f.startsWith("//")||f.startsWith("*"))&&(Xn.lastIndex=0,Xn.test(p)&&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:d,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),qn.lastIndex=0,qn.test(p))){let y=c.slice(Math.max(0,u-3),u).join(`
|
|
1114
|
+
`);/__DEV__/.test(y)||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:d,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 eo from"fs";import Pi from"path";var qs=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 Zs(e){let t=[Pi.join(e,"android","app","src","main","AndroidManifest.xml"),Pi.join(e,"android","AndroidManifest.xml")];for(let i of t)if(eo.existsSync(i))return i;return null}async function to(e,t){let i=[],n=1,o=Zs(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=eo.readFileSync(o,"utf-8"),a=Pi.relative(e,o),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=l.exec(r))!==null;){let c=s[1],d=s[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(qs.has(p))continue;let f=/android:exported="true"/.test(d),y=/android:permission="/.test(d);f&&!y&&i.push({id:`MAN-${String(n++).padStart(3,"0")}`,title:`Exported ${c}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:a,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&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:a,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&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:a,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 Xt from"fs";import $i from"path";function Qs(e){let t=$i.join(e,"ios");if(!Xt.existsSync(t))return null;let i=Xt.readdirSync(t,{withFileTypes:!0});for(let n of i){if(!n.isDirectory()||n.name==="Pods"||n.name.startsWith("."))continue;let o=$i.join(t,n.name,"Info.plist");if(Xt.existsSync(o))return o}return null}async function io(e,t){let i=[],n=1,o=Qs(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=Xt.readFileSync(o,"utf-8"),a=$i.relative(e,o),l=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let s=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&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:a,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let c=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let d=c[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&i.push({id:`ATS-${String(n++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:a,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:i,durationMs:0}}var ta=[{category:"permissions",label:"Permission Audit",fn:Hn,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Gn,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:jn,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:zn,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:Jn,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:Qn,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:to,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:io,requiresPrebuild:!0}];async function so(e,t){let i=ta;t.category&&(i=i.filter(a=>a.category===t.category),i.length===0&&(wt.error(ye.red(`Unknown category: ${t.category}`)),wt.info(ye.dim(`Available: ${Object.values(we).join(", ")}`)),process.exit(1)));let n=i.filter(a=>!a.requiresPrebuild),o=i.filter(a=>a.requiresPrebuild),r=[];for(let a of n){let l=no();l.start(ye.dim(`Running ${a.label}...`));try{let s=Date.now(),c=await a.fn(e,t);c.durationMs=Date.now()-s,r.push(c);let d=c.findings.length;l.stop(d>0?ye.yellow(`${a.label} \u2014 ${d} finding(s)`):ye.green(`${a.label} \u2014 clean`))}catch(s){l.stop(ye.red(`${a.label} \u2014 error`)),r.push({category:a.category,label:a.label,findings:[],durationMs:0,error:s.message})}}if(o.length>0){let a=ro.join(e,"android"),l=ro.join(e,"ios"),s=oo.existsSync(a)||oo.existsSync(l);if(!s&&t.prebuild){t.json||wt.info(ye.dim(`
|
|
1115
|
+
Running expo prebuild for deeper analysis...`));try{ea("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return wt.warn(ye.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),r}}else if(!s)return t.json||wt.info(ye.dim(`
|
|
1116
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let c of o){let d=no();d.start(ye.dim(`Running ${c.label}...`));try{let u=Date.now(),p=await c.fn(e,t);p.durationMs=Date.now()-u,r.push(p);let f=p.findings.length;d.stop(f>0?ye.yellow(`${c.label} \u2014 ${f} finding(s)`):ye.green(`${c.label} \u2014 clean`))}catch(u){d.stop(ye.red(`${c.label} \u2014 error`)),r.push({category:c.category,label:c.label,findings:[],durationMs:0,error:u.message})}}}return r}import oe from"chalk";import{log as ie}from"@clack/prompts";var lt={critical:oe.bgRed.white.bold,high:oe.red.bold,medium:oe.yellow.bold,low:oe.blue,info:oe.dim},qt={critical:0,high:1,medium:2,low:3,info:4};function ia(e,t){if(!t)return!0;let i=qt[t];return i===void 0?!0:qt[e]<=i}function ao(e,t){let i=0,n={critical:0,high:0,medium:0,low:0,info:0};for(let a of e){let l=a.findings.filter(c=>ia(c.severity,t));if(l.length===0&&!a.error)continue;if(ie.info(""),ie.info(oe.bold(` ${a.label}`)+oe.dim(` ${l.length} finding(s)`)),ie.info(oe.dim(" "+"\u2500".repeat(60))),a.error){ie.error(oe.red(` Error: ${a.error}`));continue}let s=[...l].sort((c,d)=>qt[c.severity]-qt[d.severity]);for(let c of s){let d=lt[c.severity](` ${c.severity.toUpperCase()} `);ie.info(` ${d} ${oe.bold(c.id)} ${c.title}`),ie.info(oe.dim(` ${c.description}`)),c.file&&ie.info(oe.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),ie.info(oe.cyan(` Fix: ${c.recommendation}`)),ie.info(""),n[c.severity]++,i++}}ie.info(""),ie.info(oe.bold(" Summary")),ie.info(oe.dim(" "+"\u2500".repeat(60))),ie.info(` Total: ${oe.bold(String(i))} finding(s)`),ie.info(` ${lt.critical(` ${n.critical} Critical `)} ${lt.high(` ${n.high} High `)} ${lt.medium(` ${n.medium} Medium `)} ${lt.low(` ${n.low} Low `)} ${lt.info(` ${n.info} Info `)}`);let o=n.critical>0,r=n.high>0;o||r?(ie.info(""),ie.error(oe.red.bold(` FAIL \u2014 ${n.critical} critical, ${n.high} high issue(s) found`))):i>0?(ie.info(""),ie.warn(oe.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(ie.info(""),ie.success(oe.green.bold(" PASS \u2014 no issues found")))}function lo(e,t){let i=e.flatMap(o=>o.findings),n={};for(let o of Object.values(be))n[o]=i.filter(r=>r.severity===o).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(o=>({category:o.category,label:o.label,findingCount:o.findings.length,durationMs:o.durationMs,error:o.error||null})),findings:i}}import{log as ne,spinner as na}from"@clack/prompts";import Z from"chalk";import Be from"fs";import oa from"os";import ct from"path";import{execSync as ra}from"child_process";var co=16384,sa=1,aa=Buffer.from([127,69,76,70]);async function uo(e){ne.info(Z.bold.underline("16KB Page Alignment Check")),console.log("");let t=ct.resolve(e);if(!Be.existsSync(t))return ne.error(Z.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return ne.error(Z.red("The provided file is not an APK file.")),!1;let i=na();i.start("Extracting and analyzing native libraries...");let n=Be.mkdtempSync(ct.join(oa.tmpdir(),"mach-16kb-"));try{try{ra(`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 o=po(ct.join(n,"lib"));if(o.length===0)return i.stop("Analysis complete."),ne.info(Z.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ne.info(Z.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let r=[];for(let s of o){let c=ct.relative(n,s),d=ca(c),u=ct.basename(s),p=la(s);p!==null&&r.push({name:u,filePath:c,arch:d,align:p,compatible:p>=co})}if(i.stop("Analysis complete."),r.length===0)return ne.info(Z.yellow("No valid ELF shared libraries found.")),!0;let a=r.filter(s=>!s.compatible),l=r.filter(s=>s.compatible);if(ne.info(Z.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
|
|
1117
|
+
`)),a.length>0){ne.info(Z.red.bold(`Incompatible libraries:
|
|
1118
|
+
`));for(let s of a)ne.error(Z.red(`${Z.bold(s.name)} ${Z.dim(`(${s.arch})`)}`)),ne.info(Z.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${co})`))}return l.length>0&&(console.log(""),ne.success(Z.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(ne.success(Z.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ne.error(Z.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ne.info(Z.yellow("To fix this:")),ne.info(Z.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ne.info(Z.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ne.info(Z.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ne.info(Z.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ne.info(Z.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return i.stop("Analysis failed."),ne.error(Z.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Be.rmSync(n,{recursive:!0,force:!0})}catch{}}}function la(e){let t=Be.openSync(e,"r");try{let i=Buffer.alloc(64);if(Be.readSync(t,i,0,64,0),!i.subarray(0,4).equals(aa))return null;let n=i[4]===2,o=i[5]===1,r=(p,f)=>o?p.readUInt16LE(f):p.readUInt16BE(f),a=(p,f)=>o?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(o?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),s,c,d;n?(s=l(i,32),c=r(i,54),d=r(i,56)):(s=a(i,28),c=r(i,42),d=r(i,44));let u=null;for(let p=0;p<d;p++){let f=Buffer.alloc(c);if(Be.readSync(t,f,0,c,s+p*c),a(f,0)!==sa)continue;let D;n?D=l(f,48):D=a(f,28),D>0&&(u===null||D<u)&&(u=D)}return u??0}catch{return null}finally{Be.closeSync(t)}}function po(e){let t=[];if(!Be.existsSync(e))return t;let i=Be.readdirSync(e,{withFileTypes:!0});for(let n of i){let o=ct.join(e,n.name);n.isDirectory()?t.push(...po(o)):n.name.endsWith(".so")&&t.push(o)}return t}function ca(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var go=async e=>{if(ge()||(_e.error(Oe.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await pa(e);return}let i=process.cwd(),n=Zt.join(i,"package.json");Ot.existsSync(n)||(_e.error(Oe.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(Ot.readFileSync(n,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(_e.info(Oe.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),_e.info(Oe.dim(`Type: ${r?"Expo":"Bare React Native"}`)),_e.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await so(i,a);e.json?console.log(JSON.stringify(lo(l,o),null,2)):ao(l,e.severity);let s=l.some(d=>d.findings.some(u=>u.severity==="critical")),c=l.some(d=>d.findings.some(u=>u.severity==="high"));(s||c)&&process.exit(1)},fo=["16kb"];async function pa(e){let t=e.category?.toLowerCase();t&&!fo.includes(t)&&(_e.error(Oe.red(`Unknown APK check category: "${t}"`)),_e.info(Oe.dim(`Available APK checks: ${fo.join(", ")}`)),process.exit(1));let i=await fa(e.apk);i||process.exit(1);let n=!t,o=!1;(n||t==="16kb")&&(await uo(i)||(o=!0)),o&&process.exit(1)}async function fa(e){if(e.startsWith("build:")){let i=e.slice(6);return await ma(i)}if(e.startsWith("http://")||e.startsWith("https://"))return await ho(e);let t=Zt.resolve(e);return Ot.existsSync(t)?t:(_e.error(Oe.red(`APK file not found: ${t}`)),null)}async function ma(e){let t=mo();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 o=n.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(t.stop("No APK artifact found"),_e.error(Oe.red("This build does not have an APK artifact.")),_e.info(Oe.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${n.buildId||e}`),await ho(o.url))}catch(i){return t.stop("Failed to fetch build"),_e.error(Oe.red(i.message)),null}}async function ho(e){let t=mo();t.start("Downloading APK...");try{let i=Ot.mkdtempSync(Zt.join(da.tmpdir(),`${m.nameLower}-audit-`)),n=Zt.join(i,"app.apk"),o=await ua.get(e,{responseType:"arraybuffer"});Ot.writeFileSync(n,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${r} MB)`),n}catch(i){return t.stop("Download failed"),_e.error(Oe.red(`Failed to download APK: ${i.message}`)),null}}var ya=console.log;console.log=()=>{};ha();console.log=ya;ue(se.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Ea=Sa(import.meta.url),Aa=Ea("../package.json"),V=new ga;V.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Aa.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);V.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await fn()});V.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{ue(se.bgCyan.black(m.cliTag("Hosting"))),await Ti()});V.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=>{ue(se.bgCyan.black(m.cliTag("Sitemap Generator"))),await Mi(e)});V.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 yo("--build-id <id>","Internal build ID").hideHelp()).addOption(new yo("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").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("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let i=V.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||ue(se.bgCyan.black(m.cliTag("Cloud Build"))),await Mt(t)});V.command("maestro").description("Run managed Maestro tests for an existing Mach build or artifact").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("--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("--json-output <path>","Write test run metadata JSON to a file for CI/CD").action(async e=>{ue(se.bgCyan.black(m.cliTag("Maestro Testing"))),await on(e)});V.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=>{ue(se.bgCyan.black(m.cliTag("OTA Update"))),await Cn(e)});V.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("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{ue(se.bgCyan.black(m.cliTag("Store Submission"))),await vn(e)});V.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{ue(se.bgCyan.black(m.cliTag("Login"))),await yn()});V.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{ue(se.bgCyan.black(m.cliTag("Link Project"))),await En()});V.command("me").description("Display currently logged in user details").action(async()=>{await Tn()});V.command("init").description(`Create a new ${m.name} Project`).action(async()=>{ue(se.bgCyan.black(m.cliTag("Init Project"))),await An()});V.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)=>{ue(se.bgCyan.black(m.cliTag("Env Manager"))),await In(e,t)});V.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=>{ue(se.bgCyan.black(m.cliTag("Dev Server"))),await xn(e)});V.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 Ln(e)});V.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-UTJERDGT.js");await t(e)});V.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=>{ue(se.bgCyan.black(m.cliTag("Credentials Setup"))),await pt(e),So(se.green("Done!"))});V.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=>{ue(se.bgCyan.black(m.cliTag("Service Credentials"))),await Ci(e),So(se.green("Done!"))});var Di=V.command("device").description("Manage registered iOS test devices");Di.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 Gt("register",e)});Di.command("list").description("List all registered devices").action(async()=>{await Gt("list",{})});Di.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await Gt("remove",e)});V.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=>{ue(se.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await go(e)});var ba=new Set(["login"]);V.hook("preAction",(e,t)=>{let i=t.name();ba.has(i)||vi()});V.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1119
|
+
See --help for a list of available commands.`,V.args.join(" ")),process.exit(1)});process.argv.slice(2).length||V.help();V.parse(process.argv);
|