@stacksjs/ts-cloud 0.16.47 → 0.16.49

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 (101) hide show
  1. package/dist/aws/index.js +1 -1
  2. package/dist/bin/{chunk-rxy9fa64.js → chunk-03gqra5e.js} +78 -78
  3. package/dist/bin/{chunk-2gqhzn2r.js → chunk-1fj03993.js} +1 -1
  4. package/dist/bin/{chunk-t1mmfpn1.js → chunk-2pzh0wxc.js} +1 -1
  5. package/dist/bin/{chunk-yp3a0j9n.js → chunk-3pazrfsf.js} +5 -5
  6. package/dist/bin/{chunk-qq1f07te.js → chunk-4mecfcjk.js} +2 -2
  7. package/dist/bin/{chunk-dn1yybdy.js → chunk-52w33yma.js} +1 -1
  8. package/dist/bin/{chunk-nhqz2j90.js → chunk-cf3jn2ey.js} +1 -1
  9. package/dist/bin/chunk-hhhrze6m.js +1 -0
  10. package/dist/bin/{chunk-her9ny96.js → chunk-psmpw0ap.js} +1 -1
  11. package/dist/bin/{chunk-de69nra4.js → chunk-vhyp4xj0.js} +2 -2
  12. package/dist/bin/{chunk-nmr484r7.js → chunk-ynwbzsz8.js} +4 -4
  13. package/dist/bin/chunk-zjvg5pg8.js +1 -0
  14. package/dist/bin/cli.js +17 -17
  15. package/dist/bin/dashboard-server.js +1 -1
  16. package/dist/{chunk-6ea5d30w.js → chunk-22hfejjs.js} +1 -1
  17. package/dist/{chunk-bvzmbksp.js → chunk-25sw2s70.js} +1 -1
  18. package/dist/{chunk-1dbe68z7.js → chunk-2pns2rkf.js} +4 -4
  19. package/dist/{chunk-zwkm3pkb.js → chunk-6mp1fyxe.js} +1 -1
  20. package/dist/{chunk-46bazfbh.js → chunk-7v7dwev4.js} +84 -84
  21. package/dist/{chunk-j2jex596.js → chunk-bdv3gpzb.js} +51 -51
  22. package/dist/{chunk-jzpwfgg1.js → chunk-da62knsv.js} +15 -15
  23. package/dist/{chunk-wb7h8ag4.js → chunk-e8k29wen.js} +1 -1
  24. package/dist/{chunk-wmxw3pe4.js → chunk-fpkpwbv3.js} +5 -5
  25. package/dist/{chunk-v1bzy3tp.js → chunk-gh0ghb21.js} +2 -2
  26. package/dist/chunk-gqadvddh.js +1 -0
  27. package/dist/{chunk-tj852ns1.js → chunk-jhtp3m31.js} +2 -2
  28. package/dist/chunk-kpmxvpcv.js +1 -0
  29. package/dist/{chunk-j73ntebp.js → chunk-kr8aeva1.js} +13 -13
  30. package/dist/{chunk-79snvzcx.js → chunk-p7myt05d.js} +3 -3
  31. package/dist/{chunk-yxzdwe7j.js → chunk-vnarc5gc.js} +3 -3
  32. package/dist/{chunk-astzz50p.js → chunk-x0ep5ybv.js} +2 -2
  33. package/dist/{chunk-r86dh7h7.js → chunk-yme6q7k4.js} +2 -2
  34. package/dist/deploy/index.js +1 -1
  35. package/dist/deploy/server-dns.d.ts +7 -1
  36. package/dist/dns/index.js +1 -1
  37. package/dist/drivers/index.js +1 -1
  38. package/dist/drivers/shared/rpx-gateway.d.ts +39 -2
  39. package/dist/index.js +3 -3
  40. package/dist/operations/index.js +1 -1
  41. package/dist/protection/index.js +1 -1
  42. package/dist/spend/index.js +1 -1
  43. package/dist/ui/404.html +1 -1
  44. package/dist/ui/accept-invitation.html +1 -1
  45. package/dist/ui/access-denied.html +1 -1
  46. package/dist/ui/account/automation.html +6 -6
  47. package/dist/ui/account/security.html +1 -1
  48. package/dist/ui/applications/compose.html +5 -5
  49. package/dist/ui/applications/new.html +2 -2
  50. package/dist/ui/data/backups.html +5 -5
  51. package/dist/ui/data/services.html +6 -6
  52. package/dist/ui/data/volumes.html +6 -6
  53. package/dist/ui/index.html +6 -6
  54. package/dist/ui/infrastructure/topology.html +5 -5
  55. package/dist/ui/integrations.html +2 -2
  56. package/dist/ui/operations/alerts.html +5 -5
  57. package/dist/ui/operations/configuration.html +6 -6
  58. package/dist/ui/operations/jobs.html +6 -6
  59. package/dist/ui/operations/maintenance.html +5 -5
  60. package/dist/ui/operations/observability.html +6 -6
  61. package/dist/ui/operations/previews.html +6 -6
  62. package/dist/ui/operations/queue.html +6 -6
  63. package/dist/ui/operations/regions.html +5 -5
  64. package/dist/ui/operations/releases.html +5 -5
  65. package/dist/ui/operations/spend.html +6 -6
  66. package/dist/ui/operations/workloads.html +6 -6
  67. package/dist/ui/security.html +2 -2
  68. package/dist/ui/server/actions.html +6 -6
  69. package/dist/ui/server/activity.html +2 -2
  70. package/dist/ui/server/capacity.html +6 -6
  71. package/dist/ui/server/database.html +6 -6
  72. package/dist/ui/server/deployments.html +5 -5
  73. package/dist/ui/server/diagnostics.html +2 -2
  74. package/dist/ui/server/firewall.html +6 -6
  75. package/dist/ui/server/fleet.html +5 -5
  76. package/dist/ui/server/logs.html +6 -6
  77. package/dist/ui/server/metrics.html +5 -5
  78. package/dist/ui/server/security.html +2 -2
  79. package/dist/ui/server/services.html +1 -1
  80. package/dist/ui/server/sites.html +6 -6
  81. package/dist/ui/server/ssh-keys.html +6 -6
  82. package/dist/ui/server/team.html +6 -6
  83. package/dist/ui/server/terminal.html +2 -2
  84. package/dist/ui/serverless/alarms.html +6 -6
  85. package/dist/ui/serverless/assets.html +2 -2
  86. package/dist/ui/serverless/cost.html +2 -2
  87. package/dist/ui/serverless/data.html +6 -6
  88. package/dist/ui/serverless/deployments.html +2 -2
  89. package/dist/ui/serverless/firewall.html +2 -2
  90. package/dist/ui/serverless/functions.html +6 -6
  91. package/dist/ui/serverless/logs.html +6 -6
  92. package/dist/ui/serverless/metrics.html +2 -2
  93. package/dist/ui/serverless/queues.html +5 -5
  94. package/dist/ui/serverless/secrets.html +5 -5
  95. package/dist/ui/serverless/traces.html +6 -6
  96. package/dist/ui/serverless.html +6 -6
  97. package/package.json +3 -3
  98. package/dist/bin/chunk-r1kg6yxp.js +0 -1
  99. package/dist/bin/chunk-vt3hjh9q.js +0 -1
  100. package/dist/chunk-4t0vj9a4.js +0 -1
  101. package/dist/chunk-s7q23exe.js +0 -1
