@radhya/mach 1.4.20 → 1.4.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +63 -61
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as ci,c as Je}from"./chunk-YXFDQM4S.js";import{a as f,b as ri,c as ue,d as si,e as gt,f as ai,g as
|
|
2
|
+
import{a as ci,c as Je}from"./chunk-YXFDQM4S.js";import{a as f,b as ri,c as ue,d as si,e as gt,f as ai,g as _}from"./chunk-YZYFEHP5.js";import{Command as qr,Option as Cn}from"commander";import{configDotenv as Jr}from"dotenv";import{intro as de,outro as Tn}from"@clack/prompts";import re from"chalk";import{text as li,confirm as Nn,spinner as kn,isCancel as Ut,cancel as Xe,note as xn,outro as Ln}from"@clack/prompts";import Ze from"chalk";async function di(){try{let e=await li({message:"Enter Bucket Name:",placeholder:"e.g. my-app-dev",validate(o){if(o.length===0)return"Bucket name is required"}});Ut(e)&&(Xe("Operation cancelled."),process.exit(0));let n=await li({message:"Enter Region:",initialValue:"ap-south-1"});Ut(n)&&(Xe("Operation cancelled."),process.exit(0));let t=await Nn({message:"Do you want to create a CloudFront Distribution for this bucket?",initialValue:!0});Ut(t)&&(Xe("Operation cancelled."),process.exit(0));let i=kn();i.start("Setting up hosting infrastructure...");try{let o=await _.post("/hosting/setup",{bucketName:e,region:n,createCloudFront:t});if(o.data.status!=="success")throw new Error(o.data.message||"Hosting setup failed");i.stop("Hosting setup complete!");let r=o.data,a=`Bucket Name: ${Ze.cyan(r.bucketName)}
|
|
3
3
|
`;a+=`Region: ${Ze.cyan(r.region)}
|
|
4
4
|
`,a+=`S3 Website URL: ${Ze.blue(r.s3WebsiteUrl)}`,r.cloudFrontId&&(a+=`
|
|
5
5
|
|
|
6
6
|
CloudFront ID: ${Ze.cyan(r.cloudFrontId)}`,a+=`
|
|
7
|
-
CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),xn(a,"Setup Complete!"),Ln("You are all set!")}catch(o){i.stop("Setup failed"),Xe(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){Xe(`An unexpected error occurred: ${e.message}`)}}import{readdir as Un,writeFile as Mn,access as Fn,mkdir as Hn}from"fs/promises";import{join as ui}from"path";import{spinner as Gn,text as pi,isCancel as fi,cancel as Mt,note as
|
|
7
|
+
CloudFront URL: ${Ze.blue(r.cloudFrontUrl)}`),xn(a,"Setup Complete!"),Ln("You are all set!")}catch(o){i.stop("Setup failed"),Xe(`Error: ${o.response?.data?.message||o.message}`)}}catch(e){Xe(`An unexpected error occurred: ${e.message}`)}}import{readdir as Un,writeFile as Mn,access as Fn,mkdir as Hn}from"fs/promises";import{join as ui}from"path";import{spinner as Gn,text as pi,isCancel as fi,cancel as Mt,note as jn,outro as Bn}from"@clack/prompts";import Kn from"chalk";async function Vn(){let e=["./app","./src/app"];for(let n of e)try{return await Fn(n),n}catch{}return null}async function mi(e){try{let t=await Vn()||"./app",i=await pi({message:"Enter path to your app directory:",placeholder:t,initialValue:t,validate(d){if(d.length===0)return"Path is required"}});fi(i)&&(Mt("Operation cancelled."),process.exit(0));let o=await pi({message:"Enter your website base URL:",placeholder:"https://example.com",validate(d){if(d.length===0)return"Base URL is required";if(!d.startsWith("http"))return"URL must start with http:// or https://"}});fi(o)&&(Mt("Operation cancelled."),process.exit(0));let r=Gn();r.start("Scanning app directory for routes...");let a=await gi(i);r.stop(`Found ${a.length} routes`);let c=zn(a,o),s=e.output||"./public/sitemap.xml";r.start(`Writing sitemap to ${s}...`);let l=s.substring(0,s.lastIndexOf("/"));if(l)try{await Hn(l,{recursive:!0})}catch{}await Mn(s,c,"utf-8"),r.stop("Sitemap generated successfully!"),jn(`Routes included:
|
|
8
8
|
${a.map(d=>` \u2022 ${d.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),
|
|
9
|
+
`)}`,"Sitemap Summary"),Bn(`Sitemap saved to ${Kn.cyan(s)}`)}catch(n){Mt(`An error occurred: ${n.message}`)}}async function gi(e,n=""){let t=[];try{let i=await Un(e,{withFileTypes:!0});for(let o of i){let r=ui(e,o.name);if(!(o.name.startsWith("_")||o.name.startsWith("."))){if(o.isDirectory()){let a=await gi(r,ui(n,o.name));t.push(...a)}else if(o.isFile()){if(o.name==="index.tsx"||o.name==="index.ts"||o.name==="index.jsx"||o.name==="index.js"){let a=n===""?"/":`/${n}`;t.push({path:a,file:r})}else if(o.name.match(/\.(tsx|ts|jsx|js)$/)&&!o.name.includes("_layout")&&!o.name.includes("+")){let a=o.name.replace(/\.(tsx|ts|jsx|js)$/,""),c=`/${n}/${a}`.replace(/\/+/g,"/");t.push({path:c,file:r})}}}}}catch(i){throw new Error(`Failed to scan directory ${e}: ${i.message}`)}return t}function zn(e,n){let t=new Date().toISOString().split("T")[0];return`<?xml version="1.0" encoding="UTF-8"?>
|
|
10
10
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
11
11
|
${e.map(o=>{let r=o.path;return r=r.replace(/\/\([^)]+\)/g,""),r=r.replace(/\/\[.*?\]/g,"/:id"),r=r.replace(/\/+/g,"/"),r===""&&(r="/"),` <url>
|
|
12
12
|
<loc>${n}${r}</loc>
|
|
@@ -274,7 +274,7 @@ sudo shutdown -h now
|
|
|
274
274
|
export MACH_APP_NAME="${e.appName||"App"}"
|
|
275
275
|
export MACH_BUILD_PROFILE="${r}"
|
|
276
276
|
{{ENV_VARS}}
|
|
277
|
-
`);if(e.dryRun){yi.info("User Data Script (dry run):"),console.log(u);return}o.start("Requesting cloud build instance...");try{let p=await
|
|
277
|
+
`);if(e.dryRun){yi.info("User Data Script (dry run):"),console.log(u);return}o.start("Requesting cloud build instance...");try{let p=await _.post("/builds/launch-android",{projectId:i,buildId:n,platform:e.platform,buildProfile:e.buildProfile,buildCommand:l,instanceType:e.instanceType,ami:e.ami,keepInstance:e.keepInstance,region:e.region,subnet:e.subnet,securityGroup:e.securityGroup,projectSecrets:t,dryRun:e.dryRun,userDataScript:u});if(p.data.status!=="success")throw new Error(p.data.message||"Failed to launch build instance");let g=p.data.instanceId;return o.stop("Build Started"),yi.success(Yn.green(`Build initiated on cloud instance (${g}).`)),{instanceId:g}}catch(p){o.stop("Android Build Failed");let g=p.response?.data?.message||p.message;throw new Error(`Failed to launch Android build: ${g}`)}};import{spinner as qn,log as He}from"@clack/prompts";import Te from"chalk";import Jn from"fs";import{execSync as Qe}from"child_process";var Ai=`#!/bin/bash
|
|
278
278
|
# --- Mach Cloud Build Script (iOS) ---
|
|
279
279
|
# All S3 operations use presigned URLs via curl \u2014 zero AWS credentials on Mac.
|
|
280
280
|
|
|
@@ -712,55 +712,57 @@ touch done
|
|
|
712
712
|
if [ ! -z "$PRESIGNED_DONE_MARKER" ]; then
|
|
713
713
|
curl -X PUT -T done "$PRESIGNED_DONE_MARKER" --silent
|
|
714
714
|
fi
|
|
715
|
-
`;var Ei=async(e,n,t={},i)=>{let o=qn();e.sshHost||(e.sshHost="localhost",He.message(Te.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Te.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",a=e.sshKey,c=`${r}@${e.sshHost}`,s=`ssh ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no ${c}`,l=`scp ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no`;try{let d=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(t.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${f.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),Qe(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let g=`/tmp/${f.nameLower}-source-${n}.zip`;Qe(`${l} ${g} ${c}:${p}/source.zip`,{stdio:"inherit"});let m=e.iosApiKeyPath?`${p}/api_key.p8`:"",h="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),Qe(`${l} ${e.iosApiKeyPath} ${c}:${m}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(h=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${m}`));let
|
|
715
|
+
`;var Ei=async(e,n,t={},i)=>{let o=qn();e.sshHost||(e.sshHost="localhost",He.message(Te.yellow("No SSH host provided, defaulting to localhost."))),o.start(`Connecting to remote Mac at ${Te.cyan(e.sshHost)}...`);let r=e.sshUser||process.env.USER||"ubuntu",a=e.sshKey,c=`${r}@${e.sshHost}`,s=`ssh ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no ${c}`,l=`scp ${a?`-i ${a}`:""} -o StrictHostKeyChecking=no`;try{let d=r==="ubuntu"?"/home/ubuntu":`/Users/${r}`,u=(t.PROJECT_ID||"default_project").replace(/[^a-zA-Z0-9-_]/g,"_"),p=`${d}/${f.remoteWorkspacesDir}/${u}`;o.message(`Preparing stable workspace: ${p}...`),Qe(`${s} "mkdir -p ${p}"`,{stdio:"inherit"}),o.message("Transferring source code...");let g=`/tmp/${f.nameLower}-source-${n}.zip`;Qe(`${l} ${g} ${c}:${p}/source.zip`,{stdio:"inherit"});let m=e.iosApiKeyPath?`${p}/api_key.p8`:"",h="";e.iosApiKeyPath&&(o.message("Uploading App Store Connect API key..."),Qe(`${l} ${e.iosApiKeyPath} ${c}:${m}`),e.iosApiKeyId&&e.iosApiKeyIssuer&&(h=`-authenticationKeyID ${e.iosApiKeyId} -authenticationKeyIssuerID ${e.iosApiKeyIssuer} -authenticationKeyPath ${m}`));let $={};if(i)try{let I=await _.post(`/builds/${i}/${n}/build-urls`,{platform:"ios"});I.data.status==="success"&&($=I.data.urls)}catch(I){He.warn(Te.yellow(`Could not fetch build URLs: ${I.message}`))}let N="";if($.credentials&&$.credentials.length>0)for(let I of $.credentials)I.type==="p12"?N+=`curl -sf -o "$CERT_DIR/${I.name}" "${I.downloadUrl}" || true
|
|
716
716
|
`:I.type==="mobileprovision"&&(N+=`curl -sf -o "$PROV_TEMP/${I.name}" "${I.downloadUrl}" || true
|
|
717
|
-
`);o.message("Generating macOS build script...");let
|
|
718
|
-
`:"";if(t)for(let[I,b]of Object.entries(t)){let
|
|
719
|
-
`}let
|
|
717
|
+
`);o.message("Generating macOS build script...");let C=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
718
|
+
`:"";if(t)for(let[I,b]of Object.entries(t)){let O=b.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");C+=`export ${I}="${O}"
|
|
719
|
+
`}let x=[C,$.logUpload?`export PRESIGNED_LOG_UPLOAD="${$.logUpload}"`:"",$.doneMarker?`export PRESIGNED_DONE_MARKER="${$.doneMarker}"`:"",$.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${$.cacheDerivedDataDownload}"`:"",$.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${$.cacheDerivedDataUpload}"`:"",$.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${$.cacheNodeModulesDownload}"`:"",$.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${$.cacheNodeModulesUpload}"`:"",$.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${$.cachePodsDownload}"`:"",$.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${$.cachePodsUpload}"`:"",$.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${$.artifactIpaUpload}"`:"",$.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${$.artifactAppZipUpload}"`:"",`export BUILD_ID="${n}"`,`export ${f.envPrefix}PROJECT_ID="${u}"`,t.MATCH_ENCRYPTION_PASSPHRASE?`export MATCH_PASSWORD="${t.MATCH_ENCRYPTION_PASSPHRASE}"`:"",t.APPLE_TEAM_ID?`export FASTLANE_TEAM_ID="${t.APPLE_TEAM_ID}"`:"",`export MATCH_KEYCHAIN_NAME="${f.credentialsKeychain}"`,`export MATCH_KEYCHAIN_PASSWORD="${f.keychainPassword}"`].filter(Boolean).join(`
|
|
720
720
|
`),H=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(`
|
|
721
|
-
`):"",
|
|
721
|
+
`):"",X=Ai,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":x,"{{CREDENTIAL_DOWNLOADS}}":N,"{{IOS_SCHEME}}":e.iosScheme||"","{{IOS_CONFIG}}":e.iosConfiguration||"Release","{{TEAM_ID}}":e.iosTeamId||"","{{AUTH_PARAMS}}":h,"{{IS_SIMULATOR}}":e.simulator?"true":"false","{{BUILD_ID}}":n,"{{EXPORT_METHOD}}":e.iosExportMethod||"ad-hoc","{{NODE_VERSION_SETUP}}":H};Object.entries(y).forEach(([I,b])=>{X=X.split(I).join(b)});let w=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Jn.writeFileSync(w,X),Qe(`${l} ${w} ${c}:${p}/build.sh`),o.stop("Remote script uploaded."),He.info(Te.cyan("Executing remote build. This might take a while...")),Qe(`${s} "bash ${p}/build.sh"`,{stdio:"inherit"}),o.stop("Remote build finished!"),i){o.start("Fetching artifact links...");try{let b=(await _.get(`/builds/${i}/${n}/artifacts`)).data.artifacts||[],O=e.simulator===!0;if(b.length===0&&!O)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),b.length>0){He.success("Build Artifacts Ready:");for(let G of b)console.log(`
|
|
722
722
|
${Te.yellow(G.name)}:
|
|
723
723
|
${Te.cyan(G.downloadUrl)}`);console.log(`
|
|
724
|
-
${Te.dim("Note: Links are valid for 7 days.")}`)}else
|
|
724
|
+
${Te.dim("Note: Links are valid for 7 days.")}`)}else O&&He.warn("Simulator build completed. No artifacts uploaded.")}catch(I){o.stop("Could not fetch artifacts"),He.warn(Te.yellow(`Artifact listing failed: ${I.message}`))}}}catch(d){throw o.stop("iOS Build Failed"),d}};import Xn from"crypto";import et from"axios";async function Ii(e,n){try{let t=await Zn(n),o=(await et.post(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits`,{},{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.id,r=0,c=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/tracks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.tracks||[];for(let s of c)if(s.releases){for(let l of s.releases)if(l.versionCodes)for(let d of l.versionCodes){let u=parseInt(d,10);u>r&&(r=u)}}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/bundles`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.bundles||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}try{let l=(await et.get(`https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${e}/edits/${o}/apks`,{headers:{Authorization:`Bearer ${t}`,Connection:"close"}})).data.apks||[];for(let d of l)d.versionCode&&d.versionCode>r&&(r=d.versionCode)}catch{}return r}catch(t){let i=t.response?.data?.error?.message||t.message;throw new Error(`Google Play API Error: ${i}`)}}async function Zn(e){let n=Math.floor(Date.now()/1e3),t=n+3600,i={alg:"RS256",typ:"JWT"},o={iss:e.client_email,sub:e.client_email,aud:"https://oauth2.googleapis.com/token",iat:n,exp:t,scope:"https://www.googleapis.com/auth/androidpublisher"},r=Buffer.from(JSON.stringify(i)).toString("base64url"),a=Buffer.from(JSON.stringify(o)).toString("base64url"),c=`${r}.${a}`,s=Xn.createSign("RSA-SHA256");s.update(c);let l=s.sign(e.private_key,"base64url"),d=`${c}.${l}`;return(await et.post("https://oauth2.googleapis.com/token",{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:d},{headers:{Connection:"close"}})).data.access_token}import{spinner as ht,log as A,isCancel as yt,confirm as Qn,select as Ft}from"@clack/prompts";import S from"chalk";import E from"fs";import P from"path";import{execSync as F,spawn as $i}from"child_process";import _e from"os";import eo from"crypto";var Pi=(e,n)=>n.filter(t=>E.existsSync(P.join(e,t))).reduce((t,i)=>t.update(E.readFileSync(P.join(e,i))),eo.createHash("sha256")).digest("hex").slice(0,16),to=e=>Pi(e,["package.json","yarn.lock","package-lock.json","bun.lockb"]),io=e=>Pi(e,["Podfile","Podfile.lock"]),no=e=>{let n=P.join(e,"fingerprint.json");try{return JSON.parse(E.readFileSync(n,"utf-8"))}catch{return{}}},bi=(e,n)=>{E.mkdirSync(e,{recursive:!0}),E.writeFileSync(P.join(e,"fingerprint.json"),JSON.stringify(n,null,2))},oo=7200*1e3,ro=(e,n)=>{E.mkdirSync(e,{recursive:!0});let t=P.join(e,"build.lock");if(E.existsSync(t))try{let i=JSON.parse(E.readFileSync(t,"utf-8")),o=Date.now()-(i.timestamp||0);if(o<oo)throw new Error(`Another build is already running for this project (build ${i.buildId}, started ${Math.round(o/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}E.writeFileSync(t,JSON.stringify({buildId:n,pid:process.pid,timestamp:Date.now()}))},so=(e,n)=>{let t=P.join(e,"build.lock");try{E.existsSync(t)&&JSON.parse(E.readFileSync(t,"utf-8")).buildId===n&&E.unlinkSync(t)}catch{}},De=(e,n,t=process.cwd(),i={},o,r)=>new Promise((a,c)=>{let s=["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin",P.join(_e.homedir(),".npm-global/bin")],d=[...(process.env.PATH||"").split(":"),...s].filter((m,h,$)=>m&&$.indexOf(m)===h).join(":");process.env[`${f.envPrefix}DEBUG`]&&console.log(S.magenta(`[${f.nameUpper}_DEBUG] Execution PATH: ${d}`));let u={...process.env,...i,PATH:d,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"};o&&process.env[`${f.envPrefix}DEBUG`]&&(o(S.magenta(`[ENVIRONMENT] node: ${process.execPath}
|
|
725
725
|
`)),o(S.magenta(`[ENVIRONMENT] PATH: ${d}
|
|
726
726
|
`)),o(S.magenta(`[ENVIRONMENT] command: ${e} ${n.join(" ")}
|
|
727
|
-
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m=
|
|
728
|
-
`)))}let g
|
|
729
|
-
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),d.abort(),p&&clearInterval(p))}catch{}},5e3));let g=
|
|
730
|
-
`)},
|
|
731
|
-
`))}catch(y){A.warn(S.yellow(`Could not fetch auto build number: ${y.message}`))}await H("lock"),e.developmentClient?(A.info(S.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(A.info(S.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await H("clone"),A.info(S.dim("Preparing source...")),await H("read_config");let y=
|
|
732
|
-
`)}await H("read_package"),
|
|
733
|
-
`),
|
|
727
|
+
`)));let p=e;if(["node","npm","npx","pod"].includes(e)){let m=P.dirname(process.execPath),h=P.join(m,e);E.existsSync(h)&&(p=h,o&&o(S.dim(`[EXEC] Using absolute path: ${p}
|
|
728
|
+
`)))}let g=$i(p,n,{stdio:"pipe",cwd:t,shell:!0,env:u,detached:process.platform!=="win32"});if(r){if(r.aborted){if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}return c(new Error("Command aborted"))}r.addEventListener("abort",()=>{if(g.pid)try{process.kill(-g.pid,"SIGTERM")}catch{g.kill()}c(new Error("Command aborted"))})}g.stdout.on("data",m=>{let h=m.toString();process.stdout.write(h),o&&o(h)}),g.stderr.on("data",m=>{let h=m.toString();process.stderr.write(h),o&&o(h)}),g.on("close",m=>{m===0?a(m):c(new Error(`Command failed with code ${m}: ${e} ${n.join(" ")}`))}),g.on("error",m=>c(m))}),ao=e=>{let n=Math.floor(e/1e3%60),t=Math.floor(e/(1e3*60)%60),i=Math.floor(e/(1e3*60*60)%24),o=[];return i>0&&o.push(`${i}h`),t>0&&o.push(`${t}m`),(n>0||o.length===0)&&o.push(`${n}s`),o.join(" ")},Ge=(e,n)=>{let t=[];try{if(!E.existsSync(e))return t;let i=E.readdirSync(e);for(let o of i){let r=P.join(e,o);try{let a=E.statSync(r);if(n.some(s=>o.endsWith(s))){t.push(P.resolve(r));continue}a.isDirectory()&&(t=t.concat(Ge(r,n)))}catch{}}}catch{}return t},Ht=async(e,n,t={},i,o={})=>{let r=ht(),a=Date.now(),c=e.platform,s=e.buildProfile||"production",l=async(y,w={})=>{if(i)for(let I=1;I<=3;I++)try{await _.patch(`/builds/${i}/${n}`,{status:y,...w});return}catch(b){let O=b?.response?.data?.message||b?.message||String(b);console.error(`[reportStatus] attempt ${I}/3 failed (status=${y}): ${O}`),I<3&&await new Promise(G=>setTimeout(G,2e3))}},d=new AbortController,{signal:u}=d,p=null;i&&(p=setInterval(async()=>{try{(await _.get(`/builds/${i}/${n}`)).data.status==="cancelled"&&(A.warn(S.yellow(`
|
|
729
|
+
\u{1F6D1} Build cancelled from dashboard. Terminating...`)),d.abort(),p&&clearInterval(p))}catch{}},5e3));let g=P.join(process.cwd(),".mach-cache"),m="setup",h="",$=null,N=async()=>{if(!h||!i)return;let y=h;h="";try{let w=y;Object.values(t).forEach(I=>{if(I&&I.length>5){let b=I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");w=w.replace(new RegExp(b,"g"),"[SECRET]")}}),await _.post(`/builds/${i}/${n}/logs`,{log:w,step:m})}catch{}},C=async()=>{$&&(clearTimeout($),$=null),await N(),so(g,n),p&&(clearInterval(p),p=null)},x=async y=>{i&&(h+=y,h.length>=8192?($&&(clearTimeout($),$=null),await N()):$||($=setTimeout(()=>{$=null,N()},2e3)))},H=async y=>{m=y,await x(`[STEP_START:${y}] ${Math.floor(Date.now()/1e3)}
|
|
730
|
+
`)},X=async(y,w,I,b)=>await De(y,w,I,b,O=>{x(O)},u);A.info(S.blue(`\u{1F680} Starting local build for ${c} (${s})...`));try{ro(g,n)}catch(y){throw await l("failed",{error:y.message}),y}if(await l("building"),await H("setup"),i&&c==="ios"&&!e.simulator)try{let y=parseInt(t.BUILD_NUMBER||"0",10),w=await _.post(`/projects/${i}/next-build-number`,{platform:"ios",startFrom:y});w.data.status==="success"&&(t.BUILD_NUMBER=String(w.data.buildNumber),A.info(S.dim(`Auto build number: ${t.BUILD_NUMBER}`)),await x(`[BUILD_NUMBER] ${t.BUILD_NUMBER}
|
|
731
|
+
`))}catch(y){A.warn(S.yellow(`Could not fetch auto build number: ${y.message}`))}await H("lock"),e.developmentClient?(A.info(S.blue("\u2139\uFE0F Configuring build to INCLUDE expo-dev-client (Development Client mode)...")),delete process.env.EXPO_NO_DEV_CLIENT,delete process.env.EXPO_AUTOLINKING_EXCLUDE):(A.info(S.blue("\u2139\uFE0F Configuring build to EXCLUDE expo-dev-client (Production/Staging mode)...")),process.env.EXPO_NO_DEV_CLIENT="1",process.env.EXPO_AUTOLINKING_EXCLUDE="expo-dev-client");try{await H("clone"),A.info(S.dim("Preparing source...")),await H("read_config");let y=P.join(process.cwd(),f.configFileName);if(E.existsSync(y)){let U=JSON.parse(E.readFileSync(y,"utf-8"))?.build?.[s]||{};await x(`[CONFIG] Profile: ${s}, distribution: ${U.distribution||"not set"}, simulator: ${U.simulator||!1}
|
|
732
|
+
`)}if(await H("read_package"),e.nodeVersion){let k=process.env.NVM_DIR||P.join(_e.homedir(),".nvm"),U=P.join(k,"versions","node"),q;if(E.existsSync(U)){let R=E.readdirSync(U).sort().reverse(),Z=e.nodeVersion.startsWith("v")?e.nodeVersion:`v${e.nodeVersion}`,V=R.find(Y=>Y===Z||Y.startsWith(Z+".")||Y.startsWith(`v${e.nodeVersion}.`));V&&(q=P.join(U,V,"bin"))}if(q&&E.existsSync(q)){let R=process.env.PATH||"";process.env.PATH=`${q}:${R}`,await x(`[NODE] Switched to Node ${e.nodeVersion} \u2014 using ${q}
|
|
733
|
+
`),A.info(S.green(`\u2713 Node switched to ${e.nodeVersion} (${q})`))}else await x(`[NODE] Warning: Node ${e.nodeVersion} not found in nvm. Run: nvm install ${e.nodeVersion} on the build machine.
|
|
734
|
+
`),A.warn(S.yellow(`Node ${e.nodeVersion} not found in nvm \u2014 using system default`))}await H("deps"),r.start("Checking dependencies...");let w=no(g),I=to(process.cwd()),b=E.existsSync("node_modules"),O=E.existsSync("yarn.lock"),G=E.existsSync("bun.lockb");b&&w.node&&w.node!==I&&(r.stop("Dependency fingerprint changed \u2014 clearing node_modules for clean install..."),await x(`[CACHE] package.json/lockfile changed \u2014 wiping node_modules
|
|
735
|
+
`),E.rmSync(P.join(process.cwd(),"node_modules"),{recursive:!0,force:!0}),b=!1);let M="npm",T=["install","--prefer-offline"];O?(M="yarn",T=["install","--prefer-offline"]):G&&(M="bun",T=["install"]),b?r.stop("Cached node_modules found. Syncing dependencies..."):r.stop("No cached dependencies. Running fresh install..."),A.info(S.dim(`Running ${M} ${T.join(" ")}...`)),await X(M,T,process.cwd(),t),w.node=I,bi(g,w),e.preBuild&&(A.info(S.blue("Running pre-install hook...")),A.info(S.dim(`> ${e.preBuild}`)),await H("prebuild"),await X("bash",[e.preBuild],process.cwd(),t));let L=JSON.parse(E.readFileSync("package.json","utf-8")),Q=L.dependencies?.expo||L.devDependencies?.expo,K=e.iosBundleIdentifier||"",j=e.name||"";if(Q){r.start(`Enforcing ${f.name} configuration...`);let k=P.join(process.cwd(),"app.json"),U=null;if(E.existsSync(k)){U=E.readFileSync(k,"utf-8");let R=JSON.parse(U);R.expo=R.expo||{},j||(j=R.expo.name||""),c==="ios"&&!K&&(K=R.expo?.ios?.bundleIdentifier||""),e.name&&(R.expo.name=e.name),e.scheme&&(R.expo.scheme=e.scheme),c==="ios"&&e.iosBundleIdentifier?(R.expo.ios=R.expo.ios||{},R.expo.ios.bundleIdentifier=e.iosBundleIdentifier):c==="android"&&e.androidPackage&&(R.expo.android=R.expo.android||{},R.expo.android.package=e.androidPackage),E.writeFileSync(k,JSON.stringify(R,null,2))}let q=["exec","--","expo","prebuild","--platform",c,"--no-install"];try{if(await H("prebuild"),await X("npm",q,process.cwd(),t),c==="ios"&&E.existsSync("ios")){await H("pods"),A.info(S.blue("Running pod install..."));try{let R=P.resolve("ios"),Z=P.join(R,"Podfile");if(!E.existsSync(Z))throw new Error("ios/Podfile not found. Skipping pod install.");let V=E.readFileSync(Z,"utf-8"),Y=e.iosDeploymentTarget||"13.4";if(!e.developmentClient&&(A.info(S.blue("\u2139\uFE0F Patching Podfile to EXCLUDE expo-dev-client...")),V.includes("use_expo_modules!")&&!V.includes("exclude:"))){let ae=/use_expo_modules!(\s*)$/m;ae.test(V)?V=V.replace(ae,'use_expo_modules!(exclude: ["expo-dev-client"])$1'):V=V.replace("use_expo_modules!",'use_expo_modules!(exclude: ["expo-dev-client"])')}let oe=`
|
|
734
736
|
installer.generated_projects.each do |project|
|
|
735
737
|
project.targets.each do |target|
|
|
736
738
|
target.build_configurations.each do |config|
|
|
737
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
739
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${Y}'
|
|
738
740
|
end
|
|
739
741
|
end
|
|
740
742
|
end
|
|
741
743
|
installer.pods_project.targets.each do |target|
|
|
742
744
|
target.build_configurations.each do |config|
|
|
743
|
-
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${
|
|
745
|
+
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '${Y}'
|
|
744
746
|
end
|
|
745
747
|
end
|
|
746
|
-
`,Ee=/post_install\s+do\s+\|installer\|/;if(Ee.test(
|
|
747
|
-
${
|
|
748
|
+
`,Ee=/post_install\s+do\s+\|installer\|/;if(Ee.test(V))A.info(S.dim(`Injecting deployment target (${Y}) into existing post_install hook...`)),V=V.replace(Ee,`post_install do |installer|
|
|
749
|
+
${oe}`),E.writeFileSync(Z,V);else{A.info(S.dim(`Appending new post_install hook for deployment target (${Y})...`));let ae=`
|
|
748
750
|
post_install do |installer|
|
|
749
|
-
${
|
|
751
|
+
${oe}
|
|
750
752
|
end
|
|
751
|
-
`;E.appendFileSync(
|
|
752
|
-
`),A.info(S.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),E.rmSync(
|
|
753
|
-
\u2713 Local build completed successfully in ${Se}`)),await l("building",{...K&&{bundleId:K},...
|
|
754
|
-
\u{1F4E6} Generated Artifacts:`)),
|
|
753
|
+
`;E.appendFileSync(Z,ae)}let qe="/opt/homebrew/bin/pod",Lt=E.existsSync(qe)?qe:"pod",Fe=io(R);E.existsSync(P.join(R,"Pods"))&&w.pods&&w.pods!==Fe&&(await x(`[CACHE] Podfile/Podfile.lock changed \u2014 wiping ios/Pods
|
|
754
|
+
`),A.info(S.dim("Podfile fingerprint changed \u2014 clearing Pods for clean install...")),E.rmSync(P.join(R,"Pods"),{recursive:!0,force:!0})),A.info(S.dim(`Using pod command: ${Lt} in ${R}`)),await X(Lt,["install"],R,t),w.pods=Fe,bi(g,w)}catch(R){let Z=R.message||"Unknown error";A.warn(S.yellow(`Native "pod" command failed: ${Z}`)),A.info(S.dim("Falling back to npm exec pod-install...")),A.info(S.magenta(`${f.nameUpper}_DEBUG: Executing pod-install override via npx --yes pod-install@latest`)),await X("npx",["--yes","pod-install@latest","ios"],process.cwd(),t)}if(E.existsSync("ios/Pods")){A.info(S.dim("Disabling signing for Pod targets to prevent conflicts..."));try{F(`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{U&&E.writeFileSync(k,U)}r.stop(`Expo prebuild complete (${f.name} config enforced).`)}let B=[];if(c==="android")await H("build"),B=await co(e,s,t,k=>x(k),u);else if(c==="ios"){await H("signing"),A.info(S.dim("Preparing credentials..."));let k=o?.distributionType;B=await lo(e,n,s,t,i,U=>x(U),u,k,U=>H(U))}e.postBuild&&(A.info(S.blue("Running post-build hook...")),A.info(S.dim(`> ${e.postBuild}`)),await X(e.postBuild,[],process.cwd(),t));let Se=ao(Date.now()-a);if(A.success(S.green(`
|
|
755
|
+
\u2713 Local build completed successfully in ${Se}`)),await l("building",{...K&&{bundleId:K},...j&&{appName:j}}),B.length>0&&(A.info(S.cyan(`
|
|
756
|
+
\u{1F4E6} Generated Artifacts:`)),B.forEach(k=>{let U=P.resolve(k);A.info(S.dim(` - ${k}`)),A.info(S.gray(` Path: ${U}`))}),e.interactive)){let k=await Qn({message:"Install on connected device?"});if(!yt(k)&&k){if(c==="android"){let U=B.find(q=>q.endsWith(".apk"))||B[0];await po(U,q=>x(q))}else if(c==="ios"){let U=B.find(R=>R.endsWith(".ipa"))||B.find(R=>R.endsWith(".app"))||B[0],q=Oe("ios");e.simulator?await fo(U,q||"",R=>x(R)):await mo(U,q||"",R=>x(R))}}}await H("upload");let Ae=[];for(let k of B)try{let U=P.join(_e.tmpdir(),`${n}-${P.basename(k)}`);E.copyFileSync(k,U),Ae.push(U),A.info(S.dim(` \u{1F4CB} Preserved artifact: ${P.basename(k)}`))}catch{A.warn(S.yellow(` Failed to preserve artifact: ${P.basename(k)}`))}B=Ae,A.info(S.dim("\u{1F9F9} Cleaning workspace (preserving dependency cache)..."));try{let k=process.cwd(),U=new Set(["node_modules"]),q=E.readdirSync(k),R=0;for(let Z of q)if(!U.has(Z)){if(Z==="ios"){let V=P.join(k,"ios"),Y=E.readdirSync(V);for(let oe of Y)if(oe!=="Pods")try{E.rmSync(P.join(V,oe),{recursive:!0,force:!0}),R++}catch{}continue}try{E.rmSync(P.join(k,Z),{recursive:!0,force:!0}),R++}catch{}}try{let Z=P.join(_e.tmpdir(),`${f.buildPrefix}-${n}.keychain-db`);E.existsSync(Z)&&F(`security delete-keychain "${Z}"`,{stdio:"ignore"})}catch{}A.info(S.dim(` Cleaned ${R} items. Cached: node_modules${E.existsSync(P.join(k,"ios","Pods"))?", ios/Pods":""}`)),A.info(S.green("\u{1F512} Security: No source code retained on build server. Only public dependencies cached."))}catch{A.warn(S.yellow("Post-build cleanup encountered errors (non-fatal)."))}try{let U=P.join(_e.homedir(),f.workspacesDir),q=F(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim(),R=parseInt(q,10)*1024;if(R<53687091200&&E.existsSync(U)){A.info(S.dim(` \u26A0\uFE0F Low disk space (${(R/1024/1024/1024).toFixed(0)} GB free). Running cache eviction...`));let Z=P.basename(process.cwd()),V=E.readdirSync(U).filter(Y=>Y!==Z).map(Y=>{let oe=P.join(U,Y);try{let Ee=E.statSync(oe);return Ee.isDirectory()?{name:Y,dir:oe,mtime:Ee.mtimeMs}:null}catch{return null}}).filter(Boolean);V.sort((Y,oe)=>Y.mtime-oe.mtime);for(let Y of V){if(R>=53687091200)break;try{E.rmSync(Y.dir,{recursive:!0,force:!0}),A.info(S.dim(` \u{1F5D1}\uFE0F Evicted stale workspace: ${Y.name}`));let oe=F(`df -k "${U}" | tail -1 | awk '{print $4}'`,{encoding:"utf8"}).trim();if(parseInt(oe,10)*1024>=53687091200)break}catch{}}}}catch{}return await C(),B}catch(y){throw await C(),y.message==="Command aborted"?(A.warn(S.yellow(`
|
|
755
757
|
\u274C Build aborted.`)),await l("failed",{error:"Aborted by user"}),y):(A.error(S.red(`
|
|
756
|
-
\u2717 Local build failed: ${y.message}`)),await l("failed",{error:y.message}),y)}},co=async(e,n,t={},i,o)=>{let r=E.existsSync("android/gradlew")?"android/gradlew":E.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let a="assembleRelease";e.distribution==="store"?a="bundleRelease":e.distribution==="internal"&&(a="assembleRelease");let c=e.buildCommand||a;A.info(S.blue(`Running Android build: ${c}...`));let s=r.includes("android/")?"android":".",l=(r.includes("android/"),"./gradlew");await De(l,[c],s,t,i,o);let d=
|
|
757
|
-
`)[0]||"unknown"}`))}if(!
|
|
758
|
-
`).map(se=>se.trim().replace(/^"|"$/g,"")).filter(se=>se.length>0),
|
|
758
|
+
\u2717 Local build failed: ${y.message}`)),await l("failed",{error:y.message}),y)}},co=async(e,n,t={},i,o)=>{let r=E.existsSync("android/gradlew")?"android/gradlew":E.existsSync("gradlew")?"./gradlew":null;if(!r)throw new Error("Could not find gradlew. Is this an Android project?");let a="assembleRelease";e.distribution==="store"?a="bundleRelease":e.distribution==="internal"&&(a="assembleRelease");let c=e.buildCommand||a;A.info(S.blue(`Running Android build: ${c}...`));let s=r.includes("android/")?"android":".",l=(r.includes("android/"),"./gradlew");await De(l,[c],s,t,i,o);let d=P.join(s,"app/build/outputs");return Ge(d,[".apk",".aab"])},lo=async(e,n,t,i={},o,r,a,c,s)=>{if(process.platform!=="darwin")throw new Error("iOS builds can only be run on macOS.");let l=P.resolve(process.cwd(),E.existsSync("ios")?"ios":"."),d=E.readdirSync(l),u=d.find(C=>C.endsWith(".xcworkspace")),p=d.find(C=>C.endsWith(".xcodeproj"));if(!u&&!p)throw new Error("Could not find Xcode workspace or project in ios/ directory.");try{let C=F("xcode-select -p").toString().trim();A.info(S.dim(`Using Xcode at: ${C}`))}catch{A.warn(S.dim("Could not detect Xcode path."))}A.info(S.blue("Running iOS build via xcodebuild..."));let g=u?u.replace(".xcworkspace",""):p?.replace(".xcodeproj",""),m=e.iosScheme||g||e.scheme,h=e.developmentClient?"Debug":e.iosConfiguration||"Release",$=(o||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),N=P.join(_e.homedir(),`Library/Developer/Xcode/DerivedData/${f.nameLower}`,$);if(E.mkdirSync(N,{recursive:!0}),e.simulator){A.info(S.dim(`Building for simulator (Scheme: ${m}, Config: ${h})...`)),await De("xcodebuild",[u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-sdk","iphonesimulator","-derivedDataPath",N,"CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO"],l,i,r,a);let C=P.join(N,"Build/Products",`${h}-iphonesimulator`),x=Ge(C,[".app"]);if(x.length>0){let H=x[0],X=P.basename(H,".app"),y=P.join(C,`${X}_simulator.zip`);return A.info(S.dim(`Creating simulator artifact: ${y}...`)),F(`cd "${C}" && zip -r "${y}" "${P.basename(H)}"`),[y]}return[]}else{A.info(S.dim(`Archiving (Scheme: ${m}, Config: ${h})...`));let C=P.join(l,"build.xcarchive"),x=P.join(l,"export"),H=i.IOS_DIST_P12,X=i.IOS_PROVISIONING_PROFILE,y=i.IOS_P12_PASSWORD||"",w=[],I,b,O={isAppStore:!1,isDevelopment:!1};if(H&&X){A.info(S.blue("\u{1F510} CI/CD Signing: Importing certificates..."));try{let j=`${f.buildPrefix}-${n}.keychain-db`,B=P.join(_e.tmpdir(),j),Se=f.keychainPassword;F(`security create-keychain -p "${Se}" "${B}" 2>/dev/null || true`),F(`security set-keychain-settings -t 3600 -l "${B}"`),F(`security unlock-keychain -p "${Se}" "${B}"`);let Ae=P.join(_e.tmpdir(),`cert-${n}.p12`),k=Buffer.from(H,"base64");E.writeFileSync(Ae,k),A.info(S.dim(`P12 data size: ${k.length} bytes, first bytes: ${k.slice(0,4).toString("hex")}`)),(k.length<100||k[0]!==48)&&(A.warn(S.yellow("\u26A0\uFE0F P12 data looks corrupted or was not decrypted correctly.")),A.warn(S.yellow(" This usually means MACH_ENCRYPTION_KEY on the Remote API differs from when credentials were uploaded.")));let U=[y,"",f.keychainPassword],q=!1;for(let se of U)try{F(`security import "${Ae}" -k "${B}" -P "${se}" -A -T /usr/bin/codesign -T /usr/bin/security`,{stdio:"pipe"}),q=!0,A.info(S.dim(`\u2713 P12 imported successfully with password: ${se?"[set]":"[empty]"}`));break}catch(ae){A.info(S.dim(` P12 import attempt with password ${se?`"${se.substring(0,3)}..."`:"[empty]"} failed: ${ae.message?.split(`
|
|
759
|
+
`)[0]||"unknown"}`))}if(!q)throw new Error("Failed to import P12.");E.unlinkSync(Ae),F(`security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${Se}" "${B}"`);let R=F("security list-keychains -d user",{encoding:"utf-8"}).split(`
|
|
760
|
+
`).map(se=>se.trim().replace(/^"|"$/g,"")).filter(se=>se.length>0),Z=[B,...R].map(se=>`"${se}"`).join(" ");F(`security list-keychains -d user -s ${Z}`),F(`security default-keychain -s "${B}"`);let V=P.join(_e.homedir(),"Library/MobileDevice/Provisioning Profiles");E.mkdirSync(V,{recursive:!0});let Y=Buffer.from(X,"base64"),oe=P.join(V,`${f.nameLower}-temp-${n}.mobileprovision`);E.writeFileSync(oe,Y);let Ee=Y.toString("utf-8"),qe=/<key>get-task-allow<\/key>\s*<true\/>/.test(Ee);O={isAppStore:!Ee.includes("<key>ProvisionedDevices</key>")&&!qe,isDevelopment:qe};try{let ae=F(`security cms -D -i "${oe}"`,{encoding:"utf-8"}).match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=ae?ae[1]:void 0}catch{let ae=Ee.match(/<key>UUID<\/key>\s*<string>([^<]+)<\/string>/);b=ae?ae[1]:void 0}b||(A.warn("Could not extract UUID from provisioning profile. Using fallback."),b=`${f.nameLower}-${n}`);let Fe=P.join(V,`${b}.mobileprovision`);E.existsSync(Fe)&&E.unlinkSync(Fe),E.renameSync(oe,Fe);try{let ae=F(`security find-identity -v -p codesigning "${B}"`,{encoding:"utf-8"}).match(/"((?:Apple|iPhone) (?:Distribution|Developer|Development)[^"]*)"/);ae&&(I=ae[1],A.info(S.blue(`Identity auto-detected from keychain: "${I}"`)))}catch{}I||(I=O.isDevelopment?"Apple Development":"Apple Distribution",A.info(S.blue(`Identity fallback (profile heuristic): "${I}"`))),A.info(S.dim(`Profile type: ${O.isDevelopment?"Development":O.isAppStore?"App Store":"Ad-Hoc"}`)),A.info(S.dim(`Identity Detection: get-task-allow=${O.isDevelopment}, Selected Identity="${I}"`)),w.push("CODE_SIGN_STYLE=Manual"),w.push(`CODE_SIGN_IDENTITY="${I}"`),w.push(`PROVISIONING_PROFILE_SPECIFIER=${b}`),e.iosTeamId&&w.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`)}catch(j){throw A.error(`Signing setup failed: ${j.message}`),j}}else w.push("-allowProvisioningUpdates"),e.iosTeamId&&w.push(`DEVELOPMENT_TEAM=${e.iosTeamId}`);s&&await s("archive"),A.info(S.blue(`Archive detected Identity: "${I}"`)),A.info(S.blue(`Archive detected UUID: "${b}"`)),await De("xcodebuild",["archive",u?"-workspace":"-project",u||p,"-scheme",m,"-configuration",h,"-archivePath",C,"-derivedDataPath",N,...w],l,i,r,a);let G;b?(O.isAppStore?G="app-store":O.isDevelopment?G="development":G="ad-hoc",A.info(S.blue(`Export method from profile: "${G}"`))):(G=e.distribution==="store"?"app-store":e.distribution==="internal"?"ad-hoc":"development",A.warn(S.yellow(`No profile UUID detected. Export method from distribution flag: "${G}"`)));let M=e.iosExportMethod||G,T=Oe("ios"),L=P.join(l,"ExportOptions.plist"),Q=`<?xml version="1.0" encoding="UTF-8"?>
|
|
759
761
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
760
762
|
<plist version="1.0">
|
|
761
763
|
<dict>
|
|
762
764
|
<key>method</key>
|
|
763
|
-
<string>${
|
|
765
|
+
<string>${M}</string>
|
|
764
766
|
<key>destination</key>
|
|
765
767
|
<string>export</string>
|
|
766
768
|
<key>signingStyle</key>
|
|
@@ -768,53 +770,53 @@ end
|
|
|
768
770
|
<key>thinning</key>
|
|
769
771
|
<string><none></string>
|
|
770
772
|
${e.iosTeamId?`<key>teamID</key><string>${e.iosTeamId}</string>`:""}
|
|
771
|
-
${
|
|
773
|
+
${T&&b?`
|
|
772
774
|
<key>provisioningProfiles</key>
|
|
773
775
|
<dict>
|
|
774
|
-
<key>${
|
|
776
|
+
<key>${T}</key>
|
|
775
777
|
<string>${b}</string>
|
|
776
778
|
</dict>`:""}
|
|
777
779
|
</dict>
|
|
778
|
-
</plist>`;if(E.writeFileSync(
|
|
779
|
-
${
|
|
780
|
+
</plist>`;if(E.writeFileSync(L,Q),process.env[`${f.envPrefix}DEBUG`]&&A.info(S.magenta(`[${f.nameUpper}_DEBUG] ExportOptions.plist:
|
|
781
|
+
${Q}`)),s&&await s("export"),A.info(S.blue(`Exporting with Bundle ID: "${T}"`)),A.info(S.blue(`Exporting with Method: "${M}"`)),r){r(S.magenta(`
|
|
780
782
|
[DIAGNOSTIC] Checking available signing identities...
|
|
781
|
-
`));try{let
|
|
782
|
-
`))}catch(
|
|
783
|
-
`))}}await De("xcodebuild",["-exportArchive","-archivePath",
|
|
784
|
-
`)}catch{let Se=`IPA validation failed for ${
|
|
785
|
-
`),new Error(Se)}return K}},Oe=e=>{try{let n=
|
|
783
|
+
`));try{let j=F("security find-identity -v -p codesigning",{encoding:"utf-8"});r(S.magenta(`${j}
|
|
784
|
+
`))}catch(j){r(S.red(`[DIAGNOSTIC] Failed to list identities: ${j.message}
|
|
785
|
+
`))}}await De("xcodebuild",["-exportArchive","-archivePath",C,"-exportPath",x,"-exportOptionsPlist",L],l,i,r,a),s&&await s("validate");let K=Ge(x,[".ipa"]);for(let j of K)try{F(`unzip -t "${j}"`,{stdio:"pipe"}),r&&r(`[IPA VALID] ${P.basename(j)} \u2014 archive integrity OK
|
|
786
|
+
`)}catch{let Se=`IPA validation failed for ${P.basename(j)}: archive may be corrupt`;throw r&&r(`[IPA CORRUPT] ${Se}
|
|
787
|
+
`),new Error(Se)}return K}},Oe=e=>{try{let n=P.join(process.cwd(),f.configFileName);if(E.existsSync(n)){let t=JSON.parse(E.readFileSync(n,"utf-8"));if(e==="android"&&t.android?.package)return t.android.package;if(e==="ios"&&t.ios?.bundleIdentifier)return t.ios.bundleIdentifier}if(e==="android"){let t=["android/app/build.gradle","app/build.gradle","build.gradle"];for(let i of t)if(E.existsSync(i)){let r=E.readFileSync(i,"utf-8").match(/applicationId\s+['"]([^'"]+)['"]/);if(r)return r[1]}}else{let t=P.resolve(process.cwd(),E.existsSync("ios")?"ios":"."),i=Ge(t,["Info.plist"]).filter(a=>!a.includes("/Pods/")&&!a.includes("/build/")&&!a.includes("/DerivedData/"));i.sort((a,c)=>c.split("/").length-a.split("/").length);for(let a of i){let s=E.readFileSync(a,"utf-8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/);if(s&&!s[1].includes("$"))return s[1]}let o=Ge(t,[".xcodeproj"]);if(o.length>0){let a=P.join(o[0],"project.pbxproj");if(E.existsSync(a)){let s=E.readFileSync(a,"utf-8").match(/PRODUCT_BUNDLE_IDENTIFIER\s*=\s*"?([^";\s]+)"?;/);if(s)return s[1]}}let r=["app.json","app.config.json","app.config.js","app.config.ts"];for(let a of r)if(E.existsSync(a)){let s=E.readFileSync(a,"utf-8").match(/"bundleIdentifier":\s*"([^"]+)"/);if(s)return s[1]}}}catch{return null}return null},uo=()=>{try{return F("emulator -version",{stdio:"ignore"}),"emulator"}catch{let n=_e.homedir(),t=[P.join(n,"Library/Android/sdk/emulator/emulator"),P.join(n,"Android/Sdk/emulator/emulator"),"/usr/local/lib/android/sdk/emulator/emulator"];for(let i of t)if(E.existsSync(i))return i}return"emulator"},po=async(e,n)=>{let t=ht();try{if(F("adb devices").toString().split(`
|
|
786
788
|
`).slice(1).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("*")).map(a=>a.split(" ")[0]).length===0){A.warn(S.yellow("No Android devices or emulators found."));let a=uo(),c=[];try{c=F(`${a} -list-avds`).toString().split(`
|
|
787
|
-
`).filter(s=>s.trim().length>0)}catch{}if(c.length>0){let s=await Ft({message:"Select an emulator to launch:",options:c.map(u=>({value:u,label:u}))});if(yt(s))return;t.start(`Launching emulator ${s}...`)
|
|
788
|
-
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),A.error(S.red(`Failed to install APK: ${i.message}`))}},fo=async(e,n,t)=>{let i=ht();try{if(!F("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(S.yellow("No iOS Simulator is currently booted."));let r=F("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,c=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&c.push({...p,runtime:u})})});let s=await Ft({message:"Select a simulator to launch:",options:c.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(yt(s))return;i.start(`Booting ${s}...`),F(`xcrun simctl boot ${s}`),F(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let l=0,d=!1;for(;l<30;){try{if(F("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on Simulator: ${o.message}`))}},mo=async(e,n,t)=>{let i=ht();i.start("Scanning for connected iOS devices...");try{let o=F("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.length===0)throw 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 c=a[0].identifier;if(a.length>1){i.stop();let s=await Ft({message:"Select a device to install on:",options:a.map(l=>({value:l.identifier,label:`${l.deviceProperties?.name||l.name||l.model?.name} (${l.model?.name||"iPhone"}) - ${l.identifier}`}))});if(yt(s))return;c=s,i.start(`Installing on ${c}...`)}else i.message(`Installing on ${a[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",c,e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",c,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on device: ${o.message}`)),A.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import St from"fs";function Ne(e){if(e){if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}if(!St.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(St.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Ue(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Ue(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let a of o.envGroups){let c=e.envGroups?.[a];c?Object.assign(r,c):log.warn(`Environment group not found: ${a}`)}o.env={...r,...o.env}}return o}var Be=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let a in o){let c=o[a],s=`${r}${a.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;c!==null&&typeof c=="object"&&!Array.isArray(c)?i(c,`${s}_`):t[s]=String(c)}};return i(e,n),t};var At=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=Gt(),t=e.buildId||go(),i=e.projectId,o=Date.now(),r=!!i,a=async c=>{if(i)try{await $.patch(`/builds/${i}/${t}`,{status:"failed",error:c})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let c=await $.get(`/builds/${i}/${e.buildId}/source-url`);if(c.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(c.data.downloadUrl,{responseType:"stream"}),l=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=we.join(ho.homedir(),f.workspacesDir,l);ce.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ce.existsSync(d)){let N=ce.readdirSync(d);for(let O of N){if(u.has(O))continue;if(O==="ios"){let H=we.join(d,"ios");try{let q=ce.readdirSync(H);for(let y of q)if(!p.has(y))try{ce.rmSync(we.join(H,y),{recursive:!0,force:!0})}catch{}}catch{}continue}let L=we.join(d,O);try{ce.rmSync(L,{recursive:!0,force:!0})}catch{}}}let g=we.join(d,"source.zip"),m=s.data,h=ce.createWriteStream(g);await new Promise((N,O)=>{m.pipe(h),m.on("error",L=>O(L)),h.on("finish",()=>N())}),new vi(g).extractAllTo(d,!0);try{ce.unlinkSync(g)}catch{}process.chdir(d),D.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),D.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(we.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(we.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(c){n.stop(`Failed to prepare isolated workspace: ${c.message}`),i&&await a(`Setup Error: ${c.message}`),process.exit(1)}}try{let c=e.repo;if(!c)try{c=wi("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!c&&e.dryRun,c||(c="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${v.cyan(t)}`);let s={},l={},d=Ne(`./${f.configFileName}`);if(d){i=d.projectId;let y=e.buildProfile||"production",w=Ue(d,y);!w&&e.buildProfile&&(D.error(`Build profile '${y}' not found in ${f.configFileName}`),process.exit(1));let I=w||{};process.env.MACH_DEBUG&&D.info(v.dim(`Build profile: ${y} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||y}`)),I.env&&(l=I.env,D.info(v.blue(`Use Build Profile: ${y}`)));let b=e.platform,R=I[b]||{},G=["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);for(let k of G){let J=R[k]!==void 0?R[k]:I[k];J!==void 0&&e[k]===void 0&&(e[k]=J)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let U=k=>{if(!k)return k;if(k.startsWith("scripts.")){let J=k.split(".")[1],K=d.scripts?.[J];if(K)return K;D.warn(`Script reference not found: ${k}`)}return k};e.buildCommand=U(e.buildCommand),e.preBuild=U(e.preBuild),e.postBuild=U(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let C={...Be(d,f.envPrefix),...Be(I,`${f.envPrefix}PROFILE_`)};s={...s,...l,...C},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&d.submit?.[y]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[y].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(D.warn(v.yellow(`Check: Using 'production' Team ID for '${y}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?D.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=wi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?m="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?m="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(m="Development");let h=e.platform==="ios"?"iOS":"Android",P=e.platform==="ios"&&e.simulator?" (Simulator)":"",N=`${h}${P} v${p} (${m})`;if(i){try{let y=e.buildProfile||"production";D.info(v.blue(`Fetching managed secrets for profile: ${y}...`));let w=e.environment||y,b=(await $.get(`/projects/${i}/secrets/export?env=${w}`)).data;b.status==="success"&&b.secrets&&(s={...s,...b.secrets},Object.keys(b.secrets).length>0&&D.info(v.magenta(`\u2713 Injected ${Object.keys(b.secrets).length} secrets from Dashboard.`)))}catch(y){D.warn(`Failed to load managed secrets from Dashboard: ${y.message}`)}try{D.info(v.blue("Fetching managed credentials..."));let y="development";e.distribution==="store"?y="store":e.distribution==="internal"&&(y=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(y="development");let w=await $.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:y}});if(w.data.status==="success"&&w.data.credentials){let I=w.data.credentials;D.info(v.magenta(`\u2713 Found ${I.length} relevant credentials.`));let b=I.filter(C=>{if(C.distributionType){let k=y==="internal"?"adhoc":y;return C.distributionType===k||C.distributionType===y}return!0});D.info(v.dim(` Filtered to ${b.length} credentials for distributionType: ${y}`));let R=!1,G=!1,U=!1;for(let C of b)if(C.downloadUrl)try{let k="",J=5;for(;J>0;)try{let K=await tt.get(C.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});k=Buffer.from(K.data).toString("base64");break}catch(K){if(J--,J===0)throw K;D.warn(v.dim(` - Temporary network error downloading ${C.name}. Retrying... (${5-J}/5)`)),await new Promise(B=>setTimeout(B,2e3))}if(C.type==="ios_cert"&&!R)s.IOS_DIST_P12=k,C.password?(s.IOS_P12_PASSWORD=C.password,D.info(v.dim(` - Injected ${C.name} as IOS_DIST_P12 with password from credential record`))):D.info(v.dim(` - Injected ${C.name} as IOS_DIST_P12`)),R=!0;else if(C.type==="ios_profile"&&!G)s.IOS_PROVISIONING_PROFILE=k,D.info(v.dim(` - Injected ${C.name} as IOS_PROVISIONING_PROFILE`)),G=!0;else if(C.type==="android_keystore"&&!U){s.ANDROID_KEYSTORE_BASE64=k;let K=C.password,B=C.alias||C.meta?.alias;if(K)s.ANDROID_KEY_PASSWORD=K,s.ANDROID_STORE_PASSWORD=K,D.info(v.dim(" - Injected keystore password from credential record"));else{let Ae=["ANDROID_KEY_PASSWORD",...[y==="store"?"PRODUCTION":y==="internal"?"STAGING":"DEVELOPMENT",y.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(x=>`KEYSTORE_PASSWORD_${x}`),"KEYSTORE_PASSWORD"].find(x=>!!s[x]);Ae&&s[Ae]&&(s.ANDROID_KEY_PASSWORD=s[Ae],s.ANDROID_STORE_PASSWORD=s[Ae])}if(B)s.ANDROID_KEY_ALIAS=B;else{let j=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Se=>!!s[Se]);j&&(s.ANDROID_KEY_ALIAS=s[j])}D.info(v.dim(` - Injected ${C.name} as ANDROID_KEYSTORE_BASE64`)),U=!0}}catch(k){D.warn(`Failed to download credential ${C.name}: ${k.message}`)}}if(e.platform==="android"){let I=d.android?.versionCode==="auto"||d.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let b=(w.data.credentials||[]).find(K=>K.type==="google_service_account");if(b||(b=((await $.get(`/credentials/${i}`)).data.credentials||[]).find(B=>B.type==="google_service_account")),!b)throw new Error("Google Service Account not found. Upload it via Dashboard to use auto-versioning.");let R=await $.get(`/credentials/${b.credentialId}/download`,{params:{projectId:i}});if(R.data.status!=="success"||!R.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let U=(await tt.get(R.data.downloadUrl,{headers:{Connection:"close"}})).data,C=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,k=await Ii(C,U);if(k==null)throw new Error("Could not retrieve any version information from Google Play.");let J=k+1;s.ANDROID_VERSION_CODE=J.toString(),n.stop(`\u2713 Resolved versionCode: ${v.green(J)} (Latest on Play Store: ${k})`)}catch(b){n.stop("Version resolution failed");let R=b.response?.data?.error?.message||b.message;D.warn(v.yellow(` \u26A0\uFE0F Auto-versioning failed: ${R}`)),D.warn(v.dim(' Falling back to version code from config. To fix: ensure Service Account has "View App Metadata" and "View App Information" permissions in Google Play Console.'))}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,b=!!s.IOS_PROVISIONING_PROFILE;if(!I||!b){let R=[...I?[]:["Distribution Certificate"],...b?[]:["Provisioning Profile"]].join(" and ");D.error(v.red(`Missing iOS credentials: ${R}`)),e.quiet&&process.exit(1);let G=e.yes||await _i({message:"Would you like to generate these credentials now?",initialValue:!0});if(G&&!Di(G))return await Je({platform:"ios",profile:g}),e.quiet||D.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){D.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let b=e.yes||await _i({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(b&&!Di(b))return await Je({platform:"android",profile:g}),e.quiet||D.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(y){D.warn(`Failed to resolve credentials: ${y.message}`)}}let O=!!(e.local&&e.buildId),L=!!(e.local||e.sshHost),H=!L&&!O;if(O){D.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let y=await Ht({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:N,buildType:m});await q(y),process.exit(0)}async function q(y){if(i&&y.length>0){let w=Gt(),I=[];e.quiet||w.start("Uploading artifacts to Dashboard...");try{for(let b of y){let R=we.basename(b),G=ce.readFileSync(b),U=we.extname(R).toLowerCase(),C="application/octet-stream",k=await $.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:R,fileType:C});if(k.data.status!=="success")throw new Error(`Failed to get upload URL for ${R}`);let J=!1;for(let K=1;K<=3;K++)try{await tt.put(k.data.uploadUrl,G,{headers:{"Content-Type":C},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),J=!0;break}catch(B){if(D.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${B.code||B.message})`)),K<3)await new Promise(j=>setTimeout(j,3e3*K));else throw B}J&&I.push({name:R,url:k.data.downloadUrl,size:G.length,type:U.substring(1)})}e.quiet||w.stop("Artifacts uploaded.")}catch(b){e.quiet||w.stop("Failed to upload artifacts."),D.error(v.red(`Upload error: ${b.message}`));try{await $.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:y.map(R=>we.basename(R)),endTime:Date.now()})}catch(R){D.warn(v.yellow(`Could not set fallback build status: ${R.message}`))}return}if(i&&I.length>0)try{D.info(v.cyan(`
|
|
789
|
-
\u{1F517} Download Links:`));for(let b of I)D.info(v.dim(` - ${b.name}: `)+v.blue.underline(b.url));await
|
|
789
|
+
`).filter(s=>s.trim().length>0)}catch{}if(c.length>0){let s=await Ft({message:"Select an emulator to launch:",options:c.map(u=>({value:u,label:u}))});if(yt(s))return;t.start(`Launching emulator ${s}...`),$i(a,["-avd",s],{detached:!0,stdio:"ignore"}).unref();let l=0,d=!1;for(;l<60;){try{if(F("adb shell getprop sys.boot_completed",{stdio:"pipe"}).toString().trim()==="1"){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw t.stop("Emulator launch timed out."),new Error("Emulator launch timed out. Please try launching it manually.");t.stop("Emulator launched.")}else throw new Error("No devices found and no emulators available to launch. (Make sure Android SDK is installed)")}t.start("Installing APK on device..."),await De("adb",["install","-r",e],process.cwd(),{},n),t.stop("Installation complete.");let r=Oe("android");if(r){A.info(S.blue(`\u{1F680} Launching ${r}...`));try{F(`adb shell dumpsys package ${r}`).toString().split(`
|
|
790
|
+
`).find(s=>s.includes("android.intent.action.MAIN")&&s.includes("android.intent.category.LAUNCHER"))?F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"}):F(`adb shell monkey -p ${r} -c android.intent.category.LAUNCHER 1`,{stdio:"ignore"})}catch{A.warn("Could not auto-launch app. You may need to open it manually.")}}}catch(i){t.stop("Installation failed."),A.error(S.red(`Failed to install APK: ${i.message}`))}},fo=async(e,n,t)=>{let i=ht();try{if(!F("xcrun simctl list devices booted").toString().includes("(Booted)")){A.warn(S.yellow("No iOS Simulator is currently booted."));let r=F("xcrun simctl list devices --json").toString(),a=JSON.parse(r).devices,c=[];Object.keys(a).forEach(u=>{a[u].forEach(p=>{p.isAvailable&&c.push({...p,runtime:u})})});let s=await Ft({message:"Select a simulator to launch:",options:c.map(u=>({value:u.udid,label:`${u.name} (${u.runtime.split(".").pop()})`}))});if(yt(s))return;i.start(`Booting ${s}...`),F(`xcrun simctl boot ${s}`),F(`open -a Simulator --args -CurrentDeviceUDID ${s}`);let l=0,d=!1;for(;l<30;){try{if(F("xcrun simctl list devices booted").toString().includes(s)){d=!0;break}}catch{}await new Promise(u=>setTimeout(u,2e3)),l++}if(!d)throw i.stop("Simulator boot timed out."),new Error("Simulator boot timed out.");i.stop("Simulator booted.")}i.start("Installing on iOS Simulator..."),await De("xcrun",["simctl","install","booted",e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["simctl","launch","booted",n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on Simulator: ${o.message}`))}},mo=async(e,n,t)=>{let i=ht();i.start("Scanning for connected iOS devices...");try{let o=F("xcrun devicectl list devices --json-output -").toString(),a=(JSON.parse(o).result?.devices||[]).filter(s=>s.connectionProperties?.transportType==="wired"||s.connectionProperties?.transportType==="localNetwork");if(a.length===0)throw 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 c=a[0].identifier;if(a.length>1){i.stop();let s=await Ft({message:"Select a device to install on:",options:a.map(l=>({value:l.identifier,label:`${l.deviceProperties?.name||l.name||l.model?.name} (${l.model?.name||"iPhone"}) - ${l.identifier}`}))});if(yt(s))return;c=s,i.start(`Installing on ${c}...`)}else i.message(`Installing on ${a[0].model.name}...`);await De("xcrun",["devicectl","device","install","app","--device",c,e],process.cwd(),{},t),i.stop("Installation complete."),A.info(S.blue(`\u{1F680} Launching ${n}...`)),await De("xcrun",["devicectl","device","launch","app","--device",c,n],process.cwd(),{},t)}catch(o){i.stop("Installation failed."),A.error(S.red(`Failed to install on device: ${o.message}`)),A.info(S.dim('Make sure your device is unlocked and "Developer Mode" is enabled in Settings -> Privacy & Security.'))}};import St from"fs";function Ne(e){if(e){if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}if(!St.existsSync(`./${f.configFileName}`))return null;try{return JSON.parse(St.readFileSync(`./${f.configFileName}`,"utf-8"))}catch{return null}}function Ue(e,n,t=new Set){if(t.has(n))throw new Error(`Circular inheritance detected in profile: ${n}`);t.add(n);let i=e.build?.[n];if(!i)return null;let o={...i};if(i.extends){let r=Ue(e,i.extends,t);r&&(o={...r,...i,env:{...r.env,...i.env},ios:{...r.ios,...i.ios},android:{...r.android,...i.android}})}if(o.envGroups&&Array.isArray(o.envGroups)){let r={};for(let a of o.envGroups){let c=e.envGroups?.[a];c?Object.assign(r,c):log.warn(`Environment group not found: ${a}`)}o.env={...r,...o.env}}return o}var je=(e,n=`${f.envPrefix}`)=>{let t={},i=(o,r)=>{if(o)for(let a in o){let c=o[a],s=`${r}${a.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`;c!==null&&typeof c=="object"&&!Array.isArray(c)?i(c,`${s}_`):t[s]=String(c)}};return i(e,n),t};var At=async e=>{e.platform!=="android"&&e.platform!=="ios"&&(D.error(`Platform ${e.platform} is not supported. Use 'android' or 'ios'.`),process.exit(1));let n=Gt(),t=e.buildId||go(),i=e.projectId,o=Date.now(),r=!!i,a=async c=>{if(i)try{await _.patch(`/builds/${i}/${t}`,{status:"failed",error:c})}catch{}};if(e.local&&e.buildId){e.quiet||n.start(`Preparing isolated workspace for build: ${e.buildId}`);try{let c=await _.get(`/builds/${i}/${e.buildId}/source-url`);if(c.data.status!=="success")throw new Error("Failed to get source download URL from API");let s=await tt.get(c.data.downloadUrl,{responseType:"stream"}),l=(i||e.projectId||"default").replace(/[^a-zA-Z0-9-_]/g,"_"),d=we.join(ho.homedir(),f.workspacesDir,l);ce.mkdirSync(d,{recursive:!0});let u=new Set(["node_modules",`.${f.nameLower}-cache-meta`]),p=new Set(["Pods"]);if(ce.existsSync(d)){let N=ce.readdirSync(d);for(let C of N){if(u.has(C))continue;if(C==="ios"){let H=we.join(d,"ios");try{let X=ce.readdirSync(H);for(let y of X)if(!p.has(y))try{ce.rmSync(we.join(H,y),{recursive:!0,force:!0})}catch{}}catch{}continue}let x=we.join(d,C);try{ce.rmSync(x,{recursive:!0,force:!0})}catch{}}}let g=we.join(d,"source.zip"),m=s.data,h=ce.createWriteStream(g);await new Promise((N,C)=>{m.pipe(h),m.on("error",x=>C(x)),h.on("finish",()=>N())}),new vi(g).extractAllTo(d,!0);try{ce.unlinkSync(g)}catch{}process.chdir(d),D.info(v.green(`\u2713 Persistent workspace ready: ${d}`)),D.info(v.dim(` \u{1F4E6} Cached dirs preserved: node_modules=${ce.existsSync(we.join(d,"node_modules"))?"\u2705":"\u274C"}, Pods=${ce.existsSync(we.join(d,"ios","Pods"))?"\u2705":"\u274C"}`)),n.stop()}catch(c){n.stop(`Failed to prepare isolated workspace: ${c.message}`),i&&await a(`Setup Error: ${c.message}`),process.exit(1)}}try{let c=e.repo;if(!c)try{c=wi("git config --get remote.origin.url").toString().trim()}catch{D.warn("Could not detect git repository URL.")}!c&&e.dryRun,c||(c="https://github.com/placeholder/repo.git"),D.info(`Build ID: ${v.cyan(t)}`);let s={},l={},d=Ne(`./${f.configFileName}`);if(d){i=d.projectId;let y=e.buildProfile||"production",w=Ue(d,y);!w&&e.buildProfile&&(D.error(`Build profile '${y}' not found in ${f.configFileName}`),process.exit(1));let I=w||{};process.env.MACH_DEBUG&&D.info(v.dim(`Build profile: ${y} | Platform: ${e.platform} | Distribution: ${I.distribution||"store"} | Environment: ${I.environment||y}`)),I.env&&(l=I.env,D.info(v.blue(`Use Build Profile: ${y}`)));let b=e.platform,O=I[b]||{},G=["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);for(let L of G){let Q=O[L]!==void 0?O[L]:I[L];Q!==void 0&&e[L]===void 0&&(e[L]=Q)}e.branch=e.branch||"main",e.iosConfiguration=e.iosConfiguration||(e.developmentClient||e.simulator?"Debug":"Release"),e.sshUser=e.sshUser||process.env.USER||"ubuntu",e.simulator===void 0&&(e.simulator=!1),e.local===void 0&&(e.local=!1),e.verbose===void 0&&(e.verbose=!1);let M=L=>{if(!L)return L;if(L.startsWith("scripts.")){let Q=L.split(".")[1],K=d.scripts?.[Q];if(K)return K;D.warn(`Script reference not found: ${L}`)}return L};e.buildCommand=M(e.buildCommand),e.preBuild=M(e.preBuild),e.postBuild=M(e.postBuild),!e.scheme&&d.scheme&&(e.scheme=d.scheme);let T={...je(d,f.envPrefix),...je(I,`${f.envPrefix}PROFILE_`)};s={...s,...l,...T},process.env.IOS_P12_PASSWORD&&!s.IOS_P12_PASSWORD&&(s.IOS_P12_PASSWORD=process.env.IOS_P12_PASSWORD),process.env.MATCH_PASSWORD&&!s.MATCH_PASSWORD&&(s.MATCH_PASSWORD=process.env.MATCH_PASSWORD),e.platform==="ios"&&(!e.iosTeamId&&I.ios?.appleTeamId&&(e.iosTeamId=I.ios.appleTeamId),!e.iosTeamId&&d.submit?.[y]?.ios?.appleTeamId&&(e.iosTeamId=d.submit[y].ios.appleTeamId),!e.iosTeamId&&d.submit?.production?.ios?.appleTeamId&&(D.warn(v.yellow(`Check: Using 'production' Team ID for '${y}' build.`)),e.iosTeamId=d.submit.production.ios.appleTeamId),e.iosTeamId?D.info(v.magenta(`\u2713 Injected iOS Team ID from config: ${e.iosTeamId}`)):D.warn(v.yellow("\u26A0\uFE0F No iOS Team ID found. Signing might fail if not managed automatically via Expo.")))}let u="unknown";try{u=wi("git rev-parse --abbrev-ref HEAD").toString().trim()}catch{D.warn("Failed to detect git branch.")}let p="1.0.0";try{ce.existsSync("./package.json")&&(p=JSON.parse(ce.readFileSync("./package.json","utf-8")).version||"1.0.0")}catch{}let g=e.buildProfile||"production",m="Internal";e.developmentClient?m="DevelopmentClient":g.toLowerCase().includes("store")||g.toLowerCase()==="production"?m="Store":g.toLowerCase().includes("preview")||g.toLowerCase().includes("staging")?m="Staging":(g.toLowerCase().includes("development")||g.toLowerCase().includes("dev"))&&(m="Development");let h=e.platform==="ios"?"iOS":"Android",$=e.platform==="ios"&&e.simulator?" (Simulator)":"",N=`${h}${$} v${p} (${m})`;if(i){try{let y=e.buildProfile||"production";D.info(v.blue(`Fetching managed secrets for profile: ${y}...`));let w=e.environment||y,b=(await _.get(`/projects/${i}/secrets/export?env=${w}`)).data;b.status==="success"&&b.secrets&&(s={...s,...b.secrets},Object.keys(b.secrets).length>0&&D.info(v.magenta(`\u2713 Injected ${Object.keys(b.secrets).length} secrets from Dashboard.`)))}catch(y){D.warn(`Failed to load managed secrets from Dashboard: ${y.message}`)}try{D.info(v.blue("Fetching managed credentials..."));let y="development";e.distribution==="store"?y="store":e.distribution==="internal"&&(y=e.platform==="ios"?"adhoc":"internal"),m==="Staging"&&e.developmentClient&&(y="development");let w=await _.get("/credentials/resolve",{params:{projectId:i,platform:e.platform,bundleId:e.iosBundleIdentifier||e.androidPackage,distributionType:y}});if(w.data.status==="success"&&w.data.credentials){let I=w.data.credentials;D.info(v.magenta(`\u2713 Found ${I.length} relevant credentials.`));let b=I.filter(T=>{if(T.distributionType){let L=y==="internal"?"adhoc":y;return T.distributionType===L||T.distributionType===y}return!0});D.info(v.dim(` Filtered to ${b.length} credentials for distributionType: ${y}`));let O=!1,G=!1,M=!1;for(let T of b)if(T.downloadUrl)try{let L="",Q=5;for(;Q>0;)try{let K=await tt.get(T.downloadUrl,{responseType:"arraybuffer",timeout:3e4,headers:{Connection:"close"}});L=Buffer.from(K.data).toString("base64");break}catch(K){if(Q--,Q===0)throw K;D.warn(v.dim(` - Temporary network error downloading ${T.name}. Retrying... (${5-Q}/5)`)),await new Promise(j=>setTimeout(j,2e3))}if(T.type==="ios_cert"&&!O)s.IOS_DIST_P12=L,T.password?(s.IOS_P12_PASSWORD=T.password,D.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12 with password from credential record`))):D.info(v.dim(` - Injected ${T.name} as IOS_DIST_P12`)),O=!0;else if(T.type==="ios_profile"&&!G)s.IOS_PROVISIONING_PROFILE=L,D.info(v.dim(` - Injected ${T.name} as IOS_PROVISIONING_PROFILE`)),G=!0;else if(T.type==="android_keystore"&&!M){s.ANDROID_KEYSTORE_BASE64=L;let K=T.password,j=T.alias||T.meta?.alias;if(K)s.ANDROID_KEY_PASSWORD=K,s.ANDROID_STORE_PASSWORD=K,D.info(v.dim(" - Injected keystore password from credential record"));else{let Ae=["ANDROID_KEY_PASSWORD",...[y==="store"?"PRODUCTION":y==="internal"?"STAGING":"DEVELOPMENT",y.toUpperCase(),"PRODUCTION","STORE","INTERNAL","STAGING","RELEASE","DEBUG"].map(k=>`KEYSTORE_PASSWORD_${k}`),"KEYSTORE_PASSWORD"].find(k=>!!s[k]);Ae&&s[Ae]&&(s.ANDROID_KEY_PASSWORD=s[Ae],s.ANDROID_STORE_PASSWORD=s[Ae])}if(j)s.ANDROID_KEY_ALIAS=j;else{let B=["ANDROID_KEY_ALIAS","KEYSTORE_ALIAS"].find(Se=>!!s[Se]);B&&(s.ANDROID_KEY_ALIAS=s[B])}D.info(v.dim(` - Injected ${T.name} as ANDROID_KEYSTORE_BASE64`)),M=!0}}catch(L){D.warn(`Failed to download credential ${T.name}: ${L.message}`)}}if(e.platform==="android"){let I=d.android?.versionCode==="auto"||d.expo?.android?.versionCode==="auto";if(e.autoVersion||I){n.start("Resolving latest versionCode from Google Play...");try{let b=(w.data.credentials||[]).find(K=>K.type==="google_service_account");if(b||(b=((await _.get(`/credentials/${i}`)).data.credentials||[]).find(j=>j.type==="google_service_account")),!b)throw new Error("Google Service Account not found. Upload it via Dashboard to use auto-versioning.");let O=await _.get(`/credentials/${b.credentialId}/download`,{params:{projectId:i}});if(O.data.status!=="success"||!O.data.downloadUrl)throw new Error("Failed to get secure download URL for service account");let M=(await tt.get(O.data.downloadUrl,{headers:{Connection:"close"}})).data,T=e.androidPackage||d.android?.package||d.expo?.android?.package||d.name,L=await Ii(T,M);if(L==null)throw new Error("Could not retrieve any version information from Google Play.");let Q=L+1;s.ANDROID_VERSION_CODE=Q.toString(),n.stop(`\u2713 Resolved versionCode: ${v.green(Q)} (Latest on Play Store: ${L})`)}catch(b){n.stop("Version resolution failed");let O=b.response?.data?.error?.message||b.message;D.warn(v.yellow(` \u26A0\uFE0F Auto-versioning failed: ${O}`)),D.warn(v.dim(' Falling back to version code from config. To fix: ensure Service Account has "View App Metadata" and "View App Information" permissions in Google Play Console.'))}}}if(e.platform==="ios"&&!e.simulator){let I=!!s.IOS_DIST_P12,b=!!s.IOS_PROVISIONING_PROFILE;if(!I||!b){let O=[...I?[]:["Distribution Certificate"],...b?[]:["Provisioning Profile"]].join(" and ");D.error(v.red(`Missing iOS credentials: ${O}`)),e.quiet&&process.exit(1);let G=e.yes||await _i({message:"Would you like to generate these credentials now?",initialValue:!0});if(G&&!Di(G))return await Je({platform:"ios",profile:g}),e.quiet||D.info(v.green("\u2713 Credentials setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials\` to set up signing credentials manually.`)),process.exit(1)}}if(e.platform==="android"&&(e.distribution==="internal"||e.distribution==="store")&&!(!!s.ANDROID_KEYSTORE_BASE64||!!s.ANDROID_KEYSTORE)){D.error(v.red("Missing Android credentials: Signing Keystore")),e.quiet&&process.exit(1);let b=e.yes||await _i({message:"Would you like to automatically create and upload an Android Keystore for this profile now?",initialValue:!0});if(b&&!Di(b))return await Je({platform:"android",profile:g}),e.quiet||D.info(v.green("\u2713 Android Keystore setup complete! Restarting build phase...")),At(e);e.quiet||D.info(v.yellow(`Run \`${f.nameLower} credentials --platform android\` to set up a signing keystore manually.`)),process.exit(1)}}catch(y){D.warn(`Failed to resolve credentials: ${y.message}`)}}let C=!!(e.local&&e.buildId),x=!!(e.local||e.sshHost),H=!x&&!C;if(C){D.info(v.magenta("\u{1F3D7}\uFE0F Runner Mode: Executing isolated build task..."));let y=await Ht({...e,interactive:!1},t,s,i,{branch:u,version:p,summary:N,buildType:m});await X(y),process.exit(0)}async function X(y){if(i&&y.length>0){let w=Gt(),I=[];e.quiet||w.start("Uploading artifacts to Dashboard...");try{for(let b of y){let O=we.basename(b),G=ce.readFileSync(b),M=we.extname(O).toLowerCase(),T="application/octet-stream",L=await _.post(`/builds/${i}/${t}/artifact-upload-url`,{fileName:O,fileType:T});if(L.data.status!=="success")throw new Error(`Failed to get upload URL for ${O}`);let Q=!1;for(let K=1;K<=3;K++)try{await tt.put(L.data.uploadUrl,G,{headers:{"Content-Type":T},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),Q=!0;break}catch(j){if(D.warn(v.yellow(`Artifact upload attempt ${K}/3 failed (${j.code||j.message})`)),K<3)await new Promise(B=>setTimeout(B,3e3*K));else throw j}Q&&I.push({name:O,url:L.data.downloadUrl,size:G.length,type:M.substring(1)})}e.quiet||w.stop("Artifacts uploaded.")}catch(b){e.quiet||w.stop("Failed to upload artifacts."),D.error(v.red(`Upload error: ${b.message}`));try{await _.patch(`/builds/${i}/${t}`,{status:"completed",artifacts:y.map(O=>we.basename(O)),endTime:Date.now()})}catch(O){D.warn(v.yellow(`Could not set fallback build status: ${O.message}`))}return}if(i&&I.length>0)try{D.info(v.cyan(`
|
|
791
|
+
\u{1F517} Download Links:`));for(let b of I)D.info(v.dim(` - ${b.name}: `)+v.blue.underline(b.url));await _.patch(`/builds/${i}/${t}`,{status:"success",artifacts:I,endTime:Date.now()}),D.success(v.green(`
|
|
790
792
|
\u2713 Build completed and reported to dashboard.`))}catch(b){D.warn(v.yellow(`
|
|
791
|
-
\u26A0\uFE0F Could not report to dashboard: ${b.message}`))}}else if(i)try{await
|
|
793
|
+
\u26A0\uFE0F Could not report to dashboard: ${b.message}`))}}else if(i)try{await _.patch(`/builds/${i}/${t}`,{status:"completed",endTime:Date.now()})}catch{}}if(x){if(D.info(v.cyan(`\u{1F680} Direct Build Mode: Executing on ${e.sshHost||"local"}...`)),i&&!r){let y=process.argv.slice(3).join(" ");await _.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"building",branch:u,version:p,summary:N,startTime:o,buildType:m,buildProfile:g,buildArgs:y,simulator:!!e.simulator})}if(e.sshHost&&e.platform==="ios"){let y=await Ei(e,t,s,i)}else{let y=await Ht({...e,interactive:!!e.local},t,s,i,{branch:u,version:p,summary:N,buildType:m});await X(y)}return}if(H&&(D.info(v.blue("\u{1F6F0}\uFE0F Cloud Initiator Mode: Preparing orchestration...")),!e.dryRun)){e.quiet||n.start("Zipping and uploading local source...");let y=await _.post("/builds/source-upload-url",{projectId:i,buildId:t});if(y.data.status!=="success")throw n.stop("Failed to get upload URL."),new Error("Failed to get source upload URL from API");let w=new vi,I=ce.readdirSync("."),b=["node_modules",".git","dist","build","builds",".gradle",".idea","android/build","ios/build","ios/Pods",`.${f.nameLower}_cli`];for(let M of I){if(b.includes(M))continue;ce.statSync(M).isDirectory()?w.addLocalFolder(M,M):w.addLocalFile(M)}let O=w.toBuffer();e.quiet||n.message(`Uploading source (${(O.length/1024/1024).toFixed(1)} MB)...`);let G=!1;for(let M=1;M<=3;M++)try{await tt.put(y.data.uploadUrl,O,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0,timeout:12e4}),G=!0;break}catch(T){if(M<3)n.message(`Upload attempt ${M} failed (${T.code||T.message}), retrying...`),await new Promise(L=>setTimeout(L,2e3*M));else throw T}if(e.quiet||n.stop("Source uploaded"),i){let M=process.argv.slice(3).join(" ");await _.post("/builds",{projectId:i,buildId:t,platform:e.platform,status:"pending",branch:u,version:p,summary:N,startTime:o,buildType:m,buildProfile:g,buildArgs:M,simulator:!!e.simulator}),D.info(v.green("\u2713 Cloud build registered."))}e.platform==="android"&&await Si(e,t,s,i),e.quiet||D.info(v.cyan("\u{1F4E1} Connecting to build stream...")),await yo(i,t,e);return}}catch(c){let s=c.message||"Build failed";c.response?.data?.message?s=c.response.data.message:c.message.includes("status code 402")?s="Insufficient wallet balance. Please add credits in the Dashboard.":c.message.includes("status code 403")&&(s="Monthly build quota exceeded. Upgrade your plan in the Dashboard."),i&&!e.local&&await a(s),D.error(v.red(`\u2717 Build failed: ${s}`)),process.exit(1)}};async function yo(e,n,t){let i=Gt(),o="pending",r=0,a=0;for(t.quiet||i.start("Connecting to build stream...");;){try{let s=(await _.get(`/builds/${e}/${n}`)).data.build;if(s){if(o=s.status,o==="building")t.quiet||i.message("Building on M4 Mac Mini...");else if(o==="failed")t.quiet||i.stop("Build failed."),D.error(v.red(`
|
|
792
794
|
\u2717 Build failed: ${s.error||"Unknown error"}`)),process.exit(1);else if(o==="completed"||o==="success"){t.quiet||i.stop("Build successful!"),D.success(v.green(`
|
|
793
795
|
\u2713 Build completed successfully!`));try{t.quiet||(D.info(v.magenta(`
|
|
794
|
-
\u{1F4F1} Installation Hub:`)),D.info(v.dim(" - View & Install Build: ")+v.white.underline(`${ai}/build/${n}`)))}catch{}return}else if(o!=="pending"){t.quiet||i.stop(`Build status: ${o}`);return}}try{let d=(await
|
|
796
|
+
\u{1F4F1} Installation Hub:`)),D.info(v.dim(" - View & Install Build: ")+v.white.underline(`${ai}/build/${n}`)))}catch{}return}else if(o!=="pending"){t.quiet||i.stop(`Build status: ${o}`);return}}try{let d=(await _.get(`/builds/${e}/${n}/logs`)).data;if(d&&typeof d=="string"&&!t.quiet){let u=d.split(`
|
|
795
797
|
`);if(u.length>r){for(let p=r;p<u.length;p++)u[p].trim()&&console.log(v.dim(` ${u[p]}`));r=u.length}}}catch{}a=0}catch{a++,a>10&&(i.stop("Connection lost."),D.error(v.red(`
|
|
796
|
-
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(c=>setTimeout(c,3e3))}}import So from"http";import{execSync as Et}from"child_process";import
|
|
798
|
+
\u2717 Lost connection to Dashboard API.`)),process.exit(1))}await new Promise(c=>setTimeout(c,3e3))}}import So from"http";import{execSync as Et}from"child_process";import jt from"chalk";import{log as Be}from"@clack/prompts";var It=7070;function Ao(){let e=[];try{let n=Et("adb devices -l",{stdio:"pipe"}).toString(),t=new Set;n.split(`
|
|
797
799
|
`).forEach(i=>{if(i.includes("List of devices")||!i.trim())return;let o=i.split(/\s+/);if(o.length<2||o[1]!=="device")return;let r=o[0];t.add(r);let a=i.match(/model:([^\s]+)/);e.push({id:r,platform:"android",type:r.startsWith("emulator-")?"emulator":"physical",name:a?a[1].replace(/_/g," "):r,status:"online",details:i.trim()})})}catch{}try{let n=`${process.env.ANDROID_HOME||`${process.env.HOME}/Library/Android/sdk`}/emulator/emulator`,i=Et(`${n} -list-avds`,{stdio:"pipe"}).toString().split(`
|
|
798
|
-
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=Et("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=Et("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ri(){process.platform!=="darwin"&&je.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=So.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${It}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=Ao();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(It,"127.0.0.1",()=>{je.success(Bt.green(`Local device agent running on http://localhost:${It}`)),je.info(Bt.dim("Keep this running while using the Install Hub on the dashboard.")),je.info(Bt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?je.error(`Port ${It} is already in use \u2014 agent may already be running.`):je.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Zr}from"module";import{text as Io,password as bo,spinner as Po,isCancel as Ti}from"@clack/prompts";import zt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var jt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(jt,"config.json");function Vt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(jt)||it.mkdirSync(jt,{recursive:!0});let t={...Vt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=Vt(),n=await Io({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ti(n))return;let t=await bo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ti(t))return;let i=Po();i.start("Authenticating...");try{let r=await(await fetch(`${gt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(ri({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Ci({lastLoginEmail:n}),i.stop(zt.green("Login successful!"))):i.stop(zt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(zt.red("Network error: "+o.message))}}import{outro as $o,select as _o,spinner as Do,isCancel as wo}from"@clack/prompts";import bt from"chalk";import Wt from"fs";import vo from"path";async function ki(){if(!ue()){console.log(bt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=Do();n.start("Fetching projects...");try{let{data:t}=await $.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log(bt.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await _o({message:"Select a project to link:",options:i});if(wo(o))return;let r=vo.join(process.cwd(),f.configFileName),a={};if(Wt.existsSync(r))try{a=JSON.parse(Wt.readFileSync(r,"utf-8"))}catch{}let c=t.projects.find(u=>u.projectId===o),s=a.android?.package||Oe("android"),l=a.ios?.bundleIdentifier||Oe("ios"),d={projectId:o,name:c?.name,slug:c?.slug,scheme:c?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:l||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:a.submit?.production?.android||{track:"internal"},ios:{ascAppId:a.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:a.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};Wt.writeFileSync(r,JSON.stringify(d,null,2)),$o(bt.green(`Linked to project ${d.name} (${d.slug})`))}catch(t){n.stop(bt.red("Error fetching projects: "+t.message))}}import{outro as Ro,text as Pt,select as Oo,spinner as Co,isCancel as nt}from"@clack/prompts";import ot from"chalk";import To from"fs";import No from"path";import{randomUUID as ko}from"crypto";async function xi(){if(!ue()){console.log(ot.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await Pt({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await Pt({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(c){if(c.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(c))return"Slug must be lowercase alphanumeric with dashes."}});if(nt(t))return;let i=await Oo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nt(i))return;let o="";if(i==="android"||i==="all"){let c=Oe("android");if(o=await Pt({message:"Android Package Name:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),nt(o))return}let r="";if(i==="ios"||i==="all"){let c=Oe("ios");if(r=await Pt({message:"iOS Bundle Identifier:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),nt(r))return}let a=Co();a.start("Creating project...");try{let c=ko(),l={projectId:c,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await $.post("/projects",l);if(d.status==="success"){a.stop(ot.green("Project created successfully!"));let u=No.join(process.cwd(),f.configFileName);To.writeFileSync(u,JSON.stringify({projectId:c,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),Ro(ot.green(`Initialized project ${n} and linked locally!`))}else a.stop(ot.red("creation failed: "+d.message))}catch(c){a.stop(ot.red("Network error: "+c.message))}}import{spinner as Ui,log as me}from"@clack/prompts";import $t from"chalk";import Li from"fs";import xo from"path";async function Mi(e,n){let t=ue();if(!t){me.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=xo.join(process.cwd(),f.configFileName);if(!Li.existsSync(i)){me.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Li.readFileSync(i,"utf-8"))}catch{me.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){me.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Lo(r,n,t):e==="list"?await Uo(r,t):me.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Lo(e,n,t){if(n.length===0){me.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Ui();i.start("Setting environment variables...");let o=0,r=0;for(let a of n){let[c,...s]=a.split("="),l=s.join("=");if(!c||l===void 0){me.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:c.trim(),value:l,type:"env",environment:"global",visibility:"secret"},{data:u}=await $.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(me.error(`Failed to set ${c}: ${u.message}`),r++)}catch(d){me.error(`Network error setting ${c}: ${d.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Uo(e,n){let t=Ui();t.start("Fetching environment variables...");try{let{data:i}=await $.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?me.info("No environment variables found for this project."):(me.info($t.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${$t.cyan(r.key)} = ${a} ${$t.gray(`[${r.environment}]`)}`)}))}else t.stop($t.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),me.error(`Network error: ${i.message}`)}}import{spinner as st,text as rt,select as qt,isCancel as ke,cancel as Jt}from"@clack/prompts";import ie from"chalk";import le from"fs";import Ke from"path";import{spawn as Mo,spawnSync as Fo}from"child_process";import Hi from"axios";import Xt from"os";import Ho from"crypto";async function Gi(e){let n=st(),t=ue(),i=`./${f.configFileName}`;if(!le.existsSync(i)){ge(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(le.readFileSync(i,"utf-8")),{projectId:r}=o;if(!r){ge(`${f.configFileName} is missing projectId.`);return}ve(ie.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=await qt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ke(h)){Jt("Operation cancelled");return}a=h}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ie.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await $.get(`/credentials/${r}`)).data.credentials||[]).filter(O=>a==="ios"?O.type==="asc_api_key":O.type==="google_service_account");if(N.length===0){n.stop("Credentials missing"),ge(`No Service Credentials found for ${a}.`),ve(`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(N.length===1)s=N[0],n.stop(`Using: ${s.name}`);else{n.stop("Multiple credentials found");let O=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(L=>({value:L.credentialId,label:L.name,hint:`${L.keyId?`ID: ${L.keyId}`:""} ${L.issuerId?`(Issuer: ${L.issuerId.substring(0,8)}...)`:""}`}))});if(ke(O)){Jt("Submission cancelled");return}s=N.find(L=>L.credentialId===O),ve(`Using selected: ${ie.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ge(`API Error: ${h.message} `);return}let l=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-submit-`)),d=s.keyId||s.meta?.keyId,u=s.issuerId||s.meta?.issuerId,p=s.type==="asc_api_key"?`AuthKey_${d}.p8`:"service-account.json",g=Ke.join(l,p);n.start("Downloading secure key...");try{let h=await $.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let P=await Hi.get(h.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(g,Buffer.from(P.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ge(`Failed to download key: ${h.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ie.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let m=a==="android"?e.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!d){let N=await rt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:O=>O.length>0?void 0:"Key ID is required"});if(ke(N))return;d=N}if(!u||u==="undefined"){let N=await rt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:O=>O.length>0?void 0:"Issuer ID is required"});if(ke(N))return;u=N}ve(`Using ASC Key ID: ${d}`),ve(`Using ASC Issuer ID: ${u}`);let h=o.ios?.bundleIdentifier,P=await Bo(c,g,u,d,h);if(P&&P.apiKeyJsonPath)throw ve(ie.cyan(`
|
|
799
|
-
[DIAGNOSTIC] API key written to: ${
|
|
800
|
-
`)),new Error("fastlane pilot execution failed");Fi(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else{let h=o.android?.package||s.bundleId;await
|
|
800
|
+
`).filter(r=>!!r.trim()),o=e.some(r=>r.platform==="android"&&r.id.startsWith("emulator-"));i.forEach(r=>{o||e.push({id:r,platform:"android",type:"emulator",name:r.replace(/_/g," "),status:"offline",details:`Android Virtual Device: ${r}`})})}catch{}if(process.platform!=="darwin")return e;try{let n=Et("/usr/bin/xcrun simctl list devices --json",{stdio:"pipe"}).toString(),t=JSON.parse(n);Object.entries(t.devices).forEach(([i,o])=>{o.forEach(r=>{r.isAvailable&&e.push({id:r.udid,platform:"ios",type:"simulator",name:r.name,status:r.state?.toLowerCase()==="booted"?"online":"offline",runtime:i,details:`${r.name} (${i})`})})})}catch{}try{let n=Et("/usr/bin/xcrun devicectl list devices --json-output -",{stdio:"pipe"}).toString();(JSON.parse(n).result?.devices||[]).forEach(i=>{let o=i.connectionProperties?.transportType;(o==="wired"||o==="localNetwork")&&e.push({id:i.identifier,platform:"ios",type:"physical",name:i.deviceProperties?.name||"iPhone",status:"online",details:`${i.deviceProperties?.name||"iPhone"} (${i.model?.name||i.hardwareModel||""}) - ${o}`})})}catch{}return e}async function Ri(){process.platform!=="darwin"&&Be.warn("Running on non-macOS \u2014 iOS discovery unavailable, Android only.");let e=So.createServer((n,t)=>{if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){t.writeHead(204),t.end();return}let i=new URL(n.url||"/",`http://localhost:${It}`);if(n.method==="GET"&&i.pathname==="/local/devices"){try{let o=Ao();t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"success",targets:o}))}catch(o){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"error",message:o.message}))}return}t.writeHead(404),t.end()});e.listen(It,"127.0.0.1",()=>{Be.success(jt.green(`Local device agent running on http://localhost:${It}`)),Be.info(jt.dim("Keep this running while using the Install Hub on the dashboard.")),Be.info(jt.dim("Press Ctrl+C to stop."))}),e.on("error",n=>{n.code==="EADDRINUSE"?Be.error(`Port ${It} is already in use \u2014 agent may already be running.`):Be.error(`Agent error: ${n.message}`),process.exit(1)}),await new Promise(()=>{})}import{createRequire as Zr}from"module";import{text as Io,password as bo,spinner as $o,isCancel as Ti}from"@clack/prompts";import zt from"chalk";import it from"fs";import Oi from"path";import Eo from"os";var Bt=Oi.join(Eo.homedir(),f.configDir),Kt=Oi.join(Bt,"config.json");function Vt(){if(!it.existsSync(Kt))return{};try{return JSON.parse(it.readFileSync(Kt,"utf-8"))}catch{return{}}}function Ci(e){it.existsSync(Bt)||it.mkdirSync(Bt,{recursive:!0});let t={...Vt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=Vt(),n=await Io({message:"Enter your email:",placeholder:"user@example.com",initialValue:e.lastLoginEmail,validate(o){if(o.length===0)return"Email is required!"}});if(Ti(n))return;let t=await bo({message:"Enter your password:",validate(o){if(o.length===0)return"Password is required!"}});if(Ti(t))return;let i=$o();i.start("Authenticating...");try{let r=await(await fetch(`${gt}/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:n,password:t})})).json();r.status==="success"&&r.user.token?(ri({id:r.user.id,email:n,token:r.user.token,refreshToken:r.user.refreshToken}),Ci({lastLoginEmail:n}),i.stop(zt.green("Login successful!"))):i.stop(zt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(zt.red("Network error: "+o.message))}}import{outro as Po,select as _o,spinner as Do,isCancel as wo}from"@clack/prompts";import bt from"chalk";import Wt from"fs";import vo from"path";async function ki(){if(!ue()){console.log(bt.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=Do();n.start("Fetching projects...");try{let{data:t}=await _.get("/projects");if(n.stop("Projects loaded."),t.status!=="success"||!t.projects||t.projects.length===0){console.log(bt.yellow(`No projects found. Run \`${f.nameLower} init\` to create one.`));return}let i=t.projects.map(u=>({value:u.projectId,label:`${u.name} (${u.slug})`})),o=await _o({message:"Select a project to link:",options:i});if(wo(o))return;let r=vo.join(process.cwd(),f.configFileName),a={};if(Wt.existsSync(r))try{a=JSON.parse(Wt.readFileSync(r,"utf-8"))}catch{}let c=t.projects.find(u=>u.projectId===o),s=a.android?.package||Oe("android"),l=a.ios?.bundleIdentifier||Oe("ios"),d={projectId:o,name:c?.name,slug:c?.slug,scheme:c?.slug?.toLowerCase()||"app",android:{package:s||""},ios:{bundleIdentifier:l||""},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:a.submit?.production?.android||{track:"internal"},ios:{ascAppId:a.submit?.production?.ios?.ascAppId||"1234567890",appleTeamId:a.submit?.production?.ios?.appleTeamId||"ABC123DEFG"}}}};Wt.writeFileSync(r,JSON.stringify(d,null,2)),Po(bt.green(`Linked to project ${d.name} (${d.slug})`))}catch(t){n.stop(bt.red("Error fetching projects: "+t.message))}}import{outro as Ro,text as $t,select as Oo,spinner as Co,isCancel as nt}from"@clack/prompts";import ot from"chalk";import To from"fs";import No from"path";import{randomUUID as ko}from"crypto";async function xi(){if(!ue()){console.log(ot.red(`You are not logged in. Run \`${f.nameLower} login\` first.`));return}let n=await $t({message:"Project Name:",placeholder:"My Awesome App",validate(c){if(c.length===0)return"Name is required!"}});if(nt(n))return;let t=await $t({message:"Project Slug (URL friendly):",placeholder:"my-awesome-app",validate(c){if(c.length===0)return"Slug is required!";if(!/^[a-z0-9-]+$/.test(c))return"Slug must be lowercase alphanumeric with dashes."}});if(nt(t))return;let i=await Oo({message:"Platform:",options:[{value:"android",label:"Android"},{value:"ios",label:"iOS"},{value:"web",label:"Web"},{value:"all",label:"All Platforms"}]});if(nt(i))return;let o="";if(i==="android"||i==="all"){let c=Oe("android");if(o=await $t({message:"Android Package Name:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Package name is required for Android!"}}),nt(o))return}let r="";if(i==="ios"||i==="all"){let c=Oe("ios");if(r=await $t({message:"iOS Bundle Identifier:",initialValue:c||"",placeholder:"com.example.app",validate(s){if(s.length===0)return"Bundle ID is required for iOS!"}}),nt(r))return}let a=Co();a.start("Creating project...");try{let c=ko(),l={projectId:c,name:n,slug:t,storageType:"managed",platforms:i==="all"?["android","ios","web"]:[i]},{data:d}=await _.post("/projects",l);if(d.status==="success"){a.stop(ot.green("Project created successfully!"));let u=No.join(process.cwd(),f.configFileName);To.writeFileSync(u,JSON.stringify({projectId:c,name:n,slug:t,...o?{android:{package:o}}:{},...r?{ios:{bundleIdentifier:r}}:{},build:{development:{environment:"development",distribution:"internal"},staging:{environment:"staging",distribution:"internal"},production:{environment:"production",distribution:"store"}},submit:{production:{android:{track:"internal"},ios:{ascAppId:"1234567890",appleTeamId:"ABC123DEFG",...r?{bundleId:r}:{}}}}},null,2)),Ro(ot.green(`Initialized project ${n} and linked locally!`))}else a.stop(ot.red("creation failed: "+d.message))}catch(c){a.stop(ot.red("Network error: "+c.message))}}import{spinner as Ui,log as me}from"@clack/prompts";import Pt from"chalk";import Li from"fs";import xo from"path";async function Mi(e,n){let t=ue();if(!t){me.error(`You are not logged in. Run \`${f.nameLower} login\` first.`);return}let i=xo.join(process.cwd(),f.configFileName);if(!Li.existsSync(i)){me.error(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o;try{o=JSON.parse(Li.readFileSync(i,"utf-8"))}catch{me.error(`Failed to parse ${f.configFileName}`);return}let{projectId:r}=o;if(!r){me.error(`${f.configFileName} is missing projectId.`);return}e==="set"?await Lo(r,n,t):e==="list"?await Uo(r,t):me.error(`Unknown env action: ${e}. Use 'set' or 'list'.`)}async function Lo(e,n,t){if(n.length===0){me.error(`Usage: ${f.nameLower} env set KEY=VALUE [KEY2=VALUE2 ...]`);return}let i=Ui();i.start("Setting environment variables...");let o=0,r=0;for(let a of n){let[c,...s]=a.split("="),l=s.join("=");if(!c||l===void 0){me.warn(`Invalid format for argument: ${a}. Expected KEY=VALUE.`),r++;continue}try{let d={key:c.trim(),value:l,type:"env",environment:"global",visibility:"secret"},{data:u}=await _.post(`/projects/${e}/secrets`,d);u.status==="success"?o++:(me.error(`Failed to set ${c}: ${u.message}`),r++)}catch(d){me.error(`Network error setting ${c}: ${d.message}`),r++}}i.stop(`Set ${o} variable(s). ${r>0?`${r} failed.`:""}`)}async function Uo(e,n){let t=Ui();t.start("Fetching environment variables...");try{let{data:i}=await _.get(`/projects/${e}/secrets`);if(i.status==="success"){t.stop("Fetched variables.");let o=i.secrets||[];o.length===0?me.info("No environment variables found for this project."):(me.info(Pt.bold("Environment Variables (Global & Scoped):")),o.forEach(r=>{let a=r.visibility==="plain"?r.value:"********";console.log(` ${Pt.cyan(r.key)} = ${a} ${Pt.gray(`[${r.environment}]`)}`)}))}else t.stop(Pt.red(`Failed to fetch variables: ${i.message}`))}catch(i){t.stop("Failed to fetch variables."),me.error(`Network error: ${i.message}`)}}import{spinner as st,text as rt,select as qt,isCancel as ke,cancel as Jt}from"@clack/prompts";import ne from"chalk";import le from"fs";import Ke from"path";import{spawn as Mo,spawnSync as Fo}from"child_process";import Hi from"axios";import Xt from"os";import Ho from"crypto";async function Gi(e){let n=st(),t=ue(),i=`./${f.configFileName}`;if(!le.existsSync(i)){ge(`No ${f.configFileName} found. Run \`${f.nameLower} init\` or \`${f.nameLower} link\` first.`);return}let o=JSON.parse(le.readFileSync(i,"utf-8")),{projectId:r}=o;if(!r){ge(`${f.configFileName} is missing projectId.`);return}ve(ne.dim(`Submit for project: ${o.name||r} `));let a=e.platform;if(!a){let h=await qt({message:"Select platform to submit:",options:[{value:"ios",label:"iOS (App Store Connect / TestFlight)"},{value:"android",label:"Android (Google Play Console)"}]});if(ke(h)){Jt("Operation cancelled");return}a=h}let c=await Go(r,a,e,t?.token);if(!c)return;ve(`Using artifact: ${ne.green(Ke.basename(c))} `),n.start("Fetching submission credentials from Dashboard...");let s;try{let N=((await _.get(`/credentials/${r}`)).data.credentials||[]).filter(C=>a==="ios"?C.type==="asc_api_key":C.type==="google_service_account");if(N.length===0){n.stop("Credentials missing"),ge(`No Service Credentials found for ${a}.`),ve(`Use '${f.nameLower} credentials:service --platform ${a}' or use the Dashboard to upload them.`);return}if(N.length===1)s=N[0],n.stop(`Using: ${s.name}`);else{n.stop("Multiple credentials found");let C=await qt({message:`Choose a ${a==="ios"?"App Store Connect":"Google Play"} credential:`,options:N.map(x=>({value:x.credentialId,label:x.name,hint:`${x.keyId?`ID: ${x.keyId}`:""} ${x.issuerId?`(Issuer: ${x.issuerId.substring(0,8)}...)`:""}`}))});if(ke(C)){Jt("Submission cancelled");return}s=N.find(x=>x.credentialId===C),ve(`Using selected: ${ne.green(s.name)}`)}}catch(h){n.stop("Failed to fetch credentials"),ge(`API Error: ${h.message} `);return}let l=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-submit-`)),d=s.keyId||s.meta?.keyId,u=s.issuerId||s.meta?.issuerId,p=s.type==="asc_api_key"?`AuthKey_${d}.p8`:"service-account.json",g=Ke.join(l,p);n.start("Downloading secure key...");try{let h=await _.get(`/credentials/${s.credentialId}/download`,{params:{projectId:r}});if(h.data.status!=="success"||!h.data.downloadUrl)throw new Error("Failed to get secure download URL");let $=await Hi.get(h.data.downloadUrl,{responseType:"arraybuffer"});le.writeFileSync(g,Buffer.from($.data)),n.stop("Key downloaded to secure temp storage")}catch(h){n.stop("Download failed"),ge(`Failed to download key: ${h.message}`);try{le.rmSync(l,{recursive:!0,force:!0})}catch{}return}ve(ne.blue(`Initiating ${a==="ios"?"TestFlight":"Google Play"} submission...`));let m=a==="android"?e.track||o.submit?.production?.android?.track||"internal":void 0;try{if(a==="ios"){if(!d){let N=await rt({message:"Enter App Store Connect Key ID (e.g. 2X948D...):",validate:C=>C.length>0?void 0:"Key ID is required"});if(ke(N))return;d=N}if(!u||u==="undefined"){let N=await rt({message:"Enter App Store Connect Issuer ID (Found on ASC Keys page):",validate:C=>C.length>0?void 0:"Issuer ID is required"});if(ke(N))return;u=N}ve(`Using ASC Key ID: ${d}`),ve(`Using ASC Issuer ID: ${u}`);let h=o.ios?.bundleIdentifier,$=await jo(c,g,u,d,h);if($&&$.apiKeyJsonPath)throw ve(ne.cyan(`
|
|
801
|
+
[DIAGNOSTIC] API key written to: ${$.apiKeyJsonPath}
|
|
802
|
+
`)),new Error("fastlane pilot execution failed");Fi(`${a==="ios"?"App Store":"Google Play"} submission successful!`)}else{let h=o.android?.package||s.bundleId;await Bo(c,g,m,h),Fi("Google Play submission successful!")}}catch(h){ge(`Submission failed: ${h.message}`)}finally{Ko(l),c.includes(`${f.nameLower}-artifact-`)}}async function Go(e,n,t,i){let o=t.buildId?"id":t.latest?"latest":null;if(!o&&(o=await qt({message:"Select artifact source:",options:[{value:"latest",label:`Latest Production Build (${f.name})`},{value:"id",label:`Input Build ID (${f.name})`},{value:"url",label:"Remote URL"},{value:"local",label:"Local File Path"}]}),ke(o)))return Jt("Operation cancelled"),null;if(o==="local"){let a=await rt({message:"Enter path to artifact (.ipa/.aab):",validate:c=>{if(!le.existsSync(c))return"File not found";if(n==="ios"&&!c.endsWith(".ipa"))return"Must be an .ipa file";if(n==="android"&&!c.endsWith(".aab"))return"Must be an .aab file"}});return ke(a)?null:a}let r=st();if(o==="latest"){r.start("Fetching latest build...");try{let a=await _.get(`/builds/${e}`,{params:{limit:50}});if(a.data.status!=="success")throw new Error(a.data.message);let c=a.data.builds||[],s=c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success"&&m.buildType?.toLowerCase()==="store")||c.find(m=>m.platform?.toLowerCase()===n.toLowerCase()&&m.status?.toLowerCase()==="success");if(!s)return r.stop("No suitable build found"),ge("No successful builds found for this platform."),null;r.stop(`Found build: ${s.buildId}`);let l=s.artifacts||[];if(l.length===0||l.every(m=>!(m.url||m.downloadUrl)))try{let m=await _.get(`/builds/${e}/${s.buildId}/artifacts`);m.data.status==="success"&&m.data.artifacts?.length>0?(l=m.data.artifacts.map(h=>({...h,url:h.url||h.downloadUrl})),console.log(ne.cyan(` [RECOVERY] Fetched ${l.length} artifact(s) with download URLs.`))):console.log(ne.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(m){console.log(ne.red(` [RECOVERY] /artifacts fetch failed: ${m.message}`))}let u=n==="ios",p=l.find(m=>{let h=(m.type||"").toLowerCase(),$=(m.name||"").toLowerCase();if(console.log(ne.dim(` - Checking: ${m.name} (Type: ${m.type}, HasLink: ${!!(m.url||m.downloadUrl)})`)),h)return h===(u?"ipa":"aab");let N=u?".ipa":".aab",C=(m.url||m.downloadUrl||"").toLowerCase();return $.endsWith(N)||C.includes(N)});if(!p||!(p.url||p.downloadUrl))return ge("Build found but artifact URL is missing."),null;let g=p.url||p.downloadUrl;return await Yt(g,u?"ios":"android")}catch(a){return r.stop("Fetch failed"),ge(`API Error: ${a.message}`),null}}if(o==="id"){let a=t.buildId||await rt({message:"Enter Build ID:",validate:c=>c.length<5?"Invalid ID":void 0});if(ke(a))return null;r.start("Fetching build...");try{let c=await _.get(`/build/${a}`);if(c.data.status!=="success")throw new Error(c.data.message);let s=c.data.build;if(!s)throw new Error("Build not found");let l=n==="ios",d=s.artifacts?.find(u=>{if(u.type)return u.type===(l?"ipa":"aab");let p=l?".ipa":".aab";return u.name&&u.name.endsWith(p)||u.url&&u.url.includes(p)});return!d||!d.url?(r.stop("Missing artifact"),ge("Artifact URL not found on build record."),null):(r.stop(`Found build: ${s.buildId}`),await Yt(d.url,l?"ios":"android"))}catch(c){return r.stop("Fetch failed"),ge(c.message),null}}if(o==="url"){let a=await rt({message:"Enter Artifact URL:",validate:c=>c.startsWith("http")?void 0:"Must be a valid URL"});return ke(a)?null:await Yt(a,n)}return null}async function Yt(e,n,t=3){let i=st();i.start("Downloading artifact...");let o=le.mkdtempSync(Ke.join(Xt.tmpdir(),`${f.nameLower}-artifact-`)),r=`app.${n==="ios"?"ipa":"aab"}`,a=Ke.join(o,r);for(let c=1;c<=t;c++)try{c>1&&(i.message(`Downloading artifact (Retry ${c}/${t})...`),await new Promise(d=>setTimeout(d,2e3*c)));let s=le.createWriteStream(a),l=await Hi({url:e,method:"GET",responseType:"stream",timeout:6e4});return await new Promise((d,u)=>{l.data.pipe(s);let p=!1;l.data.on("error",g=>{p||(p=!0,s.close(),u(g))}),s.on("finish",()=>{p||d()}),s.on("error",g=>{p||(p=!0,u(g))})}),i.stop("Download complete"),a}catch(s){if(c===t)throw i.stop("Download failed"),s}throw new Error("Download failed after retries")}async function jo(e,n,t,i,o){let r=st();if(o&&ve(`Bundled ID: ${ne.green(o)}`),!t||!i)throw ge(`Missing credentials: issuerId=${t}, keyId=${i}. Check your Dashboard.`),new Error("Missing ASC API Key Metadata (IssuerID or KeyID)");let a=le.readFileSync(n,"utf8"),c;try{c=Ho.createPrivateKey(a).export({type:"pkcs8",format:"pem"})}catch{ve("Key normalization failed, falling back to manual re-wrapping..."),c=`-----BEGIN PRIVATE KEY-----
|
|
801
803
|
${(a.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
802
804
|
`)}
|
|
803
|
-
-----END PRIVATE KEY-----`}console.log(
|
|
804
|
-
[DIAGNOSTIC] Key ID: ${i}`)),console.log(
|
|
805
|
-
`)),r.start("Uploading to TestFlight (pilot)...");let s=Ke.join(Xt.tmpdir(),`api_key_${i}.json`),l={key_id:i,issuer_id:t,key:c,in_house:!1};le.writeFileSync(s,JSON.stringify(l,null,2));let d={...process.env};return new Promise((u,p)=>{let g=Mo("fastlane",["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:d});g.on("close",m=>{if(m!==0)r.stop("Pilot failed"),u({apiKeyJsonPath:s});else{r.stop("IPA uploaded to TestFlight");try{le.unlinkSync(s)}catch{}u({apiKeyJsonPath:null})}}),g.on("error",m=>{try{le.unlinkSync(s)}catch{}r.stop("Pilot execution error"),p(m)})})}async function
|
|
806
|
-
`).filter(o=>o.includes(" device")).map(o=>o.split(" ")[0]);if(n.length===0)throw new Error("No Android devices or emulators found.");let t=n[0];Qt.info(ei.dim(`Opening deep link on Android Device (${t})...`));let i=`adb -s ${t} shell am start -a android.intent.action.VIEW -d "${e}"`;at(i)}catch(n){throw new Error(`Failed to launch Android: ${n.message}`)}}var qi=async e=>{xe.info(ze.blue(`Starting ${f.name} Dev Orchestrator...`));let n=Ne(),t=e.buildProfile||"development",i=n?Ue(n,t):null,o={...process.env};if(n?.projectId)try{xe.info(ze.dim(`Fetching managed secrets for profile: ${t}...`));let m=await
|
|
805
|
+
-----END PRIVATE KEY-----`}console.log(ne.yellow(`
|
|
806
|
+
[DIAGNOSTIC] Key ID: ${i}`)),console.log(ne.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(ne.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${c.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(ne.yellow(`[DIAGNOSTIC] Key Checksum (End): ${c.substring(c.length-28).replace(/\n/g,"\\n")}
|
|
807
|
+
`)),r.start("Uploading to TestFlight (pilot)...");let s=Ke.join(Xt.tmpdir(),`api_key_${i}.json`),l={key_id:i,issuer_id:t,key:c,in_house:!1};le.writeFileSync(s,JSON.stringify(l,null,2));let d={...process.env};return new Promise((u,p)=>{let g=Mo("fastlane",["pilot","upload","--ipa",e,"--api_key_path",s,"--skip_submission","true","--skip_waiting_for_build_processing","true"],{stdio:"inherit",env:d});g.on("close",m=>{if(m!==0)r.stop("Pilot failed"),u({apiKeyJsonPath:s});else{r.stop("IPA uploaded to TestFlight");try{le.unlinkSync(s)}catch{}u({apiKeyJsonPath:null})}}),g.on("error",m=>{try{le.unlinkSync(s)}catch{}r.stop("Pilot execution error"),p(m)})})}async function Bo(e,n,t="internal",i){let o=st();o.start(`Uploading to Google Play ${t} track (supply)...`);let r=["supply","--aab",e,"--json_key",n,"--track",t];if(i&&i!=="*"&&r.push("--package_name",i),Fo("fastlane",r,{stdio:"inherit",env:process.env}).status!==0)throw o.stop("Supply failed"),new Error("fastlane supply execution failed");o.stop(`AAB uploaded to ${t} track`)}function Ko(e){try{le.existsSync(e)&&le.rmSync(e,{recursive:!0,force:!0})}catch{}}function ge(e){console.log(ne.red(`\u274C ${e}`))}function ve(e){console.log(ne.gray(`\u2022 ${e}`))}function Fi(e){console.log(ne.green(`\u2713 ${e}`))}import{spinner as Vo,log as Me,outro as zo}from"@clack/prompts";import Zt from"chalk";import ji from"fs";import Wo from"path";import{execSync as Yo}from"child_process";import qo from"adm-zip";import Jo from"axios";import{randomUUID as Xo}from"crypto";async function Bi(e){Me.info(Zt.magenta("\u{1F680} Starting Over-The-Air (OTA) Update via Mach..."));let n=Ne();(!n||!n.projectId)&&(Me.error(`No ${f.configFileName} found or missing projectId. Run \`mach link\` first.`),process.exit(1));let t=n.projectId,i=e.branch||"production",o="1.0.0";try{o=JSON.parse(ji.readFileSync("./package.json","utf-8")).version||"1.0.0"}catch{Me.warn("Could not read package.json version. Defaulting to 1.0.0")}let r=Vo();r.start(`Compiling JavaScript bundles for OTA (Channel: ${i}, Runtime: ${o})...`);try{Yo("npx expo export --platform all",{stdio:"ignore"})}catch(l){r.stop("Compilation failed."),Me.error(`Failed to export JS bundles using Expo: ${l.message}`),process.exit(1)}r.message("Zipping artifact payload...");let a=Wo.join(process.cwd(),"dist");ji.existsSync(a)||(r.stop("Missing dist folder."),Me.error("The `dist` directory was not created. Export failed."),process.exit(1));let c=new qo;c.addLocalFolder(a,"dist");let s=c.toBuffer();r.message("Uploading payload to Mach Cloud...");try{let l=Xo(),d=await _.post("/builds/source-upload-url",{projectId:t,buildId:l});if(d.data.status!=="success")throw new Error("Could not secure upload bucket URL");let{uploadUrl:u,key:p}=d.data;await Jo.put(u,s,{headers:{"Content-Type":"application/zip"},maxBodyLength:1/0,maxContentLength:1/0}),r.message(`Promoting Update to ${i}...`),await _.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"android",updateId:`${l}-android`,manifestKey:p}),await _.post("/updates/publish",{projectId:t,channelName:i,runtimeVersion:o,platform:"ios",updateId:`${l}-ios`,manifestKey:p}),r.stop("Update Live!"),zo(Zt.green(`\u2713 OTA Update natively shipped to the '${i}' channel.`)),Me.info(Zt.dim(`Any app running runtime '${o}' will download this bundle smoothly.`))}catch(l){r.stop("Update failed during Cloud Sync."),Me.error(`Upload error: ${l.message}`),process.exit(1)}}import{intro as Zo,outro as Ki,log as Ve}from"@clack/prompts";import Re from"chalk";async function Vi(){Zo(Re.blue(`${f.name} CLI - User Profile`));let e=ue();if(!e){Ve.warn(Re.yellow("You are not logged in.")),Ve.info(`Run \`${f.nameLower} login\` to authenticate.`),Ki();return}Ve.info(`${Re.bold("Logged in as:")} ${Re.green(e.email)}`);try{await _.get("/projects");let t=ue().token.split(".");if(t.length===3){let i=JSON.parse(Buffer.from(t[1],"base64").toString());if(i.exp){let o=new Date(i.exp*1e3),r=new Date,a=o.getTime()-r.getTime();if(a>0){let c=Math.round(a/6e4),s=(c/60).toFixed(1);Ve.info(`${Re.bold("Token status:")} Valid (Expires in ~${s}h / ${c}m)`)}else Ve.warn(`${Re.bold("Token status:")} ${Re.red("Expired")} (Auto-refresh failed)`)}}}catch{Ve.warn(`${Re.bold("Token status:")} ${Re.red("Unreachable")} (Session might be truly expired)${gt}`)}Ki(Re.blue("---"))}import{spawn as ir}from"child_process";import{log as xe}from"@clack/prompts";import ze from"chalk";import nr from"fs";import Qo from"net";async function er(e){return new Promise(n=>{let t=Qo.createServer();t.once("error",i=>{i.code==="EADDRINUSE"?n(!0):n(!1)}),t.once("listening",()=>{t.close(),n(!1)}),t.listen(e,"0.0.0.0")})}async function zi(e,n=20){let t=e;for(;t<e+n;){if(!await er(t))return t;t++}throw new Error(`Could not find an available port after ${n} attempts starting from ${e}.`)}import{execSync as at}from"child_process";import{log as Qt}from"@clack/prompts";import ei from"chalk";async function Wi(e){return e.platform==="ios"?Yi(e.url):tr(e.url)}async function Yi(e){try{let n=at("xcrun simctl list devices booted --json").toString(),t=JSON.parse(n),i=null;for(let o in t.devices){let r=t.devices[o].find(a=>a.state==="Booted");if(r){i=r.udid;break}}if(!i)return Qt.info(ei.dim("No booted simulator found. Launching default simulator...")),at("open -a Simulator"),await new Promise(o=>setTimeout(o,3e3)),Yi(e);Qt.info(ei.dim(`Opening deep link on iOS Simulator (${i})...`)),at(`xcrun simctl openurl ${i} "${e}"`)}catch(n){throw new Error(`Failed to launch iOS Simulator: ${n.message}`)}}async function tr(e){try{let n=at("adb devices").toString().split(`
|
|
808
|
+
`).filter(o=>o.includes(" device")).map(o=>o.split(" ")[0]);if(n.length===0)throw new Error("No Android devices or emulators found.");let t=n[0];Qt.info(ei.dim(`Opening deep link on Android Device (${t})...`));let i=`adb -s ${t} shell am start -a android.intent.action.VIEW -d "${e}"`;at(i)}catch(n){throw new Error(`Failed to launch Android: ${n.message}`)}}var qi=async e=>{xe.info(ze.blue(`Starting ${f.name} Dev Orchestrator...`));let n=Ne(),t=e.buildProfile||"development",i=n?Ue(n,t):null,o={...process.env};if(n?.projectId)try{xe.info(ze.dim(`Fetching managed secrets for profile: ${t}...`));let m=await _.get(`/projects/${n.projectId}/secrets/export?env=${t}`);m.data?.status==="success"&&m.data.secrets&&(Object.assign(o,m.data.secrets),xe.info(ze.magenta(`\u2713 Injected secrets from ${f.name} Dashboard.`)))}catch{xe.warn("Could not fetch managed secrets. Running with local env only.")}n&&Object.assign(o,je(n,f.envPrefix)),i&&(Object.assign(o,je(i,`${f.envPrefix}PROFILE_`)),i.env&&Object.assign(o,i.env));let r=!1;try{let m=JSON.parse(nr.readFileSync("package.json","utf-8"));r=!!(m.dependencies?.expo||m.devDependencies?.expo)}catch{xe.warn("Could not parse package.json. Defaulting to Bare React Native mode.")}let a=Number(e.port||i?.port||8081),c=await zi(a);c!==a&&xe.info(ze.yellow(`Port ${a} is busy. ${f.name} is using ${c} instead.`));let s="npx",l=[];r?(l=["expo","start","--port",String(c)],e.clear&&l.push("--clear"),e.tunnel&&l.push("--tunnel"),e.lan&&l.push("--lan"),e.localhost&&l.push("--localhost")):(l=["react-native","start","--port",String(c)],e.clear&&l.push("--clear"));let d=ir(s,l,{stdio:["inherit","pipe","pipe"],shell:!0,env:o}),u=!1,p="127.0.0.1",g=m=>{let h=m.toString(),$=h.match(/http:\/\/(.+):(\d+)/);if($&&!u&&(p=$[1],u=!0,e.ios||e.android)){let N=e.ios?"ios":"android",x=`exp+${n?.scheme||f.nameLower}://expo-development-client/?url=http%3A%2F%2F${p}%3A${c}`;xe.info(ze.magenta(`\u{1F680} ${f.name} is launching ${n?.name||"app"} on ${N==="ios"?"iOS":"Android"}...`)),Wi({platform:N,url:x}).catch(H=>xe.error(ze.red(`Launch failed: ${H.message}`)))}return h.includes("Starting project")||h.includes("Using src/app")||h.includes("Starting Metro Bundler")||h.includes("Opening exp+")||h.includes("Input is required")?null:h};return d.stdout?.on("data",m=>{let h=g(m);h&&process.stdout.write(h)}),d.stderr?.on("data",m=>{let h=g(m);h&&process.stderr.write(h)}),new Promise((m,h)=>{d.on("exit",$=>{$===0?m():h(new Error(`Dev server exited with code ${$}`))}),d.on("error",$=>{h($)})})};import{log as pe}from"@clack/prompts";import Ie from"chalk";var Ji=async e=>{let n=Ne();n||(pe.error(Ie.red(`No ${f.configFileName} found in the current directory.`)),process.exit(1));let t=e.profile||"development",i=Ue(n,t);if(e.json){console.log(JSON.stringify({project:n,resolved:i},null,2));return}pe.info(Ie.bgBlue.white(` Resolved ${f.name} Config [${t}] `)),pe.info(Ie.dim("----------------------------------------")),pe.info(`${Ie.blue("Project ID:")} ${n.projectId}`),pe.info(`${Ie.blue("Name:")} ${n.name}`),pe.info(`${Ie.blue("Scheme:")} ${n.scheme}`),i?(pe.info(Ie.dim(`
|
|
807
809
|
Profile Settings:`)),pe.info(`${Ie.cyan("Distribution:")} ${i.distribution||"none"}`),pe.info(`${Ie.cyan("Development Client:")} ${i.developmentClient||"false"}`),i.env&&Object.keys(i.env).length>0&&(pe.info(Ie.dim(`
|
|
808
|
-
Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{pe.info(` ${o}=${r}`)}))):pe.warn(`Profile '${t}' not found.`),pe.info(Ie.dim("----------------------------------------"))};import{log as be,spinner as dt,text as Xi,select as Zi,confirm as or,isCancel as ct,cancel as lt,outro as ut,note as rr}from"@clack/prompts";import
|
|
810
|
+
Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{pe.info(` ${o}=${r}`)}))):pe.warn(`Profile '${t}' not found.`),pe.info(Ie.dim("----------------------------------------"))};import{log as be,spinner as dt,text as Xi,select as Zi,confirm as or,isCancel as ct,cancel as lt,outro as ut,note as rr}from"@clack/prompts";import z from"chalk";import{execSync as sr}from"child_process";async function ar(){try{let e=sr("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[]}}async function cr(e){let n=e.udid,t=e.name,i="";if(!n){let r=dt();r.start("Scanning for connected iOS devices...");let a=await ar();if(r.stop(a.length>0?`Found ${a.length} device(s)`:"No devices detected"),a.length===1)n=a[0].udid,t=t||a[0].name,i=a[0].model,be.info(`Detected: ${z.bold(t)} (${z.dim(n.substring(0,12)+"...")})`);else if(a.length>1){let c=await Zi({message:"Select a device to register:",options:a.map(l=>({value:l.udid,label:`${l.name} (${l.model})`,hint:l.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c;let s=a.find(l=>l.udid===n);t=t||s.name,i=s.model}else{be.info(z.dim("No connected devices found. Enter UDID manually."));let c=await Xi({message:"Device UDID:",placeholder:"00008101-XXXXXXXXXXXX",validate(s){if(s.length<10)return"UDID seems too short"}});if(ct(c)){lt("Cancelled");return}n=c}}if(!t){let r=await Xi({message:"Device name:",placeholder:"Nitesh's iPhone",validate(a){if(a.length===0)return"Name is required"}});if(ct(r)){lt("Cancelled");return}t=r}let o=dt();o.start("Registering device...");try{await _.post("/devices",{udid:n,name:t,platform:"ios",model:i||void 0,addedVia:"cli"}),o.stop(z.green("Device registered!")),be.info(` ${z.bold("Name:")} ${t}`),be.info(` ${z.bold("UDID:")} ${z.dim(n)}`)}catch(r){o.stop(z.red("Failed to register device")),be.error(r.response?.data?.message||r.message)}ut(z.blue("---"))}async function lr(){let e=dt();e.start("Fetching registered devices...");try{let t=(await _.get("/devices")).data.devices||[];if(e.stop(`${t.length} device(s) registered`),t.length===0){be.info(z.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),ut(z.blue("---"));return}let i=t.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${z.bold(o.name.padEnd(24))} ${z.dim(o.udid.padEnd(28))} ${z.cyan(o.addedVia.padEnd(10))} ${z.dim(r)}`});rr(` ${z.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
809
811
|
`+i.join(`
|
|
810
|
-
`),"Registered Devices")}catch(n){e.stop(
|
|
811
|
-
`),l=Dt.relative(e,a);for(let d=0;d<s.length;d++){let u=s[d];if(!Sr(u)&&!Ar(u))for(let{id:p,pattern:g,severity:m,label:h}of gr)g.lastIndex=0,g.test(u)&&t.push({id:p,title:h,description:`Potential ${h.toLowerCase()} found in source code`,severity:m,category:"secrets",file:l,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:t,durationMs:0}}import{execSync as Er}from"child_process";var Ir={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function on(e,n){let t=[],i=1,o;try{o=Er("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(c){if(o=c.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let a=r.vulnerabilities||{};for(let[c,s]of Object.entries(a)){let l=Ir[s.severity]||"info",d=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);t.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${c} \u2014 ${s.severity}`,description:`Via: ${d}. Range: ${s.range||"unknown"}`,severity:l,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${c} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:t,durationMs:0}}import wt from"fs";import vt from"path";var br=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,rn=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g
|
|
812
|
+
`),"Registered Devices")}catch(n){e.stop(z.red("Failed to fetch devices")),be.error(n.response?.data?.message||n.message)}ut(z.blue("---"))}async function dr(e){let n=e.udid;if(!n){let o=dt();o.start("Fetching registered devices...");try{let a=(await _.get("/devices")).data.devices||[];if(o.stop(`${a.length} device(s) found`),a.length===0){be.info(z.dim("No devices to remove.")),ut(z.blue("---"));return}let c=await Zi({message:"Select device to remove:",options:a.map(s=>({value:s.udid,label:s.name,hint:s.udid.substring(0,12)+"..."}))});if(ct(c)){lt("Cancelled");return}n=c}catch(r){o.stop(z.red("Failed to fetch devices")),be.error(r.response?.data?.message||r.message);return}}let t=await or({message:`Remove device ${z.dim(n.substring(0,12)+"...")}?`});if(ct(t)||!t){lt("Cancelled");return}let i=dt();i.start("Removing device...");try{await _.delete(`/devices/${encodeURIComponent(n)}`),i.stop(z.green("Device removed"))}catch(o){i.stop(z.red("Failed to remove device")),be.error(o.response?.data?.message||o.message)}ut(z.blue("---"))}async function _t(e,n){switch(e){case"register":await cr(n);break;case"list":await lr();break;case"remove":await dr(n);break;default:be.error(`Unknown action: ${e}`)}}import{log as ye,spinner as vn}from"@clack/prompts";import Pe from"chalk";import xt from"path";import mt from"fs";import Kr from"os";import Vr from"axios";var he=(r=>(r.CRITICAL="critical",r.HIGH="high",r.MEDIUM="medium",r.LOW="low",r.INFO="info",r))(he||{}),$e=(s=>(s.PERMISSIONS="permissions",s.SECRETS="secrets",s.DEPENDENCIES="dependencies",s.STORAGE="storage",s.NETWORK="network",s.DEBUG="debug",s.MANIFEST="manifest",s.ATS="ats",s))($e||{});import{spinner as Sn,log as ft}from"@clack/prompts";import fe from"chalk";import{execSync as kr}from"child_process";import An from"fs";import En from"path";import Le from"fs";import pt from"path";import{execSync as ur}from"child_process";var Qi={"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"}},pr={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 fr(e){try{let t=ur("npx expo config --type introspect --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e4});return JSON.parse(t)}catch{}let n=pt.join(e,"app.json");if(Le.existsSync(n))try{let t=JSON.parse(Le.readFileSync(n,"utf-8"));return t.expo||t}catch{}return null}function mr(e){let n=[],t=pt.join(e,"node_modules");if(!Le.existsSync(t))return n;let i=/<uses-permission\s+android:name="([^"]+)"/g;function o(r,a){let c=pt.join(r,"android","src","main","AndroidManifest.xml");if(!Le.existsSync(c))return;let s=Le.readFileSync(c,"utf-8"),l;for(;(l=i.exec(s))!==null;)n.push({pkg:a,permission:l[1]});i.lastIndex=0}for(let r of Le.readdirSync(t)){if(r.startsWith("."))continue;let a=pt.join(t,r);if(r.startsWith("@")){if(!Le.statSync(a).isDirectory())continue;for(let c of Le.readdirSync(a))o(pt.join(a,c),`${r}/${c}`)}else o(a,r)}return n}async function en(e,n){let t=[],i=1,o=fr(e),r=o?.android?.permissions||[],a=o?.android?.blockedPermissions||[];for(let l of r){let d=Qi[l];d&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${l.split(".").pop()} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:"Remove from permissions if not needed, or add justification."})}let c=mr(e);for(let{pkg:l,permission:d}of c){let u=Qi[d];u&&(a.includes(d)||r.includes(d)||t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`${d.split(".").pop()} injected by ${l}`,description:`${u.description}. Auto-injected via ${l} AndroidManifest.xml`,severity:u.severity,category:"permissions",file:`node_modules/${l}/android/src/main/AndroidManifest.xml`,recommendation:`Add "${d}" to blockedPermissions if not needed.`,autoFixable:!0}))}let s=o?.ios?.infoPlist||{};for(let[l,d]of Object.entries(pr))l in s&&t.push({id:`PERM-${String(i++).padStart(3,"0")}`,title:`iOS: ${l} declared`,description:d.description,severity:d.severity,category:"permissions",file:"app.config.ts",recommendation:`Remove ${l} from infoPlist if the app does not use this capability.`});return{category:"permissions",label:"Permission Audit",findings:t,durationMs:0}}import ti from"fs";import Dt from"path";var gr=[{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"}],hr=new Set([".ts",".tsx",".js",".jsx"]),yr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function tn(e){let n=[],t=ti.readdirSync(e,{withFileTypes:!0});for(let i of t){if(yr.has(i.name))continue;let o=Dt.join(e,i.name);i.isDirectory()?n.push(...tn(o)):hr.has(Dt.extname(i.name))&&n.push(o)}return n}function Sr(e){let n=e.trim();return n.startsWith("//")||n.startsWith("*")||n.startsWith("/*")}function Ar(e){return/process\.env\./i.test(e)||/import\.meta\.env/i.test(e)}async function nn(e,n){let t=[],i=Dt.join(e,"src"),o=ti.existsSync(i)?i:e,r=tn(o);for(let a of r){let s=ti.readFileSync(a,"utf-8").split(`
|
|
813
|
+
`),l=Dt.relative(e,a);for(let d=0;d<s.length;d++){let u=s[d];if(!Sr(u)&&!Ar(u))for(let{id:p,pattern:g,severity:m,label:h}of gr)g.lastIndex=0,g.test(u)&&t.push({id:p,title:h,description:`Potential ${h.toLowerCase()} found in source code`,severity:m,category:"secrets",file:l,line:d+1,recommendation:`Move to environment variables or a secrets manager. Use \`${f.nameLower} env set\` for managed secrets.`})}}return{category:"secrets",label:"Secrets Detection",findings:t,durationMs:0}}import{execSync as Er}from"child_process";var Ir={critical:"critical",high:"high",moderate:"medium",low:"low",info:"info"};async function on(e,n){let t=[],i=1,o;try{o=Er("npm audit --json 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:6e4})}catch(c){if(o=c.stdout||"",!o)return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to run npm audit. Ensure npm is available and dependencies are installed."}}let r;try{r=JSON.parse(o)}catch{return{category:"dependencies",label:"Dependency CVEs",findings:[],durationMs:0,error:"Failed to parse npm audit output."}}let a=r.vulnerabilities||{};for(let[c,s]of Object.entries(a)){let l=Ir[s.severity]||"info",d=Array.isArray(s.via)?s.via.map(u=>typeof u=="string"?u:u.title||u.name).join(", "):String(s.via);t.push({id:`DEP-${String(i++).padStart(3,"0")}`,title:`${c} \u2014 ${s.severity}`,description:`Via: ${d}. Range: ${s.range||"unknown"}`,severity:l,category:"dependencies",recommendation:s.fixAvailable?`Run \`npm audit fix\` or update ${c} to a patched version.`:"No fix available yet. Monitor for updates or evaluate alternatives.",autoFixable:!!s.fixAvailable})}return{category:"dependencies",label:"Dependency CVEs",findings:t,durationMs:0}}import wt from"fs";import vt from"path";var br=/(?:token|password|credential|secret|apiKey|api_key|session|auth|jwt|refresh_token|access_token|private_key|pin|otp)/i,rn=/AsyncStorage\s*\.\s*(?:setItem|mergeItem)\s*\(\s*['"`]([^'"`]+)['"`]/g,$r=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,Pr=new Set([".ts",".tsx",".js",".jsx"]),_r=new Set(["node_modules",".expo",".git","android","ios","dist","build"]);function sn(e){let n=[];if(!wt.existsSync(e))return n;let t=wt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(_r.has(i.name))continue;let o=vt.join(e,i.name);i.isDirectory()?n.push(...sn(o)):Pr.has(vt.extname(i.name))&&n.push(o)}return n}async function an(e,n){let t=[],i=1,o=vt.join(e,"src"),r=wt.existsSync(o)?o:e,a=sn(r);for(let c of a){let s=wt.readFileSync(c,"utf-8");if(!$r.test(s))continue;let l=s.split(`
|
|
812
814
|
`),d=vt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u];rn.lastIndex=0;let g;for(;(g=rn.exec(p))!==null;){let m=g[1];br.test(m)&&t.push({id:`STOR-${String(i++).padStart(3,"0")}`,title:`AsyncStorage used for "${m}"`,description:`Sensitive data key "${m}" stored in AsyncStorage (unencrypted).`,severity:"high",category:"storage",file:d,line:u+1,recommendation:"Use expo-secure-store (SecureStore) for sensitive data instead of AsyncStorage."})}}}return{category:"storage",label:"Insecure Storage",findings:t,durationMs:0}}import Rt from"fs";import Ot from"path";var cn=/['"`](http:\/\/(?!localhost|127\.0\.0\.1|10\.|192\.168\.|0\.0\.0\.0|172\.(?:1[6-9]|2\d|3[01])\.)[^'"`\s]+)['"`]/g,Dr=/\/api\/|\/v[0-9]+\/|\/graphql|\/rest\//i,wr=new Set([".ts",".tsx",".js",".jsx"]),vr=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function ln(e){let n=[];if(!Rt.existsSync(e))return n;let t=Rt.readdirSync(e,{withFileTypes:!0});for(let i of t){if(vr.has(i.name))continue;let o=Ot.join(e,i.name);i.isDirectory()?n.push(...ln(o)):wr.has(Ot.extname(i.name))&&n.push(o)}return n}async function dn(e,n){let t=[],i=1,o=Ot.join(e,"src"),r=Rt.existsSync(o)?o:e,a=ln(r);for(let c of a){let l=Rt.readFileSync(c,"utf-8").split(`
|
|
813
|
-
`),d=Ot.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(g.startsWith("//")||g.startsWith("*"))continue;cn.lastIndex=0;let m;for(;(m=cn.exec(p))!==null;){let h=m[1]
|
|
815
|
+
`),d=Ot.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(g.startsWith("//")||g.startsWith("*"))continue;cn.lastIndex=0;let m;for(;(m=cn.exec(p))!==null;){let h=m[1],$=Dr.test(h);t.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${$?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${h}`,severity:$?"high":"medium",category:"network",file:d,line:u+1,recommendation:"Use HTTPS instead of HTTP for all network requests."})}}}return{category:"network",label:"HTTP URLs",findings:t,durationMs:0}}import Ct from"fs";import Tt from"path";var un=/(?:debug|debugMode|devMode|enableDebug)\s*[:=]\s*true/gi,pn=/console\.(?:log|warn|info|debug)\s*\([^)]*(?:token|password|secret|credential|key|auth)/gi,Rr=new Set([".ts",".tsx",".js",".jsx"]),Or=new Set(["node_modules",".expo",".git","android","ios","dist","build","__tests__","__mocks__"]);function fn(e){let n=[];if(!Ct.existsSync(e))return n;let t=Ct.readdirSync(e,{withFileTypes:!0});for(let i of t){if(Or.has(i.name))continue;let o=Tt.join(e,i.name);i.isDirectory()?n.push(...fn(o)):Rr.has(Tt.extname(i.name))&&n.push(o)}return n}async function mn(e,n){let t=[],i=1,o=Tt.join(e,"src"),r=Ct.existsSync(o)?o:e,a=fn(r);for(let c of a){let l=Ct.readFileSync(c,"utf-8").split(`
|
|
814
816
|
`),d=Tt.relative(e,c);for(let u=0;u<l.length;u++){let p=l[u],g=p.trim();if(!(g.startsWith("//")||g.startsWith("*"))&&(un.lastIndex=0,un.test(p)&&t.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:d,line:u+1,recommendation:"Use __DEV__ or environment variables instead of hardcoded debug flags."}),pn.lastIndex=0,pn.test(p))){let m=l.slice(Math.max(0,u-3),u).join(`
|
|
815
|
-
`);/__DEV__/.test(m)||t.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:d,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:t,durationMs:0}}import gn from"fs";import ii from"path";var Cr=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 Tr(e){let n=[ii.join(e,"android","app","src","main","AndroidManifest.xml"),ii.join(e,"android","AndroidManifest.xml")];for(let t of n)if(gn.existsSync(t))return t;return null}async function hn(e,n){let t=[],i=1,o=Tr(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=gn.readFileSync(o,"utf-8"),a=ii.relative(e,o),c=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=c.exec(r))!==null;){let l=s[1],d=s[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Cr.has(p))continue;let g=/android:exported="true"/.test(d),m=/android:permission="/.test(d);g&&!m&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${l}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:a,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&t.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:a,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&t.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:a,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:t,durationMs:0}}import Nt from"fs";import ni from"path";function Nr(e){let n=ni.join(e,"ios");if(!Nt.existsSync(n))return null;let t=Nt.readdirSync(n,{withFileTypes:!0});for(let i of t){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let o=ni.join(n,i.name,"Info.plist");if(Nt.existsSync(o))return o}return null}async function yn(e,n){let t=[],i=1,o=Nr(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=Nt.readFileSync(o,"utf-8"),a=ni.relative(e,o),c=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let s=c[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&t.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:a,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let l=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let d=l[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:a,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:t,durationMs:0}}var xr=[{category:"permissions",label:"Permission Audit",fn:en,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:nn,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:on,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:an,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:dn,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:mn,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:hn,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:yn,requiresPrebuild:!0}];async function In(e,n){let t=xr;n.category&&(t=t.filter(a=>a.category===n.category),t.length===0&&(ft.error(fe.red(`Unknown category: ${n.category}`)),ft.info(fe.dim(`Available: ${Object.values(
|
|
817
|
+
`);/__DEV__/.test(m)||t.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:d,line:u+1,recommendation:"Wrap in __DEV__ check or remove sensitive data from console output."})}}}return{category:"debug",label:"Debug/Dev Flags",findings:t,durationMs:0}}import gn from"fs";import ii from"path";var Cr=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 Tr(e){let n=[ii.join(e,"android","app","src","main","AndroidManifest.xml"),ii.join(e,"android","AndroidManifest.xml")];for(let t of n)if(gn.existsSync(t))return t;return null}async function hn(e,n){let t=[],i=1,o=Tr(e);if(!o)return{category:"manifest",label:"Android Manifest",findings:[],durationMs:0,error:"No AndroidManifest.xml found. Run with --prebuild or run `expo prebuild` first."};let r=gn.readFileSync(o,"utf-8"),a=ii.relative(e,o),c=/<(activity|service|receiver|provider)\s+([^>]*?)(?:\/>|>)/gs,s;for(;(s=c.exec(r))!==null;){let l=s[1],d=s[2],p=d.match(/android:name="([^"]+)"/)?.[1]||"unknown";if(Cr.has(p))continue;let g=/android:exported="true"/.test(d),m=/android:permission="/.test(d);g&&!m&&t.push({id:`MAN-${String(i++).padStart(3,"0")}`,title:`Exported ${l}: ${p.split(".").pop()}`,description:`${p} is exported=true without android:permission protection`,severity:"medium",category:"manifest",file:a,recommendation:'Set android:exported="false" or add an android:permission attribute.'})}return/android:allowBackup="true"/.test(r)&&t.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:a,recommendation:'Set android:allowBackup="false" via expo-build-properties plugin.',autoFixable:!0}),/android:debuggable="true"/.test(r)&&t.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:a,recommendation:"Ensure debuggable is false for production builds. This is usually set automatically for release builds."}),{category:"manifest",label:"Android Manifest",findings:t,durationMs:0}}import Nt from"fs";import ni from"path";function Nr(e){let n=ni.join(e,"ios");if(!Nt.existsSync(n))return null;let t=Nt.readdirSync(n,{withFileTypes:!0});for(let i of t){if(!i.isDirectory()||i.name==="Pods"||i.name.startsWith("."))continue;let o=ni.join(n,i.name,"Info.plist");if(Nt.existsSync(o))return o}return null}async function yn(e,n){let t=[],i=1,o=Nr(e);if(!o)return{category:"ats",label:"iOS ATS Config",findings:[],durationMs:0,error:"No Info.plist found. Run with --prebuild or run `expo prebuild` first."};let r=Nt.readFileSync(o,"utf-8"),a=ni.relative(e,o),c=r.match(/<key>NSAppTransportSecurity<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(c){let s=c[1];/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(s)&&t.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:a,recommendation:"Remove NSAllowsArbitraryLoads or set to false. Use domain-specific exceptions only if absolutely necessary."});let l=s.match(/<key>NSExceptionDomains<\/key>\s*<dict>([\s\S]*?)<\/dict>/);if(l){let d=l[1].match(/<key>([^<]+)<\/key>/g);if(d)for(let u of d){let p=u.replace(/<\/?key>/g,"");p!=="NSExceptionDomains"&&t.push({id:`ATS-${String(i++).padStart(3,"0")}`,title:`ATS exception: ${p}`,description:`ATS exception configured for ${p}`,severity:"low",category:"ats",file:a,recommendation:`Verify that the ATS exception for ${p} is necessary. Use HTTPS where possible.`})}}}return{category:"ats",label:"iOS ATS Config",findings:t,durationMs:0}}var xr=[{category:"permissions",label:"Permission Audit",fn:en,requiresPrebuild:!1},{category:"secrets",label:"Secrets Detection",fn:nn,requiresPrebuild:!1},{category:"dependencies",label:"Dependency CVEs",fn:on,requiresPrebuild:!1},{category:"storage",label:"Insecure Storage",fn:an,requiresPrebuild:!1},{category:"network",label:"HTTP URLs",fn:dn,requiresPrebuild:!1},{category:"debug",label:"Debug/Dev Flags",fn:mn,requiresPrebuild:!1},{category:"manifest",label:"Android Manifest",fn:hn,requiresPrebuild:!0},{category:"ats",label:"iOS ATS Config",fn:yn,requiresPrebuild:!0}];async function In(e,n){let t=xr;n.category&&(t=t.filter(a=>a.category===n.category),t.length===0&&(ft.error(fe.red(`Unknown category: ${n.category}`)),ft.info(fe.dim(`Available: ${Object.values($e).join(", ")}`)),process.exit(1)));let i=t.filter(a=>!a.requiresPrebuild),o=t.filter(a=>a.requiresPrebuild),r=[];for(let a of i){let c=Sn();c.start(fe.dim(`Running ${a.label}...`));try{let s=Date.now(),l=await a.fn(e,n);l.durationMs=Date.now()-s,r.push(l);let d=l.findings.length;c.stop(d>0?fe.yellow(`${a.label} \u2014 ${d} finding(s)`):fe.green(`${a.label} \u2014 clean`))}catch(s){c.stop(fe.red(`${a.label} \u2014 error`)),r.push({category:a.category,label:a.label,findings:[],durationMs:0,error:s.message})}}if(o.length>0){let a=En.join(e,"android"),c=En.join(e,"ios"),s=An.existsSync(a)||An.existsSync(c);if(!s&&n.prebuild){n.json||ft.info(fe.dim(`
|
|
816
818
|
Running expo prebuild for deeper analysis...`));try{kr("npx expo prebuild --no-install",{cwd:e,stdio:"pipe"})}catch{return ft.warn(fe.yellow("Prebuild failed \u2014 skipping manifest/plist checks.")),r}}else if(!s)return n.json||ft.info(fe.dim(`
|
|
817
|
-
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let l of o){let d=Sn();d.start(fe.dim(`Running ${l.label}...`));try{let u=Date.now(),p=await l.fn(e,n);p.durationMs=Date.now()-u,r.push(p);let g=p.findings.length;d.stop(g>0?fe.yellow(`${l.label} \u2014 ${g} finding(s)`):fe.green(`${l.label} \u2014 clean`))}catch(u){d.stop(fe.red(`${l.label} \u2014 error`)),r.push({category:l.category,label:l.label,findings:[],durationMs:0,error:u.message})}}}return r}import
|
|
818
|
-
`)),a.length>0){
|
|
819
|
-
`));for(let s of a)Z.error(Y.red(`${Y.bold(s.name)} ${Y.dim(`(${s.arch})`)}`)),Z.info(Y.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${$n})`))}return c.length>0&&(console.log(""),Z.success(Y.green(`${c.length} librar${c.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(Z.success(Y.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(Z.error(Y.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),Z.info(Y.yellow("To fix this:")),Z.info(Y.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),Z.info(Y.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),Z.info(Y.dim(" 3. Update third-party libraries that ship prebuilt .so files")),Z.info(Y.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),Z.info(Y.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),Z.error(Y.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function Br(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(Gr))return null;let i=t[4]===2,o=t[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),a=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),c=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,l,d;i?(s=c(t,32),l=r(t,54),d=r(t,56)):(s=a(t,28),l=r(t,42),d=r(t,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(l);if(Ce.readSync(n,g,0,l,s+p*l),a(g,0)!==Hr)continue;let h;i?h=c(g,48):h=a(g,28),h>0&&(u===null||h<u)&&(u=h)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function Dn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Ye.join(e,i.name);i.isDirectory()?n.push(...Dn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function jr(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Rn=async e=>{if(ue()||(ye.error($e.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await zr(e);return}let t=process.cwd(),i=xt.join(t,"package.json");mt.existsSync(i)||(ye.error($e.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(mt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(ye.info($e.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),ye.info($e.dim(`Type: ${r?"Expo":"Bare React Native"}`)),ye.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},c=await In(t,a);e.json?console.log(JSON.stringify(Pn(c,o),null,2)):bn(c,e.severity);let s=c.some(d=>d.findings.some(u=>u.severity==="critical")),l=c.some(d=>d.findings.some(u=>u.severity==="high"));(s||l)&&process.exit(1)},wn=["16kb"];async function zr(e){let n=e.category?.toLowerCase();n&&!wn.includes(n)&&(ye.error($e.red(`Unknown APK check category: "${n}"`)),ye.info($e.dim(`Available APK checks: ${wn.join(", ")}`)),process.exit(1));let t=await Wr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await _n(t)||(o=!0)),o&&process.exit(1)}async function Wr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Yr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await On(e);let n=xt.resolve(e);return mt.existsSync(n)?n:(ye.error($e.red(`APK file not found: ${n}`)),null)}async function Yr(e){let n=vn();n.start(`Fetching APK from build ${e}...`);try{let t=await $.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),ye.error($e.red("This build does not have an APK artifact.")),ye.info($e.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await On(o.url))}catch(t){return n.stop("Failed to fetch build"),ye.error($e.red(t.message)),null}}async function On(e){let n=vn();n.start("Downloading APK...");try{let t=mt.mkdtempSync(xt.join(Kr.tmpdir(),`${f.nameLower}-audit-`)),i=xt.join(t,"app.apk"),o=await Vr.get(e,{responseType:"arraybuffer"});mt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),ye.error($e.red(`Failed to download APK: ${t.message}`)),null}}var Xr=console.log;console.log=()=>{};Jr();console.log=Xr;de(oe.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Qr=Zr(import.meta.url),es=Qr("../package.json"),z=new qr;z.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(es.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);z.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Ri()});z.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(oe.bgCyan.black(f.cliTag("Hosting"))),await di()});z.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=>{de(oe.bgCyan.black(f.cliTag("Sitemap Generator"))),await mi(e)});z.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Cn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Cn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=z.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||de(oe.bgCyan.black(f.cliTag("Cloud Build"))),await At(n)});z.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=>{de(oe.bgCyan.black(f.cliTag("OTA Update"))),await ji(e)});z.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("--track <track>","Google Play Track (internal, alpha, beta, production)","internal").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{de(oe.bgCyan.black(f.cliTag("Store Submission"))),await Gi(e)});z.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Login"))),await Ni()});z.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Link Project"))),await ki()});z.command("me").description("Display currently logged in user details").action(async()=>{await Vi()});z.command("init").description(`Create a new ${f.name} Project`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Init Project"))),await xi()});z.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{de(oe.bgCyan.black(f.cliTag("Env Manager"))),await Mi(e,n)});z.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=>{de(oe.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});z.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 Ji(e)});z.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:n}=await import("./credentials-WL7JKLF4.js");await n(e)});z.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=>{de(oe.bgCyan.black(f.cliTag("Credentials Setup"))),await Je(e),Tn(oe.green("Done!"))});z.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)").action(async e=>{de(oe.bgCyan.black(f.cliTag("Service Credentials"))),await ci(e),Tn(oe.green("Done!"))});var oi=z.command("device").description("Manage registered iOS test devices");oi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await _t("register",e)});oi.command("list").description("List all registered devices").action(async()=>{await _t("list",{})});oi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await _t("remove",e)});z.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=>{de(oe.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rn(e)});var ts=new Set(["login"]);z.hook("preAction",(e,n)=>{let t=n.name();ts.has(t)||si()});z.on("command:*",()=>{console.error(`Invalid command: %s
|
|
820
|
-
See --help for a list of available commands.`,
|
|
819
|
+
Skipping manifest/plist checks \u2014 no android/ios dirs. Use --prebuild to generate them.`)),r;for(let l of o){let d=Sn();d.start(fe.dim(`Running ${l.label}...`));try{let u=Date.now(),p=await l.fn(e,n);p.durationMs=Date.now()-u,r.push(p);let g=p.findings.length;d.stop(g>0?fe.yellow(`${l.label} \u2014 ${g} finding(s)`):fe.green(`${l.label} \u2014 clean`))}catch(u){d.stop(fe.red(`${l.label} \u2014 error`)),r.push({category:l.category,label:l.label,findings:[],durationMs:0,error:u.message})}}}return r}import ie from"chalk";import{log as ee}from"@clack/prompts";var We={critical:ie.bgRed.white.bold,high:ie.red.bold,medium:ie.yellow.bold,low:ie.blue,info:ie.dim},kt={critical:0,high:1,medium:2,low:3,info:4};function Lr(e,n){if(!n)return!0;let t=kt[n];return t===void 0?!0:kt[e]<=t}function bn(e,n){let t=0,i={critical:0,high:0,medium:0,low:0,info:0};for(let a of e){let c=a.findings.filter(l=>Lr(l.severity,n));if(c.length===0&&!a.error)continue;if(ee.info(""),ee.info(ie.bold(` ${a.label}`)+ie.dim(` ${c.length} finding(s)`)),ee.info(ie.dim(" "+"\u2500".repeat(60))),a.error){ee.error(ie.red(` Error: ${a.error}`));continue}let s=[...c].sort((l,d)=>kt[l.severity]-kt[d.severity]);for(let l of s){let d=We[l.severity](` ${l.severity.toUpperCase()} `);ee.info(` ${d} ${ie.bold(l.id)} ${l.title}`),ee.info(ie.dim(` ${l.description}`)),l.file&&ee.info(ie.dim(` File: ${l.file}${l.line?`:${l.line}`:""}`)),ee.info(ie.cyan(` Fix: ${l.recommendation}`)),ee.info(""),i[l.severity]++,t++}}ee.info(""),ee.info(ie.bold(" Summary")),ee.info(ie.dim(" "+"\u2500".repeat(60))),ee.info(` Total: ${ie.bold(String(t))} finding(s)`),ee.info(` ${We.critical(` ${i.critical} Critical `)} ${We.high(` ${i.high} High `)} ${We.medium(` ${i.medium} Medium `)} ${We.low(` ${i.low} Low `)} ${We.info(` ${i.info} Info `)}`);let o=i.critical>0,r=i.high>0;o||r?(ee.info(""),ee.error(ie.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):t>0?(ee.info(""),ee.warn(ie.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(ee.info(""),ee.success(ie.green.bold(" PASS \u2014 no issues found")))}function $n(e,n){let t=e.flatMap(o=>o.findings),i={};for(let o of Object.values(he))i[o]=t.filter(r=>r.severity===o).length;return{version:"1.0.0",timestamp:new Date().toISOString(),project:n.name||"unknown",projectVersion:n.version||"0.0.0",summary:{total:t.length,...i},passed:i.critical===0&&i.high===0,checks:e.map(o=>({category:o.category,label:o.label,findingCount:o.findings.length,durationMs:o.durationMs,error:o.error||null})),findings:t}}import{log as te,spinner as Ur}from"@clack/prompts";import J from"chalk";import Ce from"fs";import Mr from"os";import Ye from"path";import{execSync as Fr}from"child_process";var Pn=16384,Hr=1,Gr=Buffer.from([127,69,76,70]);async function _n(e){te.info(J.bold.underline("16KB Page Alignment Check")),console.log("");let n=Ye.resolve(e);if(!Ce.existsSync(n))return te.error(J.red(`APK file not found: ${n}`)),!1;if(!n.endsWith(".apk"))return te.error(J.red("The provided file is not an APK file.")),!1;let t=Ur();t.start("Extracting and analyzing native libraries...");let i=Ce.mkdtempSync(Ye.join(Mr.tmpdir(),"mach-16kb-"));try{try{Fr(`unzip -o -q "${n}" "lib/arm64-v8a/*.so" "lib/x86_64/*.so" -d "${i}" 2>/dev/null`,{encoding:"utf-8",maxBuffer:50*1024*1024})}catch{}let o=Dn(Ye.join(i,"lib"));if(o.length===0)return t.stop("Analysis complete."),te.info(J.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),te.info(J.dim("16KB alignment check only applies to arm64-v8a and x86_64 architectures.")),!0;let r=[];for(let s of o){let l=Ye.relative(i,s),d=Br(l),u=Ye.basename(s),p=jr(s);p!==null&&r.push({name:u,filePath:l,arch:d,align:p,compatible:p>=Pn})}if(t.stop("Analysis complete."),r.length===0)return te.info(J.yellow("No valid ELF shared libraries found.")),!0;let a=r.filter(s=>!s.compatible),c=r.filter(s=>s.compatible);if(te.info(J.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
|
|
820
|
+
`)),a.length>0){te.info(J.red.bold(`Incompatible libraries:
|
|
821
|
+
`));for(let s of a)te.error(J.red(`${J.bold(s.name)} ${J.dim(`(${s.arch})`)}`)),te.info(J.dim(` PT_LOAD alignment: 2**${Math.log2(s.align)} (${s.align} bytes, needs 2**14 = ${Pn})`))}return c.length>0&&(console.log(""),te.success(J.green(`${c.length} librar${c.length===1?"y":"ies"} correctly aligned (2**14 or higher).`))),console.log(""),a.length===0?(te.success(J.green.bold("ELF Verification Successful. APK is 16KB compatible.")),!0):(te.error(J.red.bold(`Found ${a.length} unaligned lib${a.length===1?"":"s"} (arm64-v8a/x86_64 libs need to be aligned).`)),console.log(""),te.info(J.yellow("To fix this:")),te.info(J.dim(" 1. Rebuild with NDK r28+ which defaults to 16KB page alignment")),te.info(J.dim(" 2. Or set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON in CMake")),te.info(J.dim(" 3. Update third-party libraries that ship prebuilt .so files")),te.info(J.dim(" 4. After rebuilding: zipalign -p -f -v 16 input.apk output.apk")),console.log(""),te.info(J.dim("Reference: https://developer.android.com/guide/practices/page-sizes")),!1)}catch(o){return t.stop("Analysis failed."),te.error(J.red(`Failed to analyze APK: ${o.message}`)),!1}finally{try{Ce.rmSync(i,{recursive:!0,force:!0})}catch{}}}function jr(e){let n=Ce.openSync(e,"r");try{let t=Buffer.alloc(64);if(Ce.readSync(n,t,0,64,0),!t.subarray(0,4).equals(Gr))return null;let i=t[4]===2,o=t[5]===1,r=(p,g)=>o?p.readUInt16LE(g):p.readUInt16BE(g),a=(p,g)=>o?p.readUInt32LE(g):p.readUInt32BE(g),c=(p,g)=>Number(o?p.readBigUInt64LE(g):p.readBigUInt64BE(g)),s,l,d;i?(s=c(t,32),l=r(t,54),d=r(t,56)):(s=a(t,28),l=r(t,42),d=r(t,44));let u=null;for(let p=0;p<d;p++){let g=Buffer.alloc(l);if(Ce.readSync(n,g,0,l,s+p*l),a(g,0)!==Hr)continue;let h;i?h=c(g,48):h=a(g,28),h>0&&(u===null||h<u)&&(u=h)}return u??0}catch{return null}finally{Ce.closeSync(n)}}function Dn(e){let n=[];if(!Ce.existsSync(e))return n;let t=Ce.readdirSync(e,{withFileTypes:!0});for(let i of t){let o=Ye.join(e,i.name);i.isDirectory()?n.push(...Dn(o)):i.name.endsWith(".so")&&n.push(o)}return n}function Br(e){return e.includes("arm64-v8a")?"arm64-v8a":e.includes("x86_64")?"x86_64":"unknown"}var Rn=async e=>{if(ue()||(ye.error(Pe.red(`You are not logged in. Run \`${f.nameLower} login\` first.`)),process.exit(1)),e.apk){await zr(e);return}let t=process.cwd(),i=xt.join(t,"package.json");mt.existsSync(i)||(ye.error(Pe.red("No package.json found. Run this command from a project root.")),process.exit(1));let o=JSON.parse(mt.readFileSync(i,"utf-8")),r=!!(o.dependencies?.expo||o.devDependencies?.expo);e.json||(ye.info(Pe.dim(`Project: ${o.name||"unknown"} v${o.version||"0.0.0"}`)),ye.info(Pe.dim(`Type: ${r?"Expo":"Bare React Native"}`)),ye.info(""));let a={json:e.json,fix:e.fix,category:e.category,severity:e.severity,prebuild:e.prebuild},c=await In(t,a);e.json?console.log(JSON.stringify($n(c,o),null,2)):bn(c,e.severity);let s=c.some(d=>d.findings.some(u=>u.severity==="critical")),l=c.some(d=>d.findings.some(u=>u.severity==="high"));(s||l)&&process.exit(1)},wn=["16kb"];async function zr(e){let n=e.category?.toLowerCase();n&&!wn.includes(n)&&(ye.error(Pe.red(`Unknown APK check category: "${n}"`)),ye.info(Pe.dim(`Available APK checks: ${wn.join(", ")}`)),process.exit(1));let t=await Wr(e.apk);t||process.exit(1);let i=!n,o=!1;(i||n==="16kb")&&(await _n(t)||(o=!0)),o&&process.exit(1)}async function Wr(e){if(e.startsWith("build:")){let t=e.slice(6);return await Yr(t)}if(e.startsWith("http://")||e.startsWith("https://"))return await On(e);let n=xt.resolve(e);return mt.existsSync(n)?n:(ye.error(Pe.red(`APK file not found: ${n}`)),null)}async function Yr(e){let n=vn();n.start(`Fetching APK from build ${e}...`);try{let t=await _.get(`/build/${e}`);if(t.data.status!=="success")throw new Error(t.data.message);let i=t.data.build;if(!i)throw new Error("Build not found");let o=i.artifacts?.find(r=>r.type?r.type==="apk":r.name?.endsWith(".apk")||r.url?.includes(".apk"));return!o||!o.url?(n.stop("No APK artifact found"),ye.error(Pe.red("This build does not have an APK artifact.")),ye.info(Pe.dim("Make sure the build produced an APK (not just an AAB).")),null):(n.stop(`Found build: ${i.buildId||e}`),await On(o.url))}catch(t){return n.stop("Failed to fetch build"),ye.error(Pe.red(t.message)),null}}async function On(e){let n=vn();n.start("Downloading APK...");try{let t=mt.mkdtempSync(xt.join(Kr.tmpdir(),`${f.nameLower}-audit-`)),i=xt.join(t,"app.apk"),o=await Vr.get(e,{responseType:"arraybuffer"});mt.writeFileSync(i,o.data);let r=(o.data.length/(1024*1024)).toFixed(1);return n.stop(`Downloaded APK (${r} MB)`),i}catch(t){return n.stop("Download failed"),ye.error(Pe.red(`Failed to download APK: ${t.message}`)),null}}var Xr=console.log;console.log=()=>{};Jr();console.log=Xr;de(re.bgCyan.black(f.cliTag("Production Build Orchestrator")));var Qr=Zr(import.meta.url),es=Qr("../package.json"),W=new qr;W.name(f.nameLower).description(`${f.name} CLI: Powerful Cloud Infrastructure Tools`).version(es.version).option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1);W.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Ri()});W.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(re.bgCyan.black(f.cliTag("Hosting"))),await di()});W.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=>{de(re.bgCyan.black(f.cliTag("Sitemap Generator"))),await mi(e)});W.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new Cn("--build-id <id>","Internal build ID").hideHelp()).addOption(new Cn("--project-id <id>","Internal project ID").hideHelp()).option("--local","Run build on local machine").option("--auto-version","Automatically fetch and increment versionCode from Google Play").option("--verbose","Enable verbose logging").option("-y, --yes","Automatically answer yes to all prompts",!1).option("--quiet","Suppress non-essential output",!1).action(async(e,n)=>{let t=W.opts();n.yes=n.yes||t.yes,n.quiet=n.quiet||t.quiet,n.platform=e||n.platform,n.buildProfile=n.profile||n.buildProfile,n.quiet||de(re.bgCyan.black(f.cliTag("Cloud Build"))),await At(n)});W.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=>{de(re.bgCyan.black(f.cliTag("OTA Update"))),await Bi(e)});W.command("submit").description("Automated Store Submission (App Store / Google Play)").option("--platform <os>","Target platform (ios/android)").option("--track <track>","Google Play Track (internal, alpha, beta, production)","internal").option("--latest","Use the latest successful build for submission").option("--build-id <id>","Use a specific build ID for submission").action(async e=>{de(re.bgCyan.black(f.cliTag("Store Submission"))),await Gi(e)});W.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{de(re.bgCyan.black(f.cliTag("Login"))),await Ni()});W.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Link Project"))),await ki()});W.command("me").description("Display currently logged in user details").action(async()=>{await Vi()});W.command("init").description(`Create a new ${f.name} Project`).action(async()=>{de(re.bgCyan.black(f.cliTag("Init Project"))),await xi()});W.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{de(re.bgCyan.black(f.cliTag("Env Manager"))),await Mi(e,n)});W.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=>{de(re.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});W.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 Ji(e)});W.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:n}=await import("./credentials-WL7JKLF4.js");await n(e)});W.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=>{de(re.bgCyan.black(f.cliTag("Credentials Setup"))),await Je(e),Tn(re.green("Done!"))});W.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)").action(async e=>{de(re.bgCyan.black(f.cliTag("Service Credentials"))),await ci(e),Tn(re.green("Done!"))});var oi=W.command("device").description("Manage registered iOS test devices");oi.command("register").description("Register a connected iOS device or enter UDID manually").option("--udid <udid>","Device UDID (skip auto-detection)").option("--name <name>","Device name").action(async e=>{await _t("register",e)});oi.command("list").description("List all registered devices").action(async()=>{await _t("list",{})});oi.command("remove").description("Remove a registered device").option("--udid <udid>","Device UDID to remove").action(async e=>{await _t("remove",e)});W.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=>{de(re.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rn(e)});var ts=new Set(["login"]);W.hook("preAction",(e,n)=>{let t=n.name();ts.has(t)||si()});W.on("command:*",()=>{console.error(`Invalid command: %s
|
|
822
|
+
See --help for a list of available commands.`,W.args.join(" ")),process.exit(1)});process.argv.slice(2).length||W.help();W.parse(process.argv);
|