phala 1.1.12 → 1.1.13

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/api/index.js CHANGED
@@ -1,54 +1,48 @@
1
1
  import { createRequire } from 'module';const require = createRequire(import.meta.url);
2
- var Ki=Object.create;var Dn=Object.defineProperty;var Wi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var Ji=Object.getPrototypeOf,Zi=Object.prototype.hasOwnProperty;var Oe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var me=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yi=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xi(t))!Zi.call(e,o)&&o!==r&&Dn(e,o,{get:()=>t[o],enumerable:!(n=Wi(t,o))||n.enumerable});return e};var Pt=(e,t,r)=>(r=e!=null?Ki(Ji(e)):{},Yi(t||!e||!e.__esModule?Dn(r,"default",{value:e,enumerable:!0}):r,e));var Mn=me((qm,Vn)=>{var ut=1e3,pt=ut*60,ft=pt*60,Qe=ft*24,Qi=Qe*7,ea=Qe*365.25;Vn.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return ta(e);if(r==="number"&&isFinite(e))return t.long?na(e):ra(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function ta(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*ea;case"weeks":case"week":case"w":return r*Qi;case"days":case"day":case"d":return r*Qe;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ft;case"minutes":case"minute":case"mins":case"min":case"m":return r*pt;case"seconds":case"second":case"secs":case"sec":case"s":return r*ut;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function ra(e){var t=Math.abs(e);return t>=Qe?Math.round(e/Qe)+"d":t>=ft?Math.round(e/ft)+"h":t>=pt?Math.round(e/pt)+"m":t>=ut?Math.round(e/ut)+"s":e+"ms"}function na(e){var t=Math.abs(e);return t>=Qe?Yt(e,t,Qe,"day"):t>=ft?Yt(e,t,ft,"hour"):t>=pt?Yt(e,t,pt,"minute"):t>=ut?Yt(e,t,ut,"second"):e+" ms"}function Yt(e,t,r,n){var o=t>=r*1.5;return Math.round(e/r)+" "+n+(o?"s":"")}});var Dr=me((Dm,Kn)=>{function oa(e){r.debug=r,r.default=r,r.coerce=l,r.disable=i,r.enable=o,r.enabled=a,r.humanize=Mn(),r.destroy=u,Object.keys(e).forEach(p=>{r[p]=e[p]}),r.names=[],r.skips=[],r.formatters={};function t(p){let f=0;for(let h=0;h<p.length;h++)f=(f<<5)-f+p.charCodeAt(h),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=t;function r(p){let f,h=null,g,C;function P(...R){if(!P.enabled)return;let q=P,Y=Number(new Date),W=Y-(f||Y);q.diff=W,q.prev=f,q.curr=Y,f=Y,R[0]=r.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let Q=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,(fe,Zt)=>{if(fe==="%%")return"%";Q++;let qn=r.formatters[Zt];if(typeof qn=="function"){let Mi=R[Q];fe=qn.call(q,Mi),R.splice(Q,1),Q--}return fe}),r.formatArgs.call(q,R),(q.log||r.log).apply(q,R)}return P.namespace=p,P.useColors=r.useColors(),P.color=r.selectColor(p),P.extend=n,P.destroy=r.destroy,Object.defineProperty(P,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==r.namespaces&&(g=r.namespaces,C=r.enabled(p)),C),set:R=>{h=R}}),typeof r.init=="function"&&r.init(P),P}function n(p,f){let h=r(this.namespace+(typeof f>"u"?":":f)+p);return h.log=this.log,h}function o(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let f=(typeof p=="string"?p:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of f)h[0]==="-"?r.skips.push(h.slice(1)):r.names.push(h)}function s(p,f){let h=0,g=0,C=-1,P=0;for(;h<p.length;)if(g<f.length&&(f[g]===p[h]||f[g]==="*"))f[g]==="*"?(C=g,P=h,g++):(h++,g++);else if(C!==-1)g=C+1,P++,h=P;else return!1;for(;g<f.length&&f[g]==="*";)g++;return g===f.length}function i(){let p=[...r.names,...r.skips.map(f=>"-"+f)].join(",");return r.enable(""),p}function a(p){for(let f of r.skips)if(s(p,f))return!1;for(let f of r.names)if(s(p,f))return!0;return!1}function l(p){return p instanceof Error?p.stack||p.message:p}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Kn.exports=oa});var Wn=me((ie,Qt)=>{ie.formatArgs=ia;ie.save=aa;ie.load=ca;ie.useColors=sa;ie.storage=la();ie.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ie.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function sa(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ia(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Qt.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(r++,o==="%c"&&(n=r))}),e.splice(n,0,t)}ie.log=console.debug||console.log||(()=>{});function aa(e){try{e?ie.storage.setItem("debug",e):ie.storage.removeItem("debug")}catch{}}function ca(){let e;try{e=ie.storage.getItem("debug")||ie.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function la(){try{return localStorage}catch{}}Qt.exports=Dr()(ie);var{formatters:ua}=Qt.exports;ua.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Jn=me((D,tr)=>{var pa=Oe("tty"),er=Oe("util");D.init=xa;D.log=ha;D.formatArgs=ma;D.save=ga;D.load=ba;D.useColors=fa;D.destroy=er.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");D.colors=[6,2,3,4,5,1];try{let e=Oe("supports-color");e&&(e.stderr||e).level>=2&&(D.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}D.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),n=process.env[t];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),e[r]=n,e},{});function fa(){return"colors"in D.inspectOpts?!!D.inspectOpts.colors:pa.isatty(process.stderr.fd)}function ma(e){let{namespace:t,useColors:r}=this;if(r){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),s=` ${o};1m${t} \x1B[0m`;e[0]=s+e[0].split(`
2
+ var Yr=Object.create;var tn=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var ns=Object.getPrototypeOf,rs=Object.prototype.hasOwnProperty;var Re=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ss=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ts(t))!rs.call(e,s)&&s!==n&&tn(e,s,{get:()=>t[s],enumerable:!(r=es(t,s))||r.enumerable});return e};var tt=(e,t,n)=>(n=e!=null?Yr(ns(e)):{},ss(t||!e||!e.__esModule?tn(n,"default",{value:e,enumerable:!0}):n,e));var rn=pe((mu,nn)=>{var De=1e3,Be=De*60,He=Be*60,Fe=He*24,os=Fe*7,as=Fe*365.25;nn.exports=function(e,t){t=t||{};var n=typeof e;if(n==="string"&&e.length>0)return is(e);if(n==="number"&&isFinite(e))return t.long?ls(e):cs(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function is(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*as;case"weeks":case"week":case"w":return n*os;case"days":case"day":case"d":return n*Fe;case"hours":case"hour":case"hrs":case"hr":case"h":return n*He;case"minutes":case"minute":case"mins":case"min":case"m":return n*Be;case"seconds":case"second":case"secs":case"sec":case"s":return n*De;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function cs(e){var t=Math.abs(e);return t>=Fe?Math.round(e/Fe)+"d":t>=He?Math.round(e/He)+"h":t>=Be?Math.round(e/Be)+"m":t>=De?Math.round(e/De)+"s":e+"ms"}function ls(e){var t=Math.abs(e);return t>=Fe?ut(e,t,Fe,"day"):t>=He?ut(e,t,He,"hour"):t>=Be?ut(e,t,Be,"minute"):t>=De?ut(e,t,De,"second"):e+" ms"}function ut(e,t,n,r){var s=t>=n*1.5;return Math.round(e/n)+" "+r+(s?"s":"")}});var At=pe((fu,sn)=>{function us(e){n.debug=n,n.default=n,n.coerce=l,n.disable=a,n.enable=s,n.enabled=c,n.humanize=rn(),n.destroy=m,Object.keys(e).forEach(d=>{n[d]=e[d]}),n.names=[],n.skips=[],n.formatters={};function t(d){let f=0;for(let b=0;b<d.length;b++)f=(f<<5)-f+d.charCodeAt(b),f|=0;return n.colors[Math.abs(f)%n.colors.length]}n.selectColor=t;function n(d){let f,b=null,C,S;function T(...O){if(!T.enabled)return;let Q=T,ue=Number(new Date),xe=ue-(f||ue);Q.diff=xe,Q.prev=f,Q.curr=ue,f=ue,O[0]=n.coerce(O[0]),typeof O[0]!="string"&&O.unshift("%O");let be=0;O[0]=O[0].replace(/%([a-zA-Z%])/g,(Ne,lt)=>{if(Ne==="%%")return"%";be++;let en=n.formatters[lt];if(typeof en=="function"){let Qr=O[be];Ne=en.call(Q,Qr),O.splice(be,1),be--}return Ne}),n.formatArgs.call(Q,O),(Q.log||n.log).apply(Q,O)}return T.namespace=d,T.useColors=n.useColors(),T.color=n.selectColor(d),T.extend=r,T.destroy=n.destroy,Object.defineProperty(T,"enabled",{enumerable:!0,configurable:!1,get:()=>b!==null?b:(C!==n.namespaces&&(C=n.namespaces,S=n.enabled(d)),S),set:O=>{b=O}}),typeof n.init=="function"&&n.init(T),T}function r(d,f){let b=n(this.namespace+(typeof f>"u"?":":f)+d);return b.log=this.log,b}function s(d){n.save(d),n.namespaces=d,n.names=[],n.skips=[];let f=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let b of f)b[0]==="-"?n.skips.push(b.slice(1)):n.names.push(b)}function o(d,f){let b=0,C=0,S=-1,T=0;for(;b<d.length;)if(C<f.length&&(f[C]===d[b]||f[C]==="*"))f[C]==="*"?(S=C,T=b,C++):(b++,C++);else if(S!==-1)C=S+1,T++,b=T;else return!1;for(;C<f.length&&f[C]==="*";)C++;return C===f.length}function a(){let d=[...n.names,...n.skips.map(f=>"-"+f)].join(",");return n.enable(""),d}function c(d){for(let f of n.skips)if(o(d,f))return!1;for(let f of n.names)if(o(d,f))return!0;return!1}function l(d){return d instanceof Error?d.stack||d.message:d}function m(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}sn.exports=us});var on=pe((oe,pt)=>{oe.formatArgs=ds;oe.save=ms;oe.load=fs;oe.useColors=ps;oe.storage=gs();oe.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();oe.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ps(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ds(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+pt.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let n=0,r=0;e[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(n++,s==="%c"&&(r=n))}),e.splice(r,0,t)}oe.log=console.debug||console.log||(()=>{});function ms(e){try{e?oe.storage.setItem("debug",e):oe.storage.removeItem("debug")}catch{}}function fs(){let e;try{e=oe.storage.getItem("debug")||oe.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function gs(){try{return localStorage}catch{}}pt.exports=At()(oe);var{formatters:hs}=pt.exports;hs.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var cn=pe((V,mt)=>{var bs=Re("tty"),dt=Re("util");V.init=Ss;V.log=ws;V.formatArgs=vs;V.save=Cs;V.load=ks;V.useColors=ys;V.destroy=dt.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");V.colors=[6,2,3,4,5,1];try{let e=Re("supports-color");e&&(e.stderr||e).level>=2&&(V.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}V.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(s,o)=>o.toUpperCase()),r=process.env[t];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),e[n]=r,e},{});function ys(){return"colors"in V.inspectOpts?!!V.inspectOpts.colors:bs.isatty(process.stderr.fd)}function vs(e){let{namespace:t,useColors:n}=this;if(n){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),o=` ${s};1m${t} \x1B[0m`;e[0]=o+e[0].split(`
3
3
  `).join(`
4
- `+s),e.push(o+"m+"+tr.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=da()+t+" "+e[0]}function da(){return D.inspectOpts.hideDate?"":new Date().toISOString()+" "}function ha(...e){return process.stderr.write(er.formatWithOptions(D.inspectOpts,...e)+`
5
- `)}function ga(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function ba(){return process.env.DEBUG}function xa(e){e.inspectOpts={};let t=Object.keys(D.inspectOpts);for(let r=0;r<t.length;r++)e.inspectOpts[t[r]]=D.inspectOpts[t[r]]}tr.exports=Dr()(D);var{formatters:Xn}=tr.exports;Xn.o=function(e){return this.inspectOpts.colors=this.useColors,er.inspect(e,this.inspectOpts).split(`
6
- `).map(t=>t.trim()).join(" ")};Xn.O=function(e){return this.inspectOpts.colors=this.useColors,er.inspect(e,this.inspectOpts)}});var Zn=me((Vm,Vr)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Vr.exports=Wn():Vr.exports=Jn()});var Mr,Qn=L(()=>{Mr="2.38.6"});function eo(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?eo(e.cause,t):t?null:e}var Kr,v,de=L(()=>{Qn();Kr={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Mr}`},v=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,o=r.cause instanceof e&&r.cause.docsPath||r.docsPath,s=Kr.getDocsUrl?.({...r,docsPath:o}),i=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Kr.version?[`Version: ${Kr.version}`]:[]].join(`
7
- `);super(i,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=Mr}walk(t){return eo(this,t)}}});var rr,nr,Wr=L(()=>{de();rr=class extends v{constructor({max:t,min:r,signed:n,size:o,value:s}){super(`Number "${s}" is not in safe ${o?`${o*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}},nr=class extends v{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}});function Ee(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}var mt=L(()=>{});function he(e){return Ee(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}var $t=L(()=>{mt()});function Lt(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let o=0;o<r.length-1&&r[t==="left"?o:r.length-o-1].toString()==="0";o++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}var to=L(()=>{});var zt,Rt,Xr=L(()=>{de();zt=class extends v{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}},Rt=class extends v{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}});function Ne(e,{dir:t,size:r=32}={}){return typeof e=="string"?ya(e,{dir:t,size:r}):va(e,{dir:t,size:r})}function ya(e,{dir:t,size:r=32}={}){if(r===null)return e;let n=e.replace("0x","");if(n.length>r*2)throw new Rt({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function va(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new Rt({size:e.length,targetSize:r,type:"bytes"});let n=new Uint8Array(r);for(let o=0;o<r;o++){let s=t==="right";n[s?o:r-o-1]=e[s?o:e.length-o-1]}return n}var Jr=L(()=>{Xr()});function ye(e,t={}){return typeof e=="number"||typeof e=="bigint"?E(e,t):typeof e=="string"?ka(e,t):typeof e=="boolean"?_a(e,t):ae(e,t)}function _a(e,t={}){let r=`0x${Number(e)}`;return typeof t.size=="number"?(Ge(r,{size:t.size}),Ne(r,{size:t.size})):r}function ae(e,t={}){let r="";for(let o=0;o<e.length;o++)r+=wa[e[o]];let n=`0x${r}`;return typeof t.size=="number"?(Ge(n,{size:t.size}),Ne(n,{dir:"right",size:t.size})):n}function E(e,t={}){let{signed:r,size:n}=t,o=BigInt(e),s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));let i=typeof s=="bigint"&&r?-s-1n:0;if(s&&o>s||o<i){let l=typeof e=="bigint"?"n":"";throw new rr({max:s?`${s}${l}`:void 0,min:`${i}${l}`,signed:r,size:n,value:`${e}${l}`})}let a=`0x${(r&&o<0?(1n<<BigInt(n*8))+BigInt(o):o).toString(16)}`;return n?Ne(a,{size:n}):a}function ka(e,t={}){let r=Ca.encode(e);return ae(r,t)}var wa,Ca,ge=L(()=>{Wr();Jr();tt();wa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ca=new TextEncoder});function or(e,t={}){return typeof e=="number"||typeof e=="bigint"?Ta(e,t):typeof e=="boolean"?Ea(e,t):Ee(e)?ve(e,t):Zr(e,t)}function Ea(e,t={}){let r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(Ge(r,{size:t.size}),Ne(r,{size:t.size})):r}function ro(e){if(e>=je.zero&&e<=je.nine)return e-je.zero;if(e>=je.A&&e<=je.F)return e-(je.A-10);if(e>=je.a&&e<=je.f)return e-(je.a-10)}function ve(e,t={}){let r=e;t.size&&(Ge(r,{size:t.size}),r=Ne(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);let o=n.length/2,s=new Uint8Array(o);for(let i=0,a=0;i<o;i++){let l=ro(n.charCodeAt(a++)),u=ro(n.charCodeAt(a++));if(l===void 0||u===void 0)throw new v(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[i]=l*16+u}return s}function Ta(e,t){let r=E(e,t);return ve(r)}function Zr(e,t={}){let r=Sa.encode(e);return typeof t.size=="number"?(Ge(r,{size:t.size}),Ne(r,{dir:"right",size:t.size})):r}var Sa,je,qe=L(()=>{de();mt();Jr();tt();ge();Sa=new TextEncoder;je={zero:48,nine:57,A:65,F:70,a:97,f:102}});function Ge(e,{size:t}){if(he(e)>t)throw new nr({givenSize:he(e),maxSize:t})}function rt(e,t={}){let{signed:r}=t;t.size&&Ge(e,{size:t.size});let n=BigInt(e);if(!r)return n;let o=(e.length-2)/2,s=(1n<<BigInt(o)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(o*2,"f")}`)-1n}function nt(e,t={}){return Number(rt(e,t))}var tt=L(()=>{Wr();$t()});function dt(e,t){return({exclude:r,format:n})=>({exclude:r,format:(o,s)=>{let i=t(o,s);if(r)for(let a of r)delete i[a];return{...i,...n(o,s)}},type:e})}var sr=L(()=>{});var Rd,Bd,jd,Ud,Fd,Hd,Od,Nd,Gd,qd,Dd,Vd,Md,Kd,Wd,Xd,Jd,Zd,Yd,Qd,eh,th,rh,nh,oh,sh,ih,ah,ch,lh,uh,ph,fh,mh,dh,hh,gh,bh,xh,yh,vh,wh,_h,Ch,kh,Sh,Eh,Th,Ih,Ah,Ph,$h,Lh,zh,Rh,Bh,jh,Uh,Fh,Hh,Oh,Nh,Gh,qh,Dh,Vh,Mh,Kh,Wh,Xh,Jh,Zh,Yh,Qh,eg,tg,rg,ng,og,sg,ig,ag,cg,lg,ug,pg,fg,mg,dg,hg,gg,bg,xg,yg,vg,ir,ao=L(()=>{Rd=2n**(8n-1n)-1n,Bd=2n**(16n-1n)-1n,jd=2n**(24n-1n)-1n,Ud=2n**(32n-1n)-1n,Fd=2n**(40n-1n)-1n,Hd=2n**(48n-1n)-1n,Od=2n**(56n-1n)-1n,Nd=2n**(64n-1n)-1n,Gd=2n**(72n-1n)-1n,qd=2n**(80n-1n)-1n,Dd=2n**(88n-1n)-1n,Vd=2n**(96n-1n)-1n,Md=2n**(104n-1n)-1n,Kd=2n**(112n-1n)-1n,Wd=2n**(120n-1n)-1n,Xd=2n**(128n-1n)-1n,Jd=2n**(136n-1n)-1n,Zd=2n**(144n-1n)-1n,Yd=2n**(152n-1n)-1n,Qd=2n**(160n-1n)-1n,eh=2n**(168n-1n)-1n,th=2n**(176n-1n)-1n,rh=2n**(184n-1n)-1n,nh=2n**(192n-1n)-1n,oh=2n**(200n-1n)-1n,sh=2n**(208n-1n)-1n,ih=2n**(216n-1n)-1n,ah=2n**(224n-1n)-1n,ch=2n**(232n-1n)-1n,lh=2n**(240n-1n)-1n,uh=2n**(248n-1n)-1n,ph=2n**(256n-1n)-1n,fh=-(2n**(8n-1n)),mh=-(2n**(16n-1n)),dh=-(2n**(24n-1n)),hh=-(2n**(32n-1n)),gh=-(2n**(40n-1n)),bh=-(2n**(48n-1n)),xh=-(2n**(56n-1n)),yh=-(2n**(64n-1n)),vh=-(2n**(72n-1n)),wh=-(2n**(80n-1n)),_h=-(2n**(88n-1n)),Ch=-(2n**(96n-1n)),kh=-(2n**(104n-1n)),Sh=-(2n**(112n-1n)),Eh=-(2n**(120n-1n)),Th=-(2n**(128n-1n)),Ih=-(2n**(136n-1n)),Ah=-(2n**(144n-1n)),Ph=-(2n**(152n-1n)),$h=-(2n**(160n-1n)),Lh=-(2n**(168n-1n)),zh=-(2n**(176n-1n)),Rh=-(2n**(184n-1n)),Bh=-(2n**(192n-1n)),jh=-(2n**(200n-1n)),Uh=-(2n**(208n-1n)),Fh=-(2n**(216n-1n)),Hh=-(2n**(224n-1n)),Oh=-(2n**(232n-1n)),Nh=-(2n**(240n-1n)),Gh=-(2n**(248n-1n)),qh=-(2n**(256n-1n)),Dh=2n**8n-1n,Vh=2n**16n-1n,Mh=2n**24n-1n,Kh=2n**32n-1n,Wh=2n**40n-1n,Xh=2n**48n-1n,Jh=2n**56n-1n,Zh=2n**64n-1n,Yh=2n**72n-1n,Qh=2n**80n-1n,eg=2n**88n-1n,tg=2n**96n-1n,rg=2n**104n-1n,ng=2n**112n-1n,og=2n**120n-1n,sg=2n**128n-1n,ig=2n**136n-1n,ag=2n**144n-1n,cg=2n**152n-1n,lg=2n**160n-1n,ug=2n**168n-1n,pg=2n**176n-1n,fg=2n**184n-1n,mg=2n**192n-1n,dg=2n**200n-1n,hg=2n**208n-1n,gg=2n**216n-1n,bg=2n**224n-1n,xg=2n**232n-1n,yg=2n**240n-1n,vg=2n**248n-1n,ir=2n**256n-1n});function ot(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}var Qr=L(()=>{});var jt,ar,cr,co=L(()=>{de();jt=class extends v{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}},ar=class extends v{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}},cr=class extends v{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}});function lr(e,{recursiveReadLimit:t=8192}={}){let r=Object.create(La);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}var La,en=L(()=>{co();La={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new cr({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new ar({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new jt({offset:e});let t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new jt({offset:e});let t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){let r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){let t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){let t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){let t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){let t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();let e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();let r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();let e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();let e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();let e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();let e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){let t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;let e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}}});var po,fo=L(()=>{po={ether:-9,wei:9}});function mo(e,t){let r=e.toString(),n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[o,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${o||"0"}${s?`.${s}`:""}`}var ho=L(()=>{});function Ut(e,t="wei"){return mo(e,po[t])}var go=L(()=>{fo();ho()});function Ba(e){let t=Object.entries(e).map(([n,o])=>o===void 0||o===!1?null:[n,o]).filter(Boolean),r=t.reduce((n,[o])=>Math.max(n,o.length),0);return t.map(([n,o])=>` ${`${n}:`.padEnd(r+1)} ${o}`).join(`
8
- `)}var ur,pr,fr,mr=L(()=>{de();ur=class extends v{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}},pr=class extends v{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Ba(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}},fr=class extends v{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}});function ja(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function tn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function st(e,...t){if(!ja(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function bt(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function gr(e,t){st(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function xo(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function De(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function br(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function we(e,t){return e<<32-t|e>>>t}function Fa(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Ha(e){for(let t=0;t<e.length;t++)e[t]=Fa(e[t]);return e}function Oa(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ft(e){return typeof e=="string"&&(e=Oa(e)),st(e),e}function xr(e){let t=n=>e().update(Ft(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}var Ua,rn,gt,yr=L(()=>{Ua=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;rn=Ua?e=>e:Ha;gt=class{}});function Ga(e,t=!1){return t?{h:Number(e&wr),l:Number(e>>wo&wr)}:{h:Number(e>>wo&wr)|0,l:Number(e&wr)|0}}function _o(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Ga(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var wr,wo,Co,ko,So,Eo,To=L(()=>{wr=BigInt(4294967295),wo=BigInt(32);Co=(e,t,r)=>e<<r|t>>>32-r,ko=(e,t,r)=>t<<r|e>>>32-r,So=(e,t,r)=>t<<r-32|e>>>64-r,Eo=(e,t,r)=>e<<r-32|t>>>64-r});var be,Er=L(()=>{de();be=class extends v{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}});var it,Bo=L(()=>{de();it=class extends v{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}});var Tr,at,nn,on,sn,an,cn,ln,un,pn,Ht,jo=L(()=>{go();de();Tr=class extends v{constructor({cause:t,message:r}={}){let n=r?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:t,name:"ExecutionRevertedError"})}};Object.defineProperty(Tr,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Tr,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted/});at=class extends v{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}};Object.defineProperty(at,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});nn=class extends v{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ut(r)}`:""} gwei) cannot be lower than the block base fee.`,{cause:t,name:"FeeCapTooLowError"})}};Object.defineProperty(nn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});on=class extends v{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}is higher than the next one expected.`,{cause:t,name:"NonceTooHighError"})}};Object.defineProperty(on,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});sn=class extends v{constructor({cause:t,nonce:r}={}){super([`Nonce provided for the transaction ${r?`(${r}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
9
- `),{cause:t,name:"NonceTooLowError"})}};Object.defineProperty(sn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});an=class extends v{constructor({cause:t,nonce:r}={}){super(`Nonce provided for the transaction ${r?`(${r}) `:""}exceeds the maximum allowed nonce.`,{cause:t,name:"NonceMaxValueError"})}};Object.defineProperty(an,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});cn=class extends v{constructor({cause:t}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
10
- `),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}};Object.defineProperty(cn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});ln=class extends v{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}};Object.defineProperty(ln,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});un=class extends v{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}};Object.defineProperty(un,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});pn=class extends v{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}};Object.defineProperty(pn,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});Ht=class extends v{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Ut(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Ut(n)} gwei`:""}).`].join(`
11
- `),{cause:t,name:"TipAboveFeeCapError"})}};Object.defineProperty(Ht,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/})});var yt,fn=L(()=>{yt=class extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){let r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){let n=this.keys().next().value;n&&this.delete(n)}return this}}});function Qa(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,l=(i+2)%10,u=r[l],p=r[l+1],f=Uo(u,p,1)^r[a],h=Fo(u,p,1)^r[a+1];for(let g=0;g<50;g+=10)e[i+g]^=f,e[i+g+1]^=h}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=Oo[i],l=Uo(o,s,a),u=Fo(o,s,a),p=Ho[i];o=e[p],s=e[p+1],e[p]=l,e[p+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Za[n],e[1]^=Ya[n]}De(r)}var Ma,Ot,Ka,Wa,Xa,Ja,Ho,Oo,No,Go,Za,Ya,Uo,Fo,mn,ec,qo,Do=L(()=>{To();yr();Ma=BigInt(0),Ot=BigInt(1),Ka=BigInt(2),Wa=BigInt(7),Xa=BigInt(256),Ja=BigInt(113),Ho=[],Oo=[],No=[];for(let e=0,t=Ot,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Ho.push(2*(5*n+r)),Oo.push((e+1)*(e+2)/2%64);let o=Ma;for(let s=0;s<7;s++)t=(t<<Ot^(t>>Wa)*Ja)%Xa,t&Ka&&(o^=Ot<<(Ot<<BigInt(s))-Ot);No.push(o)}Go=_o(No,!0),Za=Go[0],Ya=Go[1],Uo=(e,t,r)=>r>32?So(e,t,r):Co(e,t,r),Fo=(e,t,r)=>r>32?Eo(e,t,r):ko(e,t,r);mn=class e extends gt{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,tn(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=xo(this.state)}clone(){return this._cloneInto()}keccak(){rn(this.state32),Qa(this.state32,this.rounds),rn(this.state32),this.posOut=0,this.pos=0}update(t){bt(this),t=Ft(t),st(t);let{blockLen:r,state:n}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);for(let a=0;a<i;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){bt(this,!1),st(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,s=t.length;o<s;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return tn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(gr(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,De(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}},ec=(e,t,r)=>xr(()=>new mn(t,e,r)),qo=ec(1,136,256/8)});function Vo(e,t){let r=t||"hex",n=qo(Ee(e,{strict:!1})?or(e):e);return r==="bytes"?n:ye(n)}var Mo=L(()=>{Do();mt();qe();ge()});function Ko(e,t){if(dn.has(`${e}.${t}`))return dn.get(`${e}.${t}`);let r=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),n=Vo(Zr(r),"bytes"),o=(t?r.substring(`${t}0x`.length):r).split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&o[i]&&(o[i]=o[i].toUpperCase()),(n[i>>1]&15)>=8&&o[i+1]&&(o[i+1]=o[i+1].toUpperCase());let s=`0x${o.join("")}`;return dn.set(`${e}.${t}`,s),s}var dn,Wo=L(()=>{qe();Mo();fn();dn=new yt(8192)});function Te(e,t){let{strict:r=!0}=t??{},n=`${e}.${r}`;if(hn.has(n))return hn.get(n);let o=tc.test(e)?e.toLowerCase()===e?!0:r?Ko(e)===e:!0:!1;return hn.set(n,o),o}var tc,hn,Ir=L(()=>{fn();Wo();tc=/^0x[a-fA-F0-9]{40}$/,hn=new yt(8192)});function Xo(e,t,r,{strict:n}={}){return Ee(e,{strict:!1})?nc(e,t,r,{strict:n}):rc(e,t,r,{strict:n})}function Jo(e,t){if(typeof t=="number"&&t>0&&t>he(e)-1)throw new zt({offset:t,position:"start",size:he(e)})}function Zo(e,t,r){if(typeof t=="number"&&typeof r=="number"&&he(e)!==r-t)throw new zt({offset:r,position:"end",size:he(e)})}function rc(e,t,r,{strict:n}={}){Jo(e,t);let o=e.slice(t,r);return n&&Zo(o,t,r),o}function nc(e,t,r,{strict:n}={}){Jo(e,t);let o=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return n&&Zo(o,t,r),o}var Yo=L(()=>{Xr();mt();$t()});var yn=me(Dt=>{"use strict";var dc=Dt&&Dt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.encryptEnvVars=bc;var bn=Oe("@noble/curves/ed25519"),xn=dc(Oe("crypto"));function hc(e){var t,r;return e=e.startsWith("0x")?e.slice(2):e,new Uint8Array((r=(t=e.match(/.{1,2}/g))===null||t===void 0?void 0:t.map(n=>parseInt(n,16)))!==null&&r!==void 0?r:[])}function gc(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function bc(e,t){let r=JSON.stringify({env:e}),n=bn.x25519.utils.randomPrivateKey(),o=bn.x25519.getPublicKey(n),s=hc(t),i=bn.x25519.getSharedSecret(n,s),a=await xn.default.subtle.importKey("raw",i,{name:"AES-GCM",length:256},!0,["encrypt"]),l=xn.default.getRandomValues(new Uint8Array(12)),u=await xn.default.subtle.encrypt({name:"AES-GCM",iv:l},a,new TextEncoder().encode(r)),p=new Uint8Array(o.length+l.length+u.byteLength);return p.set(o),p.set(l,o.length),p.set(new Uint8Array(u),o.length+l.length),gc(p)}});var cs=me(Vt=>{"use strict";var xc=Vt&&Vt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getComposeHash=_c;var yc=xc(Oe("crypto"));function vn(e){return e==null?e:Array.isArray(e)?e.map(vn):e&&typeof e=="object"&&e.constructor===Object?Object.keys(e).sort().reduce((t,r)=>{let n=e[r];return t[r]=vn(n),t},{}):e}function vc(e){let t={...e};return t.runner==="bash"&&"docker_compose_file"in t?delete t.docker_compose_file:t.runner==="docker-compose"&&"bash_script"in t&&delete t.bash_script,"pre_launch_script"in t&&!t.pre_launch_script&&delete t.pre_launch_script,t}function wc(e){let t=vn(e);return JSON.stringify(t,(r,n)=>typeof n=="number"&&(isNaN(n)||!isFinite(n))?null:n)}function _c(e,t=!1){t&&(e=vc(e));let r=wc(e);return yc.default.createHash("sha256").update(r,"utf8").digest("hex")}});var Ps=me(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.toBig=w.shrSL=w.shrSH=w.rotrSL=w.rotrSH=w.rotrBL=w.rotrBH=w.rotr32L=w.rotr32H=w.rotlSL=w.rotlSH=w.rotlBL=w.rotlBH=w.add5L=w.add5H=w.add4L=w.add4H=w.add3L=w.add3H=void 0;w.add=Cs;w.fromBig=_n;w.split=ls;var Lr=BigInt(2**32-1),wn=BigInt(32);function _n(e,t=!1){return t?{h:Number(e&Lr),l:Number(e>>wn&Lr)}:{h:Number(e>>wn&Lr)|0,l:Number(e&Lr)|0}}function ls(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=_n(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var us=(e,t)=>BigInt(e>>>0)<<wn|BigInt(t>>>0);w.toBig=us;var ps=(e,t,r)=>e>>>r;w.shrSH=ps;var fs=(e,t,r)=>e<<32-r|t>>>r;w.shrSL=fs;var ms=(e,t,r)=>e>>>r|t<<32-r;w.rotrSH=ms;var ds=(e,t,r)=>e<<32-r|t>>>r;w.rotrSL=ds;var hs=(e,t,r)=>e<<64-r|t>>>r-32;w.rotrBH=hs;var gs=(e,t,r)=>e>>>r-32|t<<64-r;w.rotrBL=gs;var bs=(e,t)=>t;w.rotr32H=bs;var xs=(e,t)=>e;w.rotr32L=xs;var ys=(e,t,r)=>e<<r|t>>>32-r;w.rotlSH=ys;var vs=(e,t,r)=>t<<r|e>>>32-r;w.rotlSL=vs;var ws=(e,t,r)=>t<<r-32|e>>>64-r;w.rotlBH=ws;var _s=(e,t,r)=>e<<r-32|t>>>64-r;w.rotlBL=_s;function Cs(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var ks=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0);w.add3L=ks;var Ss=(e,t,r,n)=>t+r+n+(e/2**32|0)|0;w.add3H=Ss;var Es=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0);w.add4L=Es;var Ts=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0;w.add4H=Ts;var Is=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0);w.add5L=Is;var As=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;w.add5H=As;var Cc={fromBig:_n,split:ls,toBig:us,shrSH:ps,shrSL:fs,rotrSH:ms,rotrSL:ds,rotrBH:hs,rotrBL:gs,rotr32H:bs,rotr32L:xs,rotlSH:ys,rotlSL:vs,rotlBH:ws,rotlBL:_s,add:Cs,add3L:ks,add3H:Ss,add4L:Es,add4H:Ts,add5H:As,add5L:Is};w.default=Cc});var $s=me(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.crypto=void 0;var Me=Oe("crypto");zr.crypto=Me&&typeof Me=="object"&&"webcrypto"in Me?Me.webcrypto:Me&&typeof Me=="object"&&"randomBytes"in Me?Me:void 0});var Hs=me(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.wrapXOFConstructorWithOpts=x.wrapConstructorWithOpts=x.wrapConstructor=x.Hash=x.nextTick=x.swap32IfBE=x.byteSwapIfBE=x.swap8IfBE=x.isLE=void 0;x.isBytes=zs;x.anumber=Cn;x.abytes=wt;x.ahash=kc;x.aexists=Sc;x.aoutput=Ec;x.u8=Tc;x.u32=Ic;x.clean=Ac;x.createView=Pc;x.rotr=$c;x.rotl=Lc;x.byteSwap=Sn;x.byteSwap32=Rs;x.bytesToHex=Rc;x.hexToBytes=Bc;x.asyncLoop=Uc;x.utf8ToBytes=En;x.bytesToUtf8=Fc;x.toBytes=Rr;x.kdfInputToBytes=Hc;x.concatBytes=Oc;x.checkOpts=Nc;x.createHasher=js;x.createOptHasher=Us;x.createXOFer=Fs;x.randomBytes=Gc;var vt=$s();function zs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Cn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wt(e,...t){if(!zs(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function kc(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Cn(e.outputLen),Cn(e.blockLen)}function Sc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ec(e,t){wt(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Tc(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Ic(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ac(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Pc(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $c(e,t){return e<<32-t|e>>>t}function Lc(e,t){return e<<t|e>>>32-t>>>0}x.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sn(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}x.swap8IfBE=x.isLE?e=>e:e=>Sn(e);x.byteSwapIfBE=x.swap8IfBE;function Rs(e){for(let t=0;t<e.length;t++)e[t]=Sn(e[t]);return e}x.swap32IfBE=x.isLE?e=>e:Rs;var Bs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zc=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Rc(e){if(wt(e),Bs)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=zc[e[r]];return t}var He={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ls(e){if(e>=He._0&&e<=He._9)return e-He._0;if(e>=He.A&&e<=He.F)return e-(He.A-10);if(e>=He.a&&e<=He.f)return e-(He.a-10)}function Bc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Bs)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=Ls(e.charCodeAt(s)),a=Ls(e.charCodeAt(s+1));if(i===void 0||a===void 0){let l=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+s)}n[o]=i*16+a}return n}var jc=async()=>{};x.nextTick=jc;async function Uc(e,t,r){let n=Date.now();for(let o=0;o<e;o++){r(o);let s=Date.now()-n;s>=0&&s<t||(await(0,x.nextTick)(),n+=s)}}function En(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Fc(e){return new TextDecoder().decode(e)}function Rr(e){return typeof e=="string"&&(e=En(e)),wt(e),e}function Hc(e){return typeof e=="string"&&(e=En(e)),wt(e),e}function Oc(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];wt(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function Nc(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(e,t)}var kn=class{};x.Hash=kn;function js(e){let t=n=>e().update(Rr(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Us(e){let t=(n,o)=>e(o).update(Rr(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}function Fs(e){let t=(n,o)=>e(o).update(Rr(n)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}x.wrapConstructor=js;x.wrapConstructorWithOpts=Us;x.wrapXOFConstructorWithOpts=Fs;function Gc(e=32){if(vt.crypto&&typeof vt.crypto.getRandomValues=="function")return vt.crypto.getRandomValues(new Uint8Array(e));if(vt.crypto&&typeof vt.crypto.randomBytes=="function")return Uint8Array.from(vt.crypto.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}});var Ws=me(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.shake256=U.shake128=U.keccak_512=U.keccak_384=U.keccak_256=U.keccak_224=U.sha3_512=U.sha3_384=U.sha3_256=U.sha3_224=U.Keccak=void 0;U.keccakP=Ms;var Kt=Ps(),X=Hs(),qc=BigInt(0),Mt=BigInt(1),Dc=BigInt(2),Vc=BigInt(7),Mc=BigInt(256),Kc=BigInt(113),Gs=[],qs=[],Ds=[];for(let e=0,t=Mt,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Gs.push(2*(5*n+r)),qs.push((e+1)*(e+2)/2%64);let o=qc;for(let s=0;s<7;s++)t=(t<<Mt^(t>>Vc)*Kc)%Mc,t&Dc&&(o^=Mt<<(Mt<<BigInt(s))-Mt);Ds.push(o)}var Vs=(0,Kt.split)(Ds,!0),Wc=Vs[0],Xc=Vs[1],Os=(e,t,r)=>r>32?(0,Kt.rotlBH)(e,t,r):(0,Kt.rotlSH)(e,t,r),Ns=(e,t,r)=>r>32?(0,Kt.rotlBL)(e,t,r):(0,Kt.rotlSL)(e,t,r);function Ms(e,t=24){let r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)r[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,l=(i+2)%10,u=r[l],p=r[l+1],f=Os(u,p,1)^r[a],h=Ns(u,p,1)^r[a+1];for(let g=0;g<50;g+=10)e[i+g]^=f,e[i+g+1]^=h}let o=e[2],s=e[3];for(let i=0;i<24;i++){let a=qs[i],l=Os(o,s,a),u=Ns(o,s,a),p=Gs[i];o=e[p],s=e[p+1],e[p]=l,e[p+1]=u}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=e[i+a];for(let a=0;a<10;a++)e[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Wc[n],e[1]^=Xc[n]}(0,X.clean)(r)}var Wt=class e extends X.Hash{constructor(t,r,n,o=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,(0,X.anumber)(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,X.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,X.swap32IfBE)(this.state32),Ms(this.state32,this.rounds),(0,X.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(t){(0,X.aexists)(this),t=(0,X.toBytes)(t),(0,X.abytes)(t);let{blockLen:r,state:n}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);for(let a=0;a<i;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:r,pos:n,blockLen:o}=this;t[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){(0,X.aexists)(this,!1),(0,X.abytes)(t),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,s=t.length;o<s;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);t.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return(0,X.anumber)(t),this.xofInto(new Uint8Array(t))}digestInto(t){if((0,X.aoutput)(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,X.clean)(this.state)}_cloneInto(t){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(r,n,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}};U.Keccak=Wt;var Ke=(e,t,r)=>(0,X.createHasher)(()=>new Wt(t,e,r));U.sha3_224=Ke(6,144,224/8);U.sha3_256=Ke(6,136,256/8);U.sha3_384=Ke(6,104,384/8);U.sha3_512=Ke(6,72,512/8);U.keccak_224=Ke(1,144,224/8);U.keccak_256=Ke(1,136,256/8);U.keccak_384=Ke(1,104,384/8);U.keccak_512=Ke(1,72,512/8);var Ks=(e,t,r)=>(0,X.createXOFer)((n={})=>new Wt(t,e,n.dkLen===void 0?r:n.dkLen,!0));U.shake128=Ks(31,168,128/8);U.shake256=Ks(31,136,256/8)});var Xs=me(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.verifyEnvEncryptPublicKey=Yc;var Jc=Ws(),Zc=Oe("@noble/curves/secp256k1");function Yc(e,t,r){if(t.length!==65)return null;let n=Buffer.from("dstack-env-encrypt-pubkey","utf8"),o=r;r.startsWith("0x")&&(o=r.slice(2));let s=Buffer.from(o,"hex"),i=Buffer.from(":","utf8"),a=Buffer.concat([n,i,s,Buffer.from(e)]),l=(0,Jc.keccak_256)(a);try{let u=t.slice(0,32),p=t.slice(32,64),f=t[64],h=new Uint8Array(64);h.set(u,0),h.set(p,32);let g=Zc.secp256k1.Signature.fromCompact(h).addRecoveryBit(f).recoverPublicKey(l);return"0x"+Buffer.from(g.toRawBytes(!0)).toString("hex")}catch(u){return console.error("signature verification failed:",u),null}}});var oi=Pt(Zn(),1);import{ofetch as Qc}from"ofetch";function Yn(e){return{all:e=e||new Map,on:function(t,r){var n=e.get(t);n?n.push(r):e.set(t,[r])},off:function(t,r){var n=e.get(t);n&&(r?n.splice(n.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var n=e.get(t);n&&n.slice().map(function(o){o(r)}),(n=e.get("*"))&&n.slice().map(function(o){o(t,r)})}}}import{z as V}from"zod";import{z as F}from"zod";import{z as We}from"zod";import{z as S}from"zod";import{z as Xe}from"zod";function et(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}sr();tt();sr();var Yr={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Bt(e,t){let r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?nt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?nt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Yr[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=Ia(e.authorizationList)),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof r.v=="bigint"){if(r.v===0n||r.v===27n)return 0;if(r.v===1n||r.v===28n)return 1;if(r.v>=35n)return r.v%2n===0n?1:0}})(),r.type==="legacy"&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),r.type==="eip2930"&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),r.type==="eip1559"&&delete r.maxFeePerBlobGas,r}var no=dt("transaction",Bt);function Ia(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Aa(e,t){let r=(e.transactions??[]).map(n=>typeof n=="string"?n:Bt(n));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}var oo=dt("block",Aa);function so(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}tt();sr();var Pa={"0x0":"reverted","0x1":"success"};function $a(e,t){let r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(n=>so(n)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?nt(e.transactionIndex):null,status:e.status?Pa[e.status]:null,type:e.type?Yr[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}var io=dt("transactionReceipt",$a);de();en();qe();ge();function Ue(e,t="hex"){let r=lo(e),n=lr(new Uint8Array(r.length));return r.encode(n),t==="hex"?ae(n.bytes):n.bytes}function lo(e){return Array.isArray(e)?za(e.map(t=>lo(t))):Ra(e)}function za(e){let t=e.reduce((o,s)=>o+s.length,0),r=uo(t);return{length:t<=55?1+t:1+r+t,encode(o){t<=55?o.pushByte(192+t):(o.pushByte(247+r),r===1?o.pushUint8(t):r===2?o.pushUint16(t):r===3?o.pushUint24(t):o.pushUint32(t));for(let{encode:s}of e)s(o)}}}function Ra(e){let t=typeof e=="string"?ve(e):e,r=uo(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(o){t.length===1&&t[0]<128?o.pushBytes(t):t.length<=55?(o.pushByte(128+t.length),o.pushBytes(t)):(o.pushByte(183+r),r===1?o.pushUint8(t.length):r===2?o.pushUint16(t.length):r===3?o.pushUint24(t.length):o.pushUint32(t.length),o.pushBytes(t))}}}function uo(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new v("Length is too large.")}mr();ge();function bo(e){if(!e||e.length===0)return[];let t=[];for(let r of e){let{chainId:n,nonce:o,...s}=r,i=r.address;t.push([n?ye(n):"0x",i,o?ye(o):"0x",...ht({},s)])}return t}qe();ge();function dr(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>ve(s)):e.blobs,o=[];for(let s of n)o.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?o:o.map(s=>ae(s))}qe();ge();function hr(e){let{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(i=>ve(i)):e.blobs,o=typeof e.commitments[0]=="string"?e.commitments.map(i=>ve(i)):e.commitments,s=[];for(let i=0;i<n.length;i++){let a=n[i],l=o[i];s.push(Uint8Array.from(t.computeBlobKzgProof(a,l)))}return r==="bytes"?s:s.map(i=>ae(i))}ge();yr();function Na(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),l=n?4:0,u=n?0:4;e.setUint32(t+l,i,n),e.setUint32(t+u,a,n)}function yo(e,t,r){return e&t^~e&r}function vo(e,t,r){return e&t^e&r^t&r}var vr=class extends gt{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=br(this.buffer)}update(t){bt(this),t=Ft(t),st(t);let{view:r,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let l=br(t);for(;o<=s-i;i+=o)this.process(l,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){bt(this),gr(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,De(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)r[f]=0;Na(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=br(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=l/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,p[f],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Fe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);yr();var qa=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ve=new Uint32Array(64),_r=class extends vr{constructor(t=32){super(64,t,8,!1),this.A=Fe[0]|0,this.B=Fe[1]|0,this.C=Fe[2]|0,this.D=Fe[3]|0,this.E=Fe[4]|0,this.F=Fe[5]|0,this.G=Fe[6]|0,this.H=Fe[7]|0}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:l}=this;return[t,r,n,o,s,i,a,l]}set(t,r,n,o,s,i,a,l){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=l|0}process(t,r){for(let f=0;f<16;f++,r+=4)Ve[f]=t.getUint32(r,!1);for(let f=16;f<64;f++){let h=Ve[f-15],g=Ve[f-2],C=we(h,7)^we(h,18)^h>>>3,P=we(g,17)^we(g,19)^g>>>10;Ve[f]=P+Ve[f-7]+C+Ve[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:l,G:u,H:p}=this;for(let f=0;f<64;f++){let h=we(a,6)^we(a,11)^we(a,25),g=p+h+yo(a,l,u)+qa[f]+Ve[f]|0,P=(we(n,2)^we(n,13)^we(n,22))+vo(n,o,s)|0;p=u,u=l,l=a,a=i+g|0,i=s,s=o,o=n,n=g+P|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,l=l+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(n,o,s,i,a,l,u,p)}roundClean(){De(Ve)}destroy(){this.set(0,0,0,0,0,0,0,0),De(this.buffer)}};var Io=xr(()=>new _r);var Ao=Io;mt();qe();ge();function Po(e,t){let r=t||"hex",n=Ao(Ee(e,{strict:!1})?or(e):e);return r==="bytes"?n:ye(n)}function $o(e){let{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),o=Po(t,"bytes");return o.set([r],0),n==="bytes"?o:ae(o)}function Lo(e){let{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),o=[];for(let s of t)o.push($o({commitment:s,to:n,version:r}));return o}de();var Cr=class extends v{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}},xt=class extends v{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}},kr=class extends v{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}},Sr=class extends v{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${1}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}};en();$t();qe();ge();function zo(e){let t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?ve(e.data):e.data,n=he(r);if(!n)throw new xt;if(n>761855)throw new Cr({maxSize:761855,size:n});let o=[],s=!0,i=0;for(;s;){let a=lr(new Uint8Array(131072)),l=0;for(;l<4096;){let u=r.slice(i,i+31);if(a.pushByte(0),a.pushBytes(u),u.length<31){a.pushByte(128),s=!1;break}l++,i+=31}o.push(a)}return t==="bytes"?o.map(a=>a.bytes):o.map(a=>ae(a.bytes))}function Ro(e){let{data:t,kzg:r,to:n}=e,o=e.blobs??zo({data:t,to:n}),s=e.commitments??dr({blobs:o,kzg:r,to:n}),i=e.proofs??hr({blobs:o,commitments:s,kzg:r,to:n}),a=[];for(let l=0;l<o.length;l++)a.push({blob:o[l],commitment:s[l],proof:i[l]});return a}Qr();to();ge();ao();Er();de();Bo();jo();Ir();$t();Yo();tt();function Qo(e){let{authorizationList:t}=e;if(t)for(let r of t){let{chainId:n}=r,o=r.address;if(!Te(o))throw new be({address:o});if(n<0)throw new it({chainId:n})}Ar(e)}function es(e){let{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new xt;for(let r of t){let n=he(r),o=nt(Xo(r,0,1));if(n!==32)throw new kr({hash:r,size:n});if(o!==1)throw new Sr({hash:r,version:o})}}Ar(e)}function Ar(e){let{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:o}=e;if(t<=0)throw new it({chainId:t});if(o&&!Te(o))throw new be({address:o});if(n&&n>ir)throw new at({maxFeePerGas:n});if(r&&n&&r>n)throw new Ht({maxFeePerGas:n,maxPriorityFeePerGas:r})}function ts(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(t<=0)throw new it({chainId:t});if(s&&!Te(s))throw new be({address:s});if(r||o)throw new v("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>ir)throw new at({maxFeePerGas:n})}function rs(e){let{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:o,to:s}=e;if(s&&!Te(s))throw new be({address:s});if(typeof t<"u"&&t<=0)throw new it({chainId:t});if(r||o)throw new v("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>ir)throw new at({maxFeePerGas:n})}mr();function ns(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new pr({transaction:e})}Er();mr();Ir();function Nt(e){if(!e||e.length===0)return[];let t=[];for(let r=0;r<e.length;r++){let{address:n,storageKeys:o}=e[r];for(let s=0;s<o.length;s++)if(o[s].length-2!==64)throw new fr({storageKey:o[s]});if(!Te(n,{strict:!1}))throw new be({address:n});t.push([n,o])}return t}function os(e,t){let r=ns(e);return r==="eip1559"?ic(e,t):r==="eip2930"?ac(e,t):r==="eip4844"?sc(e,t):r==="eip7702"?oc(e,t):cc(e,t)}function oc(e,t){let{authorizationList:r,chainId:n,gas:o,nonce:s,to:i,value:a,maxFeePerGas:l,maxPriorityFeePerGas:u,accessList:p,data:f}=e;Qo(e);let h=Nt(p),g=bo(r);return ot(["0x04",Ue([E(n),s?E(s):"0x",u?E(u):"0x",l?E(l):"0x",o?E(o):"0x",i??"0x",a?E(a):"0x",f??"0x",h,g,...ht(e,t)])])}function sc(e,t){let{chainId:r,gas:n,nonce:o,to:s,value:i,maxFeePerBlobGas:a,maxFeePerGas:l,maxPriorityFeePerGas:u,accessList:p,data:f}=e;es(e);let h=e.blobVersionedHashes,g=e.sidecars;if(e.blobs&&(typeof h>"u"||typeof g>"u")){let W=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(fe=>ae(fe)),Q=e.kzg,se=dr({blobs:W,kzg:Q});if(typeof h>"u"&&(h=Lo({commitments:se})),typeof g>"u"){let fe=hr({blobs:W,commitments:se,kzg:Q});g=Ro({blobs:W,commitments:se,proofs:fe})}}let C=Nt(p),P=[E(r),o?E(o):"0x",u?E(u):"0x",l?E(l):"0x",n?E(n):"0x",s??"0x",i?E(i):"0x",f??"0x",C,a?E(a):"0x",h??[],...ht(e,t)],R=[],q=[],Y=[];if(g)for(let W=0;W<g.length;W++){let{blob:Q,commitment:se,proof:fe}=g[W];R.push(Q),q.push(se),Y.push(fe)}return ot(["0x03",g?Ue([P,R,q,Y]):Ue(P)])}function ic(e,t){let{chainId:r,gas:n,nonce:o,to:s,value:i,maxFeePerGas:a,maxPriorityFeePerGas:l,accessList:u,data:p}=e;Ar(e);let f=Nt(u),h=[E(r),o?E(o):"0x",l?E(l):"0x",a?E(a):"0x",n?E(n):"0x",s??"0x",i?E(i):"0x",p??"0x",f,...ht(e,t)];return ot(["0x02",Ue(h)])}function ac(e,t){let{chainId:r,gas:n,data:o,nonce:s,to:i,value:a,accessList:l,gasPrice:u}=e;ts(e);let p=Nt(l),f=[E(r),s?E(s):"0x",u?E(u):"0x",n?E(n):"0x",i??"0x",a?E(a):"0x",o??"0x",p,...ht(e,t)];return ot(["0x01",Ue(f)])}function cc(e,t){let{chainId:r=0,gas:n,data:o,nonce:s,to:i,value:a,gasPrice:l}=e;rs(e);let u=[s?E(s):"0x",l?E(l):"0x",n?E(n):"0x",i??"0x",a?E(a):"0x",o??"0x"];if(t){let p=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);let g=27n+(t.v===27n?0n:1n);if(t.v!==g)throw new ur({v:t.v});return g})(),f=Lt(t.r),h=Lt(t.s);u=[...u,E(p),f==="0x00"?"0x":f,h==="0x00"?"0x":h]}else r>0&&(u=[...u,E(r),"0x","0x"]);return Ue(u)}function ht(e,t){let r=t??e,{v:n,yParity:o}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof o>"u")return[];let s=Lt(r.r),i=Lt(r.s);return[typeof o=="number"?o?E(1):"0x":n===0n?"0x":n===1n?E(1):n===27n?"0x":E(1),s==="0x00"?"0x":s,i==="0x00"?"0x":i]}var ss={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};tt();var is={block:oo({format(e){return{transactions:e.transactions?.map(r=>{if(typeof r=="string")return r;let n=Bt(r);return n.typeHex==="0x7e"&&(n.isSystemTx=r.isSystemTx,n.mint=r.mint?rt(r.mint):void 0,n.sourceHash=r.sourceHash,n.type="deposit"),n}),stateRoot:e.stateRoot}}}),transaction:no({format(e){let t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?rt(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:io({format(e){return{l1GasPrice:e.l1GasPrice?rt(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?rt(e.l1GasUsed):null,l1Fee:e.l1Fee?rt(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};Er();Ir();Qr();ge();function lc(e,t){return pc(e)?uc(e):os(e,t)}var as={transaction:lc};function uc(e){fc(e);let{sourceHash:t,data:r,from:n,gas:o,isSystemTx:s,mint:i,to:a,value:l}=e,u=[t,n,a??"0x",i?ye(i):"0x",l?ye(l):"0x",o?ye(o):"0x",s?"0x1":"0x",r??"0x"];return ot(["0x7e",Ue(u)])}function pc(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function fc(e){let{from:t,to:r}=e;if(t&&!Te(t))throw new be({address:t});if(r&&!Te(r))throw new be({address:r})}var gn={blockTime:2e3,contracts:ss,formatters:is,serializers:as};var Pr=et({id:31337,name:"Anvil",nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["http://127.0.0.1:8545"],webSocket:["ws://127.0.0.1:8545"]}}});var Gt=1,qt=et({...gn,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...gn.contracts,disputeGameFactory:{[Gt]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[Gt]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[Gt]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[Gt]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:Gt}),mc=et({...qt,experimental_preconfirmationTime:200,rpcUrls:{default:{http:["https://mainnet-preconf.base.org"]}}});var $r=et({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}});import{z as N}from"zod";import{z as re}from"zod";import{z as m}from"zod";import{z as d}from"zod";import{z as Ct}from"zod";import{z as kt}from"zod";import{z as k}from"zod";import{z as J}from"zod";import{z as T}from"zod";import bu from"crypto";import{z as Pe}from"zod";import{z as _e}from"zod";import{z as K}from"zod";import{z as le}from"zod";import{z as ue}from"zod";import{z as Xu}from"zod";import{z as Ys}from"zod";import{z as $e}from"zod";import{z as At}from"zod";import{z as lt}from"zod";import{z as B}from"zod";import{z as Cp}from"zod";import{z as Tp}from"zod";import{z}from"zod";import{z as Ae}from"zod";import{z as Gp}from"zod";import{z as O}from"zod";import{z as y}from"zod";import{z as Tt}from"zod";import{z as Pn}from"zod";import{z as Z}from"zod";import{z as Ei}from"zod";import{z as Ie}from"zod";import{z as ce}from"zod";import{z as Je}from"zod";import{z as $n}from"zod";import{z as zn}from"zod";import{z as ct}from"zod";import{z as b}from"zod";import{z as A}from"zod";import{z as I}from"zod";import{z as G}from"zod";var vy=Pt(yn(),1);import{z as H}from"zod";var fm=Pt(yn(),1),mm=Pt(cs(),1),dm=Pt(Xs(),1);import{z as St}from"zod";import{z as ke}from"zod";import{z as Yf}from"zod";import{z as Et}from"zod";import{z as Ce}from"zod";import{z as M}from"zod";import{z as te}from"zod";import{z as Xt}from"zod";import{z as pe}from"zod";import{z as ti}from"zod";import{z as ri}from"zod";import{z as Br}from"zod";import{z as jr}from"zod";import{z as ee}from"zod";import{z as $}from"zod";var el=V.object({detail:V.union([V.string(),V.array(V.object({msg:V.string(),type:V.string().optional(),ctx:V.record(V.unknown()).optional(),loc:V.array(V.union([V.string(),V.number()])).optional(),input:V.unknown().optional()}).passthrough()),V.record(V.unknown())]).optional(),type:V.string().optional(),code:V.string().optional()}),Le=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,this.status=t.status,this.statusText=t.statusText,this.detail=t.detail,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},In=class Ur extends Le{constructor(t,r){super(t,{status:r?.status??0,statusText:r?.statusText??"Unknown Error",detail:r?.detail||t}),this.name="RequestError",this.isRequestError=!0,this.data=r?.data,this.request=r?.request,this.response=r?.response,this.code=r?.code,this.type=r?.type}static fromFetchError(t){let r=el.safeParse(t.data);return r.success?new Ur(t.message,{status:t.status??void 0,statusText:t.statusText??void 0,data:t.data,request:t.request??void 0,response:t.response??void 0,detail:r.data.detail,code:r.data.code??void 0,type:r.data.type??void 0}):new Ur(t.message,{status:t.status??void 0,statusText:t.statusText??void 0,data:t.data,request:t.request??void 0,response:t.response??void 0,detail:t.data?.detail||"Unknown API error",code:t.status?.toString()??void 0})}static fromError(t,r){return new Ur(t.message,{request:r??void 0,detail:t.message})}},tl=class extends Le{constructor(e,t){super(e,t),this.isValidationError=!0,this.validationErrors=t.validationErrors}},rl=class extends Le{constructor(){super(...arguments),this.isAuthError=!0}},si=class extends Le{constructor(){super(...arguments),this.isBusinessError=!0}},nl=class extends Le{constructor(){super(...arguments),this.isServerError=!0}},ol=class extends Le{constructor(){super(...arguments),this.isUnknownError=!0}};function sl(e){if(!e||!Array.isArray(e))return"unknown";let t=e.filter(r=>typeof r=="string"?!["body","query","path","header"].includes(r):!0);return t.length>0?t.join("."):"unknown"}function ii(e){if(!Array.isArray(e))return{errors:[],message:typeof e=="string"?e:"Validation error"};let t=e.map((o,s)=>{let i=sl(o.loc),a=i;return i==="unknown"&&o.type&&(a=o.type==="missing"?"required field":o.type),{field:a,message:o.msg,type:o.type,context:o.ctx}}),r=t.length,n=r===1?`Validation failed: ${t[0].message}`:`Validation failed (${r} issue${r>1?"s":""})`;return{errors:t,message:n}}function il(e){return e===422?"validation":e===401||e===403?"auth":e>=400&&e<500?"business":e>=500?"server":"unknown"}function al(e,t,r){if(e===422&&Array.isArray(t)){let{message:n}=ii(t);return n}if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t){let n=t.message;if(typeof n=="string")return n}return r}function cl(e){let t=e.status??0,r=e.statusText??"Unknown Error",n=e.detail,o=ul(n);if(o)return new ll(o.message,{status:t,statusText:r,detail:n,errorCode:o.error_code,structuredDetails:o.details,suggestions:o.suggestions,links:o.links});let s=il(t),i=al(t,n,e.message),a={status:t,statusText:r,detail:n};if(s==="validation"&&Array.isArray(n)){let{errors:l}=ii(n);return new tl(i,{...a,validationErrors:l})}return s==="auth"?new rl(i,a):s==="business"?new si(i,a):s==="server"?new nl(i,a):new ol(i,a)}var ll=class extends si{constructor(e,t){super(e,t),this.isResourceError=!0,this.errorCode=t.errorCode,this.structuredDetails=t.structuredDetails,this.suggestions=t.suggestions,this.links=t.links}};function ul(e){if(!e||typeof e!="object")return null;let t=e;return t.error_code&&typeof t.error_code=="string"&&t.message&&typeof t.message=="string"?{error_code:t.error_code,message:t.message,details:t.details,suggestions:t.suggestions,links:t.links}:null}var Hr=["2025-10-28","2026-01-21"],pl="2026-01-21",_t=(0,oi.default)("phala::api-client");function fl(e){return Object.entries(e).map(([t,r])=>` -H "${t}: ${r}"`).join(`
12
- `)}function ml(e){return e?` -d '${(typeof e=="string"?e:JSON.stringify(e,null,2)).replace(/'/g,"\\'")}'`:""}function Js(e,t,r,n){let o=[];r.forEach((a,l)=>{o.push(`${l}: ${a}`)});let s=o.join(`
13
- `),i=typeof n=="string"?n:JSON.stringify(n,null,2);return[`< HTTP/1.1 ${e} ${t}`,s?`< ${s.replace(/\n/g,`
14
- < `)}`:"","",i].filter(Boolean).join(`
15
- `)}var dl=class ai{constructor(t={}){this.emitter=Yn();let r=t.apiKey||process?.env?.PHALA_CLOUD_API_KEY,n=t.baseURL||process?.env?.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.com/api/v1",o=t.version&&Hr.includes(t.version)?t.version:pl;this.config={...t,apiKey:r,baseURL:n,version:o};let{apiKey:s,baseURL:i,timeout:a,headers:l,useCookieAuth:u,onResponseError:p,...f}=this.config,h={"X-Phala-Version":o,"Content-Type":"application/json"};l&&typeof l=="object"&&Object.entries(l).forEach(([g,C])=>{typeof C=="string"&&(h[g]=C)}),!u&&s&&(h["X-API-Key"]=s),this.fetchInstance=Qc.create({baseURL:i,timeout:a||3e4,headers:h,...u?{credentials:"include"}:{},...f,onRequest({request:g,options:C}){if(_t.enabled){let P=C.method||"GET",R=typeof g=="string"?g:g.url,q=R.startsWith("http")?R:`${i}${R}`,Y={};C.headers&&typeof C.headers=="object"&&Object.entries(C.headers).forEach(([Q,se])=>{typeof se=="string"&&(Y[Q]=se)});let W=[`> curl -X ${P} "${q}"`,fl(Y),C.body?ml(C.body):""].filter(Boolean).join(`
16
- `);_t(`
4
+ `+o),e.push(s+"m+"+mt.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=_s()+t+" "+e[0]}function _s(){return V.inspectOpts.hideDate?"":new Date().toISOString()+" "}function ws(...e){return process.stderr.write(dt.formatWithOptions(V.inspectOpts,...e)+`
5
+ `)}function Cs(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function ks(){return process.env.DEBUG}function Ss(e){e.inspectOpts={};let t=Object.keys(V.inspectOpts);for(let n=0;n<t.length;n++)e.inspectOpts[t[n]]=V.inspectOpts[t[n]]}mt.exports=At()(V);var{formatters:an}=mt.exports;an.o=function(e){return this.inspectOpts.colors=this.useColors,dt.inspect(e,this.inspectOpts).split(`
6
+ `).map(t=>t.trim()).join(" ")};an.O=function(e){return this.inspectOpts.colors=this.useColors,dt.inspect(e,this.inspectOpts)}});var ln=pe((gu,xt)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?xt.exports=on():xt.exports=cn()});var jt=pe(nt=>{"use strict";var Es=nt&&nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(nt,"__esModule",{value:!0});nt.encryptEnvVars=Is;var It=Re("@noble/curves/ed25519"),Rt=Es(Re("crypto"));function As(e){var t,n;return e=e.startsWith("0x")?e.slice(2):e,new Uint8Array((n=(t=e.match(/.{1,2}/g))===null||t===void 0?void 0:t.map(r=>parseInt(r,16)))!==null&&n!==void 0?n:[])}function xs(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Is(e,t){let n=JSON.stringify({env:e}),r=It.x25519.utils.randomPrivateKey(),s=It.x25519.getPublicKey(r),o=As(t),a=It.x25519.getSharedSecret(r,o),c=await Rt.default.subtle.importKey("raw",a,{name:"AES-GCM",length:256},!0,["encrypt"]),l=Rt.default.getRandomValues(new Uint8Array(12)),m=await Rt.default.subtle.encrypt({name:"AES-GCM",iv:l},c,new TextEncoder().encode(n)),d=new Uint8Array(s.length+l.length+m.byteLength);return d.set(s),d.set(l,s.length),d.set(new Uint8Array(m),s.length+l.length),xs(d)}});var pn=pe(rt=>{"use strict";var Rs=rt&&rt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(rt,"__esModule",{value:!0});rt.getComposeHash=$s;var js=Rs(Re("crypto"));function Pt(e){return e==null?e:Array.isArray(e)?e.map(Pt):e&&typeof e=="object"&&e.constructor===Object?Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return t[n]=Pt(r),t},{}):e}function Ps(e){let t={...e};return t.runner==="bash"&&"docker_compose_file"in t?delete t.docker_compose_file:t.runner==="docker-compose"&&"bash_script"in t&&delete t.bash_script,"pre_launch_script"in t&&!t.pre_launch_script&&delete t.pre_launch_script,t}function Ts(e){let t=Pt(e);return JSON.stringify(t,(n,r)=>typeof r=="number"&&(isNaN(r)||!isFinite(r))?null:r)}function $s(e,t=!1){t&&(e=Ps(e));let n=Ts(e);return js.default.createHash("sha256").update(n,"utf8").digest("hex")}});var $n=pe(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.toBig=_.shrSL=_.shrSH=_.rotrSL=_.rotrSH=_.rotrBL=_.rotrBH=_.rotr32L=_.rotr32H=_.rotlSL=_.rotlSH=_.rotlBL=_.rotlBH=_.add5L=_.add5H=_.add4L=_.add4H=_.add3L=_.add3H=void 0;_.add=An;_.fromBig=$t;_.split=dn;var ft=BigInt(2**32-1),Tt=BigInt(32);function $t(e,t=!1){return t?{h:Number(e&ft),l:Number(e>>Tt&ft)}:{h:Number(e>>Tt&ft)|0,l:Number(e&ft)|0}}function dn(e,t=!1){let n=e.length,r=new Uint32Array(n),s=new Uint32Array(n);for(let o=0;o<n;o++){let{h:a,l:c}=$t(e[o],t);[r[o],s[o]]=[a,c]}return[r,s]}var mn=(e,t)=>BigInt(e>>>0)<<Tt|BigInt(t>>>0);_.toBig=mn;var fn=(e,t,n)=>e>>>n;_.shrSH=fn;var gn=(e,t,n)=>e<<32-n|t>>>n;_.shrSL=gn;var hn=(e,t,n)=>e>>>n|t<<32-n;_.rotrSH=hn;var bn=(e,t,n)=>e<<32-n|t>>>n;_.rotrSL=bn;var yn=(e,t,n)=>e<<64-n|t>>>n-32;_.rotrBH=yn;var vn=(e,t,n)=>e>>>n-32|t<<64-n;_.rotrBL=vn;var _n=(e,t)=>t;_.rotr32H=_n;var wn=(e,t)=>e;_.rotr32L=wn;var Cn=(e,t,n)=>e<<n|t>>>32-n;_.rotlSH=Cn;var kn=(e,t,n)=>t<<n|e>>>32-n;_.rotlSL=kn;var Sn=(e,t,n)=>t<<n-32|e>>>64-n;_.rotlBH=Sn;var En=(e,t,n)=>e<<n-32|t>>>64-n;_.rotlBL=En;function An(e,t,n,r){let s=(t>>>0)+(r>>>0);return{h:e+n+(s/2**32|0)|0,l:s|0}}var xn=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);_.add3L=xn;var In=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;_.add3H=In;var Rn=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);_.add4L=Rn;var jn=(e,t,n,r,s)=>t+n+r+s+(e/2**32|0)|0;_.add4H=jn;var Pn=(e,t,n,r,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(s>>>0);_.add5L=Pn;var Tn=(e,t,n,r,s,o)=>t+n+r+s+o+(e/2**32|0)|0;_.add5H=Tn;var Ls={fromBig:$t,split:dn,toBig:mn,shrSH:fn,shrSL:gn,rotrSH:hn,rotrSL:bn,rotrBH:yn,rotrBL:vn,rotr32H:_n,rotr32L:wn,rotlSH:Cn,rotlSL:kn,rotlBH:Sn,rotlBL:En,add:An,add3L:xn,add3H:In,add4L:Rn,add4H:jn,add5H:Tn,add5L:Pn};_.default=Ls});var Ln=pe(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.crypto=void 0;var je=Re("crypto");gt.crypto=je&&typeof je=="object"&&"webcrypto"in je?je.webcrypto:je&&typeof je=="object"&&"randomBytes"in je?je:void 0});var Bn=pe(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.wrapXOFConstructorWithOpts=h.wrapConstructorWithOpts=h.wrapConstructor=h.Hash=h.nextTick=h.swap32IfBE=h.byteSwapIfBE=h.swap8IfBE=h.isLE=void 0;h.isBytes=qn;h.anumber=Lt;h.abytes=Ke;h.ahash=Os;h.aexists=qs;h.aoutput=Fs;h.u8=zs;h.u32=Us;h.clean=Ns;h.createView=Ds;h.rotr=Bs;h.rotl=Hs;h.byteSwap=qt;h.byteSwap32=Fn;h.bytesToHex=Ks;h.hexToBytes=Gs;h.asyncLoop=Ws;h.utf8ToBytes=Ft;h.bytesToUtf8=Js;h.toBytes=ht;h.kdfInputToBytes=Xs;h.concatBytes=Zs;h.checkOpts=Qs;h.createHasher=Un;h.createOptHasher=Nn;h.createXOFer=Dn;h.randomBytes=Ys;var Ve=Ln();function qn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Lt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ke(e,...t){if(!qn(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Os(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Lt(e.outputLen),Lt(e.blockLen)}function qs(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Fs(e,t){Ke(e);let n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function zs(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Us(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ns(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ds(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Bs(e,t){return e<<32-t|e>>>t}function Hs(e,t){return e<<t|e>>>32-t>>>0}h.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qt(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}h.swap8IfBE=h.isLE?e=>e:e=>qt(e);h.byteSwapIfBE=h.swap8IfBE;function Fn(e){for(let t=0;t<e.length;t++)e[t]=qt(e[t]);return e}h.swap32IfBE=h.isLE?e=>e:Fn;var zn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ks(e){if(Ke(e),zn)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Vs[e[n]];return t}var Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function On(e){if(e>=Ae._0&&e<=Ae._9)return e-Ae._0;if(e>=Ae.A&&e<=Ae.F)return e-(Ae.A-10);if(e>=Ae.a&&e<=Ae.f)return e-(Ae.a-10)}function Gs(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(zn)return Uint8Array.fromHex(e);let t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let a=On(e.charCodeAt(o)),c=On(e.charCodeAt(o+1));if(a===void 0||c===void 0){let l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}r[s]=a*16+c}return r}var Ms=async()=>{};h.nextTick=Ms;async function Ws(e,t,n){let r=Date.now();for(let s=0;s<e;s++){n(s);let o=Date.now()-r;o>=0&&o<t||(await(0,h.nextTick)(),r+=o)}}function Ft(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Js(e){return new TextDecoder().decode(e)}function ht(e){return typeof e=="string"&&(e=Ft(e)),Ke(e),e}function Xs(e){return typeof e=="string"&&(e=Ft(e)),Ke(e),e}function Zs(...e){let t=0;for(let r=0;r<e.length;r++){let s=e[r];Ke(s),t+=s.length}let n=new Uint8Array(t);for(let r=0,s=0;r<e.length;r++){let o=e[r];n.set(o,s),s+=o.length}return n}function Qs(e,t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(e,t)}var Ot=class{};h.Hash=Ot;function Un(e){let t=r=>e().update(ht(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Nn(e){let t=(r,s)=>e(s).update(ht(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}function Dn(e){let t=(r,s)=>e(s).update(ht(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}h.wrapConstructor=Un;h.wrapConstructorWithOpts=Nn;h.wrapXOFConstructorWithOpts=Dn;function Ys(e=32){if(Ve.crypto&&typeof Ve.crypto.getRandomValues=="function")return Ve.crypto.getRandomValues(new Uint8Array(e));if(Ve.crypto&&typeof Ve.crypto.randomBytes=="function")return Uint8Array.from(Ve.crypto.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}});var Zn=pe($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.shake256=$.shake128=$.keccak_512=$.keccak_384=$.keccak_256=$.keccak_224=$.sha3_512=$.sha3_384=$.sha3_256=$.sha3_224=$.Keccak=void 0;$.keccakP=Jn;var ot=$n(),X=Bn(),eo=BigInt(0),st=BigInt(1),to=BigInt(2),no=BigInt(7),ro=BigInt(256),so=BigInt(113),Kn=[],Gn=[],Mn=[];for(let e=0,t=st,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Kn.push(2*(5*r+n)),Gn.push((e+1)*(e+2)/2%64);let s=eo;for(let o=0;o<7;o++)t=(t<<st^(t>>no)*so)%ro,t&to&&(s^=st<<(st<<BigInt(o))-st);Mn.push(s)}var Wn=(0,ot.split)(Mn,!0),oo=Wn[0],ao=Wn[1],Hn=(e,t,n)=>n>32?(0,ot.rotlBH)(e,t,n):(0,ot.rotlSH)(e,t,n),Vn=(e,t,n)=>n>32?(0,ot.rotlBL)(e,t,n):(0,ot.rotlSL)(e,t,n);function Jn(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let a=0;a<10;a++)n[a]=e[a]^e[a+10]^e[a+20]^e[a+30]^e[a+40];for(let a=0;a<10;a+=2){let c=(a+8)%10,l=(a+2)%10,m=n[l],d=n[l+1],f=Hn(m,d,1)^n[c],b=Vn(m,d,1)^n[c+1];for(let C=0;C<50;C+=10)e[a+C]^=f,e[a+C+1]^=b}let s=e[2],o=e[3];for(let a=0;a<24;a++){let c=Gn[a],l=Hn(s,o,c),m=Vn(s,o,c),d=Kn[a];s=e[d],o=e[d+1],e[d]=l,e[d+1]=m}for(let a=0;a<50;a+=10){for(let c=0;c<10;c++)n[c]=e[a+c];for(let c=0;c<10;c++)e[a+c]^=~n[(c+2)%10]&n[(c+4)%10]}e[0]^=oo[r],e[1]^=ao[r]}(0,X.clean)(n)}var at=class e extends X.Hash{constructor(t,n,r,s=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,(0,X.anumber)(r),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=(0,X.u32)(this.state)}clone(){return this._cloneInto()}keccak(){(0,X.swap32IfBE)(this.state32),Jn(this.state32,this.rounds),(0,X.swap32IfBE)(this.state32),this.posOut=0,this.pos=0}update(t){(0,X.aexists)(this),t=(0,X.toBytes)(t),(0,X.abytes)(t);let{blockLen:n,state:r}=this,s=t.length;for(let o=0;o<s;){let a=Math.min(n-this.pos,s-o);for(let c=0;c<a;c++)r[this.pos++]^=t[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:s}=this;t[r]^=n,(n&128)!==0&&r===s-1&&this.keccak(),t[s-1]^=128,this.keccak()}writeInto(t){(0,X.aexists)(this,!1),(0,X.abytes)(t),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=t.length;s<o;){this.posOut>=r&&this.keccak();let a=Math.min(r-this.posOut,o-s);t.set(n.subarray(this.posOut,this.posOut+a),s),this.posOut+=a,s+=a}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return(0,X.anumber)(t),this.xofInto(new Uint8Array(t))}digestInto(t){if((0,X.aoutput)(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,X.clean)(this.state)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:a}=this;return t||(t=new e(n,r,s,a,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=r,t.outputLen=s,t.enableXOF=a,t.destroyed=this.destroyed,t}};$.Keccak=at;var Pe=(e,t,n)=>(0,X.createHasher)(()=>new at(t,e,n));$.sha3_224=Pe(6,144,224/8);$.sha3_256=Pe(6,136,256/8);$.sha3_384=Pe(6,104,384/8);$.sha3_512=Pe(6,72,512/8);$.keccak_224=Pe(1,144,224/8);$.keccak_256=Pe(1,136,256/8);$.keccak_384=Pe(1,104,384/8);$.keccak_512=Pe(1,72,512/8);var Xn=(e,t,n)=>(0,X.createXOFer)((r={})=>new at(t,e,r.dkLen===void 0?n:r.dkLen,!0));$.shake128=Xn(31,168,128/8);$.shake256=Xn(31,136,256/8)});var Qn=pe(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.verifyEnvEncryptPublicKey=lo;var io=Zn(),co=Re("@noble/curves/secp256k1");function lo(e,t,n){if(t.length!==65)return null;let r=Buffer.from("dstack-env-encrypt-pubkey","utf8"),s=n;n.startsWith("0x")&&(s=n.slice(2));let o=Buffer.from(s,"hex"),a=Buffer.from(":","utf8"),c=Buffer.concat([r,a,o,Buffer.from(e)]),l=(0,io.keccak_256)(c);try{let m=t.slice(0,32),d=t.slice(32,64),f=t[64],b=new Uint8Array(64);b.set(m,0),b.set(d,32);let C=co.secp256k1.Signature.fromCompact(b).addRecoveryBit(f).recoverPublicKey(l);return"0x"+Buffer.from(C.toRawBytes(!0)).toString("hex")}catch(m){return console.error("signature verification failed:",m),null}}});var ur=tt(ln(),1);import{ofetch as uo}from"ofetch";function un(e){return{all:e=e||new Map,on:function(t,n){var r=e.get(t);r?r.push(n):e.set(t,[n])},off:function(t,n){var r=e.get(t);r&&(n?r.splice(r.indexOf(n)>>>0,1):e.set(t,[]))},emit:function(t,n){var r=e.get(t);r&&r.slice().map(function(s){s(n)}),(r=e.get("*"))&&r.slice().map(function(s){s(t,n)})}}}var Op=tt(jt(),1),ql=tt(jt(),1),Fl=tt(pn(),1),zl=tt(Qn(),1);import{z as K}from"zod";import{z as L}from"zod";import{z as Te}from"zod";import{z as k}from"zod";import{z as $e}from"zod";import{anvil as er,base as tr,mainnet as nr}from"viem/chains";import{z as D}from"zod";import{z as te}from"zod";import{z as u}from"zod";import{z as p}from"zod";import{z as Me}from"zod";import{z as We}from"zod";import{z as w}from"zod";import{z as G}from"zod";import{z as E}from"zod";import Ra from"crypto";import{z as _e}from"zod";import{z as me}from"zod";import{z as J}from"zod";import{z as ie}from"zod";import{z as ce}from"zod";import{z as ii}from"zod";import{z as sr}from"zod";import{z as we}from"zod";import{z as et}from"zod";import{z as Ue}from"zod";import{z as j}from"zod";import{z as Oi}from"zod";import{z as Ui}from"zod";import{z as R}from"zod";import{z as ve}from"zod";import{z as ec}from"zod";import{z as N}from"zod";import{z as y}from"zod";import{z as Qe}from"zod";import{z as Dt}from"zod";import{z as Z}from"zod";import{z as Tr}from"zod";import{z as ye}from"zod";import{z as ae}from"zod";import{z as Le}from"zod";import{z as Bt}from"zod";import{z as Vt}from"zod";import{z as ze}from"zod";import{z as W}from"zod";import{z as B}from"zod";import{z as g}from"zod";import{z as x}from"zod";import{z as A}from"zod";import{z as H}from"zod";import{createPublicClient as Ip,createWalletClient as Rp,http as jp,parseEventLogs as Pp,parseEther as Tp}from"viem";import{privateKeyToAccount as Lp}from"viem/accounts";import{isHex as zp}from"viem";import{createPublicClient as Np,createWalletClient as Dp,http as Bp,custom as Hp}from"viem";import{privateKeyToAccount as Kp}from"viem/accounts";import{z as q}from"zod";import{createPublicClient as Xp,createWalletClient as Zp,http as Qp,parseEventLogs as Yp,parseEther as ed}from"viem";import{privateKeyToAccount as nd}from"viem/accounts";import{z as F}from"zod";import{createPublicClient as id,createWalletClient as cd,http as ld,parseEther as ud}from"viem";import{privateKeyToAccount as dd}from"viem/accounts";import{z}from"zod";import{createPublicClient as bd,createWalletClient as yd,http as vd,parseEther as _d}from"viem";import{privateKeyToAccount as Cd}from"viem/accounts";import{z as U}from"zod";import{createPublicClient as xd,createWalletClient as Id,http as Rd,parseEther as jd}from"viem";import{privateKeyToAccount as Td}from"viem/accounts";import{z as Je}from"zod";import{createPublicClient as Fd,http as zd}from"viem";import{createPublicClient as Dd,http as Bd}from"viem";import{z as Xe}from"zod";import{z as ge}from"zod";import{z as wl}from"zod";import{z as Ze}from"zod";import{z as fe}from"zod";import{z as M}from"zod";import{z as ee}from"zod";import{z as it}from"zod";import{z as le}from"zod";import{z as ir}from"zod";import{z as cr}from"zod";import{z as ne}from"zod";import{z as bt}from"zod";import{z as yt}from"zod";import{z as Y}from"zod";import{z as I}from"zod";var po=K.object({detail:K.union([K.string(),K.array(K.object({msg:K.string(),type:K.string().optional(),ctx:K.record(K.unknown()).optional(),loc:K.array(K.union([K.string(),K.number()])).optional(),input:K.unknown().optional()}).passthrough()),K.record(K.unknown())]).optional(),type:K.string().optional(),code:K.string().optional()}),Ce=class extends Error{constructor(e,t){super(e),this.name=this.constructor.name,this.status=t.status,this.statusText=t.statusText,this.detail=t.detail,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Ut=class vt extends Ce{constructor(t,n){super(t,{status:n?.status??0,statusText:n?.statusText??"Unknown Error",detail:n?.detail||t}),this.name="RequestError",this.isRequestError=!0,this.data=n?.data,this.request=n?.request,this.response=n?.response,this.code=n?.code,this.type=n?.type}static fromFetchError(t){let n=po.safeParse(t.data);return n.success?new vt(t.message,{status:t.status??void 0,statusText:t.statusText??void 0,data:t.data,request:t.request??void 0,response:t.response??void 0,detail:n.data.detail,code:n.data.code??void 0,type:n.data.type??void 0}):new vt(t.message,{status:t.status??void 0,statusText:t.statusText??void 0,data:t.data,request:t.request??void 0,response:t.response??void 0,detail:t.data?.detail||"Unknown API error",code:t.status?.toString()??void 0})}static fromError(t,n){return new vt(t.message,{request:n??void 0,detail:t.message})}},mo=class extends Ce{constructor(e,t){super(e,t),this.isValidationError=!0,this.validationErrors=t.validationErrors}},fo=class extends Ce{constructor(){super(...arguments),this.isAuthError=!0}},pr=class extends Ce{constructor(){super(...arguments),this.isBusinessError=!0}},go=class extends Ce{constructor(){super(...arguments),this.isServerError=!0}},ho=class extends Ce{constructor(){super(...arguments),this.isUnknownError=!0}};function bo(e){if(!e||!Array.isArray(e))return"unknown";let t=e.filter(n=>typeof n=="string"?!["body","query","path","header"].includes(n):!0);return t.length>0?t.join("."):"unknown"}function dr(e){if(!Array.isArray(e))return{errors:[],message:typeof e=="string"?e:"Validation error"};let t=e.map((s,o)=>{let a=bo(s.loc),c=a;return a==="unknown"&&s.type&&(c=s.type==="missing"?"required field":s.type),{field:c,message:s.msg,type:s.type,context:s.ctx}}),n=t.length,r=n===1?`Validation failed: ${t[0].message}`:`Validation failed (${n} issue${n>1?"s":""})`;return{errors:t,message:r}}function yo(e){return e===422?"validation":e===401||e===403?"auth":e>=400&&e<500?"business":e>=500?"server":"unknown"}function vo(e,t,n){if(e===422&&Array.isArray(t)){let{message:r}=dr(t);return r}if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t){let r=t.message;if(typeof r=="string")return r}return n}function _o(e){let t=e.status??0,n=e.statusText??"Unknown Error",r=e.detail,s=Co(r);if(s)return new wo(s.message,{status:t,statusText:n,detail:r,errorCode:s.error_code,structuredDetails:s.details,suggestions:s.suggestions,links:s.links});let o=yo(t),a=vo(t,r,e.message),c={status:t,statusText:n,detail:r};if(o==="validation"&&Array.isArray(r)){let{errors:l}=dr(r);return new mo(a,{...c,validationErrors:l})}return o==="auth"?new fo(a,c):o==="business"?new pr(a,c):o==="server"?new go(a,c):new ho(a,c)}var wo=class extends pr{constructor(e,t){super(e,t),this.isResourceError=!0,this.errorCode=t.errorCode,this.structuredDetails=t.structuredDetails,this.suggestions=t.suggestions,this.links=t.links}};function Co(e){if(!e||typeof e!="object")return null;let t=e;return t.error_code&&typeof t.error_code=="string"&&t.message&&typeof t.message=="string"?{error_code:t.error_code,message:t.message,details:t.details,suggestions:t.suggestions,links:t.links}:null}var wt=["2025-10-28","2026-01-21"],ko="2026-01-21",Ge=(0,ur.default)("phala::api-client");function So(e){return Object.entries(e).map(([t,n])=>` -H "${t}: ${n}"`).join(`
7
+ `)}function Eo(e){return e?` -d '${(typeof e=="string"?e:JSON.stringify(e,null,2)).replace(/'/g,"\\'")}'`:""}function Yn(e,t,n,r){let s=[];n.forEach((c,l)=>{s.push(`${l}: ${c}`)});let o=s.join(`
8
+ `),a=typeof r=="string"?r:JSON.stringify(r,null,2);return[`< HTTP/1.1 ${e} ${t}`,o?`< ${o.replace(/\n/g,`
9
+ < `)}`:"","",a].filter(Boolean).join(`
10
+ `)}var Ao=class mr{constructor(t={}){this.emitter=un();let n=t.apiKey||process?.env?.PHALA_CLOUD_API_KEY,r=t.baseURL||process?.env?.PHALA_CLOUD_API_PREFIX||"https://cloud-api.phala.com/api/v1",s=t.version&&wt.includes(t.version)?t.version:ko;this.config={...t,apiKey:n,baseURL:r,version:s};let{apiKey:o,baseURL:a,timeout:c,headers:l,useCookieAuth:m,onResponseError:d,...f}=this.config,b={"X-Phala-Version":s,"Content-Type":"application/json"};l&&typeof l=="object"&&Object.entries(l).forEach(([C,S])=>{typeof S=="string"&&(b[C]=S)}),!m&&o&&(b["X-API-Key"]=o),this.fetchInstance=uo.create({baseURL:a,timeout:c||3e4,headers:b,...m?{credentials:"include"}:{},...f,onRequest({request:C,options:S}){if(Ge.enabled){let T=S.method||"GET",O=typeof C=="string"?C:C.url,Q=O.startsWith("http")?O:`${a}${O}`,ue={};S.headers&&typeof S.headers=="object"&&Object.entries(S.headers).forEach(([be,Ie])=>{typeof Ie=="string"&&(ue[be]=Ie)});let xe=[`> curl -X ${T} "${Q}"`,So(ue),S.body?Eo(S.body):""].filter(Boolean).join(`
11
+ `);Ge(`
17
12
  === REQUEST ===
18
13
  %s
19
- `,W)}},onResponse({request:g,response:C,options:P}){if(_t.enabled){let R=P.method||"GET",q=typeof g=="string"?g:g.url;_t(`
14
+ `,xe)}},onResponse({request:C,response:S,options:T}){if(Ge.enabled){let O=T.method||"GET",Q=typeof C=="string"?C:C.url;Ge(`
20
15
  === RESPONSE [%s %s] (%dms) ===
21
16
  %s
22
- `,R,q,C.headers.get("x-response-time")||"?",Js(C.status,C.statusText,C.headers,C._data))}},onResponseError:({request:g,response:C,options:P})=>{if(_t.enabled){console.warn(`HTTP ${C.status}: ${C.url}`);let R=P.method||"GET",q=typeof g=="string"?g:g.url;_t(`
17
+ `,O,Q,S.headers.get("x-response-time")||"?",Yn(S.status,S.statusText,S.headers,S._data))}},onResponseError:({request:C,response:S,options:T})=>{if(Ge.enabled){console.warn(`HTTP ${S.status}: ${S.url}`);let O=T.method||"GET",Q=typeof C=="string"?C:C.url;Ge(`
23
18
  === ERROR RESPONSE [%s %s] ===
24
19
  %s
25
- `,R,q,Js(C.status,C.statusText,C.headers,C._data))}p&&p({request:g,response:C,options:P})}})}get raw(){return this.fetchInstance}on(t,r){this.emitter.on(t,r)}off(t,r){this.emitter.off(t,r)}once(t,r){let n=o=>{r(o),this.emitter.off(t,n)};this.emitter.on(t,n)}async request(t,r){try{let n=r?.method||"GET";return await this.fetchInstance(t,{...r,method:n})}catch(n){let o=this.convertToRequestError(n);throw this.emitError(o)}}async requestFull(t,r){try{let n=r?.method||"GET",o=await this.fetchInstance.raw(t,{...r,method:n,ignoreResponseError:!0});return{status:o.status,statusText:o.statusText,headers:o.headers,data:o._data,ok:o.ok}}catch(n){let o=this.convertToRequestError(n);throw this.emitError(o)}}async get(t,r){try{return await this.fetchInstance(t,{...r,method:"GET"})}catch(n){let o=this.convertToRequestError(n);throw this.emitError(o)}}async post(t,r,n){try{return await this.fetchInstance(t,{...n,method:"POST",body:r})}catch(o){let s=this.convertToRequestError(o);throw this.emitError(s)}}async put(t,r,n){try{return await this.fetchInstance(t,{...n,method:"PUT",body:r})}catch(o){let s=this.convertToRequestError(o);throw this.emitError(s)}}async patch(t,r,n){try{return await this.fetchInstance(t,{...n,method:"PATCH",body:r})}catch(o){let s=this.convertToRequestError(o);throw this.emitError(s)}}async delete(t,r){try{return await this.fetchInstance(t,{...r,method:"DELETE"})}catch(n){let o=this.convertToRequestError(n);throw this.emitError(o)}}convertToRequestError(t){return t&&typeof t=="object"&&"data"in t?In.fromFetchError(t):t instanceof Error?In.fromError(t):new In("Unknown error occurred",{detail:"Unknown error occurred"})}emitError(t){let r=cl(t);return this.emitter.emit("error",r),r}async safeRequest(t){try{return{success:!0,data:await t()}}catch(r){if(r instanceof Le)return{success:!1,error:r};let n=this.convertToRequestError(r);return this.emitError(n),{success:!1,error:n}}}async safeGet(t,r){return this.safeRequest(()=>this.get(t,r))}async safePost(t,r,n){return this.safeRequest(()=>this.post(t,r,n))}async safePut(t,r,n){return this.safeRequest(()=>this.put(t,r,n))}async safePatch(t,r,n){return this.safeRequest(()=>this.patch(t,r,n))}async safeDelete(t,r){return this.safeRequest(()=>this.delete(t,r))}async safeRequestMethod(t,r){return this.safeRequest(()=>this.request(t,r))}async safeRequestFull(t,r){return this.safeRequest(()=>this.requestFull(t,r))}withVersion(t){return new ai({...this.config,version:t})}extend(t){let r=typeof t=="function"?t(this):t,n=Object.create(this);for(let[o,s]of Object.entries(r))typeof s=="function"&&(n[o]=(...i)=>s(this,...i));return n}};function hl(e={}){return new dl(e)}var gl=F.object({username:F.string(),email:F.string(),role:F.enum(["admin","user"]),avatar:F.string(),email_verified:F.boolean(),totp_enabled:F.boolean(),has_backup_codes:F.boolean(),flag_has_password:F.boolean()}).passthrough(),bl=F.object({id:F.string(),name:F.string(),slug:F.string().nullable(),tier:F.string(),role:F.string(),avatar:F.string().nullable().optional()}).passthrough(),xl=F.object({balance:F.string().or(F.number()),granted_balance:F.string().or(F.number()),is_post_paid:F.boolean(),outstanding_amount:F.string().or(F.number()).nullable()}).passthrough(),yl=F.object({user:gl,workspace:bl,credits:xl}).passthrough(),vl=We.object({username:We.string(),email:We.string(),credits:We.number(),granted_credits:We.number(),avatar:We.string(),team_name:We.string(),team_tier:We.string()}).passthrough();function wl(e){return e==="2025-10-28"?vl:yl}async function ci(e,t){let r=await e.get("/auth/me");return t?.schema===!1?r:(t?.schema||wl(e.config.version)).parse(r)}async function _l(e,t){try{return{success:!0,data:await ci(e,t)}}catch(r){return r&&typeof r=="object"&&("status"in r||"issues"in r)?{success:!1,error:r}:{success:!1,error:{name:"Error",message:r instanceof Error?r.message:String(r)}}}}var Cl={[$r.id]:$r,[qt.id]:qt,[Pr.id]:Pr},kl=Xe.object({id:Xe.string(),slug:Xe.string().nullable(),url:Xe.string(),version:Xe.string(),chain_id:Xe.number().nullable(),kms_contract_address:Xe.string().nullable().transform(e=>e),gateway_app_id:Xe.string().nullable().transform(e=>e)}).passthrough(),ze=kl.transform(e=>{if(e.chain_id!=null){let t=Cl[e.chain_id];if(t)return{...e,chain:t}}return e});function li(e){if(e?.schema!==void 0&&e?.schema!==!1&&(typeof e.schema!="object"||e.schema===null||!("parse"in e.schema)||typeof e.schema.parse!="function"))throw new Error("Invalid schema: must be a Zod schema object, false, or undefined")}function ui(e){if(e?.schema!==void 0&&e?.schema!==!1&&(typeof e.schema!="object"||e.schema===null||!("parse"in e.schema)||typeof e.schema.parse!="function"))return{success:!1,error:{name:"ZodError",message:"Invalid schema: must be a Zod schema object, false, or undefined",issues:[{code:"invalid_type",expected:"object",received:typeof e.schema,path:["schema"],message:"Invalid schema: must be a Zod schema object, false, or undefined"}]}}}function pi(e,t){function r(i,a){return n(i,a)}async function n(i,a){li(a);let l=await t(i);return a?.schema===!1?l:(a?.schema||e).parse(l)}function o(i,a){return s(i,a)}async function s(i,a){let l=ui(a);if(l)return l;let u=await(async()=>{try{return{success:!0,data:await t(i)}}catch(f){return f&&typeof f=="object"&&"status"in f?{success:!1,error:f}:f&&typeof f=="object"&&"issues"in f?{success:!1,error:f}:{success:!1,error:{name:"Error",message:f instanceof Error?f.message:String(f)}}}})();return u.success?a?.schema===!1?{success:!0,data:u.data}:(a?.schema||e).safeParse(u.data):u}return{action:r,safeAction:o}}function _(e,t){function r(i,...a){let[l,u]=a;return n(i,l,u)}async function n(i,a,l){li(l);let u=await t(i,a);return l?.schema===!1?u:(l?.schema||e).parse(u)}function o(i,...a){let[l,u]=a;return s(i,l,u)}async function s(i,a,l){let u=ui(l);if(u)return u;let p=await(async()=>{try{return{success:!0,data:await t(i,a)}}catch(h){return h&&typeof h=="object"&&"status"in h?{success:!1,error:h}:h&&typeof h=="object"&&"issues"in h?{success:!1,error:h}:{success:!1,error:{name:"Error",message:h instanceof Error?h.message:String(h)}}}})();return p.success?l?.schema===!1?{success:!0,data:p.data}:(l?.schema||e).safeParse(p.data):p}return{action:r,safeAction:o}}var Sl=S.object({name:S.string(),is_dev:S.boolean(),version:S.union([S.tuple([S.number(),S.number(),S.number()]),S.tuple([S.number(),S.number(),S.number(),S.number()])]),os_image_hash:S.string().nullable().optional()}).passthrough(),El=S.object({teepod_id:S.number(),name:S.string(),listed:S.boolean(),resource_score:S.number(),remaining_vcpu:S.number(),remaining_memory:S.number(),remaining_cvm_slots:S.number(),images:S.array(Sl),support_onchain_kms:S.boolean().optional(),fmspc:S.string().nullable().optional(),device_id:S.string().nullable().optional(),region_identifier:S.string().nullable().optional(),default_kms:S.string().nullable().optional(),kms_list:S.array(S.string()).default([])}).passthrough(),Tl=S.object({max_instances:S.number().nullable().optional(),max_vcpu:S.number().nullable().optional(),max_memory:S.number().nullable().optional(),max_disk:S.number().nullable().optional()}).passthrough(),Il=S.object({tier:S.string(),capacity:Tl,nodes:S.array(El),kms_list:S.array(ze)}).passthrough(),{action:Al,safeAction:Pl}=pi(Il,async e=>await e.get("/teepods/available")),fi=N.object({id:N.string(),name:N.string(),description:N.string(),vcpu:N.number(),memory_mb:N.number(),hourly_rate:N.string(),requires_gpu:N.boolean(),default_disk_size_gb:N.number().default(20),family:N.string().nullable()}).passthrough(),$l=N.object({name:N.string(),items:N.array(fi),total:N.number()}).strict(),Ll=N.object({result:N.array($l)}).strict(),zl=N.object({items:N.array(fi),total:N.number(),family:N.string()}).strict(),Rl=N.object({family:N.string()}).strict(),{action:Bl,safeAction:jl}=_(Ll,async e=>await e.get("/instance-types")),{action:Ul,safeAction:Fl}=_(zl,async(e,t)=>{let r=Rl.parse(t);return await e.get(`/instance-types/${r.family}`)}),mi=re.object({id:re.string(),name:re.string(),slug:re.string().nullable(),tier:re.string(),role:re.string(),is_default:re.boolean(),created_at:re.string(),confidential_models_enabled:re.boolean().optional()}).passthrough(),Hl=re.object({has_more:re.boolean(),next_cursor:re.string().nullable(),total:re.number().nullable()}).passthrough(),Ol=re.object({data:re.array(mi),pagination:Hl}).passthrough(),{action:Nl,safeAction:Gl}=_(Ol,async(e,t)=>{let r=new URLSearchParams;t?.cursor&&r.append("cursor",t.cursor),t?.limit&&r.append("limit",t.limit.toString());let n=r.toString()?`/workspaces?${r.toString()}`:"/workspaces";return await e.get(n)}),{action:ql,safeAction:Dl}=_(mi,async(e,t)=>await e.get(`/workspaces/${t}`)),Vl=m.object({id:m.string(),name:m.string(),status:m.string(),uptime:m.string(),app_url:m.string().nullable(),app_id:m.string(),instance_id:m.string().nullable(),configuration:m.any().optional(),exited_at:m.string().nullable(),boot_progress:m.string().nullable(),boot_error:m.string().nullable(),shutdown_progress:m.string().nullable(),image_version:m.string().nullable()}),Ml=m.object({id:m.number(),username:m.string()}),di=m.object({id:m.number(),name:m.string(),region_identifier:m.string().nullable().optional()}),Rn=m.object({vcpu:m.number(),memory:m.number(),disk_size:m.number(),gpu_count:m.number().default(0)}),Bn=m.object({app:m.string(),instance:m.string()}),Kl=m.object({hosted:Vl,name:m.string(),managed_user:Ml.nullable(),node:di.nullable(),listed:m.boolean().default(!1),status:m.string(),in_progress:m.boolean().default(!1),dapp_dashboard_url:m.string().nullable(),syslog_endpoint:m.string().nullable(),allow_upgrade:m.boolean().default(!1),project_id:m.string().nullable(),project_type:m.string().nullable(),billing_period:m.string().nullable(),kms_info:ze.nullable(),vcpu:m.number().nullable(),memory:m.number().nullable(),disk_size:m.number().nullable(),gateway_domain:m.string().nullable(),public_urls:m.array(Bn),machine_info:Rn.nullable().optional(),updated_at:m.string().nullable().optional()}),hi=m.object({id:m.number(),name:m.string(),status:m.string(),in_progress:m.boolean().optional().default(!1),teepod_id:m.number().nullable(),teepod:di.optional().nullable(),app_id:m.string(),vm_uuid:m.string().nullable(),instance_id:m.string().nullable(),vcpu:m.number(),memory:m.number(),disk_size:m.number(),base_image:m.string().nullable(),encrypted_env_pubkey:m.string().nullable(),listed:m.boolean().optional().default(!1),project_id:m.string().optional().nullable(),project_type:m.string().optional().nullable(),instance_type:m.string().optional().nullable(),public_sysinfo:m.boolean().optional().default(!1),public_logs:m.boolean().optional().default(!1),dapp_dashboard_url:m.string().optional().nullable(),syslog_endpoint:m.string().optional().nullable(),kms_info:ze.optional().nullable(),contract_address:m.string().optional().nullable(),deployer_address:m.string().optional().nullable(),scheduled_delete_at:m.string().optional().nullable(),public_urls:m.array(Bn).optional().default([]),gateway_domain:m.string().optional().nullable(),machine_info:Rn.optional().nullable(),updated_at:m.string().optional().nullable()}),Wl=m.object({items:m.array(Kl),total:m.number(),page:m.number(),page_size:m.number(),pages:m.number()}),Xl=d.enum(["skip","hourly","monthly"]),Jl=d.enum(["phala","ethereum","base","legacy"]),jn=d.object({object_type:d.literal("user"),id:d.string().nullable().optional(),username:d.string().nullable().optional(),avatar_url:d.string().nullable().optional()}),Un=d.object({object_type:d.literal("workspace"),id:d.string(),name:d.string(),slug:d.string().nullable().optional(),avatar_url:d.string().nullable().optional()}),Zl=d.object({instance_type:d.string().nullable().optional(),vcpu:d.number().int().nullable().optional(),memory_in_gb:d.number().nullable().optional(),disk_in_gb:d.number().int().nullable().optional(),gpus:d.number().int().nullable().optional(),compute_billing_price:d.string().nullable().optional(),billing_period:Xl.nullable().optional()}),Yl=d.object({name:d.string().nullable().optional(),version:d.string().nullable().optional(),is_dev:d.boolean().nullable().optional(),os_image_hash:d.string().nullable().optional()}),Ql=d.object({chain_id:d.number().int().nullable().optional(),dstack_kms_address:d.string().nullable().optional(),dstack_app_address:d.string().nullable().optional(),deployer_address:d.string().nullable().optional(),rpc_endpoint:d.string().nullable().optional(),encrypted_env_pubkey:d.string().nullable().optional()}),eu=d.object({target:d.string().nullable().optional(),started_at:d.string().nullable().optional(),correlation_id:d.string().nullable().optional()}),tu=d.object({base_domain:d.string().nullable().optional(),cname:d.string().nullable().optional()}),gi=d.object({object_type:d.literal("node"),id:d.number().int().nullable().optional(),name:d.string().nullable().optional(),region:d.string().nullable().optional(),device_id:d.string().nullable().optional(),ppid:d.string().nullable().optional(),status:d.string().nullable().optional(),version:d.string().nullable().optional()});var Fr=d.object({id:d.string(),name:d.string(),app_id:d.string().nullable().optional(),vm_uuid:d.string().nullable().optional(),instance_id:d.string().nullable().optional(),resource:Zl,node_info:gi.nullable().optional(),os:Yl.nullable().optional(),kms_type:Jl.nullable().optional(),kms_info:Ql.nullable().optional(),status:d.string(),progress:eu.nullable().optional(),compose_hash:d.string().nullable().optional(),gateway:tu,services:d.array(d.record(d.any())).optional().default([]),endpoints:d.array(Bn).nullable().optional(),public_logs:d.boolean().optional(),public_sysinfo:d.boolean().optional(),public_tcbinfo:d.boolean().optional(),gateway_enabled:d.boolean().optional(),secure_time:d.boolean().optional(),listed:d.boolean().optional().default(!1),storage_fs:d.string().optional(),workspace:Un.nullable().optional(),creator:jn.nullable().optional()}),ru=Fr.extend({compose_file:d.union([d.record(d.any()),d.string()]).nullable().optional()}),nu=d.object({items:d.array(Fr),total:d.number(),page:d.number(),page_size:d.number(),pages:d.number()});function bi(e){return typeof e!="string"||e.length<5||e.length>63?!1:/^[a-zA-Z](?!.*--)([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(e)}var xe=Ct.object({id:Ct.string().optional(),uuid:Ct.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i,"Invalid UUID format").optional(),app_id:Ct.string().optional(),instance_id:Ct.string().optional(),name:Ct.string().refine(bi,{message:"Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens"}).optional()}),Re=e=>e.refine(t=>{let r=t;return!!(r.id||r.uuid||r.app_id||r.instance_id||r.name)},{message:"One of id, uuid, app_id, instance_id, or name must be provided"}),ou=Re(xe),j=ou.transform(e=>{let t;if(e.id)t=e.id;else if(e.uuid)t=e.uuid;else if(e.app_id)t=e.app_id;else if(e.instance_id)t=e.instance_id;else{if(e.name)return{cvmId:e.name};throw new Error("No valid identifier provided")}let r=/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i,n=/^[0-9a-f]{40}$/i,o;return r.test(t)?o=t.replace(/-/g,""):n.test(t)?o=`app_${t}`:o=t,{cvmId:o}}),su=j;function iu(e){return e==="2025-10-28"?hi:ru}async function xi(e,t){let{cvmId:r}=su.parse(t),n=await e.get(`/cvms/${r}`);return iu(e.config.version).parse(n)}async function Or(e,t){try{return{success:!0,data:await xi(e,t)}}catch(r){return r&&typeof r=="object"&&("status"in r||"issues"in r)?{success:!1,error:r}:{success:!1,error:{name:"Error",message:r instanceof Error?r.message:String(r)}}}}var au=kt.object({page:kt.number().int().min(1).optional(),page_size:kt.number().int().min(1).optional(),node_id:kt.number().int().min(1).optional(),teepod_id:kt.number().int().min(1).optional(),user_id:kt.string().optional()}).strict();function cu(e){return e==="2025-10-28"?Wl:nu}async function yi(e,t){let r=au.parse(t??{}),n=await e.get("/cvms/paginated",{params:r});return cu(e.config.version).parse(n)}async function Fn(e,t){try{return{success:!0,data:await yi(e,t)}}catch(r){return r&&typeof r=="object"&&("status"in r||"issues"in r)?{success:!1,error:r}:{success:!1,error:{name:"Error",message:r instanceof Error?r.message:String(r)}}}}var Zs=200*1024;function vi(e,t,r){let n=new TextEncoder,o=e?n.encode(e).byteLength:0,s=t?n.encode(t).byteLength:0,i=o+s;if(i>Zs){let a=Zs/1024,l=Math.ceil(i/1024);r.addIssue({code:J.ZodIssueCode.custom,message:`Combined size of docker_compose_file and pre_launch_script must not exceed ${a}KB (current: ${l}KB)`})}}var wi=J.object({allowed_envs:J.array(J.string()).optional(),docker_compose_file:J.string(),features:J.array(J.string()).optional(),name:J.string().optional(),manifest_version:J.number().optional(),kms_enabled:J.boolean().optional(),public_logs:J.boolean().optional(),public_sysinfo:J.boolean().optional(),tproxy_enabled:J.boolean().optional(),pre_launch_script:J.string().optional(),env_pubkey:J.string().optional(),salt:J.string().optional().nullable()}).passthrough().superRefine((e,t)=>{vi(e.docker_compose_file,e.pre_launch_script,t)}),lu=k.object({app_id:k.string().nullable().optional(),app_env_encrypt_pubkey:k.string().nullable().optional(),compose_hash:k.string(),kms_info:ze.nullable().optional(),fmspc:k.string().nullable().optional(),device_id:k.string().nullable().optional(),os_image_hash:k.string().nullable().optional(),instance_type:k.string().nullable().optional(),teepod_id:k.number().nullable().optional(),node_id:k.number().nullable().optional(),kms_id:k.string().nullable().optional()}).passthrough().transform(e=>{if("teepod_id"in e&&e.teepod_id!==void 0){let{teepod_id:t,...r}=e;return{...r,node_id:t}}return e}),An="Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens",uu=k.object({node_id:k.number().optional(),teepod_id:k.number().optional(),region:k.string().optional(),name:k.string().min(5,An).max(63,An).refine(e=>bi(e),An),instance_type:k.string().optional(),image:k.string().optional(),vcpu:k.number().optional(),memory:k.number().optional(),disk_size:k.number().optional(),compose_file:k.object({allowed_envs:k.array(k.string()).optional(),pre_launch_script:k.string().optional(),docker_compose_file:k.string().optional(),name:k.string().optional().default(""),kms_enabled:k.boolean().optional(),public_logs:k.boolean().optional(),public_sysinfo:k.boolean().optional(),gateway_enabled:k.boolean().optional(),tproxy_enabled:k.boolean().optional()}).superRefine((e,t)=>{vi(e.docker_compose_file,e.pre_launch_script,t)}),listed:k.boolean().optional(),kms_id:k.string().optional(),kms:k.enum(["PHALA","ETHEREUM","BASE"]).optional(),kms_contract:k.string().optional(),env_keys:k.array(k.string()).optional(),nonce:k.number().optional(),app_id:k.string().optional()}).passthrough().transform(e=>!e.instance_type&&!e.vcpu&&!e.memory?{...e,instance_type:"tdx.small"}:e);function pu(e){if(!e.compose_file)return e;let t={...e.compose_file};return typeof t.gateway_enabled=="boolean"&&typeof t.tproxy_enabled=="boolean"?delete t.tproxy_enabled:typeof t.tproxy_enabled=="boolean"&&typeof t.gateway_enabled>"u"&&(t.gateway_enabled=t.tproxy_enabled,delete t.tproxy_enabled,(typeof window<"u"?window.console:globalThis.console)&&console.warn("[phala/cloud] tproxy_enabled is deprecated, please use gateway_enabled instead. See docs for migration.")),{...e,compose_file:t}}var{action:fu,safeAction:mu}=_(lu,async(e,t)=>{let r=uu.parse(t),n=pu(r),o={...n};return typeof n.node_id=="number"?(o={...n,teepod_id:n.node_id},delete o.node_id):typeof n.teepod_id=="number"&&console.warn("[phala/cloud] teepod_id is deprecated, please use node_id instead."),await e.post("/cvms/provision",o)}),du=T.object({id:T.number(),name:T.string(),status:T.string(),teepod_id:T.number(),teepod:T.object({id:T.number(),name:T.string()}).nullable(),user_id:T.number().nullable(),app_id:T.string().nullable(),vm_uuid:T.string().nullable(),instance_id:T.string().nullable(),app_url:T.string().nullable().default(null),base_image:T.string().nullable(),vcpu:T.number(),memory:T.number(),disk_size:T.number(),manifest_version:T.number().nullable().default(2),version:T.string().nullable().default("1.0.0"),runner:T.string().nullable().default("docker-compose"),docker_compose_file:T.string().nullable(),features:T.array(T.string()).nullable().default(["kms","tproxy-net"]),created_at:T.string(),encrypted_env_pubkey:T.string().nullable().optional(),app_auth_contract_address:T.string().nullable().optional(),deployer_address:T.string().nullable().optional()}).passthrough(),jx=T.object({encrypted_env:T.string().optional().nullable(),app_id:T.string(),compose_hash:T.string(),kms_id:T.string().optional(),contract_address:T.string().optional(),deployer_address:T.string().optional(),env_keys:T.array(T.string()).optional().nullable()}).passthrough(),{action:hu,safeAction:gu}=_(du,async(e,t)=>await e.post("/cvms",t));function Ln(e){return e==null?e:Array.isArray(e)?e.map(Ln):e&&typeof e=="object"&&e.constructor===Object?Object.keys(e).sort().reduce((t,r)=>{let n=e[r];return t[r]=Ln(n),t},{}):e}function _i(e){let t={...e};return t.runner==="bash"&&"docker_compose_file"in t?delete t.docker_compose_file:t.runner==="docker-compose"&&"bash_script"in t&&delete t.bash_script,"pre_launch_script"in t&&!t.pre_launch_script&&delete t.pre_launch_script,t}function Ci(e){let t=Ln(e),r=JSON.stringify(t,null,4);return r=r.replace(/": /g,'":'),r}function xu(e){let t=_i(e),r=Ci(t);return bu.createHash("sha256").update(r,"utf8").digest("hex")}function yu(e){let t=e;return{...e,getHash:()=>xu(t),toString:()=>Ci(_i(t))}}var vu=wi.transform(e=>yu(e)),wu=j,{action:_u,safeAction:Hn}=_(vu,async(e,t)=>{let{cvmId:r}=wu.parse(t);return await e.get(`/cvms/${r}/compose_file`)}),Cu=Pe.object({id:Pe.string().optional(),uuid:Pe.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),app_id:Pe.string().refine(e=>!e.startsWith("app_")&&e.length===40,"app_id should be 40 characters without prefix").transform(e=>e.startsWith("app_")?e:`app_${e}`).optional(),instance_id:Pe.string().refine(e=>!e.startsWith("instance_")&&e.length===40,"instance_id should be 40 characters without prefix").transform(e=>e.startsWith("instance_")?e:`instance_${e}`).optional(),app_compose:wi,update_env_vars:Pe.boolean().optional().nullable()}).refine(e=>!!(e.id||e.uuid||e.app_id||e.instance_id),"One of id, uuid, app_id, or instance_id must be provided").transform(e=>({cvmId:e.id||e.uuid||e.app_id||e.instance_id,request:{...e.app_compose,update_env_vars:e.update_env_vars},_raw:e})),ku=Pe.object({app_id:Pe.string().nullable(),device_id:Pe.string().nullable(),compose_hash:Pe.string(),kms_info:ze.nullable().optional()}).passthrough(),{action:Su,safeAction:Eu}=_(ku,async(e,t)=>{let r=Cu.parse(t);return await e.post(`/cvms/${r.cvmId}/compose_file/provision`,r.request)}),Tu=_e.object({id:_e.string().optional(),uuid:_e.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),app_id:_e.string().refine(e=>!e.startsWith("app_")&&e.length===40,"app_id should be 40 characters without prefix").transform(e=>e.startsWith("app_")?e:`app_${e}`).optional(),instance_id:_e.string().refine(e=>!e.startsWith("instance_")&&e.length===40,"instance_id should be 40 characters without prefix").transform(e=>e.startsWith("instance_")?e:`instance_${e}`).optional(),compose_hash:_e.string().min(1,"Compose hash is required"),encrypted_env:_e.string().optional(),env_keys:_e.array(_e.string()).optional(),update_env_vars:_e.boolean().optional().nullable()}).refine(e=>!!(e.id||e.uuid||e.app_id||e.instance_id),"One of id, uuid, app_id, or instance_id must be provided").transform(e=>({cvmId:e.id||e.uuid||e.app_id||e.instance_id,compose_hash:e.compose_hash,encrypted_env:e.encrypted_env,env_keys:e.env_keys,update_env_vars:e.update_env_vars??void 0,_raw:e})),Iu=_e.any().transform(()=>{}),{action:Au,safeAction:Pu}=_(Iu,async(e,t)=>{let r=Tu.parse(t);return await e.patch(`/cvms/${r.cvmId}/compose_file`,{compose_hash:r.compose_hash,encrypted_env:r.encrypted_env,env_keys:r.env_keys,update_env_vars:r.update_env_vars})}),$u=Re(xe.extend({encrypted_env:K.string().describe("Encrypted environment variables (hex string)"),env_keys:K.array(K.string()).optional().describe("List of allowed environment variable keys"),compose_hash:K.string().optional().describe("Compose hash for verification (Phase 2, required when env_keys changes)"),transaction_hash:K.string().optional().describe("On-chain transaction hash for verification (Phase 2, required when env_keys changes)")})).transform(e=>{let{cvmId:t}=j.parse(e);return{cvmId:t,request:{encrypted_env:e.encrypted_env,env_keys:e.env_keys,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),Lu=K.object({status:K.literal("in_progress"),message:K.string(),correlation_id:K.string(),allowed_envs_changed:K.boolean()}),zu=K.object({status:K.literal("precondition_required"),message:K.string(),compose_hash:K.string(),app_id:K.string(),device_id:K.string(),kms_info:ze}),Ru=K.union([Lu,zu]),{action:Bu,safeAction:ju}=_(Ru,async(e,t)=>{let r=$u.parse(t);try{return await e.patch(`/cvms/${r.cvmId}/envs`,r.request)}catch(n){if(n instanceof Le&&n.status===465){let o=n.detail;if(o&&typeof o=="object"){let s=o;return{status:"precondition_required",message:s.message||"Compose hash verification required",compose_hash:s.compose_hash,app_id:s.app_id,device_id:s.device_id,kms_info:s.kms_info}}}throw n}}),Uu=Re(xe.extend({docker_compose_file:le.string().describe("Docker Compose YAML content"),compose_hash:le.string().optional().describe("Compose hash for verification (Phase 2, contract-owned KMS only)"),transaction_hash:le.string().optional().describe("On-chain transaction hash for verification (Phase 2, contract-owned KMS only)")})).transform(e=>{let{cvmId:t}=j.parse(e);return{cvmId:t,request:{docker_compose_file:e.docker_compose_file,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),Fu=le.object({status:le.literal("in_progress"),message:le.string(),correlation_id:le.string()}),Hu=le.object({status:le.literal("precondition_required"),message:le.string(),compose_hash:le.string(),app_id:le.string(),device_id:le.string(),kms_info:ze}),Ou=le.union([Fu,Hu]),{action:Nu,safeAction:Gu}=_(Ou,async(e,t)=>{let r=Uu.parse(t),n={"Content-Type":"text/yaml"};r.request.compose_hash&&(n["X-Compose-Hash"]=r.request.compose_hash),r.request.transaction_hash&&(n["X-Transaction-Hash"]=r.request.transaction_hash);try{return await e.patch(`/cvms/${r.cvmId}/docker-compose`,r.request.docker_compose_file,{headers:n})}catch(o){if(o instanceof Le&&o.status===465){let s=o.detail;if(s&&typeof s=="object"){let i=s;return{status:"precondition_required",message:i.message||"Compose hash verification required",compose_hash:i.compose_hash,app_id:i.app_id,device_id:i.device_id,kms_info:i.kms_info}}}throw o}}),qu=Re(xe.extend({pre_launch_script:ue.string().describe("Pre-launch script content (shell script)"),compose_hash:ue.string().optional().describe("Compose hash for verification (Phase 2, contract-owned KMS only)"),transaction_hash:ue.string().optional().describe("On-chain transaction hash for verification (Phase 2, contract-owned KMS only)")})).transform(e=>{let{cvmId:t}=j.parse(e);return{cvmId:t,request:{pre_launch_script:e.pre_launch_script,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),Du=ue.object({status:ue.literal("in_progress"),message:ue.string(),correlation_id:ue.string()}),Vu=ue.object({status:ue.literal("precondition_required"),message:ue.string(),compose_hash:ue.string(),app_id:ue.string(),device_id:ue.string(),kms_info:ze}),Mu=ue.union([Du,Vu]),{action:Ku,safeAction:Wu}=_(Mu,async(e,t)=>{let r=qu.parse(t),n={"Content-Type":"text/plain"};r.request.compose_hash&&(n["X-Compose-Hash"]=r.request.compose_hash),r.request.transaction_hash&&(n["X-Transaction-Hash"]=r.request.transaction_hash);try{return await e.patch(`/cvms/${r.cvmId}/pre-launch-script`,r.request.pre_launch_script,{headers:n})}catch(o){if(o instanceof Le&&o.status===465){let s=o.detail;if(s&&typeof s=="object"){let i=s;return{status:"precondition_required",message:i.message||"Compose hash verification required",compose_hash:i.compose_hash,app_id:i.app_id,device_id:i.device_id,kms_info:i.kms_info}}}throw o}}),Ju=j,{action:Zu,safeAction:Yu}=_(Xu.string(),async(e,t)=>{let{cvmId:r}=Ju.parse(t);return await e.get(`/cvms/${r}/pre-launch-script`)}),Qu=Ys.object({kms_id:Ys.string().min(1,"KMS ID is required")}),{action:ep,safeAction:tp}=_(ze,async(e,t)=>{let r=Qu.parse(t);return await e.get(`/kms/${r.kms_id}`)}),rp=$e.object({page:$e.number().int().min(1).optional(),page_size:$e.number().int().min(1).optional(),is_onchain:$e.boolean().optional()}).strict(),np=$e.object({items:$e.array(ze),total:$e.number(),page:$e.number(),page_size:$e.number(),pages:$e.number()}).strict(),{action:op,safeAction:sp}=_(np,async(e,t)=>{let r=rp.parse(t??{});return await e.get("/kms",{params:r})}),ip=At.object({kms:At.string().min(1,"KMS ID or slug is required"),app_id:At.string().refine(e=>e.length===40||e.startsWith("0x")&&e.length===42,"App ID must be exactly 40 characters or 42 characters with 0x prefix")}).strict(),ap=At.object({public_key:At.string(),signature:At.string()}).strict(),{action:cp,safeAction:lp}=_(ap,async(e,t)=>{let r=ip.parse(t);return await e.get(`/kms/${r.kms}/pubkey/${r.app_id}`)}),up=lt.object({counts:lt.number().int().min(1).max(20).optional().default(1)}).strict(),pp=lt.object({app_ids:lt.array(lt.object({app_id:lt.string(),nonce:lt.number().int().min(0)}))}).strict(),{action:fp,safeAction:mp}=_(pp,async(e,t)=>{let r=up.parse(t??{}),n=new URLSearchParams;return n.append("counts",r.counts.toString()),await e.get(`/kms/phala/next_app_id?${n.toString()}`)}),Jt=B.object({id:B.number(),name:B.string(),status:B.string(),teepod_id:B.number(),teepod:B.object({id:B.number(),name:B.string(),region_identifier:B.string().nullable().optional()}).optional().nullable(),user_id:B.number().optional().nullable(),app_id:B.string(),vm_uuid:B.string().nullable(),instance_id:B.string().nullable(),app_url:B.string().optional().nullable(),base_image:B.string().optional().nullable(),vcpu:B.number(),memory:B.number(),disk_size:B.number(),manifest_version:B.number().optional().nullable(),version:B.string().optional().nullable(),runner:B.string().optional().nullable(),docker_compose_file:B.string().optional().nullable(),features:B.array(B.string()).optional().nullable(),created_at:B.string(),encrypted_env_pubkey:B.string().nullable()}),dp=j,{action:hp,safeAction:gp}=_(Jt,async(e,t)=>{let{cvmId:r}=dp.parse(t);return await e.post(`/cvms/${r}/start`)}),bp=j,{action:xp,safeAction:yp}=_(Jt,async(e,t)=>{let{cvmId:r}=bp.parse(t);return await e.post(`/cvms/${r}/stop`)}),vp=j,{action:wp,safeAction:_p}=_(Jt,async(e,t)=>{let{cvmId:r}=vp.parse(t);return await e.post(`/cvms/${r}/shutdown`)}),kp=Re(xe.extend({force:Cp.boolean().optional()})),{action:Sp,safeAction:Ep}=_(Jt,async(e,t)=>{let r=kp.parse(t),{cvmId:n}=j.parse(r),{force:o=!1}=r;return await e.post(`/cvms/${n}/restart`,{force:o})}),Ip=j,{action:Ap,safeAction:Pp}=_(Tp.void(),async(e,t)=>{let{cvmId:r}=Ip.parse(t);await e.delete(`/cvms/${r}`)}),$p=z.object({name:z.string(),mount_point:z.string(),total_size:z.number(),free_size:z.number()}),Lp=z.object({os_name:z.string(),os_version:z.string(),kernel_version:z.string(),cpu_model:z.string(),num_cpus:z.number(),total_memory:z.number(),available_memory:z.number(),used_memory:z.number(),free_memory:z.number(),total_swap:z.number(),used_swap:z.number(),free_swap:z.number(),uptime:z.number(),loadavg_one:z.number(),loadavg_five:z.number(),loadavg_fifteen:z.number(),disks:z.array($p)}),zp=z.object({is_online:z.boolean(),is_public:z.boolean().default(!1),error:z.string().nullable(),sysinfo:Lp.nullable(),status:z.string().nullable(),in_progress:z.boolean().default(!1),boot_progress:z.string().nullable(),boot_error:z.string().nullable()}),Rp=j,{action:Bp,safeAction:jp}=_(zp,async(e,t)=>{let{cvmId:r}=Rp.parse(t);return await e.get(`/cvms/${r}/stats`)}),Up=Ae.object({app:Ae.string(),instance:Ae.string()}),Fp=Ae.object({is_online:Ae.boolean(),is_public:Ae.boolean().default(!0),error:Ae.string().nullable(),internal_ip:Ae.string().nullable(),latest_handshake:Ae.string().nullable(),public_urls:Ae.array(Up).nullable()}),Hp=j,{action:Op,safeAction:Np}=_(Fp,async(e,t)=>{let{cvmId:r}=Hp.parse(t);return await e.get(`/cvms/${r}/network`)}),qp=j,{action:Dp,safeAction:Vp}=_(Gp.string(),async(e,t)=>{let{cvmId:r}=qp.parse(t);return await e.get(`/cvms/${r}/docker-compose.yml`)}),Mp=O.object({id:O.string(),names:O.array(O.string()),image:O.string(),image_id:O.string(),command:O.string().nullable().optional(),created:O.number(),state:O.string(),status:O.string(),log_endpoint:O.string().nullable()}),Kp=O.object({is_online:O.boolean(),is_public:O.boolean().default(!0),error:O.string().nullable(),docker_compose_file:O.string().nullable(),manifest_version:O.number().nullable(),version:O.string().nullable(),runner:O.string().nullable(),features:O.array(O.string()).nullable(),containers:O.array(Mp).nullable()}),Wp=j,{action:Xp,safeAction:Jp}=_(Kp,async(e,t)=>{let{cvmId:r}=Wp.parse(t);return await e.get(`/cvms/${r}/composition`)}),Zp=y.object({common_name:y.string().nullable(),organization:y.string().nullable(),country:y.string().nullable(),state:y.string().nullable(),locality:y.string().nullable()}),Yp=y.object({common_name:y.string().nullable(),organization:y.string().nullable(),country:y.string().nullable()}),ki=y.object({subject:Zp,issuer:Yp,serial_number:y.string(),not_before:y.string(),not_after:y.string(),version:y.string(),fingerprint:y.string(),signature_algorithm:y.string(),sans:y.array(y.string()).nullable(),is_ca:y.boolean(),position_in_chain:y.number().nullable(),quote:y.string().nullable(),app_id:y.string().nullable().optional(),cert_usage:y.string().nullable().optional()}),Qp=y.object({imr:y.number(),event_type:y.number(),digest:y.string(),event:y.string(),event_payload:y.string()}),Si=y.object({mrtd:y.string(),rootfs_hash:y.string().nullable().optional(),rtmr0:y.string(),rtmr1:y.string(),rtmr2:y.string(),rtmr3:y.string(),event_log:y.array(Qp),app_compose:y.string()}),ef=y.object({name:y.string().nullable(),is_online:y.boolean(),is_public:y.boolean().default(!0),error:y.string().nullable(),app_certificates:y.array(ki).nullable(),tcb_info:Si.nullable(),compose_file:y.string().nullable()}),tf=j,{action:rf,safeAction:nf}=_(ef,async(e,t)=>{let{cvmId:r}=tf.parse(t);return await e.get(`/cvms/${r}/attestation`)}),of=Re(xe.extend({vcpu:Tt.number().optional(),memory:Tt.number().optional(),disk_size:Tt.number().optional(),instance_type:Tt.string().optional(),allow_restart:Tt.boolean().optional()})),{action:sf,safeAction:af}=_(Tt.void(),async(e,t)=>{let r=of.parse(t),{cvmId:n}=j.parse(r),{...o}=r;await e.patch(`/cvms/${n}/resources`,o)}),cf=Re(xe.extend({public_sysinfo:Pn.boolean(),public_logs:Pn.boolean(),public_tcbinfo:Pn.boolean().optional()})),{action:lf,safeAction:uf}=_(hi,async(e,t)=>{let r=cf.parse(t),{cvmId:n}=j.parse(r),{public_sysinfo:o,public_logs:s,public_tcbinfo:i}=r;return await e.patch(`/cvms/${n}/visibility`,{public_sysinfo:o,public_logs:s,public_tcbinfo:i})}),Qs=Z.object({name:Z.string(),os_image_hash:Z.string().nullable(),is_current:Z.boolean()}),pf=Z.object({version:Z.union([Z.tuple([Z.number(),Z.number(),Z.number(),Z.number()]),Z.tuple([Z.number(),Z.number(),Z.number()])]),prod:Qs.nullable(),dev:Qs.nullable()}),ff=Z.array(pf),mf=j,{action:df,safeAction:hf}=_(ff,async(e,t)=>{let{cvmId:r}=mf.parse(t);return await e.get(`/cvms/${r}/available-os-images`)}),gf=Re(xe.extend({os_image_name:Ei.string().min(1,"OS image name is required")})),{action:bf,safeAction:xf}=_(Ei.void(),async(e,t)=>{let r=gf.parse(t),{cvmId:n}=j.parse(r),{os_image_name:o}=r;await e.patch(`/cvms/${n}/os-image`,{os_image_name:o})}),yf=Ie.object({id:Ie.string().optional(),instance_id:Ie.string().optional(),name:Ie.string(),status:Ie.string(),uptime:Ie.string().optional(),exited_at:Ie.string().optional(),boot_progress:Ie.string().optional(),boot_error:Ie.string().optional(),shutdown_progress:Ie.string().optional()}),vf=j,{action:wf,safeAction:_f}=_(yf,async(e,t)=>{let{cvmId:r}=vf.parse(t);return await e.get(`/cvms/${r}/state`)}),Ti=ce.object({id:ce.string(),user_id:ce.string(),name:ce.string(),public_key:ce.string(),fingerprint:ce.string(),key_type:ce.string(),source:ce.string(),key_metadata:ce.record(ce.unknown()).nullable().optional(),last_synced_at:ce.string().nullable().optional(),created_at:ce.string(),updated_at:ce.string()}),Cf=ce.array(Ti);async function Ii(e){let t=await e.get("/user/ssh-keys");return Cf.parse(t)}async function kf(e){try{return{success:!0,data:await Ii(e)}}catch(t){return t&&typeof t=="object"&&("status"in t||"issues"in t)?{success:!1,error:t}:{success:!1,error:{name:"Error",message:t instanceof Error?t.message:String(t)}}}}var Sf=Je.object({github_username:Je.string().min(1)}),Ef=Je.object({github_username:Je.string(),keys_added:Je.number().int(),keys_skipped:Je.number().int(),errors:Je.array(Je.string()).default([])}),{action:Tf,safeAction:If}=_(Ef,async(e,t)=>{let{github_username:r}=Sf.parse(t);return await e.post("/user/ssh-keys/github-profile",{github_username:r})}),Af=$n.object({name:$n.string().min(1),public_key:$n.string().min(1)}),{action:Pf,safeAction:$f}=_(Ti,async(e,t)=>{let{name:r,public_key:n}=Af.parse(t);return await e.post("/user/ssh-keys",{name:r,public_key:n})}),Lf=zn.object({keyId:zn.string().min(1)}),{action:zf,safeAction:Rf}=_(zn.void(),async(e,t)=>{let{keyId:r}=Lf.parse(t);await e.delete(`/user/ssh-keys/${r}`)}),Bf=ct.object({synced_count:ct.number().int(),keys_added:ct.number().int(),keys_updated:ct.number().int(),keys_removed:ct.number().int(),errors:ct.array(ct.string()).default([])}),{action:jf,safeAction:Uf}=pi(Bf,async e=>await e.post("/user/ssh-keys/github-sync",{}));function Ai(e={}){let t=hl(e),r={getCurrentUser:ci,safeGetCurrentUser:_l,getAvailableNodes:Al,safeGetAvailableNodes:Pl,listAllInstanceTypeFamilies:Bl,safeListAllInstanceTypeFamilies:jl,listFamilyInstanceTypes:Ul,safeListFamilyInstanceTypes:Fl,listWorkspaces:Nl,safeListWorkspaces:Gl,getWorkspace:ql,safeGetWorkspace:Dl,getCvmInfo:xi,safeGetCvmInfo:Or,getCvmList:yi,safeGetCvmList:Fn,provisionCvm:fu,safeProvisionCvm:mu,commitCvmProvision:hu,safeCommitCvmProvision:gu,getCvmComposeFile:_u,safeGetCvmComposeFile:Hn,provisionCvmComposeFileUpdate:Su,safeProvisionCvmComposeFileUpdate:Eu,commitCvmComposeFileUpdate:Au,safeCommitCvmComposeFileUpdate:Pu,updateCvmEnvs:Bu,safeUpdateCvmEnvs:ju,updateDockerCompose:Nu,safeUpdateDockerCompose:Gu,updatePreLaunchScript:Ku,safeUpdatePreLaunchScript:Wu,getCvmPreLaunchScript:Zu,safeGetCvmPreLaunchScript:Yu,startCvm:hp,safeStartCvm:gp,stopCvm:xp,safeStopCvm:yp,shutdownCvm:wp,safeShutdownCvm:_p,restartCvm:Sp,safeRestartCvm:Ep,deleteCvm:Ap,safeDeleteCvm:Pp,getCvmStats:Bp,safeGetCvmStats:jp,getCvmNetwork:Op,safeGetCvmNetwork:Np,getCvmDockerCompose:Dp,safeGetCvmDockerCompose:Vp,getCvmContainersStats:Xp,safeGetCvmContainersStats:Jp,getCvmAttestation:rf,safeGetCvmAttestation:nf,updateCvmResources:sf,safeUpdateCvmResources:af,updateCvmVisibility:lf,safeUpdateCvmVisibility:uf,getAvailableOsImages:df,safeGetAvailableOsImages:hf,updateOsImage:bf,safeUpdateOsImage:xf,getKmsInfo:ep,safeGetKmsInfo:tp,getKmsList:op,safeGetKmsList:sp,getAppEnvEncryptPubKey:cp,safeGetAppEnvEncryptPubKey:lp,nextAppIds:fp,safeNextAppIds:mp,getCvmState:wf,safeGetCvmState:_f,listSshKeys:Ii,safeListSshKeys:kf,importGithubProfileSshKeys:Tf,safeImportGithubProfileSshKeys:If,createSshKey:Pf,safeCreateSshKey:$f,deleteSshKey:zf,safeDeleteSshKey:Rf,syncGithubSshKeys:jf,safeSyncGithubSshKeys:Uf};return t.extend(r)}var ei=b.object({vm_uuid:b.string().nullable(),app_id:b.string(),name:b.string().default(""),status:b.string(),vcpu:b.number().int(),memory:b.number().int(),disk_size:b.number().int(),teepod_id:b.number().int(),teepod_name:b.string(),region_identifier:b.string().nullable().optional(),kms_type:b.string().nullable().optional(),instance_type:b.string().nullable().optional(),listed:b.boolean().nullable().optional(),base_image:b.string().nullable().optional(),kms_slug:b.string().nullable().optional(),kms_id:b.string().nullable().optional(),instance_id:b.string().nullable().optional(),machine_info:Rn.nullable().optional(),updated_at:b.string().nullable().optional()}),Ff=b.object({display_name:b.string().nullable().optional(),avatar_url:b.string().nullable().optional(),description:b.string().nullable().optional(),custom_domain:b.string().nullable().optional()}),Hf=b.object({id:b.string(),name:b.string(),app_id:b.string(),app_provision_type:b.string().nullable().optional(),app_icon_url:b.string().nullable().optional(),created_at:b.string(),kms_type:b.string(),profile:Ff.nullable().optional(),current_cvm:ei.nullable().optional(),cvms:b.array(ei).default([]),cvm_count:b.number().int().default(0)}),Of=b.object({id:b.null().optional(),app_id:b.string(),name:b.null().optional(),app_provision_type:b.null().optional(),app_icon_url:b.null().optional(),created_at:b.null().optional(),kms_type:b.null().optional(),current_cvm:b.null().optional(),cvms:b.null().optional(),cvm_count:b.null().optional()}),Nf=b.union([Hf,Of]),my=b.object({dstack_apps:b.array(Nf),page:b.number().int(),page_size:b.number().int(),total:b.number().int(),total_pages:b.number().int()}),Gf=A.object({id:A.string(),name:A.string(),app_id:A.string(),app_provision_type:A.string().nullable().optional(),app_icon_url:A.string().nullable().optional(),created_at:A.string(),kms_type:A.string(),profile:A.object({display_name:A.string().nullable().optional(),avatar_url:A.string().nullable().optional(),description:A.string().nullable().optional(),custom_domain:A.string().nullable().optional()}).nullable().optional(),current_cvm:Fr.nullable().optional(),cvms:A.array(Fr).default([]),cvm_count:A.number().int().default(0)}),qf=A.object({id:A.null().optional(),app_id:A.string(),name:A.null().optional(),app_provision_type:A.null().optional(),app_icon_url:A.null().optional(),created_at:A.null().optional(),kms_type:A.null().optional(),current_cvm:A.null().optional(),cvms:A.null().optional(),cvm_count:A.null().optional()}),Df=A.union([Gf,qf]),hy=A.object({dstack_apps:A.array(Df),page:A.number().int(),page_size:A.number().int(),total:A.number().int(),total_pages:A.number().int()}),Pi=I.object({object_type:I.literal("cvm"),id:I.string().nullable().optional(),name:I.string().nullable().optional(),app_id:I.string().nullable().optional(),vm_uuid:I.string().nullable().optional()}),Vf=I.object({revision_id:I.string(),app_id:I.string(),vm_uuid:I.string(),compose_hash:I.string(),created_at:I.string(),trace_id:I.string().nullable().optional(),operation_type:I.string(),triggered_by:jn.nullable().optional(),cvm:Pi.nullable().optional(),workspace:Un.nullable().optional()}),by=I.object({revision_id:I.string(),app_id:I.string(),vm_uuid:I.string(),compose_hash:I.string(),compose_file:I.union([I.record(I.any()),I.string()]).nullable().optional(),encrypted_env:I.string(),user_config:I.string(),created_at:I.string(),trace_id:I.string().nullable().optional(),operation_type:I.string(),triggered_by:jn.nullable().optional(),cvm:Pi.nullable().optional(),workspace:Un.nullable().optional()}),xy=I.object({revisions:I.array(Vf),total:I.number().int(),page:I.number().int(),page_size:I.number().int(),total_pages:I.number().int()});var Mf=G.object({chain:G.unknown().optional(),rpcUrl:G.string().optional(),kmsContractAddress:G.string(),privateKey:G.string().optional(),walletClient:G.unknown().optional(),publicClient:G.unknown().optional(),allowAnyDevice:G.boolean().optional().default(!1),deviceId:G.string().optional().default("0000000000000000000000000000000000000000000000000000000000000000"),composeHash:G.string().optional().default("0000000000000000000000000000000000000000000000000000000000000000"),disableUpgrades:G.boolean().optional().default(!1),skipPrerequisiteChecks:G.boolean().optional().default(!1),minBalance:G.string().optional()}).passthrough(),_y=Mf.refine(e=>{let t=!!e.privateKey,r=!!e.walletClient;return t!==r},{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>{let t=!!e.publicClient,r=!!e.walletClient,n=!!e.chain;return t&&r?!0:n},{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),Cy=G.object({appId:G.string(),appAuthAddress:G.string(),deployer:G.string(),transactionHash:G.string(),blockNumber:G.bigint().optional(),gasUsed:G.bigint().optional()}).passthrough();var Sy=H.object({chain:H.unknown().optional(),rpcUrl:H.string().optional(),appId:H.string(),composeHash:H.string(),privateKey:H.string().optional(),walletClient:H.unknown().optional(),publicClient:H.unknown().optional(),skipPrerequisiteChecks:H.boolean().optional().default(!1),minBalance:H.string().optional(),timeout:H.number().optional().default(12e4),retryOptions:H.unknown().optional(),signal:H.unknown().optional(),onTransactionStateChange:H.function().optional(),onTransactionSubmitted:H.function().optional(),onTransactionConfirmed:H.function().optional()}).passthrough().refine(e=>{let t=!!e.privateKey,r=!!e.walletClient;return t!==r},{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>{let t=!!e.publicClient,r=!!e.walletClient,n=!!e.chain;return t&&r?!0:n},{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),Ey=H.object({composeHash:H.string(),appId:H.string(),transactionHash:H.string(),blockNumber:H.bigint().optional(),gasUsed:H.bigint().optional()}).passthrough();var Kf=gi;var Wf=St.object({items:St.array(Kf),total:St.number(),page:St.number(),page_size:St.number(),pages:St.number()}).passthrough(),{action:Iy,safeAction:Ay}=_(Wf,async(e,t)=>{let{teamSlug:r,page:n,pageSize:o}=t,s=new URLSearchParams;n!==void 0&&s.append("page",n.toString()),o!==void 0&&s.append("page_size",o.toString());let i=s.toString()?`/workspaces/${r}/nodes?${s.toString()}`:`/workspaces/${r}/nodes`;return await e.get(i)}),It=ke.object({limit:ke.number(),remaining:ke.number()}).passthrough(),Xf=ke.object({vm_slots:It,vcpu:It,memory_mb:It,disk_gb:It}).passthrough(),Jf=ke.object({gpus:It,in_use:ke.number(),misconfigured:ke.number()}).passthrough(),Zf=ke.object({team_slug:ke.string(),tier:ke.string(),quotas:Xf,reserved_nodes:It,reserved_gpu:Jf,as_of:ke.string()}).passthrough(),{action:$y,safeAction:Ly}=_(Zf,async(e,t)=>await e.get(`/workspaces/${t.teamSlug}/quotas`)),Qf=Re(xe.extend({node_id:Yf.number().optional()})),{action:Ry,safeAction:By}=_(Jt,async(e,t)=>{let r=Qf.parse(t),{cvmId:n}=j.parse(r),{node_id:o}=r;return await e.post(`/cvms/${n}/replicas`,{node_id:o})}),Uy=Et.object({target:Et.string().describe("Target status to wait for (e.g., 'running', 'stopped')"),interval:Et.number().min(5).max(30).default(5).describe("Polling interval in seconds"),timeout:Et.number().min(10).max(600).default(300).describe("Timeout per attempt in seconds"),maxRetries:Et.number().min(0).default(Number.POSITIVE_INFINITY).describe("Maximum number of retry attempts (Infinity for unlimited)"),retryDelay:Et.number().min(0).default(5e3).describe("Delay between retries in milliseconds")});var $i=Ce.object({cvm_id:Ce.number().int(),identifier:Ce.string(),status:Ce.enum(["updated","unchanged","skipped","conflict","error"]),old_instance_id:Ce.string().nullable().optional(),new_instance_id:Ce.string().nullable().optional(),source:Ce.enum(["teepod_state","teepod_info","gateway","none"]),verified_with_gateway:Ce.boolean(),reason:Ce.string().nullable().optional()}),em=Re(xe.extend({overwrite:Ce.boolean().optional(),dry_run:Ce.boolean().optional()})),{action:Hy,safeAction:Oy}=_($i,async(e,t)=>{let r=em.parse(t),{cvmId:n}=j.parse(r),{overwrite:o,dry_run:s}=r;return await e.patch(`/cvms/${n}/instance-id`,{overwrite:o,dry_run:s})}),tm=M.object({cvm_ids:M.array(M.string()).optional(),running_only:M.boolean().optional(),missing_only:M.boolean().optional(),overwrite:M.boolean().optional(),limit:M.number().int().min(1).max(500).optional(),dry_run:M.boolean().optional()}).strict(),rm=M.object({total:M.number().int(),scanned:M.number().int(),updated:M.number().int(),unchanged:M.number().int(),skipped:M.number().int(),conflicts:M.number().int(),errors:M.number().int(),items:M.array($i)}),{action:Gy,safeAction:qy}=_(rm,async(e,t)=>{let r=tm.parse(t);return await e.patch("/cvms/instance-ids",r)}),nm=te.object({vm_uuid:te.string(),status:te.string(),uptime:te.string().nullable().optional(),in_progress:te.boolean(),boot_progress:te.string().nullable().optional(),boot_error:te.string().nullable().optional(),operation_type:te.string().nullable().optional(),operation_started_at:te.string().nullable().optional(),correlation_id:te.string().nullable().optional()}),om=te.record(te.string(),nm),sm=te.object({vmUuids:te.array(te.string())}),{action:Vy,safeAction:My}=_(om,async(e,t)=>{let{vmUuids:r}=sm.parse(t);return await e.post("/status/batch",{vm_uuids:r})}),im=Xt.object({hostname:Xt.string().nullable().optional(),ssh_authorized_keys:Xt.array(Xt.string()).default([]),default_gateway_domain:Xt.string().nullable().optional()}),am=j,{action:Wy,safeAction:Xy}=_(im,async(e,t)=>{let{cvmId:r}=am.parse(t);return await e.get(`/cvms/${r}/user_config`)}),Zy=pe.object({page:pe.number().int().min(1).optional(),page_size:pe.number().int().min(1).max(100).optional(),search:pe.string().optional(),status:pe.array(pe.string()).optional(),listed:pe.boolean().optional(),base_image:pe.string().optional(),instance_type:pe.string().optional(),kms_slug:pe.string().optional(),kms_type:pe.string().optional(),node:pe.string().optional(),region:pe.string().optional()}).strict();var Qy=ti.object({appId:ti.string().min(1)}).strict();var tv=ri.object({appId:ri.string().min(1)}).strict();var nv=Br.object({appId:Br.string().min(1),page:Br.number().int().min(1).optional(),page_size:Br.number().int().min(1).max(1e3).optional()}).strict();var sv=jr.object({appId:jr.string().min(1),revisionId:jr.string().min(1),rawComposeFile:jr.boolean().optional()}).strict();var av=ee.object({statuses:ee.array(ee.string()),image_versions:ee.array(ee.string()),instance_types:ee.array(ee.string()),kms_slugs:ee.array(ee.string()),kms_types:ee.array(ee.string()),regions:ee.array(ee.string()),nodes:ee.array(ee.string())});var cm=$.object({contract_address:$.string(),chain_id:$.string().nullable(),version:$.string(),url:$.string(),gateway_app_id:$.string().nullable(),gateway_app_url:$.string(),kms_type:$.string()}),ni=$.object({app_id:$.string().optional(),instance_id:$.string().optional(),app_name:$.string().optional(),device_id:$.string().optional()}).passthrough().nullable(),lm=$.object({vm_uuid:$.string().nullable().optional(),name:$.string().optional(),instance_id:$.string().nullable().optional(),status:$.string().optional(),image_version:$.string().nullable().optional(),quote:$.string().nullable().optional(),ppid:$.string().optional(),device_id:$.string().optional(),tcb_info:Si.nullable().optional(),app_certificates:$.array(ki).nullable().optional(),compose_file:$.string().nullable().optional(),error:$.string().nullable().optional()}),um=$.object({app_id:$.string(),contract_address:$.string(),kms_info:cm,instances:$.array(lm),kms_guest_agent_info:ni,gateway_guest_agent_info:ni,qemu_version:$.string().nullable()}),pm=$.object({appId:$.string().min(1)}).strict(),{action:lv,safeAction:uv}=_(um,async(e,t)=>{let{appId:r}=pm.parse(t);return await e.get(`/apps/${r}/attestations`)});var hm;function Li(){return hm}import vm from"path";import On from"fs-extra";import wm from"@iarna/toml";import{z as Be}from"zod";import ne from"chalk";import bm from"ora";var gm=!1;function Se(){return gm}function xm(e,t){let r=e.split(/\s+/),n=[],o="";for(let s of r){let i=o.length===0?s:`${o} ${s}`;i.length<=t?o=i:(o.length>0&&n.push(o),o=s)}return o.length>0&&n.push(o),n}function ym(e,t){if(e.length<=t)return[e];let r=[],n=0;for(;n<e.length;)r.push(e.slice(n,n+t)),n+=t;return r}function zi(e,t){let r=[];for(let n of e.split(`
26
- `)){if(n.length<=t){r.push(n);continue}if(n.indexOf(" ")===-1){r.push(...ym(n,t));continue}let o=xm(n,t);r.push(...o)}if(r.length===0){let n=e.trim();r.push(n)}return r}var Ze={error:(e,...t)=>{Se()||(process.stderr.write(`${ne.red("\u2717")} ${ne.red(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
27
- `))},warn:(e,...t)=>{Se()||(process.stderr.write(`${ne.yellow("\u26A0")} ${ne.yellow(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
28
- `))},info:(e,...t)=>{Se()||(process.stderr.write(`${ne.blue("\u2139")} ${ne.blue(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
29
- `))},success:(e,...t)=>{Se()||(process.stderr.write(`${ne.green("\u2713")} ${ne.green(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
30
- `))},debug:(e,...t)=>{Se()||process.env.DEBUG&&(process.stderr.write(`${ne.gray("\u{1F50D}")} ${ne.gray(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
31
- `))},table:(e,t)=>{if(!Se()){if(e.length===0){console.log(ne.yellow("No data to display"));return}if(t){let r;typeof t[0]=="string"?r=t.map(i=>({key:i,header:i})):r=t;let n={};for(let i of r){let a=i.header||String(i.key);n[String(i.key)]=a.length}for(let i of e)for(let a of r){let l=String(typeof a.key=="string"&&!(a.key in i)?"":i[String(a.key)]??"");n[String(a.key)]=Math.max(n[String(a.key)],l.length)}let o=[];for(let i of r){let a=i.header||String(i.key);o.push(ne.bold(a.padEnd(n[String(i.key)])))}console.log(o.join(" "));let s=[];for(let i of r)s.push("-".repeat(n[String(i.key)]));console.log(s.join(" "));for(let i of e){let a=[];for(let l of r){let u=String(typeof l.key=="string"&&!(l.key in i)?"":i[String(l.key)]??"");a.push(u.padEnd(n[String(l.key)]))}console.log(a.join(" "))}}else{let r=e[0],n=Object.keys(r),o={};for(let a of n)o[a]=a.length;for(let a of e)for(let l of n){let u=String(a[l]??"");o[l]=Math.max(o[l],u.length)}let s=[];for(let a of n)s.push(ne.bold(a.padEnd(o[a])));console.log(s.join(" "));let i=[];for(let a of n)i.push("-".repeat(o[a]));console.log(i.join(" "));for(let a of e){let l=[];for(let u of n){let p=String(a[u]??"");l.push(p.padEnd(o[u]))}console.log(l.join(" "))}}}},keyValueTable:(e,t)=>{if(Se())return;let{borderStyle:r="single",keyColor:n=ne.blue,valueColor:o=ne.white,maxWidth:s=process.stdout.columns||80}=t||{},a={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",cross:"\u253C",leftT:"\u251C",rightT:"\u2524"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",cross:"\u256C",leftT:"\u2560",rightT:"\u2563"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",cross:"\u253C",leftT:"\u251C",rightT:"\u2524"},bold:{topLeft:"\u250F",topRight:"\u2513",bottomLeft:"\u2517",bottomRight:"\u251B",horizontal:"\u2501",vertical:"\u2503",cross:"\u254B",leftT:"\u2523",rightT:"\u252B"},none:{topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",horizontal:"",vertical:"",cross:"",leftT:"",rightT:""}}[r],l=0,u=0;for(let[C,P]of Object.entries(e)){l=Math.max(l,C.length);let R=String(P??"");u=Math.max(u,R.length)}let p=4,f=1,h=s-p-f;if(l+u>h){let C=l/(l+u);l=Math.floor(h*C),u=h-l}let g=l+u+p+f;r!=="none"&&console.log(a.topLeft+a.horizontal.repeat(g-2)+a.topRight);for(let[C,P]of Object.entries(e)){let R=C,q=String(P??""),Y=zi(R,l),W=zi(q,u),Q=Math.max(Y.length,W.length);for(;Y.length<Q;)Y.push("");for(;W.length<Q;)W.push("");for(let se=0;se<Q;se++){let fe=Y[se].padEnd(l),Zt=W[se].padEnd(u);console.log(r!=="none"?`${a.vertical} ${n(fe)} ${a.vertical} ${o(Zt)} ${a.vertical}`:`${n(fe)} : ${o(Zt)}`)}}r!=="none"&&console.log(a.bottomLeft+a.horizontal.repeat(g-2)+a.bottomRight)},break:()=>{Se()||process.stderr.write(`
32
- `)},startSpinner:e=>{if(Se())return{stop:()=>{}};let t=bm(e).start();return{stop:(r=!0,n)=>{n&&(t.text=n),r?t.succeed():t.fail()}}},logDetailedError(e,t){if(Se())return;let r=t?`[${t}] `:"",n=s=>s!==null&&typeof s=="object"&&"isRequestError"in s&&s.isRequestError===!0&&"status"in s&&"message"in s&&"data"in s,o=s=>s!==null&&typeof s=="object"&&"issues"in s&&Array.isArray(s.issues);if(n(e)){process.stderr.write(`${r}HTTP ${e.status}: ${e.message}
20
+ `,O,Q,Yn(S.status,S.statusText,S.headers,S._data))}d&&d({request:C,response:S,options:T})}})}get raw(){return this.fetchInstance}on(t,n){this.emitter.on(t,n)}off(t,n){this.emitter.off(t,n)}once(t,n){let r=s=>{n(s),this.emitter.off(t,r)};this.emitter.on(t,r)}async request(t,n){try{let r=n?.method||"GET";return await this.fetchInstance(t,{...n,method:r})}catch(r){let s=this.convertToRequestError(r);throw this.emitError(s)}}async requestFull(t,n){try{let r=n?.method||"GET",s=await this.fetchInstance.raw(t,{...n,method:r,ignoreResponseError:!0});return{status:s.status,statusText:s.statusText,headers:s.headers,data:s._data,ok:s.ok}}catch(r){let s=this.convertToRequestError(r);throw this.emitError(s)}}async get(t,n){try{return await this.fetchInstance(t,{...n,method:"GET"})}catch(r){let s=this.convertToRequestError(r);throw this.emitError(s)}}async post(t,n,r){try{return await this.fetchInstance(t,{...r,method:"POST",body:n})}catch(s){let o=this.convertToRequestError(s);throw this.emitError(o)}}async put(t,n,r){try{return await this.fetchInstance(t,{...r,method:"PUT",body:n})}catch(s){let o=this.convertToRequestError(s);throw this.emitError(o)}}async patch(t,n,r){try{return await this.fetchInstance(t,{...r,method:"PATCH",body:n})}catch(s){let o=this.convertToRequestError(s);throw this.emitError(o)}}async delete(t,n){try{return await this.fetchInstance(t,{...n,method:"DELETE"})}catch(r){let s=this.convertToRequestError(r);throw this.emitError(s)}}convertToRequestError(t){return t&&typeof t=="object"&&"data"in t?Ut.fromFetchError(t):t instanceof Error?Ut.fromError(t):new Ut("Unknown error occurred",{detail:"Unknown error occurred"})}emitError(t){let n=_o(t);return this.emitter.emit("error",n),n}async safeRequest(t){try{return{success:!0,data:await t()}}catch(n){if(n instanceof Ce)return{success:!1,error:n};let r=this.convertToRequestError(n);return this.emitError(r),{success:!1,error:r}}}async safeGet(t,n){return this.safeRequest(()=>this.get(t,n))}async safePost(t,n,r){return this.safeRequest(()=>this.post(t,n,r))}async safePut(t,n,r){return this.safeRequest(()=>this.put(t,n,r))}async safePatch(t,n,r){return this.safeRequest(()=>this.patch(t,n,r))}async safeDelete(t,n){return this.safeRequest(()=>this.delete(t,n))}async safeRequestMethod(t,n){return this.safeRequest(()=>this.request(t,n))}async safeRequestFull(t,n){return this.safeRequest(()=>this.requestFull(t,n))}withVersion(t){return new mr({...this.config,version:t})}extend(t){let n=typeof t=="function"?t(this):t,r=Object.create(this);for(let[s,o]of Object.entries(n))typeof o=="function"&&(r[s]=(...a)=>o(this,...a));return r}};function xo(e={}){return new Ao(e)}var Io=L.object({username:L.string(),email:L.string(),role:L.enum(["admin","user"]),avatar:L.string(),email_verified:L.boolean(),totp_enabled:L.boolean(),has_backup_codes:L.boolean(),flag_has_password:L.boolean()}).passthrough(),Ro=L.object({id:L.string(),name:L.string(),slug:L.string().nullable(),tier:L.string(),role:L.string(),avatar:L.string().nullable().optional()}).passthrough(),jo=L.object({balance:L.string().or(L.number()),granted_balance:L.string().or(L.number()),is_post_paid:L.boolean(),outstanding_amount:L.string().or(L.number()).nullable()}).passthrough(),Po=L.object({user:Io,workspace:Ro,credits:jo}).passthrough(),To=Te.object({username:Te.string(),email:Te.string(),credits:Te.number(),granted_credits:Te.number(),avatar:Te.string(),team_name:Te.string(),team_tier:Te.string()}).passthrough();function $o(e){return e==="2025-10-28"?To:Po}async function fr(e,t){let n=await e.get("/auth/me");return t?.schema===!1?n:(t?.schema||$o(e.config.version)).parse(n)}async function Lo(e,t){try{return{success:!0,data:await fr(e,t)}}catch(n){return n&&typeof n=="object"&&("status"in n||"issues"in n)?{success:!1,error:n}:{success:!1,error:{name:"Error",message:n instanceof Error?n.message:String(n)}}}}var Oo={[nr.id]:nr,[tr.id]:tr,[er.id]:er},qo=$e.object({id:$e.string(),slug:$e.string().nullable(),url:$e.string(),version:$e.string(),chain_id:$e.number().nullable(),kms_contract_address:$e.string().nullable().transform(e=>e),gateway_app_id:$e.string().nullable().transform(e=>e)}).passthrough(),ke=qo.transform(e=>{if(e.chain_id!=null){let t=Oo[e.chain_id];if(t)return{...e,chain:t}}return e});function gr(e){if(e?.schema!==void 0&&e?.schema!==!1&&(typeof e.schema!="object"||e.schema===null||!("parse"in e.schema)||typeof e.schema.parse!="function"))throw new Error("Invalid schema: must be a Zod schema object, false, or undefined")}function hr(e){if(e?.schema!==void 0&&e?.schema!==!1&&(typeof e.schema!="object"||e.schema===null||!("parse"in e.schema)||typeof e.schema.parse!="function"))return{success:!1,error:{name:"ZodError",message:"Invalid schema: must be a Zod schema object, false, or undefined",issues:[{code:"invalid_type",expected:"object",received:typeof e.schema,path:["schema"],message:"Invalid schema: must be a Zod schema object, false, or undefined"}]}}}function br(e,t){function n(a,c){return r(a,c)}async function r(a,c){gr(c);let l=await t(a);return c?.schema===!1?l:(c?.schema||e).parse(l)}function s(a,c){return o(a,c)}async function o(a,c){let l=hr(c);if(l)return l;let m=await(async()=>{try{return{success:!0,data:await t(a)}}catch(f){return f&&typeof f=="object"&&"status"in f?{success:!1,error:f}:f&&typeof f=="object"&&"issues"in f?{success:!1,error:f}:{success:!1,error:{name:"Error",message:f instanceof Error?f.message:String(f)}}}})();return m.success?c?.schema===!1?{success:!0,data:m.data}:(c?.schema||e).safeParse(m.data):m}return{action:n,safeAction:s}}function v(e,t){function n(a,...c){let[l,m]=c;return r(a,l,m)}async function r(a,c,l){gr(l);let m=await t(a,c);return l?.schema===!1?m:(l?.schema||e).parse(m)}function s(a,...c){let[l,m]=c;return o(a,l,m)}async function o(a,c,l){let m=hr(l);if(m)return m;let d=await(async()=>{try{return{success:!0,data:await t(a,c)}}catch(b){return b&&typeof b=="object"&&"status"in b?{success:!1,error:b}:b&&typeof b=="object"&&"issues"in b?{success:!1,error:b}:{success:!1,error:{name:"Error",message:b instanceof Error?b.message:String(b)}}}})();return d.success?l?.schema===!1?{success:!0,data:d.data}:(l?.schema||e).safeParse(d.data):d}return{action:n,safeAction:s}}var Fo=k.object({name:k.string(),is_dev:k.boolean(),version:k.union([k.tuple([k.number(),k.number(),k.number()]),k.tuple([k.number(),k.number(),k.number(),k.number()])]),os_image_hash:k.string().nullable().optional()}).passthrough(),zo=k.object({teepod_id:k.number(),name:k.string(),listed:k.boolean(),resource_score:k.number(),remaining_vcpu:k.number(),remaining_memory:k.number(),remaining_cvm_slots:k.number(),images:k.array(Fo),support_onchain_kms:k.boolean().optional(),fmspc:k.string().nullable().optional(),device_id:k.string().nullable().optional(),region_identifier:k.string().nullable().optional(),default_kms:k.string().nullable().optional(),kms_list:k.array(k.string()).default([])}).passthrough(),Uo=k.object({max_instances:k.number().nullable().optional(),max_vcpu:k.number().nullable().optional(),max_memory:k.number().nullable().optional(),max_disk:k.number().nullable().optional()}).passthrough(),No=k.object({tier:k.string(),capacity:Uo,nodes:k.array(zo),kms_list:k.array(ke)}).passthrough(),{action:Do,safeAction:Bo}=br(No,async e=>await e.get("/teepods/available")),yr=D.object({id:D.string(),name:D.string(),description:D.string(),vcpu:D.number(),memory_mb:D.number(),hourly_rate:D.string(),requires_gpu:D.boolean(),default_disk_size_gb:D.number().default(20),family:D.string().nullable()}).passthrough(),Ho=D.object({name:D.string(),items:D.array(yr),total:D.number()}).strict(),Vo=D.object({result:D.array(Ho)}).strict(),Ko=D.object({items:D.array(yr),total:D.number(),family:D.string()}).strict(),Go=D.object({family:D.string()}).strict(),{action:Mo,safeAction:Wo}=v(Vo,async e=>await e.get("/instance-types")),{action:Jo,safeAction:Xo}=v(Ko,async(e,t)=>{let n=Go.parse(t);return await e.get(`/instance-types/${n.family}`)}),vr=te.object({id:te.string(),name:te.string(),slug:te.string().nullable(),tier:te.string(),role:te.string(),is_default:te.boolean(),created_at:te.string(),confidential_models_enabled:te.boolean().optional()}).passthrough(),Zo=te.object({has_more:te.boolean(),next_cursor:te.string().nullable(),total:te.number().nullable()}).passthrough(),Qo=te.object({data:te.array(vr),pagination:Zo}).passthrough(),{action:Yo,safeAction:ea}=v(Qo,async(e,t)=>{let n=new URLSearchParams;t?.cursor&&n.append("cursor",t.cursor),t?.limit&&n.append("limit",t.limit.toString());let r=n.toString()?`/workspaces?${n.toString()}`:"/workspaces";return await e.get(r)}),{action:ta,safeAction:na}=v(vr,async(e,t)=>await e.get(`/workspaces/${t}`)),ra=u.object({id:u.string(),name:u.string(),status:u.string(),uptime:u.string(),app_url:u.string().nullable(),app_id:u.string(),instance_id:u.string().nullable(),configuration:u.any().optional(),exited_at:u.string().nullable(),boot_progress:u.string().nullable(),boot_error:u.string().nullable(),shutdown_progress:u.string().nullable(),image_version:u.string().nullable()}),sa=u.object({id:u.number(),username:u.string()}),_r=u.object({id:u.number(),name:u.string(),region_identifier:u.string().nullable().optional()}),Kt=u.object({vcpu:u.number(),memory:u.number(),disk_size:u.number(),gpu_count:u.number().default(0)}),Gt=u.object({app:u.string(),instance:u.string()}),oa=u.object({hosted:ra,name:u.string(),managed_user:sa.nullable(),node:_r.nullable(),listed:u.boolean().default(!1),status:u.string(),in_progress:u.boolean().default(!1),dapp_dashboard_url:u.string().nullable(),syslog_endpoint:u.string().nullable(),allow_upgrade:u.boolean().default(!1),project_id:u.string().nullable(),project_type:u.string().nullable(),billing_period:u.string().nullable(),kms_info:ke.nullable(),vcpu:u.number().nullable(),memory:u.number().nullable(),disk_size:u.number().nullable(),gateway_domain:u.string().nullable(),public_urls:u.array(Gt),machine_info:Kt.nullable().optional(),updated_at:u.string().nullable().optional()}),wr=u.object({id:u.number(),name:u.string(),status:u.string(),in_progress:u.boolean().optional().default(!1),teepod_id:u.number().nullable(),teepod:_r.optional().nullable(),app_id:u.string(),vm_uuid:u.string().nullable(),instance_id:u.string().nullable(),vcpu:u.number(),memory:u.number(),disk_size:u.number(),base_image:u.string().nullable(),encrypted_env_pubkey:u.string().nullable(),listed:u.boolean().optional().default(!1),project_id:u.string().optional().nullable(),project_type:u.string().optional().nullable(),instance_type:u.string().optional().nullable(),public_sysinfo:u.boolean().optional().default(!1),public_logs:u.boolean().optional().default(!1),dapp_dashboard_url:u.string().optional().nullable(),syslog_endpoint:u.string().optional().nullable(),kms_info:ke.optional().nullable(),contract_address:u.string().optional().nullable(),deployer_address:u.string().optional().nullable(),scheduled_delete_at:u.string().optional().nullable(),public_urls:u.array(Gt).optional().default([]),gateway_domain:u.string().optional().nullable(),machine_info:Kt.optional().nullable(),updated_at:u.string().optional().nullable()}),aa=u.object({items:u.array(oa),total:u.number(),page:u.number(),page_size:u.number(),pages:u.number()}),ia=p.enum(["skip","hourly","monthly"]),ca=p.enum(["phala","ethereum","base","legacy"]),Mt=p.object({object_type:p.literal("user"),id:p.string().nullable().optional(),username:p.string().nullable().optional(),avatar_url:p.string().nullable().optional()}),Wt=p.object({object_type:p.literal("workspace"),id:p.string(),name:p.string(),slug:p.string().nullable().optional(),avatar_url:p.string().nullable().optional()}),la=p.object({instance_type:p.string().nullable().optional(),vcpu:p.number().int().nullable().optional(),memory_in_gb:p.number().nullable().optional(),disk_in_gb:p.number().int().nullable().optional(),gpus:p.number().int().nullable().optional(),compute_billing_price:p.string().nullable().optional(),billing_period:ia.nullable().optional()}),ua=p.object({name:p.string().nullable().optional(),version:p.string().nullable().optional(),is_dev:p.boolean().nullable().optional(),os_image_hash:p.string().nullable().optional()}),pa=p.object({chain_id:p.number().int().nullable().optional(),dstack_kms_address:p.string().nullable().optional(),dstack_app_address:p.string().nullable().optional(),deployer_address:p.string().nullable().optional(),rpc_endpoint:p.string().nullable().optional(),encrypted_env_pubkey:p.string().nullable().optional()}),da=p.object({target:p.string().nullable().optional(),started_at:p.string().nullable().optional(),correlation_id:p.string().nullable().optional()}),ma=p.object({base_domain:p.string().nullable().optional(),cname:p.string().nullable().optional()}),Cr=p.object({object_type:p.literal("node"),id:p.number().int().nullable().optional(),name:p.string().nullable().optional(),region:p.string().nullable().optional(),device_id:p.string().nullable().optional(),ppid:p.string().nullable().optional(),status:p.string().nullable().optional(),version:p.string().nullable().optional()});var _t=p.object({id:p.string(),name:p.string(),app_id:p.string().nullable().optional(),vm_uuid:p.string().nullable().optional(),instance_id:p.string().nullable().optional(),resource:la,node_info:Cr.nullable().optional(),os:ua.nullable().optional(),kms_type:ca.nullable().optional(),kms_info:pa.nullable().optional(),status:p.string(),progress:da.nullable().optional(),compose_hash:p.string().nullable().optional(),gateway:ma,services:p.array(p.record(p.any())).optional().default([]),endpoints:p.array(Gt).nullable().optional(),public_logs:p.boolean().optional(),public_sysinfo:p.boolean().optional(),public_tcbinfo:p.boolean().optional(),gateway_enabled:p.boolean().optional(),secure_time:p.boolean().optional(),listed:p.boolean().optional().default(!1),storage_fs:p.string().optional(),workspace:Wt.nullable().optional(),creator:Mt.nullable().optional()}),fa=_t.extend({compose_file:p.union([p.record(p.any()),p.string()]).nullable().optional()}),ga=p.object({items:p.array(_t),total:p.number(),page:p.number(),page_size:p.number(),pages:p.number()});function kr(e){return typeof e!="string"||e.length<5||e.length>63?!1:/^[a-zA-Z](?!.*--)([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(e)}var de=Me.object({id:Me.string().optional(),uuid:Me.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i,"Invalid UUID format").optional(),app_id:Me.string().optional(),instance_id:Me.string().optional(),name:Me.string().refine(kr,{message:"Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens"}).optional()}),Se=e=>e.refine(t=>{let n=t;return!!(n.id||n.uuid||n.app_id||n.instance_id||n.name)},{message:"One of id, uuid, app_id, instance_id, or name must be provided"}),ha=Se(de),P=ha.transform(e=>{let t;if(e.id)t=e.id;else if(e.uuid)t=e.uuid;else if(e.app_id)t=e.app_id;else if(e.instance_id)t=e.instance_id;else{if(e.name)return{cvmId:e.name};throw new Error("No valid identifier provided")}let n=/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i,r=/^[0-9a-f]{40}$/i,s;return n.test(t)?s=t.replace(/-/g,""):r.test(t)?s=`app_${t}`:s=t,{cvmId:s}}),ba=P;function ya(e){return e==="2025-10-28"?wr:fa}async function Sr(e,t){let{cvmId:n}=ba.parse(t),r=await e.get(`/cvms/${n}`);return ya(e.config.version).parse(r)}async function Ct(e,t){try{return{success:!0,data:await Sr(e,t)}}catch(n){return n&&typeof n=="object"&&("status"in n||"issues"in n)?{success:!1,error:n}:{success:!1,error:{name:"Error",message:n instanceof Error?n.message:String(n)}}}}var va=We.object({page:We.number().int().min(1).optional(),page_size:We.number().int().min(1).optional(),node_id:We.number().int().min(1).optional(),teepod_id:We.number().int().min(1).optional(),user_id:We.string().optional()}).strict();function _a(e){return e==="2025-10-28"?aa:ga}async function Er(e,t){let n=va.parse(t??{}),r=await e.get("/cvms/paginated",{params:n});return _a(e.config.version).parse(r)}async function Jt(e,t){try{return{success:!0,data:await Er(e,t)}}catch(n){return n&&typeof n=="object"&&("status"in n||"issues"in n)?{success:!1,error:n}:{success:!1,error:{name:"Error",message:n instanceof Error?n.message:String(n)}}}}var rr=200*1024;function Ar(e,t,n){let r=new TextEncoder,s=e?r.encode(e).byteLength:0,o=t?r.encode(t).byteLength:0,a=s+o;if(a>rr){let c=rr/1024,l=Math.ceil(a/1024);n.addIssue({code:G.ZodIssueCode.custom,message:`Combined size of docker_compose_file and pre_launch_script must not exceed ${c}KB (current: ${l}KB)`})}}var xr=G.object({allowed_envs:G.array(G.string()).optional(),docker_compose_file:G.string(),features:G.array(G.string()).optional(),name:G.string().optional(),manifest_version:G.number().optional(),kms_enabled:G.boolean().optional(),public_logs:G.boolean().optional(),public_sysinfo:G.boolean().optional(),tproxy_enabled:G.boolean().optional(),storage_fs:G.enum(["ext4","zfs"]).optional(),pre_launch_script:G.string().optional(),env_pubkey:G.string().optional(),salt:G.string().optional().nullable()}).passthrough().superRefine((e,t)=>{Ar(e.docker_compose_file,e.pre_launch_script,t)}),wa=w.object({app_id:w.string().nullable().optional(),app_env_encrypt_pubkey:w.string().nullable().optional(),compose_hash:w.string(),kms_info:ke.nullable().optional(),fmspc:w.string().nullable().optional(),device_id:w.string().nullable().optional(),os_image_hash:w.string().nullable().optional(),instance_type:w.string().nullable().optional(),teepod_id:w.number().nullable().optional(),node_id:w.number().nullable().optional(),kms_id:w.string().nullable().optional()}).passthrough().transform(e=>{if("teepod_id"in e&&e.teepod_id!==void 0){let{teepod_id:t,...n}=e;return{...n,node_id:t}}return e}),Nt="Name must be 5-63 characters, start with letter, and contain only letters/numbers/hyphens",Ca=w.object({node_id:w.number().optional(),teepod_id:w.number().optional(),region:w.string().optional(),name:w.string().min(5,Nt).max(63,Nt).refine(e=>kr(e),Nt),instance_type:w.string().optional(),image:w.string().optional(),vcpu:w.number().optional(),memory:w.number().optional(),disk_size:w.number().optional(),compose_file:w.object({allowed_envs:w.array(w.string()).optional(),pre_launch_script:w.string().optional(),docker_compose_file:w.string().optional(),name:w.string().optional().default(""),kms_enabled:w.boolean().optional(),public_logs:w.boolean().optional(),public_sysinfo:w.boolean().optional(),gateway_enabled:w.boolean().optional(),tproxy_enabled:w.boolean().optional(),storage_fs:w.enum(["ext4","zfs"]).optional()}).superRefine((e,t)=>{Ar(e.docker_compose_file,e.pre_launch_script,t)}),listed:w.boolean().optional(),kms_id:w.string().optional(),kms:w.enum(["PHALA","ETHEREUM","BASE"]).optional(),kms_contract:w.string().optional(),env_keys:w.array(w.string()).optional(),nonce:w.number().optional(),app_id:w.string().optional()}).passthrough().transform(e=>!e.instance_type&&!e.vcpu&&!e.memory?{...e,instance_type:"tdx.small"}:e);function ka(e){if(!e.compose_file)return e;let t={...e.compose_file};return typeof t.gateway_enabled=="boolean"&&typeof t.tproxy_enabled=="boolean"?delete t.tproxy_enabled:typeof t.tproxy_enabled=="boolean"&&typeof t.gateway_enabled>"u"&&(t.gateway_enabled=t.tproxy_enabled,delete t.tproxy_enabled,(typeof window<"u"?window.console:globalThis.console)&&console.warn("[phala/cloud] tproxy_enabled is deprecated, please use gateway_enabled instead. See docs for migration.")),{...e,compose_file:t}}var{action:Sa,safeAction:Ea}=v(wa,async(e,t)=>{let n=Ca.parse(t),r=ka(n),s={...r};return typeof r.node_id=="number"?(s={...r,teepod_id:r.node_id},delete s.node_id):typeof r.teepod_id=="number"&&console.warn("[phala/cloud] teepod_id is deprecated, please use node_id instead."),await e.post("/cvms/provision",s)}),Aa=E.object({id:E.number(),name:E.string(),status:E.string(),teepod_id:E.number(),teepod:E.object({id:E.number(),name:E.string()}).nullable(),user_id:E.number().nullable(),app_id:E.string().nullable(),vm_uuid:E.string().nullable(),instance_id:E.string().nullable(),app_url:E.string().nullable().default(null),base_image:E.string().nullable(),vcpu:E.number(),memory:E.number(),disk_size:E.number(),manifest_version:E.number().nullable().default(2),version:E.string().nullable().default("1.0.0"),runner:E.string().nullable().default("docker-compose"),docker_compose_file:E.string().nullable(),features:E.array(E.string()).nullable().default(["kms","tproxy-net"]),created_at:E.string(),encrypted_env_pubkey:E.string().nullable().optional(),app_auth_contract_address:E.string().nullable().optional(),deployer_address:E.string().nullable().optional()}).passthrough(),Du=E.object({encrypted_env:E.string().optional().nullable(),app_id:E.string(),compose_hash:E.string(),kms_id:E.string().optional(),contract_address:E.string().optional(),deployer_address:E.string().optional(),env_keys:E.array(E.string()).optional().nullable()}).passthrough(),{action:xa,safeAction:Ia}=v(Aa,async(e,t)=>await e.post("/cvms",t));function Ht(e){return e==null?e:Array.isArray(e)?e.map(Ht):e&&typeof e=="object"&&e.constructor===Object?Object.keys(e).sort().reduce((t,n)=>{let r=e[n];return t[n]=Ht(r),t},{}):e}function Ir(e){let t={...e};return t.runner==="bash"&&"docker_compose_file"in t?delete t.docker_compose_file:t.runner==="docker-compose"&&"bash_script"in t&&delete t.bash_script,"pre_launch_script"in t&&!t.pre_launch_script&&delete t.pre_launch_script,t}function Rr(e){let t=Ht(e),n=JSON.stringify(t,null,4);return n=n.replace(/": /g,'":'),n}function ja(e){let t=Ir(e),n=Rr(t);return Ra.createHash("sha256").update(n,"utf8").digest("hex")}function Pa(e){let t=e;return{...e,getHash:()=>ja(t),toString:()=>Rr(Ir(t))}}var Ta=xr.transform(e=>Pa(e)),$a=P,{action:La,safeAction:Xt}=v(Ta,async(e,t)=>{let{cvmId:n}=$a.parse(t);return await e.get(`/cvms/${n}/compose_file`)}),Oa=_e.object({id:_e.string().optional(),uuid:_e.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),app_id:_e.string().refine(e=>!e.startsWith("app_")&&e.length===40,"app_id should be 40 characters without prefix").transform(e=>e.startsWith("app_")?e:`app_${e}`).optional(),instance_id:_e.string().refine(e=>!e.startsWith("instance_")&&e.length===40,"instance_id should be 40 characters without prefix").transform(e=>e.startsWith("instance_")?e:`instance_${e}`).optional(),app_compose:xr,update_env_vars:_e.boolean().optional().nullable()}).refine(e=>!!(e.id||e.uuid||e.app_id||e.instance_id),"One of id, uuid, app_id, or instance_id must be provided").transform(e=>({cvmId:e.id||e.uuid||e.app_id||e.instance_id,request:{...e.app_compose,update_env_vars:e.update_env_vars},_raw:e})),qa=_e.object({app_id:_e.string().nullable(),device_id:_e.string().nullable(),compose_hash:_e.string(),kms_info:ke.nullable().optional()}).passthrough(),{action:Fa,safeAction:za}=v(qa,async(e,t)=>{let n=Oa.parse(t);return await e.post(`/cvms/${n.cvmId}/compose_file/provision`,n.request)}),Ua=me.object({id:me.string().optional(),uuid:me.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),app_id:me.string().refine(e=>!e.startsWith("app_")&&e.length===40,"app_id should be 40 characters without prefix").transform(e=>e.startsWith("app_")?e:`app_${e}`).optional(),instance_id:me.string().refine(e=>!e.startsWith("instance_")&&e.length===40,"instance_id should be 40 characters without prefix").transform(e=>e.startsWith("instance_")?e:`instance_${e}`).optional(),compose_hash:me.string().min(1,"Compose hash is required"),encrypted_env:me.string().optional(),env_keys:me.array(me.string()).optional(),update_env_vars:me.boolean().optional().nullable()}).refine(e=>!!(e.id||e.uuid||e.app_id||e.instance_id),"One of id, uuid, app_id, or instance_id must be provided").transform(e=>({cvmId:e.id||e.uuid||e.app_id||e.instance_id,compose_hash:e.compose_hash,encrypted_env:e.encrypted_env,env_keys:e.env_keys,update_env_vars:e.update_env_vars??void 0,_raw:e})),Na=me.any().transform(()=>{}),{action:Da,safeAction:Ba}=v(Na,async(e,t)=>{let n=Ua.parse(t);return await e.patch(`/cvms/${n.cvmId}/compose_file`,{compose_hash:n.compose_hash,encrypted_env:n.encrypted_env,env_keys:n.env_keys,update_env_vars:n.update_env_vars})}),Ha=Se(de.extend({encrypted_env:J.string().describe("Encrypted environment variables (hex string)"),env_keys:J.array(J.string()).optional().describe("List of allowed environment variable keys"),compose_hash:J.string().optional().describe("Compose hash for verification (Phase 2, required when env_keys changes)"),transaction_hash:J.string().optional().describe("On-chain transaction hash for verification (Phase 2, required when env_keys changes)")})).transform(e=>{let{cvmId:t}=P.parse(e);return{cvmId:t,request:{encrypted_env:e.encrypted_env,env_keys:e.env_keys,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),Va=J.object({status:J.literal("in_progress"),message:J.string(),correlation_id:J.string(),allowed_envs_changed:J.boolean()}),Ka=J.object({status:J.literal("precondition_required"),message:J.string(),compose_hash:J.string(),app_id:J.string(),device_id:J.string(),kms_info:ke}),Ga=J.union([Va,Ka]),{action:Ma,safeAction:Wa}=v(Ga,async(e,t)=>{let n=Ha.parse(t);try{return await e.patch(`/cvms/${n.cvmId}/envs`,n.request)}catch(r){if(r instanceof Ce&&r.status===465){let s=r.detail;if(s&&typeof s=="object"){let o=s;return{status:"precondition_required",message:o.message||"Compose hash verification required",compose_hash:o.compose_hash,app_id:o.app_id,device_id:o.device_id,kms_info:o.kms_info}}}throw r}}),Ja=Se(de.extend({docker_compose_file:ie.string().describe("Docker Compose YAML content"),compose_hash:ie.string().optional().describe("Compose hash for verification (Phase 2, contract-owned KMS only)"),transaction_hash:ie.string().optional().describe("On-chain transaction hash for verification (Phase 2, contract-owned KMS only)")})).transform(e=>{let{cvmId:t}=P.parse(e);return{cvmId:t,request:{docker_compose_file:e.docker_compose_file,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),Xa=ie.object({status:ie.literal("in_progress"),message:ie.string(),correlation_id:ie.string()}),Za=ie.object({status:ie.literal("precondition_required"),message:ie.string(),compose_hash:ie.string(),app_id:ie.string(),device_id:ie.string(),kms_info:ke}),Qa=ie.union([Xa,Za]),{action:Ya,safeAction:ei}=v(Qa,async(e,t)=>{let n=Ja.parse(t),r={"Content-Type":"text/yaml"};n.request.compose_hash&&(r["X-Compose-Hash"]=n.request.compose_hash),n.request.transaction_hash&&(r["X-Transaction-Hash"]=n.request.transaction_hash);try{return await e.patch(`/cvms/${n.cvmId}/docker-compose`,n.request.docker_compose_file,{headers:r})}catch(s){if(s instanceof Ce&&s.status===465){let o=s.detail;if(o&&typeof o=="object"){let a=o;return{status:"precondition_required",message:a.message||"Compose hash verification required",compose_hash:a.compose_hash,app_id:a.app_id,device_id:a.device_id,kms_info:a.kms_info}}}throw s}}),ti=Se(de.extend({pre_launch_script:ce.string().describe("Pre-launch script content (shell script)"),compose_hash:ce.string().optional().describe("Compose hash for verification (Phase 2, contract-owned KMS only)"),transaction_hash:ce.string().optional().describe("On-chain transaction hash for verification (Phase 2, contract-owned KMS only)")})).transform(e=>{let{cvmId:t}=P.parse(e);return{cvmId:t,request:{pre_launch_script:e.pre_launch_script,compose_hash:e.compose_hash,transaction_hash:e.transaction_hash},_raw:e}}),ni=ce.object({status:ce.literal("in_progress"),message:ce.string(),correlation_id:ce.string()}),ri=ce.object({status:ce.literal("precondition_required"),message:ce.string(),compose_hash:ce.string(),app_id:ce.string(),device_id:ce.string(),kms_info:ke}),si=ce.union([ni,ri]),{action:oi,safeAction:ai}=v(si,async(e,t)=>{let n=ti.parse(t),r={"Content-Type":"text/plain"};n.request.compose_hash&&(r["X-Compose-Hash"]=n.request.compose_hash),n.request.transaction_hash&&(r["X-Transaction-Hash"]=n.request.transaction_hash);try{return await e.patch(`/cvms/${n.cvmId}/pre-launch-script`,n.request.pre_launch_script,{headers:r})}catch(s){if(s instanceof Ce&&s.status===465){let o=s.detail;if(o&&typeof o=="object"){let a=o;return{status:"precondition_required",message:a.message||"Compose hash verification required",compose_hash:a.compose_hash,app_id:a.app_id,device_id:a.device_id,kms_info:a.kms_info}}}throw s}}),ci=P,{action:li,safeAction:ui}=v(ii.string(),async(e,t)=>{let{cvmId:n}=ci.parse(t);return await e.get(`/cvms/${n}/pre-launch-script`)}),pi=sr.object({kms_id:sr.string().min(1,"KMS ID is required")}),{action:di,safeAction:mi}=v(ke,async(e,t)=>{let n=pi.parse(t);return await e.get(`/kms/${n.kms_id}`)}),fi=we.object({page:we.number().int().min(1).optional(),page_size:we.number().int().min(1).optional(),is_onchain:we.boolean().optional()}).strict(),gi=we.object({items:we.array(ke),total:we.number(),page:we.number(),page_size:we.number(),pages:we.number()}).strict(),{action:hi,safeAction:bi}=v(gi,async(e,t)=>{let n=fi.parse(t??{});return await e.get("/kms",{params:n})}),yi=et.object({kms:et.string().min(1,"KMS ID or slug is required"),app_id:et.string().refine(e=>e.length===40||e.startsWith("0x")&&e.length===42,"App ID must be exactly 40 characters or 42 characters with 0x prefix")}).strict(),vi=et.object({public_key:et.string(),signature:et.string()}).strict(),{action:_i,safeAction:wi}=v(vi,async(e,t)=>{let n=yi.parse(t);return await e.get(`/kms/${n.kms}/pubkey/${n.app_id}`)}),Ci=Ue.object({counts:Ue.number().int().min(1).max(20).optional().default(1)}).strict(),ki=Ue.object({app_ids:Ue.array(Ue.object({app_id:Ue.string(),nonce:Ue.number().int().min(0)}))}).strict(),{action:Si,safeAction:Ei}=v(ki,async(e,t)=>{let n=Ci.parse(t??{}),r=new URLSearchParams;return r.append("counts",n.counts.toString()),await e.get(`/kms/phala/next_app_id?${r.toString()}`)}),ct=j.object({id:j.number(),name:j.string(),status:j.string(),teepod_id:j.number(),teepod:j.object({id:j.number(),name:j.string(),region_identifier:j.string().nullable().optional()}).optional().nullable(),user_id:j.number().optional().nullable(),app_id:j.string(),vm_uuid:j.string().nullable(),instance_id:j.string().nullable(),app_url:j.string().optional().nullable(),base_image:j.string().optional().nullable(),vcpu:j.number(),memory:j.number(),disk_size:j.number(),manifest_version:j.number().optional().nullable(),version:j.string().optional().nullable(),runner:j.string().optional().nullable(),docker_compose_file:j.string().optional().nullable(),features:j.array(j.string()).optional().nullable(),created_at:j.string(),encrypted_env_pubkey:j.string().nullable()}),Ai=P,{action:xi,safeAction:Ii}=v(ct,async(e,t)=>{let{cvmId:n}=Ai.parse(t);return await e.post(`/cvms/${n}/start`)}),Ri=P,{action:ji,safeAction:Pi}=v(ct,async(e,t)=>{let{cvmId:n}=Ri.parse(t);return await e.post(`/cvms/${n}/stop`)}),Ti=P,{action:$i,safeAction:Li}=v(ct,async(e,t)=>{let{cvmId:n}=Ti.parse(t);return await e.post(`/cvms/${n}/shutdown`)}),qi=Se(de.extend({force:Oi.boolean().optional()})),{action:Fi,safeAction:zi}=v(ct,async(e,t)=>{let n=qi.parse(t),{cvmId:r}=P.parse(n),{force:s=!1}=n;return await e.post(`/cvms/${r}/restart`,{force:s})}),Ni=P,{action:Di,safeAction:Bi}=v(Ui.void(),async(e,t)=>{let{cvmId:n}=Ni.parse(t);await e.delete(`/cvms/${n}`)}),Hi=R.object({name:R.string(),mount_point:R.string(),total_size:R.number(),free_size:R.number()}),Vi=R.object({os_name:R.string(),os_version:R.string(),kernel_version:R.string(),cpu_model:R.string(),num_cpus:R.number(),total_memory:R.number(),available_memory:R.number(),used_memory:R.number(),free_memory:R.number(),total_swap:R.number(),used_swap:R.number(),free_swap:R.number(),uptime:R.number(),loadavg_one:R.number(),loadavg_five:R.number(),loadavg_fifteen:R.number(),disks:R.array(Hi)}),Ki=R.object({is_online:R.boolean(),is_public:R.boolean().default(!1),error:R.string().nullable(),sysinfo:Vi.nullable(),status:R.string().nullable(),in_progress:R.boolean().default(!1),boot_progress:R.string().nullable(),boot_error:R.string().nullable()}),Gi=P,{action:Mi,safeAction:Wi}=v(Ki,async(e,t)=>{let{cvmId:n}=Gi.parse(t);return await e.get(`/cvms/${n}/stats`)}),Ji=ve.object({app:ve.string(),instance:ve.string()}),Xi=ve.object({is_online:ve.boolean(),is_public:ve.boolean().default(!0),error:ve.string().nullable(),internal_ip:ve.string().nullable(),latest_handshake:ve.string().nullable(),public_urls:ve.array(Ji).nullable()}),Zi=P,{action:Qi,safeAction:Yi}=v(Xi,async(e,t)=>{let{cvmId:n}=Zi.parse(t);return await e.get(`/cvms/${n}/network`)}),tc=P,{action:nc,safeAction:rc}=v(ec.string(),async(e,t)=>{let{cvmId:n}=tc.parse(t);return await e.get(`/cvms/${n}/docker-compose.yml`)}),sc=N.object({id:N.string(),names:N.array(N.string()),image:N.string(),image_id:N.string(),command:N.string().nullable().optional(),created:N.number(),state:N.string(),status:N.string(),log_endpoint:N.string().nullable()}),oc=N.object({is_online:N.boolean(),is_public:N.boolean().default(!0),error:N.string().nullable(),docker_compose_file:N.string().nullable(),manifest_version:N.number().nullable(),version:N.string().nullable(),runner:N.string().nullable(),features:N.array(N.string()).nullable(),containers:N.array(sc).nullable()}),ac=P,{action:ic,safeAction:cc}=v(oc,async(e,t)=>{let{cvmId:n}=ac.parse(t);return await e.get(`/cvms/${n}/composition`)}),lc=y.object({common_name:y.string().nullable(),organization:y.string().nullable(),country:y.string().nullable(),state:y.string().nullable(),locality:y.string().nullable()}),uc=y.object({common_name:y.string().nullable(),organization:y.string().nullable(),country:y.string().nullable()}),jr=y.object({subject:lc,issuer:uc,serial_number:y.string(),not_before:y.string(),not_after:y.string(),version:y.string(),fingerprint:y.string(),signature_algorithm:y.string(),sans:y.array(y.string()).nullable(),is_ca:y.boolean(),position_in_chain:y.number().nullable(),quote:y.string().nullable(),app_id:y.string().nullable().optional(),cert_usage:y.string().nullable().optional()}),pc=y.object({imr:y.number(),event_type:y.number(),digest:y.string(),event:y.string(),event_payload:y.string()}),Pr=y.object({mrtd:y.string(),rootfs_hash:y.string().nullable().optional(),rtmr0:y.string(),rtmr1:y.string(),rtmr2:y.string(),rtmr3:y.string(),event_log:y.array(pc),app_compose:y.string()}),dc=y.object({name:y.string().nullable(),is_online:y.boolean(),is_public:y.boolean().default(!0),error:y.string().nullable(),app_certificates:y.array(jr).nullable(),tcb_info:Pr.nullable(),compose_file:y.string().nullable()}),mc=P,{action:fc,safeAction:gc}=v(dc,async(e,t)=>{let{cvmId:n}=mc.parse(t);return await e.get(`/cvms/${n}/attestation`)}),hc=Se(de.extend({vcpu:Qe.number().optional(),memory:Qe.number().optional(),disk_size:Qe.number().optional(),instance_type:Qe.string().optional(),allow_restart:Qe.boolean().optional()})),{action:bc,safeAction:yc}=v(Qe.void(),async(e,t)=>{let n=hc.parse(t),{cvmId:r}=P.parse(n),{...s}=n;await e.patch(`/cvms/${r}/resources`,s)}),vc=Se(de.extend({public_sysinfo:Dt.boolean(),public_logs:Dt.boolean(),public_tcbinfo:Dt.boolean().optional()})),{action:_c,safeAction:wc}=v(wr,async(e,t)=>{let n=vc.parse(t),{cvmId:r}=P.parse(n),{public_sysinfo:s,public_logs:o,public_tcbinfo:a}=n;return await e.patch(`/cvms/${r}/visibility`,{public_sysinfo:s,public_logs:o,public_tcbinfo:a})}),or=Z.object({name:Z.string(),os_image_hash:Z.string().nullable(),is_current:Z.boolean()}),Cc=Z.object({version:Z.union([Z.tuple([Z.number(),Z.number(),Z.number(),Z.number()]),Z.tuple([Z.number(),Z.number(),Z.number()])]),prod:or.nullable(),dev:or.nullable()}),kc=Z.array(Cc),Sc=P,{action:Ec,safeAction:Ac}=v(kc,async(e,t)=>{let{cvmId:n}=Sc.parse(t);return await e.get(`/cvms/${n}/available-os-images`)}),xc=Se(de.extend({os_image_name:Tr.string().min(1,"OS image name is required")})),{action:Ic,safeAction:Rc}=v(Tr.void(),async(e,t)=>{let n=xc.parse(t),{cvmId:r}=P.parse(n),{os_image_name:s}=n;await e.patch(`/cvms/${r}/os-image`,{os_image_name:s})}),jc=ye.object({id:ye.string().optional(),instance_id:ye.string().optional(),name:ye.string(),status:ye.string(),uptime:ye.string().optional(),exited_at:ye.string().optional(),boot_progress:ye.string().optional(),boot_error:ye.string().optional(),shutdown_progress:ye.string().optional()}),Pc=P,{action:Tc,safeAction:$c}=v(jc,async(e,t)=>{let{cvmId:n}=Pc.parse(t);return await e.get(`/cvms/${n}/state`)}),$r=ae.object({id:ae.string(),user_id:ae.string(),name:ae.string(),public_key:ae.string(),fingerprint:ae.string(),key_type:ae.string(),source:ae.string(),key_metadata:ae.record(ae.unknown()).nullable().optional(),last_synced_at:ae.string().nullable().optional(),created_at:ae.string(),updated_at:ae.string()}),Lc=ae.array($r);async function Lr(e){let t=await e.get("/user/ssh-keys");return Lc.parse(t)}async function Oc(e){try{return{success:!0,data:await Lr(e)}}catch(t){return t&&typeof t=="object"&&("status"in t||"issues"in t)?{success:!1,error:t}:{success:!1,error:{name:"Error",message:t instanceof Error?t.message:String(t)}}}}var qc=Le.object({github_username:Le.string().min(1)}),Fc=Le.object({github_username:Le.string(),keys_added:Le.number().int(),keys_skipped:Le.number().int(),errors:Le.array(Le.string()).default([])}),{action:zc,safeAction:Uc}=v(Fc,async(e,t)=>{let{github_username:n}=qc.parse(t);return await e.post("/user/ssh-keys/github-profile",{github_username:n})}),Nc=Bt.object({name:Bt.string().min(1),public_key:Bt.string().min(1)}),{action:Dc,safeAction:Bc}=v($r,async(e,t)=>{let{name:n,public_key:r}=Nc.parse(t);return await e.post("/user/ssh-keys",{name:n,public_key:r})}),Hc=Vt.object({keyId:Vt.string().min(1)}),{action:Vc,safeAction:Kc}=v(Vt.void(),async(e,t)=>{let{keyId:n}=Hc.parse(t);await e.delete(`/user/ssh-keys/${n}`)}),Gc=ze.object({synced_count:ze.number().int(),keys_added:ze.number().int(),keys_updated:ze.number().int(),keys_removed:ze.number().int(),errors:ze.array(ze.string()).default([])}),{action:Mc,safeAction:Wc}=br(Gc,async e=>await e.post("/user/ssh-keys/github-sync",{})),Jc=W.object({name:W.string(),slug:W.string(),version:W.string(),os_image_hash:W.string().nullable(),is_dev:W.boolean(),requires_gpu:W.boolean()}).passthrough(),Xc=W.object({page:W.number().int().min(1).optional(),page_size:W.number().int().min(1).optional(),is_dev:W.boolean().optional()}).strict(),Zc=W.object({items:W.array(Jc),total:W.number(),page:W.number(),page_size:W.number(),pages:W.number()}).passthrough(),{action:Qc,safeAction:Yc}=v(Zc,async(e,t)=>{let n=Xc.parse(t??{});return await e.get("/os-images",{params:n})}),el=B.object({device_id:B.string(),node_name:B.string().nullable().optional(),on_chain_allowed:B.boolean().nullable()}).passthrough(),tl=B.object({name:B.string(),version:B.string(),os_image_hash:B.string().nullable(),on_chain_allowed:B.boolean().nullable()}).passthrough(),nl=B.object({contract_address:B.string(),chain_id:B.number(),chain_name:B.string(),devices:B.array(el),os_images:B.array(tl)}).passthrough(),rl=B.object({chain_name:B.string(),chain_id:B.number(),contracts:B.array(nl)}).passthrough(),sl=B.object({chain:B.string()}).strict(),{action:ol,safeAction:al}=v(rl,async(e,t)=>{let{chain:n}=sl.parse(t);return await e.get(`/kms/on-chain/${n}`)});function Or(e={}){let t=xo(e),n={getCurrentUser:fr,safeGetCurrentUser:Lo,getAvailableNodes:Do,safeGetAvailableNodes:Bo,listAllInstanceTypeFamilies:Mo,safeListAllInstanceTypeFamilies:Wo,listFamilyInstanceTypes:Jo,safeListFamilyInstanceTypes:Xo,listWorkspaces:Yo,safeListWorkspaces:ea,getWorkspace:ta,safeGetWorkspace:na,getCvmInfo:Sr,safeGetCvmInfo:Ct,getCvmList:Er,safeGetCvmList:Jt,provisionCvm:Sa,safeProvisionCvm:Ea,commitCvmProvision:xa,safeCommitCvmProvision:Ia,getCvmComposeFile:La,safeGetCvmComposeFile:Xt,provisionCvmComposeFileUpdate:Fa,safeProvisionCvmComposeFileUpdate:za,commitCvmComposeFileUpdate:Da,safeCommitCvmComposeFileUpdate:Ba,updateCvmEnvs:Ma,safeUpdateCvmEnvs:Wa,updateDockerCompose:Ya,safeUpdateDockerCompose:ei,updatePreLaunchScript:oi,safeUpdatePreLaunchScript:ai,getCvmPreLaunchScript:li,safeGetCvmPreLaunchScript:ui,startCvm:xi,safeStartCvm:Ii,stopCvm:ji,safeStopCvm:Pi,shutdownCvm:$i,safeShutdownCvm:Li,restartCvm:Fi,safeRestartCvm:zi,deleteCvm:Di,safeDeleteCvm:Bi,getCvmStats:Mi,safeGetCvmStats:Wi,getCvmNetwork:Qi,safeGetCvmNetwork:Yi,getCvmDockerCompose:nc,safeGetCvmDockerCompose:rc,getCvmContainersStats:ic,safeGetCvmContainersStats:cc,getCvmAttestation:fc,safeGetCvmAttestation:gc,updateCvmResources:bc,safeUpdateCvmResources:yc,updateCvmVisibility:_c,safeUpdateCvmVisibility:wc,getAvailableOsImages:Ec,safeGetAvailableOsImages:Ac,updateOsImage:Ic,safeUpdateOsImage:Rc,getKmsInfo:di,safeGetKmsInfo:mi,getKmsList:hi,safeGetKmsList:bi,getAppEnvEncryptPubKey:_i,safeGetAppEnvEncryptPubKey:wi,nextAppIds:Si,safeNextAppIds:Ei,getCvmState:Tc,safeGetCvmState:$c,listSshKeys:Lr,safeListSshKeys:Oc,importGithubProfileSshKeys:zc,safeImportGithubProfileSshKeys:Uc,createSshKey:Dc,safeCreateSshKey:Bc,deleteSshKey:Vc,safeDeleteSshKey:Kc,syncGithubSshKeys:Mc,safeSyncGithubSshKeys:Wc,getOsImages:Qc,safeGetOsImages:Yc,getKmsOnChainDetail:ol,safeGetKmsOnChainDetail:al};return t.extend(n)}var ar=g.object({vm_uuid:g.string().nullable(),app_id:g.string(),name:g.string().default(""),status:g.string(),vcpu:g.number().int(),memory:g.number().int(),disk_size:g.number().int(),teepod_id:g.number().int(),teepod_name:g.string(),region_identifier:g.string().nullable().optional(),kms_type:g.string().nullable().optional(),instance_type:g.string().nullable().optional(),listed:g.boolean().nullable().optional(),base_image:g.string().nullable().optional(),kms_slug:g.string().nullable().optional(),kms_id:g.string().nullable().optional(),instance_id:g.string().nullable().optional(),machine_info:Kt.nullable().optional(),updated_at:g.string().nullable().optional()}),il=g.object({display_name:g.string().nullable().optional(),avatar_url:g.string().nullable().optional(),description:g.string().nullable().optional(),custom_domain:g.string().nullable().optional()}),cl=g.object({id:g.string(),name:g.string(),app_id:g.string(),app_provision_type:g.string().nullable().optional(),app_icon_url:g.string().nullable().optional(),created_at:g.string(),kms_type:g.string(),profile:il.nullable().optional(),current_cvm:ar.nullable().optional(),cvms:g.array(ar).default([]),cvm_count:g.number().int().default(0)}),ll=g.object({id:g.null().optional(),app_id:g.string(),name:g.null().optional(),app_provision_type:g.null().optional(),app_icon_url:g.null().optional(),created_at:g.null().optional(),kms_type:g.null().optional(),current_cvm:g.null().optional(),cvms:g.null().optional(),cvm_count:g.null().optional()}),ul=g.union([cl,ll]),_p=g.object({dstack_apps:g.array(ul),page:g.number().int(),page_size:g.number().int(),total:g.number().int(),total_pages:g.number().int()}),pl=x.object({id:x.string(),name:x.string(),app_id:x.string(),app_provision_type:x.string().nullable().optional(),app_icon_url:x.string().nullable().optional(),created_at:x.string(),kms_type:x.string(),profile:x.object({display_name:x.string().nullable().optional(),avatar_url:x.string().nullable().optional(),description:x.string().nullable().optional(),custom_domain:x.string().nullable().optional()}).nullable().optional(),current_cvm:_t.nullable().optional(),cvms:x.array(_t).default([]),cvm_count:x.number().int().default(0)}),dl=x.object({id:x.null().optional(),app_id:x.string(),name:x.null().optional(),app_provision_type:x.null().optional(),app_icon_url:x.null().optional(),created_at:x.null().optional(),kms_type:x.null().optional(),current_cvm:x.null().optional(),cvms:x.null().optional(),cvm_count:x.null().optional()}),ml=x.union([pl,dl]),Cp=x.object({dstack_apps:x.array(ml),page:x.number().int(),page_size:x.number().int(),total:x.number().int(),total_pages:x.number().int()}),qr=A.object({object_type:A.literal("cvm"),id:A.string().nullable().optional(),name:A.string().nullable().optional(),app_id:A.string().nullable().optional(),vm_uuid:A.string().nullable().optional()}),fl=A.object({revision_id:A.string(),app_id:A.string(),vm_uuid:A.string(),compose_hash:A.string(),created_at:A.string(),trace_id:A.string().nullable().optional(),operation_type:A.string(),triggered_by:Mt.nullable().optional(),cvm:qr.nullable().optional(),workspace:Wt.nullable().optional()}),Sp=A.object({revision_id:A.string(),app_id:A.string(),vm_uuid:A.string(),compose_hash:A.string(),compose_file:A.union([A.record(A.any()),A.string()]).nullable().optional(),encrypted_env:A.string(),user_config:A.string(),created_at:A.string(),trace_id:A.string().nullable().optional(),operation_type:A.string(),triggered_by:Mt.nullable().optional(),cvm:qr.nullable().optional(),workspace:Wt.nullable().optional()}),Ep=A.object({revisions:A.array(fl),total:A.number().int(),page:A.number().int(),page_size:A.number().int(),total_pages:A.number().int()});var gl=H.object({chain:H.unknown().optional(),rpcUrl:H.string().optional(),kmsContractAddress:H.string(),privateKey:H.string().optional(),walletClient:H.unknown().optional(),publicClient:H.unknown().optional(),allowAnyDevice:H.boolean().optional().default(!1),deviceId:H.string().optional().default("0000000000000000000000000000000000000000000000000000000000000000"),composeHash:H.string().optional().default("0000000000000000000000000000000000000000000000000000000000000000"),disableUpgrades:H.boolean().optional().default(!1),skipPrerequisiteChecks:H.boolean().optional().default(!1),minBalance:H.string().optional()}).passthrough(),Gp=gl.refine(e=>{let t=!!e.privateKey,n=!!e.walletClient;return t!==n},{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>{let t=!!e.publicClient,n=!!e.walletClient,r=!!e.chain;return t&&n?!0:r},{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),Mp=H.object({appId:H.string(),appAuthAddress:H.string(),deployer:H.string(),transactionHash:H.string(),blockNumber:H.bigint().optional(),gasUsed:H.bigint().optional()}).passthrough();var rd=q.object({chain:q.unknown().optional(),rpcUrl:q.string().optional(),appId:q.string(),composeHash:q.string(),privateKey:q.string().optional(),walletClient:q.unknown().optional(),publicClient:q.unknown().optional(),skipPrerequisiteChecks:q.boolean().optional().default(!1),minBalance:q.string().optional(),timeout:q.number().optional().default(12e4),retryOptions:q.unknown().optional(),signal:q.unknown().optional(),onTransactionStateChange:q.function().optional(),onTransactionSubmitted:q.function().optional(),onTransactionConfirmed:q.function().optional()}).passthrough().refine(e=>{let t=!!e.privateKey,n=!!e.walletClient;return t!==n},{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>{let t=!!e.publicClient,n=!!e.walletClient,r=!!e.chain;return t&&n?!0:r},{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),sd=q.object({composeHash:q.string(),appId:q.string(),transactionHash:q.string(),blockNumber:q.bigint().optional(),gasUsed:q.bigint().optional()}).passthrough();var md=F.object({chain:F.unknown().optional(),rpcUrl:F.string().optional(),appAddress:F.string(),deviceId:F.string(),privateKey:F.string().optional(),walletClient:F.unknown().optional(),publicClient:F.unknown().optional(),skipPrerequisiteChecks:F.boolean().optional().default(!1),minBalance:F.string().optional(),timeout:F.number().optional().default(12e4),retryOptions:F.unknown().optional(),signal:F.unknown().optional(),onTransactionStateChange:F.function().optional(),onTransactionSubmitted:F.function().optional(),onTransactionConfirmed:F.function().optional()}).passthrough().refine(e=>!!e.privateKey!=!!e.walletClient,{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>e.publicClient&&e.walletClient?!0:!!e.chain,{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),fd=F.object({appAddress:F.string(),deviceId:F.string(),transactionHash:F.string(),blockNumber:F.bigint().optional(),gasUsed:F.bigint().optional()}).passthrough();var kd=z.object({chain:z.unknown().optional(),rpcUrl:z.string().optional(),appAddress:z.string(),deviceId:z.string(),privateKey:z.string().optional(),walletClient:z.unknown().optional(),publicClient:z.unknown().optional(),skipPrerequisiteChecks:z.boolean().optional().default(!1),minBalance:z.string().optional(),timeout:z.number().optional().default(12e4),retryOptions:z.unknown().optional(),signal:z.unknown().optional(),onTransactionStateChange:z.function().optional(),onTransactionSubmitted:z.function().optional(),onTransactionConfirmed:z.function().optional()}).passthrough().refine(e=>!!e.privateKey!=!!e.walletClient,{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>e.publicClient&&e.walletClient?!0:!!e.chain,{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),Sd=z.object({appAddress:z.string(),deviceId:z.string(),transactionHash:z.string(),blockNumber:z.bigint().optional(),gasUsed:z.bigint().optional()}).passthrough();var $d=U.object({chain:U.unknown().optional(),rpcUrl:U.string().optional(),appAddress:U.string(),allow:U.boolean(),privateKey:U.string().optional(),walletClient:U.unknown().optional(),publicClient:U.unknown().optional(),skipPrerequisiteChecks:U.boolean().optional().default(!1),minBalance:U.string().optional(),timeout:U.number().optional().default(12e4),retryOptions:U.unknown().optional(),signal:U.unknown().optional(),onTransactionStateChange:U.function().optional(),onTransactionSubmitted:U.function().optional(),onTransactionConfirmed:U.function().optional()}).passthrough().refine(e=>!!e.privateKey!=!!e.walletClient,{message:"Either 'privateKey' or 'walletClient' must be provided, but not both",path:["privateKey","walletClient"]}).refine(e=>e.publicClient&&e.walletClient?!0:!!e.chain,{message:"Chain is required when publicClient or walletClient is not provided",path:["chain"]}),Ld=U.object({appAddress:U.string(),allow:U.boolean(),transactionHash:U.string(),blockNumber:U.bigint().optional(),gasUsed:U.bigint().optional()}).passthrough();var Ud=Je.object({appAddress:Je.string(),owner:Je.string(),allowAnyDevice:Je.boolean(),devices:Je.array(Je.string())});var hl=Cr;var bl=Xe.object({items:Xe.array(hl),total:Xe.number(),page:Xe.number(),page_size:Xe.number(),pages:Xe.number()}).passthrough(),{action:Vd,safeAction:Kd}=v(bl,async(e,t)=>{let{teamSlug:n,page:r,pageSize:s}=t,o=new URLSearchParams;r!==void 0&&o.append("page",r.toString()),s!==void 0&&o.append("page_size",s.toString());let a=o.toString()?`/workspaces/${n}/nodes?${o.toString()}`:`/workspaces/${n}/nodes`;return await e.get(a)}),Ye=ge.object({limit:ge.number(),remaining:ge.number()}).passthrough(),yl=ge.object({vm_slots:Ye,vcpu:Ye,memory_mb:Ye,disk_gb:Ye}).passthrough(),vl=ge.object({gpus:Ye,in_use:ge.number(),misconfigured:ge.number()}).passthrough(),_l=ge.object({team_slug:ge.string(),tier:ge.string(),quotas:yl,reserved_nodes:Ye,reserved_gpu:vl,as_of:ge.string()}).passthrough(),{action:Md,safeAction:Wd}=v(_l,async(e,t)=>await e.get(`/workspaces/${t.teamSlug}/quotas`)),Cl=Se(de.extend({node_id:wl.number().optional()})),{action:Xd,safeAction:Zd}=v(ct,async(e,t)=>{let n=Cl.parse(t),{cvmId:r}=P.parse(n),{node_id:s}=n;return await e.post(`/cvms/${r}/replicas`,{node_id:s})}),Yd=Ze.object({target:Ze.string().describe("Target status to wait for (e.g., 'running', 'stopped')"),interval:Ze.number().min(5).max(30).default(5).describe("Polling interval in seconds"),timeout:Ze.number().min(10).max(600).default(300).describe("Timeout per attempt in seconds"),maxRetries:Ze.number().min(0).default(Number.POSITIVE_INFINITY).describe("Maximum number of retry attempts (Infinity for unlimited)"),retryDelay:Ze.number().min(0).default(5e3).describe("Delay between retries in milliseconds")});var Fr=fe.object({cvm_id:fe.number().int(),identifier:fe.string(),status:fe.enum(["updated","unchanged","skipped","conflict","error"]),old_instance_id:fe.string().nullable().optional(),new_instance_id:fe.string().nullable().optional(),source:fe.enum(["teepod_state","teepod_info","gateway","none"]),verified_with_gateway:fe.boolean(),reason:fe.string().nullable().optional()}),kl=Se(de.extend({overwrite:fe.boolean().optional(),dry_run:fe.boolean().optional()})),{action:tm,safeAction:nm}=v(Fr,async(e,t)=>{let n=kl.parse(t),{cvmId:r}=P.parse(n),{overwrite:s,dry_run:o}=n;return await e.patch(`/cvms/${r}/instance-id`,{overwrite:s,dry_run:o})}),Sl=M.object({cvm_ids:M.array(M.string()).optional(),running_only:M.boolean().optional(),missing_only:M.boolean().optional(),overwrite:M.boolean().optional(),limit:M.number().int().min(1).max(500).optional(),dry_run:M.boolean().optional()}).strict(),El=M.object({total:M.number().int(),scanned:M.number().int(),updated:M.number().int(),unchanged:M.number().int(),skipped:M.number().int(),conflicts:M.number().int(),errors:M.number().int(),items:M.array(Fr)}),{action:sm,safeAction:om}=v(El,async(e,t)=>{let n=Sl.parse(t);return await e.patch("/cvms/instance-ids",n)}),Al=ee.object({vm_uuid:ee.string(),status:ee.string(),uptime:ee.string().nullable().optional(),in_progress:ee.boolean(),boot_progress:ee.string().nullable().optional(),boot_error:ee.string().nullable().optional(),operation_type:ee.string().nullable().optional(),operation_started_at:ee.string().nullable().optional(),correlation_id:ee.string().nullable().optional()}),xl=ee.record(ee.string(),Al),Il=ee.object({vmUuids:ee.array(ee.string())}),{action:im,safeAction:cm}=v(xl,async(e,t)=>{let{vmUuids:n}=Il.parse(t);return await e.post("/status/batch",{vm_uuids:n})}),Rl=it.object({hostname:it.string().nullable().optional(),ssh_authorized_keys:it.array(it.string()).default([]),default_gateway_domain:it.string().nullable().optional()}),jl=P,{action:um,safeAction:pm}=v(Rl,async(e,t)=>{let{cvmId:n}=jl.parse(t);return await e.get(`/cvms/${n}/user_config`)}),mm=le.object({page:le.number().int().min(1).optional(),page_size:le.number().int().min(1).max(100).optional(),search:le.string().optional(),status:le.array(le.string()).optional(),listed:le.boolean().optional(),base_image:le.string().optional(),instance_type:le.string().optional(),kms_slug:le.string().optional(),kms_type:le.string().optional(),node:le.string().optional(),region:le.string().optional()}).strict();var gm=ir.object({appId:ir.string().min(1)}).strict();var bm=cr.object({appId:cr.string().min(1)}).strict();var Pl=ne.object({device_id:ne.string(),node_name:ne.string().nullable(),cvm_ids:ne.array(ne.number()),allowed_onchain:ne.boolean(),status:ne.string()}),vm=ne.object({is_onchain_kms:ne.boolean(),allow_any_device:ne.boolean().nullable().optional(),chain_id:ne.number().nullable().optional(),app_contract_address:ne.string().nullable().optional(),devices:ne.array(Pl).optional().default([])}),_m=ne.object({appId:ne.string().min(1)}).strict();var Cm=bt.object({appId:bt.string().min(1),page:bt.number().int().min(1).optional(),page_size:bt.number().int().min(1).max(1e3).optional()}).strict();var Sm=yt.object({appId:yt.string().min(1),revisionId:yt.string().min(1),rawComposeFile:yt.boolean().optional()}).strict();var Am=Y.object({statuses:Y.array(Y.string()),image_versions:Y.array(Y.string()),instance_types:Y.array(Y.string()),kms_slugs:Y.array(Y.string()),kms_types:Y.array(Y.string()),regions:Y.array(Y.string()),nodes:Y.array(Y.string())});var Tl=I.object({contract_address:I.string(),chain_id:I.string().nullable(),version:I.string(),url:I.string(),gateway_app_id:I.string().nullable(),gateway_app_url:I.string(),kms_type:I.string()}),lr=I.object({app_id:I.string().optional(),instance_id:I.string().optional(),app_name:I.string().optional(),device_id:I.string().optional()}).passthrough().nullable(),$l=I.object({vm_uuid:I.string().nullable().optional(),name:I.string().optional(),instance_id:I.string().nullable().optional(),status:I.string().optional(),image_version:I.string().nullable().optional(),quote:I.string().nullable().optional(),ppid:I.string().optional(),device_id:I.string().optional(),tcb_info:Pr.nullable().optional(),app_certificates:I.array(jr).nullable().optional(),compose_file:I.string().nullable().optional(),error:I.string().nullable().optional()}),Ll=I.object({app_id:I.string(),contract_address:I.string(),kms_info:Tl,instances:I.array($l),kms_guest_agent_info:lr,gateway_guest_agent_info:lr,qemu_version:I.string().nullable()}),Ol=I.object({appId:I.string().min(1)}).strict(),{action:Im,safeAction:Rm}=v(Ll,async(e,t)=>{let{appId:n}=Ol.parse(t);return await e.get(`/apps/${n}/attestations`)});var Ul;function zr(){return Ul}import Vl from"path";import Zt from"fs-extra";import Kl from"@iarna/toml";import{z as Ee}from"zod";import re from"chalk";import Dl from"ora";var Nl=!1;function he(){return Nl}function Bl(e,t){let n=e.split(/\s+/),r=[],s="";for(let o of n){let a=s.length===0?o:`${s} ${o}`;a.length<=t?s=a:(s.length>0&&r.push(s),s=o)}return s.length>0&&r.push(s),r}function Hl(e,t){if(e.length<=t)return[e];let n=[],r=0;for(;r<e.length;)n.push(e.slice(r,r+t)),r+=t;return n}function Ur(e,t){let n=[];for(let r of e.split(`
21
+ `)){if(r.length<=t){n.push(r);continue}if(r.indexOf(" ")===-1){n.push(...Hl(r,t));continue}let s=Bl(r,t);n.push(...s)}if(n.length===0){let r=e.trim();n.push(r)}return n}var Oe={error:(e,...t)=>{he()||(process.stderr.write(`${re.red("\u2717")} ${re.red(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
22
+ `))},warn:(e,...t)=>{he()||(process.stderr.write(`${re.yellow("\u26A0")} ${re.yellow(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
23
+ `))},info:(e,...t)=>{he()||(process.stderr.write(`${re.blue("\u2139")} ${re.blue(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
24
+ `))},success:(e,...t)=>{he()||(process.stderr.write(`${re.green("\u2713")} ${re.green(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
25
+ `))},debug:(e,...t)=>{he()||process.env.DEBUG&&(process.stderr.write(`${re.gray("\u{1F50D}")} ${re.gray(e)}`),t.length>0&&process.stderr.write(` ${t.map(String).join(" ")}`),process.stderr.write(`
26
+ `))},table:(e,t)=>{if(!he()){if(e.length===0){console.log(re.yellow("No data to display"));return}if(t){let n;typeof t[0]=="string"?n=t.map(a=>({key:a,header:a})):n=t;let r={};for(let a of n){let c=a.header||String(a.key);r[String(a.key)]=c.length}for(let a of e)for(let c of n){let l=String(typeof c.key=="string"&&!(c.key in a)?"":a[String(c.key)]??"");r[String(c.key)]=Math.max(r[String(c.key)],l.length)}let s=[];for(let a of n){let c=a.header||String(a.key);s.push(re.bold(c.padEnd(r[String(a.key)])))}console.log(s.join(" "));let o=[];for(let a of n)o.push("-".repeat(r[String(a.key)]));console.log(o.join(" "));for(let a of e){let c=[];for(let l of n){let m=String(typeof l.key=="string"&&!(l.key in a)?"":a[String(l.key)]??"");c.push(m.padEnd(r[String(l.key)]))}console.log(c.join(" "))}}else{let n=e[0],r=Object.keys(n),s={};for(let c of r)s[c]=c.length;for(let c of e)for(let l of r){let m=String(c[l]??"");s[l]=Math.max(s[l],m.length)}let o=[];for(let c of r)o.push(re.bold(c.padEnd(s[c])));console.log(o.join(" "));let a=[];for(let c of r)a.push("-".repeat(s[c]));console.log(a.join(" "));for(let c of e){let l=[];for(let m of r){let d=String(c[m]??"");l.push(d.padEnd(s[m]))}console.log(l.join(" "))}}}},keyValueTable:(e,t)=>{if(he())return;let{borderStyle:n="single",keyColor:r=re.blue,valueColor:s=re.white,maxWidth:o=process.stdout.columns||80}=t||{},c={single:{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",cross:"\u253C",leftT:"\u251C",rightT:"\u2524"},double:{topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",vertical:"\u2551",cross:"\u256C",leftT:"\u2560",rightT:"\u2563"},rounded:{topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",cross:"\u253C",leftT:"\u251C",rightT:"\u2524"},bold:{topLeft:"\u250F",topRight:"\u2513",bottomLeft:"\u2517",bottomRight:"\u251B",horizontal:"\u2501",vertical:"\u2503",cross:"\u254B",leftT:"\u2523",rightT:"\u252B"},none:{topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",horizontal:"",vertical:"",cross:"",leftT:"",rightT:""}}[n],l=0,m=0;for(let[S,T]of Object.entries(e)){l=Math.max(l,S.length);let O=String(T??"");m=Math.max(m,O.length)}let d=4,f=1,b=o-d-f;if(l+m>b){let S=l/(l+m);l=Math.floor(b*S),m=b-l}let C=l+m+d+f;n!=="none"&&console.log(c.topLeft+c.horizontal.repeat(C-2)+c.topRight);for(let[S,T]of Object.entries(e)){let O=S,Q=String(T??""),ue=Ur(O,l),xe=Ur(Q,m),be=Math.max(ue.length,xe.length);for(;ue.length<be;)ue.push("");for(;xe.length<be;)xe.push("");for(let Ie=0;Ie<be;Ie++){let Ne=ue[Ie].padEnd(l),lt=xe[Ie].padEnd(m);console.log(n!=="none"?`${c.vertical} ${r(Ne)} ${c.vertical} ${s(lt)} ${c.vertical}`:`${r(Ne)} : ${s(lt)}`)}}n!=="none"&&console.log(c.bottomLeft+c.horizontal.repeat(C-2)+c.bottomRight)},break:()=>{he()||process.stderr.write(`
27
+ `)},startSpinner:e=>{if(he())return{stop:()=>{}};let t=Dl(e).start();return{stop:(n=!0,r)=>{r&&(t.text=r),n?t.succeed():t.fail()}}},logDetailedError(e,t){if(he())return;let n=t?`[${t}] `:"",r=o=>o!==null&&typeof o=="object"&&"isRequestError"in o&&o.isRequestError===!0&&"status"in o&&"message"in o&&"data"in o,s=o=>o!==null&&typeof o=="object"&&"issues"in o&&Array.isArray(o.issues);if(r(e)){process.stderr.write(`${n}HTTP ${e.status}: ${e.message}
33
28
  `),e.data!==void 0&&e.data!==null&&process.stderr.write(`${JSON.stringify(e.data,null,2)}
34
- `);return}if(o(e)){process.stderr.write(`${r}Validation error: ${JSON.stringify(e.issues)}
35
- `);return}e instanceof Error?process.stderr.write(`${r}${e.message}
36
- `):process.stderr.write(`${r}${String(e)}
37
- `)}};var _m=xe.extend({profile:Be.string().optional(),api_version:Be.enum(Hr).optional(),gateway_domain:Be.string().optional(),gateway_port:Be.number().int().positive().optional(),compose_file:Be.string().optional(),env_file:Be.string().optional(),public_logs:Be.boolean().optional(),public_sysinfo:Be.boolean().optional(),listed:Be.boolean().optional()}),Nn="phala.toml";function Ri(){return vm.join(process.cwd(),Nn)}function Cm(){return On.existsSync(Ri())}function km(){let e=Ri();if(!On.existsSync(e))throw new Error(`Project configuration file not found: ${Nn}
38
- Run 'phala init' to create one.`);try{let t=On.readFileSync(e,"utf8"),r=wm.parse(t),n=_m.parse(r);if(n.id||n.uuid||n.app_id||n.instance_id||n.name){let{cvmId:o}=j.parse(n);return{...n,cvm_id:o}}return n}catch(t){if(t instanceof Be.ZodError){let r=t.issues.map(n=>` - ${n.path.join(".")}: ${n.message}`).join(`
29
+ `);return}if(s(e)){process.stderr.write(`${n}Validation error: ${JSON.stringify(e.issues)}
30
+ `);return}e instanceof Error?process.stderr.write(`${n}${e.message}
31
+ `):process.stderr.write(`${n}${String(e)}
32
+ `)}};var Gl=de.extend({profile:Ee.string().optional(),api_version:Ee.enum(wt).optional(),gateway_domain:Ee.string().optional(),gateway_port:Ee.number().int().positive().optional(),compose_file:Ee.string().optional(),env_file:Ee.string().optional(),public_logs:Ee.boolean().optional(),public_sysinfo:Ee.boolean().optional(),listed:Ee.boolean().optional()}),Qt="phala.toml";function Nr(){return Vl.join(process.cwd(),Qt)}function Ml(){return Zt.existsSync(Nr())}function Wl(){let e=Nr();if(!Zt.existsSync(e))throw new Error(`Project configuration file not found: ${Qt}
33
+ Run 'phala init' to create one.`);try{let t=Zt.readFileSync(e,"utf8"),n=Kl.parse(t),r=Gl.parse(n);if(r.id||r.uuid||r.app_id||r.instance_id||r.name){let{cvmId:s}=P.parse(r);return{...r,cvm_id:s}}return r}catch(t){if(t instanceof Ee.ZodError){let n=t.issues.map(r=>` - ${r.path.join(".")}: ${r.message}`).join(`
39
34
  `);throw new Error(`Invalid project configuration:
40
- ${r}`)}throw new Error(`Failed to parse ${Nn}: ${t instanceof Error?t.message:String(t)}`)}}function Bi(){return Cm()?km():{}}import ji from"fs";import Sm from"os";import Fi from"path";var Ui="https://cloud-api.phala.com/api/v1";function Em(){let e=process.env.PHALA_CLOUD_DIR;return typeof e=="string"&&e.trim().length>0?e:Fi.join(Sm.homedir(),".phala-cloud")}function Tm(){return Fi.join(Em(),"credentials.json")}function Nr(e){return typeof e=="string"&&e.trim().length>0}function Im(e){let t=e.trim();return t.length===0?"default":t}function Am(){try{let e=Tm();if(!ji.existsSync(e))return null;let t=ji.readFileSync(e,"utf8"),r=JSON.parse(t);if(!r||typeof r!="object")return null;let n=r;return n.schema_version!==1||!Nr(n.current_profile)||!n.profiles||typeof n.profiles!="object"?null:n}catch(e){return Ze.error("Failed to read credentials file:",e),null}}function Hi(e){let t=Am(),r=Im(e.profile||e.projectProfile||t?.current_profile||"default"),n=e.env.PHALA_CLOUD_API_PREFIX,o=t?.profiles?.[r]?.api_prefix,s=(n&&n.trim().length>0?n:o&&o.trim().length>0?o:Ui)??Ui,i=n?"env":o?"file":"default";if(Nr(e.apiToken))return{apiKey:e.apiToken,baseURL:s,profileName:r,tokenSource:"flag",apiPrefixSource:i};if(Nr(e.env.PHALA_CLOUD_API_KEY))return{apiKey:e.env.PHALA_CLOUD_API_KEY,baseURL:s,profileName:r,tokenSource:"env",apiPrefixSource:i};let a=t?.profiles?.[r]?.token;return Nr(a)?{apiKey:a,baseURL:s,profileName:r,tokenSource:"file",apiPrefixSource:i}:{apiKey:null,baseURL:s,profileName:r,tokenSource:"none",apiPrefixSource:i}}var Pm="2026-01-21";function $m(){return{env:process.env,projectConfig:Bi()}}function Lm(e,t){let r=e??$m();return Hi({env:r.env,apiToken:t?.apiToken,profile:t?.profile,projectProfile:r.projectConfig.profile})}async function oe(e,t){let r=Lm(e,t),n=Li()??Pm;return Ai({apiKey:r.apiKey??void 0,baseURL:r.baseURL,version:n})}import{z as c}from"zod";var zm=c.object({password:c.string(),registry:c.string().nullable(),username:c.string()}),Mv=c.object({docker_compose_file:c.string(),docker_config:zm.optional().nullable(),features:c.array(c.string()),kms_enabled:c.boolean(),manifest_version:c.number(),name:c.string(),public_logs:c.boolean(),public_sysinfo:c.boolean(),runner:c.string().optional(),salt:c.string().nullable().optional(),tproxy_enabled:c.boolean(),version:c.string().optional()}).passthrough(),Oi=c.object({id:c.number(),name:c.string(),status:c.string(),teepod_id:c.number().nullable(),teepod:c.object({id:c.number(),name:c.string()}).nullable(),user_id:c.number().nullable(),app_id:c.string(),vm_uuid:c.string().nullable(),instance_id:c.string().nullable(),app_url:c.string().nullable(),base_image:c.string().nullable(),vcpu:c.number(),memory:c.number(),disk_size:c.number(),manifest_version:c.number().nullable(),version:c.string().nullable(),runner:c.string().nullable(),docker_compose_file:c.string().nullable(),features:c.array(c.string()).nullable(),created_at:c.string(),encrypted_env_pubkey:c.string().nullable()}),Kv=c.object({key:c.string(),value:c.string()}),Ni=c.object({is_online:c.boolean(),is_public:c.boolean(),error:c.string().nullable(),internal_ip:c.string(),latest_handshake:c.string(),public_urls:c.array(c.object({app:c.string(),instance:c.string()}))}),Gi=c.object({id:c.number(),name:c.string(),status:c.string(),teepod_id:c.number(),teepod:c.object({id:c.number(),name:c.string()}),user_id:c.number().nullable(),app_id:c.string(),vm_uuid:c.string().nullable(),instance_id:c.string().nullable(),app_url:c.string().nullable(),base_image:c.string().nullable(),vcpu:c.number(),memory:c.number(),disk_size:c.number(),manifest_version:c.number().nullable(),version:c.string().nullable(),runner:c.string().nullable(),docker_compose_file:c.string().nullable(),features:c.array(c.string()).nullable(),created_at:c.string(),encrypted_env_pubkey:c.string().nullable()}),qi=c.object({is_online:c.boolean(),is_public:c.boolean(),error:c.string().nullable(),app_certificates:c.array(c.object({subject:c.object({common_name:c.string().nullable(),organization:c.string().nullable(),country:c.string().nullable(),state:c.string().nullable().optional(),locality:c.string().nullable().optional()}),issuer:c.object({common_name:c.string().nullable(),organization:c.string().nullable(),country:c.string().nullable()}),serial_number:c.string(),not_before:c.string(),not_after:c.string(),version:c.string(),fingerprint:c.string(),signature_algorithm:c.string(),sans:c.string().nullable(),is_ca:c.boolean(),position_in_chain:c.number(),quote:c.string().nullable()})).nullable(),tcb_info:c.object({mrtd:c.string(),rootfs_hash:c.string(),rtmr0:c.string(),rtmr1:c.string(),rtmr2:c.string(),rtmr3:c.string(),event_log:c.array(c.object({imr:c.number(),event_type:c.number(),digest:c.string(),event:c.string(),event_payload:c.string()}))}).nullable(),compose_file:c.string().nullable()}),Rm=c.object({name:c.string(),description:c.string().optional(),version:c.array(c.number()).optional(),is_dev:c.boolean().optional(),os_image_hash:c.string().nullable().optional(),rootfs_hash:c.string().optional(),shared_ro:c.boolean().optional(),cmdline:c.string().optional(),kernel:c.string().optional(),initrd:c.string().optional(),hda:c.string().nullable().optional(),rootfs:c.string().optional(),bios:c.string().optional()}),Wv=c.object({teepod_id:c.number().nullable(),id:c.number().optional(),name:c.string(),listed:c.boolean().optional(),resource_score:c.number().optional(),remaining_vcpu:c.number().optional(),remaining_memory:c.number().optional(),remaining_cvm_slots:c.number().optional(),images:c.array(Rm).optional(),region_identifier:c.string().optional(),dedicated_for_team_id:c.number().nullable().optional(),support_onchain_kms:c.boolean().optional(),fmspc:c.string().nullable().optional(),device_id:c.string().nullable().optional()});import Bm from"inquirer";async function tw(e){let t=await oe(),r=e.replace(/^app_/,""),n=await Or(t,{app_id:r});if(!n.success)throw new Error(n.error.message);return n.data}async function rw(e){let t=await oe(),r=await Hn(t,{id:e});if(!r.success)throw new Error(r.error.message);return r.data}async function nw(e){let t=await oe(),r=e.replace(/^app_/,""),n=await t.get(`cvms/app_${r}/network`);return Ni.parse(n)}async function ow(){let e=Ze.startSpinner("Fetching available CVMs"),t=await oe(),r=await Fn(t);if(e.stop(!0),!r.success){Ze.error(`Failed to fetch CVMs: ${r.error.message}`);return}let{items:n}=r.data;if(n.length===0){Ze.info("No CVMs found for your account");return}let o=n.map(i=>({name:`${i.name} (${i.app_id??i.id}) - ${i.status}`,value:i.app_id??i.id})),{selectedCvm:s}=await Bm.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:o}]);return s}async function sw(e){let t=await oe(),r=e.replace(/^app_/,""),n=await t.get(`cvms/app_${r}/attestation`);try{return qi.parse(n)}catch(o){return Ze.debug(`Validation error: ${o instanceof Error?o.message:String(o)}`),{is_online:!!n?.is_online,is_public:!!n?.is_public,error:typeof n?.error=="string"?n.error:null,app_certificates:Array.isArray(n?.app_certificates)?n.app_certificates:null,tcb_info:n?.tcb_info||null,compose_file:typeof n?.compose_file=="string"?n.compose_file:null}}}async function iw(e,t){let r=await oe(),n=e.replace(/^app_/,""),o=await r.post(`cvms/app_${n}/replicas`,t);return Gi.parse(o)}async function aw(e,t,r,n,o){let s=await oe(),i=e.replace(/^app_/,""),a={};if(t!==void 0&&(a.vcpu=t),r!==void 0&&(a.memory=r),n!==void 0&&(a.disk_size=n),o!==void 0&&(a.allow_restart=o),Object.keys(a).length===0)throw new Error("At least one resource parameter must be provided");return await s.patch(`cvms/app_${i}/resources`,a),!0}async function cw(e){return await(await oe()).post("cvms/pubkey/from_cvm_configuration",e)}async function lw(e){let r=await(await oe()).post("cvms/from_cvm_configuration",e);return Oi.parse(r)}async function uw(e,t){let r=await oe(),n=e.replace(/^app_/,"");return await r.put(`cvms/app_${n}/compose`,t)}async function pw(e=!1){let t=await oe(),r="teepods/available";return e&&(r+="?v03x_only=1"),await t.get(r)}function Ye(e,t){let r=[];t.since&&r.push(`since=${encodeURIComponent(t.since)}`),t.until&&r.push(`until=${encodeURIComponent(t.until)}`),t.follow&&r.push("follow"),t.text&&r.push("text"),t.bare&&r.push("bare"),t.tail!==void 0&&(r.push(`tail=${t.tail}`),r.push(`lines=${t.tail}`)),t.timestamps&&r.push("timestamps"),(t.ansi??!0)&&r.push("ansi");let n=e.includes("?")?"&":"?";return e+n+r.join("&")}async function Di(e,t){let r=e.body?.getReader();if(!r)throw new Error("No response body available for streaming");let n=new TextDecoder;for(;;){let{done:o,value:s}=await r.read();if(o)break;t(n.decode(s,{stream:!0}))}}function jm(e){return!e||/\s/.test(e)||e.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(e)}function Um(e){if(!jm(e))return e;try{return Buffer.from(e,"base64").toString("utf-8")}catch{return e}}function Gr(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return typeof r.message!="string"?null:{channel:r.channel==="stderr"?"stderr":"stdout",message:Um(r.message)}}catch{return null}}function Fm(e){let t=e.split(/\r?\n/),r=[];for(let n of t){if(!n.trim())continue;let o=Gr(n);if(o){r.push(o);continue}r.push({channel:"stdout",message:`${n}
41
- `})}return r}function Hm(e){let t=e.split(/\r?\n/),r="";for(let n of t){let o=Gr(n);if(o){r+=o.message;continue}n.trim()&&(r+=`${n}
42
- `)}return r}async function Om(e,t){let r=e.body?.getReader();if(!r)throw new Error("No response body available for streaming");let n=new TextDecoder,o="",s="unknown",i=a=>{let l=Gr(a);if(l){t(l.message);return}a.trim()&&t(`${a}
43
- `)};for(;;){let{done:a,value:l}=await r.read();if(a)break;let u=n.decode(l,{stream:!0});if(s==="raw"){t(u);continue}if(o+=u,s==="unknown")if(o.trimStart().startsWith("{"))s="structured";else{s="raw",t(o),o="";continue}let p=o.indexOf(`
44
- `);for(;p>=0;){let f=o.slice(0,p);o=o.slice(p+1),i(f),p=o.indexOf(`
45
- `)}}s==="structured"&&o.trim()?i(o):s==="raw"&&o&&t(o)}async function Nm(e,t){let r=e.body?.getReader();if(!r)throw new Error("No response body available for streaming");let n=new TextDecoder,o="",s="unknown",i=a=>{let l=Gr(a);if(l){t(l);return}a.trim()&&t({channel:"stdout",message:`${a}
46
- `})};for(;;){let{done:a,value:l}=await r.read();if(a)break;let u=n.decode(l,{stream:!0});if(s==="raw"){t({channel:"stdout",message:u});continue}if(o+=u,s==="unknown")if(o.trimStart().startsWith("{"))s="structured";else{s="raw",t({channel:"stdout",message:o}),o="";continue}let p=o.indexOf(`
47
- `);for(;p>=0;){let f=o.slice(0,p);o=o.slice(p+1),i(f),p=o.indexOf(`
48
- `)}}s==="structured"&&o.trim()?i(o):s==="raw"&&o&&t({channel:"stdout",message:o})}async function Gn(e,t){let n=await(await oe()).get(`cvms/${e}`,{headers:{"X-Phala-Version":"2025-10-28"}});if(!n.syslog_endpoint)throw new Error(`No syslog endpoint available for CVM '${e}'`);return`${n.syslog_endpoint}&ch=${t}`}async function Vi(e){return Gn(e,"serial")}async function qr(e,t,r=!0){let o=await(await oe()).get(`cvms/${e}/composition`);if(!o.containers?.length)throw new Error(`No containers found for CVM '${e}'`);let s=o.containers;if(t&&(s=s.filter(a=>a.names.some(u=>u===t||u===`/${t}`)?!0:r?a.id.startsWith(t):!1),!s.length))throw new Error(`Container '${t}' not found in CVM '${e}'`);let i=s.find(a=>a.log_endpoint);if(!i?.log_endpoint)throw new Error(`No log endpoints available for CVM '${e}'`);return i.log_endpoint}async function fw(e,t={}){let r=await Vi(e),n=Ye(r,t),o=await fetch(n);if(!o.ok)throw new Error(`Failed to fetch serial logs: ${o.status} ${o.statusText}`);return o.text()}async function mw(e,t={}){let r=await qr(e,t.container,t.matchContainerIdPrefix??!0),n=t.text??!0,o=t.bare??!0,s=Ye(r,{...t,text:n,bare:o}),i=await fetch(s);if(!i.ok)throw new Error(`Failed to fetch container logs: ${i.status} ${i.statusText}`);let a=await i.text();return a.trimStart().startsWith("{")?Hm(a):a}async function dw(e,t={}){let r=await qr(e,t.container,t.matchContainerIdPrefix??!0),n=Ye(r,{...t,text:!1,bare:!1}),o=await fetch(n);if(!o.ok)throw new Error(`Failed to fetch container logs: ${o.status} ${o.statusText}`);let s=await o.text();return s.trimStart().startsWith("{")?Fm(s):[{channel:"stdout",message:s}]}async function hw(e,t,r={},n){let o=await qr(e,r.container,r.matchContainerIdPrefix??!0),s=Ye(o,{...r,follow:!0,text:!1,bare:!1}),i=await fetch(s,{signal:n});if(!i.ok)throw new Error(`Failed to stream container logs: ${i.status} ${i.statusText}`);await Nm(i,t)}async function gw(e,t,r={},n){let o=await Vi(e),s=Ye(o,{...r,follow:!0}),i=await fetch(s,{signal:n});if(!i.ok)throw new Error(`Failed to stream serial logs: ${i.status} ${i.statusText}`);await Di(i,t)}async function bw(e,t,r={},n){let o=await qr(e,r.container,r.matchContainerIdPrefix??!0),s=r.text??!0,i=r.bare??!0,a=Ye(o,{...r,follow:!0,text:s,bare:i}),l=await fetch(a,{signal:n});if(!l.ok)throw new Error(`Failed to stream container logs: ${l.status} ${l.statusText}`);await Om(l,t)}async function xw(e,t,r={}){let n=await Gn(e,t),o=Ye(n,r),s=await fetch(o);if(!s.ok)throw new Error(`Failed to fetch CVM ${t} logs: ${s.status} ${s.statusText}`);return s.text()}async function yw(e,t,r,n={},o){let s=await Gn(e,t),i=Ye(s,{...n,follow:!0}),a=await fetch(i,{signal:o});if(!a.ok)throw new Error(`Failed to stream CVM ${t} logs: ${a.status} ${a.statusText}`);await Di(a,r)}async function vw(e){let t=await oe(),r=e.replace(/^app_/,""),n=await Or(t,{app_id:r});if(!n.success)throw new Error(n.error.message);return n.data.status}export{Mv as composeFileSchema,lw as createCvm,qi as cvmAttestationResponseSchema,zm as dockerConfigSchema,Kv as encryptedEnvItemSchema,mw as fetchContainerLogs,dw as fetchContainerLogsEntries,xw as fetchCvmChannelLogs,fw as fetchSerialLogs,sw as getCvmAttestation,tw as getCvmByAppId,rw as getCvmComposeConfig,Gn as getCvmLogEndpoint,nw as getCvmNetwork,Ni as getCvmNetworkResponseSchema,vw as getCvmStatus,cw as getPubkeyFromCvm,pw as getTeepods,Rm as imageSchema,Oi as postCvmResponseSchema,iw as replicateCvm,Gi as replicateCvmResponseSchema,aw as resizeCvm,ow as selectCvm,bw as streamContainerLogs,hw as streamContainerLogsEntries,yw as streamCvmChannelLogs,gw as streamSerialLogs,Wv as teepodSchema,uw as upgradeCvm};
35
+ ${n}`)}throw new Error(`Failed to parse ${Qt}: ${t instanceof Error?t.message:String(t)}`)}}function Dr(){return Ml()?Wl():{}}import Br from"fs";import Jl from"os";import Vr from"path";var Hr="https://cloud-api.phala.com/api/v1";function Xl(){let e=process.env.PHALA_CLOUD_DIR;return typeof e=="string"&&e.trim().length>0?e:Vr.join(Jl.homedir(),".phala-cloud")}function Zl(){return Vr.join(Xl(),"credentials.json")}function kt(e){return typeof e=="string"&&e.trim().length>0}function Ql(e){let t=e.trim();return t.length===0?"default":t}function Yl(){try{let e=Zl();if(!Br.existsSync(e))return null;let t=Br.readFileSync(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return null;let r=n;return r.schema_version!==1||!kt(r.current_profile)||!r.profiles||typeof r.profiles!="object"?null:r}catch(e){return Oe.error("Failed to read credentials file:",e),null}}function Kr(e){let t=Yl(),n=Ql(e.profile||e.projectProfile||t?.current_profile||"default"),r=e.env.PHALA_CLOUD_API_PREFIX,s=t?.profiles?.[n]?.api_prefix,o=(r&&r.trim().length>0?r:s&&s.trim().length>0?s:Hr)??Hr,a=r?"env":s?"file":"default";if(kt(e.apiToken))return{apiKey:e.apiToken,baseURL:o,profileName:n,tokenSource:"flag",apiPrefixSource:a};if(kt(e.env.PHALA_CLOUD_API_KEY))return{apiKey:e.env.PHALA_CLOUD_API_KEY,baseURL:o,profileName:n,tokenSource:"env",apiPrefixSource:a};let c=t?.profiles?.[n]?.token;return kt(c)?{apiKey:c,baseURL:o,profileName:n,tokenSource:"file",apiPrefixSource:a}:{apiKey:null,baseURL:o,profileName:n,tokenSource:"none",apiPrefixSource:a}}var eu="2026-01-21";function tu(){return{env:process.env,projectConfig:Dr()}}function nu(e,t){let n=e??tu();return Kr({env:n.env,apiToken:t?.apiToken,profile:t?.profile,projectProfile:n.projectConfig.profile})}async function se(e,t){let n=nu(e,t),r=zr()??eu;return Or({apiKey:n.apiKey??void 0,baseURL:n.baseURL,version:r})}import{z as i}from"zod";var ru=i.object({password:i.string(),registry:i.string().nullable(),username:i.string()}),df=i.object({docker_compose_file:i.string(),docker_config:ru.optional().nullable(),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()}).passthrough(),Gr=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().nullable(),app_id:i.string(),vm_uuid:i.string().nullable(),instance_id:i.string().nullable(),app_url:i.string().nullable(),base_image:i.string().nullable(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),manifest_version:i.number().nullable(),version:i.string().nullable(),runner:i.string().nullable(),docker_compose_file:i.string().nullable(),features:i.array(i.string()).nullable(),created_at:i.string(),encrypted_env_pubkey:i.string().nullable()}),mf=i.object({key:i.string(),value:i.string()}),Mr=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()}))}),Wr=i.object({id:i.number(),name:i.string(),status:i.string(),teepod_id:i.number(),teepod:i.object({id:i.number(),name:i.string()}),user_id:i.number().nullable(),app_id:i.string(),vm_uuid:i.string().nullable(),instance_id:i.string().nullable(),app_url:i.string().nullable(),base_image:i.string().nullable(),vcpu:i.number(),memory:i.number(),disk_size:i.number(),manifest_version:i.number().nullable(),version:i.string().nullable(),runner:i.string().nullable(),docker_compose_file:i.string().nullable(),features:i.array(i.string()).nullable(),created_at:i.string(),encrypted_env_pubkey:i.string().nullable()}),Jr=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()}),su=i.object({name:i.string(),description:i.string().optional(),version:i.array(i.number()).optional(),is_dev:i.boolean().optional(),os_image_hash:i.string().nullable().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()}),ff=i.object({teepod_id:i.number().nullable(),id:i.number().optional(),name:i.string(),listed:i.boolean().optional(),resource_score:i.number().optional(),remaining_vcpu:i.number().optional(),remaining_memory:i.number().optional(),remaining_cvm_slots:i.number().optional(),images:i.array(su).optional(),region_identifier:i.string().optional(),dedicated_for_team_id:i.number().nullable().optional(),support_onchain_kms:i.boolean().optional(),fmspc:i.string().nullable().optional(),device_id:i.string().nullable().optional()});import ou from"inquirer";async function wf(e){let t=await se(),n=e.replace(/^app_/,""),r=await Ct(t,{app_id:n});if(!r.success)throw new Error(r.error.message);return r.data}async function Cf(e){let t=await se(),n=await Xt(t,{id:e});if(!n.success)throw new Error(n.error.message);return n.data}async function kf(e){let t=await se(),n=e.replace(/^app_/,""),r=await t.get(`cvms/app_${n}/network`);return Mr.parse(r)}async function Sf(){let e=Oe.startSpinner("Fetching available CVMs"),t=await se(),n=await Jt(t);if(e.stop(!0),!n.success){Oe.error(`Failed to fetch CVMs: ${n.error.message}`);return}let{items:r}=n.data;if(r.length===0){Oe.info("No CVMs found for your account");return}let s=r.map(a=>({name:`${a.name} (${a.app_id??a.id}) - ${a.status}`,value:a.app_id??a.id})),{selectedCvm:o}=await ou.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:s}]);return o}async function Ef(e){let t=await se(),n=e.replace(/^app_/,""),r=await t.get(`cvms/app_${n}/attestation`);try{return Jr.parse(r)}catch(s){return Oe.debug(`Validation error: ${s instanceof Error?s.message:String(s)}`),{is_online:!!r?.is_online,is_public:!!r?.is_public,error:typeof r?.error=="string"?r.error:null,app_certificates:Array.isArray(r?.app_certificates)?r.app_certificates:null,tcb_info:r?.tcb_info||null,compose_file:typeof r?.compose_file=="string"?r.compose_file:null}}}async function Af(e,t){let n=await se(),r=e.replace(/^app_/,""),s=await n.post(`cvms/app_${r}/replicas`,t);return Wr.parse(s)}async function xf(e,t,n,r,s){let o=await se(),a=e.replace(/^app_/,""),c={};if(t!==void 0&&(c.vcpu=t),n!==void 0&&(c.memory=n),r!==void 0&&(c.disk_size=r),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 o.patch(`cvms/app_${a}/resources`,c),!0}async function If(e){return await(await se()).post("cvms/pubkey/from_cvm_configuration",e)}async function Rf(e){let n=await(await se()).post("cvms/from_cvm_configuration",e);return Gr.parse(n)}async function jf(e,t){let n=await se(),r=e.replace(/^app_/,"");return await n.put(`cvms/app_${r}/compose`,t)}async function Pf(e=!1){let t=await se(),n="teepods/available";return e&&(n+="?v03x_only=1"),await t.get(n)}function qe(e,t){let n=[];t.since&&n.push(`since=${encodeURIComponent(t.since)}`),t.until&&n.push(`until=${encodeURIComponent(t.until)}`),t.follow&&n.push("follow"),t.text&&n.push("text"),t.bare&&n.push("bare"),t.tail!==void 0&&(n.push(`tail=${t.tail}`),n.push(`lines=${t.tail}`)),t.timestamps&&n.push("timestamps"),(t.ansi??!0)&&n.push("ansi");let r=e.includes("?")?"&":"?";return e+r+n.join("&")}async function Xr(e,t){let n=e.body?.getReader();if(!n)throw new Error("No response body available for streaming");let r=new TextDecoder;for(;;){let{done:s,value:o}=await n.read();if(s)break;t(r.decode(o,{stream:!0}))}}function au(e){return!e||/\s/.test(e)||e.length%4!==0?!1:/^[A-Za-z0-9+/]+={0,2}$/.test(e)}function iu(e){if(!au(e))return e;try{return Buffer.from(e,"base64").toString("utf-8")}catch{return e}}function St(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return typeof n.message!="string"?null:{channel:n.channel==="stderr"?"stderr":"stdout",message:iu(n.message)}}catch{return null}}function cu(e){let t=e.split(/\r?\n/),n=[];for(let r of t){if(!r.trim())continue;let s=St(r);if(s){n.push(s);continue}n.push({channel:"stdout",message:`${r}
36
+ `})}return n}function lu(e){let t=e.split(/\r?\n/),n="";for(let r of t){let s=St(r);if(s){n+=s.message;continue}r.trim()&&(n+=`${r}
37
+ `)}return n}async function uu(e,t){let n=e.body?.getReader();if(!n)throw new Error("No response body available for streaming");let r=new TextDecoder,s="",o="unknown",a=c=>{let l=St(c);if(l){t(l.message);return}c.trim()&&t(`${c}
38
+ `)};for(;;){let{done:c,value:l}=await n.read();if(c)break;let m=r.decode(l,{stream:!0});if(o==="raw"){t(m);continue}if(s+=m,o==="unknown")if(s.trimStart().startsWith("{"))o="structured";else{o="raw",t(s),s="";continue}let d=s.indexOf(`
39
+ `);for(;d>=0;){let f=s.slice(0,d);s=s.slice(d+1),a(f),d=s.indexOf(`
40
+ `)}}o==="structured"&&s.trim()?a(s):o==="raw"&&s&&t(s)}async function pu(e,t){let n=e.body?.getReader();if(!n)throw new Error("No response body available for streaming");let r=new TextDecoder,s="",o="unknown",a=c=>{let l=St(c);if(l){t(l);return}c.trim()&&t({channel:"stdout",message:`${c}
41
+ `})};for(;;){let{done:c,value:l}=await n.read();if(c)break;let m=r.decode(l,{stream:!0});if(o==="raw"){t({channel:"stdout",message:m});continue}if(s+=m,o==="unknown")if(s.trimStart().startsWith("{"))o="structured";else{o="raw",t({channel:"stdout",message:s}),s="";continue}let d=s.indexOf(`
42
+ `);for(;d>=0;){let f=s.slice(0,d);s=s.slice(d+1),a(f),d=s.indexOf(`
43
+ `)}}o==="structured"&&s.trim()?a(s):o==="raw"&&s&&t({channel:"stdout",message:s})}async function Yt(e,t){let r=await(await se()).get(`cvms/${e}`,{headers:{"X-Phala-Version":"2025-10-28"}});if(!r.syslog_endpoint)throw new Error(`No syslog endpoint available for CVM '${e}'`);return`${r.syslog_endpoint}&ch=${t}`}async function Zr(e){return Yt(e,"serial")}async function Et(e,t,n=!0){let s=await(await se()).get(`cvms/${e}/composition`);if(!s.containers?.length)throw new Error(`No containers found for CVM '${e}'`);let o=s.containers;if(t&&(o=o.filter(c=>c.names.some(m=>m===t||m===`/${t}`)?!0:n?c.id.startsWith(t):!1),!o.length))throw new Error(`Container '${t}' not found in CVM '${e}'`);let a=o.find(c=>c.log_endpoint);if(!a?.log_endpoint)throw new Error(`No log endpoints available for CVM '${e}'`);return a.log_endpoint}async function Tf(e,t={}){let n=await Zr(e),r=qe(n,t),s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch serial logs: ${s.status} ${s.statusText}`);return s.text()}async function $f(e,t={}){let n=await Et(e,t.container,t.matchContainerIdPrefix??!0),r=t.text??!0,s=t.bare??!0,o=qe(n,{...t,text:r,bare:s}),a=await fetch(o);if(!a.ok)throw new Error(`Failed to fetch container logs: ${a.status} ${a.statusText}`);let c=await a.text();return c.trimStart().startsWith("{")?lu(c):c}async function Lf(e,t={}){let n=await Et(e,t.container,t.matchContainerIdPrefix??!0),r=qe(n,{...t,text:!1,bare:!1}),s=await fetch(r);if(!s.ok)throw new Error(`Failed to fetch container logs: ${s.status} ${s.statusText}`);let o=await s.text();return o.trimStart().startsWith("{")?cu(o):[{channel:"stdout",message:o}]}async function Of(e,t,n={},r){let s=await Et(e,n.container,n.matchContainerIdPrefix??!0),o=qe(s,{...n,follow:!0,text:!1,bare:!1}),a=await fetch(o,{signal:r});if(!a.ok)throw new Error(`Failed to stream container logs: ${a.status} ${a.statusText}`);await pu(a,t)}async function qf(e,t,n={},r){let s=await Zr(e),o=qe(s,{...n,follow:!0}),a=await fetch(o,{signal:r});if(!a.ok)throw new Error(`Failed to stream serial logs: ${a.status} ${a.statusText}`);await Xr(a,t)}async function Ff(e,t,n={},r){let s=await Et(e,n.container,n.matchContainerIdPrefix??!0),o=n.text??!0,a=n.bare??!0,c=qe(s,{...n,follow:!0,text:o,bare:a}),l=await fetch(c,{signal:r});if(!l.ok)throw new Error(`Failed to stream container logs: ${l.status} ${l.statusText}`);await uu(l,t)}async function zf(e,t,n={}){let r=await Yt(e,t),s=qe(r,n),o=await fetch(s);if(!o.ok)throw new Error(`Failed to fetch CVM ${t} logs: ${o.status} ${o.statusText}`);return o.text()}async function Uf(e,t,n,r={},s){let o=await Yt(e,t),a=qe(o,{...r,follow:!0}),c=await fetch(a,{signal:s});if(!c.ok)throw new Error(`Failed to stream CVM ${t} logs: ${c.status} ${c.statusText}`);await Xr(c,n)}async function Nf(e){let t=await se(),n=e.replace(/^app_/,""),r=await Ct(t,{app_id:n});if(!r.success)throw new Error(r.error.message);return r.data.status}export{df as composeFileSchema,Rf as createCvm,Jr as cvmAttestationResponseSchema,ru as dockerConfigSchema,mf as encryptedEnvItemSchema,$f as fetchContainerLogs,Lf as fetchContainerLogsEntries,zf as fetchCvmChannelLogs,Tf as fetchSerialLogs,Ef as getCvmAttestation,wf as getCvmByAppId,Cf as getCvmComposeConfig,Yt as getCvmLogEndpoint,kf as getCvmNetwork,Mr as getCvmNetworkResponseSchema,Nf as getCvmStatus,If as getPubkeyFromCvm,Pf as getTeepods,su as imageSchema,Gr as postCvmResponseSchema,Af as replicateCvm,Wr as replicateCvmResponseSchema,xf as resizeCvm,Sf as selectCvm,Ff as streamContainerLogs,Of as streamContainerLogsEntries,Uf as streamCvmChannelLogs,qf as streamSerialLogs,ff as teepodSchema,jf as upgradeCvm};
49
44
  /*! Bundled license information:
50
45
 
51
- @noble/hashes/esm/utils.js:
52
46
  @noble/hashes/utils.js:
53
47
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
54
48
  */