@stacksjs/ts-cloud 0.12.13 → 0.12.15

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 (130) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/chunk-4w80w3sm.js +1 -0
  3. package/dist/bin/{chunk-wvhqjr80.js → chunk-5tsxt28g.js} +2 -2
  4. package/dist/bin/{chunk-7h6h8yxm.js → chunk-77qpn2m8.js} +3 -3
  5. package/dist/bin/{chunk-13dhcjjb.js → chunk-7xvm2ygt.js} +2 -2
  6. package/dist/bin/{chunk-6xw0r4gn.js → chunk-8tbj9h2a.js} +35 -35
  7. package/dist/bin/chunk-971tfc6m.js +1 -0
  8. package/dist/bin/{chunk-6zk2n3wk.js → chunk-9e22a51n.js} +42 -42
  9. package/dist/bin/{chunk-z2ez8wn9.js → chunk-9k60q9qz.js} +3 -3
  10. package/dist/bin/{chunk-5gehfky4.js → chunk-a929za72.js} +2 -2
  11. package/dist/bin/{chunk-w7k5rvmw.js → chunk-dpw8x3sr.js} +1 -1
  12. package/dist/bin/{chunk-84tvv3x1.js → chunk-ejqhbj1h.js} +1 -1
  13. package/dist/bin/{chunk-gj5jkhfr.js → chunk-gd4w6bht.js} +3 -3
  14. package/dist/bin/chunk-h785hw6a.js +1 -0
  15. package/dist/bin/chunk-jyggrdh2.js +1 -0
  16. package/dist/bin/{chunk-1fj5gk6r.js → chunk-kc2e193t.js} +59 -59
  17. package/dist/bin/{chunk-bnv8yd9w.js → chunk-n7eq4t9a.js} +3 -3
  18. package/dist/bin/{chunk-d5qhwtkg.js → chunk-n8cwx54p.js} +5 -5
  19. package/dist/bin/{chunk-d7r6mhyv.js → chunk-ng0949x3.js} +2 -2
  20. package/dist/bin/{chunk-p9hd27k4.js → chunk-pcyywgx7.js} +1 -1
  21. package/dist/bin/{chunk-55kmbzr5.js → chunk-pt2bz3kr.js} +1 -1
  22. package/dist/bin/{chunk-96xtj5j6.js → chunk-q524s7cx.js} +1 -1
  23. package/dist/bin/{chunk-dh2qmxw9.js → chunk-q9gpw6wv.js} +1 -1
  24. package/dist/bin/{chunk-x5x9dzk7.js → chunk-r1vtnn8w.js} +2 -2
  25. package/dist/bin/{chunk-jh1593zx.js → chunk-r1w08y38.js} +1 -1
  26. package/dist/bin/{chunk-nnkhrm4n.js → chunk-raj6j2j5.js} +2 -2
  27. package/dist/bin/{chunk-2hpnd4g4.js → chunk-s1j941z1.js} +1 -1
  28. package/dist/bin/{chunk-ymbwekjm.js → chunk-sdwr2tnp.js} +1 -1
  29. package/dist/bin/{chunk-9jfjzycs.js → chunk-swete552.js} +10 -10
  30. package/dist/bin/{chunk-yn34zgr2.js → chunk-v78r5tx0.js} +1 -1
  31. package/dist/bin/chunk-v7f4c62s.js +1 -0
  32. package/dist/bin/{chunk-jcyrm5q0.js → chunk-vesvsvdy.js} +1 -1
  33. package/dist/bin/{chunk-yt8rgkqt.js → chunk-w5hzt11d.js} +2 -2
  34. package/dist/bin/{chunk-12e9v1dw.js → chunk-x42gb7pq.js} +1 -1
  35. package/dist/bin/{chunk-0vsxpmfj.js → chunk-yx1qgp1q.js} +2 -2
  36. package/dist/bin/{chunk-xgepx8yx.js → chunk-zzsdhhmb.js} +1 -1
  37. package/dist/bin/cli.js +152 -152
  38. package/dist/bin/dashboard-server.js +1 -1
  39. package/dist/{chunk-7ww65b66.js → chunk-2knc1zyy.js} +100 -100
  40. package/dist/{chunk-tnjae324.js → chunk-678rwkz8.js} +75 -75
  41. package/dist/{chunk-emg3shmb.js → chunk-6t9tjvpy.js} +2 -2
  42. package/dist/{chunk-g8fpsdyq.js → chunk-6znnde1s.js} +4 -4
  43. package/dist/{chunk-edqhhcg9.js → chunk-83p688yv.js} +3 -3
  44. package/dist/{chunk-zmyv76f0.js → chunk-88nxsyry.js} +6 -6
  45. package/dist/{chunk-sct6mdgc.js → chunk-a6k322xc.js} +25 -25
  46. package/dist/chunk-atny1wp9.js +1 -0
  47. package/dist/{chunk-thpce63q.js → chunk-cy6qh4ea.js} +2 -2
  48. package/dist/{chunk-wpqj98h8.js → chunk-g9mnmddy.js} +2 -2
  49. package/dist/{chunk-9c29rnk3.js → chunk-gd9g0v9w.js} +8 -8
  50. package/dist/chunk-hn2v0b0d.js +1 -0
  51. package/dist/{chunk-e0919h5g.js → chunk-hnkw6pde.js} +2 -2
  52. package/dist/{chunk-1kp3y2s7.js → chunk-hw3p6pth.js} +1 -1
  53. package/dist/{chunk-1n3ckctd.js → chunk-jvqcw0b4.js} +48 -48
  54. package/dist/{chunk-13d54txj.js → chunk-qzwack6w.js} +2 -2
  55. package/dist/{chunk-e7ds04wb.js → chunk-rbem58rx.js} +1 -1
  56. package/dist/chunk-v46b25w9.js +1 -0
  57. package/dist/{chunk-3qp10j0j.js → chunk-w495x89g.js} +3 -3
  58. package/dist/{chunk-ej4sm2tw.js → chunk-x07tpsv0.js} +5 -5
  59. package/dist/{chunk-3kapcdpn.js → chunk-yq3pdbz7.js} +1 -1
  60. package/dist/deploy/index.js +1 -1
  61. package/dist/dns/index.js +1 -1
  62. package/dist/drivers/index.js +1 -1
  63. package/dist/index.d.ts +1 -1
  64. package/dist/index.js +47 -47
  65. package/dist/operations/index.js +1 -1
  66. package/dist/protection/index.js +1 -1
  67. package/dist/spend/index.js +1 -1
  68. package/dist/ui/404.html +1 -1
  69. package/dist/ui/accept-invitation.html +1 -1
  70. package/dist/ui/access-denied.html +1 -1
  71. package/dist/ui/account/automation.html +6 -6
  72. package/dist/ui/account/security.html +2 -2
  73. package/dist/ui/applications/compose.html +6 -6
  74. package/dist/ui/applications/new.html +2 -2
  75. package/dist/ui/data/backups.html +6 -6
  76. package/dist/ui/data/services.html +5 -5
  77. package/dist/ui/data/volumes.html +6 -6
  78. package/dist/ui/index.html +6 -6
  79. package/dist/ui/infrastructure/topology.html +6 -6
  80. package/dist/ui/integrations.html +1 -1
  81. package/dist/ui/operations/alerts.html +6 -6
  82. package/dist/ui/operations/configuration.html +6 -6
  83. package/dist/ui/operations/jobs.html +6 -6
  84. package/dist/ui/operations/maintenance.html +5 -5
  85. package/dist/ui/operations/observability.html +5 -5
  86. package/dist/ui/operations/previews.html +6 -6
  87. package/dist/ui/operations/queue.html +6 -6
  88. package/dist/ui/operations/regions.html +5 -5
  89. package/dist/ui/operations/releases.html +6 -6
  90. package/dist/ui/operations/spend.html +6 -6
  91. package/dist/ui/operations/workloads.html +6 -6
  92. package/dist/ui/security.html +1 -1
  93. package/dist/ui/server/actions.html +5 -5
  94. package/dist/ui/server/activity.html +2 -2
  95. package/dist/ui/server/capacity.html +5 -5
  96. package/dist/ui/server/database.html +6 -6
  97. package/dist/ui/server/deployments.html +6 -6
  98. package/dist/ui/server/diagnostics.html +2 -2
  99. package/dist/ui/server/firewall.html +6 -6
  100. package/dist/ui/server/fleet.html +6 -6
  101. package/dist/ui/server/logs.html +5 -5
  102. package/dist/ui/server/metrics.html +6 -6
  103. package/dist/ui/server/security.html +1 -1
  104. package/dist/ui/server/services.html +1 -1
  105. package/dist/ui/server/sites.html +6 -6
  106. package/dist/ui/server/ssh-keys.html +6 -6
  107. package/dist/ui/server/team.html +6 -6
  108. package/dist/ui/server/terminal.html +2 -2
  109. package/dist/ui/serverless/alarms.html +6 -6
  110. package/dist/ui/serverless/assets.html +2 -2
  111. package/dist/ui/serverless/cost.html +2 -2
  112. package/dist/ui/serverless/data.html +5 -5
  113. package/dist/ui/serverless/deployments.html +1 -1
  114. package/dist/ui/serverless/firewall.html +2 -2
  115. package/dist/ui/serverless/functions.html +5 -5
  116. package/dist/ui/serverless/logs.html +6 -6
  117. package/dist/ui/serverless/metrics.html +2 -2
  118. package/dist/ui/serverless/queues.html +6 -6
  119. package/dist/ui/serverless/secrets.html +6 -6
  120. package/dist/ui/serverless/traces.html +6 -6
  121. package/dist/ui/serverless.html +5 -5
  122. package/package.json +3 -3
  123. package/dist/bin/chunk-de88yqwy.js +0 -1
  124. package/dist/bin/chunk-p36ns96s.js +0 -1
  125. package/dist/bin/chunk-qz3za76g.js +0 -1
  126. package/dist/bin/chunk-rxwecjgc.js +0 -1
  127. package/dist/bin/chunk-xaafj6kf.js +0 -1
  128. package/dist/chunk-7by4rm7y.js +0 -1
  129. package/dist/chunk-n688m5fp.js +0 -1
  130. package/dist/chunk-wrnhbb13.js +0 -1
