@stacksjs/ts-cloud 0.16.20 → 0.16.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aws/index.js +1 -1
- package/dist/aws/secrets-manager.d.ts +1 -0
- package/dist/aws/xml-result.d.ts +20 -0
- package/dist/{chunk-g6g33pt9.js → bin/chunk-09d5qe73.js} +7 -7
- package/dist/bin/chunk-0cefbrxg.js +1 -0
- package/dist/bin/{chunk-ys5n5c84.js → chunk-12q8xrct.js} +5 -5
- package/dist/bin/chunk-1srmd473.js +1 -0
- package/dist/bin/{chunk-mxvekmdx.js → chunk-24njmb7d.js} +114 -114
- package/dist/bin/chunk-27ka240w.js +1 -0
- package/dist/bin/{chunk-ngyqqy6d.js → chunk-2gd8kqzq.js} +5 -5
- package/dist/bin/{chunk-djjj62c0.js → chunk-330kytpm.js} +2 -2
- package/dist/bin/{chunk-h1rb8qvt.js → chunk-3425j97b.js} +2 -2
- package/dist/bin/chunk-3bq69jqk.js +1 -0
- package/dist/bin/chunk-4pysr1ky.js +1 -0
- package/dist/bin/chunk-56zfvf7e.js +1 -0
- package/dist/bin/chunk-59nav625.js +1 -0
- package/dist/bin/{chunk-6kx50dyc.js → chunk-5bsknbr7.js} +1 -1
- package/dist/bin/{chunk-t10e32an.js → chunk-636jsmnz.js} +6 -6
- package/dist/bin/chunk-7kj8f72p.js +2 -0
- package/dist/bin/{chunk-e55fdn0r.js → chunk-7xr71hnt.js} +3 -3
- package/dist/bin/chunk-87f5d9qj.js +2 -0
- package/dist/bin/chunk-8agf66wn.js +3 -0
- package/dist/bin/chunk-8fjzcr2w.js +1 -0
- package/dist/bin/{chunk-apnhhfkj.js → chunk-8wnkx3jf.js} +2 -2
- package/dist/bin/{chunk-z1dtdw3j.js → chunk-95v6ry1x.js} +5 -5
- package/dist/bin/chunk-9fq0bezb.js +1 -0
- package/dist/bin/chunk-9wpy7r9f.js +1 -0
- package/dist/bin/{chunk-5a7sxtwn.js → chunk-a0me5fed.js} +2 -2
- package/dist/bin/{chunk-148x1zq8.js → chunk-and7khsv.js} +2 -2
- package/dist/bin/{chunk-7zfydgfz.js → chunk-ardzx4dw.js} +130 -130
- package/dist/bin/{chunk-0trtkv9g.js → chunk-c04dygzg.js} +6 -6
- package/dist/bin/chunk-eetz9jgy.js +1 -0
- package/dist/bin/chunk-eg6156wp.js +1 -0
- package/dist/bin/chunk-ezpz96kp.js +1 -0
- package/dist/bin/chunk-f2qpsrrj.js +1 -0
- package/dist/bin/chunk-f3sbq7pw.js +2 -0
- package/dist/bin/chunk-gmabk4qn.js +1 -0
- package/dist/bin/{chunk-9vmtm7nq.js → chunk-hmnaen1z.js} +2 -2
- package/dist/bin/{chunk-x63yz8xg.js → chunk-jp23ed1q.js} +1 -1
- package/dist/bin/{chunk-0f1qpmd6.js → chunk-k6apknm8.js} +5 -5
- package/dist/bin/{chunk-2mv692y4.js → chunk-k97ms0bs.js} +5 -5
- package/dist/bin/chunk-kr51h4gk.js +1 -0
- package/dist/bin/{chunk-48x0wc2g.js → chunk-m51vpvr6.js} +3 -3
- package/dist/bin/{chunk-mx9ppkmn.js → chunk-mbqwrs7a.js} +4 -4
- package/dist/bin/{chunk-rbtt23vx.js → chunk-mz2jbtcs.js} +3 -3
- package/dist/bin/{chunk-dyh0vndw.js → chunk-n7hmjzgd.js} +4 -4
- package/dist/bin/{chunk-dmdg23a5.js → chunk-n8dsby4k.js} +2 -2
- package/dist/bin/chunk-nx8gpr90.js +34 -0
- package/dist/bin/chunk-q62ggp3g.js +1 -0
- package/dist/bin/chunk-q957s44c.js +1 -0
- package/dist/bin/{chunk-k7wh1wr5.js → chunk-qqqx70g6.js} +2 -2
- package/dist/bin/{chunk-gfr2215x.js → chunk-rm59bcnw.js} +60 -60
- package/dist/bin/chunk-rm6qnyce.js +2 -0
- package/dist/bin/chunk-rxehseyz.js +1 -0
- package/dist/bin/chunk-tfz7djw9.js +1 -0
- package/dist/bin/chunk-tr8901hb.js +1 -0
- package/dist/bin/{chunk-3n733cgx.js → chunk-v5bjbyve.js} +2 -2
- package/dist/bin/{chunk-90102shh.js → chunk-v980gs11.js} +2 -2
- package/dist/bin/chunk-vqb80dyg.js +1 -0
- package/dist/bin/{chunk-1j8b1d58.js → chunk-vskhr9qy.js} +2 -2
- package/dist/bin/{chunk-e24bscb0.js → chunk-wqydambz.js} +17 -17
- package/dist/bin/chunk-wysyyysg.js +1 -0
- package/dist/bin/chunk-xfs7rscr.js +1 -0
- package/dist/bin/cli.js +356 -356
- package/dist/bin/dashboard-server.js +1 -1
- package/dist/chunk-2ap78e1s.js +5 -0
- package/dist/{chunk-k53agv2m.js → chunk-2dextjqf.js} +2 -2
- package/dist/chunk-2fa9cdyf.js +1 -0
- package/dist/{chunk-z3wynefj.js → chunk-3jkc3s8c.js} +19 -19
- package/dist/chunk-3zzm5f28.js +92 -0
- package/dist/{chunk-e8e1h2h9.js → chunk-5dz6bzdj.js} +2 -2
- package/dist/chunk-6d5e10md.js +1 -0
- package/dist/chunk-9gypn8w9.js +1 -0
- package/dist/{chunk-hyeeqga9.js → chunk-9p89msvs.js} +6 -6
- package/dist/{chunk-31tvc877.js → chunk-9s24pbbc.js} +18 -18
- package/dist/chunk-badb5mf3.js +34 -0
- package/dist/{chunk-w9jhyy09.js → chunk-cfrv8110.js} +4 -4
- package/dist/{bin/chunk-8jbkphmg.js → chunk-dv1jkay7.js} +6 -6
- package/dist/{chunk-e52me1c6.js → chunk-ezgpamw6.js} +1 -1
- package/dist/chunk-j6a577hr.js +1 -0
- package/dist/chunk-jt49qs0f.js +2 -0
- package/dist/{chunk-aw1tp3p3.js → chunk-khatwx29.js} +99 -99
- package/dist/{chunk-v2p7c7s4.js → chunk-kpyhx96m.js} +133 -133
- package/dist/{chunk-0j2tpr8d.js → chunk-kw852q5m.js} +164 -164
- package/dist/{chunk-3m9ghthh.js → chunk-mgg0psgc.js} +2 -2
- package/dist/{chunk-9wmer0zx.js → chunk-ms4dnha2.js} +2 -2
- package/dist/{chunk-qcaqc5b8.js → chunk-np8vgbv0.js} +3 -3
- package/dist/chunk-p0b08g9f.js +114 -0
- package/dist/{chunk-srrscggm.js → chunk-pcns0kz4.js} +5 -5
- package/dist/{chunk-kczzc599.js → chunk-pffebjr8.js} +31 -31
- package/dist/{chunk-vs0qrm09.js → chunk-pwywwdq2.js} +1 -1
- package/dist/{chunk-5far81q7.js → chunk-w4s3rswa.js} +2 -2
- package/dist/chunk-whdbz3h8.js +1 -0
- package/dist/{chunk-bxrzsth8.js → chunk-x60w04y3.js} +2 -2
- package/dist/{chunk-zx8ecz8b.js → chunk-y6k0vwfn.js} +4 -4
- package/dist/deploy/index.js +1 -1
- package/dist/dns/index.js +1 -1
- package/dist/drivers/index.js +1 -1
- package/dist/index.js +85 -85
- package/dist/operations/index.js +1 -1
- package/dist/protection/index.js +1 -1
- package/dist/spend/index.js +1 -1
- package/dist/ui/404.html +1 -1
- package/dist/ui/accept-invitation.html +1 -1
- package/dist/ui/access-denied.html +1 -1
- package/dist/ui/account/automation.html +6 -6
- package/dist/ui/account/security.html +2 -2
- package/dist/ui/applications/compose.html +6 -6
- package/dist/ui/applications/new.html +2 -2
- package/dist/ui/data/backups.html +6 -6
- package/dist/ui/data/services.html +6 -6
- package/dist/ui/data/volumes.html +6 -6
- package/dist/ui/index.html +6 -6
- package/dist/ui/infrastructure/topology.html +6 -6
- package/dist/ui/integrations.html +2 -2
- package/dist/ui/operations/alerts.html +6 -6
- package/dist/ui/operations/configuration.html +6 -6
- package/dist/ui/operations/jobs.html +5 -5
- package/dist/ui/operations/maintenance.html +5 -5
- package/dist/ui/operations/observability.html +6 -6
- package/dist/ui/operations/previews.html +6 -6
- package/dist/ui/operations/queue.html +5 -5
- package/dist/ui/operations/regions.html +5 -5
- package/dist/ui/operations/releases.html +6 -6
- package/dist/ui/operations/spend.html +6 -6
- package/dist/ui/operations/workloads.html +6 -6
- package/dist/ui/security.html +2 -2
- package/dist/ui/server/actions.html +6 -6
- package/dist/ui/server/activity.html +1 -1
- package/dist/ui/server/capacity.html +5 -5
- package/dist/ui/server/database.html +5 -5
- package/dist/ui/server/deployments.html +5 -5
- package/dist/ui/server/diagnostics.html +1 -1
- package/dist/ui/server/firewall.html +5 -5
- package/dist/ui/server/fleet.html +5 -5
- package/dist/ui/server/logs.html +6 -6
- package/dist/ui/server/metrics.html +5 -5
- package/dist/ui/server/security.html +2 -2
- package/dist/ui/server/services.html +1 -1
- package/dist/ui/server/sites.html +6 -6
- package/dist/ui/server/ssh-keys.html +6 -6
- package/dist/ui/server/team.html +6 -6
- package/dist/ui/server/terminal.html +2 -2
- package/dist/ui/serverless/alarms.html +6 -6
- package/dist/ui/serverless/assets.html +2 -2
- package/dist/ui/serverless/cost.html +1 -1
- package/dist/ui/serverless/data.html +6 -6
- package/dist/ui/serverless/deployments.html +2 -2
- package/dist/ui/serverless/firewall.html +1 -1
- package/dist/ui/serverless/functions.html +5 -5
- package/dist/ui/serverless/logs.html +5 -5
- package/dist/ui/serverless/metrics.html +2 -2
- package/dist/ui/serverless/queues.html +6 -6
- package/dist/ui/serverless/secrets.html +6 -6
- package/dist/ui/serverless/traces.html +6 -6
- package/dist/ui/serverless.html +5 -5
- package/package.json +3 -3
- package/dist/bin/chunk-0h6cggyt.js +0 -1
- package/dist/bin/chunk-28ztnqjk.js +0 -1
- package/dist/bin/chunk-2g2zrtjs.js +0 -2
- package/dist/bin/chunk-4cs098d1.js +0 -1
- package/dist/bin/chunk-52fhq35h.js +0 -1
- package/dist/bin/chunk-6se7ygxa.js +0 -1
- package/dist/bin/chunk-72g1hr4z.js +0 -1
- package/dist/bin/chunk-840arz58.js +0 -34
- package/dist/bin/chunk-c7vxdwth.js +0 -1
- package/dist/bin/chunk-e0c3agf2.js +0 -1
- package/dist/bin/chunk-egn33pr9.js +0 -2
- package/dist/bin/chunk-gf7yavs5.js +0 -1
- package/dist/bin/chunk-gp5w7e4c.js +0 -1
- package/dist/bin/chunk-gt7g41js.js +0 -1
- package/dist/bin/chunk-hagakkgm.js +0 -1
- package/dist/bin/chunk-hr3vbg6y.js +0 -1
- package/dist/bin/chunk-hyb5v8wr.js +0 -1
- package/dist/bin/chunk-ndddd2ft.js +0 -3
- package/dist/bin/chunk-nqb1faqj.js +0 -1
- package/dist/bin/chunk-p831sptd.js +0 -1
- package/dist/bin/chunk-qxx1a51w.js +0 -1
- package/dist/bin/chunk-sh248v2y.js +0 -1
- package/dist/bin/chunk-swfmx4f8.js +0 -1
- package/dist/bin/chunk-vjkyj3xy.js +0 -2
- package/dist/bin/chunk-w8k1gyzr.js +0 -1
- package/dist/bin/chunk-wagzxm7z.js +0 -1
- package/dist/bin/chunk-xdxk6baf.js +0 -1
- package/dist/bin/chunk-y286zhty.js +0 -1
- package/dist/bin/chunk-ysv52qcc.js +0 -1
- package/dist/chunk-07rjctzz.js +0 -1
- package/dist/chunk-49vvjfrd.js +0 -1
- package/dist/chunk-6kcmbymp.js +0 -1
- package/dist/chunk-7xnwa0s8.js +0 -5
- package/dist/chunk-9asn5fpt.js +0 -92
- package/dist/chunk-d46p0h6t.js +0 -34
- package/dist/chunk-dak9hfrd.js +0 -1
- package/dist/chunk-ptq9v346.js +0 -2
- package/dist/chunk-wgf1ndgq.js +0 -114
- package/dist/chunk-z4xzd43p.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Uu}from"./chunk-330kytpm.js";import"./chunk-vskhr9qy.js";import"./chunk-k97ms0bs.js";import"./chunk-mbqwrs7a.js";import"./chunk-24njmb7d.js";export{Uu as buildAndPushServerlessImage};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function
|
|
1
|
+
var l={mode:"detection",paranoiaLevel:1,inboundThreshold:5,outboundThreshold:4,maxBodyBytes:13107200,rejectOversizedBody:!0,auditLogPath:"/var/log/ts-cloud/waf-audit.log",blockStatus:403},d={bypassBase:1e5,exclusionBase:101000,rateLimitBase:102000,customBase:109000};function Je(e){return e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/[\r\n]+/g," ")}function fs(e){if(e.length>1000)return!1;if(/\([^)]*[+*]\)[+*]/.test(e))return!1;if(/\[[^\]]*\][+*]\{/.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}function b(e,r){let t=[],o=[],s=r;for(let n of e){if(n.enabled===!1)continue;if(n.key&&(n.key.source==="cookie"||n.key.source==="header")&&!n.key.name){o.push({ruleId:n.id,reason:"The rule keys on a header or cookie but names none."});continue}let c=n.path?nc(n.path):".*";if(!fs(c)){o.push({ruleId:n.id,reason:"The path pattern compiles to an unsafe regular expression."});continue}let u=[`SecRule REQUEST_URI "@rx ${Je(c)}"`];if(n.methods?.length)u.push(` "chain,id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Je(n.id)}'"`);else u.push(` "id:${s},phase:1,pass,nolog,setvar:'tx.ts_cloud_ratelimit=${Je(n.id)}'"`);if(t.push(`# Marks requests governed by the ts-cloud rate limit "${Je(n.id)}".`),t.push(u.join(" \\\n")),n.methods?.length)t.push(` SecRule REQUEST_METHOD "@within ${Je(n.methods.join(" ").toUpperCase())}" "t:none"`);t.push(""),s++}return{lines:t,unmapped:o}}function nc(e){return`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"\x01").replace(/\*/g,"[^/]*").replace(/\u0001/g,".*")}$`}function ii(e={},r=[]){let t=e.mode??l.mode,o=[],s=e.paranoiaLevel??l.paranoiaLevel,n=e.inboundThreshold??l.inboundThreshold,c=e.outboundThreshold??l.outboundThreshold,u=e.maxBodyBytes??l.maxBodyBytes,h=e.rejectOversizedBody!==!1;if(t==="blocking"&&s>=3)o.push(`Paranoia level ${s} blocks legitimate traffic on most applications until it is tuned. Run it in detection mode first.`);if(t==="blocking")o.push("zig-waf is pre-alpha. Blocking mode makes it a failure path for every request.");if(!h)o.push("Oversized bodies are passed through uninspected, so padding a request bypasses every rule.");if(e.bypassPaths?.length)o.push(`${e.bypassPaths.length} path(s) bypass inspection entirely.`);let i=["# Managed by ts-cloud. Edits are overwritten on the next deploy.",`# Mode: ${t}. Paranoia level: ${s}.`,""];if(t==="off")return i.push("SecRuleEngine Off",""),{config:`${i.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${
|
|
3
|
+
`,unmappedRateLimits:[],warnings:o,mode:t};i.push(`SecRuleEngine ${t==="blocking"?"On":"DetectionOnly"}`,"SecRequestBodyAccess On","SecResponseBodyAccess Off",`SecRequestBodyLimit ${u}`,`SecRequestBodyNoFilesLimit ${Math.min(u,131072)}`,`SecRequestBodyLimitAction ${h?"Reject":"ProcessPartial"}`,"SecRequestBodyInMemoryLimit 131072",`SecAuditEngine ${t==="blocking"?"RelevantOnly":"On"}`,"SecAuditLogParts ABIJDEFHZ",`SecAuditLog ${Je(e.auditLogPath??l.auditLogPath)}`,"SecAuditLogType Serial",`SecDefaultAction "phase:1,log,auditlog,${t==="blocking"?`deny,status:${e.blockStatus??l.blockStatus}`:"pass"}"`,"","# CRS anomaly scoring setup.",`SecAction "id:900000,phase:1,pass,nolog,t:none,setvar:tx.paranoia_level=${s}"`,`SecAction "id:900001,phase:1,pass,nolog,t:none,setvar:tx.inbound_anomaly_score_threshold=${n}"`,`SecAction "id:900002,phase:1,pass,nolog,t:none,setvar:tx.outbound_anomaly_score_threshold=${c}"`,'SecAction "id:900003,phase:1,pass,nolog,t:none,setvar:tx.critical_anomaly_score=5,setvar:tx.error_anomaly_score=4,setvar:tx.warning_anomaly_score=3,setvar:tx.notice_anomaly_score=2"','SecAction "id:900004,phase:1,pass,nolog,t:none,setvar:tx.anomaly_score=0"',"");let g=d.bypassBase;for(let a of e.bypassPaths??[]){let y=nc(a);if(!fs(y)){o.push(`Bypass path "${a}" was dropped: it compiles to an unsafe regular expression.`);continue}i.push(`# Inspection bypass for ${Je(a)}. Every bypass is an unguarded route.`,`SecRule REQUEST_URI "@rx ${Je(y)}" "id:${g},phase:1,pass,nolog,ctl:ruleEngine=Off"`,""),g++}let m=d.exclusionBase;for(let a of e.exclusions??[]){if(!Number.isInteger(a.ruleId)||a.ruleId<=0){o.push(`Exclusion with rule id "${a.ruleId}" was dropped: the id is not a positive integer.`);continue}if(i.push(`# ${Je(a.reason)}`),a.pathPattern){if(!fs(a.pathPattern)){o.push(`Exclusion for rule ${a.ruleId} was dropped: its path pattern is unsafe.`);continue}i.push(`SecRule REQUEST_URI "@rx ${Je(a.pathPattern)}" "id:${m},phase:1,pass,nolog,ctl:ruleRemoveById=${a.ruleId}"`),m++}else i.push(`SecRuleRemoveById ${a.ruleId}`);i.push("")}let p=b(r,d.rateLimitBase);if(p.lines.length>0)i.push("# Rate-limit route markers. SecLang has no counters, so the tag is set","# here and the counting stays in the ts-cloud limiter.",...p.lines);let f=d.customBase;for(let a of e.customRules??[])i.push(`# Operator-supplied rule ${f}.`,a.trim(),""),f++;if(t==="blocking")i.push("# Blocking decision: one rule, at the end, on the accumulated score.",`SecRule TX:ANOMALY_SCORE "@ge %{tx.inbound_anomaly_score_threshold}" "id:949110,phase:2,deny,status:${e.blockStatus??l.blockStatus},log,msg:'Inbound anomaly score exceeded (total: %{tx.anomaly_score})'"`,"");return{config:`${i.join(`
|
|
4
4
|
`)}
|
|
5
|
-
`,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function
|
|
5
|
+
`,unmappedRateLimits:p.unmapped,warnings:o,mode:t}}function hs(e={},r=[],t={}){let o=t.binary??"/usr/local/bin/zig-waf",s=t.configPath??"/etc/ts-cloud/waf.conf",n=ii(e,r);return`#!/usr/bin/env bash
|
|
6
6
|
# Managed by ts-cloud. Installs the zig-waf ruleset.
|
|
7
7
|
set -euo pipefail
|
|
8
8
|
|
|
@@ -33,5 +33,5 @@ fi
|
|
|
33
33
|
|
|
34
34
|
mv "${s}.new" "${s}"
|
|
35
35
|
echo "ts-cloud: WAF config installed (mode: ${n.mode})"
|
|
36
|
-
`}function
|
|
37
|
-
export{
|
|
36
|
+
`}function op(e,r){return e.map((t)=>({projectId:r.projectId,environmentId:r.environmentId,resourceId:r.resourceId,kind:"event",source:"zig-waf",name:t.action==="blocked"?"waf.blocked":"waf.matched",timestamp:t.timestamp,value:1,host:t.host,pathTemplate:t.path,method:t.method,attributes:{ruleId:t.ruleId??null,anomalyScore:t.anomalyScore,action:t.action,messages:t.messages.slice(0,5)}}))}
|
|
37
|
+
export{Je,fs,nc,ii,hs,op};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{Oo,ln,fa,Ci,Uo,Bo}from"./chunk-24njmb7d.js";import{e}from"./chunk-k97ms0bs.js";import{ft}from"./chunk-vskhr9qy.js";import{execFileSync as C}from"node:child_process";import{mkdirSync as w,mkdtempSync as I,rmSync as U,writeFileSync as g}from"node:fs";import{tmpdir as j}from"node:os";import{dirname as O,join as o}from"node:path";function E(s,t){for(let r of t){let d=o(s,r.name);w(O(d),{recursive:!0}),g(d,r.data,r.mode?{mode:r.mode}:void 0)}}async function Uu(s){let{app:t,projectRoot:r,region:d,repository:u}=s,x=t.architecture??"x86_64",R=x==="arm64"?"linux/arm64":"linux/amd64",b=t.kind==="php",n=s.onStep??(()=>{}),a=I(o(j(),"tscloud-img-"));try{let h=o(a,"app");w(h,{recursive:!0});let f,y;if(b){Uo({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n}),n("staging application tree");let i=Bo(r);E(h,i),E(o(a,"runtime"),Ci().map((c)=>({name:c.path,data:c.contents,mode:c.mode})));let v=t.handlers?.http??"public/index.php";f={http:v,queue:t.handlers?.queue??v,cli:t.handlers?.cli??v},y=Oo(i.map((c)=>`${c.name}:${c.data.length}`).join("|"))}else{n("bundling application");let i=await ln({projectRoot:r,app:t,skipBuild:s.skipBuild,onStep:n});g(o(h,"index.mjs"),i.bundle),f=i.handlers,y=i.sha256}let B=y.slice(0,16);g(o(a,"Dockerfile"),fa({kind:t.kind??"node",phpVersion:t.phpVersion,architecture:x}));let k=new ft(d),p;try{p=(await k.describeRepositories({repositoryNames:[u]})).repositories?.[0]?.repositoryUri??""}catch{p=""}if(!p)n(`creating ECR repository ${u}`),p=(await k.createRepository({repositoryName:u,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!p)throw Error(`could not resolve ECR repository URI for ${u}`);let l=`${p}:${B}`;n("docker build"),C("docker",["build","--platform",R,"--provenance=false","--sbom=false","-t",l,a],{stdio:"inherit"}),n("ecr auth + push");let m=(await k.getAuthorizationToken()).authorizationData?.[0];if(!m?.authorizationToken||!m.proxyEndpoint)throw Error("failed to get an ECR authorization token");let A=m.proxyEndpoint.replace(/^https?:\/\//,""),S=o(a,".docker");return w(S,{recursive:!0}),g(o(S,"config.json"),JSON.stringify({auths:{[A]:{auth:m.authorizationToken}}})),C("docker",["push",l],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:S}}),e(`Image: ${l}`),{imageUri:l,tag:B,handlers:f}}finally{U(a,{recursive:!0,force:!0})}}
|
|
2
|
+
export{Uu};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
export{
|
|
1
|
+
function Yo(n){let t=new RegExp("[\\u007F-\\uFFFF]","g");return JSON.stringify(n).replace(t,(o)=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}
|
|
2
|
+
export{Yo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Hn}from"./chunk-m51vpvr6.js";import"./chunk-7kj8f72p.js";import"./chunk-8agf66wn.js";import"./chunk-5bsknbr7.js";import"./chunk-k97ms0bs.js";import"./chunk-87f5d9qj.js";import"./chunk-7xr71hnt.js";import"./chunk-mbqwrs7a.js";import"./chunk-24njmb7d.js";export{Hn as resolveDashboardData};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Yo}from"./chunk-3425j97b.js";export{Yo as encodeDashboardPayload};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w}from"./chunk-n7hmjzgd.js";import"./chunk-mbqwrs7a.js";export{w as CloudFrontClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ps,pp,mp,Ns}from"./chunk-mz2jbtcs.js";import"./chunk-636jsmnz.js";import"./chunk-24njmb7d.js";export{pp as getComputeDeployHistory,Ns as restoreDatabaseBackup,Ps as rollbackComputeSite,mp as runComputeRecipe};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u}from"./chunk-mx9ppkmn.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.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),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}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 R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(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=d(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 l=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:l,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((l)=>setTimeout(l,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=d(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"}})}}
|
|
1
|
+
import{u}from"./chunk-mbqwrs7a.js";import{deflateRawSync as y}from"zlib";function d(n,e){let t=typeof e==="string"?Buffer.from(e,"utf-8"):e,i=y(t),r=f(t),s=new Date,l=(s.getHours()<<11|s.getMinutes()<<5|s.getSeconds()>>1)&65535,c=(s.getFullYear()-1980<<9|s.getMonth()+1<<5|s.getDate())&65535,m=Buffer.from(n,"utf-8"),a=Buffer.alloc(30+m.length);a.writeUInt32LE(67324752,0),a.writeUInt16LE(20,4),a.writeUInt16LE(0,6),a.writeUInt16LE(8,8),a.writeUInt16LE(l,10),a.writeUInt16LE(c,12),a.writeUInt32LE(r,14),a.writeUInt32LE(i.length,18),a.writeUInt32LE(t.length,22),a.writeUInt16LE(m.length,26),a.writeUInt16LE(0,28),m.copy(a,30);let o=Buffer.alloc(46+m.length);o.writeUInt32LE(33639248,0),o.writeUInt16LE(20,4),o.writeUInt16LE(20,6),o.writeUInt16LE(0,8),o.writeUInt16LE(8,10),o.writeUInt16LE(l,12),o.writeUInt16LE(c,14),o.writeUInt32LE(r,16),o.writeUInt32LE(i.length,20),o.writeUInt32LE(t.length,24),o.writeUInt16LE(m.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),m.copy(o,46);let p=a.length+i.length,h=o.length,g=Buffer.alloc(22);return g.writeUInt32LE(101010256,0),g.writeUInt16LE(0,4),g.writeUInt16LE(0,6),g.writeUInt16LE(1,8),g.writeUInt16LE(1,10),g.writeUInt32LE(h,12),g.writeUInt32LE(p,16),g.writeUInt16LE(0,20),Buffer.concat([a,i,o,g])}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 R{client;region;constructor(n="us-east-1",e){this.region=n,this.client=new u(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=d(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 l=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:l,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((l)=>setTimeout(l,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=d(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
2
|
export{R};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{z,Ir}from"./chunk-24njmb7d.js";function G(e,t){return`/var/www/${e}-${t}`}var _e=new Set(["laravel","php","statamic","wordpress"]);function si(e){return e.type!=null&&_e.has(e.type)}function Ds(e){let t=e.proxyTo;if(t==null)return[];return(Array.isArray(t)?t:[t]).map((n)=>String(n).trim()).filter((n)=>n.length>0)}function Se(e){return Ds(e).length>0}function ee(e){if(e.deploy)return e.deploy;if(si(e))return"server";if(e.start)return"server";return"bucket"}function P(e){if(e.redirect)return"redirect";if(Se(e))return"proxy";if(si(e))return"server-php";if(ee(e)==="bucket")return"bucket";return e.start?"server-app":"server-static"}function mo(e){return e.infrastructure?.compute!=null||Boolean(e.cloud?.attachTo?.trim())}function ks(e,t={}){let r=[],n=[],i=e.sites||{},s=mo(e),c=Ir(e);if(c)r.push(c);let d=new Map;for(let[l,o]of Object.entries(i)){if(!o)continue;let f=ee(o),E=P(o);if(E==="redirect"){if(!o.domain)r.push(`Site '${l}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof o.redirect==="string"?o.redirect:o.redirect?.to))r.push(`Site '${l}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!s)r.push(`Site '${l}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let a=[];if(o.start)a.push("start");if(o.root)a.push("root");if(o.proxyTo)a.push("proxyTo");if(a.length>0)n.push(`Site '${l}' is a redirect site but also sets ${a.join(", ")}. These are ignored.`);continue}if(E==="proxy"){if(!o.domain)r.push(`Site '${l}' is a proxy site but has no \`domain\` to route from.`);if(!s)r.push(`Site '${l}' is a proxy site but no \`infrastructure.compute\` is configured to host the gateway that forwards it.`);let p=[];if(o.start)p.push("start");if(o.root)p.push("root");if(typeof o.port==="number")p.push("port");if(o.build)p.push("build");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' sets \`proxyTo\`, so ts-cloud ships and supervises nothing for it. ${p.join(", ")} ${p.length===1?"is":"are"} ignored — remove ${p.length===1?"it":"them"}, or drop \`proxyTo\` to let ts-cloud own the service.`);continue}if(f==="server"&&!o.start&&!o.root){r.push(`Site '${l}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(E==="server-php"){if(!s)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!o.repository?.url)r.push(`Site '${l}' is a PHP site (type:'${o.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(E==="server-app"){if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server'${o.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof o.port==="number"){let p=t.occupiedPorts?.get(o.port);if(p)r.push(`Site '${l}' wants port ${o.port}, which project '${p}' already serves on this box. Attached projects share one port namespace. Give '${l}' a free port, or let the attach allocate one.`);let a=d.get(o.port);if(a)r.push(`Sites '${a}' and '${l}' both use port ${o.port}. Server apps sharing a box must use distinct ports.`);else d.set(o.port,l)}}else if(E==="server-static"){if(!o.root)r.push(`Site '${l}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!s)r.push(`Site '${l}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!o.root)r.push(`Site '${l}' deploys to a bucket but has no \`root\` directory to upload.`);let p=[];if(o.start)p.push("start");if(typeof o.port==="number")p.push("port");if(o.preStart&&o.preStart.length>0)p.push("preStart");if(p.length>0)n.push(`Site '${l}' deploys to a bucket but sets server-only field(s): ${p.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:r,warnings:n}}function _s(e){let t=P(e);return t!=="bucket"&&t!=="redirect"&&t!=="proxy"}function oc(e){return P(e)==="bucket"}function sc(e,t){if(z(e)==="serverless")return!0;let r=Object.entries(e.sites??{}).filter(([,i])=>i!=null),n=t?r.filter(([i])=>i===t):r;if(n.length===0)return!0;return!n.every(([,i])=>{let s=P(i);return s==="redirect"||s==="proxy"})}var O={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",vitess:"vitess.io",etcd:"etcd.io",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",mail:"github.com/mail-os/mail",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"};var M="/opt/pantry";function N(e){return`'${e.split("'").join("'\\''")}'`}function Sr(e={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",e.version?`export PANTRY_VERSION=${N(e.version)}`:'export PANTRY_VERSION="${PANTRY_VERSION:-latest}"',"command -v curl >/dev/null 2>&1 || (apt-get update -y && apt-get install -y curl ca-certificates)","command -v unzip >/dev/null 2>&1 || (apt-get update -y && apt-get install -y unzip)",'OS=$(uname -s | tr \'[:upper:]\' \'[:lower:]\'); ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) ARCH=x64 ;; arm64|aarch64) ARCH=arm64 ;; esac; ZIP="pantry-${OS}-${ARCH}.zip"; if [ "${PANTRY_VERSION:-latest}" = latest ]; then REL=\'latest/download\'; else REL="download/v${PANTRY_VERSION}"; fi; TMP=$(mktemp -d); curl -fsSL -o "${TMP}/${ZIP}" "https://github.com/pantry-pm/pantry/releases/${REL}/${ZIP}"; unzip -o "${TMP}/${ZIP}" -d /usr/local/bin; chmod +x /usr/local/bin/pantry; rm -rf "${TMP}"','export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function yt(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function Ye(e){if(e.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set(e)].map(N).join(" ")})`]}function go(e){return[...new Set(e)].flatMap((t)=>[`(cd /opt/pantry && pantry start ${N(t)})`,`(cd /opt/pantry && pantry enable ${N(t)})`])}var S="/etc/mail",T="mail-server",q="mail",F=`${M}/pantry/.bin`;function h(e){return`'${String(e).split("'").join("'\\''")}'`}function b(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function fe(e){return[e.version?`${O.mail}@${e.version}`:O.mail]}function Y(e,t){return`${S}/dkim/${t}.${e.dkim.selector}.pem`}function te(e){return`${e.storagePath}/smtp.db`}function ge(e){let t=["# Generated by ts-cloud. Edits are overwritten on the next deploy —","# change `services.mail` in the cloud config instead.","","[server]",`host = ${b(e.bindAddress)}`,`port = ${e.ports.smtp}`,`hostname = ${b(e.hostname)}`];if(e.domains.length>0)t.push(`local_domains = ${b(e.domains.join(", "))}`);if(e.mode==="catcher")t.push("catch_all = true");if(t.push(`max_message_size = ${e.maxMessageSize}`,"","[tls]",`enabled = ${e.tls.enabled}`),e.tls.certPath)t.push(`cert_path = ${b(e.tls.certPath)}`);if(e.tls.keyPath)t.push(`key_path = ${b(e.tls.keyPath)}`);if(t.push("","[auth]",`enabled = ${e.mode==="server"}`,"","[antispam]",`dnsbl = ${e.spam.dnsbl}`,`greylist = ${e.spam.greylist}`,`spam_filter = ${e.spam.enabled}`,`junk_score = ${e.spam.junkScore}`,`reject_score = ${e.spam.rejectScore}`,"","[dkim]",`rotation_enabled = ${e.dkim.enabled&&e.dkim.rotate}`,`rotation_interval_days = ${e.dkim.rotateIntervalDays}`,"","[acme]",`enabled = ${e.tls.acme}`),e.tls.acmeEmail)t.push(`email = ${b(e.tls.acmeEmail)}`);if(t.push("","[webhook]",`enabled = ${!!e.webhookUrl}`),e.webhookUrl)t.push(`url = ${b(e.webhookUrl)}`);return t.push(""),t.join(`
|
|
2
2
|
`)}function Te(e){let t=["# Generated by ts-cloud. See /etc/mail/config.toml for the rest.",`SMTP_DB_PATH=${te(e)}`,`SMTP_DELIVERY_METHOD=${e.delivery==="ses"?"ses":"direct"}`];if(e.delivery==="ses")t.push(`SMTP_SES_REGION=${e.sesRegion}`);if(e.ports.submission)t.push(`SUBMISSION_PORT=${e.ports.submission}`);if(e.ports.submissions)t.push(`SMTPS_PORT=${e.ports.submissions}`);if(e.ports.imap)t.push("IMAP_ENABLED=1",`IMAP_PORT=${e.ports.imap}`);if(e.webmail.enabled)t.push("SMTP_ENABLE_WEBMAIL=true",`SMTP_WEBMAIL_PORT=${e.webmail.port}`,`SMTP_WEBMAIL_SECURE_COOKIES=${e.tls.enabled}`);if(e.tls.requireForAuth)t.push("SMTP_REQUIRE_TLS_FOR_AUTH=true");if(e.dkim.enabled&&e.domains.length>0){let[r,...n]=e.domains;if(t.push(`DKIM_DOMAIN=${r}`,`DKIM_SELECTOR=${e.dkim.selector}`,`DKIM_PRIVATE_KEY_PATH=${Y(e,r)}`),n.length>0){let i=n.map((s)=>`${s}:${e.dkim.selector}:${Y(e,s)}`);t.push(`DKIM_EXTRA_KEYS=${i.join(",")}`)}}return t.push(""),t.join(`
|
|
3
|
-
`)}function he(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${
|
|
4
|
-
`)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${
|
|
3
|
+
`)}function he(e){let t=[e.ports.smtp,e.ports.submission,e.ports.submissions,e.ports.imap,e.ports.imaps].some((r)=>typeof r==="number"&&r<1024);return["[Unit]","Description=Mail server (SMTP/IMAP + webmail)","After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`User=${T}`,`Group=${T}`,`WorkingDirectory=${e.storagePath}`,`EnvironmentFile=${S}/mail.env`,`Environment="PATH=${F}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"`,`ExecStart=${F}/mail serve --config ${S}/config.toml`,"Restart=always","RestartSec=5","LimitNOFILE=65536",...t?["AmbientCapabilities=CAP_NET_BIND_SERVICE","CapabilityBoundingSet=CAP_NET_BIND_SERVICE"]:[],"NoNewPrivileges=true","PrivateTmp=true","ProtectSystem=strict","ProtectHome=true","ProtectKernelTunables=true","ProtectKernelModules=true","ProtectControlGroups=true",`ReadWritePaths=${e.storagePath} ${S}`,"","[Install]","WantedBy=multi-user.target",""].join(`
|
|
4
|
+
`)}function ve(e){if(!e.dkim.enabled||e.domains.length===0)return[];let t=[`mkdir -p ${S}/dkim`];for(let r of e.domains){let n=Y(e,r);t.push(`if [ ! -f ${h(n)} ]; then openssl genrsa -out ${h(n)} 2048; fi`,`chmod 0600 ${h(n)}`,`echo "DKIM ${e.dkim.selector}._domainkey.${r} IN TXT v=DKIM1; k=rsa; p=$(openssl rsa -in ${h(n)} -pubout -outform PEM 2>/dev/null | grep -v '^-----' | tr -d '\\n')"`)}return t.push(`chown -R ${T}:${T} ${S}/dkim`),t}function ye(e){if(e.accounts.length===0)return[];let t=(r)=>`runuser -u ${T} -- env SMTP_DB_PATH="$TS_CLOUD_MAIL_DB" ${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 re(e){if(!e.enabled)return[];return[...Ye(fe(e)),`id -u ${T} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin ${T}`,`mkdir -p ${e.storagePath} ${S}`,`chown -R ${T}:${T} ${e.storagePath}`,`TS_CLOUD_MAIL_DB="$(grep -sE '^SMTP_DB_PATH=' ${S}/mail.env | head -1 | cut -d= -f2- || true)"`,`[ -n "$TS_CLOUD_MAIL_DB" ] || TS_CLOUD_MAIL_DB=${h(te(e))}`,`cat > ${S}/config.toml <<'TS_CLOUD_MAIL_CONF_EOF'`,ge(e),"TS_CLOUD_MAIL_CONF_EOF",`cat > ${S}/mail.env <<'TS_CLOUD_MAIL_ENV_EOF'`,Te(e),"TS_CLOUD_MAIL_ENV_EOF",`sed -i "s|^SMTP_DB_PATH=.*|SMTP_DB_PATH=$TS_CLOUD_MAIL_DB|" ${S}/mail.env`,`chmod 0640 ${S}/mail.env`,`chown root:${T} ${S}/mail.env`,...ve(e),`cat > /etc/systemd/system/${q}.service <<'TS_CLOUD_MAIL_UNIT_EOF'`,he(e),"TS_CLOUD_MAIL_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${q}`,`systemctl restart ${q}`,...ye(e)]}var g=`${M}/pantry/.bin`,W=15306,K=15991,V=15999,ne=16101,w=2379,v="/var/lib/vitess",X=100;function ai(e){return e===!0||typeof e==="object"&&e!==null}function Ee(e){return typeof e==="object"&&e!==null?e:{}}function m(e){return`'${String(e).split("'").join("'\\''")}'`}function Pe(e){let r=[e.version?`vitess.io@${e.version}`:"vitess.io"];if(e.mode!=="combo"&&!e.etcdEndpoint)r.push("etcd.io");return r.push("mysql.com@8.0.43"),r}var _="vitess",be=`${g}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`,ae="/usr/local/lib/vitess",Q=new Map;function j(e){return`${ae}/${e}.sh`}function D(e,t){return Q.set(e,Ce(t)),`/bin/sh ${j(e)}`}function se(){let e=[`mkdir -p ${ae}`];for(let[t,r]of Q)e.push(`cat > ${j(t)} <<'TS_CLOUD_VITESS_LAUNCHER_EOF'`,r,"TS_CLOUD_VITESS_LAUNCHER_EOF",`chmod 0755 ${j(t)}`);return e}function Ce(e){return["#!/bin/sh","set -e",`cd ${M}`,`PANTRY_ENV="$(pantry env 2>/dev/null | grep -E '^(export [A-Za-z_]|[A-Za-z_][A-Za-z0-9_]*=)' || true)"`,'if [ -n "$PANTRY_ENV" ]; then eval "$PANTRY_ENV"; fi',`VT_MYSQL_ROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqld 2>/dev/null)")")"`,`VTROOT="$(dirname "$(dirname "$(readlink -f ${g}/mysqlctld 2>/dev/null)")")"`,"export VT_MYSQL_ROOT VTROOT",'LD_LIBRARY_PATH="$VT_MYSQL_ROOT/lib:$VTROOT/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"',"export LD_LIBRARY_PATH",`exec ${e.join(" ")}`].join(`
|
|
5
5
|
`)}function A(e){let t=["[Unit]",`Description=${e.description}`,`After=network.target${e.after?.length?` ${e.after.join(" ")}`:""}`];if(e.requires?.length)t.push(`Requires=${e.requires.join(" ")}`);return t.push("","[Service]","Type=simple",`User=${_}`,`Group=${_}`,`Environment="PATH=${be}"`,`Environment="VTDATAROOT=${v}"`,...Object.entries(e.environment??{}).map(([r,n])=>`Environment="${r}=${n}"`),...(e.execStartPre??[]).map((r)=>`ExecStartPre=${r}`),`ExecStart=${e.execStart}`,"Restart=always","RestartSec=5","LimitNOFILE=65535","","[Install]","WantedBy=multi-user.target"),t.join(`
|
|
6
|
-
`)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??X,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${w}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${B}`,`--advertise-client-urls http://127.0.0.1:${B}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${B}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${w}`,`--port ${w+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(z).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${z}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",U="/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 ${U} ] && [ "$(cat ${U})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??X}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${B}`,n=`${g}/vtctldclient --server 127.0.0.1:${w}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(z).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??X;return["for i in $(seq 1 60); do",` if (cd ${L} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function mo(e){if(!oi(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Qe(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${U}; chown ${_}:${_} ${U}; chmod 0600 ${U}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function si(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function yr(e,t="psql"){let r=e?.port??5432;if(si(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(x.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function go(e={},t={}){let r=Ne(e),n=mo(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Qe(r.packages),...po(r.services),...n,...i]}function yt(e,t={}){if(!e?.name)return[];if(!si(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,O=(u,N)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(N)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(N)};`," END IF;","END $$;"],I=(u)=>{let N=u.databases&&u.databases.length>0?u.databases:[r],H=[];for(let q of N)if(u.access==="readonly")H.push(`GRANT CONNECT ON DATABASE ${a(q)} TO ${a(u.username)};`,`\\connect ${a(q)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else H.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(q)} TO ${a(u.username)};`);return H},k=e.users||[],me=e.port??5432;return[ht(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${yr(e)} <<'TS_CLOUD_PG_EOF'`,...O(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...k.flatMap((u)=>[...O(u.username,u.password),...I(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],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 R)I.push(`GRANT ${O} ON \`${o(k)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${O} ON \`${o(k)}\`.* TO '${f(a.username)}'@'localhost';`);return I},p=e.users||[];return[ht(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${yr(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 ic(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Qr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
6
|
+
`)}function oe(e,t){return[`cat > /etc/systemd/system/${e}.service <<'TS_CLOUD_VITESS_UNIT_EOF'`,t,"TS_CLOUD_VITESS_UNIT_EOF"]}function Re(e){let t=e.cell??"zone1",r=e.vtgatePort??W,i=`${((e.keyspaces?.length)?e.keyspaces:[{name:"app"}]).map((s)=>{let c=(s.sharded?["-80","80-"]:["0"]).map((d)=>`shards:{name:"${d}"}`).join(" ");return`keyspaces:{name:"${s.name}" ${c}}`}).join(" ")} cells:"${t}"`;return A({description:"Vitess (vtcombo, single-process development stack)",execStart:D("vtcombo",[`${g}/vtcombo`,`--cell ${t}`,`--proto-topo ${m(i)}`,`--mysql-server-port ${r}`,"--mysql-server-bind-address 127.0.0.1","--mysql-auth-server-impl none","--start-mysql",`--port ${K}`,`--grpc-port ${V}`])})}function De(){return A({description:"etcd (Vitess topology store)",execStart:D("etcd",[`${g}/etcd`,`--data-dir ${v}/etcd`,`--listen-client-urls http://127.0.0.1:${w}`,`--advertise-client-urls http://127.0.0.1:${w}`]),execStartPre:[`+/bin/mkdir -p ${v}/etcd`,`+/bin/chown ${_}:${_} ${v}/etcd`]})}function J(e){return["--topo-implementation etcd2",`--topo-global-server-address ${e.etcdEndpoint??`http://127.0.0.1:${w}`}`,"--topo-global-root /vitess/global"]}function Ae(e){let t=!e.etcdEndpoint;return A({description:"Vitess vtctld (control plane)",after:t?["vitess-etcd.service"]:[],requires:t?["vitess-etcd.service"]:[],execStart:D("vtctld",[`${g}/vtctld`,...J(e),`--cell ${e.cell??"zone1"}`,"--service-map grpc-vtctl,grpc-vtctld",`--grpc-port ${V}`,`--port ${V+1}`])})}function Le(e,t,r){let n=e.cell??"zone1";return A({description:`Vitess vttablet (${t}/${r})`,after:["vitess-vtctld.service","vitess-mysqlctld.service"],requires:["vitess-mysqlctld.service"],execStart:D("vttablet",[`${g}/vttablet`,...J(e),`--tablet-path ${n}-${String(X).padStart(10,"0")}`,`--init-keyspace ${t}`,`--init-shard ${r}`,"--init-tablet-type replica",`--service-map ${m("grpc-queryservice,grpc-tabletmanager,grpc-updatestream")}`,`--port ${ne}`,`--grpc-port ${ne+1}`,`--db-port ${e.mysqlPort??3306}`,`--mycnf-mysql-port ${e.mysqlPort??3306}`])})}function Oe(e){return A({description:"Vitess mysqlctld (managed mysqld)",execStart:D("mysqlctld",[`${g}/mysqlctld`,`--tablet-uid ${X}`,`--mysql-port ${e.mysqlPort??3306}`,'--init-db-sql-file "$VTROOT/config/init_db.sql"',"--wait-time 2m"]),execStartPre:[`+/bin/mkdir -p ${v}`,`+/bin/chown ${_}:${_} ${v}`]})}var ce="/etc/vitess/auth.json",x="/var/lib/vitess/vtgate-auth.sha256";function xe(e){let t=e.username??"vitess",r=e.password??"";return["mkdir -p /etc/vitess",'VTESS_AUTH_TMP="$(mktemp)"',`cat > "$VTESS_AUTH_TMP" <<'TS_CLOUD_VITESS_AUTH_EOF'`,JSON.stringify({[t]:[{Password:r,UserData:t}]}),"TS_CLOUD_VITESS_AUTH_EOF",`VTESS_VTGATE_AUTH_SHA="$(sha256sum "$VTESS_AUTH_TMP" | awk '{print $1}')"`,"VTESS_VTGATE_AUTH_CHANGED=1",`if [ -f ${x} ] && [ "$(cat ${x})" = "$VTESS_VTGATE_AUTH_SHA" ]; then VTESS_VTGATE_AUTH_CHANGED=0; fi`,`install -o ${_} -g ${_} -m 0600 "$VTESS_AUTH_TMP" ${ce}`,'rm -f "$VTESS_AUTH_TMP"']}function Ue(e){let t=e.cell??"zone1";return A({description:"Vitess vtgate (query router)",after:["vitess-vtctld.service"],execStart:D("vtgate",[`${g}/vtgate`,...J(e),`--cell ${t}`,`--cells-to-watch ${t}`,"--tablet-types-to-wait PRIMARY,REPLICA",`--service-map ${m("grpc-vtgateservice")}`,`--mysql-server-port ${e.vtgatePort??W}`,`--mysql-server-bind-address ${e.bindAddress??"127.0.0.1"}`,"--mysql-auth-server-impl static",`--mysql-auth-server-static-file ${ce}`,`--port ${K}`,`--grpc-port ${K+1}`])})}function Ie(e){let t=e.cell??"zone1",r=e.etcdEndpoint??`http://127.0.0.1:${w}`,n=`${g}/vtctldclient --server 127.0.0.1:${V}`,i=[`for i in $(seq 1 30); do ${n} GetCellInfoNames >/dev/null 2>&1 && break; sleep 2; done`,`if ! ${n} GetCellInfoNames 2>/dev/null | grep -qx ${m(t)}; then`,` ${n} AddCellInfo --root ${m(`/vitess/${t}`)} --server-address ${m(r)} ${m(t)}`,"fi"];for(let s of e.keyspaces??[]){let c=s.sharded?" --sharded":"";i.push(`if ! ${n} GetKeyspace ${m(s.name)} >/dev/null 2>&1; then`,` ${n} CreateKeyspace${c} ${m(s.name)}`,"fi");let d=`${t}-${String(X).padStart(10,"0")}`;for(let l of s.sharded?["-80","80-"]:["0"]){let o=`${s.name}/${l}`;i.push("for i in $(seq 1 90); do",` if ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then break; fi`,` ${n} PlannedReparentShard ${m(o)} --new-primary ${m(d)} >/dev/null 2>&1 && break`,` ${n} InitShardPrimary --force ${m(o)} ${m(d)} >/dev/null 2>&1 && break`," sleep 2","done",`if ! ${n} GetShard ${m(o)} 2>/dev/null | grep -q '"is_primary_serving": *true'; then`,` echo "no primary could be elected for ${o}" >&2; exit 1`,"fi")}i.push(`${n} RebuildKeyspaceGraph ${m(s.name)} >/dev/null`)}return i}function ie(e){let t=e.vtgatePort??W;return["for i in $(seq 1 60); do",` if (cd ${M} && eval "$(pantry env 2>/dev/null)"; MYSQL_PWD=${m(e.password??"")} ${g}/mysql -h 127.0.0.1 -P ${t} -u ${m(e.username??"vitess")} --connect-timeout=2 -e 'SHOW KEYSPACES') >/dev/null 2>&1; then`,` echo "vtgate is serving on ${t}"; exit 0`," fi"," sleep 2","done",`echo "vtgate did not become ready on port ${t}" >&2`,"exit 1"]}function fo(e){if(!ai(e))return[];let t=Ee(e),r=t.mode==="combo";Q.clear();let n=['if [ "$(uname -m)" != "x86_64" ]; then',' echo "vitess: Vitess publishes only x86_64 release tarballs; this box is $(uname -m). Drop managedServices.vitess or use an x86_64 host." >&2'," exit 1","fi",...Ye(Pe(t)),`VT_MYSQL_LIB="$(dirname "$(dirname "$(readlink -f ${g}/mysqld)")")/lib"`,'if [ -d "$VT_MYSQL_LIB" ]; then',` printf '%s\\n' "$VT_MYSQL_LIB" > /etc/ld.so.conf.d/vitess-mysql.conf`," ldconfig","else",' echo "mysqld library directory not found under $VT_MYSQL_LIB" >&2; exit 1',"fi",`id -u ${_} >/dev/null 2>&1 || useradd --system --home-dir ${v} --shell /usr/sbin/nologin ${_}`,`mkdir -p ${v}`,`chown -R ${_}:${_} ${v}`];if(r)return n.push(...oe("vitess-vtcombo",Re(t)),...se(),"systemctl daemon-reload","systemctl enable --now vitess-vtcombo.service",...ie(t)),n;n.push(...xe(t));let i=[];if(!t.etcdEndpoint)i.push(["vitess-etcd",De()]);i.push(["vitess-vtctld",Ae(t)],["vitess-mysqlctld",Oe(t)],["vitess-vtgate",Ue(t)]);for(let s of t.keyspaces??[])for(let c of s.sharded?["-80","80-"]:["0"])i.push([`vitess-vttablet-${s.name}-${c.replace(/-/g,"x")}`,Le(t,s.name,c)]);for(let[s,c]of i)n.push(...oe(s,c));n.push(...se()),n.push("systemctl daemon-reload");for(let[s]of i)n.push(`systemctl enable --now ${s}.service`);return n.push(`if [ "$VTESS_VTGATE_AUTH_CHANGED" = 1 ]; then systemctl restart vitess-vtgate.service; printf '%s\\n' "$VTESS_VTGATE_AUTH_SHA" > ${x}; chown ${_}:${_} ${x}; chmod 0600 ${x}; fi`,...Ie(t),...ie(t)),n}var ke=new Set(["singlestore","vitess"]);function ci(e){if(e?.engine&&ke.has(e.engine))return!1;return!e?.host||e.host==="127.0.0.1"||e.host==="localhost"}function br(e,t="psql"){let r=e?.port??5432;if(ci(e))return`${t} -p ${r} -U postgres`;let n=e?.username||"postgres";return`${e?.password?`PGPASSWORD='${e.password.replace(/'/g,"'\\''")}' `:""}${t} -h ${e.host} -p ${r} -U ${n} -w`}function y(e){return e===!0||typeof e==="object"&&e!=null}function Ne(e){let t=[],r=[];if(y(e.mysql))t.push(typeof e.mysql==="object"&&e.mysql.version?`mysql.com@${e.mysql.version}`:"mysql.com@8.0.43"),r.push("mysql");else if(y(e.mariadb))t.push(O.mariadb),r.push("mariadb");if(y(e.postgres))t.push("postgresql.org"),r.push("postgres");if(y(e.redis))t.push("redis.io"),r.push("redis");if(y(e.memcached))t.push("memcached.org"),r.push("memcached");if(y(e.meilisearch))t.push("meilisearch.com"),r.push("meilisearch");return{packages:t,services:r}}function ho(e={},t={}){let r=Ne(e),n=fo(e.vitess),i=t.mail?re(t.mail):[];if(r.packages.length===0)return[...n,...i];return[...Ye(r.packages),...go(r.services),...n,...i]}function St(e,t={}){if(!e?.name)return[];if(!ci(e))return[];let r=e.name,n=e.username||r,i=e.password||"",s=y(t.postgres)||e.engine==="postgres",c=y(t.mariadb)||e.engine==="mariadb",d=y(t.mysql)||e.engine==="mysql";if(s&&!d&&!c){let a=(u)=>`"${u.replace(/"/g,'""')}"`,R=(u)=>`'${u.replace(/'/g,"''")}'`,L=(u,k)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${R(u)}) THEN`,` CREATE ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," ELSE",` ALTER ROLE ${a(u)} LOGIN PASSWORD ${R(k)};`," END IF;","END $$;"],U=(u)=>{let k=u.databases&&u.databases.length>0?u.databases:[r],B=[];for(let H of k)if(u.access==="readonly")B.push(`GRANT CONNECT ON DATABASE ${a(H)} TO ${a(u.username)};`,`\\connect ${a(H)}`,`GRANT USAGE ON SCHEMA public TO ${a(u.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${a(u.username)};`,`ALTER DEFAULT PRIVILEGES FOR ROLE ${a(n)} IN SCHEMA public GRANT SELECT ON TABLES TO ${a(u.username)};`,"\\connect postgres");else B.push(`GRANT ALL PRIVILEGES ON DATABASE ${a(H)} TO ${a(u.username)};`);return B},I=e.users||[],me=e.port??5432;return[yt(),`for i in $(seq 1 30); do pg_isready -p ${me} -q && break; sleep 2; done`,`${br(e)} <<'TS_CLOUD_PG_EOF'`,...L(n,i),`SELECT 'CREATE DATABASE ${a(r)} OWNER ${a(n)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${R(r)})\\gexec`,...I.flatMap((u)=>[...L(u.username,u.password),...U(u)]),"TS_CLOUD_PG_EOF",...Me(e)]}let l=c?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",o=(a)=>a.replace(/`/g,"``"),f=(a)=>a.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),E=(a)=>{let R=a.databases&&a.databases.length>0?a.databases:[r],L=a.access==="readonly"?"SELECT":"ALL PRIVILEGES",U=[`CREATE USER IF NOT EXISTS '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`CREATE USER IF NOT EXISTS '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'%' IDENTIFIED BY '${f(a.password)}';`,`ALTER USER '${f(a.username)}'@'localhost' IDENTIFIED BY '${f(a.password)}';`];for(let I of R)U.push(`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'%';`,`GRANT ${L} ON \`${o(I)}\`.* TO '${f(a.username)}'@'localhost';`);return U},p=e.users||[];return[yt(),`for i in $(seq 1 30); do mysqladmin --socket=${l} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${l} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${o(r)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...E({username:n,password:i}),...p.flatMap(E),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function Me(e){return[`${br(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 ac(e){if(!e?.name)return{};let t=e.engine==="singlestore",r=e.engine==="vitess",n=e.engine==="postgres"?"pgsql":t?"singlestore":r?"vitess":"mysql",i=e.port??(e.engine==="postgres"?5432:r?15306:3306),s={DB_CONNECTION:n,DB_HOST:e.host||"127.0.0.1",DB_PORT:String(i),DB_DATABASE:e.name};if(e.username)s.DB_USERNAME=e.username;if(e.password)s.DB_PASSWORD=e.password;if((t||r)&&e.ssl!==!1)s.DB_SSL="true";return s}var Z="/var/backups/ts-cloud",Ve="/etc/ts-cloud/backups.config.ts",le="/etc/cron.d/ts-cloud-backups",Zr="/usr/local/bin/ts-cloud-backup.sh";function we(e){if(!e.name)return null;let t=e.host||"127.0.0.1",r=e.engine==="postgres",n=r?"postgresql":"mysql",i=e.port??(r?5432:3306),s=(c)=>c.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${n}',`,` name: '${s(e.name)}',`," connection: {",` hostname: '${s(t)}',`,` port: ${i},`,` database: '${s(e.name)}',`,` username: '${s(e.username||e.name)}',`,` password: '${s(e.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
7
7
|
`)}function Be(e,t){let r=e?we(e):null,n=t.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${t.bucket}',`," prefix: 'db-backups',",...t.endpoint?[` endpoint: '${t.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,",` outputPath: '${Z}',`," retention: {",` count: ${t.retentionCount??5},`,` maxAge: ${t.retentionDays??30},`," },"," databases: [",...r?[r]:[]," ],",...n,"}","","export default config",""].join(`
|
|
8
|
-
`)}function
|
|
9
|
-
export{
|
|
8
|
+
`)}function yo(e){let{database:t,backups:r}=e;if(!r.enabled)return[];let n=r.schedule||"0 2 * * *",i=Be(t,r);return["export DEBIAN_FRONTEND=noninteractive",`mkdir -p /etc/ts-cloud ${Z}`,"command -v bun >/dev/null 2>&1 || (curl -fsSL https://bun.sh/install | bash && ln -sf /root/.bun/bin/bun /usr/local/bin/bun)","bun add -g ts-backups || true",`cat > ${Ve} <<'TS_CLOUD_BACKUP_CFG_EOF'`,i.replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF",`cat > ${Zr} <<'TS_CLOUD_BACKUP_RUN_EOF'`,"#!/bin/bash","set -uo pipefail",'export PATH="/root/.bun/bin:/usr/local/bin:$PATH"','notify() { [ -x /usr/local/bin/ts-cloud-notify ] && /usr/local/bin/ts-cloud-notify "$1" || true; }',"cd /etc/ts-cloud",'if ! ts-backups backup --config /etc/ts-cloud/backups.config.ts; then notify "❌ ts-cloud backup failed"; exit 1; fi',"TS_CLOUD_BACKUP_RUN_EOF",`chmod +x ${Zr}`,`cat > ${le} <<'TS_CLOUD_BACKUP_CRON_EOF'`,`${n} root ${Zr} >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF",`chmod 644 ${le}`]}function He(e){return e==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function li(e,t={}){if(!e?.name)return[];let r=e.name,n=e.engine==="postgres",i=t.from?`TS_CLOUD_DUMP="${t.from}"`:`TS_CLOUD_DUMP="$(find ${Z} -type f -name '*${r}*.sql' -o -type f -name '*${r}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,s=n?`${br(e)} -d "${r}"`:`mysql --socket=${He(e.engine)} -u root "${r}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',i,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+r+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${s}`,'echo "restore complete"']}var So=["storage",".env"],di=4;function C(e){return`${e.replace(/\/+$/,"")}/.ts-cloud`}function xs(e){return`${C(e)}/deploy-history.log`}function qe(e,t){return`${C(e)}/deploys/${t}.log`}function ue(e){return`${C(e)}/shared-paths`}function bo(e){return`${e.shared}/stx-images`}function Bt(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 $s(e){return typeof e==="string"?e:e.path}function cc(e){let t=new Map;for(let r of e)t.set($s(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 ui(e,t=So){let r=[`mkdir -p ${e.releases} ${e.shared} ${bo(e)}`,...Fe(e)],n=t.map((s)=>$e(e,s));for(let{path:s,target:c,seed:d}of n){if(!d)continue;if(r.push(`ts_cloud_adopt_shared '${s}' '${c}'`),de(s))r.push(`mkdir -p "$(dirname ${c})"`,`touch ${c}`);else if(s==="storage")r.push(`mkdir -p ${c}/app/public`,`mkdir -p ${c}/framework/cache/data`,`mkdir -p ${c}/framework/sessions`,`mkdir -p ${c}/framework/testing`,`mkdir -p ${c}/framework/views`,`mkdir -p ${c}/logs`);else r.push(`mkdir -p ${c}`)}let i=ue(e.base);return r.push(`mkdir -p ${C(e.base)}`,`cat > ${i} <<'TS_CLOUD_SHARED_PATHS_EOF'`,...n.map((s)=>`${s.path} ${s.target}`),"TS_CLOUD_SHARED_PATHS_EOF"),r}function Os(e,t=900){let r=`${C(e.base)}/deploy.lock`;return[`mkdir -p "$(dirname ${r})"`,`exec 9>${r}`,`flock -w ${t} 9 || { echo "[ts-cloud] another deploy of this site has held the lock for ${t}s — refusing to race it" >&2; exit 1; }`]}function Ls(e){let t=`${e.release}.incoming`;return[`rm -rf ${t}`,`mkdir -p ${t}`,...Ge(e),'if [ "$TS_CLOUD_IS_LIVE" = "yes" ]; then',` TS_CLOUD_STAGED=${t}`,"else",` rm -rf ${e.release}`,` mkdir -p ${e.release}`,` rmdir ${t}`,` TS_CLOUD_STAGED=${e.release}`,"fi"]}function Ms(e){let t=`TS_CLOUD_TRAP_LIVE="$(readlink -f ${e.current} 2>/dev/null || true)"`,r=`TS_CLOUD_TRAP_TARGET="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`;return`trap '${`if [ $? -ne 0 ]; then ${t}; ${r}; [ "$TS_CLOUD_TRAP_LIVE" = "$TS_CLOUD_TRAP_TARGET" ] || rm -rf ${e.release}; fi`}' EXIT`}function Ge(e){return[`TS_CLOUD_LIVE_PATH="$(readlink -f ${e.current} 2>/dev/null || true)"`,`TS_CLOUD_RELEASE_PATH="$(readlink -f ${e.release} 2>/dev/null || echo ${e.release})"`,'if [ -n "$TS_CLOUD_LIVE_PATH" ] && [ "$TS_CLOUD_LIVE_PATH" = "$TS_CLOUD_RELEASE_PATH" ]; then TS_CLOUD_IS_LIVE=yes; else TS_CLOUD_IS_LIVE=no; fi']}function Us(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 vo(e,t=So){let r=[];for(let n of t){let{path:i,target:s,seed:c}=$e(e,n),d=`${e.release}/${i}`,l=[`rm -rf ${d}`,`mkdir -p "$(dirname ${d})"`,`ln -sfn ${s} ${d}`];if(c){if(i!==".env"&&de(i))r.push(...Ke(d,s));r.push(...l);continue}r.push(`if [ -e ${s} ]; then`,...l.map((o)=>` ${o}`),"fi")}return r}function pe(e,t){let r=ue(e.base);return[`if [ -f ${r} ]; then`,' while IFS="\t" read -r TS_CLOUD_SP TS_CLOUD_TGT; do',' [ -n "$TS_CLOUD_SP" ] || continue',` [ -n "$TS_CLOUD_TGT" ] || TS_CLOUD_TGT="${e.shared}/$TS_CLOUD_SP"`,' [ -e "$TS_CLOUD_TGT" ] || continue',` rm -rf ${t}/"$TS_CLOUD_SP"`,` mkdir -p "$(dirname ${t}/"$TS_CLOUD_SP")"`,` ln -sfn "$TS_CLOUD_TGT" ${t}/"$TS_CLOUD_SP"`,` done < ${r}`,"fi"]}function en(e){return[`ln -sfn ${e.release} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]}function lc(e,t={}){let r=t.to?[`[ -d ${e.releases}/${t.to} ] || { echo "rollback target ${e.releases}/${t.to} not found" >&2; exit 1; }`,...pe(e,`${e.releases}/${t.to}`),`ln -sfn ${e.releases}/${t.to} ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`]:[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | while read -r r; do [ "$(readlink -f "$r")" != "$TS_CLOUD_CURRENT" ] && { echo "$r"; break; }; done)`,'[ -n "$TS_CLOUD_PREV" ] || { echo "no previous release to roll back to" >&2; exit 1; }',...pe(e,'"$TS_CLOUD_PREV"'),`ln -sfn "$TS_CLOUD_PREV" ${e.current}.tmp`,`mv -Tf ${e.current}.tmp ${e.current}`,'echo "rolled back to $TS_CLOUD_PREV"'];if(!t.unitBase)return r;let n=t.unitBase;return[...r,`TS_CLOUD_RB_ID=$(basename "$(readlink -f ${e.current})")`,`if [ -f /etc/systemd/system/${n}@.service ]; then systemctl start "${n}@\${TS_CLOUD_RB_ID}.service"; sleep 2; systemctl is-active --quiet "${n}@\${TS_CLOUD_RB_ID}.service" || { echo "rolled-back release failed to start" >&2; exit 1; }; systemctl enable "${n}@\${TS_CLOUD_RB_ID}.service" 2>/dev/null || true; systemctl list-units --plain --no-legend --type=service "${n}@*.service" 2>/dev/null | awk '{print $1}' | { grep -v "^${n}@\${TS_CLOUD_RB_ID}.service$" || true; } | while read -r TS_CLOUD_U; do systemctl stop "$TS_CLOUD_U" 2>/dev/null || true; systemctl disable "$TS_CLOUD_U" 2>/dev/null || true; done; elif [ -f /etc/systemd/system/${n}.service ]; then systemctl restart ${n}.service; fi`]}function tn(e,t=4){let r=Math.max(1,t);return[`TS_CLOUD_CURRENT=$(readlink -f ${e.current} 2>/dev/null || true)`,`ls -1dt ${e.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${r+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function je(e){return`${C(e)}/owner`}function Bs(e,t){let r=je(e);return[`if [ -f "${r}" ]; then`,` TS_CLOUD_OWNER=$(cat "${r}")`,` if [ "$TS_CLOUD_OWNER" != "${t}" ]; then`,` echo "[ts-cloud] REFUSING deploy: ${e} belongs to project '$TS_CLOUD_OWNER', not '${t}'. Another project on this box derives the same site key — give one of them a distinct site name/domain, or remove ${r} to transfer ownership." >&2`," exit 1"," fi","else",` mkdir -p "$(dirname "${r}")"`,` printf '%s\\n' "${t}" > "${r}"`,"fi"]}function To(e,t){let r=C(e),n=qe(e,t.releaseId),i=xs(e),s=Math.max(1,t.keepLogs??20),c=t.commit||"",d=t.branch||"";return[`mkdir -p ${r}/deploys`,`exec > >(tee -a ${n}) 2>&1`,`echo "[ts-cloud] deploy ${t.releaseId} commit=${c} branch=${d} starting $(date -u +%Y-%m-%dT%H:%M:%SZ)"`,"ts_cloud_record_deploy() {"," TS_CLOUD_RC=$?",' if [ "$TS_CLOUD_RC" -eq 0 ]; then TS_CLOUD_ST=success; else TS_CLOUD_ST=failed; fi',` printf '%s\\t%s\\t%s\\t%s\\trc=%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "${t.releaseId}" "${c}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${i}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${r}/deploys/*.log 2>/dev/null | tail -n +${s+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}
|
|
9
|
+
export{G,si,Ds,P,mo,ks,_s,oc,sc,M,Sr,yt,Ye,go,ai,fo,ci,br,ho,St,ac,Zr,yo,li,So,di,xs,bo,Bt,$s,cc,ui,Os,Ls,Ms,Us,vo,en,lc,tn,Bs,To};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{u}from"./chunk-mbqwrs7a.js";import{O,bt}from"./chunk-f3sbq7pw.js";class j{client;region;constructor(e="us-east-1",i){this.region=e,this.client=new u}async createQueue(e){let t={Action:"CreateQueue",QueueName:e.fifo&&!e.queueName.endsWith(".fifo")?`${e.queueName}.fifo`:e.queueName,Version:"2012-11-05"},s=1;if(e.visibilityTimeout!==void 0)t[`Attribute.${s}.Name`]="VisibilityTimeout",t[`Attribute.${s}.Value`]=e.visibilityTimeout.toString(),s++;if(e.messageRetentionPeriod!==void 0)t[`Attribute.${s}.Name`]="MessageRetentionPeriod",t[`Attribute.${s}.Value`]=e.messageRetentionPeriod.toString(),s++;if(e.delaySeconds!==void 0)t[`Attribute.${s}.Name`]="DelaySeconds",t[`Attribute.${s}.Value`]=e.delaySeconds.toString(),s++;if(e.maxMessageSize!==void 0)t[`Attribute.${s}.Name`]="MaximumMessageSize",t[`Attribute.${s}.Value`]=e.maxMessageSize.toString(),s++;if(e.receiveMessageWaitTime!==void 0)t[`Attribute.${s}.Name`]="ReceiveMessageWaitTimeSeconds",t[`Attribute.${s}.Value`]=e.receiveMessageWaitTime.toString(),s++;if(e.fifo){if(t[`Attribute.${s}.Name`]="FifoQueue",t[`Attribute.${s}.Value`]="true",s++,e.contentBasedDeduplication)t[`Attribute.${s}.Name`]="ContentBasedDeduplication",t[`Attribute.${s}.Value`]="true",s++}if(e.deadLetterTargetArn&&e.maxReceiveCount)t[`Attribute.${s}.Name`]="RedrivePolicy",t[`Attribute.${s}.Value`]=JSON.stringify({deadLetterTargetArn:e.deadLetterTargetArn,maxReceiveCount:e.maxReceiveCount}),s++;if(e.tags&&Object.keys(e.tags).length>0){let a=1;for(let[n,g]of Object.entries(e.tags))t[`Tag.${a}.Key`]=n,t[`Tag.${a}.Value`]=g,a++}let r=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{QueueUrl:r.QueueUrl||r.CreateQueueResult?.QueueUrl}}async listQueues(e){let i={Action:"ListQueues",Version:"2012-11-05"};if(e)i.QueueNamePrefix=e;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[];if(t.QueueUrl)s.push(t.QueueUrl);else if(t.ListQueuesResult?.QueueUrl)if(Array.isArray(t.ListQueuesResult.QueueUrl))s.push(...t.ListQueuesResult.QueueUrl);else s.push(t.ListQueuesResult.QueueUrl);return{QueueUrls:s}}async getQueueAttributes(e){let i={Action:"GetQueueAttributes",QueueUrl:e,Version:"2012-11-05","AttributeName.1":"All"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s={};for(let r of bt(O(t,"GetQueueAttributes")?.Attribute))s[r.Name]=String(r.Value);return{Attributes:s}}async getQueueUrl(e){let i={Action:"GetQueueUrl",QueueName:e,Version:"2012-11-05"},t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{QueueUrl:t.QueueUrl||t.GetQueueUrlResult?.QueueUrl}}async deleteQueue(e){let i={Action:"DeleteQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async purgeQueue(e){let i={Action:"PurgeQueue",QueueUrl:e,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()})}async sendMessage(e){let i={Action:"SendMessage",QueueUrl:e.queueUrl,MessageBody:e.messageBody,Version:"2012-11-05"};if(e.delaySeconds!==void 0)i.DelaySeconds=e.delaySeconds;if(e.messageGroupId)i.MessageGroupId=e.messageGroupId;if(e.messageDeduplicationId)i.MessageDeduplicationId=e.messageDeduplicationId;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()});return{MessageId:t.MessageId||t.SendMessageResult?.MessageId}}async receiveMessages(e){let i={Action:"ReceiveMessage",QueueUrl:e.queueUrl,Version:"2012-11-05"};if(e.maxMessages!==void 0)i.MaxNumberOfMessages=e.maxMessages;if(e.visibilityTimeout!==void 0)i.VisibilityTimeout=e.visibilityTimeout;if(e.waitTimeSeconds!==void 0)i.WaitTimeSeconds=e.waitTimeSeconds;let t=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(i).toString()}),s=[],r=t.Message||t.ReceiveMessageResult?.Message;if(r)if(Array.isArray(r))s.push(...r.map((a)=>({MessageId:a.MessageId,ReceiptHandle:a.ReceiptHandle,Body:a.Body})));else s.push({MessageId:r.MessageId,ReceiptHandle:r.ReceiptHandle,Body:r.Body});return{Messages:s}}async deleteMessage(e,i){let t={Action:"DeleteMessage",QueueUrl:e,ReceiptHandle:i,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}}
|
|
2
|
+
export{j};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?
|
|
1
|
+
import{mi,u}from"./chunk-mbqwrs7a.js";import{pi}from"./chunk-rm6qnyce.js";import*as c from"node:crypto";import{readFileSync as B}from"node:fs";import{readdir as L}from"node:fs/promises";import{join as z}from"node:path";function vt(e){if(e){let i=D(e);if(!i)throw Error(`AWS profile '${e}' not found in ~/.aws/credentials`);return i}let t=process.env.AWS_ACCESS_KEY_ID,s=process.env.AWS_SECRET_ACCESS_KEY;if(t&&s)return{accessKeyId:t,secretAccessKey:s,sessionToken:process.env.AWS_SESSION_TOKEN};return D(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function D(e){let{existsSync:t,readFileSync:s}=pi("node:fs"),{homedir:i}=pi("node:os"),{join:n}=pi("node:path"),r=process.env.AWS_SHARED_CREDENTIALS_FILE||n(i(),".aws","credentials");if(!t(r))return null;let o=s(r,"utf-8"),a=null,l,d,y;for(let h of o.split(`
|
|
2
|
+
`)){let m=h.trim();if(!m||m.startsWith("#")||m.startsWith(";"))continue;let p=m.match(/^\[([^\]]+)\]$/);if(p){if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};a=p[1],l=void 0,d=void 0,y=void 0;continue}if(a===e){let[b,...S]=m.split("="),f=S.join("=").trim();switch(b.trim().toLowerCase()){case"aws_access_key_id":l=f;break;case"aws_secret_access_key":d=f;break;case"aws_session_token":y=f;break}}}if(a===e&&l&&d)return{accessKeyId:l,secretAccessKey:d,sessionToken:y};return null}function U(e){let{buffer:t,byteOffset:s,byteLength:i}=e;if(t instanceof ArrayBuffer)return t.slice(s,s+i);let n=new ArrayBuffer(i);return new Uint8Array(n).set(new Uint8Array(e)),n}function j(e,t){let s=e?.[t]??e;if(s===null||typeof s!=="object"||Array.isArray(s))return s;let i={...s};return delete i["@_xmlns"],i}class g{client;region;explicitProfile;endpoint;endpointProtocol="https";forcePathStyle;explicitCredentials;constructor(e="us-east-1",t,s){let i=typeof e==="string"?s:e,n=typeof e==="string"?e:e.region??"us-east-1",r=typeof e==="string"?t:e.profile,o=i?.endpoint?mi({region:n,path:"/",endpoint:i.endpoint}):void 0;this.region=n,this.explicitProfile=r,this.endpoint=o?.host,this.endpointProtocol=o?.protocol??"https",this.forcePathStyle=i?.forcePathStyle,this.explicitCredentials=i?.credentials,this.client=new u(i?.credentials,{profile:r,endpoint:i?.endpoint,forcePathStyle:i?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let e=vt(this.explicitProfile);if(e.accessKeyId&&e.secretAccessKey)return e;throw Error("S3 credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or pass explicit credentials/profile), or configure ~/.aws/credentials.")}s3BaseHost(){return this.endpoint||`s3.${this.region}.amazonaws.com`}s3VirtualHost(e){return this.forcePathStyle?this.s3BaseHost():`${e}.${this.s3BaseHost()}`}objectPath(e,t){return this.forcePathStyle?`/${e}/${t}`:`/${t}`}objectUrl(e,t){return`${this.endpointProtocol}://${this.s3VirtualHost(e)}${this.objectPath(e,t)}`}async listBuckets(){let e=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),t=[],i=(e?.ListAllMyBucketsResult??e)?.Buckets?.Bucket;if(i){let n=Array.isArray(i)?i:[i];for(let r of n)t.push({Name:r.Name,CreationDate:r.CreationDate})}return{Buckets:t}}async createBucket(e,t){let s={};if(t?.acl)s["x-amz-acl"]=t.acl;let i;if(this.region!=="us-east-1"&&!this.endpoint)i=`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
4
4
|
<LocationConstraint>${this.region}</LocationConstraint>
|
|
5
5
|
</CreateBucketConfiguration>`,s["Content-Type"]="application/xml";await this.client.request({service:"s3",region:this.region,method:"PUT",path:`/${e}`,headers:s,body:i})}async deleteBucket(e){await this.client.request({service:"s3",region:this.region,method:"DELETE",path:`/${e}`})}async emptyAndDeleteBucket(e){let t=!0;while(t){let s=await this.listAllObjects({bucket:e});if(s.length===0){t=!1;break}let i=s.map((n)=>n.Key);for(let n=0;n<i.length;n+=1000){let r=i.slice(n,n+1000);await this.deleteObjects(e,r)}}await this.deleteBucket(e)}async listAllObjects(e){let t=[],s;do{let i={"list-type":"2","max-keys":"1000"};if(e.prefix)i.prefix=e.prefix;if(s)i["continuation-token"]=s;let n=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`,queryParams:i}),r=n?.ListBucketResult??n,o=r?.Contents;if(o){let l=Array.isArray(o)?o:[o];for(let d of l)t.push({Key:d.Key,LastModified:d.LastModified||"",Size:Number.parseInt(d.Size||"0"),ETag:d.ETag})}let a=r?.IsTruncated;s=a==="true"||a===!0?r?.NextContinuationToken:void 0}while(s);return t}async list(e){let t=await this.client.request({service:"s3",region:this.region,method:"GET",path:`/${e.bucket}`}),s=[],n=(t?.ListBucketResult??t)?.Contents;if(n){let r=Array.isArray(n)?n:[n];for(let o of r){if(e.prefix&&!o.Key?.startsWith(e.prefix))continue;if(s.push({Key:o.Key||"",LastModified:o.LastModified||"",Size:Number.parseInt(o.Size||"0"),ETag:o.ETag}),e.maxKeys&&s.length>=e.maxKeys)break}}return s}async putObject(e){let t={};if(e.acl)t["x-amz-acl"]=e.acl;if(e.cacheControl)t["Cache-Control"]=e.cacheControl;if(e.contentType)t["Content-Type"]=e.contentType;if(e.metadata)for(let[n,r]of Object.entries(e.metadata))t[`x-amz-meta-${n}`]=r;let s=e.key.split("/").map((n)=>encodeURIComponent(n)).join("/"),i=e.body instanceof Uint8Array&&!Buffer.isBuffer(e.body)?Buffer.from(e.body):e.body;if(Buffer.isBuffer(i)||i instanceof Uint8Array){let n=Buffer.isBuffer(i)?i:Buffer.from(i),{accessKeyId:r,secretAccessKey:o,sessionToken:a}=this.getCredentials(),l=this.s3VirtualHost(e.bucket),d=this.objectPath(e.bucket,s),y=this.objectUrl(e.bucket,s),h=new Date,m=h.toISOString().replace(/[:-]|\.\d{3}/g,""),p=h.toISOString().slice(0,10).replace(/-/g,""),b=c.createHash("sha256").update(n).digest("hex"),S={host:l,"x-amz-date":m,"x-amz-content-sha256":b,...t};if(a)S["x-amz-security-token"]=a;let f=Object.keys(S).sort().map((P)=>`${P.toLowerCase()}:${S[P].trim()}
|
|
@@ -89,4 +89,4 @@ host:${o}
|
|
|
89
89
|
${t.map((n)=>`<Object><Key>${n.Key}</Key>${n.VersionId?`<VersionId>${n.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
90
90
|
`)}
|
|
91
91
|
</Delete>`,i=c.createHash("md5").update(s).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${e}`,queryParams:{delete:""},body:s,headers:{"Content-Type":"application/xml","Content-MD5":i}})}}
|
|
92
|
-
export{
|
|
92
|
+
export{vt,g};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{u}from"./chunk-mbqwrs7a.js";import{O}from"./chunk-f3sbq7pw.js";class v{client;region;constructor(e="us-east-1",t){this.region=e,this.client=new u(void 0,{profile:t})}async createStack(e){let t={Action:"CreateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if(e.parameters)e.parameters.forEach((a,r)=>{t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});if(e.timeoutInMinutes)t.TimeoutInMinutes=e.timeoutInMinutes;if(e.onFailure)t.OnFailure=e.onFailure;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.CreateStackResult?.StackId}}async updateStack(e){let t={Action:"UpdateStack",StackName:e.stackName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((a,r)=>{if(t[`Parameters.member.${r+1}.ParameterKey`]=a.ParameterKey,a.UsePreviousValue)t[`Parameters.member.${r+1}.UsePreviousValue`]="true";else t[`Parameters.member.${r+1}.ParameterValue`]=a.ParameterValue});if(e.capabilities)e.capabilities.forEach((a,r)=>{t[`Capabilities.member.${r+1}`]=a});if(e.roleArn)t.RoleARN=e.roleArn;if(e.tags)e.tags.forEach((a,r)=>{t[`Tags.member.${r+1}.Key`]=a.Key,t[`Tags.member.${r+1}.Value`]=a.Value});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackId:s.StackId||s.UpdateStackResult?.StackId}}async deleteStack(e,t,s){let a={Action:"DeleteStack",StackName:e,Version:"2010-05-15"};if(t)a.RoleARN=t;if(s&&s.length>0)s.forEach((r,m)=>{a[`RetainResources.member.${m+1}`]=r});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(a).toString()})}async describeStacks(e={}){let t={Action:"DescribeStacks",Version:"2010-05-15"};if(e.stackName)t.StackName=e.stackName;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{Stacks:this.parseStacksResponse(s)}}async describeStackEvents(e){let t={Action:"DescribeStackEvents",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{StackEvents:this.parseStackEvents(s)}}async listStackResources(e){let t={Action:"ListStackResources",StackName:e,Version:"2010-05-15"},a=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,r=[];if(a)r=Array.isArray(a)?a:[a];return{StackResourceSummaries:r}}async waitForStack(e,t){let s={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},a=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],r=s[t],m=360,i=0;while(i<360)try{let c=await this.describeStacks({stackName:e});if(c.Stacks.length===0){if(t==="stack-delete-complete")return;if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack not visible yet`);await new Promise((o)=>setTimeout(o,2000)),i++;continue}let n=c.Stacks[0];if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Status = ${n.StackStatus}${n.StackStatusReason?` (${n.StackStatusReason})`:""}`);if(r.includes(n.StackStatus))return;if((t==="stack-create-complete"||t==="stack-update-complete")&&(n.StackStatus==="DELETE_IN_PROGRESS"||n.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let o="";try{let S=await this.describeStackEvents(e);console.log("[waitForStack] Stack events (most recent first):");for(let k of S.StackEvents.slice(0,15))if(k.ResourceStatus.includes("FAILED")||k.ResourceStatusReason){if(console.log(` ${k.LogicalResourceId}: ${k.ResourceStatus} - ${k.ResourceStatusReason||"No reason provided"}`),k.ResourceStatus.includes("FAILED")&&k.ResourceStatusReason&&!o)o=k.ResourceStatusReason}}catch{}let l=o||n.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${l}`)}if(n.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let o=Error("Stack deletion failed - may have resources that need to be retained");throw o.code="DELETE_FAILED",o.stackStatus=n.StackStatus,o.statusReason=n.StackStatusReason,o}if(a.includes(n.StackStatus))throw Error(`Stack reached failure status: ${n.StackStatus}`);await new Promise((o)=>setTimeout(o,5000)),i++}catch(c){if(t==="stack-delete-complete"&&c.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&c.message?.includes("does not exist")){if(i%10===0)console.log(`[waitForStack] Attempt ${i}: Stack does not exist (error), retrying...`);await new Promise((n)=>setTimeout(n,2000)),i++;continue}throw console.log(`[waitForStack] Unexpected error: ${c.message}`),c}throw console.log(`[waitForStack] Timeout after ${i} attempts`),Error(`Timeout waiting for stack to reach ${t}`)}async validateTemplate(e){let t={Action:"ValidateTemplate",TemplateBody:e,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()})}async listStacks(e){let t={Action:"ListStacks",Version:"2010-05-15"};if(e)e.forEach((c,n)=>{t[`StackStatusFilter.member.${n+1}`]=c});let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=s.ListStacksResponse||s,r=a.ListStacksResult||a,m=r.StackSummaries?.member||r.StackSummaries||[];return{StackSummaries:(Array.isArray(m)?m:m?[m]:[]).map((c)=>({StackId:c.StackId||"",StackName:c.StackName||"",TemplateDescription:c.TemplateDescription,CreationTime:c.CreationTime||"",LastUpdatedTime:c.LastUpdatedTime,DeletionTime:c.DeletionTime,StackStatus:c.StackStatus||""}))}}async createChangeSet(e){let t={Action:"CreateChangeSet",StackName:e.stackName,ChangeSetName:e.changeSetName,Version:"2010-05-15"};if(e.templateBody)t.TemplateBody=e.templateBody;else if(e.templateUrl)t.TemplateURL=e.templateUrl;if(e.parameters)e.parameters.forEach((r,m)=>{t[`Parameters.member.${m+1}.ParameterKey`]=r.ParameterKey,t[`Parameters.member.${m+1}.ParameterValue`]=r.ParameterValue});if(e.capabilities)e.capabilities.forEach((r,m)=>{t[`Capabilities.member.${m+1}`]=r});if(e.changeSetType)t.ChangeSetType=e.changeSetType;let s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()}),a=O(s,"CreateChangeSet");return{Id:a?.Id,StackId:a?.StackId}}async describeChangeSet(e,t){let s={Action:"DescribeChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async executeChangeSet(e,t){let s={Action:"ExecuteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async deleteChangeSet(e,t){let s={Action:"DeleteChangeSet",StackName:e,ChangeSetName:t,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(s).toString()})}async getStackOutputs(e){let t=await this.describeStacks({stackName:e});if(!t.Stacks||t.Stacks.length===0)throw Error(`Stack ${e} not found`);let s=t.Stacks[0],a={};if(s.Outputs)for(let r of s.Outputs)a[r.OutputKey]=r.OutputValue;return a}async getTemplate(e){let t={Action:"GetTemplate",StackName:e,Version:"2010-05-15"},s=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(t).toString()});return{TemplateBody:s?.GetTemplateResult?.TemplateBody||s?.TemplateBody||""}}parseStacksResponse(e){let t=[],s=e?.DescribeStacksResult?.Stacks?.member||e?.Stacks?.member||e?.Stacks||e;if(s&&!Array.isArray(s))s=[s];if(Array.isArray(s)){for(let a of s)if(a.StackId||a.StackName){let r;if(a.Outputs?.member)r=(Array.isArray(a.Outputs.member)?a.Outputs.member:[a.Outputs.member]).map((i)=>({OutputKey:i.OutputKey,OutputValue:i.OutputValue,Description:i.Description,ExportName:i.ExportName}));t.push({StackId:a.StackId,StackName:a.StackName,StackStatus:a.StackStatus,CreationTime:a.CreationTime,LastUpdatedTime:a.LastUpdatedTime,StackStatusReason:a.StackStatusReason,Outputs:r})}}else if(e.StackId)t.push({StackId:e.StackId,StackName:e.StackName,StackStatus:e.StackStatus,CreationTime:e.CreationTime,LastUpdatedTime:e.LastUpdatedTime});return t}parseStackEvents(e){let t=[],s=e?.DescribeStackEventsResult?.StackEvents?.member||e?.StackEvents?.member||e?.StackEvents||[];if(s&&!Array.isArray(s))s=[s];for(let a of s)if(a.LogicalResourceId)t.push({Timestamp:a.Timestamp,ResourceType:a.ResourceType,LogicalResourceId:a.LogicalResourceId,ResourceStatus:a.ResourceStatus,ResourceStatusReason:a.ResourceStatusReason});return t}async waitForStackWithProgress(e,t,s){let a={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},r=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],m=a[t],i=360,c=0,n=new Set;while(c<360)try{if(s)try{let k=[...(await this.describeStackEvents(e)).StackEvents||[]].reverse();for(let d of k){let g=`${d.LogicalResourceId}-${d.ResourceStatus}-${d.Timestamp}`;if(!n.has(g))n.add(g),s({resourceId:d.LogicalResourceId,resourceType:d.ResourceType,status:d.ResourceStatus,reason:d.ResourceStatusReason,timestamp:d.Timestamp})}}catch{}let o=await this.describeStacks({stackName:e});if(o.Stacks.length===0){if(t==="stack-delete-complete")return;await new Promise((S)=>setTimeout(S,2000)),c++;continue}let l=o.Stacks[0];if(m.includes(l.StackStatus))return;if(l.StackStatus==="DELETE_FAILED"&&t==="stack-delete-complete"){let S=Error("Stack deletion failed - may have resources that need to be retained");throw S.code="DELETE_FAILED",S.stackStatus=l.StackStatus,S.statusReason=l.StackStatusReason,S}if(r.includes(l.StackStatus))throw Error(`Stack reached failure status: ${l.StackStatus}`);await new Promise((S)=>setTimeout(S,3000)),c++}catch(o){if(t==="stack-delete-complete"&&o.message?.includes("does not exist"))return;if(t==="stack-create-complete"&&o.message?.includes("does not exist")){await new Promise((l)=>setTimeout(l,2000)),c++;continue}throw o}throw Error(`Timeout waiting for stack to reach ${t}`)}async waitForStackComplete(e,t=120,s=5000){let a=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],r=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let m=0;m<t;m++)try{let i=await this.describeStacks({stackName:e});if(i.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let c=i.Stacks[0],n=c.StackStatus;if(a.includes(n))return{success:!0,status:n};if(r.includes(n))return{success:!1,status:n,reason:c.StackStatusReason};await new Promise((o)=>setTimeout(o,s))}catch(i){if(i.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw i}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}
|
|
2
|
+
export{v};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Ne,Ys,Co,pa,ln,Lo,ma,ga,va,Ta}from"./chunk-24njmb7d.js";import{n,r,a,e,p,i,ye}from"./chunk-k97ms0bs.js";import{u}from"./chunk-mbqwrs7a.js";import{v}from"./chunk-87f5d9qj.js";import{R}from"./chunk-5bsknbr7.js";import{g}from"./chunk-7xr71hnt.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 W{client;region;constructor(t="us-east-1",s){this.region=t,this.client=new u}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 E(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:Ne(t,s),artifactBucket:Ys(c,s),assetsBucket:Co(c,s)}}function ht(t,s){let o=E(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 L(t,s=8){let o;for(let c=0;c<s;c++)try{return await t()}catch(l){let d=l?.code||l?.name||"",m=String(l?.message||"");if(d==="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 Re(t,s){if(!t.secrets)return{};let o=new W(s),c={},l=Array.isArray(t.secrets)?t.secrets.map((d)=>({envName:d.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:d})):Object.entries(t.secrets).map(([d,m])=>({envName:d,secretId:m}));if(Array.isArray(t.secrets)){let d=new Map;for(let{envName:f,secretId:S}of l)d.set(f,[...d.get(f)??[],S]);let m=[...d.entries()].filter(([,f])=>f.length>1);if(m.length){let f=m.map(([S,h])=>`${S} ← ${h.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:d,secretId:m}of l){let S=(await o.getSecretValue({SecretId:m})).SecretString??"";try{let h=JSON.parse(S);if(h&&typeof h==="object"&&!Array.isArray(h)){for(let[C,w]of Object.entries(h))c[C]=String(w);continue}}catch{}c[d]=S}return c}function Ed(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 vs(t,s,o,c,l,d,m,f={}){let S=t.kind==="php"?va({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}:{},...d?{ASSET_URL:d}:{},...t.env??{},...l}}function he(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 ve(t,s,o,c,l=!1){let d=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:he(m),cacheControl:"public, max-age=31536000, immutable"}),d++}return d}function lo(t,s){let o=Object.entries(s).reduce((c,[l,d])=>c+Buffer.byteLength(`${l}=${d}`,"utf8"),0);if(o>4096){let c=Object.entries(s).map(([l,d])=>[l,Buffer.byteLength(`${l}=${d}`,"utf8")]).sort((l,d)=>d[1]-l[1]).slice(0,5).map(([l,d])=>`${l} (${d}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){lo(s,o),await L(()=>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 L(()=>t.updateFunctionCode(l)),await t.waitForFunctionActive(s,120)}async function X(t,s){let c=(await L(()=>t.publishVersion({FunctionName:s}))).Version;if(!c)throw Error(`publishVersion returned no version for ${s}`);return await L(()=>t.updateAlias({FunctionName:s,Name:"live",FunctionVersion:c})),c}async function ap(t,s,o={}){let c=E(t,s),{app:l,slug:d,region:m,stackName:f,artifactBucket:S}=c,h=o.projectRoot??process.cwd();i(`Deploying serverless app: ${d} (${s})`),e(`Stack: ${f}`),e(`Region: ${m}`);let C=new g(m),w=new v(m),b=new R(m),P=l.kind==="php",O=l.packaging==="image",N=Lo(l),B,I,k,Y,z=[];if(O&&N.usesLayer&&N.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${N.kind}${N.kind==="node"?` ${N.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(O){p("Building + pushing container image");let{buildAndPushServerlessImage:y}=await import("./chunk-27ka240w.js"),A=await y({app:l,projectRoot:h,region:m,repository:`${d}-${s}`,skipBuild:o.skipBuild,onStep:(D)=>e(` ${D}`)});B=A.handlers,I={kind:"image",imageUri:A.imageUri},k=A.tag,z.push({ParameterKey:"ImageUri",ParameterValue:A.imageUri})}else{p("Packaging application");let y=P?Ta({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}):await ln({projectRoot:h,app:l,skipBuild:o.skipBuild,onStep:(x)=>e(` ${x}`)}),A=pa(d,s,y.sha256);if(e(`Artifact: ${y.sha256.slice(0,12)} (${(y.zip.length/1024).toFixed(0)} KB)`),B=y.handlers,k=y.sha256,N.usesLayer){let x=N.layerEnvVar?process.env[N.layerEnvVar]:void 0;if(Y=l.layers??(x?[x]:void 0),!Y?.length){let ge=N.layerKind==="php"?"serverless:build-php-layer":N.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${N.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${N.layerEnvVar} env var (build one with \`cloud ${ge}\`)${N.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await C.bucketExists(S))p(`Creating artifact bucket ${S}`),await C.createBucket(S);if(await C.headObject(S,A).then((x)=>x!==null).catch(()=>!1))e("Artifact already uploaded — reusing");else p("Uploading artifact"),await C.putObject({bucket:S,key:A,body:y.zip,contentType:"application/zip"});I={kind:"zip",bucket:S,key:A},z.push({ParameterKey:"ArtifactBucket",ParameterValue:S},{ParameterKey:"ArtifactKey",ParameterValue:A})}let T=ga({config:t,environment:s,app:l,handlers:B,runtimeLayers:Y}),te=JSON.stringify(T.template),re=["CAPABILITY_NAMED_IAM"],K=await w.describeStacks({stackName:f}).then((y)=>y.Stacks[0]?.StackStatus).catch(()=>{return}),M=K!==void 0;if(K&&/DELETE_IN_PROGRESS/.test(K))p("Waiting for an in-progress stack delete to finish"),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),M=!1;else if(K&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(K))p(`Deleting unusable stack (status ${K}) before recreate`),await w.deleteStack(f),await w.waitForStack(f,"stack-delete-complete").catch(()=>{}),M=!1;p(M?"Updating infrastructure stack":"Creating infrastructure stack");try{if(M)await w.updateStack({stackName:f,templateBody:te,parameters:z,capabilities:re}),await w.waitForStack(f,"stack-update-complete");else await w.createStack({stackName:f,templateBody:te,parameters:z,capabilities:re,onFailure:"DELETE"}),await w.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 w.getStackOutputs(f).catch(()=>({})),F;if(l.assets){let y=ne(h,l.assets);if(de(y)){let A=l.assetDomain||Q.AssetsCdnDomain;F=A?`https://${A}/${k}`:void 0,p(`Syncing assets from ${l.assets}`);let D=await ve(C,c.assetsBucket,y,k,l.dotFilesAsAssets);e(`Uploaded ${D} asset(s)${F?` → ${F}`:""}`)}else a(`Assets directory not found: ${y}`)}p("Resolving secrets");let _=await Re(l,m);if(l.database?.connection==="aurora-serverless")try{let A=await new W(m).getSecretValue({SecretId:`${d}/${s}/db`}),D=JSON.parse(A.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 C.bucketExists(S))await C.createBucket(S);let J=await G(C,S,d,s),q={},Z=T.queueNames[0],ee=Ed(l,Q);if(p("Activating functions"),q.http=vs(l,c,s,"http",_,F,Z,ee),await U(b,T.functionNames.http,q.http,I),q.cli=vs(l,c,s,"cli",_,F,Z,ee),await U(b,T.functionNames.cli,q.cli,I),T.queueNames.length)q.queue=vs(l,c,s,"queue",_,F,Z,ee),await U(b,T.functionNames.queue,q.queue,I);let se=(l.provisionedConcurrency??0)>0,H={};if(se){if(p("Publishing versions + flipping live alias"),H.http=await X(b,T.functionNames.http),H.cli=await X(b,T.functionNames.cli),T.queueNames.length)H.queue=await X(b,T.functionNames.queue)}if(await ae(C,S,d,s,{sha:k,code:I,previousSha:J?.sha,previousCode:J?.code,previousFunctionEnv:J?.functionEnv,...se?{functionVersions:H,previousFunctionVersions:J?.functionVersions}:{},functionEnv:q,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:F,timestamp:new Date().toISOString()}),!o.skipDeployHooks&&l.deploy?.length){p("Running deploy hooks");for(let y of l.deploy){e(` deploy: ${y}`);let A=await b.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:y},LogType:"Tail"});if(A.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}): ${A.Payload}`)}}let j=Q.HttpApiEndpoint;if(!o.skipHealthCheck&&j){p("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}`)}}ye(["Serverless deploy complete","",j?`URL: ${j}`:"",`Stack: ${f}`,`Build: ${k.slice(0,12)}`].filter(Boolean).join(`
|
|
2
|
+
`),"green")}async function Ts(t,s){let o=E(t,s),c=new g(o.region),l=new R(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d)throw Error("No previous release to redeploy. Run a full deploy first.");i(`Redeploying ${o.slug} (${s}) — build ${d.sha.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Re-activating ${m} (${f})`),await U(l,f,d.functionEnv[m]??{},d.code);let S=d.functionVersions?.[m];if(S)await L(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:S}))}n("Redeploy complete")}async function Es(t,s){let o=E(t,s),c=new g(o.region),l=new R(o.region),d=await G(c,o.artifactBucket,o.slug,s);if(!d?.previousCode)throw Error("No previous release to roll back to.");i(`Rolling back ${o.slug} (${s}) → ${d.previousSha?.slice(0,12)}`);for(let[m,f]of Object.entries(d.functionNames)){if(!f)continue;p(`Restoring ${m} (${f})`);let S=d.previousFunctionEnv?.[m]??d.functionEnv[m]??{};await U(l,f,S,d.previousCode);let h=d.previousFunctionVersions?.[m];if(h)await L(()=>l.updateAlias({FunctionName:f,Name:"live",FunctionVersion:h}))}await ae(c,o.artifactBucket,o.slug,s,{...d,sha:d.previousSha??d.sha,code:d.previousCode,functionEnv:d.previousFunctionEnv??d.functionEnv,functionVersions:d.previousFunctionVersions??d.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),n("Rollback complete")}async function uo(t,s,o,c){let l=E(t,s),d=new R(l.region),m=`${l.slug}-${s}-http`,S={...(await d.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 L(()=>d.updateFunctionConfiguration({FunctionName:m,Environment:{Variables:S}})),(l.app.provisionedConcurrency??0)>0)await d.waitForFunctionActive(m,120),await X(d,m);n(o?"Application is now in maintenance mode (503)":"Application is live")}async function Mt(t,s,o){let c=E(t,s),l=new R(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,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`,we=50;async function le(t,s,o,c){try{return(await t.getObjectJson(s,ce(o,c)))?.records??[]}catch{return[]}}async function cp(t,s,o){let c=E(t,s),l=new R(c.region),d=`${c.slug}-${s}-cli`,m=await l.invoke({FunctionName:d,InvocationType:"RequestResponse",Payload:{command:o},LogType:"Tail"}),f=m.Payload??"",S=m.FunctionError?"error":"ok",h=-1;try{let C=new g(c.region);if(await C.bucketExists(c.artifactBucket)){let w=await le(C,c.artifactBucket,c.slug,s);h=w.reduce((b,P)=>Math.max(b,P.id),0)+1,w.push({id:h,command:o,timestamp:new Date().toISOString(),status:S,output:f.slice(0,4000)}),await C.putObjectJson(c.artifactBucket,ce(c.slug,s),{records:w.slice(-we)})}}catch{}if(m.FunctionError)throw Error(`Command failed${h>0?` (#${h})`:""}: ${f}`);return{id:h,status:S,output:f}}async function wd(t,s){let o=E(t,s),c=new g(o.region);return le(c,o.artifactBucket,o.slug,s)}async function lp(t,s,o){let c=await wd(t,s);if(!c.length)return;return o==null?c[c.length-1]:c.find((l)=>l.id===o)}async function dp(t,s,o){let c=Buffer.from(o,"utf-8").toString("base64");return Mt(t,s,`tscloud:db-query --sql-base64=${c}`)}async function V(t,s){let o=E(t,s),c=new v(o.region),l=new R(o.region),d=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 N of O?.[0]?.Outputs??[])if(N.OutputKey)f[N.OutputKey]=N.OutputValue??""}catch{}let S=ma(o.app,o.slug,s),h=o.app.provisionedConcurrency??0,C=["http","cli",...S.length?["queue"]:[]],w=`${o.slug}-${s}`,b=[];for(let O of C){let N=`${w}-${O}`,B={mode:O,name:N,version:"$LATEST"};if(h>0){let I=await l.getAlias(N,"live").catch(()=>null);if(I?.FunctionVersion){B.version=I.FunctionVersion;let k=await l.getProvisionedConcurrencyConfig(N,"live").catch(()=>null);if(k)B.provisioned={status:k.Status??"-",allocated:k.AllocatedProvisionedConcurrentExecutions??0,requested:k.RequestedProvisionedConcurrentExecutions??0}}}b.push(B)}let P=await G(d,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:h,functions:b,lastRelease:P?{sha:P.sha,timestamp:P.timestamp}:void 0}}function ue(t,s){return`${t}-${s}-db`}async function ws(t,s,o,c){let l=E(t,s);if(l.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:d}=await import("./chunk-eetz9jgy.js"),m=new d(l.region),f=ue(l.slug,s);p(`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 up(t,s,o){let c=E(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-eetz9jgy.js"),d=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}`;p(`Restoring ${m} → new cluster ${S} (${o.latest?"latest restorable time":o.toTime.toISOString()})`),await d.restoreDBClusterToPointInTime({DBClusterIdentifier:S,SourceDBClusterIdentifier:m,RestoreToTime:o.toTime,UseLatestRestorableTime:o.latest}),p("Waiting for the restored cluster to be ready");for(let h=0;h<120;h++){let{DBClusters:C}=await d.describeDBClusters({DBClusterIdentifier:S}),w=C?.[0]?.Status;if(w&&w!=="creating")break;await new Promise((b)=>setTimeout(b,15000))}return p("Adding a writer instance"),await d.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
|
+
export{W,ht,Ed,vs,lo,ap,Ts,Es,uo,Mt,cp,wd,lp,dp,V,ws,up};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{vr,uc,pc,Tt,Tr,Er,wr,Cr,rn}from"./chunk-95v6ry1x.js";import"./chunk-c04dygzg.js";import"./chunk-24njmb7d.js";export{Tr as AwsSecretsManagerConfigurationBackend,Er as AwsSsmConfigurationBackend,Cr as ConfigurationService,vr as ConfigurationStore,wr as ExternalConfigurationBackend,Tt as LocalEncryptedConfigurationBackend,uc as parseDotenv,pc as serializeDotenv,rn as synchronizeConfiguredConfiguration};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{
|
|
1
|
+
import{Po,oa}from"./chunk-24njmb7d.js";import{g}from"./chunk-7xr71hnt.js";var l=()=>{};async function ju(a,c=l){for(let e of a){let t=new g(e.replicaRegion),i;try{i=await t.headBucket(e.replicaBucket)}catch(r){if(r?.statusCode===301)throw Error(`Failover replica bucket ${e.replicaBucket} already exists outside ${e.replicaRegion}. Pick another failover.bucket or region for infrastructure.storage.${e.name}.`);if(r?.statusCode===403)throw Error(`Failover replica bucket ${e.replicaBucket} exists but this account cannot reach it (S3 names are global, so another account may own it). Set infrastructure.storage.${e.name}.failover.bucket to a name you own.`);throw r}if(i.exists&&i.region&&i.region!==e.replicaRegion)throw Error(`Failover replica bucket ${e.replicaBucket} is in ${i.region}, not ${e.replicaRegion}.`);if(!i.exists)c(`Creating failover replica bucket ${e.replicaBucket} in ${e.replicaRegion}`),await t.createBucket(e.replicaBucket);if(await t.putPublicAccessBlock(e.replicaBucket,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!0,RestrictPublicBuckets:!0}),await t.putBucketEncryption(e.replicaBucket,"AES256"),e.replicate){if((await t.getBucketVersioning(e.replicaBucket)).Status!=="Enabled")c(`Enabling versioning on ${e.replicaBucket} (S3 replication requires it)`),await t.putBucketVersioning(e.replicaBucket,"Enabled")}}}async function Vu(a,c,e=l){for(let t of a){let i=c[t.distributionArnOutput];if(!i)throw Error(`Stack output ${t.distributionArnOutput} is missing, so the failover replica ${t.replicaBucket} cannot be scoped to its distribution.`);let r=new g(t.replicaRegion),s={Version:"2012-10-17",Statement:[...((await r.getBucketPolicy(t.replicaBucket))?.Statement??[]).filter((n)=>n?.Sid!==Po),oa({replicaBucket:t.replicaBucket,distributionArn:i})]};e(`Granting ${i} read access to ${t.replicaBucket}`),await r.putBucketPolicy(t.replicaBucket,s)}}async function zu(a,c=l){let e={};for(let t of a){let i=new g(t.primaryRegion),r=new g(t.replicaRegion),[u,p]=await Promise.all([i.listAllObjects({bucket:t.primaryBucket}),r.listAllObjects({bucket:t.replicaBucket})]),s=new Map(p.map((o)=>[o.Key,o.Size])),n=u.filter((o)=>s.get(o.Key)!==o.Size);for(let o of n)await r.copyObject({sourceBucket:t.primaryBucket,sourceKey:o.Key,destinationBucket:t.replicaBucket,destinationKey:o.Key});if(n.length>0)c(`Copied ${n.length} object(s) from ${t.primaryBucket} to ${t.replicaBucket}`);e[t.replicaBucket]=n.length}return e}async function Hu(a,c=l){for(let e of a){let t=new g(e.replicaRegion);if(!(await t.headBucket(e.replicaBucket)).exists)continue;await t.emptyBucket(e.replicaBucket),await t.deleteBucket(e.replicaBucket),c(`Deleted failover replica bucket ${e.replicaBucket}`)}}
|
|
2
|
+
export{ju,Vu,zu,Hu};
|