@stacksjs/ts-cloud 0.16.82 → 0.16.83

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.
Files changed (104) hide show
  1. package/dist/bin/chunk-1gzxerk9.js +1 -0
  2. package/dist/bin/chunk-1nnt30xt.js +1 -0
  3. package/dist/bin/{chunk-33xqndrp.js → chunk-3x9rma7g.js} +1 -1
  4. package/dist/bin/chunk-4kt2sgqk.js +1 -0
  5. package/dist/bin/{chunk-sacx9p6f.js → chunk-5xvvxh1f.js} +4 -4
  6. package/dist/bin/{chunk-wm0rq725.js → chunk-7477zgt9.js} +1 -1
  7. package/dist/bin/{chunk-w9jfrf3v.js → chunk-859pmy2r.js} +8 -8
  8. package/dist/bin/{chunk-6ybjfjbc.js → chunk-8dzqjsz1.js} +1 -1
  9. package/dist/bin/{chunk-3wvpgb8m.js → chunk-8erhr0vh.js} +1 -1
  10. package/dist/bin/{chunk-9gp8p8hv.js → chunk-9p6hkb64.js} +1 -1
  11. package/dist/bin/{chunk-5hmrqjmq.js → chunk-b61yq5rn.js} +1 -1
  12. package/dist/bin/{chunk-20rfyk4x.js → chunk-c4krzg7x.js} +1 -1
  13. package/dist/bin/{chunk-ssnvdxh4.js → chunk-eqw1dk00.js} +1 -1
  14. package/dist/bin/{chunk-462swbg5.js → chunk-f1jkvaxm.js} +1 -1
  15. package/dist/bin/{chunk-nzg624aj.js → chunk-hkgbbph1.js} +1 -1
  16. package/dist/bin/{chunk-zg8nnq7k.js → chunk-kvwm9z1r.js} +1 -1
  17. package/dist/bin/{chunk-jx062xpq.js → chunk-mhmvr5w3.js} +1 -1
  18. package/dist/bin/{chunk-gy29teqh.js → chunk-msvg10yf.js} +1 -1
  19. package/dist/bin/chunk-q82s4yzg.js +1 -0
  20. package/dist/bin/{chunk-y9qdpwa6.js → chunk-rpsnnr53.js} +1 -1
  21. package/dist/bin/{chunk-cxf9pmmw.js → chunk-sbm0ft8c.js} +1 -1
  22. package/dist/bin/{chunk-zn2efqcr.js → chunk-sge03gvm.js} +4 -4
  23. package/dist/bin/{chunk-7848wre2.js → chunk-vr9jcw65.js} +1 -1
  24. package/dist/bin/{chunk-d0m01m6d.js → chunk-yd2vnd4y.js} +1 -1
  25. package/dist/bin/{chunk-k9s81q0g.js → chunk-ydbvafmk.js} +1 -1
  26. package/dist/bin/cli.js +16 -16
  27. package/dist/bin/dashboard-server.js +1 -1
  28. package/dist/{chunk-3wh3hsvp.js → chunk-0f23y8ba.js} +1 -1
  29. package/dist/chunk-2ntc2qz2.js +1 -0
  30. package/dist/{chunk-9w8qtr4p.js → chunk-8drf81qf.js} +1 -1
  31. package/dist/{chunk-n5qbdsbj.js → chunk-9nzmfpwt.js} +48 -48
  32. package/dist/{chunk-cf274f07.js → chunk-bhbv9qqn.js} +1 -1
  33. package/dist/{chunk-k8xv271s.js → chunk-j0tv31q2.js} +2 -2
  34. package/dist/{chunk-1h95atas.js → chunk-kcb203be.js} +1 -1
  35. package/dist/{chunk-5rds38z9.js → chunk-q61qcpp4.js} +53 -53
  36. package/dist/{chunk-eyc2tvze.js → chunk-rq650jaz.js} +1 -1
  37. package/dist/{chunk-dh5m9b05.js → chunk-xyhh44eq.js} +1 -1
  38. package/dist/deploy/index.js +1 -1
  39. package/dist/drivers/index.js +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/mail/index.js +1 -1
  42. package/dist/operations/index.js +1 -1
  43. package/dist/protection/index.js +1 -1
  44. package/dist/spend/index.js +1 -1
  45. package/dist/ui/404.html +1 -1
  46. package/dist/ui/accept-invitation.html +1 -1
  47. package/dist/ui/access-denied.html +1 -1
  48. package/dist/ui/account/automation.html +6 -6
  49. package/dist/ui/account/security.html +2 -2
  50. package/dist/ui/applications/compose.html +6 -6
  51. package/dist/ui/applications/new.html +2 -2
  52. package/dist/ui/data/backups.html +5 -5
  53. package/dist/ui/data/services.html +6 -6
  54. package/dist/ui/data/volumes.html +6 -6
  55. package/dist/ui/index.html +6 -6
  56. package/dist/ui/infrastructure/topology.html +6 -6
  57. package/dist/ui/integrations.html +1 -1
  58. package/dist/ui/operations/alerts.html +6 -6
  59. package/dist/ui/operations/configuration.html +5 -5
  60. package/dist/ui/operations/jobs.html +5 -5
  61. package/dist/ui/operations/maintenance.html +5 -5
  62. package/dist/ui/operations/observability.html +6 -6
  63. package/dist/ui/operations/previews.html +6 -6
  64. package/dist/ui/operations/queue.html +5 -5
  65. package/dist/ui/operations/regions.html +5 -5
  66. package/dist/ui/operations/releases.html +6 -6
  67. package/dist/ui/operations/spend.html +6 -6
  68. package/dist/ui/operations/workloads.html +5 -5
  69. package/dist/ui/security.html +2 -2
  70. package/dist/ui/server/actions.html +6 -6
  71. package/dist/ui/server/activity.html +1 -1
  72. package/dist/ui/server/capacity.html +6 -6
  73. package/dist/ui/server/database.html +6 -6
  74. package/dist/ui/server/deployments.html +6 -6
  75. package/dist/ui/server/diagnostics.html +2 -2
  76. package/dist/ui/server/firewall.html +6 -6
  77. package/dist/ui/server/fleet.html +6 -6
  78. package/dist/ui/server/logs.html +6 -6
  79. package/dist/ui/server/metrics.html +6 -6
  80. package/dist/ui/server/security.html +2 -2
  81. package/dist/ui/server/services.html +1 -1
  82. package/dist/ui/server/sites.html +6 -6
  83. package/dist/ui/server/ssh-keys.html +6 -6
  84. package/dist/ui/server/team.html +6 -6
  85. package/dist/ui/server/terminal.html +2 -2
  86. package/dist/ui/serverless/alarms.html +6 -6
  87. package/dist/ui/serverless/assets.html +2 -2
  88. package/dist/ui/serverless/cost.html +2 -2
  89. package/dist/ui/serverless/data.html +6 -6
  90. package/dist/ui/serverless/deployments.html +2 -2
  91. package/dist/ui/serverless/firewall.html +1 -1
  92. package/dist/ui/serverless/functions.html +6 -6
  93. package/dist/ui/serverless/logs.html +6 -6
  94. package/dist/ui/serverless/metrics.html +2 -2
  95. package/dist/ui/serverless/queues.html +6 -6
  96. package/dist/ui/serverless/secrets.html +6 -6
  97. package/dist/ui/serverless/traces.html +6 -6
  98. package/dist/ui/serverless.html +6 -6
  99. package/package.json +3 -3
  100. package/dist/bin/chunk-4c4q96vm.js +0 -1
  101. package/dist/bin/chunk-9nen8018.js +0 -1
  102. package/dist/bin/chunk-abt0636a.js +0 -1
  103. package/dist/bin/chunk-tpy9t3cv.js +0 -1
  104. package/dist/chunk-5v2wpf1k.js +0 -1