@@ -1,6 +1,6 @@
1
- import{Ke,A,Ft,Cr,hi}from"./chunk-6xw0r4gn.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
- `)}var Jl="dashboard";function La(){return Ke("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function Xl(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=La(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
1
+ import{Je,A,Ft,Cr,hi}from"./chunk-8tbj9h2a.js";import{execSync as D}from"node:child_process";import{randomBytes as R}from"node:crypto";import{chmodSync as j,copyFileSync as x,existsSync as u,mkdirSync as w,readFileSync as U,statSync as N,writeFileSync as m}from"node:fs";import{tmpdir as E}from"node:os";import{basename as P,dirname as v,isAbsolute as O,join as a,resolve as B}from"node:path";import{fileURLToPath as C}from"node:url";function h(e){if(!e||typeof e!=="object")return e;return Object.fromEntries(Object.keys(e).map((r)=>[r,""]))}function M(e){let r=JSON.parse(JSON.stringify(e??{}));if(r.hetzner)delete r.hetzner.apiToken;delete r.aws,delete r.stateDir;for(let t of Object.values(r.sites??{})){if(t?.env)t.env=h(t.env);if(t?.environment)t.environment=h(t.environment)}for(let t of Object.values(r.environments??{}))if(t?.variables)t.variables=h(t.variables);for(let t of Object.values(r.infrastructure?.databases??{}))if(t?.password)t.password="";if(r.infrastructure?.appDatabase?.password)r.infrastructure.appDatabase.password="";if(r.infrastructure?.compute?.database?.password)r.infrastructure.compute.database.password="";if(r.infrastructure?.compute?.managedServices?.vitess?.password)r.infrastructure.compute.managedServices.vitess.password="";return r}function y(e){let r=M(e);return["// Generated by ts-cloud for the management dashboard — do not edit.","//","// This is the project's resolved cloud config, inlined so it needs no","// imports on the box. Credentials are deliberately absent.",`export default ${JSON.stringify(r,null,2)}`,""].join(`
2
+ `)}var Jl="dashboard";function La(){return Je("dashboard-credentials.json")}function F(){return R(24).toString("base64url")}function Xl(e,r,t){let s=process.env.TS_CLOUD_UI_PASSWORD?.trim();if(s)return{password:s,source:"env"};if(b(process.env.TS_CLOUD_UI_PUBLIC))return{password:void 0,source:"public"};let n=La(),i=A(e,"dashboard-credentials.json");try{if(u(i)){let o=JSON.parse(U(i,"utf8"));if(o?.password)return{password:o.password,source:"generated"}}}catch{}let d=F();try{w(v(i),{recursive:!0}),m(i,`${JSON.stringify({username:r,password:d,generatedAt:new Date().toISOString()},null,2)}
3
3
  `),j(i,384),t.info(`Management dashboard: generated a password for '${r}' and saved it to ${n} (read it there — it is not printed). Set TS_CLOUD_UI_PASSWORD to pin your own, or TS_CLOUD_UI_PUBLIC=1 to serve without auth.`)}catch(o){t.warn(`Management dashboard: could not persist the generated password (${o?.message??o}). Using it for this deploy only — pass: ${d}
