@stacksjs/ts-cloud 0.16.54 → 0.16.55
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-z3f0k8jt.js → chunk-3hnczw70.js} +83 -83
- package/dist/bin/{chunk-9de905c6.js → chunk-akv3qkam.js} +1 -1
- package/dist/bin/{chunk-gqyfa360.js → chunk-fw1j79zq.js} +1 -1
- package/dist/bin/cli.js +4 -4
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/{chunk-b11w48de.js → chunk-fdr2cr9r.js} +3 -3
- package/dist/{chunk-07z9bps2.js → chunk-m0vnrgdz.js} +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- 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 +5 -5
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +6 -6
- package/dist/ui/operations/observability.html +5 -5
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +6 -6
- package/dist/ui/operations/regions.html +6 -6
- package/dist/ui/operations/releases.html +5 -5
- 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 +5 -5
- package/dist/ui/server/activity.html +1 -1
- 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 +2 -2
- 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 +5 -5
- package/package.json +3 -3
|
@@ -145,10 +145,10 @@ ${k}
|
|
|
145
145
|
`).map((Y)=>Y.trim().split(/\s+/)[0]).filter(Boolean),D={};if(P.length){let Y=v("systemctl",["show",...P,"-p","Id","-p","MainPID","-p","WorkingDirectory"]);for(let X of Y.split(`
|
|
146
146
|
|
|
147
147
|
`)){let J=Object.fromEntries(X.split(`
|
|
148
|
-
`).filter(Boolean).map((E)=>{let K=E.indexOf("=");return[E.slice(0,K),E.slice(K+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))D[J.Id]=Number(J.MainPID)}}let N=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let E=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";N.set(`${J.to}${E}`,{domain:J.to,path:E})}}let R=[...N.values()],q=[],k=0;return await Promise.all(Array.from({length:Math.min(8,R.length)},async()=>{while(k<R.length){let Y=R[k++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[J,,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),K=Number(J);q.push({...Y,status:K,ok:E===0&&K>=200&&K<500})}})),{routes:q.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:D}},ge=()=>{let P=[x.mountPath,...C.entries.map((N)=>N.source)],D=new Set(["rpx-gateway.service"
|
|
148
|
+
`).filter(Boolean).map((E)=>{let K=E.indexOf("=");return[E.slice(0,K),E.slice(K+1)]}));if(J.WorkingDirectory?.startsWith(`${e.webRoot}/`)||/^(?:mail|rpx-gateway|postgresql|mysql|redis)[@.]/.test(J.Id??""))D[J.Id]=Number(J.MainPID)}}let N=new Map;if(r.existsSync("/etc/rpx/sites.d"))for(let Y of r.readdirSync("/etc/rpx/sites.d").filter((X)=>X.endsWith(".json"))){let X=JSON.parse(r.readFileSync(n.join("/etc/rpx/sites.d",Y),"utf8"));for(let J of X.proxies??[]){if(typeof J.to!=="string"||!/^[a-zA-Z0-9.-]+$/.test(J.to))continue;let E=typeof J.path==="string"&&J.path.startsWith("/")?J.path:"/";N.set(`${J.to}${E}`,{domain:J.to,path:E})}}let R=[...N.values()],q=[],k=0;return await Promise.all(Array.from({length:Math.min(8,R.length)},async()=>{while(k<R.length){let Y=R[k++],X=Bun.spawn(["curl","-sS","--max-time","12","--output","/dev/null","--write-out","%{http_code}","--resolve",`${Y.domain}:443:127.0.0.1`,`https://${Y.domain}${Y.path}`],{stdout:"pipe",stderr:"pipe"}),[J,,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text(),X.exited]),K=Number(J);q.push({...Y,status:K,ok:E===0&&K>=200&&K<500})}})),{routes:q.sort((Y,X)=>`${Y.domain}${Y.path}`.localeCompare(`${X.domain}${X.path}`)),services:D}},ge=()=>{let P=[x.mountPath,...C.entries.map((N)=>N.source)],D=new Set(["rpx-gateway.service",...A?.dependentUnits??[]]);for(let N of r.readdirSync("/etc/systemd/system")){if(!N.endsWith(".service"))continue;try{if(r.readFileSync(`/etc/systemd/system/${N}`,"utf8").includes(e.webRoot))D.add(N)}catch{}}for(let N of D){let R=`/etc/systemd/system/${N}.d`;r.mkdirSync(R,{recursive:!0}),r.writeFileSync(`${R}/ts-cloud-storage.conf`,`[Unit]
|
|
149
149
|
RequiresMountsFor=${P.join(" ")}
|
|
150
|
-
`)}v("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let P=m("/etc/ts-cloud/compute-storage.json",null);if(P){for(let E of P.volumes)if(!e.volumes.some((K)=>K.id===E.id&&K.key===E.key&&K.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(
|
|
151
|
-
`).at(-1)?.split(/\s+/)[0],K=r.statfsSync(x.mountPath);if(Number(E)>K.bavail*K.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!S("/run/ts-cloud-root-web"))v("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);for(let E=0;E<D.length;E++){if(S(D[E].source)&&y(D[E].source,D[E].destination))continue;console.log(`copy ${E+1}/${D.length}: ${D[E].source}`),await ne(D[E],!1)}for(let E of[
|
|
150
|
+
`)}v("systemctl",["daemon-reload"])};try{Z("/run/lock/ts-cloud-compute-storage.lock"),C=m("/var/lib/ts-cloud/compute-storage-state.json",{entries:[]});let P=m("/etc/ts-cloud/compute-storage.json",null);if(P){for(let E of P.volumes)if(!e.volumes.some((K)=>K.id===E.id&&K.key===E.key&&K.mountPath===E.mountPath))throw Error(`Refusing to remove or relocate managed volume ${E.name}; migrate its data explicitly first`);if(C.entries.length&&(P.deploymentStorage?.volume!==A?.volume||P.deploymentStorage?.includeBackups!==!1!==(A?.includeBackups!==!1)))throw Error("Refusing to change an active deployment-storage policy; migrate its data explicitly first")}if(u==="apply")V();for(let E of e.volumes)if(!O(E))throw Error(`Required volume is not mounted: ${E.name}`);if(!A||!x)return{volumes:e.volumes};if(u==="ensure-site"){let[E,K]=t.slice(1);if(!E?.startsWith(`${e.webRoot}/`)||!/^[\w-]+$/.test(n.basename(E))||E.includes("..")||!/^[\w-]+$/.test(K??""))throw Error("Invalid deployment site path or project slug");if(r.mkdirSync(n.join(E,"releases"),{recursive:!0}),A.includeBackups!==!1)r.mkdirSync(n.join(e.webRoot,`${K}-shared`,"backups"),{recursive:!0})}let D=(u==="reclaim"?[]:L(u==="ensure-site"?t[1]:void 0,t[2])).filter((E)=>!C.entries.some((K)=>K.source===E.source));for(let E of C.entries)if(!S(E.source)||!y(E.source,E.destination))throw Error(`Recorded deployment mount is missing: ${E.source}`);if(!D.length&&u==="ensure-site")return{inherited:!0,volume:x.name};if(!A.migrateExisting&&D.some((E)=>r.readdirSync(E.source).length>0))throw Error("Existing deployments require deploymentStorage.migrateExisting: true");if(D.length){let E=v("du",["-scx","--block-size=1",...D.map((ie)=>ie.source)]).trim().split(`
|
|
151
|
+
`).at(-1)?.split(/\s+/)[0],K=r.statfsSync(x.mountPath);if(Number(E)>K.bavail*K.bsize)throw Error("Insufficient free volume capacity for a verified deployment copy")}if(!r.existsSync("/run/ts-cloud-root-web"))r.mkdirSync("/run/ts-cloud-root-web");if(!S("/run/ts-cloud-root-web"))v("mount",["--bind",e.webRoot,"/run/ts-cloud-root-web"]);for(let E=0;E<D.length;E++){if(S(D[E].source)&&y(D[E].source,D[E].destination))continue;console.log(`copy ${E+1}/${D.length}: ${D[E].source}`),await ne(D[E],!1)}for(let E of new Set([...A.locks??[],"/run/lock/ts-cloud-host-cleanup.lock"]))Z(E);for(let E of r.readdirSync(e.webRoot,{withFileTypes:!0}).filter((K)=>K.isDirectory()).sort((K,ie)=>K.name.localeCompare(ie.name)))Z(n.join(e.webRoot,E.name,".ts-cloud/deploy.lock"));for(let E of u==="reclaim"?[]:L(u==="ensure-site"?t[1]:void 0,t[2]))if(!C.entries.some((K)=>K.source===E.source)&&!D.some((K)=>K.source===E.source))D.push(E);if(D.length)console.log("Checking application services and HTTPS routes before activation");let N=D.length?await ee():void 0;if(N)f("/var/lib/ts-cloud/compute-storage-health-before.json",N);let R=pe().filter((E)=>E.write);if(R.length)throw Error(`Live writable files must be shared before migration: ${R.map((E)=>E.file).join(", ")}`);let q={entries:[...C.entries],fstab:r.readFileSync("/etc/fstab","utf8")};if(D.length)v("sync",[]);let k=[];try{for(let E=0;E<D.length;E++){let K=D[E];if(S(K.source)){if(!y(K.source,K.destination))throw Error(`Unrecorded mount occupies ${K.source}`);C.entries.push(K),f("/var/lib/ts-cloud/compute-storage-state.json",C);continue}if(console.log(`verify and mount ${E+1}/${D.length}: ${K.source}`),await ne(K,!0),v("mount",["--bind",K.destination,K.source]),!y(K.source,K.destination))throw Error(`Bind verification failed: ${K.source}`);k.push(K),C.entries.push(K),f("/var/lib/ts-cloud/compute-storage-state.json",C),H()}if(H(),v("findmnt",["--verify"]),C.activatedAt=new Date().toISOString(),f("/var/lib/ts-cloud/compute-storage-state.json",C),ge(),N){console.log("Checking application services and HTTPS routes after activation");let E=await ee();f("/var/lib/ts-cloud/compute-storage-health-after.json",E);let K=N.routes.filter((re)=>re.ok&&!E.routes.some((Le)=>Le.domain===re.domain&&Le.path===re.path&&Le.ok)),ie=Object.keys(N.services).filter((re)=>!E.services[re]);if(K.length||ie.length)throw Error(`Application verification failed: ${K.map((re)=>re.domain+re.path).concat(ie).join(", ")}`);console.log(`Verified ${E.routes.length} routes and ${Object.keys(E.services).length} services`)}}catch(E){let K=[];for(let ie of k.reverse())try{v("umount",[ie.source])}catch{K.push(ie),console.error(`Rollback mount busy, original data retained: ${ie.source}`)}if(C.entries=[...q.entries,...K],r.writeFileSync("/etc/fstab",q.fstab),K.length)H();throw f("/var/lib/ts-cloud/compute-storage-state.json",C),v("systemctl",["daemon-reload"]),E}let Y=r.statSync(e.webRoot).dev,X=pe().filter((E)=>E.device===Y).map((E)=>E.file);for(let E of C.entries){if(!S(E.source)||!y(E.source,E.destination))throw Error(`Lost deployment mount: ${E.source}`);let K=n.join("/run/ts-cloud-root-web",n.relative(e.webRoot,E.source));if(!r.existsSync(K))continue;let ie="";try{ie=n.basename(r.realpathSync(n.join(n.dirname(E.source),"current")))}catch{}for(let re of r.readdirSync(K,{withFileTypes:!0})){let Le=n.join(K,re.name);if(n.basename(E.source)==="backups"){if(re.isFile()&&r.existsSync(n.join(E.destination,re.name)))r.unlinkSync(Le)}else if(re.isDirectory()&&!re.isSymbolicLink()&&re.name!==ie&&!X.some((kt)=>kt===n.join(E.source,re.name)||kt.startsWith(`${n.join(E.source,re.name)}/`)))r.rmSync(Le,{recursive:!0})}}v("sync",[]);let J=W();return f("/var/lib/ts-cloud/compute-storage-status.json",J),console.log(JSON.stringify(J)),J}finally{for(let P of me.reverse())ue.symbols.flock(P,8),r.closeSync(P);ue.close()}}var rn="/etc/ts-cloud/compute-storage.json",Me="/usr/local/lib/ts-cloud/compute-storage.mjs";function Yn(e,t){let r=Object.entries(e.infrastructure?.compute?.volumes??{}).map(([s,i])=>{if(!/^[a-z][a-z0-9-]*$/.test(s))throw Error(`Invalid compute volume key: ${s}`);if(!Number.isInteger(i.size)||i.size<10||i.size>10240)throw Error(`compute.volumes.${s}.size must be a whole number from 10 to 10240 GB`);if(!i.mountPath.startsWith("/")||!i.mountPath.slice(1).split("/").every((c)=>/^[\w-]+$/.test(c))||i.mountPath==="/var"||i.mountPath==="/var/lib"||["/etc","/usr","/var/www","/root","/boot","/dev","/proc","/sys","/run","/bin","/sbin","/lib"].some((c)=>i.mountPath===c||i.mountPath.startsWith(`${c}/`)))throw Error(`Unsafe compute volume mount path: ${i.mountPath}`);let a=i.name??`${e.project.slug}-${t}-${s}`;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(a))throw Error(`Invalid compute volume name: ${a}`);return{...i,key:s,name:a,mountPath:i.mountPath.replace(/\/+$/,"")}});for(let s of r)if(r.some((i)=>i!==s&&(i.name===s.name||i.mountPath===s.mountPath||i.mountPath.startsWith(`${s.mountPath}/`))))throw Error("Compute volumes must have distinct names and non-overlapping mount paths");let n=e.infrastructure?.compute?.deploymentStorage;for(let s of n?.locks??[])if(!s.startsWith("/run/lock/")||!s.slice(10).split("/").every((i)=>/^[\w.-]+$/.test(i)&&i!=="."&&i!=="..")||s==="/run/lock/ts-cloud-compute-storage.lock")throw Error(`Invalid deployment storage lock: ${s}`);for(let s of n?.dependentUnits??[])if(!/^[\w@.-]+\.service$/.test(s))throw Error(`Invalid deployment storage dependent unit: ${s}`);if(n&&!r.some((s)=>s.key===n.volume))throw Error(`deploymentStorage.volume references an undeclared compute volume: ${n.volume}`);return r}function Zt(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Zn(e){let t=`${rn}.candidate`,r=`#!/usr/bin/env bun
|
|
152
152
|
await (${Ts.toString()})(JSON.parse(await Bun.file(process.env.TS_CLOUD_STORAGE_POLICY || ${JSON.stringify(rn)}).text()), process.argv.slice(2));
|
|
153
153
|
`;return['command -v bun >/dev/null 2>&1 || { echo "Configured compute storage requires Bun on the host" >&2; exit 1; }',"install -d -m 0755 /etc/ts-cloud /usr/local/lib/ts-cloud /var/lib/ts-cloud",`printf %s ${Zt(Buffer.from(r).toString("base64"))} | base64 -d > ${Me}.new`,`chmod 0755 ${Me}.new && mv ${Me}.new ${Me}`,`printf %s ${Zt(JSON.stringify(e))} > ${t}`,`chmod 0644 ${t}`,`TS_CLOUD_STORAGE_POLICY=${t} bun ${Me} apply 2>&1 | tee /var/log/ts-cloud-compute-storage.log`,`rm -f ${t}`,"cat > /etc/systemd/system/ts-cloud-storage-check.service <<'TS_CLOUD_STORAGE_SERVICE'","[Unit]","Description=Check configured compute storage and deployment mounts","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Me} check`,"TS_CLOUD_STORAGE_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-check.timer <<'TS_CLOUD_STORAGE_TIMER'","[Unit]","Description=Check compute storage every minute","[Timer]","OnBootSec=2min","OnUnitActiveSec=1min","[Install]","WantedBy=timers.target","TS_CLOUD_STORAGE_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-check.timer","cat > /etc/systemd/system/ts-cloud-storage-reclaim.service <<'TS_CLOUD_RECLAIM_SERVICE'","[Unit]","Description=Reclaim inactive root copies of volume-backed deployments","[Service]","Type=oneshot",`ExecStart=/usr/local/bin/bun ${Me} reclaim`,"Nice=19","IOSchedulingClass=idle","TS_CLOUD_RECLAIM_SERVICE","cat > /etc/systemd/system/ts-cloud-storage-reclaim.timer <<'TS_CLOUD_RECLAIM_TIMER'","[Unit]","Description=Reclaim retired deployment copies hourly","[Timer]","OnCalendar=hourly","RandomizedDelaySec=5min","Persistent=true","[Install]","WantedBy=timers.target","TS_CLOUD_RECLAIM_TIMER","systemctl daemon-reload","systemctl enable --now ts-cloud-storage-reclaim.timer"]}function xr(e,t){return[`if [ -f ${rn} ]; then bun ${Me} ensure-site ${Zt(e)} ${Zt(t)}; fi`]}function er(e){return Object.entries(e).map(([t,r])=>`${t}=${Ea(String(r))}`).join(`
|
|
154
154
|
`)}function Ea(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}var tr=["storage",".env"],Pt=4;function Ie(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Ra(e){return`${Ie(e)}/deploy-history.log`}function Oa(e,t){return`${Ie(e)}/deploys/${t}.log`}function ws(e){return`${Ie(e)}/shared-paths`}function rr(e){return`${e.shared}/stx-images`}function Wt(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function Cs(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function nn(e){return typeof e==="string"?e:e.path}function Ps(e){let t=new Map;for(let r of e)t.set(nn(r),r);return[...t.values()]}function Es(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Da(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function Et(e,t=tr){let r=[`mkdir -p ${e.releases} ${e.shared} ${rr(e)}`,...Da(e)],n=t.map((i)=>Es(e,i));for(let{path:i,target:a,seed:c}of n){if(!c)continue;if(r.push(`ts_cloud_adopt_shared '${i}' '${a}'`),Cs(i))r.push(`mkdir -p "$(dirname ${a})"`,`touch ${a}`);else if(i==="storage")r.push(`mkdir -p ${a}/app/public`,`mkdir -p ${a}/framework/cache/data`,`mkdir -p ${a}/framework/sessions`,`mkdir -p ${a}/framework/testing`,`mkdir -p ${a}/framework/views`,`mkdir -p ${a}/logs`);else r.push(`mkdir -p ${a}`)}let s=ws(e.base);return r.push(`mkdir -p ${Ie(e.base)}`,`cat > ${s} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((i)=>`${i.path} ${i.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function sn(e,t=900){let r=`${Ie(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function on(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...xa(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function an(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function xa(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function ln(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ia(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function nr(e,t=tr){let r=[];for(let n of t){let{path:s,target:i,seed:a}=Es(e,n),c=`${e.release}/${s}`,u=[`rm -rf ${c}`,`mkdir -p "$(dirname ${c})"`,`ln -sfn ${i} ${c}`];if(a){if(s!==".env"&&Cs(s))r.push(...Ia(c,i));r.push(...u);continue}r.push(`if [ -e ${i} ]; then`,...u.map((m)=>` ${m}`),"fi")}return r}function Aa(e,t){let r=ws(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function ct(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function un(e){return`${Ie(e)}/previous-release`}function pn(e,t="TS_CLOUD_PREV_CURRENT"){let r=un(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${Ie(e.base)}; basename "$${t}" > ${r}; fi`]}function Rs(e,t){let r=un(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Og(e,t={}){return[...Rs(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function _g(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",s=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${un(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],i=[...Rs(e,t.to),...Aa(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...i,...s];let a=t.unitBase,c=`${a}@\${TS_CLOUD_RB_ID}.service`;return[...i,`if [ -f ${n}/${a}@.service ]; then`,` systemctl start "${c}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${c}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${c}" -n 30 --no-pager >&2 || true; systemctl stop "${c}" 2>/dev/null || true; exit 1; }; done`,...s.map((u)=>` ${u}`),` systemctl enable "${c}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${a}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${a}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${a}.service ]; then`,...s.map((u)=>` ${u}`),` systemctl restart ${a}.service`,"else",...s.map((u)=>` ${u}`),"fi"]}function lt(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function La(e){return`${Ie(e)}/owner`}function dn(e,t){let r=La(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function sr(e,t){let r=Ie(e),n=Oa(e,t.releaseId),s=Ra(e),i=Math.max(1,t.keepLogs??20),a=t.commit||"",c=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${a} branch=${c} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${a}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${s}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${i+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var Ua=new Set(["sqlite","sqlite3"]),Ha=new Set([":memory:","memory"]);function ka(e){let t=e?.DB_CONNECTION?.trim().toLowerCase();return t!=null&&Ua.has(t)}function Na(e){let t=e.trim().replace(/^\.\//,"");if(t===""||t.startsWith("/")||t.startsWith("~"))return;if(t.split("/").includes(".."))return;return t.replace(/\/+$/,"")}function mn(e,t=[]){if(!ka(e))return{};let r=e?.DB_DATABASE_PATH?.trim()||e?.DB_DATABASE?.trim();if(r&&Ha.has(r.toLowerCase()))return{};if(!r)return{warning:"DB_CONNECTION is sqlite but neither DB_DATABASE_PATH nor DB_DATABASE names a file, so ts-cloud cannot tell where the database lives. If it is written inside the release directory, the next deploy discards it. Set DB_DATABASE_PATH, or list the file in the site's `sharedPaths`."};let n=Na(r);if(!n)return{};if(t.some((s)=>nn(s)===n))return{};return{path:n}}function or(e,t=[]){let{path:r}=mn(e,t);return r?[r]:[]}var Or="/var/ts-cloud/artifacts",Bh="/usr/local/bin/ts-cloud-host-cleanup.sh",xh="ts-cloud-host-cleanup";var Lg=Object.freeze({stagingMaxAgeMinutes:60,artifactMaxAgeDays:2,artifactUploadMaxAgeMinutes:60,bunCacheMaxAgeDays:7,journalMaxAgeDays:14,journalMaxSizeMb:512,containerImageMaxAgeHours:168}),$g=Object.freeze({artifactMaxAgeDays:0,bunCacheMaxAgeDays:1,journalMaxAgeDays:3,journalMaxSizeMb:256,containerImageMaxAgeHours:24}),Oh=50,_h=85,Lh="daily";function Os(e){return`'${e.replace(/'/g,`'"'"'`)}'`}function Je(e,t,r=0){if(!Number.isInteger(t)||t<r)throw Error(`hostCleanup: ${e} must be a whole number >= ${r} (got ${t})`)}function Ds(e,t){for(let[r,n]of Object.entries(t))Je(`${e}.${r}`,n);Je(`${e}.stagingMaxAgeMinutes`,t.stagingMaxAgeMinutes,15),Je(`${e}.artifactUploadMaxAgeMinutes`,t.artifactUploadMaxAgeMinutes,15),Je(`${e}.journalMaxSizeMb`,t.journalMaxSizeMb,1)}function Ma(e,t){let r=`hostCleanup.paths[${t}]`,n=e.path?.replace(/\/+$/,"")??"";if(!n.startsWith("/")||n===""||/[\s'"`$\\]/.test(n)||n.split("/").includes(".."))throw Error(`${r}.path must be an absolute directory with no spaces, quotes or '..' (got ${JSON.stringify(e.path)})`);if(n==="/var/www"||n.startsWith("/var/www/"))throw Error(`${r}.path must not be under /var/www: releases are pruned by keepReleases`);if(!e.pattern||/^[*?]+$/.test(e.pattern)||e.pattern.includes("/")||/[\n'"`]/.test(e.pattern))throw Error(`${r}.pattern must be a file-name glob naming something, not a bare wildcard (got ${JSON.stringify(e.pattern)})`);if(Je(`${r}.maxAgeDays`,e.maxAgeDays),e.type!==void 0&&e.type!=="file"&&e.type!=="directory")throw Error(`${r}.type must be 'file' or 'directory'`)}function _r(e){let t=typeof e==="object"&&e!==null?e:{},r=e!==!1,n={...Lg,...xs(t.retention)};Ds("hostCleanup.retention",n);let s=null;if(t.pressure!==!1){let c=typeof t.pressure==="object"?t.pressure:{},u=c.lowWaterPercent??50,m=c.highWaterPercent??85;if(Je("hostCleanup.pressure.lowWaterPercent",u),Je("hostCleanup.pressure.highWaterPercent",m,1),m>100||u>=m)throw Error(`hostCleanup.pressure: need 0 <= lowWaterPercent < highWaterPercent <= 100 (got ${u} and ${m})`);let f={...$g,...xs(c.escalated)},v=Object.fromEntries(Object.keys(n).map((_)=>[_,Math.min(n[_],f[_]??n[_])]));Ds("hostCleanup.pressure.escalated",v),s={lowWaterPercent:u,highWaterPercent:m,escalated:v}}let i=t.schedule??"daily";if(!/^[\w*:,./~ -]+$/.test(i))throw Error(`hostCleanup.schedule must be a systemd OnCalendar expression (got ${JSON.stringify(i)})`);let a=t.paths??[];return a.forEach(Ma),{enabled:r,timer:r&&t.timer!==!1,schedule:i,retention:n,pressure:s,paths:a}}function xs(e){return Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0))}var Rt={stagingMaxAgeMinutes:"TS_CLOUD_HC_STAGING_MIN",artifactMaxAgeDays:"TS_CLOUD_HC_ARTIFACT_DAYS",artifactUploadMaxAgeMinutes:"TS_CLOUD_HC_UPLOAD_MIN",bunCacheMaxAgeDays:"TS_CLOUD_HC_BUN_DAYS",journalMaxAgeDays:"TS_CLOUD_HC_JOURNAL_DAYS",journalMaxSizeMb:"TS_CLOUD_HC_JOURNAL_MB",containerImageMaxAgeHours:"TS_CLOUD_HC_IMAGE_HOURS"};function fn(e){return Object.keys(Rt).map((t)=>`${Rt[t]}=${e[t]}`).join(" ")}var Fe=(e)=>`"$${Rt[e]}"`;function Is(e){return[`find /var/ts-cloud/staging -xdev -maxdepth 1 -type f -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /tmp -xdev -maxdepth 1 -type f -name "*-release.tar.gz" -mmin +${Fe("stagingMaxAgeMinutes")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name "*.tar.gz" -mtime +${Fe("artifactMaxAgeDays")} -delete 2>/dev/null || true`,`find /var/ts-cloud/artifacts -xdev -maxdepth 1 -type f -name ".*.tmp" -mmin +${Fe("artifactUploadMaxAgeMinutes")} -delete 2>/dev/null || true`,...e.map(Fa),`journalctl --vacuum-time=${Fe("journalMaxAgeDays")}d --vacuum-size=${Fe("journalMaxSizeMb")}M >/dev/null 2>&1 || true`]}function Fa(e){let t=Os(e.path.replace(/\/+$/,"")),r=Os(e.pattern);return e.type==="directory"?`find ${t} -xdev -mindepth 1 -maxdepth 1 -type d -name ${r} -mtime +${e.maxAgeDays} -exec rm -rf -- {} + 2>/dev/null || true`:`find ${t} -xdev -mindepth 1 -maxdepth 1 -type f -name ${r} -mtime +${e.maxAgeDays} -delete 2>/dev/null || true`}function As(){return[`find /root/.bun/install/cache -xdev -type f -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`find /root/.bun/install/cache -xdev -depth -type d -empty -mtime +${Fe("bunCacheMaxAgeDays")} -delete 2>/dev/null || true`,`if command -v docker >/dev/null 2>&1; then docker image prune --all --force --filter "until=\${${Rt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,`if command -v podman >/dev/null 2>&1; then podman image prune --all --force --filter "until=\${${Rt.containerImageMaxAgeHours}}h" >/dev/null 2>&1 || true; fi`,"if command -v apt-get >/dev/null 2>&1; then apt-get clean >/dev/null 2>&1 || true; fi"]}function Ls(e){return[`${e}="$(df -P / 2>/dev/null | awk 'NR==2 {sub(/%/, "", $5); print $5}' || true)"`,`case "$${e}" in ''|*[!0-9]*) ${e}=-1 ;; esac`]}function ei(e){let{retention:t,pressure:r,paths:n}=_r(e),s='echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',i='echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"';if(!r)return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',fn(t),...Is(n),...As(),'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"'];let{lowWaterPercent:a,highWaterPercent:c,escalated:u}=r;return['echo "[ts-cloud] host cleanup (disk before): $(df -h / | tail -1)"',...Ls("TS_CLOUD_HC_BEFORE"),"TS_CLOUD_HC_TIER=normal",fn(t),`if [ "$TS_CLOUD_HC_BEFORE" -ge 0 ] && [ "$TS_CLOUD_HC_BEFORE" -lt ${a} ]; then`," TS_CLOUD_HC_TIER=light",` echo "[ts-cloud] host cleanup: / at \${TS_CLOUD_HC_BEFORE}% (under ${a}%), skipping cache and image pruning"`,`elif [ "$TS_CLOUD_HC_BEFORE" -ge ${c} ]; then`," TS_CLOUD_HC_TIER=pressure",` ${fn(u)}`,` echo "[ts-cloud] warning: / at \${TS_CLOUD_HC_BEFORE}% (at or above ${c}%), host cleanup is using shortened retention windows" >&2`,"fi",...Is(n),'if [ "$TS_CLOUD_HC_TIER" != light ]; then',...As().map((m)=>` ${m}`),"fi",'echo "[ts-cloud] host cleanup (disk after): $(df -h / | tail -1)"',...Ls("TS_CLOUD_HC_AFTER"),`echo "[ts-cloud] host-cleanup {\\"event\\":\\"host-cleanup\\",\\"tier\\":\\"$TS_CLOUD_HC_TIER\\",\\"diskBeforePercent\\":$TS_CLOUD_HC_BEFORE,\\"diskAfterPercent\\":$TS_CLOUD_HC_AFTER,\\"lowWaterPercent\\":${a},\\"highWaterPercent\\":${c}}"`,"mkdir -p /var/lib/ts-cloud 2>/dev/null || true",'TS_CLOUD_HC_PREV="$(cat /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || echo ok)"',`if [ "$TS_CLOUD_HC_AFTER" -ge ${c} ]; then`,` echo "[ts-cloud] warning: / still at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%); something outside ts-cloud's retention rules is filling the disk" >&2`,` if [ "$TS_CLOUD_HC_PREV" != alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "⚠️ $(hostname): / at \${TS_CLOUD_HC_AFTER}% after host cleanup (high-water ${c}%)" >/dev/null 2>&1 || true; fi`," echo alert > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","else",` if [ "$TS_CLOUD_HC_PREV" = alert ] && [ -x /usr/local/bin/ts-cloud-notify ]; then /usr/local/bin/ts-cloud-notify "✅ $(hostname): / back under ${c}% after host cleanup (\${TS_CLOUD_HC_AFTER}%)" >/dev/null 2>&1 || true; fi`," echo ok > /var/lib/ts-cloud/host-cleanup.alert 2>/dev/null || true","fi"]}function Mg(e){return["#!/usr/bin/env bash","# Managed by ts-cloud: rewritten on every deploy. Configure compute.hostCleanup instead of editing.","set -uo pipefail","TS_CLOUD_HC_LOCK=/run/lock/ts-cloud-host-cleanup.lock","[ -d /run/lock ] || TS_CLOUD_HC_LOCK=/tmp/ts-cloud-host-cleanup.lock",'if command -v flock >/dev/null 2>&1 && exec 9>"$TS_CLOUD_HC_LOCK"; then',' if ! flock -n 9; then echo "[ts-cloud] host cleanup already running; skipping"; exit 0; fi',"fi",...ei(e),"exit 0"]}function gn(e,t,r,n,s){return[`cat > ${e}.ts-cloud-new <<'${r}' || true`,...t,r,`if [ -s ${e}.ts-cloud-new ] && ! cmp -s ${e}.ts-cloud-new ${e}; then chmod ${n} ${e}.ts-cloud-new && mv -f ${e}.ts-cloud-new ${e}${s?` && ${s}=1`:""} || true; else rm -f ${e}.ts-cloud-new; fi`]}function Ys(e){let t=_r(e),r="/etc/systemd/system/ts-cloud-host-cleanup",n=["if [ -f /etc/systemd/system/ts-cloud-host-cleanup.timer ]; then"," systemctl disable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true"," rm -f /etc/systemd/system/ts-cloud-host-cleanup.timer /etc/systemd/system/ts-cloud-host-cleanup.service"," systemctl daemon-reload >/dev/null 2>&1 || true","fi"];if(!t.enabled)return[...n,"rm -f /usr/local/bin/ts-cloud-host-cleanup.sh"];let s=gn("/usr/local/bin/ts-cloud-host-cleanup.sh",Mg(e),"TS_CLOUD_HOST_CLEANUP_EOF","755");if(!t.timer)return[...s,...n];return[...s,"TS_CLOUD_HC_UNITS_CHANGED=0","if command -v systemctl >/dev/null 2>&1 && [ -d /etc/systemd/system ]; then",...gn("/etc/systemd/system/ts-cloud-host-cleanup.service",["[Unit]","Description=ts-cloud host cleanup (bounded disk retention)","After=local-fs.target","","[Service]","Type=oneshot","ExecStart=/usr/local/bin/ts-cloud-host-cleanup.sh","Nice=19","IOSchedulingClass=idle"],"TS_CLOUD_HOST_CLEANUP_SVC_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),...gn("/etc/systemd/system/ts-cloud-host-cleanup.timer",["[Unit]","Description=Run ts-cloud host cleanup on a schedule, independent of deploys","","[Timer]",`OnCalendar=${t.schedule}`,"RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"],"TS_CLOUD_HOST_CLEANUP_TMR_EOF","644","TS_CLOUD_HC_UNITS_CHANGED"),' if [ "$TS_CLOUD_HC_UNITS_CHANGED" -eq 1 ]; then systemctl daemon-reload >/dev/null 2>&1 || true; fi'," systemctl enable --now ts-cloud-host-cleanup.timer >/dev/null 2>&1 || true","fi"]}function ti(e){let t=Ys(e);if(!_r(e).enabled)return t;return[...t,'if [ -x /usr/local/bin/ts-cloud-host-cleanup.sh ]; then /usr/local/bin/ts-cloud-host-cleanup.sh < /dev/null || echo "[ts-cloud] warning: host cleanup exited $?" >&2; fi']}var za=/\.(?:[cm]?[jt]sx?)$/;function ri(e,t,r){let n=t==="bun"?"/usr/local/bin/bun":t==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",s=e.trim();if(/^(?:bun|node|deno)\s+/.test(s))return`${n} ${s.replace(/^(?:bun|node|deno)\s+/,"")}`;let[i="",...a]=s.split(/\s+/);if(i&&!za.test(i)){let c=i.startsWith("/")?i:r&&i.startsWith("./")?`${r.replace(/\/+$/,"")}/${i.replace(/^\.\//,"")}`:void 0;if(c)return[c,...a].join(" ")}return`${n} ${s}`}function Us(e){return["TS_CLOUD_MEM_MB=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)","TS_CLOUD_HIGH_MB=$((TS_CLOUD_MEM_MB / 8))",'[ "$TS_CLOUD_HIGH_MB" -lt 512 ] && TS_CLOUD_HIGH_MB=512','[ "$TS_CLOUD_HIGH_MB" -gt 4096 ] && TS_CLOUD_HIGH_MB=4096',`mkdir -p /etc/systemd/system/${e}.d`,`printf '# Written by ts-cloud: memoryHigh resolved from this box.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{tl,Q,l,nl,K,g,be,p,sr,ol,Ki,Uo,ll,pl,ml,_l,un,es,gr,Ll,$l,Gl,Vl}from"./chunk-zvcd6x45.js";import{Ie,Yt,x,Zt,s,xi,fo,zr,Ed,vd,ae,c,yo,We,Kr,Td,Io,wd,Wr,bo,er,Jr,Li,nr,Ui,Qi,Je,ir,zd,Kd,Gi,Vi,vt,Oo,i,qi,Lo,$o}from"./chunk-430acqjk.js";import{n}from"./chunk-e42gpavb.js";import{Re}from"./chunk-qyr5hn6v.js";import{o}from"./chunk-jyvnfny6.js";import{Te,Sr,Os,dt,re,pe,v,we,Cr,me,ut,vr}from"./chunk-nhsefr22.js";import{ne}from"./chunk-mp2y4t6w.js";import{T,kr,Js,Kt,Nr,xg,Wt,Og,_g,Mc,qe,ht,ui,F,Jt,Ur}from"./chunk-b11w48de.js";import{U,d}from"./chunk-2hma3g5q.js";import{On}from"./chunk-94z7s8ky.js";import{_n,yg,Ps,L,P,ks,Sg}from"./chunk-hybz2q8w.js";import{S}from"./chunk-stc3ykm3.js";import{He}from"./chunk-vgtqd3sb.js";import{Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{existsSync as DI}from"node:fs";import{join as Xh}from"node:path";import{pathToFileURL as OI}from"node:url";import{existsSync as Vm,statSync as Wm}from"fs";import{resolve as Ws}from"path";import ww from"process";import{existsSync as Ew,mkdirSync as yT,readdirSync as vT,readFileSync as Rw,writeFileSync as bT}from"fs";import{homedir as jo}from"os";import{dirname as kT,resolve as Zn}from"path";import ld from"process";import{existsSync as Hm,statSync as Km}from"fs";import{existsSync as Ql,mkdirSync as Aw,readdirSync as Cw,writeFileSync as Pw}from"fs";import{homedir as Bo}from"os";import{dirname as Jm,resolve as Hr}from"path";import no from"process";import{join as _w,relative as Tw,resolve as Gm}from"path";import Yc from"process";import{existsSync as Lf,mkdirSync as DT,readdirSync as OT,writeFileSync as $T}from"fs";import{homedir as Al}from"os";import{dirname as BT,resolve as Vr}from"path";import Ks from"process";import{join as xw,relative as Dw,resolve as Qm}from"path";import Zc from"process";import{existsSync as vh,mkdirSync as UT,readdirSync as qT,writeFileSync as VT}from"fs";import{dirname as HT,resolve as Xc}from"path";import Yl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as Ow,createDecipheriv as $w,randomBytes as Cl}from"crypto";import{closeSync as Pl,createReadStream as Ym,createWriteStream as Nw,existsSync as Tl,fsyncSync as Zm,openSync as Xm,writeFileSync as jw}from"fs";import{access as Bw,constants as ef,mkdir as Mw,readdir as xc,rename as tf,stat as Mo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Fo}from"path";import Tr from"process";import{pipeline as Lw}from"stream/promises";import{createGzip as rf}from"zlib";import zo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as Fw,createDecipheriv as zw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as nf,createWriteStream as Uw,existsSync as Oc,fsyncSync as of,openSync as sf,writeFileSync as qw}from"fs";import{access as Vw,constants as af,mkdir as Ww,readdir as $c,rename as cf,stat as qo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Hw,join as Vo,resolve as Kw}from"path";import At from"process";import{pipeline as Jw}from"stream/promises";import{createGzip as df}from"zlib";import Wo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as jl}from"path";import{existsSync as Gw}from"fs";import{existsSync as Qw,readdirSync as Yw}from"fs";import{extname as Bl,resolve as lf}from"path";import Zw from"process";import{join as Xw,relative as ek,resolve as uf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as tk,createDecipheriv as rk,randomBytes as Ml}from"crypto";import{closeSync as Fl,createReadStream as pf,createWriteStream as nk,existsSync as Lc,fsyncSync as gf,openSync as mf,writeFileSync as ik}from"fs";import{access as ok,constants as ff,mkdir as sk,readdir as Fc,rename as hf,stat as Ho,unlink as zc,writeFile as zl}from"fs/promises";import{isAbsolute as ak,join as Ko,resolve as ck}from"path";import Ct from"process";import{pipeline as dk}from"stream/promises";import{createGzip as yf}from"zlib";import Jo from"process";import pi from"process";import qc from"process";import{existsSync as Vc}from"fs";import{resolve as xf}from"path";import{existsSync as _I}from"fs";class Df{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 u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),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(!Vm(e))return!0;return Wm(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 u=Vm(r)?Wm(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},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,u)=>a+u.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 Of{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}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((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,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 Df,cp=new Of;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 u=r===void 0?[]:Array.isArray(r)?r:[r];for(let m of u){if(!m)continue;if(a.push(m,`.${m}.config`,`${m}.config`,`.${m}`),t)a.push(`${t}.${m}.config`,`.${t}.${m}.config`)}return Array.from(new Set(a.filter(Boolean)))}function kw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Iw(e={}){let t=Ws(e.cwd||ww.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 lk=Object.defineProperty,uk=(e)=>e;function pk(e,t){this[e]=uk.bind(null,t)}var gk=(e,t)=>{for(var r in t)lk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pk.bind(t,r)})},mk=(e,t)=>()=>(e&&(t=e(e=0)),t),bh={};gk(bh,{withErrorRecovery:()=>kh,tryLoadConfig:()=>Bk,loadConfigWithResult:()=>Nk,loadConfig:()=>Ph,isRetryableError:()=>_k,isConfigNotFoundError:()=>Pk,isBunfigError:()=>Ih,globalPerformanceMonitor:()=>Ys,globalCache:()=>Go,getEnvOrDefault:()=>Tk,generateConfigTypes:()=>Mk,defaultGeneratedDir:()=>jh,defaultConfigDir:()=>Nh,deepMergeWithArrayStrategy:()=>gp,deepMerge:()=>Eh,createLibraryConfig:()=>Lk,config:()=>jk,bunfigPlugin:()=>Fk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>ip,SchemaValidationError:()=>Qs,PluginError:()=>sp,PerformanceMonitor:()=>lp,FileSystemError:()=>np,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>mp,ConfigValidationError:()=>tp,ConfigNotFoundError:()=>od,ConfigMergeError:()=>rp,ConfigLoader:()=>fp,ConfigLoadError:()=>Gs,ConfigFileLoader:()=>pd,ConfigCache:()=>dp,CacheUtils:()=>Th,BunfigError:()=>cn,BrowserConfigError:()=>op,ArrayMergeStrategies:()=>Oh});class dp{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 u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),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(!Hm(e))return!0;return Km(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 u=Hm(r)?Km(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},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,u)=>a+u.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 lp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}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((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,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 fk(e,t={}){let a=Object.keys(t).sort().map((u)=>`${u}:${t[u]}`).join("|");return a?`${e}:${a}`:e}function hk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yk(e){return e.getStats().size*2}function up(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 u of e)if(Vt(u)&&"name"in u){if(!a.find((f)=>Vt(f)&&("name"in f)&&f.name===u.name))a.push(u)}else if(Vt(u)&&"path"in u){if(!a.find((f)=>Vt(f)&&("path"in f)&&f.path===u.path))a.push(u)}else if(!a.some((m)=>td(m,u)))a.push(u);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let u of e)if(!a.includes(u))a.push(u);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 u=t[a];if(u===null||u===void 0)continue;else if(Vt(u)&&Vt(r[a]))r[a]=up(r[a],u);else if(Array.isArray(u)&&Array.isArray(r[a]))if(u.length>0&&r[a].length>0&&Vt(u[0])&&Vt(r[a][0])){let m=[...u];for(let f of r[a])if(Vt(f)&&"name"in f){if(!m.find((w)=>Vt(w)&&("name"in w)&&w.name===f.name))m.push(f)}else if(Vt(f)&&"path"in f){if(!m.find((w)=>Vt(w)&&("path"in w)&&w.path===f.path))m.push(f)}else if(!m.some((b)=>td(b,f)))m.push(f);r[a]=m}else if(u.every((m)=>typeof m==="string")&&r[a].every((m)=>typeof m==="string")){let m=[...u];for(let f of r[a])if(!m.includes(f))m.push(f);r[a]=m}else r[a]=u;else r[a]=u}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 u of r){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!td(e[u],t[u]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function vk(e,t){if(!vh(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 up(t,a)}catch{return null}}catch{return null}}async function bk({name:e="",cwd:t,defaultConfig:r}){let a=t||Yl.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],m=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let f of m)for(let b of u){let w=Xc(a,`${f}${b}`),y=await vk(w,r);if(y!==null)return y}try{let f=Xc(a,"package.json");if(vh(f)){let w=(await import(f))[e];if(w&&typeof w==="object"&&!Array.isArray(w))try{return up(r,w)}catch{}}}catch{}return r}function Sk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Qm(r,"..");let a=Qm(r,e||"");if(t?.relative)return Dw(Zc.cwd(),a);return a}async function wk(){try{let e=await bk({name:"clarity",defaultConfig:Hc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Hc,...e}}catch{return Hc}}function tr(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kk(){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 Sh{async format(e){let t=await kk(),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:zo.pid,hostname:t(),environment:zo.env.NODE_ENV||"development",platform:zo.platform,version:zo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:zo.env.NODE_ENV||zo.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={...Xl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Sh,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 u=this.generateKeyId(),m=this.generateKey();this.currentKeyId=u,this.keys.set(u,m),this.encryptionKeys.set(u,{key:m,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:Xl.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 u,m=0,f=3,b=1000;while(m<f)try{try{try{await Bw(this.config.logDirectory,ef.F_OK|ef.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Mw(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 w=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(u=Xm(this.currentLogFile,"a",420),jw(u,w,{flag:"a"}),Zm(u),u!==void 0)Pl(u),u=void 0;if((await Mo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,w,{flag:"w",mode:420}),(await Mo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let I=y;if(I.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(I.code)){if(m<f-1){let A=typeof I.message==="string"?I.message:"Unknown error";console.error(`Network error during write attempt ${m+1}/${f}:`,A);let D=b*2**m;await new Promise((O)=>setTimeout(O,D)),m++;continue}}if(I?.code&&["ENOSPC","EDQUOT"].includes(I.code))throw Error(`Disk quota exceeded or no space left on device: ${I.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",I),I}finally{if(u!==void 0)try{Pl(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(m===f-1){let I=w,A=typeof I.message==="string"?I.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),w}m++;let y=b*2**(m-1);await new Promise((I)=>setTimeout(I,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}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 Fo(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 Fo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Fo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tr())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((u)=>{console.error("Error rotating keys:",u)})},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 u=Array.from(this.encryptionKeys.entries()).sort(([,b],[,w])=>w.createdAt.getTime()-b.createdAt.getTime()),m=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,m);if(u.length>f)for(let[b]of u.slice(f))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Cl(16).toString("hex")}generateKey(){return Cl(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=Cl(16),a=Ow("aes-256-gcm",t,r),u=Ci.concat([a.update(e,"utf8"),a.final()]),m=a.getAuthTag();return{encrypted:Ci.concat([r,u,m]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=rf(),u=[];a.on("data",(m)=>u.push(m)),a.on("end",()=>t(Ci.from(Ci.concat(u)))),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(tr())return;let e=await Mo(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 u=await xc(this.config.logDirectory),m=u.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let I=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-I}),f=m.length>0?Number.parseInt(m[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${f}`;if(await Mo(r).catch(()=>null))try{if(await tf(r,b),t.compress)try{let w=`${b}.gz`;await this.compressLogFile(b,w),await Dc(b)}catch(w){console.error("Error compressing rotated file:",w)}if(m.length===0&&!u.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await xl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),m=r.replace(/\.log$/,`-${u}.log`);if(await Mo(r).catch(()=>null))await tf(r,m)}if(this.currentLogFile=a,t.maxFiles){let m=(await xc(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,b)=>b.localeCompare(f));for(let f of m.slice(t.maxFiles))await Dc(Fo(this.config.logDirectory,f))}}}async compressLogFile(e,t){let r=Ym(e),a=Nw(t),u=rf();await Lw(r,u,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=Xm(this.currentLogFile,"r+");Zm(e),Pl(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(!tr()&&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(Fo(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?Mt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:u,level:m,showTimestamp:f=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(f)O.push(t);if(m==="warning")O.push("WARN");else if(m==="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(u),O.join(" ")}let w=Tr.stdout.columns||120,y="";if(m==="warning"||m==="error")y=`${r} ${u}`;else if(m==="info"||m==="success")y=`${r} ${a} ${u}`;else y=`${r} ${a} ${Mt.cyan(u)}`;if(!f)return y.trim();let I=b(y).trim().length,A=b(t).length,D=Math.max(1,w-2-I-A);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(m,f)=>{let b=Number.parseInt(f,10);return b<t[0].length?String(t[0][b]):m});let r=/%([sdijfo%])/g,a=0,u=e.replace(r,(m,f)=>{if(f==="%")return"%";if(a>=t.length)return m;let b=t[a++];switch(f){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 m}});if(a<t.length)u+=` ${t.slice(a).map((m)=>typeof m==="object"?JSON.stringify(m,null,2):String(m)).join(" ")}`;return u}async log(e,t,...r){let a=new Date,u=this.formatConsoleTimestamp(a),m=this.formatFileTimestamp(a),f,b;if(t instanceof Error)f=t.message,b=t.stack;else f=this.formatMessage(t,r);if(this.fancy&&!tr()){let y=xh[e],I=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.gray(f),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.green(f),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A),b){let D=b.split(`
|
|
1
|
+
import{tl,Q,l,nl,K,g,be,p,sr,ol,Ki,Uo,ll,pl,ml,_l,un,es,gr,Ll,$l,Gl,Vl}from"./chunk-zvcd6x45.js";import{Ie,Yt,x,Zt,s,xi,fo,zr,Ed,vd,ae,c,yo,We,Kr,Td,Io,wd,Wr,bo,er,Jr,Li,nr,Ui,Qi,Je,ir,zd,Kd,Gi,Vi,vt,Oo,i,qi,Lo,$o}from"./chunk-430acqjk.js";import{n}from"./chunk-e42gpavb.js";import{Re}from"./chunk-qyr5hn6v.js";import{o}from"./chunk-jyvnfny6.js";import{Te,Sr,Os,dt,re,pe,v,we,Cr,me,ut,vr}from"./chunk-nhsefr22.js";import{ne}from"./chunk-mp2y4t6w.js";import{T,kr,Js,Kt,Nr,xg,Wt,Og,_g,Mc,qe,ht,ui,F,Jt,Ur}from"./chunk-fdr2cr9r.js";import{U,d}from"./chunk-2hma3g5q.js";import{On}from"./chunk-94z7s8ky.js";import{_n,yg,Ps,L,P,ks,Sg}from"./chunk-hybz2q8w.js";import{S}from"./chunk-stc3ykm3.js";import{He}from"./chunk-vgtqd3sb.js";import{Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{existsSync as DI}from"node:fs";import{join as Xh}from"node:path";import{pathToFileURL as OI}from"node:url";import{existsSync as Vm,statSync as Wm}from"fs";import{resolve as Ws}from"path";import ww from"process";import{existsSync as Ew,mkdirSync as yT,readdirSync as vT,readFileSync as Rw,writeFileSync as bT}from"fs";import{homedir as jo}from"os";import{dirname as kT,resolve as Zn}from"path";import ld from"process";import{existsSync as Hm,statSync as Km}from"fs";import{existsSync as Ql,mkdirSync as Aw,readdirSync as Cw,writeFileSync as Pw}from"fs";import{homedir as Bo}from"os";import{dirname as Jm,resolve as Hr}from"path";import no from"process";import{join as _w,relative as Tw,resolve as Gm}from"path";import Yc from"process";import{existsSync as Lf,mkdirSync as DT,readdirSync as OT,writeFileSync as $T}from"fs";import{homedir as Al}from"os";import{dirname as BT,resolve as Vr}from"path";import Ks from"process";import{join as xw,relative as Dw,resolve as Qm}from"path";import Zc from"process";import{existsSync as vh,mkdirSync as UT,readdirSync as qT,writeFileSync as VT}from"fs";import{dirname as HT,resolve as Xc}from"path";import Yl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as Ow,createDecipheriv as $w,randomBytes as Cl}from"crypto";import{closeSync as Pl,createReadStream as Ym,createWriteStream as Nw,existsSync as Tl,fsyncSync as Zm,openSync as Xm,writeFileSync as jw}from"fs";import{access as Bw,constants as ef,mkdir as Mw,readdir as xc,rename as tf,stat as Mo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Fo}from"path";import Tr from"process";import{pipeline as Lw}from"stream/promises";import{createGzip as rf}from"zlib";import zo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as Fw,createDecipheriv as zw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as nf,createWriteStream as Uw,existsSync as Oc,fsyncSync as of,openSync as sf,writeFileSync as qw}from"fs";import{access as Vw,constants as af,mkdir as Ww,readdir as $c,rename as cf,stat as qo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Hw,join as Vo,resolve as Kw}from"path";import At from"process";import{pipeline as Jw}from"stream/promises";import{createGzip as df}from"zlib";import Wo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as jl}from"path";import{existsSync as Gw}from"fs";import{existsSync as Qw,readdirSync as Yw}from"fs";import{extname as Bl,resolve as lf}from"path";import Zw from"process";import{join as Xw,relative as ek,resolve as uf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as tk,createDecipheriv as rk,randomBytes as Ml}from"crypto";import{closeSync as Fl,createReadStream as pf,createWriteStream as nk,existsSync as Lc,fsyncSync as gf,openSync as mf,writeFileSync as ik}from"fs";import{access as ok,constants as ff,mkdir as sk,readdir as Fc,rename as hf,stat as Ho,unlink as zc,writeFile as zl}from"fs/promises";import{isAbsolute as ak,join as Ko,resolve as ck}from"path";import Ct from"process";import{pipeline as dk}from"stream/promises";import{createGzip as yf}from"zlib";import Jo from"process";import pi from"process";import qc from"process";import{existsSync as Vc}from"fs";import{resolve as xf}from"path";import{existsSync as _I}from"fs";class Df{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 u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),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(!Vm(e))return!0;return Wm(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 u=Vm(r)?Wm(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},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,u)=>a+u.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 Of{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}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((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,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 Df,cp=new Of;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 u=r===void 0?[]:Array.isArray(r)?r:[r];for(let m of u){if(!m)continue;if(a.push(m,`.${m}.config`,`${m}.config`,`.${m}`),t)a.push(`${t}.${m}.config`,`.${t}.${m}.config`)}return Array.from(new Set(a.filter(Boolean)))}function kw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Iw(e={}){let t=Ws(e.cwd||ww.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 lk=Object.defineProperty,uk=(e)=>e;function pk(e,t){this[e]=uk.bind(null,t)}var gk=(e,t)=>{for(var r in t)lk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:pk.bind(t,r)})},mk=(e,t)=>()=>(e&&(t=e(e=0)),t),bh={};gk(bh,{withErrorRecovery:()=>kh,tryLoadConfig:()=>Bk,loadConfigWithResult:()=>Nk,loadConfig:()=>Ph,isRetryableError:()=>_k,isConfigNotFoundError:()=>Pk,isBunfigError:()=>Ih,globalPerformanceMonitor:()=>Ys,globalCache:()=>Go,getEnvOrDefault:()=>Tk,generateConfigTypes:()=>Mk,defaultGeneratedDir:()=>jh,defaultConfigDir:()=>Nh,deepMergeWithArrayStrategy:()=>gp,deepMerge:()=>Eh,createLibraryConfig:()=>Lk,config:()=>jk,bunfigPlugin:()=>Fk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>ip,SchemaValidationError:()=>Qs,PluginError:()=>sp,PerformanceMonitor:()=>lp,FileSystemError:()=>np,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>mp,ConfigValidationError:()=>tp,ConfigNotFoundError:()=>od,ConfigMergeError:()=>rp,ConfigLoader:()=>fp,ConfigLoadError:()=>Gs,ConfigFileLoader:()=>pd,ConfigCache:()=>dp,CacheUtils:()=>Th,BunfigError:()=>cn,BrowserConfigError:()=>op,ArrayMergeStrategies:()=>Oh});class dp{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 u=this.generateKey(e,r),m=a??this.options.ttl,f=this.estimateSize(t);this.cache.set(u,{value:t,timestamp:new Date,ttl:m,hits:0,size:f}),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(!Hm(e))return!0;return Km(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 u=Hm(r)?Km(r):null,m=u?u.mtime:new Date;this.set(e,{value:t,fileTimestamp:m},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,u)=>a+u.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 lp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),u=new Date;try{let m=await t(),f=performance.now()-a;return this.recordMetric({operation:e,duration:f,timestamp:u,...r}),m}catch(m){let f=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:f,timestamp:u,...r}),m}}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((u)=>u.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((u)=>u.duration),a=r.reduce((u,m)=>u+m,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 fk(e,t={}){let a=Object.keys(t).sort().map((u)=>`${u}:${t[u]}`).join("|");return a?`${e}:${a}`:e}function hk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function yk(e){return e.getStats().size*2}function up(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 u of e)if(Vt(u)&&"name"in u){if(!a.find((f)=>Vt(f)&&("name"in f)&&f.name===u.name))a.push(u)}else if(Vt(u)&&"path"in u){if(!a.find((f)=>Vt(f)&&("path"in f)&&f.path===u.path))a.push(u)}else if(!a.some((m)=>td(m,u)))a.push(u);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let u of e)if(!a.includes(u))a.push(u);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 u=t[a];if(u===null||u===void 0)continue;else if(Vt(u)&&Vt(r[a]))r[a]=up(r[a],u);else if(Array.isArray(u)&&Array.isArray(r[a]))if(u.length>0&&r[a].length>0&&Vt(u[0])&&Vt(r[a][0])){let m=[...u];for(let f of r[a])if(Vt(f)&&"name"in f){if(!m.find((w)=>Vt(w)&&("name"in w)&&w.name===f.name))m.push(f)}else if(Vt(f)&&"path"in f){if(!m.find((w)=>Vt(w)&&("path"in w)&&w.path===f.path))m.push(f)}else if(!m.some((b)=>td(b,f)))m.push(f);r[a]=m}else if(u.every((m)=>typeof m==="string")&&r[a].every((m)=>typeof m==="string")){let m=[...u];for(let f of r[a])if(!m.includes(f))m.push(f);r[a]=m}else r[a]=u;else r[a]=u}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 u of r){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!td(e[u],t[u]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function vk(e,t){if(!vh(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 up(t,a)}catch{return null}}catch{return null}}async function bk({name:e="",cwd:t,defaultConfig:r}){let a=t||Yl.cwd(),u=[".ts",".js",".mjs",".cjs",".json"],m=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let f of m)for(let b of u){let w=Xc(a,`${f}${b}`),y=await vk(w,r);if(y!==null)return y}try{let f=Xc(a,"package.json");if(vh(f)){let w=(await import(f))[e];if(w&&typeof w==="object"&&!Array.isArray(w))try{return up(r,w)}catch{}}}catch{}return r}function Sk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Qm(r,"..");let a=Qm(r,e||"");if(t?.relative)return Dw(Zc.cwd(),a);return a}async function wk(){try{let e=await bk({name:"clarity",defaultConfig:Hc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Hc,...e}}catch{return Hc}}function tr(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kk(){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 Sh{async format(e){let t=await kk(),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:zo.pid,hostname:t(),environment:zo.env.NODE_ENV||"development",platform:zo.platform,version:zo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:zo.env.NODE_ENV||zo.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={...Xl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Sh,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 u=this.generateKeyId(),m=this.generateKey();this.currentKeyId=u,this.keys.set(u,m),this.encryptionKeys.set(u,{key:m,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:Xl.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 u,m=0,f=3,b=1000;while(m<f)try{try{try{await Bw(this.config.logDirectory,ef.F_OK|ef.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Mw(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 w=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(u=Xm(this.currentLogFile,"a",420),jw(u,w,{flag:"a"}),Zm(u),u!==void 0)Pl(u),u=void 0;if((await Mo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,w,{flag:"w",mode:420}),(await Mo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let I=y;if(I.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(I.code)){if(m<f-1){let A=typeof I.message==="string"?I.message:"Unknown error";console.error(`Network error during write attempt ${m+1}/${f}:`,A);let D=b*2**m;await new Promise((O)=>setTimeout(O,D)),m++;continue}}if(I?.code&&["ENOSPC","EDQUOT"].includes(I.code))throw Error(`Disk quota exceeded or no space left on device: ${I.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",I),I}finally{if(u!==void 0)try{Pl(u)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(w){if(m===f-1){let I=w,A=typeof I.message==="string"?I.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",A),w}m++;let y=b*2**(m-1);await new Promise((I)=>setTimeout(I,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(u){throw console.error("Debug: [writeToFile] Error in operation:",u),u}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 Fo(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 Fo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Fo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(tr())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((u)=>{console.error("Error rotating keys:",u)})},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 u=Array.from(this.encryptionKeys.entries()).sort(([,b],[,w])=>w.createdAt.getTime()-b.createdAt.getTime()),m=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,m);if(u.length>f)for(let[b]of u.slice(f))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Cl(16).toString("hex")}generateKey(){return Cl(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=Cl(16),a=Ow("aes-256-gcm",t,r),u=Ci.concat([a.update(e,"utf8"),a.final()]),m=a.getAuthTag();return{encrypted:Ci.concat([r,u,m]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=rf(),u=[];a.on("data",(m)=>u.push(m)),a.on("end",()=>t(Ci.from(Ci.concat(u)))),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(tr())return;let e=await Mo(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 u=await xc(this.config.logDirectory),m=u.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,y)=>{let I=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-I}),f=m.length>0?Number.parseInt(m[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${f}`;if(await Mo(r).catch(()=>null))try{if(await tf(r,b),t.compress)try{let w=`${b}.gz`;await this.compressLogFile(b,w),await Dc(b)}catch(w){console.error("Error compressing rotated file:",w)}if(m.length===0&&!u.some((w)=>w.endsWith(".log.1")))try{let w=`${r}.1`;await xl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let u=new Date().toISOString().replace(/[:.]/g,"-"),m=r.replace(/\.log$/,`-${u}.log`);if(await Mo(r).catch(()=>null))await tf(r,m)}if(this.currentLogFile=a,t.maxFiles){let m=(await xc(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,b)=>b.localeCompare(f));for(let f of m.slice(t.maxFiles))await Dc(Fo(this.config.logDirectory,f))}}}async compressLogFile(e,t){let r=Ym(e),a=Nw(t),u=rf();await Lw(r,u,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=Xm(this.currentLogFile,"r+");Zm(e),Pl(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(!tr()&&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(Fo(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?Mt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:u,level:m,showTimestamp:f=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(f)O.push(t);if(m==="warning")O.push("WARN");else if(m==="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(u),O.join(" ")}let w=Tr.stdout.columns||120,y="";if(m==="warning"||m==="error")y=`${r} ${u}`;else if(m==="info"||m==="success")y=`${r} ${a} ${u}`;else y=`${r} ${a} ${Mt.cyan(u)}`;if(!f)return y.trim();let I=b(y).trim().length,A=b(t).length,D=Math.max(1,w-2-I-A);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(m,f)=>{let b=Number.parseInt(f,10);return b<t[0].length?String(t[0][b]):m});let r=/%([sdijfo%])/g,a=0,u=e.replace(r,(m,f)=>{if(f==="%")return"%";if(a>=t.length)return m;let b=t[a++];switch(f){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 m}});if(a<t.length)u+=` ${t.slice(a).map((m)=>typeof m==="object"?JSON.stringify(m,null,2):String(m)).join(" ")}`;return u}async log(e,t,...r){let a=new Date,u=this.formatConsoleTimestamp(a),m=this.formatFileTimestamp(a),f,b;if(t instanceof Error)f=t.message,b=t.stack;else f=this.formatMessage(t,r);if(this.fancy&&!tr()){let y=xh[e],I=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",A;switch(e){case"debug":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.gray(f),level:e}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A);break;case"success":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:Mt.green(f),level:e}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:u,icon:y,tag:I,message:f,level:e}),console.error(A),b){let D=b.split(`
|
|
2
2
|
`);for(let O of D)if(O.trim()&&!O.includes(f))console.error(this.formatConsoleMessage({timestamp:u,message:Mt.gray(` ${O}`),level:e,showTimestamp:!1}))}break}}else if(!tr()){if(console.error(`${m} ${this.environment}.${e.toUpperCase()}: ${f}`),b)console.error(b)}if(!this.shouldLog(e))return;let w=`${m} ${this.environment}.${e.toUpperCase()}: ${f}
|
|
3
3
|
`;if(b)w+=`${b}
|
|
4
4
|
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(e){let t=performance.now();if(this.fancy&&!tr()){let r=this.options.showTags!==!1&&this.name?Mt.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:Mt.blue("◐"),tag:r,message:`${Mt.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),u=Math.round(a-t),m=`${e} completed in ${u}ms`,f=new Date,b=this.formatConsoleTimestamp(f),y=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${m}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{wn,Rn,Ku,ys,Wu,Ju,Xu,za,Yu,Zu,dh,eg,E,tg,Ss,Me,rg,ng,$S,ig,sg,og,ag,cg,lh,MS,FS,US,uh,gh,QS,HS,ph,mh,GS,Is,Ar,Ka,Dn,Pn,yr,ct,Lt,bs,fh,kn,dg,lg,Wa,Es,Bn,vs,dc}from"../chunk-
|
|
1
|
+
import{wn,Rn,Ku,ys,Wu,Ju,Xu,za,Yu,Zu,dh,eg,E,tg,Ss,Me,rg,ng,$S,ig,sg,og,ag,cg,lh,MS,FS,US,uh,gh,QS,HS,ph,mh,GS,Is,Ar,Ka,Dn,Pn,yr,ct,Lt,bs,fh,kn,dg,lg,Wa,Es,Bn,vs,dc}from"../chunk-m0vnrgdz.js";import{lc,xn,On,Ts,ws,Rs,Ds,uc,gc}from"../chunk-94z7s8ky.js";import{pc}from"../chunk-hybz2q8w.js";import"../chunk-nhsefr22.js";import"../chunk-qyr5hn6v.js";import"../chunk-stc3ykm3.js";import"../chunk-vgtqd3sb.js";import"../chunk-mp2y4t6w.js";import"../chunk-smt4t6rc.js";import"../chunk-y7k5872m.js";import{Dg,kc,Pg,De,Nc,Wn,kg,Bc,rd,no,nd,Jt,vi,io}from"../chunk-fdr2cr9r.js";import"../chunk-yt8qgn5d.js";import"../chunk-80bgb48v.js";import"../chunk-d245va6b.js";import"../chunk-jyvnfny6.js";import"../chunk-e42gpavb.js";import{It,AA,md,ki,Ni,Bi,Mp}from"../chunk-apj1eqcy.js";import{U,Vr,qr,fd,po,d,yA,Fp,Up,CI,EI}from"../chunk-2hma3g5q.js";import"../chunk-430acqjk.js";import"../chunk-zvcd6x45.js";import"../chunk-a99wz633.js";export{AA as DEFAULT_SITE_PORT_RANGE,It as HOST_SITES_DIR,Nc as IPV6_EXCLUDED_HOST_LABELS,rd as MANAGEMENT_DASHBOARD_SITE,wn as addSiteToCloudConfig,Mp as allocateSitePorts,GS as buildAndPushContainerImage,pc as buildAndPushServerlessImage,Ar as buildFunctionEnv,Ni as buildHostSitePortsScript,io as buildManagementDashboardArtifact,Lt as buildServerTopology,bs as buildServerlessTopology,fh as buildTopology,Wa as collectEgressMetrics,Dg as collectServerDnsDomains,mh as createContainerImageDependencies,uh as createExistingStaticFullStackDependencies,lh as createStaticApiOriginDependencies,Bn as dashboardActions,no as dashboardCredentialsFile,rg as dashboardPageRoutes,ag as deleteFailoverReplicaBuckets,uc as deleteStaticSite,QS as deployExistingStaticFullStack,Ka as deployServerlessApp,EI as deployShipsFiles,cg as deploySite,MS as deployStaticApiOrigin,ws as deployStaticSite,gc as deployStaticSiteFull,xn as deployStaticSiteWithExternalDns,On as deployStaticSiteWithExternalDnsFull,dg as egressReportMetrics,E as ensureDashboardActor,ig as ensureFailoverReplicaBuckets,vi as ensureManagementDashboard,HS as estimateExistingStaticFullStackMonthlyCost,US as estimateStaticApiOriginMonthlyCost,lg as fetchEgressReport,gh as generateExistingStaticFullStackTemplate,lc as generateExternalDnsStaticSiteTemplate,Ts as generateStaticSiteTemplate,sg as grantFailoverReplicaAccess,yA as hasComputeConfigured,fd as hasProxyUpstream,ph as hashContainerContext,Wn as hostAcceptsIpv6,Is as infraEnvFromOutputs,tg as initializeDashboardControlPlane,Ds as invalidateCache,Vr as isPhpSite,za as isValidHostname,De as normalizePublicIpv6,ki as occupiedHostPorts,Bi as parseHostSiteFragments,md as parseUpstreamPort,kg as reconcileAddressRecords,Dn as redeployServerlessApp,Pg as removeAddressRecords,Rn as removeSiteFromCloudConfig,kc as removeStaleServerAddressRecords,Yu as renderAliasesValue,Xu as renderEnvValue,Zu as renderRedirectsValue,dh as renderSiteSnippet,Wu as renderSslValue,Ju as renderStringValue,vs as resolveDashboardAction,nd as resolveDashboardAuth,kn as resolveDashboardData,ng as resolveLegacyDashboardRoute,qr as resolveProxyUpstreams,po as resolveSiteDeployTarget,d as resolveSiteKind,Jt as resolveUiSource,Pn as rollbackServerlessApp,$S as routesForDashboard,ct as runRemoteCommand,Es as sanitizeCloudConfig,og as seedFailoverReplicas,eg as setAttachToInCloudConfig,yr as setMaintenance,ys as setSitePropertyInCloudConfig,Up as shipsARelease,CI as shipsToBucket,U as siteInstallBase,dc as startLocalDashboardServer,Ss as synchronizeDashboardUsers,Me as trackDashboardOperation,Ku as updateSiteInCloudConfig,Rs as uploadStaticFiles,Fp as validateDeploymentConfig,Bc as verifyAddressRecord,FS as verifyStaticApiOrigin};
|
package/dist/drivers/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Jn,jt,Pr,zt,Xn,M,Br,Yn,Zn,xr,Or,Bh,xh,Lg,$g,Oh,_h,Lh,_r,ei,Mg,Ys,ti,ri,ni,ii,si,xc,Oc,oi,Lr,Se,_c,ai,Lc,ci,$c,$r,Fc,Ve,se,Zs,Fg,Uc,Qc,Hc,Gc,Vc,mt,qe,je,ft,di,li,Pe,eo,qc,Ug,Qg,jc,Hg,ht,ui,zc,Gg,Vg,Kc,Mr,ke,Wc,qg,jg,to,gi,At,zg,Kg,Wg,Jg,Xg,Yg,Zg,ep,tp,pi,mi,fi,hi,Ai,yi,Si,rp,np,Fr,F,ro,ip,sp,op,Jc,ap,cp,$h,Mh,Fh,Xc,dp,Uh,Qh,Hh,Ii,bi,Ci,Ei,Yc,Zc,ed,td,Gh,so,id,Ti,sd,lp,up,gp,Vh}from"../chunk-
|
|
1
|
+
import{Jn,jt,Pr,zt,Xn,M,Br,Yn,Zn,xr,Or,Bh,xh,Lg,$g,Oh,_h,Lh,_r,ei,Mg,Ys,ti,ri,ni,ii,si,xc,Oc,oi,Lr,Se,_c,ai,Lc,ci,$c,$r,Fc,Ve,se,Zs,Fg,Uc,Qc,Hc,Gc,Vc,mt,qe,je,ft,di,li,Pe,eo,qc,Ug,Qg,jc,Hg,ht,ui,zc,Gg,Vg,Kc,Mr,ke,Wc,qg,jg,to,gi,At,zg,Kg,Wg,Jg,Xg,Yg,Zg,ep,tp,pi,mi,fi,hi,Ai,yi,Si,rp,np,Fr,F,ro,ip,sp,op,Jc,ap,cp,$h,Mh,Fh,Xc,dp,Uh,Qh,Hh,Ii,bi,Ci,Ei,Yc,Zc,ed,td,Gh,so,id,Ti,sd,lp,up,gp,Vh}from"../chunk-fdr2cr9r.js";import{ao,lo,uo,qh,cd,B,Xt,bI,go,hp,ze,G,Ne}from"../chunk-yt8qgn5d.js";import"../chunk-80bgb48v.js";import"../chunk-d245va6b.js";import"../chunk-jyvnfny6.js";import"../chunk-e42gpavb.js";import"../chunk-2hma3g5q.js";import"../chunk-zvcd6x45.js";import"../chunk-a99wz633.js";export{td as AwsBoxProvisioner,Br as AwsDriver,op as BOOT_PARTITION_LABEL,ro as CloudDriverFactory,$g as DEFAULT_HOST_CLEANUP_ESCALATED,_h as DEFAULT_HOST_CLEANUP_HIGH_WATER_PERCENT,Oh as DEFAULT_HOST_CLEANUP_LOW_WATER_PERCENT,Lg as DEFAULT_HOST_CLEANUP_RETENTION,Lh as DEFAULT_HOST_CLEANUP_SCHEDULE,ao as DEFAULT_RPX_CERTS_DIR,sp as FIRST_BOOT_SCRIPT_PATH,Or as HOST_ARTIFACT_CACHE_DIR,Bh as HOST_CLEANUP_SCRIPT_PATH,xh as HOST_CLEANUP_UNIT,ed as HetznerBoxProvisioner,$r as HetznerClient,Pe as HetznerDriver,Vc as LEGACY_DRIVER_STATE_DIR,eo as LocalBoxDriver,up as MANAGED_CACHE_POLICY_DISABLED,lp as MANAGED_CACHE_POLICY_OPTIMIZED,gp as MANAGED_ORIGIN_REQUEST_POLICY_ALL_VIEWER,jg as RASPBERRY_PI_DEFAULT_SWAP_GB,$c as REMOTE_SCRIPT_RUNNER,go as RPX_DIR,hp as RPX_LAUNCHER_PATH,ze as RPX_SERVICE_NAME,Wc as SSH_BOOTSTRAP_MARKER_DIR,ke as SSH_BOOTSTRAP_VERSION,At as SSH_DEFAULTS,Si as SSH_DEPLOY_STORAGE_PATH,Ug as SSH_INSECURE_HOST_KEY_OPTS,Qg as SSH_KEEPALIVE_OPTS,mi as SSH_PREFLIGHT_SCRIPT,rp as SSH_SKIP_BOOTSTRAP_ENV,Fr as SshDriver,Mr as SystemSshTransport,Yc as UBUNTU_2404_AMI_PARAM,Hh as acquireResizeLock,$h as applyHetznerHostOptimization,li as applyHetznerVolumes,to as assertArchSupported,np as assertSshComputeConfig,xc as buildAwsArtifactFetch,Zc as buildBoxUserData,Vh as buildCloudFrontOriginConfig,Jc as buildCloudInitFirstBoot,Zn as buildComputeStorageInstallScript,xr as buildComputeStorageSiteScript,cp as buildHetznerHostOptimizationScript,ti as buildHostCleanupDeployScript,Mg as buildHostCleanupExecutable,Ys as buildHostCleanupInstallScript,ei as buildHostCleanupScript,Oc as buildLocalArtifactFetch,B as buildRpxConfig,Ne as buildRpxFragmentRefreshScript,Xt as buildRpxLbConfig,G as buildRpxProvisionScript,Hg as buildScpArgsFor,ni as buildSiteDeployScript,oi as buildSshArgs,jc as buildSshArgsFor,gi as buildSshBootstrapScript,ii as buildStaticSiteDeployScript,ip as cloudDrivers,Mh as collectHetznerHostOptimizationReport,Qc as collectHetznerResizeManifest,Gh as createBoxProvisioner,F as createCloudDriver,id as deployAllComputeSites,so as deploySiteRelease,cd as deriveRouteId,Jn as describeScriptSyntaxError,mt as driverStateDir,qe as driverStatePath,bi as ensureFirewall,Ci as ensureServer,Ii as ensureSshKey,hi as evaluatePreflight,Uc as executeHetznerServerResize,Vg as findKnownHostKey,yi as formatPreflightFindings,jt as formatSshFailure,uo as gatewayHostnames,M as generateUbuntuAppCloudInit,lo as hasAutoWwwVariant,qc as isBoxMode,Fg as isHetznerCapacityError,Xn as isLocalDatabase,Gg as knownHostsLine,zc as knownHostsToken,qh as normalizeRoutePath,Ve as normalizeSshPublicKey,fi as parsePreflightFacts,Zs as planHetznerServerResize,di as planHetznerVolumes,Ai as preflightFailed,Hc as prepareHetznerResize,je as readDriverState,Uh as readResizeCheckpoint,si as releaseTarballTmpPath,Ti as reloadRpxGateway,ci as remoteScriptRunner,bI as renderRpxLauncher,sd as renewRpxCertificates,Xc as resizeCheckpointPath,dp as resizeLockPath,Yn as resolveComputeVolumes,ri as resolveExecStart,Fc as resolveHetznerApiToken,ap as resolveHetznerHostOptimizationPlan,_r as resolveHostCleanupConfig,Xg as resolveSshHostKeyPolicy,zg as resolveSshHosts,tp as resolveSshLan,Wg as resolveSshPort,Jg as resolveSshPrivateKeyPath,Zg as resolveSshProfile,ep as resolveSshPublicIp,pi as resolveSshSettings,Yg as resolveSshSudo,Kg as resolveSshUser,ui as scanHostKey,_c as scpUpload,Ei as serverPublicIpv4,qg as sshBootstrapMarkerPath,Lr as sshExec,Se as sshExecOrThrow,ht as sshHostKeyFingerprint,Kc as sshKnownHostsPath,zt as summarizeRemoteFailures,Pr as surfaceRemoteNotices,Fh as verifyHetznerHostOptimization,Gc as verifyHetznerResize,Lc as waitForCloudInit,ai as waitForSsh,se as wrapCloudInitUserData,ft as writeDriverState,Qh as writeResizeCheckpoint};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{DI,PI,el,um,tl,rl,on,Q,l,nl,gm,K,il,g,zA,b,Xe,zi,an,w,be,sl,KA,r,t,kI,NI,p,BI,xI,OI,_I,LI,sr,ol,Ki,WA,$I,MI,xe,Ye,al,pm,mm,FI,fm,hm,Am,Mo,cl,ce,cn,Tt,Fo,wt,Ce,JA,dl,Uo,ym,Sm,Im,bm,ll,UI,W,C,XA,YA,Cm,a,y,Ze,m,Em,et,J,Rt,QI,vm,X,ul,Oe,or,Qo,de,gl,le,ZA,Ho,Y,Z,_,Wi,D,ar,Dt,ee,e,dn,HI,Tm,pl,GI,VI,qI,jI,ml,zI,KI,WI,JI,XI,YI,ZI,eb,tb,rb,nb,ib,ey,ty,ry,ny,iy,sy,oy,cr,wm,Rm,dr,Ji,sb,Dm,ob,ab,ln,cb,db,lb,ub,gb,pb,ay,cy,dy,ly,uy,Xi,mb,Go,gy,Pm,V,py,tt,Vo,Pt,my,km,fy,hy,Ay,Nm,q,fb,hb,Ab,yb,yy,Sb,te,Ib,bb,Cb,fl,hl,Sy,Bm,xm,Eb,vb,Tb,wb,Rb,Iy,Al,Db,Pb,kb,Nb,Bb,by,Cy,xb,Ob,_b,Lb,$b,Mb,Fb,Ey,Ub,Om,yl,Qb,Hb,Gb,Vb,_m,Lm,$m,qb,Sl,vy,Ty,wy,Ry,Il,Dy,jb,zb,Kb,Wb,Jb,Xb,Yb,Py,ky,Ny,By,Mm,Zb,eC,tC,rC,nC,iC,sC,oC,aC,xy,Oy,_y,Ly,cC,dC,Fm,lC,Um,Qm,Hm,Gm,uC,gC,pC,mC,_e,Yi,fC,hC,AC,yC,SC,IC,bC,CC,$y,EC,vC,Vm,qm,TC,wC,My,RC,DC,PC,kC,NC,BC,xC,OC,_C,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,bl,Fy,Cl,Uy,El,Qy,vl,Hy,Tl,Gy,lr,Vy,wl,qy,Zi,jy,Rl,zy,Dl,Ky,jm,KC,zm,WC,Pl,Wy,ur,Jy,Km,JC,kl,Xy,Wm,XC,Jm,YC,Xm,ZC,Nl,Yy,Ym,eE,Zm,tE,ef,rE,tf,nE,Bl,Zy,xl,eS,rf,iE,nf,sE,sf,oE,of,aE,af,cE,cf,dE,Ol,tS,df,lE,lf,uE,uf,gE,gf,pE,pf,mE,mf,fE,ff,hf,Af,yf,Sf,hE,If,AE,bf,yE,Cf,SE,rt,Ef,rS,qo,_l,un,nS,es,gr,Ll,$l,iS,sS,Ml,vf,Fl,Tf,IE,bE,jo,zo,Ko,Ul,gn,Ql,Hl,ts,Wo,Jo,wf,oS,aS,cS,CE,Rf,Df,EE,dS,Pf,lS,uS,gS,vE,kf,pn,Gl,Nf,TE,pS,Xo,Yo,Vl,Bf,wE,ql,mS,xf,RE,Of,DE,_f,PE}from"./chunk-zvcd6x45.js";import{jl,k,zl,Zo,fS,Lf,hS,AS,yS,SS,IS,bS,CS,ES}from"./chunk-a99wz633.js";import{sa,$f,eu,RS,ss,tu,oa,Mf,Ff,fn,aa,ru,it,nu,iu,su,os,hn,Uf,st,ou,ca,da,la,au,cu,du,as,ua,lu,An,cs,ga,kt,Qf,uu,gu,Hf,pu,pa,pr,mu,fu,hu,Au,ot,Gf,yu,mr,ma,fa,ha,ds,ls,yn,Su,us,Aa,ya,Sn,Iu,In,Vf,qf,Nt,bn,Sa,jf,bu,Cu,Ia,Eu,vu,Tu,DS,ue,wu,PS,kS,gs,ps,NS,Ee,zf,Bt,Le,$e,xt,Ru,Du,Pu,ku,Kf,Wf,ba,Jf,Xf,Ca,Nu,Bu,Yf,ge,Zf,xu,ve,Ea,at,Ot,_t,Cn,ms,Ou,BS,eh,th,rh,nh,va,Ta,_u,wa,En,Ra,Lu,fs,$u,Da,Pa,ka,Na,Ba,xa,Oa,_a,Mu,fr,La,Fu,vn,Uu,$a,Ma,Qu,hr,Fa,Ua,ih,xS,hs,OS,_S,LS,Qa,Ha,Hu,sh,Ga,Tn,Gu,As,Vu,qu,ju,Va,oh,qa,zu,ah,ja,ch,wn,Rn,Ku,ys,eg,ig,sg,og,ag,cg,Is,Ar,Ka,Dn,Pn,yr,ct,hh,Ja,Ah,yh,ug,Xa,Cs,gg,Ya,$t,Fe,pg,Za,ec,mg,tc,rc,nc,ic,fg,hg,Nn,sc,oc,ac,cc,Ag,Es,Bn,vs,dc}from"./chunk-07z9bps2.js";import{U,qr,fd,po,d,Fp,Up}from"./chunk-2hma3g5q.js";import{It,md,ki,Ni,Bi,Mp}from"./chunk-apj1eqcy.js";import{zh,Kh,Wh,Sp,Ip,bp,Jh,Cp,Ep,Xh,Yh,vp,Zh,eA,gd,Tp,tA,rA,wp,nA,iA,sA,oA,aA,cA,dA,Pi,pd,Rp,Dp,Pp,kp,Np,Bp,xp,Op,_p,Lp,$p,lA,uA,gA,pA,mA,fA,hA}from"./chunk-184bvh5s.js";import{Ke,hd,Ie,Yt,Ad,x,Zt,bt,yd,mo,SA,Qp,Sd,s,xi,fo,jr,Id,bd,zr,IA,Cd,vI,TI,ho,wI,RI,Ed,vd,Oi,Ao,ae,c,yo,We,Kr,bA,CA,Td,EA,So,vA,TA,Io,wd,Wr,bo,wA,er,Rd,Hp,tr,Jr,RA,Co,DA,O,PA,Dd,Gp,Eo,kA,NA,BA,Pd,_i,vo,kd,rr,Ct,xA,Xr,OA,Nd,Vp,qp,To,Bd,xd,Et,jp,Li,Od,wo,Yr,zp,$i,_d,Ld,Mi,Kp,$d,Md,Fd,Ud,Ro,Wp,Jp,_A,Xp,Qd,Fi,Yp,Zp,Do,Zr,Po,ko,No,Hd,em,Gd,Bo,LA,nr,$A,Vd,en,qd,MA,jd,tm,Ui,tn,xo,Qi,Je,FA,rm,nm,ir,zd,Kd,Wd,Hi,Gi,Vi,UA,QA,vt,Oo,HA,rn,im,_o,GA,sm,om,am,VA,cm,dm,qA,i,jA,qi,Lo,$o}from"./chunk-430acqjk.js";import{n}from"./chunk-e42gpavb.js";import{Re,gt,Vn}from"./chunk-qyr5hn6v.js";import{o}from"./chunk-jyvnfny6.js";import{Te,Ns,Bs,Ig,mc,fc,xs,hc,dt,re,lt,pe,v,we,Ln,Ac,Ue,yc,$n,Mn,Un,Mt,Ft,Ut,Qn,Ir,Sc,br,Cr,ut,Hn,bc,Qt,Er,Gn,Ec,Tg,wg,vc,vr}from"./chunk-nhsefr22.js";import{pt,he,Ge,Rg,Ht,wc,Rc,Gt,H,qn,Vt,qt,jn,$s,Ms,Tr,wr,zn,Rr,Fs,Us,Qs,Hs,ie,Gs,Vs,qs,js,Ae,zs,Ks,Ws,N,Dc,Kn,Pc,ye,Dr}from"./chunk-smt4t6rc.js";import{ne}from"./chunk-mp2y4t6w.js";import{Dg,kc,Pg,De,Nc,Wn,kg,Bc,Ng,Bg,Nh,Xn,Xs,M,Br,Yn,Zn,xr,_r,ei,Ys,ti,ri,ni,ii,oi,Lr,Se,_c,ai,Lc,$r,Fc,Ve,se,qe,je,ft,di,li,Pe,Mr,ke,gi,pi,mi,fi,hi,Ai,yi,Fr,F,ro,ip,Jc,Ii,bi,Ci,Ei,rd,no,nd,Jt,vi,io,so,id,Ti,sd}from"./chunk-b11w48de.js";import{ao,lo,uo,B,Ne}from"./chunk-yt8qgn5d.js";import{Kl,ea,rs,ns,ta,Wl,Jl,is,ra,na,Yl,Zl,ia}from"./chunk-gmtds745.js";import{lc,xn,On,Ts,ws,Rs,Ds,uc,gc}from"./chunk-94z7s8ky.js";import{pc}from"./chunk-hybz2q8w.js";import{Tc,Qe,S}from"./chunk-stc3ykm3.js";import{He}from"./chunk-vgtqd3sb.js";import{I}from"./chunk-y7k5872m.js";import{oe,wi,oo,od,Ri,pp}from"./chunk-wbbbpt4v.js";import{Qr,Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{Jd,nn,Xd,Yd,Zd,ji,lm,sn}from"./chunk-qjp3f5y8.js";import{vS,nt}from"./chunk-c482jhc6.js";var qh="https://api.machines.dev/v1";class Ls extends Error{status;path;constructor(u,f,R){super(u);this.status=f;this.path=R;this.name="FlyApiError"}}function Qc(u){let f=u.ip.includes(":");if(f&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return f?"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,f,R={}){let A=new URL(`https://api.machines.dev/v1${f}`);for(let[L,z]of Object.entries(R.query??{}))A.searchParams.set(L,z);let T=await this.fetch(A,{method:u,headers:{Authorization:`Bearer ${this.token}`,...R.body!==void 0?{"Content-Type":"application/json"}:{},...R.headers},body:R.body===void 0?void 0:JSON.stringify(R.body)});if(T.status===404&&R.notFound==="null")return null;let E=await T.text(),P=E?yp(E):void 0;if(!T.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):E||T.statusText;throw new Ls(`Fly.io ${u} ${f} failed (${T.status}): ${L}`,T.status,f)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,f){return this.rest("POST","/apps",{body:{app_name:u,org_slug:f}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:f})}updateMachine(u,f,R,A){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}`,{body:R,headers:{"fly-machine-lease-nonce":A}})}async acquireLease(u,f,R=120){let T=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{body:{ttl:R}})).data?.nonce;if(!T)throw new Ls(`Fly.io gave no lease nonce for Machine ${f}`,200,`/machines/${f}/lease`);return T}async releaseLease(u,f,R){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{headers:{"fly-machine-lease-nonce":R}})}async waitForState(u,f,R,A={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/wait`,{query:{state:R,timeout:String(A.timeoutSeconds??60),...A.instanceId?{instance_id:A.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...f,encrypted:!0}})}async setSecrets(u,f){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:f}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,f){let R=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:f}});if(!R.ip)throw new Ls(`Fly.io assigned no ${f} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:R.ip,shared:R.shared??f==="shared_v4",region:R.region}}async requestCertificate(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:f}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var Wc="ts-cloud-role";function $S(u,f){let R=u.fly??{},A=R.app??`${u.project.slug}-${f.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(A))throw Error(`"${A}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let T=R.internalPort??3000,E=R.count??1;if(!Number.isInteger(E)||E<1)throw Error(`fly.count must be a whole number of at least 1, got ${E}.`);return{app:A,org:R.org??"personal",image:f.image,regions:R.regions?.length?R.regions:["iad"],count:E,internalPort:T,healthPath:R.healthPath??"/",vm:{cpuKind:R.vm?.cpuKind??"shared",cpus:R.vm?.cpus??1,memoryMb:R.vm?.memoryMb??512},...R.volume?{volume:{name:R.volume.name??"data",sizeGb:R.volume.sizeGb,path:R.volume.path}}:{},autoStop:R.autoStop??!1,env:{...f.env,PORT:String(T)},secrets:f.secrets??{},hostnames:R.hostnames??[],release:f.release}}function Ap(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:{[Wc]:"app","ts-cloud-release":u.release}}}async function wS(u,f,R=()=>{}){let A=!1;if(!await u.getApp(f.app))R(`Creating Fly app ${f.app} in ${f.org}`),await u.createApp(f.app,f.org),A=!0;let T;if(Object.keys(f.secrets).length>0)T=await u.setSecrets(f.app,f.secrets),R(`Set ${Object.keys(f.secrets).length} secret(s) (version ${T})`);let E=await u.listIpAssignments(f.app),P=new Set(E.map(Qc));if(!P.has("v6"))E.push(await u.assignIp(f.app,"v6")),R("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))E.push(await u.assignIp(f.app,"shared_v4")),R("Assigned a shared IPv4");let L=Ap(f),z=(await u.listMachines(f.app)).filter((Me)=>{let ze=Me.config?.metadata??{};if(ze[Wc])return ze[Wc]==="app";return!ze.fly_process_group||ze.fly_process_group==="app"}),fe=f.volume?await u.listVolumes(f.app):[],me=[],At=[],Lt=new Set;for(let Me of f.regions){let ze=z.filter((j)=>j.region===Me).sort((j,yt)=>j.id.localeCompare(yt.id));for(let j=0;j<f.count;j++){let yt=ze[j];if(yt){Lt.add(yt.id),await tg(u,f.app,yt,L,T),At.push(yt.id),R(`Updated ${yt.id} (${Me}) to ${f.image}`);continue}let G=f.volume?[{volume:(await rg(u,f,Me,fe)).id,path:f.volume.path}]:void 0,ht=await u.createMachine(f.app,{region:Me,name:`${f.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...T!==void 0?{min_secrets_version:T}:{}});await u.waitForState(f.app,ht.id,"started",{instanceId:ht.instance_id}),me.push(ht.id),R(`Created ${ht.id} in ${Me}`)}}let mt=[];for(let Me of f.hostnames)mt.push(await u.requestCertificate(f.app,Me));return{app:f.app,url:`https://${f.app}.fly.dev`,createdApp:A,created:me,updated:At,untouched:z.filter((Me)=>!Lt.has(Me.id)).map((Me)=>Me.id),ips:E,certificates:mt}}async function tg(u,f,R,A,T){let E=await u.acquireLease(f,R.id);try{let P=await u.updateMachine(f,R.id,{config:{...A,...R.config?.mounts?.length?{mounts:R.config.mounts}:{}},...T!==void 0?{min_secrets_version:T}:{}},E);await u.waitForState(f,R.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(f,R.id,E)}}async function rg(u,f,R,A){let T=A.find((P)=>P.region===R&&P.name===f.volume.name&&!P.attached_machine_id);if(T)return T.attached_machine_id="pending",T;let E=await u.createVolume(f.app,{name:f.volume.name,region:R,size_gb:f.volume.sizeGb});return A.push({...E,attached_machine_id:"pending"}),E}import{createHmac as Xl,createSign as ng,timingSafeEqual as lg}from"node:crypto";function eo(u){let f=u instanceof Date?u.getTime():u;if(!Number.isFinite(f))throw TypeError("Media access timestamp must be finite");return Math.floor(f/1000)}function Wu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function dg(u){return Buffer.from(u).toString("base64url")}function Zu(u,f=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let R=f?u.replaceAll("*","wildcard"):u,A=new URL(R);if(!["http:","https:"].includes(A.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!f&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function Ju(u,f){let R=ng("RSA-SHA1");return R.update(u),R.end(),Wu(R.sign(f))}function Yu(u){Zu(u.resource,!0);let R={DateLessThan:{"AWS:EpochTime":eo(u.expiresAt)}};if(u.activeAt!==void 0)R.DateGreaterThan={"AWS:EpochTime":eo(u.activeAt)};if(u.ipAddress)R.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:R}]})}function HS(u,f,R){Zu(u);let A=eo(f),T=u.includes("?")?"&":"?",E=Yu({resource:u,expiresAt:f}),P=Ju(E,R.privateKey);return`${u}${T}Expires=${A}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(R.keyPairId)}`}function US(u,f){let R=Yu(u);return{"CloudFront-Key-Pair-Id":f.keyPairId,"CloudFront-Policy":Wu(Buffer.from(R)),"CloudFront-Signature":Ju(R,f.privateKey)}}function GS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let f=dg(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:eo(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),R=Xl("sha256",u.secret).update(f).digest("base64url");return`${f}.${R}`}function jS(u,f){let[R,A,T]=u.split(".");if(!R||!A||T)return null;let E=Xl("sha256",f.secret).update(R).digest(),P;try{P=Buffer.from(A,"base64url")}catch{return null}if(E.length!==P.length||!lg(E,P))return null;try{let L=JSON.parse(Buffer.from(R,"base64url").toString("utf8")),z=eo(f.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(f.resource&&L.resource!==f.resource)return null;if(f.audience&&L.audience!==f.audience)return null;return L}catch{return null}}function KS(u,f=!1){let R=new URL(u,"https://media.invalid").pathname.toLowerCase(),A=/\.(?:m3u8|mpd|vtt|json)$/.test(R),T=/\.(?:key|license)$/.test(R)||R.includes("/keys/")||R.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":f&&(A||T)?"private, no-store":A?"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 qS(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 f=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",R=u.protected??!1,A="public, max-age=31536000, immutable",T=R?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:f,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.mpd",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.vtt",cacheControl:T,compress:!0,signed:R},{pathPattern:"*",cacheControl:A,compress:!1,signed:R}],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 yg{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new sl(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let f=this.config.environments[this.environment]?.infrastructure;if(!f)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...f,compute:{...this.config.infrastructure?.compute,...f.compute},storage:{...this.config.infrastructure?.storage,...f.storage},functions:{...this.config.infrastructure?.functions,...f.functions},servers:{...this.config.infrastructure?.servers,...f.servers},databases:{...this.config.infrastructure?.databases,...f.databases},cdn:{...this.config.infrastructure?.cdn,...f.cdn},sftp:f.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...f.queues},redirects:{...this.config.infrastructure?.redirects,...f.redirects},realtime:{...this.config.infrastructure?.realtime,...f.realtime},cache:{...this.config.infrastructure?.cache,...f.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...f.fileSystem},email:{...this.config.infrastructure?.email,...f.email},search:{...this.config.infrastructure?.search,...f.search},ai:{...this.config.infrastructure?.ai,...f.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let f=this.config.features||{};if(!u.requiresFeatures.every((A)=>f[A]===!0))return!1}if(u.regions){let f=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(f))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,f=Number(u||3008);return Number.isFinite(f)&&f>0?f: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,f){return u==="public"||f.routeCompute===!0}storageBucketName(u,f,R){return this.mergedConfig.infrastructure?.storage?.[R]?.bucket??`${u}-${f}-${R}`}fileSystemLogicalId(u,f,R){return t(r({slug:`${u}-${R}`,environment:f,resourceType:"efs"}))}resolveSftpStorage(u,f,R){let A=u.storage;if(A?.type==="efs"&&A.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[A.fileSystem])throw Error(`sftp: storage.fileSystem "${A.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(f,R,A.fileSystem)},posixProfile:A.posixProfile}}if(A?.type==="s3"&&A.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[A.storageBucket])throw Error(`sftp: storage.storageBucket "${A.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(f,R,A.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,f){return{PathPattern:u,TargetOriginId:f,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,f,R,A,T,E){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${A}-${T}-api`,fe=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",me=fe==="us-east-1"?".compute-1.amazonaws.com":`.${fe}.compute.amazonaws.com`,At={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},me]]},Lt=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:At,CustomOriginConfig:{HTTPPort:Lt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),R.push(P),L)R.push(L);for(let mt of E)f.push(this.createComputeCacheBehavior(mt,z))}buildCaddyfile(u){let f=u.filter(([,T])=>typeof T.domain==="string"&&T.domain&&typeof T.port==="number");if(f.length===0)return;let R=new Map;for(let[,T]of f){let E=R.get(T.domain)??[];E.push({port:T.port,path:T.path}),R.set(T.domain,E)}let A=[];for(let[T,E]of R){let L=[...E].sort((z,fe)=>{let me=!z.path||z.path==="/",At=!fe.path||fe.path==="/";if(me&&!At)return 1;if(!me&&At)return-1;return(fe.path?.length??0)-(z.path?.length??0)}).map((z)=>{let fe=!z.path||z.path==="/",me=`reverse_proxy localhost:${z.port}`;return fe?` handle {
|
|
1
|
+
import{DI,PI,el,um,tl,rl,on,Q,l,nl,gm,K,il,g,zA,b,Xe,zi,an,w,be,sl,KA,r,t,kI,NI,p,BI,xI,OI,_I,LI,sr,ol,Ki,WA,$I,MI,xe,Ye,al,pm,mm,FI,fm,hm,Am,Mo,cl,ce,cn,Tt,Fo,wt,Ce,JA,dl,Uo,ym,Sm,Im,bm,ll,UI,W,C,XA,YA,Cm,a,y,Ze,m,Em,et,J,Rt,QI,vm,X,ul,Oe,or,Qo,de,gl,le,ZA,Ho,Y,Z,_,Wi,D,ar,Dt,ee,e,dn,HI,Tm,pl,GI,VI,qI,jI,ml,zI,KI,WI,JI,XI,YI,ZI,eb,tb,rb,nb,ib,ey,ty,ry,ny,iy,sy,oy,cr,wm,Rm,dr,Ji,sb,Dm,ob,ab,ln,cb,db,lb,ub,gb,pb,ay,cy,dy,ly,uy,Xi,mb,Go,gy,Pm,V,py,tt,Vo,Pt,my,km,fy,hy,Ay,Nm,q,fb,hb,Ab,yb,yy,Sb,te,Ib,bb,Cb,fl,hl,Sy,Bm,xm,Eb,vb,Tb,wb,Rb,Iy,Al,Db,Pb,kb,Nb,Bb,by,Cy,xb,Ob,_b,Lb,$b,Mb,Fb,Ey,Ub,Om,yl,Qb,Hb,Gb,Vb,_m,Lm,$m,qb,Sl,vy,Ty,wy,Ry,Il,Dy,jb,zb,Kb,Wb,Jb,Xb,Yb,Py,ky,Ny,By,Mm,Zb,eC,tC,rC,nC,iC,sC,oC,aC,xy,Oy,_y,Ly,cC,dC,Fm,lC,Um,Qm,Hm,Gm,uC,gC,pC,mC,_e,Yi,fC,hC,AC,yC,SC,IC,bC,CC,$y,EC,vC,Vm,qm,TC,wC,My,RC,DC,PC,kC,NC,BC,xC,OC,_C,LC,$C,MC,FC,UC,QC,HC,GC,VC,qC,jC,zC,bl,Fy,Cl,Uy,El,Qy,vl,Hy,Tl,Gy,lr,Vy,wl,qy,Zi,jy,Rl,zy,Dl,Ky,jm,KC,zm,WC,Pl,Wy,ur,Jy,Km,JC,kl,Xy,Wm,XC,Jm,YC,Xm,ZC,Nl,Yy,Ym,eE,Zm,tE,ef,rE,tf,nE,Bl,Zy,xl,eS,rf,iE,nf,sE,sf,oE,of,aE,af,cE,cf,dE,Ol,tS,df,lE,lf,uE,uf,gE,gf,pE,pf,mE,mf,fE,ff,hf,Af,yf,Sf,hE,If,AE,bf,yE,Cf,SE,rt,Ef,rS,qo,_l,un,nS,es,gr,Ll,$l,iS,sS,Ml,vf,Fl,Tf,IE,bE,jo,zo,Ko,Ul,gn,Ql,Hl,ts,Wo,Jo,wf,oS,aS,cS,CE,Rf,Df,EE,dS,Pf,lS,uS,gS,vE,kf,pn,Gl,Nf,TE,pS,Xo,Yo,Vl,Bf,wE,ql,mS,xf,RE,Of,DE,_f,PE}from"./chunk-zvcd6x45.js";import{jl,k,zl,Zo,fS,Lf,hS,AS,yS,SS,IS,bS,CS,ES}from"./chunk-a99wz633.js";import{sa,$f,eu,RS,ss,tu,oa,Mf,Ff,fn,aa,ru,it,nu,iu,su,os,hn,Uf,st,ou,ca,da,la,au,cu,du,as,ua,lu,An,cs,ga,kt,Qf,uu,gu,Hf,pu,pa,pr,mu,fu,hu,Au,ot,Gf,yu,mr,ma,fa,ha,ds,ls,yn,Su,us,Aa,ya,Sn,Iu,In,Vf,qf,Nt,bn,Sa,jf,bu,Cu,Ia,Eu,vu,Tu,DS,ue,wu,PS,kS,gs,ps,NS,Ee,zf,Bt,Le,$e,xt,Ru,Du,Pu,ku,Kf,Wf,ba,Jf,Xf,Ca,Nu,Bu,Yf,ge,Zf,xu,ve,Ea,at,Ot,_t,Cn,ms,Ou,BS,eh,th,rh,nh,va,Ta,_u,wa,En,Ra,Lu,fs,$u,Da,Pa,ka,Na,Ba,xa,Oa,_a,Mu,fr,La,Fu,vn,Uu,$a,Ma,Qu,hr,Fa,Ua,ih,xS,hs,OS,_S,LS,Qa,Ha,Hu,sh,Ga,Tn,Gu,As,Vu,qu,ju,Va,oh,qa,zu,ah,ja,ch,wn,Rn,Ku,ys,eg,ig,sg,og,ag,cg,Is,Ar,Ka,Dn,Pn,yr,ct,hh,Ja,Ah,yh,ug,Xa,Cs,gg,Ya,$t,Fe,pg,Za,ec,mg,tc,rc,nc,ic,fg,hg,Nn,sc,oc,ac,cc,Ag,Es,Bn,vs,dc}from"./chunk-m0vnrgdz.js";import{U,qr,fd,po,d,Fp,Up}from"./chunk-2hma3g5q.js";import{It,md,ki,Ni,Bi,Mp}from"./chunk-apj1eqcy.js";import{zh,Kh,Wh,Sp,Ip,bp,Jh,Cp,Ep,Xh,Yh,vp,Zh,eA,gd,Tp,tA,rA,wp,nA,iA,sA,oA,aA,cA,dA,Pi,pd,Rp,Dp,Pp,kp,Np,Bp,xp,Op,_p,Lp,$p,lA,uA,gA,pA,mA,fA,hA}from"./chunk-184bvh5s.js";import{Ke,hd,Ie,Yt,Ad,x,Zt,bt,yd,mo,SA,Qp,Sd,s,xi,fo,jr,Id,bd,zr,IA,Cd,vI,TI,ho,wI,RI,Ed,vd,Oi,Ao,ae,c,yo,We,Kr,bA,CA,Td,EA,So,vA,TA,Io,wd,Wr,bo,wA,er,Rd,Hp,tr,Jr,RA,Co,DA,O,PA,Dd,Gp,Eo,kA,NA,BA,Pd,_i,vo,kd,rr,Ct,xA,Xr,OA,Nd,Vp,qp,To,Bd,xd,Et,jp,Li,Od,wo,Yr,zp,$i,_d,Ld,Mi,Kp,$d,Md,Fd,Ud,Ro,Wp,Jp,_A,Xp,Qd,Fi,Yp,Zp,Do,Zr,Po,ko,No,Hd,em,Gd,Bo,LA,nr,$A,Vd,en,qd,MA,jd,tm,Ui,tn,xo,Qi,Je,FA,rm,nm,ir,zd,Kd,Wd,Hi,Gi,Vi,UA,QA,vt,Oo,HA,rn,im,_o,GA,sm,om,am,VA,cm,dm,qA,i,jA,qi,Lo,$o}from"./chunk-430acqjk.js";import{n}from"./chunk-e42gpavb.js";import{Re,gt,Vn}from"./chunk-qyr5hn6v.js";import{o}from"./chunk-jyvnfny6.js";import{Te,Ns,Bs,Ig,mc,fc,xs,hc,dt,re,lt,pe,v,we,Ln,Ac,Ue,yc,$n,Mn,Un,Mt,Ft,Ut,Qn,Ir,Sc,br,Cr,ut,Hn,bc,Qt,Er,Gn,Ec,Tg,wg,vc,vr}from"./chunk-nhsefr22.js";import{pt,he,Ge,Rg,Ht,wc,Rc,Gt,H,qn,Vt,qt,jn,$s,Ms,Tr,wr,zn,Rr,Fs,Us,Qs,Hs,ie,Gs,Vs,qs,js,Ae,zs,Ks,Ws,N,Dc,Kn,Pc,ye,Dr}from"./chunk-smt4t6rc.js";import{ne}from"./chunk-mp2y4t6w.js";import{Dg,kc,Pg,De,Nc,Wn,kg,Bc,Ng,Bg,Nh,Xn,Xs,M,Br,Yn,Zn,xr,_r,ei,Ys,ti,ri,ni,ii,oi,Lr,Se,_c,ai,Lc,$r,Fc,Ve,se,qe,je,ft,di,li,Pe,Mr,ke,gi,pi,mi,fi,hi,Ai,yi,Fr,F,ro,ip,Jc,Ii,bi,Ci,Ei,rd,no,nd,Jt,vi,io,so,id,Ti,sd}from"./chunk-fdr2cr9r.js";import{ao,lo,uo,B,Ne}from"./chunk-yt8qgn5d.js";import{Kl,ea,rs,ns,ta,Wl,Jl,is,ra,na,Yl,Zl,ia}from"./chunk-gmtds745.js";import{lc,xn,On,Ts,ws,Rs,Ds,uc,gc}from"./chunk-94z7s8ky.js";import{pc}from"./chunk-hybz2q8w.js";import{Tc,Qe,S}from"./chunk-stc3ykm3.js";import{He}from"./chunk-vgtqd3sb.js";import{I}from"./chunk-y7k5872m.js";import{oe,wi,oo,od,Ri,pp}from"./chunk-wbbbpt4v.js";import{Qr,Be}from"./chunk-80bgb48v.js";import{h}from"./chunk-d245va6b.js";import{Jd,nn,Xd,Yd,Zd,ji,lm,sn}from"./chunk-qjp3f5y8.js";import{vS,nt}from"./chunk-c482jhc6.js";var qh="https://api.machines.dev/v1";class Ls extends Error{status;path;constructor(u,f,R){super(u);this.status=f;this.path=R;this.name="FlyApiError"}}function Qc(u){let f=u.ip.includes(":");if(f&&u.ip.startsWith("fdaa:"))return"private_v6";if(u.shared)return"shared_v4";return f?"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,f,R={}){let A=new URL(`https://api.machines.dev/v1${f}`);for(let[L,z]of Object.entries(R.query??{}))A.searchParams.set(L,z);let T=await this.fetch(A,{method:u,headers:{Authorization:`Bearer ${this.token}`,...R.body!==void 0?{"Content-Type":"application/json"}:{},...R.headers},body:R.body===void 0?void 0:JSON.stringify(R.body)});if(T.status===404&&R.notFound==="null")return null;let E=await T.text(),P=E?yp(E):void 0;if(!T.ok){let L=typeof P==="object"&&P&&"error"in P?String(P.error):E||T.statusText;throw new Ls(`Fly.io ${u} ${f} failed (${T.status}): ${L}`,T.status,f)}return P}getApp(u){return this.rest("GET",`/apps/${encodeURIComponent(u)}`,{notFound:"null"})}createApp(u,f){return this.rest("POST","/apps",{body:{app_name:u,org_slug:f}})}async listMachines(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines`)??[]}createMachine(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines`,{body:f})}updateMachine(u,f,R,A){return this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}`,{body:R,headers:{"fly-machine-lease-nonce":A}})}async acquireLease(u,f,R=120){let T=(await this.rest("POST",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{body:{ttl:R}})).data?.nonce;if(!T)throw new Ls(`Fly.io gave no lease nonce for Machine ${f}`,200,`/machines/${f}/lease`);return T}async releaseLease(u,f,R){await this.rest("DELETE",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/lease`,{headers:{"fly-machine-lease-nonce":R}})}async waitForState(u,f,R,A={}){await this.rest("GET",`/apps/${encodeURIComponent(u)}/machines/${encodeURIComponent(f)}/wait`,{query:{state:R,timeout:String(A.timeoutSeconds??60),...A.instanceId?{instance_id:A.instanceId}:{}}})}async listVolumes(u){return await this.rest("GET",`/apps/${encodeURIComponent(u)}/volumes`)??[]}createVolume(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/volumes`,{body:{...f,encrypted:!0}})}async setSecrets(u,f){return(await this.rest("POST",`/apps/${encodeURIComponent(u)}/secrets`,{body:{values:f}})).version}async listIpAssignments(u){return(await this.rest("GET",`/apps/${encodeURIComponent(u)}/ip_assignments`)).ips??[]}async assignIp(u,f){let R=await this.rest("POST",`/apps/${encodeURIComponent(u)}/ip_assignments`,{body:{type:f}});if(!R.ip)throw new Ls(`Fly.io assigned no ${f} address to ${u}`,200,`/apps/${u}/ip_assignments`);return{ip:R.ip,shared:R.shared??f==="shared_v4",region:R.region}}async requestCertificate(u,f){return this.rest("POST",`/apps/${encodeURIComponent(u)}/certificates/acme`,{body:{hostname:f}})}}function yp(u){try{return JSON.parse(u)}catch{return}}var Wc="ts-cloud-role";function $S(u,f){let R=u.fly??{},A=R.app??`${u.project.slug}-${f.environment}`;if(!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(A))throw Error(`"${A}" is not a valid Fly app name: lowercase letters, digits and dashes, 3 to 63 characters.`);let T=R.internalPort??3000,E=R.count??1;if(!Number.isInteger(E)||E<1)throw Error(`fly.count must be a whole number of at least 1, got ${E}.`);return{app:A,org:R.org??"personal",image:f.image,regions:R.regions?.length?R.regions:["iad"],count:E,internalPort:T,healthPath:R.healthPath??"/",vm:{cpuKind:R.vm?.cpuKind??"shared",cpus:R.vm?.cpus??1,memoryMb:R.vm?.memoryMb??512},...R.volume?{volume:{name:R.volume.name??"data",sizeGb:R.volume.sizeGb,path:R.volume.path}}:{},autoStop:R.autoStop??!1,env:{...f.env,PORT:String(T)},secrets:f.secrets??{},hostnames:R.hostnames??[],release:f.release}}function Ap(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:{[Wc]:"app","ts-cloud-release":u.release}}}async function wS(u,f,R=()=>{}){let A=!1;if(!await u.getApp(f.app))R(`Creating Fly app ${f.app} in ${f.org}`),await u.createApp(f.app,f.org),A=!0;let T;if(Object.keys(f.secrets).length>0)T=await u.setSecrets(f.app,f.secrets),R(`Set ${Object.keys(f.secrets).length} secret(s) (version ${T})`);let E=await u.listIpAssignments(f.app),P=new Set(E.map(Qc));if(!P.has("v6"))E.push(await u.assignIp(f.app,"v6")),R("Assigned a dedicated IPv6");if(!P.has("v4")&&!P.has("shared_v4"))E.push(await u.assignIp(f.app,"shared_v4")),R("Assigned a shared IPv4");let L=Ap(f),z=(await u.listMachines(f.app)).filter((Me)=>{let ze=Me.config?.metadata??{};if(ze[Wc])return ze[Wc]==="app";return!ze.fly_process_group||ze.fly_process_group==="app"}),fe=f.volume?await u.listVolumes(f.app):[],me=[],At=[],Lt=new Set;for(let Me of f.regions){let ze=z.filter((j)=>j.region===Me).sort((j,yt)=>j.id.localeCompare(yt.id));for(let j=0;j<f.count;j++){let yt=ze[j];if(yt){Lt.add(yt.id),await tg(u,f.app,yt,L,T),At.push(yt.id),R(`Updated ${yt.id} (${Me}) to ${f.image}`);continue}let G=f.volume?[{volume:(await rg(u,f,Me,fe)).id,path:f.volume.path}]:void 0,ht=await u.createMachine(f.app,{region:Me,name:`${f.app}-${Me}-${j+1}`,config:{...L,...G?{mounts:G}:{}},...T!==void 0?{min_secrets_version:T}:{}});await u.waitForState(f.app,ht.id,"started",{instanceId:ht.instance_id}),me.push(ht.id),R(`Created ${ht.id} in ${Me}`)}}let mt=[];for(let Me of f.hostnames)mt.push(await u.requestCertificate(f.app,Me));return{app:f.app,url:`https://${f.app}.fly.dev`,createdApp:A,created:me,updated:At,untouched:z.filter((Me)=>!Lt.has(Me.id)).map((Me)=>Me.id),ips:E,certificates:mt}}async function tg(u,f,R,A,T){let E=await u.acquireLease(f,R.id);try{let P=await u.updateMachine(f,R.id,{config:{...A,...R.config?.mounts?.length?{mounts:R.config.mounts}:{}},...T!==void 0?{min_secrets_version:T}:{}},E);await u.waitForState(f,R.id,"started",{instanceId:P.instance_id})}finally{await u.releaseLease(f,R.id,E)}}async function rg(u,f,R,A){let T=A.find((P)=>P.region===R&&P.name===f.volume.name&&!P.attached_machine_id);if(T)return T.attached_machine_id="pending",T;let E=await u.createVolume(f.app,{name:f.volume.name,region:R,size_gb:f.volume.sizeGb});return A.push({...E,attached_machine_id:"pending"}),E}import{createHmac as Xl,createSign as ng,timingSafeEqual as lg}from"node:crypto";function eo(u){let f=u instanceof Date?u.getTime():u;if(!Number.isFinite(f))throw TypeError("Media access timestamp must be finite");return Math.floor(f/1000)}function Wu(u){return Buffer.from(u).toString("base64").replaceAll("+","-").replaceAll("=","_").replaceAll("/","~")}function dg(u){return Buffer.from(u).toString("base64url")}function Zu(u,f=!1){if(!u||/[\r\n]/.test(u))throw TypeError("Media resource is invalid");let R=f?u.replaceAll("*","wildcard"):u,A=new URL(R);if(!["http:","https:"].includes(A.protocol))throw TypeError("Media resource must use HTTP or HTTPS");if(!f&&u.includes("*"))throw TypeError("Canned policies cannot contain wildcards")}function Ju(u,f){let R=ng("RSA-SHA1");return R.update(u),R.end(),Wu(R.sign(f))}function Yu(u){Zu(u.resource,!0);let R={DateLessThan:{"AWS:EpochTime":eo(u.expiresAt)}};if(u.activeAt!==void 0)R.DateGreaterThan={"AWS:EpochTime":eo(u.activeAt)};if(u.ipAddress)R.IpAddress={"AWS:SourceIp":u.ipAddress};return JSON.stringify({Statement:[{Resource:u.resource,Condition:R}]})}function HS(u,f,R){Zu(u);let A=eo(f),T=u.includes("?")?"&":"?",E=Yu({resource:u,expiresAt:f}),P=Ju(E,R.privateKey);return`${u}${T}Expires=${A}&Signature=${encodeURIComponent(P)}&Key-Pair-Id=${encodeURIComponent(R.keyPairId)}`}function US(u,f){let R=Yu(u);return{"CloudFront-Key-Pair-Id":f.keyPairId,"CloudFront-Policy":Wu(Buffer.from(R)),"CloudFront-Signature":Ju(R,f.privateKey)}}function GS(u){if(!u.resource||/[\r\n]/.test(u.resource))throw TypeError("Media resource is invalid");let f=dg(Buffer.from(JSON.stringify({resource:u.resource,expiresAt:eo(u.expiresAt),...u.keyId?{keyId:u.keyId}:{},...u.audience?{audience:u.audience}:{}}))),R=Xl("sha256",u.secret).update(f).digest("base64url");return`${f}.${R}`}function jS(u,f){let[R,A,T]=u.split(".");if(!R||!A||T)return null;let E=Xl("sha256",f.secret).update(R).digest(),P;try{P=Buffer.from(A,"base64url")}catch{return null}if(E.length!==P.length||!lg(E,P))return null;try{let L=JSON.parse(Buffer.from(R,"base64url").toString("utf8")),z=eo(f.now??Date.now());if(!L.resource||!Number.isSafeInteger(L.expiresAt)||L.expiresAt<=z)return null;if(f.resource&&L.resource!==f.resource)return null;if(f.audience&&L.audience!==f.audience)return null;return L}catch{return null}}function KS(u,f=!1){let R=new URL(u,"https://media.invalid").pathname.toLowerCase(),A=/\.(?:m3u8|mpd|vtt|json)$/.test(R),T=/\.(?:key|license)$/.test(R)||R.includes("/keys/")||R.includes("/licenses/");return{"Accept-Ranges":"bytes","Cache-Control":f&&(A||T)?"private, no-store":A?"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 qS(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 f=u.prefix?`/${u.prefix.replace(/^\/+|\/+$/g,"")}`:"",R=u.protected??!1,A="public, max-age=31536000, immutable",T=R?"private, no-store":"public, max-age=5, s-maxage=30, stale-while-revalidate=30";return{originDomain:`${u.bucket}.s3.${u.region}.amazonaws.com`,originPath:f,domain:u.domain,trustedKeyGroupIds:[...new Set(u.trustedKeyGroupIds??[])],behaviors:[{pathPattern:"*.m3u8",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.mpd",cacheControl:T,compress:!0,signed:R},{pathPattern:"*.vtt",cacheControl:T,compress:!0,signed:R},{pathPattern:"*",cacheControl:A,compress:!1,signed:R}],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 yg{builder;config;environment;mergedConfig;serverEipLogicalIds=new Map;storageFailoverReplicas=[];constructor(u){this.config=u.config,this.environment=u.environment,this.builder=new sl(`${this.config.project.name} - ${this.environment}`),this.mergedConfig=this.mergeEnvironmentConfig()}mergeEnvironmentConfig(){let f=this.config.environments[this.environment]?.infrastructure;if(!f)return this.config;return{...this.config,infrastructure:{...this.config.infrastructure,...f,compute:{...this.config.infrastructure?.compute,...f.compute},storage:{...this.config.infrastructure?.storage,...f.storage},functions:{...this.config.infrastructure?.functions,...f.functions},servers:{...this.config.infrastructure?.servers,...f.servers},databases:{...this.config.infrastructure?.databases,...f.databases},cdn:{...this.config.infrastructure?.cdn,...f.cdn},sftp:f.sftp??this.config.infrastructure?.sftp,queues:{...this.config.infrastructure?.queues,...f.queues},redirects:{...this.config.infrastructure?.redirects,...f.redirects},realtime:{...this.config.infrastructure?.realtime,...f.realtime},cache:{...this.config.infrastructure?.cache,...f.cache},fileSystem:{...this.config.infrastructure?.fileSystem,...f.fileSystem},email:{...this.config.infrastructure?.email,...f.email},search:{...this.config.infrastructure?.search,...f.search},ai:{...this.config.infrastructure?.ai,...f.ai}}}}shouldDeploy(u){if(u.environments&&!u.environments.includes(this.environment))return!1;if(u.requiresFeatures){let f=this.config.features||{};if(!u.requiresFeatures.every((A)=>f[A]===!0))return!1}if(u.regions){let f=this.config.environments[this.environment]?.region||this.config.project.region;if(!u.regions.includes(f))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,f=Number(u||3008);return Number.isFinite(f)&&f>0?f: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,f){return u==="public"||f.routeCompute===!0}storageBucketName(u,f,R){return this.mergedConfig.infrastructure?.storage?.[R]?.bucket??`${u}-${f}-${R}`}fileSystemLogicalId(u,f,R){return t(r({slug:`${u}-${R}`,environment:f,resourceType:"efs"}))}resolveSftpStorage(u,f,R){let A=u.storage;if(A?.type==="efs"&&A.fileSystem){if(!this.mergedConfig.infrastructure?.fileSystem?.[A.fileSystem])throw Error(`sftp: storage.fileSystem "${A.fileSystem}" is not defined in infrastructure.fileSystem`);return{type:"efs",fileSystemId:{Ref:this.fileSystemLogicalId(f,R,A.fileSystem)},posixProfile:A.posixProfile}}if(A?.type==="s3"&&A.storageBucket){if(!this.mergedConfig.infrastructure?.storage?.[A.storageBucket])throw Error(`sftp: storage.storageBucket "${A.storageBucket}" is not defined in infrastructure.storage`);return{type:"s3",bucket:this.storageBucketName(f,R,A.storageBucket)}}return}resolveComputeCachePathPatterns(u){if(u&&u.length>0)return u;return this.defaultComputeCachePathPatterns()}createComputeCacheBehavior(u,f){return{PathPattern:u,TargetOriginId:f,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,f,R,A,T,E){let P=this.serverEipLogicalIds.get("app"),L=this.serverEipLogicalIds.get("appInstance");if(!P)return;let z=`EC2-${A}-${T}-api`,fe=this.mergedConfig.infrastructure?.servers?.app?.region||this.mergedConfig.project?.region||"us-east-1",me=fe==="us-east-1"?".compute-1.amazonaws.com":`.${fe}.compute.amazonaws.com`,At={"Fn::Join":["",["ec2-",{"Fn::Join":["-",{"Fn::Split":[".",{Ref:P}]}]},me]]},Lt=this.resolveApiOriginPort();if(u.push({Id:z,DomainName:At,CustomOriginConfig:{HTTPPort:Lt,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}),R.push(P),L)R.push(L);for(let mt of E)f.push(this.createComputeCacheBehavior(mt,z))}buildCaddyfile(u){let f=u.filter(([,T])=>typeof T.domain==="string"&&T.domain&&typeof T.port==="number");if(f.length===0)return;let R=new Map;for(let[,T]of f){let E=R.get(T.domain)??[];E.push({port:T.port,path:T.path}),R.set(T.domain,E)}let A=[];for(let[T,E]of R){let L=[...E].sort((z,fe)=>{let me=!z.path||z.path==="/",At=!fe.path||fe.path==="/";if(me&&!At)return 1;if(!me&&At)return-1;return(fe.path?.length??0)-(z.path?.length??0)}).map((z)=>{let fe=!z.path||z.path==="/",me=`reverse_proxy localhost:${z.port}`;return fe?` handle {
|
|
2
2
|
${me}
|
|
3
3
|
}`:` handle ${z.path} {
|
|
4
4
|
${me}
|
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="mv9ubqhv8q733o"><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="mv9ubqhv8q733o"><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 = [];
|