@@ -1,4 +1,4 @@
1
- import{ln,mr}from"./chunk-5rds38z9.js";import{Kr,d}from"./chunk-dh5m9b05.js";import{isIP as L}from"node:net";var go="/etc/rpx/certs",A="/etc/rpx/local-ca",M="rpx-root-ca.crt";function po(e=A){return`${e.replace(/\/+$/,"")}/${M}`}function mo(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function fo(e,t={}){let r=new Set;for(let o of Object.values(e)){if(!o?.domain)continue;if(d(o)==="bucket")continue;r.add(o.domain)}let n=new Set;for(let o of Object.values(e)){if(!o?.domain||d(o)==="bucket")continue;for(let u of o.aliases??[]){let i=String(u).trim().toLowerCase();if(i&&i!==o.domain)n.add(i)}}if(t.autoWww!==!1)for(let o of[...r]){if(!mo(o))continue;r.add(`www.${o}`)}for(let o of n)r.add(o);return[...r]}var k=["1.1.1.1","8.8.8.8"],I="/var/www/acme-challenge";function W(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function U(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function dd(e){if(!e)return;return e.tls??"local-ca"}function Cp(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Ep(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function X(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(L(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function F(e,t,r){let n=[],o=new Set,u=(g,a)=>{let p=g.trim().toLowerCase();if(!p||o.has(p))return;o.add(p),n.push({host:p,source:a})},i=t.hostname?.trim(),c=(i||`${r}.local`).toLowerCase();if(u(c,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([g,a])=>!!a&&mr(g)))u(`dashboard.${c}`,"the management dashboard site");for(let[g,a]of Object.entries(e)){if(!a?.domain)continue;if(d(a)==="bucket")continue;if(!X(a.domain))continue;u(a.domain,`site "${g}"`)}return n}function H(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function K(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let o=H(r,t.allowedSuffixes);if(!o)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${o}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function V(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function D(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function eA(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ld(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Y(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function N(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),o=t.slug??"app",u=t.proxy.certsDir??go,i=t.proxy.loadBalancer,c=[],f=new Set,g=new Map;for(let[l,s]of Object.entries(e)){if(!s||!s.domain)continue;let w=d(s);if(w==="bucket")continue;let v=c.length,E=[...new Set((s.aliases??[]).map((m)=>String(m).trim().toLowerCase()).filter((m)=>m&&m!==s.domain))],b=()=>{let m=c.slice(v).filter((h)=>h.to===s.domain);for(let h of E){for(let O of m)c.push({...O,to:h,id:ld(h,O.path)});if(V(h)){if(!g.has(h))g.set(h,{domain:h,dnsEnvFile:`${n}/${o}-${l}/shared/.env`})}else f.add(h)}},C=eA(s.path),S=ld(s.domain,C),y=U(s);if(w==="redirect"){c.push({to:s.domain,path:C,redirect:W(s.redirect),id:S,...y?{auth:y}:{}}),f.add(s.domain),b();continue}if(w==="proxy"){let m=Kr(s);if(m.length===0)continue;let h=m.length===1?m[0]:m;c.push({to:s.domain,path:C,from:h,id:S,...y?{auth:y}:{},...Array.isArray(h)&&i?{loadBalancer:i}:{}}),f.add(s.domain),b();continue}if(w==="server-app"){if(typeof s.port!=="number")continue;let m=Y(s.port,r);c.push({to:s.domain,path:C,from:m,id:S,...y?{auth:y}:{},...Array.isArray(m)&&i?{loadBalancer:i}:{}})}else c.push({to:s.domain,path:C,static:{dir:`${n}/${o}-${l}/current`,spa:s.spa??!1,pathRewriteStyle:s.pathRewriteStyle??"directory"},cleanUrls:s.pathRewriteStyle!=="flat",...y?{auth:y}:{},id:S});f.add(s.domain),b()}if(t.proxy.autoWww!==!1)for(let l of[...f]){if(!mo(l))continue;let s=`www.${l}`;if(f.has(s))continue;c.push({to:s,redirect:{to:`https://${l}`},id:ld(s)}),f.add(s)}c.sort((l,s)=>{if(l.to!==s.to)return l.to.localeCompare(s.to);return(s.path?.length??0)-(l.path?.length??0)});let a={proxies:c,productionCerts:{certsDir:u,certsDirServerNames:[...f,...g.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...g.size>0?{wildcardCerts:[...g.values()]}:{}};if(t.proxy.onDemandTls&&f.size>0)a.onDemandTls={enabled:!0,allowedSuffixes:[...f],email:t.proxy.onDemandTlsEmail,certsDir:u,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)a.acmeChallengeWebroot=t.proxy.acmeWebroot??I;let p=t.proxy.cdn,x=p?.frontedHosts?.length?p.frontedHosts:[...f];if(p?.secret&&x.length>0)a.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:x};if(t.lan)if(dd(t.lan)==="off")a.https=!1;else{let l=F(e,t.lan,o);K(l,a.onDemandTls);let s=t.lan.ip&&L(t.lan.ip)!==0?[t.lan.ip]:[];a.localCa={dir:A,hosts:l.map((w)=>w.host),...s.length>0?{ips:s}:{},installTrust:!0}}return a}function B(e,t){return N({...e,...t.mail?ln(t.mail):{}},t)}function rr(e,t,r){return N({...e,...r.mail?ln(r.mail):{}},r,t)}function kI(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
1
+ import{ln,mr}from"./chunk-q61qcpp4.js";import{Kr,d}from"./chunk-xyhh44eq.js";import{isIP as L}from"node:net";var go="/etc/rpx/certs",A="/etc/rpx/local-ca",M="rpx-root-ca.crt";function po(e=A){return`${e.replace(/\/+$/,"")}/${M}`}function mo(e){if(e.toLowerCase().endsWith(".local"))return!1;return e.split(".").length===2}function fo(e,t={}){let r=new Set;for(let o of Object.values(e)){if(!o?.domain)continue;if(d(o)==="bucket")continue;r.add(o.domain)}let n=new Set;for(let o of Object.values(e)){if(!o?.domain||d(o)==="bucket")continue;for(let u of o.aliases??[]){let i=String(u).trim().toLowerCase();if(i&&i!==o.domain)n.add(i)}}if(t.autoWww!==!1)for(let o of[...r]){if(!mo(o))continue;r.add(`www.${o}`)}for(let o of n)r.add(o);return[...r]}var k=["1.1.1.1","8.8.8.8"],I="/var/www/acme-challenge";function W(e){if(typeof e==="string")return{to:e};let t={to:e.to};if(e.status!=null)t.status=e.status;if(e.preservePath!=null)t.preservePath=e.preservePath;return t}function U(e){let t=e.auth;if(!t||t.enabled===!1||!t.password)return;return{username:t.username||"admin",password:t.password,...t.realm?{realm:t.realm}:{}}}function dd(e){if(!e)return;return e.tls??"local-ca"}function Cp(e,t){if(e.cloud?.provider!=="ssh")return;let r=e.ssh?.lan;if(!r)return;return{...r.hostname?{hostname:r.hostname}:{},tls:r.tls??"local-ca",...t?{ip:t}:{}}}function Ep(e){if(e.cloud?.provider!=="ssh")return;return e.ssh?.profile}function X(e){let t=e.trim().toLowerCase();if(!t||t.startsWith("*")||t.includes(":")||t.includes("/")||t.includes(" "))return!1;if(L(t)!==0)return!1;return t.endsWith(".local")||!t.includes(".")}function F(e,t,r){let n=[],o=new Set,u=(g,a)=>{let p=g.trim().toLowerCase();if(!p||o.has(p))return;o.add(p),n.push({host:p,source:a})},i=t.hostname?.trim(),c=(i||`${r}.local`).toLowerCase();if(u(c,i?"ssh.lan.hostname":`the ssh provider's default LAN name for project "${r}"`),Object.entries(e).some(([g,a])=>!!a&&mr(g)))u(`dashboard.${c}`,"the management dashboard site");for(let[g,a]of Object.entries(e)){if(!a?.domain)continue;if(d(a)==="bucket")continue;if(!X(a.domain))continue;u(a.domain,`site "${g}"`)}return n}function H(e,t){if(!t?.length)return;return t.find((r)=>{let n=(r.startsWith(".")?r.slice(1):r).toLowerCase();return e===n||e.endsWith(`.${n}`)})}function K(e,t){if(!t?.enabled)return;for(let{host:r,source:n}of e){let o=H(r,t.allowedSuffixes);if(!o)continue;throw Error(`The LAN certificate authority and public on-demand TLS both claim "${r}". LAN source: ${n}. Public source: the on-demand TLS allowed suffix "${o}", which is derived from the site domains. A host is either LAN-only, with a certificate signed by the box's own CA, or public, with one issued by Let's Encrypt, never both. Give the LAN a name no site domain covers (ssh.lan.hostname), or take that domain out of the sites this deploy routes.`)}}function V(e){let t=e.split(".");return t.length>=3&&t[0]==="*"&&t.slice(1).every((r)=>/^[a-z0-9-]+$/i.test(r))}function D(e,t={}){let{wildcardCerts:r,...n}=e;return JSON.stringify({...t,...n},null,2)}function eA(e){if(!e||e==="/")return;let t=`/${e}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!t.startsWith("/"))t=`/${t}`;return t===""||t==="/"?void 0:t}function ld(e,t){let n=(t?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return n.length>0?n:"rpx"}function Y(e,t){if(!t||t.length===0)return`localhost:${e}`;return t.map((r)=>`${r.privateIp??r.publicIp}:${e}`)}function N(e,t,r){let n=(t.wwwRoot??"/var/www").replace(/\/+$/,""),o=t.slug??"app",u=t.proxy.certsDir??go,i=t.proxy.loadBalancer,c=[],f=new Set,g=new Map;for(let[l,s]of Object.entries(e)){if(!s||!s.domain)continue;let w=d(s);if(w==="bucket")continue;let v=c.length,E=[...new Set((s.aliases??[]).map((m)=>String(m).trim().toLowerCase()).filter((m)=>m&&m!==s.domain))],b=()=>{let m=c.slice(v).filter((h)=>h.to===s.domain);for(let h of E){for(let O of m)c.push({...O,to:h,id:ld(h,O.path)});if(V(h)){if(!g.has(h))g.set(h,{domain:h,dnsEnvFile:`${n}/${o}-${l}/shared/.env`})}else f.add(h)}},C=eA(s.path),S=ld(s.domain,C),y=U(s);if(w==="redirect"){c.push({to:s.domain,path:C,redirect:W(s.redirect),id:S,...y?{auth:y}:{}}),f.add(s.domain),b();continue}if(w==="proxy"){let m=Kr(s);if(m.length===0)continue;let h=m.length===1?m[0]:m;c.push({to:s.domain,path:C,from:h,id:S,...y?{auth:y}:{},...Array.isArray(h)&&i?{loadBalancer:i}:{}}),f.add(s.domain),b();continue}if(w==="server-app"){if(typeof s.port!=="number")continue;let m=Y(s.port,r);c.push({to:s.domain,path:C,from:m,id:S,...y?{auth:y}:{},...Array.isArray(m)&&i?{loadBalancer:i}:{}})}else c.push({to:s.domain,path:C,static:{dir:`${n}/${o}-${l}/current`,spa:s.spa??!1,pathRewriteStyle:s.pathRewriteStyle??"directory"},cleanUrls:s.pathRewriteStyle!=="flat",...y?{auth:y}:{},id:S});f.add(s.domain),b()}if(t.proxy.autoWww!==!1)for(let l of[...f]){if(!mo(l))continue;let s=`www.${l}`;if(f.has(s))continue;c.push({to:s,redirect:{to:`https://${l}`},id:ld(s)}),f.add(s)}c.sort((l,s)=>{if(l.to!==s.to)return l.to.localeCompare(s.to);return(s.path?.length??0)-(l.path?.length??0)});let a={proxies:c,productionCerts:{certsDir:u,certsDirServerNames:[...f,...g.keys()]},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1},...g.size>0?{wildcardCerts:[...g.values()]}:{}};if(t.proxy.onDemandTls&&f.size>0)a.onDemandTls={enabled:!0,allowedSuffixes:[...f],email:t.proxy.onDemandTlsEmail,certsDir:u,staging:t.proxy.onDemandTlsStaging??!1};if(t.proxy.onDemandTls)a.acmeChallengeWebroot=t.proxy.acmeWebroot??I;let p=t.proxy.cdn,x=p?.frontedHosts?.length?p.frontedHosts:[...f];if(p?.secret&&x.length>0)a.originGuard={header:p.secretHeader??"X-Origin-Verify",value:p.secret,hosts:x};if(t.lan)if(dd(t.lan)==="off")a.https=!1;else{let l=F(e,t.lan,o);K(l,a.onDemandTls);let s=t.lan.ip&&L(t.lan.ip)!==0?[t.lan.ip]:[];a.localCa={dir:A,hosts:l.map((w)=>w.host),...s.length>0?{ips:s}:{},installTrust:!0}}return a}function B(e,t){return N({...e,...t.mail?ln(t.mail):{}},t)}function rr(e,t,r){return N({...e,...r.mail?ln(r.mail):{}},r,t)}function kI(e){return`// Generated by ts-cloud — rpx reverse-proxy gateway.
2
2
  // Routes are derived from the \`sites\` model on every \`buddy deploy\`.
3
3
  import { startProxies } from '@stacksjs/rpx'
4
4
 
@@ -1,4 +1,4 @@
1
- import{nl,Q,l,sl,K,p,ce,m,lr,cl,Xi,Vo,gl,fl,hl,$l,mn,ns,Ar,Ml,Fl,ql,jl}from"./chunk-5rds38z9.js";import{be,nr,x,ir,s,Li,So,Jr,Td,wd,ae,c,Co,Xe,Xr,Rd,vo,Dd,Yr,To,sr,Zr,Fi,cr,Gi,Vi,Ye,dr,Wd,Jd,ji,zi,Pt,Mo,i,Ki,Uo,Qo}from"./chunk-eyc2tvze.js";import{n}from"./chunk-m9szynnf.js";import{Re}from"./chunk-cz4dw2hk.js";import{o}from"./chunk-c8kf2268.js";import{Te,vr,$s,ut,re,me,T,we,Rr,fe,pt,Pr}from"./chunk-7ea0q5tg.js";import{ne}from"./chunk-nftqsker.js";import{u,ht,Zs,Ve,Lr,Lg,Zt,$g,Mg,Hc,je,It,pi,F,tr,Vr}from"./chunk-n5qbdsbj.js";import{U,d}from"./chunk-dh5m9b05.js";import{$n}from"./chunk-dvw5dy32.js";import{Mn,bg,Bs,L,P,xs,Cg}from"./chunk-1h95atas.js";import{I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Ws}from"path";import kw from"process";import{existsSync as Rw,mkdirSync as ST,readdirSync as wT,readFileSync as Aw,writeFileSync as kT}from"fs";import{homedir as $o}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Yl,mkdirSync as Cw,readdirSync as Pw,writeFileSync as _w}from"fs";import{homedir as No}from"os";import{dirname as Gm,resolve as qr}from"path";import no from"process";import{join as Tw,relative as xw,resolve as Qm}from"path";import Yc from"process";import{existsSync as Mf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Cl}from"os";import{dirname as FT,resolve as Ur}from"path";import Ks from"process";import{join as Dw,relative as Ow,resolve as Ym}from"path";import Zc from"process";import{existsSync as Lf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Zl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as $w,createDecipheriv as Nw,randomBytes as Pl}from"crypto";import{closeSync as _l,createReadStream as Zm,createWriteStream as jw,existsSync as Tl,fsyncSync as Xm,openSync as ef,writeFileSync as Bw}from"fs";import{access as Mw,constants as tf,mkdir as Lw,readdir as xc,rename as rf,stat as jo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Bo}from"path";import Tr from"process";import{pipeline as Fw}from"stream/promises";import{createGzip as nf}from"zlib";import Lo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as zw,createDecipheriv as Uw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as qw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Vw}from"fs";import{access as Ww,constants as cf,mkdir as Hw,readdir as $c,rename as df,stat as Fo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Kw,join as zo,resolve as Jw}from"path";import At from"process";import{pipeline as Gw}from"stream/promises";import{createGzip as lf}from"zlib";import qo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Bl}from"path";import{existsSync as Qw}from"fs";import{existsSync as Yw,readdirSync as Zw}from"fs";import{extname as Ll,resolve as uf}from"path";import Xw from"process";import{join as ek,relative as tk,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as rk,createDecipheriv as nk,randomBytes as zl}from"crypto";import{closeSync as Ul,createReadStream as gf,createWriteStream as ik,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as ok}from"fs";import{access as sk,constants as hf,mkdir as ak,readdir as Lc,rename as yf,stat as Wo,unlink as Fc,writeFile as Vl}from"fs/promises";import{isAbsolute as ck,join as Ho,resolve as dk}from"path";import Ct from"process";import{pipeline as lk}from"stream/promises";import{createGzip as vf}from"zlib";import Ko from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Wm(e))return!0;return Hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new Of,sp=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Bf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function Iw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Ew(e={}){let t=Ws(e.cwd||kw.cwd());return Array.from(new Set([t,Ws(t,"config"),Ws(t,".config"),e.configDir?Ws(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var uk=Object.defineProperty,pk=(e)=>e;function gk(e,t){this[e]=pk.bind(null,t)}var mk=(e,t)=>{for(var r in t)uk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gk.bind(t,r)})},fk=(e,t)=>()=>(e&&(t=e(e=0)),t),Ff={};mk(Ff,{withErrorRecovery:()=>Hf,tryLoadConfig:()=>Mk,loadConfigWithResult:()=>jk,loadConfig:()=>Ph,isRetryableError:()=>Tk,isConfigNotFoundError:()=>_k,isBunfigError:()=>Gf,globalPerformanceMonitor:()=>Qs,globalCache:()=>Jo,getEnvOrDefault:()=>xk,generateConfigTypes:()=>Lk,defaultGeneratedDir:()=>Bh,defaultConfigDir:()=>jh,deepMergeWithArrayStrategy:()=>up,deepMerge:()=>Qf,createLibraryConfig:()=>Fk,config:()=>Bk,bunfigPlugin:()=>zk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>rp,SchemaValidationError:()=>Gs,PluginError:()=>ip,PerformanceMonitor:()=>cp,FileSystemError:()=>tp,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>pp,ConfigValidationError:()=>ru,ConfigNotFoundError:()=>od,ConfigMergeError:()=>ep,ConfigLoader:()=>gp,ConfigLoadError:()=>Js,ConfigFileLoader:()=>pd,ConfigCache:()=>ap,CacheUtils:()=>xh,BunfigError:()=>cn,BrowserConfigError:()=>np,ArrayMergeStrategies:()=>$h});class ap{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Km(e))return!0;return Jm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class cp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hk(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function yk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vk(e){return e.getStats().size*2}function dp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let g of e)if(Vt(g)&&"name"in g){if(!a.find((h)=>Vt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(Vt(g)&&"path"in g){if(!a.find((h)=>Vt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(Vt(g)&&Vt(r[a]))r[a]=dp(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&Vt(g[0])&&Vt(r[a][0])){let f=[...g];for(let h of r[a])if(Vt(h)&&"name"in h){if(!f.find((S)=>Vt(S)&&("name"in S)&&S.name===h.name))f.push(h)}else if(Vt(h)&&"path"in h){if(!f.find((S)=>Vt(S)&&("path"in S)&&S.path===h.path))f.push(h)}else if(!f.some((b)=>td(b,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function bk(e,t){if(!Lf(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return dp(t,a)}catch{return null}}catch{return null}}async function Sk({name:e="",cwd:t,defaultConfig:r}){let a=t||Zl.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let b of g){let S=Xc(a,`${h}${b}`),y=await bk(S,r);if(y!==null)return y}try{let h=Xc(a,"package.json");if(Lf(h)){let S=(await import(h))[e];if(S&&typeof S==="object"&&!Array.isArray(S))try{return dp(r,S)}catch{}}}catch{}return r}function wk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return Ow(Zc.cwd(),a);return a}async function kk(){try{let e=await Sk({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ik(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Uf{async format(e){let t=await Ik(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Lo.pid,hostname:t(),environment:Lo.env.NODE_ENV||"development",platform:Lo.platform,version:Lo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lo.env.NODE_ENV||Lo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...eu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Uf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:eu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let g,f=0,h=3,b=1000;while(f<h)try{try{try{await Mw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Lw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let S=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Bw(g,S,{flag:"a"}),Xm(g),g!==void 0)_l(g),g=void 0;if((await jo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,S,{flag:"w",mode:420}),(await jo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let k=y;if(k.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(k.code)){if(f<h-1){let R=typeof k.message==="string"?k.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,R);let D=b*2**f;await new Promise((O)=>setTimeout(O,D)),f++;continue}}if(k?.code&&["ENOSPC","EDQUOT"].includes(k.code))throw Error(`Disk quota exceeded or no space left on device: ${k.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",k),k}finally{if(g!==void 0)try{_l(g)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(S){if(f===h-1){let k=S,R=typeof k.message==="string"?k.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",R),S}f++;let y=b*2**(f-1);await new Promise((k)=>setTimeout(k,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((g)=>{console.error("Error rotating keys:",g)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let g=Array.from(this.encryptionKeys.entries()).sort(([,b],[,S])=>S.createdAt.getTime()-b.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[b]of g.slice(h))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Pl(16).toString("hex")}generateKey(){return Pl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Pl(16),a=$w("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Yt())return;let e=await jo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let g=await xc(this.config.logDirectory),f=g.filter((S)=>S.startsWith(this.name)&&/\.log\.\d+$/.test(S)).sort((S,y)=>{let k=Number.parseInt(S.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-k}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${h}`;if(await jo(r).catch(()=>null))try{if(await rf(r,b),t.compress)try{let S=`${b}.gz`;await this.compressLogFile(b,S),await Dc(b)}catch(S){console.error("Error compressing rotated file:",S)}if(f.length===0&&!g.some((S)=>S.endsWith(".log.1")))try{let S=`${r}.1`;await xl(S,"")}catch(S){console.error("Error creating backup file:",S)}}catch(S){console.error(`Error during rotation: ${S instanceof Error?S.message:String(S)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await jo(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,b)=>b.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(Bo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=jw(t),g=nf();await Fw(r,g,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Tl(this.currentLogFile))try{let e=ef(this.currentLogFile,"r+");Xm(e),_l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Yt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Bo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Nt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(h)O.push(t);if(f==="warning")O.push("WARN");else if(f==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(g),O.join(" ")}let S=Tr.stdout.columns||120,y="";if(f==="warning"||f==="error")y=`${r} ${g}`;else if(f==="info"||f==="success")y=`${r} ${a} ${g}`;else y=`${r} ${a} ${Nt.cyan(g)}`;if(!h)return y.trim();let k=b(y).trim().length,R=b(t).length,D=Math.max(1,S-2-k-R);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let b=Number.parseInt(h,10);return b<t[0].length?String(t[0][b]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let b=t[a++];switch(h){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,b;if(t instanceof Error)h=t.message,b=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let y=Dh[e],k=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.gray(h),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R);break;case"success":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.green(h),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R),b){let D=b.split(`
1
+ import{nl,Q,l,sl,K,p,ce,m,lr,cl,Xi,Vo,gl,fl,hl,$l,mn,ns,Ar,Ml,Fl,ql,jl}from"./chunk-q61qcpp4.js";import{be,nr,x,ir,s,Li,So,Jr,Td,wd,ae,c,Co,Xe,Xr,Rd,vo,Dd,Yr,To,sr,Zr,Fi,cr,Gi,Vi,Ye,dr,Wd,Jd,ji,zi,Pt,Mo,i,Ki,Uo,Qo}from"./chunk-rq650jaz.js";import{n}from"./chunk-m9szynnf.js";import{Re}from"./chunk-cz4dw2hk.js";import{o}from"./chunk-c8kf2268.js";import{Te,vr,$s,ut,re,me,T,we,Rr,fe,pt,Pr}from"./chunk-7ea0q5tg.js";import{ne}from"./chunk-nftqsker.js";import{u,ht,Zs,Ve,Lr,Lg,Zt,$g,Mg,Hc,je,It,pi,F,tr,Vr}from"./chunk-9nzmfpwt.js";import{U,d}from"./chunk-xyhh44eq.js";import{$n}from"./chunk-dvw5dy32.js";import{Mn,bg,Bs,L,P,xs,Cg}from"./chunk-kcb203be.js";import{I}from"./chunk-z56sccfh.js";import{He}from"./chunk-fdf181e6.js";import{Be}from"./chunk-vq8bejep.js";import{A}from"./chunk-tmp2ym80.js";import{existsSync as OI}from"node:fs";import{join as ey}from"node:path";import{pathToFileURL as $I}from"node:url";import{existsSync as Wm,statSync as Hm}from"fs";import{resolve as Ws}from"path";import kw from"process";import{existsSync as Rw,mkdirSync as ST,readdirSync as wT,readFileSync as Aw,writeFileSync as kT}from"fs";import{homedir as $o}from"os";import{dirname as RT,resolve as Zn}from"path";import ld from"process";import{existsSync as Km,statSync as Jm}from"fs";import{existsSync as Yl,mkdirSync as Cw,readdirSync as Pw,writeFileSync as _w}from"fs";import{homedir as No}from"os";import{dirname as Gm,resolve as qr}from"path";import no from"process";import{join as Tw,relative as xw,resolve as Qm}from"path";import Yc from"process";import{existsSync as Mf,mkdirSync as NT,readdirSync as jT,writeFileSync as BT}from"fs";import{homedir as Cl}from"os";import{dirname as FT,resolve as Ur}from"path";import Ks from"process";import{join as Dw,relative as Ow,resolve as Ym}from"path";import Zc from"process";import{existsSync as Lf,mkdirSync as WT,readdirSync as HT,writeFileSync as KT}from"fs";import{dirname as GT,resolve as Xc}from"path";import Zl from"process";import{Buffer as Ci}from"buffer";import{createCipheriv as $w,createDecipheriv as Nw,randomBytes as Pl}from"crypto";import{closeSync as _l,createReadStream as Zm,createWriteStream as jw,existsSync as Tl,fsyncSync as Xm,openSync as ef,writeFileSync as Bw}from"fs";import{access as Mw,constants as tf,mkdir as Lw,readdir as xc,rename as rf,stat as jo,unlink as Dc,writeFile as xl}from"fs/promises";import{join as Bo}from"path";import Tr from"process";import{pipeline as Fw}from"stream/promises";import{createGzip as nf}from"zlib";import Lo from"process";import di from"process";import{Buffer as ai}from"buffer";import{createCipheriv as zw,createDecipheriv as Uw,randomBytes as Dl}from"crypto";import{closeSync as Ol,createReadStream as of,createWriteStream as qw,existsSync as Oc,fsyncSync as sf,openSync as af,writeFileSync as Vw}from"fs";import{access as Ww,constants as cf,mkdir as Hw,readdir as $c,rename as df,stat as Fo,unlink as Nc,writeFile as Nl}from"fs/promises";import{isAbsolute as Kw,join as zo,resolve as Jw}from"path";import At from"process";import{pipeline as Gw}from"stream/promises";import{createGzip as lf}from"zlib";import qo from"process";import li from"process";import jc from"process";import{existsSync as Bc}from"fs";import{resolve as Bl}from"path";import{existsSync as Qw}from"fs";import{existsSync as Yw,readdirSync as Zw}from"fs";import{extname as Ll,resolve as uf}from"path";import Xw from"process";import{join as ek,relative as tk,resolve as pf}from"path";import ed from"process";import{Buffer as ci}from"buffer";import{createCipheriv as rk,createDecipheriv as nk,randomBytes as zl}from"crypto";import{closeSync as Ul,createReadStream as gf,createWriteStream as ik,existsSync as Mc,fsyncSync as mf,openSync as ff,writeFileSync as ok}from"fs";import{access as sk,constants as hf,mkdir as ak,readdir as Lc,rename as yf,stat as Wo,unlink as Fc,writeFile as Vl}from"fs/promises";import{isAbsolute as ck,join as Ho,resolve as dk}from"path";import Ct from"process";import{pipeline as lk}from"stream/promises";import{createGzip as vf}from"zlib";import Ko from"process";import ui from"process";import Uc from"process";import{existsSync as qc}from"fs";import{resolve as Df}from"path";import{existsSync as TI}from"fs";class Of{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Wm(e))return!0;return Hm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Wm(r)?Hm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class $f{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var Qc=new Of,sp=new $f;var Nf=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];function Bf(e={}){let{name:t="",alias:r}=e,a=["config",".config"];if(t)a.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let g=r===void 0?[]:Array.isArray(r)?r:[r];for(let f of g){if(!f)continue;if(a.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)a.push(`${t}.${f}.config`,`.${t}.${f}.config`)}return Array.from(new Set(a.filter(Boolean)))}function Iw(e){return Bf(e).flatMap((r)=>Nf.map((a)=>Ws(e.directory,`${r}${a}`)))}function Ew(e={}){let t=Ws(e.cwd||kw.cwd());return Array.from(new Set([t,Ws(t,"config"),Ws(t,".config"),e.configDir?Ws(t,e.configDir):void 0].filter((r)=>Boolean(r))))}var uk=Object.defineProperty,pk=(e)=>e;function gk(e,t){this[e]=pk.bind(null,t)}var mk=(e,t)=>{for(var r in t)uk(e,r,{get:t[r],enumerable:!0,configurable:!0,set:gk.bind(t,r)})},fk=(e,t)=>()=>(e&&(t=e(e=0)),t),Ff={};mk(Ff,{withErrorRecovery:()=>Hf,tryLoadConfig:()=>Mk,loadConfigWithResult:()=>jk,loadConfig:()=>Ph,isRetryableError:()=>Tk,isConfigNotFoundError:()=>_k,isBunfigError:()=>Gf,globalPerformanceMonitor:()=>Qs,globalCache:()=>Jo,getEnvOrDefault:()=>xk,generateConfigTypes:()=>Lk,defaultGeneratedDir:()=>Bh,defaultConfigDir:()=>jh,deepMergeWithArrayStrategy:()=>up,deepMerge:()=>Qf,createLibraryConfig:()=>Fk,config:()=>Bk,bunfigPlugin:()=>zk,applyEnvVarsToConfig:()=>Hs,TypeGenerationError:()=>rp,SchemaValidationError:()=>Gs,PluginError:()=>ip,PerformanceMonitor:()=>cp,FileSystemError:()=>tp,ErrorFactory:()=>Pi,EnvVarError:()=>sd,EnvProcessor:()=>ud,ConfigValidator:()=>pp,ConfigValidationError:()=>ru,ConfigNotFoundError:()=>od,ConfigMergeError:()=>ep,ConfigLoader:()=>gp,ConfigLoadError:()=>Js,ConfigFileLoader:()=>pd,ConfigCache:()=>ap,CacheUtils:()=>xh,BunfigError:()=>cn,BrowserConfigError:()=>np,ArrayMergeStrategies:()=>$h});class ap{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let g=this.generateKey(e,r),f=a??this.options.ttl,h=this.estimateSize(t);this.cache.set(g,{value:t,timestamp:new Date,ttl:f,hits:0,size:h}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!Km(e))return!0;return Jm(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let g=Km(r)?Jm(r):null,f=g?g.mtime:new Date;this.set(e,{value:t,fileTimestamp:f},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,g)=>a+g.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class cp{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),g=new Date;try{let f=await t(),h=performance.now()-a;return this.recordMetric({operation:e,duration:h,timestamp:g,...r}),f}catch(f){let h=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:h,timestamp:g,...r}),f}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((g)=>g.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((g)=>g.duration),a=r.reduce((g,f)=>g+f,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function hk(e,t={}){let a=Object.keys(t).sort().map((g)=>`${g}:${t[g]}`).join("|");return a?`${e}:${a}`:e}function yk(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function vk(e){return e.getStats().size*2}function dp(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Vt(t[0])&&"id"in t[0]&&t[0].id===3&&Vt(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Vt(t)&&Vt(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Vt(e)&&"arr"in e&&Array.isArray(e.arr)&&Vt(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Vt(t[0])&&Vt(e[0])){let a=[...t];for(let g of e)if(Vt(g)&&"name"in g){if(!a.find((h)=>Vt(h)&&("name"in h)&&h.name===g.name))a.push(g)}else if(Vt(g)&&"path"in g){if(!a.find((h)=>Vt(h)&&("path"in h)&&h.path===g.path))a.push(g)}else if(!a.some((f)=>td(f,g)))a.push(g);return a}if(t.every((a)=>typeof a==="string")&&e.every((a)=>typeof a==="string")){let a=[...t];for(let g of e)if(!a.includes(g))a.push(g);return a}return t}if(!Vt(t)||!Vt(e))return t;let r={...e};for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a)){let g=t[a];if(g===null||g===void 0)continue;else if(Vt(g)&&Vt(r[a]))r[a]=dp(r[a],g);else if(Array.isArray(g)&&Array.isArray(r[a]))if(g.length>0&&r[a].length>0&&Vt(g[0])&&Vt(r[a][0])){let f=[...g];for(let h of r[a])if(Vt(h)&&"name"in h){if(!f.find((S)=>Vt(S)&&("name"in S)&&S.name===h.name))f.push(h)}else if(Vt(h)&&"path"in h){if(!f.find((S)=>Vt(S)&&("path"in S)&&S.path===h.path))f.push(h)}else if(!f.some((b)=>td(b,h)))f.push(h);r[a]=f}else if(g.every((f)=>typeof f==="string")&&r[a].every((f)=>typeof f==="string")){let f=[...g];for(let h of r[a])if(!f.includes(h))f.push(h);r[a]=f}else r[a]=g;else r[a]=g}return r}function td(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!td(e[r],t[r]))return!1;return!0}if(Vt(e)&&Vt(t)){let r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(let g of r){if(!Object.prototype.hasOwnProperty.call(t,g))return!1;if(!td(e[g],t[g]))return!1}return!0}return!1}function Vt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function bk(e,t){if(!Lf(e))return null;try{let r=await import(e),a=r.default||r;if(typeof a!=="object"||a===null||Array.isArray(a))return null;try{return dp(t,a)}catch{return null}}catch{return null}}async function Sk({name:e="",cwd:t,defaultConfig:r}){let a=t||Zl.cwd(),g=[".ts",".js",".mjs",".cjs",".json"],f=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let h of f)for(let b of g){let S=Xc(a,`${h}${b}`),y=await bk(S,r);if(y!==null)return y}try{let h=Xc(a,"package.json");if(Lf(h)){let S=(await import(h))[e];if(S&&typeof S==="object"&&!Array.isArray(S))try{return dp(r,S)}catch{}}}catch{}return r}function wk(e,t={}){let r=Zc.cwd();while(r.includes("storage"))r=Ym(r,"..");let a=Ym(r,e||"");if(t?.relative)return Ow(Zc.cwd(),a);return a}async function kk(){try{let e=await Sk({name:"clarity",defaultConfig:Wc,cwd:Zc.cwd(),endpoint:"",headers:{}});return{...Wc,...e}}catch{return Wc}}function Yt(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ik(){if(di.env.NODE_ENV==="test"||di.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof di<"u"){let e=di.type;if(e==="renderer"||e==="worker")return!1;return!!(di.versions&&(di.versions.node||di.versions.bun))}return!1}class Uf{async format(e){let t=await Ik(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Lo.pid,hostname:t(),environment:Lo.env.NODE_ENV||"development",platform:Lo.platform,version:Lo.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Lo.env.NODE_ENV||Lo.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rd{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...eu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Uf,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Tr.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let g=this.generateKeyId(),f=this.generateKey();this.currentKeyId=g,this.keys.set(g,f),this.encryptionKeys.set(g,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Kc,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Kc};return{...Kc,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:eu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let g,f=0,h=3,b=1000;while(f<h)try{try{try{await Mw(this.config.logDirectory,tf.F_OK|tf.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Lw(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let S=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ci.from(e);try{if(!Tl(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(g=ef(this.currentLogFile,"a",420),Bw(g,S,{flag:"a"}),Xm(g),g!==void 0)_l(g),g=void 0;if((await jo(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,S,{flag:"w",mode:420}),(await jo(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let k=y;if(k.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(k.code)){if(f<h-1){let R=typeof k.message==="string"?k.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${h}:`,R);let D=b*2**f;await new Promise((O)=>setTimeout(O,D)),f++;continue}}if(k?.code&&["ENOSPC","EDQUOT"].includes(k.code))throw Error(`Disk quota exceeded or no space left on device: ${k.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",k),k}finally{if(g!==void 0)try{_l(g)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch(S){if(f===h-1){let k=S,R=typeof k.message==="string"?k.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",R),S}f++;let y=b*2**(f-1);await new Promise((k)=>setTimeout(k,y))}})();this.pendingOperations.push(r);let a=this.pendingOperations.length-1;try{await r}catch(g){throw console.error("Debug: [writeToFile] Error in operation:",g),g}finally{this.pendingOperations.splice(a,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Bo(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Bo(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Bo(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Yt())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,a=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((g)=>{console.error("Error rotating keys:",g)})},a)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),a=this.generateKey();this.currentKeyId=r,this.keys.set(r,a),this.encryptionKeys.set(r,{key:a,createdAt:new Date});let g=Array.from(this.encryptionKeys.entries()).sort(([,b],[,S])=>S.createdAt.getTime()-b.createdAt.getTime()),f=typeof t.maxKeys==="number"?t.maxKeys:1,h=Math.max(1,f);if(g.length>h)for(let[b]of g.slice(h))this.encryptionKeys.delete(b),this.keys.delete(b)}generateKeyId(){return Pl(16).toString("hex")}generateKey(){return Pl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Pl(16),a=$w("aes-256-gcm",t,r),g=Ci.concat([a.update(e,"utf8"),a.final()]),f=a.getAuthTag();return{encrypted:Ci.concat([r,g,f]),iv:r}}async compressData(e){return new Promise((t,r)=>{let a=nf(),g=[];a.on("data",(f)=>g.push(f)),a.on("end",()=>t(Ci.from(Ci.concat(g)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Yt())return;let e=await jo(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let g=await xc(this.config.logDirectory),f=g.filter((S)=>S.startsWith(this.name)&&/\.log\.\d+$/.test(S)).sort((S,y)=>{let k=Number.parseInt(S.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-k}),h=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,b=`${r}.${h}`;if(await jo(r).catch(()=>null))try{if(await rf(r,b),t.compress)try{let S=`${b}.gz`;await this.compressLogFile(b,S),await Dc(b)}catch(S){console.error("Error compressing rotated file:",S)}if(f.length===0&&!g.some((S)=>S.endsWith(".log.1")))try{let S=`${r}.1`;await xl(S,"")}catch(S){console.error("Error creating backup file:",S)}}catch(S){console.error(`Error during rotation: ${S instanceof Error?S.message:String(S)}`)}}else{let g=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${g}.log`);if(await jo(r).catch(()=>null))await rf(r,f)}if(this.currentLogFile=a,t.maxFiles){let f=(await xc(this.config.logDirectory)).filter((h)=>h.startsWith(this.name)).sort((h,b)=>b.localeCompare(h));for(let h of f.slice(t.maxFiles))await Dc(Bo(this.config.logDirectory,h))}}}async compressLogFile(e,t){let r=Zm(e),a=jw(t),g=nf();await Fw(r,g,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);await this.writeToFile(a),console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Tl(this.currentLogFile))try{let e=ef(this.currentLogFile,"r+");Xm(e),_l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Yt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await xc(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dc(Bo(this.config.logDirectory,r))}catch(a){console.error(`Failed to delete temp file ${r}:`,a)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Nt.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:g,level:f,showTimestamp:h=!0}=e,b=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(h)O.push(t);if(f==="warning")O.push("WARN");else if(f==="error")O.push("ERROR");else if(r)O.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)O.push(a.replace(/[[\]]/g,""));return O.push(g),O.join(" ")}let S=Tr.stdout.columns||120,y="";if(f==="warning"||f==="error")y=`${r} ${g}`;else if(f==="info"||f==="success")y=`${r} ${a} ${g}`;else y=`${r} ${a} ${Nt.cyan(g)}`;if(!h)return y.trim();let k=b(y).trim().length,R=b(t).length,D=Math.max(1,S-2-k-R);return`${y.trim()}${" ".repeat(D)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(f,h)=>{let b=Number.parseInt(h,10);return b<t[0].length?String(t[0][b]):f});let r=/%([sdijfo%])/g,a=0,g=e.replace(r,(f,h)=>{if(h==="%")return"%";if(a>=t.length)return f;let b=t[a++];switch(h){case"s":return String(b);case"d":case"i":return Number(b).toString();case"j":case"o":return JSON.stringify(b,null,2);default:return f}});if(a<t.length)g+=` ${t.slice(a).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return g}async log(e,t,...r){let a=new Date,g=this.formatConsoleTimestamp(a),f=this.formatFileTimestamp(a),h,b;if(t instanceof Error)h=t.message,b=t.stack;else h=this.formatMessage(t,r);if(this.fancy&&!Yt()){let y=Dh[e],k=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",R;switch(e){case"debug":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.gray(h),level:e}),console.error(R);break;case"info":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R);break;case"success":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:Nt.green(h),level:e}),console.error(R);break;case"warning":R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.warn(R);break;case"error":if(R=this.formatConsoleMessage({timestamp:g,icon:y,tag:k,message:h,level:e}),console.error(R),b){let D=b.split(`
2
2
  `);for(let O of D)if(O.trim()&&!O.includes(h))console.error(this.formatConsoleMessage({timestamp:g,message:Nt.gray(` ${O}`),level:e,showTimestamp:!1}))}break}}else if(!Yt()){if(console.error(`${f} ${this.environment}.${e.toUpperCase()}: ${h}`),b)console.error(b)}if(!this.shouldLog(e))return;let S=`${f} ${this.environment}.${e.toUpperCase()}: ${h}
3
3
  `;if(b)S+=`${b}
4
4
  `;S=S.replace(this.ANSI_PATTERN,""),await this.writeToFile(S)}time(e){let t=performance.now();if(this.fancy&&!Yt()){let r=this.options.showTags!==!1&&this.name?Nt.gray(this.formatTag(this.name)):"",a=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:a,icon:Nt.blue("◐"),tag:r,message:`${Nt.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let a=performance.now(),g=Math.round(a-t),f=`${e} completed in ${g}ms`,h=new Date,b=this.formatConsoleTimestamp(h),y=`${this.formatFileTimestamp(h)} ${this.environment}.INFO: ${f}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
@@ -176,7 +176,7 @@ export const handler = async (event) => {
176
176
  body: JSON.stringify({ ok: statusCode === 200, service: 'ts-cloud-static-api', path, coldStart: currentColdStart, initializedAt })
177
177
  }
178
178
  }
179
- `;function Av(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function AA(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(Av(e))}function Ev(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(Av(e))}function Rv(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let a=r[t];if(a===void 0)return[];return Array.isArray(a)?a:[a]}function Rg(e){let t=e?.Aliases?.Items,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function CA(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,a=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(a))throw Error("IAM role name is invalid");let g=e.memorySize??256,f=e.timeout??10,h=e.logRetentionDays??14;if(g<128||g>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(f<1||f>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:a,memorySize:g,timeout:f,logRetentionDays:h}}function yh(e){let t=e.region||"us-east-1";return{cloudfront:new I(e.profile),iam:new Re(t,e.profile),lambda:new T(t,e.profile),logs:new we(t,e.profile),sts:new Te(t,e.profile),sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}async function zS(e,t){let r=CA(e),a=t||yh({profile:e.profile,region:r.region}),[g,f,h]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId),a.cloudfront.getDistributionConfig(e.distributionId)]);if(!g.Account)throw Error("AWS identity did not return an account ID");if(!f.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(Rg(f).length?Rg(f):Rg(h.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let S,y=!0;try{S=await a.iam.getRole({RoleName:r.roleName})}catch(Ze){if(!AA(Ze))throw Ze;y=!1}let k=S?.Arn||`arn:aws:iam::${g.Account}:role/${r.roleName}`,R=await a.lambda.functionExists(e.functionName),D=R?await a.lambda.getFunctionUrl(e.functionName):null,O=await a.cloudfront.listOriginAccessControls(),M=`${e.functionName}-lambda-url`,z=O.some((Ze)=>Ze.Name===M&&Ze.OriginAccessControlOriginType==="lambda"),J=Rv(h.DistributionConfig.Origins,"Origin"),Z=Rv(h.DistributionConfig.CacheBehaviors,"CacheBehavior"),oe=J.some((Ze)=>String(Ze.Id)===r.originId),G=Z.some((Ze)=>String(Ze.PathPattern)===r.pathPattern),te=[...!y?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...R?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!D?["create private AWS_IAM function URL"]:[],...!z?[`create Lambda origin access control ${M}`]:[],"grant CloudFront function-URL and invocation permissions",`${G?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],ye={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!R,removeRole:!y},Se={mode:e.apply?"apply":"plan",accountId:g.Account,identityArn:g.Arn,distribution:{id:f.Id,arn:f.ARN,alias:e.expectedAlias,domainName:f.DomainName,status:f.Status},function:{name:e.functionName,existed:R,runtime:"nodejs22.x",urlExisted:!!D,url:D?.FunctionUrl},role:{name:r.roleName,existed:y,arn:k},origin:{id:r.originId,pathPattern:r.pathPattern,existed:oe,behaviorExisted:G,accessControlExisted:z},changes:te,rollback:ye,applied:!1};if(!e.apply)return Se;let ie=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==ie)throw Error(`Pass exact confirmation token ${ie} to mutate the live distribution`);if(!S)S=await a.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await a.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${g.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await a.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(Ze){if(!Ev(Ze))throw Ze}await a.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let xe=e.code||RA;if(R)await a.lambda.updateFunctionCodeInline(e.functionName,xe,"index.mjs"),await a.lambda.waitForFunctionActive(e.functionName),await a.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:S.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let Ze;for(let wt=0;wt<8;wt++)try{await a.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:S.Arn,Handler:"index.handler",Code:xe,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),Ze=void 0;break}catch(Bt){if(Ze=Bt,!String(Bt.message).toLowerCase().includes("role"))throw Bt;await a.sleep(1000)}if(Ze)throw Ze}await a.lambda.waitForFunctionActive(e.functionName);let ee=D||await a.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!ee.FunctionUrl)throw Error("Lambda did not return a function URL");let De=new URL(ee.FunctionUrl).hostname,Je=await a.cloudfront.findOrCreateOriginAccessControl(M,"lambda"),gt=f.ARN||`arn:aws:cloudfront::${g.Account}:distribution/${e.distributionId}`,jt=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:gt,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:gt,InvokedViaFunctionUrl:!0}];for(let Ze of jt)try{await a.lambda.addPermission(Ze)}catch(wt){if(!Ev(wt))throw wt}return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:De,pathPattern:r.pathPattern,originAccessControlId:Je.Id}),{...Se,function:{...Se.function,url:ee.FunctionUrl},applied:!0}}async function KS(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,a=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),g=new Uint8Array(await a.arrayBuffer()),f=EA("sha256").update(g).digest("hex"),h=Date.now(),b=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),S=Date.now()-h,y=await b.text(),k=y;try{k=JSON.parse(y)}catch{}let R;if(e.logs&&e.functionName){let D=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:h-60000,filterPattern:'"Init Duration"',limit:25});for(let O of D.events||[]){let M=O.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(M)R=Number(M[1])}}return{frontend:{url:t,status:a.status,sha256:f,unchanged:e.expectedFrontendSha256?f===e.expectedFrontendSha256:void 0,bytes:g.byteLength},api:{url:r,status:b.status,latencyMs:S,healthy:b.ok&&!!k?.ok,body:k},coldStart:{observed:R!==void 0,initDurationMs:R},verifiedAt:(e.now?.()||new Date).toISOString()}}function WS(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),a=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),g=r/1e6*0.2+a*0.0000166667,f=9.010025,h=16.425;return{lambdaUsd:Number(g.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as PA}from"node:crypto";function _A(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function TA(e){return _A(e)==="ValidationError"&&String(e.message).includes("does not exist")}function xA(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function DA(e){let t=e?.Aliases?.Items??e?.Aliases,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function Cv(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let a=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(a)||a==="/*")throw Error("Backend path must be a non-default wildcard pattern");let g=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(g))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:a,originId:g,digest:t}}function Sh(e){let t=e.region||"us-east-1";return{cloudformation:new A(t,e.profile),cloudfront:new I(e.profile),sts:new Te(t,e.profile),fetch,sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}function Ih(e){let t=Cv(e),r=hl({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),a=fl(r);return a.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,a.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},a}async function OA(e,t,r){let a;for(let g=0;g<30;g++){let f=Date.now();try{let h=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),b=Date.now()-f,S=await h.text(),y=S;try{y=JSON.parse(S)}catch{}if(h.ok)return{url:t,status:h.status,latencyMs:b,body:y};a=Error(`origin returned ${h.status}`)}catch(h){a=h}if(g<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${a instanceof Error?a.message:String(a)}`)}async function JS(e,t){let r=Cv(e),a=t||Sh({region:r.region,profile:e.profile}),[g,f]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId)]);if(!g.Account)throw Error("AWS identity did not return an account ID");if(!f.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!DA(f).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let h;try{h=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(te){if(!TA(te))throw te}let b=Ih(e),S=JSON.stringify(b);if(Buffer.byteLength(S)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let y=Object.values(b.Resources||{}).reduce((te,ye)=>(te[ye.Type]=(te[ye.Type]||0)+1,te),{}),k=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],R={mode:e.apply?"apply":"plan",accountId:g.Account,stack:{name:r.stackName,existed:!!h,status:h?.StackStatus,templateSha256:PA("sha256").update(S).digest("hex"),resourceCount:Object.keys(b.Resources||{}).length,resourceTypes:y},distribution:{id:f.Id,alias:e.expectedAlias,domainName:f.DomainName,status:f.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:k};if(!e.apply)return R;let D=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==D)throw Error(`Pass exact confirmation token ${D} to provision the backend and change live routing`);if(h)try{await a.cloudformation.updateStack({stackName:r.stackName,templateBody:S,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(te){if(!String(te.message).includes("No updates are to be performed"))throw te}else await a.cloudformation.createStack({stackName:r.stackName,templateBody:S,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-create-complete");let O=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],M=xA(O?.Outputs),z=M.AppLoadBalancerDnsName;if(!z)throw Error("Backend stack did not return AppLoadBalancerDnsName");let J=!1;if(e.originDomain&&e.originDomain!==z){if(!a.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${z}`);let te=await a.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:z,ttl:300});if(!te.success)throw Error(te.message||"External DNS update failed");J=!0}let Z=e.originDomain||z,oe=e.certificateArn?"https-only":"http-only",G=e.skipHealthCheck?void 0:await OA(a,`${oe==="https-only"?"https":"http"}://${Z}/api/health`,e.originVerifySecret);return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:Z,pathPattern:r.pathPattern,protocolPolicy:oe,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...R,outputs:M,health:G,cloudFrontApplied:!0,dnsApplied:J,applied:!0}}function XS(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((a,g)=>a+g,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([a,g])=>[a,Number(g.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as $A}from"node:child_process";import{createHash as NA}from"node:crypto";import{existsSync as Pv,mkdirSync as jA,mkdtempSync as BA,readdirSync as MA,readFileSync as LA,rmSync as FA,statSync as _v,writeFileSync as zA}from"node:fs";import{tmpdir as UA}from"node:os";import{basename as qA,join as as,relative as VA,resolve as Pg}from"node:path";var WA=new Set([".git","node_modules","dist","coverage"]);function Tv(e,t=e){let r=[];for(let a of MA(e).sort()){if(WA.has(a))continue;let g=as(e,a);if(sl(g,t))continue;let f=_v(g);if(f.isDirectory())r.push(...Tv(g,t));else if(f.isFile())r.push(VA(t,g))}return r}function bh(e){let t=Pg(e);if(!Pv(t)||!_v(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=NA("sha256");for(let a of Tv(t))r.update(a),r.update("\x00"),r.update(LA(as(t,a))),r.update("\x00");return r.digest("hex")}function Ch(e){return{ecr:new He(e.region||"us-east-1",e.profile),run:(t,r,a)=>{$A(t,r,{cwd:a?.cwd,env:a?.env,stdio:a?.stdio||"inherit"})}}}async function YS(e,t){let r=Pg(e.context),a=Pg(e.dockerfile||as(r,"Dockerfile"));if(!Pv(a))throw Error(`Dockerfile does not exist: ${a}`);if(!e.repository.split("/").every((M)=>/^[a-z0-9][a-z0-9._-]*$/.test(M)&&!/[._-]$/.test(M)&&!/[._-]{2}/.test(M)))throw Error("ECR repository name is invalid");let h=t||Ch(e),b=bh(r),S=`sha-${b.slice(0,20)}`,y="";try{y=(await h.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!y)y=(await h.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!y)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await h.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let k=`${y}:${S}`,R=BA(as(UA(),"ts-cloud-container-"));try{h.run("docker",["version"],{stdio:"ignore"}),h.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",a,"--tag",k,r],{cwd:r});let M=(await h.ecr.getAuthorizationToken()).authorizationData?.[0];if(!M?.authorizationToken||!M.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let z=M.proxyEndpoint.replace(/^https?:\/\//,""),J=as(R,"docker");jA(J,{recursive:!0}),zA(as(J,"config.json"),JSON.stringify({auths:{[z]:{auth:M.authorizationToken}}}),{mode:384}),h.run("docker",["push",k],{env:{...process.env,DOCKER_CONFIG:J}})}finally{FA(R,{recursive:!0,force:!0})}let O=(await h.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:S}]})).imageDetails?.[0]?.imageDigest;if(!O||!/^sha256:[a-f0-9]{64}$/i.test(O))throw Error(`ECR did not return an immutable digest for ${qA(k)}`);return{repository:e.repository,tag:S,imageUri:k,digest:O,digestUri:`${y}@${O}`,contextSha256:b}}import{existsSync as HA,readdirSync as KA,readFileSync as JA,statSync as GA}from"node:fs";import{join as xv,relative as QA}from"node:path";function yo(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let a=e.project.slug,g=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:a,region:g,stackName:lr(e,t),artifactBucket:cl(a,t),assetsBucket:Xi(a,t)}}async function ho(e,t=8){let r;for(let a=0;a<t;a++)try{return await e()}catch(g){let f=g?.code||g?.name||"",h=String(g?.message||"");if(f==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(h)){r=g,await new Promise((b)=>setTimeout(b,3000));continue}throw g}throw r}var Dv=(e,t)=>`releases/${e}/${t}/current.json`;async function Ld(e,t,r,a){try{return await e.getObjectJson(t,Dv(r,a))}catch{return null}}async function Ov(e,t,r,a,g){await e.putObjectJson(t,Dv(r,a),g)}async function YA(e,t){if(!e.secrets)return{};let r=new re(t),a={},g=Array.isArray(e.secrets)?e.secrets.map((f)=>({envName:f.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:f})):Object.entries(e.secrets).map(([f,h])=>({envName:f,secretId:h}));if(Array.isArray(e.secrets)){let f=new Map;for(let{envName:b,secretId:S}of g)f.set(b,[...f.get(b)??[],S]);let h=[...f.entries()].filter(([,b])=>b.length>1);if(h.length){let b=h.map(([S,y])=>`${S} ← ${y.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${b}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:f,secretId:h}of g){let S=(await r.getSecretValue({SecretId:h})).SecretString??"";try{let y=JSON.parse(S);if(y&&typeof y==="object"&&!Array.isArray(y)){for(let[k,R]of Object.entries(y))a[k]=String(R);continue}}catch{}a[f]=S}return a}function Es(e,t){let r={},a=t.DbProxyEndpoint||t.DbEndpoint;if(a)r.DB_CONNECTION="mysql",r.DB_HOST=a,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Cr(e,t,r,a,g,f,h,b={}){let S=e.kind==="php"?ql({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:a,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...b,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...h?{TSCLOUD_QUEUE:h,SQS_QUEUE:h}:{},...f?{ASSET_URL:f}:{},...e.env??{},...g}}function ZA(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*$v(e){for(let t of KA(e)){let r=xv(e,t);if(GA(r).isDirectory())yield*$v(r);else yield r}}async function XA(e,t,r,a,g=!1){let f=0;for(let h of $v(r)){let b=QA(r,h).replace(/\\/g,"/");if(!g&&b.split("/").some((S)=>S.startsWith(".")))continue;await e.putObject({bucket:t,key:`${a}/${b}`,body:JA(h),contentType:ZA(h),cacheControl:"public, max-age=31536000, immutable"}),f++}return f}function eC(e,t){let r=Object.entries(t).reduce((a,[g,f])=>a+Buffer.byteLength(`${g}=${f}`,"utf8"),0);if(r>4096){let a=Object.entries(t).map(([g,f])=>[g,Buffer.byteLength(`${g}=${f}`,"utf8")]).sort((g,f)=>f[1]-g[1]).slice(0,5).map(([g,f])=>`${g} (${f}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${a}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function sa(e,t,r,a){eC(t,r),await ho(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let g=a.kind==="image"?{FunctionName:t,ImageUri:a.imageUri}:{FunctionName:t,S3Bucket:a.bucket,S3Key:a.key};await ho(()=>e.updateFunctionCode(g)),await e.waitForFunctionActive(t,120)}async function Md(e,t){let a=(await ho(()=>e.publishVersion({FunctionName:t}))).Version;if(!a)throw Error(`publishVersion returned no version for ${t}`);return await ho(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:a})),a}async function Ya(e,t,r={}){let a=yo(e,t),{app:g,slug:f,region:h,stackName:b,artifactBucket:S}=a,y=r.projectRoot??process.cwd();xs(`Deploying serverless app: ${f} (${t})`),L(`Stack: ${b}`),L(`Region: ${h}`);let k=new o(h),R=new A(h),D=new T(h),O=g.kind==="php",M=g.packaging==="image",z=ns(g),J,Z,oe,G,te=[];if(M&&z.usesLayer&&z.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${z.kind}${z.kind==="node"?` ${z.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(M){P("Building + pushing container image");let{buildAndPushServerlessImage:ue}=await import("./chunk-5v2wpf1k.js"),Ce=await ue({app:g,projectRoot:y,region:h,repository:`${f}-${t}`,skipBuild:r.skipBuild,onStep:(mt)=>L(` ${mt}`)});J=Ce.handlers,Z={kind:"image",imageUri:Ce.imageUri},oe=Ce.tag,te.push({ParameterKey:"ImageUri",ParameterValue:Ce.imageUri})}else{P("Packaging application");let ue=O?jl({projectRoot:y,app:g,skipBuild:r.skipBuild,onStep:(kt)=>L(` ${kt}`)}):await mn({projectRoot:y,app:g,skipBuild:r.skipBuild,onStep:(kt)=>L(` ${kt}`)}),Ce=$l(f,t,ue.sha256);if(L(`Artifact: ${ue.sha256.slice(0,12)} (${(ue.zip.length/1024).toFixed(0)} KB)`),J=ue.handlers,oe=ue.sha256,z.usesLayer){let kt=z.layerEnvVar?process.env[z.layerEnvVar]:void 0;if(G=g.layers??(kt?[kt]:void 0),!G?.length){let _e=z.layerKind==="php"?"serverless:build-php-layer":z.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${z.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${z.layerEnvVar} env var (build one with \`cloud ${_e}\`)${z.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await k.bucketExists(S))P(`Creating artifact bucket ${S}`),await k.createBucket(S);if(await k.headObject(S,Ce).then((kt)=>kt!==null).catch(()=>!1))L("Artifact already uploaded — reusing");else P("Uploading artifact"),await k.putObject({bucket:S,key:Ce,body:ue.zip,contentType:"application/zip"});Z={kind:"zip",bucket:S,key:Ce},te.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:Ce})}let ye=Fl({config:e,environment:t,app:g,handlers:J,runtimeLayers:G}),Se=JSON.stringify(ye.template),ie=["CAPABILITY_NAMED_IAM"],xe=await R.describeStacks({stackName:b}).then((ue)=>ue.Stacks[0]?.StackStatus).catch(()=>{return}),ee=xe!==void 0;if(xe&&/DELETE_IN_PROGRESS/.test(xe))P("Waiting for an in-progress stack delete to finish"),await R.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;else if(xe&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(xe))P(`Deleting unusable stack (status ${xe}) before recreate`),await R.deleteStack(b),await R.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;P(ee?"Updating infrastructure stack":"Creating infrastructure stack");try{if(ee)await R.updateStack({stackName:b,templateBody:Se,parameters:te,capabilities:ie}),await R.waitForStack(b,"stack-update-complete");else await R.createStack({stackName:b,templateBody:Se,parameters:te,capabilities:ie,onFailure:"DELETE"}),await R.waitForStack(b,"stack-create-complete")}catch(ue){if(/No updates are to be performed/i.test(String(ue?.message)))L("No infrastructure changes");else throw ue}let De=await R.getStackOutputs(b).catch(()=>({})),Je;if(g.assets){let ue=xv(y,g.assets);if(HA(ue)){let Ce=g.assetDomain||De.AssetsCdnDomain;Je=Ce?`https://${Ce}/${oe}`:void 0,P(`Syncing assets from ${g.assets}`);let mt=await XA(k,a.assetsBucket,ue,oe,g.dotFilesAsAssets);L(`Uploaded ${mt} asset(s)${Je?` → ${Je}`:""}`)}else Bs(`Assets directory not found: ${ue}`)}P("Resolving secrets");let gt=await YA(g,h);if(g.database?.connection==="aurora-serverless")try{let Ce=await new re(h).getSecretValue({SecretId:`${f}/${t}/db`}),mt=JSON.parse(Ce.SecretString??"{}");if(mt.username)gt.DB_USERNAME=mt.username;if(mt.password)gt.DB_PASSWORD=mt.password}catch(ue){Bs(`Could not resolve Aurora DB credentials: ${ue.message}`)}if(!await k.bucketExists(S))await k.createBucket(S);let jt=await Ld(k,S,f,t),Ze={},wt=ye.queueNames[0],Bt=Es(g,De);if(P("Activating functions"),Ze.http=Cr(g,a,t,"http",gt,Je,wt,Bt),await sa(D,ye.functionNames.http,Ze.http,Z),Ze.cli=Cr(g,a,t,"cli",gt,Je,wt,Bt),await sa(D,ye.functionNames.cli,Ze.cli,Z),ye.queueNames.length)Ze.queue=Cr(g,a,t,"queue",gt,Je,wt,Bt),await sa(D,ye.functionNames.queue,Ze.queue,Z);let nt=(g.provisionedConcurrency??0)>0,W={};if(nt){if(P("Publishing versions + flipping live alias"),W.http=await Md(D,ye.functionNames.http),W.cli=await Md(D,ye.functionNames.cli),ye.queueNames.length)W.queue=await Md(D,ye.functionNames.queue)}if(await Ov(k,S,f,t,{sha:oe,code:Z,previousSha:jt?.sha,previousCode:jt?.code,previousFunctionEnv:jt?.functionEnv,...nt?{functionVersions:W,previousFunctionVersions:jt?.functionVersions}:{},functionEnv:Ze,functionNames:{http:ye.functionNames.http,cli:ye.functionNames.cli,...ye.queueNames.length?{queue:ye.functionNames.queue}:{}},assetUrl:Je,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&g.deploy?.length){P("Running deploy hooks");for(let ue of g.deploy){L(` deploy: ${ue}`);let Ce=await D.invoke({FunctionName:ye.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:ue},LogType:"Tail"});if(Ce.FunctionError)throw bg("Deploy hook failed — the new build is ALREADY LIVE."),L(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${ue}): ${Ce.Payload}`)}}let se=De.HttpApiEndpoint;if(!r.skipHealthCheck&&se){P("Health check");try{let ue=await fetch(se,{method:"GET"});L(`GET ${se} → ${ue.status}`)}catch(ue){Bs(`Health check could not reach ${se}: ${ue.message}`)}}Cg(["Serverless deploy complete","",se?`URL: ${se}`:"",`Stack: ${b}`,`Build: ${oe.slice(0,12)}`].filter(Boolean).join(`
179
+ `;function Av(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function AA(e){return["NoSuchEntity","ResourceNotFoundException","404"].includes(Av(e))}function Ev(e){return["EntityAlreadyExists","ResourceAlreadyExistsException","ResourceConflictException","409"].includes(Av(e))}function Rv(e,t){let r=e?.Items;if(!r)return[];if(Array.isArray(r))return r;let a=r[t];if(a===void 0)return[];return Array.isArray(a)?a:[a]}function Rg(e){let t=e?.Aliases?.Items,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function CA(e){if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected CloudFront alias is invalid");if(!/^[A-Za-z0-9-_]{1,64}$/.test(e.functionName))throw Error("Lambda function name is invalid");let t=e.pathPattern?.startsWith("/")?e.pathPattern:`/${e.pathPattern||"api/*"}`;if(t==="/"||t==="/*"||!t.endsWith("*"))throw Error("API path must be a non-default wildcard pattern such as /api/*");let r=e.originId||`${e.functionName}-url`,a=e.roleName||`${e.functionName}-execution`;if(!/^[A-Za-z0-9_.-]{1,64}$/.test(a))throw Error("IAM role name is invalid");let g=e.memorySize??256,f=e.timeout??10,h=e.logRetentionDays??14;if(g<128||g>10240)throw Error("Lambda memory must be between 128 and 10240 MB");if(f<1||f>900)throw Error("Lambda timeout must be between 1 and 900 seconds");return{region:e.region||"us-east-1",pathPattern:t,originId:r,roleName:a,memorySize:g,timeout:f,logRetentionDays:h}}function yh(e){let t=e.region||"us-east-1";return{cloudfront:new I(e.profile),iam:new Re(t,e.profile),lambda:new T(t,e.profile),logs:new we(t,e.profile),sts:new Te(t,e.profile),sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}async function zS(e,t){let r=CA(e),a=t||yh({profile:e.profile,region:r.region}),[g,f,h]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId),a.cloudfront.getDistributionConfig(e.distributionId)]);if(!g.Account)throw Error("AWS identity did not return an account ID");if(!f.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!(Rg(f).length?Rg(f):Rg(h.DistributionConfig)).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let S,y=!0;try{S=await a.iam.getRole({RoleName:r.roleName})}catch(Ze){if(!AA(Ze))throw Ze;y=!1}let k=S?.Arn||`arn:aws:iam::${g.Account}:role/${r.roleName}`,R=await a.lambda.functionExists(e.functionName),D=R?await a.lambda.getFunctionUrl(e.functionName):null,O=await a.cloudfront.listOriginAccessControls(),M=`${e.functionName}-lambda-url`,z=O.some((Ze)=>Ze.Name===M&&Ze.OriginAccessControlOriginType==="lambda"),J=Rv(h.DistributionConfig.Origins,"Origin"),Z=Rv(h.DistributionConfig.CacheBehaviors,"CacheBehavior"),oe=J.some((Ze)=>String(Ze.Id)===r.originId),G=Z.some((Ze)=>String(Ze.PathPattern)===r.pathPattern),te=[...!y?[`create IAM execution role ${r.roleName}`]:[`reconcile IAM execution policy ${r.roleName}`],...R?[`update Lambda ${e.functionName} code and configuration`]:[`create Lambda ${e.functionName}`],...!D?["create private AWS_IAM function URL"]:[],...!z?[`create Lambda origin access control ${M}`]:[],"grant CloudFront function-URL and invocation permissions",`${G?"reconcile":"add"} ${r.pathPattern} behavior without changing the default behavior`],ye={command:`cloud cdn:origin:remove ${e.distributionId} FUNCTION_URL_HOST --id ${r.originId} --path '${r.pathPattern}' --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,removeFunction:!R,removeRole:!y},Se={mode:e.apply?"apply":"plan",accountId:g.Account,identityArn:g.Arn,distribution:{id:f.Id,arn:f.ARN,alias:e.expectedAlias,domainName:f.DomainName,status:f.Status},function:{name:e.functionName,existed:R,runtime:"nodejs22.x",urlExisted:!!D,url:D?.FunctionUrl},role:{name:r.roleName,existed:y,arn:k},origin:{id:r.originId,pathPattern:r.pathPattern,existed:oe,behaviorExisted:G,accessControlExisted:z},changes:te,rollback:ye,applied:!1};if(!e.apply)return Se;let ie=`${e.distributionId}:${r.pathPattern}`;if(e.confirm!==ie)throw Error(`Pass exact confirmation token ${ie} to mutate the live distribution`);if(!S)S=await a.iam.createRole({RoleName:r.roleName,Description:`Execution role for ${e.functionName}`,AssumeRolePolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]}),Tags:[{Key:"ManagedBy",Value:"ts-cloud"}]});await a.iam.putRolePolicy({RoleName:r.roleName,PolicyName:"lambda-logs",PolicyDocument:JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogStream","logs:PutLogEvents"],Resource:`arn:aws:logs:${r.region}:${g.Account}:log-group:/aws/lambda/${e.functionName}:*`}]})});try{await a.logs.createLogGroup(`/aws/lambda/${e.functionName}`,{ManagedBy:"ts-cloud"})}catch(Ze){if(!Ev(Ze))throw Ze}await a.logs.putRetentionPolicy(`/aws/lambda/${e.functionName}`,r.logRetentionDays);let xe=e.code||RA;if(R)await a.lambda.updateFunctionCodeInline(e.functionName,xe,"index.mjs"),await a.lambda.waitForFunctionActive(e.functionName),await a.lambda.updateFunctionConfiguration({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:S.Arn,Handler:"index.handler",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize});else{let Ze;for(let wt=0;wt<8;wt++)try{await a.lambda.createFunctionWithCode({FunctionName:e.functionName,Runtime:"nodejs22.x",Role:S.Arn,Handler:"index.handler",Code:xe,Filename:"index.mjs",Description:`Private API origin for ${e.expectedAlias}`,Timeout:r.timeout,MemorySize:r.memorySize}),Ze=void 0;break}catch(Bt){if(Ze=Bt,!String(Bt.message).toLowerCase().includes("role"))throw Bt;await a.sleep(1000)}if(Ze)throw Ze}await a.lambda.waitForFunctionActive(e.functionName);let ee=D||await a.lambda.createFunctionUrl({FunctionName:e.functionName,AuthType:"AWS_IAM",InvokeMode:"BUFFERED"});if(!ee.FunctionUrl)throw Error("Lambda did not return a function URL");let De=new URL(ee.FunctionUrl).hostname,Je=await a.cloudfront.findOrCreateOriginAccessControl(M,"lambda"),gt=f.ARN||`arn:aws:cloudfront::${g.Account}:distribution/${e.distributionId}`,jt=[{FunctionName:e.functionName,StatementId:"AllowCloudFrontFunctionUrl",Action:"lambda:InvokeFunctionUrl",Principal:"cloudfront.amazonaws.com",SourceArn:gt,FunctionUrlAuthType:"AWS_IAM"},{FunctionName:e.functionName,StatementId:"AllowCloudFrontInvoke",Action:"lambda:InvokeFunction",Principal:"cloudfront.amazonaws.com",SourceArn:gt,InvokedViaFunctionUrl:!0}];for(let Ze of jt)try{await a.lambda.addPermission(Ze)}catch(wt){if(!Ev(wt))throw wt}return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:De,pathPattern:r.pathPattern,originAccessControlId:Je.Id}),{...Se,function:{...Se.function,url:ee.FunctionUrl},applied:!0}}async function KS(e){let t=`https://${e.alias}/`,r=`https://${e.alias}/api/health`,a=await fetch(t,{redirect:"follow",headers:{"cache-control":"no-cache"}}),g=new Uint8Array(await a.arrayBuffer()),f=EA("sha256").update(g).digest("hex"),h=Date.now(),b=await fetch(r,{redirect:"follow",headers:{"cache-control":"no-cache"}}),S=Date.now()-h,y=await b.text(),k=y;try{k=JSON.parse(y)}catch{}let R;if(e.logs&&e.functionName){let D=await e.logs.filterLogEvents({logGroupName:`/aws/lambda/${e.functionName}`,startTime:h-60000,filterPattern:'"Init Duration"',limit:25});for(let O of D.events||[]){let M=O.message?.match(/Init Duration:\s*([0-9.]+)\s*ms/i);if(M)R=Number(M[1])}}return{frontend:{url:t,status:a.status,sha256:f,unchanged:e.expectedFrontendSha256?f===e.expectedFrontendSha256:void 0,bytes:g.byteLength},api:{url:r,status:b.status,latencyMs:S,healthy:b.ok&&!!k?.ok,body:k},coldStart:{observed:R!==void 0,initDurationMs:R},verifiedAt:(e.now?.()||new Date).toISOString()}}function WS(e){let t=(e.memoryMb||256)/1024,r=Math.max(0,e.requests-(e.includeFreeTier===!1?0:1e6)),a=Math.max(0,e.requests*(e.averageDurationMs/1000)*t-(e.includeFreeTier===!1?0:400000)),g=r/1e6*0.2+a*0.0000166667,f=9.010025,h=16.425;return{lambdaUsd:Number(g.toFixed(2)),alwaysOnFargateAndAlbUsd:Number(25.435025000000003 .toFixed(2)),assumptions:["us-east-1 public list rates snapshot, July 2026","Lambda x86 request and duration pricing with optional monthly free tier","Fargate comparison uses one always-on 0.25 vCPU/0.5 GB task plus one ALB before LCU charges","excludes CloudFront, data transfer, logs, taxes, and application data services"]}}import{createHash as PA}from"node:crypto";function _A(e){let t=e;return String(t?.code||t?.name||t?.statusCode||"")}function TA(e){return _A(e)==="ValidationError"&&String(e.message).includes("does not exist")}function xA(e){return Object.fromEntries((e||[]).map((t)=>[t.OutputKey,t.OutputValue]))}function DA(e){let t=e?.Aliases?.Items??e?.Aliases,r=t?.CNAME??t;if(Array.isArray(r))return r.map(String);if(typeof r==="string")return[r];return[]}function Cv(e){if(!/^[a-z][a-z0-9-]{1,62}$/.test(e.slug))throw Error("Slug must be a lowercase DNS-safe identifier");if(!/^[A-Z0-9]{8,32}$/.test(e.distributionId))throw Error("CloudFront distribution ID is invalid");if(!/^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z0-9-]{2,63}$/.test(e.expectedAlias))throw Error("Expected distribution alias is invalid");let t=e.imageUri.match(/@((?:sha256:)[a-f0-9]{64})$/i)?.[1];if(!t)throw Error("Container image must use an immutable ECR digest URI ending in @sha256:<64 hex>");let r=e.stackName||`${e.slug}-backend`;if(!/^[A-Za-z][A-Za-z0-9-]{0,127}$/.test(r))throw Error("CloudFormation stack name is invalid");let a=e.pathPattern||"/api/*";if(!/^\/[A-Za-z0-9_.*?~!$&'()+,;=:@%/-]+\*$/.test(a)||a==="/*")throw Error("Backend path must be a non-default wildcard pattern");let g=e.originId||`${e.slug}-backend`;if(!/^[A-Za-z0-9_.-]{1,128}$/.test(g))throw Error("CloudFront origin ID is invalid");if(e.originVerifySecret&&e.originVerifySecret.length<24)throw Error("Origin verification secret must contain at least 24 characters");if(!!e.originDomain!==!!e.certificateArn)throw Error("A custom origin domain and matching ACM certificate ARN must be provided together");return{stackName:r,region:e.region||"us-east-1",pathPattern:a,originId:g,digest:t}}function Sh(e){let t=e.region||"us-east-1";return{cloudformation:new A(t,e.profile),cloudfront:new I(e.profile),sts:new Te(t,e.profile),fetch,sleep:(r)=>new Promise((a)=>setTimeout(a,r))}}function Ih(e){let t=Cv(e),r=hl({name:e.name,slug:e.slug,domain:e.originDomain||e.expectedAlias,imageUri:e.imageUri,certificateArn:e.certificateArn,originVerifySecret:e.originVerifySecret,desiredCount:e.desiredCount,database:e.database,cache:e.cache,queue:e.queue}),a=fl(r);return a.Description=`Managed backend for existing static frontend ${e.expectedAlias}`,a.Metadata={ManagedBy:"ts-cloud",ExistingDistributionId:e.distributionId,ExistingDistributionAlias:e.expectedAlias,BackendPathPattern:t.pathPattern,ContainerDigest:t.digest},a}async function OA(e,t,r){let a;for(let g=0;g<30;g++){let f=Date.now();try{let h=await e.fetch(t,{redirect:"manual",headers:r?{"x-origin-verify":r}:void 0}),b=Date.now()-f,S=await h.text(),y=S;try{y=JSON.parse(S)}catch{}if(h.ok)return{url:t,status:h.status,latencyMs:b,body:y};a=Error(`origin returned ${h.status}`)}catch(h){a=h}if(g<29)await e.sleep(1e4)}throw Error(`Backend origin did not become healthy: ${a instanceof Error?a.message:String(a)}`)}async function JS(e,t){let r=Cv(e),a=t||Sh({region:r.region,profile:e.profile}),[g,f]=await Promise.all([a.sts.getCallerIdentity(),a.cloudfront.getDistribution(e.distributionId)]);if(!g.Account)throw Error("AWS identity did not return an account ID");if(!f.Enabled)throw Error(`CloudFront distribution ${e.distributionId} is disabled`);if(!DA(f).includes(e.expectedAlias))throw Error(`Distribution ${e.distributionId} does not contain expected alias ${e.expectedAlias}`);let h;try{h=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0]}catch(te){if(!TA(te))throw te}let b=Ih(e),S=JSON.stringify(b);if(Buffer.byteLength(S)>51200)throw Error("Generated template exceeds the direct CloudFormation template body limit");let y=Object.values(b.Resources||{}).reduce((te,ye)=>(te[ye.Type]=(te[ye.Type]||0)+1,te),{}),k=[`cloud cdn:origin:remove ${e.distributionId} ${e.originDomain||"ALB_HOST"} --id ${r.originId} --path '${r.pathPattern}' --profile ${e.profile||"default"} --apply --confirm 'remove:${e.distributionId}:${r.pathPattern}'`,`After CloudFront is deployed, restore external DNS if changed and delete stack ${r.stackName} only with an approved data-retention decision.`],R={mode:e.apply?"apply":"plan",accountId:g.Account,stack:{name:r.stackName,existed:!!h,status:h?.StackStatus,templateSha256:PA("sha256").update(S).digest("hex"),resourceCount:Object.keys(b.Resources||{}).length,resourceTypes:y},distribution:{id:f.Id,alias:e.expectedAlias,domainName:f.DomainName,status:f.Status,pathPattern:r.pathPattern,originId:r.originId},artifact:{imageUri:e.imageUri,digest:r.digest},services:{database:e.database!==!1,cache:e.cache!==!1,queue:e.queue!==!1,mail:"ses",desiredCount:e.desiredCount||1},cloudFrontApplied:!1,dnsApplied:!1,applied:!1,rollback:k};if(!e.apply)return R;let D=`${e.distributionId}:${r.pathPattern}:${r.stackName}`;if(e.confirm!==D)throw Error(`Pass exact confirmation token ${D} to provision the backend and change live routing`);if(h)try{await a.cloudformation.updateStack({stackName:r.stackName,templateBody:S,capabilities:["CAPABILITY_NAMED_IAM"],tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-update-complete")}catch(te){if(!String(te.message).includes("No updates are to be performed"))throw te}else await a.cloudformation.createStack({stackName:r.stackName,templateBody:S,capabilities:["CAPABILITY_NAMED_IAM"],onFailure:"ROLLBACK",tags:[{Key:"ManagedBy",Value:"ts-cloud"},{Key:"Application",Value:e.slug}]}),await a.cloudformation.waitForStack(r.stackName,"stack-create-complete");let O=(await a.cloudformation.describeStacks({stackName:r.stackName})).Stacks[0],M=xA(O?.Outputs),z=M.AppLoadBalancerDnsName;if(!z)throw Error("Backend stack did not return AppLoadBalancerDnsName");let J=!1;if(e.originDomain&&e.originDomain!==z){if(!a.dns)throw Error(`External DNS provider is required to map ${e.originDomain} to ${z}`);let te=await a.dns.upsertRecord(e.originDomain,{name:e.originDomain,type:"CNAME",content:z,ttl:300});if(!te.success)throw Error(te.message||"External DNS update failed");J=!0}let Z=e.originDomain||z,oe=e.certificateArn?"https-only":"http-only",G=e.skipHealthCheck?void 0:await OA(a,`${oe==="https-only"?"https":"http"}://${Z}/api/health`,e.originVerifySecret);return await a.cloudfront.upsertExistingDistributionOrigin(e.distributionId,{id:r.originId,domainName:Z,pathPattern:r.pathPattern,protocolPolicy:oe,customHeaders:e.originVerifySecret?{"X-Origin-Verify":e.originVerifySecret}:void 0}),{...R,outputs:M,health:G,cloudFrontApplied:!0,dnsApplied:J,applied:!0}}function XS(e={}){let r={fargate:730*(e.desiredCount||1)*0.012342500000000001,applicationLoadBalancer:16.425,natGateway:32.85,postgres:730*(e.multiAzDatabase?0.032:0.016),redis:23.36};return{monthlyUsd:Number(Object.values(r).reduce((a,g)=>a+g,0).toFixed(2)),components:Object.fromEntries(Object.entries(r).map(([a,g])=>[a,Number(g.toFixed(2))])),assumptions:["us-east-1 public on-demand rate snapshot, July 2026","one 0.25 vCPU/0.5 GB Linux Fargate task unless desiredCount is changed","one ALB before LCU charges and one NAT gateway before data processing","single-AZ db.t4g.micro PostgreSQL by default and two cache.t4g.micro Redis nodes","excludes storage, backups, CloudFront, data transfer, public IPv4, logs, email, queue requests, taxes, and free-tier credits"]}}import{execFileSync as $A}from"node:child_process";import{createHash as NA}from"node:crypto";import{existsSync as Pv,mkdirSync as jA,mkdtempSync as BA,readdirSync as MA,readFileSync as LA,rmSync as FA,statSync as _v,writeFileSync as zA}from"node:fs";import{tmpdir as UA}from"node:os";import{basename as qA,join as as,relative as VA,resolve as Pg}from"node:path";var WA=new Set([".git","node_modules","dist","coverage"]);function Tv(e,t=e){let r=[];for(let a of MA(e).sort()){if(WA.has(a))continue;let g=as(e,a);if(sl(g,t))continue;let f=_v(g);if(f.isDirectory())r.push(...Tv(g,t));else if(f.isFile())r.push(VA(t,g))}return r}function bh(e){let t=Pg(e);if(!Pv(t)||!_v(t).isDirectory())throw Error(`Container context does not exist: ${t}`);let r=NA("sha256");for(let a of Tv(t))r.update(a),r.update("\x00"),r.update(LA(as(t,a))),r.update("\x00");return r.digest("hex")}function Ch(e){return{ecr:new He(e.region||"us-east-1",e.profile),run:(t,r,a)=>{$A(t,r,{cwd:a?.cwd,env:a?.env,stdio:a?.stdio||"inherit"})}}}async function YS(e,t){let r=Pg(e.context),a=Pg(e.dockerfile||as(r,"Dockerfile"));if(!Pv(a))throw Error(`Dockerfile does not exist: ${a}`);if(!e.repository.split("/").every((M)=>/^[a-z0-9][a-z0-9._-]*$/.test(M)&&!/[._-]$/.test(M)&&!/[._-]{2}/.test(M)))throw Error("ECR repository name is invalid");let h=t||Ch(e),b=bh(r),S=`sha-${b.slice(0,20)}`,y="";try{y=(await h.ecr.describeRepositories({repositoryNames:[e.repository]})).repositories?.[0]?.repositoryUri||""}catch{}if(!y)y=(await h.ecr.createRepository({repositoryName:e.repository,imageTagMutability:"IMMUTABLE",imageScanningConfiguration:{scanOnPush:!0},tags:[{Key:"ManagedBy",Value:"ts-cloud"}]})).repository?.repositoryUri||"";if(!y)throw Error(`Could not resolve ECR repository URI for ${e.repository}`);await h.ecr.putLifecyclePolicy({repositoryName:e.repository,lifecyclePolicyText:JSON.stringify({rules:[{rulePriority:1,description:"Retain the newest 25 release images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:25},action:{type:"expire"}}]})});let k=`${y}:${S}`,R=BA(as(UA(),"ts-cloud-container-"));try{h.run("docker",["version"],{stdio:"ignore"}),h.run("docker",["build","--platform",e.platform||"linux/amd64","--provenance=false","--sbom=false","--file",a,"--tag",k,r],{cwd:r});let M=(await h.ecr.getAuthorizationToken()).authorizationData?.[0];if(!M?.authorizationToken||!M.proxyEndpoint)throw Error("ECR did not return Docker authorization data");let z=M.proxyEndpoint.replace(/^https?:\/\//,""),J=as(R,"docker");jA(J,{recursive:!0}),zA(as(J,"config.json"),JSON.stringify({auths:{[z]:{auth:M.authorizationToken}}}),{mode:384}),h.run("docker",["push",k],{env:{...process.env,DOCKER_CONFIG:J}})}finally{FA(R,{recursive:!0,force:!0})}let O=(await h.ecr.describeImages({repositoryName:e.repository,imageIds:[{imageTag:S}]})).imageDetails?.[0]?.imageDigest;if(!O||!/^sha256:[a-f0-9]{64}$/i.test(O))throw Error(`ECR did not return an immutable digest for ${qA(k)}`);return{repository:e.repository,tag:S,imageUri:k,digest:O,digestUri:`${y}@${O}`,contextSha256:b}}import{existsSync as HA,readdirSync as KA,readFileSync as JA,statSync as GA}from"node:fs";import{join as xv,relative as QA}from"node:path";function yo(e,t){let r=e.environments?.[t]?.app;if(!r)throw Error(`No serverless app configured for environment '${t}'. Add environments.${t}.app to your config.`);let a=e.project.slug,g=e.environments?.[t]?.region||e.project.region||"us-east-1";return{app:r,slug:a,region:g,stackName:lr(e,t),artifactBucket:cl(a,t),assetsBucket:Xi(a,t)}}async function ho(e,t=8){let r;for(let a=0;a<t;a++)try{return await e()}catch(g){let f=g?.code||g?.name||"",h=String(g?.message||"");if(f==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(h)){r=g,await new Promise((b)=>setTimeout(b,3000));continue}throw g}throw r}var Dv=(e,t)=>`releases/${e}/${t}/current.json`;async function Ld(e,t,r,a){try{return await e.getObjectJson(t,Dv(r,a))}catch{return null}}async function Ov(e,t,r,a,g){await e.putObjectJson(t,Dv(r,a),g)}async function YA(e,t){if(!e.secrets)return{};let r=new re(t),a={},g=Array.isArray(e.secrets)?e.secrets.map((f)=>({envName:f.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:f})):Object.entries(e.secrets).map(([f,h])=>({envName:f,secretId:h}));if(Array.isArray(e.secrets)){let f=new Map;for(let{envName:b,secretId:S}of g)f.set(b,[...f.get(b)??[],S]);let h=[...f.entries()].filter(([,b])=>b.length>1);if(h.length){let b=h.map(([S,y])=>`${S} ← ${y.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${b}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:f,secretId:h}of g){let S=(await r.getSecretValue({SecretId:h})).SecretString??"";try{let y=JSON.parse(S);if(y&&typeof y==="object"&&!Array.isArray(y)){for(let[k,R]of Object.entries(y))a[k]=String(R);continue}}catch{}a[f]=S}return a}function Es(e,t){let r={},a=t.DbProxyEndpoint||t.DbEndpoint;if(a)r.DB_CONNECTION="mysql",r.DB_HOST=a,r.DB_PORT="3306",r.DB_DATABASE=r.DB_DATABASE||"app";if(t.CacheEndpoint){if(r.REDIS_HOST=t.CacheEndpoint,r.REDIS_PORT="6379",e.cache?.driver==="elasticache")r.CACHE_STORE="redis",r.CACHE_DRIVER="redis",r.SESSION_DRIVER="redis"}return r}function Cr(e,t,r,a,g,f,h,b={}){let S=e.kind==="php"?ql({cacheDriver:e.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:a,TSCLOUD_ENV:r,MAINTENANCE_MODE:"0",...e.octane?{TSCLOUD_OCTANE:"1"}:{},...e.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...e.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...b,...t.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${t.slug}-${r}-cache`}:{},...h?{TSCLOUD_QUEUE:h,SQS_QUEUE:h}:{},...f?{ASSET_URL:f}:{},...e.env??{},...g}}function ZA(e){let t=e.slice(e.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[t]??"application/octet-stream"}function*$v(e){for(let t of KA(e)){let r=xv(e,t);if(GA(r).isDirectory())yield*$v(r);else yield r}}async function XA(e,t,r,a,g=!1){let f=0;for(let h of $v(r)){let b=QA(r,h).replace(/\\/g,"/");if(!g&&b.split("/").some((S)=>S.startsWith(".")))continue;await e.putObject({bucket:t,key:`${a}/${b}`,body:JA(h),contentType:ZA(h),cacheControl:"public, max-age=31536000, immutable"}),f++}return f}function eC(e,t){let r=Object.entries(t).reduce((a,[g,f])=>a+Buffer.byteLength(`${g}=${f}`,"utf8"),0);if(r>4096){let a=Object.entries(t).map(([g,f])=>[g,Buffer.byteLength(`${g}=${f}`,"utf8")]).sort((g,f)=>f[1]-g[1]).slice(0,5).map(([g,f])=>`${g} (${f}B)`).join(", ");throw Error(`${e}: environment variables total ${r}B, over AWS's 4096B limit (${r-4096}B too large). Largest: ${a}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function sa(e,t,r,a){eC(t,r),await ho(()=>e.updateFunctionConfiguration({FunctionName:t,Environment:{Variables:r}})),await e.waitForFunctionActive(t,120);let g=a.kind==="image"?{FunctionName:t,ImageUri:a.imageUri}:{FunctionName:t,S3Bucket:a.bucket,S3Key:a.key};await ho(()=>e.updateFunctionCode(g)),await e.waitForFunctionActive(t,120)}async function Md(e,t){let a=(await ho(()=>e.publishVersion({FunctionName:t}))).Version;if(!a)throw Error(`publishVersion returned no version for ${t}`);return await ho(()=>e.updateAlias({FunctionName:t,Name:"live",FunctionVersion:a})),a}async function Ya(e,t,r={}){let a=yo(e,t),{app:g,slug:f,region:h,stackName:b,artifactBucket:S}=a,y=r.projectRoot??process.cwd();xs(`Deploying serverless app: ${f} (${t})`),L(`Stack: ${b}`),L(`Region: ${h}`);let k=new o(h),R=new A(h),D=new T(h),O=g.kind==="php",M=g.packaging==="image",z=ns(g),J,Z,oe,G,te=[];if(M&&z.usesLayer&&z.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${z.kind}${z.kind==="node"?` ${z.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(M){P("Building + pushing container image");let{buildAndPushServerlessImage:ue}=await import("./chunk-2ntc2qz2.js"),Ce=await ue({app:g,projectRoot:y,region:h,repository:`${f}-${t}`,skipBuild:r.skipBuild,onStep:(mt)=>L(` ${mt}`)});J=Ce.handlers,Z={kind:"image",imageUri:Ce.imageUri},oe=Ce.tag,te.push({ParameterKey:"ImageUri",ParameterValue:Ce.imageUri})}else{P("Packaging application");let ue=O?jl({projectRoot:y,app:g,skipBuild:r.skipBuild,onStep:(kt)=>L(` ${kt}`)}):await mn({projectRoot:y,app:g,skipBuild:r.skipBuild,onStep:(kt)=>L(` ${kt}`)}),Ce=$l(f,t,ue.sha256);if(L(`Artifact: ${ue.sha256.slice(0,12)} (${(ue.zip.length/1024).toFixed(0)} KB)`),J=ue.handlers,oe=ue.sha256,z.usesLayer){let kt=z.layerEnvVar?process.env[z.layerEnvVar]:void 0;if(G=g.layers??(kt?[kt]:void 0),!G?.length){let _e=z.layerKind==="php"?"serverless:build-php-layer":z.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${z.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${z.layerEnvVar} env var (build one with \`cloud ${_e}\`)${z.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await k.bucketExists(S))P(`Creating artifact bucket ${S}`),await k.createBucket(S);if(await k.headObject(S,Ce).then((kt)=>kt!==null).catch(()=>!1))L("Artifact already uploaded — reusing");else P("Uploading artifact"),await k.putObject({bucket:S,key:Ce,body:ue.zip,contentType:"application/zip"});Z={kind:"zip",bucket:S,key:Ce},te.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:Ce})}let ye=Fl({config:e,environment:t,app:g,handlers:J,runtimeLayers:G}),Se=JSON.stringify(ye.template),ie=["CAPABILITY_NAMED_IAM"],xe=await R.describeStacks({stackName:b}).then((ue)=>ue.Stacks[0]?.StackStatus).catch(()=>{return}),ee=xe!==void 0;if(xe&&/DELETE_IN_PROGRESS/.test(xe))P("Waiting for an in-progress stack delete to finish"),await R.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;else if(xe&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(xe))P(`Deleting unusable stack (status ${xe}) before recreate`),await R.deleteStack(b),await R.waitForStack(b,"stack-delete-complete").catch(()=>{}),ee=!1;P(ee?"Updating infrastructure stack":"Creating infrastructure stack");try{if(ee)await R.updateStack({stackName:b,templateBody:Se,parameters:te,capabilities:ie}),await R.waitForStack(b,"stack-update-complete");else await R.createStack({stackName:b,templateBody:Se,parameters:te,capabilities:ie,onFailure:"DELETE"}),await R.waitForStack(b,"stack-create-complete")}catch(ue){if(/No updates are to be performed/i.test(String(ue?.message)))L("No infrastructure changes");else throw ue}let De=await R.getStackOutputs(b).catch(()=>({})),Je;if(g.assets){let ue=xv(y,g.assets);if(HA(ue)){let Ce=g.assetDomain||De.AssetsCdnDomain;Je=Ce?`https://${Ce}/${oe}`:void 0,P(`Syncing assets from ${g.assets}`);let mt=await XA(k,a.assetsBucket,ue,oe,g.dotFilesAsAssets);L(`Uploaded ${mt} asset(s)${Je?` → ${Je}`:""}`)}else Bs(`Assets directory not found: ${ue}`)}P("Resolving secrets");let gt=await YA(g,h);if(g.database?.connection==="aurora-serverless")try{let Ce=await new re(h).getSecretValue({SecretId:`${f}/${t}/db`}),mt=JSON.parse(Ce.SecretString??"{}");if(mt.username)gt.DB_USERNAME=mt.username;if(mt.password)gt.DB_PASSWORD=mt.password}catch(ue){Bs(`Could not resolve Aurora DB credentials: ${ue.message}`)}if(!await k.bucketExists(S))await k.createBucket(S);let jt=await Ld(k,S,f,t),Ze={},wt=ye.queueNames[0],Bt=Es(g,De);if(P("Activating functions"),Ze.http=Cr(g,a,t,"http",gt,Je,wt,Bt),await sa(D,ye.functionNames.http,Ze.http,Z),Ze.cli=Cr(g,a,t,"cli",gt,Je,wt,Bt),await sa(D,ye.functionNames.cli,Ze.cli,Z),ye.queueNames.length)Ze.queue=Cr(g,a,t,"queue",gt,Je,wt,Bt),await sa(D,ye.functionNames.queue,Ze.queue,Z);let nt=(g.provisionedConcurrency??0)>0,W={};if(nt){if(P("Publishing versions + flipping live alias"),W.http=await Md(D,ye.functionNames.http),W.cli=await Md(D,ye.functionNames.cli),ye.queueNames.length)W.queue=await Md(D,ye.functionNames.queue)}if(await Ov(k,S,f,t,{sha:oe,code:Z,previousSha:jt?.sha,previousCode:jt?.code,previousFunctionEnv:jt?.functionEnv,...nt?{functionVersions:W,previousFunctionVersions:jt?.functionVersions}:{},functionEnv:Ze,functionNames:{http:ye.functionNames.http,cli:ye.functionNames.cli,...ye.queueNames.length?{queue:ye.functionNames.queue}:{}},assetUrl:Je,timestamp:new Date().toISOString()}),!r.skipDeployHooks&&g.deploy?.length){P("Running deploy hooks");for(let ue of g.deploy){L(` deploy: ${ue}`);let Ce=await D.invoke({FunctionName:ye.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:ue},LogType:"Tail"});if(Ce.FunctionError)throw bg("Deploy hook failed — the new build is ALREADY LIVE."),L(` Roll back with: cloud serverless:rollback --env ${t}`),Error(`Deploy hook failed (${ue}): ${Ce.Payload}`)}}let se=De.HttpApiEndpoint;if(!r.skipHealthCheck&&se){P("Health check");try{let ue=await fetch(se,{method:"GET"});L(`GET ${se} → ${ue.status}`)}catch(ue){Bs(`Health check could not reach ${se}: ${ue.message}`)}}Cg(["Serverless deploy complete","",se?`URL: ${se}`:"",`Stack: ${b}`,`Build: ${oe.slice(0,12)}`].filter(Boolean).join(`
180
180
  `),"green")}async function Nn(e,t){let r=yo(e,t),a=new o(r.region),g=new T(r.region),f=await Ld(a,r.artifactBucket,r.slug,t);if(!f)throw Error("No previous release to redeploy. Run a full deploy first.");xs(`Redeploying ${r.slug} (${t}) — build ${f.sha.slice(0,12)}`);for(let[h,b]of Object.entries(f.functionNames)){if(!b)continue;P(`Re-activating ${h} (${b})`),await sa(g,b,f.functionEnv[h]??{},f.code);let S=f.functionVersions?.[h];if(S)await ho(()=>g.updateAlias({FunctionName:b,Name:"live",FunctionVersion:S}))}Mn("Redeploy complete")}async function Bn(e,t){let r=yo(e,t),a=new o(r.region),g=new T(r.region),f=await Ld(a,r.artifactBucket,r.slug,t);if(!f?.previousCode)throw Error("No previous release to roll back to.");xs(`Rolling back ${r.slug} (${t}) → ${f.previousSha?.slice(0,12)}`);for(let[h,b]of Object.entries(f.functionNames)){if(!b)continue;P(`Restoring ${h} (${b})`);let S=f.previousFunctionEnv?.[h]??f.functionEnv[h]??{};await sa(g,b,S,f.previousCode);let y=f.previousFunctionVersions?.[h];if(y)await ho(()=>g.updateAlias({FunctionName:b,Name:"live",FunctionVersion:y}))}await Ov(a,r.artifactBucket,r.slug,t,{...f,sha:f.previousSha??f.sha,code:f.previousCode,functionEnv:f.previousFunctionEnv??f.functionEnv,functionVersions:f.previousFunctionVersions??f.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),Mn("Rollback complete")}async function Er(e,t,r,a){let g=yo(e,t),f=new T(g.region),h=`${g.slug}-${t}-http`,S={...(await f.getFunction(h)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=r?"1":"0",r&&a)S.MAINTENANCE_BYPASS_SECRET=a;if(!r)delete S.MAINTENANCE_BYPASS_SECRET;if(await ho(()=>f.updateFunctionConfiguration({FunctionName:h,Environment:{Variables:S}})),(g.app.provisionedConcurrency??0)>0)await f.waitForFunctionActive(h,120),await Md(f,h);Mn(r?"Application is now in maintenance mode (503)":"Application is live")}async function lt(e,t,r){let a=yo(e,t),g=new T(a.region),f=`${a.slug}-${t}-cli`,h=await g.invoke({FunctionName:f,InvocationType:"RequestResponse",Payload:{command:r},LogType:"Tail"});if(h.FunctionError)throw Error(`Command failed: ${h.Payload}`);return h.Payload??""}async function hr(e,t){let r=yo(e,t),a=new A(r.region),g=new T(r.region),f=new o(r.region),h="not deployed",b={};try{let{Stacks:M}=await a.describeStacks({stackName:r.stackName});h=M?.[0]?.StackStatus??h;for(let z of M?.[0]?.Outputs??[])if(z.OutputKey)b[z.OutputKey]=z.OutputValue??""}catch{}let S=Ml(r.app,r.slug,t),y=r.app.provisionedConcurrency??0,k=["http","cli",...S.length?["queue"]:[]],R=`${r.slug}-${t}`,D=[];for(let M of k){let z=`${R}-${M}`,J={mode:M,name:z,version:"$LATEST"};if(y>0){let Z=await g.getAlias(z,"live").catch(()=>null);if(Z?.FunctionVersion){J.version=Z.FunctionVersion;let oe=await g.getProvisionedConcurrencyConfig(z,"live").catch(()=>null);if(oe)J.provisioned={status:oe.Status??"-",allocated:oe.AllocatedProvisionedConcurrentExecutions??0,requested:oe.RequestedProvisionedConcurrentExecutions??0}}}D.push(J)}let O=await Ld(f,r.artifactBucket,r.slug,t).catch(()=>null);return{slug:r.slug,environment:t,region:r.region,stackStatus:h,endpoint:b.HttpApiEndpoint,assetUrl:O?.assetUrl,scheduler:r.app.scheduler??"on",queues:S,provisionedConcurrency:y,functions:D,lastRelease:O?{sha:O.sha,timestamp:O.timestamp}:void 0}}function tC(e,t){return`${e}-${t}-db`}async function Nv(e,t,r,a){let g=yo(e,t);if(g.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:f}=await import("./chunk-86qwnp25.js"),h=new f(g.region),b=tC(g.slug,t);P(`Scaling ${b} → ${r}–${a} ACUs`),await h.modifyDBCluster({DBClusterIdentifier:b,ServerlessV2ScalingConfiguration:{MinCapacity:r,MaxCapacity:a},ApplyImmediately:!0}),Mn(`Scaling applied to ${b} (takes effect shortly).`)}class _g{client;region;constructor(e="us-east-1"){this.region=e,this.client=new n}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((f)=>({Name:f.Name,Priority:f.Priority,Action:f.Action?Object.keys(f.Action)[0]:f.OverrideAction?Object.keys(f.OverrideAction)[0]:"count"}))}}var rC=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"routing",label:"Routing"},{index:4,id:"apps",label:"Applications"},{index:5,id:"runtime",label:"Background runtime"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],nC=[{index:0,id:"clients",label:"Clients"},{index:1,id:"dns",label:"DNS & TLS"},{index:2,id:"edge",label:"Edge"},{index:3,id:"entry",label:"Entry points"},{index:4,id:"compute",label:"Compute"},{index:5,id:"messaging",label:"Messaging & pooling"},{index:6,id:"data",label:"Data services"},{index:7,id:"durability",label:"Durability"}],iC=[{match:/^redis/,kind:"cache",label:"Redis"},{match:/^(?:mysql|mariadb)/,kind:"database",label:"MySQL"},{match:/^postgres/,kind:"database",label:"PostgreSQL"},{match:/^meilisearch/,kind:"database",label:"Meilisearch"},{match:/^vitess|^vtgate/,kind:"database",label:"Vitess"},{match:/^memcached/,kind:"cache",label:"Memcached"}],oC=/^(?:rpx-gateway|nginx|caddy|traefik|haproxy)$/;function Pe(e,t=""){let r=e==null?"":String(e).trim();return r&&r!=="-"&&r!=="—"?r:t}function sC(e){return Array.isArray(e)?e.length:0}function Jn(e){let t=Pe(e).toLowerCase();if(!t)return"unknown";if(["running","live","active","available","success","ok","healthy","enabled"].includes(t))return"ok";if(["failed","stopped","unreachable","error","critical","disabled"].includes(t))return"bad";if(["configured","creating","pending","degraded","shadowed","warn","unknown"].includes(t))return"warn";return"warn"}function Gt(e,t,r){if(r.has(t.source)&&r.has(t.target))e.push(t)}function Qt(e,t={}){let r=[],a=[],g=[],f=e.server??{},h=Array.isArray(e.sites)?e.sites:[],b=Array.isArray(e.services)?e.services:[],S=Array.isArray(e.workers)?e.workers:[],y=e.security??{},k=!!e._serverReachable&&!e.metricsUnavailable,R="box";if(!k)g.push("The compute box could not be probed, so live service state is missing; the shape comes from your cloud config.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let D=[...new Set(h.map((ie)=>Pe(ie.domain)||Pe(ie.route).split("/")[0]).filter((ie)=>ie&&ie!=="internal"&&ie!=="loopback"))],O=Array.isArray(y.tlsCertificates)?y.tlsCertificates:[],M=O.filter((ie)=>Number(ie?.daysRemaining??999)<21).length;r.push({id:"dns",label:D.length===1?D[0]:"Public domains",kind:"dns",layer:1,status:M?"warn":D.length?"ok":"unknown",sub:D.length>1?`${D.length} domains`:"DNS & certificates",facts:[{label:"Domains",value:D.length?D.slice(0,6).join(", "):"none resolved"},{label:"Certificates",value:O.length?`${O.length} issued`:"none reported"},...M?[{label:"Expiring",value:`${M} within 21 days`}]:[]],href:"/server/security",external:!0});let z=y.firewall??{},J=Array.isArray(y.ports)?y.ports:[];r.push({id:"firewall",label:"Host firewall",kind:"firewall",layer:2,status:Jn(z.status),sub:Pe(z.summary,"Inbound filtering"),facts:[{label:"State",value:Pe(z.status,"unknown")},{label:"Open ports",value:J.length?J.map((ie)=>Pe(ie.listen)).join(", "):"not reported"}],href:"/server/firewall",group:"box"});let Z=b.find((ie)=>oC.test(Pe(ie.name)));r.push({id:"proxy",label:Pe(Z?.name,"Reverse proxy"),kind:"proxy",layer:3,status:Z?Jn(Z.status):"unknown",sub:"TLS termination & routing",facts:[{label:"Service",value:Pe(Z?.name,"not detected")},{label:"State",value:Pe(Z?.status,k?"not running":"not probed")},{label:"Routes",value:`${h.length} site${h.length===1?"":"s"}`}],href:"/server/services",group:"box"});for(let ie of h){let xe=`site:${Pe(ie.name)}`;if(!Pe(ie.name))continue;r.push({id:xe,label:Pe(ie.name),kind:"site",layer:4,status:Jn(ie.status),sub:Pe(ie.runtime,"runtime"),facts:[{label:"Route",value:Pe(ie.route,"internal")},{label:"Runtime",value:Pe(ie.runtime,"unknown")},{label:"Delivery",value:Pe(ie.deploy,"unknown")},{label:"TLS",value:Pe(ie.tls,"unknown")},...ie.responseMs!=null?[{label:"Response",value:`${Math.round(Number(ie.responseMs))} ms`}]:[],...ie.httpStatus!=null?[{label:"HTTP",value:String(ie.httpStatus)}]:[]],href:"/server/sites",group:"box"})}for(let ie of S){let xe=`worker:${Pe(ie.name)}`;if(!Pe(ie.name))continue;r.push({id:xe,label:Pe(ie.name),kind:"worker",layer:5,status:Jn(ie.status),sub:`${Number(ie.processes??1)} process${Number(ie.processes??1)===1?"":"es"}`,facts:[{label:"Processes",value:String(ie.processes??1)},{label:"State",value:Pe(ie.status,"unknown")},...Pe(ie.site)?[{label:"Site",value:Pe(ie.site)}]:[]],href:"/operations/jobs",group:"box"})}let oe=e.serverScheduler??{};if(oe.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:5,status:"ok",sub:"Cron dispatch",facts:[{label:"Last run",value:Pe(oe.lastRun,"unknown")}],href:"/operations/jobs",group:"box"});let G=b.map((ie)=>{let xe=Pe(ie.name),ee=iC.find((De)=>De.match.test(xe));return ee?{service:ie,name:xe,...ee}:null}).filter((ie)=>!!ie);for(let ie of G)r.push({id:`data:${ie.name}`,label:ie.label,kind:ie.kind,layer:6,status:Jn(ie.service.status),sub:ie.name,facts:[{label:"Unit",value:ie.name},{label:"State",value:Pe(ie.service.status,"unknown")}],href:"/data/services",group:"box"});let te=e.backup??{};if(te.enabled)r.push({id:"backup",label:"Backups",kind:"backup",layer:7,status:"ok",sub:Pe(te.destination,"destination"),facts:[{label:"Destination",value:Pe(te.destination,"unknown")},{label:"Schedule",value:Pe(te.schedule,"unknown")},{label:"Retention",value:`${te.retention??0} copies`},{label:"Last run",value:Pe(te.last,"unknown")}],href:"/data/backups"});let ye=new Set(r.map((ie)=>ie.id));Gt(a,{source:"internet",target:"dns",flow:"request",label:"https"},ye),Gt(a,{source:"dns",target:"firewall",flow:"request",label:"443/80"},ye),Gt(a,{source:"firewall",target:"proxy",flow:"request"},ye);for(let ie of h){let xe=`site:${Pe(ie.name)}`;Gt(a,{source:"proxy",target:xe,flow:"request",label:Pe(ie.path)||void 0,status:Jn(ie.status)},ye)}for(let ie of S){let xe=`worker:${Pe(ie.name)}`,ee=`site:${Pe(ie.site)}`;if(ye.has(ee))Gt(a,{source:ee,target:xe,flow:"async",label:"queue"},ye);else Gt(a,{source:"proxy",target:xe,flow:"async",label:"queue"},ye)}for(let ie of S)Gt(a,{source:"scheduler",target:`worker:${Pe(ie.name)}`,flow:"async",label:"dispatch"},ye);let Se=[...h.map((ie)=>`site:${Pe(ie.name)}`),...S.map((ie)=>`worker:${Pe(ie.name)}`)];for(let ie of G)for(let xe of Se)Gt(a,{source:xe,target:`data:${ie.name}`,flow:"data",label:"localhost"},ye);if(G.length&&Se.length)g.push("Data-service edges show co-location on the box: every process on it can reach localhost. They are not a declared per-site binding.");for(let ie of G)Gt(a,{source:`data:${ie.name}`,target:"backup",flow:"backup",label:"snapshot"},ye);for(let ie of h)Gt(a,{source:`site:${Pe(ie.name)}`,target:"backup",flow:"backup"},ye);return{mode:"server",project:Pe(t.project)||Pe(e.project?.name)||Pe(f.name,"project"),environment:Pe(t.environment)||Pe(e.environment,"production"),provider:Pe(f.provider,"unknown"),region:Pe(f.region,"unknown"),generatedAt:new Date().toISOString(),layers:rC,groups:[{id:"box",label:Pe(f.name,"App server"),sub:[Pe(f.provider),Pe(f.region),Pe(f.ip)].filter(Boolean).join(" · ")}],nodes:r,links:a,notes:g}}function vs(e,t={}){let r=[],a=[],g=[],f=e.app??{},h=Array.isArray(e.functions)?e.functions:[],b=Array.isArray(e.queues)?e.queues:[],S=e.metrics??{};if(!h.length)g.push("No Lambda functions were read for this environment, so the compute layer is empty rather than assumed.");r.push({id:"internet",label:"Internet",kind:"internet",layer:0,status:"ok",sub:"Public traffic",facts:[],external:!0});let y=Pe(f.url),k=y.replace(/^https?:\/\//,"").split("/")[0];r.push({id:"dns",label:k||"Application domain",kind:"dns",layer:1,status:k?"ok":"unknown",sub:"DNS & certificates",facts:[{label:"Endpoint",value:y||"not resolved"}],external:!0});let R=e.waf;if(R)r.push({id:"waf",label:"WAF",kind:"waf",layer:2,status:Jn(R.status??"active"),sub:Pe(R.scope,"Managed rules"),facts:[{label:"Web ACL",value:Pe(R.name,"unnamed")},...R.blocked!=null?[{label:"Blocked (24h)",value:String(R.blocked)}]:[],{label:"Rules",value:String(sC(e.wafRules))}],href:"/serverless/firewall"});let D=e.assetsInfo;if(D)r.push({id:"cdn",label:"Asset CDN",kind:"cdn",layer:2,status:"ok",sub:Pe(D.cdn,"CloudFront"),facts:[{label:"Distribution",value:Pe(D.cdn,"unknown")},{label:"Custom domain",value:Pe(D.customDomain,"none")}],href:"/serverless/assets"}),r.push({id:"assets",label:"Asset bucket",kind:"storage",layer:6,status:"ok",sub:Pe(D.bucket,"S3"),facts:[{label:"Bucket",value:Pe(D.bucket,"unknown")},...D.files?[{label:"Objects",value:String(D.files)}]:[],...D.sizeMb?[{label:"Size",value:`${D.sizeMb} MB`}]:[]],href:"/serverless/assets"});let O=h.find((ee)=>Pe(ee.key).startsWith("http"));r.push({id:"gateway",label:"HTTP entry point",kind:"gateway",layer:3,status:O?"ok":"unknown",sub:"Function URL / API Gateway",facts:[{label:"Endpoint",value:y||"not resolved"},{label:"Invocations (24h)",value:String(S.invocations??0)},...S.errorRatePct!=null?[{label:"Error rate",value:`${S.errorRatePct}%`}]:[]],href:"/serverless/metrics"});for(let ee of h){let De=`fn:${Pe(ee.name)}`;if(!Pe(ee.name))continue;let Je=Number(ee.errors??0),gt=Number(ee.invocations??0);r.push({id:De,label:Pe(ee.key,Pe(ee.name)),kind:"function",layer:4,status:Je>0?gt&&Je/gt>0.02?"bad":"warn":gt?"ok":"idle",sub:Pe(ee.runtime,"lambda"),facts:[{label:"Function",value:Pe(ee.name)},{label:"Memory",value:`${ee.memory??0} MB`},{label:"Timeout",value:`${ee.timeout??0}s`},{label:"Invocations (24h)",value:String(gt)},{label:"Errors (24h)",value:String(Je)},{label:"p95",value:`${ee.p95??0} ms`},...ee.provisioned?[{label:"Provisioned",value:Pe(ee.provisioned)}]:[]],href:"/serverless/functions"})}for(let ee of b){let De=`queue:${Pe(ee.name)}`;if(!Pe(ee.name))continue;let Je=Number(ee.dlq??0);r.push({id:De,label:Pe(ee.name),kind:"queue",layer:5,status:Je>0?"bad":Number(ee.visible??0)>0?"warn":"ok",sub:"SQS",facts:[{label:"Visible",value:String(ee.visible??0)},{label:"In flight",value:String(ee.inFlight??0)},{label:"Processed (24h)",value:String(ee.processed??0)},{label:"Dead letter",value:String(Je)}],href:"/serverless/queues"})}let M=e.aurora;if(M)r.push({id:"database",label:"Aurora Serverless",kind:"database",layer:6,status:Jn(M.status),sub:Pe(M.engine,"aurora"),facts:[{label:"Cluster",value:Pe(M.id,"unknown")},{label:"Capacity",value:`${M.currentAcu??0} ACU (${M.minAcu??0}–${M.maxAcu??0})`},{label:"Connections",value:String(M.connections??0)}],href:"/serverless/data"});let z=e.proxy;if(z)r.push({id:"rds-proxy",label:"RDS Proxy",kind:"database",layer:5,status:Jn(z.status),sub:"Connection pooling",facts:[{label:"Proxy",value:Pe(z.name,"unknown")},{label:"Endpoint",value:Pe(z.endpoint,"unknown")},{label:"Pooled",value:String(z.pooledConns??0)}],href:"/serverless/data"});let J=e.redis;if(J)r.push({id:"cache",label:"ElastiCache",kind:"cache",layer:6,status:Jn(J.status),sub:Pe(J.node,"redis"),facts:[{label:"Group",value:Pe(J.id,"unknown")},{label:"Hit rate",value:`${J.hitRate??0}%`}],href:"/serverless/data"});let Z=e.efs;if(Z)r.push({id:"efs",label:"EFS",kind:"filesystem",layer:6,status:Jn(Z.status),sub:Pe(Z.mount,"/mnt/local"),facts:[{label:"File system",value:Pe(Z.id,"unknown")},{label:"Mount",value:Pe(Z.mount,"unknown")},{label:"Size",value:`${Z.sizeMb??0} MB`}],href:"/data/volumes"});let oe=e.scheduler??{};if(oe.enabled)r.push({id:"scheduler",label:"Scheduler",kind:"scheduler",layer:3,status:"ok",sub:Pe(oe.expression,"rate(1 minute)"),facts:[{label:"Expression",value:Pe(oe.expression,"unknown")},{label:"Last run",value:Pe(oe.lastRun,"unknown")}],href:"/operations/jobs"});let G=new Set(r.map((ee)=>ee.id)),te=G.has("waf")?"waf":"gateway";Gt(a,{source:"internet",target:"dns",flow:"request",label:"https"},G),Gt(a,{source:"dns",target:te,flow:"request"},G),Gt(a,{source:"dns",target:"cdn",flow:"request",label:"assets"},G),Gt(a,{source:"waf",target:"gateway",flow:"request",label:"allowed"},G),Gt(a,{source:"cdn",target:"assets",flow:"data",label:"origin"},G);let ye=h.filter((ee)=>Pe(ee.key).startsWith("http")),Se=h.filter((ee)=>Pe(ee.key).startsWith("queue")),ie=h.filter((ee)=>Pe(ee.key).startsWith("cli"));for(let ee of ye)Gt(a,{source:"gateway",target:`fn:${Pe(ee.name)}`,flow:"request",label:"invoke"},G);for(let ee of ie)Gt(a,{source:"scheduler",target:`fn:${Pe(ee.name)}`,flow:"async",label:"schedule"},G);for(let ee of b){for(let De of ye)Gt(a,{source:`fn:${Pe(De.name)}`,target:`queue:${Pe(ee.name)}`,flow:"async",label:"publish"},G);for(let De of Se)Gt(a,{source:`queue:${Pe(ee.name)}`,target:`fn:${Pe(De.name)}`,flow:"async",label:"consume"},G)}let xe=["rds-proxy","database","cache","efs","assets"];for(let ee of h){let De=`fn:${Pe(ee.name)}`;if(G.has("rds-proxy"))Gt(a,{source:De,target:"rds-proxy",flow:"data",label:"pooled"},G);else Gt(a,{source:De,target:"database",flow:"data",label:"sql"},G);for(let Je of xe.filter((gt)=>gt!=="rds-proxy"&&gt!=="database"))Gt(a,{source:De,target:Je,flow:"data"},G)}return Gt(a,{source:"rds-proxy",target:"database",flow:"data",label:"sql"},G),{mode:"serverless",project:Pe(t.project)||Pe(f.name,"application"),environment:Pe(t.environment)||Pe(f.env,"production"),provider:"aws",region:Pe(f.region,"unknown"),generatedAt:new Date().toISOString(),layers:nC,groups:[],nodes:r,links:a,notes:g}}function Eh(e,t,r={}){return e==="serverless"?vs(t,r):Qt(t,r)}function jv(e){return String(e).padStart(2,"0")}function ks(e){return`${e.getUTCFullYear()}-${jv(e.getUTCMonth()+1)}-${jv(e.getUTCDate())}`}function aC(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function aa(e,t,r,a,g,f){let h=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:g,EndTime:f,Period:86400,Statistics:[a]}).catch(()=>[]);if(!h.length)return 0;if(a==="Sum")return h.reduce((b,S)=>b+(S.Sum??0),0);if(a==="Maximum")return Math.max(...h.map((b)=>b.Maximum??0));return h.reduce((b,S)=>b+(S.Average??0),0)/h.length}async function ca(e,t,r,a,g,f,h){let b=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:f,EndTime:h,Period:86400,Statistics:[g]}).catch(()=>[]);if(!b.length)return 0;if(g==="Sum")return b.reduce((S,y)=>S+(y.Sum??0),0);if(g==="Maximum")return Math.max(...b.map((S)=>S.Maximum??0));return b.reduce((S,y)=>S+(y.Average??0),0)/b.length}async function Tg(e,t,r,a,g){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:g,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(f.reduce((h,b)=>h+(b.Percentiles?.[r]??0),0))}async function xn(e,t){let r=await hr(e,t),a=r.region,g=new fe(a),f=new T(a),h=new we(a),b=new Date,S=new Date(b.getTime()-86400000),y=e.environments?.[t]?.app,k={};k.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},k.maintenance={enabled:!1},k.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let R=0,D=0,O=0,M=[],z=[],J=[];for(let te of r.functions){let[ye,Se,ie,xe,ee,De,Je,gt,jt]=await Promise.all([aa(g,te.name,"Invocations","Sum",S,b),aa(g,te.name,"Errors","Sum",S,b),aa(g,te.name,"Throttles","Sum",S,b),aa(g,te.name,"Duration","Average",S,b),f.getFunction(te.name).catch(()=>null),Tg(g,te.name,"p50",S,b),Tg(g,te.name,"p95",S,b),Tg(g,te.name,"p99",S,b),g.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:te.name}],StartTime:new Date(b.getTime()-43200000),EndTime:b,Period:3600,Stat:"Sum"}).catch(()=>[])]);R+=ye,D+=Se,O=Math.max(O,xe);let Ze=ee?.Configuration?.MemorySize??0,wt=Object.keys(ee?.Configuration?.Environment?.Variables??{}),Bt=[],nt=0;try{let{events:se=[]}=await h.filterLogEvents({logGroupName:`/aws/lambda/${te.name}`,startTime:S.getTime(),limit:120});for(let ue of se){let Ce=(ue.message??"").trim(),mt=/Max Memory Used:\s*(\d+)\s*MB/.exec(Ce);if(mt)nt=Math.max(nt,Number(mt[1]));if(Ce&&!/^(?:START|END|REPORT|INIT_START)/.test(Ce))J.push({source:te.mode||te.name,timestamp:new Date(ue.timestamp??0).toISOString(),when:aC(ue.timestamp??0),message:Ce.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(Ce)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(Ce)?"warn":"info"})}Bt=se.filter((ue)=>!/^(?:START|END|REPORT|INIT_START)/.test((ue.message??"").trim())).slice(-6).map((ue)=>({ts:new Date(ue.timestamp??0).toISOString().slice(11,19),msg:(ue.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(ue.message??"")}))}catch{}let W=Math.max(1,...jt);M.push({key:te.mode,name:te.name,version:te.version,memory:Ze,timeout:ee?.Configuration?.Timeout??0,runtime:ee?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(ye),errors:Math.round(Se),p95:Je||Math.round(xe),status:"active",provisioned:te.provisioned?`${te.provisioned.allocated}/${te.provisioned.requested}`:void 0}),z.push({key:te.mode,name:te.name,runtime:ee?.Configuration?.Runtime??"provided.al2023",arch:ee?.Configuration?.Architectures?.[0]??"x86_64",memory:Ze,timeout:ee?.Configuration?.Timeout??0,ephemeral:ee?.Configuration?.EphemeralStorage?.Size??512,version:te.version,concurrency:y?.concurrency??"—",invocations:Math.round(ye),errors:Math.round(Se),throttles:Math.round(ie),p50:De||Math.round(xe),p95:Je||Math.round(xe),p99:gt||Math.round(xe),maxMem:nt,spark:jt.length?jt.map((se)=>Math.round(se/W*100)):[0],env:wt.length?wt:["(none)"],recent:Bt.length?Bt:[{ts:"—",msg:"no recent events",err:!1}]})}k.functions=M,k.functionsDetail=z,k.serverlessLogs=J.sort((te,ye)=>String(ye.timestamp).localeCompare(String(te.timestamp))).slice(0,600),k.serverlessLogsEmptyReason=J.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let Z=R?Number((D/R*100).toFixed(2)):0,oe=Math.round(await aa(g,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",S,b));k.metrics={invocations:Math.round(R),errorRatePct:Z,p95Ms:Math.round(O),coldStartPct:void 0,concurrency:oe,estCostUsd:void 0};try{let te=new me(a),ye=[],Se=[],ie=0;try{let{QueueUrl:ee}=await te.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:De}=await te.getQueueAttributes(ee);ie=Number(De.ApproximateNumberOfMessages??0)}catch{}let xe=y?Ar(y,r.slug,t):[];for(let ee of xe){let De=ee.name.replace(`${r.slug}-${t}-`,""),Je=0,gt=0;try{let{QueueUrl:Ze}=await te.getQueueUrl(ee.name),{Attributes:wt}=await te.getQueueAttributes(Ze);Je=Number(wt.ApproximateNumberOfMessages??0),gt=Number(wt.ApproximateNumberOfMessagesNotVisible??0)}catch{}let jt=Math.round(await ca(g,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:ee.name}],"Sum",S,b));ye.push({name:De,visible:Je,inFlight:gt,processed:jt,dlq:ie}),Se.push({name:ee.name,short:De,visible:Je,inFlight:gt,delayed:0,processed:jt,oldestSec:0,concurrency:ee.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:ie})}if(ye.length)k.queues=ye;if(Se.length)k.queuesDetail=Se;k.dlqItems=[]}catch{}try{let te=new A(a),{Stacks:ye}=await te.describeStacks({stackName:lr(e,t)}),Se={};for(let ie of ye?.[0]?.Outputs??[])if(ie.OutputKey)Se[ie.OutputKey]=ie.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let ie=`${r.slug}-${t}-db`,xe=[{Name:"DBClusterIdentifier",Value:ie}],[ee,De]=await Promise.all([ca(g,"AWS/RDS","ServerlessDatabaseCapacity",xe,"Average",S,b),ca(g,"AWS/RDS","DatabaseConnections",xe,"Maximum",S,b)]);if(k.aurora={id:ie,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:ee?Number(ee.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(De),status:Se.DbEndpoint?"available":"creating"},y?.rdsProxy)k.proxy={name:`${r.slug}-${t}-proxy`,endpoint:Se.DbProxyEndpoint??"—",pooledConns:Math.round(De),status:"available"}}if(y?.cache?.driver==="elasticache"){let ie=`${r.slug}-${t}-cache`,xe=[{Name:"CacheClusterId",Value:`${ie}-001`}],[ee,De]=await Promise.all([ca(g,"AWS/ElastiCache","CacheHits",xe,"Sum",S,b),ca(g,"AWS/ElastiCache","CacheMisses",xe,"Sum",S,b)]),Je=ee+De>0?Number((ee/(ee+De)*100).toFixed(1)):0;k.redis={id:ie,node:"cache.t4g.micro",engine:"redis",hitRate:Je,status:Se.CacheEndpoint?"available":"creating"}}if(y?.efs){let ie=0;try{if(Se.EfsFileSystemId){let xe=new Pr(a),{FileSystems:ee}=await xe.describeFileSystems({FileSystemId:Se.EfsFileSystemId});ie=Number(((ee?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}k.efs={id:Se.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:ie,status:"available"}}k.assetsInfo=Se.AssetsCdnDomain?{bucket:Se.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:Se.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:k.app.build}:void 0}catch{}if(k.assetsInfo)try{let ye=await new o(a).list({bucket:k.assetsInfo.bucket,maxKeys:1000});k.assetsInfo.files=ye.length,k.assetsInfo.sizeMb=Number((ye.reduce((Se,ie)=>Se+(ie.Size??0),0)/1048576).toFixed(1)),k.assetsRecent=ye.slice(0,8).map((Se)=>({path:`/${Se.Key}`,size:`${Math.max(1,Math.round((Se.Size??0)/1024))} KB`,type:Se.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let te=Array.isArray(y.secrets)?y.secrets.map((ye)=>({key:ye.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:ye})):Object.entries(y.secrets).map(([ye,Se])=>({key:ye,source:String(Se)}));k.secretsList=te.map((ye)=>({...ye,updated:"—"}))}}catch{}try{let te=new o(a),ye=`${r.slug}-${t}-deployments`,Se=await te.getObjectJson(ye,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(Se?.records?.length)k.deploymentsDetail=Se.records.slice(-12).reverse().map((ie)=>({sha:(ie.sha??"").slice(0,7),status:ie.status??"success",when:ie.timestamp??"—",took:ie.took??"—",by:ie.by??"—",version:ie.version??"—",hooks:ie.hooks??[]}))}catch{}k.metricsTotals={invocations:k.metrics.invocations,errors:Math.round(D),errorRatePct:Z,p95Ms:k.metrics.p95Ms,throttles:z.reduce((te,ye)=>te+ye.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:oe},k.metricsPerFn=z.map((te)=>({key:te.key,invocations:te.invocations,errors:te.errors,throttles:te.throttles,avgMs:te.p50,maxMs:te.p99,costUsd:void 0}));try{k.invSpark=await g.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((te)=>te.mode==="http")?.name??""}],StartTime:new Date(b.getTime()-86400000),EndTime:b,Period:3600,Stat:"Sum"})}catch{}try{let te=new $s,ye=b,Se=new Date(Date.UTC(ye.getUTCFullYear(),ye.getUTCMonth(),1)),ie=new Date(Date.UTC(ye.getUTCFullYear(),ye.getUTCMonth()-1,1)),[xe,ee]=await Promise.all([te.getCostByService({start:ks(Se),end:ks(ye),granularity:"MONTHLY"}).catch(()=>[]),te.getCostByService({start:ks(ie),end:ks(Se),granularity:"MONTHLY"}).catch(()=>[])]);if(xe.length){let De=xe.reduce((nt,W)=>nt+W.amount,0),Je=ee.reduce((nt,W)=>nt+W.amount,0),gt=ye.getUTCDate(),jt=new Date(Date.UTC(ye.getUTCFullYear(),ye.getUTCMonth()+1,0)).getUTCDate();k.costSummary={monthToDateUsd:Number(De.toFixed(2)),projectedUsd:Number((De/gt*jt).toFixed(2)),lastMonthUsd:Number(Je.toFixed(2)),dailyAvgUsd:Number((De/gt).toFixed(2))},k.costServices=xe.filter((nt)=>nt.amount>0).sort((nt,W)=>W.amount-nt.amount).slice(0,12).map((nt)=>({name:nt.service,usd:Number(nt.amount.toFixed(2)),note:""})),k.metrics.estCostUsd=Number((De/gt).toFixed(2)),k.metricsTotals.estCostUsd=k.metrics.estCostUsd,k.costTrend=await te.getDailyTotals({start:ks(Se),end:ks(ye)}).catch(()=>[]);let Ze=xe.find((nt)=>/lambda/i.test(nt.service))?.amount??0,wt=(nt)=>nt.invocations*(nt.p50/1000)*(nt.memory/1024),Bt=z.reduce((nt,W)=>nt+wt(W),0)||1;k.costPerFn=z.map((nt)=>({key:nt.key,requests:nt.invocations,gbSec:Math.round(wt(nt)),usd:Number((Ze*(wt(nt)/Bt)).toFixed(2))}))}}catch{}if(y?.firewall)try{let te=await g.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:S,EndTime:b,Period:86400,Statistics:["Sum"]}).catch(()=>[]),ye=await g.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:S,EndTime:b,Period:86400,Statistics:["Sum"]}).catch(()=>[]);k.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(ye.reduce((Se,ie)=>Se+(ie.Sum??0),0)),blocked24h:Math.round(te.reduce((Se,ie)=>Se+(ie.Sum??0),0))};try{let Se=new _g(a),ie=await Se.listWebACLs("REGIONAL"),xe=ie.find((ee)=>ee.Name?.includes(`${r.slug}-${t}`))??ie[0];if(xe?.Name&&xe.Id){k.waf.acl=xe.Name;let ee=await Se.getWebACLRules(xe.Name,xe.Id,"REGIONAL");if(ee.length)k.wafRules=ee.map((De)=>({name:De.Name??"—",detail:`priority ${De.Priority??0}`,action:De.Action??"count",blocked24h:0}))}}catch{}}catch{}let G=[];if(k.aurora)G.push({name:"Aurora Serverless v2",detail:`${k.aurora.id} · ${k.aurora.minAcu}-${k.aurora.maxAcu} ACU`,status:k.aurora.status});if(k.proxy)G.push({name:"RDS Proxy",detail:k.proxy.name,status:k.proxy.status});if(k.redis)G.push({name:`ElastiCache (${k.redis.engine})`,detail:`${k.redis.node} · ${k.redis.hitRate}% hit rate`,status:k.redis.status});if(k.efs)G.push({name:"EFS",detail:`${k.efs.mount} · ${k.efs.sizeMb} MB`,status:k.efs.status});if(G.length)k.dataServices=G;if(r.scheduler!=="off"&&y?.kind==="php")try{let te=await lt(e,t,"schedule:list"),ye=[];for(let Se of(te||"").split(`
181
181
  `)){let ie=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(Se);if(ie&&/[*\d]/.test(ie[1])&&ie[1].trim().split(/\s+/).length===5)ye.push({command:ie[2].trim().replace(/^php artisan /,""),cron:ie[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(ye.length)k.schedulerTasks=ye}catch{}return k.topology=vs(k,{project:e.project.name,environment:t}),k}function Ui(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function cC(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;let t=Date.parse(`${e}T12:00:00.000Z`);return Number.isFinite(t)?new Date(t).toISOString():null}function gg(e,t){if(!e||typeof e!=="object")return[];let r={source:t.name},a=[],g=t.now,f=(y,k,R,D=g)=>{if(k!==null)a.push({name:y,value:k,unit:R,timestamp:D,attributes:r})};f("storage.egress.month",Ui(e.monthBytes),"bytes"),f("storage.egress.today",Ui(e.todayBytes),"bytes"),f("storage.egress.projected_month",Ui(e.projectedMonthBytes),"bytes");let h=Ui(e.budgetBytes);if(h!==null&&h>0){f("storage.egress.budget",h,"bytes");let y=e.budgetUsedPercent,k=typeof y==="number"&&Number.isFinite(y)?y:Ui(e.monthBytes)!==null?Math.round(Ui(e.monthBytes)/h*1000)/10:null;f("storage.egress.budget_used_percent",k,"percent")}let b=t.maxReplayDays??45,S=Array.isArray(e.days)?e.days.slice(-b):[];for(let y of S){let k=cC(String(y?.date??"")),R=Ui(y?.bytes);if(!k||R===null)continue;a.push({name:"storage.egress.day",value:R,unit:"bytes",timestamp:k,attributes:r});let D=Ui(y?.downloads);if(D!==null)a.push({name:"storage.egress.day_downloads",value:D,unit:"count",timestamp:k,attributes:r})}return a}async function pg(e,t=process.env,r=fetch){let a=e.tokenEnv?t[e.tokenEnv]:void 0,g=await r(e.url,{headers:a?{Authorization:`Bearer ${a}`}:{},signal:AbortSignal.timeout(1e4)});if(!g.ok)throw Error(`HTTP ${g.status}`);return await g.json()}async function Za(e,t){let r=[],a=[];if(!Array.isArray(e)||e.length===0)return{metrics:r,errors:a};let g=await Promise.all(e.map(async(f)=>{if(!f?.name||!f?.url)return{endpoint:f,error:"egress endpoint needs both a name and a url"};try{let h=await pg(f,t.env,t.fetchImpl);return{endpoint:f,report:h}}catch(h){return{endpoint:f,error:h instanceof Error?h.message:String(h)}}}));for(let f of g){let h=`egress:${f.endpoint?.name??"unnamed"}`;if("error"in f&&f.error){a.push({source:h,message:f.error});continue}r.push(...gg(f.report,{name:f.endpoint.name,now:t.now}))}return{metrics:r,errors:a}}import{createHash as j_}from"node:crypto";import{existsSync as Si,mkdtempSync as Im,readdirSync as NS,rmSync as Ao,statSync as cw}from"node:fs";import{readFile as ni,writeFile as Eo}from"node:fs/promises";import{tmpdir as vl}from"node:os";import{dirname as B_,extname as Ic,join as xt,normalize as M_,relative as L_,resolve as F_,sep as z_}from"node:path";import{fileURLToPath as U_}from"node:url";import{isIP as Bv}from"node:net";var vt=(e)=>e==null?void 0:String(e),Fd=(e)=>Number(e)===1,qi=(e,t)=>{try{return JSON.parse(String(e))}catch{return t}};function Mv(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),name:String(e.name),provider:String(e.provider),endpoint:vt(e.endpoint),endpointPolicy:String(e.endpoint_policy),bucket:vt(e.bucket),prefix:String(e.prefix),region:vt(e.region),forcePathStyle:Fd(e.force_path_style),credentialRef:vt(e.credential_ref),encryption:String(e.encryption),encryptionKeyRef:vt(e.encryption_key_ref),immutability:qi(e.immutability,{}),status:String(e.status),lastTestedAt:vt(e.last_tested_at),lastSuccessAt:vt(e.last_success_at),lastFailureAt:vt(e.last_failure_at),lastError:vt(e.last_error),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function xg(e){return{id:String(e.id),organizationId:String(e.organization_id),projectId:String(e.project_id),environmentId:vt(e.environment_id),resourceId:vt(e.resource_id),dataServiceId:vt(e.data_service_id),destinationId:String(e.destination_id),name:String(e.name),resourceKind:String(e.resource_kind),schedule:String(e.schedule),timezone:String(e.timezone),retention:qi(e.retention,{}),compression:String(e.compression),encryption:String(e.encryption),includePatterns:qi(e.include_patterns,[]),excludePatterns:qi(e.exclude_patterns,[]),expectedRpoMinutes:Number(e.expected_rpo_minutes),expectedRtoMinutes:Number(e.expected_rto_minutes),healthCheckId:vt(e.health_check_id),enabled:Fd(e.enabled),nextRunAt:vt(e.next_run_at),lastRunAt:vt(e.last_run_at),version:Number(e.version),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Dg(e){return{id:String(e.id),projectId:String(e.project_id),policyId:vt(e.policy_id),destinationId:String(e.destination_id),resourceId:vt(e.resource_id),dataServiceId:vt(e.data_service_id),backupJobId:vt(e.backup_job_id),kind:String(e.kind),pointInTime:String(e.point_in_time),uri:String(e.uri),sizeBytes:Number(e.size_bytes),checksum:String(e.checksum),manifest:qi(e.manifest,{}),toolVersion:vt(e.tool_version),engineVersion:vt(e.engine_version),expiresAt:vt(e.expires_at),lockedUntil:vt(e.locked_until),held:Fd(e.held),pinned:Fd(e.pinned),status:String(e.status),verificationState:String(e.verification_state),verifiedAt:vt(e.verified_at),durationMs:e.duration_ms==null?void 0:Number(e.duration_ms),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Og(e){return{id:String(e.id),projectId:String(e.project_id),policyId:vt(e.policy_id),recoveryPointId:vt(e.recovery_point_id),operationId:vt(e.operation_id),kind:String(e.kind),status:String(e.status),idempotencyKey:String(e.idempotency_key),target:qi(e.target,{}),restoreMode:vt(e.restore_mode),cancellability:String(e.cancellability),safetyBackupId:vt(e.safety_backup_id),healthResult:e.health_result?qi(e.health_result,{}):void 0,progress:qi(e.progress,{}),error:vt(e.error),startedAt:vt(e.started_at),finishedAt:vt(e.finished_at),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function dC(e){let t=e.toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;if(Bv(t)===6)return t==="::1"||t.startsWith("fe80:");if(Bv(t)!==4)return!1;let[r,a]=t.split(".").map(Number);return r===10||r===127||r===0||r===169&&a===254||r===172&&a>=16&&a<=31||r===192&&a===168}function vh(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup destination names must be 2-63 lowercase letters, numbers, or dashes.");if(e.provider!=="aws_backup"&&!e.bucket)throw Error("S3 backup destinations require a bucket.");if(e.provider==="s3_compatible"&&!e.endpoint)throw Error("S3-compatible destinations require an explicit endpoint.");if(e.provider==="s3_compatible"&&!e.credentialRef)throw Error("S3-compatible destinations require a credential reference.");if(e.encryption!=="provider"&&!e.encryptionKeyRef)throw Error("Client-side encryption requires an encryption key reference.");if(e.endpoint){let t=new URL(e.endpoint);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw Error("Backup endpoints must be origin-only HTTPS URLs without credentials, paths, queries, or fragments.");if(dC(t.hostname)&&e.endpointPolicy!=="allow_private")throw Error("Private backup endpoints require endpointPolicy allow_private.")}}class ec{controlPlane;now;constructor(e,t=()=>new Date){this.controlPlane=e;this.now=t}createDestination(e){vh(e);let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_destinations (id,organization_id,project_id,name,provider,endpoint,endpoint_policy,bucket,prefix,region,force_path_style,credential_ref,encryption,encryption_key_ref,immutability,status,last_tested_at,last_success_at,last_failure_at,last_error,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.organizationId,e.projectId,e.name,e.provider,e.endpoint??null,e.endpointPolicy,e.bucket??null,e.prefix,e.region??null,e.forcePathStyle?1:0,e.credentialRef??null,e.encryption,e.encryptionKeyRef??null,JSON.stringify(e.immutability),e.status,e.lastTestedAt??null,e.lastSuccessAt??null,e.lastFailureAt??null,e.lastError??null,1,r,r]),this.getDestination(t)}getDestination(e){let t=this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE id=?").get(e);return t?Mv(t):void 0}listDestinations(e){return this.controlPlane.database.query("SELECT * FROM backup_destinations WHERE project_id=? ORDER BY name").all(e).map(Mv)}recordDestinationTest(e,t){let r=this.now().toISOString();return this.controlPlane.database.run("UPDATE backup_destinations SET status=?,last_tested_at=?,last_success_at=CASE WHEN ? THEN ? ELSE last_success_at END,last_failure_at=CASE WHEN ? THEN last_failure_at ELSE ? END,last_error=?,version=version+1,updated_at=? WHERE id=?",[t.ok?"healthy":"failing",r,t.ok?1:0,r,t.ok?1:0,r,t.ok?null:String(t.error??"Destination test failed.").slice(0,1000),r,e]),this.getDestination(e)}createPolicy(e){if(!/^[a-z0-9][a-z0-9-]{1,62}$/.test(e.name))throw Error("Backup policy names must be lowercase slugs.");if(!e.resourceId&&!e.dataServiceId&&!["control_plane","infrastructure"].includes(e.resourceKind))throw Error("A backup policy requires a resource or data service target.");let t=this.getDestination(e.destinationId);if(!t||t.projectId!==e.projectId)throw Error("Backup destination was not found.");if(e.resourceKind==="control_plane"&&t.encryption==="provider")throw Error("Control-plane backups require client-side destination encryption.");if(["logical_database","volume","files","control_plane"].includes(e.resourceKind)&&t.provider==="aws_backup")throw Error(`${e.resourceKind} backups require an object-storage destination.`);if(e.resourceKind==="infrastructure"&&t.provider!=="aws_backup")throw Error("Infrastructure backups require an AWS Backup destination.");let r=dt(e.schedule),a=Ft(r.normalized,e.timezone,this.now(),1)[0],g=crypto.randomUUID(),f=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_policies (id,organization_id,project_id,environment_id,resource_id,data_service_id,destination_id,name,resource_kind,schedule,timezone,retention,compression,encryption,include_patterns,exclude_patterns,expected_rpo_minutes,expected_rto_minutes,health_check_id,enabled,next_run_at,last_run_at,version,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[g,e.organizationId,e.projectId,e.environmentId??null,e.resourceId??null,e.dataServiceId??null,e.destinationId,e.name,e.resourceKind,r.normalized,e.timezone,JSON.stringify(e.retention),e.compression,e.encryption,JSON.stringify(e.includePatterns),JSON.stringify(e.excludePatterns),e.expectedRpoMinutes,e.expectedRtoMinutes,e.healthCheckId??null,e.enabled?1:0,a,e.lastRunAt??null,1,f,f]),this.getPolicy(g)}getPolicy(e){let t=this.controlPlane.database.query("SELECT * FROM backup_policies WHERE id=?").get(e);return t?xg(t):void 0}listPolicies(e,t){return this.controlPlane.database.query(`SELECT * FROM backup_policies WHERE project_id=?${t?" AND environment_id=?":""} ORDER BY name`).all(e,...t?[t]:[]).map(xg)}duePolicies(e=this.now()){return this.controlPlane.database.query("SELECT * FROM backup_policies WHERE enabled=1 AND next_run_at<=? ORDER BY next_run_at,id").all(e.toISOString()).map(xg)}advancePolicy(e,t){let r=this.getPolicy(e);if(!r)throw Error("Backup policy was not found.");let a=Ft(r.schedule,r.timezone,new Date(t),1)[0];return this.controlPlane.database.run("UPDATE backup_policies SET last_run_at=?,next_run_at=?,version=version+1,updated_at=? WHERE id=?",[t,a,this.now().toISOString(),e]),this.getPolicy(e)}createJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE idempotency_key=?").get(e.idempotencyKey);if(t)return Og(t);let r=crypto.randomUUID(),a=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO backup_jobs (id,project_id,policy_id,recovery_point_id,operation_id,kind,status,idempotency_key,target,restore_mode,cancellability,safety_backup_id,health_result,progress,error,started_at,finished_at,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[r,e.projectId,e.policyId??null,e.recoveryPointId??null,e.operationId??null,e.kind,e.status,e.idempotencyKey,JSON.stringify(e.target),e.restoreMode??null,e.cancellability,e.safetyBackupId??null,e.healthResult?JSON.stringify(e.healthResult):null,JSON.stringify(e.progress),e.error??null,e.startedAt??null,e.finishedAt??null,a,a]),this.getJob(r)}getJob(e){let t=this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE id=?").get(e);return t?Og(t):void 0}listJobs(e){return this.controlPlane.database.query("SELECT * FROM backup_jobs WHERE project_id=? ORDER BY created_at DESC").all(e).map(Og)}updateJob(e,t){let r=this.getJob(e);if(!r)throw Error("Backup job was not found.");let a={...r,...t};return this.controlPlane.database.run("UPDATE backup_jobs SET status=?,operation_id=?,recovery_point_id=?,progress=?,health_result=?,error=?,started_at=?,finished_at=?,safety_backup_id=?,updated_at=? WHERE id=?",[a.status,a.operationId??null,a.recoveryPointId??null,JSON.stringify(a.progress),a.healthResult?JSON.stringify(a.healthResult):null,a.error??null,a.startedAt??null,a.finishedAt??null,a.safetyBackupId??null,this.now().toISOString(),e]),this.getJob(e)}createRecoveryPoint(e){if(!/^sha256:[a-f0-9]{64}$/i.test(e.checksum))throw Error("Recovery points require a SHA-256 checksum.");if(typeof e.uri!=="string"||!["s3:","aws-backup:","file:"].some((a)=>e.uri.startsWith(a)))throw Error("Recovery point URI uses an unsupported destination scheme.");let t=crypto.randomUUID(),r=this.now().toISOString();return this.controlPlane.database.run("INSERT INTO recovery_points (id,project_id,policy_id,destination_id,resource_id,data_service_id,backup_job_id,kind,point_in_time,uri,size_bytes,checksum,manifest,tool_version,engine_version,expires_at,locked_until,held,pinned,status,verification_state,verified_at,duration_ms,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[t,e.projectId,e.policyId??null,e.destinationId,e.resourceId??null,e.dataServiceId??null,e.backupJobId??null,e.kind,e.pointInTime,e.uri,e.sizeBytes,e.checksum,JSON.stringify(e.manifest),e.toolVersion??null,e.engineVersion??null,e.expiresAt??null,e.lockedUntil??null,e.held?1:0,e.pinned?1:0,e.status,e.verificationState,e.verifiedAt??null,e.durationMs??null,r,r]),this.getRecoveryPoint(t)}getRecoveryPoint(e){let t=this.controlPlane.database.query("SELECT * FROM recovery_points WHERE id=?").get(e);return t?Dg(t):void 0}listRecoveryPoints(e,t){return this.controlPlane.database.query(`SELECT * FROM recovery_points WHERE project_id=?${t?" AND policy_id=?":""} ORDER BY point_in_time DESC`).all(e,...t?[t]:[]).map(Dg)}updateRecoveryPoint(e,t){let r=this.getRecoveryPoint(e);if(!r)throw Error("Recovery point was not found.");let a={...r,...t};return this.controlPlane.database.run("UPDATE recovery_points SET status=?,verification_state=?,verified_at=?,held=?,pinned=?,manifest=?,duration_ms=?,updated_at=? WHERE id=?",[a.status,a.verificationState,a.verifiedAt??null,a.held?1:0,a.pinned?1:0,JSON.stringify(a.manifest),a.durationMs??null,this.now().toISOString(),e]),this.getRecoveryPoint(e)}retentionCandidates(e=this.now()){let t=this.controlPlane.database.query(`SELECT rp.* FROM recovery_points rp
182
182
  WHERE rp.status='available' AND rp.held=0 AND rp.pinned=0
@@ -1,4 +1,4 @@
1
- import{Wo,mn,Ql,hn,ta,ra}from"./chunk-5rds38z9.js";import{He}from"./chunk-fdf181e6.js";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function b(t,e){return`${r[e]}${t}${r.reset}`}function Mn(t){console.log(`${r.green}✓${r.reset} ${t}`)}function bg(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Bs(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function L(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function P(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function xs(t){console.log(`
1
+ import{Wo,mn,Ql,hn,ta,ra}from"./chunk-q61qcpp4.js";import{He}from"./chunk-fdf181e6.js";var r={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};function b(t,e){return`${r[e]}${t}${r.reset}`}function Mn(t){console.log(`${r.green}✓${r.reset} ${t}`)}function bg(t){console.error(`${r.red}✗${r.reset} ${t}`)}function Bs(t){console.warn(`${r.yellow}⚠${r.reset} ${t}`)}function L(t){console.log(`${r.blue}ℹ${r.reset} ${t}`)}function P(t){console.log(`${r.cyan}→${r.reset} ${t}`)}function xs(t){console.log(`
2
2
  ${r.bright}${r.cyan}${t}${r.reset}
3
3
  `)}var F=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI);function Cg(t,e="cyan"){let n=t.split(`
4
4
  `),i=Math.max(...n.map((l)=>l.length)),a="─".repeat(i+2);console.log(b(`┌${a}┐`,e)),n.forEach((l)=>{console.log(b(`│ ${l.padEnd(i)} │`,e))}),console.log(b(`└${a}┘`,e))}import{execFileSync as k}from"node:child_process";import{mkdirSync as I,mkdtempSync as M,rmSync as U,writeFileSync as d}from"node:fs";import{tmpdir as O}from"node:os";import{dirname as j,join as s}from"node:path";function C(t,e){for(let n of e){let i=s(t,n.name);I(j(i),{recursive:!0}),d(i,n.data,n.mode?{mode:n.mode}:void 0)}}async function Ac(t){let{app:e,projectRoot:n,region:i,repository:a}=t,l=e.architecture??"x86_64",A=l==="arm64"?"linux/arm64":"linux/amd64",R=e.kind==="php",c=t.onStep??(()=>{}),p=M(s(O(),"tscloud-img-"));try{let f=s(p,"app");I(f,{recursive:!0});let y,w;if(R){ta({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c}),c("staging application tree");let o=ra(n);C(f,o),C(s(p,"runtime"),hn().map((g)=>({name:g.path,data:g.contents,mode:g.mode})));let B=e.handlers?.http??"public/index.php";y={http:B,queue:e.handlers?.queue??B,cli:e.handlers?.cli??B},w=Wo(o.map((g)=>`${g.name}:${g.data.length}`).join("|"))}else{c("bundling application");let o=await mn({projectRoot:n,app:e,skipBuild:t.skipBuild,onStep:c});d(s(f,"index.mjs"),o.bundle),y=o.handlers,w=o.sha256}let S=w.slice(0,16);d(s(p,"Dockerfile"),Ql({kind:e.kind??"node",phpVersion:e.phpVersion,architecture:l}));let v=new He(i),u;try{u=(await v.describeRepositories({repositoryNames:[a]})).repositories?.[0]?.repositoryUri??""}catch{u=""}if(!u)c(`creating ECR repository ${a}`),u=(await v.createRepository({repositoryName:a,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!u)throw Error(`could not resolve ECR repository URI for ${a}`);let m=`${u}:${S}`;c("docker build"),k("docker",["build","--platform",A,"--provenance=false","--sbom=false","-t",m,p],{stdio:"inherit"}),c("ecr auth + push");let h=(await v.getAuthorizationToken()).authorizationData?.[0];if(!h?.authorizationToken||!h.proxyEndpoint)throw Error("failed to get an ECR authorization token");let E=h.proxyEndpoint.replace(/^https?:\/\//,""),x=s(p,".docker");return I(x,{recursive:!0}),d(s(x,"config.json"),JSON.stringify({auths:{[E]:{auth:h.authorizationToken}}})),k("docker",["push",m],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:x}}),L(`Image: ${m}`),{imageUri:m,tag:S,handlers:y}}finally{U(p,{recursive:!0,force:!0})}}