@stacksjs/ts-cloud 0.16.78 → 0.16.79
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/bin/{chunk-n5sapbxq.js → chunk-2wkw8qy0.js} +60 -58
- package/dist/bin/{chunk-hkqq09p2.js → chunk-fgnvksyx.js} +1 -1
- package/dist/bin/{chunk-2xtxktj3.js → chunk-grx14tmn.js} +1 -1
- package/dist/bin/cli.js +4 -4
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-wxy6jk7d.js → chunk-p9cm5ynz.js} +55 -53
- package/dist/{chunk-m95n1mbv.js → chunk-wy0bqg1v.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/shared/runtime-isolation.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +1 -1
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +5 -5
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +2 -2
- package/dist/ui/server/capacity.html +6 -6
- package/dist/ui/server/database.html +6 -6
- package/dist/ui/server/deployments.html +6 -6
- package/dist/ui/server/diagnostics.html +2 -2
- package/dist/ui/server/firewall.html +6 -6
- package/dist/ui/server/fleet.html +6 -6
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +6 -6
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +2 -2
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +6 -6
- package/dist/ui/serverless/logs.html +6 -6
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +6 -6
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{nl,Q,l,sl,K,p,ce,m,lr,cl,Xi,Vo,gl,fl,hl,$l,mn,ns,Ar,Ml,Fl,ql,jl}from"./chunk-t7qgvz8z.js";import{be,nr,x,ir,s,Li,So,Jr,Td,wd,ae,c,Co,Xe,Xr,Rd,vo,Dd,Yr,To,sr,Zr,Fi,cr,Gi,Vi,Ye,dr,Wd,Jd,ji,zi,Pt,Mo,i,Ki,Uo,Qo}from"./chunk-b6wsc7jp.js";import{n}from"./chunk-m9szynnf.js";import{Re}from"./chunk-v6s9k1mp.js";import{o}from"./chunk-c8kf2268.js";import{Te,vr,$s,ut,re,me,T,we,Rr,fe,pt,Pr}from"./chunk-tp37gyhc.js";import{ne}from"./chunk-nftqsker.js";import{u,ht,Zs,Ve,Lr,Lg,Zt,$g,Mg,Hc,je,It,pi,F,tr,Vr}from"./chunk-wxy6jk7d.js";import{U,d}from"./chunk-0cgrk9g3.js";import{$n}from"./chunk-z5c5amm1.js";import{Mn,bg,Bs,L,P,xs,Cg}from"./chunk-etv0rcjd.js";import{I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Ws}from"path";import kw from"process";import{existsSync as Rw,mkdirSync as ST,readdirSync as wT,readFileSync as Aw,writeFileSync as kT}from"fs";import{homedir as $o}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Yl,mkdirSync as Cw,readdirSync as Pw,writeFileSync as _w}from"fs";import{homedir as No}from"os";import{dirname as Gm,resolve as qr}from"path";import no from"process";import{join as Tw,relative as xw,resolve as Qm}from"path";import Yc from"process";import{existsSync as Mf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Cl}from"os";import{dirname as FT,resolve as Ur}from"path";import Ks from"process";import{join as Dw,relative as Ow,resolve as Ym}from"path";import Zc from"process";import{existsSync as Lf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Zl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as $w,createDecipheriv as Nw,randomBytes as Pl}from"crypto";import{closeSync as _l,createReadStream as Zm,createWriteStream as jw,existsSync as Tl,fsyncSync as Xm,openSync as ef,writeFileSync as Bw}from"fs";import{access as Mw,constants as tf,mkdir as Lw,readdir as xc,rename as rf,stat as jo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Bo}from"path";import Tr from"process";import{pipeline as Fw}from"stream/promises";import{createGzip as nf}from"zlib";import Lo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as zw,createDecipheriv as Uw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as qw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Vw}from"fs";import{access as Ww,constants as cf,mkdir as Hw,readdir as $c,rename as df,stat as Fo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Kw,join as zo,resolve as Jw}from"path";import At from"process";import{pipeline as Gw}from"stream/promises";import{createGzip as lf}from"zlib";import qo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Bl}from"path";import{existsSync as Qw}from"fs";import{existsSync as Yw,readdirSync as Zw}from"fs";import{extname as Ll,resolve as uf}from"path";import Xw from"process";import{join as ek,relative as tk,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as rk,createDecipheriv as nk,randomBytes as zl}from"crypto";import{closeSync as Ul,createReadStream as gf,createWriteStream as ik,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as ok}from"fs";import{access as sk,constants as hf,mkdir as ak,readdir as Lc,rename as yf,stat as Wo,unlink as Fc,writeFile as Vl}from"fs/promises";import{isAbsolute as ck,join as Ho,resolve as dk}from"path";import Ct from"process";import{pipeline as lk}from"stream/promises";import{createGzip as vf}from"zlib";import Ko from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Wm(e))return!0;return Hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new Of,sp=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Bf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function Iw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Ew(e={}){let t=Ws(e.cwd||kw.cwd());return Array.from(new Set([t,Ws(t,"config"),Ws(t,".config"),e.configDir?Ws(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var uk=Object.defineProperty,pk=(e)=>e;function gk(e,t){this[e]=pk.bind(null,t)}var mk=(e,t)=>{for(var r in t)uk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gk.bind(t,r)})},fk=(e,t)=>()=>(e&&(t=e(e=0)),t),Ff={};mk(Ff,{withErrorRecovery:()=>Hf,tryLoadConfig:()=>Mk,loadConfigWithResult:()=>jk,loadConfig:()=>Ph,isRetryableError:()=>Tk,isConfigNotFoundError:()=>_k,isBunfigError:()=>Gf,globalPerformanceMonitor:()=>Qs,globalCache:()=>Jo,getEnvOrDefault:()=>xk,generateConfigTypes:()=>Lk,defaultGeneratedDir:()=>Bh,defaultConfigDir:()=>jh,deepMergeWithArrayStrategy:()=>up,deepMerge:()=>Qf,createLibraryConfig:()=>Fk,config:()=>Bk,bunfigPlugin:()=>zk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>rp,SchemaValidationError:()=>Gs,PluginError:()=>ip,PerformanceMonitor:()=>cp,FileSystemError:()=>tp,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>pp,ConfigValidationError:()=>ru,ConfigNotFoundError:()=>od,ConfigMergeError:()=>ep,ConfigLoader:()=>gp,ConfigLoadError:()=>Js,ConfigFileLoader:()=>pd,ConfigCache:()=>ap,CacheUtils:()=>xh,BunfigError:()=>cn,BrowserConfigError:()=>np,ArrayMergeStrategies:()=>$h});class ap{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Km(e))return!0;return Jm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class cp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hk(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function yk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vk(e){return e.getStats().size*2}function dp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let g of e)if(Vt(g)&&"name"in g){if(!a.find((h)=>Vt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(Vt(g)&&"path"in g){if(!a.find((h)=>Vt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(Vt(g)&&Vt(r[a]))r[a]=dp(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&Vt(g[0])&&Vt(r[a][0])){let f=[...g];for(let h of r[a])if(Vt(h)&&"name"in h){if(!f.find((S)=>Vt(S)&&("name"in S)&&S.name===h.name))f.push(h)}else if(Vt(h)&&"path"in h){if(!f.find((S)=>Vt(S)&&("path"in S)&&S.path===h.path))f.push(h)}else if(!f.some((b)=>td(b,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function bk(e,t){if(!Lf(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return dp(t,a)}catch{return null}}catch{return null}}async function Sk({name:e="",cwd:t,defaultConfig:r}){let a=t||Zl.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let b of g){let S=Xc(a,`${h}${b}`),y=await bk(S,r);if(y!==null)return y}try{let h=Xc(a,"package.json");if(Lf(h)){let S=(await import(h))[e];if(S&&typeof S==="object"&&!Array.isArray(S))try{return dp(r,S)}catch{}}}catch{}return r}function wk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return Ow(Zc.cwd(),a);return a}async function kk(){try{let e=await Sk({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ik(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Uf{async format(e){let t=await Ik(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Lo.pid,hostname:t(),environment:Lo.env.NODE_ENV||"development",platform:Lo.platform,version:Lo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lo.env.NODE_ENV||Lo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...eu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Uf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:eu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let g,f=0,h=3,b=1000;while(f<h)try{try{try{await Mw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Lw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let S=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Bw(g,S,{flag:"a"}),Xm(g),g!==void 0)_l(g),g=void 0;if((await jo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,S,{flag:"w",mode:420}),(await jo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let k=y;if(k.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(k.code)){if(f<h-1){let R=typeof k.message==="string"?k.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,R);let D=b*2**f;await new Promise((O)=>setTimeout(O,D)),f++;continue}}if(k?.code&&["ENOSPC","EDQUOT"].includes(k.code))throw Error(`Disk quota exceeded or no space left on device: ${k.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",k),k}finally{if(g!==void 0)try{_l(g)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(S){if(f===h-1){let k=S,R=typeof k.message==="string"?k.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",R),S}f++;let y=b*2**(f-1);await new Promise((k)=>setTimeout(k,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((g)=>{console.error("Error rotating keys:",g)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let g=Array.from(this.encryptionKeys.entries()).sort(([,b],[,S])=>S.createdAt.getTime()-b.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[b]of g.slice(h))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Pl(16).toString("hex")}generateKey(){return Pl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Pl(16),a=$w("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Yt())return;let e=await jo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let g=await xc(this.config.logDirectory),f=g.filter((S)=>S.startsWith(this.name)&&/\.log\.\d+$/.test(S)).sort((S,y)=>{let k=Number.parseInt(S.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-k}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${h}`;if(await jo(r).catch(()=>null))try{if(await rf(r,b),t.compress)try{let S=`${b}.gz`;await this.compressLogFile(b,S),await Dc(b)}catch(S){console.error("Error compressing rotated file:",S)}if(f.length===0&&!g.some((S)=>S.endsWith(".log.1")))try{let S=`${r}.1`;await xl(S,"")}catch(S){console.error("Error creating backup file:",S)}}catch(S){console.error(`Error during rotation: ${S instanceof Error?S.message:String(S)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await jo(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,b)=>b.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(Bo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=jw(t),g=nf();await Fw(r,g,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Tl(this.currentLogFile))try{let e=ef(this.currentLogFile,"r+");Xm(e),_l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Yt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Bo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Nt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(h)O.push(t);if(f==="warning")O.push("WARN");else if(f==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(g),O.join(" ")}let S=Tr.stdout.columns||120,y="";if(f==="warning"||f==="error")y=`${r} ${g}`;else if(f==="info"||f==="success")y=`${r} ${a} ${g}`;else y=`${r} ${a} ${Nt.cyan(g)}`;if(!h)return y.trim();let k=b(y).trim().length,R=b(t).length,D=Math.max(1,S-2-k-R);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let b=Number.parseInt(h,10);return b<t[0].length?String(t[0][b]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let b=t[a++];switch(h){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,b;if(t instanceof Error)h=t.message,b=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let y=Dh[e],k=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.gray(h),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R);break;case"success":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.green(h),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R),b){let D=b.split(`
|
|
1
|
+
import{nl,Q,l,sl,K,p,ce,m,lr,cl,Xi,Vo,gl,fl,hl,$l,mn,ns,Ar,Ml,Fl,ql,jl}from"./chunk-t7qgvz8z.js";import{be,nr,x,ir,s,Li,So,Jr,Td,wd,ae,c,Co,Xe,Xr,Rd,vo,Dd,Yr,To,sr,Zr,Fi,cr,Gi,Vi,Ye,dr,Wd,Jd,ji,zi,Pt,Mo,i,Ki,Uo,Qo}from"./chunk-b6wsc7jp.js";import{n}from"./chunk-m9szynnf.js";import{Re}from"./chunk-v6s9k1mp.js";import{o}from"./chunk-c8kf2268.js";import{Te,vr,$s,ut,re,me,T,we,Rr,fe,pt,Pr}from"./chunk-tp37gyhc.js";import{ne}from"./chunk-nftqsker.js";import{u,ht,Zs,Ve,Lr,Lg,Zt,$g,Mg,Hc,je,It,pi,F,tr,Vr}from"./chunk-p9cm5ynz.js";import{U,d}from"./chunk-0cgrk9g3.js";import{$n}from"./chunk-z5c5amm1.js";import{Mn,bg,Bs,L,P,xs,Cg}from"./chunk-etv0rcjd.js";import{I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Ws}from"path";import kw from"process";import{existsSync as Rw,mkdirSync as ST,readdirSync as wT,readFileSync as Aw,writeFileSync as kT}from"fs";import{homedir as $o}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Yl,mkdirSync as Cw,readdirSync as Pw,writeFileSync as _w}from"fs";import{homedir as No}from"os";import{dirname as Gm,resolve as qr}from"path";import no from"process";import{join as Tw,relative as xw,resolve as Qm}from"path";import Yc from"process";import{existsSync as Mf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Cl}from"os";import{dirname as FT,resolve as Ur}from"path";import Ks from"process";import{join as Dw,relative as Ow,resolve as Ym}from"path";import Zc from"process";import{existsSync as Lf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Zl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as $w,createDecipheriv as Nw,randomBytes as Pl}from"crypto";import{closeSync as _l,createReadStream as Zm,createWriteStream as jw,existsSync as Tl,fsyncSync as Xm,openSync as ef,writeFileSync as Bw}from"fs";import{access as Mw,constants as tf,mkdir as Lw,readdir as xc,rename as rf,stat as jo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Bo}from"path";import Tr from"process";import{pipeline as Fw}from"stream/promises";import{createGzip as nf}from"zlib";import Lo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as zw,createDecipheriv as Uw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as qw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Vw}from"fs";import{access as Ww,constants as cf,mkdir as Hw,readdir as $c,rename as df,stat as Fo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Kw,join as zo,resolve as Jw}from"path";import At from"process";import{pipeline as Gw}from"stream/promises";import{createGzip as lf}from"zlib";import qo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Bl}from"path";import{existsSync as Qw}from"fs";import{existsSync as Yw,readdirSync as Zw}from"fs";import{extname as Ll,resolve as uf}from"path";import Xw from"process";import{join as ek,relative as tk,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as rk,createDecipheriv as nk,randomBytes as zl}from"crypto";import{closeSync as Ul,createReadStream as gf,createWriteStream as ik,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as ok}from"fs";import{access as sk,constants as hf,mkdir as ak,readdir as Lc,rename as yf,stat as Wo,unlink as Fc,writeFile as Vl}from"fs/promises";import{isAbsolute as ck,join as Ho,resolve as dk}from"path";import Ct from"process";import{pipeline as lk}from"stream/promises";import{createGzip as vf}from"zlib";import Ko from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Wm(e))return!0;return Hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new Of,sp=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Bf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function Iw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Ew(e={}){let t=Ws(e.cwd||kw.cwd());return Array.from(new Set([t,Ws(t,"config"),Ws(t,".config"),e.configDir?Ws(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var uk=Object.defineProperty,pk=(e)=>e;function gk(e,t){this[e]=pk.bind(null,t)}var mk=(e,t)=>{for(var r in t)uk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gk.bind(t,r)})},fk=(e,t)=>()=>(e&&(t=e(e=0)),t),Ff={};mk(Ff,{withErrorRecovery:()=>Hf,tryLoadConfig:()=>Mk,loadConfigWithResult:()=>jk,loadConfig:()=>Ph,isRetryableError:()=>Tk,isConfigNotFoundError:()=>_k,isBunfigError:()=>Gf,globalPerformanceMonitor:()=>Qs,globalCache:()=>Jo,getEnvOrDefault:()=>xk,generateConfigTypes:()=>Lk,defaultGeneratedDir:()=>Bh,defaultConfigDir:()=>jh,deepMergeWithArrayStrategy:()=>up,deepMerge:()=>Qf,createLibraryConfig:()=>Fk,config:()=>Bk,bunfigPlugin:()=>zk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>rp,SchemaValidationError:()=>Gs,PluginError:()=>ip,PerformanceMonitor:()=>cp,FileSystemError:()=>tp,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>pp,ConfigValidationError:()=>ru,ConfigNotFoundError:()=>od,ConfigMergeError:()=>ep,ConfigLoader:()=>gp,ConfigLoadError:()=>Js,ConfigFileLoader:()=>pd,ConfigCache:()=>ap,CacheUtils:()=>xh,BunfigError:()=>cn,BrowserConfigError:()=>np,ArrayMergeStrategies:()=>$h});class ap{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Km(e))return!0;return Jm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class cp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hk(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function yk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vk(e){return e.getStats().size*2}function dp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let g of e)if(Vt(g)&&"name"in g){if(!a.find((h)=>Vt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(Vt(g)&&"path"in g){if(!a.find((h)=>Vt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(Vt(g)&&Vt(r[a]))r[a]=dp(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&Vt(g[0])&&Vt(r[a][0])){let f=[...g];for(let h of r[a])if(Vt(h)&&"name"in h){if(!f.find((S)=>Vt(S)&&("name"in S)&&S.name===h.name))f.push(h)}else if(Vt(h)&&"path"in h){if(!f.find((S)=>Vt(S)&&("path"in S)&&S.path===h.path))f.push(h)}else if(!f.some((b)=>td(b,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function bk(e,t){if(!Lf(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return dp(t,a)}catch{return null}}catch{return null}}async function Sk({name:e="",cwd:t,defaultConfig:r}){let a=t||Zl.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let b of g){let S=Xc(a,`${h}${b}`),y=await bk(S,r);if(y!==null)return y}try{let h=Xc(a,"package.json");if(Lf(h)){let S=(await import(h))[e];if(S&&typeof S==="object"&&!Array.isArray(S))try{return dp(r,S)}catch{}}}catch{}return r}function wk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return Ow(Zc.cwd(),a);return a}async function kk(){try{let e=await Sk({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ik(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Uf{async format(e){let t=await Ik(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Lo.pid,hostname:t(),environment:Lo.env.NODE_ENV||"development",platform:Lo.platform,version:Lo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lo.env.NODE_ENV||Lo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...eu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Uf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:eu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let g,f=0,h=3,b=1000;while(f<h)try{try{try{await Mw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Lw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let S=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Bw(g,S,{flag:"a"}),Xm(g),g!==void 0)_l(g),g=void 0;if((await jo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,S,{flag:"w",mode:420}),(await jo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let k=y;if(k.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(k.code)){if(f<h-1){let R=typeof k.message==="string"?k.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,R);let D=b*2**f;await new Promise((O)=>setTimeout(O,D)),f++;continue}}if(k?.code&&["ENOSPC","EDQUOT"].includes(k.code))throw Error(`Disk quota exceeded or no space left on device: ${k.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",k),k}finally{if(g!==void 0)try{_l(g)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(S){if(f===h-1){let k=S,R=typeof k.message==="string"?k.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",R),S}f++;let y=b*2**(f-1);await new Promise((k)=>setTimeout(k,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((g)=>{console.error("Error rotating keys:",g)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let g=Array.from(this.encryptionKeys.entries()).sort(([,b],[,S])=>S.createdAt.getTime()-b.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[b]of g.slice(h))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Pl(16).toString("hex")}generateKey(){return Pl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Pl(16),a=$w("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Yt())return;let e=await jo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let g=await xc(this.config.logDirectory),f=g.filter((S)=>S.startsWith(this.name)&&/\.log\.\d+$/.test(S)).sort((S,y)=>{let k=Number.parseInt(S.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-k}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${h}`;if(await jo(r).catch(()=>null))try{if(await rf(r,b),t.compress)try{let S=`${b}.gz`;await this.compressLogFile(b,S),await Dc(b)}catch(S){console.error("Error compressing rotated file:",S)}if(f.length===0&&!g.some((S)=>S.endsWith(".log.1")))try{let S=`${r}.1`;await xl(S,"")}catch(S){console.error("Error creating backup file:",S)}}catch(S){console.error(`Error during rotation: ${S instanceof Error?S.message:String(S)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await jo(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,b)=>b.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(Bo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=jw(t),g=nf();await Fw(r,g,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Tl(this.currentLogFile))try{let e=ef(this.currentLogFile,"r+");Xm(e),_l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Yt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Bo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Nt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(h)O.push(t);if(f==="warning")O.push("WARN");else if(f==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(g),O.join(" ")}let S=Tr.stdout.columns||120,y="";if(f==="warning"||f==="error")y=`${r} ${g}`;else if(f==="info"||f==="success")y=`${r} ${a} ${g}`;else y=`${r} ${a} ${Nt.cyan(g)}`;if(!h)return y.trim();let k=b(y).trim().length,R=b(t).length,D=Math.max(1,S-2-k-R);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let b=Number.parseInt(h,10);return b<t[0].length?String(t[0][b]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let b=t[a++];switch(h){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,b;if(t instanceof Error)h=t.message,b=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let y=Dh[e],k=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.gray(h),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R);break;case"success":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.green(h),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R),b){let D=b.split(`
|
|
2
2
|
`);for(let O of D)if(O.trim()&&!O.includes(h))console.error(this.formatConsoleMessage({timestamp:g,message:Nt.gray(` ${O}`),level:e,showTimestamp:!1}))}break}}else if(!Yt()){if(console.error(`${f} ${this.environment}.${e.toUpperCase()}: ${h}`),b)console.error(b)}if(!this.shouldLog(e))return;let S=`${f} ${this.environment}.${e.toUpperCase()}: ${h}
|
|
3
3
|
`;if(b)S+=`${b}
|
|
4
4
|
`;S=S.replace(this.ANSI_PATTERN,""),await this.writeToFile(S)}time(e){let t=performance.now();if(this.fancy&&!Yt()){let r=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:Nt.blue("◐"),tag:r,message:`${Nt.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),g=Math.round(a-t),f=`${e} completed in ${g}ms`,h=new Date,b=this.formatConsoleTimestamp(h),y=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${f}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Pn,kn,Xu,bs,Yu,Zu,eg,Xa,tg,rg,Ah,ng,v,ig,Cs,Me,sg,og,jS,ag,cg,dg,lg,ug,yh,zS,KS,WS,Sh,Ih,JS,XS,bh,Ch,YS,Es,Cr,Ya,Nn,Bn,Er,lt,Qt,vs,Eh,xn,gg,pg,Za,ws,_n,Rs,pc}from"../chunk-
|
|
1
|
+
import{Pn,kn,Xu,bs,Yu,Zu,eg,Xa,tg,rg,Ah,ng,v,ig,Cs,Me,sg,og,jS,ag,cg,dg,lg,ug,yh,zS,KS,WS,Sh,Ih,JS,XS,bh,Ch,YS,Es,Cr,Ya,Nn,Bn,Er,lt,Qt,vs,Eh,xn,gg,pg,Za,ws,_n,Rs,pc}from"../chunk-wy0bqg1v.js";import{mc,Ln,$n,Ds,Ps,ks,Ns,fc,hc}from"../chunk-z5c5amm1.js";import{Ac}from"../chunk-etv0rcjd.js";import"../chunk-tp37gyhc.js";import"../chunk-nftqsker.js";import"../chunk-v6s9k1mp.js";import"../chunk-z56sccfh.js";import"../chunk-fdf181e6.js";import"../chunk-8k44kaz0.js";import"../chunk-hg93a2g9.js";import{Ng,Oc,Bg,De,_c,Yn,xg,Lc,id,ao,sd,tr,Ri,co}from"../chunk-p9cm5ynz.js";import"../chunk-w8sctn7m.js";import"../chunk-vq8bejep.js";import"../chunk-tmp2ym80.js";import"../chunk-c8kf2268.js";import"../chunk-m9szynnf.js";import{Tt,wA,hd,xi,Oi,_i,jp}from"../chunk-nxj8pwa7.js";import{U,zr,Kr,Ad,Ao,d,RA,zp,Kp,NI,BI}from"../chunk-0cgrk9g3.js";import"../chunk-b6wsc7jp.js";import"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";export{wA as DEFAULT_SITE_PORT_RANGE,Tt as HOST_SITES_DIR,_c as IPV6_EXCLUDED_HOST_LABELS,id as MANAGEMENT_DASHBOARD_SITE,Pn as addSiteToCloudConfig,jp as allocateSitePorts,YS as buildAndPushContainerImage,Ac as buildAndPushServerlessImage,Cr as buildFunctionEnv,Oi as buildHostSitePortsScript,co as buildManagementDashboardArtifact,Qt as buildServerTopology,vs as buildServerlessTopology,Eh as buildTopology,Za as collectEgressMetrics,Ng as collectServerDnsDomains,Ch as createContainerImageDependencies,Sh as createExistingStaticFullStackDependencies,yh as createStaticApiOriginDependencies,_n as dashboardActions,ao as dashboardCredentialsFile,sg as dashboardPageRoutes,lg as deleteFailoverReplicaBuckets,fc as deleteStaticSite,JS as deployExistingStaticFullStack,Ya as deployServerlessApp,BI as deployShipsFiles,ug as deploySite,zS as deployStaticApiOrigin,Ps as deployStaticSite,hc as deployStaticSiteFull,Ln as deployStaticSiteWithExternalDns,$n as deployStaticSiteWithExternalDnsFull,gg as egressReportMetrics,v as ensureDashboardActor,ag as ensureFailoverReplicaBuckets,Ri as ensureManagementDashboard,XS as estimateExistingStaticFullStackMonthlyCost,WS as estimateStaticApiOriginMonthlyCost,pg as fetchEgressReport,Ih as generateExistingStaticFullStackTemplate,mc as generateExternalDnsStaticSiteTemplate,Ds as generateStaticSiteTemplate,cg as grantFailoverReplicaAccess,RA as hasComputeConfigured,Ad as hasProxyUpstream,bh as hashContainerContext,Yn as hostAcceptsIpv6,Es as infraEnvFromOutputs,ig as initializeDashboardControlPlane,Ns as invalidateCache,zr as isPhpSite,Xa as isValidHostname,De as normalizePublicIpv6,xi as occupiedHostPorts,_i as parseHostSiteFragments,hd as parseUpstreamPort,xg as reconcileAddressRecords,Nn as redeployServerlessApp,Bg as removeAddressRecords,kn as removeSiteFromCloudConfig,Oc as removeStaleServerAddressRecords,tg as renderAliasesValue,eg as renderEnvValue,rg as renderRedirectsValue,Ah as renderSiteSnippet,Yu as renderSslValue,Zu as renderStringValue,Rs as resolveDashboardAction,sd as resolveDashboardAuth,xn as resolveDashboardData,og as resolveLegacyDashboardRoute,Kr as resolveProxyUpstreams,Ao as resolveSiteDeployTarget,d as resolveSiteKind,tr as resolveUiSource,Bn as rollbackServerlessApp,jS as routesForDashboard,lt as runRemoteCommand,ws as sanitizeCloudConfig,dg as seedFailoverReplicas,ng as setAttachToInCloudConfig,Er as setMaintenance,bs as setSitePropertyInCloudConfig,Kp as shipsARelease,NI as shipsToBucket,U as siteInstallBase,pc as startLocalDashboardServer,Cs as synchronizeDashboardUsers,Me as trackDashboardOperation,Xu as updateSiteInCloudConfig,ks as uploadStaticFiles,zp as validateDeploymentConfig,Lc as verifyAddressRecord,KS as verifyStaticApiOrigin};
|
package/dist/drivers/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Zn,Xt,Or,Yt,_r,M,$r,ei,ti,Mr,Fr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Ur,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Qr,Ie,Fc,At,Uc,di,Qc,Hr,Gc,qe,se,er,Hg,li,Vc,qc,jc,zc,yt,je,ze,St,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,It,pi,Wc,jg,zg,Jc,bt,ke,Xc,Kg,Wg,io,mi,Ct,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Gr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,lo,od,Di,ad,yp,Sp,Ip,Zh}from"../chunk-
|
|
1
|
+
import{Zn,Xt,Or,Yt,_r,M,$r,ei,ti,Mr,Fr,Uh,Qh,Fg,Ug,Hh,Gh,Vh,Ur,ri,Qg,to,ni,ii,si,oi,ai,$c,Mc,ci,Qr,Ie,Fc,At,Uc,di,Qc,Hr,Gc,qe,se,er,Hg,li,Vc,qc,jc,zc,yt,je,ze,St,ui,gi,Pe,ro,no,Gg,Vg,Kc,qg,It,pi,Wc,jg,zg,Jc,bt,ke,Xc,Kg,Wg,io,mi,Ct,Jg,Xg,Yg,Zg,ep,tp,rp,np,ip,fi,hi,Ai,yi,Si,Ii,bi,sp,op,Gr,F,so,ap,cp,dp,Yc,lp,up,qh,jh,zh,Zc,gp,Kh,Wh,Jh,Ci,Ei,vi,Ti,ed,td,wi,rd,Xh,oo,pp,mp,fp,hp,Ap,nd,Yh,lo,od,Di,ad,yp,Sp,Ip,Zh}from"../chunk-p9cm5ynz.js";import{go,mo,fo,eA,ld,B,rr,kI,ho,vp,Ke,G,Ne}from"../chunk-w8sctn7m.js";import"../chunk-vq8bejep.js";import"../chunk-tmp2ym80.js";import"../chunk-c8kf2268.js";import"../chunk-m9szynnf.js";import"../chunk-0cgrk9g3.js";import"../chunk-t7qgvz8z.js";import"../chunk-928z0h9b.js";export{rd as AwsBoxProvisioner,$r as AwsDriver,dp as BOOT_PARTITION_LABEL,pp as BOX_PANTRY_BIN_DIR,oo as BOX_PANTRY_CLI_DIR,so as CloudDriverFactory,Ug as DEFAULT_HOST_CLEANUP_ESCALATED,Gh as DEFAULT_HOST_CLEANUP_HIGH_WATER_PERCENT,Hh as DEFAULT_HOST_CLEANUP_LOW_WATER_PERCENT,Fg as DEFAULT_HOST_CLEANUP_RETENTION,Vh as DEFAULT_HOST_CLEANUP_SCHEDULE,go as DEFAULT_RPX_CERTS_DIR,cp as FIRST_BOOT_SCRIPT_PATH,Fr as HOST_ARTIFACT_CACHE_DIR,Uh as HOST_CLEANUP_SCRIPT_PATH,Qh as HOST_CLEANUP_UNIT,wi as HetznerBoxProvisioner,Hr as HetznerClient,Pe as HetznerDriver,zc as LEGACY_DRIVER_STATE_DIR,ro as LocalBoxDriver,Sp as MANAGED_CACHE_POLICY_DISABLED,yp as MANAGED_CACHE_POLICY_OPTIMIZED,Ip as MANAGED_ORIGIN_REQUEST_POLICY_ALL_VIEWER,Wg as RASPBERRY_PI_DEFAULT_SWAP_GB,Qc as REMOTE_SCRIPT_RUNNER,ho as RPX_DIR,vp as RPX_LAUNCHER_PATH,Ke as RPX_SERVICE_NAME,Xc as SSH_BOOTSTRAP_MARKER_DIR,ke as SSH_BOOTSTRAP_VERSION,Ct as SSH_DEFAULTS,bi as SSH_DEPLOY_STORAGE_PATH,Gg as SSH_INSECURE_HOST_KEY_OPTS,Vg as SSH_KEEPALIVE_OPTS,hi as SSH_PREFLIGHT_SCRIPT,sp as SSH_SKIP_BOOTSTRAP_ENV,Gr as SshDriver,bt as SystemSshTransport,ed as UBUNTU_2404_AMI_PARAM,Jh as acquireResizeLock,qh as applyHetznerHostOptimization,gi as applyHetznerVolumes,io as assertArchSupported,op as assertSshComputeConfig,$c as buildAwsArtifactFetch,Ap as buildBoxConvergeScript,mp as buildBoxSandboxConvergeScript,td as buildBoxUserData,Zh as buildCloudFrontOriginConfig,Yc as buildCloudInitFirstBoot,ti as buildComputeStorageInstallScript,Mr as buildComputeStorageSiteScript,up as buildHetznerHostOptimizationScript,ni as buildHostCleanupDeployScript,Qg as buildHostCleanupExecutable,to as buildHostCleanupInstallScript,ri as buildHostCleanupScript,Mc as buildLocalArtifactFetch,B as buildRpxConfig,Ne as buildRpxFragmentRefreshScript,rr as buildRpxLbConfig,G as buildRpxProvisionScript,qg as buildScpArgsFor,si as buildSiteDeployScript,ci as buildSshArgs,Kc as buildSshArgsFor,mi as buildSshBootstrapScript,oi as buildStaticSiteDeployScript,ap as cloudDrivers,jh as collectHetznerHostOptimizationReport,Vc as collectHetznerResizeManifest,Xh as createBoxProvisioner,F as createCloudDriver,od as deployAllComputeSites,lo as deploySiteRelease,ld as deriveRouteId,Zn as describeScriptSyntaxError,yt as driverStateDir,je as driverStatePath,Ei as ensureFirewall,vi as ensureServer,Ci as ensureSshKey,yi as evaluatePreflight,li as executeHetznerServerResize,zg as findKnownHostKey,Ii as formatPreflightFindings,Xt as formatSshFailure,fo as gatewayHostnames,M as generateUbuntuAppCloudInit,mo as hasAutoWwwVariant,no as isBoxMode,Hg as isHetznerCapacityError,_r as isLocalDatabase,jg as knownHostsLine,Wc as knownHostsToken,eA as normalizeRoutePath,qe as normalizeSshPublicKey,nd as parseBoxReport,Ai as parsePreflightFacts,er as planHetznerServerResize,ui as planHetznerVolumes,Si as preflightFailed,qc as prepareHetznerResize,Yh as provisionBox,ze as readDriverState,Kh as readResizeCheckpoint,ai as releaseTarballTmpPath,Di as reloadRpxGateway,di as remoteScriptRunner,hp as renderBoxUnit,fp as renderEnvFile,kI as renderRpxLauncher,ad as renewRpxCertificates,Zc as resizeCheckpointPath,gp as resizeLockPath,ei as resolveComputeVolumes,ii as resolveExecStart,Gc as resolveHetznerApiToken,lp as resolveHetznerHostOptimizationPlan,Ur as resolveHostCleanupConfig,ep as resolveSshHostKeyPolicy,Jg as resolveSshHosts,ip as resolveSshLan,Yg as resolveSshPort,Zg as resolveSshPrivateKeyPath,rp as resolveSshProfile,np as resolveSshPublicIp,fi as resolveSshSettings,tp as resolveSshSudo,Xg as resolveSshUser,pi as scanHostKey,Fc as scpUpload,Ti as serverPublicIpv4,Kg as sshBootstrapMarkerPath,Qr as sshExec,Ie as sshExecOrThrow,It as sshHostKeyFingerprint,Jc as sshKnownHostsPath,Yt as summarizeRemoteFailures,Or as surfaceRemoteNotices,zh as verifyHetznerHostOptimization,jc as verifyHetznerResize,Uc as waitForCloudInit,At as waitForSsh,se as wrapCloudInitUserData,St as writeDriverState,Wh as writeResizeCheckpoint};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Preserve ProtectHome when adopting a host whose Bun was installed under root. */
|
|
2
|
+
export declare function buildAccessibleBunScript(): string[];
|
|
1
3
|
/** One unprivileged identity per project; its web/API/workers may share that project's data. */
|
|
2
4
|
export declare function runtimeIsolationUser(slug: string): string;
|
|
3
5
|
export declare function runtimeIsolationDirectives(user: string, base: string, slug: string): string[];
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,C,Ze,Ji,ln,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,un,kt,Go,Nt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME}from"./chunk-t7qgvz8z.js";import{Kl,k,Wl,na,vS,Vf,TS,wS,RS,DS,PS,kS,NS,BS}from"./chunk-928z0h9b.js";import{da,qf,nu,LS,cs,iu,la,jf,zf,yn,ua,su,ot,ou,au,cu,ds,Sn,Kf,at,du,ga,pa,ma,lu,uu,gu,ls,fa,pu,In,us,ha,_t,Wf,mu,fu,Jf,hu,Aa,yr,Au,yu,Su,Iu,ct,Xf,bu,Sr,ya,Sa,Ia,gs,ps,bn,Cu,ms,ba,Ca,Cn,Eu,En,Yf,Zf,Lt,vn,Ea,eh,vu,Tu,va,wu,Ru,Du,$S,ge,Pu,MS,FS,fs,hs,US,Ee,th,$t,Le,$e,Mt,ku,Nu,Bu,xu,rh,nh,Ta,ih,sh,wa,Ou,_u,oh,pe,ah,Lu,ve,Ra,dt,Ft,Ut,Tn,As,$u,QS,ch,dh,lh,uh,Da,Pa,Mu,ka,wn,Na,Fu,ys,Uu,Ba,xa,Oa,_a,La,$a,Ma,Fa,Qu,Ir,Ua,Hu,Rn,Gu,Qa,Ha,Vu,br,Ga,Va,gh,HS,Ss,GS,VS,qS,qa,ja,qu,ph,za,Dn,ju,Is,zu,Ku,Wu,Ka,mh,Wa,Ju,fh,Ja,hh,Pn,kn,Xu,bs,ng,ag,cg,dg,lg,ug,Es,Cr,Ya,Nn,Bn,Er,lt,vh,ec,Th,wh,mg,tc,Ts,fg,rc,Ht,Fe,hg,nc,ic,Ag,sc,oc,ac,cc,yg,Sg,On,dc,lc,uc,gc,Ig,ws,_n,Rs,pc}from"./chunk-m95n1mbv.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-0cgrk9g3.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-nxj8pwa7.js";import{rA,nA,iA,Rp,Dp,Pp,sA,kp,Np,oA,aA,Bp,cA,dA,md,xp,lA,uA,Op,gA,pA,mA,fA,hA,AA,yA,Bi,fd,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,Vp,qp,SA,IA,bA,CA,EA,vA,TA}from"./chunk-dvma06m5.js";import{Je,yd,be,nr,Sd,x,ir,wt,Id,yo,DA,Wp,bd,s,Li,So,Wr,Cd,Ed,Jr,PA,vd,xI,OI,Io,_I,LI,Td,wd,$i,bo,ae,c,Co,Xe,Xr,kA,NA,Rd,BA,Eo,xA,OA,vo,Dd,Yr,To,_A,sr,Pd,Jp,or,Zr,LA,wo,$A,O,MA,kd,Xp,Ro,FA,UA,QA,Nd,Mi,Do,Bd,ar,Rt,HA,en,GA,xd,Yp,Zp,Po,Od,_d,Dt,em,Fi,Ld,ko,tn,tm,Ui,$d,Md,Qi,rm,Fd,Ud,Qd,Hd,No,nm,im,VA,sm,Gd,Hi,om,am,Bo,rn,xo,Oo,_o,Vd,cm,qd,Lo,qA,cr,jA,jd,nn,zd,zA,Kd,dm,Gi,sn,$o,Vi,Ye,KA,lm,um,dr,Wd,Jd,Xd,qi,ji,zi,WA,JA,Pt,Mo,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,i,ty,Ki,Uo,Qo}from"./chunk-b6wsc7jp.js";import{n}from"./chunk-m9szynnf.js";import{Re,mt,zn}from"./chunk-v6s9k1mp.js";import{o}from"./chunk-c8kf2268.js";import{Te,Os,_s,Eg,yc,Sc,Ls,Ic,ut,re,gt,me,T,we,Un,bc,Ue,Cc,Qn,Hn,Gn,Gt,Vt,qt,Vn,Tr,Ec,wr,Rr,pt,qn,Tc,jt,Dr,jn,Rc,Dg,Pg,Dc,Pr}from"./chunk-tp37gyhc.js";import{ft,Ae,Ge,kg,zt,kc,Nc,Kt,H,Kn,Wt,Jt,Wn,Us,Qs,kr,Nr,Jn,Br,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,ye,Js,Xs,Ys,N,Bc,Xn,xc,Se,xr}from"./chunk-8k44kaz0.js";import{ne}from"./chunk-nftqsker.js";import{Ng,Oc,Bg,De,_c,Yn,xg,Lc,Og,_g,Fh,_r,eo,M,$r,ei,ti,Mr,Ur,ri,to,ni,ii,si,oi,ci,Qr,Ie,Fc,At,Uc,Hr,Gc,qe,se,je,ze,St,ui,gi,Pe,bt,ke,mi,fi,hi,Ai,yi,Si,Ii,Gr,F,so,ap,Yc,Ci,Ei,vi,Ti,id,ao,sd,tr,Ri,co,lo,od,Di,ad}from"./chunk-wxy6jk7d.js";import{go,mo,fo,B,Ne}from"./chunk-w8sctn7m.js";import{Jl,ia,ss,os,sa,Xl,Yl,as,oa,aa,eu,tu,ca}from"./chunk-jx1zz1pw.js";import{mc,Ln,$n,Ds,Ps,ks,Ns,fc,hc}from"./chunk-z5c5amm1.js";import{Ac}from"./chunk-etv0rcjd.js";import{Pc,Qe,I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{b}from"./chunk-hg93a2g9.js";import{oe,Pi,uo,cd,ki,bp}from"./chunk-42vtybcm.js";import{qr,Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"./chunk-84z2a1xn.js";import{xS,st}from"./chunk-9pwvnh3f.js";var jh="https://api.machines.dev/v1";class Cs extends Error{status;path;constructor(u,g,h){super(u);this.status=g;this.path=h;this.name="FlyApiError"}}function Qc(u){let g=u.ip.includes(":");if(g&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return g?"v6":"v4"}class hp{token;fetch;constructor(u){if(!u.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=u.token,this.fetch=u.fetch??fetch}async rest(u,g,h={}){let y=new URL(`https://api.machines.dev/v1${g}`);for(let[L,z]of Object.entries(h.query??{}))y.searchParams.set(L,z);let R=await this.fetch(y,{method:u,headers:{Authorization:`Bearer ${this.token}`,...h.body!==void 0?{"Content-Type":"application/json"}:{},...h.headers},body:h.body===void 0?void 0:JSON.stringify(h.body)});if(R.status===404&&h.notFound==="null")return null;let v=await R.text(),P=v?yp(v):void 0;if(!R.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):v||R.statusText;throw new Cs(`Fly.io ${u} ${g} failed (${R.status}): ${L}`,R.status,g)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,g){return this.rest("POST","/apps",{body:{app_name:u,org_slug:g}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:g})}updateMachine(u,g,h,y){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}`,{body:h,headers:{"fly-machine-lease-nonce":y}})}async acquireLease(u,g,h=120){let R=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{body:{ttl:h}})).data?.nonce;if(!R)throw new Cs(`Fly.io gave no lease nonce for Machine ${g}`,200,`/machines/${g}/lease`);return R}async releaseLease(u,g,h){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{headers:{"fly-machine-lease-nonce":h}})}async waitForState(u,g,h,y={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/wait`,{query:{state:h,timeout:String(y.timeoutSeconds??60),...y.instanceId?{instance_id:y.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...g,encrypted:!0}})}async setSecrets(u,g){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:g}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,g){let h=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:g}});if(!h.ip)throw new Cs(`Fly.io assigned no ${g} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:h.ip,shared:h.shared??g==="shared_v4",region:h.region}}async requestCertificate(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:g}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var vc="ts-cloud-role";function Zh(u,g){let h=u.fly??{},y=h.app??`${u.project.slug}-${g.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(y))throw Error(`"${y}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let R=h.internalPort??3000,v=h.count??1;if(!Number.isInteger(v)||v<1)throw Error(`fly.count must be a whole number of at least 1, got ${v}.`);return{app:y,org:h.org??"personal",image:g.image,regions:h.regions?.length?h.regions:["iad"],count:v,internalPort:R,healthPath:h.healthPath??"/",vm:{cpuKind:h.vm?.cpuKind??"shared",cpus:h.vm?.cpus??1,memoryMb:h.vm?.memoryMb??512},...h.volume?{volume:{name:h.volume.name??"data",sizeGb:h.volume.sizeGb,path:h.volume.path}}:{},autoStop:h.autoStop??!1,env:{...g.env,PORT:String(R)},secrets:g.secrets??{},hostnames:h.hostnames??[],release:g.release}}function Cp(u){return{image:u.image,env:u.env,guest:{cpu_kind:u.vm.cpuKind,cpus:u.vm.cpus,memory_mb:u.vm.memoryMb},services:[{protocol:"tcp",internal_port:u.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:u.autoStop?"stop":"off",autostart:!0,...u.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:u.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[vc]:"app","ts-cloud-release":u.release}}}async function Jh(u,g,h=()=>{}){let y=!1;if(!await u.getApp(g.app))h(`Creating Fly app ${g.app} in ${g.org}`),await u.createApp(g.app,g.org),y=!0;let R;if(Object.keys(g.secrets).length>0)R=await u.setSecrets(g.app,g.secrets),h(`Set ${Object.keys(g.secrets).length} secret(s) (version ${R})`);let v=await u.listIpAssignments(g.app),P=new Set(v.map(Qc));if(!P.has("v6"))v.push(await u.assignIp(g.app,"v6")),h("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))v.push(await u.assignIp(g.app,"shared_v4")),h("Assigned a shared IPv4");let L=Cp(g),z=(await u.listMachines(g.app)).filter((Me)=>{let We=Me.config?.metadata??{};if(We[vc])return We[vc]==="app";return!We.fly_process_group||We.fly_process_group==="app"}),he=g.volume?await u.listVolumes(g.app):[],fe=[],Ct=[],It=new Set;for(let Me of g.regions){let We=z.filter((j)=>j.region===Me).sort((j,ht)=>j.id.localeCompare(ht.id));for(let j=0;j<g.count;j++){let ht=We[j];if(ht){It.add(ht.id),await Sp(u,g.app,ht,L,R),Ct.push(ht.id),h(`Updated ${ht.id} (${Me}) to ${g.image}`);continue}let G=g.volume?[{volume:(await Ap(u,g,Me,he)).id,path:g.volume.path}]:void 0,Ke=await u.createMachine(g.app,{region:Me,name:`${g.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...R!==void 0?{min_secrets_version:R}:{}});await u.waitForState(g.app,Ke.id,"started",{instanceId:Ke.instance_id}),fe.push(Ke.id),h(`Created ${Ke.id} in ${Me}`)}}let Ve=[];for(let Me of g.hostnames)Ve.push(await u.requestCertificate(g.app,Me));return{app:g.app,url:`https://${g.app}.fly.dev`,createdApp:y,created:fe,updated:Ct,untouched:z.filter((Me)=>!It.has(Me.id)).map((Me)=>Me.id),ips:v,certificates:Ve}}async function Sp(u,g,h,y,R){let v=await u.acquireLease(g,h.id);try{let P=await u.updateMachine(g,h.id,{config:{...y,...h.config?.mounts?.length?{mounts:h.config.mounts}:{}},...R!==void 0?{min_secrets_version:R}:{}},v);await u.waitForState(g,h.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(g,h.id,v)}}async function Ap(u,g,h,y){let R=y.find((P)=>P.region===h&&P.name===g.volume.name&&!P.attached_machine_id);if(R)return R.attached_machine_id="pending",R;let v=await u.createVolume(g.app,{name:g.volume.name,region:h,size_gb:g.volume.sizeGb});return y.push({...v,attached_machine_id:"pending"}),v}import{createHmac as Zl,createSign as Tp,timingSafeEqual as wp}from"node:crypto";function bi(u){let g=u instanceof Date?u.getTime():u;if(!Number.isFinite(g))throw TypeError("Media access timestamp must be finite");return Math.floor(g/1000)}function Zu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Ip(u){return Buffer.from(u).toString("base64url")}function Yu(u,g=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let h=g?u.replaceAll("*","wildcard"):u,y=new URL(h);if(!["http:","https:"].includes(y.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!g&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function ed(u,g){let h=Tp("RSA-SHA1");return h.update(u),h.end(),Zu(h.sign(g))}function td(u){Yu(u.resource,!0);let h={DateLessThan:{"AWS:EpochTime":bi(u.expiresAt)}};if(u.activeAt!==void 0)h.DateGreaterThan={"AWS:EpochTime":bi(u.activeAt)};if(u.ipAddress)h.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:h}]})}function WS(u,g,h){Yu(u);let y=bi(g),R=u.includes("?")?"&":"?",v=td({resource:u,expiresAt:g}),P=ed(v,h.privateKey);return`${u}${R}Expires=${y}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(h.keyPairId)}`}function zS(u,g){let h=td(u);return{"CloudFront-Key-Pair-Id":g.keyPairId,"CloudFront-Policy":Zu(Buffer.from(h)),"CloudFront-Signature":ed(h,g.privateKey)}}function jS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let g=Ip(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:bi(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),h=Zl("sha256",u.secret).update(g).digest("base64url");return`${g}.${h}`}function KS(u,g){let[h,y,R]=u.split(".");if(!h||!y||R)return null;let v=Zl("sha256",g.secret).update(h).digest(),P;try{P=Buffer.from(y,"base64url")}catch{return null}if(v.length!==P.length||!wp(v,P))return null;try{let L=JSON.parse(Buffer.from(h,"base64url").toString("utf8")),z=bi(g.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(g.resource&&L.resource!==g.resource)return null;if(g.audience&&L.audience!==g.audience)return null;return L}catch{return null}}function ZS(u,g=!1){let h=new URL(u,"https://media.invalid").pathname.toLowerCase(),y=/\.(?:m3u8|mpd|vtt|json)$/.test(h),R=/\.(?:key|license)$/.test(h)||h.includes("/keys/")||h.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":g&&(y||R)?"private, no-store":y?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function JS(u){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(u.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(u.region))throw TypeError("Media bucket region is invalid");let g=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",h=u.protected??!1,y="public, max-age=31536000, immutable",R=h?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:g,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.mpd",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.vtt",cacheControl:R,compress:!0,signed:h},{pathPattern:"*",cacheControl:y,compress:!1,signed:h}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class vp{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new al(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let g=this.config.environments[this.environment]?.infrastructure;if(!g)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...g,compute:{...this.config.infrastructure?.compute,...g.compute},storage:{...this.config.infrastructure?.storage,...g.storage},functions:{...this.config.infrastructure?.functions,...g.functions},servers:{...this.config.infrastructure?.servers,...g.servers},databases:{...this.config.infrastructure?.databases,...g.databases},cdn:{...this.config.infrastructure?.cdn,...g.cdn},sftp:g.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...g.queues},redirects:{...this.config.infrastructure?.redirects,...g.redirects},realtime:{...this.config.infrastructure?.realtime,...g.realtime},cache:{...this.config.infrastructure?.cache,...g.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...g.fileSystem},email:{...this.config.infrastructure?.email,...g.email},search:{...this.config.infrastructure?.search,...g.search},ai:{...this.config.infrastructure?.ai,...g.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let g=this.config.features||{};if(!u.requiresFeatures.every((y)=>g[y]===!0))return!1}if(u.regions){let g=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(g))return!1}if(u.condition&&typeof u.condition==="function")return u.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let u=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,g=Number(u||3008);return Number.isFinite(g)&&g>0?g:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(u,g){return u==="public"||g.routeCompute===!0}storageBucketName(u,g,h){return this.mergedConfig.infrastructure?.storage?.[h]?.bucket??`${u}-${g}-${h}`}fileSystemLogicalId(u,g,h){return t(r({slug:`${u}-${h}`,environment:g,resourceType:"efs"}))}resolveSftpStorage(u,g,h){let y=u.storage;if(y?.type==="efs"&&y.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[y.fileSystem])throw Error(`sftp: storage.fileSystem "${y.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(g,h,y.fileSystem)},posixProfile:y.posixProfile}}if(y?.type==="s3"&&y.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[y.storageBucket])throw Error(`sftp: storage.storageBucket "${y.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(g,h,y.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,g){return{PathPattern:u,TargetOriginId:g,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(u,g,h,y,R,v){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${y}-${R}-api`,he=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",fe=he==="us-east-1"?".compute-1.amazonaws.com":`.${he}.compute.amazonaws.com`,Ct={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},fe]]},It=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:Ct,CustomOriginConfig:{HTTPPort:It,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),h.push(P),L)h.push(L);for(let Ve of v)g.push(this.createComputeCacheBehavior(Ve,z))}buildCaddyfile(u){let g=u.filter(([,R])=>typeof R.domain==="string"&&R.domain&&typeof R.port==="number");if(g.length===0)return;let h=new Map;for(let[,R]of g){let v=h.get(R.domain)??[];v.push({port:R.port,path:R.path}),h.set(R.domain,v)}let y=[];for(let[R,v]of h){let L=[...v].sort((z,he)=>{let fe=!z.path||z.path==="/",Ct=!he.path||he.path==="/";if(fe&&!Ct)return 1;if(!fe&&Ct)return-1;return(he.path?.length??0)-(z.path?.length??0)}).map((z)=>{let he=!z.path||z.path==="/",fe=`reverse_proxy localhost:${z.port}`;return he?` handle {
|
|
1
|
+
import{$I,MI,rl,Sm,nl,il,dn,Q,l,sl,Im,K,ol,p,ry,C,Ze,Ji,ln,w,ce,al,ny,r,t,FI,UI,m,QI,HI,GI,VI,qI,lr,cl,Xi,iy,jI,zI,xe,et,dl,bm,Cm,KI,Em,vm,Tm,Ho,ll,de,un,kt,Go,Nt,Ce,sy,ul,Vo,wm,Rm,Dm,Pm,gl,WI,W,E,oy,ay,km,a,S,tt,f,Nm,rt,J,Bt,JI,Bm,X,pl,Oe,ur,qo,le,ml,ue,cy,jo,Y,Z,_,Yi,D,gr,xt,ee,e,gn,XI,xm,fl,YI,ZI,eb,tb,hl,rb,nb,ib,sb,ob,ab,cb,db,lb,ub,gb,pb,dy,ly,uy,gy,py,my,fy,pr,Om,_m,mr,Zi,mb,Lm,fb,hb,pn,Ab,yb,Sb,Ib,bb,Cb,hy,Ay,yy,Sy,Iy,es,Eb,zo,by,$m,V,Cy,nt,Ko,Ot,Ey,Mm,vy,Ty,wy,Fm,q,vb,Tb,wb,Rb,Ry,Db,te,Pb,kb,Nb,Al,yl,Dy,Um,Qm,Bb,xb,Ob,_b,Lb,Py,Sl,$b,Mb,Fb,Ub,Qb,ky,Ny,Hb,Gb,Vb,qb,jb,zb,Kb,By,Wb,Hm,Il,Jb,Xb,Yb,Zb,Gm,Vm,qm,eC,bl,xy,Oy,_y,Ly,Cl,$y,tC,rC,nC,iC,sC,oC,aC,My,Fy,Uy,Qy,jm,cC,dC,lC,uC,gC,pC,mC,fC,hC,Hy,Gy,Vy,qy,AC,yC,zm,SC,Km,Wm,Jm,Xm,IC,bC,CC,EC,_e,ts,vC,TC,wC,RC,DC,PC,kC,NC,jy,BC,xC,Ym,Zm,OC,_C,zy,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,KC,WC,JC,XC,YC,ZC,eE,tE,rE,El,Ky,vl,Wy,Tl,Jy,wl,Xy,Rl,Yy,fr,Zy,Dl,eS,rs,tS,Pl,rS,kl,nS,ef,nE,tf,iE,Nl,iS,hr,sS,rf,sE,Bl,oS,nf,oE,sf,aE,of,cE,xl,aS,af,dE,cf,lE,df,uE,lf,gE,Ol,cS,_l,dS,uf,pE,gf,mE,pf,fE,mf,hE,ff,AE,hf,yE,Ll,lS,Af,SE,yf,IE,Sf,bE,If,CE,bf,EE,Cf,vE,Ef,vf,Tf,wf,Rf,TE,Df,wE,Pf,RE,kf,DE,it,Nf,uS,Wo,$l,mn,gS,ns,Ar,Ml,Fl,pS,mS,Ul,Bf,Ql,xf,PE,kE,Jo,Xo,Yo,Hl,fn,Gl,Vl,is,Zo,ea,Of,fS,hS,AS,NE,_f,Lf,BE,yS,$f,SS,IS,bS,xE,Mf,hn,ql,Ff,OE,CS,ta,ra,jl,Uf,_E,zl,ES,Qf,LE,Hf,$E,Gf,ME}from"./chunk-t7qgvz8z.js";import{Kl,k,Wl,na,vS,Vf,TS,wS,RS,DS,PS,kS,NS,BS}from"./chunk-928z0h9b.js";import{da,qf,nu,LS,cs,iu,la,jf,zf,yn,ua,su,ot,ou,au,cu,ds,Sn,Kf,at,du,ga,pa,ma,lu,uu,gu,ls,fa,pu,In,us,ha,_t,Wf,mu,fu,Jf,hu,Aa,yr,Au,yu,Su,Iu,ct,Xf,bu,Sr,ya,Sa,Ia,gs,ps,bn,Cu,ms,ba,Ca,Cn,Eu,En,Yf,Zf,Lt,vn,Ea,eh,vu,Tu,va,wu,Ru,Du,$S,ge,Pu,MS,FS,fs,hs,US,Ee,th,$t,Le,$e,Mt,ku,Nu,Bu,xu,rh,nh,Ta,ih,sh,wa,Ou,_u,oh,pe,ah,Lu,ve,Ra,dt,Ft,Ut,Tn,As,$u,QS,ch,dh,lh,uh,Da,Pa,Mu,ka,wn,Na,Fu,ys,Uu,Ba,xa,Oa,_a,La,$a,Ma,Fa,Qu,Ir,Ua,Hu,Rn,Gu,Qa,Ha,Vu,br,Ga,Va,gh,HS,Ss,GS,VS,qS,qa,ja,qu,ph,za,Dn,ju,Is,zu,Ku,Wu,Ka,mh,Wa,Ju,fh,Ja,hh,Pn,kn,Xu,bs,ng,ag,cg,dg,lg,ug,Es,Cr,Ya,Nn,Bn,Er,lt,vh,ec,Th,wh,mg,tc,Ts,fg,rc,Ht,Fe,hg,nc,ic,Ag,sc,oc,ac,cc,yg,Sg,On,dc,lc,uc,gc,Ig,ws,_n,Rs,pc}from"./chunk-wy0bqg1v.js";import{ru}from"./chunk-fjs0wgyw.js";import{U,Kr,Ad,Ao,d,zp,Kp}from"./chunk-0cgrk9g3.js";import{Tt,hd,xi,Oi,_i,jp}from"./chunk-nxj8pwa7.js";import{rA,nA,iA,Rp,Dp,Pp,sA,kp,Np,oA,aA,Bp,cA,dA,md,xp,lA,uA,Op,gA,pA,mA,fA,hA,AA,yA,Bi,fd,_p,Lp,$p,Mp,Fp,Up,Qp,Hp,Gp,Vp,qp,SA,IA,bA,CA,EA,vA,TA}from"./chunk-dvma06m5.js";import{Je,yd,be,nr,Sd,x,ir,wt,Id,yo,DA,Wp,bd,s,Li,So,Wr,Cd,Ed,Jr,PA,vd,xI,OI,Io,_I,LI,Td,wd,$i,bo,ae,c,Co,Xe,Xr,kA,NA,Rd,BA,Eo,xA,OA,vo,Dd,Yr,To,_A,sr,Pd,Jp,or,Zr,LA,wo,$A,O,MA,kd,Xp,Ro,FA,UA,QA,Nd,Mi,Do,Bd,ar,Rt,HA,en,GA,xd,Yp,Zp,Po,Od,_d,Dt,em,Fi,Ld,ko,tn,tm,Ui,$d,Md,Qi,rm,Fd,Ud,Qd,Hd,No,nm,im,VA,sm,Gd,Hi,om,am,Bo,rn,xo,Oo,_o,Vd,cm,qd,Lo,qA,cr,jA,jd,nn,zd,zA,Kd,dm,Gi,sn,$o,Vi,Ye,KA,lm,um,dr,Wd,Jd,Xd,qi,ji,zi,WA,JA,Pt,Mo,XA,on,gm,Fo,YA,pm,mm,fm,ZA,hm,Am,ey,i,ty,Ki,Uo,Qo}from"./chunk-b6wsc7jp.js";import{n}from"./chunk-m9szynnf.js";import{Re,mt,zn}from"./chunk-v6s9k1mp.js";import{o}from"./chunk-c8kf2268.js";import{Te,Os,_s,Eg,yc,Sc,Ls,Ic,ut,re,gt,me,T,we,Un,bc,Ue,Cc,Qn,Hn,Gn,Gt,Vt,qt,Vn,Tr,Ec,wr,Rr,pt,qn,Tc,jt,Dr,jn,Rc,Dg,Pg,Dc,Pr}from"./chunk-tp37gyhc.js";import{ft,Ae,Ge,kg,zt,kc,Nc,Kt,H,Kn,Wt,Jt,Wn,Us,Qs,kr,Nr,Jn,Br,Hs,Gs,Vs,qs,ie,js,zs,Ks,Ws,ye,Js,Xs,Ys,N,Bc,Xn,xc,Se,xr}from"./chunk-8k44kaz0.js";import{ne}from"./chunk-nftqsker.js";import{Ng,Oc,Bg,De,_c,Yn,xg,Lc,Og,_g,Fh,_r,eo,M,$r,ei,ti,Mr,Ur,ri,to,ni,ii,si,oi,ci,Qr,Ie,Fc,At,Uc,Hr,Gc,qe,se,je,ze,St,ui,gi,Pe,bt,ke,mi,fi,hi,Ai,yi,Si,Ii,Gr,F,so,ap,Yc,Ci,Ei,vi,Ti,id,ao,sd,tr,Ri,co,lo,od,Di,ad}from"./chunk-p9cm5ynz.js";import{go,mo,fo,B,Ne}from"./chunk-w8sctn7m.js";import{Jl,ia,ss,os,sa,Xl,Yl,as,oa,aa,eu,tu,ca}from"./chunk-jx1zz1pw.js";import{mc,Ln,$n,Ds,Ps,ks,Ns,fc,hc}from"./chunk-z5c5amm1.js";import{Ac}from"./chunk-etv0rcjd.js";import{Pc,Qe,I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{b}from"./chunk-hg93a2g9.js";import{oe,Pi,uo,cd,ki,bp}from"./chunk-42vtybcm.js";import{qr,Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{Yd,an,Zd,el,tl,Wi,ym,cn}from"./chunk-84z2a1xn.js";import{xS,st}from"./chunk-9pwvnh3f.js";var jh="https://api.machines.dev/v1";class Cs extends Error{status;path;constructor(u,g,h){super(u);this.status=g;this.path=h;this.name="FlyApiError"}}function Qc(u){let g=u.ip.includes(":");if(g&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return g?"v6":"v4"}class hp{token;fetch;constructor(u){if(!u.token)throw Error("Fly.io needs an API token: set FLY_API_TOKEN (`fly tokens create deploy` makes one scoped to an app).");this.token=u.token,this.fetch=u.fetch??fetch}async rest(u,g,h={}){let y=new URL(`https://api.machines.dev/v1${g}`);for(let[L,z]of Object.entries(h.query??{}))y.searchParams.set(L,z);let R=await this.fetch(y,{method:u,headers:{Authorization:`Bearer ${this.token}`,...h.body!==void 0?{"Content-Type":"application/json"}:{},...h.headers},body:h.body===void 0?void 0:JSON.stringify(h.body)});if(R.status===404&&h.notFound==="null")return null;let v=await R.text(),P=v?yp(v):void 0;if(!R.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):v||R.statusText;throw new Cs(`Fly.io ${u} ${g} failed (${R.status}): ${L}`,R.status,g)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,g){return this.rest("POST","/apps",{body:{app_name:u,org_slug:g}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:g})}updateMachine(u,g,h,y){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}`,{body:h,headers:{"fly-machine-lease-nonce":y}})}async acquireLease(u,g,h=120){let R=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{body:{ttl:h}})).data?.nonce;if(!R)throw new Cs(`Fly.io gave no lease nonce for Machine ${g}`,200,`/machines/${g}/lease`);return R}async releaseLease(u,g,h){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/lease`,{headers:{"fly-machine-lease-nonce":h}})}async waitForState(u,g,h,y={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(g)}/wait`,{query:{state:h,timeout:String(y.timeoutSeconds??60),...y.instanceId?{instance_id:y.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...g,encrypted:!0}})}async setSecrets(u,g){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:g}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,g){let h=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:g}});if(!h.ip)throw new Cs(`Fly.io assigned no ${g} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:h.ip,shared:h.shared??g==="shared_v4",region:h.region}}async requestCertificate(u,g){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:g}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var vc="ts-cloud-role";function Zh(u,g){let h=u.fly??{},y=h.app??`${u.project.slug}-${g.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(y))throw Error(`"${y}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let R=h.internalPort??3000,v=h.count??1;if(!Number.isInteger(v)||v<1)throw Error(`fly.count must be a whole number of at least 1, got ${v}.`);return{app:y,org:h.org??"personal",image:g.image,regions:h.regions?.length?h.regions:["iad"],count:v,internalPort:R,healthPath:h.healthPath??"/",vm:{cpuKind:h.vm?.cpuKind??"shared",cpus:h.vm?.cpus??1,memoryMb:h.vm?.memoryMb??512},...h.volume?{volume:{name:h.volume.name??"data",sizeGb:h.volume.sizeGb,path:h.volume.path}}:{},autoStop:h.autoStop??!1,env:{...g.env,PORT:String(R)},secrets:g.secrets??{},hostnames:h.hostnames??[],release:g.release}}function Cp(u){return{image:u.image,env:u.env,guest:{cpu_kind:u.vm.cpuKind,cpus:u.vm.cpus,memory_mb:u.vm.memoryMb},services:[{protocol:"tcp",internal_port:u.internalPort,ports:[{port:80,handlers:["http"],force_https:!0},{port:443,handlers:["tls","http"]}],autostop:u.autoStop?"stop":"off",autostart:!0,...u.autoStop?{min_machines_running:0}:{},checks:[{type:"http",method:"GET",path:u.healthPath,interval:"15s",timeout:"5s",grace_period:"10s"}]}],restart:{policy:"on-failure",max_retries:10},metadata:{[vc]:"app","ts-cloud-release":u.release}}}async function Jh(u,g,h=()=>{}){let y=!1;if(!await u.getApp(g.app))h(`Creating Fly app ${g.app} in ${g.org}`),await u.createApp(g.app,g.org),y=!0;let R;if(Object.keys(g.secrets).length>0)R=await u.setSecrets(g.app,g.secrets),h(`Set ${Object.keys(g.secrets).length} secret(s) (version ${R})`);let v=await u.listIpAssignments(g.app),P=new Set(v.map(Qc));if(!P.has("v6"))v.push(await u.assignIp(g.app,"v6")),h("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))v.push(await u.assignIp(g.app,"shared_v4")),h("Assigned a shared IPv4");let L=Cp(g),z=(await u.listMachines(g.app)).filter((Me)=>{let We=Me.config?.metadata??{};if(We[vc])return We[vc]==="app";return!We.fly_process_group||We.fly_process_group==="app"}),he=g.volume?await u.listVolumes(g.app):[],fe=[],Ct=[],It=new Set;for(let Me of g.regions){let We=z.filter((j)=>j.region===Me).sort((j,ht)=>j.id.localeCompare(ht.id));for(let j=0;j<g.count;j++){let ht=We[j];if(ht){It.add(ht.id),await Sp(u,g.app,ht,L,R),Ct.push(ht.id),h(`Updated ${ht.id} (${Me}) to ${g.image}`);continue}let G=g.volume?[{volume:(await Ap(u,g,Me,he)).id,path:g.volume.path}]:void 0,Ke=await u.createMachine(g.app,{region:Me,name:`${g.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...R!==void 0?{min_secrets_version:R}:{}});await u.waitForState(g.app,Ke.id,"started",{instanceId:Ke.instance_id}),fe.push(Ke.id),h(`Created ${Ke.id} in ${Me}`)}}let Ve=[];for(let Me of g.hostnames)Ve.push(await u.requestCertificate(g.app,Me));return{app:g.app,url:`https://${g.app}.fly.dev`,createdApp:y,created:fe,updated:Ct,untouched:z.filter((Me)=>!It.has(Me.id)).map((Me)=>Me.id),ips:v,certificates:Ve}}async function Sp(u,g,h,y,R){let v=await u.acquireLease(g,h.id);try{let P=await u.updateMachine(g,h.id,{config:{...y,...h.config?.mounts?.length?{mounts:h.config.mounts}:{}},...R!==void 0?{min_secrets_version:R}:{}},v);await u.waitForState(g,h.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(g,h.id,v)}}async function Ap(u,g,h,y){let R=y.find((P)=>P.region===h&&P.name===g.volume.name&&!P.attached_machine_id);if(R)return R.attached_machine_id="pending",R;let v=await u.createVolume(g.app,{name:g.volume.name,region:h,size_gb:g.volume.sizeGb});return y.push({...v,attached_machine_id:"pending"}),v}import{createHmac as Zl,createSign as Tp,timingSafeEqual as wp}from"node:crypto";function bi(u){let g=u instanceof Date?u.getTime():u;if(!Number.isFinite(g))throw TypeError("Media access timestamp must be finite");return Math.floor(g/1000)}function Zu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function Ip(u){return Buffer.from(u).toString("base64url")}function Yu(u,g=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let h=g?u.replaceAll("*","wildcard"):u,y=new URL(h);if(!["http:","https:"].includes(y.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!g&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function ed(u,g){let h=Tp("RSA-SHA1");return h.update(u),h.end(),Zu(h.sign(g))}function td(u){Yu(u.resource,!0);let h={DateLessThan:{"AWS:EpochTime":bi(u.expiresAt)}};if(u.activeAt!==void 0)h.DateGreaterThan={"AWS:EpochTime":bi(u.activeAt)};if(u.ipAddress)h.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:h}]})}function WS(u,g,h){Yu(u);let y=bi(g),R=u.includes("?")?"&":"?",v=td({resource:u,expiresAt:g}),P=ed(v,h.privateKey);return`${u}${R}Expires=${y}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(h.keyPairId)}`}function zS(u,g){let h=td(u);return{"CloudFront-Key-Pair-Id":g.keyPairId,"CloudFront-Policy":Zu(Buffer.from(h)),"CloudFront-Signature":ed(h,g.privateKey)}}function jS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let g=Ip(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:bi(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),h=Zl("sha256",u.secret).update(g).digest("base64url");return`${g}.${h}`}function KS(u,g){let[h,y,R]=u.split(".");if(!h||!y||R)return null;let v=Zl("sha256",g.secret).update(h).digest(),P;try{P=Buffer.from(y,"base64url")}catch{return null}if(v.length!==P.length||!wp(v,P))return null;try{let L=JSON.parse(Buffer.from(h,"base64url").toString("utf8")),z=bi(g.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(g.resource&&L.resource!==g.resource)return null;if(g.audience&&L.audience!==g.audience)return null;return L}catch{return null}}function ZS(u,g=!1){let h=new URL(u,"https://media.invalid").pathname.toLowerCase(),y=/\.(?:m3u8|mpd|vtt|json)$/.test(h),R=/\.(?:key|license)$/.test(h)||h.includes("/keys/")||h.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":g&&(y||R)?"private, no-store":y?"public, max-age=5, s-maxage=30, stale-while-revalidate=30":"public, max-age=31536000, immutable","Cross-Origin-Resource-Policy":"cross-origin","X-Content-Type-Options":"nosniff"}}function JS(u){if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(u.bucket))throw TypeError("Media bucket is invalid");if(!/^[a-z0-9-]+$/.test(u.region))throw TypeError("Media bucket region is invalid");let g=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",h=u.protected??!1,y="public, max-age=31536000, immutable",R=h?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:g,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.mpd",cacheControl:R,compress:!0,signed:h},{pathPattern:"*.vtt",cacheControl:R,compress:!0,signed:h},{pathPattern:"*",cacheControl:y,compress:!1,signed:h}],responseHeaders:{"Access-Control-Allow-Headers":"Range, If-Range","Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"Accept-Ranges, Content-Length, Content-Range, ETag","X-Content-Type-Options":"nosniff"}}}class vp{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new al(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let g=this.config.environments[this.environment]?.infrastructure;if(!g)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...g,compute:{...this.config.infrastructure?.compute,...g.compute},storage:{...this.config.infrastructure?.storage,...g.storage},functions:{...this.config.infrastructure?.functions,...g.functions},servers:{...this.config.infrastructure?.servers,...g.servers},databases:{...this.config.infrastructure?.databases,...g.databases},cdn:{...this.config.infrastructure?.cdn,...g.cdn},sftp:g.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...g.queues},redirects:{...this.config.infrastructure?.redirects,...g.redirects},realtime:{...this.config.infrastructure?.realtime,...g.realtime},cache:{...this.config.infrastructure?.cache,...g.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...g.fileSystem},email:{...this.config.infrastructure?.email,...g.email},search:{...this.config.infrastructure?.search,...g.search},ai:{...this.config.infrastructure?.ai,...g.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let g=this.config.features||{};if(!u.requiresFeatures.every((y)=>g[y]===!0))return!1}if(u.regions){let g=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(g))return!1}if(u.condition&&typeof u.condition==="function")return u.condition(this.config,this.environment);return!0}resolveApiOriginPort(){let u=this.mergedConfig.infrastructure?.api?.port??this.mergedConfig.ports?.api,g=Number(u||3008);return Number.isFinite(g)&&g>0?g:3008}defaultComputeCachePathPatterns(){return["/api/*","/auth/*","/publisher/api/*","/publisher/*","/publish","/publish/*","/analytics/*","/packages/*","/npm/*","/zig/*","/php/*","/commits/*","/health","/dashboard/*","/search","/login","/logout","/signup","/account","/account/*"]}shouldRouteStorageBucketToCompute(u,g){return u==="public"||g.routeCompute===!0}storageBucketName(u,g,h){return this.mergedConfig.infrastructure?.storage?.[h]?.bucket??`${u}-${g}-${h}`}fileSystemLogicalId(u,g,h){return t(r({slug:`${u}-${h}`,environment:g,resourceType:"efs"}))}resolveSftpStorage(u,g,h){let y=u.storage;if(y?.type==="efs"&&y.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[y.fileSystem])throw Error(`sftp: storage.fileSystem "${y.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(g,h,y.fileSystem)},posixProfile:y.posixProfile}}if(y?.type==="s3"&&y.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[y.storageBucket])throw Error(`sftp: storage.storageBucket "${y.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(g,h,y.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,g){return{PathPattern:u,TargetOriginId:g,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac"}}appendComputeAppOrigin(u,g,h,y,R,v){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${y}-${R}-api`,he=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",fe=he==="us-east-1"?".compute-1.amazonaws.com":`.${he}.compute.amazonaws.com`,Ct={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},fe]]},It=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:Ct,CustomOriginConfig:{HTTPPort:It,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),h.push(P),L)h.push(L);for(let Ve of v)g.push(this.createComputeCacheBehavior(Ve,z))}buildCaddyfile(u){let g=u.filter(([,R])=>typeof R.domain==="string"&&R.domain&&typeof R.port==="number");if(g.length===0)return;let h=new Map;for(let[,R]of g){let v=h.get(R.domain)??[];v.push({port:R.port,path:R.path}),h.set(R.domain,v)}let y=[];for(let[R,v]of h){let L=[...v].sort((z,he)=>{let fe=!z.path||z.path==="/",Ct=!he.path||he.path==="/";if(fe&&!Ct)return 1;if(!fe&&Ct)return-1;return(he.path?.length??0)-(z.path?.length??0)}).map((z)=>{let he=!z.path||z.path==="/",fe=`reverse_proxy localhost:${z.port}`;return he?` handle {
|
|
2
2
|
${fe}
|
|
3
3
|
}`:` handle ${z.path} {
|
|
4
4
|
${fe}
|
package/dist/ui/404.html
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="
|
|
1
|
+
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="mvu20oqf5mvp1s"><meta name="title" content="stx Project"><meta name="description" content="A website built with stx templating engine"><meta property="og:title" content="stx Project"><meta property="og:description" content="A website built with stx templating engine"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="stx Project"><meta name="twitter:description" content="A website built with stx templating engine"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ts-cloud - Accept invitation</title><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="/_stx/style.448ab192.css"><style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.616c25f3.css"></head><body class="auth-page"><main class="auth-card" id="main-content"><a class="brand" href="/"><span class="dot"></span><span>ts-cloud</span></a><div><span class="context-label">Organization invitation</span><h1>Join your team</h1><p>Choose the dashboard username and password you will use after this invitation is accepted.</p></div><form id="accept-invitation-form" class="auth-form"><div class="field-block"><label for="invite-name">Name</label><input id="invite-name" name="name" autocomplete="name" placeholder="Chris Breuer"></div><div class="field-block"><label for="invite-username">Username</label><input id="invite-username" name="username" autocomplete="username" minlength="2" maxlength="32" required></div><div class="field-block"><label for="invite-password">Password</label><input id="invite-password" name="password" type="password" autocomplete="new-password" minlength="12" required><small>At least 12 characters.</small></div><button class="btn" type="submit">Accept invitation</button><div id="invitation-status" class="auth-status" role="status"></div></form><p class="note">If this link expired or was already used, ask an organization owner to resend the invitation.</p></main> <script data-stx-scoped data-stx-run="always">
|
|
2
2
|
;(function() {
|
|
3
3
|
'use strict';
|
|
4
4
|
(() => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="
|
|
1
|
+
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="mvu20oqf5mvp1s"><meta name="title" content="Access unavailable · ts-cloud"><meta name="description" content="A website built with stx templating engine"><meta property="og:title" content="Access unavailable · ts-cloud"><meta property="og:description" content="A website built with stx templating engine"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Access unavailable · ts-cloud"><meta name="twitter:description" content="A website built with stx templating engine"> <script data-stx-runtime src="/_stx/runtime.dbee66d1.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Access unavailable · ts-cloud</title><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="/_stx/style.448ab192.css"><style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.906ee17c.css"></head><body data-stx-auto><a data-stx-scope="stx_scope_nav_50" class="skip-link" href="#main-content">Skip to content</a><button class="nav-toggle-button" type="button" aria-label="Open navigation" aria-controls="primary-navigation" aria-expanded="false"><span></span><span></span><span></span></button><button class="nav-scrim" type="button" aria-label="Close navigation"></button><aside class="app-sidebar" id="primary-navigation" aria-label="Primary navigation"><a class="brand" href="/?env=production"><span class="dot"></span><span>ts-cloud</span></a><div class="sidebar-context"><span class="context-label">Project</span><strong>ts-cloud</strong></div><div class="environment-picker" aria-label="Environment"><span class="context-label">Environment</span><details><summary class="environment-current production"><span>PROD</span><strong>production</strong></summary></details></div><button class="command-trigger" type="button" aria-keyshortcuts="Meta+K Control+K"><span>Search resources</span><kbd>⌘ K</kbd></button><div class="nav-groups"><section class="nav-group"><h2>Overview</h2><a class="" href="/?env=production">Dashboard</a><a href="/server/activity?env=production">Activity</a></section><section class="nav-group"><h2>Applications</h2><a class="" href="/server/sites?env=production">Services</a><a class="" href="/server/deployments?env=production">Deployments</a><a class="" href="/server/logs?env=production">Logs</a><a class="" href="/integrations?env=production">Git integrations</a><a class="" href="/applications/new?env=production">Create application</a><a class="" href="/applications/compose?env=production">Compose applications</a></section><section class="nav-group"><h2>Operations</h2><a class="" href="/operations/queue?env=production">Deployment queue</a><a class="" href="/operations/previews?env=production">Preview environments</a><a class="" href="/operations/releases?env=production">Releases & promotion</a><a class="" href="/operations/regions?env=production">Regions & failover</a><a class="" href="/operations/maintenance?env=production">Maintenance & DR</a><a class="" href="/operations/workloads?env=production">Workloads</a><a class="" href="/operations/observability?env=production">Observability</a><a class="" href="/operations/alerts?env=production">Alerts & health</a><a class="" href="/operations/spend?env=production">Spend & budgets</a><a href="/server/metrics?env=production">Metrics</a><a href="/server/services?env=production">Runtime services</a><a class="" href="/operations/jobs?env=production">Workers & schedules</a><a class="" href="/operations/configuration?env=production">Environment & secrets</a><a class="" href="/data/backups?env=production">Backups & recovery</a><a class="" href="/data/volumes?env=production">Persistent volumes</a><a href="/server/actions?env=production">Run operations</a></section><section class="nav-group"><h2>Infrastructure</h2><a class="" href="/infrastructure/topology?env=production">Infrastructure map</a><a class="" href="/data/services?env=production">Data services</a><a class="" href="/data/volumes?env=production">Persistent volumes</a><a href="/server/firewall?env=production">Network & firewall</a><a href="/server/ssh-keys?env=production">SSH keys</a><a class="" href="/server/fleet?env=production">Fleet inventory</a><a class="" href="/server/capacity?env=production">Capacity & placement</a><a href="/security?env=production">Security posture</a><a href="/server/terminal?env=production">Terminal</a></section><section class="nav-group"><h2>Organization</h2><a class="" href="/server/team?env=production">People & access</a><a class="" href="/account/automation?env=production">API & automation</a></section><section class="nav-group"><h2>Account</h2><a class="" href="/account/security?env=production">Sign-in & security</a></section></div><form method="post" action="/api/logout" class="signout"><button type="submit">Sign out</button></form></aside><dialog class="command-palette" aria-labelledby="command-title"><div class="command-search"><span aria-hidden="true">⌕</span><input type="search" placeholder="Search services, domains, deployments…" aria-label="Search resources" autocomplete="off"><button type="button" class="command-close" aria-label="Close search">Esc</button></div><h2 id="command-title" class="sr-only">Search resources and navigation</h2><div class="command-status" role="status">Start typing to search this project.</div><section class="saved-views" aria-labelledby="saved-views-title"><div class="saved-views-heading"><h3 id="saved-views-title">Saved views</h3><form class="save-view-form"><label class="sr-only" for="save-view-name">Saved view name</label><input id="save-view-name" maxlength="64" placeholder="Name this view" autocomplete="off"><button type="submit">Save current filters</button></form></div><div class="saved-view-list"></div></section><form class="tag-result-form"><label for="tag-result-name">Tag selected resource</label><input id="tag-result-name" maxlength="32" placeholder="customer-facing" pattern="[A-Za-z0-9][A-Za-z0-9 -]{0,31}" autocomplete="off"><input class="tag-color" type="color" value="#5a8be0" aria-label="Tag color"><button type="submit">Add tag</button></form><div class="command-results" role="listbox" aria-label="Search results"></div><footer><span>↑ ↓ navigate</span><span>Enter open</span><span>Esc close</span></footer></dialog><div class="context-bar" aria-label="Current scope"><div class="context-path"><div class="context-breadcrumb"><span>ts-cloud</span><i>/</i><strong>production</strong></div><div class="context-filters" aria-label="Active filters"></div></div><span class="scope-safety production">Production scope</span></div> <script data-stx-scoped data-stx-run="always">
|
|
2
2
|
(function() {
|
|
3
3
|
var { batch, computed, configureFetch, defineEmits, defineExpose, definePageMeta, defineProps, defineSlots, defineStore, derived, effect, goBack, goForward, inject, invalidateRoute, isDerived, isSignal, navigate, nextTick, onBeforeMount, onBeforeUnmount, onDestroy, onMount, onMounted, onUnmounted, peek, provide, reactive, ref, refresh, registerStoresClient, setRouteParams, state, untrack, useAsync, useClickOutside, useColorMode, useCookie, useCounter, useDark, useDebounce, useDebouncedValue, useEventListener, useFetch, useFocus, useHead, useId, useInterval, useLocalStorage, useMediaQuery, useMutation, useOptimistic, usePreferredContrast, usePreferredDark, usePreferredLight, usePreferredReducedMotion, useQuery, useReactiveProp, useRef, useRoute, useRouteParam, useRouteParams, useScrollLock, useSearchParams, useSeoMeta, useSessionStorage, useSlots, useStore, useThrottle, useTimeout, useToggle, useWebSocket, watch, watchEffect, watchMultiple, withDefaults } = window.stx;
|
|
4
4
|
var __destroyHooks = [];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="
|
|
2
|
-
function
|
|
1
|
+
<!DOCTYPE html><html lang="en" data-theme="dark"><head><meta charset="UTF-8"><meta name="stx-build" content="mvu20oqf5mvp1s"><meta name="title" content="stx Project"><meta name="description" content="A website built with stx templating engine"><meta property="og:title" content="stx Project"><meta property="og:description" content="A website built with stx templating engine"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="stx Project"><meta name="twitter:description" content="A website built with stx templating engine"> <script data-stx-runtime src="/_stx/runtime.dbee66d1.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ts-cloud - API & automation</title><link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='3' y='3' width='26' height='26' rx='8' fill='%235a8be0'/%3E%3C/svg%3E"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="/_stx/style.448ab192.css"> <script data-stx-scoped>
|
|
2
|
+
function __stx_setup_1793309239015_6() {
|
|
3
3
|
const { batch, computed, configureFetch, defineEmits, defineExpose, definePageMeta, defineProps, defineSlots, defineStore, derived, effect, goBack, goForward, inject, invalidateRoute, isDerived, isSignal, navigate, nextTick, onBeforeMount, onBeforeUnmount, onDestroy, onMount, onMounted, onUnmounted, peek, provide, reactive, ref, refresh, registerStoresClient, setRouteParams, state, untrack, useAsync, useClickOutside, useColorMode, useCookie, useCounter, useDark, useDebounce, useDebouncedValue, useEventListener, useFetch, useFocus, useHead, useId, useInterval, useLocalStorage, useMediaQuery, useMutation, useOptimistic, usePreferredContrast, usePreferredDark, usePreferredLight, usePreferredReducedMotion, useQuery, useReactiveProp, useRef, useRoute, useRouteParam, useRouteParams, useScrollLock, useSearchParams, useSeoMeta, useSessionStorage, useSlots, useStore, useThrottle, useTimeout, useToggle, useWebSocket, watch, watchEffect, watchMultiple, withDefaults } = window.stx;
|
|
4
4
|
|
|
5
5
|
const accounts = state([]);
|
|
@@ -189,9 +189,9 @@ onMount(() => {
|
|
|
189
189
|
|
|
190
190
|
return { accounts, project, environments, resources, message, messageKind, reveal, accountSlug, accountName, accountRole, accountScopeType, accountScopeId, selectedAccount, tokenName, tokenCapabilities, tokenScopeType, tokenScopeId, tokenExpiry, password, mfaCode, capabilities, setMessage, setScope, scopeLabel, tokenState, toggleCapability, load, selectAccount, stepUp, createAccount, createToken, tokenAction, disableAccount, curlExample, cliExample, copy };
|
|
191
191
|
}
|
|
192
|
-
window.__stx_latestSetup=
|
|
193
|
-
if(window.stx)window.stx._latestSetup=
|
|
194
|
-
</script> <style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.906ee17c.css"></head><body data-stx="
|
|
192
|
+
window.__stx_latestSetup=__stx_setup_1793309239015_6;
|
|
193
|
+
if(window.stx)window.stx._latestSetup=__stx_setup_1793309239015_6;
|
|
194
|
+
</script> <style data-stx-cloak>[x-cloak]{display:none !important}</style><link data-crosswind="generated" rel="stylesheet" href="/_stx/crosswind.906ee17c.css"></head><body data-stx="__stx_setup_1793309239015_6"><a data-stx-scope="stx_scope_nav_9" class="skip-link" href="#main-content">Skip to content</a><button class="nav-toggle-button" type="button" aria-label="Open navigation" aria-controls="primary-navigation" aria-expanded="false"><span></span><span></span><span></span></button><button class="nav-scrim" type="button" aria-label="Close navigation"></button><aside class="app-sidebar" id="primary-navigation" aria-label="Primary navigation"><a class="brand" href="/?env=production"><span class="dot"></span><span>ts-cloud</span></a><div class="sidebar-context"><span class="context-label">Project</span><strong>ts-cloud</strong></div><div class="environment-picker" aria-label="Environment"><span class="context-label">Environment</span><details><summary class="environment-current production"><span>PROD</span><strong>production</strong></summary></details></div><button class="command-trigger" type="button" aria-keyshortcuts="Meta+K Control+K"><span>Search resources</span><kbd>⌘ K</kbd></button><div class="nav-groups"><section class="nav-group"><h2>Overview</h2><a class="" href="/?env=production">Dashboard</a><a href="/server/activity?env=production">Activity</a></section><section class="nav-group"><h2>Applications</h2><a class="" href="/server/sites?env=production">Services</a><a class="" href="/server/deployments?env=production">Deployments</a><a class="" href="/server/logs?env=production">Logs</a><a class="" href="/integrations?env=production">Git integrations</a><a class="" href="/applications/new?env=production">Create application</a><a class="" href="/applications/compose?env=production">Compose applications</a></section><section class="nav-group"><h2>Operations</h2><a class="" href="/operations/queue?env=production">Deployment queue</a><a class="" href="/operations/previews?env=production">Preview environments</a><a class="" href="/operations/releases?env=production">Releases & promotion</a><a class="" href="/operations/regions?env=production">Regions & failover</a><a class="" href="/operations/maintenance?env=production">Maintenance & DR</a><a class="" href="/operations/workloads?env=production">Workloads</a><a class="" href="/operations/observability?env=production">Observability</a><a class="" href="/operations/alerts?env=production">Alerts & health</a><a class="" href="/operations/spend?env=production">Spend & budgets</a><a href="/server/metrics?env=production">Metrics</a><a href="/server/services?env=production">Runtime services</a><a class="" href="/operations/jobs?env=production">Workers & schedules</a><a class="" href="/operations/configuration?env=production">Environment & secrets</a><a class="" href="/data/backups?env=production">Backups & recovery</a><a class="" href="/data/volumes?env=production">Persistent volumes</a><a href="/server/actions?env=production">Run operations</a></section><section class="nav-group"><h2>Infrastructure</h2><a class="" href="/infrastructure/topology?env=production">Infrastructure map</a><a class="" href="/data/services?env=production">Data services</a><a class="" href="/data/volumes?env=production">Persistent volumes</a><a href="/server/firewall?env=production">Network & firewall</a><a href="/server/ssh-keys?env=production">SSH keys</a><a class="" href="/server/fleet?env=production">Fleet inventory</a><a class="" href="/server/capacity?env=production">Capacity & placement</a><a href="/security?env=production">Security posture</a><a href="/server/terminal?env=production">Terminal</a></section><section class="nav-group"><h2>Organization</h2><a class="" href="/server/team?env=production">People & access</a><a class="active" href="/account/automation?env=production">API & automation</a></section><section class="nav-group"><h2>Account</h2><a class="" href="/account/security?env=production">Sign-in & security</a></section></div><form method="post" action="/api/logout" class="signout"><button type="submit">Sign out</button></form></aside><dialog class="command-palette" aria-labelledby="command-title"><div class="command-search"><span aria-hidden="true">⌕</span><input type="search" placeholder="Search services, domains, deployments…" aria-label="Search resources" autocomplete="off"><button type="button" class="command-close" aria-label="Close search">Esc</button></div><h2 id="command-title" class="sr-only">Search resources and navigation</h2><div class="command-status" role="status">Start typing to search this project.</div><section class="saved-views" aria-labelledby="saved-views-title"><div class="saved-views-heading"><h3 id="saved-views-title">Saved views</h3><form class="save-view-form"><label class="sr-only" for="save-view-name">Saved view name</label><input id="save-view-name" maxlength="64" placeholder="Name this view" autocomplete="off"><button type="submit">Save current filters</button></form></div><div class="saved-view-list"></div></section><form class="tag-result-form"><label for="tag-result-name">Tag selected resource</label><input id="tag-result-name" maxlength="32" placeholder="customer-facing" pattern="[A-Za-z0-9][A-Za-z0-9 -]{0,31}" autocomplete="off"><input class="tag-color" type="color" value="#5a8be0" aria-label="Tag color"><button type="submit">Add tag</button></form><div class="command-results" role="listbox" aria-label="Search results"></div><footer><span>↑ ↓ navigate</span><span>Enter open</span><span>Esc close</span></footer></dialog><div class="context-bar" aria-label="Current scope"><div class="context-path"><div class="context-breadcrumb"><span>ts-cloud</span><i>/</i><strong>production</strong></div><div class="context-filters" aria-label="Active filters"></div></div><span class="scope-safety production">Production scope</span></div> <script data-stx-scoped data-stx-run="always">
|
|
195
195
|
(function() {
|
|
196
196
|
var { batch, computed, configureFetch, defineEmits, defineExpose, definePageMeta, defineProps, defineSlots, defineStore, derived, effect, goBack, goForward, inject, invalidateRoute, isDerived, isSignal, navigate, nextTick, onBeforeMount, onBeforeUnmount, onDestroy, onMount, onMounted, onUnmounted, peek, provide, reactive, ref, refresh, registerStoresClient, setRouteParams, state, untrack, useAsync, useClickOutside, useColorMode, useCookie, useCounter, useDark, useDebounce, useDebouncedValue, useEventListener, useFetch, useFocus, useHead, useId, useInterval, useLocalStorage, useMediaQuery, useMutation, useOptimistic, usePreferredContrast, usePreferredDark, usePreferredLight, usePreferredReducedMotion, useQuery, useReactiveProp, useRef, useRoute, useRouteParam, useRouteParams, useScrollLock, useSearchParams, useSeoMeta, useSessionStorage, useSlots, useStore, useThrottle, useTimeout, useToggle, useWebSocket, watch, watchEffect, watchMultiple, withDefaults } = window.stx;
|
|
197
197
|
var __destroyHooks = [];
|
|
@@ -542,6 +542,6 @@ if(window.stx)window.stx._latestSetup=__stx_setup_1793308571746_6;
|
|
|
542
542
|
|
|
543
543
|
|
|
544
544
|
try { if (typeof __stxScopeRenames !== 'undefined' && __stxScopeRenames) { for (var __stxRK in __stxScopeRenames) __scopeRegistration[__stxRK] = __stxScopeRenames[__stxRK]; } } catch (e) { /* no renames */ }
|
|
545
|
-
window.stx._scopes['
|
|
545
|
+
window.stx._scopes['stx_scope_nav_9'] = __scopeRegistration;
|
|
546
546
|
})();
|
|
547
547
|
</script> <div class="wrap"><div class="crumbs"><a href="/">Dashboard</a><span class="sep">/</span> Organization <span class="sep">/</span> API & automation</div><header class="page"><div><h1>API & automation</h1><p>Create least-privilege machine identities for CI. Tokens never create browser sessions and cannot access outside their membership and token scope.</p></div><a class="btn ghost" href="/api/v1/openapi.json">OpenAPI 3.1</a></header><div class="automation-message msg" :class="messageKind()" role="status" aria-live="polite" x-cloak>{{ message() }}</div><div class="panel reveal" @show="!!reveal()" x-cloak><div><strong>Copy this token now</strong><span>The raw secret is shown once. Rotation keeps the old token active until you explicitly revoke it.</span></div><code x-cloak>{{ reveal()?.secret }}</code><button class="btn sm" type="button" @click="copy(reveal()?.secret)">Copy token</button><label>curl</label><code x-cloak>{{ curlExample() }}</code><button class="btn ghost sm" type="button" @click="copy(curlExample())">Copy curl</button><label>CLI</label><code x-cloak>{{ cliExample() }}</code><button class="btn ghost sm" type="button" @click="copy(cliExample())">Copy CLI</button><button class="btn danger sm" type="button" @click="reveal.set(null)">I saved it; hide secret</button></div><div class="section"><h2>Service accounts</h2><div class="accounts" x-cloak><template :for="item in accounts()"><article class="account panel" :class="selectedAccount() === item.account.id ? 'selected' : ''" x-cloak><button class="account-main" type="button" @click="selectAccount(item)" x-cloak><span x-cloak><strong x-cloak>{{ item.account.name }}</strong><small x-cloak>{{ item.account.slug }} · {{ item.membership?.roleTemplate }} · {{ scopeLabel(item.membership?.scope) }}</small><small x-cloak>Created {{ new Date(item.account.createdAt).toLocaleDateString() }} by {{ item.createdBy?.displayName || 'offline administrator' }}</small></span><span class="tag" x-cloak>{{ item.account.state }}</span></button><div class="token-list" x-cloak><template :for="token in item.tokens"><div class="token" x-cloak><div x-cloak><strong x-cloak>{{ token.name }}</strong><code x-cloak>{{ token.prefix }}</code><small x-cloak>{{ tokenState(token) }} · created {{ new Date(token.createdAt).toLocaleDateString() }} by {{ token.createdBy?.displayName || 'offline administrator' }} · expires {{ new Date(token.expiresAt).toLocaleDateString() }} · last used {{ token.lastUsedAt ? new Date(token.lastUsedAt).toLocaleString() : 'never' }}</small><small x-cloak>{{ token.capabilities.join(', ') }} · {{ scopeLabel(token.scope) }}</small></div><div class="table-actions"><button class="btn ghost sm" type="button" @show="token.state === 'active'" @click="tokenAction(token, 'rotate')" x-cloak>Rotate</button><button class="btn danger sm" type="button" @show="token.state === 'active'" @click="tokenAction(token, 'revoke')" x-cloak>Revoke</button></div></div></template><div class="compact empty" @show="item.tokens.length === 0" x-cloak><span>No tokens yet.</span></div></div><button class="btn danger sm" type="button" @show="item.account.state === 'active'" @click="disableAccount(item)" x-cloak>Disable account and tokens</button></article></template><div class="compact empty panel" @show="accounts().length === 0" x-cloak><strong>No service accounts</strong><span>Create one for a CI system or external automation.</span></div></div></div><div class="section"><h2>Create service account</h2><div class="panel"><form class="form-grid" @submit.prevent="createAccount()"><div class="field-block"><label for="account-name">Name</label><input id="account-name" :value="accountName()" @input="accountName.set($event.target.value)" placeholder="Production CI" required></div><div class="field-block"><label for="account-slug">Slug</label><input id="account-slug" :value="accountSlug()" @input="accountSlug.set($event.target.value)" pattern="[a-z0-9][a-z0-9-]{1,47}" placeholder="production-ci" required></div><div class="field-block"><label for="account-role">Maximum role</label><select id="account-role" :value="accountRole()" @change="accountRole.set($event.target.value)"><option value="viewer">Viewer</option><option value="auditor">Auditor</option><option value="deployer">Deployer</option><option value="operator">Operator</option><option value="admin">Admin</option></select><small>Service accounts can never be owners.</small></div><div class="field-block"><label for="account-scope">Maximum scope</label><select id="account-scope" :value="accountScopeType()" @change="accountScopeType.set($event.target.value); setScope($event.target.value, accountScopeId)"><option value="organization">Organization</option><option value="project">Current project</option><option value="environment">One environment</option><option value="resource">One service</option></select></div><div class="field-block" @show="accountScopeType() === 'environment'" x-cloak><label for="account-environment">Environment</label><select id="account-environment" :value="accountScopeId()" @change="accountScopeId.set($event.target.value)"><template :for="environment in environments()"><option :value="environment.id">{{ environment.name }}</option></template></select></div><div class="field-block" @show="accountScopeType() === 'resource'" x-cloak><label for="account-resource">Service</label><select id="account-resource" :value="accountScopeId()" @change="accountScopeId.set($event.target.value)"><template :for="resource in resources()"><option :value="resource.id">{{ resource.name }}</option></template></select></div><div class="form-actions"><button class="btn" type="submit">Create service account</button></div></form></div></div><div class="section"><h2>Create API token</h2><div class="panel"><form class="form-grid" @submit.prevent="createToken()"><div class="field-block"><label for="token-account">Service account</label><select id="token-account" :value="selectedAccount()" @change="selectAccount(accounts().find(item => item.account.id === $event.target.value))" required><template :for="item in accounts()"><option :value="item.account.id" :disabled="item.account.state !== 'active'">{{ item.account.name }}</option></template></select></div><div class="field-block"><label for="token-name">Token name</label><input id="token-name" :value="tokenName()" @input="tokenName.set($event.target.value)" required></div><div class="field-block"><label for="token-expiry">Expiry</label><input id="token-expiry" type="date" :value="tokenExpiry()" @input="tokenExpiry.set($event.target.value)"><small>Defaults to 90 days; maximum one year.</small></div><div class="field-block"><label for="token-scope">Token scope</label><select id="token-scope" :value="tokenScopeType()" @change="tokenScopeType.set($event.target.value); setScope($event.target.value, tokenScopeId)"><option value="organization">Organization</option><option value="project">Current project</option><option value="environment">One environment</option><option value="resource">One service</option></select><small>Must be equal to or narrower than the service-account scope.</small></div><div class="field-block" @show="tokenScopeType() === 'environment'" x-cloak><label>Environment</label><select :value="tokenScopeId()" @change="tokenScopeId.set($event.target.value)"><template :for="environment in environments()"><option :value="environment.id">{{ environment.name }}</option></template></select></div><div class="field-block" @show="tokenScopeType() === 'resource'" x-cloak><label>Service</label><select :value="tokenScopeId()" @change="tokenScopeId.set($event.target.value)"><template :for="resource in resources()"><option :value="resource.id">{{ resource.name }}</option></template></select></div><fieldset class="capabilities"><legend>Explicit capabilities</legend><template :for="capability in capabilities"><label class="capability" x-cloak><input type="checkbox" :checked="tokenCapabilities().includes(capability[0])" @change="toggleCapability(capability[0])"><span x-cloak><b x-cloak>{{ capability[0] }}</b><small x-cloak>{{ capability[1] }}</small></span></label></template></fieldset><div class="form-actions"><button class="btn" type="submit" :disabled="!selectedAccount() || tokenCapabilities().length === 0">Create and reveal token</button></div></form></div></div><div class="section"><h2>Confirm sensitive changes</h2><div class="auth-grid panel"><div class="field-block"><label for="automation-password">Your password</label><input id="automation-password" type="password" autocomplete="current-password" :value="password()" @input="password.set($event.target.value)" required></div><div class="field-block"><label for="automation-code">Authenticator or recovery code</label><input id="automation-code" autocomplete="one-time-code" :value="mfaCode()" @input="mfaCode.set($event.target.value)"><small>Required when MFA is enabled. Used only for recent-auth confirmation.</small></div></div></div></div><style> .automation-message{min-height:20px;margin-top:12px}.accounts{display:grid;gap:12px}.account{display:grid;gap:14px}.account.selected{border-color:var(--accent)} .account-main{display:flex;justify-content:space-between;gap:12px;width:100%;text-align:left;background:none;border:0;color:inherit;cursor:pointer}.account-main span:first-child{display:grid;gap:4px}.account-main small,.token small{color:var(--txt3);font-size:12px;line-height:1.5} .token-list{display:grid;gap:10px}.token{display:flex;justify-content:space-between;gap:14px;padding:12px;border:1px solid var(--panel-br);border-radius:10px}.token>div:first-child{display:grid;gap:4px;min-width:0}.token code{color:var(--txt2)} .reveal{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;margin-top:18px;border-color:rgba(53,209,155,.35)}.reveal>div,.reveal>code,.reveal>label{grid-column:1/-1}.reveal>div{display:grid;gap:4px}.reveal span{color:var(--txt2);font-size:12px}.reveal code{padding:10px;background:rgba(0,0,0,.25);border-radius:8px;overflow-wrap:anywhere;user-select:all} .capabilities{grid-column:1/-1;border:1px solid var(--panel-br);border-radius:10px;padding:12px;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.capabilities legend{padding:0 6px;color:var(--txt3);font-size:11px;font-weight:800;text-transform:uppercase}.capability{display:flex;gap:9px;align-items:flex-start;padding:9px}.capability input{width:auto;margin-top:3px}.capability span{display:grid;gap:2px}.capability small{color:var(--txt3);font-size:11px}.auth-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px} @media(max-width:700px){.token{display:grid}.reveal,.capabilities,.auth-grid{grid-template-columns:1fr}.reveal>*{grid-column:1}} </style></body></html>
|