4
- This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var I={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return Ke("dashboard-release")}function L(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||L()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=A(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=L(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
4
+ This password is now in your deploy log. Set TS_CLOUD_UI_PASSWORD to a value of your own and redeploy once ${n} is writable.`)}return{password:d,source:"generated"}}var I={info:()=>{},warn:()=>{}};function b(e){return e!=null&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function J(){return Je("dashboard-release")}function L(){let e=v(C(import.meta.url));for(let r of[a(e,"..","..","package.json"),a(e,"..","package.json")])try{let t=JSON.parse(U(r,"utf8"));if(t.name==="@stacksjs/ts-cloud"&&t.version)return`^${t.version}`}catch{}return"latest"}function z(){return process.env.TS_CLOUD_UI_VERSION?.trim()||L()}function V(e,r,t){if(!e?.project?.slug)return t.warn("Management dashboard: the cloud config has no project slug — skipping the live dashboard."),null;let s=A(r,"dashboard-release");try{w(s,{recursive:!0}),m(a(s,"cloud.config.ts"),y(e));let n=z();if(n.startsWith("file:")){let d=n.slice(5),o=O(d)?d:B(r,d);if(!u(o)||!N(o).isFile())n=L(),t.warn(`Management dashboard: TS_CLOUD_UI_VERSION points to a missing package file (${o}); using the deploying ts-cloud version ${n} instead.`);else{let c=P(o),l=a(s,c);if(o!==l)x(o,l);n=`file:./${c}`}}let i={name:"ts-cloud-dashboard",private:!0,type:"module",dependencies:{"@stacksjs/ts-cloud":n}};return m(a(s,"package.json"),`${JSON.stringify(i,null,2)}
5
5
  `),J()}catch(n){return t.warn(`Management dashboard: could not stage the live release (${n?.message??n}) — skipping.`),null}}function no(e){if(u(a(e,"packages","ui","pages"))||u(a(e,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let r=v(C(import.meta.url)),t=[a(r,"ui"),a(r,"..","ui"),a(r,"..","..","ui"),a(r,"..","dist","ui")];for(let s of t)if(u(a(s,"index.html"))||u(a(s,"serverless.html")))return{uiRoot:s,build:!1};return null}function io(e,r={}){let t=r.logger??I,s=r.cwd??process.cwd();if(b(process.env.TS_CLOUD_UI_DISABLE))return t.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),e;if(e.cloud?.attachTo)return t.info(`Management dashboard: ${e.project.slug} is attached to ${e.cloud.attachTo}; the server owner's dashboard monitors every attached project.`),e;if(Ft(e))return e;let n=e.environments&&Object.keys(e.environments)[0],i=process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,d=Number(process.env.TS_CLOUD_UI_PORT)||void 0,o={...e.sites??{}};if(!b(process.env.TS_CLOUD_UI_STATIC)){let g=V(e,s,t);if(!g)return e;let p=hi(e,n??"production",{uiRoot:g,build:!1,domain:i,port:d,live:!0});if(p.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;for(let{name:k,site:_}of p)o[k]=_,t.info(`Management dashboard → https://${_.domain} (sign in with your ts-cloud account; the first deploy prints an admin password once)`);return e.sites=o,e}let c=no(s);if(!c)return t.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),e;let l=process.env.TS_CLOUD_UI_USERNAME?.trim()||"admin",f=Xl(s,l,t),S=hi(e,n??"production",{uiRoot:c.uiRoot,build:c.build,domain:i,username:l,password:f.password,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:!1,port:d});if(S.length===0)return t.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),e;let T=f.source==="public"?"NO AUTH — TS_CLOUD_UI_PUBLIC is set (dashboard is publicly reachable)":f.source==="env"?"htpasswd-protected (TS_CLOUD_UI_PASSWORD)":`htpasswd-protected (auto-generated — see ${La()})`;t.warn("Management dashboard: static mode — one shared password, and no per-site collaborators. Unset TS_CLOUD_UI_STATIC for the live dashboard.");for(let{name:g,site:p}of S)o[g]=p,t.info(`Management dashboard → https://${p.domain} (${T})`);return e.sites=o,e}function oo(e){return Object.keys(e.sites??{}).filter(Cr)}function ms(e,r){if(!e?.root)return null;let t=r.cwd??process.cwd(),s=r.logger??I;try{if(typeof e.build==="string"&&e.build.trim())s.info(`Management dashboard: building UI (${e.build})`),D(e.build,{cwd:t,stdio:"inherit"});let n=O(e.root)?e.root:a(t,e.root);if(!u(n))return s.warn(`Management dashboard: build output not found at ${n} — skipping dashboard artifact.`),null;let i=a(E(),`${r.slug}-${r.siteName??Jl}-${r.sha}.tar.gz`);return D(`tar czf "${i}" -C "${n}" .`,{stdio:"inherit"}),i}catch(n){return s.warn(`Management dashboard: failed to build artifact — ${n?.message??n}. Skipping dashboard deploy.`),null}}
6
6
  export{Jl,La,Xl,no,io,oo,ms};
@@ -1,9 +1,9 @@
1
- import{V,wr}from"./chunk-6xw0r4gn.js";function W(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ni(e){return e.type!=null&&_e.has(e.type)}function gs(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return gs(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ni(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ni(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function so(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function fs(e,t={}){let r=[],n=[],i=e.sites||{},s=so(e),c=wr(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function hs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Ma(e){return P(e)==="bucket"}function Ua(e,t){if(V(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function gr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function ft(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ge(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function ao(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",F="mail",G=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
1
+ import{V,wr}from"./chunk-8tbj9h2a.js";function W(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function ni(e){return e.type!=null&&_e.has(e.type)}function gs(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return gs(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(ni(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(ni(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function so(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function fs(e,t={}){let r=[],n=[],i=e.sites||{},s=so(e),c=wr(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function hs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Ma(e){return P(e)==="bucket"}function Ua(e,t){if(V(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function gr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function ft(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ke(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function ao(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",F="mail",G=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
2
2
  `)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
3
3
  `)}function he(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${G}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${G}/mail serve --config ${S}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${S}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
- `)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${G}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ge(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(te(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Te(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${F}`,`systemctl restart ${F}`,...ye(e)]}var g=`${M}/pantry/.bin`,X=15306,K=15991,w=15999,ne=16101,B=2379,v="/var/lib/vitess",z=100;function ii(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
4
+ `)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${G}/mail user:local ${r} || true`;return e.accounts.flatMap((r)=>[t(`create ${h(r.address)} ${h(r.password)} ${h(r.address)}`),t(`change-password ${h(r.address)} ${h(r.password)}`)])}function re(e){if(!e.enabled)return[];return[...Ke(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(te(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Te(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${F}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${F}`,`systemctl restart ${F}`,...ye(e)]}var g=`${M}/pantry/.bin`,X=15306,K=15991,w=15999,ne=16101,B=2379,v="/var/lib/vitess",z=100;function ii(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
5
5
  `)}function A(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${_}`,`Group=${_}`,`Environment="PATH=${be}"`,`Environment="VTDATAROOT=${v}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
6
- `)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??X,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${w}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function co(e){if(!ii(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ge(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function oi(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function fr(e,t="psql"){let r=e?.port??5432;if(oi(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function lo(e={},t={}){let r=Ne(e),n=co(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ge(r.packages),...ao(r.services),...n,...i]}function ht(e,t={}){if(!e?.name)return[];if(!oi(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],H=[];for(let q of k)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},I=e.users||[],me=e.port??5432;return[ft(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${fr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[ft(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${fr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Ba(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Gr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
6
+ `)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??X,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${w}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function co(e){if(!ii(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ke(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function oi(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function fr(e,t="psql"){let r=e?.port??5432;if(oi(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function lo(e={},t={}){let r=Ne(e),n=co(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ke(r.packages),...ao(r.services),...n,...i]}function ht(e,t={}){if(!e?.name)return[];if(!oi(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],H=[];for(let q of k)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},I=e.users||[],me=e.port??5432;return[ft(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${fr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[ft(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${fr(e)} -tA <<'TS_CLOUD_PG_CAP_EOF' || true`,"\\set QUIET on","SELECT CASE WHEN used::float / NULLIF(cap, 0) >= 0.8"," THEN '[ts-cloud] postgres is at ' || used || '/' || cap || ' connections on this server.'"," || ' Raise max_connections (ALTER SYSTEM SET max_connections = ...; then restart) or'"," || ' set idle_session_timeout so abandoned pools are reclaimed.'"," ELSE NULL END","FROM (SELECT (SELECT count(*) FROM pg_stat_activity) AS used,"," (SELECT setting::int FROM pg_settings WHERE name = 'max_connections') AS cap) c","WHERE CASE WHEN used::float / NULLIF(cap, 0) >= 0.8 THEN true ELSE false END;","SELECT '[ts-cloud] ' || coalesce(datname, '(background)') || ': ' || count(*) || ' connection(s), oldest idle ' ||"," coalesce(round(extract(epoch from max(now() - state_change)) / 60)::text || 'm', 'n/a')","FROM pg_stat_activity","WHERE (SELECT count(*)::float / NULLIF((SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 0) FROM pg_stat_activity) >= 0.8","GROUP BY datname ORDER BY count(*) DESC;","TS_CLOUD_PG_CAP_EOF"]}function Ba(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Kr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
7
7
  `)}function Be(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
8
- `)}function uo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Gr} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Gr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Gr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function si(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${fr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var po=["storage",".env"],ai=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ys(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function Ot(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Ss(e){return typeof e==="string"?e:e.path}function Fa(e){let t=new Map;for(let r of e)t.set(Ss(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function ci(e,t=po){let r=[`mkdir -p ${e.releases} ${e.shared}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function bs(e,t=900){let r=`${C(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function vs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ye(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ts(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ye(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Es(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ke(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function mo(e,t=po){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ke(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function Kr(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ja(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function Jr(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function je(e){return`${C(e)}/owner`}function ws(e,t){let r=je(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function go(e,t){let r=C(e),n=qe(e,t.releaseId),i=ys(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
- export{W,ni,gs,P,so,fs,hs,Ma,Ua,M,gr,ft,Ge,ao,ii,co,oi,fr,lo,ht,Ba,Gr,uo,si,po,ai,ys,Ot,Ss,Fa,ci,bs,vs,Ts,Es,mo,Kr,ja,Jr,ws,go};
8
+ `)}function uo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Kr} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Kr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Kr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function si(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${fr(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var po=["storage",".env"],ai=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function ys(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function Ot(e,t){let r=e.replace(/\/+$/,"");return{base:r,releases:`${r}/releases`,shared:`${r}/shared`,current:`${r}/current`,release:`${r}/releases/${t}`}}function de(e){let t=e.split("/").pop()||e;if(t===".env"||t.startsWith(".env."))return!0;return/\.[a-z0-9]+$/i.test(t)}function Ss(e){return typeof e==="string"?e:e.path}function Fa(e){let t=new Map;for(let r of e)t.set(Ss(r),r);return[...t.values()]}function $e(e,t){if(typeof t==="string")return{path:t,target:`${e.shared}/${t}`,seed:!0};return{path:t.path,target:t.target??`${e.shared}/${t.path}`,seed:t.seed!==!1}}function Fe(e){return["ts_cloud_adopt_shared() {",' TS_CLOUD_SP="$1"',' TS_CLOUD_DST="$2"',` TS_CLOUD_SRC="${e.current}/$TS_CLOUD_SP"`,' if [ -e "$TS_CLOUD_DST" ]; then return 0; fi',' if [ -L "$TS_CLOUD_SRC" ] || [ ! -e "$TS_CLOUD_SRC" ]; then return 0; fi',' mkdir -p "$(dirname "$TS_CLOUD_DST")"',' cp -a "$TS_CLOUD_SRC" "$TS_CLOUD_DST"'," for TS_CLOUD_SIDECAR in -wal -shm; do",' if [ -f "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" ]; then cp -a "$TS_CLOUD_SRC$TS_CLOUD_SIDECAR" "$TS_CLOUD_DST$TS_CLOUD_SIDECAR"; fi'," done",' echo "[ts-cloud] adopted $TS_CLOUD_SP from the live release into shared/ — it now survives deploys"'," return 0","}"]}function ci(e,t=po){let r=[`mkdir -p ${e.releases} ${e.shared}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function bs(e,t=900){let r=`${C(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function vs(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ge(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ts(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ge(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Es(e){let t=`${e.release}.incoming`;return[`if [ "$TS_CLOUD_STAGED" = "${t}" ]; then`,` rm -rf ${e.release}.previous`,` mv ${e.release} ${e.release}.previous`,` mv ${t} ${e.release}`,` rm -rf ${e.release}.previous`,"fi"]}function Ye(e,t){return[`if [ -f ${e} ] && [ ! -L ${e} ] && [ -s ${e} ] && [ ! -s ${t} ]; then`,` cp -a ${e} ${t}`,` echo "[ts-cloud] seeded shared/ from the release's own copy of the file"`,"fi"]}function mo(e,t=po){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ye(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function Jr(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ja(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function Xr(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function je(e){return`${C(e)}/owner`}function ws(e,t){let r=je(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function go(e,t){let r=C(e),n=qe(e,t.releaseId),i=ys(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
9
+ export{W,ni,gs,P,so,fs,hs,Ma,Ua,M,gr,ft,Ke,ao,ii,co,oi,fr,lo,ht,Ba,Kr,uo,si,po,ai,ys,Ot,Ss,Fa,ci,bs,vs,Ts,Es,mo,Jr,ja,Xr,ws,go};
@@ -1,4 +1,4 @@
1
- import{u}from"./chunk-bckm6fre.js";import{f}from"./chunk-80zkjpfz.js";import{O}from"./chunk-57w9nsjk.js";import{li}from"./chunk-wge61ccr.js";function h(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[m,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${m}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),m;while((m=c.exec(i[1]))!==null)n.push(m[1]);return n}class Y{client;region;constructor(e="us-east-1",t){this.client=new u(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=h(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let m=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:m.length>0?m:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class fe{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class za{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new fe(this.region),this.s3=new f(this.region),this.iam=new Y(this.region),this.route53=new O(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-c51xp8f7.js"),a=new s,i=(d,p)=>{let y={Action:d,Version:"2010-05-08",...p};return Object.entries(y).map(([P,A])=>`${encodeURIComponent(P)}=${encodeURIComponent(A)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(d){if(!d.message?.includes("EntityAlreadyExists"))throw d}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=li("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let m=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:m}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
1
+ import{u}from"./chunk-bckm6fre.js";import{f}from"./chunk-80zkjpfz.js";import{O}from"./chunk-57w9nsjk.js";import{li}from"./chunk-wge61ccr.js";function h(e,t){let s=[`Action=${e}`,"Version=2010-05-08"];for(let[a,i]of Object.entries(t)){if(i===void 0||i===null)continue;if(Array.isArray(i))i.forEach((n,c)=>{if(typeof n==="object"&&n!==null)for(let[m,l]of Object.entries(n))s.push(`${a}.member.${c+1}.${m}=${encodeURIComponent(String(l))}`);else s.push(`${a}.member.${c+1}=${encodeURIComponent(String(n))}`)});else if(typeof i==="object"){for(let[n,c]of Object.entries(i))if(c!==void 0&&c!==null)s.push(`${a}.${n}=${encodeURIComponent(String(c))}`)}else s.push(`${a}=${encodeURIComponent(String(i))}`)}return s.join("&")}function r(e,t){let s=new RegExp(`<${t}>([^<]*)</${t}>`),a=e.match(s);return a?a[1]:void 0}function o(e,t,s){let a=new RegExp(`<${t}>([\\s\\S]*?)</${t}>`),i=e.match(a);if(!i)return[];let n=[],c=new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"),m;while((m=c.exec(i[1]))!==null)n.push(m[1]);return n}class Y{client;region;constructor(e="us-east-1",t){this.client=new u(void 0,{profile:t}),this.region=e}async request(e,t={}){let s=h(e,t);return await this.client.request({service:"iam",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s})}async createUser(e){let t=await this.request("CreateUser",e);return this.parseUser(t)}async getUser(e={}){let t=await this.request("GetUser",e);return this.parseUser(t)}async listUsers(e={}){let t=await this.request("ListUsers",e),s=this.parseUsers(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Users:s,IsTruncated:a,Marker:i}}async updateUser(e){await this.request("UpdateUser",e)}async deleteUser(e){await this.request("DeleteUser",e)}parseUser(e){return{UserName:r(e,"UserName")||"",UserId:r(e,"UserId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),PasswordLastUsed:r(e,"PasswordLastUsed")}}parseUsers(e){return o(e,"Users","member").map((s)=>({UserName:r(s,"UserName")||"",UserId:r(s,"UserId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),PasswordLastUsed:r(s,"PasswordLastUsed")}))}async createGroup(e){let t=await this.request("CreateGroup",e);return this.parseGroup(t)}async getGroup(e){let t=await this.request("GetGroup",e),s=this.parseGroup(t),a=this.parseUsers(t),i=r(t,"IsTruncated")==="true",n=r(t,"Marker");return{Group:s,Users:a,IsTruncated:i,Marker:n}}async listGroups(e={}){let t=await this.request("ListGroups",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}async updateGroup(e){await this.request("UpdateGroup",e)}async deleteGroup(e){await this.request("DeleteGroup",e)}async addUserToGroup(e){await this.request("AddUserToGroup",e)}async removeUserFromGroup(e){await this.request("RemoveUserFromGroup",e)}async listGroupsForUser(e){let t=await this.request("ListGroupsForUser",e),s=this.parseGroups(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Groups:s,IsTruncated:a,Marker:i}}parseGroup(e){return{GroupName:r(e,"GroupName")||"",GroupId:r(e,"GroupId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseGroups(e){return o(e,"Groups","member").map((s)=>({GroupName:r(s,"GroupName")||"",GroupId:r(s,"GroupId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async createRole(e){let t=await this.request("CreateRole",e);return this.parseRole(t)}async getRole(e){let t=await this.request("GetRole",e);return this.parseRole(t)}async listRoles(e={}){let t=await this.request("ListRoles",e),s=this.parseRoles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Roles:s,IsTruncated:a,Marker:i}}async updateRole(e){await this.request("UpdateRole",e)}async updateRoleDescription(e){let t=await this.request("UpdateRoleDescription",e);return this.parseRole(t)}async updateAssumeRolePolicy(e){await this.request("UpdateAssumeRolePolicy",e)}async deleteRole(e){await this.request("DeleteRole",e)}async tagRole(e){await this.request("TagRole",e)}async untagRole(e){await this.request("UntagRole",e)}async listRoleTags(e){let t=await this.request("ListRoleTags",e),s=this.parseTags(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Tags:s,IsTruncated:a,Marker:i}}parseRole(e){return{RoleName:r(e,"RoleName")||"",RoleId:r(e,"RoleId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate"),AssumeRolePolicyDocument:r(e,"AssumeRolePolicyDocument"),Description:r(e,"Description"),MaxSessionDuration:r(e,"MaxSessionDuration")?Number.parseInt(r(e,"MaxSessionDuration"),10):void 0}}parseRoles(e){return o(e,"Roles","member").map((s)=>({RoleName:r(s,"RoleName")||"",RoleId:r(s,"RoleId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate"),AssumeRolePolicyDocument:r(s,"AssumeRolePolicyDocument"),Description:r(s,"Description"),MaxSessionDuration:r(s,"MaxSessionDuration")?Number.parseInt(r(s,"MaxSessionDuration"),10):void 0}))}parseTags(e){return o(e,"Tags","member").map((s)=>({Key:r(s,"Key")||"",Value:r(s,"Value")||""}))}async createPolicy(e){let t=await this.request("CreatePolicy",e);return this.parsePolicy(t)}async getPolicy(e){let t=await this.request("GetPolicy",e);return this.parsePolicy(t)}async getPolicyVersion(e){let t=await this.request("GetPolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate"),Document:r(t,"Document")}}async listPolicies(e={}){let t=await this.request("ListPolicies",e),s=this.parsePolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Policies:s,IsTruncated:a,Marker:i}}async listPolicyVersions(e){let t=await this.request("ListPolicyVersions",e),s=this.parsePolicyVersions(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{Versions:s,IsTruncated:a,Marker:i}}async createPolicyVersion(e){let t=await this.request("CreatePolicyVersion",e);return{VersionId:r(t,"VersionId")||"",IsDefaultVersion:r(t,"IsDefaultVersion")==="true",CreateDate:r(t,"CreateDate")}}async deletePolicyVersion(e){await this.request("DeletePolicyVersion",e)}async setDefaultPolicyVersion(e){await this.request("SetDefaultPolicyVersion",e)}async deletePolicy(e){await this.request("DeletePolicy",e)}async attachUserPolicy(e){await this.request("AttachUserPolicy",e)}async detachUserPolicy(e){await this.request("DetachUserPolicy",e)}async attachGroupPolicy(e){await this.request("AttachGroupPolicy",e)}async detachGroupPolicy(e){await this.request("DetachGroupPolicy",e)}async attachRolePolicy(e){await this.request("AttachRolePolicy",e)}async detachRolePolicy(e){await this.request("DetachRolePolicy",e)}async listAttachedUserPolicies(e){let t=await this.request("ListAttachedUserPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedGroupPolicies(e){let t=await this.request("ListAttachedGroupPolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}async listAttachedRolePolicies(e){let t=await this.request("ListAttachedRolePolicies",e),s=this.parseAttachedPolicies(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AttachedPolicies:s,IsTruncated:a,Marker:i}}parsePolicy(e){return{PolicyName:r(e,"PolicyName")||"",PolicyId:r(e,"PolicyId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),DefaultVersionId:r(e,"DefaultVersionId"),AttachmentCount:r(e,"AttachmentCount")?Number.parseInt(r(e,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(e,"PermissionsBoundaryUsageCount")?Number.parseInt(r(e,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(e,"IsAttachable")==="true",Description:r(e,"Description"),CreateDate:r(e,"CreateDate"),UpdateDate:r(e,"UpdateDate")}}parsePolicies(e){return o(e,"Policies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyId:r(s,"PolicyId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),DefaultVersionId:r(s,"DefaultVersionId"),AttachmentCount:r(s,"AttachmentCount")?Number.parseInt(r(s,"AttachmentCount"),10):void 0,PermissionsBoundaryUsageCount:r(s,"PermissionsBoundaryUsageCount")?Number.parseInt(r(s,"PermissionsBoundaryUsageCount"),10):void 0,IsAttachable:r(s,"IsAttachable")==="true",Description:r(s,"Description"),CreateDate:r(s,"CreateDate"),UpdateDate:r(s,"UpdateDate")}))}parsePolicyVersions(e){return o(e,"Versions","member").map((s)=>({VersionId:r(s,"VersionId")||"",IsDefaultVersion:r(s,"IsDefaultVersion")==="true",CreateDate:r(s,"CreateDate")}))}parseAttachedPolicies(e){return o(e,"AttachedPolicies","member").map((s)=>({PolicyName:r(s,"PolicyName")||"",PolicyArn:r(s,"PolicyArn")||""}))}async putUserPolicy(e){await this.request("PutUserPolicy",e)}async getUserPolicy(e){let t=await this.request("GetUserPolicy",e);return{UserName:r(t,"UserName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteUserPolicy(e){await this.request("DeleteUserPolicy",e)}async listUserPolicies(e){let t=await this.request("ListUserPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putGroupPolicy(e){await this.request("PutGroupPolicy",e)}async getGroupPolicy(e){let t=await this.request("GetGroupPolicy",e);return{GroupName:r(t,"GroupName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteGroupPolicy(e){await this.request("DeleteGroupPolicy",e)}async listGroupPolicies(e){let t=await this.request("ListGroupPolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async putRolePolicy(e){await this.request("PutRolePolicy",e)}async getRolePolicy(e){let t=await this.request("GetRolePolicy",e);return{RoleName:r(t,"RoleName")||"",PolicyName:r(t,"PolicyName")||"",PolicyDocument:decodeURIComponent(r(t,"PolicyDocument")||"")}}async deleteRolePolicy(e){await this.request("DeleteRolePolicy",e)}async listRolePolicies(e){let t=await this.request("ListRolePolicies",e),s=o(t,"PolicyNames","member"),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{PolicyNames:s,IsTruncated:a,Marker:i}}async createAccessKey(e={}){let t=await this.request("CreateAccessKey",e);if(typeof t==="object"){let s=t?.CreateAccessKeyResult?.AccessKey||t?.AccessKey;if(s)return{AccessKey:{UserName:s.UserName||"",AccessKeyId:s.AccessKeyId||"",Status:s.Status||"Active",SecretAccessKey:s.SecretAccessKey||"",CreateDate:s.CreateDate}}}return{AccessKey:{UserName:r(t,"UserName")||"",AccessKeyId:r(t,"AccessKeyId")||"",Status:r(t,"Status")||"Active",SecretAccessKey:r(t,"SecretAccessKey")||"",CreateDate:r(t,"CreateDate")}}}async listAccessKeys(e={}){let t=await this.request("ListAccessKeys",e),s=this.parseAccessKeys(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{AccessKeyMetadata:s,IsTruncated:a,Marker:i}}async updateAccessKey(e){await this.request("UpdateAccessKey",e)}async deleteAccessKey(e){await this.request("DeleteAccessKey",e)}async getAccessKeyLastUsed(e){let t=await this.request("GetAccessKeyLastUsed",e);return{UserName:r(t,"UserName")||"",AccessKeyLastUsed:{LastUsedDate:r(t,"LastUsedDate"),ServiceName:r(t,"ServiceName"),Region:r(t,"Region")}}}parseAccessKeys(e){return o(e,"AccessKeyMetadata","member").map((s)=>({UserName:r(s,"UserName"),AccessKeyId:r(s,"AccessKeyId")||"",Status:r(s,"Status")||"Active",CreateDate:r(s,"CreateDate")}))}async createInstanceProfile(e){let t=await this.request("CreateInstanceProfile",e);return this.parseInstanceProfile(t)}async getInstanceProfile(e){let t=await this.request("GetInstanceProfile",e);return this.parseInstanceProfile(t)}async listInstanceProfiles(e={}){let t=await this.request("ListInstanceProfiles",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async listInstanceProfilesForRole(e){let t=await this.request("ListInstanceProfilesForRole",e),s=this.parseInstanceProfiles(t),a=r(t,"IsTruncated")==="true",i=r(t,"Marker");return{InstanceProfiles:s,IsTruncated:a,Marker:i}}async addRoleToInstanceProfile(e){await this.request("AddRoleToInstanceProfile",e)}async removeRoleFromInstanceProfile(e){await this.request("RemoveRoleFromInstanceProfile",e)}async deleteInstanceProfile(e){await this.request("DeleteInstanceProfile",e)}parseInstanceProfile(e){return{InstanceProfileName:r(e,"InstanceProfileName")||"",InstanceProfileId:r(e,"InstanceProfileId")||"",Arn:r(e,"Arn")||"",Path:r(e,"Path"),CreateDate:r(e,"CreateDate")}}parseInstanceProfiles(e){return o(e,"InstanceProfiles","member").map((s)=>({InstanceProfileName:r(s,"InstanceProfileName")||"",InstanceProfileId:r(s,"InstanceProfileId")||"",Arn:r(s,"Arn")||"",Path:r(s,"Path"),CreateDate:r(s,"CreateDate")}))}async getAccountPasswordPolicy(){let e=await this.request("GetAccountPasswordPolicy");return{MinimumPasswordLength:r(e,"MinimumPasswordLength")?Number.parseInt(r(e,"MinimumPasswordLength"),10):void 0,RequireSymbols:r(e,"RequireSymbols")==="true",RequireNumbers:r(e,"RequireNumbers")==="true",RequireUppercaseCharacters:r(e,"RequireUppercaseCharacters")==="true",RequireLowercaseCharacters:r(e,"RequireLowercaseCharacters")==="true",AllowUsersToChangePassword:r(e,"AllowUsersToChangePassword")==="true",ExpirePasswords:r(e,"ExpirePasswords")==="true",MaxPasswordAge:r(e,"MaxPasswordAge")?Number.parseInt(r(e,"MaxPasswordAge"),10):void 0,PasswordReusePrevention:r(e,"PasswordReusePrevention")?Number.parseInt(r(e,"PasswordReusePrevention"),10):void 0,HardExpiry:r(e,"HardExpiry")==="true"}}async updateAccountPasswordPolicy(e){await this.request("UpdateAccountPasswordPolicy",e)}async deleteAccountPasswordPolicy(){await this.request("DeleteAccountPasswordPolicy")}async getAccountSummary(){let e=await this.request("GetAccountSummary"),t={},s=o(e,"SummaryMap","entry");for(let a of s){let i=r(a,"key"),n=r(a,"value");if(i&&n)t[i]=Number.parseInt(n,10)}return t}async listAccountAliases(){let e=await this.request("ListAccountAliases"),t=o(e,"AccountAliases","member"),s=r(e,"IsTruncated")==="true",a=r(e,"Marker");return{AccountAliases:t,IsTruncated:s,Marker:a}}async createAccountAlias(e){await this.request("CreateAccountAlias",e)}async deleteAccountAlias(e){await this.request("DeleteAccountAlias",e)}async simulatePrincipalPolicy(e){let t=await this.request("SimulatePrincipalPolicy",e);return this.parseSimulationResults(t)}parseSimulationResults(e){let s=o(e,"EvaluationResults","member").map((n)=>{let m=o(n,"MatchedStatements","member").map((l)=>({SourcePolicyId:r(l,"SourcePolicyId"),SourcePolicyType:r(l,"SourcePolicyType")}));return{EvalActionName:r(n,"EvalActionName")||"",EvalResourceName:r(n,"EvalResourceName"),EvalDecision:r(n,"EvalDecision")||"",MatchedStatements:m.length>0?m:void 0}}),a=r(e,"IsTruncated")==="true",i=r(e,"Marker");return{EvaluationResults:s,IsTruncated:a,Marker:i}}}class he{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(t)}async createEmailIdentity(e){return await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/identities",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailIdentity(e){let t=await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}});return{IdentityType:t.IdentityType,IdentityName:e,SendingEnabled:t.VerifiedForSendingStatus,VerificationStatus:t.VerificationStatus,DkimAttributes:t.DkimAttributes,MailFromAttributes:t.MailFromAttributes}}async putEmailIdentityMailFromAttributes(e,t){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e)}/mail-from`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listEmailIdentities(e){let t="/v2/email/identities",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;let a=await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}});return{EmailIdentities:a.EmailIdentities,NextToken:a.NextToken}}async deleteEmailIdentity(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/identities/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async putEmailIdentityDkimAttributes(e){await this.client.request({service:"email",region:this.region,method:"PUT",path:`/v2/email/identities/${encodeURIComponent(e.EmailIdentity)}/dkim`,headers:{"Content-Type":"application/json"},body:JSON.stringify({SigningEnabled:e.SigningEnabled})})}async sendEmail(e){return{MessageId:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).MessageId}}async sendBulkEmail(e){return{BulkEmailEntryResults:(await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/outbound-bulk-emails",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).BulkEmailEntryResults}}async createEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"POST",path:"/v2/email/templates",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async getEmailTemplate(e){return await this.client.request({service:"email",region:this.region,method:"GET",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async deleteEmailTemplate(e){await this.client.request({service:"email",region:this.region,method:"DELETE",path:`/v2/email/templates/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async listEmailTemplates(e){let t="/v2/email/templates",s=[];if(e?.PageSize)s.push(`PageSize=${e.PageSize}`);if(e?.NextToken)s.push(`NextToken=${encodeURIComponent(e.NextToken)}`);if(s.length>0)t+=`?${s.join("&")}`;return await this.client.request({service:"email",region:this.region,method:"GET",path:t,headers:{"Content-Type":"application/json"}})}async getSendStatistics(){return{SendDataPoints:(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendStatistics&Version=2010-12-01"})).GetSendStatisticsResponse?.GetSendStatisticsResult?.SendDataPoints?.member}}async getSendQuota(){let t=(await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetSendQuota&Version=2010-12-01"})).GetSendQuotaResponse?.GetSendQuotaResult;return{Max24HourSend:t?.Max24HourSend?Number(t.Max24HourSend):void 0,MaxSendRate:t?.MaxSendRate?Number(t.MaxSendRate):void 0,SentLast24Hours:t?.SentLast24Hours?Number(t.SentLast24Hours):void 0}}async verifyDomain(e){let t=await this.createEmailIdentity({EmailIdentity:e});return{dkimTokens:t.DkimAttributes?.Tokens,verificationStatus:t.DkimAttributes?.Status}}async sendSimpleEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0,a={};if(e.text)a.Text={Data:e.text};if(e.html)a.Html={Data:e.html};return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Simple:{Subject:{Data:e.subject},Body:a}},ReplyToAddresses:s})}async sendTemplatedEmail(e){let t=Array.isArray(e.to)?e.to:[e.to],s=e.replyTo?Array.isArray(e.replyTo)?e.replyTo:[e.replyTo]:void 0;return this.sendEmail({FromEmailAddress:e.from,Destination:{ToAddresses:t},Content:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.templateData)}},ReplyToAddresses:s})}async getDkimRecords(e){let t=await this.getEmailIdentity(e);if(!t.DkimAttributes?.Tokens)return[];return t.DkimAttributes.Tokens.map((s)=>({name:`${s}._domainkey.${e}`,type:"CNAME",value:`${s}.dkim.amazonses.com`}))}async isDomainVerified(e){try{let t=await this.getEmailIdentity(e);return t.VerificationStatus==="SUCCESS"&&t.SendingEnabled===!0}catch{return!1}}async waitForDomainVerification(e,t=60,s=30000){for(let a=0;a<t;a++){if(await this.isDomainVerified(e))return!0;await new Promise((n)=>setTimeout(n,s))}return!1}buildFormBody(e){return Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>`${encodeURIComponent(s)}=${encodeURIComponent(a)}`).join("&")}async createReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async deleteReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async setActiveReceiptRuleSet(e){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetActiveReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})})}async listReceiptRuleSets(e){let t={Action:"ListReceiptRuleSets",Version:"2010-12-01"};if(e)t.NextToken=e;let s=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)}),a=s?.ListReceiptRuleSetsResponse?.ListReceiptRuleSetsResult||s?.ListReceiptRuleSetsResult,i=a?.RuleSets?.member;return{RuleSets:Array.isArray(i)?i:i?[i]:[],NextToken:a?.NextToken}}async describeReceiptRuleSet(e){let t=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeReceiptRuleSet",Version:"2010-12-01",RuleSetName:e})}),s=t?.DescribeReceiptRuleSetResponse?.DescribeReceiptRuleSetResult||t?.DescribeReceiptRuleSetResult,a=s?.Rules?.member;return{Metadata:s?.Metadata,Rules:Array.isArray(a)?a:a?[a]:[]}}async createReceiptRule(e){let t={Action:"CreateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name,"Rule.Enabled":e.Rule.Enabled!==!1?"true":"false"};if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.After)t.After=e.After;if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async deleteReceiptRule(e,t){await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteReceiptRule",Version:"2010-12-01",RuleSetName:e,RuleName:t})})}async receiptRuleSetExists(e){try{return await this.describeReceiptRuleSet(e),!0}catch(t){if(t.code==="RuleSetDoesNotExist"||t.statusCode===400)return!1;throw t}}async getActiveReceiptRuleSet(){let e=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DescribeActiveReceiptRuleSet",Version:"2010-12-01"})}),t=e?.DescribeActiveReceiptRuleSetResponse?.DescribeActiveReceiptRuleSetResult||e?.DescribeActiveReceiptRuleSetResult;if(!t?.Metadata)return null;let s=t?.Rules?.member;return{Metadata:t?.Metadata,Rules:Array.isArray(s)?s:s?[s]:[]}}async updateReceiptRule(e){let t={Action:"UpdateReceiptRule",Version:"2010-12-01",RuleSetName:e.RuleSetName,"Rule.Name":e.Rule.Name};if(e.Rule.Enabled!==void 0)t["Rule.Enabled"]=e.Rule.Enabled?"true":"false";if(e.Rule.TlsPolicy)t["Rule.TlsPolicy"]=e.Rule.TlsPolicy;if(e.Rule.ScanEnabled!==void 0)t["Rule.ScanEnabled"]=e.Rule.ScanEnabled?"true":"false";if(e.Rule.Recipients)e.Rule.Recipients.forEach((s,a)=>{t[`Rule.Recipients.member.${a+1}`]=s});e.Rule.Actions.forEach((s,a)=>{let i=a+1;if(s.S3Action){if(t[`Rule.Actions.member.${i}.S3Action.BucketName`]=s.S3Action.BucketName,s.S3Action.ObjectKeyPrefix)t[`Rule.Actions.member.${i}.S3Action.ObjectKeyPrefix`]=s.S3Action.ObjectKeyPrefix;if(s.S3Action.KmsKeyArn)t[`Rule.Actions.member.${i}.S3Action.KmsKeyArn`]=s.S3Action.KmsKeyArn}if(s.LambdaAction)t[`Rule.Actions.member.${i}.LambdaAction.FunctionArn`]=s.LambdaAction.FunctionArn,t[`Rule.Actions.member.${i}.LambdaAction.InvocationType`]=s.LambdaAction.InvocationType||"Event";if(s.SNSAction){if(t[`Rule.Actions.member.${i}.SNSAction.TopicArn`]=s.SNSAction.TopicArn,s.SNSAction.Encoding)t[`Rule.Actions.member.${i}.SNSAction.Encoding`]=s.SNSAction.Encoding}if(s.StopAction){if(t[`Rule.Actions.member.${i}.StopAction.Scope`]=s.StopAction.Scope,s.StopAction.TopicArn)t[`Rule.Actions.member.${i}.StopAction.TopicArn`]=s.StopAction.TopicArn}}),await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(t)})}async sendRawEmail(e){let t=Buffer.from(e.rawMessage).toString("base64"),s={Action:"SendRawEmail",Version:"2010-12-01",Source:e.source,"RawMessage.Data":t};e.destinations.forEach((n,c)=>{s[`Destinations.member.${c+1}`]=n});let a=await this.client.request({service:"ses",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(s)});return{MessageId:(a?.SendRawEmailResponse?.SendRawEmailResult||a?.SendRawEmailResult)?.MessageId}}async getSuppressedDestination(e){try{return(await this.client.request({service:"ses",region:this.region,method:"GET",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`}))?.SuppressedDestination||null}catch(t){if(t.message?.includes("404")||t.message?.includes("NotFoundException"))return null;throw t}}async deleteSuppressedDestination(e){await this.client.request({service:"ses",region:this.region,method:"DELETE",path:`/v2/email/suppression/addresses/${encodeURIComponent(e)}`})}}class za{ses;s3;iam;route53;region;domain;defaultFrom;constructor(e={}){this.region=e.region||"us-east-1",this.domain=e.domain,this.defaultFrom=e.defaultFrom,this.ses=new he(this.region),this.s3=new f(this.region),this.iam=new Y(this.region),this.route53=new O(this.region)}async send(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required. Set defaultFrom in constructor or provide from in options.");let s=e.fromName?`${e.fromName} <${t}>`:t,a=Array.isArray(e.to)?e.to:[e.to];if(!e.attachments||e.attachments.length===0)return{messageId:(await this.ses.sendSimpleEmail({from:s,to:a,subject:e.subject,text:e.text,html:e.html,replyTo:e.replyTo})).MessageId||""};let i=this.buildRawEmail(e,s,a);return{messageId:(await this.ses.sendEmail({FromEmailAddress:s,Destination:{ToAddresses:a,CcAddresses:e.cc?Array.isArray(e.cc)?e.cc:[e.cc]:void 0,BccAddresses:e.bcc?Array.isArray(e.bcc)?e.bcc:[e.bcc]:void 0},Content:{Raw:{Data:Buffer.from(i).toString("base64")}}})).MessageId||""}}async sendTemplate(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.fromName?`${e.fromName} <${t}>`:t;return{messageId:(await this.ses.sendTemplatedEmail({from:s,to:e.to,templateName:e.templateName,templateData:e.templateData,replyTo:e.replyTo})).MessageId||""}}async sendBulk(e){let t=e.from||this.defaultFrom;if(!t)throw Error("From address is required");let s=e.recipients.map((i)=>({Destination:{ToAddresses:Array.isArray(i.to)?i.to:[i.to]},ReplacementEmailContent:i.templateData?{ReplacementTemplate:{ReplacementTemplateData:JSON.stringify(i.templateData)}}:void 0}));return{results:(await this.ses.sendBulkEmail({FromEmailAddress:t,BulkEmailEntries:s,DefaultContent:{Template:{TemplateName:e.templateName,TemplateData:JSON.stringify(e.defaultTemplateData)}}})).BulkEmailEntryResults?.map((i)=>({status:i.Status||"UNKNOWN",messageId:i.MessageId,error:i.Error}))||[]}}async setupDomain(e){let t;try{t=await this.ses.getEmailIdentity(e)}catch{let a=await this.ses.createEmailIdentity({EmailIdentity:e});t={VerificationStatus:a.DkimAttributes?.Status,DkimAttributes:a.DkimAttributes,SendingEnabled:a.VerifiedForSendingStatus}}try{await this.ses.putEmailIdentityDkimAttributes({EmailIdentity:e,SigningEnabled:!0})}catch{}try{await this.ses.putEmailIdentityMailFromAttributes(e,{MailFromDomain:`mail.${e}`,BehaviorOnMxFailure:"USE_DEFAULT_VALUE"})}catch{}let s=await this.ses.getDkimRecords(e);return{domainVerified:t.SendingEnabled===!0,dkimStatus:t.DkimAttributes?.Status||"UNKNOWN",dkimTokens:t.DkimAttributes?.Tokens,mailFromStatus:t.MailFromAttributes?.MailFromDomainStatus}}async getDnsRecords(e){let t=[],s=await this.ses.getDkimRecords(e);for(let a of s)t.push({type:a.type,name:a.name,value:a.value,ttl:1800});return t.push({type:"MX",name:e,value:`inbound-smtp.${this.region}.amazonaws.com`,priority:10,ttl:3600}),t.push({type:"MX",name:`mail.${e}`,value:`feedback-smtp.${this.region}.amazonses.com`,priority:10,ttl:3600}),t.push({type:"TXT",name:`mail.${e}`,value:"v=spf1 include:amazonses.com ~all",ttl:3600}),t.push({type:"TXT",name:`_dmarc.${e}`,value:`v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${e}`,ttl:3600}),t}async isDomainReady(e){try{let t=await this.ses.getEmailIdentity(e);return t.SendingEnabled===!0&&t.DkimAttributes?.Status==="SUCCESS"}catch{return!1}}async setupReceiving(e){let t={Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:`arn:aws:s3:::${e.bucketName}/*`,Condition:{StringEquals:{"AWS:SourceAccount":e.accountId}}}]};await this.s3.putBucketPolicy(e.bucketName,t);try{await this.ses.createReceiptRuleSet(e.ruleSetName)}catch(a){if(!a.message?.includes("already exists")&&a.code!=="AlreadyExists")throw a}let s=[{S3Action:{BucketName:e.bucketName,ObjectKeyPrefix:e.prefix||"inbox/"}}];if(e.lambdaArn)s.push({LambdaAction:{FunctionArn:e.lambdaArn,InvocationType:"Event"}});try{await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}})}catch(a){if(a.message?.includes("already exists"))await this.ses.deleteReceiptRule(e.ruleSetName,e.ruleName),await this.ses.createReceiptRule({RuleSetName:e.ruleSetName,Rule:{Name:e.ruleName,Enabled:!0,TlsPolicy:"Optional",Recipients:e.recipients||[e.domain],ScanEnabled:e.scanEnabled!==!1,Actions:s}});else throw a}await this.ses.setActiveReceiptRuleSet(e.ruleSetName)}async getIncomingEmails(e){return(await this.s3.list({bucket:e.bucket,prefix:e.prefix||"incoming/",maxKeys:e.maxResults||100})).map((s)=>({key:s.Key||"",lastModified:s.LastModified||"",size:s.Size||0}))}async readEmail(e){return await this.s3.getObject(e.bucket,e.key)}async createSmtpCredentials(e){let t=`ses-smtp-${e.username.replace(/[^a-zA-Z0-9]/g,"-")}`,{AWSClient:s}=await import("./chunk-c51xp8f7.js"),a=new s,i=(d,p)=>{let y={Action:d,Version:"2010-05-08",...p};return Object.entries(y).map(([P,A])=>`${encodeURIComponent(P)}=${encodeURIComponent(A)}`).join("&")};try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateUser",{UserName:t})})}catch(d){if(!d.message?.includes("EntityAlreadyExists"))throw d}let n={Version:"2012-10-17",Statement:[{Effect:"Allow",Action:"ses:SendRawEmail",Resource:"*",Condition:{StringLike:{"ses:FromAddress":`*@${e.domain}`}}}]},c=`ses-smtp-policy-${e.domain.replace(/\./g,"-")}`;try{await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("PutUserPolicy",{UserName:t,PolicyName:c,PolicyDocument:JSON.stringify(n)})})}catch{}let l=(await a.request({service:"iam",region:"us-east-1",method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i("CreateAccessKey",{UserName:t})}))?.CreateAccessKeyResult?.AccessKey;if(!l?.AccessKeyId||!l?.SecretAccessKey)throw Error("Failed to create access key");let g=this.deriveSmtpPassword(l.SecretAccessKey);return{username:l.AccessKeyId,password:g,server:`email-smtp.${this.region}.amazonaws.com`,port:587}}deriveSmtpPassword(e){let t=li("node:crypto"),s="SendRawEmail",a=Buffer.from([4]),i=t.createHmac("sha256",`AWS4${e}`).update("11111111").digest();return i=t.createHmac("sha256",i).update(this.region).digest(),i=t.createHmac("sha256",i).update("ses").digest(),i=t.createHmac("sha256",i).update("aws4_request").digest(),i=t.createHmac("sha256",i).update("SendRawEmail").digest(),Buffer.concat([a,i]).toString("base64")}async createTemplate(e){await this.ses.createEmailTemplate({TemplateName:e.name,TemplateContent:{Subject:e.subject,Text:e.text,Html:e.html}})}async getTemplate(e){try{let t=await this.ses.getEmailTemplate(e);return{name:t.TemplateName||e,subject:t.TemplateContent?.Subject,text:t.TemplateContent?.Text,html:t.TemplateContent?.Html}}catch{return null}}async deleteTemplate(e){await this.ses.deleteEmailTemplate(e)}async listTemplates(){return(await this.ses.listEmailTemplates()).TemplatesMetadata?.map((t)=>({name:t.TemplateName||"",createdAt:t.CreatedTimestamp}))||[]}async deploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=e.storage?.bucketName||`${e.appName}-${e.environment}-email`,i=await this.setupDomain(e.domain);if(!(await this.s3.listBuckets()).Buckets?.some((l)=>l.Name===a))await this.s3.createBucket(a);await this.setupReceiving({domain:e.domain,ruleSetName:t,ruleName:s,bucketName:a,prefix:e.storage?.prefix||"inbox/",accountId:e.accountId,recipients:e.catchAll?[e.domain]:e.mailboxes,scanEnabled:!0});let m=await this.getDnsRecords(e.domain);return{success:!0,domainVerified:i.domainVerified,dkimStatus:i.dkimStatus,receiptRuleSet:t,storageBucket:a,dnsRecords:m}}async undeploy(e){let t=`${e.appName}-${e.environment}-email-rules`,s=`${e.appName}-inbound-email`,a=`${e.appName}-${e.environment}-email`;try{await this.ses.deleteReceiptRule(t,s)}catch{}try{await this.ses.deleteReceiptRuleSet(t)}catch{}if(e.deleteBucket)try{await this.s3.emptyAndDeleteBucket(a)}catch{}}async getSendingStats(){let e=await this.ses.getSendQuota();return{sentLast24Hours:e.SentLast24Hours||0,maxSendRate:e.MaxSendRate||0,max24HourSend:e.Max24HourSend||0}}buildRawEmail(e,t,s){let a=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`,i="";if(i+=`From: ${t}\r
2
2
  `,i+=`To: ${s.join(", ")}\r
3
3
  `,e.cc){let n=Array.isArray(e.cc)?e.cc:[e.cc];i+=`Cc: ${n.join(", ")}\r
4
4
  `}if(i+=`Subject: ${e.subject}\r
@@ -31,4 +31,4 @@ import{u}from"./chunk-bckm6fre.js";import{f}from"./chunk-80zkjpfz.js";import{O}f
31
31
  `,i+=`${n.content}\r
32
32
  `;return i+=`--${a}--\r
33
33
  `,i}}var Ou=new za;
34
- export{Y,fe,za,Ou};
34
+ export{Y,he,za,Ou};
@@ -1,4 +1,4 @@
1
- import{U}from"./chunk-6xw0r4gn.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
1
+ import{U}from"./chunk-8tbj9h2a.js";function g(t){let e=t.sites||{};for(let r of Object.values(e))if(r?.repository?.url)return{provider:r.repository.provider,branch:r.repository.branch};return}function m(t){let e=t.trim().toLowerCase();if(e.includes("github.com"))return"github";if(e.includes("gitlab.com"))return"gitlab";if(e.includes("bitbucket.org"))return"bitbucket";return}function a(t){return`'${t.replace(/'/g,"'\\''")}'`}function E(t){return t.replace(/'/g,"''")}function _(t,e){let r=["bunx --bun @stacksjs/ts-cloud deploy","--env",a(t)];if(e.site)r.push("--site",a(e.site));if(e.skipDnsVerification)r.push("--skip-dns-verification");return r.push("--yes"),r.join(" ")}function v(t,e="production",r={}){let l=g(t),n=r.provider||l?.provider;if(n!=="github"&&n!=="gitlab"&&n!=="bitbucket")return null;let i=t.environments?.[e],s=i?.deployBranch||l?.branch||"main",u=_(e,r),c=JSON.stringify(s),d=JSON.stringify(e),p=i?.domain?i.domain.startsWith("http")?i.domain:`https://${i.domain}`:void 0,f=p?`
2
2
  url: ${JSON.stringify(p)}`:"",h=r.setup==="pantry"?` - name: Setup Pantry
3
3
  uses: home-lang/pantry/packages/action@main`:` - uses: oven-sh/setup-bun@v2
4
4
  - run: bun install --frozen-lockfile`,y=U(t)==="hetzner"&&!!t.infrastructure?.compute,o=r.sshPrivateKeySecret||"SSH_PRIVATE_KEY";if(!/^[A-Z_][A-Z0-9_]*$/i.test(o))throw Error(`Invalid SSH private key secret name '${o}'`);let b=y?`
@@ -1 +1 @@
1
- import{to}from"./chunk-f35pte64.js";var su="\x00";function El(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function ta(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!El(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function ra(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class wl{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>ta(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=ra(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!ta(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=ra(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function au(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function cu(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",Vt=24,sn=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Vt,Math.max(0.25,e))}var f=500;class zt{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,sn)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,Vt)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!to(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function vi(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function lu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function an(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function ko(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:an(o,i)}}}}export{su,El,ta,ra,wl,au,cu,Vt,sn,zt,vi,lu,an,ko};
1
+ import{to}from"./chunk-f35pte64.js";var su="\x00";function El(t,i){if(t==="*"||t==="**")return!0;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*");return new RegExp(`^${e}$`).test(i)}function g(t,i){if(t.startsWith("*.")){let e=t.slice(1);return i.endsWith(e)&&i.length>e.length}return t===i}function ta(t,i){if(t.enabled===!1)return!1;if(t.methods?.length&&!t.methods.some((e)=>e.toUpperCase()===i.method.toUpperCase()))return!1;if(t.path&&!El(t.path,i.path))return!1;if(t.host&&!g(t.host,i.host??""))return!1;return!0}function ra(t,i){let e=t.key??{source:"ip"},o=e.fallbackToIp!==!1,r;if(e.source==="ip")r=i.ip;else if(e.source==="global")r="global";else if(e.source==="host")r=i.host??"";else if(e.source==="path")r=i.path;else if(e.source==="header")r=e.name?i.headers?.[e.name.toLowerCase()]:void 0;else if(e.source==="cookie")r=e.name?i.cookies?.[e.name]:void 0;if(!r&&e.source!=="global")r=o?i.ip:"__missing__";return`${t.id}\x00${r}`}class wl{clock;maxTrackedKeys;buckets=new Map;windows=new Map;rules;constructor(t,i=()=>Date.now(),e=1e5){this.clock=i;this.maxTrackedKeys=e;this.rules=[...t].sort((o,r)=>(o.priority??0)-(r.priority??0))}check(t){let i=this.clock(),e=this.rules.filter((n)=>ta(n,t)),o;for(let n of e){let s=this.test(n,t,i);if(s.allowed)continue;if(!o||d(s.action)>d(o.action))o=s}if(o)return o;let r={action:"allow",allowed:!0};for(let n of e){let s=this.consume(n,t,i);if(s.remaining!=null&&(r.remaining??1/0)>s.remaining)r=s}return r}test(t,i,e){let o=ra(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let n=t.burst??t.limit,s=this.buckets.get(o),a=s?Math.min(n,s.tokens+this.refill(t,e-s.updatedAt)):n;if(a>=1)return{action:"allow",allowed:!0};return this.blocked(t,o,0,this.msPerToken(t)*(1-a),e)}let r=(this.windows.get(o)?.hits??[]).filter((n)=>n>e-t.windowMs);if(r.length<t.limit)return{action:"allow",allowed:!0};return this.blocked(t,o,0,r[0]+t.windowMs-e,e)}peek(t){let i=this.clock();for(let e of this.rules){if(!ta(e,t))continue;let o=this.test(e,t,i);if(!o.allowed)return o}return{action:"allow",allowed:!0}}msPerToken(t){return t.windowMs/Math.max(1,t.limit)}refill(t,i){return Math.max(0,i)/this.msPerToken(t)}blocked(t,i,e,o,r){let n=t.action??"deny";return{action:n,allowed:n==="allow"||n==="log",ruleId:t.id,limit:t.limit,remaining:e,retryAfterMs:Math.max(0,Math.ceil(o)),resetAt:r+Math.max(0,o),key:i}}consume(t,i,e){let o=ra(t,i);if((t.algorithm??"token_bucket")==="token_bucket"){let l=t.burst??t.limit,u=this.buckets.get(o)??{tokens:l,updatedAt:e},c=Math.min(l,u.tokens+this.refill(t,e-u.updatedAt));if(c<1)return this.buckets.set(o,{tokens:c,updatedAt:e}),this.blocked(t,o,0,this.msPerToken(t)*(1-c),e);return this.evictIfNeeded(this.buckets),this.buckets.set(o,{tokens:c-1,updatedAt:e}),{action:"allow",allowed:!0,ruleId:t.id,limit:l,remaining:Math.floor(c-1),resetAt:e+this.msPerToken(t)*(l-(c-1)),key:o}}let n=this.windows.get(o)??{hits:[]},s=e-t.windowMs,a=n.hits.filter((l)=>l>s);if(a.length>=t.limit)return this.windows.set(o,{hits:a}),this.blocked(t,o,0,a[0]+t.windowMs-e,e);return a.push(e),this.evictIfNeeded(this.windows),this.windows.set(o,{hits:a}),{action:"allow",allowed:!0,ruleId:t.id,limit:t.limit,remaining:t.limit-a.length,resetAt:a[0]+t.windowMs,key:o}}evictIfNeeded(t){if(t.size<this.maxTrackedKeys)return;let i=t.size-this.maxTrackedKeys+1,e=0;for(let o of t.keys())if(t.delete(o),++e>=i)break}sweep(){let t=this.clock(),i=0;for(let[e,o]of this.windows){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n){this.windows.delete(e),i++;continue}if(o.hits.every((s)=>s<=t-n.windowMs))this.windows.delete(e),i++}for(let[e,o]of this.buckets){let r=e.split("\x00")[0],n=this.rules.find((s)=>s.id===r);if(!n||t-o.updatedAt>n.windowMs*2)this.buckets.delete(e),i++}return i}get trackedKeys(){return this.buckets.size+this.windows.size}}function d(t){return{allow:0,log:1,throttle:2,challenge:3,deny:4}[t]}function au(t){let i={};if(t.limit!=null)i["ratelimit-limit"]=String(t.limit);if(t.remaining!=null)i["ratelimit-remaining"]=String(t.remaining);if(t.resetAt!=null)i["ratelimit-reset"]=String(Math.max(0,Math.ceil((t.resetAt-Date.now())/1000)));if(!t.allowed&&t.retryAfterMs!=null)i["retry-after"]=String(Math.max(1,Math.ceil(t.retryAfterMs/1000)));return i}function cu(){return[{id:"global-ip",limit:600,windowMs:60000,burst:100,key:{source:"ip"},action:"deny",priority:100},{id:"api-ip",limit:120,windowMs:60000,burst:30,path:"/api/**",key:{source:"ip"},action:"deny",priority:50},{id:"auth-ip",limit:10,windowMs:60000,algorithm:"sliding_window",path:"/auth/**",methods:["POST"],key:{source:"ip"},action:"challenge",priority:10}]}var m="protection.controls",Vt=24,an=4,R={ipRules:{allow:[],block:[]}};function p(t,i){if(!t?.enabled)return;return new Date(t.expiresAt).getTime()>i.getTime()?t:void 0}function h(t,i){let e=Number.isFinite(t)?Number(t):i;return Math.min(Vt,Math.max(0.25,e))}var f=500;class zt{controlPlane;options;constructor(t,i={}){this.controlPlane=t;this.options=i}now(){return this.options.now?.()??new Date}read(){let t=this.controlPlane.getSetting(m);if(!t||typeof t!=="object"||Array.isArray(t))return{...R,ipRules:{allow:[],block:[]}};let i=t;return{attackMode:i.attackMode,mitigationPause:i.mitigationPause,ipRules:{allow:Array.isArray(i.ipRules?.allow)?i.ipRules.allow:[],block:Array.isArray(i.ipRules?.block)?i.ipRules.block:[]},updatedAt:i.updatedAt}}write(t){let i={...t,updatedAt:this.now().toISOString()};return this.controlPlane.setSetting(m,i),i}raw(){return this.read()}current(){let t=this.now(),i=this.read();return{attackMode:p(i.attackMode,t),mitigationPause:p(i.mitigationPause,t),ipRules:i.ipRules}}enableAttackMode(t){let i=this.now(),e={enabled:!0,startedAt:i.toISOString(),expiresAt:new Date(i.getTime()+h(t.hours,an)*3600000).toISOString(),reason:t.reason.trim()||"Attack mode enabled by an operator.",actorId:t.actorId};return this.write({...this.read(),attackMode:e}),e}disableAttackMode(){let t=this.read();if(!t.attackMode?.enabled)return!1;return this.write({...t,attackMode:{...t.attackMode,enabled:!1}}),!0}pauseMitigations(t){let i=t.reason.trim();if(!i)throw Error("Pausing mitigations requires a reason: you are liable for the traffic it admits.");let e=this.now(),o={enabled:!0,startedAt:e.toISOString(),expiresAt:new Date(e.getTime()+h(t.hours,Vt)*3600000).toISOString(),reason:i,actorId:t.actorId};return this.write({...this.read(),mitigationPause:o}),o}resumeMitigations(){let t=this.read();if(!t.mitigationPause?.enabled)return!1;return this.write({...t,mitigationPause:{...t.mitigationPause,enabled:!1}}),!0}addIpRule(t,i){let e=i.trim();if(!to(e))throw Error(`Not a valid IP or CIDR: ${i}`);let o=this.read(),r={...o.ipRules,[t]:[...new Set([...o.ipRules[t],e])]};if(r[t].length>f)throw Error(`At most ${f} ${t} rules are supported.`);let n=t==="allow"?"block":"allow";return r[n]=r[n].filter((s)=>s!==e),this.write({...o,ipRules:r}),r}removeIpRule(t,i){let e=this.read(),o={...e.ipRules,[t]:e.ipRules[t].filter((r)=>r!==i.trim())};return this.write({...e,ipRules:o}),o}}function vi(t){if(t.mitigationPause)return{attackMode:!!t.attackMode,mitigationPaused:!0,summary:`Automatic mitigation is paused until ${t.mitigationPause.expiresAt}. All traffic is being served and billed.`,expiresAt:t.mitigationPause.expiresAt};if(t.attackMode)return{attackMode:!0,mitigationPaused:!1,summary:`Attack mode is on until ${t.attackMode.expiresAt}. Every visitor is being challenged.`,expiresAt:t.attackMode.expiresAt};return{attackMode:!1,mitigationPaused:!1,summary:"Protection is in its normal posture."}}function lu(t,i){if(i.mitigationPause)return t.map((e)=>({...e,enabled:!1}));if(!i.attackMode)return[...t];return t.map((e)=>({...e,action:e.action==="deny"?"deny":"challenge",burst:Math.max(1,Math.min(e.burst??e.limit,5))}))}function cn(t,i){let e=[...new Set([...t.allowlist??[],...i.ipRules.allow])],o=[...new Set([...t.blocklist??[],...i.ipRules.block])];if(i.mitigationPause)return{...t,allowlist:e,blocklist:o,monitorOnly:!0};if(!i.attackMode)return{...t,allowlist:e,blocklist:o};let r=t.thresholds??{};return{...t,allowlist:e,blocklist:o,thresholds:{...r,newConnectionsPerSecond:Math.max(1,Math.floor((r.newConnectionsPerSecond??50)/5)),concurrentPerSource:Math.max(1,Math.floor((r.concurrentPerSource??100)/5))}}}function ko(t,i){let e=t?.infrastructure?.compute;if(!e||e.ddos===!1)return t;let o=typeof e.ddos==="object"&&e.ddos!==null?e.ddos:{};return{...t,infrastructure:{...t.infrastructure,compute:{...e,ddos:cn(o,i)}}}}export{su,El,ta,ra,wl,au,cu,Vt,an,zt,vi,lu,cn,ko};
@@ -1 +1 @@
1
- import{dt,zl,Yo,Vi,Pu,Zo,es,zi,_t,Nu,ql,ku,Du,j,ts,xu}from"./chunk-x5x9dzk7.js";import"./chunk-4zbnwt9b.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-7h6h8yxm.js";import"./chunk-bckm6fre.js";import"./chunk-6xw0r4gn.js";export{Vi as assertEnvWithinLimit,Yo as buildFunctionEnv,Pu as deployServerlessApp,ku as getCommandRecord,zl as infraEnvFromOutputs,ql as listCommandHistory,Zo as redeployServerlessApp,dt as resolveServerlessFunctions,xu as restoreServerlessDatabase,es as rollbackServerlessApp,Nu as runAndRecordCommand,Du as runDbQuery,_t as runRemoteCommand,ts as scaleServerlessDatabase,j as serverlessInfo,zi as setMaintenance};
1
+ import{ut,zl,Yo,Vi,Pu,Zo,es,zi,_t,Nu,ql,ku,Du,j,ts,xu}from"./chunk-r1vtnn8w.js";import"./chunk-4zbnwt9b.js";import"./chunk-vymg9ywg.js";import"./chunk-80zkjpfz.js";import"./chunk-77qpn2m8.js";import"./chunk-bckm6fre.js";import"./chunk-8tbj9h2a.js";export{Vi as assertEnvWithinLimit,Yo as buildFunctionEnv,Pu as deployServerlessApp,ku as getCommandRecord,zl as infraEnvFromOutputs,ql as listCommandHistory,Zo as redeployServerlessApp,ut as resolveServerlessFunctions,xu as restoreServerlessDatabase,es as rollbackServerlessApp,Nu as runAndRecordCommand,Du as runDbQuery,_t as runRemoteCommand,ts as scaleServerlessDatabase,j as serverlessInfo,zi as setMaintenance};
@@ -1 +1 @@
1
- import{q,ji}from"./chunk-wvhqjr80.js";import"./chunk-57w9nsjk.js";import"./chunk-bckm6fre.js";export{q as ACMClient,ji as ACMDnsValidator};
1
+ import{q,ji}from"./chunk-5tsxt28g.js";import"./chunk-57w9nsjk.js";import"./chunk-bckm6fre.js";export{q as ACMClient,ji as ACMDnsValidator};