@radhya/mach 2.0.8 → 2.0.10
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 +32 -3
- package/dist/chunk-YMJWGZX6.js +61 -0
- package/dist/{credentials-KDH6HGWP.js → credentials-3MYGMYJK.js} +1 -1
- package/dist/index.js +185 -153
- package/package.json +1 -1
- package/dist/chunk-UZNUPNFP.js +0 -61
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
2
|
+
import{a as ln,b as ir,c as rr,d as or,e as $e,f as nt,g as sr,h as ar,i as At,j as lr,l as Tt}from"./chunk-YMJWGZX6.js";import{a as m,b as er,c as Pe,d as tr,e as nr,f as bt,g as We,h as N}from"./chunk-HIP5BA3H.js";import{Command as Cf,Option as xe}from"commander";import{configDotenv as Nf}from"dotenv";import{intro as we,outro as sa}from"@clack/prompts";import be from"chalk";import{text as dr,confirm as la,spinner as da,isCancel as qn,cancel as kt,note as ca,outro as ua}from"@clack/prompts";import xt from"chalk";async function cr(){try{let e=await dr({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(r){if(r.length===0)return"Bucket name is required"}});qn(e)&&(kt("Operation cancelled."),process.exit(0));let t=await dr({message:"Enter Region:",initialValue:"ap-south-1"});qn(t)&&(kt("Operation cancelled."),process.exit(0));let n=await la({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});qn(n)&&(kt("Operation cancelled."),process.exit(0));let i=da();i.start("Setting up hosting infrastructure...");try{let r=await N.post("/hosting/setup",{bucketName:e,region:t,createCloudFront:n});if(r.data.status!=="success")throw new Error(r.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let o=r.data,s=`Bucket Name: ${xt.cyan(o.bucketName)}
|
|
3
3
|
`;s+=`Region: ${xt.cyan(o.region)}
|
|
4
4
|
`,s+=`S3 Website URL: ${xt.blue(o.s3WebsiteUrl)}`,o.cloudFrontId&&(s+=`
|
|
5
5
|
|
|
6
6
|
CloudFront ID: ${xt.cyan(o.cloudFrontId)}`,s+=`
|
|
7
|
-
CloudFront URL: ${xt.blue(o.cloudFrontUrl)}`),
|
|
7
|
+
CloudFront URL: ${xt.blue(o.cloudFrontUrl)}`),ca(s,"Setup Complete!"),ua("You are all set!")}catch(r){i.stop("Setup failed"),kt(`Error: ${r.response?.data?.message||r.message}`)}}catch(e){kt(`An unexpected error occurred: ${e.message}`)}}import{readdir as fa,writeFile as pa,access as ma,mkdir as ga}from"fs/promises";import{join as ur}from"path";import{spinner as ha,text as fr,isCancel as pr,cancel as Xn,note as ya,outro as Sa}from"@clack/prompts";import ba from"chalk";async function Aa(){let e=["./app","./src/app"];for(let t of e)try{return await ma(t),t}catch{}return null}async function mr(e){try{let n=await Aa()||"./app",i=await fr({message:"Enter path to your app directory:",placeholder:n,initialValue:n,validate(u){if(u.length===0)return"Path is required"}});pr(i)&&(Xn("Operation cancelled."),process.exit(0));let r=await fr({message:"Enter your website base URL:",placeholder:"https://example.com",validate(u){if(u.length===0)return"Base URL is required";if(!u.startsWith("http"))return"URL must start with http:// or https://"}});pr(r)&&(Xn("Operation cancelled."),process.exit(0));let o=ha();o.start("Scanning app directory for routes...");let s=await gr(i);o.stop(`Found ${s.length} routes`);let l=Ea(s,r),a=e.output||"./public/sitemap.xml";o.start(`Writing sitemap to ${a}...`);let c=a.substring(0,a.lastIndexOf("/"));if(c)try{await ga(c,{recursive:!0})}catch{}await pa(a,l,"utf-8"),o.stop("Sitemap generated successfully!"),ya(`Routes included:
|
|
8
8
|
${s.map(u=>` \u2022 ${u.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
9
|
+
`)}`,"Sitemap Summary"),Sa(`Sitemap saved to ${ba.cyan(a)}`)}catch(t){Xn(`An error occurred: ${t.message}`)}}async function gr(e,t=""){let n=[];try{let i=await fa(e,{withFileTypes:!0});for(let r of i){let o=ur(e,r.name);if(!(r.name.startsWith("_")||r.name.startsWith("."))){if(r.isDirectory()){let s=await gr(o,ur(t,r.name));n.push(...s)}else if(r.isFile()){if(r.name==="index.tsx"||r.name==="index.ts"||r.name==="index.jsx"||r.name==="index.js"){let s=t===""?"/":`/${t}`;n.push({path:s,file:o})}else if(r.name.match(/\.(tsx|ts|jsx|js)$/)&&!r.name.includes("_layout")&&!r.name.includes("+")){let s=r.name.replace(/\.(tsx|ts|jsx|js)$/,""),l=`/${t}/${s}`.replace(/\/+/g,"/");n.push({path:l,file:o})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return n}function Ea(e,t){let n=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
10
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
11
11
|
${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[.*?\]/g,"/:id"),o=o.replace(/\/+/g,"/"),o===""&&(o="/"),` <url>
|
|
12
12
|
<loc>${t}${o}</loc>
|
|
@@ -15,7 +15,7 @@ ${e.map(r=>{let o=r.path;return o=o.replace(/\/\([^)]+\)/g,""),o=o.replace(/\/\[
|
|
|
15
15
|
<priority>0.8</priority>
|
|
16
16
|
</url>`}).join(`
|
|
17
17
|
`)}
|
|
18
|
-
</urlset>`}import{randomUUID as
|
|
18
|
+
</urlset>`}import{randomUUID as Qd}from"crypto";import ve from"path";import En from"axios";import ec from"os";import{spinner as Ci,select as bo,confirm as Ao,isCancel as In,cancel as Eo,log as v}from"@clack/prompts";import R from"chalk";import de from"fs";import{execSync as Io}from"child_process";import wo from"adm-zip";import{spinner as Ra,log as dn}from"@clack/prompts";import yr from"chalk";import Sr from"fs";import br from"path";var hr=`#!/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}}"
|
|
@@ -28,8 +28,12 @@ echo "Starting build setup..."
|
|
|
28
28
|
|
|
29
29
|
# Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
30
30
|
{{ENV_VARS}}
|
|
31
|
-
export
|
|
32
|
-
echo "[ENV]
|
|
31
|
+
export MACH_FRAMEWORK="\${MACH_FRAMEWORK:-react-native}"
|
|
32
|
+
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
33
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
34
|
+
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
35
|
+
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
36
|
+
fi
|
|
33
37
|
export HUSKY=0
|
|
34
38
|
export CI=true
|
|
35
39
|
export npm_config_engine_strict=false
|
|
@@ -76,6 +80,7 @@ command -v pigz >/dev/null 2>&1 || TAR_COMPRESS="-z"
|
|
|
76
80
|
|
|
77
81
|
# --- Project Setup ---
|
|
78
82
|
export HOME=/root
|
|
83
|
+
export MACH_INSTANCE_ID="$(curl -fsS --max-time 2 http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null || true)"
|
|
79
84
|
|
|
80
85
|
function step_marker() {
|
|
81
86
|
local MARKER="[STEP_START:$1] $(date +%s)"
|
|
@@ -93,8 +98,12 @@ function upload_logs() {
|
|
|
93
98
|
function report_status() {
|
|
94
99
|
local STATUS=$1
|
|
95
100
|
local ERROR_MSG=$2
|
|
101
|
+
if [ -f /tmp/mach-spot-interrupted ] && [ "$STATUS" != "interrupted" ]; then
|
|
102
|
+
echo "[SPOT] Skipping status '$STATUS' because spot recovery is already in progress."
|
|
103
|
+
return 0
|
|
104
|
+
fi
|
|
96
105
|
if [ ! -z "$MACH_API_URL" ] && [ ! -z "$MACH_PROJECT_ID" ] && [ ! -z "$MACH_BUILD_ID" ]; then
|
|
97
|
-
PAYLOAD=$(STATUS="$STATUS" ERROR_MSG="$ERROR_MSG" python3 -c 'import json, os; payload = {"status": os.environ.get("STATUS", "")}; error = os.environ.get("ERROR_MSG", ""); payload.update({"error": error} if error else {}); print(json.dumps(payload))')
|
|
106
|
+
PAYLOAD=$(STATUS="$STATUS" ERROR_MSG="$ERROR_MSG" MACH_INSTANCE_ID="$MACH_INSTANCE_ID" python3 -c 'import json, os; payload = {"status": os.environ.get("STATUS", "")}; instance_id = os.environ.get("MACH_INSTANCE_ID", ""); error = os.environ.get("ERROR_MSG", ""); payload.update({"instanceId": instance_id} if instance_id else {}); payload.update({"error": error} if error else {}); print(json.dumps(payload))')
|
|
98
107
|
HTTP_CODE=$(curl -sS -o /tmp/mach-worker-status-response.txt -w "%{http_code}" -X POST "$MACH_API_URL/builds/$MACH_PROJECT_ID/$MACH_BUILD_ID/worker-status" -H "Content-Type: application/json" --data-binary "$PAYLOAD" || echo "000")
|
|
99
108
|
case "$HTTP_CODE" in
|
|
100
109
|
2*) ;;
|
|
@@ -107,6 +116,17 @@ function report_status() {
|
|
|
107
116
|
fi
|
|
108
117
|
}
|
|
109
118
|
|
|
119
|
+
function mark_done() {
|
|
120
|
+
if [ -f /tmp/mach-spot-interrupted ]; then
|
|
121
|
+
echo "[SPOT] Skipping done marker because recovery is in progress."
|
|
122
|
+
return 0
|
|
123
|
+
fi
|
|
124
|
+
touch done
|
|
125
|
+
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
126
|
+
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
127
|
+
fi
|
|
128
|
+
}
|
|
129
|
+
|
|
110
130
|
# Start log uploader (every 5 seconds)
|
|
111
131
|
(
|
|
112
132
|
while true; do
|
|
@@ -124,10 +144,9 @@ UPLOADER_PID=$!
|
|
|
124
144
|
NOTICE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 2 "http://169.254.169.254/latest/meta-data/spot/termination-time" 2>/dev/null)
|
|
125
145
|
if [ "$NOTICE" = "200" ]; then
|
|
126
146
|
echo "[SPOT] Interruption notice received \u2014 flushing logs and notifying API..."
|
|
147
|
+
touch /tmp/mach-spot-interrupted
|
|
127
148
|
upload_logs
|
|
128
149
|
report_status "interrupted" "Spot instance interrupted by AWS \u2014 build will be retried automatically"
|
|
129
|
-
touch done
|
|
130
|
-
[ ! -z "$PRESIGNED_DONE_MARKER" ] && curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
131
150
|
sudo shutdown -h now
|
|
132
151
|
exit 0
|
|
133
152
|
fi
|
|
@@ -245,8 +264,7 @@ if [ ! -z "$PRESIGNED_PREBUILD_SCRIPT" ]; then
|
|
|
245
264
|
echo "[ERROR] preBuild hook failed with exit code $HOOK_EXIT"
|
|
246
265
|
upload_logs
|
|
247
266
|
report_status "failed" "preBuild hook failed with exit code $HOOK_EXIT"
|
|
248
|
-
|
|
249
|
-
[ ! -z "$PRESIGNED_DONE_MARKER" ] && curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
267
|
+
mark_done
|
|
250
268
|
sleep 5
|
|
251
269
|
sudo shutdown -h now
|
|
252
270
|
exit $HOOK_EXIT
|
|
@@ -266,14 +284,16 @@ clear_js_transform_caches
|
|
|
266
284
|
# Apply before Expo prebuild so generated Gradle files receive the new versionCode.
|
|
267
285
|
if [ ! -z "$ANDROID_VERSION_CODE" ]; then
|
|
268
286
|
echo "[VERSIONING] Applying injected versionCode: $ANDROID_VERSION_CODE"
|
|
269
|
-
|
|
287
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
288
|
+
node -e "const fs=require('fs');const p='app.json';if(fs.existsSync(p)){const j=JSON.parse(fs.readFileSync(p,'utf8'));j.expo=j.expo||{};j.expo.android=j.expo.android||{};j.expo.android.versionCode=Number(process.env.ANDROID_VERSION_CODE);fs.writeFileSync(p,JSON.stringify(j,null,2));console.log('[VERSIONING] app.json expo.android.versionCode updated');}"
|
|
289
|
+
fi
|
|
270
290
|
fi
|
|
271
291
|
|
|
272
|
-
# --- Prebuild (
|
|
292
|
+
# --- Prebuild (Expo only) ---
|
|
273
293
|
# Compute a hash of native-affecting files and the Mach-injected app env to
|
|
274
294
|
# decide if android/ cache is still valid. Env names are project-defined, so the
|
|
275
295
|
# CLI precomputes MACH_ENV_FINGERPRINT from all relevant managed values.
|
|
276
|
-
if
|
|
296
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
277
297
|
if [ -f "app.json" ] || [ -f "app.config.ts" ] || [ -f "app.config.js" ]; then
|
|
278
298
|
PREBUILD_HASH_FILE="/home/ubuntu/build/.mach-prebuild-hash"
|
|
279
299
|
PREBUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
@@ -304,6 +324,8 @@ if grep -q '"expo"' package.json 2>/dev/null; then
|
|
|
304
324
|
echo "$PREBUILD_CURRENT_HASH" > "$PREBUILD_HASH_FILE"
|
|
305
325
|
fi
|
|
306
326
|
fi
|
|
327
|
+
else
|
|
328
|
+
echo "[PREBUILD] Skipping Expo prebuild for framework: $MACH_FRAMEWORK"
|
|
307
329
|
fi
|
|
308
330
|
|
|
309
331
|
# Build
|
|
@@ -346,7 +368,9 @@ echo "org.gradle.workers.max=8" >> gradle.properties
|
|
|
346
368
|
echo "org.gradle.configureondemand=true" >> gradle.properties
|
|
347
369
|
# Use Gradle build cache (works with the restored ~/.gradle cache)
|
|
348
370
|
echo "org.gradle.caching=true" >> gradle.properties
|
|
349
|
-
|
|
371
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
372
|
+
echo "expo.enableHermes=true" >> gradle.properties
|
|
373
|
+
fi
|
|
350
374
|
# Disable Sentry Gradle plugin upload \u2014 runs after Gradle via sentry-cli instead (avoids hangs).
|
|
351
375
|
# These env vars are read directly by @sentry/react-native's sentry.gradle.
|
|
352
376
|
export SENTRY_DISABLE_AUTO_UPLOAD=true
|
|
@@ -366,8 +390,9 @@ if printf "%s" "{{BUILD_COMMAND}}" | grep -iq "release"; then
|
|
|
366
390
|
echo "[OPTIMIZATION] Release build uses ARM device ABI(s): $ANDROID_RELEASE_ABIS"
|
|
367
391
|
fi
|
|
368
392
|
|
|
369
|
-
|
|
370
|
-
|
|
393
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
394
|
+
echo "expo.enableProguardInReleaseBuilds=true" >> gradle.properties
|
|
395
|
+
fi
|
|
371
396
|
fi
|
|
372
397
|
# --- EAS-style Android Signing (via Gradle injection) ---
|
|
373
398
|
SIGNING_FLAGS=()
|
|
@@ -479,11 +504,7 @@ else
|
|
|
479
504
|
echo "\\n[SYSTEM] Gradle build failed with exit code $BUILD_EXIT_CODE. Skipping artifact upload."
|
|
480
505
|
upload_logs
|
|
481
506
|
report_status "failed" "Gradle build failed with exit code $BUILD_EXIT_CODE"
|
|
482
|
-
|
|
483
|
-
touch done
|
|
484
|
-
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
485
|
-
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
486
|
-
fi
|
|
507
|
+
mark_done
|
|
487
508
|
sleep 5
|
|
488
509
|
sudo shutdown -h now
|
|
489
510
|
exit $BUILD_EXIT_CODE
|
|
@@ -518,10 +539,7 @@ fi
|
|
|
518
539
|
# Report success immediately \u2014 don't make the user wait for cache uploads
|
|
519
540
|
upload_logs
|
|
520
541
|
report_status "success"
|
|
521
|
-
|
|
522
|
-
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
523
|
-
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
524
|
-
fi
|
|
542
|
+
mark_done
|
|
525
543
|
touch /opt/mach-prewarmed
|
|
526
544
|
|
|
527
545
|
# Wait for background cache saves to finish before shutdown
|
|
@@ -530,15 +548,16 @@ for pid in "\${cache_pids[@]}"; do wait "$pid" || true; done
|
|
|
530
548
|
echo "Build orchestrator finished. Auto-terminating instance in 5 seconds..."
|
|
531
549
|
sleep 5
|
|
532
550
|
sudo shutdown -h now
|
|
533
|
-
`;import
|
|
534
|
-
`):"",f;if(r){let
|
|
535
|
-
export MACH_APP_NAME="${
|
|
536
|
-
export MACH_BUILD_PROFILE="${
|
|
537
|
-
export MACH_ANDROID_RELEASE_ABIS="${
|
|
538
|
-
export MACH_ENV_FINGERPRINT="${
|
|
539
|
-
export
|
|
551
|
+
`;import Ia from"crypto";var wa="mach-env-v2-js-bundle-cache",_a=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"]),$a=["PRESIGNED_","KEYSTORE_PASSWORD_"],va=e=>!e||_a.has(e)?!1:!$a.some(t=>e.startsWith(t)),ft=(e,t,n)=>{let i=n.framework||"react-native";return{...e,...i==="expo"?{EXPO_NO_DOTENV:"1"}:{},MACH_FRAMEWORK:i,MACH_BUILD_PROFILE:t,MACH_APP_NAME:n.appName||n.name||"App"}},Et=e=>{let t=Object.entries(e).filter(([n])=>va(n)).sort(([n],[i])=>n.localeCompare(i));return Ia.createHash("sha256").update(JSON.stringify({version:wa,entries:t})).digest("hex")};var cn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Zn=e=>["1","true","yes","on"].includes(String(e||"").trim().toLowerCase()),Pa=e=>/(^|[-_])(maestro|e2e|test|emulator)([-_]|$)/i.test(e),Oa=(e,t,n)=>{let i=n.MACH_ANDROID_RELEASE_ABIS||n.MACH_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_RELEASE_ABIS||n.MACH_PROFILE_ANDROID_ABIS||n.MACH_PROFILE_ANDROID_ARCHITECTURES||n.MACH_PROFILE_ANDROID_REACT_NATIVE_ARCHITECTURES;return i||(!!e.maestro||Pa(t)||Zn(n.MACH_PROFILE_ANDROID_EMULATOR)||Zn(n.MACH_ANDROID_INCLUDE_EMULATOR_ABIS)||Zn(n.MACH_PROFILE_ANDROID_INCLUDE_EMULATOR_ABIS)?"armeabi-v7a,arm64-v8a,x86_64":"armeabi-v7a,arm64-v8a")},Ar=async(e,t,n={},i,r)=>{let o=Ra(),s=e.framework||"react-native";if(s==="flutter")throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.');let l=e.buildProfile||"production",a=l==="production",c=e.apk===!0,u=e.developmentClient?"assembleDebug":a?"bundleRelease":"assembleRelease",d=e.buildCommand||(c?"assembleRelease":u),p=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(`
|
|
552
|
+
`):"",f;if(r){let b=br.isAbsolute(r)?r:br.resolve(process.cwd(),r);Sr.existsSync(b)?(f=Sr.readFileSync(b,"utf-8"),dn.info(yr.magenta(`\u2713 Loaded preBuild hook: ${r}`))):dn.warn(`preBuild script not found at ${b} \u2014 skipping`)}let h=Oa(e,l,n),S={...ft(n,l,e),MACH_ANDROID_RELEASE_ABIS:h},L=Et(S),x=hr.replace(/\{\{BUILD_ID\}\}/g,t).replace(/\{\{BUILD_COMMAND\}\}/g,d).replace("{{NODE_VERSION_SETUP}}",p).replace("{{ENV_VARS}}",`
|
|
553
|
+
export MACH_APP_NAME="${cn(S.MACH_APP_NAME)}"
|
|
554
|
+
export MACH_BUILD_PROFILE="${cn(l)}"
|
|
555
|
+
export MACH_ANDROID_RELEASE_ABIS="${cn(h)}"
|
|
556
|
+
export MACH_ENV_FINGERPRINT="${L}"
|
|
557
|
+
export MACH_FRAMEWORK="${cn(s)}"
|
|
558
|
+
${s==="expo"?"export EXPO_NO_DOTENV=1":""}
|
|
540
559
|
{{ENV_VARS}}
|
|
541
|
-
`);if(e.dryRun){
|
|
560
|
+
`);if(e.dryRun){dn.info("User Data Script (dry run):"),console.log(x);return}o.start("Requesting cloud build instance...");try{let b=await N.post("/builds/launch-android",{projectId:i,buildId:t,platform:e.platform,buildProfile:e.buildProfile,buildCommand:d,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:n,dryRun:e.dryRun,userDataScript:x,preBuildScriptContent:f});if(b.data.status!=="success")throw new Error(b.data.message||"Failed to launch build instance");let U=b.data.instanceId;return o.stop("Build Started"),dn.success(yr.green(`Build initiated on cloud instance (${U}).`)),{instanceId:U}}catch(b){o.stop("Android Build Failed");let U=b.response?.data?.message||b.message;throw new Error(`Failed to launch Android build: ${U}`)}};import{spinner as Da,log as It}from"@clack/prompts";import it from"chalk";import Ca from"fs";import{execSync as Mt}from"child_process";var Er=`#!/bin/bash
|
|
542
561
|
# --- Mach Cloud Build Script (iOS) ---
|
|
543
562
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
544
563
|
|
|
@@ -565,8 +584,12 @@ set -e
|
|
|
565
584
|
|
|
566
585
|
# 4. Forward environment variables (includes PRESIGNED_* URLs + project secrets)
|
|
567
586
|
{{ENV_VARS}}
|
|
568
|
-
export
|
|
569
|
-
echo "[ENV]
|
|
587
|
+
export MACH_FRAMEWORK="\${MACH_FRAMEWORK:-react-native}"
|
|
588
|
+
echo "[ENV] MACH_FRAMEWORK=$MACH_FRAMEWORK"
|
|
589
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
590
|
+
export EXPO_NO_DOTENV="\${EXPO_NO_DOTENV:-1}"
|
|
591
|
+
echo "[ENV] EXPO_NO_DOTENV=$EXPO_NO_DOTENV"
|
|
592
|
+
fi
|
|
570
593
|
|
|
571
594
|
BUILD_ID="{{BUILD_ID}}"
|
|
572
595
|
BUILD_ENV_HASH="\${MACH_ENV_FINGERPRINT:-missing-env-fingerprint}"
|
|
@@ -691,12 +714,14 @@ if [ ! -z "$PRESIGNED_CACHE_NODE_UPLOAD" ]; then
|
|
|
691
714
|
rm node_modules.tar.gz
|
|
692
715
|
fi
|
|
693
716
|
|
|
694
|
-
#
|
|
717
|
+
# Expo prebuild is explicit from mach.config.json.
|
|
695
718
|
echo "[STEP_START:prebuild] $(date +%s)"
|
|
696
|
-
if
|
|
697
|
-
echo "Expo
|
|
719
|
+
if [ "$MACH_FRAMEWORK" = "expo" ]; then
|
|
720
|
+
echo "Expo framework configured. Running prebuild..."
|
|
698
721
|
# Use --no-install so we can patch the Podfile before pod install
|
|
699
722
|
CI=1 npx expo prebuild --platform ios --clean --no-install
|
|
723
|
+
else
|
|
724
|
+
echo "Skipping Expo prebuild for framework: $MACH_FRAMEWORK"
|
|
700
725
|
fi
|
|
701
726
|
|
|
702
727
|
# 5. Apply simulator fix to Podfile dynamically (keeps project source clean)
|
|
@@ -1129,41 +1154,41 @@ touch done
|
|
|
1129
1154
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
1130
1155
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
1131
1156
|
fi
|
|
1132
|
-
`;var
|
|
1133
|
-
`:
|
|
1134
|
-
`);r.message("Generating macOS build script...");let
|
|
1135
|
-
`:"";if(n)for(let[
|
|
1136
|
-
`}let
|
|
1137
|
-
`),
|
|
1138
|
-
`):"",
|
|
1139
|
-
${it.yellow(
|
|
1140
|
-
${it.cyan(
|
|
1141
|
-
${it.dim("Note: Links are valid for 7 days.")}`)}else x&&It.warn("Simulator build completed. No artifacts uploaded.")}catch(A){r.stop("Could not fetch artifacts"),It.warn(it.yellow(`Artifact listing failed: ${A.message}`))}}}catch(u){throw r.stop("iOS Build Failed"),u}};import $a from"crypto";import Me from"axios";import Er from"fs";var Ye=6e4,va=12e4,Zn=4,Xe=e=>encodeURIComponent(e),Ra=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=Zn;i++)try{return await t()}catch(r){if(n=r,i>=Zn||!Pa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${Zn}); retrying in ${Math.round(s/1e3)}s...`),await Ra(s)}throw n}function Pa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Ar(e,t){let n;try{let i=await dn(t),r=Xe(e);if(n=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Xe(n),l=0,c=(await Ue("list tracks",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let f of d.versionCodes){let p=parseInt(f,10);p>l&&(l=p)}}try{let d=(await Ue("list bundles",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.bundles||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}try{let d=(await Ue("list APKs",()=>Me.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.apks||[];for(let f of d)f.versionCode&&f.versionCode>l&&(l=f.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await dn(t);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(e)}/edits/${Xe(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))}catch{}}}async function Ir(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await dn(n)}`,Connection:"close"},d=Xe(t);if(a=(await Ue("create edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Ye}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let p=Xe(a),h=Er.statSync(i),D=await Ue("upload AAB",()=>Me.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${p}/bundles`,Er.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:va})),N=Number(D.data.versionCode);if(!N)throw new Error("Google Play upload succeeded but did not return a versionCode.");let U={versionCodes:[String(N)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(U.userFraction=s),await Ue("update track",()=>Me.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}/tracks/${Xe(r)}`,{releases:[U]},{headers:u,timeout:Ye})),await Ue("commit edit",()=>Me.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${p}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ye})),{editId:a,versionCode:N,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await dn(n);await Ue("delete edit",()=>Me.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(t)}/edits/${Xe(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Ye}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function dn(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=$a.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await Ue("OAuth token exchange",()=>Me.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Ye}))).data.access_token}import Da from"crypto";import wr from"axios";var ei="https://api.appstoreconnect.apple.com/v1",_r=6e4,Qn=4,Oa=e=>new Promise(t=>setTimeout(t,e));function Ca(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=Da.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Na(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function $r(e,t){let n;for(let i=1;i<=Qn;i++)try{return await t()}catch(r){if(n=r,i>=Qn||!Na(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${Qn}); retrying in ${Math.round(s/1e3)}s...`),await Oa(s)}throw n}function vr(e){return{Authorization:`Bearer ${Ca(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function Ta(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function cn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function ka(e,t){let n=cn(e),i=cn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function xa(e){let t=cn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function La(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await $r("lookup app by bundle ID",()=>wr.get(`${ei}/apps`,{headers:vr(e),params:{"filter[bundleId]":n,limit:1},timeout:_r}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function Rr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await La(t,e.ascAppId,e.bundleId),i=`${ei}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await $r("list builds",()=>wr.get(i,{headers:vr(t),params:i===`${ei}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:_r})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();cn(u)&&ka(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:xa(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${Ta(n)}`)}}import{spinner as un,log as I,isCancel as fn,confirm as Ma,select as ni}from"@clack/prompts";import E from"chalk";import y from"fs";import _ from"path";import{execFileSync as Mt,execSync as ee,spawn as Cr}from"child_process";import Ae from"os";import Ua from"crypto";var Nr=(e,t)=>t.filter(n=>y.existsSync(_.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(_.join(e,i))),Ua.createHash("sha256")).digest("hex").slice(0,16),Ba=e=>Nr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Fa=e=>Nr(e,["Podfile","Podfile.lock"]),Ha=e=>{let t=_.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},Pr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},ja=7200*1e3,Ga=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=_.join(e,"build.lock");if(y.existsSync(n))try{let i=JSON.parse(y.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<ja)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}y.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Ka=(e,t)=>{let n=_.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Dr=15e5,Or=(e,t)=>{let n=e+t;return n.length>Dr?n.slice(-Dr):n},Tr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),kr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),Va=e=>{let t=new Set,n=[];e.forEach((r,o)=>{kr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},za=(e,t,n,i)=>{let r=Tr(i).replace(/\r/g,`
|
|
1157
|
+
`;var Qn=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),Ir=async(e,t,n={},i)=>{let r=Da(),o=e.framework||"react-native";if(o==="flutter")throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.');e.sshHost||(e.sshHost="localhost",It.message(it.yellow("No SSH host provided, defaulting to localhost."))),r.start(`Connecting to remote Mac at ${it.cyan(e.sshHost)}...`);let s=e.sshUser||process.env.USER||"ubuntu",l=e.sshKey,a=`${s}@${e.sshHost}`,c=`ssh ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no ${a}`,u=`scp ${l?`-i ${l}`:""} -o StrictHostKeyChecking=no`;try{let d=s==="ubuntu"?"/home/ubuntu":`/Users/${s}`,p=(n.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),f=`${d}/${m.remoteWorkspacesDir}/${p}`;r.message(`Preparing stable workspace: ${f}...`),Mt(`${c} "mkdir -p ${f}"`,{stdio:"inherit"}),r.message("Transferring source code...");let h=`/tmp/${m.nameLower}-source-${t}.zip`;Mt(`${u} ${h} ${a}:${f}/source.zip`,{stdio:"inherit"});let S=e.iosApiKeyPath?`${f}/api_key.p8`:"",L="";e.iosApiKeyPath&&(r.message("Uploading App Store Connect API key..."),Mt(`${u} ${e.iosApiKeyPath} ${a}:${S}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(L=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${S}`));let x={};if(i)try{let g=await N.post(`/builds/${i}/${t}/build-urls`,{platform:"ios"});g.data.status==="success"&&(x=g.data.urls)}catch(g){It.warn(it.yellow(`Could not fetch build URLs: ${g.message}`))}let b="";if(x.credentials&&x.credentials.length>0)for(let g of x.credentials)g.type==="p12"?b+=`curl -sf -o "$CERT_DIR/${g.name}" "${g.downloadUrl}" || true
|
|
1158
|
+
`:g.type==="mobileprovision"&&(b+=`curl -sf -o "$PROV_TEMP/${g.name}" "${g.downloadUrl}" || true
|
|
1159
|
+
`);r.message("Generating macOS build script...");let U=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
1160
|
+
`:"";if(n)for(let[g,k]of Object.entries(n)){let F=k.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");U+=`export ${g}="${F}"
|
|
1161
|
+
`}let w=e.buildProfile||"production",z=ft(n,w,e),Q=Et(z),O=[U,x.logUpload?`export PRESIGNED_LOG_UPLOAD="${x.logUpload}"`:"",x.doneMarker?`export PRESIGNED_DONE_MARKER="${x.doneMarker}"`:"",x.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${x.cacheDerivedDataDownload}"`:"",x.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${x.cacheDerivedDataUpload}"`:"",x.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${x.cacheNodeModulesDownload}"`:"",x.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${x.cacheNodeModulesUpload}"`:"",x.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${x.cachePodsDownload}"`:"",x.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${x.cachePodsUpload}"`:"",x.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${x.artifactIpaUpload}"`:"",x.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${x.artifactAppZipUpload}"`:"",`export BUILD_ID="${t}"`,`export MACH_BUILD_PROFILE="${Qn(w)}"`,`export MACH_APP_NAME="${Qn(z.MACH_APP_NAME)}"`,`export MACH_ENV_FINGERPRINT="${Q}"`,`export MACH_FRAMEWORK="${Qn(o)}"`,o==="expo"?"export EXPO_NO_DOTENV=1":"",`export ${m.envPrefix}PROJECT_ID="${p}"`,n.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${n.MATCH_ENCRYPTION_PASSPHRASE}"`:"",n.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${n.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${m.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${m.keychainPassword}"`].filter(Boolean).join(`
|
|
1162
|
+
`),E=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(`
|
|
1163
|
+
`):"",D=Er,$={"{{REMOTE_DIR}}":f,"{{ENV_VARS}}":O,"{{CREDENTIAL_DOWNLOADS}}":b,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":L,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":t,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":E};Object.entries($).forEach(([g,k])=>{D=D.split(g).join(k)});let C=`/tmp/${m.nameLower}-mac-build-${t}.sh`;if(Ca.writeFileSync(C,D),Mt(`${u} ${C} ${a}:${f}/build.sh`),r.stop("Remote script uploaded."),It.info(it.cyan("Executing remote build. This might take a while...")),Mt(`${c} "bash ${f}/build.sh"`,{stdio:"inherit"}),r.stop("Remote build finished!"),i){r.start("Fetching artifact links...");try{let k=(await N.get(`/builds/${i}/${t}/artifacts`)).data.artifacts||[],F=e.simulator===!0;if(k.length===0&&!F)throw r.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(r.stop("Build Successful!"),k.length>0){It.success("Build Artifacts Ready:");for(let V of k)console.log(`
|
|
1164
|
+
${it.yellow(V.name)}:
|
|
1165
|
+
${it.cyan(V.downloadUrl)}`);console.log(`
|
|
1166
|
+
${it.dim("Note: Links are valid for 7 days.")}`)}else F&&It.warn("Simulator build completed. No artifacts uploaded.")}catch(g){r.stop("Could not fetch artifacts"),It.warn(it.yellow(`Artifact listing failed: ${g.message}`))}}}catch(d){throw r.stop("iOS Build Failed"),d}};import Na from"crypto";import Le from"axios";import wr from"fs";var Ye=6e4,Ta=12e4,ei=4,Xe=e=>encodeURIComponent(e),ka=e=>new Promise(t=>setTimeout(t,e));async function Ue(e,t){let n;for(let i=1;i<=ei;i++)try{return await t()}catch(r){if(n=r,i>=ei||!xa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[Google Play] ${e} failed (attempt ${i}/${ei}); retrying in ${Math.round(s/1e3)}s...`),await ka(s)}throw n}function xa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function _r(e,t){let n;try{let i=await un(t),r=Xe(e);if(n=(await Ue("create edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits`,{},{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.id,!n)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let s=Xe(n),l=0,c=(await Ue("list tracks",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/tracks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.tracks||[];for(let u of c)if(u.releases){for(let d of u.releases)if(d.versionCodes)for(let p of d.versionCodes){let f=parseInt(p,10);f>l&&(l=f)}}try{let d=(await Ue("list bundles",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/bundles`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.bundles||[];for(let p of d)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}try{let d=(await Ue("list APKs",()=>Le.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${r}/edits/${s}/apks`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))).data.apks||[];for(let p of d)p.versionCode&&p.versionCode>l&&(l=p.versionCode)}catch{}return l}catch(i){let r=i.response?.data?.error?.message||i.message;throw new Error(`Google Play API Error: ${r}`)}finally{if(n)try{let i=await un(t);await Ue("delete edit",()=>Le.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(e)}/edits/${Xe(n)}`,{headers:{Authorization:`Bearer ${i}`,Connection:"close"},timeout:Ye}))}catch{}}}async function $r(e){let{packageName:t,serviceAccount:n,aabPath:i,track:r,releaseStatus:o,userFraction:s,changesNotSentForReview:l}=e,a;try{let u={Authorization:`Bearer ${await un(n)}`,Connection:"close"},d=Xe(t);if(a=(await Ue("create edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits`,{},{headers:u,timeout:Ye}))).data.id,!a)throw new Error("Google Play edit insert succeeded but did not return an edit id.");let f=Xe(a),h=wr.statSync(i),S=await Ue("upload AAB",()=>Le.post(`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${d}/edits/${f}/bundles`,wr.createReadStream(i),{headers:{...u,"Content-Type":"application/octet-stream","Content-Length":h.size},maxBodyLength:1/0,maxContentLength:1/0,params:{uploadType:"media"},timeout:Ta})),L=Number(S.data.versionCode);if(!L)throw new Error("Google Play upload succeeded but did not return a versionCode.");let x={versionCodes:[String(L)],status:o};return(o==="inProgress"||o==="halted")&&typeof s=="number"&&(x.userFraction=s),await Ue("update track",()=>Le.put(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${f}/tracks/${Xe(r)}`,{releases:[x]},{headers:u,timeout:Ye})),await Ue("commit edit",()=>Le.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${d}/edits/${f}:commit`,{},{headers:u,params:l?{changesNotSentForReview:!0}:void 0,timeout:Ye})),{editId:a,versionCode:L,track:r,releaseStatus:o,userFraction:s}}catch(c){if(a)try{let d=await un(n);await Ue("delete edit",()=>Le.delete(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${Xe(t)}/edits/${Xe(a)}`,{headers:{Authorization:`Bearer ${d}`,Connection:"close"},timeout:Ye}))}catch{}let u=c.response?.data?.error?.message||c.message;throw new Error(`Google Play API Error: ${u}`)}}async function un(e){let t=Math.floor(Date.now()/1e3),n=t+3600,i={alg:"RS256",typ:"JWT"},r={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:t,exp:n,scope:"https://www.googleapis.com/auth/androidpublisher"},o=Buffer.from(JSON.stringify(i)).toString("base64url"),s=Buffer.from(JSON.stringify(r)).toString("base64url"),l=`${o}.${s}`,a=Na.createSign("RSA-SHA256");a.update(l);let c=a.sign(e.private_key,"base64url"),u=`${l}.${c}`;return(await Ue("OAuth token exchange",()=>Le.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:u},{headers:{Connection:"close"},timeout:Ye}))).data.access_token}import Ma from"crypto";import vr from"axios";var ni="https://api.appstoreconnect.apple.com/v1",Rr=6e4,ti=4,La=e=>new Promise(t=>setTimeout(t,e));function Ua(e,t,n){let i=Math.floor(Date.now()/1e3),r=Buffer.from(JSON.stringify({alg:"ES256",kid:e,typ:"JWT"})).toString("base64url"),o=Buffer.from(JSON.stringify({iss:t,iat:i,exp:i+1200,aud:"appstoreconnect-v1"})).toString("base64url"),s=`${r}.${o}`,l=Ma.createSign("SHA256");l.update(s);let a=l.sign({key:n,dsaEncoding:"ieee-p1363"}).toString("base64url");return`${s}.${a}`}function Fa(e){let t=e.response?.status;return t?t===408||t===409||t===425||t===429||t>=500:!0}async function Pr(e,t){let n;for(let i=1;i<=ti;i++)try{return await t()}catch(r){if(n=r,i>=ti||!Fa(r))throw r;let o=Number(r.response?.headers?.["retry-after"]),s=Number.isFinite(o)&&o>0?o*1e3:Math.min(2e3*i*i,15e3);console.log(`[App Store Connect] ${e} failed (attempt ${i}/${ti}); retrying in ${Math.round(s/1e3)}s...`),await La(s)}throw n}function Or(e){return{Authorization:`Bearer ${Ua(e.keyId,e.issuerId,e.privateKey)}`,"Content-Type":"application/json",Connection:"close"}}function Ba(e){let t=e.response?.data?.errors;return Array.isArray(t)&&t.length>0?t.map(n=>n.detail||n.title||n.code).filter(Boolean).join("; "):e.response?.data?.error?.message||e.message||"Unknown App Store Connect error"}function fn(e){let t=String(e||"").trim();if(/^\d+(?:\.\d+){0,2}$/.test(t))return t.split(".").map(n=>Number(n))}function Ha(e,t){let n=fn(e),i=fn(t);if(!n&&!i)return 0;if(!n)return-1;if(!i)return 1;let r=Math.max(n.length,i.length);for(let o=0;o<r;o++){let s=n[o]||0,l=i[o]||0;if(s!==l)return s>l?1:-1}return 0}function ja(e){let t=fn(e);return!t||t.length===0?"1":(t[t.length-1]+=1,t.join("."))}async function Ga(e,t,n){if(t)return t;if(!n)throw new Error("Set ios.ascAppId or ios.bundleIdentifier so Mach can find the App Store Connect app.");let r=(await Pr("lookup app by bundle ID",()=>vr.get(`${ni}/apps`,{headers:Or(e),params:{"filter[bundleId]":n,limit:1},timeout:Rr}))).data?.data?.[0];if(!r?.id)throw new Error(`No App Store Connect app found for bundle ID ${n}. Set ios.ascAppId in mach.config.json if the app exists.`);return r.id}async function Dr(e){let t={keyId:e.keyId,issuerId:e.issuerId,privateKey:e.privateKey};try{let n=await Ga(t,e.ascAppId,e.bundleId),i=`${ni}/builds`,r="0",o,s=0;for(;i&&s<10;){s+=1;let l=await Pr("list builds",()=>vr.get(i,{headers:Or(t),params:i===`${ni}/builds`?{"filter[app]":n,"fields[builds]":"version,uploadedDate",sort:"-uploadedDate",limit:200}:void 0,timeout:Rr})),a=l.data?.data||[];for(let c of a){let u=String(c.attributes?.version||"").trim();fn(u)&&Ha(u,r)>0&&(r=u,o=c.attributes?.uploadedDate)}i=l.data?.links?.next}return{appId:n,latestBuildNumber:r,nextBuildNumber:ja(r),latestUploadedDate:o}}catch(n){throw new Error(`App Store Connect API Error: ${Ba(n)}`)}}import{spinner as pn,log as I,isCancel as mn,confirm as Ka,select as ri}from"@clack/prompts";import A from"chalk";import y from"fs";import _ from"path";import{execFileSync as Lt,execSync as te,spawn as kr}from"child_process";import Ee from"os";import Va from"crypto";var xr=(e,t)=>t.filter(n=>y.existsSync(_.join(e,n))).reduce((n,i)=>n.update(y.readFileSync(_.join(e,i))),Va.createHash("sha256")).digest("hex").slice(0,16),za=e=>xr(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),Wa=e=>xr(e,["Podfile","Podfile.lock"]),Ya=e=>{let t=_.join(e,"fingerprint.json");try{return JSON.parse(y.readFileSync(t,"utf-8"))}catch{return{}}},Cr=(e,t)=>{y.mkdirSync(e,{recursive:!0}),y.writeFileSync(_.join(e,"fingerprint.json"),JSON.stringify(t,null,2))},Ja=7200*1e3,qa=(e,t)=>{y.mkdirSync(e,{recursive:!0});let n=_.join(e,"build.lock");if(y.existsSync(n))try{let i=JSON.parse(y.readFileSync(n,"utf-8")),r=Date.now()-(i.timestamp||0);if(r<Ja)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(r/6e4)}m ago). Cancel it from the dashboard first, or wait for it to complete.`)}catch(i){if(i.message.includes("Another build"))throw i}y.writeFileSync(n,JSON.stringify({buildId:t,pid:process.pid,timestamp:Date.now()}))},Xa=(e,t)=>{let n=_.join(e,"build.lock");try{y.existsSync(n)&&JSON.parse(y.readFileSync(n,"utf-8")).buildId===t&&y.unlinkSync(n)}catch{}},Nr=15e5,Tr=(e,t)=>{let n=e+t;return n.length>Nr?n.slice(-Nr):n},Mr=e=>e.replace(/\u001b\[[0-9;]*m/g,""),Lr=e=>/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|PhaseScriptExecution|Command .* failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|node: command not found|env: node|No such file or directory|Permission denied/i.test(e),Za=e=>{let t=new Set,n=[];e.forEach((r,o)=>{Lr(r)&&n.push(o)});for(let r of n){let o=/PhaseScriptExecution|Command PhaseScriptExecution failed|The following build commands failed/i.test(e[r])?18:8,s=/The following build commands failed/i.test(e[r])?18:10;for(let l=Math.max(0,r-o);l<=Math.min(e.length-1,r+s);l++)t.add(l)}if(t.size===0)return e.slice(-120);let i=Array.from(t).sort((r,o)=>r-o).map(r=>e[r]);return i.length>160?i.slice(-160):i},Qa=(e,t,n,i)=>{let r=Mr(i).replace(/\r/g,`
|
|
1142
1167
|
`).split(`
|
|
1143
|
-
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(
|
|
1168
|
+
`).map(a=>a.trimEnd()).filter(Boolean),o=r.filter(Lr),s=o.length>0?Za(r):r.slice(-80),l=o.length>0?"Key failure output":"Last command output";return[`Command failed with code ${n}: ${e} ${t.join(" ")}`,s.length>0?`
|
|
1144
1169
|
${l}:
|
|
1145
1170
|
${s.join(`
|
|
1146
|
-
`)}`:""].join("")},
|
|
1147
|
-
`)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let
|
|
1148
|
-
`)),r(
|
|
1149
|
-
`)),r(
|
|
1150
|
-
`)));let
|
|
1151
|
-
`)))}let
|
|
1171
|
+
`)}`:""].join("")},el=e=>e==="xcodebuild"&&process.env.MACH_XCODE_FULL_LOGS!=="1",tl=e=>{let t=Mr(e).trim();return t?/\berror:|fatal error:|xcodebuild: error|The following build commands failed|Command PhaseScriptExecution failed|CodeSign|Provisioning profile|No profiles|requires a provisioning profile|Undefined symbols|ld:|clang: error|SwiftCompile|CompileC|CFBundleVersion|ARCHIVE SUCCEEDED|ARCHIVE FAILED|EXPORT SUCCEEDED|EXPORT FAILED|Exported .* to:|\[IPA VALID\]/i.test(t):!1},Fe=e=>{try{y.existsSync(e)&&y.rmSync(e,{recursive:!0,force:!0})}catch{}},nl=(e,t)=>{try{if(!y.existsSync(e))return;for(let n of y.readdirSync(e))t(n)&&Fe(_.join(e,n))}catch{}},ii=e=>{I.info(A.dim("Clearing Metro/Hermes JS transform caches..."));let t=Ee.tmpdir();nl(t,n=>n==="metro-cache"||n.startsWith("metro-")||n.startsWith("haste-map-")||n.startsWith("react-native-packager-cache-")),Fe(_.join(e,".expo")),Fe(_.join(e,"node_modules/.cache/metro")),Fe(_.join(Ee.homedir(),".cache/metro")),Fe(_.join(Ee.homedir(),".cache/react-native-packager")),Fe(_.join(Ee.homedir(),"Library/Caches/metro")),Fe(_.join(Ee.homedir(),"Library/Caches/react-native-packager"))},il=e=>/Internal inconsistency error|never received target ended message/i.test(String(e?.message||e)),rl=e=>{I.warn(A.yellow("Xcode build system hit an internal inconsistency. Clearing simulator build state and retrying once...")),Fe(_.join(e,"Build")),Fe(_.join(e,"Index.noindex")),Fe(_.join(e,"ModuleCache.noindex")),Fe(_.join(e,"SourcePackages"))},ol=(e,t,n,i,r)=>{let o=a=>{let c=a.filter(d=>d?.id&&String(d?.platform||"").includes("iOS Simulator")&&!d?.error),u=c.find(d=>/iphone/i.test(d.name||""))||c[0];return u?.id?`id=${u.id}`:void 0},s=a=>{let c=[],u=!1;for(let d of a.split(`
|
|
1172
|
+
`)){if(/Ineligible destinations/i.test(d)&&(u=!0),u||!d.includes("platform:iOS Simulator")||d.includes("error:"))continue;let p=d.match(/\bid:([^,}]+)/)?.[1]?.trim(),f=d.match(/\bname:([^,}]+)/)?.[1]?.trim();p&&c.push({id:p,name:f,platform:"iOS Simulator"})}return o(c)},l=[t?"-workspace":"-project",t||n,"-scheme",i,"-configuration",r,"-sdk","iphonesimulator","-showdestinations"];try{let a=Lt("xcodebuild",[...l,"-json"],{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),c=JSON.parse(a),u=Array.isArray(c.destinations)?c.destinations:Array.isArray(c.availableDestinations)?c.availableDestinations:[],d=o(u);if(d)return d}catch{}try{let a=Lt("xcodebuild",l,{cwd:e,encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return s(a)}catch{}},Be=(e,t,n=process.cwd(),i={},r,o)=>new Promise((s,l)=>{let a="",c=el(e),u=Date.now(),d=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",_.join(Ee.homedir(),".npm-global/bin")],f=[...(process.env.PATH||"").split(":"),...d].filter((b,U,w)=>b&&w.indexOf(b)===U).join(":");process.env[`${m.envPrefix}DEBUG`]&&console.log(A.magenta(`[${m.nameUpper}_DEBUG] Execution PATH: ${f}`));let h={...process.env,...i,PATH:f,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};r&&process.env[`${m.envPrefix}DEBUG`]&&(r(A.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
1173
|
+
`)),r(A.magenta(`[ENVIRONMENT] PATH: ${f}
|
|
1174
|
+
`)),r(A.magenta(`[ENVIRONMENT] command: ${e} ${t.join(" ")}
|
|
1175
|
+
`)));let S=e;if(["node","npm","npx","pod"].includes(e)){let b=_.dirname(process.execPath),U=_.join(b,e);y.existsSync(U)&&(S=U,r&&r(A.dim(`[EXEC] Using absolute path: ${S}
|
|
1176
|
+
`)))}let L=kr(S,t,{stdio:"pipe",cwd:n,shell:!0,env:h,detached:process.platform!=="win32"});if(o){if(o.aborted){if(L.pid)try{process.kill(-L.pid,"SIGTERM")}catch{L.kill()}return l(new Error("Command aborted"))}o.addEventListener("abort",()=>{if(L.pid)try{process.kill(-L.pid,"SIGTERM")}catch{L.kill()}l(new Error("Command aborted"))})}let x=(b,U)=>{if(!c){U.write(b);return}let w=b.replace(/\r/g,`
|
|
1152
1177
|
`).split(`
|
|
1153
|
-
`).filter(
|
|
1178
|
+
`).filter(tl);if(w.length>0){U.write(`${w.join(`
|
|
1154
1179
|
`)}
|
|
1155
|
-
`),u=Date.now();return}let
|
|
1156
|
-
`),u=
|
|
1157
|
-
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${_.basename(e)} has no Payload/*.app/Info.plist.`);let i=y.mkdtempSync(_.join(
|
|
1158
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),
|
|
1159
|
-
`)},
|
|
1160
|
-
`);else if(i&&l==="ios"&&!e.simulator)try{let
|
|
1161
|
-
`)),n.BUILD_NUMBER=
|
|
1162
|
-
`)}}catch(
|
|
1163
|
-
`)}if(await
|
|
1164
|
-
`),I.info(
|
|
1165
|
-
`),I.warn(
|
|
1166
|
-
`),y.rmSync(_.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),
|
|
1180
|
+
`),u=Date.now();return}let z=Date.now();z-u>3e4&&(U.write(`[xcodebuild] still running; detailed output is streamed to Mach logs.
|
|
1181
|
+
`),u=z)};L.stdout.on("data",b=>{let U=b.toString();a=Tr(a,U),x(U,process.stdout),r&&r(U)}),L.stderr.on("data",b=>{let U=b.toString();a=Tr(a,U),x(U,process.stderr),r&&r(U)}),L.on("close",b=>{b===0?s(b):l(new Error(Qa(e,t,b,a)))}),L.on("error",b=>l(b))}),sl=e=>{let t=Math.floor(e/1e3%60),n=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),r=[];return i>0&&r.push(`${i}h`),n>0&&r.push(`${n}m`),(t>0||r.length===0)&&r.push(`${t}s`),r.join(" ")},pt=(e,t)=>{let n=[];try{if(!y.existsSync(e))return n;let i=y.readdirSync(e);for(let r of i){let o=_.join(e,r);try{let s=y.statSync(o);if(t.some(a=>r.endsWith(a))){n.push(_.resolve(o));continue}s.isDirectory()&&(n=n.concat(pt(o,t)))}catch{}}}catch{}return n},al=/^\d+(?:\.\d+){0,2}$/,oi=e=>{let t=String(e||"").trim();return!t||t==="undefined"||t==="null"?null:al.test(t)?t:null},Ur=(e,t)=>{let n=oi(e);if(!n)throw new Error(`Invalid iOS CFBundleVersion from ${t}: "${e||""}". Apple requires one to three period-separated integers, for example "42" or "1.2.3". If you see "[Decryption Failed]", fix/remove the broken BUILD_NUMBER secret and rebuild.`);return n},Fr=(e,t)=>Lt("/usr/libexec/PlistBuddy",["-c",`Print :${t}`,e],{encoding:"utf-8"}).trim(),ll=e=>{let t=_.join(e,"Info.plist");if(!y.existsSync(t))throw new Error(`Could not validate iOS build number: ${t} not found.`);return Ur(Fr(t,"CFBundleVersion"),t)},dl=e=>{let n=Lt("unzip",["-Z1",e],{encoding:"utf-8"}).split(`
|
|
1182
|
+
`).find(r=>/^Payload\/[^/]+\.app\/Info\.plist$/.test(r.trim()));if(!n)throw new Error(`Could not validate iOS build number: ${_.basename(e)} has no Payload/*.app/Info.plist.`);let i=y.mkdtempSync(_.join(Ee.tmpdir(),`${m.nameLower}-ipa-plist-`));try{let r=_.join(i,"Info.plist"),o=Lt("unzip",["-p",e,n.trim()]);return y.writeFileSync(r,o),Ur(Fr(r,"CFBundleVersion"),`${_.basename(e)}:${n.trim()}`)}finally{y.rmSync(i,{recursive:!0,force:!0})}},si=async(e,t,n={},i,r={})=>{let o=pn(),s=Date.now(),l=e.platform,a=e.buildProfile||"production",c=e.framework||"react-native",u=()=>ft(n,a,e);if(c==="flutter")throw new Error('Flutter builds are not implemented yet. Set framework to "expo" or "react-native" for this build.');let d=async(E,D={})=>{if(i)for(let $=1;$<=3;$++)try{await N.patch(`/builds/${i}/${t}`,{status:E,...D});return}catch(C){let g=C?.response?.data?.message||C?.message||String(C);console.error(`[reportStatus] attempt ${$}/3 failed (status=${E}): ${g}`),$<3&&await new Promise(k=>setTimeout(k,2e3))}},p=new AbortController,{signal:f}=p,h=null;i&&(h=setInterval(async()=>{try{(await N.get(`/builds/${i}/${t}`)).data.status==="cancelled"&&(I.warn(A.yellow(`
|
|
1183
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),p.abort(),h&&clearInterval(h))}catch{}},5e3));let S=_.join(process.cwd(),".mach-cache"),L="setup",x="",b=null,U=async()=>{if(!x||!i)return;let E=x;x="";try{let D=E;Object.values(n).forEach($=>{if($&&$.length>5){let C=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");D=D.replace(new RegExp(C,"g"),"[SECRET]")}}),await N.post(`/builds/${i}/${t}/logs`,{log:D,step:L})}catch{}},w=async()=>{b&&(clearTimeout(b),b=null),await U(),Xa(S,t),h&&(clearInterval(h),h=null);try{let E=_.join(Ee.tmpdir(),`${m.buildPrefix}-${t}.keychain-db`);y.existsSync(E)&&(te(`security delete-keychain "${E}"`,{stdio:"ignore"}),I.info(A.dim("\u{1F511} Build keychain deleted.")))}catch{}try{let E=_.join(Ee.homedir(),"Library/MobileDevice/Provisioning Profiles");if(y.existsSync(E)){let D=y.readdirSync(E).filter($=>$.includes(t)||$.startsWith(`${m.nameLower}-temp-${t}`));for(let $ of D)y.unlinkSync(_.join(E,$))}}catch{}},z=async E=>{i&&(x+=E,x.length>=8192?(b&&(clearTimeout(b),b=null),await U()):b||(b=setTimeout(()=>{b=null,U()},2e3)))},Q=async E=>{L=E,await z(`[STEP_START:${E}] ${Math.floor(Date.now()/1e3)}
|
|
1184
|
+
`)},O=async(E,D,$,C)=>await Be(E,D,$,C,g=>{z(g)},f);I.info(A.blue(`\u{1F680} Starting local build for ${l} (${a})...`));try{qa(S,t)}catch(E){throw await d("failed",{error:E.message}),E}if(await d("building"),await Q("setup"),l==="ios"&&!e.simulator&&n.MACH_IOS_BUILD_NUMBER_LOCKED==="1"&&n.BUILD_NUMBER)I.info(A.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await z(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1185
|
+
`);else if(i&&l==="ios"&&!e.simulator)try{let E=parseInt(n.BUILD_NUMBER||"0",10),D=Number.isFinite(E)?E:0,$=await N.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:D});if($.data.status==="success"){let C=oi(String($.data.buildNumber||""));if(!C)throw new Error(`Dashboard returned invalid iOS build number: "${$.data.buildNumber||""}"`);let g=parseInt(C,10),k=D>0&&Number.isFinite(g)&&g<D?String(D):C;k!==C&&(I.warn(A.yellow(`Dashboard build counter returned ${C}; using minimum ${k}.`)),await z(`[BUILD_NUMBER] Dashboard returned ${C}; using minimum ${k}
|
|
1186
|
+
`)),n.BUILD_NUMBER=k,I.info(A.dim(`Auto build number: ${n.BUILD_NUMBER}`)),await z(`[BUILD_NUMBER] ${n.BUILD_NUMBER}
|
|
1187
|
+
`)}}catch(E){I.warn(A.yellow(`Could not fetch auto build number: ${E.message}`))}await Q("lock"),c==="expo"?e.developmentClient?(I.info(A.blue("\u2139\uFE0F Configuring Expo build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(I.info(A.blue("\u2139\uFE0F Configuring Expo build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client"):(delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE);try{await Q("clone"),I.info(A.dim("Preparing source...")),await Q("read_config");let E=_.join(process.cwd(),m.configFileName);if(y.existsSync(E)){let j=JSON.parse(y.readFileSync(E,"utf-8"))?.build?.[a]||{};await z(`[CONFIG] Profile: ${a}, distribution: ${j.distribution||"not set"}, simulator: ${j.simulator||!1}
|
|
1188
|
+
`)}if(await Q("read_package"),e.nodeVersion){let G=process.env.NVM_DIR||_.join(Ee.homedir(),".nvm"),j=_.join(G,"versions","node"),X;if(y.existsSync(j)){let T=y.readdirSync(j).sort().reverse(),K=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,Z=T.find(ae=>ae===K||ae.startsWith(K+".")||ae.startsWith(`v${e.nodeVersion}.`));Z&&(X=_.join(j,Z,"bin"))}if(X&&y.existsSync(X)){let T=process.env.PATH||"";process.env.PATH=`${X}:${T}`,await z(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${X}
|
|
1189
|
+
`),I.info(A.green(`\u2713 Node switched to ${e.nodeVersion} (${X})`))}else await z(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
1190
|
+
`),I.warn(A.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await Q("deps"),o.start("Checking dependencies...");let D=Ya(S),$=za(process.cwd()),C=y.existsSync("node_modules"),g=y.existsSync("yarn.lock"),k=y.existsSync("bun.lockb");C&&D.node&&D.node!==$&&(o.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await z(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
1191
|
+
`),y.rmSync(_.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),C=!1);let F="npm",V=["install","--prefer-offline"];g?(F="yarn",V=["install","--prefer-offline"]):k&&(F="bun",V=["install"]),C?o.stop("Cached node_modules found. Syncing dependencies..."):o.stop("No cached dependencies. Running fresh install..."),e.preBuild&&(I.info(A.blue("Running pre-install hook...")),I.info(A.dim(`> ${e.preBuild}`)),await Q("prebuild"),await O("bash",[e.preBuild],process.cwd(),u())),I.info(A.dim(`Running ${F} ${V.join(" ")}...`)),await O(F,V,process.cwd(),u()),D.node=$,Cr(S,D);let J=c==="expo",H=e.iosBundleIdentifier||"",P=e.name||"";if(J){o.start(`Enforcing ${m.name} configuration...`);let G=_.join(process.cwd(),"app.json"),j=null;if(y.existsSync(G)){j=y.readFileSync(G,"utf-8");let T=JSON.parse(j);T.expo=T.expo||{},P||(P=T.expo.name||""),l==="ios"&&!H&&(H=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),y.writeFileSync(G,JSON.stringify(T,null,2))}let X=["exec","--","expo","prebuild","--platform",l,"--no-install"];try{if(await Q("prebuild"),await O("npm",X,process.cwd(),u()),l==="ios"&&y.existsSync("ios")){await Q("pods"),I.info(A.blue("Running pod install..."));try{let T=_.resolve("ios"),K=_.join(T,"Podfile");if(!y.existsSync(K))throw new Error("ios/Podfile not found. Skipping pod install.");let Z=y.readFileSync(K,"utf-8"),ae=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(I.info(A.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),Z.includes("use_expo_modules!")&&!Z.includes("exclude:"))){let ut=/use_expo_modules!(\s*)$/m;ut.test(Z)?Z=Z.replace(ut,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):Z=Z.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let Se=`
|
|
1167
1192
|
installer.generated_projects.each do |project|
|
|
1168
1193
|
project.targets.each do |target|
|
|
1169
1194
|
target.build_configurations.each do |config|
|
|
@@ -1176,19 +1201,19 @@ ${s.join(`
|
|
|
1176
1201
|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${ae}'
|
|
1177
1202
|
end
|
|
1178
1203
|
end
|
|
1179
|
-
`,qe=/post_install\s+do\s+\|installer\|/;if(qe.test(Z))I.info(
|
|
1180
|
-
${Se}`),y.writeFileSync(
|
|
1204
|
+
`,qe=/post_install\s+do\s+\|installer\|/;if(qe.test(Z))I.info(A.dim(`Injecting deployment target (${ae}) into existing post_install hook...`)),Z=Z.replace(qe,`post_install do |installer|
|
|
1205
|
+
${Se}`),y.writeFileSync(K,Z);else{I.info(A.dim(`Appending new post_install hook for deployment target (${ae})...`));let ut=`
|
|
1181
1206
|
post_install do |installer|
|
|
1182
1207
|
${Se}
|
|
1183
1208
|
end
|
|
1184
|
-
`;y.appendFileSync(
|
|
1185
|
-
`),I.info(
|
|
1186
|
-
\u2713 Local build completed successfully in ${ye}`)),await
|
|
1187
|
-
\u{1F4E6} Generated Artifacts:`)),q.forEach(
|
|
1188
|
-
\u274C Build aborted.`)),await
|
|
1189
|
-
\u2717 Local build failed: ${
|
|
1190
|
-
`)[0]||"unknown"}`))}if(!Ct)throw new Error("Failed to import P12.");y.unlinkSync(ae),
|
|
1191
|
-
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),sn=[
|
|
1209
|
+
`;y.appendFileSync(K,ut)}let Ct="/opt/homebrew/bin/pod",on=y.existsSync(Ct)?Ct:"pod",sn=Wa(T);y.existsSync(_.join(T,"Pods"))&&D.pods&&D.pods!==sn&&(await z(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
1210
|
+
`),I.info(A.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),y.rmSync(_.join(T,"Pods"),{recursive:!0,force:!0})),I.info(A.dim(`Using pod command: ${on} in ${T}`)),await O(on,["install"],T,u()),D.pods=sn,Cr(S,D)}catch(T){let K=T.message||"Unknown error";I.warn(A.yellow(`Native "pod" command failed: ${K}`)),I.info(A.dim("Falling back to npm exec pod-install...")),I.info(A.magenta(`${m.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await O("npx",["--yes","pod-install@latest","ios"],process.cwd(),u())}if(y.existsSync("ios/Pods")){I.info(A.dim("Disabling signing for Pod targets to prevent conflicts..."));try{te(`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{j&&y.writeFileSync(G,j)}o.stop(`Expo prebuild complete (${m.name} config enforced).`)}let q=[];if(l==="android")await Q("build"),q=await cl(e,a,n,G=>z(G),f);else if(l==="ios"){await Q("signing"),I.info(A.dim("Preparing credentials..."));let G=r?.distributionType;q=await ul(e,t,a,n,i,j=>z(j),f,G,j=>Q(j))}e.postBuild&&(I.info(A.blue("Running post-build hook...")),I.info(A.dim(`> ${e.postBuild}`)),await O(e.postBuild,[],process.cwd(),u()));let ye=sl(Date.now()-s);if(I.success(A.green(`
|
|
1211
|
+
\u2713 Local build completed successfully in ${ye}`)),await d("building",{...H&&{bundleId:H},...P&&{appName:P}}),q.length>0&&(I.info(A.cyan(`
|
|
1212
|
+
\u{1F4E6} Generated Artifacts:`)),q.forEach(G=>{let j=_.resolve(G);I.info(A.dim(` - ${G}`)),I.info(A.gray(` Path: ${j}`))}),e.interactive)){let G=await Ka({message:"Install on connected device?"});if(!mn(G)&&G){if(l==="android"){let j=q.find(X=>X.endsWith(".apk"))||q[0];await pl(j,X=>z(X))}else if(l==="ios"){let j=q.find(T=>T.endsWith(".ipa"))||q.find(T=>T.endsWith(".app"))||q[0],X=Ze("ios");e.simulator?await ml(j,X||"",T=>z(T)):await gl(j,X||"",T=>z(T))}}}await Q("upload");let Ae=[];for(let G of q)try{let j=_.join(Ee.tmpdir(),`${t}-${_.basename(G)}`);y.copyFileSync(G,j),Ae.push(j),I.info(A.dim(` \u{1F4CB} Preserved artifact: ${_.basename(G)}`))}catch{I.warn(A.yellow(` Failed to preserve artifact: ${_.basename(G)}`))}q=Ae,I.info(A.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let G=process.cwd(),j=new Set(["node_modules"]),X=y.readdirSync(G),T=0;for(let K of X)if(!j.has(K)){if(K==="ios"){let Z=_.join(G,"ios"),ae=y.readdirSync(Z);for(let Se of ae)if(Se!=="Pods")try{y.rmSync(_.join(Z,Se),{recursive:!0,force:!0}),T++}catch{}continue}try{y.rmSync(_.join(G,K),{recursive:!0,force:!0}),T++}catch{}}I.info(A.dim(` Cleaned ${T} items. Cached: node_modules${y.existsSync(_.join(G,"ios","Pods"))?", ios/Pods":""}`)),I.info(A.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{I.warn(A.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let j=_.join(Ee.homedir(),m.workspacesDir),X=te(`df -k "${j}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),T=parseInt(X,10)*1024;if(T<53687091200&&y.existsSync(j)){I.info(A.dim(` \u26A0\uFE0F Low disk space (${(T/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let K=_.basename(process.cwd()),Z=y.readdirSync(j).filter(ae=>ae!==K).map(ae=>{let Se=_.join(j,ae);try{let qe=y.statSync(Se);return qe.isDirectory()?{name:ae,dir:Se,mtime:qe.mtimeMs}:null}catch{return null}}).filter(Boolean);Z.sort((ae,Se)=>ae.mtime-Se.mtime);for(let ae of Z){if(T>=53687091200)break;try{y.rmSync(ae.dir,{recursive:!0,force:!0}),I.info(A.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${ae.name}`));let Se=te(`df -k "${j}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(Se,10)*1024>=53687091200)break}catch{}}}}catch{}return await w(),q}catch(E){throw await w(),E.message==="Command aborted"?(I.warn(A.yellow(`
|
|
1213
|
+
\u274C Build aborted.`)),await d("failed",{error:"Aborted by user"}),E):(I.error(A.red(`
|
|
1214
|
+
\u2717 Local build failed: ${E.message}`)),await d("failed",{error:E.message}),E)}},cl=async(e,t,n={},i,r)=>{let o=y.existsSync("android/gradlew")?"android/gradlew":y.existsSync("gradlew")?"./gradlew":null;if(!o)throw new Error("Could not find gradlew. Is this an Android project?");let s=e.developmentClient?"assembleDebug":"assembleRelease";!e.developmentClient&&e.distribution==="store"?s="bundleRelease":!e.developmentClient&&e.distribution==="internal"&&(s="assembleRelease");let l=e.buildCommand||s;I.info(A.blue(`Running Android build: ${l}...`));let a=o.includes("android/")?"android":".",c=(o.includes("android/"),"./gradlew"),u=[l],d=e.framework||"react-native",p={...n,...d==="expo"?{EXPO_NO_DOTENV:"1"}:{},MACH_FRAMEWORK:d,MACH_BUILD_PROFILE:t,MACH_APP_NAME:e.appName||e.name||"App"};if(n.ANDROID_VERSION_CODE){let h=_.join(a,"app/build.gradle");if(y.existsSync(h)){let S=n.ANDROID_VERSION_CODE,L=y.readFileSync(h,"utf-8");L=L.replace(/versionCode\s+\d+/,`versionCode ${S}`),y.writeFileSync(h,L),I.info(A.green(`\u2713 Applied Android versionCode ${S}`))}u.push(`-Pandroid.injected.version.code=${n.ANDROID_VERSION_CODE}`)}for(let h of["app/build","build",".cxx"]){let S=_.join(a,h);y.existsSync(S)&&y.rmSync(S,{recursive:!0,force:!0})}ii(process.cwd()),await Be(c,u,a,p,i,r);let f=_.join(a,"app/build/outputs");return pt(f,[".apk",".aab"])},ul=async(e,t,n,i={},r,o,s,l,a)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let c=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),u=y.readdirSync(c),d=u.find(D=>D.endsWith(".xcworkspace")),p=u.find(D=>D.endsWith(".xcodeproj")),f=ft(i,n,e),h=oi(f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION);if((f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION)&&!h)throw new Error(`Invalid iOS BUILD_NUMBER/CURRENT_PROJECT_VERSION: "${f.BUILD_NUMBER||f.CURRENT_PROJECT_VERSION}". Apple requires one to three period-separated integers. Fix the Dashboard secret or remove it so Mach can use its auto build number.`);let S=h?[`BUILD_NUMBER=${h}`,`CURRENT_PROJECT_VERSION=${h}`]:[];if(h&&(f.BUILD_NUMBER=h,f.CURRENT_PROJECT_VERSION=h,I.info(A.dim(`Using iOS build number: ${h}`))),!d&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let D=te("xcode-select -p").toString().trim();I.info(A.dim(`Using Xcode at: ${D}`))}catch{I.warn(A.dim("Could not detect Xcode path."))}I.info(A.blue("Running iOS build via xcodebuild..."));let L=d?d.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),x=e.iosScheme||L||e.scheme,b=e.developmentClient?"Debug":e.iosConfiguration||"Release",U=(r||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),w=_.join(Ee.homedir(),`Library/Developer/Xcode/DerivedData/${m.nameLower}`,U);y.mkdirSync(w,{recursive:!0});let z=Et(f),Q=_.join(w,".mach-env-hash"),O=_.join(w,"Build"),E=y.existsSync(Q)?y.readFileSync(Q,"utf-8").trim():"";if(y.existsSync(O)){let D=E&&E!==z?"Build environment changed \u2014 clearing iOS DerivedData build products.":E?"Clearing iOS DerivedData build products to force a fresh JS bundle.":"DerivedData has no environment stamp \u2014 clearing iOS build products.";I.info(A.dim(D)),y.rmSync(O,{recursive:!0,force:!0})}if(y.writeFileSync(Q,z),ii(process.cwd()),e.simulator){let D=ol(c,d,p,x,b),$=D?["-destination",D]:[];I.info(A.dim(D?`Building for simulator (Scheme: ${x}, Config: ${b}, Destination: ${D})...`:`Building for simulator (Scheme: ${x}, Config: ${b}; xcodebuild will choose destination)...`));let C=[d?"-workspace":"-project",d||p,"-scheme",x,"-configuration",b,"-sdk","iphonesimulator",...$,"-derivedDataPath",w,...S,"COMPILER_INDEX_STORE_ENABLE=NO","CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"];try{await Be("xcodebuild",C,c,f,o,s)}catch(F){if(!il(F))throw F;rl(w),ii(process.cwd()),await Be("xcodebuild",C,c,f,o,s)}let g=_.join(w,"Build/Products",`${b}-iphonesimulator`),k=pt(g,[".app"]);if(k.length>0){let F=k[0],V=_.basename(F,".app"),J=_.join(g,`${V}_simulator.zip`);return I.info(A.dim(`Creating simulator artifact: ${J}...`)),te(`cd "${g}" && zip -r "${J}" "${_.basename(F)}"`),[J]}return[]}else{I.info(A.dim(`Archiving (Scheme: ${x}, Config: ${b})...`));let D=_.join(c,"build.xcarchive"),$=_.join(c,"export");y.rmSync(D,{recursive:!0,force:!0}),y.rmSync($,{recursive:!0,force:!0});let C=i.IOS_DIST_P12,g=i.IOS_PROVISIONING_PROFILE,k=i.IOS_P12_PASSWORD||"",F=[],V,J,H={isAppStore:!1,isDevelopment:!1};if(C&&g){I.info(A.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let T=`${m.buildPrefix}-${t}.keychain-db`,K=_.join(Ee.tmpdir(),T),Z=m.keychainPassword;te(`security create-keychain -p "${Z}" "${K}" 2>/dev/null || true`),te(`security set-keychain-settings -t 3600 -l "${K}"`),te(`security unlock-keychain -p "${Z}" "${K}"`);let ae=_.join(Ee.tmpdir(),`cert-${t}.p12`),Se=Buffer.from(C,"base64");y.writeFileSync(ae,Se),I.info(A.dim(`P12 data size: ${Se.length} bytes, first bytes: ${Se.slice(0,4).toString("hex")}`)),(Se.length<100||Se[0]!==48)&&(I.warn(A.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),I.warn(A.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let qe=[k,"",m.keychainPassword],Ct=!1;for(let _e of qe)try{te(`security import "${ae}" -k "${K}" -P "${_e}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),Ct=!0,I.info(A.dim(`\u2713 P12 imported successfully with password: ${_e?"[set]":"[empty]"}`));break}catch(Me){I.info(A.dim(` P12 import attempt with password ${_e?`"${_e.substring(0,3)}..."`:"[empty]"} failed: ${Me.message?.split(`
|
|
1215
|
+
`)[0]||"unknown"}`))}if(!Ct)throw new Error("Failed to import P12.");y.unlinkSync(ae),te(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Z}" "${K}"`);let on=te("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
1216
|
+
`).map(_e=>_e.trim().replace(/^"|"$/g,"")).filter(_e=>_e.length>0),sn=[K,...on].map(_e=>`"${_e}"`).join(" ");te(`security list-keychains -d user -s ${sn}`),te(`security default-keychain -s "${K}"`);let an=_.join(Ee.homedir(),"Library/MobileDevice/Provisioning Profiles");y.mkdirSync(an,{recursive:!0});let ut=Buffer.from(g,"base64"),Wn=_.join(an,`${m.nameLower}-temp-${t}.mobileprovision`);y.writeFileSync(Wn,ut);let Yn=ut.toString("utf-8"),Xi=/<key>get-task-allow<\/key>\s*<true\/>/.test(Yn);H={isAppStore:!Yn.includes("<key>ProvisionedDevices</key>")&&!Xi,isDevelopment:Xi};try{let Me=te(`security cms -D -i "${Wn}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);J=Me?Me[1]:void 0}catch{let Me=Yn.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);J=Me?Me[1]:void 0}J||(I.warn("Could not extract UUID from provisioning profile. Using fallback."),J=`${m.nameLower}-${t}`);let Jn=_.join(an,`${J}.mobileprovision`);y.existsSync(Jn)&&y.unlinkSync(Jn),y.renameSync(Wn,Jn);try{let _e=te(`security find-identity -v -p codesigning "${K}"`,{encoding:"utf-8"}),Me=Array.from(_e.matchAll(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/g),Nt=>Nt[1]),Zi=H.isDevelopment?Me.find(Nt=>/\b(Development|Developer)\b/.test(Nt)):Me.find(Nt=>/\bDistribution\b/.test(Nt)),Qi=Me[0];(Zi||Qi)&&(V=Zi||Qi,I.info(A.blue(`Identity auto-detected from keychain: "${V}"`)))}catch{}V||(V=H.isDevelopment?"Apple Development":"Apple Distribution",I.info(A.blue(`Identity fallback (profile heuristic): "${V}"`))),I.info(A.dim(`Profile type: ${H.isDevelopment?"Development":H.isAppStore?"App Store":"Ad-Hoc"}`)),I.info(A.dim(`Identity Detection: get-task-allow=${H.isDevelopment}, Selected Identity="${V}"`)),F.push("CODE_SIGN_STYLE=Manual"),F.push(`CODE_SIGN_IDENTITY="${V}"`),F.push(`PROVISIONING_PROFILE_SPECIFIER=${J}`),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(T){throw I.error(`Signing setup failed: ${T.message}`),T}}else F.push("-allowProvisioningUpdates"),e.iosTeamId&&F.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);a&&await a("archive"),I.info(A.blue(`Archive detected Identity: "${V}"`)),I.info(A.blue(`Archive detected UUID: "${J}"`)),await Be("xcodebuild",["archive",d?"-workspace":"-project",d||p,"-scheme",x,"-configuration",b,"-archivePath",D,"-derivedDataPath",w,...S,...F],c,f,o,s);let P=pt(_.join(D,"Products","Applications"),[".app"]);for(let T of P){let K=ll(T);I.info(A.dim(`Validated iOS CFBundleVersion ${K} in ${_.basename(T)}`))}let q;J?(H.isAppStore?q="app-store":H.isDevelopment?q="development":q="ad-hoc",I.info(A.blue(`Export method from profile: "${q}"`))):(q=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",I.warn(A.yellow(`No profile UUID detected. Export method from distribution flag: "${q}"`)));let ye=e.iosExportMethod||q,Ae=e.iosBundleIdentifier||Ze("ios"),G=_.join(c,"ExportOptions.plist"),j=`<?xml version="1.0" encoding="UTF-8"?>
|
|
1192
1217
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1193
1218
|
<plist version="1.0">
|
|
1194
1219
|
<dict>
|
|
@@ -1197,68 +1222,75 @@ end
|
|
|
1197
1222
|
<key>destination</key>
|
|
1198
1223
|
<string>export</string>
|
|
1199
1224
|
<key>signingStyle</key>
|
|
1200
|
-
<string>${
|
|
1225
|
+
<string>${J?"manual":"automatic"}</string>
|
|
1201
1226
|
<key>thinning</key>
|
|
1202
1227
|
<string><none></string>
|
|
1203
1228
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
1204
|
-
${
|
|
1229
|
+
${Ae&&J?`
|
|
1205
1230
|
<key>provisioningProfiles</key>
|
|
1206
1231
|
<dict>
|
|
1207
|
-
<key>${
|
|
1208
|
-
<string>${
|
|
1232
|
+
<key>${Ae}</key>
|
|
1233
|
+
<string>${J}</string>
|
|
1209
1234
|
</dict>`:""}
|
|
1210
1235
|
</dict>
|
|
1211
|
-
</plist>`;if(y.writeFileSync(
|
|
1212
|
-
${
|
|
1236
|
+
</plist>`;if(y.writeFileSync(G,j),process.env[`${m.envPrefix}DEBUG`]&&I.info(A.magenta(`[${m.nameUpper}_DEBUG] ExportOptions.plist:
|
|
1237
|
+
${j}`)),a&&await a("export"),I.info(A.blue(`Exporting with Bundle ID: "${Ae}"`)),I.info(A.blue(`Exporting with Method: "${ye}"`)),o){o(A.magenta(`
|
|
1213
1238
|
[DIAGNOSTIC] Checking available signing identities...
|
|
1214
|
-
`));try{let
|
|
1215
|
-
`))}catch(
|
|
1216
|
-
`))}}await
|
|
1217
|
-
`),o&&o(`[IPA VALID] CFBundleVersion ${
|
|
1218
|
-
`)}catch(
|
|
1219
|
-
`),new Error(Z)}return X}},Ze=e=>{try{let t=_.join(process.cwd(),m.configFileName);if(y.existsSync(t)){let n=JSON.parse(y.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(y.existsSync(i)){let o=y.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),i=pt(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=y.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=pt(n,[".xcodeproj"]);if(r.length>0){let s=_.join(r[0],"project.pbxproj");if(y.existsSync(s)){let a=y.readFileSync(s,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(a)return a[1]}}let o=["app.json","app.config.json","app.config.js","app.config.ts"];for(let s of o)if(y.existsSync(s)){let a=y.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},
|
|
1220
|
-
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){I.warn(
|
|
1221
|
-
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await
|
|
1222
|
-
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?
|
|
1239
|
+
`));try{let T=te("security find-identity -v -p codesigning",{encoding:"utf-8"});o(A.magenta(`${T}
|
|
1240
|
+
`))}catch(T){o(A.red(`[DIAGNOSTIC] Failed to list identities: ${T.message}
|
|
1241
|
+
`))}}await Be("xcodebuild",["-exportArchive","-archivePath",D,"-exportPath",$,"-exportOptionsPlist",G],c,f,o,s),a&&await a("validate");let X=pt($,[".ipa"]);for(let T of X)try{te(`unzip -t "${T}"`,{stdio:"pipe"});let K=dl(T);o&&o(`[IPA VALID] ${_.basename(T)} \u2014 archive integrity OK
|
|
1242
|
+
`),o&&o(`[IPA VALID] CFBundleVersion ${K}
|
|
1243
|
+
`)}catch(K){let Z=`IPA validation failed for ${_.basename(T)}: ${K.message||"archive may be corrupt"}`;throw o&&o(`[IPA CORRUPT] ${Z}
|
|
1244
|
+
`),new Error(Z)}return X}},Ze=e=>{try{let t=_.join(process.cwd(),m.configFileName);if(y.existsSync(t)){let n=JSON.parse(y.readFileSync(t,"utf-8"));if(e==="android"&&n.android?.package)return n.android.package;if(e==="ios"&&n.ios?.bundleIdentifier)return n.ios.bundleIdentifier}if(e==="android"){let n=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of n)if(y.existsSync(i)){let o=y.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(o)return o[1]}}else{let n=_.resolve(process.cwd(),y.existsSync("ios")?"ios":"."),i=pt(n,["Info.plist"]).filter(s=>!s.includes("/Pods/")&&!s.includes("/build/")&&!s.includes("/DerivedData/"));i.sort((s,l)=>l.split("/").length-s.split("/").length);for(let s of i){let a=y.readFileSync(s,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(a&&!a[1].includes("$"))return a[1]}let r=pt(n,[".xcodeproj"]);if(r.length>0){let s=_.join(r[0],"project.pbxproj");if(y.existsSync(s)){let a=y.readFileSync(s,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(a)return a[1]}}let o=["app.json","app.config.json","app.config.js","app.config.ts"];for(let s of o)if(y.existsSync(s)){let a=y.readFileSync(s,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(a)return a[1]}}}catch{return null}return null},fl=()=>{try{return te("emulator -version",{stdio:"ignore"}),"emulator"}catch{let t=Ee.homedir(),n=[_.join(t,"Library/Android/sdk/emulator/emulator"),_.join(t,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of n)if(y.existsSync(i))return i}return"emulator"},pl=async(e,t)=>{let n=pn();try{if(te("adb devices").toString().split(`
|
|
1245
|
+
`).slice(1).map(s=>s.trim()).filter(s=>s.length>0&&!s.startsWith("*")).map(s=>s.split(" ")[0]).length===0){I.warn(A.yellow("No Android devices or emulators found."));let s=fl(),l=[];try{l=te(`${s} -list-avds`).toString().split(`
|
|
1246
|
+
`).filter(a=>a.trim().length>0)}catch{}if(l.length>0){let a=await ri({message:"Select an emulator to launch:",options:l.map(d=>({value:d,label:d}))});if(mn(a))return;n.start(`Launching emulator ${a}...`),kr(s,["-avd",a],{detached:!0,stdio:"ignore"}).unref();let c=0,u=!1;for(;c<60;){try{if(te("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw n.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");n.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}n.start("Installing APK on device..."),await Be("adb",["install","-r",e],process.cwd(),{},t),n.stop("Installation complete.");let o=Ze("android");if(o){I.info(A.blue(`\u{1F680} Launching ${o}...`));try{te(`adb shell dumpsys package ${o}`).toString().split(`
|
|
1247
|
+
`).find(a=>a.includes("android.intent.action.MAIN")&&a.includes("android.intent.category.LAUNCHER"))?te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):te(`adb shell monkey -p ${o} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{I.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){n.stop("Installation failed."),I.error(A.red(`Failed to install APK: ${i.message}`))}},ml=async(e,t,n)=>{let i=pn();try{if(!te("xcrun simctl list devices booted").toString().includes("(Booted)")){I.warn(A.yellow("No iOS Simulator is currently booted."));let o=te("xcrun simctl list devices --json").toString(),s=JSON.parse(o).devices,l=[];Object.keys(s).forEach(d=>{s[d].forEach(p=>{p.isAvailable&&l.push({...p,runtime:d})})});let a=await ri({message:"Select a simulator to launch:",options:l.map(d=>({value:d.udid,label:`${d.name} (${d.runtime.split(".").pop()})`}))});if(mn(a))return;i.start(`Booting ${a}...`),te(`xcrun simctl boot ${a}`),te(`open -a Simulator --args -CurrentDeviceUDID ${a}`);let c=0,u=!1;for(;c<30;){try{if(te("xcrun simctl list devices booted").toString().includes(a)){u=!0;break}}catch{}await new Promise(d=>setTimeout(d,2e3)),c++}if(!u)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await Be("xcrun",["simctl","install","booted",e],process.cwd(),{},n),i.stop("Installation complete."),I.info(A.blue(`\u{1F680} Launching ${t}...`)),await Be("xcrun",["simctl","launch","booted",t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),I.error(A.red(`Failed to install on Simulator: ${r.message}`))}},gl=async(e,t,n)=>{let i=pn();i.start("Scanning for connected iOS devices...");try{let r=te("xcrun devicectl list devices --json-output -").toString(),s=(JSON.parse(r).result?.devices||[]).filter(a=>a.connectionProperties?.transportType==="wired"||a.connectionProperties?.transportType==="localNetwork");if(s.length===0)throw i.stop("No connected iOS devices found."),new Error("Please connect your iPhone via USB or ensure it is on the same Wi-Fi for wireless debugging.");let l=s[0].identifier;if(s.length>1){i.stop();let a=await ri({message:"Select a device to install on:",options:s.map(c=>({value:c.identifier,label:`${c.deviceProperties?.name||c.name||c.model?.name} (${c.model?.name||"iPhone"}) - ${c.identifier}`}))});if(mn(a))return;l=a,i.start(`Installing on ${l}...`)}else i.message(`Installing on ${s[0].model.name}...`);await Be("xcrun",["devicectl","device","install","app","--device",l,e],process.cwd(),{},n),i.stop("Installation complete."),I.info(A.blue(`\u{1F680} Launching ${t}...`)),await Be("xcrun",["devicectl","device","launch","app","--device",l,t],process.cwd(),{},n)}catch(r){i.stop("Installation failed."),I.error(A.red(`Failed to install on device: ${r.message}`)),I.info(A.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import M from"fs";import _t from"os";import Y from"path";import{spawn as Wr,spawnSync as He}from"child_process";import{randomUUID as hl}from"crypto";import{pipeline as yl}from"stream/promises";import{isCancel as ci,log as B,select as Yr,spinner as Ft,text as Sl}from"@clack/prompts";import Ut from"axios";import W from"chalk";import gn from"adm-zip";async function Jr(e){if(e.localRunner){let n=await wl(e);process.exitCode=n?n.exitCode:1;return}if(e.local){let n=await _l(e);n&&(process.exitCode=n.exitCode);return}let t=await mi(e);if(t&&(B.success(W.green(`Maestro run ${t.status||"queued"}: ${t.testRunId}`)),t.launchDeferredReason&&B.warn(W.yellow(t.launchDeferredReason)),t.dashboardUrl&&B.info(W.dim("View test run: ")+W.white.underline(t.dashboardUrl)),e.wait)){let n=await $l(e,t);n&&(process.exitCode=n.status==="passed"?0:1)}}var bl=new Set(["passed","failed","cancelled","interrupted"]),Br=Number(process.env.MACH_FLOW_UPLOAD_MAX_ATTEMPTS||4),Al=Number(process.env.MACH_FLOW_UPLOAD_TIMEOUT_MS||12e4),qr=process.env.MACH_MAESTRO_FAST_FAIL_RETRY==="1";function pi(e){let t=Array.isArray(e)?e:e?[e]:[];return[...new Set(t.flatMap(n=>String(n||"").split(",")).map(n=>n.trim()).filter(Boolean))]}function El(e){let t=pi(e);if(t.length===0)return;let n={};for(let i of t){let r=process.env[i];r!==void 0&&(n[i]=r)}return Object.keys(n).length>0?n:void 0}function Il(e){let t={};for(let[i,r]of Object.entries(process.env))i.startsWith("MAESTRO_TEST_")&&r!==void 0&&(t[i]=r);let n=pi(e);for(let i of n){let r=process.env[i];r!==void 0&&(t[i]=r)}return t}async function wl(e){let t=e.projectId,n=e.testRunId,i=e.runnerToken||process.env.MACH_RUNNER_TOKEN||process.env.MACH_TOKEN,r=(process.env.MACH_API_URL||bt).replace(/\/$/,""),o=M.mkdtempSync(Y.join(_t.tmpdir(),"mach-maestro-runner-")),s=Y.join(o,"mach-maestro-output"),l=Y.join(o,"runner.log");if(M.mkdirSync(s,{recursive:!0}),!t||!n||!i)return B.error(W.red("--local-runner requires --project-id, --test-run-id, and a runner token.")),{status:"failed",exitCode:1,attempts:0,flows:".maestro",platform:e.platform};let a=null,c=null,u=null,d=f=>{M.appendFileSync(l,`${f}${f.endsWith(`
|
|
1223
1248
|
`)?"":`
|
|
1224
|
-
`}`)},f=async(p,h)=>{try{await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:p,error:h,logPreview:Rl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(D){d(`[WARN] Could not post runner update: ${D.message||D}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let p=await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(p.data?.status!=="success"||!p.data?.payload)throw new Error(p.data?.message||"Runner payload was not returned.");a=p.data.payload;let h=Object.keys(a.env||{});d(`Using Maestro env vars: ${h.length>0?h.join(", "):"none"}`);let D={...process.env,...a.env||{}},N=Pl(a.env);N.length>0&&d(`Passing Maestro env vars to test command: ${h.sort().join(", ")}`),await f("running");let U=a.platform==="android"?"app.apk":"app.zip",R=V.join(o,U),K=V.join(o,"source.zip"),b=V.join(o,"source");M.mkdirSync(b,{recursive:!0}),d("Downloading app artifact..."),await di(a.artifactUrl,R),d(`Downloaded app artifact: ${U} (${Br(M.statSync(R).size)})`),d("Downloading Maestro source..."),await di(a.urls.sourceUrl,K),d(`Downloaded Maestro source: source.zip (${Br(M.statSync(K).size)})`),new pn(K).extractAllTo(b,!0);let W=Dl(b,a.flowPath||".maestro");if(!M.existsSync(W))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${V.relative(b,W)||"."}`),a.platform==="ios"){await kl(a.device||"iphone_15",l);let A=xl(R,o),S=Jr(A,l);d(`Resolved iOS app bundle: ${A}`),d(`Resolved iOS bundle id: ${S||"unknown"}`),Ml(A,l),ci("xcrun",["simctl","install","booted",A],l),S&&(u={platform:a.platform,appId:S}),S&&Qe("xcrun",["simctl","get_app_container","booted",S,"app"],l),oi(s,l,"ios-before-maestro.png"),a.record&&(c=Ll(s,l))}else{let A=Fl(R,l),S=Bl(a.device,l),x=S?["-s",S]:[];d(`Resolved Android application id: ${A||"unknown"}`),ci("adb",[...x,"install","-r",R],l),A&&(u={platform:a.platform,appId:A,deviceId:S||void 0})}let g=Math.max(0,Math.min(10,Number(a.retries??1)))+1,T=V.join(s,"report.xml"),w=Nl(l);if(!w)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let k=1;for(let A=1;A<=g&&(d(`Running Maestro attempt ${A}/${g}...`),k=Qe(w,["test","--platform",a.platform,...N,W,"--format","junit","--output",T,"--test-output-dir",s],l,void 0,D),k!==0);A+=1);return a.platform==="ios"&&oi(s,l,"ios-after-maestro.png"),await Fr(c,l),c=null,await Gr(a.urls,o,s,l),k===0?(await f("passed"),G.success(z.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:g,flows:a.flowPath,platform:a.platform}):(await f("failed",`Maestro exited with code ${k}`),G.error(z.red(`Managed Maestro run failed with exit code ${k}`)),{status:"failed",exitCode:k,attempts:g,flows:a.flowPath,platform:a.platform})}catch(p){let h=p.message||String(p);return d(`MACH_MAESTRO_RUN_FAILED: ${h}`),a?.platform==="ios"&&oi(s,l,"ios-after-failure.png"),await Fr(c,l),a?.urls&&await Gr(a.urls,o,s,l),await f("failed",h),G.error(z.red(`Managed Maestro runner failed: ${h}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Ul(u,l)}}async function Sl(e){let t=e.maestroFlows||".maestro",n=Wr(e.maestroRetries);if(n===null)return null;let i=V.resolve(t);if(!M.existsSync(i))return G.error(z.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await _l(e);if(r?.url){if(!await vl(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&G.warn(z.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=hl(e.maestroEnv),a=Object.keys(l);if(a.length>0){G.info(z.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[p,h]of Object.entries(l))s.push("-e",`${p}=${h}`)}s.push(t);let c=n+1,u=1;for(let p=1;p<=c;p+=1){G.info(z.dim(`Running local Maestro attempt ${p}/${c}...`));let h=He("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(h.error){let D=h.error.message||"Failed to run Maestro";G.error(z.red(`Local Maestro failed to start: ${D}`)),G.info(z.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}if(u=typeof h.status=="number"?h.status:1,u===0)break}let d=u===0?"passed":"failed",f={status:d,exitCode:u,attempts:c,flows:t,platform:o};return Wl(e,f),d==="passed"?G.success(z.green("Local Maestro run passed")):G.error(z.red(`Local Maestro run failed with exit code ${u}`)),f}async function fi(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await Kr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(li(d))return null;r=d}let o=await wl(e);if(!o)return null;if(o.kind==="latest"&&!r)return G.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return G.error("Pass --platform when using --artifact-url."),null;let s=Wr(e.maestroRetries);if(s===null)return null;let l=ui(e.maestroEnv),a=gl(e.maestroEnv);!e.quiet&&l.length>0&&G.info(z.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await El(e,n);if(c===null)return null;let u=Bt();e.quiet||u.start("Queuing Maestro run...");try{let d=await P.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let f=d.data.testRun,p={testRunId:f.testRunId,status:f.status,projectId:n,buildId:f.buildId,platform:f.platform,dashboardUrl:f.dashboardUrl||`${We}/tests/${f.testRunId}`,launchDeferredReason:f.launchDeferredReason};return Xr(e,p),e.quiet||u.stop("Maestro run queued"),p}catch(d){e.quiet||u.stop("Could not queue Maestro run");let f=d.response?.data?.message||d.message||"Unknown error";return G.error(z.red(`Maestro queue failed: ${f}`)),null}}async function bl(e,t){let n=Ur(e.waitTimeout,60,"--wait-timeout"),i=Ur(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(G.info(z.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Il(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,G.info(z.dim(`Maestro status: ${l}`))),pl.has(String(a.status)))return Xr(e,a),a.status==="passed"?G.success(z.green(`Maestro run passed: ${a.testRunId}`)):(G.error(z.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&G.error(z.red(String(a.error)))),a;await pi(o)}return G.error(z.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function El(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=V.resolve(n);if(!M.existsSync(i))return e.maestroFlows?(G.error(z.red(`Maestro flows not found: ${n}`)),null):void 0;let r=V.relative(process.cwd(),i);if(!r||r.startsWith("..")||V.isAbsolute(r))return G.error(z.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Bt();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await P.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:cl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new pn;if(M.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=V.dirname(r);l.addLocalFile(i,u==="."?void 0:u,V.basename(r))}let c=l.toBuffer();return await Al(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return G.error(z.red(`Maestro flow upload failed: ${l}`)),null}}function zr(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function Al(e,t,n,i,r){let o;for(let s=1;s<=Mr;s+=1)try{await Ut.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:ml});return}catch(l){if(o=l,!zr(l)||s>=Mr)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await pi(a)}throw o}async function Il(e,t){try{let n=await P.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${We}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return G.error(z.red(`Could not fetch Maestro run status: ${i}`)),null}}async function wl(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 Kr({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(li(t))return null;if(t==="latest")return{kind:"latest"};let n=await fl({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return li(n)?null:{kind:t,value:String(n).trim()}}function Ur(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(G.error(`${n} must be a positive number.`),null):i}function pi(e){return new Promise(t=>setTimeout(t,e))}function Wr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(G.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function _l(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||gi(e.artifactUrl),name:qr(e.artifactUrl)};let t=e.buildId||zl(e.buildUrl);return t?Yr(t,e.platform):e.latest?$l(e):null}async function Yr(e,t){let n=Bt();n.start(`Resolving build ${e}...`);try{let i=await P.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Vl(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||gi(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return G.error(z.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function $l(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return G.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return G.error("Pass --platform when using --latest with --local."),null;let r=Bt();r.start("Resolving latest build...");try{let o=await P.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Yr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return G.error(z.red(`Latest build lookup failed: ${s}`)),null}}async function vl(e){let t=e.platform||gi(e.url);if(!t)return G.error(z.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=M.mkdtempSync(V.join(_t.tmpdir(),"mach-maestro-")),i=e.name||qr(e.url)||(t==="android"?"app.apk":"app.zip"),r=V.join(n,i),o=Bt();o.start(`Downloading ${i}...`);try{await di(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),G.error(z.red(s.message||"Failed to download artifact")),!1}return t==="android"?Gl(r):Kl(r,n)}async function di(e,t){let n=await Ut.get(e,{responseType:"stream"});await ul(n.data,M.createWriteStream(t))}function Rl(e,t=12e3){try{return M.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function Br(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function Pl(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function Dl(e,t){let n=V.resolve(e,t||".maestro"),i=V.relative(e,n);if(i.startsWith("..")||V.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function Ol(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function Qe(e,t,n,i,r=process.env){M.appendFileSync(n,`
|
|
1225
|
-
$ ${
|
|
1249
|
+
`}`)},p=async(f,h)=>{try{await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner`,{projectId:t,runnerToken:i,status:f,error:h,logPreview:Tl(l),junitUrl:a?.urls?.junitDownloadUrl,logsUrl:a?.urls?.logsDownloadUrl,artifactsUrl:a?.urls?.artifactsDownloadUrl})}catch(S){d(`[WARN] Could not post runner update: ${S.message||S}`)}};try{d(`Mach Maestro local runner starting for ${n}`);let f=await Ut.post(`${r}/internal/tests/${encodeURIComponent(n)}/runner-payload`,{projectId:t,runnerToken:i});if(f.data?.status!=="success"||!f.data?.payload)throw new Error(f.data?.message||"Runner payload was not returned.");a=f.data.payload;let h=Object.keys(a.env||{});d(`Using Maestro env vars: ${h.length>0?h.join(", "):"none"}`);let S={...process.env,...a.env||{}},L=kl(a.env);L.length>0&&d(`Passing Maestro env vars to test command: ${h.sort().join(", ")}`),await p("running");let x=a.platform==="android"?"app.apk":"app.zip",b=Y.join(o,x),U=Y.join(o,"source.zip"),w=Y.join(o,"source");M.mkdirSync(w,{recursive:!0}),d("Downloading app artifact..."),await ui(a.artifactUrl,b),d(`Downloaded app artifact: ${x} (${jr(M.statSync(b).size)})`),d("Downloading Maestro source..."),await ui(a.urls.sourceUrl,U),d(`Downloaded Maestro source: source.zip (${jr(M.statSync(U).size)})`),new gn(U).extractAllTo(w,!0);let z=xl(w,a.flowPath||".maestro");if(!M.existsSync(z))throw new Error(`Maestro flow path not found: ${a.flowPath||".maestro"}`);if(d(`Resolved Maestro flow path: ${Y.relative(w,z)||"."}`),a.platform==="ios"){await Hl(a.device||"iphone_15",l);let C=jl(b,o),g=no(C,l);d(`Resolved iOS app bundle: ${C}`),d(`Resolved iOS bundle id: ${g||"unknown"}`),Kl(C,l),fi("xcrun",["simctl","install","booted",C],l),g&&(u={platform:a.platform,appId:g}),g&&Qe("xcrun",["simctl","get_app_container","booted",g,"app"],l),ai(s,l,"ios-before-maestro.png"),a.record&&(c=Gl(s,l))}else{let C=Wl(b,l),g=zl(a.device,l),k=g?["-s",g]:[];d(`Resolved Android application id: ${C||"unknown"}`),fi("adb",[...k,"install","-r",b],l),C&&(u={platform:a.platform,appId:C,deviceId:g||void 0})}let O=Math.max(0,Math.min(10,Number(a.retries??1)))+1,E=Y.join(s,"report.xml"),D=Fl(l);if(!D)throw new Error("Maestro CLI not found on this runner. Install Maestro or set MAESTRO_BIN to the full maestro path.");let $=1;for(let C=1;C<=O;C+=1){d(`Running Maestro attempt ${C}/${O}...`);let g=["test","--platform",a.platform,...L,z,"--format","junit","--output",E,"--test-output-dir",s];if(qr&&C<O?$=(await to(D,g,{logPath:l,env:S,fastFailOnFlowFailure:!0})).exitCode:$=Qe(D,g,l,void 0,S),$===0)break}return a.platform==="ios"&&ai(s,l,"ios-after-maestro.png"),await Gr(c,l),c=null,await zr(a.urls,o,s,l),$===0?(await p("passed"),B.success(W.green(`Managed Maestro run passed: ${n}`)),{status:"passed",exitCode:0,attempts:O,flows:a.flowPath,platform:a.platform}):(await p("failed",`Maestro exited with code ${$}`),B.error(W.red(`Managed Maestro run failed with exit code ${$}`)),{status:"failed",exitCode:$,attempts:O,flows:a.flowPath,platform:a.platform})}catch(f){let h=f.message||String(f);return d(`MACH_MAESTRO_RUN_FAILED: ${h}`),a?.platform==="ios"&&ai(s,l,"ios-after-failure.png"),await Gr(c,l),a?.urls&&await zr(a.urls,o,s,l),await p("failed",h),B.error(W.red(`Managed Maestro runner failed: ${h}`)),{status:"failed",exitCode:1,attempts:0,flows:a?.flowPath||".maestro",platform:a?.platform||e.platform}}finally{Vl(u,l)}}async function _l(e){let t=e.maestroFlows||".maestro",n=Zr(e.maestroRetries);if(n===null)return null;let i=Y.resolve(t);if(!M.existsSync(i))return B.error(W.red(`Maestro flows not found: ${t}`)),{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};let r=await Dl(e);if(r?.url){if(!await Nl(r))return{status:"failed",exitCode:1,attempts:0,flows:t,platform:r.platform||e.platform}}else if(e.buildId||e.buildUrl||e.artifactUrl||e.latest)return{status:"failed",exitCode:1,attempts:0,flows:t,platform:e.platform};e.maestroRecord&&B.warn(W.yellow("--maestro-record is managed-runner only and is ignored in --local mode."));let o=r?.platform||e.platform,s=["test"];o&&s.push("--platform",o),e.maestroDevice&&s.push("--device",String(e.maestroDevice));let l=Il(e.maestroEnv),a=Object.keys(l);if(a.length>0){B.info(W.dim(`Passing Maestro env vars to local run: ${a.join(", ")}`));for(let[f,h]of Object.entries(l))s.push("-e",`${f}=${h}`)}s.push(t);let c=n+1,u=1;for(let f=1;f<=c;f+=1){if(B.info(W.dim(`Running local Maestro attempt ${f}/${c}...`)),qr&&f<c){let h=await to("maestro",s,{cwd:process.cwd(),env:process.env,echoOutput:!0,fastFailOnFlowFailure:!0});if(h.error){let S=h.error.message||"Failed to run Maestro";B.error(W.red(`Local Maestro failed to start: ${S}`)),B.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=h.exitCode}else{let h=He("maestro",s,{cwd:process.cwd(),stdio:"inherit",env:process.env});if(h.error){let S=h.error.message||"Failed to run Maestro";B.error(W.red(`Local Maestro failed to start: ${S}`)),B.info(W.dim("Install Maestro locally, then retry: https://maestro.mobile.dev/getting-started/installing-maestro")),u=1;break}u=typeof h.status=="number"?h.status:1}if(u===0)break}let d=u===0?"passed":"failed",p={status:d,exitCode:u,attempts:c,flows:t,platform:o};return ed(e,p),d==="passed"?B.success(W.green("Local Maestro run passed")):B.error(W.red(`Local Maestro run failed with exit code ${u}`)),p}async function mi(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return B.error(`No projectId found. Run \`${m.nameLower} link\` first or pass an internal project id.`),null;let r=e.platform;if(!r&&e.latest){let d=await Yr({message:"Select platform for the latest build:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});if(ci(d))return null;r=d}let o=await Ol(e);if(!o)return null;if(o.kind==="latest"&&!r)return B.error("Pass --platform when using --latest."),null;if(o.kind==="artifact-url"&&!r)return B.error("Pass --platform when using --artifact-url."),null;let s=Zr(e.maestroRetries);if(s===null)return null;let l=pi(e.maestroEnv),a=El(e.maestroEnv);!e.quiet&&l.length>0&&B.info(W.dim(`Forwarding Maestro env vars by name: ${l.join(", ")}`));let c=await vl(e,n);if(c===null)return null;let u=Ft();e.quiet||u.start("Queuing Maestro run...");try{let d=await N.post("/tests/maestro",{projectId:n,platform:r,profile:i,latest:o.kind==="latest",buildId:o.kind==="build-id"?o.value:e.buildId,buildUrl:o.kind==="build-url"?o.value:e.buildUrl,artifactUrl:o.kind==="artifact-url"?o.value:e.artifactUrl,flowSourceKey:c,flows:e.maestroFlows||".maestro",device:e.maestroDevice||(r==="ios"?"iphone_15":"pixel_6"),retries:s,record:!!e.maestroRecord,...l.length>0?{envNames:l}:{},...a?{env:a}:{}});if(d.data.status!=="success")throw new Error(d.data.message||"Failed to queue Maestro run");let p=d.data.testRun,f={testRunId:p.testRunId,status:p.status,projectId:n,buildId:p.buildId,platform:p.platform,dashboardUrl:p.dashboardUrl||`${We}/tests/${p.testRunId}`,launchDeferredReason:p.launchDeferredReason};return ro(e,f),e.quiet||u.stop("Maestro run queued"),f}catch(d){e.quiet||u.stop("Could not queue Maestro run");let p=d.response?.data?.message||d.message||"Unknown error";return B.error(W.red(`Maestro queue failed: ${p}`)),null}}async function $l(e,t){let n=Hr(e.waitTimeout,60,"--wait-timeout"),i=Hr(e.waitInterval,15,"--wait-interval");if(n===null||i===null)return null;let r=n*60*1e3,o=Math.max(5,i)*1e3,s=Date.now(),l=t.status||"queued";for(B.info(W.dim(`Waiting for Maestro run ${t.testRunId} to finish...`));Date.now()-s<=r;){let a=await Pl(t.projectId,t.testRunId);if(!a)return null;if(a.status&&a.status!==l&&(l=a.status,B.info(W.dim(`Maestro status: ${l}`))),bl.has(String(a.status)))return ro(e,a),a.status==="passed"?B.success(W.green(`Maestro run passed: ${a.testRunId}`)):(B.error(W.red(`Maestro run ${a.status}: ${a.testRunId}`)),a.error&&B.error(W.red(String(a.error)))),a;await gi(o)}return B.error(W.red(`Timed out waiting for Maestro run ${t.testRunId} after ${n} minute(s).`)),{...t,status:"timeout"}}async function vl(e,t){if(e.maestroUseBuildSource)return;let n=e.maestroFlows||".maestro",i=Y.resolve(n);if(!M.existsSync(i))return e.maestroFlows?(B.error(W.red(`Maestro flows not found: ${n}`)),null):void 0;let r=Y.relative(process.cwd(),i);if(!r||r.startsWith("..")||Y.isAbsolute(r))return B.error(W.red("Managed Maestro flow uploads must be inside the current project directory.")),null;let o=Ft();e.quiet||o.start(`Uploading Maestro flows from ${r}...`);try{let s=await N.post("/tests/maestro/source-upload-url",{projectId:t,uploadId:hl()});if(s.data.status!=="success"||!s.data.uploadUrl||!s.data.key)throw new Error(s.data.message||"Failed to get Maestro flow upload URL");let l=new gn;if(M.statSync(i).isDirectory())l.addLocalFolder(i,r);else{let u=Y.dirname(r);l.addLocalFile(i,u==="."?void 0:u,Y.basename(r))}let c=l.toBuffer();return await Rl(s.data.uploadUrl,c,"application/zip","Maestro flow upload",u=>{e.quiet||o.message(u)}),e.quiet||o.stop("Maestro flows uploaded"),s.data.key}catch(s){e.quiet||o.stop("Could not upload Maestro flows");let l=s.response?.data?.message||s.message||"Unknown error";return B.error(W.red(`Maestro flow upload failed: ${l}`)),null}}function Xr(e){let t=e.response?.status,n=e.code||"",i=e.message||"";return t&&![408,409,425,429].includes(t)&&t<500?!1:/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`)||!t}async function Rl(e,t,n,i,r){let o;for(let s=1;s<=Br;s+=1)try{await Ut.put(e,t,{headers:{"Content-Type":n},maxBodyLength:1/0,maxContentLength:1/0,timeout:Al});return}catch(l){if(o=l,!Xr(l)||s>=Br)break;let a=Math.min(2e4,2e3*s),c=l.code||l.response?.status||l.message||"network error";r?.(`${i} attempt ${s} failed (${c}), retrying...`),await gi(a)}throw o}async function Pl(e,t){try{let n=await N.get(`/tests/${encodeURIComponent(t)}`,{params:{projectId:e}});if(n.data.status!=="success")throw new Error(n.data.message||"Failed to fetch Maestro run");let i=n.data.testRun;return{testRunId:i.testRunId,status:i.status,projectId:e,buildId:i.buildId,platform:i.platform,dashboardUrl:i.dashboardUrl||`${We}/tests/${i.testRunId}`,launchDeferredReason:i.launchDeferredReason,...i.error?{error:i.error}:{}}}catch(n){let i=n.response?.data?.message||n.message||"Unknown error";return B.error(W.red(`Could not fetch Maestro run status: ${i}`)),null}}async function Ol(e){if(e.buildId)return{kind:"build-id",value:e.buildId};if(e.buildUrl)return{kind:"build-url",value:e.buildUrl};if(e.artifactUrl)return{kind:"artifact-url",value:e.artifactUrl};if(e.latest)return{kind:"latest"};let t=await Yr({message:"Select app artifact source for Maestro:",options:[{value:"latest",label:"Latest successful build"},{value:"build-id",label:"Build ID"},{value:"build-url",label:`${m.name} build URL`},{value:"artifact-url",label:"Direct artifact URL"}]});if(ci(t))return null;if(t==="latest")return{kind:"latest"};let n=await Sl({message:t==="build-id"?"Enter build ID:":t==="build-url"?`Enter ${m.name} build URL:`:"Enter artifact URL:",validate:i=>{let r=String(i||"").trim();if(!r)return"Value is required";if((t==="build-url"||t==="artifact-url")&&!r.startsWith("http"))return"Must be a URL"}});return ci(n)?null:{kind:t,value:String(n).trim()}}function Hr(e,t,n){if(e==null||e==="")return t;let i=Number(e);return!Number.isFinite(i)||i<=0?(B.error(`${n} must be a positive number.`),null):i}function gi(e){return new Promise(t=>setTimeout(t,e))}function Zr(e){if(e==null||e==="")return 1;let t=Number(e);return!Number.isInteger(t)||t<0||t>10?(B.error("--maestro-retries must be an integer between 0 and 10."),null):t}async function Dl(e){if(e.artifactUrl)return{url:e.artifactUrl,platform:e.platform||yi(e.artifactUrl),name:io(e.artifactUrl)};let t=e.buildId||Ql(e.buildUrl);return t?Qr(t,e.platform):e.latest?Cl(e):null}async function Qr(e,t){let n=Ft();n.start(`Resolving build ${e}...`);try{let i=await N.get(`/public/builds/${encodeURIComponent(e)}`);if(i.data.status!=="success")throw new Error(i.data.message||"Build lookup failed");let r=t||i.data.build?.platform,o=Zl(i.data.artifacts||[],r);if(!o?.downloadUrl)throw new Error("No installable APK or simulator app artifact found for this build.");return n.stop("Build artifact resolved"),{url:o.downloadUrl,platform:r||yi(o.name||o.downloadUrl),name:o.name}}catch(i){n.stop("Could not resolve build artifact");let r=i.response?.data?.message||i.message||"Unknown error";return B.error(W.red(`Local Maestro artifact lookup failed: ${r}`)),null}}async function Cl(e){let t=$e(`./${m.configFileName}`),n=e.projectId||t?.projectId,i=String(e.profile||e.buildProfile||"production").toLowerCase();if(!n)return B.error(`No projectId found. Run \`${m.nameLower} link\` first or pass --build-id/--artifact-url.`),null;if(!e.platform)return B.error("Pass --platform when using --latest with --local."),null;let r=Ft();r.start("Resolving latest build...");try{let o=await N.get(`/builds/${n}`,{params:{limit:100}}),l=(Array.isArray(o.data.builds)?o.data.builds:[]).find(a=>a.status==="success"&&a.platform===e.platform&&String(a.buildProfile||a.buildType||"production").toLowerCase()===i);if(!l?.buildId)throw new Error(`No successful ${e.platform} build found for profile ${i}.`);return r.stop(`Latest build resolved: ${l.buildId}`),Qr(l.buildId,e.platform)}catch(o){r.stop("Could not resolve latest build");let s=o.response?.data?.message||o.message||"Unknown error";return B.error(W.red(`Latest build lookup failed: ${s}`)),null}}async function Nl(e){let t=e.platform||yi(e.url);if(!t)return B.error(W.red("Could not infer platform for local install. Pass --platform android or --platform ios.")),!1;let n=M.mkdtempSync(Y.join(_t.tmpdir(),"mach-maestro-")),i=e.name||io(e.url)||(t==="android"?"app.apk":"app.zip"),r=Y.join(n,i),o=Ft();o.start(`Downloading ${i}...`);try{await ui(e.url,r),o.stop("Artifact downloaded")}catch(s){return o.stop("Artifact download failed"),B.error(W.red(s.message||"Failed to download artifact")),!1}return t==="android"?ql(r):Xl(r,n)}async function ui(e,t){let n=await Ut.get(e,{responseType:"stream"});await yl(n.data,M.createWriteStream(t))}function Tl(e,t=12e3){try{return M.readFileSync(e,"utf-8").slice(-t)}catch{return""}}function jr(e){if(!Number.isFinite(e)||e<0)return"unknown size";if(e<1024)return`${e} B`;let t=["KB","MB","GB"],n=e/1024,i=t[0];for(let r=1;n>=1024&&r<t.length;r+=1)n/=1024,i=t[r];return`${n.toFixed(n>=10?1:2)} ${i}`}function kl(e){return Object.entries(e||{}).filter(([t,n])=>!!t&&n!==void 0).sort(([t],[n])=>t.localeCompare(n)).flatMap(([t,n])=>["-e",`${t}=${n}`])}function xl(e,t){let n=Y.resolve(e,t||".maestro"),i=Y.relative(e,n);if(i.startsWith("..")||Y.isAbsolute(i))throw new Error("Maestro flow path must stay inside the build source.");return n}function eo(e,t){let n=[e];for(let i=0;i<t.length;i+=1){let r=t[i],o=t[i-1];(o==="-e"||o==="--env")&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(r)?n.push(`${r.slice(0,r.indexOf("="))}=<redacted>`):n.push(r)}return n.join(" ")}function Ml(e){return/\[Failed\]\s+/.test(e)}function Ll(e){if(!e.killed){try{e.kill("SIGTERM")}catch{}setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},5e3).unref()}}function to(e,t,n={}){let{cwd:i,env:r=process.env,logPath:o,echoOutput:s=!1,fastFailOnFlowFailure:l=!1}=n;return o&&M.appendFileSync(o,`
|
|
1250
|
+
$ ${eo(e,t)}
|
|
1251
|
+
`),new Promise(a=>{let c=!1,u=!1,d="",p=S=>{u||(u=!0,a(S))},f=Wr(e,t,{cwd:i,env:r,stdio:["ignore","pipe","pipe"]}),h=S=>{d+=S;let L=d.split(/\r?\n/);d=L.pop()||"";for(let x of L)if(l&&Ml(x)&&!c){c=!0;let b="Mach fast-fail: detected failed Maestro flow; stopping this attempt early to retry...";o&&M.appendFileSync(o,`
|
|
1252
|
+
${b}
|
|
1253
|
+
`),s&&process.stderr.write(`${b}
|
|
1254
|
+
`),Ll(f)}};f.stdout?.on("data",S=>{let L=S.toString();o&&M.appendFileSync(o,L),s&&process.stdout.write(L),h(L)}),f.stderr?.on("data",S=>{let L=S.toString();o&&M.appendFileSync(o,L),s&&process.stderr.write(L),h(L)}),f.on("error",S=>{o&&M.appendFileSync(o,`${S.message}
|
|
1255
|
+
`),p({exitCode:1,fastFailed:c,error:S})}),f.on("close",(S,L)=>{c&&o&&M.appendFileSync(o,`Maestro attempt stopped after first failed flow${L?` (${L})`:""}.
|
|
1256
|
+
`),p({exitCode:typeof S=="number"?S:1,fastFailed:c})})})}function Qe(e,t,n,i,r=process.env){M.appendFileSync(n,`
|
|
1257
|
+
$ ${eo(e,t)}
|
|
1226
1258
|
`);let o=He(e,t,{cwd:i,encoding:"utf-8",env:r});return o.stdout&&M.appendFileSync(n,o.stdout),o.stderr&&M.appendFileSync(n,o.stderr),o.error?(M.appendFileSync(n,`${o.error.message}
|
|
1227
|
-
`),1):typeof o.status=="number"?o.status:1}function
|
|
1228
|
-
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&
|
|
1259
|
+
`),1):typeof o.status=="number"?o.status:1}function fi(e,t,n,i){let r=Qe(e,t,n,i);if(r!==0)throw new Error(`${e} ${t.join(" ")} failed with exit code ${r}`)}function Ul(e){try{return M.accessSync(e,M.constants.X_OK),!0}catch{return!1}}function Fl(e){let t=[process.env.MAESTRO_BIN,Y.join(_t.homedir(),".maestro","bin","maestro"),"/opt/homebrew/bin/maestro","/usr/local/bin/maestro"].filter(Boolean),n=He("/usr/bin/env",["which","maestro"],{encoding:"utf-8",env:process.env}),i=n.status===0?String(n.stdout||"").split(`
|
|
1260
|
+
`)[0]?.trim():"";i&&t.unshift(i);for(let r of t)if(r&&Ul(r))return e&&M.appendFileSync(e,`Using Maestro CLI at ${r}
|
|
1229
1261
|
`),r;return e&&M.appendFileSync(e,`Maestro CLI not found. Checked: ${t.join(", ")}
|
|
1230
|
-
`),null}function
|
|
1231
|
-
`);return}let i=
|
|
1262
|
+
`),null}function Bl(e){let t=String(e||"").trim();return t?t.replace(/_/g," ").replace(/\bios\b/gi,"").replace(/\biphone\b/i,"iPhone").replace(/\s+/g," ").trim():"iPhone 15"}async function Hl(e,t){if((He("xcrun",["simctl","list","devices","booted"],{encoding:"utf-8"}).stdout||"").includes("(Booted)")){M.appendFileSync(t,`Using already booted iOS Simulator.
|
|
1263
|
+
`);return}let i=Bl(e),r=He("xcrun",["simctl","list","devices","--json"],{encoding:"utf-8"});if(r.status!==0||!r.stdout)throw new Error("Could not list iOS simulators.");let o=JSON.parse(r.stdout),s=Object.values(o.devices||{}).flatMap(c=>Array.isArray(c)?c:[]).filter(c=>c?.isAvailable),l=s.find(c=>c.name===i)||s.find(c=>String(c.name||"").toLowerCase().includes(i.toLowerCase()))||s.find(c=>String(c.name||"").startsWith("iPhone"));if(!l?.udid)throw new Error(`No available iOS Simulator found for ${i}.`);M.appendFileSync(t,`Booting iOS Simulator ${l.name} (${l.udid})...
|
|
1232
1264
|
`),Qe("xcrun",["simctl","boot",l.udid],t)!==0&&M.appendFileSync(t,`simctl boot returned non-zero; continuing to bootstatus in case it was already booting.
|
|
1233
|
-
`),
|
|
1265
|
+
`),fi("xcrun",["simctl","bootstatus",l.udid,"-b"],t)}function jl(e,t){if(e.endsWith(".ipa"))throw new Error("iOS Maestro runs need a simulator .app.zip artifact, not an App Store .ipa.");if(e.endsWith(".zip")){let n=Y.join(t,"ios-app");M.mkdirSync(n,{recursive:!0}),new gn(e).extractAllTo(n,!0);let i=hi(n);if(!i)throw new Error("Could not find a .app bundle inside the iOS artifact zip.");return i}if(e.endsWith(".app"))return e;throw new Error("iOS Maestro runs need a .app bundle or .app.zip artifact.")}function no(e,t){let n=Y.join(e,"Info.plist");if(!M.existsSync(n))return M.appendFileSync(t,`Could not find Info.plist in ${e}; skipping uninstall.
|
|
1234
1266
|
`),null;let i=He("/usr/bin/plutil",["-extract","CFBundleIdentifier","raw","-o","-",n],{encoding:"utf-8",env:process.env}),r=String(i.stdout||"").trim();return i.status!==0||!r?(M.appendFileSync(t,`Could not read CFBundleIdentifier from Info.plist; skipping uninstall.
|
|
1235
|
-
`),null):r}function
|
|
1236
|
-
`)}function
|
|
1237
|
-
`);let i=
|
|
1238
|
-
`)}),i}async function
|
|
1267
|
+
`),null):r}function ai(e,t,n){let i=Y.join(e,n);Qe("xcrun",["simctl","io","booted","screenshot",i],t)!==0&&M.appendFileSync(t,`[WARN] Could not capture iOS simulator screenshot: ${n}
|
|
1268
|
+
`)}function Gl(e,t){let n=Y.join(e,"ios-simulator-recording.mp4");M.appendFileSync(t,`Starting iOS simulator recording: ${n}
|
|
1269
|
+
`);let i=Wr("xcrun",["simctl","io","booted","recordVideo",n],{stdio:["ignore","pipe","pipe"],env:process.env});return i.stdout?.on("data",r=>{M.appendFileSync(t,r)}),i.stderr?.on("data",r=>{M.appendFileSync(t,r)}),i.on("error",r=>{M.appendFileSync(t,`[WARN] Could not start iOS simulator recording: ${r.message}
|
|
1270
|
+
`)}),i}async function Gr(e,t){e&&await new Promise(n=>{let i=!1,r=()=>{i||(i=!0,n())};e.once("exit",r),e.once("close",r),e.killed||(M.appendFileSync(t,`Stopping iOS simulator recording...
|
|
1239
1271
|
`),e.kill("SIGINT")),setTimeout(()=>{!i&&!e.killed&&(M.appendFileSync(t,`[WARN] iOS simulator recording did not stop after SIGINT; sending SIGKILL.
|
|
1240
|
-
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function
|
|
1272
|
+
`),e.kill("SIGKILL")),r()},5e3).unref?.()})}function Kl(e,t){let n=no(e,t);if(!n)return;M.appendFileSync(t,`Uninstalling existing iOS app data for ${n} if present...
|
|
1241
1273
|
`),Qe("xcrun",["simctl","uninstall","booted",n],t)!==0&&M.appendFileSync(t,`No existing app install removed for ${n}; continuing.
|
|
1242
|
-
`)}function
|
|
1274
|
+
`)}function Vl(e,t){if(!e?.appId)return;if(M.appendFileSync(t,`Cleaning up installed app after Maestro run...
|
|
1243
1275
|
`),e.platform==="ios"){let r=Qe("xcrun",["simctl","uninstall","booted",e.appId],t);r===0?M.appendFileSync(t,`Uninstalled iOS app ${e.appId} after Maestro run.
|
|
1244
1276
|
`):M.appendFileSync(t,`Warning: failed to uninstall iOS app ${e.appId} after Maestro run: xcrun simctl uninstall exited with code ${r}
|
|
1245
1277
|
`);return}let n=e.deviceId?["-s",e.deviceId]:[],i=Qe("adb",[...n,"uninstall",e.appId],t);i===0?M.appendFileSync(t,`Uninstalled Android app ${e.appId} after Maestro run.
|
|
1246
1278
|
`):M.appendFileSync(t,`Warning: failed to uninstall Android app ${e.appId} after Maestro run: adb uninstall exited with code ${i}
|
|
1247
|
-
`)}function
|
|
1279
|
+
`)}function zl(e,t){let n=He("adb",["devices"],{encoding:"utf-8",env:process.env});if(n.status!==0||n.error)return M.appendFileSync(t,`[WARN] Could not list Android devices before install; using adb default target.
|
|
1248
1280
|
`),null;let i=String(n.stdout||"").split(`
|
|
1249
1281
|
`).map(r=>r.trim().split(/\s+/)).filter(r=>r.length>=2&&r[1]==="device").map(r=>r[0]).filter(Boolean);return e&&i.includes(e)?(M.appendFileSync(t,`Using Android device ${e} for install and cleanup.
|
|
1250
1282
|
`),e):i.length===1?(M.appendFileSync(t,`Using Android device ${i[0]} for install and cleanup.
|
|
1251
1283
|
`),i[0]):(i.length>1&&M.appendFileSync(t,`[WARN] Multiple Android devices are connected; using adb default target for install and cleanup.
|
|
1252
|
-
`),null)}function
|
|
1253
|
-
`),null)}function
|
|
1254
|
-
`)[0]?.trim()||null}async function
|
|
1255
|
-
`)}try{await
|
|
1256
|
-
`)}try{Qe("tar",["-czf",o,"-C",t,
|
|
1257
|
-
`)}}function Gl(e){if(!e.endsWith(".apk"))return G.error(z.red("Local Android Maestro runs need an APK artifact.")),!1;G.info(z.dim("Installing APK on local Android device/emulator..."));let t=He("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(G.error(z.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(G.error(z.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Kl(e,t){if(e.endsWith(".ipa"))return G.error(z.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=V.join(t,"ios-app");M.mkdirSync(r,{recursive:!0}),new pn(e).extractAllTo(r,!0);let o=mi(r);if(!o)return G.error(z.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return G.error(z.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;G.info(z.dim("Installing app on booted iOS Simulator..."));let i=He("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(G.error(z.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(G.error(z.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function mi(e){let t=M.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=V.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=mi(i);if(r)return r}}return null}function Vl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>wt(i,".apk")):n==="ios"?e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip")):e.find(i=>wt(i,".apk"))||e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip"))}function wt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function gi(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function qr(e){if(e)try{return V.basename(new URL(e).pathname)||void 0}catch{return V.basename(e)||void 0}}function zl(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function Xr(e,t){if(!e.jsonOutput)return;let n=V.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=V.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(z.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function Wl(e,t){if(!e.jsonOutput)return;let n=V.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=V.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){G.warn(z.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as st,text as Ft,select as Ei,isCancel as rt,cancel as Ai,log as ro}from"@clack/prompts";import te from"chalk";import se from"fs";import Ie from"path";import{spawn as Yl,spawnSync as mt}from"child_process";import oo from"axios";import ht from"os";import _i from"crypto";var Jl=5e3,ql=12,so=100,hi=24,Zr=8e3,Xl={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},Zl=e=>e?.type==="google_service_account",gn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,ao=e=>e.submitArgs||process.argv.slice(3).join(" ");async function hn(e){let t=st(),n=Pe(),i=Ql(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,fe(te.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let S=await Ei({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(rt(S)){Ai("Operation cancelled");return}s=S}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?gd(i,o,e):null;if(s==="ios"&&!e.local&&!l){await ed(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(S,x={})=>{u&&await rd(r,u,{status:S,...x})},f=s==="android"?e.packageName||e.androidPackage||fd(i,o):void 0,p=s==="ios"?e.bundleId||e.iosBundleIdentifier||md(i,o):void 0,h,D,N,U=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",D=hd(i,o,e.releaseStatus),N=Sd(i,o,e.rollout),U=bd(i,o,e.changesNotSentForReview),Ed(D,N))}catch(S){le(S.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await td(i,r,s,o,e,{packageName:f,track:h,releaseStatus:D,rollout:N,changesNotSentForReview:U}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:f,track:h,releaseStatus:D,rollout:N,startTime:Date.now(),...c?sd():{}});let R=null,K=null;try{K=await Ad(r,s,e,n?.token),R=K?.filePath||null}catch(S){await d("failed",{error:`Failed to resolve submission artifact: ${S.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${S.message}`),process.exitCode=1;return}if(!R){let S=wd(s,e);await d("failed",{error:S,endTime:Date.now()}),le(S),process.exitCode=1;return}await d("running",{buildId:K?.buildId,artifactName:K?.artifactName,artifactSource:K?.source}),fe(`Using artifact: ${te.green(Ie.basename(R))} `),t.start("Fetching submission credentials from Dashboard...");let b;try{let x=(await P.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!f){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let B=x.filter(Zl),Y=s==="ios"?x.filter(L=>L.type==="asc_api_key"):pd(B,f);if(Y.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${f}.`:`No Service Credentials found for ${s}.`),s==="android"){let L=B.map(gn).filter(Boolean).join(", ");L&&fe(`Found Google Play service credential(s) for: ${L}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${f}' or upload it under that package in the Dashboard.`)}else fe(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(b=ld(Y,e.credentialId),!b&&s==="ios"&&p&&(b=dd(Y,p)),b||Y.length===1)b=b||Y[0],t.stop(`Using: ${b.name}`),s==="android"&&gn(b)==="*"&&fe(te.yellow(`Using legacy wildcard Google Play credential for ${f}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),cd()){let J=Y.map(O=>`${O.name||"credential"} (${O.credentialId||O.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${J}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let L=await Ei({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:Y.map(J=>({value:J.credentialId,label:J.name,hint:`${J.keyId?`ID: ${J.keyId}`:""} ${J.issuerId?`(Issuer: ${J.issuerId.substring(0,8)}...)`:""}`}))});if(rt(L)){Ai("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}b=Y.find(J=>J.credentialId===L),fe(`Using selected: ${te.green(b.name)}`)}}catch(S){t.stop("Failed to fetch credentials"),le(`API Error: ${S.message} `),await d("failed",{error:`Failed to fetch credentials: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}let W=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-submit-`)),ne=b.keyId||b.meta?.keyId,g=b.issuerId||b.meta?.issuerId,T=b.type==="asc_api_key"?`AuthKey_${ne}.p8`:"service-account.json",w=Ie.join(W,T);t.start("Downloading secure key...");try{let S=await P.get(`/credentials/${b.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(S.data.status!=="success"||!S.data.downloadUrl)throw new Error("Failed to get secure download URL");let x=await oo.get(S.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(w,Buffer.from(x.data)),t.stop("Key downloaded to secure temp storage")}catch(S){t.stop("Download failed"),le(`Failed to download key: ${S.message}`);try{se.rmSync(W,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${S.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(te.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let k=!1,A;try{if(s==="ios"){if(!ne){let x=await Ft({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:B=>B.length>0?void 0:"Key ID is required"});if(rt(x)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}ne=x}if(!g||g==="undefined"){let x=await Ft({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:B=>B.length>0?void 0:"Issuer ID is required"});if(rt(x)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}g=x}fe(`Using ASC Key ID: ${ne}`),fe(`Using ASC Issuer ID: ${g}`);let S=l?await $d(R,w,g,ne,p,l):await _d(R,w,g,ne,p);wi(`${s==="ios"?"App Store":"Google Play"} submission successful!`),k=!0}else A=await Od(R,w,h||"internal",f,D||"completed",N,U,o),wi("Google Play submission successful!"),k=!0}catch(S){le(`Submission failed: ${S.message}`),await d("failed",{error:S.message,endTime:Date.now()}),ot(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:K?.buildId||e.buildId,artifactName:K?.artifactName,error:S.message,dashboardUrl:u?gt(u,r):void 0}),process.exitCode=1}finally{k&&(await d("success",{endTime:Date.now(),versionCode:A?.versionCode,track:h,releaseStatus:D}),ot(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:K?.buildId||e.buildId,artifactName:K?.artifactName,versionCode:A?.versionCode,track:h,releaseStatus:D,dashboardUrl:u?gt(u,r):void 0})),Vd(W),R&&R.includes(`${m.nameLower}-artifact-`)}}function Ql(e){let t=`./${m.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function ed(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||_i.randomUUID(),o=!!n.latest||!n.buildId,s=nd({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:ao(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(ud).join(" "),appName:e.name,startTime:Date.now()},a=st();a.start("Queuing iOS submit on macOS runner...");try{let c=await P.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||gt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${te.cyan(r)}`),fe(`Dashboard: ${te.blue.underline(d)}`),ot(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await id(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(ad(c)),process.exitCode=1}}async function td(e,t,n,i,r,o={}){let s=r.submitId||_i.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:ao(r),appName:e.name,startTime:Date.now(),...o};try{let c=await P.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||gt(s,t);return fe(`Submission ID: ${te.cyan(s)}`),fe(`Dashboard: ${te.blue.underline(d)}`),ot(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return fe(te.yellow(`Could not create submission tracking record: ${u}`)),null}}function nd(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function id(e,t,n){let i=st(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await P.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(te.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),wi("App Store submission successful!"),ot(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||gt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ot(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||gt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await Ii(Jl)}catch(s){if(r++,r>=ql){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await Ii(Math.min(2e3*r,15e3))}}async function rd(e,t,n){let i;for(let r=1;r<=3;r++)try{await P.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!od(o))break;await Ii(1e3*r)}ro.warn(te.dim(`Could not report submission status: ${i?.message||i}`))}function od(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function sd(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function ad(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1258
|
-
`):n||e.message||String(e)}function gt(e,t){if(!e)return We;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${n}`}function ot(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||gt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&se.mkdirSync(r,{recursive:!0}),se.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){ro.warn(te.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function ld(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function dd(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function cd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function Ii(e){return new Promise(t=>setTimeout(t,e))}function ud(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function fd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=nr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(se.existsSync(i))try{return JSON.parse(se.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(se.existsSync(r))try{let o=JSON.parse(se.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function pd(e,t){let n=e.filter(o=>gn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=gn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function md(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:ir(e,t)}function gd(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function hd(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return yd(i)}function yd(e){let t=Xl[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function Sd(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function bd(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function Ed(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 Ad(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=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(rt(s))return Ai("Operation cancelled"),null;r=s}if(r==="local"){let s=await Ft({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!se.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 rt(s)?null:{filePath:s,source:"local"}}let o=st();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await P.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success",d=b=>c?[b.buildProfile,b.profile,b.profileName,b.buildType].filter(Boolean).some(W=>String(W).toLowerCase()===c):!0,f=a.filter(b=>u(b)&&d(b)),p=f.find(b=>b.buildType?.toLowerCase()==="store"||b.distribution?.toLowerCase()==="store")||f[0],h=a.some(b=>b.platform?.toLowerCase()===t.toLowerCase()&&b.status?.toLowerCase()==="success");if(!p)return o.stop("No suitable build found"),le(s&&h?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${p.buildId}`);let D=p.artifacts||[];if(D.length===0||D.every(b=>!(b.url||b.downloadUrl)))try{let b=await P.get(`/builds/${e}/${p.buildId}/artifacts`);b.data.status==="success"&&b.data.artifacts?.length>0?(D=b.data.artifacts.map(W=>({...W,url:W.url||W.downloadUrl})),console.log(te.cyan(` [RECOVERY] Fetched ${D.length} artifact(s) with download URLs.`))):console.log(te.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(b){console.log(te.red(` [RECOVERY] /artifacts fetch failed: ${b.message}`))}let U=t==="ios",R=D.find(b=>{let W=(b.type||"").toLowerCase(),ne=(b.name||"").toLowerCase();if(console.log(te.dim(` - Checking: ${b.name} (Type: ${b.type}, HasLink: ${!!(b.url||b.downloadUrl)})`)),W)return W===(U?"ipa":"aab");let g=U?".ipa":".aab",T=(b.url||b.downloadUrl||"").toLowerCase();return ne.endsWith(g)||T.includes(g)});if(!R||!(R.url||R.downloadUrl))return le("Build found but artifact URL is missing."),null;let K=R.url||R.downloadUrl;return{filePath:await yi(K,U?"ios":"android"),buildId:p.buildId,artifactName:R.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Ft({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(rt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let p=await P.get(`/builds/${e}/${l}`);p.data.status==="success"&&(a=p.data.build)}catch(p){p.response?.status!==404&&console.log(te.dim(` [RECOVERY] Project build lookup skipped: ${p.message}`))}if(!a){let p=await P.get(`/build/${l}`);if(p.data.status!=="success")throw new Error(p.data.message);a=p.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=mn(a.artifacts);Id(u)||(u=await eo(e,l,u));let d=Qr(u,t);if(d||(u=await eo(e,l,u),d=Qr(u,t)),!d)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let f=d.url||d.downloadUrl;if(!f)throw new Error(`Artifact ${d.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await yi(f,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Ft({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return rt(s)?null:{filePath:await yi(s,t),source:"url"}}return null}function mn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Id(e){return e.some(t=>!!(t.url||t.downloadUrl))}function Qr(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function wd(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function eo(e,t,n){try{let i=await P.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=mn(i.data.artifacts);return console.log(te.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(te.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await P.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=mn(i.data.artifacts);return console.log(te.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(te.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return mn(n)}async function yi(e,t,n=3){let i=st();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=se.createWriteStream(s),c=await oo({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let f=!1;c.data.on("error",p=>{f||(f=!0,a.close(),d(p))}),a.on("finish",()=>{f||u()}),a.on("error",p=>{f||(f=!0,d(p))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function _d(e,t,n,i,r){let o=st();if(r&&fe(`Bundle ID: ${te.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=lo(t,n,i),l=Nd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=kd(),d=Yl(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});d.stdout?.on("data",f=>u.append(f,process.stdout)),d.stderr?.on("data",f=>u.append(f,process.stderr)),d.on("close",f=>{if(u.flush(),f!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}c(xd(f,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),d.on("error",f=>{u.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let p=Gd(f);p.logs=u.lines(),c(p)})})}async function $d(e,t,n,i,r,o){let s=st();if(r&&fe(`Bundle ID: ${te.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=lo(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=vd(o),u=Rd(o),d="",f="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=Pd("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Si("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Si("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),f=Ie.join(ht.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(f,Dd(d)),Si("scp",[...u,f,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let p=`chmod +x ${Ht(`${d}/submit.sh`)} && bash ${Ht(`${d}/submit.sh`)}`,h=mt("ssh",[...c,p],{stdio:"inherit"});if(h.error)throw $i("ssh",h.error);if(h.status!==0)throw new Error(`Remote iOS submit failed with exit code ${h.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(p){throw s.stop("Remote iOS submit failed"),p}finally{try{se.unlinkSync(l)}catch{}if(f)try{se.unlinkSync(f)}catch{}if(d)try{mt("ssh",[...c,`rm -rf ${Ht(d)}`],{stdio:"ignore"})}catch{}}}function lo(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=_i.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1284
|
+
`),null)}function Wl(e,t){let i=(li("aapt",["dump","badging",e])||li("aapt2",["dump","badging",e]))?.match(/package:\s+name='([^']+)'/);if(i?.[1])return i[1];let o=li("apkanalyzer",["manifest","application-id",e])?.split(/\s+/).find(Boolean);return o||(M.appendFileSync(t,`[WARN] Could not determine Android application id from APK; post-run uninstall will be skipped.
|
|
1285
|
+
`),null)}function li(e,t){for(let n of Yl(e)){let i=He(n,t,{encoding:"utf-8",env:process.env,maxBuffer:10485760});if(i.status===0&&i.stdout)return String(i.stdout).trim()}return null}function Yl(e){let t=process.platform==="win32"&&!e.endsWith(".exe")?`${e}.exe`:e,n=[];if(e==="aapt"||e==="aapt2")for(let r of Kr()){let o=Y.join(r,"build-tools");for(let s of Vr(o))n.push(Y.join(o,s,t))}if(e==="apkanalyzer")for(let r of Kr()){n.push(Y.join(r,"cmdline-tools","latest","bin",t));let o=Y.join(r,"cmdline-tools");for(let s of Vr(o))n.push(Y.join(o,s,"bin",t));n.push(Y.join(r,"tools","bin",t))}let i=Jl(e);return i&&n.unshift(i),n.push(t),[...new Set(n)]}function Kr(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];return process.platform==="darwin"?e.push(Y.join(_t.homedir(),"Library","Android","sdk")):process.platform==="linux"&&e.push(Y.join(_t.homedir(),"Android","Sdk"),Y.join(_t.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk"),[...new Set(e.filter(t=>!!t))]}function Vr(e){try{return M.readdirSync(e,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>n.localeCompare(t,void 0,{numeric:!0}))}catch{return[]}}function Jl(e){let t=process.platform==="win32"?"where":"/usr/bin/env",n=process.platform==="win32"?[e]:["which",e],i=He(t,n,{encoding:"utf-8",env:process.env});return i.status!==0||!i.stdout?null:String(i.stdout).split(`
|
|
1286
|
+
`)[0]?.trim()||null}async function di(e,t,n){if(!M.existsSync(e))return;let i=M.readFileSync(e),r;for(let o=1;o<=3;o+=1)try{await Ut.put(t,i,{headers:{"Content-Type":n,"Content-Length":String(i.length)},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4});return}catch(s){if(r=s,!Xr(s)||o>=3)break;await gi(2e3*o)}throw r}async function zr(e,t,n,i){let r=Y.join(n,"report.xml"),o=Y.join(t,"artifacts.tar.gz");try{await di(r,e.junitUploadUrl,"application/xml")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload JUnit report: ${s.message||s}
|
|
1287
|
+
`)}try{await di(i,e.logUploadUrl,"text/plain")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload runner log: ${s.message||s}
|
|
1288
|
+
`)}try{Qe("tar",["-czf",o,"-C",t,Y.basename(n)],i),await di(o,e.artifactsUploadUrl,"application/gzip")}catch(s){M.appendFileSync(i,`[WARN] Failed to upload Maestro artifacts: ${s.message||s}
|
|
1289
|
+
`)}}function ql(e){if(!e.endsWith(".apk"))return B.error(W.red("Local Android Maestro runs need an APK artifact.")),!1;B.info(W.dim("Installing APK on local Android device/emulator..."));let t=He("adb",["install","-r",e],{stdio:"inherit",env:process.env});return t.error?(B.error(W.red(`adb failed to start: ${t.error.message}`)),!1):t.status!==0?(B.error(W.red(`adb install failed with exit code ${t.status??1}`)),!1):!0}function Xl(e,t){if(e.endsWith(".ipa"))return B.error(W.red("Local iOS Maestro runs need an iOS Simulator .app.zip artifact, not an App Store .ipa.")),!1;let n=e;if(e.endsWith(".zip")){let r=Y.join(t,"ios-app");M.mkdirSync(r,{recursive:!0}),new gn(e).extractAllTo(r,!0);let o=hi(r);if(!o)return B.error(W.red("Could not find a .app bundle inside the downloaded zip.")),!1;n=o}if(!n.endsWith(".app"))return B.error(W.red("Local iOS Maestro runs need an iOS Simulator .app bundle or .app.zip artifact.")),!1;B.info(W.dim("Installing app on booted iOS Simulator..."));let i=He("xcrun",["simctl","install","booted",n],{stdio:"inherit",env:process.env});return i.error?(B.error(W.red(`xcrun failed to start: ${i.error.message}`)),!1):i.status!==0?(B.error(W.red(`iOS Simulator install failed with exit code ${i.status??1}`)),!1):!0}function hi(e){let t=M.readdirSync(e,{withFileTypes:!0});for(let n of t){let i=Y.join(e,n.name);if(n.isDirectory()&&n.name.endsWith(".app"))return i;if(n.isDirectory()){let r=hi(i);if(r)return r}}return null}function Zl(e,t){let n=String(t||"").toLowerCase();return n==="android"?e.find(i=>wt(i,".apk")):n==="ios"?e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip")):e.find(i=>wt(i,".apk"))||e.find(i=>wt(i,".app.zip"))||e.find(i=>wt(i,".zip"))}function wt(e,t){return String(e?.name||e?.downloadUrl||e?.url||"").toLowerCase().endsWith(t)}function yi(e){let t=String(e||"").toLowerCase();if(t.includes(".apk"))return"android";if(t.includes(".app.zip")||t.endsWith(".app")||t.includes(".ipa"))return"ios"}function io(e){if(e)try{return Y.basename(new URL(e).pathname)||void 0}catch{return Y.basename(e)||void 0}}function Ql(e){return e?e.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)?.[0]:void 0}function ro(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){B.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}function ed(e,t){if(!e.jsonOutput)return;let n=Y.resolve(e.jsonOutput),i={mode:"local",...t,updatedAt:new Date().toISOString()};try{let r=Y.dirname(n);r&&r!=="."&&M.mkdirSync(r,{recursive:!0}),M.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){B.warn(W.yellow(`Could not write Maestro metadata JSON: ${r.message}`))}}import{spinner as st,text as Bt,select as Ii,isCancel as rt,cancel as wi,log as fo}from"@clack/prompts";import ne from"chalk";import se from"fs";import Ie from"path";import{spawn as td,spawnSync as mt}from"child_process";import po from"axios";import ht from"os";import vi from"crypto";var nd=5e3,id=12,mo=100,Si=24,oo=8e3,rd={completed:"completed",draft:"draft",halted:"halted",inprogress:"inProgress","in-progress":"inProgress"},od=e=>e?.type==="google_service_account",yn=e=>e?.bundleId||e?.packageName||e?.meta?.packageName||e?.meta?.bundleId,go=e=>e.submitArgs||process.argv.slice(3).join(" ");async function Sn(e){let t=st(),n=Pe(),i=sd(e);if(!i){process.exitCode=1;return}let r=e.projectId||i.projectId,o=e.profile||e.buildProfile||"production";if(!r){le(`${m.configFileName} is missing projectId. Pass --project-id in runner mode.`),process.exitCode=1;return}i.projectId=r,fe(ne.dim(`Submit for project: ${i.name||r} | Profile: ${o}`));let s=e.platform;if(!s){let g=await Ii({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(rt(g)){wi("Operation cancelled");return}s=g}if(s=String(s).toLowerCase(),s!=="ios"&&s!=="android"){le(`Platform ${s} is not supported. Use 'ios' or 'android'.`),process.exitCode=1;return}let l=s==="ios"&&!e.local&&e.sshHost?Id(i,o,e):null;if(s==="ios"&&!e.local&&!l){await ad(i,o,e);return}let a=e.submitId,c=!!(e.local&&a),u=a||null,d=async(g,k={})=>{u&&await ud(r,u,{status:g,...k})},p=s==="android"?e.packageName||e.androidPackage||bd(i,o):void 0,f=s==="ios"?e.bundleId||e.iosBundleIdentifier||Ed(i,o):void 0,h,S,L,x=!1;try{s==="android"&&(h=e.track||i.submit?.[o]?.android?.track||i.submit?.production?.android?.track||"internal",S=wd(i,o,e.releaseStatus),L=$d(i,o,e.rollout),x=vd(i,o,e.changesNotSentForReview),Rd(S,L))}catch(g){le(g.message),process.exitCode=1;return}if(s==="android"&&!c&&(u=await ld(i,r,s,o,e,{packageName:p,track:h,releaseStatus:S,rollout:L,changesNotSentForReview:x}),!u)){le("Could not create submission tracking record. Submission was not started."),process.exitCode=1;return}await d("running",{platform:s,profile:o,packageName:p,track:h,releaseStatus:S,rollout:L,startTime:Date.now(),...c?pd():{}});let b=null,U=null;try{U=await Pd(r,s,e,n?.token),b=U?.filePath||null}catch(g){await d("failed",{error:`Failed to resolve submission artifact: ${g.message}`,endTime:Date.now()}),le(`Failed to resolve submission artifact: ${g.message}`),process.exitCode=1;return}if(!b){let g=Dd(s,e);await d("failed",{error:g,endTime:Date.now()}),le(g),process.exitCode=1;return}await d("running",{buildId:U?.buildId,artifactName:U?.artifactName,artifactSource:U?.source}),fe(`Using artifact: ${ne.green(Ie.basename(b))} `),t.start("Fetching submission credentials from Dashboard...");let w;try{let k=(await N.get(`/credentials/${r}`)).data.credentials||[];if(s==="android"&&!p){t.stop("Package name missing"),le("Could not resolve Android package name. Set android.package in mach.config.json/app.json."),await d("failed",{error:"Could not resolve Android package name.",endTime:Date.now()}),process.exitCode=1;return}let F=k.filter(od),V=s==="ios"?k.filter(J=>J.type==="asc_api_key"):Ad(F,p);if(V.length===0){if(t.stop("Credentials missing"),le(s==="android"?`No Google Play service credential found for package ${p}.`:`No Service Credentials found for ${s}.`),s==="android"){let J=F.map(yn).filter(Boolean).join(", ");J&&fe(`Found Google Play service credential(s) for: ${J}`),fe(`Use '${m.nameLower} credentials:service --platform android --package-name ${p}' or upload it under that package in the Dashboard.`)}else fe(`Use '${m.nameLower} credentials:service --platform ${s}' or use the Dashboard to upload them.`);await d("failed",{error:`No submission credentials found for ${s}.`,endTime:Date.now()}),process.exitCode=1;return}if(w=gd(V,e.credentialId),!w&&s==="ios"&&f&&(w=hd(V,f)),w||V.length===1)w=w||V[0],t.stop(`Using: ${w.name}`),s==="android"&&yn(w)==="*"&&fe(ne.yellow(`Using legacy wildcard Google Play credential for ${p}. Upload a package-scoped credential when possible.`));else{if(t.stop("Multiple credentials found"),yd()){let H=V.map(P=>`${P.name||"credential"} (${P.credentialId||P.id||"no-id"})`).join(", ");le(`Multiple ${s==="ios"?"App Store Connect":"Google Play"} credentials found. Use --credential-id in CI. Available: ${H}`),await d("failed",{error:"Multiple submission credentials found; --credential-id is required in CI.",endTime:Date.now()}),process.exitCode=1;return}let J=await Ii({message:`Choose a ${s==="ios"?"App Store Connect":"Google Play"} credential:`,options:V.map(H=>({value:H.credentialId,label:H.name,hint:`${H.keyId?`ID: ${H.keyId}`:""} ${H.issuerId?`(Issuer: ${H.issuerId.substring(0,8)}...)`:""}`}))});if(rt(J)){wi("Submission cancelled"),await d("failed",{error:"Submission cancelled while selecting credential.",endTime:Date.now()}),process.exitCode=1;return}w=V.find(H=>H.credentialId===J),fe(`Using selected: ${ne.green(w.name)}`)}}catch(g){t.stop("Failed to fetch credentials"),le(`API Error: ${g.message} `),await d("failed",{error:`Failed to fetch credentials: ${g.message}`,endTime:Date.now()}),process.exitCode=1;return}let z=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-submit-`)),Q=w.keyId||w.meta?.keyId,O=w.issuerId||w.meta?.issuerId,E=w.type==="asc_api_key"?`AuthKey_${Q}.p8`:"service-account.json",D=Ie.join(z,E);t.start("Downloading secure key...");try{let g=await N.get(`/credentials/${w.credentialId}/download`,{params:{projectId:r,format:"raw"}});if(g.data.status!=="success"||!g.data.downloadUrl)throw new Error("Failed to get secure download URL");let k=await po.get(g.data.downloadUrl,{responseType:"arraybuffer"});se.writeFileSync(D,Buffer.from(k.data)),t.stop("Key downloaded to secure temp storage")}catch(g){t.stop("Download failed"),le(`Failed to download key: ${g.message}`);try{se.rmSync(z,{recursive:!0,force:!0})}catch{}await d("failed",{error:`Failed to download credential key: ${g.message}`,endTime:Date.now()}),process.exitCode=1;return}fe(ne.blue(`Initiating ${s==="ios"?"TestFlight":"Google Play"} submission...`));let $=!1,C;try{if(s==="ios"){if(!Q){let k=await Bt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:F=>F.length>0?void 0:"Key ID is required"});if(rt(k)){await d("failed",{error:"Submission cancelled while entering ASC Key ID.",endTime:Date.now()}),process.exitCode=1;return}Q=k}if(!O||O==="undefined"){let k=await Bt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:F=>F.length>0?void 0:"Issuer ID is required"});if(rt(k)){await d("failed",{error:"Submission cancelled while entering ASC Issuer ID.",endTime:Date.now()}),process.exitCode=1;return}O=k}fe(`Using ASC Key ID: ${Q}`),fe(`Using ASC Issuer ID: ${O}`);let g=l?await Nd(b,D,O,Q,f,l):await Cd(b,D,O,Q,f);$i(`${s==="ios"?"App Store":"Google Play"} submission successful!`),$=!0}else C=await Ld(b,D,h||"internal",p,S||"completed",L,x,o),$i("Google Play submission successful!"),$=!0}catch(g){le(`Submission failed: ${g.message}`),await d("failed",{error:g.message,endTime:Date.now()}),ot(e,{status:"failed",projectId:r,submitId:u,platform:s,profile:o,buildId:U?.buildId||e.buildId,artifactName:U?.artifactName,error:g.message,dashboardUrl:u?gt(u,r):void 0}),process.exitCode=1}finally{$&&(await d("success",{endTime:Date.now(),versionCode:C?.versionCode,track:h,releaseStatus:S}),ot(e,{status:"success",projectId:r,submitId:u,platform:s,profile:o,buildId:U?.buildId||e.buildId,artifactName:U?.artifactName,versionCode:C?.versionCode,track:h,releaseStatus:S,dashboardUrl:u?gt(u,r):void 0})),Zd(z),b&&b.includes(`${m.nameLower}-artifact-`)}}function sd(e){let t=`./${m.configFileName}`;if(se.existsSync(t))try{return JSON.parse(se.readFileSync(t,"utf-8"))}catch(n){return le(`Failed to read ${m.configFileName}: ${n.message}`),null}return e.projectId?{projectId:e.projectId}:(le(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`),null)}async function ad(e,t,n){let i=n.projectId||e.projectId;if(!i){le(`${m.configFileName} is missing projectId.`),process.exitCode=1;return}let r=n.submitId||vi.randomUUID(),o=!!n.latest||!n.buildId,s=dd({...n,latest:o,profile:t,projectId:i,submitId:r}),l={projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,credentialId:n.credentialId,status:"pending",source:"cli",submitArgs:go(n),runnerArgs:s,runnerCommand:[m.nameLower,"submit",...s].map(Sd).join(" "),appName:e.name,startTime:Date.now()},a=st();a.start("Queuing iOS submit on macOS runner...");try{let c=await N.post("/submissions",l),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||gt(r,i);a.stop("iOS submit queued"),fe(`Submission ID: ${ne.cyan(r)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),ot(n,{status:"pending",projectId:i,submitId:r,platform:"ios",profile:t,latest:o,buildId:n.buildId,dashboardUrl:d}),await cd(i,r,n)}catch(c){a.stop("Could not queue iOS submit"),le(md(c)),process.exitCode=1}}async function ld(e,t,n,i,r,o={}){let s=r.submitId||vi.randomUUID(),l=!!r.latest||!r.buildId,a={projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,credentialId:r.credentialId,status:"running",source:"cli-direct",submitArgs:go(r),appName:e.name,startTime:Date.now(),...o};try{let c=await N.post("/submissions",a),u=c.data?.submission||c.data?.submit||{},d=c.data?.dashboardUrl||u.dashboardUrl||gt(s,t);return fe(`Submission ID: ${ne.cyan(s)}`),fe(`Dashboard: ${ne.blue.underline(d)}`),ot(r,{status:"running",projectId:t,submitId:s,platform:n,profile:i,latest:l,buildId:r.buildId,dashboardUrl:d}),s}catch(c){let u=c.response?.data?.message||c.response?.data?.error||c.message;return fe(ne.yellow(`Could not create submission tracking record: ${u}`)),null}}function dd(e){let t=["--local","--submit-id",e.submitId,"--project-id",e.projectId,"--platform","ios","--profile",e.profile||"production"];return e.buildId?t.push("--build-id",e.buildId):t.push("--latest"),e.credentialId&&t.push("--credential-id",e.credentialId),e.bundleId&&t.push("--bundle-id",e.bundleId),e.packageName&&t.push("--package-name",e.packageName),e.quiet&&t.push("--quiet"),e.jsonOutput&&t.push("--json-output",e.jsonOutput),t.filter(n=>n!=null&&n!=="")}async function cd(e,t,n){let i=st(),r=0,o=0;for(n.quiet||i.start("Waiting for iOS submit runner...");;)try{let s=await N.get(`/submissions/${e}/${t}`),l=s.data?.submission||s.data?.submit||s.data,a=String(l?.status||"pending").toLowerCase();r=0;let c=Array.isArray(l?.logs)?l.logs:[];for(let u=o;u<c.length;u++){let d=c[u];d&&console.log(ne.dim(String(d)))}if(o=c.length,["success","completed","succeeded"].includes(a)){n.quiet||i.stop("iOS submit completed"),$i("App Store submission successful!"),ot(n,{status:"success",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,dashboardUrl:l?.dashboardUrl||gt(t,e)});return}if(["failed","error","cancelled","canceled"].includes(a)){n.quiet||i.stop("iOS submit failed");let u=l?.error||l?.message||"Unknown iOS submit failure.";le(u),ot(n,{status:"failed",projectId:e,submitId:t,platform:"ios",profile:l?.profile||n.profile||"production",buildId:l?.buildId||n.buildId,artifactName:l?.artifactName,error:u,dashboardUrl:l?.dashboardUrl||gt(t,e)}),process.exitCode=1;return}n.quiet||i.message(`iOS submit ${a}...`),await _i(nd)}catch(s){if(r++,r>=id){n.quiet||i.stop("Lost connection to iOS submit status"),le(`Could not fetch iOS submit status after ${r} attempts: ${s.message}`),process.exitCode=1;return}await _i(Math.min(2e3*r,15e3))}}async function ud(e,t,n){let i;for(let r=1;r<=3;r++)try{await N.patch(`/submissions/${e}/${t}`,n);return}catch(o){if(i=o,r>=3||!fd(o))break;await _i(1e3*r)}fo.warn(ne.dim(`Could not report submission status: ${i?.message||i}`))}function fd(e){let t=e.response?.status;return!t||t===408||t===409||t===425||t===429||t>=500}function pd(){let e={gitlabJobId:process.env.CI_JOB_ID,gitlabJobUrl:process.env.CI_JOB_URL,gitlabPipelineId:process.env.CI_PIPELINE_ID,gitlabProjectId:process.env.CI_PROJECT_ID,gitlabProjectPath:process.env.CI_PROJECT_PATH};return Object.fromEntries(Object.entries(e).filter(([,t])=>!!t))}function md(e){let t=e.response?.status,n=e.response?.data?.message||e.response?.data?.error;return t===404||t===405?["Managed iOS submit is not enabled on this Mach API yet.","Deploy the API/dashboard submission orchestration endpoint, then retry the same command.","Expected API: POST /submissions and GET/PATCH /submissions/:projectId/:submitId."].join(`
|
|
1290
|
+
`):n||e.message||String(e)}function gt(e,t){if(!e)return We;let n=t?`?projectId=${encodeURIComponent(t)}`:"";return`${We}/submissions/${e}${n}`}function ot(e,t){if(!e.jsonOutput)return;let n=Ie.resolve(e.jsonOutput),i={...t,url:t.url||t.dashboardUrl||gt(t.submitId,t.projectId),updatedAt:new Date().toISOString()};try{let r=Ie.dirname(n);r&&r!=="."&&se.mkdirSync(r,{recursive:!0}),se.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){fo.warn(ne.yellow(`Could not write submission metadata JSON: ${r.message}`))}}function gd(e,t){return t&&e.find(n=>n.credentialId===t||n.id===t||n.keyId===t||n.meta?.keyId===t)||null}function hd(e,t){let n=e.filter(i=>[i.bundleId,i.bundleIdentifier,i.appIdentifier,i.meta?.bundleId,i.meta?.bundleIdentifier,i.meta?.appIdentifier].filter(Boolean).map(String).includes(t));return n.length===1?n[0]:null}function yd(){return process.env.CI==="true"||process.env.CI==="1"||!process.stdin.isTTY}function _i(e){return new Promise(t=>setTimeout(t,e))}function Sd(e){return/^[a-zA-Z0-9_./:=@-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function bd(e,t){if(e.submit?.[t]?.android?.package)return e.submit[t].android.package;let n=sr(e,t);if(n)return n;let i=Ie.join(process.cwd(),"app.json");if(se.existsSync(i))try{return JSON.parse(se.readFileSync(i,"utf-8")).expo?.android?.package}catch{}let r=Ie.join(process.cwd(),"app.config.json");if(se.existsSync(r))try{let o=JSON.parse(se.readFileSync(r,"utf-8"));return o.expo?.android?.package||o.android?.package}catch{}}function Ad(e,t){let n=e.filter(o=>yn(o)===t);if(n.length>0)return n;let i=e.filter(o=>{let s=yn(o);return!s||s==="*"});return e.length>0&&e.length===i.length?i:[]}function Ed(e,t){return e.submit?.[t]?.ios?.bundleIdentifier?e.submit[t].ios.bundleIdentifier:e.submit?.[t]?.ios?.bundleId?e.submit[t].ios.bundleId:ar(e,t)}function Id(e,t,n){let i=e.submit?.[t]?.ios||{},r=e.submit?.production?.ios||{},o=n.sshHost||i.sshHost||r.sshHost||process.env.MACH_IOS_SUBMIT_SSH_HOST;return o?{sshHost:o,sshUser:n.sshUser||i.sshUser||r.sshUser||process.env.MACH_IOS_SUBMIT_SSH_USER||process.env.USER||"ubuntu",sshKey:n.sshKey||i.sshKey||r.sshKey||process.env.MACH_IOS_SUBMIT_SSH_KEY}:null}function wd(e,t,n){let i=n||e.submit?.[t]?.android?.releaseStatus||e.submit?.production?.android?.releaseStatus||"completed";return _d(i)}function _d(e){let t=rd[String(e).trim().toLowerCase()];if(!t)throw new Error(`Invalid Android release status "${e}". Use completed, draft, halted, or inProgress.`);return t}function $d(e,t,n){let i=n??e.submit?.[t]?.android?.rollout??e.submit?.[t]?.android?.userFraction??e.submit?.[t]?.android?.rolloutFraction??e.submit?.production?.android?.rollout??e.submit?.production?.android?.userFraction??e.submit?.production?.android?.rolloutFraction;if(i==null||i==="")return;let r=Number(i);if(!Number.isFinite(r)||r<=0||r>=1)throw new Error(`Invalid Android rollout fraction "${i}". Use a number greater than 0 and less than 1, for example 0.1.`);return r}function vd(e,t,n){let i=n??e.submit?.[t]?.android?.changesNotSentForReview??e.submit?.[t]?.android?.changes_not_sent_for_review??e.submit?.production?.android?.changesNotSentForReview??e.submit?.production?.android?.changes_not_sent_for_review??!1;return i===!0||i==="true"||i==="1"}function Rd(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 Pd(e,t,n,i){let r=n.buildId?"id":n.latest?"latest":null;if(!r){let s=await Ii({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(rt(s))return wi("Operation cancelled"),null;r=s}if(r==="local"){let s=await Bt({message:"Enter path to artifact (.ipa/.aab):",validate:l=>{if(!se.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 rt(s)?null:{filePath:s,source:"local"}}let o=st();if(r==="latest"){let s=n.profile||n.buildProfile;o.start(`Fetching latest${s?` ${s}`:""} build...`);try{let l=await N.get(`/builds/${e}`,{params:{limit:50}});if(l.data.status!=="success")throw new Error(l.data.message);let a=l.data.builds||[],c=s?.toLowerCase(),u=w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success",d=w=>c?[w.buildProfile,w.profile,w.profileName,w.buildType].filter(Boolean).some(z=>String(z).toLowerCase()===c):!0,p=a.filter(w=>u(w)&&d(w)),f=p.find(w=>w.buildType?.toLowerCase()==="store"||w.distribution?.toLowerCase()==="store")||p[0],h=a.some(w=>w.platform?.toLowerCase()===t.toLowerCase()&&w.status?.toLowerCase()==="success");if(!f)return o.stop("No suitable build found"),le(s&&h?`No successful ${t} builds found for profile "${s}".`:"No successful builds found for this platform."),null;o.stop(`Found build: ${f.buildId}`);let S=f.artifacts||[];if(S.length===0||S.every(w=>!(w.url||w.downloadUrl)))try{let w=await N.get(`/builds/${e}/${f.buildId}/artifacts`);w.data.status==="success"&&w.data.artifacts?.length>0?(S=w.data.artifacts.map(z=>({...z,url:z.url||z.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${S.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(w){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${w.message}`))}let x=t==="ios",b=S.find(w=>{let z=(w.type||"").toLowerCase(),Q=(w.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${w.name} (Type: ${w.type}, HasLink: ${!!(w.url||w.downloadUrl)})`)),z)return z===(x?"ipa":"aab");let O=x?".ipa":".aab",E=(w.url||w.downloadUrl||"").toLowerCase();return Q.endsWith(O)||E.includes(O)});if(!b||!(b.url||b.downloadUrl))return le("Build found but artifact URL is missing."),null;let U=b.url||b.downloadUrl;return{filePath:await bi(U,x?"ios":"android"),buildId:f.buildId,artifactName:b.name,source:"latest"}}catch(l){return o.stop("Fetch failed"),le(`API Error: ${l.message}`),null}}if(r==="id"){let s=n.buildId||await Bt({message:"Enter Build ID:",validate:a=>a.length<5?"Invalid ID":void 0});if(rt(s))return null;let l=String(s);o.start("Fetching build...");try{let a=null;try{let f=await N.get(`/builds/${e}/${l}`);f.data.status==="success"&&(a=f.data.build)}catch(f){f.response?.status!==404&&console.log(ne.dim(` [RECOVERY] Project build lookup skipped: ${f.message}`))}if(!a){let f=await N.get(`/build/${l}`);if(f.data.status!=="success")throw new Error(f.data.message);a=f.data.build}if(!a)throw new Error(`Build ${l} was not found.`);let c=t==="ios",u=hn(a.artifacts);Od(u)||(u=await ao(e,l,u));let d=so(u,t);if(d||(u=await ao(e,l,u),d=so(u,t)),!d)throw new Error(`No ${c?".ipa":".aab"} artifact found for build ${l}. The build exists, but its artifact list does not contain a downloadable submission artifact.`);let p=d.url||d.downloadUrl;if(!p)throw new Error(`Artifact ${d.name||"(unnamed)"} for build ${l} has no download URL. Retry after the build artifact upload is visible in the Installation Hub.`);return o.stop(`Found build: ${a.buildId||l}`),{filePath:await bi(p,c?"ios":"android"),buildId:a.buildId||l,artifactName:d.name,source:"id"}}catch(a){throw o.stop("Fetch failed"),a}}if(r==="url"){let s=await Bt({message:"Enter Artifact URL:",validate:l=>l.startsWith("http")?void 0:"Must be a valid URL"});return rt(s)?null:{filePath:await bi(s,t),source:"url"}}return null}function hn(e){return(e||[]).map(t=>({...t,url:t.url||t.downloadUrl}))}function Od(e){return e.some(t=>!!(t.url||t.downloadUrl))}function so(e,t){let n=t==="ios",i=n?"ipa":"aab",r=n?".ipa":".aab";return e.find(o=>{let s=String(o.type||"").toLowerCase(),l=String(o.name||"").toLowerCase(),a=String(o.url||o.downloadUrl||"").toLowerCase();return s?s===i:l.endsWith(r)||a.includes(r)})||null}function Dd(e,t){let n=e==="ios"?".ipa":".aab";if(t.buildId)return`No downloadable ${n} artifact found for build ${t.buildId}. Check that the build finished artifact upload before submitting.`;if(t.latest){let i=t.profile||t.buildProfile;return`No latest successful ${e}${i?` ${i}`:""} build has a downloadable ${n} artifact.`}return`No downloadable ${n} artifact was selected for submission.`}async function ao(e,t,n){try{let i=await N.get(`/builds/${e}/${t}/artifacts`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=hn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Project artifact lookup skipped: ${i.message}`))}try{let i=await N.get(`/public/builds/${t}`);if(i.data.status==="success"&&i.data.artifacts?.length>0){let r=hn(i.data.artifacts);return console.log(ne.cyan(` [RECOVERY] Fetched ${r.length} public artifact(s) with download URLs.`)),r}}catch(i){console.log(ne.dim(` [RECOVERY] Public artifact lookup skipped: ${i.message}`))}return hn(n)}async function bi(e,t,n=3){let i=st();i.start("Downloading artifact...");let r=se.mkdtempSync(Ie.join(ht.tmpdir(),`${m.nameLower}-artifact-`)),o=`app.${t==="ios"?"ipa":"aab"}`,s=Ie.join(r,o);for(let l=1;l<=n;l++)try{l>1&&(i.message(`Downloading artifact (Retry ${l}/${n})...`),await new Promise(u=>setTimeout(u,2e3*l)));let a=se.createWriteStream(s),c=await po({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((u,d)=>{c.data.pipe(a);let p=!1;c.data.on("error",f=>{p||(p=!0,a.close(),d(f))}),a.on("finish",()=>{p||u()}),a.on("error",f=>{p||(p=!0,d(f))})}),i.stop("Download complete"),s}catch(a){if(l===n)throw i.stop("Download failed"),a}throw new Error("Download failed after retries")}async function Cd(e,t,n,i,r){let o=st();if(r&&fe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let s=ho(t,n,i),l=Fd();return o.start("Uploading to TestFlight (pilot)..."),new Promise((a,c)=>{let u=Hd(),d=td(l.command,["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:["ignore","pipe","pipe"],env:l.env});d.stdout?.on("data",p=>u.append(p,process.stdout)),d.stderr?.on("data",p=>u.append(p,process.stderr)),d.on("close",p=>{if(u.flush(),p!==0){o.stop("Pilot failed");try{se.unlinkSync(s)}catch{}c(jd(p,u.lines()))}else{o.stop("IPA uploaded to TestFlight");try{se.unlinkSync(s)}catch{}a({})}}),d.on("error",p=>{u.flush();try{se.unlinkSync(s)}catch{}o.stop("Pilot execution error");let f=qd(p);f.logs=u.lines(),c(f)})})}async function Nd(e,t,n,i,r,o){let s=st();if(r&&fe(`Bundle ID: ${ne.green(r)}`),!n||!i)throw le(`Missing credentials: issuerId=${n}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let l=ho(t,n,i),a=`${o.sshUser}@${o.sshHost}`,c=Td(o),u=kd(o),d="",p="";try{if(s.start(`Preparing remote iOS submit runner (${a})...`),d=xd("ssh",[...c,"mktemp -d /tmp/mach-submit.XXXXXX"]).trim(),!d)throw new Error("Remote runner did not return a temp directory.");s.stop(`Remote runner ready: ${a}`),s.start("Uploading IPA and App Store Connect key to remote runner..."),Ai("scp",[...u,e,`${a}:${d}/app.ipa`],"IPA upload to remote runner"),Ai("scp",[...u,l,`${a}:${d}/api_key.json`],"ASC key upload to remote runner"),p=Ie.join(ht.tmpdir(),`${m.nameLower}-ios-submit-${Date.now()}.sh`),se.writeFileSync(p,Md(d)),Ai("scp",[...u,p,`${a}:${d}/submit.sh`],"submit script upload to remote runner"),s.stop("Remote submit inputs uploaded"),s.start("Uploading to TestFlight on remote runner...");let f=`chmod +x ${Ht(`${d}/submit.sh`)} && bash ${Ht(`${d}/submit.sh`)}`,h=mt("ssh",[...c,f],{stdio:"inherit"});if(h.error)throw Ri("ssh",h.error);if(h.status!==0)throw new Error(`Remote iOS submit failed with exit code ${h.status}.`);return s.stop("IPA uploaded to TestFlight"),{apiKeyJsonPath:null}}catch(f){throw s.stop("Remote iOS submit failed"),f}finally{try{se.unlinkSync(l)}catch{}if(p)try{se.unlinkSync(p)}catch{}if(d)try{mt("ssh",[...c,`rm -rf ${Ht(d)}`],{stdio:"ignore"})}catch{}}}function ho(e,t,n){let i=se.readFileSync(e,"utf8"),r;try{r=vi.createPrivateKey(i).export({type:"pkcs8",format:"pem"})}catch{fe("Key normalization failed, falling back to manual re-wrapping..."),r=`-----BEGIN PRIVATE KEY-----
|
|
1259
1291
|
${(i.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
1260
1292
|
`)}
|
|
1261
|
-
-----END PRIVATE KEY-----`}let o=Ie.join(ht.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return se.writeFileSync(o,JSON.stringify(s,null,2)),o}function
|
|
1293
|
+
-----END PRIVATE KEY-----`}let o=Ie.join(ht.tmpdir(),`api_key_${n}_${Date.now()}.json`),s={key_id:n,issuer_id:t,key:r,in_house:!1};return se.writeFileSync(o,JSON.stringify(s,null,2)),o}function Td(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 kd(e){let t=["-o","StrictHostKeyChecking=no","-o","ServerAliveInterval=30"];return e.sshKey&&t.push("-i",e.sshKey),t}function xd(e,t){let n=mt(e,t,{encoding:"utf-8",stdio:["ignore","pipe","inherit"]});if(n.error)throw Ri(e,n.error);if(n.status!==0)throw new Error(`${e} failed with exit code ${n.status}.`);return n.stdout||""}function Ai(e,t,n){let i=mt(e,t,{stdio:"inherit"});if(i.error)throw Ri(e,i.error);if(i.status!==0)throw new Error(`${n} failed with exit code ${i.status}.`)}function Ri(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 Ht(e){return`'${e.replace(/'/g,"'\\''")}'`}function Md(e){let t=Ht(`${e}/app.ipa`),n=Ht(`${e}/api_key.json`);return`#!/bin/bash
|
|
1262
1294
|
set -euo pipefail
|
|
1263
1295
|
|
|
1264
1296
|
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/.local/share/fastlane/3.4.0/bin:$PATH"
|
|
@@ -1286,39 +1318,39 @@ fastlane pilot upload \\
|
|
|
1286
1318
|
--api_key_path ${n} \\
|
|
1287
1319
|
--skip_submission true \\
|
|
1288
1320
|
--skip_waiting_for_build_processing true
|
|
1289
|
-
`}async function
|
|
1321
|
+
`}async function Ld(e,t,n="internal",i,r="completed",o,s=!1,l="production"){let a=st();if(!i||i==="*")throw new Error("Android package name is required for Google Play submission.");let c=o!==void 0?` (${o} rollout)`:"";a.start(`Uploading to Google Play ${n} track with ${r} release status${c}...`);try{let u=JSON.parse(se.readFileSync(t,"utf-8"));Ud(u);let d=await $r({packageName:i,serviceAccount:u,aabPath:e,track:n,releaseStatus:r,userFraction:o,changesNotSentForReview:s});return a.stop(`AAB uploaded to ${n} track (versionCode ${d.versionCode})`),d}catch(u){throw a.stop("Google Play upload failed"),new Error(Xd(u,n,i,l))}}function Ud(e){if(!e?.client_email||!e?.private_key)throw new Error("Invalid Google service account JSON: missing client_email or private_key.")}function Ei(){let e=process.env.HOME||ht.homedir(),t=process.env.FASTLANE_GEM_HOME||Ie.join(e,".local/share/fastlane/3.4.0"),n=[process.env.FASTLANE_BIN_DIR,"/usr/local/opt/ruby/bin","/opt/homebrew/opt/ruby/bin","/usr/local/bin","/opt/homebrew/bin","/usr/local/Cellar/fastlane/2.227.0/libexec/bin",Ie.join(t,"bin"),process.env.PATH].filter(Boolean).join(":");return{...process.env,PATH:n,GEM_HOME:t,GEM_PATH:[t,"/usr/local/Cellar/fastlane/2.227.0/libexec",process.env.GEM_PATH].filter(Boolean).join(":"),FASTLANE_INSTALLED_VIA_HOMEBREW:"true",FASTLANE_SKIP_UPDATE_CHECK:"1",FASTLANE_HIDE_CHANGELOG:"1",LANG:process.env.LANG||"en_US.UTF-8",LC_ALL:process.env.LC_ALL||"en_US.UTF-8",CI:process.env.CI||"1"}}function Fd(){let e=Ei(),t=lo(e);if(t)return t;if(process.env.MACH_SKIP_FASTLANE_INSTALL!=="1"){Bd(e);let n=lo(Ei());if(n)return n}return{command:"fastlane",env:Ei()}}function lo(e){let t=process.env.HOME||ht.homedir(),n=[process.env.FASTLANE_BINARY,"/usr/local/bin/fastlane","/opt/homebrew/bin/fastlane","/usr/local/Cellar/fastlane/2.227.0/libexec/bin/fastlane",Ie.join(process.env.FASTLANE_GEM_HOME||Ie.join(t,".local/share/fastlane/3.4.0"),"bin/fastlane"),"fastlane"].filter(Boolean);for(let i of n){if(i.includes("/")&&!se.existsSync(i))continue;if(!mt(i,["--version"],{env:e,stdio:"ignore"}).error)return{command:i,env:e}}return null}function Bd(e){let t=mt("gem",["--version"],{env:e,stdio:"ignore"});if(t.error||t.status!==0)return;let n=process.env.HOME||ht.homedir(),i=process.env.FASTLANE_GEM_HOME||Ie.join(n,".local/share/fastlane/3.4.0"),r=Ie.join(i,"bin");se.mkdirSync(r,{recursive:!0}),fe(ne.dim("fastlane not found. Installing fastlane into the local Mach runner cache..."));let o=mt("gem",["install","fastlane","-NV","--install-dir",i,"--bindir",r],{env:{...e,GEM_HOME:i,GEM_PATH:[i,e.GEM_PATH].filter(Boolean).join(":")},stdio:"inherit"});(o.error||o.status!==0)&&fe(ne.yellow("Automatic fastlane install failed; Mach will try PATH resolution once more."))}function Hd(e=mo){let t=[],n="",i=r=>{let o=So(r);if(o)for(t.push(o);t.length>e;)t.shift()};return{append(r,o){let s=Buffer.isBuffer(r)?r.toString("utf8"):String(r);o.write(s),n+=s;let l=n.split(/\r?\n/);n=l.pop()||"";for(let a of l)i(a)},flush(){n.trim()&&i(n),n=""},lines(){return t.slice()}}}function jd(e,t){let n=new Error(Gd(e,t));return n.logs=yo(t),n.exitCode=e,n}function Gd(e,t){let n=`fastlane pilot failed with exit code ${e??"unknown"}.`,i=Kd(t);return i.length===0?n:`${n}
|
|
1290
1322
|
|
|
1291
1323
|
Fastlane output:
|
|
1292
1324
|
${i.join(`
|
|
1293
|
-
`)}`}function
|
|
1294
|
-
`),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function
|
|
1295
|
-
`))}function
|
|
1325
|
+
`)}`}function Kd(e){let t=yo(e);if(t.length===0)return[];let n=co(t.filter(zd)),i=Vd(t);if(i)return[i,...uo(n,Si-1,oo)];let r=n.length>0?n:t.slice(-Si);return uo(co(r),Si,oo)}function Vd(e){let t=e.join(`
|
|
1326
|
+
`),n=t.match(/CFBundleShortVersionString\s*\[([^\]]+)\]/i)?.[1]||t.match(/train version ['"]([^'"]+)['"]/i)?.[1];if(/Invalid Pre-Release Train/i.test(t)||/CFBundleShortVersionString[\s\S]*must contain a higher version/i.test(t))return[`App Store Connect rejected CFBundleShortVersionString${n?` ${n}`:""}: this App Store version train is closed or not higher than the approved version.`,'ios.buildNumber="auto" only changes CFBundleVersion; bump the marketing version (Expo app.json "expo.version" / iOS MARKETING_VERSION), rebuild, then submit the new build.'].join(" ");if(!/bundle version must be higher than the previously uploaded version/i.test(t))return null;let i=t.match(/previous(?:ly)?BundleVersion\s*:\s*([0-9.]+)/i)?.[1]||t.match(/previously uploaded version:\s*[‘'"]?([0-9.]+)/i)?.[1];return`App Store Connect rejected CFBundleVersion: the bundle version must be higher than the previously uploaded version.${i?` Previous uploaded build: ${i}.`:""}`}function zd(e){return/\[!\]|ERROR ITMS-\d+|ITMS-\d+|ENTITY_ERROR|previousBundleVersion|CFBundleVersion|Application Loader Error Output|Transporter Error|Transporter transfer failed|Asset validation failed|Validation failed|Error Domain=|The request could not be completed|No suitable application records|Could not|authentication|unauthori[sz]ed|invalid|failed|exception/i.test(e)}function co(e){let t=new Set,n=[];for(let i of e){let r=i.trim();!r||t.has(r)||(t.add(r),n.push(i))}return n}function uo(e,t,n){let i=[],r=0;for(let o=e.length-1;o>=0&&i.length<t;o--){let s=e[o],l=r+s.length+1;if(l>n&&i.length>0)break;i.unshift(s.length>n?`${s.slice(0,n-18)}... [truncated]`:s),r=l}return i}function yo(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let i=String(n).split(/\r?\n/);for(let r of i){let o=So(r);o&&t.push(o)}}return t.slice(-mo)}function So(e){return Yd(Wd(e).trimEnd()).trim()}function Wd(e){return e.replace(/[\u001b\u009b][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g,"")}function Yd(e){let t=e.replace(/-----BEGIN [^-]+-----[\s\S]*?-----END [^-]+-----/g,"[REDACTED_PRIVATE_KEY]").replace(/(authorization:\s*bearer\s+)[A-Za-z0-9._-]+/ig,"$1[REDACTED]").replace(/((?:password|token|secret|private[_-]?key)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s,]+)/ig,"$1[REDACTED]");for(let[n,i]of Object.entries(process.env))!i||i.length<8||/(TOKEN|SECRET|PASSWORD|PASS|PRIVATE|CREDENTIAL)/i.test(n)&&(t=t.replace(new RegExp(Jd(i),"g"),"[REDACTED]"));return t}function Jd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qd(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(`
|
|
1327
|
+
`))}function Xd(e,t,n,i="production"){let r=e?.message||String(e);if(/changesNotSentForReview/i.test(r))return["Google Play rejected the commit because this change may need explicit review handling.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --changes-not-sent-for-review`,"Then send the change for review from Google Play Console if required."].join(`
|
|
1296
1328
|
`);if(/caller does not have permission|permission denied|insufficient permissions|not authorized/i.test(r))return["Google Play rejected the service account permissions.",`Package: ${n||"unknown"} | Track: ${t}`,"Grant this service account access to the app in Play Console with release permissions, then retry."].join(`
|
|
1297
1329
|
`);if(/package.*not found|application.*not found|no application was found/i.test(r))return["Google Play could not find this package for the selected service account.",`Package: ${n||"unknown"} | Track: ${t}`,"Check android.package / submit.<profile>.android.package and make sure the app exists in this Play Console account."].join(`
|
|
1298
1330
|
`);if(/only releases with status draft|draft app/i.test(r))return["Google Play requires a draft release for this app state.",`Package: ${n||"unknown"} | Track: ${t}`,`Retry with: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t} --release-status draft`].join(`
|
|
1299
1331
|
`);if(r.includes("does not allow any existing users to upgrade"))return["Google Play rejected this release because the uploaded AAB is not an upgrade for existing users.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`,`Then: ${m.nameLower} submit --latest --platform android --profile ${i} --track ${t}`].join(`
|
|
1300
1332
|
`);if(/version code \d+ has already been used/i.test(r))return[r.match(/version code \d+ has already been used[^\n]*/i)?.[0]||"Version code has already been used.",`Package: ${n||"unknown"} | Track: ${t}`,"Build a new Android artifact with a higher versionCode, then submit that build.",`Recommended: ${m.nameLower} build --platform android --profile ${i} --auto-version`].join(`
|
|
1301
|
-
`);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function Vd(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(te.red(`\u274C ${e}`))}function fe(e){console.log(te.gray(`\u2022 ${e}`))}function wi(e){console.log(te.green(`\u2713 ${e}`))}var vi=8,Yd=6,yo=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Ri=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),Jd=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],Oo=e=>new Promise(t=>setTimeout(t,e)),qd=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,Xd=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},Zd=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?Jd:n.map(i=>({value:i,label:i,hint:Xd(t[i])}))},Qd=async e=>{let t=qd(e);if(!e.platform&&t){let n=await fo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});En(n)&&(mo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=Zd(),i=await fo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});En(i)&&(mo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},So=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},Co=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},ec=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),tc=e=>{let n=Co(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},nc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await P.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||tc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||Co(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=So(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:ec(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=So(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){$.warn(v.yellow(`Could not load saved build options for runner: ${t.message}`))}},ic=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},rc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},yn=async(e,t,n=Yd)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!rc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";$.warn(v.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await Oo(s)}throw i},oc=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round(Ri/1e3);try{await yn(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Ri);try{await bn.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Ri,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},yo)}catch(s){throw new Error(`${i} (${ic(r)}) failed after ${yo} upload attempt(s): ${s.message||s}`)}return r},sc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},jt=e=>e.credentialId||e.id,ac=async(e,t)=>{let n=jt(e);if(!n)return e.downloadUrl;let i=await P.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},No=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=vi;i++)try{if((!n||i>1)&&(n=await ac(e,t)),!n)throw new Error(`Credential ${e.name||jt(e)||"unknown"} has no download URL.`);let r=await bn.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=vi||!sc(r))throw r;let o=Math.min(1500*i*i,15e3);$.warn(v.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${vi})`)),await Oo(o)}throw new Error(`Failed to download credential ${e.name||jt(e)||"unknown"}.`)},bo=async(e,t)=>{let n=await No(e,t);return Buffer.from(n,"base64").toString("utf8")},lc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},dc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),cc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,uc=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,Eo=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Ao=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>Eo(o)===t);if(i)return i;let r=n.find(o=>Eo(o)==="*");if(r)return r}return n[0]}},fc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",To=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ve.join(e,r.name);r.isDirectory()?To(o,t,n):r.name===t&&n.push(o)}return n},pc=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},mc=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=To(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:pc(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},Sn=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),An=(e,t)=>{let n=Sn(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Io=(e,t,n)=>{let i=An(e.distributionType||e.meta?.distributionType,n);return i?i===An(t,n):!0},wo=(e,t,n)=>{let i=An(e.distributionType||e.meta?.distributionType,n),r=An(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},gc=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},hc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},yc=(e,t)=>{let n=Sn(e.distribution),i=Sn(e.iosExportMethod),r=Sn(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":gc(t)?"development":(hc(t),"adhoc")},ko=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,_o=(e,t)=>{if(!t)return!0;let n=ko(e);return!n||n==="*"||n===t},$o=(e,t)=>{let n=ko(e);return!t||!n?0:n===t?2:n==="*"?1:-1},xo=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},Sc=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},bc=(e,t)=>{if(!t)return!0;let n=xo(e);if(n)return Sc(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},In=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&($.error(v.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await P.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),$.info(v.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){$.error(v.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await nc(e),await Qd(e),e.platform!=="android"&&e.platform!=="ios"&&($.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&($.error(v.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&$.warn(v.yellow("--auto-submit is ignored during --dry-run."));let t=Di(),n=e.buildId||zd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await P.patch(`/builds/${i}/${n}`,{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 P.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await bn.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ve.join(Wd.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),f=new Set(["Pods"]);if(de.existsSync(u)){let U=de.readdirSync(u);for(let R of U){if(d.has(R))continue;if(R==="ios"){let b=ve.join(u,"ios");try{let W=de.readdirSync(b);for(let ne of W)if(!f.has(ne))try{de.rmSync(ve.join(b,ne),{recursive:!0,force:!0})}catch{}}catch{}continue}let K=ve.join(u,R);try{de.rmSync(K,{recursive:!0,force:!0})}catch{}}}let p=ve.join(u,"source.zip"),h=a.data,D=de.createWriteStream(p);await new Promise((U,R)=>{h.pipe(D),h.on("error",K=>R(K)),D.on("finish",()=>U())}),new ho(p).extractAllTo(u,!0);try{de.unlinkSync(p)}catch{}process.chdir(u),$.info(v.green(`\u2713 Persistent workspace ready: ${u}`)),$.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ve.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ve.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=go("git config --get remote.origin.url").toString().trim()}catch{$.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),$.info(`Build ID: ${v.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d){u=d,i=d.projectId;let g=e.buildProfile||"production",T=nt(d,g);!T&&e.buildProfile&&($.error(`Build profile '${g}' not found in ${m.configFileName}`),process.exit(1));let w=T||{};process.env.MACH_DEBUG&&$.info(v.dim(`Build profile: ${g} | Platform: ${e.platform} | Distribution: ${w.distribution||"store"} | Environment: ${w.environment||g}`)),w.env&&(c=w.env,$.info(v.blue(`Use Build Profile: ${g}`)));let k=e.platform,A=w[k]||{},S=["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 x=L=>L==="androidPackage"?A.androidPackage??A.package??w.androidPackage??w.android?.package:L==="iosBundleIdentifier"?A.iosBundleIdentifier??A.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier:A[L]!==void 0?A[L]:w[L];for(let L of S){let J=x(L),O=L==="androidPackage"||L==="iosBundleIdentifier";J!==void 0&&(e[L]===void 0||O)&&(e[L]=J)}if(e.platform==="ios"&&!(A.iosBundleIdentifier??A.bundleIdentifier??w.iosBundleIdentifier??w.ios?.bundleIdentifier)){let J=mc(e,g);J&&J!==e.iosBundleIdentifier&&($.warn(v.yellow(`Detected native iOS bundle identifier ${J}; using it for credential lookup. Set build.${g}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=J)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let B=L=>{if(!L)return L;if(L.startsWith("scripts.")){let J=L.split(".")[1],O=d.scripts?.[J];if(O)return O;$.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=B(e.buildCommand),e.preBuild=B(e.preBuild),e.postBuild=B(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let Y={...Et(d,m.envPrefix),...Et(w,`${m.envPrefix}PROFILE_`)};a={...a,...c,...Y},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&w.ios?.appleTeamId&&(e.iosTeamId=w.ios.appleTeamId),!e.iosTeamId&&d.submit?.[g]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[g].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&($.warn(v.yellow(`Check: Using 'production' Team ID for '${g}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?$.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||$.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let f="unknown";try{f=go("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{$.warn("Failed to detect git branch.")}let p="1.0.0";try{de.existsSync("./package.json")&&(p=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let h=e.buildProfile||"production",D="Internal";e.developmentClient?D="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?D="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?D="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(D="Development");let N=e.platform==="ios"?"iOS":"Android",U=e.platform==="ios"&&e.simulator?" (Simulator)":"",R=`${N}${U} v${p} (${D})`;if(wn(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:h,branch:f,version:p,buildType:D,developmentClient:!!e.developmentClient,summary:R}),i){try{let g=e.buildProfile||"production",T=e.environment||g;$.info(v.blue(`Fetching managed secrets for profile: ${g} (environment: ${T})...`));let k=(await P.get(`/projects/${i}/secrets/export?env=${T}`)).data;k.status==="success"&&k.secrets&&(a={...a,...k.secrets},Object.keys(k.secrets).length>0&&$.info(v.magenta(`\u2713 Injected ${Object.keys(k.secrets).length} secrets from Dashboard.`)))}catch(g){$.warn(`Failed to load managed secrets from Dashboard: ${g.message}`)}if(e.platform==="ios"&&e.simulator)$.info(v.dim("Skipping managed iOS signing credentials for simulator build."));else try{$.info(v.blue("Fetching managed credentials..."));let g=yc(e,h),T=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,w=e.platform==="ios"?"bundle":"package";$.info(v.dim(` Credential target: ${w} ${T||"not set"} (${g})`));let k=await P.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:T,distributionType:g,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if(k.data.status==="success"&&k.data.credentials){let A=k.data.credentials;$.info(v.magenta(`\u2713 Found ${A.length} relevant credentials.`));let S=A.filter(O=>e.platform==="ios"&&O.type==="ios_profile"?Io(O,g,e.platform)?_o(O,T):!1:e.platform==="android"&&O.type==="android_keystore"?_o(O,T):!!Io(O,g,e.platform)).sort((O,q)=>$o(q,T)*10+wo(q,g,e.platform)-($o(O,T)*10+wo(O,g,e.platform)));$.info(v.dim(` Filtered to ${S.length} credentials for distributionType: ${g}`));let x=!1,B=!1,Y=!1,L=[];for(let O of S)if(!(O.type==="ios_cert"&&x||O.type==="ios_profile"&&B||O.type==="android_keystore"&&Y)&&["ios_cert","ios_profile","android_keystore"].includes(O.type)&&(O.downloadUrl||jt(O)))try{let ye=await No(O,i);if(O.type==="ios_cert"&&!x)a.IOS_DIST_P12=ye,O.password?(a.IOS_P12_PASSWORD=O.password,$.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12 with password from credential record`))):$.info(v.dim(` - Injected ${O.name} as IOS_DIST_P12`)),x=!0;else if(O.type==="ios_profile"&&!B){if(!bc(ye,T)){let Ee=xo(ye)||"unknown";throw new Error(`Provisioning profile ${O.name||jt(O)||"unknown"} is for a different bundle ID. Expected ${T}, found ${Ee}. Upload a ${g} profile for ${T}.`)}a.IOS_PROVISIONING_PROFILE=ye,$.info(v.dim(` - Injected ${O.name} as IOS_PROVISIONING_PROFILE`)),B=!0}else if(O.type==="android_keystore"&&!Y){a.ANDROID_KEYSTORE_BASE64=ye;let Ee=O.keystorePassword||O.password,H=O.keyPassword||O.keystorePassword||O.password,F=O.alias||O.meta?.alias;if(Ee)a.ANDROID_STORE_PASSWORD=Ee,$.info(v.dim(" - Injected keystore password from credential record"));else{let j=["ANDROID_STORE_PASSWORD",...[g==="store"?"PRODUCTION":g==="internal"||g==="adhoc"?"STAGING":"DEVELOPMENT",g.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(Z=>`KEYSTORE_PASSWORD_${Z}`),"KEYSTORE_PASSWORD"].find(Z=>!!a[Z]);j&&a[j]&&(a.ANDROID_STORE_PASSWORD=a[j])}if(H?(a.ANDROID_KEY_PASSWORD=H,$.info(v.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",F)a.ANDROID_KEY_ALIAS=F;else{let X=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(C=>!!a[C]);X&&(a.ANDROID_KEY_ALIAS=a[X])}$.info(v.dim(` - Injected ${O.name} as ANDROID_KEYSTORE_BASE64`)),Y=!0}}catch(ye){L.push(`${O.name||O.type}: ${ye.message}`)}let J=e.platform==="ios"?e.simulator||x&&B:Y||!S.some(O=>O.type==="android_keystore");if(L.length>0&&!J)throw new Error(`Credential setup failed:
|
|
1302
|
-
${
|
|
1303
|
-
`)}`);
|
|
1304
|
-
\u{1F517} Download Links:`));for(let
|
|
1305
|
-
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!
|
|
1306
|
-
${
|
|
1307
|
-
\u{1F3BC} Queuing managed Maestro test...`)),await
|
|
1308
|
-
Auto-submit: submitting the successful build...`));try{let r=await
|
|
1309
|
-
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!")
|
|
1310
|
-
\u2713 Build completed successfully!`));try{n.quiet||(
|
|
1311
|
-
\u{1F4F1} Installation Hub:`))
|
|
1312
|
-
`);if(d.length>o){for(let
|
|
1313
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as
|
|
1333
|
+
`);let o=r.match(/Google Api Error:[^\n]+/)||r.match(/Google Play API Error:[^\n]+/);return o?o[0]:r||"Google Play submission failed"}function Zd(e){try{se.existsSync(e)&&se.rmSync(e,{recursive:!0,force:!0})}catch{}}function le(e){console.log(ne.red(`\u274C ${e}`))}function fe(e){console.log(ne.gray(`\u2022 ${e}`))}function $i(e){console.log(ne.green(`\u2713 ${e}`))}var Pi=8,tc=6,_o=Number(process.env.MACH_ARTIFACT_UPLOAD_MAX_ATTEMPTS||2),Oi=Number(process.env.MACH_ARTIFACT_UPLOAD_TIMEOUT_MS||12e4),nc=[{value:"production",label:"production",hint:"Store / release build"},{value:"staging",label:"staging",hint:"Internal testing build"},{value:"development",label:"development",hint:"Development build"}],Lo=e=>new Promise(t=>setTimeout(t,e)),ic=e=>!e.yes&&!e.failOnly&&!e.buildId&&process.stdin.isTTY&&process.stdout.isTTY,rc=e=>{if(!e||typeof e!="object")return;let t=[e.distribution?`distribution: ${e.distribution}`:void 0,e.environment?`env: ${e.environment}`:void 0,e.developmentClient?"development client":void 0,e.simulator?"simulator":void 0].filter(Boolean);return t.length>0?t.join(", "):void 0},oc=()=>{let e=$e(`./${m.configFileName}`),t=e?.build&&typeof e.build=="object"?e.build:{},n=Object.keys(t);return n.length===0?nc:n.map(i=>({value:i,label:i,hint:rc(t[i])}))},sc=async e=>{let t=ic(e);if(!e.platform&&t){let n=await bo({message:"Select platform",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"}]});In(n)&&(Eo("Build cancelled."),process.exit(0)),e.platform=n}if(!e.buildProfile&&t){let n=oc(),i=await bo({message:"Select build profile",options:n,initialValue:n.find(r=>r.value==="production")?.value||n[0]?.value});In(i)&&(Eo("Build cancelled."),process.exit(0)),e.buildProfile=i}e.buildProfile||(e.buildProfile="production")},$o=e=>{if(e===!0||e===!1)return e;if(e===1||e==="1")return!0;if(e===0||e==="0")return!1;if(typeof e!="string")return;let t=e.trim().toLowerCase();if(["true","yes","on"].includes(t))return!0;if(["false","no","off"].includes(t))return!1},Uo=(e,t)=>{if(e)for(let n of t){let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|\\s)${i}(?:=|\\s+)([^\\s]+)`));if(r?.[1])return r[1].replace(/^["']|["']$/g,"")}},ac=(e,t)=>!!e&&t.some(n=>new RegExp(`(?:^|\\s)${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$)`).test(e)),lc=e=>{let n=Uo(e,["--platform"])||e?.split(/\s+/).find(i=>i==="ios"||i==="android");return n==="ios"||n==="android"?n:void 0},dc=async e=>{if(!(!e.projectId||!e.buildId))try{let t=await N.get(`/builds/${e.projectId}/${e.buildId}`),n=t.data?.build||t.data;if(!n||typeof n!="object")return;let i=typeof n.buildArgs=="string"?n.buildArgs:void 0;if(!e.platform){let r=n.platform||lc(i);(r==="ios"||r==="android")&&(e.platform=r)}if(e.buildProfile||(e.buildProfile=n.buildProfile||n.profile||n.profileName||Uo(i,["--profile","--build-profile","-p"])),e.simulator===void 0){let r=$o(n.simulator??n.isSimulator);r!==void 0?e.simulator=r:ac(i,["--simulator"])&&(e.simulator=!0)}if(e.developmentClient===void 0){let r=$o(n.developmentClient??n.devClient);r!==void 0&&(e.developmentClient=r)}}catch(t){v.warn(R.yellow(`Could not load saved build options for runner: ${t.message}`))}},cc=e=>{if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/Math.pow(1024,n)).toFixed(n===0?0:1)} ${t[n]}`},uc=e=>{let t=e.response?.status,n=e.code||"",i=e.message||"";return t?t===408||t===409||t===425||t===429||t>=500||/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(`${n} ${i}`):!0},bn=async(e,t,n=tc)=>{let i;for(let r=1;r<=n;r++)try{return await t()}catch(o){if(i=o,!uc(o)||r>=n)break;let s=Math.min(6e4,2e3*Math.pow(2,r-1)),l=o.response?.status||o.code||o.message||"network error";v.warn(R.yellow(`${e} failed transiently (${l}). Retrying in ${Math.round(s/1e3)}s... (${r}/${n})`)),await Lo(s)}throw i},fc=async(e,t,n)=>{let i=ve.basename(e),r=de.statSync(e).size,o=Math.round(Oi/1e3);try{await bn(`Upload artifact ${i}`,async()=>{let s=new AbortController,l=de.createReadStream(e),a=setTimeout(()=>{l.destroy(new Error(`Artifact upload timed out after ${o}s`)),s.abort()},Oi);try{await En.put(t,l,{headers:{"Content-Type":n,"Content-Length":r,Connection:"close"},maxBodyLength:1/0,maxContentLength:1/0,timeout:Oi,timeoutErrorMessage:`Artifact upload timed out after ${o}s`,signal:s.signal})}finally{clearTimeout(a)}},_o)}catch(s){throw new Error(`${i} (${cc(r)}) failed after ${_o} upload attempt(s): ${s.message||s}`)}return r},pc=e=>{let t=e.response?.status;return t?t===408||t===429||t>=500:!0},jt=e=>e.credentialId||e.id,mc=async(e,t)=>{let n=jt(e);if(!n)return e.downloadUrl;let i=await N.get(`/credentials/${n}/download`,{params:{projectId:t,format:"raw"}});return i.data?.status==="success"&&i.data?.downloadUrl?i.data.downloadUrl:e.downloadUrl},Fo=async(e,t)=>{let n=e.downloadUrl;for(let i=1;i<=Pi;i++)try{if((!n||i>1)&&(n=await mc(e,t)),!n)throw new Error(`Credential ${e.name||jt(e)||"unknown"} has no download URL.`);let r=await En.get(n,{responseType:"arraybuffer",timeout:6e4,maxContentLength:1/0,maxBodyLength:1/0,headers:{Connection:"close"}});return Buffer.from(r.data).toString("base64")}catch(r){if(i>=Pi||!pc(r))throw r;let o=Math.min(1500*i*i,15e3);v.warn(R.dim(` - Temporary network error downloading ${e.name}. Retrying... (${i}/${Pi})`)),await Lo(o)}throw new Error(`Failed to download credential ${e.name||jt(e)||"unknown"}.`)},vo=async(e,t)=>{let n=await Fo(e,t);return Buffer.from(n,"base64").toString("utf8")},gc=(e,t)=>{try{return JSON.parse(e)}catch{throw new Error(`${t} is not valid JSON.`)}},hc=e=>/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|ECONNABORTED|socket hang up|network|timeout/i.test(e),yc=(e,t)=>t?.ios?.buildNumber??t?.iosBuildNumber??e?.ios?.buildNumber??e?.expo?.ios?.buildNumber,Sc=(e,t,n)=>t?.ios?.ascAppId??t?.ascAppId??e?.ios?.ascAppId??e?.submit?.[n]?.ios?.ascAppId??e?.submit?.production?.ios?.ascAppId,Ro=e=>e.bundleId||e.bundleIdentifier||e.meta?.bundleId||e.meta?.bundleIdentifier,Po=(e,t)=>{let n=e.filter(i=>i.type==="asc_api_key");if(n.length!==0){if(t){let i=n.find(o=>Ro(o)===t);if(i)return i;let r=n.find(o=>Ro(o)==="*");if(r)return r}return n[0]}},bc=e=>typeof e=="string"&&e.trim().toLowerCase()==="auto",Bo=(e,t,n=[])=>{if(!de.existsSync(e))return n;let i;try{i=de.readdirSync(e,{withFileTypes:!0})}catch{return n}for(let r of i){if(r.name==="Pods"||r.name==="build"||r.name==="DerivedData")continue;let o=ve.join(e,r.name);r.isDirectory()?Bo(o,t,n):r.name===t&&n.push(o)}return n},Ac=(e,t,n)=>{let i=`${n} ${t.environment||""}`.toLowerCase(),r=e.toLowerCase(),o=0;return(i.includes("development")||i.includes("dev"))&&/(^|[.-])dev(elopment)?($|[.-])/.test(r)&&(o+=20),(i.includes("staging")||i.includes("stage"))&&/(^|[.-])stag(e|ing)?($|[.-])/.test(r)&&(o+=20),(i.includes("production")||i.includes("prod"))&&(/(^|[.-])(dev|development|stag|stage|staging)($|[.-])/.test(r)||(o+=20)),o},Ec=(e,t)=>{let n=ve.resolve(process.cwd(),de.existsSync("ios")?"ios":"."),i=Bo(n,"project.pbxproj"),r=[];for(let o of i)try{let l=de.readFileSync(o,"utf8").matchAll(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/g);for(let a of l){let c=a[1]?.trim();c&&!c.includes("$")&&!c.startsWith("com.apple.")&&!r.includes(c)&&r.push(c)}}catch{}if(r.length!==0)return r.length===1?r[0]:r.map(o=>({bundleId:o,score:Ac(o,e,t)})).sort((o,s)=>s.score-o.score)[0]?.bundleId},An=e=>String(e||"").trim().toLowerCase().replace(/_/g,"-"),wn=(e,t)=>{let n=An(e);return t==="ios"&&(n==="internal"||n==="ad-hoc")?"adhoc":t==="android"&&["internal","adhoc","ad-hoc","development","dev","staging","stage"].includes(n)?"internal":n},Oo=(e,t,n)=>{let i=wn(e.distributionType||e.meta?.distributionType,n);return i?i===wn(t,n):!0},Do=(e,t,n)=>{let i=wn(e.distributionType||e.meta?.distributionType,n),r=wn(t,n);return i?i===r?3:n==="android"&&r!=="store"&&i!=="store"?2:0:1},Ic=e=>{let t=e.toLowerCase();return t==="development"||t==="dev"||t.startsWith("development-")||t.startsWith("dev-")||t.endsWith("-development")||t.endsWith("-dev")},wc=e=>{let t=e.toLowerCase();return t.includes("staging")||t.includes("stage")||t.includes("preview")||t.includes("adhoc")||t.includes("ad-hoc")},_c=(e,t)=>{let n=An(e.distribution),i=An(e.iosExportMethod),r=An(e.environment);return e.platform!=="ios"?n==="store"?"store":"internal":e.developmentClient||e.simulator?"development":i==="app-store"||n==="store"?"store":i==="development"||n==="development"?"development":i==="ad-hoc"||i==="adhoc"||n==="ad-hoc"||n==="adhoc"||n==="internal"?"adhoc":r==="production"||r==="store"?"store":r==="development"||r==="dev"?"development":r==="staging"||r==="stage"||r==="preview"?"adhoc":t.toLowerCase()==="production"||t.toLowerCase().includes("store")?"store":Ic(t)?"development":(wc(t),"adhoc")},Ho=e=>e.bundleId||e.bundleIdentifier||e.packageName||e.meta?.bundleId||e.meta?.bundleIdentifier||e.meta?.packageName,Co=(e,t)=>{if(!t)return!0;let n=Ho(e);return!n||n==="*"||n===t},No=(e,t)=>{let n=Ho(e);return!t||!n?0:n===t?2:n==="*"?1:-1},jo=e=>{try{let t=Buffer.from(e,"base64").toString("utf8"),n=t.match(/<key>application-identifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(!n)return;let i=t.match(/<key>TeamIdentifier<\/key>\s*<array>\s*<string>([^<]+)<\/string>/)?.[1]?.trim();if(i&&n.startsWith(`${i}.`))return n.slice(i.length+1);let r=n.indexOf(".");return r>=0?n.slice(r+1):n}catch{return}},$c=(e,t)=>{if(e===t||e==="*")return!0;if(e.endsWith(".*")){let n=e.slice(0,-2);return t.startsWith(`${n}.`)}return!1},vc=(e,t)=>{if(!t)return!0;let n=jo(e);if(n)return $c(n,t);try{return Buffer.from(e,"base64").toString("latin1").includes(t)}catch{return!0}},_n=async e=>{if(e.failOnly){(!e.projectId||!e.buildId)&&(v.error(R.red("--project-id and --build-id are required with --fail-only.")),process.exit(1));let l=e.error||"Build runner failed before it could report a final status.";try{await N.patch(`/builds/${e.projectId}/${e.buildId}`,{status:"failed",error:l,endTime:Date.now()}),v.info(R.yellow(`Marked build ${e.buildId} as failed.`));return}catch(a){v.error(R.red(`Could not mark build failed: ${a.message}`)),process.exit(1)}}await dc(e),await sc(e),e.platform!=="android"&&e.platform!=="ios"&&(v.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1)),e.autoSubmit&&e.platform==="ios"&&e.simulator&&(v.error(R.red("--auto-submit cannot be used with --simulator because simulator builds are not App Store artifacts.")),process.exit(1)),e.autoSubmit&&e.dryRun&&v.warn(R.yellow("--auto-submit is ignored during --dry-run."));let t=Ci(),n=e.buildId||Qd(),i=e.projectId,r=Date.now(),o=!!i,s=async l=>{if(i)try{await N.patch(`/builds/${i}/${n}`,{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 N.get(`/builds/${i}/${e.buildId}/source-url`);if(l.data.status!=="success")throw new Error("Failed to get source download URL from API");let a=await En.get(l.data.downloadUrl,{responseType:"stream"}),c=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),u=ve.join(ec.homedir(),m.workspacesDir,c);de.mkdirSync(u,{recursive:!0});let d=new Set(["node_modules",`.${m.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(de.existsSync(u)){let x=de.readdirSync(u);for(let b of x){if(d.has(b))continue;if(b==="ios"){let w=ve.join(u,"ios");try{let z=de.readdirSync(w);for(let Q of z)if(!p.has(Q))try{de.rmSync(ve.join(w,Q),{recursive:!0,force:!0})}catch{}}catch{}continue}let U=ve.join(u,b);try{de.rmSync(U,{recursive:!0,force:!0})}catch{}}}let f=ve.join(u,"source.zip"),h=a.data,S=de.createWriteStream(f);await new Promise((x,b)=>{h.pipe(S),h.on("error",U=>b(U)),S.on("finish",()=>x())}),new wo(f).extractAllTo(u,!0);try{de.unlinkSync(f)}catch{}process.chdir(u),v.info(R.green(`\u2713 Persistent workspace ready: ${u}`)),v.info(R.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${de.existsSync(ve.join(u,"node_modules"))?"\u2705":"\u274C"}, Pods=${de.existsSync(ve.join(u,"ios","Pods"))?"\u2705":"\u274C"}`)),t.stop()}catch(l){t.stop(`Failed to prepare isolated workspace: ${l.message}`),i&&await s(`Setup Error: ${l.message}`),process.exit(1)}}try{let l=e.repo;if(!l)try{l=Io("git config --get remote.origin.url").toString().trim()}catch{v.warn("Could not detect git repository URL.")}!l&&e.dryRun,l||(l="https://github.com/placeholder/repo.git"),v.info(`Build ID: ${R.cyan(n)}`);let a={},c={},u=null,d=$e(`./${m.configFileName}`);if(d||(v.error(R.red(`${m.configFileName} not found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`)),process.exit(1)),d){u=d;let O=rr(d);e.framework=O,i=d.projectId;let E=e.buildProfile||"production",D=nt(d,E);!D&&e.buildProfile&&(v.error(`Build profile '${E}' not found in ${m.configFileName}`),process.exit(1));let $=D||{};process.env.MACH_DEBUG&&v.info(R.dim(`Framework: ${O} | Build profile: ${E} | Platform: ${e.platform} | Distribution: ${$.distribution||"store"} | Environment: ${$.environment||E}`)),$.env&&(c=$.env,v.info(R.blue(`Use Build Profile: ${E}`)));let C=e.platform,g=$[C]||{},k=["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=H=>H==="androidPackage"?g.androidPackage??g.package??$.androidPackage??$.android?.package:H==="iosBundleIdentifier"?g.iosBundleIdentifier??g.bundleIdentifier??$.iosBundleIdentifier??$.ios?.bundleIdentifier:g[H]!==void 0?g[H]:$[H];for(let H of k){let P=F(H),q=H==="androidPackage"||H==="iosBundleIdentifier";P!==void 0&&(e[H]===void 0||q)&&(e[H]=P)}if(e.platform==="ios"&&!(g.iosBundleIdentifier??g.bundleIdentifier??$.iosBundleIdentifier??$.ios?.bundleIdentifier)){let P=Ec(e,E);P&&P!==e.iosBundleIdentifier&&(v.warn(R.yellow(`Detected native iOS bundle identifier ${P}; using it for credential lookup. Set build.${E}.ios.bundleIdentifier to make this explicit.`)),e.iosBundleIdentifier=P)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let V=H=>{if(!H)return H;if(H.startsWith("scripts.")){let P=H.split(".")[1],q=d.scripts?.[P];if(q)return q;v.warn(`Script reference not found: ${H}`)}return H};e.buildCommand=V(e.buildCommand),e.preBuild=V(e.preBuild),e.postBuild=V(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let J={...At(d,m.envPrefix),...At($,`${m.envPrefix}PROFILE_`)};a={...a,...c,...J},process.env.IOS_P12_PASSWORD&&!a.IOS_P12_PASSWORD&&(a.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!a.MATCH_PASSWORD&&(a.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&$.ios?.appleTeamId&&(e.iosTeamId=$.ios.appleTeamId),!e.iosTeamId&&d.submit?.[E]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[E].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(v.warn(R.yellow(`Check: Using 'production' Team ID for '${E}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?v.info(R.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):e.simulator||v.warn(R.yellow("\u26A0\uFE0F No iOS Team ID found. Device or archive signing may fail unless managed iOS credentials provide the team automatically.")))}let p="unknown";try{p=Io("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{v.warn("Failed to detect git branch.")}let f="1.0.0";try{de.existsSync("./package.json")&&(f=JSON.parse(de.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let h=e.buildProfile||"production",S="Internal";e.developmentClient?S="DevelopmentClient":h.toLowerCase().includes("store")||h.toLowerCase()==="production"?S="Store":h.toLowerCase().includes("preview")||h.toLowerCase().includes("staging")?S="Staging":(h.toLowerCase().includes("development")||h.toLowerCase().includes("dev"))&&(S="Development");let L=e.platform==="ios"?"iOS":"Android",x=e.platform==="ios"&&e.simulator?" (Simulator)":"",b=`${L}${x} v${f} (${S})`;if($n(e,{status:"created",projectId:i,buildId:n,platform:e.platform,profile:h,branch:p,version:f,buildType:S,developmentClient:!!e.developmentClient,summary:b}),i){try{let O=e.buildProfile||"production",E=e.environment||O;v.info(R.blue(`Fetching managed secrets for profile: ${O} (environment: ${E})...`));let $=(await N.get(`/projects/${i}/secrets/export?env=${E}`)).data;$.status==="success"&&$.secrets&&(a={...a,...$.secrets},Object.keys($.secrets).length>0&&v.info(R.magenta(`\u2713 Injected ${Object.keys($.secrets).length} secrets from Dashboard.`)))}catch(O){v.warn(`Failed to load managed secrets from Dashboard: ${O.message}`)}if(e.platform==="ios"&&e.simulator)v.info(R.dim("Skipping managed iOS signing credentials for simulator build."));else try{v.info(R.blue("Fetching managed credentials..."));let O=_c(e,h),E=e.platform==="ios"?e.iosBundleIdentifier:e.androidPackage,D=e.platform==="ios"?"bundle":"package";v.info(R.dim(` Credential target: ${D} ${E||"not set"} (${O})`));let $=await N.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:E,distributionType:O,teamId:e.platform==="ios"?e.iosTeamId:void 0}});if($.data.status==="success"&&$.data.credentials){let C=$.data.credentials;v.info(R.magenta(`\u2713 Found ${C.length} relevant credentials.`));let g=C.filter(P=>e.platform==="ios"&&P.type==="ios_profile"?Oo(P,O,e.platform)?Co(P,E):!1:e.platform==="android"&&P.type==="android_keystore"?Co(P,E):!!Oo(P,O,e.platform)).sort((P,q)=>No(q,E)*10+Do(q,O,e.platform)-(No(P,E)*10+Do(P,O,e.platform)));v.info(R.dim(` Filtered to ${g.length} credentials for distributionType: ${O}`));let k=!1,F=!1,V=!1,J=[];for(let P of g)if(!(P.type==="ios_cert"&&k||P.type==="ios_profile"&&F||P.type==="android_keystore"&&V)&&["ios_cert","ios_profile","android_keystore"].includes(P.type)&&(P.downloadUrl||jt(P)))try{let ye=await Fo(P,i);if(P.type==="ios_cert"&&!k)a.IOS_DIST_P12=ye,P.password?(a.IOS_P12_PASSWORD=P.password,v.info(R.dim(` - Injected ${P.name} as IOS_DIST_P12 with password from credential record`))):v.info(R.dim(` - Injected ${P.name} as IOS_DIST_P12`)),k=!0;else if(P.type==="ios_profile"&&!F){if(!vc(ye,E)){let Ae=jo(ye)||"unknown";throw new Error(`Provisioning profile ${P.name||jt(P)||"unknown"} is for a different bundle ID. Expected ${E}, found ${Ae}. Upload a ${O} profile for ${E}.`)}a.IOS_PROVISIONING_PROFILE=ye,v.info(R.dim(` - Injected ${P.name} as IOS_PROVISIONING_PROFILE`)),F=!0}else if(P.type==="android_keystore"&&!V){a.ANDROID_KEYSTORE_BASE64=ye;let Ae=P.keystorePassword||P.password,G=P.keyPassword||P.keystorePassword||P.password,j=P.alias||P.meta?.alias;if(Ae)a.ANDROID_STORE_PASSWORD=Ae,v.info(R.dim(" - Injected keystore password from credential record"));else{let K=["ANDROID_STORE_PASSWORD",...[O==="store"?"PRODUCTION":O==="internal"||O==="adhoc"?"STAGING":"DEVELOPMENT",O.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(Z=>`KEYSTORE_PASSWORD_${Z}`),"KEYSTORE_PASSWORD"].find(Z=>!!a[Z]);K&&a[K]&&(a.ANDROID_STORE_PASSWORD=a[K])}if(G?(a.ANDROID_KEY_PASSWORD=G,v.info(R.dim(" - Injected key password from credential record"))):a.ANDROID_KEY_PASSWORD=a.ANDROID_STORE_PASSWORD||"",j)a.ANDROID_KEY_ALIAS=j;else{let X=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(T=>!!a[T]);X&&(a.ANDROID_KEY_ALIAS=a[X])}v.info(R.dim(` - Injected ${P.name} as ANDROID_KEYSTORE_BASE64`)),V=!0}}catch(ye){J.push(`${P.name||P.type}: ${ye.message}`)}let H=e.platform==="ios"?e.simulator||k&&F:V||!g.some(P=>P.type==="android_keystore");if(J.length>0&&!H)throw new Error(`Credential setup failed:
|
|
1334
|
+
${J.map(P=>`- ${P}`).join(`
|
|
1335
|
+
`)}`);J.length>0&&v.warn(R.dim(` Skipped ${J.length} stale or unusable credential(s).`))}if(e.platform==="ios"&&!e.simulator){let C=e.buildProfile||"production",g=nt(d,C)||{},k=yc(d,g),F=bc(k),V=e.distribution!==void 0?e.distribution==="store":S==="Store",J=k===void 0&&V,H=e.autoVersion||F&&V||J,P=e.autoVersion||F&&V;if(F&&!V&&v.info(R.dim(` Skipping App Store Connect buildNumber lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){let q=e.iosBundleIdentifier||d.ios?.bundleIdentifier||d.expo?.ios?.bundleIdentifier,ye=Sc(d,g,C),Ae=$.data.credentials||[],G=Po(Ae,q);if(!G&&(P||J)){let j=await N.get(`/credentials/${i}`);G=Po(j.data.credentials||[],q)}if(G){t.start("Resolving latest iOS buildNumber from App Store Connect...");try{let j=G.keyId||G.meta?.keyId,X=G.issuerId||G.meta?.issuerId;if(!j||!X)throw new Error("App Store Connect credential is missing keyId or issuerId.");let T=await vo(G,i),K=await Dr({keyId:j,issuerId:X,privateKey:T,ascAppId:ye,bundleId:q}),Z=/^\d+$/.test(K.latestBuildNumber);Z?(a.BUILD_NUMBER=K.nextBuildNumber,delete a.MACH_IOS_BUILD_NUMBER_LOCKED):(a.BUILD_NUMBER=K.nextBuildNumber,a.CURRENT_PROJECT_VERSION=K.nextBuildNumber,a.MACH_IOS_BUILD_NUMBER_LOCKED="1"),t.stop(Z?`\u2713 Latest iOS buildNumber on App Store Connect: ${R.green(K.latestBuildNumber)} (Mach will assign >= ${K.nextBuildNumber})`:`\u2713 Resolved iOS buildNumber: ${R.green(K.nextBuildNumber)} (Latest on App Store Connect: ${K.latestBuildNumber})`)}catch(j){t.stop("iOS buildNumber lookup failed");let X=j.response?.data?.error?.message||j.message;if(P)throw new Error(`Auto-versioning failed: ${X}. Fix App Store Connect API key permissions or remove ios.buildNumber="auto".`);v.warn(R.yellow(`Could not check App Store Connect buildNumber: ${X}. Falling back to Mach counter.`))}}else if(P)throw new Error(`Auto-versioning failed: App Store Connect API key not found. Upload it with '${m.nameLower} credentials:service --platform ios'.`)}}if(e.platform==="android"){let C=e.buildProfile||"production",g=nt(d,C)||{},V=((g.android||{}).versionCode??g.androidVersionCode??d.android?.versionCode??d.expo?.android?.versionCode)==="auto",J=e.distribution!==void 0?e.distribution==="store":S==="Store",H=e.autoVersion||V&&J;if(V&&!H&&v.info(R.dim(` Skipping Google Play versionCode lookup for ${e.distribution||"non-store"} build. Pass --auto-version to force it.`)),H){t.start("Resolving latest versionCode from Google Play...");try{let P=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,q=($.data.credentials||[]).find(X=>X.type==="google_service_account"&&(!X.bundleId||X.bundleId===P));if(!q){let T=((await N.get(`/credentials/${i}`)).data.credentials||[]).filter(K=>K.type==="google_service_account");if(q=T.find(K=>K.type==="google_service_account"&&K.bundleId===P),!q&&T.length>0){let K=T.map(Z=>Z.bundleId).filter(Boolean).join(", ");throw new Error(`Google Service Account not found for package ${P}. Found service credential(s) for: ${K}.`)}}if(!q)throw new Error(`Google Service Account not found for package ${P}. Upload it under this package in Dashboard or run '${m.nameLower} credentials:service --platform android --package-name ${P}'.`);let ye=await vo(q,i),Ae=gc(ye,"Google Play service account");if(!Ae.client_email||!Ae.private_key)throw new Error("Google Play service account JSON is missing client_email or private_key.");let G=await _r(P,Ae);if(G==null)throw new Error("Could not retrieve any version information from Google Play.");let j=G+1;a.ANDROID_VERSION_CODE=j.toString(),t.stop(`\u2713 Resolved versionCode: ${R.green(j)} (Latest on Play Store: ${G})`)}catch(P){t.stop("Version resolution failed");let q=P.response?.data?.error?.message||P.message,ye=hc(q)?"This looks like a temporary network error while contacting Mach or Google Play. Retry the command, or build and submit as separate steps if it continues.":'Fix Google Play service account permissions or remove android.versionCode="auto".';throw new Error(`Auto-versioning failed: ${q}. ${ye}`)}}}if(e.platform==="ios"&&!e.simulator){let C=!!a.IOS_DIST_P12,g=!!a.IOS_PROVISIONING_PROFILE;if(!C||!g){let k=[...C?[]:["Distribution Certificate"],...g?[]:["Provisioning Profile"]].join(" and ");if(e.local&&e.buildId)throw new Error(`Missing iOS credentials: ${k}. Expected ${O} credentials for ${E||"the selected bundle ID"}. Run \`${m.nameLower} credentials --platform ios --profile ${h}\` and select ${E||"the correct bundle ID"}.`);v.error(R.red(`Missing iOS credentials: ${k}`)),e.quiet&&process.exit(1);let F=e.yes||await Ao({message:"Would you like to generate these credentials now?",initialValue:!0});if(F&&!In(F))return await Tt({platform:"ios",profile:h}),e.quiet||v.info(R.green("\u2713 Credentials setup complete! Restarting build phase...")),_n(e);e.quiet||v.info(R.yellow(`Run \`${m.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&!e.developmentClient&&(e.distribution==="internal"||e.distribution==="store")&&!(!!a.ANDROID_KEYSTORE_BASE64||!!a.ANDROID_KEYSTORE)){v.error(R.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let g=e.yes||await Ao({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(g&&!In(g))return await Tt({platform:"android",profile:h}),e.quiet||v.info(R.green("\u2713 Android Keystore setup complete! Restarting build phase...")),_n(e);e.quiet||v.info(R.yellow(`Run \`${m.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(O){(String(O.message||"").startsWith("Credential download failed")||String(O.message||"").startsWith("Credential setup failed")||String(O.message||"").startsWith("Missing iOS credentials")||String(O.message||"").startsWith("Auto-versioning failed"))&&(v.error(R.red(O.message)),process.exit(1)),e.platform==="ios"&&e.local&&e.buildId&&(v.error(R.red(`Failed to resolve iOS credentials: ${O.message}`)),process.exit(1)),v.warn(`Failed to resolve credentials: ${O.message}`)}}let U=!!(e.local&&e.buildId),w=!!(e.local||e.sshHost),z=!w&&!U;if(U){v.info(R.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let O=await si({...e,interactive:!1},n,a,i,{branch:p,version:f,summary:b,buildType:S});await Q(O),process.exit(0)}async function Q(O){let E=async D=>{if(i)try{await bn("Report failed build status",()=>N.patch(`/builds/${i}/${n}`,{status:"failed",error:D,endTime:Date.now()}),3)}catch($){v.warn(R.yellow(`Could not report failed build status: ${$.message}`))}};if(i&&O.length>0){let D=Ci(),$=[];e.quiet||D.start("Uploading artifacts to Dashboard...");try{for(let C of O){let g=ve.basename(C),k=de.statSync(C).size,F=ve.extname(g).toLowerCase(),V="application/octet-stream",J=await bn(`Create artifact upload URL for ${g}`,()=>N.post(`/builds/${i}/${n}/artifact-upload-url`,{fileName:g,fileType:V}));if(J.data.status!=="success")throw new Error(`Failed to get upload URL for ${g}`);await fc(C,J.data.uploadUrl,V),$.push({name:g,url:J.data.downloadUrl,size:k,type:F.substring(1)})}e.quiet||D.stop("Artifacts uploaded.")}catch(C){e.quiet||D.stop("Failed to upload artifacts.");let g=`Artifact upload failed: ${C.message}`;throw v.error(R.red(g)),await E(g),new Error(g)}if(i&&$.length>0)try{v.info(R.cyan(`
|
|
1336
|
+
\u{1F517} Download Links:`));for(let C of $)v.info(R.dim(` - ${C.name}: `)+R.blue.underline(C.url));await bn("Finalize build in dashboard",()=>N.patch(`/builds/${i}/${n}`,{status:"success",artifacts:$,endTime:Date.now()})),$n(e,{status:"success",projectId:i,buildId:n,platform:e.platform,profile:h,branch:p,version:f,buildType:S,developmentClient:!!e.developmentClient,summary:b,artifacts:$}),v.success(R.green(`
|
|
1337
|
+
\u2713 Build completed and reported to dashboard.`)),e.maestro&&!U&&await To(i,n,e,h),e.autoSubmit&&!U&&await Di(i,n,e,h)}catch(C){let g=`Build artifact uploaded but dashboard finalization failed: ${C.message}`;throw v.error(R.red(`
|
|
1338
|
+
${g}`)),await E(g),new Error(g)}}else if(i){let D="Build completed but produced no uploadable artifacts.";throw v.error(R.red(D)),await E(D),new Error(D)}}if(w){if(v.info(R.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!o){let O=process.argv.slice(3).join(" ");await N.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"building",branch:p,version:f,summary:b,startTime:r,buildType:S,buildProfile:h,buildArgs:O,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...ko(e,n,h,u)}),xo(e)}if(e.sshHost&&e.platform==="ios")await Ir(e,n,a,i),e.autoSubmit&&await Di(i,n,e,h);else{let O=await si({...e,interactive:!!e.local},n,a,i,{branch:p,version:f,summary:b,buildType:S});await Q(O)}return}if(z&&(v.info(R.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||t.start("Zipping and uploading local source...");let O=await N.post("/builds/source-upload-url",{projectId:i,buildId:n});if(O.data.status!=="success")throw t.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let E=new wo,D=de.readdirSync("."),$=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${m.nameLower}_cli`];for(let k of D){if($.includes(k))continue;de.statSync(k).isDirectory()?E.addLocalFolder(k,k):E.addLocalFile(k)}let C=E.toBuffer();e.quiet||t.message(`Uploading source (${(C.length/1024/1024).toFixed(1)} MB)...`);let g=!1;for(let k=1;k<=3;k++)try{await En.put(O.data.uploadUrl,C,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),g=!0;break}catch(F){if(k<3)t.message(`Upload attempt ${k} failed (${F.code||F.message}), retrying...`),await new Promise(V=>setTimeout(V,2e3*k));else throw F}if(e.quiet||t.stop("Source uploaded"),i){let k=process.argv.slice(3).join(" ");await N.post("/builds",{projectId:i,buildId:n,platform:e.platform,status:"pending",branch:p,version:f,summary:b,startTime:r,buildType:S,buildProfile:h,buildArgs:k,framework:e.framework,simulator:!!e.simulator,developmentClient:!!e.developmentClient,...ko(e,n,h,u)}),v.info(R.green("\u2713 Cloud build registered.")),xo(e)}e.platform==="android"&&await Ar(e,n,a,i,e.preBuild),e.quiet||v.info(R.cyan("\u{1F4E1} Connecting to build stream...")),await Oc(i,n,e),e.maestro&&await To(i,n,e,h),e.autoSubmit&&await Di(i,n,e,h);return}}catch(l){let a=l.message||"Build failed";l.response?.data?.message?a=l.response.data.message:l.message.includes("status code 402")?a="Insufficient wallet balance. Please add credits in the Dashboard.":l.message.includes("status code 403")&&(a="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await s(a),v.error(R.red(`\u2717 Build failed: ${a}`)),process.exit(1)}};async function To(e,t,n,i){v.info(R.cyan(`
|
|
1339
|
+
\u{1F3BC} Queuing managed Maestro test...`)),await mi({projectId:e,buildId:t,platform:n.platform,profile:i,maestroFlows:n.maestroFlows,maestroDevice:n.maestroDevice,maestroRetries:n.maestroRetries,maestroRecord:n.maestroRecord,maestroUseBuildSource:n.maestroUseBuildSource,maestroEnv:n.maestroEnv,quiet:n.quiet})}async function Di(e,t,n,i){if(!e){v.error(R.red("Auto-submit requires a linked Mach project. Run `mach link` or pass --project-id.")),process.exitCode=1;return}v.info(R.cyan(`
|
|
1340
|
+
Auto-submit: submitting the successful build...`));try{let r=await Rc(e,t);if(r?.autoSubmit){let o=r.submissionId?`${We}/submissions/${r.submissionId}?projectId=${encodeURIComponent(e)}`:void 0,s=String(r.status||"").toLowerCase(),l=String(r.autoSubmitStatus||"").toLowerCase(),a=r.submissionId||["success","completed","succeeded"].includes(s)||["starting","submitted","failed","skipped"].includes(l);if(r.submissionId?(v.info(R.green(`Auto-submit is already queued by Mach backend: ${r.submissionId}`)),v.info(R.dim(`Dashboard: ${o}`))):r.autoSubmitStatus==="failed"?v.warn(R.yellow(`Backend auto-submit failed: ${r.autoSubmitError||"Unknown error"}`)):a&&v.info(R.green("Auto-submit is registered with Mach backend; skipping local duplicate submit.")),a){ot(n,{status:r.autoSubmitStatus||"pending",projectId:e,submitId:r.submissionId,platform:n.platform,profile:i,buildId:t,dashboardUrl:o});return}}await Sn({platform:n.platform,profile:i,buildProfile:i,buildId:t,projectId:e,yes:n.yes,quiet:n.quiet,track:n.submitTrack,releaseStatus:n.submitReleaseStatus,rollout:n.submitRollout,changesNotSentForReview:n.submitChangesNotSentForReview,credentialId:n.submitCredentialId,packageName:n.androidPackage,jsonOutput:n.submitJsonOutput,submitArgs:Go(n,t,i)})}catch(r){v.error(R.red(`Auto-submit failed: ${r.message||r}`)),process.exitCode=1}}function Go(e,t,n){let i=["--platform",e.platform,"--profile",n,"--build-id",t];return e.submitTrack&&i.push("--track",String(e.submitTrack)),e.submitReleaseStatus&&i.push("--release-status",String(e.submitReleaseStatus)),e.submitRollout!==void 0&&i.push("--rollout",String(e.submitRollout)),e.submitChangesNotSentForReview&&i.push("--changes-not-sent-for-review"),e.submitCredentialId&&i.push("--credential-id",e.submitCredentialId),e.platform==="android"&&e.androidPackage&&i.push("--package-name",e.androidPackage),e.platform==="ios"&&e.iosBundleIdentifier&&i.push("--bundle-id",e.iosBundleIdentifier),e.submitJsonOutput&&i.push("--json-output",e.submitJsonOutput),i.join(" ")}async function Rc(e,t){try{let i=(await N.get(`/builds/${e}/${t}`)).data?.build;if(i?.autoSubmit)return i}catch(n){v.warn(R.dim(`Could not check backend auto-submit status: ${n.message}`))}return null}function Ko(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Pc(e,t,n){let i=n?.submit?.[t]?.android||{},r=n?.submit?.production?.android||{},o=e.submitTrack||i.track||r.track,s=e.submitReleaseStatus||i.releaseStatus||r.releaseStatus,l=e.submitRollout??i.rollout??i.userFraction??i.rolloutFraction??r.rollout??r.userFraction??r.rolloutFraction,a=e.submitChangesNotSentForReview??i.changesNotSentForReview??i.changes_not_sent_for_review??r.changesNotSentForReview??r.changes_not_sent_for_review;return Ko({track:o,releaseStatus:s,rollout:l,changesNotSentForReview:a===void 0?!1:a===!0||a==="true"||a==="1"})}function ko(e,t,n,i){if(!e.autoSubmit||e.dryRun)return{};let r=e.platform==="android"?Pc(e,n,i):{};return{autoSubmit:!0,autoSubmitStatus:"pending",autoSubmitOptions:Ko({platform:e.platform,profile:n,buildId:t,latest:!1,...r,credentialId:e.submitCredentialId,packageName:e.platform==="android"?e.androidPackage:void 0,bundleId:e.platform==="ios"?e.iosBundleIdentifier:void 0,submitArgs:Go(e,t,n)})}}function xo(e){!e.autoSubmit||e.dryRun||e.quiet||(v.info(R.green("\u2713 Auto-submit has been registered with the build.")),v.info(R.dim(" You can close this terminal; submission will start after build success.")))}function Mo(e){return`${We}/build/${e}`}function $n(e,t){if(!e.jsonOutput)return;let n=ve.resolve(e.jsonOutput),i={...t,url:t.url||Mo(t.buildId),dashboardUrl:t.dashboardUrl||Mo(t.buildId),updatedAt:new Date().toISOString()};try{let r=ve.dirname(n);r&&r!=="."&&de.mkdirSync(r,{recursive:!0}),de.writeFileSync(n,JSON.stringify(i,null,2))}catch(r){v.warn(R.yellow(`Could not write build metadata JSON: ${r.message}`))}}async function Oc(e,t,n){let i=Ci(),r="pending",o=0,s=0;for(n.quiet||i.start("Connecting to build stream...");;){try{let a=(await N.get(`/builds/${e}/${t}`)).data.build;if(a){if(r=a.status,r==="building")n.quiet||i.message("Build in progress...");else if(r==="failed")n.quiet||i.stop("Build failed."),$n(n,{status:"failed",projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,error:a.error||"Unknown error",artifacts:a.artifacts||[]}),v.error(R.red(`
|
|
1341
|
+
\u2717 Build failed: ${a.error||"Unknown error"}`)),process.exit(1);else if(r==="completed"||r==="success"){n.quiet||i.stop("Build successful!"),$n(n,{status:r,projectId:e,buildId:t,platform:n.platform,profile:a.buildProfile,buildType:a.buildType,developmentClient:!!a.developmentClient,version:a.version,summary:a.summary,artifacts:a.artifacts||[]}),v.success(R.green(`
|
|
1342
|
+
\u2713 Build completed successfully!`));try{n.quiet||(v.info(R.magenta(`
|
|
1343
|
+
\u{1F4F1} Installation Hub:`)),v.info(R.dim(" - View & Install Build: ")+R.white.underline(`${We}/build/${t}`)))}catch{}return}else if(r!=="pending"){n.quiet||i.stop(`Build status: ${r}`);return}}try{let u=(await N.get(`/builds/${e}/${t}/logs`)).data;if(u&&typeof u=="string"&&!n.quiet){let d=u.split(`
|
|
1344
|
+
`);if(d.length>o){for(let p=o;p<d.length;p++)d[p].trim()&&console.log(R.dim(` ${d[p]}`));o=d.length}}}catch{}s=0}catch{s++,s>10&&(i.stop("Connection lost."),v.error(R.red(`
|
|
1345
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(l=>setTimeout(l,3e3))}}import*as Dn from"http";import*as Jo from"net";import{execFile as Dc,execFileSync as Cn,execSync as yt,spawn as Vo}from"child_process";import ce from"chalk";import{log as ee}from"@clack/prompts";import Cc from"axios";import pe from"fs";import je from"os";import ie from"path";var et=7070,Kt=`http://127.0.0.1:${et}`,vt="com.radhya.mach.agent",$t="Mach Agent",Rt=`${vt}.service`,Nc=5e3,Tc=3e3,vn=null,Rn=null,Ge=()=>ie.join(je.homedir(),m.configDir),qo=()=>ie.join(je.homedir(),"Library","LaunchAgents"),Pn=()=>ie.join(qo(),`${vt}.plist`),Xo=()=>ie.join(je.homedir(),".config","systemd","user"),Ti=()=>ie.join(Xo(),Rt),ki=()=>ie.join(Ge(),"agent.cmd");function xi(){return`gui/${process.getuid?.()||Number(yt("id -u").toString().trim())}`}function Zo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Gt(e){return`<string>${Zo(e)}</string>`}function Mi(){let e=process.argv[1]?pe.realpathSync(process.argv[1]):"";if(!e||!pe.existsSync(e))throw new Error("Could not resolve the current Mach CLI entrypoint.");return[process.execPath,e,"agent","run"]}function Li(){let e=Qo(),t=process.platform==="win32"?[process.env.SystemRoot?ie.join(process.env.SystemRoot,"System32"):void 0,process.env.SystemRoot]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"],n={HOME:je.homedir(),PATH:[process.env.PATH,...e.flatMap(i=>[ie.join(i,"platform-tools"),ie.join(i,"emulator"),ie.join(i,"cmdline-tools","latest","bin"),ie.join(i,"tools","bin")]),...t].filter(Boolean).join(ie.delimiter)};for(let i of["ANDROID_HOME","ANDROID_SDK_ROOT","JAVA_HOME","SHELL"])process.env[i]&&(n[i]=process.env[i]);return n}function Qo(){let e=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT];if(process.platform==="darwin")e.push(ie.join(je.homedir(),"Library","Android","sdk"));else if(process.platform==="linux")e.push(ie.join(je.homedir(),"Android","Sdk"),ie.join(je.homedir(),"Android","sdk"),"/opt/android-sdk","/usr/lib/android-sdk");else if(process.platform==="win32"){let t=process.env.LOCALAPPDATA,n=process.env.USERPROFILE||je.homedir();e.push(t?ie.join(t,"Android","Sdk"):void 0,ie.join(n,"AppData","Local","Android","Sdk"))}return Array.from(new Set(e.filter(t=>!!t)))}function kc(e){return process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")?`${e}.exe`:e}function es(e,t){let n=kc(e);for(let i of Qo()){let r=ie.join(i,t,n);if(pe.existsSync(r))return r}return n}function ts(){return es("adb","platform-tools")}function ns(){return es("emulator","emulator")}function Ni(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%")}"`}function xc(){if(process.platform!=="linux")throw new Error("Linux service install requires Linux.");pe.mkdirSync(Ge(),{recursive:!0}),pe.mkdirSync(Xo(),{recursive:!0});let e=Mi(),t=Li(),n=Object.entries(t).map(([r,o])=>`Environment=${Ni(`${r}=${o}`)}`).join(`
|
|
1314
1346
|
`),i=`[Unit]
|
|
1315
1347
|
Description=Mach local device agent
|
|
1316
1348
|
After=default.target
|
|
1317
1349
|
|
|
1318
1350
|
[Service]
|
|
1319
1351
|
Type=simple
|
|
1320
|
-
ExecStart=${e.map(
|
|
1321
|
-
WorkingDirectory=${
|
|
1352
|
+
ExecStart=${e.map(Ni).join(" ")}
|
|
1353
|
+
WorkingDirectory=${Ni(je.homedir())}
|
|
1322
1354
|
${n}
|
|
1323
1355
|
Restart=on-failure
|
|
1324
1356
|
RestartSec=5
|
|
@@ -1327,12 +1359,12 @@ StandardError=append:%h/${m.configDir}/agent.error.log
|
|
|
1327
1359
|
|
|
1328
1360
|
[Install]
|
|
1329
1361
|
WantedBy=default.target
|
|
1330
|
-
`;return pe.writeFileSync(
|
|
1362
|
+
`;return pe.writeFileSync(Ti(),i),Ti()}function lt(e,t={}){try{return Cn("systemctl",["--user",...e],{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Mc(){if(process.platform!=="win32")throw new Error("Windows agent script requires Windows.");pe.mkdirSync(Ge(),{recursive:!0});let e=Li(),[t,n,...i]=Mi(),r=ie.join(Ge(),"agent.log"),o=ie.join(Ge(),"agent.error.log"),s=Object.entries(e).map(([c,u])=>`set "${c}=${u}"`).join(`\r
|
|
1331
1363
|
`),l=i.map(c=>`"${c.replace(/"/g,'\\"')}"`).join(" "),a=`@echo off\r
|
|
1332
1364
|
${s}\r
|
|
1333
1365
|
cd /d "${je.homedir()}"\r
|
|
1334
1366
|
"${t}" "${n}" ${l} >> "${r}" 2>> "${o}"\r
|
|
1335
|
-
`;return pe.writeFileSync(
|
|
1367
|
+
`;return pe.writeFileSync(ki(),a),ki()}function Vt(e,t={}){try{return Cn("schtasks.exe",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Lc(){if(process.platform!=="darwin")throw new Error("Background agent install currently supports macOS only.");pe.mkdirSync(Ge(),{recursive:!0}),pe.mkdirSync(qo(),{recursive:!0});let e=Mi(),t=Li(),n=ie.join(Ge(),"agent.log"),i=ie.join(Ge(),"agent.error.log"),r=Object.entries(t).map(([l,a])=>` <key>${Zo(l)}</key>
|
|
1336
1368
|
${Gt(a)}`).join(`
|
|
1337
1369
|
`),o=e.map(l=>` ${Gt(l)}`).join(`
|
|
1338
1370
|
`),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
@@ -1357,23 +1389,23 @@ ${r}
|
|
|
1357
1389
|
${Gt(i)}
|
|
1358
1390
|
</dict>
|
|
1359
1391
|
</plist>
|
|
1360
|
-
`;return pe.writeFileSync(
|
|
1361
|
-
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await
|
|
1362
|
-
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function Gc(){if(process.platform!=="darwin")return[];try{let e=await Rn("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Kc(){if(process.platform!=="darwin")return[];try{let e=await Rn("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function Vc(){let[e,t,n]=await Promise.all([jc(),Gc(),Kc()]);return[...e,...t,...n]}async function zc(){let e=Date.now();return _n&&e-_n.updatedAt<vc?_n.targets:($n||($n=Vc().then(t=>(_n={targets:t,updatedAt:Date.now()},t)).finally(()=>{$n=null})),$n)}async function Ho(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function Wc(e,t){let n=await _c({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=pe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function Yc(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ie.join(je.tmpdir(),`${et}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await Wc(t,s),i==="android"){Dn(Yo(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");yt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=yt(`find ${JSON.stringify(ie.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=yt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{yt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{yt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{pe.rmSync(o,{recursive:!0,force:!0})}}function Jc(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 yt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Uo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Uo(Jo(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function qc(){process.platform!=="darwin"&&Q.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Pn.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${et}`);if(i.method==="GET"&&o.pathname==="/local/devices"){zc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:et,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Ho(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await Yc(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await Ho(i),l=Jc(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(et,"127.0.0.1",()=>{Q.success(ce.green(`Local device agent running on http://localhost:${et}`)),Q.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),Q.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?Q.error(`Port ${et} is already in use \u2014 agent may already be running.`):Q.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function es(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await qc();return}if(t==="install"){await Bo();return}if(t==="status"){await Hc();return}if(t==="stop"){await Fo();return}if(t==="uninstall"){await Fc();return}if(t==="restart"){await Fo(),await Bo();return}Q.error(`Unknown agent action: ${e}`),Q.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as Rf}from"module";import{text as Zc,password as Qc,spinner as eu,isCancel as is}from"@clack/prompts";import Fi from"chalk";import zt from"fs";import ts from"path";import Xc from"os";var Mi=ts.join(Xc.homedir(),m.configDir),Ui=ts.join(Mi,"config.json");function Bi(){if(!zt.existsSync(Ui))return{};try{return JSON.parse(zt.readFileSync(Ui,"utf-8"))}catch{return{}}}function ns(e){zt.existsSync(Mi)||zt.mkdirSync(Mi,{recursive:!0});let n={...Bi(),...e};zt.writeFileSync(Ui,JSON.stringify(n,null,2))}async function rs(){let e=Bi(),t=await Zc({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(is(t))return;let n=await Qc({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(is(n))return;let i=eu();i.start("Authenticating...");try{let o=await(await fetch(`${bt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(Zi({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ns({lastLoginEmail:t}),i.stop(Fi.green("Login successful!"))):i.stop(Fi.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(Fi.red("Network error: "+r.message))}}import{log as On,outro as tu}from"@clack/prompts";import Wt from"chalk";async function os(){let e=Qi(),t=`${m.envPrefix}TOKEN`;e?On.success(Wt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):On.warn(Wt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(On.warn(Wt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),On.info(Wt.dim(`Run: unset ${t}`))),tu(Wt.blue("---"))}import{outro as nu,select as iu,spinner as ru,isCancel as ou}from"@clack/prompts";import Cn from"chalk";import Hi from"fs";import su from"path";var ss=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",au=()=>process.versions.node.split(".")[0]||"24";async function as(){if(!Pe()){console.log(Cn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=ru();t.start("Fetching projects...");try{let{data:n}=await P.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Cn.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),r=await iu({message:"Select a project to link:",options:i});if(ou(r))return;let o=su.join(process.cwd(),m.configFileName),s={};if(Hi.existsSync(o))try{s=JSON.parse(Hi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Ze("android"),c=s.ios?.bundleIdentifier||Ze("ios"),u=s.android||{},d=s.submit?.production?.android||{},f=s.submit?.production?.ios||{},p={projectId:r,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||au(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:ss(f.ascAppId),appleTeamId:ss(f.appleTeamId)}}}};Hi.writeFileSync(o,JSON.stringify(p,null,2)),nu(Cn.green(`Linked to project ${p.name} (${p.slug})`))}catch(n){t.stop(Cn.red("Error fetching projects: "+n.message))}}import{outro as lu,text as Nn,select as du,spinner as cu,isCancel as Yt}from"@clack/prompts";import Jt from"chalk";import uu from"fs";import fu from"path";import{randomUUID as pu}from"crypto";var mu=()=>process.versions.node.split(".")[0]||"24";async function ls(){if(!Pe()){console.log(Jt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await Nn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Yt(t))return;let n=await Nn({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(Yt(n))return;let i=await du({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Yt(i))return;let r="";if(i==="android"||i==="all"){let l=Ze("android");if(r=await Nn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Yt(r))return}let o="";if(i==="ios"||i==="all"){let l=Ze("ios");if(o=await Nn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Yt(o))return}let s=cu();s.start("Creating project...");try{let l=pu(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await P.post("/projects",c);if(u.status==="success"){s.stop(Jt.green("Project created successfully!"));let d=fu.join(process.cwd(),m.configFileName);uu.writeFileSync(d,JSON.stringify({projectId:l,name:t,slug:n,nodeVersion:mu(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),lu(Jt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Jt.red("creation failed: "+u.message))}catch(l){s.stop(Jt.red("Network error: "+l.message))}}import{spinner as ji,log as Re}from"@clack/prompts";import qt from"chalk";import Tn from"fs";import ds from"path";function Gi(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function gu(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function hu(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${gu(e[i])}`)].join(`
|
|
1392
|
+
`;return pe.writeFileSync(Pn(),s),Pn()}function at(e,t={}){try{return Cn("launchctl",e,{stdio:t.ignoreError?"ignore":"pipe"}),!0}catch(n){if(t.ignoreError)return!1;throw n}}function Uc(e){return new Promise(t=>setTimeout(t,e))}function On(e,t,n=Nc){return new Promise((i,r)=>{Dc(e,t,{timeout:n,maxBuffer:10*1024*1024,windowsHide:!0},(o,s,l)=>{if(o){let a=l?.toString().trim();r(new Error(a||o.message));return}i(s?.toString()||"")})})}async function is(){if(typeof fetch=="function"){let e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return(await fetch(`${Kt}/health`,{signal:e.signal})).ok}catch{return!1}finally{clearTimeout(t)}}return new Promise(e=>{let t=!1,n=r=>{t||(t=!0,e(r))},i=Dn.get(`${Kt}/health`,r=>{r.resume(),n(r.statusCode===200)});i.setTimeout(3e3,()=>{i.destroy(),n(!1)}),i.on("error",()=>n(!1))})}async function Fc(e=8e3){let t=Date.now()+e;for(;Date.now()<t;){if(await is())return!0;await Uc(250)}return!1}async function rs(){return new Promise(e=>{let t=!1,n=Jo.createConnection({host:"127.0.0.1",port:et}),i=r=>{t||(t=!0,n.destroy(),e(r))};n.setTimeout(1e3),n.once("connect",()=>i(!0)),n.once("timeout",()=>i(!1)),n.once("error",()=>i(!1))})}async function Ui(){if(await Fc()){ee.success(ce.green("Mach agent installed and started."));return}if(await rs()){ee.warn(`Mach agent service is installed, but port ${et} is held by a process that is not answering /health.`),ee.info(ce.dim(`Run \`${m.nameLower} agent stop\`, close any foreground \`${m.nameLower} agent\` terminal, then run \`${m.nameLower} agent install\` again.`));return}ee.warn(`Mach agent service is installed, but it did not start listening on ${Kt}.`)}async function Bc(){let e=Lc(),t=xi();at(["bootout",t,e],{ignoreError:!0}),at(["bootstrap",t,e],{ignoreError:!0})||at(["load","-w",e]),at(["enable",`${t}/${vt}`],{ignoreError:!0}),at(["kickstart","-k",`${t}/${vt}`],{ignoreError:!0}),await Ui(),ee.info(ce.dim(`It will start automatically when you log in. Plist: ${e}`)),ee.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function os(){let e=Pn(),t=xi();at(["bootout",t,e],{ignoreError:!0})||at(["unload","-w",e],{ignoreError:!0})?ee.success(ce.green("Mach agent service stopped.")):ee.warn("Mach agent service was not loaded.")}async function Hc(){await os();let e=Pn();pe.existsSync(e)&&pe.unlinkSync(e),ee.success(ce.green("Mach agent service uninstalled."))}async function jc(){let e=xc();lt(["daemon-reload"]),lt(["enable","--now",Rt]),await Ui(),ee.info(ce.dim(`It will start automatically when you log in. Service: ${e}`)),ee.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function Gc(){lt(["stop",Rt],{ignoreError:!0})?ee.success(ce.green("Mach agent service stopped.")):ee.warn("Mach agent service was not running.")}async function Kc(){lt(["disable","--now",Rt],{ignoreError:!0}),lt(["daemon-reload"],{ignoreError:!0});let e=Ti();pe.existsSync(e)&&pe.unlinkSync(e),lt(["daemon-reload"],{ignoreError:!0}),ee.success(ce.green("Mach agent service uninstalled."))}async function Vc(){let e=Mc();Vt(["/Create","/TN",$t,"/SC","ONLOGON","/TR",`"${e}"`,"/RL","LIMITED","/F"]),Vt(["/Run","/TN",$t],{ignoreError:!0}),await Ui(),ee.info(ce.dim(`It will start automatically when you log in. Task: ${$t}`)),ee.info(ce.dim(`Logs: ${ie.join(Ge(),"agent.log")}`))}async function ss(){Vt(["/End","/TN",$t],{ignoreError:!0})?ee.success(ce.green("Mach agent task stopped.")):ee.warn("Mach agent task was not running.")}async function zc(){await ss(),Vt(["/Delete","/TN",$t,"/F"],{ignoreError:!0});let e=ki();pe.existsSync(e)&&pe.unlinkSync(e),ee.success(ce.green("Mach agent task uninstalled."))}async function zo(){if(process.platform==="darwin")return Bc();if(process.platform==="linux")return jc();if(process.platform==="win32")return Vc();throw new Error(`Background agent install is not supported on ${process.platform}.`)}async function Wo(){if(process.platform==="darwin")return os();if(process.platform==="linux")return Gc();if(process.platform==="win32")return ss();ee.warn(`Background agent service control is not supported on ${process.platform}.`)}async function Wc(){if(process.platform==="darwin")return Hc();if(process.platform==="linux")return Kc();if(process.platform==="win32")return zc();ee.warn(`Background agent uninstall is not supported on ${process.platform}.`)}async function Yc(){let e=await is(),t=e?!0:await rs();if(e?ee.success(ce.green(`Mach agent is online at ${Kt}`)):t?ee.warn(`Mach agent port is open, but /health did not respond. Run \`${m.nameLower} agent restart\` if the dashboard still shows offline.`):ee.warn(`Mach agent is not responding at ${Kt}`),process.platform==="darwin"){let n=at(["print",`${xi()}/${vt}`],{ignoreError:!0});ee.info(ce.dim(`Login service: ${n?"installed/loaded":"not loaded"}`))}else if(process.platform==="linux"){let n=lt(["is-enabled",Rt],{ignoreError:!0}),i=lt(["is-active",Rt],{ignoreError:!0});ee.info(ce.dim(`Login service: ${n?"enabled":"not enabled"} / ${i?"active":"inactive"}`))}else if(process.platform==="win32"){let n=Vt(["/Query","/TN",$t],{ignoreError:!0});ee.info(ce.dim(`Login task: ${n?"installed":"not installed"}`))}}async function Jc(){let e=[];try{(await On(ts(),["devices","-l"])).split(`
|
|
1393
|
+
`).forEach(n=>{if(n.includes("List of devices")||!n.trim())return;let i=n.split(/\s+/);if(i.length<2||i[1]!=="device")return;let r=i[0],o=n.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:o?o[1].replace(/_/g," "):r,status:"online",details:n.trim()})})}catch{}try{let n=(await On(ns(),["-list-avds"])).split(`
|
|
1394
|
+
`).filter(r=>!!r.trim()),i=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));n.forEach(r=>{i||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}return e}async function qc(){if(process.platform!=="darwin")return[];try{let e=await On("/usr/bin/xcrun",["simctl","list","devices","--json"]),t=JSON.parse(e),n=[];return Object.entries(t.devices||{}).forEach(([i,r])=>{r.forEach(o=>{o.isAvailable&&n.push({id:o.udid,platform:"ios",type:"simulator",name:o.name,status:o.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${o.name} (${i})`})})}),n}catch{return[]}}async function Xc(){if(process.platform!=="darwin")return[];try{let e=await On("/usr/bin/xcrun",["devicectl","list","devices","--json-output","-"]);return(JSON.parse(e).result?.devices||[]).filter(n=>{let i=n.connectionProperties?.transportType;return i==="wired"||i==="localNetwork"}).map(n=>{let i=n.connectionProperties?.transportType,r=n.deviceProperties?.name||"iPhone";return{id:n.identifier,platform:"ios",type:"physical",name:r,status:"online",details:`${r} (${n.model?.name||n.hardwareModel||""}) - ${i}`}})}catch{return[]}}async function Zc(){let[e,t,n]=await Promise.all([Jc(),qc(),Xc()]);return[...e,...t,...n]}async function Qc(){let e=Date.now();return vn&&e-vn.updatedAt<Tc?vn.targets:(Rn||(Rn=Zc().then(t=>(vn={targets:t,updatedAt:Date.now()},t)).finally(()=>{Rn=null})),Rn)}async function Yo(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));return t.length===0?{}:JSON.parse(Buffer.concat(t).toString("utf-8"))}async function eu(e,t){let n=await Cc({method:"GET",url:e,responseType:"stream",timeout:12e4}),i=pe.createWriteStream(t);n.data.pipe(i),await new Promise((r,o)=>{i.on("finish",r),i.on("error",o)})}async function tu(e,t,n){let i=n||(t.toLowerCase().includes(".apk")?"android":"ios"),r=t.toLowerCase().includes(".ipa"),o=pe.mkdtempSync(ie.join(je.tmpdir(),`${et}-install-`)),s=ie.join(o,i==="android"?"install.apk":r?"install.ipa":"install.zip");try{if(await eu(t,s),i==="android"){Cn(ts(),["-s",e,"install","-r",s],{stdio:"pipe"});return}if(process.platform!=="darwin")throw new Error("iOS local install requires macOS.");yt(`unzip -o ${JSON.stringify(s)} -d ${JSON.stringify(o)}`,{stdio:"pipe"});let l="";try{l=yt(`find ${JSON.stringify(ie.join(o,"Payload"))} -maxdepth 1 -name "*.app" 2>/dev/null | head -n 1`,{stdio:"pipe"}).toString().trim()}catch{}if(l||(l=yt(`find ${JSON.stringify(o)} -name "*.app" -type d | head -n 1`,{stdio:"pipe"}).toString().trim()),!l)throw new Error(`No .app bundle found inside the ${r?"IPA":"archive"}.`);try{yt(`/usr/bin/xcrun devicectl device install app --device ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch(a){try{yt(`/usr/bin/xcrun simctl install ${JSON.stringify(e)} ${JSON.stringify(l)}`,{stdio:"pipe"})}catch{throw new Error(a.stderr?.toString().trim()||a.message||"iOS install failed.")}}}finally{pe.rmSync(o,{recursive:!0,force:!0})}}function nu(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 yt(`/usr/bin/xcrun simctl boot ${JSON.stringify(e)}`,{stdio:"pipe"}),Vo("open",["-a","Simulator"],{detached:!0,stdio:"ignore"}).unref(),"Simulator booting..."}if(t==="android")return Vo(ns(),["-avd",e],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),"Emulator booting in background...";throw new Error("Invalid platform.")}async function iu(){process.platform!=="darwin"&&ee.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=Dn.createServer((i,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),i.method==="OPTIONS"){r.writeHead(204),r.end();return}let o=new URL(i.url||"/",`http://localhost:${et}`);if(i.method==="GET"&&o.pathname==="/local/devices"){Qc().then(s=>{r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",targets:s}))}).catch(s=>{r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:s.message}))});return}if(i.method==="GET"&&o.pathname==="/health"){r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",service:"mach-agent",port:et,platform:process.platform}));return}if(i.method==="POST"&&o.pathname==="/install-local"){t(i,r);return}if(i.method==="POST"&&o.pathname==="/local/boot"){n(i,r);return}r.writeHead(404),r.end()}),t=async(i,r)=>{try{let{deviceId:o,artifactUrl:s,platform:l}=await Yo(i);if(!o||!s){r.writeHead(400,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:"deviceId and artifactUrl are required"}));return}await tu(o,s,l),r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:`Installed on ${o}`}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local install failed"}))}},n=async(i,r)=>{try{let{id:o,platform:s}=await Yo(i),l=nu(o,s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"success",message:l}))}catch(o){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"error",message:o.message||"Local device launch failed"}))}};e.listen(et,"127.0.0.1",()=>{ee.success(ce.green(`Local device agent running on http://localhost:${et}`)),ee.info(ce.dim("Keep this running while using the Install Hub on the dashboard.")),ee.info(ce.dim("Press Ctrl+C to stop."))}),e.on("error",i=>{i.code==="EADDRINUSE"?ee.error(`Port ${et} is already in use \u2014 agent may already be running.`):ee.error(`Agent error: ${i.message}`),process.exit(1)}),await new Promise(()=>{})}async function as(e="start"){let t=String(e||"start").toLowerCase();if(t==="start"||t==="run"){await iu();return}if(t==="install"){await zo();return}if(t==="status"){await Yc();return}if(t==="stop"){await Wo();return}if(t==="uninstall"){await Wc();return}if(t==="restart"){await Wo(),await zo();return}ee.error(`Unknown agent action: ${e}`),ee.info(ce.dim(`Use: ${m.nameLower} agent start | install | status | restart | stop | uninstall`)),process.exit(1)}import{createRequire as kf}from"module";import{text as ou,password as su,spinner as au,isCancel as cs}from"@clack/prompts";import ji from"chalk";import zt from"fs";import ls from"path";import ru from"os";var Fi=ls.join(ru.homedir(),m.configDir),Bi=ls.join(Fi,"config.json");function Hi(){if(!zt.existsSync(Bi))return{};try{return JSON.parse(zt.readFileSync(Bi,"utf-8"))}catch{return{}}}function ds(e){zt.existsSync(Fi)||zt.mkdirSync(Fi,{recursive:!0});let n={...Hi(),...e};zt.writeFileSync(Bi,JSON.stringify(n,null,2))}async function us(){let e=Hi(),t=await ou({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(r){if(r.length===0)return"Email is required!"}});if(cs(t))return;let n=await su({message:"Enter your password:",validate(r){if(r.length===0)return"Password is required!"}});if(cs(n))return;let i=au();i.start("Authenticating...");try{let o=await(await fetch(`${bt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:n})})).json();o.status==="success"&&o.user.token?(er({id:o.user.id,email:t,token:o.user.token,refreshToken:o.user.refreshToken}),ds({lastLoginEmail:t}),i.stop(ji.green("Login successful!"))):i.stop(ji.red("Login failed: "+(o.message||"Unknown error")))}catch(r){i.stop(ji.red("Network error: "+r.message))}}import{log as Nn,outro as lu}from"@clack/prompts";import Wt from"chalk";async function fs(){let e=tr(),t=`${m.envPrefix}TOKEN`;e?Nn.success(Wt.green(`Logged out. Removed saved credentials from ~/${m.configDir}/credentials.json.`)):Nn.warn(Wt.yellow(`No saved ${m.name} credentials found.`)),process.env[t]&&(Nn.warn(Wt.yellow(`${t} is still set in this shell. Commands will continue to authenticate with that token until you unset it.`)),Nn.info(Wt.dim(`Run: unset ${t}`))),lu(Wt.blue("---"))}import{outro as du,select as cu,spinner as uu,isCancel as fu}from"@clack/prompts";import Tn from"chalk";import Gi from"fs";import pu from"path";var ps=e=>e==="1234567890"||e==="ABC123DEFG"||e==="XXXXXXXXXX"?"":typeof e=="string"?e:"",mu=()=>process.versions.node.split(".")[0]||"24";async function ms(){if(!Pe()){console.log(Tn.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=uu();t.start("Fetching projects...");try{let{data:n}=await N.get("/projects");if(t.stop("Projects loaded."),n.status!=="success"||!n.projects||n.projects.length===0){console.log(Tn.yellow(`No projects found. Run \`${m.nameLower} init\` to create one.`));return}let i=n.projects.map(h=>({value:h.projectId,label:`${h.name} (${h.slug})`})),r=await cu({message:"Select a project to link:",options:i});if(fu(r))return;let o=pu.join(process.cwd(),m.configFileName),s={};if(Gi.existsSync(o))try{s=JSON.parse(Gi.readFileSync(o,"utf-8"))}catch{}let l=n.projects.find(h=>h.projectId===r),a=s.android?.package||Ze("android"),c=s.ios?.bundleIdentifier||Ze("ios"),u=s.android||{},d=s.submit?.production?.android||{},p=s.submit?.production?.ios||{},f={projectId:r,framework:ir(s.framework)||ln,name:l?.name,slug:l?.slug,nodeVersion:s.nodeVersion||mu(),scheme:l?.slug?.toLowerCase()||"app",android:{...u,package:a||"",versionCode:u.versionCode||"auto"},ios:{bundleIdentifier:c||"",buildNumber:s.ios?.buildNumber||"auto"},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{...d,track:d.track||"internal",releaseStatus:d.releaseStatus||"completed"},ios:{ascAppId:ps(p.ascAppId),appleTeamId:ps(p.appleTeamId)}}}};Gi.writeFileSync(o,JSON.stringify(f,null,2)),du(Tn.green(`Linked to project ${f.name} (${f.slug})`))}catch(n){t.stop(Tn.red("Error fetching projects: "+n.message))}}import{outro as gu,text as kn,select as hu,spinner as yu,isCancel as Yt}from"@clack/prompts";import Jt from"chalk";import Su from"fs";import bu from"path";import{randomUUID as Au}from"crypto";var Eu=()=>process.versions.node.split(".")[0]||"24";async function gs(){if(!Pe()){console.log(Jt.red(`You are not logged in. Run \`${m.nameLower} login\` first.`));return}let t=await kn({message:"Project Name:",placeholder:"My Awesome App",validate(l){if(l.length===0)return"Name is required!"}});if(Yt(t))return;let n=await kn({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(Yt(n))return;let i=await hu({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(Yt(i))return;let r="";if(i==="android"||i==="all"){let l=Ze("android");if(r=await kn({message:"Android Package Name:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Package name is required for Android!"}}),Yt(r))return}let o="";if(i==="ios"||i==="all"){let l=Ze("ios");if(o=await kn({message:"iOS Bundle Identifier:",initialValue:l||"",placeholder:"com.example.app",validate(a){if(a.length===0)return"Bundle ID is required for iOS!"}}),Yt(o))return}let s=yu();s.start("Creating project...");try{let l=Au(),c={projectId:l,name:t,slug:n,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:u}=await N.post("/projects",c);if(u.status==="success"){s.stop(Jt.green("Project created successfully!"));let d=bu.join(process.cwd(),m.configFileName);Su.writeFileSync(d,JSON.stringify({projectId:l,framework:ln,name:t,slug:n,nodeVersion:Eu(),...r?{android:{package:r,versionCode:"auto"}}:{},...o?{ios:{bundleIdentifier:o,buildNumber:"auto"}}:{},build:{development:{environment:"development",distribution:"development"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal",releaseStatus:"completed"},ios:{ascAppId:"",appleTeamId:""}}}},null,2)),gu(Jt.green(`Initialized project ${t} and linked locally!`))}else s.stop(Jt.red("creation failed: "+u.message))}catch(l){s.stop(Jt.red("Network error: "+l.message))}}import{spinner as Ki,log as Re}from"@clack/prompts";import qt from"chalk";import xn from"fs";import hs from"path";function Vi(e,t,n,i){let r=e?.response?.status,o=e?.response?.data?.message||e?.response?.data?.error,s=i?` ${i}`:"";return r===401?`Not logged in or token expired while trying to ${n}${s}. Run \`${m.nameLower} login\` and try again.`:r===403?[`Permission denied while trying to ${n}${s}.`,o?`API says: ${o}.`:void 0,`Current Mach account/token does not have access to project ${t}.`,`Run \`${m.nameLower} login\` with the correct account, or ask a project owner to grant access.`].filter(Boolean).join(" "):r===404?[`Project or environment endpoint was not found while trying to ${n}${s}.`,`Project ID: ${t}.`,o?`API says: ${o}.`:void 0].filter(Boolean).join(" "):r?`Failed to ${n}${s}: ${o||`API returned HTTP ${r}`}`:`Network error while trying to ${n}${s}: ${e?.message||"Unknown error"}`}function Iu(e){let t=String(e??"");return t===""?'""':/^[A-Za-z0-9_./:@%+-]+$/.test(t)?t:JSON.stringify(t)}function wu(e,t){return`${[`# Generated by ${m.nameLower} env pull --environment ${t}`,"# Do not commit this file.","",...Object.keys(e).sort((i,r)=>i.localeCompare(r)).map(i=>`${i}=${Iu(e[i])}`)].join(`
|
|
1363
1395
|
`)}
|
|
1364
|
-
`}async function
|
|
1365
|
-
`))}else dt.info(Ce.dim(`Metro URL: http://localhost:${l}`));let u=
|
|
1366
|
-
Profile Settings:`)),
|
|
1367
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{
|
|
1396
|
+
`}async function ys(e,t,n={}){let i=Pe();if(!i){Re.error(`You are not logged in. Run \`${m.nameLower} login\` first.`);return}let r=hs.join(process.cwd(),m.configFileName);if(!xn.existsSync(r)){Re.error(`No ${m.configFileName} found. Run \`${m.nameLower} init\` or \`${m.nameLower} link\` first.`);return}let o;try{o=JSON.parse(xn.readFileSync(r,"utf-8"))}catch{Re.error(`Failed to parse ${m.configFileName}`);return}let{projectId:s}=o;if(!s){Re.error(`${m.configFileName} is missing projectId.`);return}e==="set"?await _u(s,t,i):e==="list"?await $u(s,i):e==="pull"||e==="download"||e==="export"?await vu(s,n):Re.error(`Unknown env action: ${e}. Use 'set', 'list', or 'pull'.`)}async function _u(e,t,n){if(t.length===0){Re.error(`Usage: ${m.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Ki();i.start("Setting environment variables...");let r=0,o=0;for(let s of t){let[l,...a]=s.split("="),c=a.join("=");if(!l||c===void 0){Re.warn(`Invalid format for argument: ${s}. Expected KEY=VALUE.`),o++;continue}try{let u={key:l.trim(),value:c,type:"env",environment:"global",visibility:"secret"},{data:d}=await N.post(`/projects/${e}/secrets`,u);d.status==="success"?r++:(Re.error(`Failed to set ${l}: ${d.message}`),o++)}catch(u){Re.error(Vi(u,e,"set",l)),o++}}i.stop(`Set ${r} variable(s). ${o>0?`${o} failed.`:""}`)}async function $u(e,t){let n=Ki();n.start("Fetching environment variables...");try{let{data:i}=await N.get(`/projects/${e}/secrets`);if(i.status==="success"){n.stop("Fetched variables.");let r=i.secrets||[];r.length===0?Re.info("No environment variables found for this project."):(Re.info(qt.bold("Environment Variables (Global & Scoped):")),r.forEach(o=>{let s=o.visibility==="plain"?o.value:"********";console.log(` ${qt.cyan(o.key)} = ${s} ${qt.gray(`[${o.environment}]`)}`)}))}else n.stop(qt.red(`Failed to fetch variables: ${i.message}`))}catch(i){n.stop("Failed to fetch variables."),Re.error(Vi(i,e,"list"))}}async function vu(e,t){let n=(t.environment||"development").trim(),i=t.out||".env.local",r=hs.resolve(process.cwd(),i);if(xn.existsSync(r)&&!t.overwrite){Re.error(`${i} already exists. Re-run with \`--overwrite\` to replace it.`);return}let o=Ki();o.start(`Downloading ${n} environment variables...`);try{let{data:s}=await N.get(`/projects/${e}/secrets/export?env=${encodeURIComponent(n)}`);if(s.status!=="success"){o.stop(qt.red(`Failed to download variables: ${s.message||"Unknown API error"}`));return}let l=s.secrets||{},a=wu(l,n);xn.writeFileSync(r,a,{encoding:"utf-8",mode:384}),o.stop(`Wrote ${Object.keys(l).length} variable(s) to ${i}.`)}catch(s){o.stop("Failed to download variables."),Re.error(Vi(s,e,"pull"))}}import{spinner as Ru,log as St,outro as Pu}from"@clack/prompts";import zi from"chalk";import Ss from"fs";import Ou from"path";import{execSync as Du}from"child_process";import Cu from"adm-zip";import Nu from"axios";import{randomUUID as Tu}from"crypto";async function bs(e){St.info(zi.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let t=$e();(!t||!t.projectId)&&(St.error(`No ${m.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let n=t.projectId,i=e.branch||"production",r="1.0.0";try{r=JSON.parse(Ss.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{St.warn("Could not read package.json version. Defaulting to 1.0.0")}let o=Ru();o.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${r})...`);try{Du("npx expo export --platform all",{stdio:"ignore"})}catch(c){o.stop("Compilation failed."),St.error(`Failed to export JS bundles using Expo: ${c.message}`),process.exit(1)}o.message("Zipping artifact payload...");let s=Ou.join(process.cwd(),"dist");Ss.existsSync(s)||(o.stop("Missing dist folder."),St.error("The `dist` directory was not created. Export failed."),process.exit(1));let l=new Cu;l.addLocalFolder(s,"dist");let a=l.toBuffer();o.message("Uploading payload to Mach Cloud...");try{let c=Tu(),u=await N.post("/builds/source-upload-url",{projectId:n,buildId:c});if(u.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:d,key:p}=u.data;await Nu.put(d,a,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),o.message(`Promoting Update to ${i}...`),await N.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"android",updateId:`${c}-android`,manifestKey:p}),await N.post("/updates/publish",{projectId:n,channelName:i,runtimeVersion:r,platform:"ios",updateId:`${c}-ios`,manifestKey:p}),o.stop("Update Live!"),Pu(zi.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),St.info(zi.dim(`Any app running runtime '${r}' will download this bundle smoothly.`))}catch(c){o.stop("Update failed during Cloud Sync."),St.error(`Upload error: ${c.message}`),process.exit(1)}}import{intro as ku,outro as As,log as Pt}from"@clack/prompts";import Je from"chalk";async function Es(){ku(Je.blue(`${m.name} CLI - User Profile`));let e=Pe();if(!e){Pt.warn(Je.yellow("You are not logged in.")),Pt.info(`Run \`${m.nameLower} login\` to authenticate.`),As();return}Pt.info(`${Je.bold("Logged in as:")} ${Je.green(e.email)}`);try{await N.get("/projects");let n=Pe().token.split(".");if(n.length===3){let i=JSON.parse(Buffer.from(n[1],"base64").toString());if(i.exp){let r=new Date(i.exp*1e3),o=new Date,s=r.getTime()-o.getTime();if(s>0){let l=Math.round(s/6e4),a=(l/60).toFixed(1);Pt.info(`${Je.bold("Token status:")} Valid (Expires in ~${a}h / ${l}m)`)}else Pt.warn(`${Je.bold("Token status:")} ${Je.red("Expired")} (Auto-refresh failed)`)}}}catch{Pt.warn(`${Je.bold("Token status:")} ${Je.red("Unreachable")} (Session might be truly expired)${bt}`)}As(Je.blue("---"))}import{spawn as Lu}from"child_process";import{log as dt}from"@clack/prompts";import Ce from"chalk";import Uu from"fs";import xu from"net";async function Mu(e){return new Promise(t=>{let n=xu.createServer();n.once("error",i=>{i.code==="EADDRINUSE"?t(!0):t(!1)}),n.once("listening",()=>{n.close(),t(!1)}),n.listen(e,"0.0.0.0")})}async function Is(e,t=20){let n=e;for(;n<e+t;){if(!await Mu(n))return n;n++}throw new Error(`Could not find an available port after ${t} attempts starting from ${e}.`)}var ws=async e=>{dt.info(Ce.blue(`Starting ${m.name} Dev Orchestrator...`));let t=$e(),n=e.buildProfile||"development",i=t?nt(t,n):null,r={...process.env};if(t?.projectId)try{dt.info(Ce.dim(`Fetching managed secrets for profile: ${n}...`));let d=await N.get(`/projects/${t.projectId}/secrets/export?env=${n}`);d.data?.status==="success"&&d.data.secrets&&(Object.assign(r,d.data.secrets),dt.info(Ce.magenta(`\u2713 Injected secrets from ${m.name} Dashboard.`)))}catch{dt.warn("Could not fetch managed secrets. Running with local env only.")}t&&Object.assign(r,At(t,m.envPrefix)),i&&(Object.assign(r,At(i,`${m.envPrefix}PROFILE_`)),i.env&&Object.assign(r,i.env));let o=!1;try{let d=JSON.parse(Uu.readFileSync("package.json","utf-8"));o=!!(d.dependencies?.expo||d.devDependencies?.expo)}catch{dt.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let s=Number(e.port||i?.port||8081),l=await Is(s);l!==s&&dt.info(Ce.yellow(`Port ${s} is busy. ${m.name} is using ${l} instead.`));let a=process.platform==="win32"?"npx.cmd":"npx",c=[];if(o?(c=["expo","start","--port",String(l)],e.clear&&c.push("--clear"),e.tunnel&&c.push("--tunnel"),e.lan&&c.push("--lan"),e.localhost&&c.push("--localhost"),e.ios&&c.push("--ios"),e.android&&c.push("--android"),e.web&&c.push("--web")):(c=["react-native","start","--port",String(l)],e.clear&&c.push("--clear")),o){let d=[`${Ce.cyan("i")} open iOS simulator`,`${Ce.cyan("a")} open Android emulator/device`,`${Ce.cyan("w")} open web`,`${Ce.cyan("r")} reload app`];dt.info([Ce.bold("Launch controls"),...d.map(p=>` ${p}`),"",Ce.dim("Direct launch: mach start --ios | --android | --web"),Ce.dim(`Metro URL: http://localhost:${l}`)].join(`
|
|
1397
|
+
`))}else dt.info(Ce.dim(`Metro URL: http://localhost:${l}`));let u=Lu(a,c,{stdio:"inherit",env:r});return new Promise((d,p)=>{u.on("exit",f=>{f===0?d():p(new Error(`Dev server exited with code ${f}`))}),u.on("error",f=>{p(f)})})};import{log as Oe}from"@clack/prompts";import Ke from"chalk";var _s=async e=>{let t=$e();t||(Oe.error(Ke.red(`No ${m.configFileName} found in the current directory.`)),process.exit(1));let n=e.profile||"development",i=nt(t,n);if(e.json){console.log(JSON.stringify({project:t,resolved:i},null,2));return}Oe.info(Ke.bgBlue.white(` Resolved ${m.name} Config [${n}] `)),Oe.info(Ke.dim("----------------------------------------")),Oe.info(`${Ke.blue("Project ID:")} ${t.projectId}`),Oe.info(`${Ke.blue("Name:")} ${t.name}`),Oe.info(`${Ke.blue("Scheme:")} ${t.scheme}`),i?(Oe.info(Ke.dim(`
|
|
1398
|
+
Profile Settings:`)),Oe.info(`${Ke.cyan("Distribution:")} ${i.distribution||"none"}`),Oe.info(`${Ke.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(Oe.info(Ke.dim(`
|
|
1399
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([r,o])=>{Oe.info(` ${r}=${o}`)}))):Oe.warn(`Profile '${n}' not found.`),Oe.info(Ke.dim("----------------------------------------"))};import{log as Ne,spinner as Qt,text as $s,select as vs,confirm as Fu,isCancel as Xt,cancel as Zt,outro as en,note as Bu}from"@clack/prompts";import re from"chalk";import{execSync as Hu}from"child_process";async function ju(){try{let e=Hu("xcrun devicectl list devices --json-output -",{stdio:["pipe","pipe","pipe"]}).toString();return(JSON.parse(e).result?.devices||[]).filter(i=>i.connectionProperties?.transportType==="wired"||i.connectionProperties?.transportType==="localNetwork").map(i=>({udid:i.identifier,name:i.deviceProperties?.name||"Unknown Device",model:i.hardwareProperties?.marketingName||"iPhone"}))}catch{return[]}}var Rs=e=>e?.trim().toUpperCase()||void 0;function Ps(e){let t=$e(),n=t?or(t):{},i=Rs(e.teamId),r=i||n.teamId;return{...n,teamId:r,developerTeamId:i||n.developerTeamId||r}}async function Gu(e){let t=e.udid,n=e.name,i=Ps(e),r=i.teamId;if(!t){let s=Qt();s.start("Scanning for connected iOS devices...");let l=await ju();if(s.stop(l.length>0?`Found ${l.length} device(s)`:"No devices detected"),l.length===1)t=l[0].udid,n=n||l[0].name,Ne.info(`Detected: ${re.bold(n)} (${re.dim(t.substring(0,12)+"...")})`);else if(l.length>1){let a=await vs({message:"Select a device to register:",options:l.map(u=>({value:u.udid,label:`${u.name} (${u.model})`,hint:u.udid.substring(0,12)+"..."}))});if(Xt(a)){Zt("Cancelled");return}t=a;let c=l.find(u=>u.udid===t);n=n||c.name}else{Ne.info(re.dim("No connected devices found. Enter UDID manually."));let a=await $s({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(c){if(c.length<10)return"UDID seems too short"}});if(Xt(a)){Zt("Cancelled");return}t=a}}if(!n){let s=await $s({message:"Device name:",placeholder:"Nitesh's iPhone",validate(l){if(l.length===0)return"Name is required"}});if(Xt(s)){Zt("Cancelled");return}n=s}let o=Qt();o.start("Registering device...");try{await N.post("/devices",{udid:t,name:n,platform:"ios",addedVia:"cli",teamId:r,teamName:i.teamName,developerTeamId:i.developerTeamId,appStoreConnectTeamId:i.appStoreConnectTeamId,providerId:i.providerId,providerName:i.providerName}),o.stop(re.green("Device registered!")),Ne.info(` ${re.bold("Name:")} ${n}`),Ne.info(` ${re.bold("UDID:")} ${re.dim(t)}`),r&&Ne.info(` ${re.bold("Team:")} ${re.dim(r)}`)}catch(s){o.stop(re.red("Failed to register device")),Ne.error(s.response?.data?.message||s.message)}en(re.blue("---"))}async function Ku(e={}){let t=Rs(e.teamId),n=Qt();n.start("Fetching registered devices...");try{let r=(await N.get("/devices",t?{params:{teamId:t}}:void 0)).data.devices||[];if(n.stop(`${r.length} device(s) registered${t?` for team ${t}`:""}`),r.length===0){Ne.info(re.dim(`No devices registered yet. Run \`${m.nameLower} device register\` to add one.`)),en(re.blue("---"));return}let o=r.map(s=>{let l=new Date(s.createdAt).toLocaleDateString();return` ${re.bold(s.name.padEnd(24))} ${re.dim(s.udid.padEnd(28))} ${re.dim((s.teamId||"-").padEnd(12))} ${re.cyan((s.addedVia||"-").padEnd(10))} ${re.dim(l)}`});Bu(` ${re.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Team".padEnd(12)} ${"Via".padEnd(10)} Date
|
|
1368
1400
|
`+o.join(`
|
|
1369
|
-
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}en(re.blue("---"))}async function
|
|
1370
|
-
`),c=
|
|
1371
|
-
`),u=
|
|
1372
|
-
`),u=
|
|
1373
|
-
`),u=
|
|
1374
|
-
`);/__DEV__/.test(h)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import
|
|
1375
|
-
Running expo prebuild for deeper analysis...`));try{
|
|
1376
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=
|
|
1401
|
+
`),"Registered Devices")}catch(i){n.stop(re.red("Failed to fetch devices")),Ne.error(i.response?.data?.message||i.message)}en(re.blue("---"))}async function Vu(e){let t=e.udid,n=Ps(e).teamId;if(!t){let o=Qt();o.start("Fetching registered devices...");try{let l=(await N.get("/devices",n?{params:{teamId:n}}:void 0)).data.devices||[];if(o.stop(`${l.length} device(s) found`),l.length===0){Ne.info(re.dim("No devices to remove.")),en(re.blue("---"));return}let a=await vs({message:"Select device to remove:",options:l.map(u=>({value:u.deviceKey||u.udid,label:u.name,hint:`${u.udid.substring(0,12)}...${u.teamId?` \xB7 ${u.teamId}`:""}`}))});if(Xt(a)){Zt("Cancelled");return}let c=l.find(u=>(u.deviceKey||u.udid)===a);t=c?.udid||a,n=c?.teamId||n}catch(s){o.stop(re.red("Failed to fetch devices")),Ne.error(s.response?.data?.message||s.message);return}}let i=await Fu({message:`Remove device ${re.dim(t.substring(0,12)+"...")}?`});if(Xt(i)||!i){Zt("Cancelled");return}let r=Qt();r.start("Removing device...");try{await N.delete(`/devices/${encodeURIComponent(t)}`,n?{params:{teamId:n}}:void 0),r.stop(re.green("Device removed"))}catch(o){r.stop(re.red("Failed to remove device")),Ne.error(o.response?.data?.message||o.message)}en(re.blue("---"))}async function Mn(e,t){switch(e){case"register":await Gu(t);break;case"list":await Ku(t);break;case"remove":await Vu(t);break;default:Ne.error(`Unknown action: ${e}`)}}import{log as ke,spinner as ia}from"@clack/prompts";import ze from"chalk";import zn from"path";import rn from"fs";import vf from"os";import Rf from"axios";var Te=(o=>(o.CRITICAL="critical",o.HIGH="high",o.MEDIUM="medium",o.LOW="low",o.INFO="info",o))(Te||{}),Ve=(a=>(a.PERMISSIONS="permissions",a.SECRETS="secrets",a.DEPENDENCIES="dependencies",a.STORAGE="storage",a.NETWORK="network",a.DEBUG="debug",a.MANIFEST="manifest",a.ATS="ats",a))(Ve||{});import{spinner as Ws,log as nn}from"@clack/prompts";import De from"chalk";import{execSync as hf}from"child_process";import Ys from"fs";import Js from"path";import ct from"fs";import tn from"path";import{execSync as zu}from"child_process";var Os={"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"}},Wu={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 Yu(e){try{let n=zu("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(n)}catch{}let t=tn.join(e,"app.json");if(ct.existsSync(t))try{let n=JSON.parse(ct.readFileSync(t,"utf-8"));return n.expo||n}catch{}return null}function Ju(e){let t=[],n=tn.join(e,"node_modules");if(!ct.existsSync(n))return t;let i=/<uses-permission\s+android:name="([^"]+)"/g;function r(o,s){let l=tn.join(o,"android","src","main","AndroidManifest.xml");if(!ct.existsSync(l))return;let a=ct.readFileSync(l,"utf-8"),c;for(;(c=i.exec(a))!==null;)t.push({pkg:s,permission:c[1]});i.lastIndex=0}for(let o of ct.readdirSync(n)){if(o.startsWith("."))continue;let s=tn.join(n,o);if(o.startsWith("@")){if(!ct.statSync(s).isDirectory())continue;for(let l of ct.readdirSync(s))r(tn.join(s,l),`${o}/${l}`)}else r(s,o)}return t}async function Ds(e,t){let n=[],i=1,r=Yu(e),o=r?.android?.permissions||[],s=r?.android?.blockedPermissions||[];for(let c of o){let u=Os[c];u&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${c.split(".").pop()} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let l=Ju(e);for(let{pkg:c,permission:u}of l){let d=Os[u];d&&(s.includes(u)||o.includes(u)||n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${u.split(".").pop()} injected by ${c}`,description:`${d.description}. Auto-injected via ${c} AndroidManifest.xml`,severity:d.severity,category:"permissions",file:`node_modules/${c}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${u}" to blockedPermissions if not needed.`,autoFixable:!0}))}let a=r?.ios?.infoPlist||{};for(let[c,u]of Object.entries(Wu))c in a&&n.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${c} declared`,description:u.description,severity:u.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${c} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:n,durationMs:0}}import Wi from"fs";import Ln from"path";var qu=[{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"}],Xu=new Set([".ts",".tsx",".js",".jsx"]),Zu=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Cs(e){let t=[],n=Wi.readdirSync(e,{withFileTypes:!0});for(let i of n){if(Zu.has(i.name))continue;let r=Ln.join(e,i.name);i.isDirectory()?t.push(...Cs(r)):Xu.has(Ln.extname(i.name))&&t.push(r)}return t}function Qu(e){let t=e.trim();return t.startsWith("//")||t.startsWith("*")||t.startsWith("/*")}function ef(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function Ns(e,t){let n=[],i=Ln.join(e,"src"),r=Wi.existsSync(i)?i:e,o=Cs(r);for(let s of o){let a=Wi.readFileSync(s,"utf-8").split(`
|
|
1402
|
+
`),c=Ln.relative(e,s);for(let u=0;u<a.length;u++){let d=a[u];if(!Qu(d)&&!ef(d))for(let{id:p,pattern:f,severity:h,label:S}of qu)f.lastIndex=0,f.test(d)&&n.push({id:p,title:S,description:`Potential ${S.toLowerCase()} found in source code`,severity:h,category:"secrets",file:c,line:u+1,recommendation:`Move to environment variables or a secrets manager. Use \`${m.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:n,durationMs:0}}import{execSync as tf}from"child_process";var nf={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function Ts(e,t){let n=[],i=1,r;try{r=tf("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(l){if(r=l.stdout||"",!r)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let o;try{o=JSON.parse(r)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let s=o.vulnerabilities||{};for(let[l,a]of Object.entries(s)){let c=nf[a.severity]||"info",u=Array.isArray(a.via)?a.via.map(d=>typeof d=="string"?d:d.title||d.name).join(", "):String(a.via);n.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${l} \u2014 ${a.severity}`,description:`Via: ${u}. Range: ${a.range||"unknown"}`,severity:c,category:"dependencies",recommendation:a.fixAvailable?`Run \`npm audit fix\` or update ${l} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!a.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:n,durationMs:0}}import Un from"fs";import Fn from"path";var rf=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,ks=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,of=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,sf=new Set([".ts",".tsx",".js",".jsx"]),af=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function xs(e){let t=[];if(!Un.existsSync(e))return t;let n=Un.readdirSync(e,{withFileTypes:!0});for(let i of n){if(af.has(i.name))continue;let r=Fn.join(e,i.name);i.isDirectory()?t.push(...xs(r)):sf.has(Fn.extname(i.name))&&t.push(r)}return t}async function Ms(e,t){let n=[],i=1,r=Fn.join(e,"src"),o=Un.existsSync(r)?r:e,s=xs(o);for(let l of s){let a=Un.readFileSync(l,"utf-8");if(!of.test(a))continue;let c=a.split(`
|
|
1403
|
+
`),u=Fn.relative(e,l);for(let d=0;d<c.length;d++){let p=c[d];ks.lastIndex=0;let f;for(;(f=ks.exec(p))!==null;){let h=f[1];rf.test(h)&&n.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${h}"`,description:`Sensitive data key "${h}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:u,line:d+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:n,durationMs:0}}import Bn from"fs";import Hn from"path";var Ls=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,lf=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,df=new Set([".ts",".tsx",".js",".jsx"]),cf=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function Us(e){let t=[];if(!Bn.existsSync(e))return t;let n=Bn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(cf.has(i.name))continue;let r=Hn.join(e,i.name);i.isDirectory()?t.push(...Us(r)):df.has(Hn.extname(i.name))&&t.push(r)}return t}async function Fs(e,t){let n=[],i=1,r=Hn.join(e,"src"),o=Bn.existsSync(r)?r:e,s=Us(o);for(let l of s){let c=Bn.readFileSync(l,"utf-8").split(`
|
|
1404
|
+
`),u=Hn.relative(e,l);for(let d=0;d<c.length;d++){let p=c[d],f=p.trim();if(f.startsWith("//")||f.startsWith("*"))continue;Ls.lastIndex=0;let h;for(;(h=Ls.exec(p))!==null;){let S=h[1],L=lf.test(S);n.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${L?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${S}`,severity:L?"high":"medium",category:"network",file:u,line:d+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:n,durationMs:0}}import jn from"fs";import Gn from"path";var Bs=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,Hs=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,uf=new Set([".ts",".tsx",".js",".jsx"]),ff=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function js(e){let t=[];if(!jn.existsSync(e))return t;let n=jn.readdirSync(e,{withFileTypes:!0});for(let i of n){if(ff.has(i.name))continue;let r=Gn.join(e,i.name);i.isDirectory()?t.push(...js(r)):uf.has(Gn.extname(i.name))&&t.push(r)}return t}async function Gs(e,t){let n=[],i=1,r=Gn.join(e,"src"),o=jn.existsSync(r)?r:e,s=js(o);for(let l of s){let c=jn.readFileSync(l,"utf-8").split(`
|
|
1405
|
+
`),u=Gn.relative(e,l);for(let d=0;d<c.length;d++){let p=c[d],f=p.trim();if(!(f.startsWith("//")||f.startsWith("*"))&&(Bs.lastIndex=0,Bs.test(p)&&n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Hardcoded debug flag",description:"Debug/dev mode enabled in source code",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),Hs.lastIndex=0,Hs.test(p))){let h=c.slice(Math.max(0,d-3),d).join(`
|
|
1406
|
+
`);/__DEV__/.test(h)||n.push({id:`DBG-${String(i++).padStart(3,"0")}`,title:"Sensitive data in console log",description:"Console log may expose sensitive data (token, password, etc.) in production",severity:"medium",category:"debug",file:u,line:d+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:n,durationMs:0}}import Ks from"fs";import Yi from"path";var pf=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 mf(e){let t=[Yi.join(e,"android","app","src","main","AndroidManifest.xml"),Yi.join(e,"android","AndroidManifest.xml")];for(let n of t)if(Ks.existsSync(n))return n;return null}async function Vs(e,t){let n=[],i=1,r=mf(e);if(!r)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let o=Ks.readFileSync(r,"utf-8"),s=Yi.relative(e,r),l=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,a;for(;(a=l.exec(o))!==null;){let c=a[1],u=a[2],p=u.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(pf.has(p))continue;let f=/android:exported="true"/.test(u),h=/android:permission="/.test(u);f&&!h&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${c}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:s,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"allowBackup is enabled",description:'android:allowBackup="true" allows data extraction via ADB backup',severity:"medium",category:"manifest",file:s,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(o)&&n.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:"App is debuggable",description:'android:debuggable="true" allows attaching a debugger in production',severity:"critical",category:"manifest",file:s,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:n,durationMs:0}}import Kn from"fs";import Ji from"path";function gf(e){let t=Ji.join(e,"ios");if(!Kn.existsSync(t))return null;let n=Kn.readdirSync(t,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let r=Ji.join(t,i.name,"Info.plist");if(Kn.existsSync(r))return r}return null}async function zs(e,t){let n=[],i=1,r=gf(e);if(!r)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let o=Kn.readFileSync(r,"utf-8"),s=Ji.relative(e,r),l=o.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let a=l[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(a)&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:"ATS disabled \u2014 NSAllowsArbitraryLoads",description:"App Transport Security is completely disabled. All HTTP connections are allowed.",severity:"critical",category:"ats",file:s,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let c=a.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let u=c[1].match(/<key>([^<]+)<\/key>/g);if(u)for(let d of u){let p=d.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&n.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:s,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:n,durationMs:0}}var yf=[{category:"permissions",label:"Permission Audit",fn:Ds,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:Ns,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:Ts,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:Ms,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:Fs,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:Gs,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:Vs,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:zs,requiresPrebuild:!0}];async function qs(e,t){let n=yf;t.category&&(n=n.filter(s=>s.category===t.category),n.length===0&&(nn.error(De.red(`Unknown category: ${t.category}`)),nn.info(De.dim(`Available: ${Object.values(Ve).join(", ")}`)),process.exit(1)));let i=n.filter(s=>!s.requiresPrebuild),r=n.filter(s=>s.requiresPrebuild),o=[];for(let s of i){let l=Ws();l.start(De.dim(`Running ${s.label}...`));try{let a=Date.now(),c=await s.fn(e,t);c.durationMs=Date.now()-a,o.push(c);let u=c.findings.length;l.stop(u>0?De.yellow(`${s.label} \u2014 ${u} finding(s)`):De.green(`${s.label} \u2014 clean`))}catch(a){l.stop(De.red(`${s.label} \u2014 error`)),o.push({category:s.category,label:s.label,findings:[],durationMs:0,error:a.message})}}if(r.length>0){let s=Js.join(e,"android"),l=Js.join(e,"ios"),a=Ys.existsSync(s)||Ys.existsSync(l);if(!a&&t.prebuild){t.json||nn.info(De.dim(`
|
|
1407
|
+
Running expo prebuild for deeper analysis...`));try{hf("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return nn.warn(De.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),o}}else if(!a)return t.json||nn.info(De.dim(`
|
|
1408
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),o;for(let c of r){let u=Ws();u.start(De.dim(`Running ${c.label}...`));try{let d=Date.now(),p=await c.fn(e,t);p.durationMs=Date.now()-d,o.push(p);let f=p.findings.length;u.stop(f>0?De.yellow(`${c.label} \u2014 ${f} finding(s)`):De.green(`${c.label} \u2014 clean`))}catch(d){u.stop(De.red(`${c.label} \u2014 error`)),o.push({category:c.category,label:c.label,findings:[],durationMs:0,error:d.message})}}}return o}import he from"chalk";import{log as me}from"@clack/prompts";var Ot={critical:he.bgRed.white.bold,high:he.red.bold,medium:he.yellow.bold,low:he.blue,info:he.dim},Vn={critical:0,high:1,medium:2,low:3,info:4};function Sf(e,t){if(!t)return!0;let n=Vn[t];return n===void 0?!0:Vn[e]<=n}function Xs(e,t){let n=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let s of e){let l=s.findings.filter(c=>Sf(c.severity,t));if(l.length===0&&!s.error)continue;if(me.info(""),me.info(he.bold(` ${s.label}`)+he.dim(` ${l.length} finding(s)`)),me.info(he.dim(" "+"\u2500".repeat(60))),s.error){me.error(he.red(` Error: ${s.error}`));continue}let a=[...l].sort((c,u)=>Vn[c.severity]-Vn[u.severity]);for(let c of a){let u=Ot[c.severity](` ${c.severity.toUpperCase()} `);me.info(` ${u} ${he.bold(c.id)} ${c.title}`),me.info(he.dim(` ${c.description}`)),c.file&&me.info(he.dim(` File: ${c.file}${c.line?`:${c.line}`:""}`)),me.info(he.cyan(` Fix: ${c.recommendation}`)),me.info(""),i[c.severity]++,n++}}me.info(""),me.info(he.bold(" Summary")),me.info(he.dim(" "+"\u2500".repeat(60))),me.info(` Total: ${he.bold(String(n))} finding(s)`),me.info(` ${Ot.critical(` ${i.critical} Critical `)} ${Ot.high(` ${i.high} High `)} ${Ot.medium(` ${i.medium} Medium `)} ${Ot.low(` ${i.low} Low `)} ${Ot.info(` ${i.info} Info `)}`);let r=i.critical>0,o=i.high>0;r||o?(me.info(""),me.error(he.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):n>0?(me.info(""),me.warn(he.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(me.info(""),me.success(he.green.bold(" PASS \u2014 no issues found")))}function Zs(e,t){let n=e.flatMap(r=>r.findings),i={};for(let r of Object.values(Te))i[r]=n.filter(o=>o.severity===r).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:t.name||"unknown",projectVersion:t.version||"0.0.0",summary:{total:n.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(r=>({category:r.category,label:r.label,findingCount:r.findings.length,durationMs:r.durationMs,error:r.error||null})),findings:n}}import{log as ge,spinner as bf}from"@clack/prompts";import ue from"chalk";import tt from"fs";import Af from"os";import Dt from"path";import{execSync as Ef}from"child_process";var Qs=16384,If=1,wf=Buffer.from([127,69,76,70]);async function ea(e){ge.info(ue.bold.underline("16KB Page Alignment Check")),console.log("");let t=Dt.resolve(e);if(!tt.existsSync(t))return ge.error(ue.red(`APK file not found: ${t}`)),!1;if(!t.endsWith(".apk"))return ge.error(ue.red("The provided file is not an APK file.")),!1;let n=bf();n.start("Extracting and analyzing native libraries...");let i=tt.mkdtempSync(Dt.join(Af.tmpdir(),"mach-16kb-"));try{try{Ef(`unzip -o -q "${t}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let r=ta(Dt.join(i,"lib"));if(r.length===0)return n.stop("Analysis complete."),ge.info(ue.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),ge.info(ue.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let o=[];for(let a of r){let c=Dt.relative(i,a),u=$f(c),d=Dt.basename(a),p=_f(a);p!==null&&o.push({name:d,filePath:c,arch:u,align:p,compatible:p>=Qs})}if(n.stop("Analysis complete."),o.length===0)return ge.info(ue.yellow("No valid ELF shared libraries found.")),!0;let s=o.filter(a=>!a.compatible),l=o.filter(a=>a.compatible);if(ge.info(ue.dim(`Checked ${o.length} native librar${o.length===1?"y":"ies"}
|
|
1377
1409
|
`)),s.length>0){ge.info(ue.red.bold(`Incompatible libraries:
|
|
1378
|
-
`));for(let a of s)ge.error(ue.red(`${ue.bold(a.name)} ${ue.dim(`(${a.arch})`)}`)),ge.info(ue.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${zs})`))}return l.length>0&&(console.log(""),ge.success(ue.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(ge.success(ue.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ge.error(ue.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ge.info(ue.yellow("To fix this:")),ge.info(ue.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ge.info(ue.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ge.info(ue.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ge.info(ue.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ge.info(ue.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),ge.error(ue.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{tt.rmSync(i,{recursive:!0,force:!0})}catch{}}}function yf(e){let t=tt.openSync(e,"r");try{let n=Buffer.alloc(64);if(tt.readSync(t,n,0,64,0),!n.subarray(0,4).equals(hf))return null;let i=n[4]===2,r=n[5]===1,o=(f,p)=>r?f.readUInt16LE(p):f.readUInt16BE(p),s=(f,p)=>r?f.readUInt32LE(p):f.readUInt32BE(p),l=(f,p)=>Number(r?f.readBigUInt64LE(p):f.readBigUInt64BE(p)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let f=0;f<u;f++){let p=Buffer.alloc(c);if(tt.readSync(t,p,0,c,a+f*c),s(p,0)!==gf)continue;let D;i?D=l(p,48):D=s(p,28),D>0&&(d===null||D<d)&&(d=D)}return d??0}catch{return null}finally{tt.closeSync(t)}}function Ys(e){let t=[];if(!tt.existsSync(e))return t;let n=tt.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Ot.join(e,i.name);i.isDirectory()?t.push(...Ys(r)):i.name.endsWith(".so")&&t.push(r)}return t}function Sf(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Xs=async e=>{if(Pe()||(ke.error(ze.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Af(e);return}let n=process.cwd(),i=Kn.join(n,"package.json");rn.existsSync(i)||(ke.error(ze.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(rn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(ze.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(ze.dim(`Type: ${o?"Expo":"Bare React Native"}`)),ke.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await Gs(n,s);e.json?console.log(JSON.stringify(Vs(l,r),null,2)):Ks(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},Js=["16kb"];async function Af(e){let t=e.category?.toLowerCase();t&&!Js.includes(t)&&(ke.error(ze.red(`Unknown APK check category: "${t}"`)),ke.info(ze.dim(`Available APK checks: ${Js.join(", ")}`)),process.exit(1));let n=await If(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await Ws(n)||(r=!0)),r&&process.exit(1)}async function If(e){if(e.startsWith("build:")){let n=e.slice(6);return await wf(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await Zs(e);let t=Kn.resolve(e);return rn.existsSync(t)?t:(ke.error(ze.red(`APK file not found: ${t}`)),null)}async function wf(e){let t=qs();t.start(`Fetching APK from build ${e}...`);try{let n=await P.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),ke.error(ze.red("This build does not have an APK artifact.")),ke.info(ze.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await Zs(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(ze.red(n.message)),null}}async function Zs(e){let t=qs();t.start("Downloading APK...");try{let n=rn.mkdtempSync(Kn.join(bf.tmpdir(),`${m.nameLower}-audit-`)),i=Kn.join(n,"app.apk"),r=await Ef.get(e,{responseType:"arraybuffer"});rn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),ke.error(ze.red(`Failed to download APK: ${n.message}`)),null}}var vf=console.log;console.log=()=>{};$f();console.log=vf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var Pf=Rf(import.meta.url),Df=Pf("../package.json"),ea=(e,t=[])=>t.concat(e),oe=new _f;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Df.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);oe.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await es(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await sr()});oe.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(be.bgCyan.black(m.cliTag("Sitemap Generator"))),await cr(e)});oe.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new xe("--build-id <id>","Internal build ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new xe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",ea,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=oe.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(be.bgCyan.black(m.cliTag("Cloud Build"))),await In(t)});oe.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",ea,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new xe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new xe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(be.bgCyan.black(m.cliTag("Maestro Testing"))),await Vr(e)});oe.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(be.bgCyan.black(m.cliTag("OTA Update"))),await fs(e)});oe.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new xe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new xe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=oe.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(be.bgCyan.black(m.cliTag("Store Submission"))),await hn(e)});oe.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(be.bgCyan.black(m.cliTag("Login"))),await rs()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await os()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await as()});oe.command("me").description("Display currently logged in user details").action(async()=>{await ms()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await ls()});oe.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(be.bgCyan.black(m.cliTag("Env Manager"))),await cs(e,t,n)});oe.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(be.bgCyan.black(m.cliTag("Dev Server"))),await hs(e)});oe.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 ys(e)});oe.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-KDH6HGWP.js");await t(e)});oe.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(be.bgCyan.black(m.cliTag("Credentials Setup"))),await Tt(e),Qs(be.green("Done!"))});oe.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(be.bgCyan.black(m.cliTag("Service Credentials"))),await rr(e),Qs(be.green("Done!"))});var Yi=oe.command("device").description("Manage registered iOS test devices");Yi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await kn("register",e)});Yi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await kn("list",e)});Yi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await kn("remove",e)});oe.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(be.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await Xs(e)});var Of=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Of.has(n)||er()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1410
|
+
`));for(let a of s)ge.error(ue.red(`${ue.bold(a.name)} ${ue.dim(`(${a.arch})`)}`)),ge.info(ue.dim(` PT_LOAD alignment: 2**${Math.log2(a.align)} (${a.align} bytes, needs 2**14 = ${Qs})`))}return l.length>0&&(console.log(""),ge.success(ue.green(`${l.length} librar${l.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),s.length===0?(ge.success(ue.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(ge.error(ue.red.bold(`Found ${s.length} unaligned lib${s.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),ge.info(ue.yellow("To fix this:")),ge.info(ue.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),ge.info(ue.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),ge.info(ue.dim(" 3. Update third-party libraries that ship prebuilt .so files")),ge.info(ue.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),ge.info(ue.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(r){return n.stop("Analysis failed."),ge.error(ue.red(`Failed to analyze APK: ${r.message}`)),!1}finally{try{tt.rmSync(i,{recursive:!0,force:!0})}catch{}}}function _f(e){let t=tt.openSync(e,"r");try{let n=Buffer.alloc(64);if(tt.readSync(t,n,0,64,0),!n.subarray(0,4).equals(wf))return null;let i=n[4]===2,r=n[5]===1,o=(p,f)=>r?p.readUInt16LE(f):p.readUInt16BE(f),s=(p,f)=>r?p.readUInt32LE(f):p.readUInt32BE(f),l=(p,f)=>Number(r?p.readBigUInt64LE(f):p.readBigUInt64BE(f)),a,c,u;i?(a=l(n,32),c=o(n,54),u=o(n,56)):(a=s(n,28),c=o(n,42),u=o(n,44));let d=null;for(let p=0;p<u;p++){let f=Buffer.alloc(c);if(tt.readSync(t,f,0,c,a+p*c),s(f,0)!==If)continue;let S;i?S=l(f,48):S=s(f,28),S>0&&(d===null||S<d)&&(d=S)}return d??0}catch{return null}finally{tt.closeSync(t)}}function ta(e){let t=[];if(!tt.existsSync(e))return t;let n=tt.readdirSync(e,{withFileTypes:!0});for(let i of n){let r=Dt.join(e,i.name);i.isDirectory()?t.push(...ta(r)):i.name.endsWith(".so")&&t.push(r)}return t}function $f(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var ra=async e=>{if(Pe()||(ke.error(ze.red(`You are not logged in. Run \`${m.nameLower} login\` first.`)),process.exit(1)),e.apk){await Pf(e);return}let n=process.cwd(),i=zn.join(n,"package.json");rn.existsSync(i)||(ke.error(ze.red("No package.json found. Run this command from a project root.")),process.exit(1));let r=JSON.parse(rn.readFileSync(i,"utf-8")),o=!!(r.dependencies?.expo||r.devDependencies?.expo);e.json||(ke.info(ze.dim(`Project: ${r.name||"unknown"} v${r.version||"0.0.0"}`)),ke.info(ze.dim(`Type: ${o?"Expo":"Bare React Native"}`)),ke.info(""));let s={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},l=await qs(n,s);e.json?console.log(JSON.stringify(Zs(l,r),null,2)):Xs(l,e.severity);let a=l.some(u=>u.findings.some(d=>d.severity==="critical")),c=l.some(u=>u.findings.some(d=>d.severity==="high"));(a||c)&&process.exit(1)},na=["16kb"];async function Pf(e){let t=e.category?.toLowerCase();t&&!na.includes(t)&&(ke.error(ze.red(`Unknown APK check category: "${t}"`)),ke.info(ze.dim(`Available APK checks: ${na.join(", ")}`)),process.exit(1));let n=await Of(e.apk);n||process.exit(1);let i=!t,r=!1;(i||t==="16kb")&&(await ea(n)||(r=!0)),r&&process.exit(1)}async function Of(e){if(e.startsWith("build:")){let n=e.slice(6);return await Df(n)}if(e.startsWith("http://")||e.startsWith("https://"))return await oa(e);let t=zn.resolve(e);return rn.existsSync(t)?t:(ke.error(ze.red(`APK file not found: ${t}`)),null)}async function Df(e){let t=ia();t.start(`Fetching APK from build ${e}...`);try{let n=await N.get(`/build/${e}`);if(n.data.status!=="success")throw new Error(n.data.message);let i=n.data.build;if(!i)throw new Error("Build not found");let r=i.artifacts?.find(o=>o.type?o.type==="apk":o.name?.endsWith(".apk")||o.url?.includes(".apk"));return!r||!r.url?(t.stop("No APK artifact found"),ke.error(ze.red("This build does not have an APK artifact.")),ke.info(ze.dim("Make sure the build produced an APK (not just an AAB).")),null):(t.stop(`Found build: ${i.buildId||e}`),await oa(r.url))}catch(n){return t.stop("Failed to fetch build"),ke.error(ze.red(n.message)),null}}async function oa(e){let t=ia();t.start("Downloading APK...");try{let n=rn.mkdtempSync(zn.join(vf.tmpdir(),`${m.nameLower}-audit-`)),i=zn.join(n,"app.apk"),r=await Rf.get(e,{responseType:"arraybuffer"});rn.writeFileSync(i,r.data);let o=(r.data.length/(1024*1024)).toFixed(1);return t.stop(`Downloaded APK (${o} MB)`),i}catch(n){return t.stop("Download failed"),ke.error(ze.red(`Failed to download APK: ${n.message}`)),null}}var Tf=console.log;console.log=()=>{};Nf();console.log=Tf;we(be.bgCyan.black(m.cliTag("Production Build Orchestrator")));var xf=kf(import.meta.url),Mf=xf("../package.json"),aa=(e,t=[])=>t.concat(e),oe=new Cf;oe.name(m.nameLower).description(`${m.name} CLI: Powerful Cloud Infrastructure Tools`).version(Mf.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);oe.command("agent").description("Manage local device discovery agent for the Install Hub (port 7070)").argument("[action]","start, run, install, status, restart, stop, or uninstall","start").action(async e=>{await as(e)});oe.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{we(be.bgCyan.black(m.cliTag("Hosting"))),await cr()});oe.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{we(be.bgCyan.black(m.cliTag("Sitemap Generator"))),await mr(e)});oe.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new xe("--build-id <id>","Internal build ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--fail-only","Internal: mark an existing build failed").hideHelp()).addOption(new xe("--error <message>","Internal failure message").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment Android versionCode or iOS buildNumber from the store").option("--auto-submit","Submit this build after it completes successfully").option("--submit-track <track>","Google Play track to use with --auto-submit").option("--submit-release-status <status>","Google Play release status to use with --auto-submit").option("--submit-rollout <fraction>","Google Play staged rollout fraction to use with --auto-submit").option("--submit-changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review when using --auto-submit").option("--submit-credential-id <id>","Service credential ID to use with --auto-submit").option("--submit-json-output <path>","Write auto-submit metadata JSON to a file for CI/CD").option("--verbose","Enable verbose logging").option("--json-output <path>","Write build metadata JSON to a file for CI/CD").option("--maestro","Queue a managed Maestro test run after a successful build").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",aa,[]).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,t)=>{let n=oe.opts();t.yes=t.yes||n.yes,t.quiet=t.quiet||n.quiet,t.platform=e||t.platform,t.buildProfile=t.profile||t.buildProfile,t.quiet||we(be.bgCyan.black(m.cliTag("Cloud Build"))),await _n(t)});oe.command("maestro").description("Run Maestro tests locally or with the managed Mach runner").option("--platform <os>","Target platform (android/ios)").option("-p, --profile <name>","Build profile to resolve when using --latest","production").option("--latest","Use the latest successful build for the platform/profile").option("--build-id <id>","Use a specific Mach build ID").option("--build-url <url>","Use a Mach build URL").option("--artifact-url <url>","Use a direct APK or iOS simulator app artifact URL").option("--local","Run Maestro on a connected local emulator/device instead of the managed runner").option("--maestro-flows <path>","Maestro flow file or directory (default: .maestro)").option("--maestro-device <device>","Managed Maestro device profile").option("--maestro-retries <n>","Retries for the Maestro run","1").option("--maestro-record","Enable screen recording where supported").option("--maestro-use-build-source","Use Maestro flows from the build source snapshot instead of uploading local flows").option("--maestro-env <name>","Forward an environment variable to the managed Maestro runner; repeat or comma-separate names",aa,[]).option("--wait","Wait for managed Maestro completion and exit non-zero on failure").option("--wait-timeout <minutes>","Maximum minutes to wait for managed Maestro completion","60").option("--wait-interval <seconds>","Polling interval while waiting for managed Maestro completion","15").option("--json-output <path>","Write test run metadata JSON to a file for CI/CD").addOption(new xe("--local-runner","Internal: execute a managed Maestro run on this machine").hideHelp()).addOption(new xe("--test-run-id <id>","Internal test run ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--runner-token <token>","Internal runner token").hideHelp()).action(async e=>{we(be.bgCyan.black(m.cliTag("Maestro Testing"))),await Jr(e)});oe.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{we(be.bgCyan.black(m.cliTag("OTA Update"))),await bs(e)});oe.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("-p, --profile <name>","Build/submission profile to submit from (e.g. production, preprod)").option("--track <track>","Google Play Track (internal, alpha, beta, production)").option("--release-status <status>","Google Play release status (completed, draft, halted, inProgress)").option("--rollout <fraction>","Google Play staged rollout fraction for inProgress releases (example: 0.1)").option("--changes-not-sent-for-review","Commit Google Play changes without automatically sending them for review").option("--ssh-host <host>","Remote macOS host for iOS submission").option("--ssh-user <user>","SSH username for remote iOS submission").option("--ssh-key <path>","Path to private SSH key for remote iOS submission").option("--credential-id <id>","Service credential ID to use when multiple submission credentials exist").option("--local","Run submission on this machine (internal runner mode for iOS)").addOption(new xe("--submit-id <id>","Internal submission ID").hideHelp()).addOption(new xe("--project-id <id>","Internal project ID").hideHelp()).addOption(new xe("--package-name <name>","Internal Android package name").hideHelp()).addOption(new xe("--bundle-id <id>","Internal iOS bundle identifier").hideHelp()).option("--json-output <path>","Write submission metadata JSON to a file for CI/CD").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{let t=oe.opts();e.quiet=e.quiet||t.quiet,e.yes=e.yes||t.yes,we(be.bgCyan.black(m.cliTag("Store Submission"))),await Sn(e)});oe.command("login").description(`Login to ${m.name} Dashboard`).action(async()=>{we(be.bgCyan.black(m.cliTag("Login"))),await us()});oe.command("logout").description(`Logout from ${m.name} on this machine`).action(async()=>{we(be.bgCyan.black(m.cliTag("Logout"))),await fs()});oe.command("link").description(`Link local directory to a ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Link Project"))),await ms()});oe.command("me").description("Display currently logged in user details").action(async()=>{await Es()});oe.command("init").description(`Create a new ${m.name} Project`).action(async()=>{we(be.bgCyan.black(m.cliTag("Init Project"))),await gs()});oe.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set, list, pull, download, or export").argument("[args...]","Key=Value pairs for set action").option("-e, --environment <name>","Environment to pull/download","development").option("-o, --out <file>","Output file for pull/download",".env.local").option("--overwrite","Overwrite output file if it already exists").action(async(e,t,n)=>{we(be.bgCyan.black(m.cliTag("Env Manager"))),await ys(e,t,n)});oe.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{we(be.bgCyan.black(m.cliTag("Dev Server"))),await ws(e)});oe.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 _s(e)});oe.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:t}=await import("./credentials-3MYGMYJK.js");await t(e)});oe.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{we(be.bgCyan.black(m.cliTag("Credentials Setup"))),await Tt(e),sa(be.green("Done!"))});oe.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").option("--bundle-id <id>","Bundle identifier / Android package name to attach this service credential to").option("--package-name <name>","Android package name to attach this service credential to").option("-p, --profile <name>","Build profile to resolve package/bundle identifier from config").action(async e=>{we(be.bgCyan.black(m.cliTag("Service Credentials"))),await lr(e),sa(be.green("Done!"))});var qi=oe.command("device").description("Manage registered iOS test devices");qi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Mn("register",e)});qi.command("list").description("List all registered devices").option("--team-id <id>","Filter by Apple Developer Team ID").action(async e=>{await Mn("list",e)});qi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").option("--team-id <id>","Apple Developer Team ID for this device").action(async e=>{await Mn("remove",e)});oe.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{we(be.bgCyan.black(m.cliTag(e.apk?"APK Audit":"Security Audit"))),await ra(e)});var Lf=new Set(["login","logout","agent"]);oe.hook("preAction",(e,t)=>{let n=t.name(),i=t.opts?.()||{};n==="maestro"&&(i.local||i.localRunner)||Lf.has(n)||nr()});oe.on("command:*",()=>{console.error(`Invalid command: %s
|
|
1379
1411
|
See --help for a list of available commands.`,oe.args.join(" ")),process.exit(1)});process.argv.slice(2).length||oe.help();oe.parse(process.argv);
|