@@ -1 +1 @@
1
- import{bt,Kd,_s,Io,sm,Os,$s,Po,Bt,am,Jd,cm,lm,z,Ls,dm}from"./chunk-qq1f07te.js";import"./chunk-de69nra4.js";import"./chunk-6y6g726g.js";import"./chunk-xdk0gmxt.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{Io as assertEnvWithinLimit,_s as buildFunctionEnv,sm as deployServerlessApp,cm as getCommandRecord,Kd as infraEnvFromOutputs,Jd as listCommandHistory,Os as redeployServerlessApp,bt as resolveServerlessFunctions,dm as restoreServerlessDatabase,$s as rollbackServerlessApp,am as runAndRecordCommand,lm as runDbQuery,Bt as runRemoteCommand,Ls as scaleServerlessDatabase,z as serverlessInfo,Po as setMaintenance};
1
+ import{bt,Kd,_s,Io,sm,Os,$s,Po,Bt,am,Jd,cm,lm,z,Ls,dm}from"./chunk-4mecfcjk.js";import"./chunk-vhyp4xj0.js";import"./chunk-6y6g726g.js";import"./chunk-xdk0gmxt.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{Io as assertEnvWithinLimit,_s as buildFunctionEnv,sm as deployServerlessApp,cm as getCommandRecord,Kd as infraEnvFromOutputs,Jd as listCommandHistory,Os as redeployServerlessApp,bt as resolveServerlessFunctions,dm as restoreServerlessDatabase,$s as rollbackServerlessApp,am as runAndRecordCommand,lm as runDbQuery,Bt as runRemoteCommand,Ls as scaleServerlessDatabase,z as serverlessInfo,Po as setMaintenance};
@@ -1 +1 @@
1
- import{si}from"./chunk-nhqz2j90.js";import"./chunk-xx9mrcfs.js";import"./chunk-qq1f07te.js";import"./chunk-de69nra4.js";import"./chunk-6y6g726g.js";import"./chunk-xdk0gmxt.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{si as resolveDashboardData};
1
+ import{si}from"./chunk-cf3jn2ey.js";import"./chunk-xx9mrcfs.js";import"./chunk-4mecfcjk.js";import"./chunk-vhyp4xj0.js";import"./chunk-6y6g726g.js";import"./chunk-xdk0gmxt.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{si as resolveDashboardData};
@@ -1,9 +1,9 @@
1
- import{H,$r}from"./chunk-dj03v81n.js";function J(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function Ei(e){return e.type!=null&&me.has(e.type)}function zs(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 fe(e){return zs(e).length>0}function te(e){if(e.deploy)return e.deploy;if(Ei(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(Ei(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function ko(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Hs(e,t={}){let r=[],n=[],o=e.sites||{},s=ko(e),c=$r(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),R=P(i);if(R==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.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(i.start)a.push("start");if(i.root)a.push("root");if(i.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(R==="proxy"){if(!i.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 u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(R==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(R==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(R==="server-static"){if(!i.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(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function qs(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Vc(e){return P(e)==="bucket"}function zc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=P(o);return s==="redirect"||s==="proxy"})}var A={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 U="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function Ir(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${M(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 St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function et(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function No(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",T="mail-server",q="mail",F=`${U}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${A.mail}@${e.version}`:A.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${C(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${C(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${C(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 = ${C(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${C(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 = ${C(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${C(e.webhookUrl)}`);return t.push(""),t.join(`
1
+ import{H,$r}from"./chunk-dj03v81n.js";function J(e,t){return`/var/www/${e}-${t}`}var me=new Set(["laravel","php","statamic","wordpress"]);function Ei(e){return e.type!=null&&me.has(e.type)}function zs(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 fe(e){return zs(e).length>0}function te(e){if(e.deploy)return e.deploy;if(Ei(e))return"server";if(e.start)return"server";return"bucket"}function I(e){if(e.redirect)return"redirect";if(fe(e))return"proxy";if(Ei(e))return"server-php";if(te(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function ko(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function Hs(e,t={}){let r=[],n=[],o=e.sites||{},s=ko(e),c=$r(e);if(c)r.push(c);let p=new Map;for(let[l,i]of Object.entries(o)){if(!i)continue;let f=te(i),R=I(i);if(R==="redirect"){if(!i.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof i.redirect==="string"?i.redirect:i.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(i.start)a.push("start");if(i.root)a.push("root");if(i.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(R==="proxy"){if(!i.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 u=[];if(i.start)u.push("start");if(i.root)u.push("root");if(typeof i.port==="number")u.push("port");if(i.build)u.push("build");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${u.join(", ")} ${u.length===1?"is":"are"} ignored — remove ${u.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!i.start&&!i.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(R==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!i.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${i.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(R==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${i.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof i.port==="number"){let u=t.occupiedPorts?.get(i.port);if(u)r.push(`Site '${l}' wants port ${i.port}, which project '${u}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=p.get(i.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${i.port}. Server apps sharing a box must use distinct ports.`);else p.set(i.port,l)}}else if(R==="server-static"){if(!i.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(!i.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let u=[];if(i.start)u.push("start");if(typeof i.port==="number")u.push("port");if(i.preStart&&i.preStart.length>0)u.push("preStart");if(u.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${u.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function qs(e){let t=I(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function Vc(e){return I(e)==="bucket"}function zc(e,t){if(H(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,o])=>o!=null),n=t?r.filter(([o])=>o===t):r;if(n.length===0)return!0;return!n.every(([,o])=>{let s=I(o);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 U="/opt/pantry";function M(e){return`'${e.split("'").join("'\\''")}'`}function Ir(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${M(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 St(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function et(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(M).join(" ")})`]}function No(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${M(t)})`,`(cd /opt/pantry && pantry enable ${M(t)})`])}var m="/etc/mail",T="mail-server",q="mail",F=`${U}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function C(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function ge(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${m}/dkim/${t}.${e.dkim.selector}.pem`}function re(e){return`${e.storagePath}/smtp.db`}function Te(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${C(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${C(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${C(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 = ${C(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${C(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 = ${C(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${C(e.webhookUrl)}`);return t.push(""),t.join(`
2
2
  `)}function he(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${re(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 o=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${o.join(",")}`)}}return t.push(""),t.join(`
3
3
  `)}function Ee(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=${m}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${m}/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} ${m}`,"","[Install]","WantedBy=multi-user.target",""].join(`
4
- `)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${m}/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} ${m}/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" ${F}/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 ne(e){if(!e.enabled)return[];return[...et(ge(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${m}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${m}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(re(e))}`,`cat > ${m}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Te(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${m}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${m}/mail.env`,`chmod 0640 ${m}/mail.env`,`chown root:${T} ${m}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${U}/pantry/.bin`,W=15306,K=15991,B=15999,se=16101,V=2379,E="/var/lib/vitess",X=100;function wi(e){return e===!0||typeof e==="object"&&e!==null}function Re(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Ce(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 S="vitess",Pe=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",z=new Map;function j(e){return`${ce}/${e}.sh`}function D(e,t){return z.set(e,be(t)),`/bin/sh ${j(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of z)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${U}`,`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
- `)}function L(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=${S}`,`Group=${S}`,`Environment="PATH=${Pe}"`,`Environment="VTDATAROOT=${E}"`,...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 ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??W,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return L({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${B}`])})}function Le(){return L({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${V}`,`--advertise-client-urls http://127.0.0.1:${V}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function Q(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${V}`}`,"--topo-global-root /vitess/global"]}function Oe(e){let t=!e.etcdEndpoint;return L({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...Q(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${B}`,`--port ${B+1}`])})}function Ae(e,t,r){let n=e.cell??"zone1";return L({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...Q(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return L({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/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 ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function Ie(e){let t=e.cell??"zone1";return L({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...Q(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function ke(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${V}`,n=`${g}/vtctldclient --server 127.0.0.1:${B}`,o=[`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 ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${_(s.name)}`,"fi");let p=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${l}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${U} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${_(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 xo(e){if(!wi(e))return[];let t=Re(e),r=t.mode==="combo";z.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",...et(Ce(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 ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Le()]);o.push(["vitess-vtctld",Oe(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",Ie(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Ae(t,s.name,c)]);for(let[s,c]of o)n.push(...ie(s,c));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)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 ${S}:${S} ${x}; chmod 0600 ${x}; fi`,...ke(t),...ae(t)),n}var Ne=new Set(["singlestore","vitess"]);function Ai(e){if(e?.engine&&Ne.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Pr(e,t="psql"){let r=e?.port??5432;if(Ai(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 v(e){return e===!0||typeof e==="object"&&e!=null}function Me(e){let t=[],r=[];if(v(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(v(e.mariadb))t.push(A.mariadb),r.push("mariadb");if(v(e.postgres))t.push("postgresql.org"),r.push("postgres");if(v(e.redis))t.push("redis.io"),r.push("redis");if(v(e.memcached))t.push("memcached.org"),r.push("memcached");if(v(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function _o(e={},t={}){let r=Me(e),n=xo(e.vitess),o=t.mail?ne(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...et(r.packages),...No(r.services),...n,...o]}function vt(e,t={}){if(!e?.name)return[];if(!Ai(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=v(t.postgres)||e.engine==="postgres",c=v(t.mariadb)||e.engine==="mariadb",p=v(t.mysql)||e.engine==="mysql";if(s&&!p&&!c){let a=(d)=>`"${d.replace(/"/g,'""')}"`,b=(d)=>`'${d.replace(/'/g,"''")}'`,O=(d,N)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${b(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${b(N)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${b(N)};`," END IF;","END $$;"],I=(d)=>{let N=d.databases&&d.databases.length>0?d.databases:[r],w=[];for(let G of N)if(d.access==="readonly")w.push(`GRANT CONNECT ON DATABASE ${a(G)} TO ${a(d.username)};`,`\\connect ${a(G)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else w.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(G)} TO ${a(d.username)};`);return w},k=e.users||[],Se=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Pr(e)} <<'TS_CLOUD_PG_EOF'`,...O(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${b(r)})\\gexec`,...k.flatMap((d)=>[...O(d.username,d.password),...I(d)]),"TS_CLOUD_PG_EOF",...Be(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),R=(a)=>{let b=a.databases&&a.databases.length>0?a.databases:[r],O=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",I=[`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 k of b)I.push(`GRANT ${O} ON \`${i(k)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${O} ON \`${i(k)}\`.* TO '${f(a.username)}'@'localhost';`);return I},u=e.users||[];return[St(),`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 \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...R({username:n,password:o}),...u.flatMap(R),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Be(e){return[`${Pr(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 Hc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),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",pe="/etc/cron.d/ts-cloud-backups",un="/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",o=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${o},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
4
+ `)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${m}/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} ${m}/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" ${F}/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 ne(e){if(!e.enabled)return[];return[...et(ge(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${m}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${m}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(re(e))}`,`cat > ${m}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,Te(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${m}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,he(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${m}/mail.env`,`chmod 0640 ${m}/mail.env`,`chown root:${T} ${m}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,Ee(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${U}/pantry/.bin`,W=15306,K=15991,B=15999,se=16101,V=2379,E="/var/lib/vitess",X=100;function wi(e){return e===!0||typeof e==="object"&&e!==null}function Re(e){return typeof e==="object"&&e!==null?e:{}}function _(e){return`'${String(e).split("'").join("'\\''")}'`}function Ce(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 S="vitess",Pe=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ce="/usr/local/lib/vitess",z=new Map;function j(e){return`${ce}/${e}.sh`}function b(e,t){return z.set(e,be(t)),`/bin/sh ${j(e)}`}function oe(){let e=[`mkdir -p ${ce}`];for(let[t,r]of z)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function be(e){return["#!/bin/sh","set -e",`cd ${U}`,`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
+ `)}function D(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=${S}`,`Group=${S}`,`Environment="PATH=${Pe}"`,`Environment="VTDATAROOT=${E}"`,...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 ie(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function De(e){let t=e.cell??"zone1",r=e.vtgatePort??W,o=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((p)=>`shards:{name:"${p}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return D({description:"Vitess (vtcombo, single-process development stack)",execStart:b("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${_(o)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${B}`])})}function Le(){return D({description:"etcd (Vitess topology store)",execStart:b("etcd",[`${g}/etcd`,`--data-dir ${E}/etcd`,`--listen-client-urls http://127.0.0.1:${V}`,`--advertise-client-urls http://127.0.0.1:${V}`]),execStartPre:[`+/bin/mkdir -p ${E}/etcd`,`+/bin/chown ${S}:${S} ${E}/etcd`]})}function Q(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${V}`}`,"--topo-global-root /vitess/global"]}function Oe(e){let t=!e.etcdEndpoint;return D({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:b("vtctld",[`${g}/vtctld`,...Q(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${B}`,`--port ${B+1}`])})}function Ae(e,t,r){let n=e.cell??"zone1";return D({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:b("vttablet",[`${g}/vttablet`,...Q(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${_("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${se}`,`--grpc-port ${se+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Ue(e){return D({description:"Vitess mysqlctld (managed mysqld)",execStart:b("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${E}`,`+/bin/chown ${S}:${S} ${E}`]})}var le="/etc/vitess/auth.json",A="/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 ${A} ] && [ "$(cat ${A})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${S} -g ${S} -m 0600 "$VTESS_AUTH_TMP" ${le}`,'rm -f "$VTESS_AUTH_TMP"']}function Ie(e){let t=e.cell??"zone1";return D({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:b("vtgate",[`${g}/vtgate`,...Q(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${_("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${le}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function ke(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${V}`,n=`${g}/vtctldclient --server 127.0.0.1:${B}`,o=[`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 ${_(t)}; then`,` ${n} AddCellInfo --root ${_(`/vitess/${t}`)} --server-address ${_(r)} ${_(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";o.push(`if ! ${n} GetKeyspace ${_(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${_(s.name)}`,"fi");let p=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let i=`${s.name}/${l}`;o.push("for i in $(seq 1 90); do",` if ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${_(i)} --new-primary ${_(p)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${_(i)} ${_(p)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${_(i)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${i}" >&2; exit 1`,"fi")}o.push(`${n} RebuildKeyspaceGraph ${_(s.name)} >/dev/null`)}return o}function ae(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${U} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${_(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${_(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 xo(e){if(!wi(e))return[];let t=Re(e),r=t.mode==="combo";z.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",...et(Ce(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 ${S} >/dev/null 2>&1 || useradd --system --home-dir ${E} --shell /usr/sbin/nologin ${S}`,`mkdir -p ${E}`,`chown -R ${S}:${S} ${E}`];if(r)return n.push(...ie("vitess-vtcombo",De(t)),...oe(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ae(t)),n;n.push(...xe(t));let o=[];if(!t.etcdEndpoint)o.push(["vitess-etcd",Le()]);o.push(["vitess-vtctld",Oe(t)],["vitess-mysqlctld",Ue(t)],["vitess-vtgate",Ie(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])o.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Ae(t,s.name,c)]);for(let[s,c]of o)n.push(...ie(s,c));n.push(...oe()),n.push("systemctl daemon-reload");for(let[s]of o)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" > ${A}; chown ${S}:${S} ${A}; chmod 0600 ${A}; fi`,...ke(t),...ae(t)),n}var Ne=new Set(["singlestore","vitess"]);function Ai(e){if(e?.engine&&Ne.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function Pr(e,t="psql"){let r=e?.port??5432;if(Ai(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 v(e){return e===!0||typeof e==="object"&&e!=null}function Me(e){let t=[],r=[];if(v(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(v(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(v(e.postgres))t.push("postgresql.org"),r.push("postgres");if(v(e.redis))t.push("redis.io"),r.push("redis");if(v(e.memcached))t.push("memcached.org"),r.push("memcached");if(v(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function _o(e={},t={}){let r=Me(e),n=xo(e.vitess),o=t.mail?ne(t.mail):[];if(r.packages.length===0)return[...n,...o];return[...et(r.packages),...No(r.services),...n,...o]}function vt(e,t={}){if(!e?.name)return[];if(!Ai(e))return[];let r=e.name,n=e.username||r,o=e.password||"",s=v(t.postgres)||e.engine==="postgres",c=v(t.mariadb)||e.engine==="mariadb",p=v(t.mysql)||e.engine==="mysql";if(s&&!p&&!c){let a=(d)=>`"${d.replace(/"/g,'""')}"`,P=(d)=>`'${d.replace(/'/g,"''")}'`,L=(d,N)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${P(d)}) THEN`,` CREATE ROLE ${a(d)} LOGIN PASSWORD ${P(N)};`," ELSE",` ALTER ROLE ${a(d)} LOGIN PASSWORD ${P(N)};`," END IF;","END $$;"],x=(d)=>{let N=d.databases&&d.databases.length>0?d.databases:[r],w=[];for(let G of N)if(d.access==="readonly")w.push(`GRANT CONNECT ON DATABASE ${a(G)} TO ${a(d.username)};`,`\\connect ${a(G)}`,`GRANT USAGE ON SCHEMA public TO ${a(d.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(d.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(d.username)};`,"\\connect postgres");else w.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(G)} TO ${a(d.username)};`);return w},k=e.users||[],Se=e.port??5432;return[St(),`for i in $(seq 1 30); do pg_isready -p ${Se} -q && break; sleep 2; done`,`${Pr(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,o),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${P(r)})\\gexec`,...k.flatMap((d)=>[...L(d.username,d.password),...x(d)]),"TS_CLOUD_PG_EOF",...Be(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",i=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),R=(a)=>{let P=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",x=[`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 k of P)x.push(`GRANT ${L} ON \`${i(k)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${i(k)}\`.* TO '${f(a.username)}'@'localhost';`);return x},u=e.users||[];return[St(),`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 \`${i(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...R({username:n,password:o}),...u.flatMap(R),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Be(e){return[`${Pr(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 Hc(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",o=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(o),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",pe="/etc/cron.d/ts-cloud-backups",un="/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",o=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${o},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
7
7
  `)}function He(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
8
  `)}function Oo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",o=He(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'`,o.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${un} <<'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 start --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${un}`,`cat > ${pe} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${un} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${pe}`]}function Ge(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function Ri(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",o=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?`${Pr(e)} -d "${r}"`:`mysql --socket=${Ge(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',o,'[ -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 $o=["storage",".env"],Ii=4;function y(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function Gs(e){return`${y(e)}/deploy-history.log`}function qe(e,t){return`${y(e)}/deploys/${t}.log`}function ue(e){return`${y(e)}/shared-paths`}function Lo(e){return`${e.shared}/stx-images`}function Vt(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 Ws(e){return typeof e==="string"?e:e.path}function qc(e){let t=new Map;for(let r of e)t.set(Ws(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 Pi(e,t=$o){let r=[`mkdir -p ${e.releases} ${e.shared} ${Lo(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:p}of n){if(!p)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 o=ue(e.base);return r.push(`mkdir -p ${y(e.base)}`,`cat > ${o} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Ks(e,t=900){let r=`${y(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 Js(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 Xs(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 Qs(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=$o){let r=[];for(let n of t){let{path:o,target:s,seed:c}=$e(e,n),p=`${e.release}/${o}`,l=[`rm -rf ${p}`,`mkdir -p "$(dirname ${p})"`,`ln -sfn ${s} ${p}`];if(c){if(o!==".env"&&de(o))r.push(...Ke(p,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((i)=>` ${i}`),"fi")}return r}function je(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 pn(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function ee(e){return`${y(e)}/previous-release`}function Ys(e,t="TS_CLOUD_PREV_CURRENT"){let r=ee(e.base);return[`if [ -n "\${${t}:-}" ] && [ -d "$${t}" ] && [ "$(readlink -f "$${t}")" != "$(readlink -f ${e.release})" ]; then mkdir -p ${y(e.base)}; basename "$${t}" > ${r}; fi`]}function _e(e,t){let r=ee(e.base);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,...t?[`TS_CLOUD_RB_TARGET=${e.releases}/${t}`]:["TS_CLOUD_RB_TARGET=",`if [ -f ${r} ]; then TS_CLOUD_REC="${e.releases}/$(cat ${r})"; if [ -d "$TS_CLOUD_REC" ] && [ "$(readlink -f "$TS_CLOUD_REC")" != "$TS_CLOUD_CURRENT" ]; then TS_CLOUD_RB_TARGET="$TS_CLOUD_REC"; fi; fi`,`[ -n "$TS_CLOUD_RB_TARGET" ] || TS_CLOUD_RB_TARGET=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`],'[ -n "$TS_CLOUD_RB_TARGET" ] && [ -d "$TS_CLOUD_RB_TARGET" ] || { echo "no release to roll back to (looked for ${TS_CLOUD_RB_TARGET:-a previous release})" >&2; exit 1; }','[ "$(readlink -f "$TS_CLOUD_RB_TARGET")" != "$TS_CLOUD_CURRENT" ] || { echo "$(basename "$TS_CLOUD_RB_TARGET") is already the live release" >&2; exit 1; }','TS_CLOUD_RB_ID=$(basename "$TS_CLOUD_RB_TARGET")']}function Gc(e,t={}){return[..._e(e,t.to),'echo "would roll back from $(basename "${TS_CLOUD_CURRENT:-none}") to $TS_CLOUD_RB_ID (dry run: nothing changed)"']}function Wc(e,t={}){let r=Math.max(1,t.gateSeconds??5),n=t.systemdDir??"/etc/systemd/system",o=[`ln -sfn "$TS_CLOUD_RB_TARGET" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,`rm -f ${ee(e.base)}`,'echo "rolled back to $TS_CLOUD_RB_ID"'],s=[..._e(e,t.to),...je(e,'"$TS_CLOUD_RB_TARGET"')];if(!t.unitBase)return[...s,...o];let c=t.unitBase,p=`${c}@\${TS_CLOUD_RB_ID}.service`;return[...s,`if [ -f ${n}/${c}@.service ]; then`,` systemctl start "${p}"`,` for TS_CLOUD_I in $(seq 1 ${r}); do sleep 1; systemctl is-active --quiet "${p}" || { echo "the release rolled back to, $TS_CLOUD_RB_ID, did not stay up; the current release keeps serving" >&2; journalctl -u "${p}" -n 30 --no-pager >&2 || true; systemctl stop "${p}" 2>/dev/null || true; exit 1; }; done`,...o.map((l)=>` ${l}`),` systemctl enable "${p}" 2>/dev/null || true`,` systemctl list-units --plain --no-legend --type=service "${c}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${c}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done`,`elif [ -f ${n}/${c}.service ]; then`,...o.map((l)=>` ${l}`),` systemctl restart ${c}.service`,"else",...o.map((l)=>` ${l}`),"fi"]}function mn(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 We(e){return`${y(e)}/owner`}function Zs(e,t){let r=We(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 Uo(e,t){let r=y(e),n=qe(e,t.releaseId),o=Gs(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",p=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${p} 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" >> ${o}`,"}","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{J,Ei,zs,P,ko,Hs,qs,Vc,zc,U,Ir,St,et,No,wi,xo,Ai,Pr,_o,vt,Hc,un,Oo,Ri,$o,Ii,Gs,Lo,Vt,Ws,qc,Pi,Ks,Js,Xs,Qs,Mo,pn,Ys,Gc,Wc,mn,Zs,Uo};
9
+ export{J,Ei,zs,I,ko,Hs,qs,Vc,zc,U,Ir,St,et,No,wi,xo,Ai,Pr,_o,vt,Hc,un,Oo,Ri,$o,Ii,Gs,Lo,Vt,Ws,qc,Pi,Ks,Js,Xs,Qs,Mo,pn,Ys,Gc,Wc,mn,Zs,Uo};
@@ -1,3 +1,3 @@
1
- import{xe,pa,Ni,Ha,En,Bi,qa,Ga,ec,tc}from"./chunk-dj03v81n.js";import{n,r,a,e,d,i,Ce}from"./chunk-6y6g726g.js";import{p}from"./chunk-psvqpztv.js";import{v}from"./chunk-xdk0gmxt.js";import{I}from"./chunk-de69nra4.js";import{g}from"./chunk-12x968en.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as Se}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new p(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function k(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:xe(t,s),artifactBucket:pa(c,s),assetsBucket:Ni(c,s)}}function bt(t,s){let o=k(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let u=l?.code||l?.name||"",m=String(l?.message||"");if(u==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function ye(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((u)=>({envName:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:u})):Object.entries(t.secrets).map(([u,m])=>({envName:u,secretId:m}));if(Array.isArray(t.secrets)){let u=new Map;for(let{envName:f,secretId:S}of l)u.set(f,[...u.get(f)??[],S]);let m=[...u.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,R])=>`${S} ← ${R.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:u,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let R=JSON.parse(S);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[w,N]of Object.entries(R))c[w]=String(N);continue}}catch{}c[u]=S}return c}function Kd(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function _s(t,s,o,c,l,u,m,f={}){let S=t.kind==="php"?ec({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...u?{ASSET_URL:u}:{},...t.env??{},...l}}function Re(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function he(t,s,o,c,l=!1){let u=0;for(let m of oe(o)){let f=Se(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:Re(m),cacheControl:"public, max-age=31536000, immutable"}),u++}return u}function Io(t,s){let o=Object.entries(s).reduce((c,[l,u])=>c+Buffer.byteLength(`${l}=${u}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,u])=>[l,Buffer.byteLength(`${l}=${u}`,"utf8")]).sort((l,u)=>u[1]-l[1]).slice(0,5).map(([l,u])=>`${l} (${u}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){Io(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function sm(t,s,o={}){let c=k(t,s),{app:l,slug:u,region:m,stackName:f,artifactBucket:S}=c,R=o.projectRoot??process.cwd();i(`Deploying serverless app: ${u} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let w=new g(m),N=new v(m),T=new I(m),P=l.kind==="php",O=l.packaging==="image",h=Bi(l),V,E,b,Y,M=[];if(O&&h.usesLayer&&h.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${h.kind}${h.kind==="node"?` ${h.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){d("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-z8scg2vy.js"),C=await y({app:l,projectRoot:R,region:m,repository:`${u}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});V=C.handlers,E={kind:"image",imageUri:C.imageUri},b=C.tag,M.push({ParameterKey:"ImageUri",ParameterValue:C.imageUri})}else{d("Packaging application");let y=P?tc({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await En({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),C=Ha(u,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,b=y.sha256,h.usesLayer){let x=h.layerEnvVar?process.env[h.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=h.layerKind==="php"?"serverless:build-php-layer":h.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${h.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${h.layerEnvVar} env var (build one with \`cloud ${ge}\`)${h.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await w.bucketExists(S))d(`Creating artifact bucket ${S}`),await w.createBucket(S);if(await w.headObject(S,C).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else d("Uploading artifact"),await w.putObject({bucket:S,key:C,body:y.zip,contentType:"application/zip"});E={kind:"zip",bucket:S,key:C},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:C})}let A=Ga({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(A.template),re=["CAPABILITY_NAMED_IAM"],L=await N.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))d("Waiting for an in-progress stack delete to finish"),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))d(`Deleting unusable stack (status ${L}) before recreate`),await N.deleteStack(f),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;d(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await N.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await N.waitForStack(f,"stack-update-complete");else await N.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await N.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await N.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(R,l.assets);if(de(y)){let C=l.assetDomain||Q.AssetsCdnDomain;B=C?`https://${C}/${b}`:void 0,d(`Syncing assets from ${l.assets}`);let D=await he(w,c.assetsBucket,y,b,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}d("Resolving secrets");let _=await ye(l,m);if(l.database?.connection==="aurora-serverless")try{let C=await new K(m).getSecretValue({SecretId:`${u}/${s}/db`}),D=JSON.parse(C.SecretString??"{}");if(D.username)_.DB_USERNAME=D.username;if(D.password)_.DB_PASSWORD=D.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await w.bucketExists(S))await w.createBucket(S);let H=await G(w,S,u,s),F={},Z=A.queueNames[0],ee=Kd(l,Q);if(d("Activating functions"),F.http=_s(l,c,s,"http",_,B,Z,ee),await U(T,A.functionNames.http,F.http,E),F.cli=_s(l,c,s,"cli",_,B,Z,ee),await U(T,A.functionNames.cli,F.cli,E),A.queueNames.length)F.queue=_s(l,c,s,"queue",_,B,Z,ee),await U(T,A.functionNames.queue,F.queue,E);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(d("Publishing versions + flipping live alias"),W.http=await X(T,A.functionNames.http),W.cli=await X(T,A.functionNames.cli),A.queueNames.length)W.queue=await X(T,A.functionNames.queue)}if(await ae(w,S,u,s,{sha:b,code:E,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:A.functionNames.http,cli:A.functionNames.cli,...A.queueNames.length?{queue:A.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){d("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let C=await T.invoke({FunctionName:A.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(C.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${C.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){d("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Ce(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${b.slice(0,12)}`].filter(Boolean).join(`
2
- `),"green")}async function Os(t,s){let o=k(t,s),c=new g(o.region),l=new I(o.region),u=await G(c,o.artifactBucket,o.slug,s);if(!u)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${u.sha.slice(0,12)}`);for(let[m,f]of Object.entries(u.functionNames)){if(!f)continue;d(`Re-activating ${m} (${f})`),await U(l,f,u.functionEnv[m]??{},u.code);let S=u.functionVersions?.[m];if(S)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function $s(t,s){let o=k(t,s),c=new g(o.region),l=new I(o.region),u=await G(c,o.artifactBucket,o.slug,s);if(!u?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${u.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(u.functionNames)){if(!f)continue;d(`Restoring ${m} (${f})`);let S=u.previousFunctionEnv?.[m]??u.functionEnv[m]??{};await U(l,f,S,u.previousCode);let R=u.previousFunctionVersions?.[m];if(R)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:R}))}await ae(c,o.artifactBucket,o.slug,s,{...u,sha:u.previousSha??u.sha,code:u.previousCode,functionEnv:u.previousFunctionEnv??u.functionEnv,functionVersions:u.previousFunctionVersions??u.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function Po(t,s,o,c){let l=k(t,s),u=new I(l.region),m=`${l.slug}-${s}-http`,S={...(await u.getFunction(m)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=o?"1":"0",o&&c)S.MAINTENANCE_BYPASS_SECRET=c;if(!o)delete S.MAINTENANCE_BYPASS_SECRET;if(await q(()=>u.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await u.waitForFunctionActive(m,120),await X(u,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Bt(t,s,o){let c=k(t,s),l=new I(c.region),u=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:u,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"});if(m.FunctionError)throw Error(`Command failed: ${m.Payload}`);return m.Payload??""}var ce=(t,s)=>`commands/${t}/${s}/history.json`,ve=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function am(t,s,o){let c=k(t,s),l=new I(c.region),u=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:u,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",R=-1;try{let w=new g(c.region);if(await w.bucketExists(c.artifactBucket)){let N=await le(w,c.artifactBucket,c.slug,s);R=N.reduce((T,P)=>Math.max(T,P.id),0)+1,N.push({id:R,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await w.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:N.slice(-ve)})}}catch{}if(m.FunctionError)throw Error(`Command failed${R>0?` (#${R})`:""}: ${f}`);return{id:R,status:S,output:f}}async function Jd(t,s){let o=k(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function cm(t,s,o){let c=await Jd(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function lm(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Bt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function z(t,s){let o=k(t,s),c=new v(o.region),l=new I(o.region),u=new g(o.region),m="not deployed",f={};try{let{Stacks:O}=await c.describeStacks({stackName:o.stackName});m=O?.[0]?.StackStatus??m;for(let h of O?.[0]?.Outputs??[])if(h.OutputKey)f[h.OutputKey]=h.OutputValue??""}catch{}let S=qa(o.app,o.slug,s),R=o.app.provisionedConcurrency??0,w=["http","cli",...S.length?["queue"]:[]],N=`${o.slug}-${s}`,T=[];for(let O of w){let h=`${N}-${O}`,V={mode:O,name:h,version:"$LATEST"};if(R>0){let E=await l.getAlias(h,"live").catch(()=>null);if(E?.FunctionVersion){V.version=E.FunctionVersion;let b=await l.getProvisionedConcurrencyConfig(h,"live").catch(()=>null);if(b)V.provisioned={status:b.Status??"-",allocated:b.AllocatedProvisionedConcurrentExecutions??0,requested:b.RequestedProvisionedConcurrentExecutions??0}}}T.push(V)}let P=await G(u,o.artifactBucket,o.slug,s).catch(()=>null);return{slug:o.slug,environment:s,region:o.region,stackStatus:m,endpoint:f.HttpApiEndpoint,assetUrl:P?.assetUrl,scheduler:o.app.scheduler??"on",queues:S,provisionedConcurrency:R,functions:T,lastRelease:P?{sha:P.sha,timestamp:P.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function Ls(t,s,o,c){let l=k(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:u}=await import("./chunk-5f1n5d80.js"),m=new u(l.region),f=ue(l.slug,s);d(`Scaling ${f} → ${o}–${c} ACUs`),await m.modifyDBCluster({DBClusterIdentifier:f,ServerlessV2ScalingConfiguration:{MinCapacity:o,MaxCapacity:c},ApplyImmediately:!0}),n(`Scaling applied to ${f} (takes effect shortly).`)}async function dm(t,s,o){let c=k(t,s);if(c.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!o.toTime&&!o.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:l}=await import("./chunk-5f1n5d80.js"),u=new l(c.region),m=ue(c.slug,s),f=o.latest?"latest":o.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),S=o.target??`${m}-restore-${f}`;d(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await u.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),d("Waiting for the restored cluster to be ready");for(let R=0;R<120;R++){let{DBClusters:w}=await u.describeDBClusters({DBClusterIdentifier:S}),N=w?.[0]?.Status;if(N&&N!=="creating")break;await new Promise((T)=>setTimeout(T,15000))}return d("Adding a writer instance"),await u.createDBInstance({DBInstanceIdentifier:`${S}-1`,DBClusterIdentifier:S,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),n(`Restore complete → cluster ${S} with writer ${S}-1. Point an env's database at it once available.`),S}
1
+ import{xe,pa,Ni,Ha,En,Bi,qa,Ga,ec,tc}from"./chunk-dj03v81n.js";import{n,r,a,e,d,i,Ce}from"./chunk-6y6g726g.js";import{p}from"./chunk-psvqpztv.js";import{v}from"./chunk-xdk0gmxt.js";import{P}from"./chunk-vhyp4xj0.js";import{g}from"./chunk-12x968en.js";import{existsSync as de,readdirSync as me,readFileSync as pe,statSync as fe}from"node:fs";import{join as ne,relative as Se}from"node:path";class K{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new p(void 0,{profile:s})}async createSecret(t){let s={Name:t.Name};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.Tags&&t.Tags.length>0)s.Tags=t.Tags;if(t.AddReplicaRegions&&t.AddReplicaRegions.length>0)s.AddReplicaRegions=t.AddReplicaRegions;if(t.ForceOverwriteReplicaSecret!==void 0)s.ForceOverwriteReplicaSecret=t.ForceOverwriteReplicaSecret;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CreateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,ReplicationStatus:o.ReplicationStatus}}async updateSecret(t){let s={SecretId:t.SecretId,ClientRequestToken:t.ClientRequestToken||crypto.randomUUID()};if(t.Description)s.Description=t.Description;if(t.KmsKeyId)s.KmsKeyId=t.KmsKeyId;if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UpdateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async putSecretValue(t){let s={SecretId:t.SecretId};if(t.SecretBinary)s.SecretBinary=t.SecretBinary;if(t.SecretString)s.SecretString=t.SecretString;if(t.VersionStages&&t.VersionStages.length>0)s.VersionStages=t.VersionStages;s.ClientRequestToken=t.ClientRequestToken||crypto.randomUUID();let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,VersionStages:o.VersionStages}}async getSecretValue(t){let s={SecretId:t.SecretId};if(t.VersionId)s.VersionId=t.VersionId;if(t.VersionStage)s.VersionStage=t.VersionStage;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetSecretValue","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId,SecretBinary:o.SecretBinary,SecretString:o.SecretString,VersionStages:o.VersionStages,CreatedDate:o.CreatedDate}}async describeSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DescribeSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return this.parseSecret(o)}async listSecrets(t){let s={};if(t?.MaxResults)s.MaxResults=t.MaxResults;if(t?.NextToken)s.NextToken=t.NextToken;if(t?.Filters&&t.Filters.length>0)s.Filters=t.Filters;if(t?.SortOrder)s.SortOrder=t.SortOrder;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.ListSecrets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{SecretList:o.SecretList?.map((c)=>this.parseSecret(c)),NextToken:o.NextToken}}async deleteSecret(t){let s={SecretId:t.SecretId};if(t.RecoveryWindowInDays!==void 0)s.RecoveryWindowInDays=t.RecoveryWindowInDays;if(t.ForceDeleteWithoutRecovery!==void 0)s.ForceDeleteWithoutRecovery=t.ForceDeleteWithoutRecovery;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,DeletionDate:o.DeletionDate}}async restoreSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RestoreSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async rotateSecret(t){let s={SecretId:t.SecretId};if(t.ClientRequestToken)s.ClientRequestToken=t.ClientRequestToken;if(t.RotationLambdaARN)s.RotationLambdaARN=t.RotationLambdaARN;if(t.RotationRules)s.RotationRules=t.RotationRules;if(t.RotateImmediately!==void 0)s.RotateImmediately=t.RotateImmediately;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.RotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,VersionId:o.VersionId}}async cancelRotateSecret(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.CancelRotateSecret","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async getResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.GetResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name,ResourcePolicy:o.ResourcePolicy}}async putResourcePolicy(t){let s={SecretId:t.SecretId,ResourcePolicy:t.ResourcePolicy};if(t.BlockPublicPolicy!==void 0)s.BlockPublicPolicy=t.BlockPublicPolicy;let o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.PutResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async deleteResourcePolicy(t){let s={SecretId:t},o=await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.DeleteResourcePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)});return{ARN:o.ARN,Name:o.Name}}async tagResource(t){let s={SecretId:t.SecretId,Tags:t.Tags};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async untagResource(t){let s={SecretId:t.SecretId,TagKeys:t.TagKeys};await this.client.request({service:"secretsmanager",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"secretsmanager.UntagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(s)})}async setString(t,s,o){try{let c=await this.putSecretValue({SecretId:t,SecretString:s});return{ARN:c.ARN,VersionId:c.VersionId}}catch(c){if(c.code==="ResourceNotFoundException"){let l=await this.createSecret({Name:t,SecretString:s,Description:o?.description,KmsKeyId:o?.kmsKeyId,Tags:o?.tags});return{ARN:l.ARN,VersionId:l.VersionId}}throw c}}async setJson(t,s,o){return this.setString(t,JSON.stringify(s),o)}async getString(t){return(await this.getSecretValue({SecretId:t})).SecretString}async getJson(t){let s=await this.getString(t);if(s)return JSON.parse(s);return}async listAll(){let t=[],s;do{let o=await this.listSecrets({NextToken:s});if(o.SecretList)t.push(...o.SecretList);s=o.NextToken}while(s);return t}parseSecret(t){return{ARN:t.ARN,Name:t.Name,Description:t.Description,KmsKeyId:t.KmsKeyId,RotationEnabled:t.RotationEnabled,RotationLambdaARN:t.RotationLambdaARN,RotationRules:t.RotationRules,LastRotatedDate:t.LastRotatedDate,LastChangedDate:t.LastChangedDate,LastAccessedDate:t.LastAccessedDate,DeletedDate:t.DeletedDate,NextRotationDate:t.NextRotationDate,Tags:t.Tags,SecretVersionsToStages:t.SecretVersionsToStages,CreatedDate:t.CreatedDate,PrimaryRegion:t.PrimaryRegion}}}function k(t,s){let o=t.environments?.[s]?.app;if(!o)throw Error(`No serverless app configured for environment '${s}'. Add environments.${s}.app to your config.`);let c=t.project.slug,l=t.environments?.[s]?.region||t.project.region||"us-east-1";return{app:o,slug:c,region:l,stackName:xe(t,s),artifactBucket:pa(c,s),assetsBucket:Ni(c,s)}}function bt(t,s){let o=k(t,s),c=`${o.slug}-${s}`;return{region:o.region,slug:o.slug,stackName:o.stackName,functions:{http:`${c}-http`,queue:`${c}-queue`,cli:`${c}-cli`}}}async function q(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let u=l?.code||l?.name||"",m=String(l?.message||"");if(u==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(m)){o=l,await new Promise((f)=>setTimeout(f,3000));continue}throw l}throw o}var ie=(t,s)=>`releases/${t}/${s}/current.json`;async function G(t,s,o,c){try{return await t.getObjectJson(s,ie(o,c))}catch{return null}}async function ae(t,s,o,c,l){await t.putObjectJson(s,ie(o,c),l)}async function ye(t,s){if(!t.secrets)return{};let o=new K(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((u)=>({envName:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:u})):Object.entries(t.secrets).map(([u,m])=>({envName:u,secretId:m}));if(Array.isArray(t.secrets)){let u=new Map;for(let{envName:f,secretId:S}of l)u.set(f,[...u.get(f)??[],S]);let m=[...u.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,R])=>`${S} ← ${R.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${f}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:u,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let R=JSON.parse(S);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[w,N]of Object.entries(R))c[w]=String(N);continue}}catch{}c[u]=S}return c}function Kd(t,s){let o={},c=s.DbProxyEndpoint||s.DbEndpoint;if(c)o.DB_CONNECTION="mysql",o.DB_HOST=c,o.DB_PORT="3306",o.DB_DATABASE=o.DB_DATABASE||"app";if(s.CacheEndpoint){if(o.REDIS_HOST=s.CacheEndpoint,o.REDIS_PORT="6379",t.cache?.driver==="elasticache")o.CACHE_STORE="redis",o.CACHE_DRIVER="redis",o.SESSION_DRIVER="redis"}return o}function _s(t,s,o,c,l,u,m,f={}){let S=t.kind==="php"?ec({cacheDriver:t.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:c,TSCLOUD_ENV:o,MAINTENANCE_MODE:"0",...t.octane?{TSCLOUD_OCTANE:"1"}:{},...t.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...t.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...S,...f,...s.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${s.slug}-${o}-cache`}:{},...m?{TSCLOUD_QUEUE:m,SQS_QUEUE:m}:{},...u?{ASSET_URL:u}:{},...t.env??{},...l}}function Re(t){let s=t.slice(t.lastIndexOf(".")).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".txt":"text/plain",".map":"application/json"}[s]??"application/octet-stream"}function*oe(t){for(let s of me(t)){let o=ne(t,s);if(fe(o).isDirectory())yield*oe(o);else yield o}}async function he(t,s,o,c,l=!1){let u=0;for(let m of oe(o)){let f=Se(o,m).replace(/\\/g,"/");if(!l&&f.split("/").some((S)=>S.startsWith(".")))continue;await t.putObject({bucket:s,key:`${c}/${f}`,body:pe(m),contentType:Re(m),cacheControl:"public, max-age=31536000, immutable"}),u++}return u}function Io(t,s){let o=Object.entries(s).reduce((c,[l,u])=>c+Buffer.byteLength(`${l}=${u}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,u])=>[l,Buffer.byteLength(`${l}=${u}`,"utf8")]).sort((l,u)=>u[1]-l[1]).slice(0,5).map(([l,u])=>`${l} (${u}B)`).join(", ");throw Error(`${t}: environment variables total ${o}B, over AWS's 4096B limit (${o-4096}B too large). Largest: ${c}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function U(t,s,o,c){Io(s,o),await q(()=>t.updateFunctionConfiguration({FunctionName:s,Environment:{Variables:o}})),await t.waitForFunctionActive(s,120);let l=c.kind==="image"?{FunctionName:s,ImageUri:c.imageUri}:{FunctionName:s,S3Bucket:c.bucket,S3Key:c.key};await q(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await q(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await q(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function sm(t,s,o={}){let c=k(t,s),{app:l,slug:u,region:m,stackName:f,artifactBucket:S}=c,R=o.projectRoot??process.cwd();i(`Deploying serverless app: ${u} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let w=new g(m),N=new v(m),T=new P(m),D=l.kind==="php",O=l.packaging==="image",h=Bi(l),V,E,b,Y,M=[];if(O&&h.usesLayer&&h.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${h.kind}${h.kind==="node"?` ${h.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){d("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-z8scg2vy.js"),C=await y({app:l,projectRoot:R,region:m,repository:`${u}-${s}`,skipBuild:o.skipBuild,onStep:(I)=>e(` ${I}`)});V=C.handlers,E={kind:"image",imageUri:C.imageUri},b=C.tag,M.push({ParameterKey:"ImageUri",ParameterValue:C.imageUri})}else{d("Packaging application");let y=D?tc({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await En({projectRoot:R,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),C=Ha(u,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),V=y.handlers,b=y.sha256,h.usesLayer){let x=h.layerEnvVar?process.env[h.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=h.layerKind==="php"?"serverless:build-php-layer":h.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${h.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${h.layerEnvVar} env var (build one with \`cloud ${ge}\`)${h.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await w.bucketExists(S))d(`Creating artifact bucket ${S}`),await w.createBucket(S);if(await w.headObject(S,C).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else d("Uploading artifact"),await w.putObject({bucket:S,key:C,body:y.zip,contentType:"application/zip"});E={kind:"zip",bucket:S,key:C},M.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:C})}let A=Ga({config:t,environment:s,app:l,handlers:V,runtimeLayers:Y}),te=JSON.stringify(A.template),re=["CAPABILITY_NAMED_IAM"],L=await N.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),J=L!==void 0;if(L&&/DELETE_IN_PROGRESS/.test(L))d("Waiting for an in-progress stack delete to finish"),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;else if(L&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(L))d(`Deleting unusable stack (status ${L}) before recreate`),await N.deleteStack(f),await N.waitForStack(f,"stack-delete-complete").catch(()=>{}),J=!1;d(J?"Updating infrastructure stack":"Creating infrastructure stack");try{if(J)await N.updateStack({stackName:f,templateBody:te,parameters:M,capabilities:re}),await N.waitForStack(f,"stack-update-complete");else await N.createStack({stackName:f,templateBody:te,parameters:M,capabilities:re,onFailure:"DELETE"}),await N.waitForStack(f,"stack-create-complete")}catch(y){if(/No updates are to be performed/i.test(String(y?.message)))e("No infrastructure changes");else throw y}let Q=await N.getStackOutputs(f).catch(()=>({})),B;if(l.assets){let y=ne(R,l.assets);if(de(y)){let C=l.assetDomain||Q.AssetsCdnDomain;B=C?`https://${C}/${b}`:void 0,d(`Syncing assets from ${l.assets}`);let I=await he(w,c.assetsBucket,y,b,l.dotFilesAsAssets);e(`Uploaded ${I} asset(s)${B?` → ${B}`:""}`)}else a(`Assets directory not found: ${y}`)}d("Resolving secrets");let _=await ye(l,m);if(l.database?.connection==="aurora-serverless")try{let C=await new K(m).getSecretValue({SecretId:`${u}/${s}/db`}),I=JSON.parse(C.SecretString??"{}");if(I.username)_.DB_USERNAME=I.username;if(I.password)_.DB_PASSWORD=I.password}catch(y){a(`Could not resolve Aurora DB credentials: ${y.message}`)}if(!await w.bucketExists(S))await w.createBucket(S);let H=await G(w,S,u,s),F={},Z=A.queueNames[0],ee=Kd(l,Q);if(d("Activating functions"),F.http=_s(l,c,s,"http",_,B,Z,ee),await U(T,A.functionNames.http,F.http,E),F.cli=_s(l,c,s,"cli",_,B,Z,ee),await U(T,A.functionNames.cli,F.cli,E),A.queueNames.length)F.queue=_s(l,c,s,"queue",_,B,Z,ee),await U(T,A.functionNames.queue,F.queue,E);let se=(l.provisionedConcurrency??0)>0,W={};if(se){if(d("Publishing versions + flipping live alias"),W.http=await X(T,A.functionNames.http),W.cli=await X(T,A.functionNames.cli),A.queueNames.length)W.queue=await X(T,A.functionNames.queue)}if(await ae(w,S,u,s,{sha:b,code:E,previousSha:H?.sha,previousCode:H?.code,previousFunctionEnv:H?.functionEnv,...se?{functionVersions:W,previousFunctionVersions:H?.functionVersions}:{},functionEnv:F,functionNames:{http:A.functionNames.http,cli:A.functionNames.cli,...A.queueNames.length?{queue:A.functionNames.queue}:{}},assetUrl:B,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){d("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let C=await T.invoke({FunctionName:A.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(C.FunctionError)throw r("Deploy hook failed — the new build is ALREADY LIVE."),e(` Roll back with: cloud serverless:rollback --env ${s}`),Error(`Deploy hook failed (${y}): ${C.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){d("Health check");try{let y=await fetch(j,{method:"GET"});e(`GET ${j} → ${y.status}`)}catch(y){a(`Health check could not reach ${j}: ${y.message}`)}}Ce(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${b.slice(0,12)}`].filter(Boolean).join(`
2
+ `),"green")}async function Os(t,s){let o=k(t,s),c=new g(o.region),l=new P(o.region),u=await G(c,o.artifactBucket,o.slug,s);if(!u)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${u.sha.slice(0,12)}`);for(let[m,f]of Object.entries(u.functionNames)){if(!f)continue;d(`Re-activating ${m} (${f})`),await U(l,f,u.functionEnv[m]??{},u.code);let S=u.functionVersions?.[m];if(S)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function $s(t,s){let o=k(t,s),c=new g(o.region),l=new P(o.region),u=await G(c,o.artifactBucket,o.slug,s);if(!u?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${u.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(u.functionNames)){if(!f)continue;d(`Restoring ${m} (${f})`);let S=u.previousFunctionEnv?.[m]??u.functionEnv[m]??{};await U(l,f,S,u.previousCode);let R=u.previousFunctionVersions?.[m];if(R)await q(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:R}))}await ae(c,o.artifactBucket,o.slug,s,{...u,sha:u.previousSha??u.sha,code:u.previousCode,functionEnv:u.previousFunctionEnv??u.functionEnv,functionVersions:u.previousFunctionVersions??u.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function Po(t,s,o,c){let l=k(t,s),u=new P(l.region),m=`${l.slug}-${s}-http`,S={...(await u.getFunction(m)).Configuration?.Environment?.Variables??{}};if(S.MAINTENANCE_MODE=o?"1":"0",o&&c)S.MAINTENANCE_BYPASS_SECRET=c;if(!o)delete S.MAINTENANCE_BYPASS_SECRET;if(await q(()=>u.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await u.waitForFunctionActive(m,120),await X(u,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Bt(t,s,o){let c=k(t,s),l=new P(c.region),u=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:u,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"});if(m.FunctionError)throw Error(`Command failed: ${m.Payload}`);return m.Payload??""}var ce=(t,s)=>`commands/${t}/${s}/history.json`,ve=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function am(t,s,o){let c=k(t,s),l=new P(c.region),u=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:u,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",R=-1;try{let w=new g(c.region);if(await w.bucketExists(c.artifactBucket)){let N=await le(w,c.artifactBucket,c.slug,s);R=N.reduce((T,D)=>Math.max(T,D.id),0)+1,N.push({id:R,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await w.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:N.slice(-ve)})}}catch{}if(m.FunctionError)throw Error(`Command failed${R>0?` (#${R})`:""}: ${f}`);return{id:R,status:S,output:f}}async function Jd(t,s){let o=k(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function cm(t,s,o){let c=await Jd(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function lm(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Bt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function z(t,s){let o=k(t,s),c=new v(o.region),l=new P(o.region),u=new g(o.region),m="not deployed",f={};try{let{Stacks:O}=await c.describeStacks({stackName:o.stackName});m=O?.[0]?.StackStatus??m;for(let h of O?.[0]?.Outputs??[])if(h.OutputKey)f[h.OutputKey]=h.OutputValue??""}catch{}let S=qa(o.app,o.slug,s),R=o.app.provisionedConcurrency??0,w=["http","cli",...S.length?["queue"]:[]],N=`${o.slug}-${s}`,T=[];for(let O of w){let h=`${N}-${O}`,V={mode:O,name:h,version:"$LATEST"};if(R>0){let E=await l.getAlias(h,"live").catch(()=>null);if(E?.FunctionVersion){V.version=E.FunctionVersion;let b=await l.getProvisionedConcurrencyConfig(h,"live").catch(()=>null);if(b)V.provisioned={status:b.Status??"-",allocated:b.AllocatedProvisionedConcurrentExecutions??0,requested:b.RequestedProvisionedConcurrentExecutions??0}}}T.push(V)}let D=await G(u,o.artifactBucket,o.slug,s).catch(()=>null);return{slug:o.slug,environment:s,region:o.region,stackStatus:m,endpoint:f.HttpApiEndpoint,assetUrl:D?.assetUrl,scheduler:o.app.scheduler??"on",queues:S,provisionedConcurrency:R,functions:T,lastRelease:D?{sha:D.sha,timestamp:D.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function Ls(t,s,o,c){let l=k(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:u}=await import("./chunk-5f1n5d80.js"),m=new u(l.region),f=ue(l.slug,s);d(`Scaling ${f} → ${o}–${c} ACUs`),await m.modifyDBCluster({DBClusterIdentifier:f,ServerlessV2ScalingConfiguration:{MinCapacity:o,MaxCapacity:c},ApplyImmediately:!0}),n(`Scaling applied to ${f} (takes effect shortly).`)}async function dm(t,s,o){let c=k(t,s);if(c.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!o.toTime&&!o.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:l}=await import("./chunk-5f1n5d80.js"),u=new l(c.region),m=ue(c.slug,s),f=o.latest?"latest":o.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),S=o.target??`${m}-restore-${f}`;d(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await u.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),d("Waiting for the restored cluster to be ready");for(let R=0;R<120;R++){let{DBClusters:w}=await u.describeDBClusters({DBClusterIdentifier:S}),N=w?.[0]?.Status;if(N&&N!=="creating")break;await new Promise((T)=>setTimeout(T,15000))}return d("Adding a writer instance"),await u.createDBInstance({DBInstanceIdentifier:`${S}-1`,DBClusterIdentifier:S,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),n(`Restore complete → cluster ${S} with writer ${S}-1. Point an env's database at it once available.`),S}
3
3
  export{K,bt,Kd,_s,Io,sm,Os,$s,Po,Bt,am,Jd,cm,lm,z,Ls,dm};
@@ -1 +1 @@
1
- import{di}from"./chunk-rxy9fa64.js";import"./chunk-q8b77zgw.js";import"./chunk-gyvkravq.js";import"./chunk-xdk0gmxt.js";import"./chunk-yp3a0j9n.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{di as resolveServerDashboardData};
1
+ import{di}from"./chunk-03gqra5e.js";import"./chunk-q8b77zgw.js";import"./chunk-gyvkravq.js";import"./chunk-xdk0gmxt.js";import"./chunk-3pazrfsf.js";import"./chunk-12x968en.js";import"./chunk-psvqpztv.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{di as resolveServerDashboardData};
@@ -1,3 +1,3 @@
1
- import{xe,Jt}from"./chunk-dj03v81n.js";import{p,D}from"./chunk-psvqpztv.js";import{v}from"./chunk-xdk0gmxt.js";import{Ct,g}from"./chunk-12x968en.js";import{I}from"./chunk-de69nra4.js";import{V}from"./chunk-xx9mrcfs.js";import{Bt,z}from"./chunk-qq1f07te.js";import{hc}from"./chunk-5nmt4s5w.js";class G{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(Ct(t))}async query(e){let t=new URLSearchParams(D({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,f)=>{t[`Statistics.member.${f+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,f)=>{t[`ExtendedStatistics.member.${f+1}`]=o}),(e.Dimensions??[]).forEach((o,f)=>{t[`Dimensions.member.${f+1}.Name`]=o.Name,t[`Dimensions.member.${f+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let f={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)f[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(f).length?f:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class oe{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as W}from"node:path";var ie=1,ae=3600000,Se=24*ae,Ce=ae,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return W(e&&e.trim()?e:W(fe(),".cache"),"ts-cloud","cost-explorer")}function Q(e){return W(X(),e??"__default__")}function ne(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=W(Q(e),`${ne(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=Q(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(W(a,`${ne(t)}.json`),JSON.stringify(s))}function dc(e){let t=e===void 0?X():Q(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let f=W(s,o.name);if(o.isDirectory())a(f);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function uc(e){return e===void 0?X():Q(e)}class He{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new p(Ct(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,f=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,d);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let y=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:f,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let E=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let K of E?.ResultsByTime??[])for(let N of K?.Groups??[]){let F=N.Keys?.[0]??"Unknown",H=Number.parseFloat(N.Metrics?.UnblendedCost?.Amount??"0"),Y=N.Metrics?.UnblendedCost?.Unit??"USD",O=y.get(F);y.set(F,{key:F,amount:(O?.amount??0)+H,unit:Y})}i=E?.NextPageToken||void 0}while(i);let L=[...y.values()].filter((b)=>b.amount>0).sort((b,E)=>E.amount-b.amount);if(this.useCache)ce(this.profile,d,L);return L}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function _(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function B(e,t,r,a,s,o){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!f.length)return 0;if(a==="Sum")return f.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,d)=>m+(d.Average??0),0)/f.length}async function j(e,t,r,a,s,o,f){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:f,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,y)=>d+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,y)=>d+(y.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((f,m)=>f+(m.Percentiles?.[r]??0),0))}async function si(e,t){let r=await z(e,t),a=r.region,s=new G(a),o=new I(a),f=new oe(a),m=new Date,d=new Date(m.getTime()-86400000),y=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let L=0,b=0,E=0,K=[],N=[],F=[];for(let n of r.functions){let[u,l,c,C,h,T,A,M,R]=await Promise.all([B(s,n.name,"Invocations","Sum",d,m),B(s,n.name,"Errors","Sum",d,m),B(s,n.name,"Throttles","Sum",d,m),B(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",d,m),te(s,n.name,"p95",d,m),te(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);L+=u,b+=l,E=Math.max(E,C);let U=h?.Configuration?.MemorySize??0,x=Object.keys(h?.Configuration?.Environment?.Variables??{}),q=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let w of J){let k=(w.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(k);if(re)S=Math.max(S,Number(re[1]));if(k&&!/^(?:START|END|REPORT|INIT_START)/.test(k))F.push({source:n.mode||n.name,timestamp:new Date(w.timestamp??0).toISOString(),when:Ae(w.timestamp??0),message:k.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(k)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(k)?"warn":"info"})}q=J.filter((w)=>!/^(?:START|END|REPORT|INIT_START)/.test((w.message??"").trim())).slice(-6).map((w)=>({ts:new Date(w.timestamp??0).toISOString().slice(11,19),msg:(w.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(w.message??"")}))}catch{}let P=Math.max(1,...R);K.push({key:n.mode,name:n.name,version:n.version,memory:U,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:A||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),N.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:U,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:T||Math.round(C),p95:A||Math.round(C),p99:M||Math.round(C),maxMem:S,spark:R.length?R.map((J)=>Math.round(J/P*100)):[0],env:x.length?x:["(none)"],recent:q.length?q:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=N,i.serverlessLogs=F.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=F.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=L?Number((b/L*100).toFixed(2)):0,Y=Math.round(await B(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(L),errorRatePct:H,p95Ms:Math.round(E),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new V(a),u=[],l=[],c=0;try{let{QueueUrl:h}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(h);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=y?Jt(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),A=0,M=0;try{let{QueueUrl:U}=await n.getQueueUrl(h.name),{Attributes:x}=await n.getQueueAttributes(U);A=Number(x.ApproximateNumberOfMessages??0),M=Number(x.ApproximateNumberOfMessagesNotVisible??0)}catch{}let R=Math.round(await j(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",d,m));u.push({name:T,visible:A,inFlight:M,processed:R,dlq:c}),l.push({name:h.name,short:T,visible:A,inFlight:M,delayed:0,processed:R,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:u}=await n.describeStacks({stackName:xe(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[h,T]=await Promise.all([j(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",d,m),j(s,"AWS/RDS","DatabaseConnections",C,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:h?Number(h.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:l.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(y?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[h,T]=await Promise.all([j(s,"AWS/ElastiCache","CacheHits",C,"Sum",d,m),j(s,"AWS/ElastiCache","CacheMisses",C,"Sum",d,m)]),A=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:A,status:l.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(l.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(y.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new g(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:H,p95Ms:i.metrics.p95Ms,throttles:N.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=N.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new He,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:_(l),end:_(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:_(c),end:_(l),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,P)=>S+P.amount,0),A=h.reduce((S,P)=>S+P.amount,0),M=u.getUTCDate(),R=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/M*R).toFixed(2)),lastMonthUsd:Number(A.toFixed(2)),dailyAvgUsd:Number((T/M).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,P)=>P.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/M).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:_(l),end:_(u)}).catch(()=>[]);let U=C.find((S)=>/lambda/i.test(S.service))?.amount??0,x=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),q=N.reduce((S,P)=>S+x(P),0)||1;i.costPerFn=N.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(x(S)),usd:Number((U*(x(S)/q)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new ee(a),c=await l.listWebACLs("REGIONAL"),C=c.find((h)=>h.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let h=await l.getWebACLRules(C.Name,C.Id,"REGIONAL");if(h.length)i.wafRules=h.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let O=[];if(i.aurora)O.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)O.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)O.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)O.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(O.length)i.dataServices=O;if(r.scheduler!=="off"&&y?.kind==="php")try{let n=await Bt(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
1
+ import{xe,Jt}from"./chunk-dj03v81n.js";import{p,D}from"./chunk-psvqpztv.js";import{v}from"./chunk-xdk0gmxt.js";import{Ct,g}from"./chunk-12x968en.js";import{P}from"./chunk-vhyp4xj0.js";import{V}from"./chunk-xx9mrcfs.js";import{Bt,z}from"./chunk-4mecfcjk.js";import{hc}from"./chunk-5nmt4s5w.js";class G{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(Ct(t))}async query(e){let t=new URLSearchParams(D({Version:"2010-08-01",...e})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t})}async getMetricStatistics(e){let t={Action:"GetMetricStatistics",Namespace:e.Namespace,MetricName:e.MetricName,StartTime:e.StartTime.toISOString(),EndTime:e.EndTime.toISOString(),Period:e.Period};(e.Statistics??[]).forEach((o,f)=>{t[`Statistics.member.${f+1}`]=o}),(e.ExtendedStatistics??[]).forEach((o,f)=>{t[`ExtendedStatistics.member.${f+1}`]=o}),(e.Dimensions??[]).forEach((o,f)=>{t[`Dimensions.member.${f+1}.Name`]=o.Name,t[`Dimensions.member.${f+1}.Value`]=o.Value});let r=await this.query(t),s=(r.GetMetricStatisticsResult||r)?.Datapoints?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>{let f={},m=o.ExtendedStatistics?.entry;if(m){if(!Array.isArray(m))m=[m];for(let d of m)if(d?.key!=null)f[d.key]=Number(d.value)}return{Timestamp:o.Timestamp,Sum:o.Sum!=null?Number(o.Sum):void 0,Average:o.Average!=null?Number(o.Average):void 0,Maximum:o.Maximum!=null?Number(o.Maximum):void 0,Minimum:o.Minimum!=null?Number(o.Minimum):void 0,Percentiles:Object.keys(f).length?f:void 0,Unit:o.Unit}})}async getMetricSeries(e){let t=/^p\d/.test(e.Stat);return(await this.getMetricStatistics({Namespace:e.Namespace,MetricName:e.MetricName,Dimensions:e.Dimensions,StartTime:e.StartTime,EndTime:e.EndTime,Period:e.Period,Statistics:t?[]:[e.Stat],ExtendedStatistics:t?[e.Stat]:[]})).slice().sort((a,s)=>new Date(a.Timestamp??0).getTime()-new Date(s.Timestamp??0).getTime()).map((a)=>t?a.Percentiles?.[e.Stat]??0:a[e.Stat]??0)}async describeAlarms(e){let t={Action:"DescribeAlarms"};if(e?.AlarmNamePrefix)t.AlarmNamePrefix=e.AlarmNamePrefix;if(e?.MaxRecords)t.MaxRecords=e.MaxRecords;let r=await this.query(t),s=(r.DescribeAlarmsResult||r)?.MetricAlarms?.member??[];if(!Array.isArray(s))s=s?[s]:[];return s.map((o)=>({AlarmName:o.AlarmName,StateValue:o.StateValue,MetricName:o.MetricName,ComparisonOperator:o.ComparisonOperator,Threshold:o.Threshold!=null?Number(o.Threshold):void 0,Namespace:o.Namespace}))}async putMetricAlarm(e){let t={Action:"PutMetricAlarm",AlarmName:e.AlarmName,Namespace:e.Namespace,MetricName:e.MetricName,ComparisonOperator:e.ComparisonOperator,Threshold:e.Threshold,EvaluationPeriods:e.EvaluationPeriods,Period:e.Period,Statistic:e.Statistic};if(e.AlarmDescription)t.AlarmDescription=e.AlarmDescription;(e.Dimensions??[]).forEach((r,a)=>{t[`Dimensions.member.${a+1}.Name`]=r.Name,t[`Dimensions.member.${a+1}.Value`]=r.Value}),(e.AlarmActions??[]).forEach((r,a)=>{t[`AlarmActions.member.${a+1}`]=r}),await this.query(t)}async deleteAlarms(e){if(!e.length)return;let t={Action:"DeleteAlarms"};e.forEach((r,a)=>{t[`AlarmNames.member.${a+1}`]=r}),await this.query(t)}}class oe{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new p(void 0,{profile:t})}async createLogGroup(e,t){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.CreateLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,...t?{tags:t}:{}})})}async putRetentionPolicy(e,t){if(![1,3,5,7,14,30,60,90,120,150,180,365,400,545,731,1096,1827,2192,2557,2922,3288,3653].includes(t))throw Error("Unsupported CloudWatch Logs retention period");await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.PutRetentionPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e,retentionInDays:t})})}async describeLogStreams(e){let t={logGroupName:e.logGroupName};if(e.logStreamNamePrefix)t.logStreamNamePrefix=e.logStreamNamePrefix;if(e.orderBy)t.orderBy=e.orderBy;if(e.descending!==void 0)t.descending=e.descending;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async getLogEvents(e){let t={logGroupName:e.logGroupName,logStreamName:e.logStreamName};if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.limit)t.limit=e.limit;if(e.startFromHead!==void 0)t.startFromHead=e.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async describeLogGroups(e){let t={};if(e?.logGroupNamePrefix)t.logGroupNamePrefix=e.logGroupNamePrefix;if(e?.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}async deleteLogGroup(e){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:e})})}async filterLogEvents(e){let t={logGroupName:e.logGroupName};if(e.logStreamNames)t.logStreamNames=e.logStreamNames;if(e.startTime)t.startTime=e.startTime;if(e.endTime)t.endTime=e.endTime;if(e.filterPattern)t.filterPattern=e.filterPattern;if(e.limit)t.limit=e.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(t)})}}import{createHash as le}from"node:crypto";import{existsSync as se,mkdirSync as de,readdirSync as ge,readFileSync as pe,rmSync as he,writeFileSync as ye}from"node:fs";import{homedir as fe}from"node:os";import{join as W}from"node:path";var ie=1,ae=3600000,Se=24*ae,Ce=ae,Te=30*Se;function X(){let e=process.env.XDG_CACHE_HOME;return W(e&&e.trim()?e:W(fe(),".cache"),"ts-cloud","cost-explorer")}function Q(e){return W(X(),e??"__default__")}function ne(e){let t={s:e.start,e:e.end,g:e.granularity,m:[...e.metrics].sort(),gb:[...e.groupBy].map((r)=>`${r.Type}:${r.Key}`).sort(),f:e.filter??null};return le("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}function be(e,t){let r=Date.parse(`${t}T00:00:00Z`);if(Number.isNaN(r))return!1;let a=new Date,s=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),1);return r<=s}function Ne(e){return be(e.start,e.end)?Te:Ce}function me(e,t){let r=W(Q(e),`${ne(t)}.json`);if(!se(r))return null;let a;try{a=JSON.parse(pe(r,"utf-8"))}catch{return null}if(a.schema!==ie)return null;let s=Date.now()-a.savedAt;if(s<0||s>Ne(t))return null;return{response:a.response,ageSeconds:Math.floor(s/1000)}}function ce(e,t,r){let a=Q(e);de(a,{recursive:!0});let s={schema:ie,savedAt:Date.now(),key:t,response:r};ye(W(a,`${ne(t)}.json`),JSON.stringify(s))}function dc(e){let t=e===void 0?X():Q(e);if(!se(t))return{deletedFiles:0,scope:e??"all profiles"};let r=0;function a(s){for(let o of ge(s,{withFileTypes:!0})){let f=W(s,o.name);if(o.isDirectory())a(f);else if(o.isFile()&&o.name.endsWith(".json"))r++}}return a(t),he(t,{recursive:!0,force:!0}),{deletedFiles:r,scope:e??"all profiles"}}function uc(e){return e===void 0?X():Q(e)}class He{client;profile;useCache;lastCacheAgeSeconds=null;constructor(e,t){this.profile=e,this.useCache=t?.useCache??!0,this.client=new p(Ct(e))}async getCostByService(e){return(await this.getCostByDimension({...e,dimension:"SERVICE"})).map((r)=>({service:r.key,amount:r.amount,unit:r.unit}))}async getCostByDimension(e){let{start:t,end:r,dimension:a,granularity:s="MONTHLY",filter:o}=e,f=["UnblendedCost"],m=[{Type:"DIMENSION",Key:a}],d={start:t,end:r,granularity:s,metrics:f,groupBy:m,filter:o};if(this.useCache){let b=me(this.profile,d);if(b)return this.lastCacheAgeSeconds=b.ageSeconds,b.response}this.lastCacheAgeSeconds=null;let y=new Map,i;do{let b={TimePeriod:{Start:t,End:r},Granularity:s,Metrics:f,GroupBy:m};if(o)b.Filter=o;if(i)b.NextPageToken=i;let O=await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify(b)});for(let K of O?.ResultsByTime??[])for(let N of K?.Groups??[]){let F=N.Keys?.[0]??"Unknown",H=Number.parseFloat(N.Metrics?.UnblendedCost?.Amount??"0"),Y=N.Metrics?.UnblendedCost?.Unit??"USD",R=y.get(F);y.set(F,{key:F,amount:(R?.amount??0)+H,unit:Y})}i=O?.NextPageToken||void 0}while(i);let I=[...y.values()].filter((b)=>b.amount>0).sort((b,O)=>O.amount-b.amount);if(this.useCache)ce(this.profile,d,I);return I}async getDailyTotals(e){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:e.start,End:e.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((a)=>Number.parseFloat(a.Total?.UnblendedCost?.Amount??"0"))}}class Z{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async describeFileSystems(e){let t=[];if(e?.FileSystemId)t.push(`FileSystemId=${encodeURIComponent(e.FileSystemId)}`);if(e?.CreationToken)t.push(`CreationToken=${encodeURIComponent(e.CreationToken)}`);let r=`/2015-02-01/file-systems${t.length>0?`?${t.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:r,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((s)=>({FileSystemId:s.FileSystemId,Name:s.Name,CreationTime:s.CreationTime,LifeCycleState:s.LifeCycleState,NumberOfMountTargets:s.NumberOfMountTargets,SizeInBytes:s.SizeInBytes?{Value:s.SizeInBytes.Value,Timestamp:s.SizeInBytes.Timestamp}:void 0,PerformanceMode:s.PerformanceMode,Encrypted:s.Encrypted,ThroughputMode:s.ThroughputMode,Tags:s.Tags}))}}}class ee{client;region;constructor(e="us-east-1"){this.region=e,this.client=new p}async call(e,t){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${e}`},body:JSON.stringify(t)})}async listWebACLs(e="REGIONAL"){return(await this.call("ListWebACLs",{Scope:e,Limit:100}))?.WebACLs??[]}async getWebACLRules(e,t,r="REGIONAL"){return((await this.call("GetWebACL",{Name:e,Id:t,Scope:r}))?.WebACL?.Rules??[]).map((o)=>({Name:o.Name,Priority:o.Priority,Action:o.Action?Object.keys(o.Action)[0]:o.OverrideAction?Object.keys(o.OverrideAction)[0]:"count"}))}}function ue(e){return String(e).padStart(2,"0")}function _(e){return`${e.getUTCFullYear()}-${ue(e.getUTCMonth()+1)}-${ue(e.getUTCDate())}`}function Ae(e){let t=Math.max(0,Math.round((Date.now()-e)/1000));if(t<60)return`${t}s ago`;let r=Math.round(t/60);if(r<60)return`${r}m ago`;let a=Math.round(r/60);if(a<48)return`${a}h ago`;return`${Math.round(a/24)}d ago`}async function B(e,t,r,a,s,o){let f=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:r,Dimensions:[{Name:"FunctionName",Value:t}],StartTime:s,EndTime:o,Period:86400,Statistics:[a]}).catch(()=>[]);if(!f.length)return 0;if(a==="Sum")return f.reduce((m,d)=>m+(d.Sum??0),0);if(a==="Maximum")return Math.max(...f.map((m)=>m.Maximum??0));return f.reduce((m,d)=>m+(d.Average??0),0)/f.length}async function j(e,t,r,a,s,o,f){let m=await e.getMetricStatistics({Namespace:t,MetricName:r,Dimensions:a,StartTime:o,EndTime:f,Period:86400,Statistics:[s]}).catch(()=>[]);if(!m.length)return 0;if(s==="Sum")return m.reduce((d,y)=>d+(y.Sum??0),0);if(s==="Maximum")return Math.max(...m.map((d)=>d.Maximum??0));return m.reduce((d,y)=>d+(y.Average??0),0)/m.length}async function te(e,t,r,a,s){let o=await e.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:t}],StartTime:a,EndTime:s,Period:86400,ExtendedStatistics:[r]}).catch(()=>[]);return Math.round(o.reduce((f,m)=>f+(m.Percentiles?.[r]??0),0))}async function si(e,t){let r=await z(e,t),a=r.region,s=new G(a),o=new P(a),f=new oe(a),m=new Date,d=new Date(m.getTime()-86400000),y=e.environments?.[t]?.app,i={};i.app={name:r.slug,env:t,region:a,runtime:y?.kind==="php"?`php-${y?.phpVersion??"8.3"} (fpm)`:y?.kind??"node",url:r.endpoint??"",build:r.lastRelease?.sha?.slice(0,7)??"—",deployedAt:r.lastRelease?.timestamp??"—"},i.maintenance={enabled:!1},i.scheduler={enabled:r.scheduler!=="off",expression:r.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let I=0,b=0,O=0,K=[],N=[],F=[];for(let n of r.functions){let[u,l,c,C,h,T,A,M,L]=await Promise.all([B(s,n.name,"Invocations","Sum",d,m),B(s,n.name,"Errors","Sum",d,m),B(s,n.name,"Throttles","Sum",d,m),B(s,n.name,"Duration","Average",d,m),o.getFunction(n.name).catch(()=>null),te(s,n.name,"p50",d,m),te(s,n.name,"p95",d,m),te(s,n.name,"p99",d,m),s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:n.name}],StartTime:new Date(m.getTime()-43200000),EndTime:m,Period:3600,Stat:"Sum"}).catch(()=>[])]);I+=u,b+=l,O=Math.max(O,C);let U=h?.Configuration?.MemorySize??0,x=Object.keys(h?.Configuration?.Environment?.Variables??{}),q=[],S=0;try{let{events:J=[]}=await f.filterLogEvents({logGroupName:`/aws/lambda/${n.name}`,startTime:d.getTime(),limit:120});for(let E of J){let k=(E.message??"").trim(),re=/Max Memory Used:\s*(\d+)\s*MB/.exec(k);if(re)S=Math.max(S,Number(re[1]));if(k&&!/^(?:START|END|REPORT|INIT_START)/.test(k))F.push({source:n.mode||n.name,timestamp:new Date(E.timestamp??0).toISOString(),when:Ae(E.timestamp??0),message:k.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(k)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(k)?"warn":"info"})}q=J.filter((E)=>!/^(?:START|END|REPORT|INIT_START)/.test((E.message??"").trim())).slice(-6).map((E)=>({ts:new Date(E.timestamp??0).toISOString().slice(11,19),msg:(E.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(E.message??"")}))}catch{}let w=Math.max(1,...L);K.push({key:n.mode,name:n.name,version:n.version,memory:U,timeout:h?.Configuration?.Timeout??0,runtime:h?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(u),errors:Math.round(l),p95:A||Math.round(C),status:"active",provisioned:n.provisioned?`${n.provisioned.allocated}/${n.provisioned.requested}`:void 0}),N.push({key:n.mode,name:n.name,runtime:h?.Configuration?.Runtime??"provided.al2023",arch:h?.Configuration?.Architectures?.[0]??"x86_64",memory:U,timeout:h?.Configuration?.Timeout??0,ephemeral:h?.Configuration?.EphemeralStorage?.Size??512,version:n.version,concurrency:y?.concurrency??"—",invocations:Math.round(u),errors:Math.round(l),throttles:Math.round(c),p50:T||Math.round(C),p95:A||Math.round(C),p99:M||Math.round(C),maxMem:S,spark:L.length?L.map((J)=>Math.round(J/w*100)):[0],env:x.length?x:["(none)"],recent:q.length?q:[{ts:"—",msg:"no recent events",err:!1}]})}i.functions=K,i.functionsDetail=N,i.serverlessLogs=F.sort((n,u)=>String(u.timestamp).localeCompare(String(n.timestamp))).slice(0,600),i.serverlessLogsEmptyReason=F.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let H=I?Number((b/I*100).toFixed(2)):0,Y=Math.round(await B(s,r.functions[0]?.name??"","ConcurrentExecutions","Maximum",d,m));i.metrics={invocations:Math.round(I),errorRatePct:H,p95Ms:Math.round(O),coldStartPct:void 0,concurrency:Y,estCostUsd:void 0};try{let n=new V(a),u=[],l=[],c=0;try{let{QueueUrl:h}=await n.getQueueUrl(`${r.slug}-${t}-dlq`),{Attributes:T}=await n.getQueueAttributes(h);c=Number(T.ApproximateNumberOfMessages??0)}catch{}let C=y?Jt(y,r.slug,t):[];for(let h of C){let T=h.name.replace(`${r.slug}-${t}-`,""),A=0,M=0;try{let{QueueUrl:U}=await n.getQueueUrl(h.name),{Attributes:x}=await n.getQueueAttributes(U);A=Number(x.ApproximateNumberOfMessages??0),M=Number(x.ApproximateNumberOfMessagesNotVisible??0)}catch{}let L=Math.round(await j(s,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:h.name}],"Sum",d,m));u.push({name:T,visible:A,inFlight:M,processed:L,dlq:c}),l.push({name:h.name,short:T,visible:A,inFlight:M,delayed:0,processed:L,oldestSec:0,concurrency:h.concurrency??y?.queueConcurrency??"—",tries:y?.queueTries??3,visTimeout:(y?.queueTimeout??120)*6,dlq:c})}if(u.length)i.queues=u;if(l.length)i.queuesDetail=l;i.dlqItems=[]}catch{}try{let n=new v(a),{Stacks:u}=await n.describeStacks({stackName:xe(e,t)}),l={};for(let c of u?.[0]?.Outputs??[])if(c.OutputKey)l[c.OutputKey]=c.OutputValue??"";if(y?.database?.connection==="aurora-serverless"){let c=`${r.slug}-${t}-db`,C=[{Name:"DBClusterIdentifier",Value:c}],[h,T]=await Promise.all([j(s,"AWS/RDS","ServerlessDatabaseCapacity",C,"Average",d,m),j(s,"AWS/RDS","DatabaseConnections",C,"Maximum",d,m)]);if(i.aurora={id:c,engine:"aurora-mysql",minAcu:y?.database?.minCapacity??0.5,maxAcu:y?.database?.maxCapacity??4,currentAcu:h?Number(h.toFixed(1)):y?.database?.minCapacity??0.5,database:"app",connections:Math.round(T),status:l.DbEndpoint?"available":"creating"},y?.rdsProxy)i.proxy={name:`${r.slug}-${t}-proxy`,endpoint:l.DbProxyEndpoint??"—",pooledConns:Math.round(T),status:"available"}}if(y?.cache?.driver==="elasticache"){let c=`${r.slug}-${t}-cache`,C=[{Name:"CacheClusterId",Value:`${c}-001`}],[h,T]=await Promise.all([j(s,"AWS/ElastiCache","CacheHits",C,"Sum",d,m),j(s,"AWS/ElastiCache","CacheMisses",C,"Sum",d,m)]),A=h+T>0?Number((h/(h+T)*100).toFixed(1)):0;i.redis={id:c,node:"cache.t4g.micro",engine:"redis",hitRate:A,status:l.CacheEndpoint?"available":"creating"}}if(y?.efs){let c=0;try{if(l.EfsFileSystemId){let C=new Z(a),{FileSystems:h}=await C.describeFileSystems({FileSystemId:l.EfsFileSystemId});c=Number(((h?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}i.efs={id:l.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:c,status:"available"}}i.assetsInfo=l.AssetsCdnDomain?{bucket:l.AssetsBucketName??`${r.slug}-${t}-assets`,cdn:l.AssetsCdnDomain,customDomain:y?.assetDomain??"—",assetUrl:r.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:i.app.build}:void 0}catch{}if(i.assetsInfo)try{let u=await new g(a).list({bucket:i.assetsInfo.bucket,maxKeys:1000});i.assetsInfo.files=u.length,i.assetsInfo.sizeMb=Number((u.reduce((l,c)=>l+(c.Size??0),0)/1048576).toFixed(1)),i.assetsRecent=u.slice(0,8).map((l)=>({path:`/${l.Key}`,size:`${Math.max(1,Math.round((l.Size??0)/1024))} KB`,type:l.Key.split(".").pop()??""}))}catch{}try{if(y?.secrets){let n=Array.isArray(y.secrets)?y.secrets.map((u)=>({key:u.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:u})):Object.entries(y.secrets).map(([u,l])=>({key:u,source:String(l)}));i.secretsList=n.map((u)=>({...u,updated:"—"}))}}catch{}try{let n=new g(a),u=`${r.slug}-${t}-deployments`,l=await n.getObjectJson(u,`deployments/${r.slug}/${t}/history.json`).catch(()=>null);if(l?.records?.length)i.deploymentsDetail=l.records.slice(-12).reverse().map((c)=>({sha:(c.sha??"").slice(0,7),status:c.status??"success",when:c.timestamp??"—",took:c.took??"—",by:c.by??"—",version:c.version??"—",hooks:c.hooks??[]}))}catch{}i.metricsTotals={invocations:i.metrics.invocations,errors:Math.round(b),errorRatePct:H,p95Ms:i.metrics.p95Ms,throttles:N.reduce((n,u)=>n+u.throttles,0),coldStartPct:void 0,estCostUsd:void 0,concurrency:Y},i.metricsPerFn=N.map((n)=>({key:n.key,invocations:n.invocations,errors:n.errors,throttles:n.throttles,avgMs:n.p50,maxMs:n.p99,costUsd:void 0}));try{i.invSpark=await s.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:r.functions.find((n)=>n.mode==="http")?.name??""}],StartTime:new Date(m.getTime()-86400000),EndTime:m,Period:3600,Stat:"Sum"})}catch{}try{let n=new He,u=m,l=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth(),1)),c=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()-1,1)),[C,h]=await Promise.all([n.getCostByService({start:_(l),end:_(u),granularity:"MONTHLY"}).catch(()=>[]),n.getCostByService({start:_(c),end:_(l),granularity:"MONTHLY"}).catch(()=>[])]);if(C.length){let T=C.reduce((S,w)=>S+w.amount,0),A=h.reduce((S,w)=>S+w.amount,0),M=u.getUTCDate(),L=new Date(Date.UTC(u.getUTCFullYear(),u.getUTCMonth()+1,0)).getUTCDate();i.costSummary={monthToDateUsd:Number(T.toFixed(2)),projectedUsd:Number((T/M*L).toFixed(2)),lastMonthUsd:Number(A.toFixed(2)),dailyAvgUsd:Number((T/M).toFixed(2))},i.costServices=C.filter((S)=>S.amount>0).sort((S,w)=>w.amount-S.amount).slice(0,12).map((S)=>({name:S.service,usd:Number(S.amount.toFixed(2)),note:""})),i.metrics.estCostUsd=Number((T/M).toFixed(2)),i.metricsTotals.estCostUsd=i.metrics.estCostUsd,i.costTrend=await n.getDailyTotals({start:_(l),end:_(u)}).catch(()=>[]);let U=C.find((S)=>/lambda/i.test(S.service))?.amount??0,x=(S)=>S.invocations*(S.p50/1000)*(S.memory/1024),q=N.reduce((S,w)=>S+x(w),0)||1;i.costPerFn=N.map((S)=>({key:S.key,requests:S.invocations,gbSec:Math.round(x(S)),usd:Number((U*(x(S)/q)).toFixed(2))}))}}catch{}if(y?.firewall)try{let n=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]),u=await s.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:d,EndTime:m,Period:86400,Statistics:["Sum"]}).catch(()=>[]);i.waf={enabled:!0,scope:"REGIONAL",acl:`${r.slug}-${t}-waf`,allowed24h:Math.round(u.reduce((l,c)=>l+(c.Sum??0),0)),blocked24h:Math.round(n.reduce((l,c)=>l+(c.Sum??0),0))};try{let l=new ee(a),c=await l.listWebACLs("REGIONAL"),C=c.find((h)=>h.Name?.includes(`${r.slug}-${t}`))??c[0];if(C?.Name&&C.Id){i.waf.acl=C.Name;let h=await l.getWebACLRules(C.Name,C.Id,"REGIONAL");if(h.length)i.wafRules=h.map((T)=>({name:T.Name??"—",detail:`priority ${T.Priority??0}`,action:T.Action??"count",blocked24h:0}))}}catch{}}catch{}let R=[];if(i.aurora)R.push({name:"Aurora Serverless v2",detail:`${i.aurora.id} · ${i.aurora.minAcu}-${i.aurora.maxAcu} ACU`,status:i.aurora.status});if(i.proxy)R.push({name:"RDS Proxy",detail:i.proxy.name,status:i.proxy.status});if(i.redis)R.push({name:`ElastiCache (${i.redis.engine})`,detail:`${i.redis.node} · ${i.redis.hitRate}% hit rate`,status:i.redis.status});if(i.efs)R.push({name:"EFS",detail:`${i.efs.mount} · ${i.efs.sizeMb} MB`,status:i.efs.status});if(R.length)i.dataServices=R;if(r.scheduler!=="off"&&y?.kind==="php")try{let n=await Bt(e,t,"schedule:list"),u=[];for(let l of(n||"").split(`
2
2
  `)){let c=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(l);if(c&&/[*\d]/.test(c[1])&&c[1].trim().split(/\s+/).length===5)u.push({command:c[2].trim().replace(/^php artisan /,""),cron:c[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(u.length)i.schedulerTasks=u}catch{}return i.topology=hc(i,{project:e.project.name,environment:t}),i}
3
3
  export{oe,G,dc,uc,He,si};
@@ -0,0 +1 @@
1
+ import{js,um,pm,Vs}from"./chunk-psmpw0ap.js";import"./chunk-3pazrfsf.js";import"./chunk-dj03v81n.js";import"./chunk-4yym8xm4.js";export{um as getComputeDeployHistory,Vs as restoreDatabaseBackup,js as rollbackComputeSite,pm as runComputeRecipe};
@@ -1,3 +1,3 @@
1
- import{J,U,Ri,Gs,Vt,Gc,Wc}from"./chunk-yp3a0j9n.js";function g(e){return`'${e.split("'").join("'\\''")}'`}function c(e){let r=e.user||"root",n=e.script.join(`
1
+ import{J,U,Ri,Gs,Vt,Gc,Wc}from"./chunk-3pazrfsf.js";function g(e){return`'${e.split("'").join("'\\''")}'`}function c(e){let r=e.user||"root",n=e.script.join(`
2
2
  `),s=r==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${g(r)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${e.name} (user=${r})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,n,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',s,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${e.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var m={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}};async function l(e){return await e.driver.findComputeTargets({slug:e.slug,environment:e.environment,role:e.role||"app"})}async function js(e,r){let n=e.logger||m,s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let t=J(e.slug,r.siteName),o=Vt(t,r.to||"unused"),a=r.onlyIfLive?f(o.current,r.siteName,r.onlyIfLive):[];if(r.dryRun){let i=await e.driver.runRemoteDeploy({targets:s,commands:["set -uo pipefail",...a,...Gc(o,r.to?{to:r.to}:{})],comment:`ts-cloud rollback plan ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:i.success,error:i.error,perInstance:i.perInstance}}let p=["set -uo pipefail",...a,...Wc(o,{...r.to?{to:r.to}:{},unitBase:`${e.slug}-${r.siteName}`}),`(cd ${U} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${o.current} && eval "$(cd ${U} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];n.step(`Rolling back ${r.siteName}${r.to?` to ${r.to}`:" to the previous release"} on ${s.length} server(s)...`);let u=await e.driver.runRemoteDeploy({targets:s,commands:p,comment:`ts-cloud rollback ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!u.success)n.error(`Rollback failed: ${u.error||"unknown error"}`);else n.success(`Rolled back ${r.siteName}.`);return{success:u.success,error:u.error,perInstance:u.perInstance}}function f(e,r,n){let s=n.replace(/[^0-9A-Za-z._-]/g,"");return[`TS_CLOUD_LIVE_ID=$(basename "$(readlink -f ${e} 2>/dev/null)" 2>/dev/null || true)`,`if [ -z "$TS_CLOUD_LIVE_ID" ] || [ "$TS_CLOUD_LIVE_ID" = "." ]; then echo "${r}: no live release here; left alone"; exit 0; fi`,`case "${s}" in "$TS_CLOUD_LIVE_ID"*) ;; *) echo "${r} serves $TS_CLOUD_LIVE_ID, not ${s}; left alone"; exit 0 ;; esac`]}async function um(e,r){let n=await l(e);if(n.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};let s=Gs(J(e.slug,r.siteName)),t=Math.max(1,r.limit??20),o=[`[ -f ${s} ] && tail -n ${t} ${s} || echo "no deploy history for ${r.siteName}"`],a=await e.driver.runRemoteDeploy({targets:n,commands:o,comment:`ts-cloud deploy:history ${e.slug}/${r.siteName}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});return{success:a.success,error:a.error,perInstance:a.perInstance}}async function pm(e,r){let n=e.logger||m,s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};n.step(`Running recipe '${r.name}' as ${r.user||"root"} on ${s.length} server(s)...`);let t=await e.driver.runRemoteDeploy({targets:s,commands:c({name:r.name,script:r.script,user:r.user}),comment:`ts-cloud recipe ${r.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!t.success)n.error(`Recipe '${r.name}' failed: ${t.error||"unknown error"}`);else n.success(`Recipe '${r.name}' completed.`);return{success:t.success,error:t.error,perInstance:t.perInstance}}async function Vs(e,r){let n=e.logger||m;if(!r.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let s=await l(e);if(s.length===0)return{success:!1,error:`No '${e.role||"app"}' servers found for ${e.slug}/${e.environment}.`};n.step(`Restoring database '${r.database.name}'${r.from?` from ${r.from}`:" from the latest backup"} on ${s.length} server(s)...`);let t=await e.driver.runRemoteDeploy({targets:s,commands:Ri(r.database,{from:r.from}),comment:`ts-cloud db:restore ${e.slug}/${r.database.name}`,tags:{Project:e.slug,Environment:e.environment,Role:e.role||"app"}});if(!t.success)n.error(`Restore failed: ${t.error||"unknown error"}`);else n.success(`Restored ${r.database.name}.`);return{success:t.success,error:t.error,perInstance:t.perInstance}}
3
3
  export{js,um,pm,Vs};
@@ -1,2 +1,2 @@
1
- import{p}from"./chunk-psvqpztv.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let d=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(d,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class I{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new p(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
2
- export{I};
1
+ import{p}from"./chunk-psvqpztv.js";import{deflateRawSync as y}from"zlib";function m(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,g=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,l=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+l.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(g,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(l.length,26),a.writeUInt16LE(0,28),l.copy(a,30);let o=Buffer.alloc(46+l.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(g,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(l.length,28),o.writeUInt16LE(0,30),o.writeUInt16LE(0,32),o.writeUInt16LE(0,34),o.writeUInt16LE(0,36),o.writeUInt32LE(0,38),o.writeUInt32LE(0,42),l.copy(o,46);let d=a.length+i.length,h=o.length,u=Buffer.alloc(22);return u.writeUInt32LE(101010256,0),u.writeUInt16LE(0,4),u.writeUInt16LE(0,6),u.writeUInt16LE(1,8),u.writeUInt16LE(1,10),u.writeUInt32LE(h,12),u.writeUInt32LE(d,16),u.writeUInt16LE(0,20),Buffer.concat([a,i,o,u])}function f(n){let e=[];for(let i=0;i<256;i++){let r=i;for(let s=0;s<8;s++)r=r&1?3988292384^r>>>1:r>>>1;e[i]=r}let t=4294967295;for(let i=0;i<n.length;i++)t=e[(t^n[i])&255]^t>>>8;return(t^4294967295)>>>0}class P{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new p(void 0,{profile:e})}async createFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"POST",path:"/2015-03-31/functions",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})}async getFunction(n){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateFunctionCodeInline(n,e,t="index.js"){let i=m(t,e);return this.updateFunctionCode({FunctionName:n,ZipFile:i.toString("base64")})}async updateFunctionConfiguration(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async deleteFunction(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}`,headers:{"Content-Type":"application/json"}})}async invoke(n){let{FunctionName:e,InvocationType:t="RequestResponse",Payload:i,LogType:r}=n,s={"Content-Type":"application/json","X-Amz-Invocation-Type":t};if(r)s["X-Amz-Log-Type"]=r;let g=i?typeof i==="string"?i:JSON.stringify(i):void 0,c=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/invocations`,headers:s,body:g,returnHeaders:!0});return{StatusCode:c.statusCode||200,FunctionError:c.headers?.["x-amz-function-error"],LogResult:c.headers?.["x-amz-log-result"],Payload:typeof c.body==="string"?c.body:JSON.stringify(c.body),ExecutedVersion:c.headers?.["x-amz-executed-version"]}}async listFunctions(n){let e={};if(n?.MaxItems)e.MaxItems=String(n.MaxItems);if(n?.Marker)e.Marker=n.Marker;if(n?.FunctionVersion)e.FunctionVersion=n.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(e).length>0?e:void 0,headers:{"Content-Type":"application/json"}})}async addPermission(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async removePermission(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent(n)}/policy/${encodeURIComponent(e)}`,headers:{"Content-Type":"application/json"}})}async publishVersion(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async createAlias(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async updateAlias(n){let{FunctionName:e,Name:t,...i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(e)}/aliases/${encodeURIComponent(t)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async getAlias(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent(n)}/aliases/${encodeURIComponent(e)}`})}catch(t){if(/ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async getProvisionedConcurrencyConfig(n,e){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}catch(t){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(t?.message)))return null;throw t}}async putProvisionedConcurrencyConfig(n){let{FunctionName:e,Qualifier:t,ProvisionedConcurrentExecutions:i}=n;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(e)}/provisioned-concurrency`,queryParams:{Qualifier:t},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:i})})}async getFunctionConcurrency(n){try{return(await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`}))?.ReservedConcurrentExecutions??null}catch(e){if(/ResourceNotFound|ProvisionedConcurrencyConfigNotFound/i.test(String(e?.message)))return null;throw e}}async putFunctionConcurrency(n,e){await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`,headers:{"Content-Type":"application/json"},body:JSON.stringify({ReservedConcurrentExecutions:e})})}async deleteFunctionConcurrency(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-10-31/functions/${encodeURIComponent(n)}/concurrency`})}async deleteProvisionedConcurrencyConfig(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent(n)}/provisioned-concurrency`,queryParams:{Qualifier:e}})}async waitForFunctionActive(n,e=60){let t=Date.now(),i=e*1000;while(Date.now()-t<i)try{let r=await this.getFunction(n),s=r.Configuration?.State;if(s==="Active")return r.Configuration;if(s==="Failed")throw Error(`Function ${n} failed: ${r.Configuration?.StateReason}`);await new Promise((g)=>setTimeout(g,2000))}catch(r){if(r.code==="ResourceNotFoundException"){await new Promise((s)=>setTimeout(s,2000));continue}throw r}throw Error(`Timeout waiting for function ${n} to become active`)}async functionExists(n){try{return await this.getFunction(n),!0}catch(e){if(e.code==="ResourceNotFoundException"||e.statusCode===404)return!1;throw e}}async createFunctionUrl(n){let{FunctionName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(e)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async getFunctionUrl(n){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}catch(e){if(e.statusCode===404)return null;throw e}}async deleteFunctionUrl(n){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent(n)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode(n){let{Code:e,Filename:t="index.js",...i}=n,r=m(t,e);return this.createFunction({...i,Code:{ZipFile:r.toString("base64")}})}async addFunctionUrlPermission(n){return this.addPermission({FunctionName:n,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion(n){let{LayerName:e,...t}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async listLayerVersions(n,e){let t={};if(e?.CompatibleRuntime)t.CompatibleRuntime=e.CompatibleRuntime;if(e?.CompatibleArchitecture)t.CompatibleArchitecture=e.CompatibleArchitecture;if(e?.MaxItems)t.MaxItems=String(e.MaxItems);if(e?.Marker)t.Marker=e.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions`,queryParams:Object.keys(t).length>0?t:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion(n,e){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission(n){let{LayerName:e,VersionNumber:t,...i}=n;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(e)}/versions/${t}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})}async deleteLayerVersion(n,e){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent(n)}/versions/${e}`,headers:{"Content-Type":"application/json"}})}}
2
+ export{P};