@radhya/mach 1.4.19 → 1.4.20
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 +10 -10
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,9 +4,9 @@ import{a as ci,c as Je}from"./chunk-YXFDQM4S.js";import{a as f,b as ri,c as ue,d
|
|
|
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 Bn,outro as jn}from"@clack/prompts";import Kn from"chalk";async function
|
|
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 Bn,outro as jn}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!"),Bn(`Routes included:
|
|
8
8
|
${a.map(d=>` \u2022 ${d.path}`).join(`
|
|
9
|
-
`)}`,"Sitemap Summary"),jn(`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
|
|
9
|
+
`)}`,"Sitemap Summary"),jn(`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>
|
|
@@ -717,7 +717,7 @@ fi
|
|
|
717
717
|
`);o.message("Generating macOS build script...");let O=process.env.CODEARTIFACT_AUTH_TOKEN?`export CODEARTIFACT_AUTH_TOKEN="${process.env.CODEARTIFACT_AUTH_TOKEN}"
|
|
718
718
|
`:"";if(t)for(let[I,b]of Object.entries(t)){let R=b.replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");O+=`export ${I}="${R}"
|
|
719
719
|
`}let L=[O,P.logUpload?`export PRESIGNED_LOG_UPLOAD="${P.logUpload}"`:"",P.doneMarker?`export PRESIGNED_DONE_MARKER="${P.doneMarker}"`:"",P.cacheDerivedDataDownload?`export PRESIGNED_CACHE_DD_DOWNLOAD="${P.cacheDerivedDataDownload}"`:"",P.cacheDerivedDataUpload?`export PRESIGNED_CACHE_DD_UPLOAD="${P.cacheDerivedDataUpload}"`:"",P.cacheNodeModulesDownload?`export PRESIGNED_CACHE_NODE_DOWNLOAD="${P.cacheNodeModulesDownload}"`:"",P.cacheNodeModulesUpload?`export PRESIGNED_CACHE_NODE_UPLOAD="${P.cacheNodeModulesUpload}"`:"",P.cachePodsDownload?`export PRESIGNED_CACHE_PODS_DOWNLOAD="${P.cachePodsDownload}"`:"",P.cachePodsUpload?`export PRESIGNED_CACHE_PODS_UPLOAD="${P.cachePodsUpload}"`:"",P.artifactIpaUpload?`export PRESIGNED_ARTIFACT_IPA_UPLOAD="${P.artifactIpaUpload}"`:"",P.artifactAppZipUpload?`export PRESIGNED_ARTIFACT_APP_ZIP_UPLOAD="${P.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
|
-
`),H=e.nodeVersion?['export NVM_DIR="$HOME/.nvm"','[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"',`nvm install ${e.nodeVersion} 2>/dev/null || true`,`nvm use ${e.nodeVersion}
|
|
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
|
`):"",q=Ai,y={"{{REMOTE_DIR}}":p,"{{ENV_VARS}}":L,"{{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])=>{q=q.split(I).join(b)});let w=`/tmp/${f.nameLower}-mac-build-${n}.sh`;if(Jn.writeFileSync(w,q),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||[],R=e.simulator===!0;if(b.length===0&&!R)throw o.stop("Build Failed!"),new Error("Build completed but no artifacts were generated. Check build logs for errors.");if(o.stop("Build Successful!"),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(`
|
|
@@ -795,19 +795,19 @@ ${J}`)),s&&await s("export"),A.info(S.blue(`Exporting with Bundle ID: "${C}"`)),
|
|
|
795
795
|
`);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
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 Bt from"chalk";import{log as je}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
797
|
`).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 Vt 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 zt(){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={...zt(),...e};it.writeFileSync(Kt,JSON.stringify(t,null,2))}async function Ni(){let e=zt(),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(Vt.green("Login successful!"))):i.stop(Vt.red("Login failed: "+(r.message||"Unknown error")))}catch(o){i.stop(Vt.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(`
|
|
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
799
|
[DIAGNOSTIC] API key written to: ${P.apiKeyJsonPath}
|
|
800
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 jo(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(ie.cyan(` [RECOVERY] Fetched ${l.length} artifact(s) with download URLs.`))):console.log(ie.yellow(" [RECOVERY] /artifacts endpoint returned 0 artifacts."))}catch(m){console.log(ie.red(` [RECOVERY] /artifacts fetch failed: ${m.message}`))}let u=n==="ios",p=l.find(m=>{let h=(m.type||"").toLowerCase(),P=(m.name||"").toLowerCase();if(console.log(ie.dim(` - Checking: ${m.name} (Type: ${m.type}, HasLink: ${!!(m.url||m.downloadUrl)})`)),h)return h===(u?"ipa":"aab");let N=u?".ipa":".aab",O=(m.url||m.downloadUrl||"").toLowerCase();return P.endsWith(N)||O.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 Bo(e,n,t,i,o){let r=st();if(o&&ve(`Bundled ID: ${ie.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
801
|
${(a.replace(/-----BEGIN[^-]*-----/g,"").replace(/-----END[^-]*-----/g,"").replace(/\s+/g,"").match(/.{1,64}/g)||[]).join(`
|
|
802
802
|
`)}
|
|
803
803
|
-----END PRIVATE KEY-----`}console.log(ie.yellow(`
|
|
804
804
|
[DIAGNOSTIC] Key ID: ${i}`)),console.log(ie.yellow(`[DIAGNOSTIC] Issuer ID: ${t}`)),console.log(ie.yellow(`[DIAGNOSTIC] Key Checksum (Start): ${c.substring(0,45).replace(/\n/g,"\\n")}`)),console.log(ie.yellow(`[DIAGNOSTIC] Key Checksum (End): ${c.substring(c.length-28).replace(/\n/g,"\\n")}
|
|
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 jo(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(ie.red(`\u274C ${e}`))}function ve(e){console.log(ie.gray(`\u2022 ${e}`))}function Fi(e){console.log(ie.green(`\u2713 ${e}`))}import{spinner as
|
|
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(
|
|
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 jo(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(ie.red(`\u274C ${e}`))}function ve(e){console.log(ie.gray(`\u2022 ${e}`))}function Fi(e){console.log(ie.green(`\u2713 ${e}`))}import{spinner as Vo,log as Me,outro as zo}from"@clack/prompts";import Zt from"chalk";import Bi 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 ji(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(Bi.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");Bi.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(`
|
|
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 $.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,Be(n,f.envPrefix)),i&&(Object.assign(o,Be(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(),P=h.match(/http:\/\/(.+):(\d+)/);if(P&&!u&&(p=P[1],u=!0,e.ios||e.android)){let N=e.ios?"ios":"android",L=`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:L}).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",P=>{P===0?m():h(new Error(`Dev server exited with code ${P}`))}),d.on("error",P=>{h(P)})})};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
807
|
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
|
|
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 V 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: ${V.bold(t)} (${V.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(V.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(V.green("Device registered!")),be.info(` ${V.bold("Name:")} ${t}`),be.info(` ${V.bold("UDID:")} ${V.dim(n)}`)}catch(r){o.stop(V.red("Failed to register device")),be.error(r.response?.data?.message||r.message)}ut(V.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(V.dim(`No devices registered yet. Run \`${f.nameLower} device register\` to add one.`)),ut(V.blue("---"));return}let i=t.map(o=>{let r=new Date(o.createdAt).toLocaleDateString();return` ${V.bold(o.name.padEnd(24))} ${V.dim(o.udid.padEnd(28))} ${V.cyan(o.addedVia.padEnd(10))} ${V.dim(r)}`});rr(` ${V.bold("Name".padEnd(24))} ${"UDID".padEnd(28)} ${"Via".padEnd(10)} Date
|
|
809
809
|
`+i.join(`
|
|
810
|
-
`),"Registered Devices")}catch(n){e.stop(
|
|
810
|
+
`),"Registered Devices")}catch(n){e.stop(V.red("Failed to fetch devices")),be.error(n.response?.data?.message||n.message)}ut(V.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(V.dim("No devices to remove.")),ut(V.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(V.red("Failed to fetch devices")),be.error(r.response?.data?.message||r.message);return}}let t=await or({message:`Remove device ${V.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(V.green("Device removed"))}catch(o){i.stop(V.red("Failed to remove device")),be.error(o.response?.data?.message||o.message)}ut(V.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 $e 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||{}),Pe=(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))(Pe||{});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(`
|
|
811
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,Pr=/from\s+['"]@react-native-async-storage\/async-storage['"]|from\s+['"]react-native['"].*AsyncStorage/,$r=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)):$r.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(!Pr.test(s))continue;let l=s.split(`
|
|
812
812
|
`),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
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],P=Dr.test(h);t.push({id:`NET-${String(i++).padStart(3,"0")}`,title:`Insecure HTTP URL${P?" (API endpoint)":""}`,description:`Plain HTTP URL found: ${h}`,severity:P?"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(`
|
|
@@ -816,5 +816,5 @@ Environment Variables:`)),Object.entries(i.env).forEach(([o,r])=>{pe.info(` ${o
|
|
|
816
816
|
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
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 ee from"chalk";import{log as X}from"@clack/prompts";var We={critical:ee.bgRed.white.bold,high:ee.red.bold,medium:ee.yellow.bold,low:ee.blue,info:ee.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(X.info(""),X.info(ee.bold(` ${a.label}`)+ee.dim(` ${c.length} finding(s)`)),X.info(ee.dim(" "+"\u2500".repeat(60))),a.error){X.error(ee.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()} `);X.info(` ${d} ${ee.bold(l.id)} ${l.title}`),X.info(ee.dim(` ${l.description}`)),l.file&&X.info(ee.dim(` File: ${l.file}${l.line?`:${l.line}`:""}`)),X.info(ee.cyan(` Fix: ${l.recommendation}`)),X.info(""),i[l.severity]++,t++}}X.info(""),X.info(ee.bold(" Summary")),X.info(ee.dim(" "+"\u2500".repeat(60))),X.info(` Total: ${ee.bold(String(t))} finding(s)`),X.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?(X.info(""),X.error(ee.red.bold(` FAIL \u2014 ${i.critical} critical, ${i.high} high issue(s) found`))):t>0?(X.info(""),X.warn(ee.yellow(" PASS (with warnings) \u2014 no critical or high issues"))):(X.info(""),X.success(ee.green.bold(" PASS \u2014 no issues found")))}function Pn(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 Z,spinner as Ur}from"@clack/prompts";import Y from"chalk";import Ce from"fs";import Mr from"os";import Ye from"path";import{execSync as Fr}from"child_process";var $n=16384,Hr=1,Gr=Buffer.from([127,69,76,70]);async function _n(e){Z.info(Y.bold.underline("16KB Page Alignment Check")),console.log("");let n=Ye.resolve(e);if(!Ce.existsSync(n))return Z.error(Y.red(`APK file not found: ${n}`)),!1;if(!n.endsWith(".apk"))return Z.error(Y.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."),Z.info(Y.yellow("No arm64-v8a or x86_64 native libraries found in the APK.")),Z.info(Y.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=jr(l),u=Ye.basename(s),p=Br(s);p!==null&&r.push({name:u,filePath:l,arch:d,align:p,compatible:p>=$n})}if(t.stop("Analysis complete."),r.length===0)return Z.info(Y.yellow("No valid ELF shared libraries found.")),!0;let a=r.filter(s=>!s.compatible),c=r.filter(s=>s.compatible);if(Z.info(Y.dim(`Checked ${r.length} native librar${r.length===1?"y":"ies"}
|
|
818
818
|
`)),a.length>0){Z.info(Y.red.bold(`Incompatible libraries:
|
|
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 Vr(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 Vr(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 zr.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"),V=new qr;V.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);V.command("agent").description("Start local device discovery agent for the Install Hub (port 7070)").action(async()=>{await Ri()});V.command("host").description("Setup AWS S3 static hosting and CloudFront").action(async()=>{de(oe.bgCyan.black(f.cliTag("Hosting"))),await di()});V.command("sitemap").description("Generate sitemap.xml from Expo Router app structure").option("-o, --output <path>","Output path for sitemap.xml","./public/sitemap.xml").action(async e=>{de(oe.bgCyan.black(f.cliTag("Sitemap Generator"))),await mi(e)});V.command("build").description("Run a build on a cloud provider (AWS Spot Instances)").argument("[platform]","Target platform (android, ios)").option("--platform <os>","Target platform alias (android, ios) [Optional]").option("--repo <url>","Git Repository URL").option("--branch <name>","Git Branch").option("--ami <id>","AMI ID").option("--bucket <name>","S3 Bucket for artifacts").option("--region <region>","AWS Region").option("--aws-profile <name>","AWS Credentials Profile").option("-p, --build-profile <name>","Build Profile (e.g. production, staging)","production").option("--profile <name>","Build Profile (alias for --build-profile)").option("--dry-run","Generate User Data script without launching").option("--keep-instance","Do not terminate the instance after build").option("--subnet <id>","VPC Subnet ID to launch the instance in").option("--security-group <id>","VPC Security Group ID to use").option("--ssh-host <host>","Remote host for iOS build (SSH)").option("--ssh-user <user>","SSH username for remote host").option("--ssh-key <path>","Path to private SSH key for remote host").option("--ios-scheme <scheme>","iOS Scheme to build").option("--ios-team-id <id>","Apple Development Team ID").option("--ios-configuration <config>","Xcode configuration (Release/Debug)").option("--ios-export-method <method>","Export method (ad-hoc, app-store, development, enterprise)").option("--ios-api-key-id <id>","App Store Connect API Key ID").option("--ios-api-key-issuer <id>","App Store Connect API Key Issuer ID").option("--ios-api-key-path <path>","Path to App Store Connect API Key (.p8) file").option("--simulator","Build for iOS Simulator (no signing required)").addOption(new 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=V.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)});V.command("update").description("Deploy an Over-The-Air (OTA) update to your live channel").option("--branch <name>","Channel or Branch to deploy to (e.g., production)","production").action(async e=>{de(oe.bgCyan.black(f.cliTag("OTA Update"))),await ji(e)});V.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)});V.command("login").description(`Login to ${f.name} Dashboard`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Login"))),await Ni()});V.command("link").description(`Link local directory to a ${f.name} Project`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Link Project"))),await ki()});V.command("me").description("Display currently logged in user details").action(async()=>{await zi()});V.command("init").description(`Create a new ${f.name} Project`).action(async()=>{de(oe.bgCyan.black(f.cliTag("Init Project"))),await xi()});V.command("env").description("Manage Environment Variables").argument("<action>","Action to perform: set or list").argument("[args...]","Key=Value pairs for set action").action(async(e,n)=>{de(oe.bgCyan.black(f.cliTag("Env Manager"))),await Mi(e,n)});V.command("start").description("Start the development server (Metro)").option("-p, --build-profile <name>","Build profile (e.g. development, staging)","development").option("--tunnel","Use ngrok tunnel").option("--lan","Use LAN IP").option("--localhost","Use localhost").option("-c, --clear","Clear Metro cache").option("--port <number>","Port to listen on").option("--ios","Start on iOS").option("--android","Start on Android").option("--web","Start on Web").action(async e=>{de(oe.bgCyan.black(f.cliTag("Dev Server"))),await qi(e)});V.command("config").description("Show resolved configuration for a profile").option("-p, --profile <name>","Build profile to resolve","development").option("--json","Output as JSON").action(async e=>{await Ji(e)});V.command("credentials").description("Unified, interactive credential management (iOS/Android)").option("-p, --profile <name>","Build profile (production, staging, development)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{let{credentialsMainCommand:n}=await import("./credentials-WL7JKLF4.js");await n(e)});V.command("credentials:setup").description("Automated credential provisioning (iOS/Android) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--profile <name>","Build profile (production, staging, development)").option("--bundle-id <id>","Bundle ID / Package Name (optional, auto-detected)").option("--team-id <id>","Apple Team ID (iOS only)").option("--key-alias <alias>","Android keystore alias (optional, auto-generated)").option("--aws-profile <name>","AWS Credentials Profile (for S3 storage)").option("--force","Force recreate certificates (nuke existing on Apple Portal)",!1).action(async e=>{de(oe.bgCyan.black(f.cliTag("Credentials Setup"))),await Je(e),Tn(oe.green("Done!"))});V.command("credentials:service").description("Upload Service Credentials (ASC API Key / Google Service JSON) [Legacy]").requiredOption("--platform <os>","Platform: ios or android").option("--file <path>","Path to credential file (.p8 or .json)").option("--issuer-id <id>","ASC API Key Issuer ID (iOS only)").option("--key-id <id>","ASC API Key ID (iOS only)").action(async e=>{de(oe.bgCyan.black(f.cliTag("Service Credentials"))),await ci(e),Tn(oe.green("Done!"))});var oi=V.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)});V.command("audit").description("Run automated security audit on the project or APK").option("--apk <path>","Path to APK file (runs APK diagnostics like 16KB alignment)").option("--json","Output results as JSON (for CI/CD)").option("--fix","Auto-apply fixes where possible").option("--category <name>","Run only a specific check category (e.g. 16kb, permissions, secrets)").option("--severity <level>","Minimum severity to display (critical, high, medium, low, info)").option("--prebuild","Run expo prebuild for deeper manifest/plist analysis").action(async e=>{de(oe.bgCyan.black(f.cliTag(e.apk?"APK Audit":"Security Audit"))),await Rn(e)});var ts=new Set(["login"]);V.hook("preAction",(e,n)=>{let t=n.name();ts.has(t)||si()});V.on("command:*",()=>{console.error(`Invalid command: %s
|
|
820
|
-
See --help for a list of available commands.`,
|
|
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.`,z.args.join(" ")),process.exit(1)});process.argv.slice(2).length||z.help();z.parse(process.argv);
|