phala 1.0.6 → 1.0.7

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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- var gr=Object.defineProperty;var hr=(t,e,o)=>e in t?gr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var He=(t,e,o)=>(hr(t,typeof e!="symbol"?e+"":e,o),o);import{Command as Ro}from"commander";import Ze from"chalk";var Ye=Ze.hex("#cdfa50"),ye=Ye(`
2
+ var hr=Object.defineProperty;var yr=(t,e,o)=>e in t?hr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var Ze=(t,e,o)=>(yr(t,typeof e!="symbol"?e+"":e,o),o);import{Command as Fo}from"commander";import Ye from"chalk";var Je=Ye.hex("#cdfa50"),be=Je(`
3
3
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
4
4
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
5
5
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
@@ -21,7 +21,7 @@ var gr=Object.defineProperty;var hr=(t,e,o)=>e in t?gr(t,e,{enumerable:!0,config
21
21
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
22
22
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
23
23
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
24
- `),Lo=Ye(`
24
+ `),No=Je(`
25
25
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28E0\u28E4\u28E4\u28E4\u28C0\u2840\u2800\u2880\u28C0\u28E4\u28E4\u28C0\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
26
26
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u28F4\u287F\u281B\u2809\u2801\u2800\u2808\u2809\u281B\u283F\u281B\u2809\u2809\u2809\u2809\u2819\u2837\u28C4\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
27
27
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u28FF\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2818\u28E7\u2800\u2800\u2800\u2800\u2800\u2800\u2800
@@ -43,7 +43,7 @@ var gr=Object.defineProperty;var hr=(t,e,o)=>e in t?gr(t,e,{enumerable:!0,config
43
43
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u28C6\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2809\u281B\u283F\u283F\u28FF\u28FF\u28FF\u28FF\u28FF\u283F\u281F\u280B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28FE\u2800\u2800\u2800\u2800\u2800\u2800\u2800
44
44
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u283B\u28B6\u28E6\u28E4\u28C4\u28C0\u28C0\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28C0\u28C0\u28C0\u28E4\u28F4\u28F6\u283F\u281B\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800
45
45
  \u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2809\u2819\u281B\u283B\u283F\u283F\u283F\u283F\u28BF\u28FF\u28FF\u28FF\u283F\u283F\u283F\u283F\u281F\u281B\u281B\u2809\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800
46
- `),No=Ze.cyan("PHALA TEE CLOUD CLI");import{Command as zr}from"commander";import{Command as Lr}from"commander";import V from"node:fs";import De from"node:path";import Z from"node:os";import be from"node:crypto";import _ from"chalk";function yr(t){let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return t.replace(new RegExp(e,"g"),"")}function H(t){return yr(t).length}function oe(t,e){if(!t)return[""];if(H(t)<=e)return[t];let o=[],n="",s=0,c=t.split(/(\s+)/).filter(a=>a.trim().length>0);for(let a of c){let p=H(a);if(p>e){n&&(o.push(n),n="",s=0),o.push(a);continue}s+p+(s>0?1:0)>e?(o.push(n),n=a,s=p):n?(n=`${n} ${a}`,s+=p+1):(n=a,s=p)}return n&&o.push(n),o}var r={error:(t,...e)=>{console.error(_.red("\u2717"),_.red(t),...e)},warn:(t,...e)=>{console.log(_.yellow("\u26A0"),_.yellow(t),...e)},info:(t,...e)=>{console.log(_.blue("\u2139"),_.blue(t),...e)},success:(t,...e)=>{console.log(_.green("\u2713"),_.green(t),...e)},debug:(t,...e)=>{process.env.DEBUG&&console.log(_.gray("\u{1F50D}"),_.gray(t),...e)},table:(t,e)=>{if(t.length===0){console.log(_.yellow("No data to display"));return}if(e)if(typeof e[0]=="string"){let o=e.map(n=>({key:n,header:n.charAt(0).toUpperCase()+n.slice(1)}));Pe(t,{columns:o,borderStyle:"rounded",headerStyle:n=>_.cyan.bold(n)})}else Pe(t,{columns:e,borderStyle:"rounded",headerStyle:o=>_.cyan.bold(o)});else Pe(t,{borderStyle:"rounded",headerStyle:o=>_.cyan.bold(o)})},keyValueTable:(t,e)=>{let n={...{borderStyle:"rounded",enableTextWrapping:!0,maxDepth:2,formatKeys:!0,keyFormatter:w=>{let E=["URL","ID","API","UI","URI","CPU","GPU","RAM","JSON","XML","HTML","HTTP","HTTPS","SSH","FTP","IP","TCP","UDP","DNS","SSL","TLS","SQL","VCPU","CVM","TEE","IO"],I={teepod:"TEEPod",dstack:"Dstack"},M;w.includes("_")?M=w.split("_").map(F=>F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join(" "):w.includes("-")?M=w.split("-").map(F=>F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join(" "):M=w.charAt(0).toUpperCase()+w.slice(1).replace(/([a-z])([A-Z])/g,"$1 $2");for(let F of E){let U=new RegExp(`\\b${F.toLowerCase()}\\b`,"gi");M=M.replace(U,F)}for(let[F,U]of Object.entries(I)){let he=new RegExp(`\\b${F}\\b`,"gi");M=M.replace(he,U)}return M},valueFormatter:w=>String(w??"")},...e},{include:s,exclude:c,keyFormatter:a,valueFormatter:p,formatKeys:h,keyWidth:f,valueWidth:C,borderStyle:k,enableTextWrapping:m,maxDepth:l}=n,u=Object.keys(t);if(s&&(u=u.filter(w=>s.includes(w))),c&&(u=u.filter(w=>!c.includes(w))),u.length===0){console.log(_.yellow("No properties to display"));return}let g=u.map(w=>{let E=t[w],I;return E==null?I="":typeof E=="object"&&!Array.isArray(E)?I=Je(E,0,l):Array.isArray(E)?E.length===0?I="[]":typeof E[0]=="object"?I=`[${E.length} items]`:I=`[${E.join(", ")}]`:I=String(E),p&&(I=p(E,w)),{key:h&&a?_.cyan.bold(a(w)):_.cyan.bold(w),value:I}}),b=Xe(),d=f,v=C;if(d||(d=Math.max(...g.map(w=>H(w.key)),10),d=Math.min(d,Math.floor(b/3))),!v){v=Math.max(...g.map(I=>H(I.value)),10),v+=3;let w=7,E=b-d-w;v=Math.min(v,E)}let y=br(k),x=`${y.topLeft}${y.horizontal.repeat(d+2)}${y.topT}${y.horizontal.repeat(v+2)}${y.topRight}`,L=`${y.leftT}${y.horizontal.repeat(d+2)}${y.cross}${y.horizontal.repeat(v+2)}${y.rightT}`;console.log(x),console.log(L),g.forEach((w,E)=>{let I=m?oe(w.key,d):[w.key],M=m?oe(w.value,v):[w.value],F=Math.max(I.length,M.length);for(let U=0;U<F;U++){let he=I[U]||"",qe=M[U]||"",ur=he+" ".repeat(Math.max(0,d-H(he))),fr=qe+" ".repeat(Math.max(0,v-H(qe)));console.log(`${y.vertical} ${ur} ${y.vertical} ${fr} ${y.vertical}`)}E<g.length-1&&console.log(`${y.leftT}${y.horizontal.repeat(d+2)}${y.cross}${y.horizontal.repeat(v+2)}${y.rightT}`)});let Te=`${y.bottomLeft}${y.horizontal.repeat(d+2)}${y.bottomT}${y.horizontal.repeat(v+2)}${y.bottomRight}`;console.log(Te)},startSpinner:t=>(process.stdout.write(`${_.blue("\u27F3")} ${t}... `),{stop:(e=!0,o)=>{let n=e?_.green("\u2713"):_.red("\u2717"),s=o?`: ${o}`:"";console.log(`${n}${s}`)}}),break(){console.log("")}};function Je(t,e,o){if(e>=o)return"[Nested Object]";if(t==null)return"";if(Array.isArray(t))return t.length===0?"[]":`[${t.length} items]`;let n=[];for(let[s,c]of Object.entries(t))c==null?n.push(`${s}: `):typeof c=="object"?n.push(`${s}: ${Je(c,e+1,o)}`):n.push(`${s}: ${c}`);return n.join(", ")}function br(t="single"){return{single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"}}[t]}function Xe(){return process.stdout.columns||80}function vr(t,e,o={}){let n=Xe(),s=o.borderChars??3,a=(o.additionalBorderWidth??1)+e.length*s,p=n-a,h={},f=0,C=0;for(let l of e){let u=l.key;if(l.fixedWidth!==void 0){h[u]=l.fixedWidth,f+=l.fixedWidth;continue}let g=l.minWidth??l.header.length,b;l.getWidth?b=Math.max(g,l.header.length,...t.map(d=>l.getWidth(d))):l.getValue?b=Math.max(g,l.header.length,...t.map(d=>String(l.getValue(d)||"").length)):b=Math.max(g,l.header.length,...t.map(d=>String(d[l.key]||"").length)),h[u]=b,f+=b,C+=l.weight??1}let k=Math.max(0,p-f);if(k>0&&C>0)for(let l of e){let u=l.key;if(l.fixedWidth===void 0&&l.weight){let g=Math.floor(k*(l.weight/C));h[u]+=g}}let m=Object.values(h).reduce((l,u)=>l+u,0)+a;if(m>n){let l=p/(m-a),u={};for(let g of e){let b=g.key,d=g.minWidth??g.header.length;u[b]=Math.max(d,Math.floor(h[b]*l))}return u}return h}function Pe(t,e={}){if(e.keyValueMode&&t.length===1){let m=t[0],l=[];e.columns||(e.columns=Object.keys(m).map(u=>({key:u,header:u.charAt(0).toUpperCase()+u.slice(1).replace(/([A-Z])/g," $1")})));for(let u of e.columns){let g=String(u.key),b;if(u.accessor)b=u.accessor(m);else if(typeof u.key=="string"&&u.key.includes(".")){let d=u.key.split("."),v=m;for(let y of d){if(v==null){b="";break}v=v[y]}b=v}else b=m[u.key];u.formatter&&(b=u.formatter(b)),l.push({key:u.header||g,value:b})}t=l,e.columns=[{key:"key",minWidth:15},{key:"value",minWidth:20}]}if(t.length===0){console.log(_.yellow("No data to display"));return}let n={...{includeHeaders:!0,border:!0,borderStyle:"single",headerStyle:m=>_.bold(m),cellStyle:m=>m,enableTextWrapping:!0},...e},s=n.columns;if(s)s=s.map(m=>({...m,enableTextWrapping:m.enableTextWrapping!==void 0?m.enableTextWrapping:n.enableTextWrapping}));else{let m=t[0];s=Object.keys(m).map(l=>({key:l,header:l.charAt(0).toUpperCase()+l.slice(1),enableTextWrapping:n.enableTextWrapping}))}let a={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"}}[n.borderStyle],p=s.map(m=>({key:m.key,header:m.header||String(m.key),minWidth:m.minWidth||3,weight:m.weight,enableTextWrapping:m.enableTextWrapping,getValue:m.accessor?l=>m.accessor(l):l=>{if(typeof m.key=="string"&&m.key.includes(".")){let u=m.key.split("."),g=l;for(let b of u){if(g==null)return"";g=g[b]}return g??""}return l[m.key]??""}})),h=vr(t,p),f=s.map((m,l)=>({...m,width:h[p[l].key]})),C=f.map(m=>m.header||String(m.key)),k=(m,l)=>{let u=f.map(d=>{let v;if(d.accessor)v=d.accessor(m);else if(typeof d.key=="string"&&d.key.includes(".")){let x=d.key.split("."),L=m;for(let Te of x){if(L==null){v="";break}L=L[Te]}v=L??""}else v=m[d.key]??"";let y=d.formatter?d.formatter(v):String(v||"");return d.enableTextWrapping?{lines:oe(y,d.width),key:String(d.key)}:{lines:[y.length>d.width?y.substring(0,d.width-1)+"\u2026":y],key:String(d.key)}}),g=Math.max(...u.map(d=>d.lines.length)),b=[];for(let d=0;d<g;d++){let v=u.map((y,x)=>{let L=y.lines[d]||"";return n.cellStyle(L.padEnd(f[x].width),l,y.key)});b.push(v)}return b};if(n.border){let m=a.topLeft+f.map(u=>a.horizontal.repeat(u.width+2)).join(a.topT)+a.topRight;if(console.log(m),n.includeHeaders){let u=f.map((d,v)=>({lines:d.enableTextWrapping?oe(C[v],d.width):[C[v]],width:d.width})),g=Math.max(...u.map(d=>d.lines.length));for(let d=0;d<g;d++){let v=a.vertical+u.map(y=>{let x=y.lines[d]||"";return" "+n.headerStyle(x.padEnd(y.width))+" "}).join(a.vertical)+a.vertical;console.log(v)}let b=a.leftT+f.map(d=>a.horizontal.repeat(d.width+2)).join(a.cross)+a.rightT;console.log(b)}t.forEach((u,g)=>{let b=k(u,g);if(b.forEach(d=>{console.log(a.vertical+d.map(v=>` ${v} `).join(a.vertical)+a.vertical)}),g<t.length-1&&b.length>1){let d=a.leftT+f.map(v=>a.horizontal.repeat(v.width+2)).join(a.cross)+a.rightT;console.log(d)}});let l=a.bottomLeft+f.map(u=>a.horizontal.repeat(u.width+2)).join(a.bottomT)+a.bottomRight;console.log(l)}else{if(n.includeHeaders){let m=f.map((g,b)=>({lines:g.enableTextWrapping?oe(C[b],g.width):[C[b]],width:g.width})),l=Math.max(...m.map(g=>g.lines.length));for(let g=0;g<l;g++){let b=m.map(d=>{let v=d.lines[g]||"";return n.headerStyle(v.padEnd(d.width))}).join(" ");console.log(b)}let u=f.map(g=>"\u2500".repeat(g.width)).join(" ");console.log(u)}t.forEach((m,l)=>{let u=k(m,l);u.forEach(g=>{console.log(g.join(" "))}),l<t.length-1&&u.length>1&&console.log("")})}console.log(`Total: ${t.length} rows`)}var ne=De.join(Z.homedir(),".phala-cloud"),se=De.join(ne,"api-key"),Ie=De.join(ne,"docker-credentials.json");function Qe(){if(!V.existsSync(ne))try{V.mkdirSync(ne,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${ne}:`,t),t}}function et(){let t=[Z.hostname(),Z.platform(),Z.arch(),Z.cpus()[0]?.model||"",Z.userInfo().username],e=be.createHash("sha256");return e.update(t.join("|")),e.digest()}function Cr(t){try{let e=et(),o=be.randomBytes(16),n=be.createCipheriv("aes-256-cbc",e.slice(0,32),o),s=n.update(t,"utf8","hex");return s+=n.final("hex"),o.toString("hex")+":"+s}catch(e){throw r.error("Encryption failed:",e),new Error("Failed to encrypt data")}}function kr(t){try{let e=et(),o=t.split(":");if(o.length!==2)throw new Error("Invalid encrypted format");let n=Buffer.from(o[0],"hex"),s=o[1],c=be.createDecipheriv("aes-256-cbc",e.slice(0,32),n),a=c.update(s,"hex","utf8");return a+=c.final("utf8"),a}catch(e){throw r.error("Decryption failed:",e),new Error("Failed to decrypt data")}}async function Ae(t){Qe();try{let e=Cr(t);V.writeFileSync(se,e,{mode:384})}catch(e){throw r.error("Failed to save API key:",e),e}}async function Y(){try{if(V.existsSync(se)){let t=V.readFileSync(se,"utf8").trim();return kr(t)}return null}catch(t){return r.error("Failed to read API key:",t),null}}async function ie(){try{V.existsSync(se)?(V.unlinkSync(se),r.success("API key removed successfully.")):r.warn("No API key found to remove.")}catch(t){throw r.error("Failed to remove API key:",t),t}}async function Re(t){Qe();try{V.writeFileSync(Ie,JSON.stringify(t,null,2),{mode:384}),r.success("Docker information saved successfully.")}catch(e){throw r.error("Failed to save Docker information:",e),e}}async function N(){try{if(V.existsSync(Ie)){let t=V.readFileSync(Ie,"utf8");return JSON.parse(t)}return null}catch(t){return r.error("Failed to read Docker credentials:",t),null}}import Nr from"prompts";import wr from"axios";var Fe=process.env.CLOUD_API_URL||"https://cloud-api.phala.network",S=process.env.CLOUD_URL||"https://cloud.phala.network",tt="0.0.1";var rt="phalanetwork/tappd-simulator:latest",Me=2,Ve=4096,Le=40;var ot="dstack-0.3.5",$={USER_INFO:"/api/v1/auth/me",TEEPODS:"/api/v1/teepods/available",TEEPOD_IMAGES:t=>`/api/v1/teepods/${t}/images`,CVMS:t=>`/api/v1/cvms?user_id=${t}`,CVM_BY_APP_ID:t=>`/api/v1/cvms/app_${t}`,CVM_NETWORK:t=>`/api/v1/cvms/app_${t}/network`,CVM_START:t=>`/api/v1/cvms/app_${t}/start`,CVM_STOP:t=>`/api/v1/cvms/app_${t}/stop`,CVM_RESTART:t=>`/api/v1/cvms/app_${t}/restart`,CVM_LOGS:t=>`/api/v1/cvms/app_${t}/logs`,CVM_FROM_CONFIGURATION:"/api/v1/cvms/from_cvm_configuration",CVM_PUBKEY:"/api/v1/cvms/pubkey/from_cvm_configuration",CVM_UPGRADE:t=>`/api/v1/cvms/app_${t}/compose`,CVM_ATTESTATION:t=>`/api/v1/cvms/app_${t}/attestation`,CVM_RESIZE:t=>`/api/v1/cvms/app_${t}/resources`},nt=`version: '3.8'
46
+ `),Oo=Ye.cyan("PHALA TEE CLOUD CLI");import{Command as jr}from"commander";import{Command as Nr}from"commander";import V from"node:fs";import Ae from"node:path";import Z from"node:os";import ve from"node:crypto";import _ from"chalk";function br(t){let e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return t.replace(new RegExp(e,"g"),"")}function H(t){return br(t).length}function oe(t,e){if(!t)return[""];if(H(t)<=e)return[t];let o=[],n="",s=0,c=t.split(/(\s+)/).filter(a=>a.trim().length>0);for(let a of c){let p=H(a);if(p>e){n&&(o.push(n),n="",s=0),o.push(a);continue}s+p+(s>0?1:0)>e?(o.push(n),n=a,s=p):n?(n=`${n} ${a}`,s+=p+1):(n=a,s=p)}return n&&o.push(n),o}var r={error:(t,...e)=>{console.error(_.red("\u2717"),_.red(t),...e)},warn:(t,...e)=>{console.log(_.yellow("\u26A0"),_.yellow(t),...e)},info:(t,...e)=>{console.log(_.blue("\u2139"),_.blue(t),...e)},success:(t,...e)=>{console.log(_.green("\u2713"),_.green(t),...e)},debug:(t,...e)=>{process.env.DEBUG&&console.log(_.gray("\u{1F50D}"),_.gray(t),...e)},table:(t,e)=>{if(t.length===0){console.log(_.yellow("No data to display"));return}if(e)if(typeof e[0]=="string"){let o=e.map(n=>({key:n,header:n.charAt(0).toUpperCase()+n.slice(1)}));Ie(t,{columns:o,borderStyle:"rounded",headerStyle:n=>_.cyan.bold(n)})}else Ie(t,{columns:e,borderStyle:"rounded",headerStyle:o=>_.cyan.bold(o)});else Ie(t,{borderStyle:"rounded",headerStyle:o=>_.cyan.bold(o)})},keyValueTable:(t,e)=>{let n={...{borderStyle:"rounded",enableTextWrapping:!0,maxDepth:2,formatKeys:!0,keyFormatter:w=>{let x=["URL","ID","API","UI","URI","CPU","GPU","RAM","JSON","XML","HTML","HTTP","HTTPS","SSH","FTP","IP","TCP","UDP","DNS","SSL","TLS","SQL","VCPU","CVM","TEE","IO"],I={teepod:"TEEPod",dstack:"Dstack"},M;w.includes("_")?M=w.split("_").map(F=>F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join(" "):w.includes("-")?M=w.split("-").map(F=>F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join(" "):M=w.charAt(0).toUpperCase()+w.slice(1).replace(/([a-z])([A-Z])/g,"$1 $2");for(let F of x){let U=new RegExp(`\\b${F.toLowerCase()}\\b`,"gi");M=M.replace(U,F)}for(let[F,U]of Object.entries(I)){let ye=new RegExp(`\\b${F}\\b`,"gi");M=M.replace(ye,U)}return M},valueFormatter:w=>String(w??"")},...e},{include:s,exclude:c,keyFormatter:a,valueFormatter:p,formatKeys:y,keyWidth:f,valueWidth:v,borderStyle:k,enableTextWrapping:m,maxDepth:l}=n,u=Object.keys(t);if(s&&(u=u.filter(w=>s.includes(w))),c&&(u=u.filter(w=>!c.includes(w))),u.length===0){console.log(_.yellow("No properties to display"));return}let g=u.map(w=>{let x=t[w],I;return x==null?I="":typeof x=="object"&&!Array.isArray(x)?I=Xe(x,0,l):Array.isArray(x)?x.length===0?I="[]":typeof x[0]=="object"?I=`[${x.length} items]`:I=`[${x.join(", ")}]`:I=String(x),p&&(I=p(x,w)),{key:y&&a?_.cyan.bold(a(w)):_.cyan.bold(w),value:I}}),b=Qe(),d=f,C=v;if(d||(d=Math.max(...g.map(w=>H(w.key)),10),d=Math.min(d,Math.floor(b/3))),!C){C=Math.max(...g.map(I=>H(I.value)),10),C+=3;let w=7,x=b-d-w;C=Math.min(C,x)}let h=vr(k),$=`${h.topLeft}${h.horizontal.repeat(d+2)}${h.topT}${h.horizontal.repeat(C+2)}${h.topRight}`,L=`${h.leftT}${h.horizontal.repeat(d+2)}${h.cross}${h.horizontal.repeat(C+2)}${h.rightT}`;console.log($),console.log(L),g.forEach((w,x)=>{let I=m?oe(w.key,d):[w.key],M=m?oe(w.value,C):[w.value],F=Math.max(I.length,M.length);for(let U=0;U<F;U++){let ye=I[U]||"",He=M[U]||"",fr=ye+" ".repeat(Math.max(0,d-H(ye))),gr=He+" ".repeat(Math.max(0,C-H(He)));console.log(`${h.vertical} ${fr} ${h.vertical} ${gr} ${h.vertical}`)}x<g.length-1&&console.log(`${h.leftT}${h.horizontal.repeat(d+2)}${h.cross}${h.horizontal.repeat(C+2)}${h.rightT}`)});let Pe=`${h.bottomLeft}${h.horizontal.repeat(d+2)}${h.bottomT}${h.horizontal.repeat(C+2)}${h.bottomRight}`;console.log(Pe)},startSpinner:t=>(process.stdout.write(`${_.blue("\u27F3")} ${t}... `),{stop:(e=!0,o)=>{let n=e?_.green("\u2713"):_.red("\u2717"),s=o?`: ${o}`:"";console.log(`${n}${s}`)}}),break(){console.log("")}};function Xe(t,e,o){if(e>=o)return"[Nested Object]";if(t==null)return"";if(Array.isArray(t))return t.length===0?"[]":`[${t.length} items]`;let n=[];for(let[s,c]of Object.entries(t))c==null?n.push(`${s}: `):typeof c=="object"?n.push(`${s}: ${Xe(c,e+1,o)}`):n.push(`${s}: ${c}`);return n.join(", ")}function vr(t="single"){return{single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"}}[t]}function Qe(){return process.stdout.columns||80}function Cr(t,e,o={}){let n=Qe(),s=o.borderChars??3,a=(o.additionalBorderWidth??1)+e.length*s,p=n-a,y={},f=0,v=0;for(let l of e){let u=l.key;if(l.fixedWidth!==void 0){y[u]=l.fixedWidth,f+=l.fixedWidth;continue}let g=l.minWidth??l.header.length,b;l.getWidth?b=Math.max(g,l.header.length,...t.map(d=>l.getWidth(d))):l.getValue?b=Math.max(g,l.header.length,...t.map(d=>String(l.getValue(d)||"").length)):b=Math.max(g,l.header.length,...t.map(d=>String(d[l.key]||"").length)),y[u]=b,f+=b,v+=l.weight??1}let k=Math.max(0,p-f);if(k>0&&v>0)for(let l of e){let u=l.key;if(l.fixedWidth===void 0&&l.weight){let g=Math.floor(k*(l.weight/v));y[u]+=g}}let m=Object.values(y).reduce((l,u)=>l+u,0)+a;if(m>n){let l=p/(m-a),u={};for(let g of e){let b=g.key,d=g.minWidth??g.header.length;u[b]=Math.max(d,Math.floor(y[b]*l))}return u}return y}function Ie(t,e={}){if(e.keyValueMode&&t.length===1){let m=t[0],l=[];e.columns||(e.columns=Object.keys(m).map(u=>({key:u,header:u.charAt(0).toUpperCase()+u.slice(1).replace(/([A-Z])/g," $1")})));for(let u of e.columns){let g=String(u.key),b;if(u.accessor)b=u.accessor(m);else if(typeof u.key=="string"&&u.key.includes(".")){let d=u.key.split("."),C=m;for(let h of d){if(C==null){b="";break}C=C[h]}b=C}else b=m[u.key];u.formatter&&(b=u.formatter(b)),l.push({key:u.header||g,value:b})}t=l,e.columns=[{key:"key",minWidth:15},{key:"value",minWidth:20}]}if(t.length===0){console.log(_.yellow("No data to display"));return}let n={...{includeHeaders:!0,border:!0,borderStyle:"single",headerStyle:m=>_.bold(m),cellStyle:m=>m,enableTextWrapping:!0},...e},s=n.columns;if(s)s=s.map(m=>({...m,enableTextWrapping:m.enableTextWrapping!==void 0?m.enableTextWrapping:n.enableTextWrapping}));else{let m=t[0];s=Object.keys(m).map(l=>({key:l,header:l.charAt(0).toUpperCase()+l.slice(1),enableTextWrapping:n.enableTextWrapping}))}let a={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"}}[n.borderStyle],p=s.map(m=>({key:m.key,header:m.header||String(m.key),minWidth:m.minWidth||3,weight:m.weight,enableTextWrapping:m.enableTextWrapping,getValue:m.accessor?l=>m.accessor(l):l=>{if(typeof m.key=="string"&&m.key.includes(".")){let u=m.key.split("."),g=l;for(let b of u){if(g==null)return"";g=g[b]}return g??""}return l[m.key]??""}})),y=Cr(t,p),f=s.map((m,l)=>({...m,width:y[p[l].key]})),v=f.map(m=>m.header||String(m.key)),k=(m,l)=>{let u=f.map(d=>{let C;if(d.accessor)C=d.accessor(m);else if(typeof d.key=="string"&&d.key.includes(".")){let $=d.key.split("."),L=m;for(let Pe of $){if(L==null){C="";break}L=L[Pe]}C=L??""}else C=m[d.key]??"";let h=d.formatter?d.formatter(C):String(C||"");return d.enableTextWrapping?{lines:oe(h,d.width),key:String(d.key)}:{lines:[h.length>d.width?h.substring(0,d.width-1)+"\u2026":h],key:String(d.key)}}),g=Math.max(...u.map(d=>d.lines.length)),b=[];for(let d=0;d<g;d++){let C=u.map((h,$)=>{let L=h.lines[d]||"";return n.cellStyle(L.padEnd(f[$].width),l,h.key)});b.push(C)}return b};if(n.border){let m=a.topLeft+f.map(u=>a.horizontal.repeat(u.width+2)).join(a.topT)+a.topRight;if(console.log(m),n.includeHeaders){let u=f.map((d,C)=>({lines:d.enableTextWrapping?oe(v[C],d.width):[v[C]],width:d.width})),g=Math.max(...u.map(d=>d.lines.length));for(let d=0;d<g;d++){let C=a.vertical+u.map(h=>{let $=h.lines[d]||"";return" "+n.headerStyle($.padEnd(h.width))+" "}).join(a.vertical)+a.vertical;console.log(C)}let b=a.leftT+f.map(d=>a.horizontal.repeat(d.width+2)).join(a.cross)+a.rightT;console.log(b)}t.forEach((u,g)=>{let b=k(u,g);if(b.forEach(d=>{console.log(a.vertical+d.map(C=>` ${C} `).join(a.vertical)+a.vertical)}),g<t.length-1&&b.length>1){let d=a.leftT+f.map(C=>a.horizontal.repeat(C.width+2)).join(a.cross)+a.rightT;console.log(d)}});let l=a.bottomLeft+f.map(u=>a.horizontal.repeat(u.width+2)).join(a.bottomT)+a.bottomRight;console.log(l)}else{if(n.includeHeaders){let m=f.map((g,b)=>({lines:g.enableTextWrapping?oe(v[b],g.width):[v[b]],width:g.width})),l=Math.max(...m.map(g=>g.lines.length));for(let g=0;g<l;g++){let b=m.map(d=>{let C=d.lines[g]||"";return n.headerStyle(C.padEnd(d.width))}).join(" ");console.log(b)}let u=f.map(g=>"\u2500".repeat(g.width)).join(" ");console.log(u)}t.forEach((m,l)=>{let u=k(m,l);u.forEach(g=>{console.log(g.join(" "))}),l<t.length-1&&u.length>1&&console.log("")})}console.log(`Total: ${t.length} rows`)}var ne=Ae.join(Z.homedir(),".phala-cloud"),se=Ae.join(ne,"api-key"),De=Ae.join(ne,"docker-credentials.json");function et(){if(!V.existsSync(ne))try{V.mkdirSync(ne,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${ne}:`,t),t}}function tt(){let t=[Z.hostname(),Z.platform(),Z.arch(),Z.cpus()[0]?.model||"",Z.userInfo().username],e=ve.createHash("sha256");return e.update(t.join("|")),e.digest()}function kr(t){try{let e=tt(),o=ve.randomBytes(16),n=ve.createCipheriv("aes-256-cbc",e.slice(0,32),o),s=n.update(t,"utf8","hex");return s+=n.final("hex"),o.toString("hex")+":"+s}catch(e){throw r.error("Encryption failed:",e),new Error("Failed to encrypt data")}}function wr(t){try{let e=tt(),o=t.split(":");if(o.length!==2)throw new Error("Invalid encrypted format");let n=Buffer.from(o[0],"hex"),s=o[1],c=ve.createDecipheriv("aes-256-cbc",e.slice(0,32),n),a=c.update(s,"hex","utf8");return a+=c.final("utf8"),a}catch(e){throw r.error("Decryption failed:",e),new Error("Failed to decrypt data")}}async function Re(t){et();try{let e=kr(t);V.writeFileSync(se,e,{mode:384})}catch(e){throw r.error("Failed to save API key:",e),e}}async function Y(){try{if(V.existsSync(se)){let t=V.readFileSync(se,"utf8").trim();return wr(t)}return null}catch(t){return r.error("Failed to read API key:",t),null}}async function ie(){try{V.existsSync(se)?(V.unlinkSync(se),r.success("API key removed successfully.")):r.warn("No API key found to remove.")}catch(t){throw r.error("Failed to remove API key:",t),t}}async function Fe(t){et();try{V.writeFileSync(De,JSON.stringify(t,null,2),{mode:384}),r.success("Docker information saved successfully.")}catch(e){throw r.error("Failed to save Docker information:",e),e}}async function N(){try{if(V.existsSync(De)){let t=V.readFileSync(De,"utf8");return JSON.parse(t)}return null}catch(t){return r.error("Failed to read Docker credentials:",t),null}}import Or from"prompts";import _r from"axios";var Me=process.env.CLOUD_API_URL||"https://cloud-api.phala.network",S=process.env.CLOUD_URL||"https://cloud.phala.network",rt="0.0.1";var ot="phalanetwork/tappd-simulator:latest",Ve=2,Le=4096,Ne=40,nt="3",ae="dstack-0.3.5",E={USER_INFO:"/api/v1/auth/me",TEEPODS:"/api/v1/teepods/available",TEEPOD_IMAGES:t=>`/api/v1/teepods/${t}/images`,CVMS:t=>`/api/v1/cvms?user_id=${t}`,CVM_BY_APP_ID:t=>`/api/v1/cvms/app_${t}`,CVM_NETWORK:t=>`/api/v1/cvms/app_${t}/network`,CVM_START:t=>`/api/v1/cvms/app_${t}/start`,CVM_STOP:t=>`/api/v1/cvms/app_${t}/stop`,CVM_RESTART:t=>`/api/v1/cvms/app_${t}/restart`,CVM_LOGS:t=>`/api/v1/cvms/app_${t}/logs`,CVM_FROM_CONFIGURATION:"/api/v1/cvms/from_cvm_configuration",CVM_PUBKEY:"/api/v1/cvms/pubkey/from_cvm_configuration",CVM_UPGRADE:t=>`/api/v1/cvms/app_${t}/compose`,CVM_ATTESTATION:t=>`/api/v1/cvms/app_${t}/attestation`,CVM_RESIZE:t=>`/api/v1/cvms/app_${t}/resources`},st=`version: '3.8'
47
47
  services:
48
48
  postgres:
49
49
  image: ankane/pgvector:latest
@@ -87,7 +87,7 @@ networks:
87
87
  driver: bridge
88
88
 
89
89
  volumes:
90
- postgres-data:`,st=`version: '3.8'
90
+ postgres-data:`,it=`version: '3.8'
91
91
  services:
92
92
  app:
93
93
  image: {{imageName}}
@@ -98,21 +98,21 @@ services:
98
98
  {{#each envVars}} - {{{this}}}
99
99
  {{/each}}
100
100
  restart: always
101
- `;function Ne(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}var Oe=class{client;apiKey=null;constructor(e){r.debug(`Creating API client with base URL: ${e}`),this.client=wr.create({baseURL:e,headers:{"Content-Type":"application/json","User-Agent":`tee-cloud-cli/${tt}`}}),this.client.interceptors.request.use(async o=>{if(!this.apiKey){if(this.apiKey=await Y(),!this.apiKey)throw new Error('API key not found. Please set an API key first with "phala auth login"');r.debug(`API key loaded: ${this.apiKey.substring(0,5)}...`)}return o.headers["X-API-Key"]=this.apiKey,r.debug(`Making request to: ${o.baseURL}${o.url}`),o}),this.client.interceptors.response.use(o=>(r.debug(`Received successful response from: ${o.config.url}`),o),o=>{if(o.response){let{status:n,data:s}=o.response;r.debug(`Received error response: ${n} - ${Ne(s)}`),n===401?r.error("Authentication failed. Please check your API key."):n===403?r.error("You do not have permission to perform this action."):n===404?r.error("Resource not found."):r.error(`API Error (${n}): ${s.message||Ne(s)}`)}else o.request?(r.error("No response received from the server. Please check your internet connection."),r.debug(`Request details: ${Ne(o.request).substring(0,200)}...`)):r.error(`Error: ${o.message}`);return Promise.reject(o)})}async get(e,o){try{return r.debug(`GET request to: ${e}`),(await this.client.get(e,o)).data}catch(n){throw r.debug(`GET request failed: ${n instanceof Error?n.message:String(n)}`),n}}async post(e,o,n){try{return r.debug(`POST request to: ${e}`),(await this.client.post(e,o,n)).data}catch(s){throw r.debug(`POST request failed: ${s instanceof Error?s.message:String(s)}`),s}}async put(e,o,n){try{return r.debug(`PUT request to: ${e}`),(await this.client.put(e,o,n)).data}catch(s){throw r.debug(`PUT request failed: ${s instanceof Error?s.message:String(s)}`),s}}async delete(e,o){try{return r.debug(`DELETE request to: ${e}`),(await this.client.delete(e,o)).data}catch(n){throw r.debug(`DELETE request failed: ${n instanceof Error?n.message:String(n)}`),n}}async patch(e,o,n){try{return r.debug(`PATCH request to: ${e}`),(await this.client.patch(e,o,n)).data}catch(s){throw r.debug(`PATCH request failed: ${s instanceof Error?s.message:String(s)}`),s}}};r.debug(`Initializing API client with URL: ${Fe}`);var T=new Oe(Fe);import{z as i}from"zod";import{INVALID as _r,ParseStatus as Sr,ZodIssueCode as J,ZodParsedType as it,ZodType as xr,addIssueToContext as X,z as at}from"zod";var Er="ZodDecimal",$r=/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,ae=class extends xr{_parse(e){if(e.data!==null&&typeof e.data=="object"&&"toNumber"in e.data&&(e.data=e.data.toNumber()),this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==it.number){let c=this._getOrReturnCtx(e);return X(c,{code:J.invalid_type,expected:it.number,received:c.parsedType}),_r}let n,s=new Sr;for(let c of this._def.checks)if(c.kind==="precision"){let a=e.data.toString().match($r);Math.max((a[1]?a[1].length:0)-(a[2]?parseInt(a[2],10):0),0)>c.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.custom,message:c.message,params:{precision:c.value}}),s.dirty())}else c.kind==="wholeNumber"?e.data.toString().split(".")[0].length>c.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.custom,message:c.message,params:{wholeNumber:c.value}}),s.dirty()):c.kind==="min"?(c.inclusive?e.data<c.value:e.data<=c.value)&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.too_small,minimum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),s.dirty()):c.kind==="max"?(c.inclusive?e.data>c.value:e.data>=c.value)&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.too_big,maximum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),s.dirty()):c.kind==="finite"&&(Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:J.not_finite,message:c.message}),s.dirty()));return{status:s.value,value:e.data}}setLimit(e,o,n,s){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:o,inclusive:n,message:s}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}lte(e,o){return this.setLimit("max",e,!0,o)}lt(e,o){return this.setLimit("max",e,!1,o)}max=this.lte;gt(e,o){return this.setLimit("min",e,!1,o)}gte(e,o){return this.setLimit("min",e,!0,o)}min=this.gte;precision(e,o){return this._addCheck({kind:"precision",value:e,message:o})}wholeNumber(e,o){return this._addCheck({kind:"wholeNumber",value:e,message:o})}get minValue(){let e=null;for(let o of this._def.checks)o.kind==="min"&&(e===null||o.value>e)&&(e=o.value);return e}get maxValue(){let e=null;for(let o of this._def.checks)o.kind==="max"&&(e===null||o.value<e)&&(e=o.value);return e}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e})}finite(e){return this._addCheck({kind:"finite",message:e})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e})}get isFinite(){let e=null,o=null;for(let n of this._def.checks){if(n.kind==="finite")return!0;n.kind==="min"?(o===null||n.value>o)&&(o=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(o)&&Number.isFinite(e)}},Q=ae;He(Q,"create",e=>new ae({checks:[],typeName:Er,coerce:e?.coerce??!1}));var ct=at.object({template:at.string().min(1,"Template cannot be empty")});var Tr=i.object({password:i.string(),registry:i.string().nullable(),username:i.string()}),Pr=i.object({docker_compose_file:i.string(),docker_config:Tr.optional(),features:i.array(i.string()),kms_enabled:i.boolean(),manifest_version:i.number(),name:i.string(),public_logs:i.boolean(),public_sysinfo:i.boolean(),runner:i.string().optional(),salt:i.string().nullable().optional(),tproxy_enabled:i.boolean(),version:i.string().optional()}),Ir=i.object({name:i.string(),image:i.string(),compose_file:Pr,vcpu:i.number(),memory:i.number(),disk_size:i.number(),ports:i.array(i.any())}),Dr=i.object({id:i.string(),name:i.string(),status:i.string(),uptime:i.string(),app_url:i.string(),app_id:i.string(),instance_id:i.string(),configuration:Ir,exited_at:i.string(),boot_progress:i.string(),boot_error:i.string(),shutdown_progress:i.string(),image_version:i.string()}),Ar=i.object({id:i.number(),username:i.string()}),Rr=i.object({id:i.number(),name:i.string()}),Ue=i.object({hosted:Dr,name:i.string(),managed_user:Ar,node:Rr,listed:i.boolean(),status:i.string(),in_progress:i.boolean(),dapp_dashboard_url:i.string().nullable(),syslog_endpoint:i.string(),allow_upgrade:i.boolean()}),ce=i.object({id:i.number(),name:i.string(),status:i.string(),teepod_id:i.number().nullable(),teepod:i.object({id:i.number(),name:i.string()}).nullable(),user_id:i.number(),app_id:i.string(),vm_uuid:i.string().nullable(),instance_id:i.string().nullable(),app_url:i.string().nullable(),base_image:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),manifest_version:i.number(),version:i.string(),runner:i.string(),docker_compose_file:i.string(),features:i.array(i.string()).nullable(),created_at:i.string(),encrypted_env_pubkey:i.string()}),mt=i.object({app_env_encrypt_pubkey:i.string(),app_id_salt:i.string()}),lt=i.object({id:i.number(),teepod_id:i.number().nullable(),teepod:i.object({id:i.number(),name:i.string()}).nullable(),name:i.string(),status:i.string(),in_progress:i.boolean(),app_id:i.string(),vm_uuid:i.string(),instance_id:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),base_image:i.string(),encrypted_env_pubkey:i.string(),listed:i.boolean(),project_id:i.string(),project_type:i.string().nullable()}),pt=i.object({username:i.string(),email:i.string(),credits:Q.create({coerce:!0}),granted_credits:Q.create({coerce:!0}),role:i.string(),avatar:i.string(),flag_reset_password:i.boolean(),team_name:i.string(),team_tier:i.string(),trial_ended_at:i.string().nullable()}),un=i.array(Ue),dt=i.object({detail:i.string()}),fn=i.object({key:i.string(),value:i.string()}),ut=i.object({name:i.string(),description:i.string().optional(),version:i.array(i.number()).optional(),is_dev:i.boolean().optional(),rootfs_hash:i.string().optional(),shared_ro:i.boolean().optional(),cmdline:i.string().optional(),kernel:i.string().optional(),initrd:i.string().optional(),hda:i.string().nullable().optional(),rootfs:i.string().optional(),bios:i.string().optional()}),Fr=i.object({teepod_id:i.number().nullable(),name:i.string(),listed:i.boolean(),resource_score:i.number(),remaining_vcpu:i.number(),remaining_memory:i.number(),remaining_cvm_slots:i.number(),images:i.array(ut).optional()}),Mr=i.object({max_instances:i.number().nullable(),max_vcpu:i.number().nullable(),max_memory:i.number().nullable(),max_disk:i.number().nullable()}),ft=i.object({tier:i.string(),capacity:Mr,nodes:i.array(Fr)}),Vr=i.object({is_online:i.boolean(),is_public:i.boolean(),error:i.string().nullable(),internal_ip:i.string(),latest_handshake:i.string(),public_urls:i.array(i.object({app:i.string(),instance:i.string()}))}),gt=i.object({is_online:i.boolean(),is_public:i.boolean(),error:i.string().nullable(),app_certificates:i.array(i.object({subject:i.object({common_name:i.string().nullable(),organization:i.string().nullable(),country:i.string().nullable(),state:i.string().nullable().optional(),locality:i.string().nullable().optional()}),issuer:i.object({common_name:i.string().nullable(),organization:i.string().nullable(),country:i.string().nullable()}),serial_number:i.string(),not_before:i.string(),not_after:i.string(),version:i.string(),fingerprint:i.string(),signature_algorithm:i.string(),sans:i.string().nullable(),is_ca:i.boolean(),position_in_chain:i.number(),quote:i.string().nullable()})).nullable(),tcb_info:i.object({mrtd:i.string(),rootfs_hash:i.string(),rtmr0:i.string(),rtmr1:i.string(),rtmr2:i.string(),rtmr3:i.string(),event_log:i.array(i.object({imr:i.number(),event_type:i.number(),digest:i.string(),event:i.string(),event_payload:i.string()}))}).nullable(),compose_file:i.string().nullable()});function ht(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}async function B(){try{r.debug(`Fetching user info from ${$.USER_INFO}`);let t=await T.get($.USER_INFO);r.debug(`Received response: ${ht(t)}`);try{return pt.parse(t)}catch(e){throw r.error(`Failed to parse user info response: ${e}`),r.debug(`Response structure: ${ht(t)}`),e}}catch(t){throw r.error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`),new Error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`)}}var yt=new Lr().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async t=>{try{let e;if(!t)t=(await Nr({type:"password",name:"apiKey",message:"Enter your API key:",validate:async n=>{if(n.length===0)return"API key cannot be empty";try{if(await Ae(n),e=await B(),!e.username)return await ie(),"Invalid API key"}catch{return"Invalid API key"}return!0}})).apiKey;else if(await Ae(t),e=await B(),!e.username)return await ie(),"Invalid API key";r.success(`Welcome ${e.username}! API key validated and saved successfully`),r.break(),r.info(`Open in Web UI at ${S}/dashboard/`)}catch(e){r.error(`Failed to set API key: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Or}from"commander";var bt=new Or().name("logout").description("Remove the stored API key").action(async()=>{try{await ie(),r.success("API key removed successfully")}catch(t){r.error(`Failed to remove API key: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Ur}from"commander";var vt=new Ur().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async t=>{try{t.debug&&(process.env.DEBUG="true");let e=await Y();if(!e){r.warn('Not authenticated. Please set an API key with "phala auth login"');return}r.debug(`Using API key: ${e.substring(0,5)}...`);let o=r.startSpinner("Checking authentication status");try{let n=await B();if(o.stop(!0),t.json){console.log(JSON.stringify(n,null,2));return}r.break(),r.success(`Authenticated as ${n.username}`);let s={Username:n.username,Email:n.email,Role:n.role,Team:`${n.team_name} (${n.team_tier})`,Credits:`${n.credits+n.granted_credits}`};n.trial_ended_at&&(s["Trial Ended At"]=n.trial_ended_at),r.keyValueTable(s,{borderStyle:"rounded"})}catch(n){o.stop(!1),r.error("Authentication failed. Your API key may be invalid or expired."),r.info('Please set a new API key with "phala auth login"'),t.debug&&r.debug(`Error details: ${n instanceof Error?n.message:String(n)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Ct=new zr().name("auth").description("Authenticate with Phala Cloud").addCommand(yt).addCommand(bt).addCommand(vt);import{Command as oo}from"commander";import{Command as Jr}from"commander";import{execa as Gr}from"execa";import O from"node:fs";import le from"node:path";import Kr from"handlebars";import{exec as qr,spawn as Hr}from"node:child_process";import{promisify as Zr}from"node:util";import xt from"node:os";import jr from"inquirer";import ze from"node:fs";import je from"node:path";function W(t,e=process.cwd()){let o=je.resolve(e,t);if(!ze.existsSync(o))throw new Error(`File not found at ${o}`);return!0}async function G(t,e,o="file",n=process.cwd()){return(await jr.prompt([{type:"input",name:o,message:t,default:e,validate:c=>{let a=je.resolve(n,c);return ze.existsSync(a)?!0:`File not found at ${a}`}}]))[o]}function ve(t,e){for(let o of t){let n=je.join(process.cwd(),o);if(ze.existsSync(n))return e?r.info(e.replace("{path}",n)):r.info(`File detected: ${n}`),o}}import*as R from"node:fs";import*as z from"node:path";import*as ee from"node:os";import{execSync as te,spawn as Br}from"node:child_process";import*as Be from"node:net";var D={version:"0.1.4",baseUrl:"https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4",installDir:z.join(ee.homedir(),".phala-cloud","tappd-simulator"),defaultLogPath:z.join(ee.homedir(),".phala-cloud","logs","tappd-simulator.log"),platforms:{darwin:{filename:"tappd-simulator-0.1.4-aarch64-apple-darwin.tgz",extractedFolder:"tappd-simulator-0.1.4-aarch64-apple-darwin",socketArg:"unix:/tmp/tappd.sock"},linux:{filename:"tappd-simulator-0.1.4-x86_64-linux-musl.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-linux-musl",socketArg:"unix:/tmp/tappd.sock"},win32:{filename:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc",socketArg:"127.0.0.1:8090"}}};function kt(){try{if(!R.existsSync(D.installDir))return!1;let t=ee.platform();if(!D.platforms[t])throw new Error(`Unsupported platform: ${t}`);let e=z.join(D.installDir,D.platforms[t].extractedFolder);if(!R.existsSync(e))return!1;let n=z.join(e,t==="win32"?"tappd-simulator.exe":"tappd-simulator");return R.existsSync(n)}catch(t){return r.error("Error checking if simulator is installed:",t),!1}}function me(){let t=ee.platform();if(!D.platforms[t])throw new Error(`Unsupported platform: ${t}. Only darwin, linux, and win32 are supported.`);return t}async function wt(t){let e=o=>{r.info(o),t&&t(o)};try{let o=me(),n=D.platforms[o];R.existsSync(D.installDir)||(r.info(`Creating installation directory at ${D.installDir}`),R.mkdirSync(D.installDir,{recursive:!0})),process.chdir(D.installDir);let s=`${D.baseUrl}/${n.filename}`;r.info(`Downloading simulator from ${s}`),te(`wget ${s}`,{stdio:"inherit"}),r.info(`Extracting ${n.filename}`),te(`tar -xvf ${n.filename}`,{stdio:"inherit"}),r.success("Simulator installation completed successfully")}catch(o){throw r.error("Error installing simulator:",o),new Error(`Failed to install simulator: ${o}`)}}async function _t(t={}){try{let e=me(),o=D.platforms[e],n=z.join(D.installDir,o.extractedFolder);process.chdir(n);let s=e==="win32"?"tappd-simulator.exe":"./tappd-simulator",c={background:t.background??!0,logToFile:t.logToFile??!0,logFilePath:t.logFilePath??D.defaultLogPath};if(c.logToFile){let f=z.dirname(c.logFilePath);R.existsSync(f)||R.mkdirSync(f,{recursive:!0}),r.info(`Simulator logs will be written to: ${c.logFilePath}`)}r.info(`Starting simulator with: ${s} -l ${o.socketArg}`);let a="inherit",p=null;c.logToFile&&(p=R.createWriteStream(c.logFilePath,{flags:"a"}),a=["ignore",p,p]);let h=Br(s,["-l",o.socketArg],{stdio:a,shell:e==="win32",detached:c.background});if(p){let f=new Date().toISOString();p.write(`
101
+ `;function Oe(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}var Ue=class{client;apiKey=null;constructor(e){r.debug(`Creating API client with base URL: ${e}`),this.client=_r.create({baseURL:e,headers:{"Content-Type":"application/json","User-Agent":`tee-cloud-cli/${rt}`}}),this.client.interceptors.request.use(async o=>{if(!this.apiKey){if(this.apiKey=await Y(),!this.apiKey)throw new Error('API key not found. Please set an API key first with "phala auth login"');r.debug(`API key loaded: ${this.apiKey.substring(0,5)}...`)}return o.headers["X-API-Key"]=this.apiKey,r.debug(`Making request to: ${o.baseURL}${o.url}`),o}),this.client.interceptors.response.use(o=>(r.debug(`Received successful response from: ${o.config.url}`),o),o=>{if(o.response){let{status:n,data:s}=o.response;r.debug(`Received error response: ${n} - ${Oe(s)}`),n===401?r.error("Authentication failed. Please check your API key."):n===403?r.error("You do not have permission to perform this action."):n===404?r.error("Resource not found."):r.error(`API Error (${n}): ${s.message||Oe(s)}`)}else o.request?(r.error("No response received from the server. Please check your internet connection."),r.debug(`Request details: ${Oe(o.request).substring(0,200)}...`)):r.error(`Error: ${o.message}`);return Promise.reject(o)})}async get(e,o){try{return r.debug(`GET request to: ${e}`),(await this.client.get(e,o)).data}catch(n){throw r.debug(`GET request failed: ${n instanceof Error?n.message:String(n)}`),n}}async post(e,o,n){try{return r.debug(`POST request to: ${e}`),(await this.client.post(e,o,n)).data}catch(s){throw r.debug(`POST request failed: ${s instanceof Error?s.message:String(s)}`),s}}async put(e,o,n){try{return r.debug(`PUT request to: ${e}`),(await this.client.put(e,o,n)).data}catch(s){throw r.debug(`PUT request failed: ${s instanceof Error?s.message:String(s)}`),s}}async delete(e,o){try{return r.debug(`DELETE request to: ${e}`),(await this.client.delete(e,o)).data}catch(n){throw r.debug(`DELETE request failed: ${n instanceof Error?n.message:String(n)}`),n}}async patch(e,o,n){try{return r.debug(`PATCH request to: ${e}`),(await this.client.patch(e,o,n)).data}catch(s){throw r.debug(`PATCH request failed: ${s instanceof Error?s.message:String(s)}`),s}}};r.debug(`Initializing API client with URL: ${Me}`);var T=new Ue(Me);import{z as i}from"zod";import{INVALID as Sr,ParseStatus as xr,ZodIssueCode as J,ZodParsedType as at,ZodType as Er,addIssueToContext as X,z as ct}from"zod";var $r="ZodDecimal",Tr=/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,ce=class extends Er{_parse(e){if(e.data!==null&&typeof e.data=="object"&&"toNumber"in e.data&&(e.data=e.data.toNumber()),this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==at.number){let c=this._getOrReturnCtx(e);return X(c,{code:J.invalid_type,expected:at.number,received:c.parsedType}),Sr}let n,s=new xr;for(let c of this._def.checks)if(c.kind==="precision"){let a=e.data.toString().match(Tr);Math.max((a[1]?a[1].length:0)-(a[2]?parseInt(a[2],10):0),0)>c.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.custom,message:c.message,params:{precision:c.value}}),s.dirty())}else c.kind==="wholeNumber"?e.data.toString().split(".")[0].length>c.value&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.custom,message:c.message,params:{wholeNumber:c.value}}),s.dirty()):c.kind==="min"?(c.inclusive?e.data<c.value:e.data<=c.value)&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.too_small,minimum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),s.dirty()):c.kind==="max"?(c.inclusive?e.data>c.value:e.data>=c.value)&&(n=this._getOrReturnCtx(e,n),X(n,{code:J.too_big,maximum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),s.dirty()):c.kind==="finite"&&(Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),X(n,{code:J.not_finite,message:c.message}),s.dirty()));return{status:s.value,value:e.data}}setLimit(e,o,n,s){return new ce({...this._def,checks:[...this._def.checks,{kind:e,value:o,inclusive:n,message:s}]})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}lte(e,o){return this.setLimit("max",e,!0,o)}lt(e,o){return this.setLimit("max",e,!1,o)}max=this.lte;gt(e,o){return this.setLimit("min",e,!1,o)}gte(e,o){return this.setLimit("min",e,!0,o)}min=this.gte;precision(e,o){return this._addCheck({kind:"precision",value:e,message:o})}wholeNumber(e,o){return this._addCheck({kind:"wholeNumber",value:e,message:o})}get minValue(){let e=null;for(let o of this._def.checks)o.kind==="min"&&(e===null||o.value>e)&&(e=o.value);return e}get maxValue(){let e=null;for(let o of this._def.checks)o.kind==="max"&&(e===null||o.value<e)&&(e=o.value);return e}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:e})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:e})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:e})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:e})}finite(e){return this._addCheck({kind:"finite",message:e})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:e})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:e})}get isFinite(){let e=null,o=null;for(let n of this._def.checks){if(n.kind==="finite")return!0;n.kind==="min"?(o===null||n.value>o)&&(o=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(o)&&Number.isFinite(e)}},Q=ce;Ze(Q,"create",e=>new ce({checks:[],typeName:$r,coerce:e?.coerce??!1}));var mt=ct.object({template:ct.string().min(1,"Template cannot be empty")});var Pr=i.object({password:i.string(),registry:i.string().nullable(),username:i.string()}),Ir=i.object({docker_compose_file:i.string(),docker_config:Pr.optional(),features:i.array(i.string()),kms_enabled:i.boolean(),manifest_version:i.number(),name:i.string(),public_logs:i.boolean(),public_sysinfo:i.boolean(),runner:i.string().optional(),salt:i.string().nullable().optional(),tproxy_enabled:i.boolean(),version:i.string().optional()}),Dr=i.object({name:i.string(),image:i.string(),compose_file:Ir,vcpu:i.number(),memory:i.number(),disk_size:i.number(),ports:i.array(i.any())}),Ar=i.object({id:i.string(),name:i.string(),status:i.string(),uptime:i.string(),app_url:i.string(),app_id:i.string(),instance_id:i.string(),configuration:Dr,exited_at:i.string(),boot_progress:i.string(),boot_error:i.string(),shutdown_progress:i.string(),image_version:i.string()}),Rr=i.object({id:i.number(),username:i.string()}),Fr=i.object({id:i.number(),name:i.string()}),ze=i.object({hosted:Ar,name:i.string(),managed_user:Rr,node:Fr,listed:i.boolean(),status:i.string(),in_progress:i.boolean(),dapp_dashboard_url:i.string().nullable(),syslog_endpoint:i.string(),allow_upgrade:i.boolean()}),me=i.object({id:i.number(),name:i.string(),status:i.string(),teepod_id:i.number().nullable(),teepod:i.object({id:i.number(),name:i.string()}).nullable(),user_id:i.number(),app_id:i.string(),vm_uuid:i.string().nullable(),instance_id:i.string().nullable(),app_url:i.string().nullable(),base_image:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),manifest_version:i.number(),version:i.string(),runner:i.string(),docker_compose_file:i.string(),features:i.array(i.string()).nullable(),created_at:i.string(),encrypted_env_pubkey:i.string()}),lt=i.object({app_env_encrypt_pubkey:i.string(),app_id_salt:i.string()}),pt=i.object({id:i.number(),teepod_id:i.number().nullable(),teepod:i.object({id:i.number(),name:i.string()}).nullable(),name:i.string(),status:i.string(),in_progress:i.boolean(),app_id:i.string(),vm_uuid:i.string(),instance_id:i.string(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),base_image:i.string(),encrypted_env_pubkey:i.string(),listed:i.boolean(),project_id:i.string(),project_type:i.string().nullable()}),dt=i.object({username:i.string(),email:i.string(),credits:Q.create({coerce:!0}),granted_credits:Q.create({coerce:!0}),role:i.string(),avatar:i.string(),flag_reset_password:i.boolean(),team_name:i.string(),team_tier:i.string(),trial_ended_at:i.string().nullable()}),fn=i.array(ze),ut=i.object({detail:i.string()}),gn=i.object({key:i.string(),value:i.string()}),ft=i.object({name:i.string(),description:i.string().optional(),version:i.array(i.number()).optional(),is_dev:i.boolean().optional(),rootfs_hash:i.string().optional(),shared_ro:i.boolean().optional(),cmdline:i.string().optional(),kernel:i.string().optional(),initrd:i.string().optional(),hda:i.string().nullable().optional(),rootfs:i.string().optional(),bios:i.string().optional()}),Mr=i.object({teepod_id:i.number().nullable(),name:i.string(),listed:i.boolean(),resource_score:i.number(),remaining_vcpu:i.number(),remaining_memory:i.number(),remaining_cvm_slots:i.number(),images:i.array(ft).optional()}),Vr=i.object({max_instances:i.number().nullable(),max_vcpu:i.number().nullable(),max_memory:i.number().nullable(),max_disk:i.number().nullable()}),gt=i.object({tier:i.string(),capacity:Vr,nodes:i.array(Mr)}),Lr=i.object({is_online:i.boolean(),is_public:i.boolean(),error:i.string().nullable(),internal_ip:i.string(),latest_handshake:i.string(),public_urls:i.array(i.object({app:i.string(),instance:i.string()}))}),ht=i.object({is_online:i.boolean(),is_public:i.boolean(),error:i.string().nullable(),app_certificates:i.array(i.object({subject:i.object({common_name:i.string().nullable(),organization:i.string().nullable(),country:i.string().nullable(),state:i.string().nullable().optional(),locality:i.string().nullable().optional()}),issuer:i.object({common_name:i.string().nullable(),organization:i.string().nullable(),country:i.string().nullable()}),serial_number:i.string(),not_before:i.string(),not_after:i.string(),version:i.string(),fingerprint:i.string(),signature_algorithm:i.string(),sans:i.string().nullable(),is_ca:i.boolean(),position_in_chain:i.number(),quote:i.string().nullable()})).nullable(),tcb_info:i.object({mrtd:i.string(),rootfs_hash:i.string(),rtmr0:i.string(),rtmr1:i.string(),rtmr2:i.string(),rtmr3:i.string(),event_log:i.array(i.object({imr:i.number(),event_type:i.number(),digest:i.string(),event:i.string(),event_payload:i.string()}))}).nullable(),compose_file:i.string().nullable()});function yt(t){try{return JSON.stringify(t)}catch(e){return e instanceof Error&&e.message.includes("cyclic")?"[Cyclic Object]":String(t)}}async function B(){try{r.debug(`Fetching user info from ${E.USER_INFO}`);let t=await T.get(E.USER_INFO);r.debug(`Received response: ${yt(t)}`);try{return dt.parse(t)}catch(e){throw r.error(`Failed to parse user info response: ${e}`),r.debug(`Response structure: ${yt(t)}`),e}}catch(t){throw r.error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`),new Error(`Failed to get user info: ${t instanceof Error?t.message:String(t)}`)}}var bt=new Nr().name("login").description("Set the API key for authentication").argument("[api-key]","Phala Cloud API key to set").action(async t=>{try{let e;if(!t)t=(await Or({type:"password",name:"apiKey",message:"Enter your API key:",validate:async n=>{if(n.length===0)return"API key cannot be empty";try{if(await Re(n),e=await B(),!e.username)return await ie(),"Invalid API key"}catch{return"Invalid API key"}return!0}})).apiKey;else if(await Re(t),e=await B(),!e.username)return await ie(),"Invalid API key";r.success(`Welcome ${e.username}! API key validated and saved successfully`),r.break(),r.info(`Open in Web UI at ${S}/dashboard/`)}catch(e){r.error(`Failed to set API key: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Ur}from"commander";var vt=new Ur().name("logout").description("Remove the stored API key").action(async()=>{try{await ie(),r.success("API key removed successfully")}catch(t){r.error(`Failed to remove API key: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as zr}from"commander";var Ct=new zr().name("status").description("Check authentication status").option("-j, --json","Output in JSON format").option("-d, --debug","Enable debug output").action(async t=>{try{t.debug&&(process.env.DEBUG="true");let e=await Y();if(!e){r.warn('Not authenticated. Please set an API key with "phala auth login"');return}r.debug(`Using API key: ${e.substring(0,5)}...`);let o=r.startSpinner("Checking authentication status");try{let n=await B();if(o.stop(!0),t.json){console.log(JSON.stringify(n,null,2));return}r.break(),r.success(`Authenticated as ${n.username}`);let s={Username:n.username,Email:n.email,Role:n.role,Team:`${n.team_name} (${n.team_tier})`,Credits:`$${(n.credits+n.granted_credits).toFixed(2)}`};n.trial_ended_at&&(s["Trial Ended At"]=n.trial_ended_at),r.keyValueTable(s,{borderStyle:"rounded"})}catch(n){o.stop(!1),r.error("Authentication failed. Your API key may be invalid or expired."),r.info('Please set a new API key with "phala auth login"'),t.debug&&r.debug(`Error details: ${n instanceof Error?n.message:String(n)}`)}}catch(e){r.error(`Failed to check authentication status: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var kt=new jr().name("auth").description("Authenticate with Phala Cloud").addCommand(bt).addCommand(vt).addCommand(Ct);import{Command as no}from"commander";import{Command as Xr}from"commander";import{execa as Kr}from"execa";import O from"node:fs";import pe from"node:path";import qr from"handlebars";import{exec as Hr,spawn as Zr}from"node:child_process";import{promisify as Yr}from"node:util";import Et from"node:os";import Br from"inquirer";import je from"node:fs";import Be from"node:path";function W(t,e=process.cwd()){let o=Be.resolve(e,t);if(!je.existsSync(o))throw new Error(`File not found at ${o}`);return!0}async function G(t,e,o="file",n=process.cwd()){return(await Br.prompt([{type:"input",name:o,message:t,default:e,validate:c=>{let a=Be.resolve(n,c);return je.existsSync(a)?!0:`File not found at ${a}`}}]))[o]}function Ce(t,e){for(let o of t){let n=Be.join(process.cwd(),o);if(je.existsSync(n))return e?r.info(e.replace("{path}",n)):r.info(`File detected: ${n}`),o}}import*as R from"node:fs";import*as z from"node:path";import*as ee from"node:os";import{execSync as te,spawn as Wr}from"node:child_process";import*as We from"node:net";var D={version:"0.1.4",baseUrl:"https://github.com/Leechael/tappd-simulator/releases/download/v0.1.4",installDir:z.join(ee.homedir(),".phala-cloud","tappd-simulator"),defaultLogPath:z.join(ee.homedir(),".phala-cloud","logs","tappd-simulator.log"),platforms:{darwin:{filename:"tappd-simulator-0.1.4-aarch64-apple-darwin.tgz",extractedFolder:"tappd-simulator-0.1.4-aarch64-apple-darwin",socketArg:"unix:/tmp/tappd.sock"},linux:{filename:"tappd-simulator-0.1.4-x86_64-linux-musl.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-linux-musl",socketArg:"unix:/tmp/tappd.sock"},win32:{filename:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc.tgz",extractedFolder:"tappd-simulator-0.1.4-x86_64-pc-windows-msvc",socketArg:"127.0.0.1:8090"}}};function wt(){try{if(!R.existsSync(D.installDir))return!1;let t=ee.platform();if(!D.platforms[t])throw new Error(`Unsupported platform: ${t}`);let e=z.join(D.installDir,D.platforms[t].extractedFolder);if(!R.existsSync(e))return!1;let n=z.join(e,t==="win32"?"tappd-simulator.exe":"tappd-simulator");return R.existsSync(n)}catch(t){return r.error("Error checking if simulator is installed:",t),!1}}function le(){let t=ee.platform();if(!D.platforms[t])throw new Error(`Unsupported platform: ${t}. Only darwin, linux, and win32 are supported.`);return t}async function _t(t){let e=o=>{r.info(o),t&&t(o)};try{let o=le(),n=D.platforms[o];R.existsSync(D.installDir)||(r.info(`Creating installation directory at ${D.installDir}`),R.mkdirSync(D.installDir,{recursive:!0})),process.chdir(D.installDir);let s=`${D.baseUrl}/${n.filename}`;r.info(`Downloading simulator from ${s}`),te(`wget ${s}`,{stdio:"inherit"}),r.info(`Extracting ${n.filename}`),te(`tar -xvf ${n.filename}`,{stdio:"inherit"}),r.success("Simulator installation completed successfully")}catch(o){throw r.error("Error installing simulator:",o),new Error(`Failed to install simulator: ${o}`)}}async function St(t={}){try{let e=le(),o=D.platforms[e],n=z.join(D.installDir,o.extractedFolder);process.chdir(n);let s=e==="win32"?"tappd-simulator.exe":"./tappd-simulator",c={background:t.background??!0,logToFile:t.logToFile??!0,logFilePath:t.logFilePath??D.defaultLogPath};if(c.logToFile){let f=z.dirname(c.logFilePath);R.existsSync(f)||R.mkdirSync(f,{recursive:!0}),r.info(`Simulator logs will be written to: ${c.logFilePath}`)}r.info(`Starting simulator with: ${s} -l ${o.socketArg}`);let a="inherit",p=null;c.logToFile&&(p=R.createWriteStream(c.logFilePath,{flags:"a"}),a=["ignore",p,p]);let y=Wr(s,["-l",o.socketArg],{stdio:a,shell:e==="win32",detached:c.background});if(p){let f=new Date().toISOString();p.write(`
102
102
  [${f}] Simulator started
103
- `)}return c.background&&(h.unref(),r.success("Simulator is running in the background")),await We(),h}catch(e){throw r.error("Error running simulator:",e),new Error(`Failed to run simulator: ${e}`)}}async function Ce(){try{let t=me(),e=D.platforms[t];if(t==="darwin"||t==="linux"){let o="/tmp/tappd.sock";return R.existsSync(o)?new Promise(n=>{let s=Be.createConnection({path:o}).on("connect",()=>{s.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{s.end(),n(!1)},1e3)}):!1}if(t==="win32"){let o="127.0.0.1";return new Promise(s=>{let c=Be.createConnection({host:o,port:8090}).on("connect",()=>{c.end(),s(!0)}).on("error",()=>{s(!1)});setTimeout(()=>{c.end(),s(!1)},1e3)})}return!1}catch(t){return r.error("Error checking if simulator is running:",t),!1}}async function St(){try{let t=me();if(!await Ce())return r.info("Simulator is not running"),!0;r.info("Stopping simulator..."),t==="win32"?te(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :8080') do taskkill /F /PID %a`,{stdio:"inherit"}):te("pkill -f tappd-simulator",{stdio:"inherit"});let e=!await Ce();return e?r.success("Simulator stopped successfully"):r.error("Failed to stop simulator"),await K(),e}catch(t){return r.error("Error stopping simulator:",t),!1}}function Wr(){return me()==="win32"?"http://127.0.0.1:8090":"unix:///tmp/tappd.sock"}async function We(t){try{let e=Wr(),o=t||e;return await te(`export DSTACK_SIMULATOR_ENDPOINT=${o}`),r.success(`Setting DSTACK_SIMULATOR_ENDPOINT=${o} for current process`),t}catch(e){throw r.error("Error setting simulator endpoint environment variable:",e),new Error(`Failed to set simulator endpoint: ${e}`)}}async function K(){return await te("unset DSTACK_SIMULATOR_ENDPOIN"),r.success("Deleted DSTACK_SIMULATOR_ENDPOINT from current process"),!0}var pe=Zr(qr),Et=".phala-cloud/logs",Yr=".phala-cloud/compose",$t=10,P=class{username;image;registry;constructor(e,o,n){this.image=e,this.username=o||"",this.registry=n||""}ensureLogsDir(){let e=le.resolve(Et);O.existsSync(e)||O.mkdirSync(e,{recursive:!0})}getLogFilePath(e,o){let n=new Date().toISOString().replace(/[:.]/g,"-");return le.resolve(Et,`${o||this.image}-${e}-${n}.log`)}getSystemArchitecture(){let e=xt.arch();switch(e){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return e}}spawnProcess(e,o,n,s){return new Promise((c,a)=>{let p=Hr(e,o);this.ensureLogsDir();let h=this.getLogFilePath(n,s),f=O.createWriteStream(h,{flags:"a"}),C=[],k=(m,l=!1)=>{let u=m.toString().split(`
104
- `);f.write(m);for(let g of u)if(g.trim()){C.push(g),C.length>$t&&C.shift(),console.clear(),console.log(`Latest ${$t} lines (full log at ${h}):`),console.log("-".repeat(50));for(let b of C)l?console.error(b):console.log(b)}};p.stdout.on("data",m=>k(m)),p.stderr.on("data",m=>k(m,!0)),p.on("close",m=>{f.end(),m===0?(console.log(`
105
- Operation completed. Full log available at: ${h}`),c()):a(new Error(`Process exited with code ${m}. Check log file: ${h}`))}),p.on("error",m=>{f.end(),a(m)})})}setCredentials(e,o){this.username=e,o&&(this.registry=o)}async buildImage(e,o){try{let n=this.getSystemArchitecture(),s=`${this.username}/${this.image}:${o}`,c=r.startSpinner(`Building Docker image ${this.username}/${this.image}:${o}`);W(e);let a=["build","-t",s,"-f",e];return n==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),a.push("--platform","linux/amd64")),a.push("."),await this.spawnProcess("docker",a,"build",this.image),c.stop(!0,`Docker image ${s} built successfully`),!0}catch(n){return r.error(`Failed to build Docker image: ${n instanceof Error?n.message:String(n)}`),!1}}async pushImage(e){try{let o=r.startSpinner(`Pushing Docker image ${e} to Docker Hub`);if(!await N())throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let s=e;return console.log(`Pushing image ${s} to Docker Hub...`),await this.spawnProcess("docker",["push",s],"push",e.replace(/.*\/+(\w+):.*$/g,"$1")),o.stop(!0,`Docker image ${s} pushed successfully`),!0}catch(o){return r.error(`Failed to push Docker image: ${o instanceof Error?o.message:String(o)}`),!1}}async login(e,o,n){try{let s=r.startSpinner(`Logging in to Docker Hub as ${e}`);if(await this.checkLogin())return s.stop(!0,"Already logged in to Docker Hub"),this.setCredentials(e,n),!0;if(!o)throw s.stop(!1),new Error("Password is required for Docker login");try{await Gr("docker",["login",...n?[n]:[],"-u",e,"--password-stdin"],{input:o,timeout:1e4})}catch(a){throw a.timedOut?(s.stop(!1),new Error("Docker login timed out. Please check your credentials and try again.")):a}return s.stop(!0,"Logged in to Docker Hub successfully"),this.setCredentials(e,n),!0}catch(s){return r.error(`Failed to login to Docker Hub: ${s instanceof Error?s.message:String(s)}`),!1}}async checkLogin(){try{let e=xt.homedir(),o=le.join(e,".docker","config.json");if(!O.existsSync(o))return!1;let n=JSON.parse(O.readFileSync(o,"utf-8"));return!!(n?.auths&&Object.keys(n.auths).length>0)}catch(e){return r.debug(`Docker login check failed: ${e instanceof Error?e.message:String(e)}`),!1}}async buildComposeFile(e,o,n){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let s=n==="eliza"?nt:st,c=ct.parse({template:s}),a=le.resolve(Yr);O.existsSync(a)||(r.info(`Creating directory: ${a}`),O.mkdirSync(a,{recursive:!0}));let p=[];o&&(p=O.readFileSync(o,"utf-8").split(`
106
- `).filter(l=>l&&!l.startsWith("#")).map(l=>{let u=l.indexOf("#");return u>0&&(l=l.substring(0,u).trim()),l.trim()}).filter(l=>l.includes("=")).map(l=>{let[u,g]=l.split("=",2),b=u.trim();return(g?g.trim():"")===""?null:`${b}=${b}`}).filter(Boolean));let h=e,C=Kr.compile(c.template,{noEscape:!0})({imageName:h,envVars:p.map(m=>m.replace(/=.*/,`=\${${m.split("=")[0]}}`))}),k=le.join(a,`${e.replace(/.*\/+(\w+):.*$/g,"$1")}-tee-compose.yaml`);return O.writeFileSync(k,C),r.success(`Backup of docker compose file created at: ${k}`),k}async runComposeLocally(e,o){try{let n=r.startSpinner(`Running Docker Compose file at ${e}`);W(e);let s=["-f",e,"up","-d"];return o&&(W(o),s.splice(2,0,"--env-file",o)),await pe(`docker compose ${s.join(" ")}`),n.stop(!0,"Docker Compose file running successfully"),!0}catch(n){return r.error(`Failed to run Docker Compose file: ${n instanceof Error?n.message:String(n)}`),!1}}async runSimulator(e,o){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await pe(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:n}=await pe(`docker run -d --name tee-simulator --rm -p ${o}:${o} ${e}`),s=n.trim();return r.success(`TEE simulator running successfully. Container ID: ${s}`),r.break(),r.break(),r.info("Useful commands:"),r.info(`- View logs: docker logs -f ${s}`),r.info(`- Stop simulator: docker stop ${s}`),We(`http://localhost:${o}`),!0}catch(n){return r.error(`Failed to run TEE simulator: ${n instanceof Error?n.message:String(n)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await pe("docker stop tee-simulator"),await K(),e.stop(!0,"TEE simulator stopped successfully"),!0}catch(e){return r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),!1}}static async listLocalImages(){try{let{stdout:e}=await pe('docker images --format "{{.Repository}}:{{.Tag}}"'),n=(await N())?.username;return e.split(`
107
- `).filter(c=>c&&!c.includes("<none>")).filter(c=>c.includes(`${n}/`)).map(c=>({imageName:c}))}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import Tt from"prompts";var Pt=new Jr().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async t=>{try{let e=t.username,o=t.password,n=t.registry;if(!e){r.info("First we need your Docker Hub username to check if you are already logged in.");let p=await Tt({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:h=>h.length>0?!0:"Username cannot be empty"});p.username||(r.error("Username is required"),process.exit(1)),e=p.username}let s=new P("",e,n);if(await s.login(e)){r.success(`${e} is logged in to Docker Hub`),await Re({username:e,registry:n||null});return}if(!o){let p=await Tt({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:h=>h.length>0?!0:"Password cannot be empty"});p.password||(r.error("Password is required"),process.exit(1)),o=p.password}await s.login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await Re({username:e,registry:n||null}),r.success("Logged in to Docker Hub successfully")}catch(e){r.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Xr}from"commander";import It from"node:path";import Dt from"inquirer";import Qr from"node:fs";var At=new Xr().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async t=>{try{let e=await N();if(e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let a=await Dt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:p=>p.trim()?!0:"Image name is required"}]);t.image=a.image}if(!t.tag){let a=await Dt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:p=>p.trim()?!0:"Tag is required"}]);t.tag=a.tag}let o=It.resolve(process.cwd(),t.file);Qr.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await G("Enter the path to your Dockerfile:","Dockerfile","file"));let n=It.resolve(process.cwd(),t.file);await new P(t.image,e.username,e.registry).buildImage(n,t.tag)||(r.error("Failed to build Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){r.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as eo}from"commander";import to from"inquirer";var Rt=new eo().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Full image name (e.g. username/image:tag)").action(async t=>{try{let e=await N();e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image;if(!o){let c=await P.listLocalImages();if(c.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let a=Array.from(new Set(c.map(h=>h.imageName))),{selectedImage:p}=await to.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:a}]);o=p}}await new P("",e.username,e.registry).pushImage(o)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${o} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as ro}from"commander";import de from"inquirer";import ue from"node:fs";import ke from"node:path";var Ft=new ro().name("generate").description("Generate a Docker Compose file").option("-i, --image <imageName>","Docker image name to use in the compose file (e.g. phala/phala-cloud)").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").action(async t=>{try{let e=await N();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let o=t.image;if(!o){let p=await P.listLocalImages();if(p.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let h=Array.from(new Set(p.map(C=>C.imageName))),{selectedImage:f}=await de.prompt([{type:"list",name:"selectedImage",message:"Select an image to use in the compose file:",choices:h}]);o=f}}let n=t.envFile;if(n)try{W(n)}catch{r.error(`File not found: ${n}`),process.exit(1)}else{let p=ke.join(process.cwd(),".env");if(ue.existsSync(p)){let{useDefault:f}=await de.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);f&&(n=p)}if(!n){let{envPath:f}=await de.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:C=>{try{return W(C),!0}catch{return`File not found: ${C}`}}}]);n=f}}let s=t.output;if(!s&&(s=ke.join(process.cwd(),"docker-compose.yml"),ue.existsSync(s))){let{confirmOverwrite:p}=await de.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${s} already exists. Overwrite?`,default:!1}]);if(!p){let{customPath:h}=await de.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:ke.join(process.cwd(),"docker-generated-compose.yml")}]);s=h}}let c=new P("",e.username,e.registry);n?r.info(`Generating Docker Compose file for ${o} using env file: ${n}`):r.info(`Generating Docker Compose file for ${o} without env file`);let a=await c.buildComposeFile(o,n,t.template);if(a!==s){let p=ke.dirname(s);ue.existsSync(p)||(r.info(`Creating directory: ${p}`),ue.mkdirSync(p,{recursive:!0})),ue.copyFileSync(a,s)}r.success(`Docker Compose file generated successfully: ${s}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Mt=new oo().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(Pt).addCommand(At).addCommand(Rt).addCommand(Ft);import{Command as io}from"commander";import{Command as no}from"commander";var Vt=new no().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",rt).option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{if(t.type==="docker")await new P("").runSimulator(t.image,t.port)||(r.error("Failed to start TEE simulator"),process.exit(1));else if(t.type==="native")if(kt()||await wt(),await Ce()){r.success("TEE simulator is already running");return}else{let o=_t();r.success("TEE simulator started successfully")}else r.error("Invalid simulator type"),process.exit(1)}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as so}from"commander";var Lt=new so().name("stop").description("Stop the TEE simulator").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{t.type==="docker"?await new P("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1)):t.type==="native"?await St()||(r.error("Failed to stop TEE simulator"),process.exit(1)):(r.error("Invalid simulator type"),process.exit(1))}catch(e){r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Nt=new io().name("simulator").description("TEE simulator commands").addCommand(Vt).addCommand(Lt);import{Command as xo}from"commander";import{Command as co}from"commander";import ao from"inquirer";import{z as Ot}from"zod";async function we(){try{let t=await T.get($.CVMS(0));return Ot.array(Ue).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function _e(t){let o=(await we()).find(n=>n.hosted?.app_id===t||`app_${n.hosted?.app_id}`===t);if(!o)r.error(`CVM with App ID app_${t} not detected`),process.exit(1);else return r.success(`CVM with App ID app_${t} detected`),o.hosted?.app_id||""}async function re(t){try{let e=await T.get($.CVM_BY_APP_ID(t));return lt.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function Se(t){try{let e=await T.post($.CVM_PUBKEY,t);return mt.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function xe(t){try{let e=await T.post($.CVM_FROM_CONFIGURATION,t);return ce.parse(e)}catch(e){throw e instanceof Ot.ZodError?(r.error("Schema validation error:",JSON.stringify(e.errors,null,2)),r.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ut(t){try{let e=await T.post($.CVM_START(t));return ce.parse(e)}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function zt(t){try{let e=await T.post($.CVM_STOP(t));return ce.parse(e)}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function jt(t){try{let e=await T.post($.CVM_RESTART(t));return ce.parse(e)}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Bt(t,e){try{let o=await T.put($.CVM_UPGRADE(t),e);return dt.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Wt(t){try{return await T.delete($.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ee(){let t=r.startSpinner("Fetching available CVMs"),e=await we();if(t.stop(!0),!e||e.length===0){r.info("No CVMs found for your account");return}let o=e.map(s=>{let c=s.hosted?.app_id||s.hosted?.id,a=s.name||s.hosted?.name,p=s.status||s.hosted?.status;return{name:`${a||"Unnamed"} (${c}) - Status: ${p||"Unknown"}`,value:c}}),{selectedCvm:n}=await ao.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:o}]);return n}async function Gt(t){try{let e=await T.get($.CVM_ATTESTATION(t));try{return gt.parse(e)}catch(o){return r.debug(`Validation error: ${o instanceof Error?o.message:String(o)}`),{is_online:!!e?.is_online,is_public:!!e?.is_public,error:typeof e?.error=="string"?e.error:null,app_certificates:Array.isArray(e?.app_certificates)?e.app_certificates:null,tcb_info:e?.tcb_info||null,compose_file:typeof e?.compose_file=="string"?e.compose_file:null}}}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function Kt(t,e,o,n,s){try{let c={};if(e!==void 0&&(c.vcpu=e),o!==void 0&&(c.memory=o),n!==void 0&&(c.disk_size=n),s!==void 0&&(c.allow_restart=s),Object.keys(c).length===0)throw new Error("At least one resource parameter must be provided");return await T.patch($.CVM_RESIZE(t),c),!0}catch(c){throw new Error(`Failed to resize CVM: ${c instanceof Error?c.message:String(c)}`)}}import Ge from"chalk";var qt=new co().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await we();if(e.stop(!0),!o||o.length===0){r.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(o,null,2));return}for(let n of o)r.keyValueTable({Name:n.name,"App ID":`app_${n.hosted.app_id}`,Status:n.status==="running"?Ge.green(n.status):n.status==="stopped"?Ge.red(n.status):Ge.yellow(n.status),"Node Info URL":n.hosted.app_url,"App URL":`${S}/dashboard/cvms/app_${n.hosted.app_id}`}),r.break();r.success(`Found ${o.length} CVMs`),r.break(),r.info(`Go to ${S}/dashboard/ to view your CVMs`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as mo}from"commander";import Ke from"chalk";async function A(t){if(!t){let e=await Ee();return e||void 0}return await _e(t)}var Ht=new mo().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o=await A(t),n=r.startSpinner(`Fetching CVM with App ID app_${o}`),s=await re(o);if(n.stop(!0),r.break(),s||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),e.json){console.log(JSON.stringify(s,null,2));return}r.keyValueTable({Name:s.name,"App ID":`app_${s.app_id}`,Status:s.status==="running"?Ke.green(s.status):s.status==="stopped"?Ke.red(s.status):Ke.yellow(s.status),vCPU:s.vcpu,Memory:`${s.memory} MB`,"Disk Size":`${s.disk_size} GB`,"Dstack Image":s.base_image,"App URL":`${S}/dashboard/cvms/app_${s.app_id}`})}catch(o){r.error(`Failed to get CVM details: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as lo}from"commander";var Zt=new lo().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Starting CVM with App ID app_${e}`),n=await Ut(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being started. You can check the dashboard for more details:
108
- ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as po}from"commander";var Yt=new po().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Stopping CVM with App ID app_${e}`),n=await zt(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being stopped. You can check the dashboard for more details:
109
- ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as uo}from"commander";var Jt=new uo().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Restarting CVM with App ID app_${e}`),n=await jt(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`,"App URL":n.app_url?n.app_url:`${S}/dashboard/cvms/app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being restarted. You can check the dashboard for more details:
110
- ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as fo}from"commander";import $e from"chalk";var Xt=new fo().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o;if(t)o=await _e(t);else{r.info("No CVM specified, fetching available CVMs...");let s=await Ee();if(!s)return;o=s}let n=r.startSpinner(`Fetching attestation information for CVM app_${o}...`);try{let s=await Gt(o);if(n.stop(!0),!s||Object.keys(s).length===0){r.info("No attestation information found");return}if(e?.json){r.info(JSON.stringify(s,null,2));return}r.success("Attestation Summary:");let c={Status:s.is_online?$e.green("Online"):$e.red("Offline"),"Public Access":s.is_public?$e.green("Enabled"):$e.yellow("Disabled"),Error:s.error||"None",Certificates:`${s.app_certificates?.length||0} found`};if(r.keyValueTable(c,{borderStyle:"rounded"}),s.app_certificates&&s.app_certificates.length>0&&s.app_certificates.forEach((a,p)=>{r.break(),r.success(`Certificate #${p+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let h={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};r.keyValueTable(h,{borderStyle:"rounded"})}),s.tcb_info){r.break(),r.success("Trusted Computing Base (TCB) Information:");let a={Mrtd:s.tcb_info.mrtd,"Rootfs Hash":s.tcb_info.rootfs_hash,Rtmr0:s.tcb_info.rtmr0,Rtmr1:s.tcb_info.rtmr1,Rtmr2:s.tcb_info.rtmr2,Rtmr3:s.tcb_info.rtmr3,"Event Log Entries":`${s.tcb_info.event_log.length} entries`};if(r.keyValueTable(a,{borderStyle:"rounded"}),s.tcb_info.event_log&&s.tcb_info.event_log.length>0){r.break(),r.success("Event Log (Showing entries to reproduce RTMR3):");let p=5,h=s.tcb_info.event_log.filter(f=>f.event!==null&&f.event!=="").map(f=>({Event:f.event,IMR:f.imr.toString(),"Event Type":f.event_type.toString(),Payload:f.event_payload}));r.table(h,[{key:"Event",header:"Event",minWidth:8},{key:"IMR",header:"IMR",minWidth:3},{key:"Event Type",header:"Type",minWidth:8},{key:"Payload",header:"Payload",minWidth:25}]),s.tcb_info.event_log.length>p&&r.info("To see all full attestation data, use --json"),r.break(),r.success("To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/")}}}catch(s){throw n.stop(!1),s}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as ho}from"commander";import{z as ha}from"zod";async function Qt(){try{let t=await T.get($.TEEPODS);return ft.parse(t).nodes}catch(t){throw new Error(`Failed to get TEEPods: ${t instanceof Error?t.message:String(t)}`)}}import{encryptEnvVars as yo}from"@phala/dstack-sdk/encrypt-env-vars";import er from"node:fs";import bo from"node:path";import tr from"inquirer";import go from"node:fs";var q=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[s,c]=n.split("=");s&&c&&(o[s]=c)}}if(e){let n=go.readFileSync(e,"utf8");for(let s of n.split(`
111
- `))if(!(!s.trim()||s.trim().startsWith("#"))&&s.includes("=")){let[c,...a]=s.split("="),p=a.join("="),h=p.search(/\s+#/);h!==-1&&(p=p.substring(0,h).trim()),c&&p&&(o[c.trim()]=p.trim())}}return Object.entries(o).map(([n,s])=>({key:n,value:s}))};var rr=new ho().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>",`Number of vCPUs, default is ${Me}`).option("--memory <memory>",`Memory in MB, default is ${Ve}`).option("--disk-size <diskSize>",`Disk size in GB, default is ${Le}`).option("--teepod-id <teepodId>","TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.").option("--image <image>","Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.").option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async t=>{try{if(!t.name){let{name:y}=await tr.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:x=>x.trim()?x.trim().length>20?"CVM name must be less than 20 characters":x.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test(x)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);t.name=y}if(!t.compose){let x=ve(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await G("Enter the path to your Docker Compose file:",x,"file")}let e=bo.resolve(t.compose);er.existsSync(e)||(r.error(`Docker Compose file not found: ${e}`),process.exit(1));let o=er.readFileSync(e,"utf8");await K();let n=[];if(t.envFile)try{n=q([],t.envFile)}catch(y){r.error(`Failed to read environment file: ${y instanceof Error?y.message:String(y)}`),process.exit(1)}else if(!t.skipEnv){let{shouldSkip:y}=await tr.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!0}]);if(y)r.info("Skipping environment variable prompt");else{let x=await G("Enter the path to your environment file:",".env","file");n=q([],x)}}let s=Number(t.vcpu)||Me,c=Number(t.memory)||Ve,a=Number(t.diskSize)||Le;(isNaN(s)||s<=0)&&(r.error(`Invalid number of vCPUs: ${s}`),process.exit(1)),(isNaN(c)||c<=0)&&(r.error(`Invalid memory: ${c}`),process.exit(1)),(isNaN(a)||a<=0)&&(r.error(`Invalid disk size: ${a}`),process.exit(1));let p=r.startSpinner("Fetching available TEEPods"),h=await Qt();p.stop(!0),h.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let f;t.teepodId?(f=h.find(y=>y.teepod_id===t.teepodId),f||(r.error("Failed to find selected TEEPod"),process.exit(1))):f=h[0];let C;t.image?f.images?.find(x=>x.name===t.image)||(r.error(`Failed to find selected image: ${t.image}`),process.exit(1)):C=f.images[0];let k={teepod_id:f.teepod_id,name:t.name,image:C.name,vcpu:s,memory:c,disk_size:a,compose_manifest:{docker_compose_file:o,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:t.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},m=r.startSpinner("Getting public key from CVM"),l=await Se(k);m.stop(!0),l||(r.error("Failed to get public key from CVM"),process.exit(1));let u=r.startSpinner("Encrypting environment variables"),g=await yo(n,l.app_env_encrypt_pubkey);u.stop(!0),t.debug&&(r.debug("Public key:",l.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",g),r.debug("Environment variables:",JSON.stringify(n)));let b=r.startSpinner("Creating CVM"),d=await xe({...k,encrypted_env:g,app_env_encrypt_pubkey:l.app_env_encrypt_pubkey,app_id_salt:l.app_id_salt});b.stop(!0),d||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.break();let v={"CVM ID":d.id,Name:d.name,Status:d.status,"App ID":`app_${d.app_id}`,"App URL":d.app_url?d.app_url:`${S}/dashboard/cvms/app_${d.app_id}`};r.keyValueTable(v,{borderStyle:"rounded"}),r.info(""),r.success(`Your CVM is being created. You can check its status with:
112
- phala cvms get app_${d.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as vo}from"commander";import Co from"inquirer";var or=new vo().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(t,e)=>{try{let o=await A(t);if(!e.force){let{confirm:c}=await Co.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID app_${o}? This action cannot be undone.`,default:!1}]);if(!c){r.info("Deletion cancelled");return}}let n=r.startSpinner(`Deleting CVM app_${o}`),s=await Wt(o);n.stop(!0),s||(r.error(`Failed to delete CVM app_${o}`),process.exit(1)),r.success(`CVM app_${o} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as ko}from"commander";import wo from"node:fs";import{encryptEnvVars as _o}from"@phala/dstack-sdk/encrypt-env-vars";var nr=new ko().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(t,e)=>{try{let o=await A(t),n=r.startSpinner(`Fetching current configuration for CVM app_${o}`),s=await re(o);if(n.stop(!0),s||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),!e.compose){let k=ve(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");e.compose=await G("Enter the path to your Docker Compose file:",k,"file")}let c="";if(e.compose)try{c=wo.readFileSync(e.compose,"utf8")}catch(C){r.error(`Failed to read Docker Compose file: ${C instanceof Error?C.message:String(C)}`),process.exit(1)}await K();let a="";if(e.envFile){let C=[];if(e.envFile)try{C=q([],e.envFile),a=await _o(C,s.encrypted_env_pubkey)}catch(k){r.error(`Failed to read environment file: ${k instanceof Error?k.message:String(k)}`),process.exit(1)}}let p={compose_manifest:{docker_compose_file:c,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${o}`},encrypted_env:a,allow_restart:!0},h=r.startSpinner(`Upgrading CVM app_${o}`),f=await Bt(o,p);f||(h.stop(!1),r.error("Failed to upgrade CVM"),process.exit(1)),h.stop(!0),f.detail&&r.info(`Details: ${f.detail}`),r.break(),r.success(`Your CVM is being upgraded. You can check the dashboard for more details:
113
- ${S}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as So}from"commander";import fe from"inquirer";import j from"chalk";var sr=new So().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(t,e)=>{try{let o=await A(t),n=await re(o),s=e.vcpu,c=e.memory,a=e.diskSize,p=e.allowRestart;s||(s=(await fe.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.vcpu,filter:m=>parseInt(m)}])).vcpu),c||(c=(await fe.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.memory,filter:m=>parseInt(m)}])).memory),a||(a=(await fe.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.disk_size,filter:m=>parseInt(m)}])).diskSize),p||(p=(await fe.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let h=`Are you sure you want to resize CVM app_${o} with the following changes:
114
- `;if(r.keyValueTable({vCPUs:n.vcpu!==s?`${j.red(n.vcpu)} -> ${j.green(s)}`:n.vcpu,Memory:n.memory!==c?`${j.red(n.memory)} MB -> ${j.green(c)} MB`:n.memory,"Disk Size":n.disk_size!==a?`${j.red(n.disk_size)} GB -> ${j.green(a)} GB`:n.disk_size,"Allow Restart":p?j.green("Yes"):j.red("No")}),!e.yes){let{confirm:k}=await fe.prompt([{type:"confirm",name:"confirm",message:h,default:!1}]);if(!k){r.info("Resize operation cancelled");return}}let f=r.startSpinner(`Resizing CVM with App ID app_${o}`);await Kt(o,s,c,a,p?1:0),f.stop(!0),r.break(),r.success(`Your CVM is being resized. You can check the dashboard for more details:
115
- ${S}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var ir=new xo().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(Xt).addCommand(rr).addCommand(or).addCommand(Ht).addCommand(qt).addCommand(Zt).addCommand(Yt).addCommand(sr).addCommand(Jt).addCommand(nr);import{Command as Eo}from"commander";import{execSync as ge}from"node:child_process";import*as cr from"node:os";function $o(t){let e=cr.platform();try{switch(e){case"darwin":ge(`open "${t}"`);break;case"win32":ge(`start "" "${t}"`);break;case"linux":try{ge(`xdg-open "${t}"`)}catch{try{ge(`gnome-open "${t}"`)}catch{ge(`kde-open "${t}"`)}}break;default:throw new Error(`Unsupported platform: ${e}`)}r.success(`Opened URL in your default browser: ${t}`)}catch(o){r.error(`Failed to open URL: ${o instanceof Error?o.message:String(o)}`),r.info(`Please manually open this URL in your browser: ${t}`)}}function ar(t){return new Promise(e=>setTimeout(e,t))}var mr=new Eo().name("join").alias("free").description("Join Phala Cloud! Get an account and deploy a CVM for FREE").action(async()=>{try{let t="https://cloud.phala.network/register?invite=PHALACLI",e=r.startSpinner("Brewing a fresh cup of TEE \u{1F375}");await ar(2e3),e.stop(!0),r.break(),r.break(),console.log(ye),r.info("TEE is served! Opening Phala Cloud registration page..."),await ar(1e3),r.break(),$o(t)}catch(t){r.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Io}from"commander";var To=`version: '3'
103
+ `)}return c.background&&(y.unref(),r.success("Simulator is running in the background")),await Ge(),y}catch(e){throw r.error("Error running simulator:",e),new Error(`Failed to run simulator: ${e}`)}}async function ke(){try{let t=le(),e=D.platforms[t];if(t==="darwin"||t==="linux"){let o="/tmp/tappd.sock";return R.existsSync(o)?new Promise(n=>{let s=We.createConnection({path:o}).on("connect",()=>{s.end(),n(!0)}).on("error",()=>{n(!1)});setTimeout(()=>{s.end(),n(!1)},1e3)}):!1}if(t==="win32"){let o="127.0.0.1";return new Promise(s=>{let c=We.createConnection({host:o,port:8090}).on("connect",()=>{c.end(),s(!0)}).on("error",()=>{s(!1)});setTimeout(()=>{c.end(),s(!1)},1e3)})}return!1}catch(t){return r.error("Error checking if simulator is running:",t),!1}}async function xt(){try{let t=le();if(!await ke())return r.info("Simulator is not running"),!0;r.info("Stopping simulator..."),t==="win32"?te(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :8080') do taskkill /F /PID %a`,{stdio:"inherit"}):te("pkill -f tappd-simulator",{stdio:"inherit"});let e=!await ke();return e?r.success("Simulator stopped successfully"):r.error("Failed to stop simulator"),await K(),e}catch(t){return r.error("Error stopping simulator:",t),!1}}function Gr(){return le()==="win32"?"http://127.0.0.1:8090":"unix:///tmp/tappd.sock"}async function Ge(t){try{let e=Gr(),o=t||e;return await te(`export DSTACK_SIMULATOR_ENDPOINT=${o}`),r.success(`Setting DSTACK_SIMULATOR_ENDPOINT=${o} for current process`),t}catch(e){throw r.error("Error setting simulator endpoint environment variable:",e),new Error(`Failed to set simulator endpoint: ${e}`)}}async function K(){return await te("unset DSTACK_SIMULATOR_ENDPOIN"),r.success("Deleted DSTACK_SIMULATOR_ENDPOINT from current process"),!0}var de=Yr(Hr),$t=".phala-cloud/logs",Jr=".phala-cloud/compose",Tt=10,P=class{username;image;registry;constructor(e,o,n){this.image=e,this.username=o||"",this.registry=n||""}ensureLogsDir(){let e=pe.resolve($t);O.existsSync(e)||O.mkdirSync(e,{recursive:!0})}getLogFilePath(e,o){let n=new Date().toISOString().replace(/[:.]/g,"-");return pe.resolve($t,`${o||this.image}-${e}-${n}.log`)}getSystemArchitecture(){let e=Et.arch();switch(e){case"arm":case"arm64":return"arm64";case"x64":return"amd64";default:return e}}spawnProcess(e,o,n,s){return new Promise((c,a)=>{let p=Zr(e,o);this.ensureLogsDir();let y=this.getLogFilePath(n,s),f=O.createWriteStream(y,{flags:"a"}),v=[],k=(m,l=!1)=>{let u=m.toString().split(`
104
+ `);f.write(m);for(let g of u)if(g.trim()){v.push(g),v.length>Tt&&v.shift(),console.clear(),console.log(`Latest ${Tt} lines (full log at ${y}):`),console.log("-".repeat(50));for(let b of v)l?console.error(b):console.log(b)}};p.stdout.on("data",m=>k(m)),p.stderr.on("data",m=>k(m,!0)),p.on("close",m=>{f.end(),m===0?(console.log(`
105
+ Operation completed. Full log available at: ${y}`),c()):a(new Error(`Process exited with code ${m}. Check log file: ${y}`))}),p.on("error",m=>{f.end(),a(m)})})}setCredentials(e,o){this.username=e,o&&(this.registry=o)}async buildImage(e,o){try{let n=this.getSystemArchitecture(),s=`${this.username}/${this.image}:${o}`,c=r.startSpinner(`Building Docker image ${this.username}/${this.image}:${o}`);W(e);let a=["build","-t",s,"-f",e];return n==="arm64"&&(console.log("Detected arm64 architecture, using --platform linux/amd64"),a.push("--platform","linux/amd64")),a.push("."),await this.spawnProcess("docker",a,"build",this.image),c.stop(!0,`Docker image ${s} built successfully`),!0}catch(n){return r.error(`Failed to build Docker image: ${n instanceof Error?n.message:String(n)}`),!1}}async pushImage(e){try{let o=r.startSpinner(`Pushing Docker image ${e} to Docker Hub`);if(!await N())throw o.stop(!1),new Error('Docker credentials not found. Please log in first with "phala docker login"');let s=e;return console.log(`Pushing image ${s} to Docker Hub...`),await this.spawnProcess("docker",["push",s],"push",e.replace(/.*\/+([\w-]+):.*$/g,"$1")),o.stop(!0,`Docker image ${s} pushed successfully`),!0}catch(o){return r.error(`Failed to push Docker image: ${o instanceof Error?o.message:String(o)}`),!1}}async login(e,o,n){try{let s=r.startSpinner(`Logging in to Docker Hub as ${e}`);if(await this.checkLogin())return s.stop(!0,"Already logged in to Docker Hub"),this.setCredentials(e,n),!0;if(!o)throw s.stop(!1),new Error("Password is required for Docker login");try{await Kr("docker",["login",...n?[n]:[],"-u",e,"--password-stdin"],{input:o,timeout:1e4})}catch(a){throw a.timedOut?(s.stop(!1),new Error("Docker login timed out. Please check your credentials and try again.")):a}return s.stop(!0,"Logged in to Docker Hub successfully"),this.setCredentials(e,n),!0}catch(s){return r.error(`Failed to login to Docker Hub: ${s instanceof Error?s.message:String(s)}`),!1}}async checkLogin(){try{let e=Et.homedir(),o=pe.join(e,".docker","config.json");if(!O.existsSync(o))return!1;let n=JSON.parse(O.readFileSync(o,"utf-8"));return!!(n?.auths&&Object.keys(n.auths).length>0)}catch(e){return r.debug(`Docker login check failed: ${e instanceof Error?e.message:String(e)}`),!1}}async buildComposeFile(e,o,n){if(!this.username)throw new Error("Docker Hub username is required for building compose file");let s=n==="eliza"?st:it,c=mt.parse({template:s}),a=pe.resolve(Jr);O.existsSync(a)||(r.info(`Creating directory: ${a}`),O.mkdirSync(a,{recursive:!0}));let p=[];o&&(p=O.readFileSync(o,"utf-8").split(`
106
+ `).filter(l=>l&&!l.startsWith("#")).map(l=>{let u=l.indexOf("#");return u>0&&(l=l.substring(0,u).trim()),l.trim()}).filter(l=>l.includes("=")).map(l=>{let[u,g]=l.split("=",2),b=u.trim();return(g?g.trim():"")===""?null:`${b}=${b}`}).filter(Boolean));let y=e,v=qr.compile(c.template,{noEscape:!0})({imageName:y,envVars:p.map(m=>m.replace(/=.*/,`=\${${m.split("=")[0]}}`))}),k=pe.join(a,`${e.replace(/.*\/+([\w-]+):.*$/g,"$1")}-tee-compose.yaml`);return O.writeFileSync(k,v),r.success(`Backup of docker compose file created at: ${k}`),k}async runComposeLocally(e,o){try{let n=r.startSpinner(`Running Docker Compose file at ${e}`);W(e);let s=["-f",e,"up","-d"];return o&&(W(o),s.splice(2,0,"--env-file",o)),await de(`docker compose ${s.join(" ")}`),n.stop(!0,"Docker Compose file running successfully"),!0}catch(n){return r.error(`Failed to run Docker Compose file: ${n instanceof Error?n.message:String(n)}`),!1}}async runSimulator(e,o){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await de(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:n}=await de(`docker run -d --name tee-simulator --rm -p ${o}:${o} ${e}`),s=n.trim();return r.success(`TEE simulator running successfully. Container ID: ${s}`),r.break(),r.break(),r.info("Useful commands:"),r.info(`- View logs: docker logs -f ${s}`),r.info(`- Stop simulator: docker stop ${s}`),Ge(`http://localhost:${o}`),!0}catch(n){return r.error(`Failed to run TEE simulator: ${n instanceof Error?n.message:String(n)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await de("docker stop tee-simulator"),await K(),e.stop(!0,"TEE simulator stopped successfully"),!0}catch(e){return r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),!1}}static async listLocalImages(){try{let{stdout:e}=await de('docker images --format "{{.Repository}}:{{.Tag}}"'),n=(await N())?.username;return e.split(`
107
+ `).filter(c=>c&&!c.includes("<none>")).filter(c=>c.includes(`${n}/`)).map(c=>({imageName:c}))}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import Pt from"prompts";var It=new Xr().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async t=>{try{let e=t.username,o=t.password,n=t.registry;if(!e){r.info("First we need your Docker Hub username to check if you are already logged in.");let p=await Pt({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:y=>y.length>0?!0:"Username cannot be empty"});p.username||(r.error("Username is required"),process.exit(1)),e=p.username}let s=new P("",e,n);if(await s.login(e)){r.success(`${e} is logged in to Docker Hub`),await Fe({username:e,registry:n||null});return}if(!o){let p=await Pt({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:y=>y.length>0?!0:"Password cannot be empty"});p.password||(r.error("Password is required"),process.exit(1)),o=p.password}await s.login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await Fe({username:e,registry:n||null}),r.success("Logged in to Docker Hub successfully")}catch(e){r.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Qr}from"commander";import Dt from"node:path";import At from"inquirer";import eo from"node:fs";var Rt=new Qr().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async t=>{try{let e=await N();if(e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let a=await At.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:p=>p.trim()?!0:"Image name is required"}]);t.image=a.image}if(!t.tag){let a=await At.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:p=>p.trim()?!0:"Tag is required"}]);t.tag=a.tag}let o=Dt.resolve(process.cwd(),t.file);eo.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await G("Enter the path to your Dockerfile:","Dockerfile","file"));let n=Dt.resolve(process.cwd(),t.file);await new P(t.image,e.username,e.registry).buildImage(n,t.tag)||(r.error("Failed to build Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){r.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as to}from"commander";import ro from"inquirer";var Ft=new to().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Full image name (e.g. username/image:tag)").action(async t=>{try{let e=await N();e||(r.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image;if(!o){let c=await P.listLocalImages();if(c.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let a=Array.from(new Set(c.map(y=>y.imageName))),{selectedImage:p}=await ro.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:a}]);o=p}}await new P("",e.username,e.registry).pushImage(o)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${o} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as oo}from"commander";import ue from"inquirer";import fe from"node:fs";import we from"node:path";var Mt=new oo().name("generate").description("Generate a Docker Compose file").option("-i, --image <imageName>","Docker image name to use in the compose file (e.g. phala/phala-cloud)").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").action(async t=>{try{let e=await N();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let o=t.image;if(!o){let p=await P.listLocalImages();if(p.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let y=Array.from(new Set(p.map(v=>v.imageName))),{selectedImage:f}=await ue.prompt([{type:"list",name:"selectedImage",message:"Select an image to use in the compose file:",choices:y}]);o=f}}let n=t.envFile;if(n)try{W(n)}catch{r.error(`File not found: ${n}`),process.exit(1)}else{let p=we.join(process.cwd(),".env");if(fe.existsSync(p)){let{useDefault:f}=await ue.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);f&&(n=p)}if(!n){let{envPath:f}=await ue.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:v=>{try{return W(v),!0}catch{return`File not found: ${v}`}}}]);n=f}}let s=t.output;if(!s&&(s=we.join(process.cwd(),"docker-compose.yml"),fe.existsSync(s))){let{confirmOverwrite:p}=await ue.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${s} already exists. Overwrite?`,default:!1}]);if(!p){let{customPath:y}=await ue.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:we.join(process.cwd(),"docker-generated-compose.yml")}]);s=y}}let c=new P("",e.username,e.registry);n?r.info(`Generating Docker Compose file for ${o} using env file: ${n}`):r.info(`Generating Docker Compose file for ${o} without env file`);let a=await c.buildComposeFile(o,n,t.template);if(a!==s){let p=we.dirname(s);fe.existsSync(p)||(r.info(`Creating directory: ${p}`),fe.mkdirSync(p,{recursive:!0})),fe.copyFileSync(a,s)}r.success(`Docker Compose file generated successfully: ${s}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Vt=new no().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(It).addCommand(Rt).addCommand(Ft).addCommand(Mt);import{Command as ao}from"commander";import{Command as so}from"commander";var Lt=new so().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",ot).option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{if(t.type==="docker")await new P("").runSimulator(t.image,t.port)||(r.error("Failed to start TEE simulator"),process.exit(1));else if(t.type==="native")if(wt()||await _t(),await ke()){r.success("TEE simulator is already running");return}else{let o=St();r.success("TEE simulator started successfully")}else r.error("Invalid simulator type"),process.exit(1)}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as io}from"commander";var Nt=new io().name("stop").description("Stop the TEE simulator").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{t.type==="docker"?await new P("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1)):t.type==="native"?await xt()||(r.error("Failed to stop TEE simulator"),process.exit(1)):(r.error("Invalid simulator type"),process.exit(1))}catch(e){r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Ot=new ao().name("simulator").description("TEE simulator commands").addCommand(Lt).addCommand(Nt);import{Command as Eo}from"commander";import{Command as mo}from"commander";import co from"inquirer";import{z as Ut}from"zod";async function _e(){try{let t=await T.get(E.CVMS(0));return Ut.array(ze).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function Se(t){let o=(await _e()).find(n=>n.hosted?.app_id===t||`app_${n.hosted?.app_id}`===t);if(!o)r.error(`CVM with App ID app_${t} not detected`),process.exit(1);else return r.success(`CVM with App ID app_${t} detected`),o.hosted?.app_id||""}async function re(t){try{let e=await T.get(E.CVM_BY_APP_ID(t));return pt.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function xe(t){try{let e=await T.post(E.CVM_PUBKEY,t);return lt.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Ee(t){try{let e=await T.post(E.CVM_FROM_CONFIGURATION,t);return me.parse(e)}catch(e){throw e instanceof Ut.ZodError?(r.error("Schema validation error:",JSON.stringify(e.errors,null,2)),r.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function zt(t){try{let e=await T.post(E.CVM_START(t));return me.parse(e)}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function jt(t){try{let e=await T.post(E.CVM_STOP(t));return me.parse(e)}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Bt(t){try{let e=await T.post(E.CVM_RESTART(t));return me.parse(e)}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Wt(t,e){try{let o=await T.put(E.CVM_UPGRADE(t),e);return ut.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Gt(t){try{return await T.delete(E.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function $e(){let t=r.startSpinner("Fetching available CVMs"),e=await _e();if(t.stop(!0),!e||e.length===0){r.info("No CVMs found for your account");return}let o=e.map(s=>{let c=s.hosted?.app_id||s.hosted?.id,a=s.name||s.hosted?.name,p=s.status||s.hosted?.status;return{name:`${a||"Unnamed"} (${c}) - Status: ${p||"Unknown"}`,value:c}}),{selectedCvm:n}=await co.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:o}]);return n}async function Kt(t){try{let e=await T.get(E.CVM_ATTESTATION(t));try{return ht.parse(e)}catch(o){return r.debug(`Validation error: ${o instanceof Error?o.message:String(o)}`),{is_online:!!e?.is_online,is_public:!!e?.is_public,error:typeof e?.error=="string"?e.error:null,app_certificates:Array.isArray(e?.app_certificates)?e.app_certificates:null,tcb_info:e?.tcb_info||null,compose_file:typeof e?.compose_file=="string"?e.compose_file:null}}}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function qt(t,e,o,n,s){try{let c={};if(e!==void 0&&(c.vcpu=e),o!==void 0&&(c.memory=o),n!==void 0&&(c.disk_size=n),s!==void 0&&(c.allow_restart=s),Object.keys(c).length===0)throw new Error("At least one resource parameter must be provided");return await T.patch(E.CVM_RESIZE(t),c),!0}catch(c){throw new Error(`Failed to resize CVM: ${c instanceof Error?c.message:String(c)}`)}}import Ke from"chalk";var Ht=new mo().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await _e();if(e.stop(!0),!o||o.length===0){r.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(o,null,2));return}for(let n of o)r.keyValueTable({Name:n.name,"App ID":`app_${n.hosted.app_id}`,Status:n.status==="running"?Ke.green(n.status):n.status==="stopped"?Ke.red(n.status):Ke.yellow(n.status),"Node Info URL":n.hosted.app_url,"App URL":`${S}/dashboard/cvms/app_${n.hosted.app_id}`}),r.break();r.success(`Found ${o.length} CVMs`),r.break(),r.info(`Go to ${S}/dashboard/ to view your CVMs`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as lo}from"commander";import qe from"chalk";async function A(t){if(!t){let e=await $e();return e||void 0}return await Se(t)}var Zt=new lo().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o=await A(t),n=r.startSpinner(`Fetching CVM with App ID app_${o}`),s=await re(o);if(n.stop(!0),r.break(),s||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),e.json){console.log(JSON.stringify(s,null,2));return}r.keyValueTable({Name:s.name,"App ID":`app_${s.app_id}`,Status:s.status==="running"?qe.green(s.status):s.status==="stopped"?qe.red(s.status):qe.yellow(s.status),vCPU:s.vcpu,Memory:`${s.memory} MB`,"Disk Size":`${s.disk_size} GB`,"Dstack Image":s.base_image,"App URL":`${S}/dashboard/cvms/app_${s.app_id}`})}catch(o){r.error(`Failed to get CVM details: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as po}from"commander";var Yt=new po().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Starting CVM with App ID app_${e}`),n=await zt(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being started. You can check the dashboard for more details:
108
+ ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as uo}from"commander";var Jt=new uo().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Stopping CVM with App ID app_${e}`),n=await jt(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being stopped. You can check the dashboard for more details:
109
+ ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as fo}from"commander";var Xt=new fo().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{let e=await A(t),o=r.startSpinner(`Restarting CVM with App ID app_${e}`),n=await Bt(e);o.stop(!0),r.break();let s={"CVM ID":n.id,Name:n.name,Status:n.status,"App ID":`app_${n.app_id}`,"App URL":n.app_url?n.app_url:`${S}/dashboard/cvms/app_${n.app_id}`};r.keyValueTable(s,{borderStyle:"rounded"}),r.break(),r.success(`Your CVM is being restarted. You can check the dashboard for more details:
110
+ ${S}/dashboard/cvms/app_${n.app_id}`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as go}from"commander";import Te from"chalk";var Qt=new go().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{let o;if(t)o=await Se(t);else{r.info("No CVM specified, fetching available CVMs...");let s=await $e();if(!s)return;o=s}let n=r.startSpinner(`Fetching attestation information for CVM app_${o}...`);try{let s=await Kt(o);if(n.stop(!0),!s||Object.keys(s).length===0){r.info("No attestation information found");return}if(e?.json){r.info(JSON.stringify(s,null,2));return}r.success("Attestation Summary:");let c={Status:s.is_online?Te.green("Online"):Te.red("Offline"),"Public Access":s.is_public?Te.green("Enabled"):Te.yellow("Disabled"),Error:s.error||"None",Certificates:`${s.app_certificates?.length||0} found`};if(r.keyValueTable(c,{borderStyle:"rounded"}),s.app_certificates&&s.app_certificates.length>0&&s.app_certificates.forEach((a,p)=>{r.break(),r.success(`Certificate #${p+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let y={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};r.keyValueTable(y,{borderStyle:"rounded"})}),s.tcb_info){r.break(),r.success("Trusted Computing Base (TCB) Information:");let a={Mrtd:s.tcb_info.mrtd,"Rootfs Hash":s.tcb_info.rootfs_hash,Rtmr0:s.tcb_info.rtmr0,Rtmr1:s.tcb_info.rtmr1,Rtmr2:s.tcb_info.rtmr2,Rtmr3:s.tcb_info.rtmr3,"Event Log Entries":`${s.tcb_info.event_log.length} entries`};if(r.keyValueTable(a,{borderStyle:"rounded"}),s.tcb_info.event_log&&s.tcb_info.event_log.length>0){r.break(),r.success("Event Log (Showing entries to reproduce RTMR3):");let p=5,y=s.tcb_info.event_log.filter(f=>f.event!==null&&f.event!=="").map(f=>({Event:f.event,IMR:f.imr.toString(),"Event Type":f.event_type.toString(),Payload:f.event_payload}));r.table(y,[{key:"Event",header:"Event",minWidth:8},{key:"IMR",header:"IMR",minWidth:3},{key:"Event Type",header:"Type",minWidth:8},{key:"Payload",header:"Payload",minWidth:25}]),s.tcb_info.event_log.length>p&&r.info("To see all full attestation data, use --json"),r.break(),r.success("To reproduce RTMR3, use the tool at https://rtmr3-calculator.vercel.app/")}}}catch(s){throw n.stop(!1),s}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as yo}from"commander";import{z as ya}from"zod";async function er(){try{let t=await T.get(E.TEEPODS);return gt.parse(t).nodes}catch(t){throw new Error(`Failed to get TEEPods: ${t instanceof Error?t.message:String(t)}`)}}import{encryptEnvVars as bo}from"@phala/dstack-sdk/encrypt-env-vars";import tr from"node:fs";import vo from"node:path";import rr from"inquirer";import ho from"node:fs";var q=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[s,c]=n.split("=");s&&c&&(o[s]=c)}}if(e){let n=ho.readFileSync(e,"utf8");for(let s of n.split(`
111
+ `))if(!(!s.trim()||s.trim().startsWith("#"))&&s.includes("=")){let[c,...a]=s.split("="),p=a.join("="),y=p.search(/\s+#/);y!==-1&&(p=p.substring(0,y).trim()),c&&p&&(o[c.trim()]=p.trim())}}return Object.entries(o).map(([n,s])=>({key:n,value:s}))};var or=new yo().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>",`Number of vCPUs, default is ${Ve}`).option("--memory <memory>",`Memory in MB, default is ${Le}`).option("--disk-size <diskSize>",`Disk size in GB, default is ${Ne}`).option("--teepod-id <teepodId>","TEEPod ID to use. If not provided, it will be selected from the list of available TEEPods.").option("--image <image>","Version of dstack image to use. If not provided, it will be selected from the list of available images for the selected TEEPod.").option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async t=>{try{if(!t.name){let{name:h}=await rr.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:$=>$.trim()?$.trim().length>20?"CVM name must be less than 20 characters":$.trim().length<3?"CVM name must be at least 3 characters":/^[a-zA-Z0-9_-]+$/.test($)?!0:"CVM name must contain only letters, numbers, underscores, and hyphens":"CVM name is required"}]);t.name=h}if(!t.compose){let $=Ce(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await G("Enter the path to your Docker Compose file:",$,"file")}let e=vo.resolve(t.compose);tr.existsSync(e)||(r.error(`Docker Compose file not found: ${e}`),process.exit(1));let o=tr.readFileSync(e,"utf8");await K();let n=[];if(t.envFile)try{n=q([],t.envFile)}catch(h){r.error(`Failed to read environment file: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}else if(!t.skipEnv){let{shouldSkip:h}=await rr.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!0}]);if(h)r.info("Skipping environment variable prompt");else{let $=await G("Enter the path to your environment file:",".env","file");n=q([],$)}}let s=Number(t.vcpu)||Ve,c=Number(t.memory)||Le,a=Number(t.diskSize)||Ne;(Number.isNaN(s)||s<=0)&&(r.error(`Invalid number of vCPUs: ${s}`),process.exit(1)),(Number.isNaN(c)||c<=0)&&(r.error(`Invalid memory: ${c}`),process.exit(1)),(Number.isNaN(a)||a<=0)&&(r.error(`Invalid disk size: ${a}`),process.exit(1));let p=r.startSpinner("Fetching available TEEPods"),y=await er();p.stop(!0),y.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let f;t.teepodId?(f=y.find(h=>h.teepod_id===Number(t.teepodId)),f||(r.error("Failed to find selected TEEPod"),process.exit(1))):(f=y.find(h=>h.teepod_id===Number(nt)),f||(r.error("Failed to find default TEEPod"),process.exit(1)));let v;t.image?(v=f.images?.find(h=>h.name===t.image),v||(r.error(`Failed to find selected image: ${t.image}`),process.exit(1))):(v=f.images?.find(h=>h.name===ae),v||(r.error(`Failed to find default image ${ae}`),process.exit(1)));let k={teepod_id:f.teepod_id,name:t.name,image:v.name,vcpu:s,memory:c,disk_size:a,compose_manifest:{docker_compose_file:o,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:t.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},m=r.startSpinner("Getting public key from CVM"),l=await xe(k);m.stop(!0),l||(r.error("Failed to get public key from CVM"),process.exit(1));let u=r.startSpinner("Encrypting environment variables"),g=await bo(n,l.app_env_encrypt_pubkey);u.stop(!0),t.debug&&(r.debug("Public key:",l.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",g),r.debug("Environment variables:",JSON.stringify(n)));let b=r.startSpinner("Creating CVM"),d=await Ee({...k,encrypted_env:g,app_env_encrypt_pubkey:l.app_env_encrypt_pubkey,app_id_salt:l.app_id_salt});b.stop(!0),d||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.break();let C={"CVM ID":d.id,Name:d.name,Status:d.status,"App ID":`app_${d.app_id}`,"App URL":d.app_url?d.app_url:`${S}/dashboard/cvms/app_${d.app_id}`};r.keyValueTable(C,{borderStyle:"rounded"}),r.info(""),r.success(`Your CVM is being created. You can check its status with:
112
+ phala cvms get app_${d.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Co}from"commander";import ko from"inquirer";var nr=new Co().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(t,e)=>{try{let o=await A(t);if(!e.force){let{confirm:c}=await ko.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID app_${o}? This action cannot be undone.`,default:!1}]);if(!c){r.info("Deletion cancelled");return}}let n=r.startSpinner(`Deleting CVM app_${o}`),s=await Gt(o);n.stop(!0),s||(r.error(`Failed to delete CVM app_${o}`),process.exit(1)),r.success(`CVM app_${o} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as wo}from"commander";import _o from"node:fs";import{encryptEnvVars as So}from"@phala/dstack-sdk/encrypt-env-vars";var sr=new wo().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(t,e)=>{try{let o=await A(t),n=r.startSpinner(`Fetching current configuration for CVM app_${o}`),s=await re(o);if(n.stop(!0),s||(r.error(`CVM with App ID app_${o} not found`),process.exit(1)),!e.compose){let k=Ce(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");e.compose=await G("Enter the path to your Docker Compose file:",k,"file")}let c="";if(e.compose)try{c=_o.readFileSync(e.compose,"utf8")}catch(v){r.error(`Failed to read Docker Compose file: ${v instanceof Error?v.message:String(v)}`),process.exit(1)}await K();let a="";if(e.envFile){let v=[];if(e.envFile)try{v=q([],e.envFile),a=await So(v,s.encrypted_env_pubkey)}catch(k){r.error(`Failed to read environment file: ${k instanceof Error?k.message:String(k)}`),process.exit(1)}}let p={compose_manifest:{docker_compose_file:c,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${o}`},encrypted_env:a,allow_restart:!0},y=r.startSpinner(`Upgrading CVM app_${o}`),f=await Wt(o,p);f||(y.stop(!1),r.error("Failed to upgrade CVM"),process.exit(1)),y.stop(!0),f.detail&&r.info(`Details: ${f.detail}`),r.break(),r.success(`Your CVM is being upgraded. You can check the dashboard for more details:
113
+ ${S}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as xo}from"commander";import ge from"inquirer";import j from"chalk";var ir=new xo().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(t,e)=>{try{let o=await A(t),n=await re(o),s=e.vcpu,c=e.memory,a=e.diskSize,p=e.allowRestart;s||(s=(await ge.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.vcpu,filter:m=>parseInt(m)}])).vcpu),c||(c=(await ge.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.memory,filter:m=>parseInt(m)}])).memory),a||(a=(await ge.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:m=>{let l=parseInt(m);return isNaN(l)||l<0?"Please enter a valid non-negative number":!0},default:n.disk_size,filter:m=>parseInt(m)}])).diskSize),p||(p=(await ge.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let y=`Are you sure you want to resize CVM app_${o} with the following changes:
114
+ `;if(r.keyValueTable({vCPUs:n.vcpu!==s?`${j.red(n.vcpu)} -> ${j.green(s)}`:n.vcpu,Memory:n.memory!==c?`${j.red(n.memory)} MB -> ${j.green(c)} MB`:n.memory,"Disk Size":n.disk_size!==a?`${j.red(n.disk_size)} GB -> ${j.green(a)} GB`:n.disk_size,"Allow Restart":p?j.green("Yes"):j.red("No")}),!e.yes){let{confirm:k}=await ge.prompt([{type:"confirm",name:"confirm",message:y,default:!1}]);if(!k){r.info("Resize operation cancelled");return}}let f=r.startSpinner(`Resizing CVM with App ID app_${o}`);await qt(o,s,c,a,p?1:0),f.stop(!0),r.break(),r.success(`Your CVM is being resized. You can check the dashboard for more details:
115
+ ${S}/dashboard/cvms/app_${o}`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var ar=new Eo().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(Qt).addCommand(or).addCommand(nr).addCommand(Zt).addCommand(Ht).addCommand(Yt).addCommand(Jt).addCommand(ir).addCommand(Xt).addCommand(sr);import{Command as $o}from"commander";import{execSync as he}from"node:child_process";import*as mr from"node:os";function To(t){let e=mr.platform();try{switch(e){case"darwin":he(`open "${t}"`);break;case"win32":he(`start "" "${t}"`);break;case"linux":try{he(`xdg-open "${t}"`)}catch{try{he(`gnome-open "${t}"`)}catch{he(`kde-open "${t}"`)}}break;default:throw new Error(`Unsupported platform: ${e}`)}r.success(`Opened URL in your default browser: ${t}`)}catch(o){r.error(`Failed to open URL: ${o instanceof Error?o.message:String(o)}`),r.info(`Please manually open this URL in your browser: ${t}`)}}function cr(t){return new Promise(e=>setTimeout(e,t))}var lr=new $o().name("join").alias("free").description("Join Phala Cloud! Get an account and deploy a CVM for FREE").action(async()=>{try{let t="https://cloud.phala.network/register?invite=beta",e=r.startSpinner("Brewing a fresh cup of TEE \u{1F375}");await cr(2e3),e.stop(!0),r.break(),r.break(),console.log(be),r.info("TEE is served! Opening Phala Cloud registration page..."),await cr(1e3),r.break(),To(t)}catch(t){r.error(`Error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});import{Command as Do}from"commander";var Po=`version: '3'
116
116
  services:
117
117
  jupyter:
118
118
  image: quay.io/jupyter/base-notebook
@@ -124,13 +124,13 @@ services:
124
124
  - GRANT_SUDO=yes
125
125
  user: root
126
126
  command: "start-notebook.sh --NotebookApp.token=\${TOKEN}"
127
- `,Po=`version: '3'
127
+ `,Io=`version: '3'
128
128
  services:
129
129
  httpbin:
130
130
  image: kennethreitz/httpbin:latest
131
131
  ports:
132
132
  - "80:80"
133
- `,lr={jupyter:{compose:To,name:"Jupyter Notebook"},httpbin:{compose:Po,name:"HTTPBin"}};import{encryptEnvVars as Do}from"@phala/dstack-sdk/encrypt-env-vars";import pr from"inquirer";import Ao from"node:crypto";var dr=new Io().name("demo").description("Demo commands to launch a demo on Phala Cloud").action(async()=>{try{await Y()||(r.error("You need to be logged in to use the demo command"),r.info("Please login with: phala auth login"),process.exit(1));try{let u=r.startSpinner("Verifying your credentials"),g=await B();u.stop(!0),r.success(`Logged in as ${g.username}`)}catch{r.error("Authentication failed. Your API key may be invalid or expired."),r.info("Please set a new API key with: phala auth login"),process.exit(1)}let e=Object.values(lr);e.length===0&&(r.error("No template files found in the templates directory"),process.exit(1));let{selectedTemplate:o}=await pr.prompt([{type:"list",name:"selectedTemplate",message:"Select a template to deploy:",choices:e.map(u=>({name:u.name,value:u}))}]),n=o.compose;r.success(`Selected template: ${o.name}`);let s=Ao.randomBytes(16).toString("hex"),c=q([`TOKEN=${s}`],""),{cvmName:a}=await pr.prompt([{type:"input",name:"cvmName",message:"Enter a name for your CVM:",default:`${o.name.replace(" ","-")}`,validate:u=>u.trim()?!0:"CVM name is required"}]);r.info("Preparing to deploy your CVM...");let p={teepod_id:3,name:a,image:ot,vcpu:2,memory:2048,disk_size:20,compose_manifest:{docker_compose_file:n,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:a,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},h=r.startSpinner("Preparing CVM configuration"),f=await Se(p);h.stop(!0),f||(r.error("Failed to prepare CVM configuration"),process.exit(1));let C=await Do(c,f.app_env_encrypt_pubkey);r.debug("Public key:",f.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",C);let k=r.startSpinner("Creating your demo CVM"),m=await xe({...p,encrypted_env:C,app_env_encrypt_pubkey:f.app_env_encrypt_pubkey,app_id_salt:f.app_id_salt});k.stop(!0),m||(r.error("Failed to create demo CVM"),process.exit(1)),r.success("Demo CVM created successfully! \u{1F389}"),r.break();let l={"CVM ID":m.id,Name:m.name,Status:m.status,"App ID":`app_${m.app_id}`,"App URL":m.app_url?m.app_url:`${S}/dashboard/cvms/app_${m.app_id}`,Template:o.name,Resources:"2 vCPUs, 2GB RAM, 20GB Storage"};o.name.includes("Jupyter Notebook")&&(l["Jupyter Token"]=s,l["Access Instructions"]="Access your Jupyter notebook using the token above. Go to 'Network' tab to see the public URL."),r.keyValueTable(l,{borderStyle:"rounded"}),r.break(),r.success(`Your demo is being created. You can check its status with:
134
- phala cvms get app_${m.app_id}`)}catch(t){r.error(`Failed to launch demo: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Fo(){new Ro().name("phala").alias("pha").description(`${ye}
135
- Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.6").addCommand(Ct).addCommand(ir).addCommand(Mt).addCommand(Nt).addCommand(dr).addCommand(mr).parse(process.argv)}Fo().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
133
+ `,pr={jupyter:{compose:Po,name:"Jupyter Notebook"},httpbin:{compose:Io,name:"HTTPBin"}};import{encryptEnvVars as Ao}from"@phala/dstack-sdk/encrypt-env-vars";import dr from"inquirer";import Ro from"node:crypto";var ur=new Do().name("demo").description("Demo commands to launch a demo on Phala Cloud").action(async()=>{try{await Y()||(r.error("You need to be logged in to use the demo command"),r.info("Please login with: phala auth login"),process.exit(1));try{let u=r.startSpinner("Verifying your credentials"),g=await B();u.stop(!0),r.success(`Logged in as ${g.username}`)}catch{r.error("Authentication failed. Your API key may be invalid or expired."),r.info("Please set a new API key with: phala auth login"),process.exit(1)}let e=Object.values(pr);e.length===0&&(r.error("No template files found in the templates directory"),process.exit(1));let{selectedTemplate:o}=await dr.prompt([{type:"list",name:"selectedTemplate",message:"Select a template to deploy:",choices:e.map(u=>({name:u.name,value:u}))}]),n=o.compose;r.success(`Selected template: ${o.name}`);let s=Ro.randomBytes(16).toString("hex"),c=q([`TOKEN=${s}`],""),{cvmName:a}=await dr.prompt([{type:"input",name:"cvmName",message:"Enter a name for your CVM:",default:`${o.name.replace(" ","-")}`,validate:u=>u.trim()?!0:"CVM name is required"}]);r.info("Preparing to deploy your CVM...");let p={teepod_id:3,name:a,image:ae,vcpu:2,memory:2048,disk_size:20,compose_manifest:{docker_compose_file:n,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:a,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},y=r.startSpinner("Preparing CVM configuration"),f=await xe(p);y.stop(!0),f||(r.error("Failed to prepare CVM configuration"),process.exit(1));let v=await Ao(c,f.app_env_encrypt_pubkey);r.debug("Public key:",f.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",v);let k=r.startSpinner("Creating your demo CVM"),m=await Ee({...p,encrypted_env:v,app_env_encrypt_pubkey:f.app_env_encrypt_pubkey,app_id_salt:f.app_id_salt});k.stop(!0),m||(r.error("Failed to create demo CVM"),process.exit(1)),r.success("Demo CVM created successfully! \u{1F389}"),r.break();let l={"CVM ID":m.id,Name:m.name,Status:m.status,"App ID":`app_${m.app_id}`,"App URL":m.app_url?m.app_url:`${S}/dashboard/cvms/app_${m.app_id}`,Template:o.name,Resources:"2 vCPUs, 2GB RAM, 20GB Storage"};o.name.includes("Jupyter Notebook")&&(l["Jupyter Token"]=s,l["Access Instructions"]="Access your Jupyter notebook using the token above. Go to 'Network' tab to see the public URL."),r.keyValueTable(l,{borderStyle:"rounded"}),r.break(),r.success(`Your demo is being created. You can check its status with:
134
+ phala cvms get app_${m.app_id}`)}catch(t){r.error(`Failed to launch demo: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Mo(){new Fo().name("phala").alias("pha").description(`${be}
135
+ Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("v1.0.7").addCommand(kt).addCommand(ar).addCommand(Vt).addCommand(Ot).addCommand(ur).addCommand(lr).parse(process.argv)}Mo().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
136
136
  //# sourceMappingURL=index.js.map