@stacksjs/ts-cloud 0.5.27 → 0.5.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +67 -67
- package/dist/index.js +37 -37
- package/dist/ui/index.html +3 -3
- package/dist/ui/server/actions.html +3 -3
- package/dist/ui/server/backups.html +3 -3
- package/dist/ui/server/database.html +3 -3
- package/dist/ui/server/deployments.html +3 -3
- package/dist/ui/server/logs.html +3 -3
- package/dist/ui/server/services.html +3 -3
- package/dist/ui/server/sites.html +3 -3
- package/dist/ui/server/ssh-keys.html +3 -3
- package/dist/ui/server/workers.html +3 -3
- package/dist/ui/serverless/logs.html +3 -3
- package/package.json +3 -3
package/dist/bin/cli.js
CHANGED
|
@@ -8,7 +8,7 @@ import{createRequire as VX}from"node:module";var KX=Object.defineProperty;var OX
|
|
|
8
8
|
${X0.bright}${X0.cyan}${$}${X0.reset}
|
|
9
9
|
`)}class N{frames=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];interval=null;currentFrame=0;message;constructor($){this.message=$}get text(){return this.message}set text($){if(this.message=$,j5&&this.interval)console.log(` ${$}`)}start(){if(j5){console.log(` ${this.message}`),this.interval=!0;return}this.interval=setInterval(()=>{process.stdout.write(`\r${X0.cyan}${this.frames[this.currentFrame]}${X0.reset} ${this.message}`),this.currentFrame=(this.currentFrame+1)%this.frames.length},80)}succeed($){this.stop(),h($||this.message)}fail($){this.stop(),w($||this.message)}warn($){this.stop(),u1($||this.message)}stop(){if(this.interval){if(!j5)process.stdout.write("\r");if(typeof this.interval==="object")clearInterval(this.interval);this.interval=null}}}class FW{total;current=0;width=40;constructor($){this.total=$}update($){this.current=$,this.render()}increment(){this.current++,this.render()}render(){let $=Math.floor(this.current/this.total*100),J=Math.floor(this.current/this.total*this.width),Y=this.width-J,Z=`${"█".repeat(J)}${"░".repeat(Y)}`;if(process.stdout.write(`\r${X0.cyan}${Z}${X0.reset} ${$}% (${this.current}/${this.total})`),this.current>=this.total)process.stdout.write(`
|
|
10
10
|
`)}}async function T0($,J){let Z=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout});return new Promise((Q)=>{let G=J?`${X0.cyan}?${X0.reset} ${$} ${X0.gray}(${J})${X0.reset}: `:`${X0.cyan}?${X0.reset} ${$}: `;Z.question(G,(W)=>{Z.close(),Q(W||J||"")})})}async function g($,J=!1){let Y=await T0(`${$} (y/n)`,J?"y":"n");return Y.toLowerCase()==="y"||Y.toLowerCase()==="yes"}async function v9($,J){console.log(`${X0.cyan}?${X0.reset} ${$}`),J.forEach((Q,G)=>{console.log(` ${X0.gray}${G+1}.${X0.reset} ${Q}`)});let Y=await T0("Select","1"),Z=Number.parseInt(Y)-1;if(Z>=0&&Z<J.length)return J[Z];return J[0]}function p($,J){let Y=$.map((Q,G)=>{let W=Math.max(...J.map((z)=>(z[G]||"").length));return Math.max(Q.length,W)}),Z=$.map((Q,G)=>Q.padEnd(Y[G])).join(" ");console.log(k2(Z,"bright")),console.log(k2("─".repeat(Z.length),"gray")),J.forEach((Q)=>{let G=Q.map((W,z)=>(W||"").padEnd(Y[z])).join(" ");console.log(G)})}function f9($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Z=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Z).toFixed(2))} ${Y[Z]}`}function CB($){if($<1000)return`${$}ms`;let J=Math.floor($/1000);if(J<60)return`${J}s`;let Y=Math.floor(J/60),Z=J%60;if(Y<60)return`${Y}m ${Z}s`;let Q=Math.floor(Y/60),G=Y%60;return`${Q}h ${G}m`}function k1($,J="cyan"){let Y=$.split(`
|
|
11
|
-
`),Z=Math.max(...Y.map((G)=>G.length)),Q="─".repeat(Z+2);console.log(k2(`┌${Q}┐`,J)),Y.forEach((G)=>{console.log(k2(`│ ${G.padEnd(Z)} │`,J))}),console.log(k2(`└${Q}┘`,J))}async function L5(){return!0}async function E5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2));return await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function M5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2)),Y=await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return Y.Account||Y.GetCallerIdentityResult?.Account||null}catch{return null}}async function q5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2)),Y=await new $().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),Z=[];if(Y.regionInfo){let Q=Array.isArray(Y.regionInfo)?Y.regionInfo:[Y.regionInfo];Z.push(...Q.map((G)=>G.regionName))}return Z.length>0?Z:HW()}catch{return HW()}}function HW(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}var X0,u1,j5;var z0=o(()=>{X0={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};u1=v;j5=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI)});class _8{name="porkbun";apiKey;secretKey;constructor($,J){this.apiKey=$,this.secretKey=J}async request($,J={}){let Y=await fetch(`https://api.porkbun.com/api/json/v3${$}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...J})});if(!Y.ok)throw Error(`Porkbun API error: ${Y.status} ${Y.statusText}`);let Z=await Y.json();if(Z.status==="ERROR")throw Error(`Porkbun API error: ${Z.message||"Unknown error"}`);return Z}getSubdomain($,J){let Y=$.replace(/\.$/,""),Z=J.replace(/\.$/,"");if(Y===Z)return"";if(Y.endsWith(`.${Z}`))return Y.slice(0,-(Z.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async createRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Z)Q.name=Z;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Q.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Q.content=`${J.weight} ${J.port} ${J.content}`;return{success:!0,id:(await this.request(`/dns/create/${Y}`,Q)).id?.toString(),message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.listRecords($,J.type);if(Q.success){let G=Q.records.find((W)=>{return this.getSubdomain(W.name,Y)===Z&&W.type===J.type});if(G?.id){let W={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Z)W.name=Z;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)W.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)W.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${Y}/${G.id}`,W),{success:!0,id:G.id,message:"Record updated successfully"}}}return this.createRecord($,J)}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.listRecords($,J.type);if(!Q.success)return{success:!1,message:"Failed to list records"};let G=Q.records.find((W)=>{return this.getSubdomain(W.name,Y)===Z&&W.type===J.type&&W.content===J.content});if(!G?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${Y}/${G.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Z=`/dns/retrieve/${Y}`;if(J)Z=`/dns/retrieveByNameType/${Y}/${J}`;return{success:!0,records:((await this.request(Z)).records||[]).map((W)=>({id:W.id,name:W.name||Y,type:W.type,content:W.content,ttl:Number.parseInt(W.ttl,10),priority:W.prio?Number.parseInt(W.prio,10):void 0}))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request(`/dns/retrieve/${J}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((J)=>J.domain)}catch{return[]}}async getNameServers($){try{let J=this.getRootDomain($);return(await this.request(`/dns/getNS/${J}`)).ns||[]}catch{return[]}}async updateNameServers($,J){try{let Y=this.getRootDomain($);return await this.request(`/dns/updateNS/${Y}`,{ns:J}),!0}catch{return!1}}}class j8{name="godaddy";apiKey;apiSecret;baseUrl;constructor($,J,Y="production"){this.apiKey=$,this.apiSecret=J,this.baseUrl=Y==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request($,J,Y){let Z=`${this.baseUrl}${J}`,Q={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},G={method:$,headers:Q};if(Y)G.body=JSON.stringify(Y);let W=await fetch(Z,G);if(W.status===204)return{};if(W.ok){let U=await W.text();if(U)return JSON.parse(U);return{}}let z=`GoDaddy API error: ${W.status} ${W.statusText}`;try{let U=await W.json();if(U.message)z=`GoDaddy API error: ${U.message}`;if(U.fields)z+=` - Fields: ${JSON.stringify(U.fields)}`}catch{}throw Error(z)}getSubdomain($,J){let Y=$.replace(/\.$/,""),Z=J.replace(/\.$/,"");if(Y===Z)return"@";if(Y.endsWith(`.${Z}`))return Y.slice(0,-(Z.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}toGoDaddyRecord($,J){let Y=this.getRootDomain(J),Z=this.getSubdomain($.name,Y),Q={type:$.type,name:Z,data:$.content,ttl:$.ttl||600};if($.type==="MX"&&$.priority!==void 0)Q.priority=$.priority;return Q}fromGoDaddyRecord($,J){let Y=this.getRootDomain(J),Z=$.name;if(Z==="@")Z=Y;else if(!Z.endsWith(Y))Z=`${Z}.${Y}`;return{name:Z,type:$.type,content:$.data,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=this.getRootDomain($),Z=this.toGoDaddyRecord(J,$);return await this.request("PATCH",`/v1/domains/${Y}/records`,[Z]),{success:!0,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Z=this.toGoDaddyRecord(J,$);return await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Z.name}`,[Z]),{success:!0,message:"Record upserted successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.request("GET",`/v1/domains/${Y}/records/${J.type}/${Z}`),G=Q.filter((W)=>W.data!==J.content);if(G.length===Q.length)return{success:!1,message:"Record not found"};if(G.length===0)try{await this.request("DELETE",`/v1/domains/${Y}/records/${J.type}/${Z}`)}catch{}else await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Z}`,G);return{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Z=`/v1/domains/${Y}/records`;if(J)Z=`/v1/domains/${Y}/records/${J}`;return{success:!0,records:(await this.request("GET",Z)).map((G)=>this.fromGoDaddyRecord(G,$))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request("GET",`/v1/domains/${J}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((J)=>J.domain)}catch{return[]}}async getDomainDetails($){try{let J=this.getRootDomain($),Y=await this.request("GET",`/v1/domains/${J}`);return{domain:Y.domain,status:Y.status,nameServers:Y.nameServers,expires:Y.expires}}catch{return null}}async updateNameServers($,J){try{let Y=this.getRootDomain($);return await this.request("PUT",`/v1/domains/${Y}/records/NS`,J.map((Z)=>({type:"NS",name:"@",data:Z,ttl:3600}))),!0}catch{return!1}}async checkDomainAvailability($){try{let J=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent($)}`);return{available:J.available,price:J.price,currency:J.currency}}catch{return{available:!1}}}}class T6{name="cloudflare";apiToken;zoneCache=new Map;constructor($){this.apiToken=$}async request($,J,Y){let Z=`https://api.cloudflare.com/client/v4${J}`,Q={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},G={method:$,headers:Q};if(Y)G.body=JSON.stringify(Y);let z=await(await fetch(Z,G)).json();if(!z.success){let U=z.errors.map((H)=>H.message).join(", ");throw Error(`Cloudflare API error: ${U}`)}return z}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getZoneId($){let J=this.getRootDomain($),Y=this.zoneCache.get(J);if(Y)return Y;let Z=await this.request("GET",`/zones?name=${encodeURIComponent(J)}`);if(!Z.result||Z.result.length===0)throw Error(`Zone not found for domain: ${J}`);let Q=Z.result[0].id;return this.zoneCache.set(J,Q),Q}getFullRecordName($,J){let Y=this.getRootDomain(J),Z=$.replace(/\.$/,"");if(!Z||Z===Y||Z==="@")return Y;if(Z.endsWith(`.${Y}`))return Z;return`${Z}.${Y}`}toCloudflareRecord($,J){let Y={type:$.type,name:this.getFullRecordName($.name,J),content:$.content||$.value||"",ttl:$.ttl||1};if($.type==="MX"&&$.priority!==void 0)Y.priority=$.priority;if($.type==="SRV"){if($.priority!==void 0)Y.priority=$.priority}return Y}fromCloudflareRecord($){return{id:$.id,name:$.name,type:$.type,content:$.content,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=await this.getZoneId($),Z=this.toCloudflareRecord(J,$);return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,Z)).result.id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`),G=this.toCloudflareRecord(J,$);if(Q.result&&Q.result.length>0){let z=Q.result[0].id;return{success:!0,id:(await this.request("PUT",`/zones/${Y}/dns_records/${z}`,G)).result.id,message:"Record updated successfully"}}return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,G)).result.id,message:"Record created successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`);if(!Q.result||Q.result.length===0)return{success:!1,message:"Record not found"};let G=Q.result.find((W)=>W.content===J.content);if(!G)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${Y}/dns_records/${G.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Z=`/zones/${await this.getZoneId($)}/dns_records?per_page=100`;if(J)Z+=`&type=${J}`;let Q=[],G=1,W=!0;while(W){let z=await this.request("GET",`${Z}&page=${G}`);if(Q.push(...z.result||[]),z.result_info)W=G<z.result_info.total_pages,G++;else W=!1}return{success:!0,records:Q.map((z)=>this.fromCloudflareRecord(z))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{return await this.getZoneId($),!0}catch{return!1}}async listDomains(){try{let $=[],J=1,Y=!0;while(Y){let Z=await this.request("GET",`/zones?per_page=50&page=${J}`);if($.push(...Z.result||[]),Z.result_info)Y=J<Z.result_info.total_pages,J++;else Y=!1}return $.map((Z)=>Z.name)}catch{return[]}}async getZoneDetails($){try{let J=await this.getZoneId($),Y=await this.request("GET",`/zones/${J}`);return{id:Y.result.id,name:Y.result.name,status:Y.result.status,nameServers:Y.result.name_servers,paused:Y.result.paused}}catch{return null}}async purgeCache($,J){try{let Y=await this.getZoneId($),Z={};if(J?.purgeEverything)Z.purge_everything=!0;else{if(J?.files)Z.files=J.files;if(J?.tags)Z.tags=J.tags;if(J?.hosts)Z.hosts=J.hosts}if(Object.keys(Z).length===0)Z.purge_everything=!0;return await this.request("POST",`/zones/${Y}/purge_cache`,Z),!0}catch{return!1}}async getRecordProxyStatus($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`);if(Q.result&&Q.result.length>0)return Q.result.find((W)=>W.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus($,J,Y){try{let Z=await this.getZoneId($),Q=this.getFullRecordName(J.name,$),G=await this.request("GET",`/zones/${Z}/dns_records?type=${J.type}&name=${encodeURIComponent(Q)}`);if(!G.result||G.result.length===0)return!1;let W=G.result.find((z)=>z.content===J.content);if(!W)return!1;return await this.request("PATCH",`/zones/${Z}/dns_records/${W.id}`,{proxied:Y}),!0}catch{return!1}}}var e0;var s2=o(()=>{Y0();e0=class e0{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async createHostedZone($){let J=$.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,Y=`<?xml version="1.0" encoding="UTF-8"?>
|
|
11
|
+
`),Z=Math.max(...Y.map((G)=>G.length)),Q="─".repeat(Z+2);console.log(k2(`┌${Q}┐`,J)),Y.forEach((G)=>{console.log(k2(`│ ${G.padEnd(Z)} │`,J))}),console.log(k2(`└${Q}┘`,J))}async function L5(){return!0}async function E5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2));return await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()}),!0}catch{return!1}}async function M5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2)),Y=await new $().request({service:"sts",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}).toString()});return Y.Account||Y.GetCallerIdentityResult?.Account||null}catch{return null}}async function q5(){try{let{AWSClient:$}=await Promise.resolve().then(() => (Y0(),I2)),Y=await new $().request({service:"ec2",region:"us-east-1",method:"POST",path:"/",body:new URLSearchParams({Action:"DescribeRegions",Version:"2016-11-15"}).toString()}),Z=[];if(Y.regionInfo){let Q=Array.isArray(Y.regionInfo)?Y.regionInfo:[Y.regionInfo];Z.push(...Q.map((G)=>G.regionName))}return Z.length>0?Z:HW()}catch{return HW()}}function HW(){return["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1","ap-northeast-1"]}var X0,u1,j5;var z0=o(()=>{X0={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m"};u1=v;j5=!!(process.env.CI||process.env.GITHUB_ACTIONS||process.env.BUILDKITE||process.env.CIRCLECI||process.env.GITLAB_CI)});class _8{name="porkbun";apiKey;secretKey;constructor($,J){this.apiKey=$,this.secretKey=J}async request($,J={}){let Y=await fetch(`https://api.porkbun.com/api/json/v3${$}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretKey,...J})});if(!Y.ok)throw Error(`Porkbun API error: ${Y.status} ${Y.statusText}`);let Z=await Y.json();if(Z.status==="ERROR")throw Error(`Porkbun API error: ${Z.message||"Unknown error"}`);return Z}getSubdomain($,J){let Y=$.replace(/\.$/,""),Z=J.replace(/\.$/,"");if(Y===Z)return"";if(Y.endsWith(`.${Z}`))return Y.slice(0,-(Z.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async createRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Z)Q.name=Z;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)Q.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)Q.content=`${J.weight} ${J.port} ${J.content}`;return{success:!0,id:(await this.request(`/dns/create/${Y}`,Q)).id?.toString(),message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.listRecords($,J.type);if(Q.success){let G=Q.records.find((W)=>{return this.getSubdomain(W.name,Y)===Z&&W.type===J.type});if(G?.id){let W={type:J.type,content:J.content,ttl:String(J.ttl||600)};if(Z)W.name=Z;if((J.type==="MX"||J.type==="SRV")&&J.priority!==void 0)W.prio=String(J.priority);if(J.type==="SRV"&&J.weight!==void 0&&J.port!==void 0)W.content=`${J.weight} ${J.port} ${J.content}`;return await this.request(`/dns/edit/${Y}/${G.id}`,W),{success:!0,id:G.id,message:"Record updated successfully"}}}return this.createRecord($,J)}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.listRecords($,J.type);if(!Q.success)return{success:!1,message:"Failed to list records"};let G=Q.records.find((W)=>{return this.getSubdomain(W.name,Y)===Z&&W.type===J.type&&W.content===J.content});if(!G?.id)return{success:!1,message:"Record not found"};return await this.request(`/dns/delete/${Y}/${G.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Z=`/dns/retrieve/${Y}`;if(J)Z=`/dns/retrieveByNameType/${Y}/${J}`;return{success:!0,records:((await this.request(Z)).records||[]).map((W)=>({id:W.id,name:W.name||Y,type:W.type,content:W.content,ttl:Number.parseInt(W.ttl,10),priority:W.prio?Number.parseInt(W.prio,10):void 0}))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request(`/dns/retrieve/${J}`),!0}catch{return!1}}async listDomains(){try{return((await this.request("/domain/listAll")).domains||[]).map((J)=>J.domain)}catch{return[]}}async getNameServers($){try{let J=this.getRootDomain($);return(await this.request(`/dns/getNS/${J}`)).ns||[]}catch{return[]}}async updateNameServers($,J){try{let Y=this.getRootDomain($);return await this.request(`/dns/updateNS/${Y}`,{ns:J}),!0}catch{return!1}}}class j8{name="godaddy";apiKey;apiSecret;baseUrl;constructor($,J,Y="production"){this.apiKey=$,this.apiSecret=J,this.baseUrl=Y==="ote"?"https://api.ote-godaddy.com":"https://api.godaddy.com"}async request($,J,Y){let Z=`${this.baseUrl}${J}`,Q={Authorization:`sso-key ${this.apiKey}:${this.apiSecret}`,"Content-Type":"application/json",Accept:"application/json"},G={method:$,headers:Q};if(Y)G.body=JSON.stringify(Y);let W=await fetch(Z,G);if(W.status===204)return{};if(W.ok){let U=await W.text();if(U)return JSON.parse(U);return{}}let z=`GoDaddy API error: ${W.status} ${W.statusText}`;try{let U=await W.json();if(U.message)z=`GoDaddy API error: ${U.message}`;if(U.fields)z+=` - Fields: ${JSON.stringify(U.fields)}`}catch{}throw Error(z)}getSubdomain($,J){let Y=$.replace(/\.$/,""),Z=J.replace(/\.$/,"");if(Y===Z)return"@";if(Y.endsWith(`.${Z}`))return Y.slice(0,-(Z.length+1));return Y}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}toGoDaddyRecord($,J){let Y=this.getRootDomain(J),Z=this.getSubdomain($.name,Y),Q={type:$.type,name:Z,data:$.content,ttl:$.ttl||600};if($.type==="MX"&&$.priority!==void 0)Q.priority=$.priority;return Q}fromGoDaddyRecord($,J){let Y=this.getRootDomain(J),Z=$.name;if(Z==="@")Z=Y;else if(!Z.endsWith(Y))Z=`${Z}.${Y}`;return{name:Z,type:$.type,content:$.data,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=this.getRootDomain($),Z=this.toGoDaddyRecord(J,$);return await this.request("PATCH",`/v1/domains/${Y}/records`,[Z]),{success:!0,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=this.getRootDomain($),Z=this.toGoDaddyRecord(J,$);return await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Z.name}`,[Z]),{success:!0,message:"Record upserted successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=this.getRootDomain($),Z=this.getSubdomain(J.name,Y),Q=await this.request("GET",`/v1/domains/${Y}/records/${J.type}/${Z}`),G=Q.filter((W)=>W.data!==J.content);if(G.length===Q.length)return{success:!1,message:"Record not found"};if(G.length===0)try{await this.request("DELETE",`/v1/domains/${Y}/records/${J.type}/${Z}`)}catch{}else await this.request("PUT",`/v1/domains/${Y}/records/${J.type}/${Z}`,G);return{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=this.getRootDomain($),Z=`/v1/domains/${Y}/records`;if(J)Z=`/v1/domains/${Y}/records/${J}`;return{success:!0,records:(await this.request("GET",Z)).map((G)=>this.fromGoDaddyRecord(G,$))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{let J=this.getRootDomain($);return await this.request("GET",`/v1/domains/${J}`),!0}catch{return!1}}async listDomains(){try{return(await this.request("GET","/v1/domains")).map((J)=>J.domain)}catch{return[]}}async getDomainDetails($){try{let J=this.getRootDomain($),Y=await this.request("GET",`/v1/domains/${J}`);return{domain:Y.domain,status:Y.status,nameServers:Y.nameServers,expires:Y.expires}}catch{return null}}async updateNameServers($,J){try{let Y=this.getRootDomain($);return await this.request("PUT",`/v1/domains/${Y}/records/NS`,J.map((Z)=>({type:"NS",name:"@",data:Z,ttl:3600}))),!0}catch{return!1}}async checkDomainAvailability($){try{let J=await this.request("GET",`/v1/domains/available?domain=${encodeURIComponent($)}`);return{available:J.available,price:J.price,currency:J.currency}}catch{return{available:!1}}}}class T6{name="cloudflare";apiToken;zoneCache=new Map;constructor($){this.apiToken=$}async request($,J,Y){let Z=`https://api.cloudflare.com/client/v4${J}`,Q={Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},G={method:$,headers:Q};if(Y)G.body=JSON.stringify(Y);let z=await(await fetch(Z,G)).json();if(!z.success){let U=z.errors.map((H)=>H.message).join(", ");throw Error(`Cloudflare API error: ${U}`)}return z}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getZoneId($){let J=this.getRootDomain($),Y=this.zoneCache.get(J);if(Y)return Y;let Z=await this.request("GET",`/zones?name=${encodeURIComponent(J)}`);if(!Z.result||Z.result.length===0)throw Error(`Zone not found for domain: ${J}`);let Q=Z.result[0].id;return this.zoneCache.set(J,Q),Q}getFullRecordName($,J){let Y=this.getRootDomain(J),Z=$.replace(/\.$/,"");if(!Z||Z===Y||Z==="@")return Y;if(Z.endsWith(`.${Y}`))return Z;return`${Z}.${Y}`}toCloudflareRecord($,J){let Y={type:$.type,name:this.getFullRecordName($.name,J),content:$.content||$.value||"",ttl:$.ttl||1};if($.type==="MX"&&$.priority!==void 0)Y.priority=$.priority;if($.type==="SRV"){if($.priority!==void 0)Y.priority=$.priority}return Y}fromCloudflareRecord($){return{id:$.id,name:$.name,type:$.type,content:$.content,ttl:$.ttl,priority:$.priority}}async createRecord($,J){try{let Y=await this.getZoneId($),Z=this.toCloudflareRecord(J,$);return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,Z)).result.id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`),G=this.toCloudflareRecord(J,$);if(Q.result&&Q.result.length>0){let z=Q.result[0].id;return{success:!0,id:(await this.request("PUT",`/zones/${Y}/dns_records/${z}`,G)).result.id,message:"Record updated successfully"}}return{success:!0,id:(await this.request("POST",`/zones/${Y}/dns_records`,G)).result.id,message:"Record created successfully"}}catch(Y){return this.createRecord($,J)}}async deleteRecord($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`);if(!Q.result||Q.result.length===0)return{success:!1,message:"Record not found"};let G=Q.result.find((W)=>W.content===J.content);if(!G)return{success:!1,message:"Record with matching content not found"};return await this.request("DELETE",`/zones/${Y}/dns_records/${G.id}`),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Z=`/zones/${await this.getZoneId($)}/dns_records?per_page=100`;if(J)Z+=`&type=${J}`;let Q=[],G=1,W=!0;while(W){let z=await this.request("GET",`${Z}&page=${G}`);if(Q.push(...z.result||[]),z.result_info)W=G<z.result_info.total_pages,G++;else W=!1}return{success:!0,records:Q.map((z)=>this.fromCloudflareRecord(z))}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){try{return await this.getZoneId($),!0}catch{return!1}}async listDomains(){try{let $=[],J=1,Y=!0;while(Y){let Z=await this.request("GET",`/zones?per_page=50&page=${J}`);if($.push(...Z.result||[]),Z.result_info)Y=J<Z.result_info.total_pages,J++;else Y=!1}return $.map((Z)=>Z.name)}catch{return[]}}async getZoneDetails($){try{let J=await this.getZoneId($),Y=await this.request("GET",`/zones/${J}`);return{id:Y.result.id,name:Y.result.name,status:Y.result.status,nameServers:Y.result.name_servers,paused:Y.result.paused}}catch{return null}}async purgeCache($,J){try{let Y=await this.getZoneId($),Z={};if(J?.purgeEverything)Z.purge_everything=!0;else{if(J?.files)Z.files=J.files;if(J?.tags)Z.tags=J.tags;if(J?.hosts)Z.hosts=J.hosts}if(Object.keys(Z).length===0)Z.purge_everything=!0;return await this.request("POST",`/zones/${Y}/purge_cache`,Z),!0}catch{return!1}}async getRecordProxyStatus($,J){try{let Y=await this.getZoneId($),Z=this.getFullRecordName(J.name,$),Q=await this.request("GET",`/zones/${Y}/dns_records?type=${J.type}&name=${encodeURIComponent(Z)}`);if(Q.result&&Q.result.length>0)return Q.result.find((W)=>W.content===J.content)?.proxied??null;return null}catch{return null}}async setRecordProxyStatus($,J,Y){try{let Z=await this.getZoneId($),Q=this.getFullRecordName(J.name,$),G=await this.request("GET",`/zones/${Z}/dns_records?type=${J.type}&name=${encodeURIComponent(Q)}`);if(!G.result||G.result.length===0)return!1;let W=G.result.find((z)=>z.content===J.content);if(!W)return!1;return await this.request("PATCH",`/zones/${Z}/dns_records/${W.id}`,{proxied:Y}),!0}catch{return!1}}}var e0;var o2=o(()=>{Y0();e0=class e0{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async createHostedZone($){let J=$.CallerReference||`${Date.now()}-${Math.random().toString(36).slice(2)}`,Y=`<?xml version="1.0" encoding="UTF-8"?>
|
|
12
12
|
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
|
|
13
13
|
<Name>${$.Name}</Name>
|
|
14
14
|
<CallerReference>${J}</CallerReference>`;if($.HostedZoneConfig){if(Y+=`
|
|
@@ -56,24 +56,24 @@ ${X0.bright}${X0.cyan}${$}${X0.reset}
|
|
|
56
56
|
</Change>`}Y+=`
|
|
57
57
|
</Changes>
|
|
58
58
|
</ChangeBatch>
|
|
59
|
-
</ChangeResourceRecordSetsRequest>`;let Z=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${J}/rrset`,headers:{"content-type":"application/xml"},body:Y});return this.parseChangeResourceRecordSetsResponse(Z)}escapeXml($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse($){let J=$.CreateHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(J.DelegationSet),Location:J.Location||""}}parseListHostedZonesResponse($){let J=$.ListHostedZonesResponse||$.ListHostedZonesByNameResponse||$,Y=J.HostedZones?.HostedZone||J.HostedZones||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{HostedZones:Y.map((Z)=>this.parseHostedZone(Z)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",Marker:J.Marker,NextMarker:J.NextMarker}}parseGetHostedZoneResponse($){let J=$.GetHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),DelegationSet:this.parseDelegationSet(J.DelegationSet),VPCs:J.VPCs?.VPC?Array.isArray(J.VPCs.VPC)?J.VPCs.VPC:[J.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse($){let J=$.ListResourceRecordSetsResponse||$,Y=J.ResourceRecordSets?.ResourceRecordSet||J.ResourceRecordSets||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{ResourceRecordSets:Y.map((Z)=>this.parseResourceRecordSet(Z)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",NextRecordName:J.NextRecordName,NextRecordType:J.NextRecordType,NextRecordIdentifier:J.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse($){let J=$.ChangeResourceRecordSetsResponse||$;return{ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||"",Comment:J.ChangeInfo?.Comment}}}parseHostedZone($){if(!$)return{Id:"",Name:""};return{Id:$.Id||"",Name:$.Name||"",CallerReference:$.CallerReference,Config:$.Config?{Comment:$.Config.Comment,PrivateZone:$.Config.PrivateZone==="true"||$.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:$.ResourceRecordSetCount?Number($.ResourceRecordSetCount):void 0}}parseDelegationSet($){if(!$)return{NameServers:[]};let J=$.NameServers?.NameServer||$.NameServers||[];if(!Array.isArray(J))J=J?[J]:[];return{Id:$.Id,CallerReference:$.CallerReference,NameServers:J}}parseResourceRecordSet($){if(!$)return{Name:"",Type:""};let J=$.ResourceRecords?.ResourceRecord||$.ResourceRecords||[];if(!Array.isArray(J))J=J?[J]:[];return{Name:$.Name||"",Type:$.Type||"",TTL:$.TTL?Number($.TTL):void 0,ResourceRecords:J.map((Y)=>({Value:Y.Value||Y})),AliasTarget:$.AliasTarget?{HostedZoneId:$.AliasTarget.HostedZoneId,DNSName:$.AliasTarget.DNSName,EvaluateTargetHealth:$.AliasTarget.EvaluateTargetHealth==="true"||$.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:$.SetIdentifier,Weight:$.Weight?Number($.Weight):void 0,Region:$.Region,GeoLocation:$.GeoLocation,Failover:$.Failover,HealthCheckId:$.HealthCheckId}}async findHostedZoneByName($){let J=$.endsWith(".")?$:`${$}.`;return(await this.listHostedZonesByName({DNSName:J})).HostedZones.find((Q)=>Q.Name===J)||null}async createARecord($){let J=Array.isArray($.Value)?$.Value:[$.Value];return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"A",TTL:$.TTL||300,ResourceRecords:J.map((Y)=>({Value:Y}))}}]}})}async createCnameRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"CNAME",TTL:$.TTL||300,ResourceRecords:[{Value:$.Value}]}}]}})}async createAliasRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:$.Type||"A",AliasTarget:{HostedZoneId:$.TargetHostedZoneId,DNSName:$.TargetDNSName,EvaluateTargetHealth:$.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord($){let Y=(Array.isArray($.Value)?$.Value:[$.Value]).map((Z)=>{if(!Z.startsWith('"'))return`"${Z}"`;return Z});return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"TXT",TTL:$.TTL||300,ResourceRecords:Y.map((Z)=>({Value:Z}))}}]}})}async createMxRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"MX",TTL:$.TTL||300,ResourceRecords:$.Values.map((J)=>({Value:`${J.priority} ${J.mailServer}`}))}}]}})}async deleteRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:$.RecordSet}]}})}async waitForChange($,J=60,Y=5000){let Z=$.replace("/change/","");for(let Q=0;Q<J;Q++){let G=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${Z}`});if((G.GetChangeResponse?.ChangeInfo?.Status||G.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((z)=>setTimeout(z,Y))}return!1}async findOrCreateHostedZone($){let J=$.domainName.endsWith(".")?$.domainName:`${$.domainName}.`,Y=await this.findHostedZoneByName(J);if(Y){let Q=await this.getHostedZone({Id:Y.Id});return{hostedZone:Y,nameServers:Q.DelegationSet.NameServers,isNew:!1}}let Z=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:$.comment||`Hosted zone for ${$.domainName}`,PrivateZone:$.privateZone},VPC:$.vpc});return{hostedZone:Z.HostedZone,nameServers:Z.DelegationSet.NameServers,isNew:!0}}static getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length<=2)return $;return J.slice(-2).join(".")}async findHostedZoneForDomain($){let Y=$.replace(/\.$/,"").split(".");for(let Z=0;Z<Y.length-1;Z++){let Q=Y.slice(Z).join("."),G=await this.findHostedZoneByName(Q);if(G)return G}return null}async ensureHostedZone($){let J=await this.findOrCreateHostedZone({domainName:$.domainName,comment:$.comment});return{hostedZoneId:J.hostedZone.Id.replace("/hostedzone/",""),nameServers:J.nameServers,isNew:J.isNew,action:J.isNew?"created":"found"}}async setupDomainDns($){let{domain:J,createIfNotExists:Y=!0}=$,Z=await this.findHostedZoneByName(J);if(Z){let G=await this.getHostedZone({Id:Z.Id});return{success:!0,hostedZoneId:Z.Id.replace("/hostedzone/",""),nameServers:G.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${J}`}}if(!Y)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${J} and createIfNotExists is false`};let Q=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${J}`}});return{success:!0,hostedZoneId:Q.HostedZone.Id.replace("/hostedzone/",""),nameServers:Q.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${J}. Please update your domain registrar with these name servers: ${Q.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}});class o2{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor($="us-east-1",J){this.client=new e0($),this.providedHostedZoneId=J}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getHostedZoneId($){if(this.providedHostedZoneId)return this.providedHostedZoneId;let J=this.getRootDomain($),Y=this.hostedZoneCache.get(J);if(Y)return Y;let Z=await this.client.findHostedZoneForDomain($);if(Z){let Q=Z.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,Q),Q}return null}normalizeName($){return $.endsWith(".")?$:`${$}.`}async createRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async deleteRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,records:[],message:`No hosted zone found for domain: ${$}`};let Z=await this.client.listResourceRecordSets({HostedZoneId:Y,StartRecordType:J}),Q=[];for(let G of Z.ResourceRecordSets){if(J&&G.Type!==J)continue;if(G.AliasTarget)continue;for(let W of G.ResourceRecords||[]){let z=W.Value,U;if(G.Type==="MX"){let H=z.split(" ");if(H.length>=2)U=Number.parseInt(H[0],10),z=H.slice(1).join(" ")}if(G.Type==="TXT"&&z.startsWith('"')&&z.endsWith('"'))z=z.slice(1,-1);Q.push({name:G.Name.replace(/\.$/,""),type:G.Type,content:z,ttl:G.TTL,priority:U})}}return{success:!0,records:Q}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){return await this.getHostedZoneId($)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((J)=>J.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord($){try{let J=await this.getHostedZoneId($.domain);if(!J)return{success:!1,message:`No hosted zone found for domain: ${$.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:J,Name:this.normalizeName($.name),TargetHostedZoneId:$.targetHostedZoneId,TargetDNSName:$.targetDnsName,EvaluateTargetHealth:$.evaluateTargetHealth,Type:$.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(J){return{success:!1,message:J instanceof Error?J.message:"Unknown error"}}}async createCloudFrontAlias($){return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:e0.CloudFrontHostedZoneId,targetDnsName:$.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias($){let J=e0.ALBHostedZoneIds[$.region];if(!J)return{success:!1,message:`Unknown region for ALB: ${$.region}`};return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:J,targetDnsName:$.albDnsName,evaluateTargetHealth:!0})}}var w6=o(()=>{s2()});var v4={};h0(v4,{ACMDnsValidator:()=>L8,ACMClient:()=>$1});class $1{client;region;constructor($="us-east-1"){this.client=new i,this.region=$}async requestCertificate($){let J={DomainName:$.DomainName,ValidationMethod:$.ValidationMethod||"DNS"};if($.SubjectAlternativeNames)J.SubjectAlternativeNames=$.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(J)})).CertificateArn||""}}async describeCertificate($){let Y=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Certificate||{};return{CertificateArn:Y.CertificateArn||"",DomainName:Y.DomainName||"",SubjectAlternativeNames:Y.SubjectAlternativeNames,Status:Y.Status||"PENDING_VALIDATION",Type:Y.Type,DomainValidationOptions:Y.DomainValidationOptions?.map((Z)=>({DomainName:Z.DomainName,ValidationDomain:Z.ValidationDomain,ValidationStatus:Z.ValidationStatus,ResourceRecord:Z.ResourceRecord?{Name:Z.ResourceRecord.Name,Type:Z.ResourceRecord.Type,Value:Z.ResourceRecord.Value}:void 0,ValidationMethod:Z.ValidationMethod})),CreatedAt:Y.CreatedAt,IssuedAt:Y.IssuedAt,NotBefore:Y.NotBefore,NotAfter:Y.NotAfter}}async listCertificates($){let J={};if($?.CertificateStatuses)J.CertificateStatuses=$.CertificateStatuses;if($?.MaxItems)J.MaxItems=$.MaxItems;if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(J)});return{CertificateSummaryList:(Y.CertificateSummaryList||[]).map((Z)=>({CertificateArn:Z.CertificateArn,DomainName:Z.DomainName})),NextToken:Y.NextToken}}async deleteCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})}async listTagsForCertificate($){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Tags||[]}}async addTagsToCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn,Tags:$.Tags})})}async resendValidationEmail($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:$.CertificateArn,Domain:$.Domain,ValidationDomain:$.ValidationDomain})})}async findCertificateByDomain($){let Y=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((Z)=>Z.DomainName===$||Z.DomainName===`*.${$.split(".").slice(1).join(".")}`);if(!Y)return null;return this.describeCertificate({CertificateArn:Y.CertificateArn})}async waitForCertificateValidation($,J=60,Y=30000){for(let Z=0;Z<J;Z++){let Q=await this.describeCertificate({CertificateArn:$});if(Q.Status==="ISSUED")return Q;if(Q.Status==="FAILED"||Q.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((G)=>setTimeout(G,Y))}return null}async getDnsValidationRecords($){let J=await this.describeCertificate({CertificateArn:$});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter((Y)=>Y.ResourceRecord&&Y.ValidationMethod==="DNS").map((Y)=>({domainName:Y.DomainName,recordName:Y.ResourceRecord.Name,recordType:Y.ResourceRecord.Type,recordValue:Y.ResourceRecord.Value}))}async requestCertificateWithSans($){let J=new Set;if(J.add($.DomainName),$.IncludeWww!==!1)J.add(`www.${$.DomainName}`);if($.IncludeWildcard)J.add(`*.${$.DomainName}`);if($.AdditionalSans)for(let Y of $.AdditionalSans)J.add(Y);return this.requestCertificate({DomainName:$.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain($,J){let Y=await this.describeCertificate({CertificateArn:$});if(Y.Status!=="ISSUED")return!1;if(Y.DomainName===J)return!0;if(Y.DomainName?.startsWith("*.")){let Z=Y.DomainName.slice(2),Q=J.split("."),G=Z.split(".");if(Q.slice(-G.length).join(".")===Z)return!0}if(Y.SubjectAlternativeNames)for(let Z of Y.SubjectAlternativeNames){if(Z===J)return!0;if(Z.startsWith("*.")){let Q=Z.slice(2),G=J.split("."),W=Q.split(".");if(G.slice(-W.length).join(".")===Q)return!0}}return!1}}class L8{acm;route53;dnsProvider;constructor($="us-east-1",J){if(this.acm=new $1($),this.route53=new e0,J&&J.provider!=="route53")this.dnsProvider=U1(J)}async requestAndValidate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z=[],waitForValidation:Q=!1,maxWaitMinutes:G=30}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:W}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Z.length>0?[J,...Z]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(W);let z=await this.acm.getDnsValidationRecords(W);if(this.dnsProvider)for(let U of z){let H=await this.dnsProvider.upsertRecord(J,{name:U.recordName,type:U.recordType,content:U.recordValue,ttl:300});if(!H.success)console.warn(`Failed to create validation record for ${U.domainName}: ${H.message}`)}else if(Y)for(let U of z)await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${U.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:U.recordName,Type:U.recordType,TTL:300,ResourceRecords:[{Value:U.recordValue}]}}]}});if(Q){if(!await this.acm.waitForCertificateValidation(W,G*2,30000))throw Error(`Certificate validation timed out after ${G} minutes`)}return{certificateArn:W,validationRecords:z}}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Z=await this.acm.describeCertificate({CertificateArn:$});if(Z.DomainValidationOptions&&Z.DomainValidationOptions.length>0&&Z.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Z}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let Q=await this.acm.getDnsValidationRecords(J),G=[];if(this.dnsProvider){let W=Z||Q[0]?.domainName;for(let z of Q){let U=await this.dnsProvider.upsertRecord(W,{name:z.recordName,type:z.recordType,content:z.recordValue,ttl:300});G.push({...z,changeId:U.success?U.id:void 0})}}else if(Y)for(let W of Q){let z=await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${W.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:W.recordName,Type:W.recordType,TTL:300,ResourceRecords:[{Value:W.recordValue}]}}]}});G.push({...W,changeId:z.ChangeInfo?.Id})}return G}async deleteValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Z}=$,Q=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let G=Z||Q[0]?.domainName;for(let W of Q)try{await this.dnsProvider.deleteRecord(G,{name:W.recordName,type:W.recordType,content:W.recordValue})}catch{}}else if(Y)for(let G of Q)try{await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${G.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:G.recordName,Type:G.recordType,TTL:300,ResourceRecords:[{Value:G.recordValue}]}}]}})}catch{}}async findOrCreateCertificate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z,waitForValidation:Q=!0}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let G=await this.acm.findCertificateByDomain(J);if(G&&G.Status==="ISSUED")return{certificateArn:G.CertificateArn,isNew:!1};let{certificateArn:W}=await this.requestAndValidate({domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z,waitForValidation:Q});return{certificateArn:W,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}var j2=o(()=>{Y0();s2();$2()});class e2{acm;dnsProvider;constructor($,J="us-east-1"){if(this.acm=new $1(J),"provider"in $)this.dnsProvider=U1($);else this.dnsProvider=$}getProvider(){return this.dnsProvider}async requestAndValidate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Z=!1,maxWaitMinutes:Q=30}=$,{CertificateArn:G}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Y.length>0?[J,...Y]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(G);let W=await this.acm.getDnsValidationRecords(G);for(let U of W){let H=await this.dnsProvider.upsertRecord(J,{name:U.recordName,type:U.recordType,content:U.recordValue,ttl:300});if(!H.success)console.warn(`Failed to create validation record for ${U.domainName}: ${H.message}`)}let z="pending";if(Z)z=(await this.acm.waitForCertificateValidation(G,Q*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:G,validationRecords:W.map((U)=>({domainName:U.domainName,recordName:U.recordName,recordType:U.recordType,recordValue:U.recordValue})),isNew:!0,status:z}}async createValidationRecords($){let{certificateArn:J,domain:Y}=$,Z=[],Q=await this.acm.getDnsValidationRecords(J);for(let G of Q){let W=await this.dnsProvider.upsertRecord(Y,{name:G.recordName,type:G.recordType,content:G.recordValue,ttl:300});if(!W.success)Z.push(`Failed to create record for ${G.domainName}: ${W.message}`)}return{success:Z.length===0,records:Q.map((G)=>({domainName:G.domainName,recordName:G.recordName,recordType:G.recordType,recordValue:G.recordValue})),errors:Z}}async deleteValidationRecords($){let{certificateArn:J,domain:Y}=$,Z=[],Q=await this.acm.getDnsValidationRecords(J);for(let G of Q){let W=await this.dnsProvider.deleteRecord(Y,{name:G.recordName,type:G.recordType,content:G.recordValue});if(!W.success)Z.push(`Failed to delete record for ${G.domainName}: ${W.message}`)}return{success:Z.length===0,errors:Z}}async findOrCreateCertificate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Z=!0,maxWaitMinutes:Q}=$,G=await this.acm.findCertificateByDomain(J);if(G&&G.Status==="ISSUED"){let W=G.SubjectAlternativeNames||[G.DomainName],z=W.some((H)=>H===`*.${J}`);if(Y.every((H)=>W.includes(H)||z))return{certificateArn:G.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:J,subjectAlternativeNames:Y,waitForValidation:Z,maxWaitMinutes:Q})}async requestCertificateWithCommonSans($){let{domainName:J,includeWww:Y=!0,includeWildcard:Z=!1,additionalSans:Q=[],waitForValidation:G=!1}=$,W=[];if(Y)W.push(`www.${J}`);if(Z)W.push(`*.${J}`);return W.push(...Q),this.requestAndValidate({domainName:J,subjectAlternativeNames:W,waitForValidation:G})}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Z=await this.acm.describeCertificate({CertificateArn:$});if(Z.DomainValidationOptions&&Z.DomainValidationOptions.length>0&&Z.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus($){let J=await this.acm.describeCertificate({CertificateArn:$});return{status:J.Status,domainValidations:(J.DomainValidationOptions||[]).map((Y)=>({domain:Y.DomainName,status:Y.ValidationStatus||"UNKNOWN"}))}}}var KJ=o(()=>{j2();$2()});function U1($){switch($.provider){case"route53":return new o2($.region,$.hostedZoneId);case"porkbun":return new _8($.apiKey,$.secretKey);case"godaddy":return new j8($.apiKey,$.apiSecret,$.environment);case"cloudflare":return new T6($.apiToken);default:throw Error(`Unknown DNS provider: ${$.provider}`)}}class E8{providers=new Map;configs=[];addConfig($){return this.configs.push($),this}addRoute53($,J){return this.configs.push({provider:"route53",region:$,hostedZoneId:J}),this}addPorkbun($,J){return this.configs.push({provider:"porkbun",apiKey:$,secretKey:J}),this}addGoDaddy($,J,Y){return this.configs.push({provider:"godaddy",apiKey:$,apiSecret:J,environment:Y}),this}addCloudflare($){return this.configs.push({provider:"cloudflare",apiToken:$}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let $=process.env.PORKBUN_API_KEY,J=process.env.PORKBUN_SECRET_KEY;if($&&J)this.addPorkbun($,J);let Y=process.env.GODADDY_API_KEY,Z=process.env.GODADDY_API_SECRET;if(Y&&Z){let G=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(Y,Z,G)}let Q=process.env.CLOUDFLARE_API_TOKEN;if(Q)this.addCloudflare(Q);return this}getProvider($){let J=this.providers.get($);if(J)return J;let Y=this.configs.find((Q)=>Q.provider===$);if(!Y)return null;let Z=U1(Y);return this.providers.set($,Z),Z}async getProviderForDomain($){for(let J of this.configs){let Y=U1(J);if(await Y.canManageDomain($))return Y}return null}getAllProviders(){return this.configs.map(($)=>U1($))}}var iO;var $2=o(()=>{w6();KJ();w6();iO=new E8});var l8={};h0(l8,{xrayManager:()=>DL,withTimeout:()=>u_,withSecurity:()=>eV,withQueue:()=>Z_,withMonitoring:()=>oV,withDatabase:()=>$_,withCache:()=>J_,withCDN:()=>Y_,validateTemplateSize:()=>wA,validateTemplate:()=>OA,validateResourceLimits:()=>DA,validateCredentials:()=>j_,validateConfiguration:()=>V_,validateCommand:()=>Rj,validateAgainstSchema:()=>t_,validateAccountStructure:()=>oj,templateCache:()=>R_,syntheticsManager:()=>SL,suggestRegions:()=>uj,suggestRegionPairs:()=>dj,suggestQuotaIncrease:()=>T_,suggestIAMPolicy:()=>E_,suggestFlags:()=>Tj,suggestCommand:()=>oJ,storageAdvancedManager:()=>JM,staticSiteManager:()=>$M,stackDependencyManager:()=>kj,signRequestAsync:()=>v6,signRequest:()=>Z1,sharedRuntimeLoop:()=>HZ,sha256:()=>r6,serviceMeshManager:()=>uL,sequence:()=>g_,senderReputationManager:()=>oL,securityScanningManager:()=>yL,securityHubManager:()=>EL,secretsRotationManager:()=>kL,secretsManager:()=>hL,searchCommands:()=>Mj,sanitizeName:()=>SA,runPhpBuildHooks:()=>t6,runBuildHooks:()=>FU,route53RoutingManager:()=>nL,route53ResolverManager:()=>aL,responseToResult:()=>qU,resourceManagementManager:()=>QM,resolveStorageBucketName:()=>PA,resolveSiteStackName:()=>SJ,resolveSiteResourceName:()=>PJ,resolveSiteBucketName:()=>CJ,resolveServerlessRuntime:()=>n6,resolveServerlessAssetBucketName:()=>d6,resolveServerlessArtifactBucketName:()=>xJ,resolveServerlessAppStackName:()=>W$,resolveRegion:()=>kz,resolveQueues:()=>m8,resolveQueueNames:()=>GZ,resolveProjectStackName:()=>j1,resolveManagementDashboardSite:()=>yJ,resolveDeployBucketName:()=>jz,resolveDashboardDomain:()=>wz,resolveCredentials:()=>m6,resolveCloudProvider:()=>M2,resolveApp:()=>SE,requiresReplacement:()=>l_,replicaManager:()=>CL,regionPairManager:()=>Ij,quickHash:()=>h_,queueManagementManager:()=>QE,progressiveDeploymentManager:()=>wL,processInChunks:()=>d_,previewNotifications:()=>Wj,previewManager:()=>Yj,phpRuntimeLayerAssets:()=>v8,phpLayerPackages:()=>KU,phpLayerBuildStage:()=>zZ,performanceManager:()=>xL,parseXMLResponse:()=>C8,parseJSONResponse:()=>Fz,parallelWithRetry:()=>f_,parallelMap:()=>v_,parallel:()=>l6,packageServerlessApp:()=>c8,packagePhpApp:()=>BZ,organizationManager:()=>nj,networkSecurityManager:()=>ZM,multiRegionManager:()=>Pj,multiAccountManager:()=>rj,migrationManager:()=>PL,metricsManager:()=>RL,mergeInfrastructure:()=>U$,makeAWSRequestOnce:()=>Uz,makeAWSRequestAsync:()=>Hz,makeAWSRequest:()=>Z$,logsManager:()=>NL,laravelServerlessEnvDefaults:()=>FZ,lambdaVersionsManager:()=>cL,lambdaVPCManager:()=>pL,lambdaLayersManager:()=>dL,lambdaDestinationsManager:()=>lL,lambdaDLQManager:()=>rL,lambdaConcurrencyManager:()=>mL,isWebCryptoAvailable:()=>Oz,isValidRegion:()=>fj,isNodeCryptoAvailable:()=>Kz,isLocalDevelopment:()=>s_,isLikelyTypo:()=>Lj,imageScanningManager:()=>vL,healthCheckManager:()=>YM,hashString:()=>pJ,hashManifest:()=>k_,hashFile:()=>lJ,hashDirectory:()=>I_,hashBuffer:()=>x_,hasManagementDashboardSite:()=>z$,guardDutyManager:()=>LL,globalResourceManager:()=>xj,getTimestamp:()=>NA,getSigningKeyCacheSize:()=>Bz,getRequiredPermissions:()=>dz,getRegionsByPricingTier:()=>vj,getRegionsByLocation:()=>bj,getRegionsByCompliance:()=>yj,getRegionStats:()=>pj,getRegion:()=>f$,getRecommendedStructure:()=>tj,getQuotaUsageSummary:()=>q_,getLocalEnvVars:()=>$j,getLocalEndpoint:()=>o_,getLocalCredentials:()=>e_,getLocalConfig:()=>p6,getErrorDetails:()=>uz,getDiffSummary:()=>m_,getDiffStats:()=>i_,getDeploymentStrategy:()=>n_,getCredentials:()=>d8,getContextualHelp:()=>Ej,getCommandUsage:()=>Dj,getClosestRegion:()=>gj,getAllRegions:()=>hj,getAccountId:()=>hz,generateScheduledWorkflow:()=>ZL,generateScheduledPipeline:()=>UL,generateScheduledConfig:()=>BL,generateResourceName:()=>f,generatePreviewWorkflow:()=>Zj,generatePreviewPipeline:()=>zL,generatePhpLayerDockerfile:()=>OU,generatePhpFpmConfig:()=>RU,generateParallelConfig:()=>OL,generatePRPreviewWorkflow:()=>YL,generateMultiEnvWorkflow:()=>JL,generateMultiEnvPipeline:()=>WL,generateMultiEnvConfig:()=>XL,generateMatrixWorkflow:()=>QL,generateManualPipeline:()=>HL,generateLogicalId:()=>x,generateDeploymentWorkflow:()=>$L,generateDeploymentPipeline:()=>GL,generateDeploymentConfig:()=>FL,generateCrossAccountRoleCF:()=>sj,generateCostReportWorkflow:()=>Gj,generateCleanupWorkflow:()=>Qj,generateBootstrap:()=>HU,generateApprovalConfig:()=>KL,generateAppImageDockerfile:()=>UZ,fromWebIdentity:()=>Iz,fromSharedCredentials:()=>Pz,fromEnvironment:()=>Sz,fromECSMetadata:()=>xz,fromEC2Metadata:()=>Cz,formatTree:()=>Fj,formatTable:()=>zj,formatSuggestion:()=>jj,formatRegionList:()=>lj,formatRegion:()=>YU,formatProgressBar:()=>Xj,formatList:()=>Oj,formatKeyValue:()=>Aj,formatHistoryStats:()=>Sj,formatHistory:()=>Nj,formatFlagSuggestions:()=>wj,formatDuration:()=>Kj,formatDiff:()=>kA,formatBytes:()=>Bj,formatAccountStructure:()=>ej,findChangedFiles:()=>b_,fifoQueueManager:()=>JE,extendPreset:()=>wJ,eventToRequest:()=>MU,emailTemplateManager:()=>eL,emailAnalyticsManager:()=>sL,drManager:()=>VL,dnssecManager:()=>iL,dlqMonitoringManager:()=>YE,diffTemplates:()=>c_,detectServiceRegion:()=>y6,detectMisconfigurations:()=>__,defaultLocalConfig:()=>rJ,databaseUserManager:()=>IL,crossRegionReferenceManager:()=>Cj,createZip:()=>d$,createWordPressPreset:()=>gV,createTraditionalWebAppPreset:()=>pV,createStaticSitePreset:()=>kV,createServerlessNodePreset:()=>yV,createServerlessLaravelPreset:()=>nV,createS3Client:()=>A_,createRealtimeAppPreset:()=>cV,createQueueHandler:()=>wU,createPresignedUrlAsync:()=>Jz,createPresignedUrl:()=>NJ,createPreset:()=>sV,createNodeJsServerlessPreset:()=>bV,createNodeJsServerPreset:()=>hV,createMockAWS:()=>Jj,createMicroservicesPreset:()=>dV,createMLApiPreset:()=>lV,createLaravelPreset:()=>rV,createJamstackPreset:()=>uV,createHttpHandler:()=>TU,createHandlers:()=>kE,createFullStackAppPreset:()=>vV,createError:()=>RJ,createDataPipelinePreset:()=>mV,createDashboardSite:()=>iV,createCredentialProvider:()=>G_,createCliHandler:()=>DU,createApiBackendPreset:()=>fV,containerRegistryManager:()=>gL,composeServerlessAppTemplate:()=>WZ,composePresets:()=>tV,collectPhpAppEntries:()=>s6,cloudTrailManager:()=>jL,cloudConfigSchema:()=>a_,clearSigningKeyCache:()=>Xz,chunk:()=>rz,checkServiceQuotas:()=>M_,checkIAMPermissions:()=>L_,certificateManager:()=>bL,categorizeChanges:()=>r_,canaryManager:()=>qL,buildPhpRuntimeLayerZip:()=>nE,buildOptimizationManager:()=>fL,buildNodeRuntimeLayerZip:()=>DE,buildCloudFormationTemplate:()=>IV,buildBunRuntimeLayerZip:()=>RE,bounceComplaintHandler:()=>tL,blueGreenManager:()=>ML,batchProcessingManager:()=>ZE,batch:()=>y_,backupManager:()=>AL,awsConfigManager:()=>_L,autocomplete:()=>qj,artifactKey:()=>QZ,analyzeStackDiff:()=>CA,abTestManager:()=>TL,XRayManager:()=>OY,Workflow:()=>Tz,ValidationError:()=>uJ,TemplateCache:()=>cJ,TemplateBuilder:()=>u6,TaskList:()=>sz,SyntheticsManager:()=>Y$,StorageAdvancedManager:()=>OZ,Storage:()=>l1,StaticSiteManager:()=>KZ,StacksIntegration:()=>fA,StackDependencyManager:()=>ZY,Spinner:()=>tz,SmsHandlers:()=>qz,SmsAdvanced:()=>UU,ServiceMeshManager:()=>SY,SenderReputationManager:()=>uY,SecurityScanningManager:()=>wY,SecurityHubManager:()=>J$,Security:()=>y0,SecretsRotationManager:()=>MY,SecretsManager:()=>qY,Secrets:()=>v$,Search:()=>d2,SMS:()=>B1,S3Error:()=>V1,S3Client:()=>gJ,Route53RoutingManager:()=>bY,Route53ResolverManager:()=>vY,ResourceManagementManager:()=>_Z,ReplicaManager:()=>jY,Registry:()=>J2,RegionPairManager:()=>YY,Redirects:()=>E2,RealtimePresets:()=>KA,RateLimiter:()=>pz,REPLContext:()=>ez,REPLCommandBuilder:()=>$U,REPL:()=>oz,RECOMMENDED_SCPS:()=>ij,RECOMMENDED_ACCOUNT_STRUCTURES:()=>ZU,QueuePresets:()=>BA,QueueManagementManager:()=>ZZ,Queue:()=>_1,Pseudo:()=>RA,ProgressiveDeploymentManager:()=>KY,ProgressBar:()=>iz,PreviewNotificationService:()=>sJ,PreviewEnvironmentManager:()=>tJ,PhoneHandlers:()=>Mz,PhoneAdvanced:()=>zU,Phone:()=>Y2,Permissions:()=>R1,PerformanceManager:()=>LY,ParameterStore:()=>m0,PHP_LAYER_EXTENSIONS:()=>BU,PHP_DEFAULT_EXCLUDES:()=>kU,OrganizationManager:()=>GY,NetworkSecurityManager:()=>VZ,Network:()=>x0,MultiStepProgress:()=>az,MultiRegionManager:()=>eJ,MultiAccountManager:()=>QY,Monitoring:()=>u8,MockS3:()=>iJ,MockDynamoDB:()=>aJ,MockCloudFormation:()=>nJ,MigrationManager:()=>_Y,MetricsManager:()=>AY,Messaging:()=>D1,MANAGED_NODE_VERSIONS:()=>XU,LogsManager:()=>VY,LambdaVersionsManager:()=>CY,LambdaVPCManager:()=>kY,LambdaLayersManager:()=>PY,LambdaDestinationsManager:()=>IY,LambdaDLQManager:()=>hY,LambdaConcurrencyManager:()=>xY,LARAVEL_SERVERLESS_BUILD_STEPS:()=>SU,JobLoader:()=>L2,ImageScanningManager:()=>DY,HealthCheckManager:()=>AZ,HashCache:()=>mz,GuardDutyManager:()=>FY,GlobalResourceManager:()=>JY,Fn:()=>L,FileSystem:()=>Z2,FileCache:()=>dJ,FIFOQueueManager:()=>$Z,ErrorCodes:()=>gz,EmailTemplateManager:()=>dY,EmailHandlers:()=>GU,EmailAnalyticsManager:()=>gY,EmailAdvanced:()=>QU,Email:()=>q0,DisasterRecoveryManager:()=>zY,DeploymentError:()=>vz,Deployment:()=>O1,DependencyGraph:()=>Lz,DebugLogger:()=>N1,DatabaseUserManager:()=>EY,Database:()=>m2,DNSSECManager:()=>yY,DNS:()=>X1,DLQMonitoringManager:()=>JZ,DEFAULT_SERVICE_LIMITS:()=>F1,CrossRegionReferenceManager:()=>$Y,CredentialError:()=>g2,ContainerRegistryManager:()=>NY,ConfigurationError:()=>I8,Compute:()=>Z0,Communication:()=>A1,CommandHistory:()=>JU,CloudTrailManager:()=>HY,CloudFrontClient:()=>yz,CloudFormationClient:()=>bz,CloudFormationBuilder:()=>bJ,CloudError:()=>Q2,CertificateManager:()=>TY,CanaryManager:()=>y8,Cache:()=>g8,COMMON_CROSS_ACCOUNT_ROLES:()=>aj,CDN:()=>m1,BuildOptimizationManager:()=>RY,BounceComplaintHandler:()=>fY,BlueGreenManager:()=>XY,BatchProcessingManager:()=>YZ,BackupManager:()=>WY,Auth:()=>K1,AssetHasher:()=>J1,Arn:()=>h8,ApiGateway:()=>c6,AWS_REGIONS:()=>r1,AWS_PSEUDO_PARAMETERS:()=>nA,AWSConfigManager:()=>UY,AWSAPIError:()=>fz,AI:()=>p1,ABTestManager:()=>BY});import{createRequire as QA}from"node:module";import{existsSync as w8,readdirSync as hA}from"node:fs";import{join as f2}from"node:path";import{createHash as cA}from"node:crypto";import{readFileSync as N6,readdirSync as mA,statSync as lA,existsSync as jJ,writeFileSync as S6,copyFileSync as pA}from"node:fs";import{join as D8,basename as rA,dirname as p4,extname as r4}from"node:path";import{readFileSync as fJ,existsSync as Dz}from"node:fs";import{homedir as Rz}from"node:os";import{join as Nz}from"node:path";import{createHash as cz}from"node:crypto";import{existsSync as t4,mkdirSync as w_,readFileSync as s4,readdirSync as o4,unlinkSync as R8,writeFileSync as D_}from"node:fs";import{join as EJ}from"node:path";import{createHash as mJ}from"node:crypto";import{createReadStream as N_,readdirSync as S_,statSync as h6}from"node:fs";import{join as P_,relative as C_}from"node:path";import{deflateRawSync as GE}from"node:zlib";import{execSync as FE}from"node:child_process";import{createHash as XE}from"node:crypto";import{cpSync as BE,mkdtempSync as KE,rmSync as OE,writeFileSync as AE}from"node:fs";import{tmpdir as VE}from"node:os";import{dirname as _E,isAbsolute as jE,join as S8,resolve as LE}from"node:path";import{fileURLToPath as EE}from"node:url";import{execFileSync as i6}from"node:child_process";import{mkdtempSync as AU,readFileSync as a6,rmSync as VU}from"node:fs";import{tmpdir as _U}from"node:os";import{dirname as TE,join as c2}from"node:path";import{fileURLToPath as wE}from"node:url";import{readFileSync as hE}from"node:fs";import{dirname as bE,join as NU}from"node:path";import{fileURLToPath as yE}from"node:url";import{execFileSync as C6}from"node:child_process";import{existsSync as fE,mkdirSync as gE,mkdtempSync as uE,readdirSync as dE,readFileSync as cE,rmSync as mE,statSync as PU,writeFileSync as lE}from"node:fs";import{tmpdir as pE}from"node:os";import{join as y$,relative as rE}from"node:path";import{execSync as iE}from"node:child_process";import{createHash as aE}from"node:crypto";import{readdirSync as tE,readFileSync as sE,statSync as xU}from"node:fs";import{join as oE,relative as IU,resolve as XZ}from"node:path";function zA($,J){this[$]=WA.bind(null,J)}function y6($){let J=typeof $==="string"?new URL($):$,{hostname:Y,pathname:Z}=J;if(Y.endsWith(".on.aws")){let z=Y.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(z)return{service:"lambda",region:z[1]};return{service:"",region:""}}if(Y.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(Y.endsWith(".backblazeb2.com")){let z=Y.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(z)return{service:"s3",region:z[1]};return{service:"",region:""}}let Q=Y.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!Q)return{service:"",region:""};let G=Q[1],W=Q[2]||"";if(W==="us-gov")W="us-gov-west-1";else if(W==="s3"||W==="s3-accelerate")W="us-east-1",G="s3";else if(G==="iot")if(Y.startsWith("iot."))G="execute-api";else if(Y.startsWith("data.jobs.iot."))G="iot-jobs-data";else G=Z==="/mqtt"?"iotdevicegateway":"iotdata";else if(G==="autoscaling");else if(!W&&G.startsWith("s3-"))W=G.slice(3).replace(/^fips-|^external-1/,""),G="s3";else if(G.endsWith("-fips"))G=G.slice(0,-5);else if(W&&/-\d$/.test(G)&&!/-\d$/.test(W))[G,W]=[W,G];return G=Vz[G]||G,{service:G,region:W||"us-east-1"}}function Z1($){let{method:J,url:Y,body:Z="",accessKeyId:Q,secretAccessKey:G,sessionToken:W,signQuery:z=!1,expiresIn:U=86400,datetime:H}=$,F=new URL(Y),B=F.hostname,K=y6(F),O=$.service||K.service,V=$.region||K.region;if(!O)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!V)throw Error("Could not detect region from URL. Please provide region explicitly.");let A=H||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),_=A.substring(0,8),M=[_,V,O,"aws4_request"].join("/"),E="AWS4-HMAC-SHA256";if(z)return FA({urlObj:F,method:J,body:Z,accessKeyId:Q,secretAccessKey:G,sessionToken:W,service:O,region:V,timestamp:A,date:_,credentialScope:M,algorithm:E,expiresIn:U,cache:$.cache});let j=F.pathname||"/",q=f6(F.searchParams),T={host:B,"x-amz-date":A,...$.headers};if(W)T["x-amz-security-token"]=W;let D=Object.keys(T).some((u)=>u.toLowerCase()==="content-type");if(Z&&!D)T["content-type"]="application/x-amz-json-1.0";if(O==="s3"&&!T["x-amz-content-sha256"])T["x-amz-content-sha256"]=P8(Z);let S=Yz(T),P=Zz(T),C=T["x-amz-content-sha256"]||P8(Z),I=[J,g6(j),q,S,P,C].join(`
|
|
59
|
+
</ChangeResourceRecordSetsRequest>`;let Z=await this.client.request({service:"route53",region:this.region,method:"POST",path:`/2013-04-01/hostedzone/${J}/rrset`,headers:{"content-type":"application/xml"},body:Y});return this.parseChangeResourceRecordSetsResponse(Z)}escapeXml($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}parseCreateHostedZoneResponse($){let J=$.CreateHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||""},DelegationSet:this.parseDelegationSet(J.DelegationSet),Location:J.Location||""}}parseListHostedZonesResponse($){let J=$.ListHostedZonesResponse||$.ListHostedZonesByNameResponse||$,Y=J.HostedZones?.HostedZone||J.HostedZones||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{HostedZones:Y.map((Z)=>this.parseHostedZone(Z)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",Marker:J.Marker,NextMarker:J.NextMarker}}parseGetHostedZoneResponse($){let J=$.GetHostedZoneResponse||$;return{HostedZone:this.parseHostedZone(J.HostedZone),DelegationSet:this.parseDelegationSet(J.DelegationSet),VPCs:J.VPCs?.VPC?Array.isArray(J.VPCs.VPC)?J.VPCs.VPC:[J.VPCs.VPC]:void 0}}parseListResourceRecordSetsResponse($){let J=$.ListResourceRecordSetsResponse||$,Y=J.ResourceRecordSets?.ResourceRecordSet||J.ResourceRecordSets||[];if(!Array.isArray(Y))Y=Y?[Y]:[];return{ResourceRecordSets:Y.map((Z)=>this.parseResourceRecordSet(Z)),IsTruncated:J.IsTruncated==="true"||J.IsTruncated===!0,MaxItems:J.MaxItems||"100",NextRecordName:J.NextRecordName,NextRecordType:J.NextRecordType,NextRecordIdentifier:J.NextRecordIdentifier}}parseChangeResourceRecordSetsResponse($){let J=$.ChangeResourceRecordSetsResponse||$;return{ChangeInfo:{Id:J.ChangeInfo?.Id||"",Status:J.ChangeInfo?.Status||"",SubmittedAt:J.ChangeInfo?.SubmittedAt||"",Comment:J.ChangeInfo?.Comment}}}parseHostedZone($){if(!$)return{Id:"",Name:""};return{Id:$.Id||"",Name:$.Name||"",CallerReference:$.CallerReference,Config:$.Config?{Comment:$.Config.Comment,PrivateZone:$.Config.PrivateZone==="true"||$.Config.PrivateZone===!0}:void 0,ResourceRecordSetCount:$.ResourceRecordSetCount?Number($.ResourceRecordSetCount):void 0}}parseDelegationSet($){if(!$)return{NameServers:[]};let J=$.NameServers?.NameServer||$.NameServers||[];if(!Array.isArray(J))J=J?[J]:[];return{Id:$.Id,CallerReference:$.CallerReference,NameServers:J}}parseResourceRecordSet($){if(!$)return{Name:"",Type:""};let J=$.ResourceRecords?.ResourceRecord||$.ResourceRecords||[];if(!Array.isArray(J))J=J?[J]:[];return{Name:$.Name||"",Type:$.Type||"",TTL:$.TTL?Number($.TTL):void 0,ResourceRecords:J.map((Y)=>({Value:Y.Value||Y})),AliasTarget:$.AliasTarget?{HostedZoneId:$.AliasTarget.HostedZoneId,DNSName:$.AliasTarget.DNSName,EvaluateTargetHealth:$.AliasTarget.EvaluateTargetHealth==="true"||$.AliasTarget.EvaluateTargetHealth===!0}:void 0,SetIdentifier:$.SetIdentifier,Weight:$.Weight?Number($.Weight):void 0,Region:$.Region,GeoLocation:$.GeoLocation,Failover:$.Failover,HealthCheckId:$.HealthCheckId}}async findHostedZoneByName($){let J=$.endsWith(".")?$:`${$}.`;return(await this.listHostedZonesByName({DNSName:J})).HostedZones.find((Q)=>Q.Name===J)||null}async createARecord($){let J=Array.isArray($.Value)?$.Value:[$.Value];return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"A",TTL:$.TTL||300,ResourceRecords:J.map((Y)=>({Value:Y}))}}]}})}async createCnameRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"CNAME",TTL:$.TTL||300,ResourceRecords:[{Value:$.Value}]}}]}})}async createAliasRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:$.Type||"A",AliasTarget:{HostedZoneId:$.TargetHostedZoneId,DNSName:$.TargetDNSName,EvaluateTargetHealth:$.EvaluateTargetHealth??!1}}}]}})}async createTxtRecord($){let Y=(Array.isArray($.Value)?$.Value:[$.Value]).map((Z)=>{if(!Z.startsWith('"'))return`"${Z}"`;return Z});return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"TXT",TTL:$.TTL||300,ResourceRecords:Y.map((Z)=>({Value:Z}))}}]}})}async createMxRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:$.Name,Type:"MX",TTL:$.TTL||300,ResourceRecords:$.Values.map((J)=>({Value:`${J.priority} ${J.mailServer}`}))}}]}})}async deleteRecord($){return this.changeResourceRecordSets({HostedZoneId:$.HostedZoneId,ChangeBatch:{Changes:[{Action:"DELETE",ResourceRecordSet:$.RecordSet}]}})}async waitForChange($,J=60,Y=5000){let Z=$.replace("/change/","");for(let Q=0;Q<J;Q++){let G=await this.client.request({service:"route53",region:this.region,method:"GET",path:`/2013-04-01/change/${Z}`});if((G.GetChangeResponse?.ChangeInfo?.Status||G.ChangeInfo?.Status)==="INSYNC")return!0;await new Promise((z)=>setTimeout(z,Y))}return!1}async findOrCreateHostedZone($){let J=$.domainName.endsWith(".")?$.domainName:`${$.domainName}.`,Y=await this.findHostedZoneByName(J);if(Y){let Q=await this.getHostedZone({Id:Y.Id});return{hostedZone:Y,nameServers:Q.DelegationSet.NameServers,isNew:!1}}let Z=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:$.comment||`Hosted zone for ${$.domainName}`,PrivateZone:$.privateZone},VPC:$.vpc});return{hostedZone:Z.HostedZone,nameServers:Z.DelegationSet.NameServers,isNew:!0}}static getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length<=2)return $;return J.slice(-2).join(".")}async findHostedZoneForDomain($){let Y=$.replace(/\.$/,"").split(".");for(let Z=0;Z<Y.length-1;Z++){let Q=Y.slice(Z).join("."),G=await this.findHostedZoneByName(Q);if(G)return G}return null}async ensureHostedZone($){let J=await this.findOrCreateHostedZone({domainName:$.domainName,comment:$.comment});return{hostedZoneId:J.hostedZone.Id.replace("/hostedzone/",""),nameServers:J.nameServers,isNew:J.isNew,action:J.isNew?"created":"found"}}async setupDomainDns($){let{domain:J,createIfNotExists:Y=!0}=$,Z=await this.findHostedZoneByName(J);if(Z){let G=await this.getHostedZone({Id:Z.Id});return{success:!0,hostedZoneId:Z.Id.replace("/hostedzone/",""),nameServers:G.DelegationSet.NameServers,isNew:!1,message:`Found existing hosted zone for ${J}`}}if(!Y)return{success:!1,hostedZoneId:null,nameServers:[],isNew:!1,message:`No hosted zone found for ${J} and createIfNotExists is false`};let Q=await this.createHostedZone({Name:J,HostedZoneConfig:{Comment:`Created automatically by ts-cloud for ${J}`}});return{success:!0,hostedZoneId:Q.HostedZone.Id.replace("/hostedzone/",""),nameServers:Q.DelegationSet.NameServers,isNew:!0,message:`Created new hosted zone for ${J}. Please update your domain registrar with these name servers: ${Q.DelegationSet.NameServers.join(", ")}`}}static CloudFrontHostedZoneId="Z2FDTNDATAQYW2";static S3WebsiteHostedZoneIds={"us-east-1":"Z3AQBSTGFYJSTF","us-east-2":"Z2O1EMRO9K5GLX","us-west-1":"Z2F56UZL2M1ACD","us-west-2":"Z3BJ6K6RIION7M","ap-east-1":"ZNB98KWMFR0R6","ap-south-1":"Z11RGJOFQNVJUP","ap-northeast-1":"Z2M4EHUR26P7ZW","ap-northeast-2":"Z3W03O7B5YMIYP","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"Z3O0J2DXBE1FTB","ap-southeast-2":"Z1WCIGYICN2BYD","ca-central-1":"Z1QDHH18159H29","eu-central-1":"Z21DNDUVLTQW6Q","eu-west-1":"Z1BKCTXD74EZPE","eu-west-2":"Z3GKZC51ZF0DB4","eu-west-3":"Z3R1K369G5AVDG","eu-north-1":"Z3BAZG2TWCNX0D","sa-east-1":"Z7KQH4QJS55SO"};static ALBHostedZoneIds={"us-east-1":"Z35SXDOTRQ7X7K","us-east-2":"Z3AADJGX6KTTL2","us-west-1":"Z368ELLRRE2KJ0","us-west-2":"Z1H1FL5HABSF5","ap-east-1":"Z3DQVH9N71FHZ0","ap-south-1":"ZP97RAFLXTNZK","ap-northeast-1":"Z14GRHDCWA56QT","ap-northeast-2":"ZWKZPGTI48KDX","ap-northeast-3":"Z5LXEBD8Y73MNV","ap-southeast-1":"Z1LMS91P8CMLE5","ap-southeast-2":"Z1GM3OXH4ZPM65","ca-central-1":"ZQSVJUPU6J1EY","eu-central-1":"Z215JYRZR1TBD5","eu-west-1":"Z32O12XQLNTSW2","eu-west-2":"ZHURV8PSTC4K8","eu-west-3":"Z3Q77PNBQS71R4","eu-north-1":"Z23TAZ6LKFMNIO","sa-east-1":"Z2P70J7HTTTPLU"};static APIGatewayHostedZoneIds={"us-east-1":"Z1UJRXOUMOOFQ8","us-east-2":"ZOJJZC49E0EPZ","us-west-1":"Z2MUQ32089INYE","us-west-2":"Z2OJLYMUO9EFXC","ap-east-1":"Z3FD1VL90ND7K5","ap-south-1":"Z3VO1THU9YC4UR","ap-northeast-1":"Z1YSHQZHG15GKL","ap-northeast-2":"Z20JF4UZKIW1U8","ap-northeast-3":"Z2YQB5RD63NC85","ap-southeast-1":"ZL327KTPIQFUL","ap-southeast-2":"Z2RPCDW04V8134","ca-central-1":"Z19DQILCV0OWEC","eu-central-1":"Z1U9ULNL0V5AJ3","eu-west-1":"ZLY8HYME6SFDD","eu-west-2":"ZJ5UAJN8Y3Z2Q","eu-west-3":"Z3KY65QIEKYHQQ","eu-north-1":"Z3UWIKFBOOGXPP","sa-east-1":"ZCMLWB8V5SYIT"}}});class e2{name="route53";client;hostedZoneCache=new Map;providedHostedZoneId;constructor($="us-east-1",J){this.client=new e0($),this.providedHostedZoneId=J}getRootDomain($){let J=$.replace(/\.$/,"").split(".");if(J.length>=2)return J.slice(-2).join(".");return $}async getHostedZoneId($){if(this.providedHostedZoneId)return this.providedHostedZoneId;let J=this.getRootDomain($),Y=this.hostedZoneCache.get(J);if(Y)return Y;let Z=await this.client.findHostedZoneForDomain($);if(Z){let Q=Z.Id.replace("/hostedzone/","");return this.hostedZoneCache.set(J,Q),Q}return null}normalizeName($){return $.endsWith(".")?$:`${$}.`}async createRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Created by ts-cloud DNS provider",Changes:[{Action:"CREATE",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record created successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async upsertRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return{success:!0,id:(await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Upserted by ts-cloud DNS provider",Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}})).ChangeInfo?.Id,message:"Record upserted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async deleteRecord($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,message:`No hosted zone found for domain: ${$}`};let Z=this.normalizeName(J.name),Q=J.content;if(J.type==="TXT"&&!Q.startsWith('"'))Q=`"${Q}"`;if(J.type==="MX"&&J.priority!==void 0)Q=`${J.priority} ${Q}`;return await this.client.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:"Deleted by ts-cloud DNS provider",Changes:[{Action:"DELETE",ResourceRecordSet:{Name:Z,Type:J.type,TTL:J.ttl||300,ResourceRecords:[{Value:Q}]}}]}}),{success:!0,message:"Record deleted successfully"}}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:"Unknown error"}}}async listRecords($,J){try{let Y=await this.getHostedZoneId($);if(!Y)return{success:!1,records:[],message:`No hosted zone found for domain: ${$}`};let Z=await this.client.listResourceRecordSets({HostedZoneId:Y,StartRecordType:J}),Q=[];for(let G of Z.ResourceRecordSets){if(J&&G.Type!==J)continue;if(G.AliasTarget)continue;for(let W of G.ResourceRecords||[]){let z=W.Value,U;if(G.Type==="MX"){let H=z.split(" ");if(H.length>=2)U=Number.parseInt(H[0],10),z=H.slice(1).join(" ")}if(G.Type==="TXT"&&z.startsWith('"')&&z.endsWith('"'))z=z.slice(1,-1);Q.push({name:G.Name.replace(/\.$/,""),type:G.Type,content:z,ttl:G.TTL,priority:U})}}return{success:!0,records:Q}}catch(Y){return{success:!1,records:[],message:Y instanceof Error?Y.message:"Unknown error"}}}async canManageDomain($){return await this.getHostedZoneId($)!==null}async listDomains(){try{return(await this.client.listHostedZones()).HostedZones.map((J)=>J.Name.replace(/\.$/,""))}catch{return[]}}getRoute53Client(){return this.client}async createAliasRecord($){try{let J=await this.getHostedZoneId($.domain);if(!J)return{success:!1,message:`No hosted zone found for domain: ${$.domain}`};return{success:!0,id:(await this.client.createAliasRecord({HostedZoneId:J,Name:this.normalizeName($.name),TargetHostedZoneId:$.targetHostedZoneId,TargetDNSName:$.targetDnsName,EvaluateTargetHealth:$.evaluateTargetHealth,Type:$.type})).ChangeInfo?.Id,message:"Alias record created successfully"}}catch(J){return{success:!1,message:J instanceof Error?J.message:"Unknown error"}}}async createCloudFrontAlias($){return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:e0.CloudFrontHostedZoneId,targetDnsName:$.cloudFrontDomainName,evaluateTargetHealth:!1})}async createAlbAlias($){let J=e0.ALBHostedZoneIds[$.region];if(!J)return{success:!1,message:`Unknown region for ALB: ${$.region}`};return this.createAliasRecord({domain:$.domain,name:$.name,targetHostedZoneId:J,targetDnsName:$.albDnsName,evaluateTargetHealth:!0})}}var w6=o(()=>{o2()});var v4={};h0(v4,{ACMDnsValidator:()=>L8,ACMClient:()=>$1});class $1{client;region;constructor($="us-east-1"){this.client=new i,this.region=$}async requestCertificate($){let J={DomainName:$.DomainName,ValidationMethod:$.ValidationMethod||"DNS"};if($.SubjectAlternativeNames)J.SubjectAlternativeNames=$.SubjectAlternativeNames;return{CertificateArn:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.RequestCertificate"},body:JSON.stringify(J)})).CertificateArn||""}}async describeCertificate($){let Y=(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DescribeCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Certificate||{};return{CertificateArn:Y.CertificateArn||"",DomainName:Y.DomainName||"",SubjectAlternativeNames:Y.SubjectAlternativeNames,Status:Y.Status||"PENDING_VALIDATION",Type:Y.Type,DomainValidationOptions:Y.DomainValidationOptions?.map((Z)=>({DomainName:Z.DomainName,ValidationDomain:Z.ValidationDomain,ValidationStatus:Z.ValidationStatus,ResourceRecord:Z.ResourceRecord?{Name:Z.ResourceRecord.Name,Type:Z.ResourceRecord.Type,Value:Z.ResourceRecord.Value}:void 0,ValidationMethod:Z.ValidationMethod})),CreatedAt:Y.CreatedAt,IssuedAt:Y.IssuedAt,NotBefore:Y.NotBefore,NotAfter:Y.NotAfter}}async listCertificates($){let J={};if($?.CertificateStatuses)J.CertificateStatuses=$.CertificateStatuses;if($?.MaxItems)J.MaxItems=$.MaxItems;if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListCertificates"},body:JSON.stringify(J)});return{CertificateSummaryList:(Y.CertificateSummaryList||[]).map((Z)=>({CertificateArn:Z.CertificateArn,DomainName:Z.DomainName})),NextToken:Y.NextToken}}async deleteCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.DeleteCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})}async listTagsForCertificate($){return{Tags:(await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ListTagsForCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn})})).Tags||[]}}async addTagsToCertificate($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.AddTagsToCertificate"},body:JSON.stringify({CertificateArn:$.CertificateArn,Tags:$.Tags})})}async resendValidationEmail($){await this.client.request({service:"acm",region:this.region,method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"CertificateManager.ResendValidationEmail"},body:JSON.stringify({CertificateArn:$.CertificateArn,Domain:$.Domain,ValidationDomain:$.ValidationDomain})})}async findCertificateByDomain($){let Y=(await this.listCertificates({CertificateStatuses:["ISSUED"]})).CertificateSummaryList.find((Z)=>Z.DomainName===$||Z.DomainName===`*.${$.split(".").slice(1).join(".")}`);if(!Y)return null;return this.describeCertificate({CertificateArn:Y.CertificateArn})}async waitForCertificateValidation($,J=60,Y=30000){for(let Z=0;Z<J;Z++){let Q=await this.describeCertificate({CertificateArn:$});if(Q.Status==="ISSUED")return Q;if(Q.Status==="FAILED"||Q.Status==="VALIDATION_TIMED_OUT")return null;await new Promise((G)=>setTimeout(G,Y))}return null}async getDnsValidationRecords($){let J=await this.describeCertificate({CertificateArn:$});if(!J.DomainValidationOptions)return[];return J.DomainValidationOptions.filter((Y)=>Y.ResourceRecord&&Y.ValidationMethod==="DNS").map((Y)=>({domainName:Y.DomainName,recordName:Y.ResourceRecord.Name,recordType:Y.ResourceRecord.Type,recordValue:Y.ResourceRecord.Value}))}async requestCertificateWithSans($){let J=new Set;if(J.add($.DomainName),$.IncludeWww!==!1)J.add(`www.${$.DomainName}`);if($.IncludeWildcard)J.add(`*.${$.DomainName}`);if($.AdditionalSans)for(let Y of $.AdditionalSans)J.add(Y);return this.requestCertificate({DomainName:$.DomainName,SubjectAlternativeNames:Array.from(J),ValidationMethod:"DNS"})}async isCertificateValidForDomain($,J){let Y=await this.describeCertificate({CertificateArn:$});if(Y.Status!=="ISSUED")return!1;if(Y.DomainName===J)return!0;if(Y.DomainName?.startsWith("*.")){let Z=Y.DomainName.slice(2),Q=J.split("."),G=Z.split(".");if(Q.slice(-G.length).join(".")===Z)return!0}if(Y.SubjectAlternativeNames)for(let Z of Y.SubjectAlternativeNames){if(Z===J)return!0;if(Z.startsWith("*.")){let Q=Z.slice(2),G=J.split("."),W=Q.split(".");if(G.slice(-W.length).join(".")===Q)return!0}}return!1}}class L8{acm;route53;dnsProvider;constructor($="us-east-1",J){if(this.acm=new $1($),this.route53=new e0,J&&J.provider!=="route53")this.dnsProvider=U1(J)}async requestAndValidate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z=[],waitForValidation:Q=!1,maxWaitMinutes:G=30}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let{CertificateArn:W}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Z.length>0?[J,...Z]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(W);let z=await this.acm.getDnsValidationRecords(W);if(this.dnsProvider)for(let U of z){let H=await this.dnsProvider.upsertRecord(J,{name:U.recordName,type:U.recordType,content:U.recordValue,ttl:300});if(!H.success)console.warn(`Failed to create validation record for ${U.domainName}: ${H.message}`)}else if(Y)for(let U of z)await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${U.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:U.recordName,Type:U.recordType,TTL:300,ResourceRecords:[{Value:U.recordValue}]}}]}});if(Q){if(!await this.acm.waitForCertificateValidation(W,G*2,30000))throw Error(`Certificate validation timed out after ${G} minutes`)}return{certificateArn:W,validationRecords:z}}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Z=await this.acm.describeCertificate({CertificateArn:$});if(Z.DomainValidationOptions&&Z.DomainValidationOptions.length>0&&Z.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async createValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Z}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let Q=await this.acm.getDnsValidationRecords(J),G=[];if(this.dnsProvider){let W=Z||Q[0]?.domainName;for(let z of Q){let U=await this.dnsProvider.upsertRecord(W,{name:z.recordName,type:z.recordType,content:z.recordValue,ttl:300});G.push({...z,changeId:U.success?U.id:void 0})}}else if(Y)for(let W of Q){let z=await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`ACM DNS validation for ${W.domainName}`,Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:W.recordName,Type:W.recordType,TTL:300,ResourceRecords:[{Value:W.recordValue}]}}]}});G.push({...W,changeId:z.ChangeInfo?.Id})}return G}async deleteValidationRecords($){let{certificateArn:J,hostedZoneId:Y,domain:Z}=$,Q=await this.acm.getDnsValidationRecords(J);if(this.dnsProvider){let G=Z||Q[0]?.domainName;for(let W of Q)try{await this.dnsProvider.deleteRecord(G,{name:W.recordName,type:W.recordType,content:W.recordValue})}catch{}}else if(Y)for(let G of Q)try{await this.route53.changeResourceRecordSets({HostedZoneId:Y,ChangeBatch:{Comment:`Cleanup ACM DNS validation for ${G.domainName}`,Changes:[{Action:"DELETE",ResourceRecordSet:{Name:G.recordName,Type:G.recordType,TTL:300,ResourceRecords:[{Value:G.recordValue}]}}]}})}catch{}}async findOrCreateCertificate($){let{domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z,waitForValidation:Q=!0}=$;if(!this.dnsProvider&&!Y)throw Error("Either hostedZoneId or external DNS provider configuration is required");let G=await this.acm.findCertificateByDomain(J);if(G&&G.Status==="ISSUED")return{certificateArn:G.CertificateArn,isNew:!1};let{certificateArn:W}=await this.requestAndValidate({domainName:J,hostedZoneId:Y,subjectAlternativeNames:Z,waitForValidation:Q});return{certificateArn:W,isNew:!0}}hasExternalDnsProvider(){return this.dnsProvider!==void 0}getDnsProviderName(){return this.dnsProvider?.name||"route53"}}var j2=o(()=>{Y0();o2();$2()});class $${acm;dnsProvider;constructor($,J="us-east-1"){if(this.acm=new $1(J),"provider"in $)this.dnsProvider=U1($);else this.dnsProvider=$}getProvider(){return this.dnsProvider}async requestAndValidate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Z=!1,maxWaitMinutes:Q=30}=$,{CertificateArn:G}=await this.acm.requestCertificate({DomainName:J,SubjectAlternativeNames:Y.length>0?[J,...Y]:void 0,ValidationMethod:"DNS"});await this.waitForValidationOptions(G);let W=await this.acm.getDnsValidationRecords(G);for(let U of W){let H=await this.dnsProvider.upsertRecord(J,{name:U.recordName,type:U.recordType,content:U.recordValue,ttl:300});if(!H.success)console.warn(`Failed to create validation record for ${U.domainName}: ${H.message}`)}let z="pending";if(Z)z=(await this.acm.waitForCertificateValidation(G,Q*2,30000))?.Status==="ISSUED"?"issued":"failed";return{certificateArn:G,validationRecords:W.map((U)=>({domainName:U.domainName,recordName:U.recordName,recordType:U.recordType,recordValue:U.recordValue})),isNew:!0,status:z}}async createValidationRecords($){let{certificateArn:J,domain:Y}=$,Z=[],Q=await this.acm.getDnsValidationRecords(J);for(let G of Q){let W=await this.dnsProvider.upsertRecord(Y,{name:G.recordName,type:G.recordType,content:G.recordValue,ttl:300});if(!W.success)Z.push(`Failed to create record for ${G.domainName}: ${W.message}`)}return{success:Z.length===0,records:Q.map((G)=>({domainName:G.domainName,recordName:G.recordName,recordType:G.recordType,recordValue:G.recordValue})),errors:Z}}async deleteValidationRecords($){let{certificateArn:J,domain:Y}=$,Z=[],Q=await this.acm.getDnsValidationRecords(J);for(let G of Q){let W=await this.dnsProvider.deleteRecord(Y,{name:G.recordName,type:G.recordType,content:G.recordValue});if(!W.success)Z.push(`Failed to delete record for ${G.domainName}: ${W.message}`)}return{success:Z.length===0,errors:Z}}async findOrCreateCertificate($){let{domainName:J,subjectAlternativeNames:Y=[],waitForValidation:Z=!0,maxWaitMinutes:Q}=$,G=await this.acm.findCertificateByDomain(J);if(G&&G.Status==="ISSUED"){let W=G.SubjectAlternativeNames||[G.DomainName],z=W.some((H)=>H===`*.${J}`);if(Y.every((H)=>W.includes(H)||z))return{certificateArn:G.CertificateArn,validationRecords:[],isNew:!1,status:"issued"};console.log("Existing certificate doesn't cover all required SANs, requesting new certificate...")}return this.requestAndValidate({domainName:J,subjectAlternativeNames:Y,waitForValidation:Z,maxWaitMinutes:Q})}async requestCertificateWithCommonSans($){let{domainName:J,includeWww:Y=!0,includeWildcard:Z=!1,additionalSans:Q=[],waitForValidation:G=!1}=$,W=[];if(Y)W.push(`www.${J}`);if(Z)W.push(`*.${J}`);return W.push(...Q),this.requestAndValidate({domainName:J,subjectAlternativeNames:W,waitForValidation:G})}async waitForValidationOptions($,J=30){for(let Y=0;Y<J;Y++){let Z=await this.acm.describeCertificate({CertificateArn:$});if(Z.DomainValidationOptions&&Z.DomainValidationOptions.length>0&&Z.DomainValidationOptions[0].ResourceRecord)return;await new Promise((Q)=>setTimeout(Q,2000))}throw Error("Timeout waiting for DNS validation options")}async getCertificateStatus($){let J=await this.acm.describeCertificate({CertificateArn:$});return{status:J.Status,domainValidations:(J.DomainValidationOptions||[]).map((Y)=>({domain:Y.DomainName,status:Y.ValidationStatus||"UNKNOWN"}))}}}var KJ=o(()=>{j2();$2()});function U1($){switch($.provider){case"route53":return new e2($.region,$.hostedZoneId);case"porkbun":return new _8($.apiKey,$.secretKey);case"godaddy":return new j8($.apiKey,$.apiSecret,$.environment);case"cloudflare":return new T6($.apiToken);default:throw Error(`Unknown DNS provider: ${$.provider}`)}}class E8{providers=new Map;configs=[];addConfig($){return this.configs.push($),this}addRoute53($,J){return this.configs.push({provider:"route53",region:$,hostedZoneId:J}),this}addPorkbun($,J){return this.configs.push({provider:"porkbun",apiKey:$,secretKey:J}),this}addGoDaddy($,J,Y){return this.configs.push({provider:"godaddy",apiKey:$,apiSecret:J,environment:Y}),this}addCloudflare($){return this.configs.push({provider:"cloudflare",apiToken:$}),this}loadFromEnv(){if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_REGION)this.addRoute53(process.env.AWS_REGION);let $=process.env.PORKBUN_API_KEY,J=process.env.PORKBUN_SECRET_KEY;if($&&J)this.addPorkbun($,J);let Y=process.env.GODADDY_API_KEY,Z=process.env.GODADDY_API_SECRET;if(Y&&Z){let G=process.env.GODADDY_ENVIRONMENT;this.addGoDaddy(Y,Z,G)}let Q=process.env.CLOUDFLARE_API_TOKEN;if(Q)this.addCloudflare(Q);return this}getProvider($){let J=this.providers.get($);if(J)return J;let Y=this.configs.find((Q)=>Q.provider===$);if(!Y)return null;let Z=U1(Y);return this.providers.set($,Z),Z}async getProviderForDomain($){for(let J of this.configs){let Y=U1(J);if(await Y.canManageDomain($))return Y}return null}getAllProviders(){return this.configs.map(($)=>U1($))}}var iO;var $2=o(()=>{w6();KJ();w6();iO=new E8});var l8={};h0(l8,{xrayManager:()=>DL,withTimeout:()=>u_,withSecurity:()=>eV,withQueue:()=>Z_,withMonitoring:()=>oV,withDatabase:()=>$_,withCache:()=>J_,withCDN:()=>Y_,validateTemplateSize:()=>wA,validateTemplate:()=>OA,validateResourceLimits:()=>DA,validateCredentials:()=>j_,validateConfiguration:()=>V_,validateCommand:()=>Rj,validateAgainstSchema:()=>t_,validateAccountStructure:()=>oj,templateCache:()=>R_,syntheticsManager:()=>SL,suggestRegions:()=>uj,suggestRegionPairs:()=>dj,suggestQuotaIncrease:()=>T_,suggestIAMPolicy:()=>E_,suggestFlags:()=>Tj,suggestCommand:()=>oJ,storageAdvancedManager:()=>JM,staticSiteManager:()=>$M,stackDependencyManager:()=>kj,signRequestAsync:()=>v6,signRequest:()=>Z1,sharedRuntimeLoop:()=>HZ,sha256:()=>r6,serviceMeshManager:()=>uL,sequence:()=>g_,senderReputationManager:()=>oL,securityScanningManager:()=>yL,securityHubManager:()=>EL,secretsRotationManager:()=>kL,secretsManager:()=>hL,searchCommands:()=>Mj,sanitizeName:()=>SA,runPhpBuildHooks:()=>t6,runBuildHooks:()=>FU,route53RoutingManager:()=>nL,route53ResolverManager:()=>aL,responseToResult:()=>qU,resourceManagementManager:()=>QM,resolveStorageBucketName:()=>PA,resolveSiteStackName:()=>SJ,resolveSiteResourceName:()=>PJ,resolveSiteBucketName:()=>CJ,resolveServerlessRuntime:()=>n6,resolveServerlessAssetBucketName:()=>d6,resolveServerlessArtifactBucketName:()=>xJ,resolveServerlessAppStackName:()=>z$,resolveRegion:()=>kz,resolveQueues:()=>m8,resolveQueueNames:()=>GZ,resolveProjectStackName:()=>j1,resolveManagementDashboardSite:()=>yJ,resolveDeployBucketName:()=>jz,resolveDashboardDomain:()=>wz,resolveCredentials:()=>m6,resolveCloudProvider:()=>M2,resolveApp:()=>SE,requiresReplacement:()=>l_,replicaManager:()=>CL,regionPairManager:()=>Ij,quickHash:()=>h_,queueManagementManager:()=>QE,progressiveDeploymentManager:()=>wL,processInChunks:()=>d_,previewNotifications:()=>Wj,previewManager:()=>Yj,phpRuntimeLayerAssets:()=>v8,phpLayerPackages:()=>KU,phpLayerBuildStage:()=>zZ,performanceManager:()=>xL,parseXMLResponse:()=>C8,parseJSONResponse:()=>Fz,parallelWithRetry:()=>f_,parallelMap:()=>v_,parallel:()=>l6,packageServerlessApp:()=>c8,packagePhpApp:()=>BZ,organizationManager:()=>nj,networkSecurityManager:()=>ZM,multiRegionManager:()=>Pj,multiAccountManager:()=>rj,migrationManager:()=>PL,metricsManager:()=>RL,mergeInfrastructure:()=>H$,makeAWSRequestOnce:()=>Uz,makeAWSRequestAsync:()=>Hz,makeAWSRequest:()=>Q$,logsManager:()=>NL,laravelServerlessEnvDefaults:()=>FZ,lambdaVersionsManager:()=>cL,lambdaVPCManager:()=>pL,lambdaLayersManager:()=>dL,lambdaDestinationsManager:()=>lL,lambdaDLQManager:()=>rL,lambdaConcurrencyManager:()=>mL,isWebCryptoAvailable:()=>Oz,isValidRegion:()=>fj,isNodeCryptoAvailable:()=>Kz,isLocalDevelopment:()=>s_,isLikelyTypo:()=>Lj,imageScanningManager:()=>vL,healthCheckManager:()=>YM,hashString:()=>pJ,hashManifest:()=>k_,hashFile:()=>lJ,hashDirectory:()=>I_,hashBuffer:()=>x_,hasManagementDashboardSite:()=>U$,guardDutyManager:()=>LL,globalResourceManager:()=>xj,getTimestamp:()=>NA,getSigningKeyCacheSize:()=>Bz,getRequiredPermissions:()=>dz,getRegionsByPricingTier:()=>vj,getRegionsByLocation:()=>bj,getRegionsByCompliance:()=>yj,getRegionStats:()=>pj,getRegion:()=>f$,getRecommendedStructure:()=>tj,getQuotaUsageSummary:()=>q_,getLocalEnvVars:()=>$j,getLocalEndpoint:()=>o_,getLocalCredentials:()=>e_,getLocalConfig:()=>p6,getErrorDetails:()=>uz,getDiffSummary:()=>m_,getDiffStats:()=>i_,getDeploymentStrategy:()=>n_,getCredentials:()=>d8,getContextualHelp:()=>Ej,getCommandUsage:()=>Dj,getClosestRegion:()=>gj,getAllRegions:()=>hj,getAccountId:()=>hz,generateScheduledWorkflow:()=>ZL,generateScheduledPipeline:()=>UL,generateScheduledConfig:()=>BL,generateResourceName:()=>f,generatePreviewWorkflow:()=>Zj,generatePreviewPipeline:()=>zL,generatePhpLayerDockerfile:()=>OU,generatePhpFpmConfig:()=>RU,generateParallelConfig:()=>OL,generatePRPreviewWorkflow:()=>YL,generateMultiEnvWorkflow:()=>JL,generateMultiEnvPipeline:()=>WL,generateMultiEnvConfig:()=>XL,generateMatrixWorkflow:()=>QL,generateManualPipeline:()=>HL,generateLogicalId:()=>x,generateDeploymentWorkflow:()=>$L,generateDeploymentPipeline:()=>GL,generateDeploymentConfig:()=>FL,generateCrossAccountRoleCF:()=>sj,generateCostReportWorkflow:()=>Gj,generateCleanupWorkflow:()=>Qj,generateBootstrap:()=>HU,generateApprovalConfig:()=>KL,generateAppImageDockerfile:()=>UZ,fromWebIdentity:()=>Iz,fromSharedCredentials:()=>Pz,fromEnvironment:()=>Sz,fromECSMetadata:()=>xz,fromEC2Metadata:()=>Cz,formatTree:()=>Fj,formatTable:()=>zj,formatSuggestion:()=>jj,formatRegionList:()=>lj,formatRegion:()=>YU,formatProgressBar:()=>Xj,formatList:()=>Oj,formatKeyValue:()=>Aj,formatHistoryStats:()=>Sj,formatHistory:()=>Nj,formatFlagSuggestions:()=>wj,formatDuration:()=>Kj,formatDiff:()=>kA,formatBytes:()=>Bj,formatAccountStructure:()=>ej,findChangedFiles:()=>b_,fifoQueueManager:()=>JE,extendPreset:()=>wJ,eventToRequest:()=>MU,emailTemplateManager:()=>eL,emailAnalyticsManager:()=>sL,drManager:()=>VL,dnssecManager:()=>iL,dlqMonitoringManager:()=>YE,diffTemplates:()=>c_,detectServiceRegion:()=>y6,detectMisconfigurations:()=>__,defaultLocalConfig:()=>rJ,databaseUserManager:()=>IL,crossRegionReferenceManager:()=>Cj,createZip:()=>d$,createWordPressPreset:()=>gV,createTraditionalWebAppPreset:()=>pV,createStaticSitePreset:()=>kV,createServerlessNodePreset:()=>yV,createServerlessLaravelPreset:()=>nV,createS3Client:()=>A_,createRealtimeAppPreset:()=>cV,createQueueHandler:()=>wU,createPresignedUrlAsync:()=>Jz,createPresignedUrl:()=>NJ,createPreset:()=>sV,createNodeJsServerlessPreset:()=>bV,createNodeJsServerPreset:()=>hV,createMockAWS:()=>Jj,createMicroservicesPreset:()=>dV,createMLApiPreset:()=>lV,createLaravelPreset:()=>rV,createJamstackPreset:()=>uV,createHttpHandler:()=>TU,createHandlers:()=>kE,createFullStackAppPreset:()=>vV,createError:()=>RJ,createDataPipelinePreset:()=>mV,createDashboardSite:()=>iV,createCredentialProvider:()=>G_,createCliHandler:()=>DU,createApiBackendPreset:()=>fV,containerRegistryManager:()=>gL,composeServerlessAppTemplate:()=>WZ,composePresets:()=>tV,collectPhpAppEntries:()=>s6,cloudTrailManager:()=>jL,cloudConfigSchema:()=>a_,clearSigningKeyCache:()=>Xz,chunk:()=>rz,checkServiceQuotas:()=>M_,checkIAMPermissions:()=>L_,certificateManager:()=>bL,categorizeChanges:()=>r_,canaryManager:()=>qL,buildPhpRuntimeLayerZip:()=>nE,buildOptimizationManager:()=>fL,buildNodeRuntimeLayerZip:()=>DE,buildCloudFormationTemplate:()=>IV,buildBunRuntimeLayerZip:()=>RE,bounceComplaintHandler:()=>tL,blueGreenManager:()=>ML,batchProcessingManager:()=>ZE,batch:()=>y_,backupManager:()=>AL,awsConfigManager:()=>_L,autocomplete:()=>qj,artifactKey:()=>QZ,analyzeStackDiff:()=>CA,abTestManager:()=>TL,XRayManager:()=>OY,Workflow:()=>Tz,ValidationError:()=>uJ,TemplateCache:()=>cJ,TemplateBuilder:()=>u6,TaskList:()=>sz,SyntheticsManager:()=>Z$,StorageAdvancedManager:()=>OZ,Storage:()=>l1,StaticSiteManager:()=>KZ,StacksIntegration:()=>fA,StackDependencyManager:()=>ZY,Spinner:()=>tz,SmsHandlers:()=>qz,SmsAdvanced:()=>UU,ServiceMeshManager:()=>SY,SenderReputationManager:()=>uY,SecurityScanningManager:()=>wY,SecurityHubManager:()=>Y$,Security:()=>y0,SecretsRotationManager:()=>MY,SecretsManager:()=>qY,Secrets:()=>v$,Search:()=>d2,SMS:()=>B1,S3Error:()=>V1,S3Client:()=>gJ,Route53RoutingManager:()=>bY,Route53ResolverManager:()=>vY,ResourceManagementManager:()=>_Z,ReplicaManager:()=>jY,Registry:()=>J2,RegionPairManager:()=>YY,Redirects:()=>E2,RealtimePresets:()=>KA,RateLimiter:()=>pz,REPLContext:()=>ez,REPLCommandBuilder:()=>$U,REPL:()=>oz,RECOMMENDED_SCPS:()=>ij,RECOMMENDED_ACCOUNT_STRUCTURES:()=>ZU,QueuePresets:()=>BA,QueueManagementManager:()=>ZZ,Queue:()=>_1,Pseudo:()=>RA,ProgressiveDeploymentManager:()=>KY,ProgressBar:()=>iz,PreviewNotificationService:()=>sJ,PreviewEnvironmentManager:()=>tJ,PhoneHandlers:()=>Mz,PhoneAdvanced:()=>zU,Phone:()=>Y2,Permissions:()=>R1,PerformanceManager:()=>LY,ParameterStore:()=>m0,PHP_LAYER_EXTENSIONS:()=>BU,PHP_DEFAULT_EXCLUDES:()=>kU,OrganizationManager:()=>GY,NetworkSecurityManager:()=>VZ,Network:()=>x0,MultiStepProgress:()=>az,MultiRegionManager:()=>eJ,MultiAccountManager:()=>QY,Monitoring:()=>u8,MockS3:()=>iJ,MockDynamoDB:()=>aJ,MockCloudFormation:()=>nJ,MigrationManager:()=>_Y,MetricsManager:()=>AY,Messaging:()=>D1,MANAGED_NODE_VERSIONS:()=>XU,LogsManager:()=>VY,LambdaVersionsManager:()=>CY,LambdaVPCManager:()=>kY,LambdaLayersManager:()=>PY,LambdaDestinationsManager:()=>IY,LambdaDLQManager:()=>hY,LambdaConcurrencyManager:()=>xY,LARAVEL_SERVERLESS_BUILD_STEPS:()=>SU,JobLoader:()=>L2,ImageScanningManager:()=>DY,HealthCheckManager:()=>AZ,HashCache:()=>mz,GuardDutyManager:()=>FY,GlobalResourceManager:()=>JY,Fn:()=>L,FileSystem:()=>Z2,FileCache:()=>dJ,FIFOQueueManager:()=>$Z,ErrorCodes:()=>gz,EmailTemplateManager:()=>dY,EmailHandlers:()=>GU,EmailAnalyticsManager:()=>gY,EmailAdvanced:()=>QU,Email:()=>q0,DisasterRecoveryManager:()=>zY,DeploymentError:()=>vz,Deployment:()=>O1,DependencyGraph:()=>Lz,DebugLogger:()=>N1,DatabaseUserManager:()=>EY,Database:()=>m2,DNSSECManager:()=>yY,DNS:()=>X1,DLQMonitoringManager:()=>JZ,DEFAULT_SERVICE_LIMITS:()=>F1,CrossRegionReferenceManager:()=>$Y,CredentialError:()=>g2,ContainerRegistryManager:()=>NY,ConfigurationError:()=>I8,Compute:()=>Z0,Communication:()=>A1,CommandHistory:()=>JU,CloudTrailManager:()=>HY,CloudFrontClient:()=>yz,CloudFormationClient:()=>bz,CloudFormationBuilder:()=>bJ,CloudError:()=>Q2,CertificateManager:()=>TY,CanaryManager:()=>y8,Cache:()=>g8,COMMON_CROSS_ACCOUNT_ROLES:()=>aj,CDN:()=>m1,BuildOptimizationManager:()=>RY,BounceComplaintHandler:()=>fY,BlueGreenManager:()=>XY,BatchProcessingManager:()=>YZ,BackupManager:()=>WY,Auth:()=>K1,AssetHasher:()=>J1,Arn:()=>h8,ApiGateway:()=>c6,AWS_REGIONS:()=>r1,AWS_PSEUDO_PARAMETERS:()=>nA,AWSConfigManager:()=>UY,AWSAPIError:()=>fz,AI:()=>p1,ABTestManager:()=>BY});import{createRequire as QA}from"node:module";import{existsSync as w8,readdirSync as hA}from"node:fs";import{join as f2}from"node:path";import{createHash as cA}from"node:crypto";import{readFileSync as N6,readdirSync as mA,statSync as lA,existsSync as jJ,writeFileSync as S6,copyFileSync as pA}from"node:fs";import{join as D8,basename as rA,dirname as p4,extname as r4}from"node:path";import{readFileSync as fJ,existsSync as Dz}from"node:fs";import{homedir as Rz}from"node:os";import{join as Nz}from"node:path";import{createHash as cz}from"node:crypto";import{existsSync as t4,mkdirSync as w_,readFileSync as s4,readdirSync as o4,unlinkSync as R8,writeFileSync as D_}from"node:fs";import{join as EJ}from"node:path";import{createHash as mJ}from"node:crypto";import{createReadStream as N_,readdirSync as S_,statSync as h6}from"node:fs";import{join as P_,relative as C_}from"node:path";import{deflateRawSync as GE}from"node:zlib";import{execSync as FE}from"node:child_process";import{createHash as XE}from"node:crypto";import{cpSync as BE,mkdtempSync as KE,rmSync as OE,writeFileSync as AE}from"node:fs";import{tmpdir as VE}from"node:os";import{dirname as _E,isAbsolute as jE,join as S8,resolve as LE}from"node:path";import{fileURLToPath as EE}from"node:url";import{execFileSync as i6}from"node:child_process";import{mkdtempSync as AU,readFileSync as a6,rmSync as VU}from"node:fs";import{tmpdir as _U}from"node:os";import{dirname as TE,join as c2}from"node:path";import{fileURLToPath as wE}from"node:url";import{readFileSync as hE}from"node:fs";import{dirname as bE,join as NU}from"node:path";import{fileURLToPath as yE}from"node:url";import{execFileSync as C6}from"node:child_process";import{existsSync as fE,mkdirSync as gE,mkdtempSync as uE,readdirSync as dE,readFileSync as cE,rmSync as mE,statSync as PU,writeFileSync as lE}from"node:fs";import{tmpdir as pE}from"node:os";import{join as y$,relative as rE}from"node:path";import{execSync as iE}from"node:child_process";import{createHash as aE}from"node:crypto";import{readdirSync as tE,readFileSync as sE,statSync as xU}from"node:fs";import{join as oE,relative as IU,resolve as XZ}from"node:path";function zA($,J){this[$]=WA.bind(null,J)}function y6($){let J=typeof $==="string"?new URL($):$,{hostname:Y,pathname:Z}=J;if(Y.endsWith(".on.aws")){let z=Y.match(/^[^.]+\.lambda-url\.([^.]+)\.on\.aws$/);if(z)return{service:"lambda",region:z[1]};return{service:"",region:""}}if(Y.endsWith(".r2.cloudflarestorage.com"))return{service:"s3",region:"auto"};if(Y.endsWith(".backblazeb2.com")){let z=Y.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);if(z)return{service:"s3",region:z[1]};return{service:"",region:""}}let Q=Y.replace("dualstack.","").match(/([^.]+)\.(?:([^.]+)\.)?amazonaws\.com(?:\.cn)?$/);if(!Q)return{service:"",region:""};let G=Q[1],W=Q[2]||"";if(W==="us-gov")W="us-gov-west-1";else if(W==="s3"||W==="s3-accelerate")W="us-east-1",G="s3";else if(G==="iot")if(Y.startsWith("iot."))G="execute-api";else if(Y.startsWith("data.jobs.iot."))G="iot-jobs-data";else G=Z==="/mqtt"?"iotdevicegateway":"iotdata";else if(G==="autoscaling");else if(!W&&G.startsWith("s3-"))W=G.slice(3).replace(/^fips-|^external-1/,""),G="s3";else if(G.endsWith("-fips"))G=G.slice(0,-5);else if(W&&/-\d$/.test(G)&&!/-\d$/.test(W))[G,W]=[W,G];return G=Vz[G]||G,{service:G,region:W||"us-east-1"}}function Z1($){let{method:J,url:Y,body:Z="",accessKeyId:Q,secretAccessKey:G,sessionToken:W,signQuery:z=!1,expiresIn:U=86400,datetime:H}=$,F=new URL(Y),B=F.hostname,K=y6(F),O=$.service||K.service,V=$.region||K.region;if(!O)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!V)throw Error("Could not detect region from URL. Please provide region explicitly.");let A=H||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),_=A.substring(0,8),M=[_,V,O,"aws4_request"].join("/"),E="AWS4-HMAC-SHA256";if(z)return FA({urlObj:F,method:J,body:Z,accessKeyId:Q,secretAccessKey:G,sessionToken:W,service:O,region:V,timestamp:A,date:_,credentialScope:M,algorithm:E,expiresIn:U,cache:$.cache});let j=F.pathname||"/",q=f6(F.searchParams),T={host:B,"x-amz-date":A,...$.headers};if(W)T["x-amz-security-token"]=W;let D=Object.keys(T).some((u)=>u.toLowerCase()==="content-type");if(Z&&!D)T["content-type"]="application/x-amz-json-1.0";if(O==="s3"&&!T["x-amz-content-sha256"])T["x-amz-content-sha256"]=P8(Z);let S=Yz(T),P=Zz(T),C=T["x-amz-content-sha256"]||P8(Z),I=[J,g6(j),q,S,P,C].join(`
|
|
60
60
|
`),b=P8(I),y=[E,A,M,b].join(`
|
|
61
|
-
`),c=$.cache??
|
|
61
|
+
`),c=$.cache??W$,r=Gz(G,_,V,O,y,c),d=[`${E} Credential=${Q}/${M}`,`SignedHeaders=${P}`,`Signature=${r}`].join(", ");return T.authorization=d,{url:Y,method:J,headers:T,body:Z||void 0}}async function v6($){let{method:J,url:Y,body:Z="",accessKeyId:Q,secretAccessKey:G,sessionToken:W,signQuery:z=!1,expiresIn:U=86400,datetime:H}=$,F=new URL(Y),B=F.hostname,K=y6(F),O=$.service||K.service,V=$.region||K.region;if(!O)throw Error("Could not detect service from URL. Please provide service explicitly.");if(!V)throw Error("Could not detect region from URL. Please provide region explicitly.");let A=H||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),_=A.substring(0,8),M=[_,V,O,"aws4_request"].join("/"),E="AWS4-HMAC-SHA256";if(z)return XA({urlObj:F,method:J,body:Z,accessKeyId:Q,secretAccessKey:G,sessionToken:W,service:O,region:V,timestamp:A,date:_,credentialScope:M,algorithm:E,expiresIn:U,cache:$.cache});let j=F.pathname||"/",q=f6(F.searchParams),T={host:B,"x-amz-date":A,...$.headers};if(W)T["x-amz-security-token"]=W;let D=Object.keys(T).some((s)=>s.toLowerCase()==="content-type");if(Z&&!D)T["content-type"]="application/x-amz-json-1.0";let S=await x6(Z);if(O==="s3"&&!T["x-amz-content-sha256"])T["x-amz-content-sha256"]=S;let P=Yz(T),C=Zz(T),I=T["x-amz-content-sha256"]||S,b=[J,g6(j),q,P,C,I].join(`
|
|
62
62
|
`),y=await x6(b),c=[E,A,M,y].join(`
|
|
63
|
-
`),r=$.cache??
|
|
63
|
+
`),r=$.cache??W$,d=await Wz(G,_,V,O,c,r),u=[`${E} Credential=${Q}/${M}`,`SignedHeaders=${C}`,`Signature=${d}`].join(", ");return T.authorization=u,{url:Y,method:J,headers:T,body:Z||void 0}}function FA($){let{urlObj:J,method:Y,body:Z,accessKeyId:Q,secretAccessKey:G,sessionToken:W,service:z,region:U,timestamp:H,date:F,credentialScope:B,algorithm:K,expiresIn:O,cache:V}=$,A=new URL(J.toString());A.searchParams.set("X-Amz-Algorithm",K),A.searchParams.set("X-Amz-Credential",`${Q}/${B}`),A.searchParams.set("X-Amz-Date",H),A.searchParams.set("X-Amz-Expires",String(O));let _=z==="s3"?"UNSIGNED-PAYLOAD":P8(Z);if(z==="s3")A.searchParams.set("X-Amz-Content-Sha256",_);let M="host";if(A.searchParams.set("X-Amz-SignedHeaders",M),W)A.searchParams.set("X-Amz-Security-Token",W);let E=g6(A.pathname||"/"),j=`host:${A.hostname}
|
|
64
64
|
`,q=f6(A.searchParams),T=[Y,E,q,j,M,_].join(`
|
|
65
65
|
`),D=[K,H,B,P8(T)].join(`
|
|
66
|
-
`),P=Gz(G,F,U,z,D,V??
|
|
66
|
+
`),P=Gz(G,F,U,z,D,V??W$);return A.searchParams.set("X-Amz-Signature",P),{url:A.toString(),method:Y,headers:{},body:Z||void 0}}async function XA($){let{urlObj:J,method:Y,body:Z,accessKeyId:Q,secretAccessKey:G,sessionToken:W,service:z,region:U,timestamp:H,date:F,credentialScope:B,algorithm:K,expiresIn:O,cache:V}=$,A=new URL(J.toString());A.searchParams.set("X-Amz-Algorithm",K),A.searchParams.set("X-Amz-Credential",`${Q}/${B}`),A.searchParams.set("X-Amz-Date",H),A.searchParams.set("X-Amz-Expires",String(O));let _=z==="s3"?"UNSIGNED-PAYLOAD":await x6(Z);if(z==="s3")A.searchParams.set("X-Amz-Content-Sha256",_);let M="host";if(A.searchParams.set("X-Amz-SignedHeaders",M),W)A.searchParams.set("X-Amz-Security-Token",W);let E=g6(A.pathname||"/"),j=`host:${A.hostname}
|
|
67
67
|
`,q=f6(A.searchParams),T=[Y,E,q,j,M,_].join(`
|
|
68
68
|
`),D=[K,H,B,await x6(T)].join(`
|
|
69
|
-
`),P=await Wz(G,F,U,z,D,V??
|
|
69
|
+
`),P=await Wz(G,F,U,z,D,V??W$);return A.searchParams.set("X-Amz-Signature",P),{url:A.toString(),method:Y,headers:{},body:Z||void 0}}function NJ($){let{url:J,method:Y="GET",expiresIn:Z=3600,...Q}=$,G=Math.min(Z,604800);return Z1({...Q,url:J,method:Y,signQuery:!0,expiresIn:G}).url}async function Jz($){let{url:J,method:Y="GET",expiresIn:Z=3600,...Q}=$,G=Math.min(Z,604800);return(await v6({...Q,url:J,method:Y,signQuery:!0,expiresIn:G})).url}function Yz($){return Object.keys($).sort().map((J)=>`${J.toLowerCase()}:${$[J].trim().replace(/\s+/g," ")}`).join(`
|
|
70
70
|
`)+`
|
|
71
|
-
`}function Zz($){return Object.keys($).sort().map((J)=>J.toLowerCase()).join(";")}function f6($){let J=[];return $.forEach((Y,Z)=>{J.push([qJ(Z),qJ(Y)])}),J.sort((Y,Z)=>{if(Y[0]<Z[0])return-1;if(Y[0]>Z[0])return 1;if(Y[1]<Z[1])return-1;if(Y[1]>Z[1])return 1;return 0}),J.map(([Y,Z])=>`${Y}=${Z}`).join("&")}function g6($){return $.split("/").map((J)=>qJ(J)).join("/")}function qJ($){return encodeURIComponent($).replace(/[!'()*]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}function P8($){if(!u$)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return u$.createHash("sha256").update($,"utf8").digest("hex")}function q8($,J){if(!u$)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return u$.createHmac("sha256",$).update(J,"utf8").digest()}async function x6($){let Y=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Y);return Qz(new Uint8Array(Z))}async function T8($,J){let Y=new TextEncoder,Z=typeof $==="string"?Y.encode($):$,Q=Y.encode(J),G=await crypto.subtle.importKey("raw",Z.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),W=await crypto.subtle.sign("HMAC",G,Q.buffer);return new Uint8Array(W)}function Qz($){return Array.from($).map((J)=>J.toString(16).padStart(2,"0")).join("")}function Gz($,J,Y,Z,Q,G){let W=`${$}:${J}:${Y}:${Z}`,z=G.get(W);if(!z){let U=q8(`AWS4${$}`,J),H=q8(U,Y),F=q8(H,Z);if(z=q8(F,"aws4_request"),G.size>=Az){let B=G.keys().next().value;if(B)G.delete(B)}G.set(W,z)}return q8(z,Q).toString("hex")}async function Wz($,J,Y,Z,Q,G){let W=`${$}:${J}:${Y}:${Z}`,z=G.get(W);if(!z){let H=await T8(`AWS4${$}`,J),F=await T8(H,Y),B=await T8(F,Z);if(z=await T8(B,"aws4_request"),G.size>=Az){let K=G.keys().next().value;if(K)G.delete(K)}G.set(W,z)}let U=await T8(z,Q);return Qz(U)}function zz($,J){return J.includes($)}function I6($,J,Y){let Z=J*Math.pow(2,$),Q=Math.random()*0.3*Z;return Math.min(Z+Q,Y)}function k6($){return new Promise((J)=>setTimeout(J,$))}async function
|
|
71
|
+
`}function Zz($){return Object.keys($).sort().map((J)=>J.toLowerCase()).join(";")}function f6($){let J=[];return $.forEach((Y,Z)=>{J.push([qJ(Z),qJ(Y)])}),J.sort((Y,Z)=>{if(Y[0]<Z[0])return-1;if(Y[0]>Z[0])return 1;if(Y[1]<Z[1])return-1;if(Y[1]>Z[1])return 1;return 0}),J.map(([Y,Z])=>`${Y}=${Z}`).join("&")}function g6($){return $.split("/").map((J)=>qJ(J)).join("/")}function qJ($){return encodeURIComponent($).replace(/[!'()*]/g,(J)=>`%${J.charCodeAt(0).toString(16).toUpperCase()}`)}function P8($){if(!u$)throw Error("Synchronous hash not available in browser. Use signRequestAsync() instead.");return u$.createHash("sha256").update($,"utf8").digest("hex")}function q8($,J){if(!u$)throw Error("Synchronous hmac not available in browser. Use signRequestAsync() instead.");return u$.createHmac("sha256",$).update(J,"utf8").digest()}async function x6($){let Y=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Y);return Qz(new Uint8Array(Z))}async function T8($,J){let Y=new TextEncoder,Z=typeof $==="string"?Y.encode($):$,Q=Y.encode(J),G=await crypto.subtle.importKey("raw",Z.buffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),W=await crypto.subtle.sign("HMAC",G,Q.buffer);return new Uint8Array(W)}function Qz($){return Array.from($).map((J)=>J.toString(16).padStart(2,"0")).join("")}function Gz($,J,Y,Z,Q,G){let W=`${$}:${J}:${Y}:${Z}`,z=G.get(W);if(!z){let U=q8(`AWS4${$}`,J),H=q8(U,Y),F=q8(H,Z);if(z=q8(F,"aws4_request"),G.size>=Az){let B=G.keys().next().value;if(B)G.delete(B)}G.set(W,z)}return q8(z,Q).toString("hex")}async function Wz($,J,Y,Z,Q,G){let W=`${$}:${J}:${Y}:${Z}`,z=G.get(W);if(!z){let H=await T8(`AWS4${$}`,J),F=await T8(H,Y),B=await T8(F,Z);if(z=await T8(B,"aws4_request"),G.size>=Az){let K=G.keys().next().value;if(K)G.delete(K)}G.set(W,z)}let U=await T8(z,Q);return Qz(U)}function zz($,J){return J.includes($)}function I6($,J,Y){let Z=J*Math.pow(2,$),Q=Math.random()*0.3*Z;return Math.min(Z+Q,Y)}function k6($){return new Promise((J)=>setTimeout(J,$))}async function Q$($,J){let{maxRetries:Y=3,initialDelayMs:Z=100,maxDelayMs:Q=5000,retryableStatusCodes:G=[429,500,502,503,504],timeoutMs:W=30000}=J??{},z,U;for(let H=0;H<=Y;H++){let F=Z1($),B={method:F.method,headers:F.headers};if(F.body)B.body=F.body;let K=new AbortController,O=setTimeout(()=>K.abort(),W);B.signal=K.signal;try{let V=await fetch(F.url,B);if(clearTimeout(O),U=V,V.ok)return V;if(H<Y&&zz(V.status,G)){let _=I6(H,Z,Q);await k6(_);continue}let A=await V.text();throw Error(`AWS API request failed (${V.status}): ${A}`)}catch(V){if(clearTimeout(O),z=V,V instanceof Error&&V.name==="AbortError")z=Error(`Request timed out after ${W}ms`);if(H<Y&&!(V instanceof Error&&V.message.includes("AWS API request failed"))){let A=I6(H,Z,Q);await k6(A);continue}throw z}}throw z??Error("Request failed after retries")}async function Uz($){return Q$($,{maxRetries:0})}async function Hz($,J){let{maxRetries:Y=3,initialDelayMs:Z=100,maxDelayMs:Q=5000,retryableStatusCodes:G=[429,500,502,503,504],timeoutMs:W=30000}=J??{},z;for(let U=0;U<=Y;U++){let H=await v6($),F={method:H.method,headers:H.headers};if(H.body)F.body=H.body;let B=new AbortController,K=setTimeout(()=>B.abort(),W);F.signal=B.signal;try{let O=await fetch(H.url,F);if(clearTimeout(K),O.ok)return O;if(U<Y&&zz(O.status,G)){let A=I6(U,Z,Q);await k6(A);continue}let V=await O.text();throw Error(`AWS API request failed (${O.status}): ${V}`)}catch(O){if(clearTimeout(K),z=O,O instanceof Error&&O.name==="AbortError")z=Error(`Request timed out after ${W}ms`);if(U<Y&&!(O instanceof Error&&O.message.includes("AWS API request failed"))){let V=I6(U,Z,Q);await k6(V);continue}throw z}}throw z??Error("Request failed after retries")}async function C8($){let J=await $.text(),Y={},Z=/<(\w+)>([^<]+)<\/\1>/g,Q;while((Q=Z.exec(J))!==null){let[,G,W]=Q;Y[G]=W}return Y}async function Fz($){return await $.json()}function Xz(){W$.clear()}function Bz(){return W$.size}function Kz(){return u$!==void 0}function Oz(){return typeof crypto<"u"&&typeof crypto.subtle<"u"}function M2($){if($.cloud?.provider)return $.cloud.provider;if($.hetzner?.apiToken)return"hetzner";return"aws"}class u6{template;constructor($){this.template={AWSTemplateFormatVersion:"2010-09-09",Description:$,Resources:{}}}addResource($,J){return this.template.Resources[$]=J,this}addResources($){return Object.assign(this.template.Resources,$),this}addParameter($,J){if(!this.template.Parameters)this.template.Parameters={};return this.template.Parameters[$]=J,this}addOutput($,J){if(!this.template.Outputs)this.template.Outputs={};return this.template.Outputs[$]=J,this}hasResource($){return $ in this.template.Resources}getResources(){return this.template.Resources}build(){return this.template}toJSON($=!0){return JSON.stringify(this.template,null,$?2:0)}toYAML(){return this.convertToYAML(this.template)}convertToYAML($,J=0){let Y=" ".repeat(J),Z="";for(let[Q,G]of Object.entries($)){if(G===null||G===void 0)continue;if(typeof G==="object"&&!Array.isArray(G))Z+=`${Y}${Q}:
|
|
72
72
|
${this.convertToYAML(G,J+1)}`;else if(Array.isArray(G)){Z+=`${Y}${Q}:
|
|
73
73
|
`;for(let W of G)if(typeof W==="object")Z+=`${Y} -
|
|
74
74
|
${this.convertToYAML(W,J+2)}`;else Z+=`${Y} - ${W}
|
|
75
75
|
`}else Z+=`${Y}${Q}: ${G}
|
|
76
|
-
`}return Z}}function OA($){let J=[],Y=[],Z=[];if(AA($,J),$.Resources)VA($.Resources,J,Y);else J.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if($.Parameters)_A($.Parameters,J,Y);if($.Outputs)jA($.Outputs,J);LA($,J);let Q=EA($);if(Q.length>0)for(let G of Q)J.push({path:"Resources",message:`Circular dependency detected: ${G.join(" → ")}`,severity:"error"});return qA($,Y,Z),{valid:J.length===0,errors:J,warnings:Y,info:Z}}function AA($,J){if(!$.AWSTemplateFormatVersion)J.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if($.AWSTemplateFormatVersion!=="2010-09-09")J.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function VA($,J,Y){let Z=Object.keys($);if(Z.length===0){J.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(Z.length>500)Y.push({path:"Resources",message:`Template contains ${Z.length} resources (limit is 500)`,severity:"warning"});for(let Q of Z){let G=$[Q];if(!/^[a-zA-Z0-9]+$/.test(Q))J.push({path:`Resources.${Q}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!G.Type)J.push({path:`Resources.${Q}.Type`,message:"Resource Type is required",severity:"error"});else if(!G.Type.startsWith("AWS::")&&!G.Type.startsWith("Custom::"))J.push({path:`Resources.${Q}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(G.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(G.DeletionPolicy))J.push({path:`Resources.${Q}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!G.DeletionPolicy&&_z(G.Type))Y.push({path:`Resources.${Q}.DeletionPolicy`,message:`${G.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function _A($,J,Y){let Z=Object.keys($);if(Z.length>200)Y.push({path:"Parameters",message:`Template contains ${Z.length} parameters (limit is 200)`,severity:"warning"});for(let Q of Z){let G=$[Q];if(!G.Type)J.push({path:`Parameters.${Q}.Type`,message:"Parameter Type is required",severity:"error"});let W=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(G.Type&&!W.includes(G.Type))J.push({path:`Parameters.${Q}.Type`,message:`Invalid parameter type: ${G.Type}`,severity:"error"})}}function jA($,J){let Y=Object.keys($);for(let Z of Y)if(!$[Z].Value)J.push({path:`Outputs.${Z}.Value`,message:"Output Value is required",severity:"error"})}function LA($,J){let Y=$.Resources||{},Z=$.Parameters||{},Q=new Set(Object.keys(Y)),G=new Set(Object.keys(Z));function W(z,U){if(typeof z!=="object"||z===null)return;if(z.Ref){let H=z.Ref;if(!Q.has(H)&&!G.has(H)&&H!=="AWS::Region"&&H!=="AWS::AccountId"&&H!=="AWS::StackName"&&H!=="AWS::StackId"&&H!=="AWS::URLSuffix"&&H!=="AWS::Partition"&&H!=="AWS::NoValue")J.push({path:U,message:`Reference to non-existent resource or parameter: ${H}`,severity:"error"})}if(z["Fn::GetAtt"]){let H=z["Fn::GetAtt"];if(Array.isArray(H)&&H.length>=1){let F=H[0];if(!Q.has(F))J.push({path:U,message:`GetAtt references non-existent resource: ${F}`,severity:"error"})}}for(let H in z)W(z[H],`${U}.${H}`)}for(let z in Y)W(Y[z],`Resources.${z}`);if($.Outputs)for(let z in $.Outputs)W($.Outputs[z],`Outputs.${z}`)}function EA($){let J=$.Resources||{},Y=new Map;for(let z in J){let U=new Set,H=J[z];if(H.DependsOn)if(Array.isArray(H.DependsOn))H.DependsOn.forEach((B)=>U.add(B));else U.add(H.DependsOn);MA(H).forEach((B)=>U.add(B)),Y.set(z,U)}let Z=[],Q=new Set,G=new Set;function W(z,U){Q.add(z),G.add(z),U.push(z);let H=Y.get(z)||new Set;for(let F of H)if(!Q.has(F))W(F,[...U]);else if(G.has(F)){let B=U.indexOf(F),K=[...U.slice(B),F];Z.push(K)}G.delete(z)}for(let z of Y.keys())if(!Q.has(z))W(z,[]);return Z}function MA($){let J=new Set;function Y(Z){if(typeof Z!=="object"||Z===null)return;if(Z.Ref&&typeof Z.Ref==="string"){if(!Z.Ref.startsWith("AWS::"))J.add(Z.Ref)}if(Z["Fn::GetAtt"]&&Array.isArray(Z["Fn::GetAtt"]))J.add(Z["Fn::GetAtt"][0]);for(let Q in Z)Y(Z[Q])}return Y($),J}function _z($){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes($)}function qA($,J,Y){let Z=$.Resources||{};if(!$.Description)Y.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let Q in Z){let G=Z[Q],W=G.Properties;if(W&&!W.Tags&&TA(G.Type))Y.push({path:`Resources.${Q}`,message:`Consider adding Tags to ${G.Type}`,severity:"info"});if(_z(G.Type)){if(G.Type==="AWS::S3::Bucket"&&!W?.BucketEncryption)J.push({path:`Resources.${Q}`,message:"S3 bucket should enable encryption",severity:"warning"});if(G.Type==="AWS::RDS::DBInstance"&&!W?.StorageEncrypted)J.push({path:`Resources.${Q}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function TA($){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes($)}function wA($){let J=[],Y=[],Z=[],Q=Buffer.byteLength($,"utf8"),G=Q/1024,W=51200,z=460800;if(Q>460800)J.push({path:"Template",message:`Template size (${G.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(Q>51200)Y.push({path:"Template",message:`Template size (${G.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:J.length===0,errors:J,warnings:Y,info:Z}}function DA($){let J=[],Y=[],Z=[],Q=$.Resources||{},G=$.Parameters||{},W=$.Outputs||{};if(Object.keys(Q).length>500)J.push({path:"Resources",message:`Template has ${Object.keys(Q).length} resources (limit is 500)`,severity:"error"});if(Object.keys(G).length>200)J.push({path:"Parameters",message:`Template has ${Object.keys(G).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(W).length>200)J.push({path:"Outputs",message:`Template has ${Object.keys(W).length} outputs (limit is 200)`,severity:"error"});return{valid:J.length===0,errors:J,warnings:Y,info:Z}}function f($){let{slug:J,environment:Y,resourceType:Z,timestamp:Q,suffix:G}=$,W=[J,Y,Z];if(Q)W.push(Q);if(G)W.push(G);return W.join("-")}function x($){return $.split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}function NA(){return Date.now().toString()}function SA($){return $.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function j1($,J){return $.project.stackName??`${$.project.slug}-${J}`}function SJ($,J,Y,Z){return Y.stackName??`${$.project.slug}-${Z}-${J}-site`}function PJ($,J){return`${$.project.slug}-${J}`}function CJ($,J,Y,Z){if(Z)return Z;if(Y==="main")return`${$}-${J}-site`;return`${$}-${J}-${Y}`}function PA($,J,Y,Z){return Z??`${$}-${J}-${Y}`}function jz($,J){return`${$}-${J}-deploy`}function W$($,J){return`${$.project.slug}-${J}-app`}function xJ($,J){return`${$}-${J}-deployments`}function d6($,J){return`${$}-${J}-assets`}class Lz{nodes=new Map;addResource($,J){let Y=this.extractDependencies(J);this.nodes.set($,{logicalId:$,resource:J,dependencies:Y})}extractDependencies($){let J=new Set;if($.DependsOn)if(Array.isArray($.DependsOn))$.DependsOn.forEach((Y)=>J.add(Y));else J.add($.DependsOn);return this.findReferences($.Properties||{},J),J}findReferences($,J){if(!$||typeof $!=="object")return;if("Ref"in $&&typeof $.Ref==="string"){if(!$.Ref.startsWith("AWS::"))J.add($.Ref)}if("Fn::GetAtt"in $&&Array.isArray($["Fn::GetAtt"]))J.add($["Fn::GetAtt"][0]);for(let Y of Object.values($))if(typeof Y==="object")this.findReferences(Y,J)}topologicalSort(){let $=[],J=new Set,Y=new Set,Z=(Q)=>{if(J.has(Q))return;if(Y.has(Q))throw Error(`Circular dependency detected: ${Q}`);Y.add(Q);let G=this.nodes.get(Q);if(G)for(let W of G.dependencies)Z(W);Y.delete(Q),J.add(Q),$.push(Q)};for(let Q of this.nodes.keys())Z(Q);return $}validate(){for(let[$,J]of this.nodes.entries())for(let Y of J.dependencies)if(!this.nodes.has(Y))throw Error(`Resource "${$}" depends on "${Y}" which does not exist`)}getDependents($){let J=[];for(let[Y,Z]of this.nodes.entries())if(Z.dependencies.has($))J.push(Y);return J}}function CA($,J){let Y=[],Z=[],Q=[],G=[],W=[],z=$.Resources||{},U=J.Resources||{},H=new Set([...Object.keys(z),...Object.keys(U)]);for(let B of H){let K=z[B],O=U[B];if(!K&&O)Y.push({logicalId:B,action:"add",resourceType:O.Type});else if(K&&!O)Z.push({logicalId:B,action:"remove",resourceType:K.Type});else if(K&&O)if(K.Type!==O.Type)G.push({logicalId:B,action:"replace",resourceType:O.Type,reason:`Type changed from ${K.Type} to ${O.Type}`});else{let V=Ez(K.Properties||{},O.Properties||{});if(V.length>0)if(xA(K.Type,V))G.push({logicalId:B,action:"replace",resourceType:O.Type,changes:V,reason:"Property changes require replacement"});else Q.push({logicalId:B,action:"update",resourceType:O.Type,changes:V});else W.push(B)}}let F=IA([...Z,...G,...Q]);return{added:Y,removed:Z,updated:Q,replaced:G,unchanged:W,summary:{totalChanges:Y.length+Z.length+Q.length+G.length,requiresReplacement:G.length>0,dangerousChanges:F}}}function Ez($,J,Y=""){let Z=[],Q=new Set([...Object.keys($),...Object.keys(J)]);for(let G of Q){let W=Y?`${Y}.${G}`:G,z=$[G],U=J[G];if(z===void 0&&U!==void 0)Z.push({path:W,oldValue:void 0,newValue:U});else if(z!==void 0&&U===void 0)Z.push({path:W,oldValue:z,newValue:void 0});else if(typeof z!==typeof U)Z.push({path:W,oldValue:z,newValue:U});else if(typeof z==="object"&&z!==null)if(Array.isArray(z)&&Array.isArray(U)){if(JSON.stringify(z)!==JSON.stringify(U))Z.push({path:W,oldValue:z,newValue:U})}else if(!Array.isArray(z)&&!Array.isArray(U)){let H=Ez(z,U,W);Z.push(...H)}else Z.push({path:W,oldValue:z,newValue:U});else if(z!==U)Z.push({path:W,oldValue:z,newValue:U})}return Z}function xA($,J){let Z={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[$];if(!Z)return!1;for(let Q of J){let G=Q.path.split(".")[0];if(Z.has(G))return!0}return!1}function IA($){let J=[];for(let Y of $){if(Y.action==="remove"&&(Y.resourceType==="AWS::RDS::DBInstance"||Y.resourceType==="AWS::DynamoDB::Table"||Y.resourceType==="AWS::ElastiCache::CacheCluster"))J.push(`Removing ${Y.resourceType} ${Y.logicalId} - data loss risk!`);if(Y.action==="replace"&&(Y.resourceType==="AWS::RDS::DBInstance"||Y.resourceType==="AWS::DynamoDB::Table"))J.push(`Replacing ${Y.resourceType} ${Y.logicalId} - data loss risk!`);if((Y.action==="remove"||Y.action==="replace")&&Y.resourceType==="AWS::S3::Bucket")J.push(`${Y.action==="remove"?"Removing":"Replacing"} S3 bucket ${Y.logicalId} - data loss risk!`);if(Y.action==="replace"&&Y.resourceType==="AWS::EC2::Instance")J.push(`Replacing EC2 instance ${Y.logicalId} - downtime expected`);if(Y.action==="update"&&Y.resourceType==="AWS::EC2::SecurityGroup")J.push(`Updating security group ${Y.logicalId} - may affect connectivity`);if((Y.action==="update"||Y.action==="replace")&&(Y.resourceType==="AWS::IAM::Role"||Y.resourceType==="AWS::IAM::Policy"))J.push(`Modifying IAM ${Y.resourceType.split("::")[2]} ${Y.logicalId} - may affect permissions`)}return J}function kA($){let J=[];if(J.push(`=== Stack Update Analysis ===
|
|
76
|
+
`}return Z}}function OA($){let J=[],Y=[],Z=[];if(AA($,J),$.Resources)VA($.Resources,J,Y);else J.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});if($.Parameters)_A($.Parameters,J,Y);if($.Outputs)jA($.Outputs,J);LA($,J);let Q=EA($);if(Q.length>0)for(let G of Q)J.push({path:"Resources",message:`Circular dependency detected: ${G.join(" → ")}`,severity:"error"});return qA($,Y,Z),{valid:J.length===0,errors:J,warnings:Y,info:Z}}function AA($,J){if(!$.AWSTemplateFormatVersion)J.push({path:"AWSTemplateFormatVersion",message:"Template should specify AWSTemplateFormatVersion",severity:"error"});else if($.AWSTemplateFormatVersion!=="2010-09-09")J.push({path:"AWSTemplateFormatVersion",message:'AWSTemplateFormatVersion must be "2010-09-09"',severity:"error"})}function VA($,J,Y){let Z=Object.keys($);if(Z.length===0){J.push({path:"Resources",message:"Template must contain at least one resource",severity:"error"});return}if(Z.length>500)Y.push({path:"Resources",message:`Template contains ${Z.length} resources (limit is 500)`,severity:"warning"});for(let Q of Z){let G=$[Q];if(!/^[a-zA-Z0-9]+$/.test(Q))J.push({path:`Resources.${Q}`,message:"Logical ID must contain only alphanumeric characters",severity:"error"});if(!G.Type)J.push({path:`Resources.${Q}.Type`,message:"Resource Type is required",severity:"error"});else if(!G.Type.startsWith("AWS::")&&!G.Type.startsWith("Custom::"))J.push({path:`Resources.${Q}.Type`,message:'Resource Type must start with "AWS::" or "Custom::"',severity:"error"});if(G.DeletionPolicy&&!["Delete","Retain","Snapshot"].includes(G.DeletionPolicy))J.push({path:`Resources.${Q}.DeletionPolicy`,message:'DeletionPolicy must be "Delete", "Retain", or "Snapshot"',severity:"error"});if(!G.DeletionPolicy&&_z(G.Type))Y.push({path:`Resources.${Q}.DeletionPolicy`,message:`${G.Type} should specify DeletionPolicy to prevent accidental data loss`,severity:"warning"})}}function _A($,J,Y){let Z=Object.keys($);if(Z.length>200)Y.push({path:"Parameters",message:`Template contains ${Z.length} parameters (limit is 200)`,severity:"warning"});for(let Q of Z){let G=$[Q];if(!G.Type)J.push({path:`Parameters.${Q}.Type`,message:"Parameter Type is required",severity:"error"});let W=["String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>","AWS::SSM::Parameter::Name","AWS::SSM::Parameter::Value<String>","AWS::SSM::Parameter::Value<List<String>>","AWS::SSM::Parameter::Value<CommaDelimitedList>"];if(G.Type&&!W.includes(G.Type))J.push({path:`Parameters.${Q}.Type`,message:`Invalid parameter type: ${G.Type}`,severity:"error"})}}function jA($,J){let Y=Object.keys($);for(let Z of Y)if(!$[Z].Value)J.push({path:`Outputs.${Z}.Value`,message:"Output Value is required",severity:"error"})}function LA($,J){let Y=$.Resources||{},Z=$.Parameters||{},Q=new Set(Object.keys(Y)),G=new Set(Object.keys(Z));function W(z,U){if(typeof z!=="object"||z===null)return;if(z.Ref){let H=z.Ref;if(!Q.has(H)&&!G.has(H)&&H!=="AWS::Region"&&H!=="AWS::AccountId"&&H!=="AWS::StackName"&&H!=="AWS::StackId"&&H!=="AWS::URLSuffix"&&H!=="AWS::Partition"&&H!=="AWS::NoValue")J.push({path:U,message:`Reference to non-existent resource or parameter: ${H}`,severity:"error"})}if(z["Fn::GetAtt"]){let H=z["Fn::GetAtt"];if(Array.isArray(H)&&H.length>=1){let F=H[0];if(!Q.has(F))J.push({path:U,message:`GetAtt references non-existent resource: ${F}`,severity:"error"})}}for(let H in z)W(z[H],`${U}.${H}`)}for(let z in Y)W(Y[z],`Resources.${z}`);if($.Outputs)for(let z in $.Outputs)W($.Outputs[z],`Outputs.${z}`)}function EA($){let J=$.Resources||{},Y=new Map;for(let z in J){let U=new Set,H=J[z];if(H.DependsOn)if(Array.isArray(H.DependsOn))H.DependsOn.forEach((B)=>U.add(B));else U.add(H.DependsOn);MA(H).forEach((B)=>U.add(B)),Y.set(z,U)}let Z=[],Q=new Set,G=new Set;function W(z,U){Q.add(z),G.add(z),U.push(z);let H=Y.get(z)||new Set;for(let F of H)if(!Q.has(F))W(F,[...U]);else if(G.has(F)){let B=U.indexOf(F),K=[...U.slice(B),F];Z.push(K)}G.delete(z)}for(let z of Y.keys())if(!Q.has(z))W(z,[]);return Z}function MA($){let J=new Set;function Y(Z){if(typeof Z!=="object"||Z===null)return;if(Z.Ref&&typeof Z.Ref==="string"){if(!Z.Ref.startsWith("AWS::"))J.add(Z.Ref)}if(Z["Fn::GetAtt"]&&Array.isArray(Z["Fn::GetAtt"]))J.add(Z["Fn::GetAtt"][0]);for(let Q in Z)Y(Z[Q])}return Y($),J}function _z($){return["AWS::S3::Bucket","AWS::DynamoDB::Table","AWS::RDS::DBInstance","AWS::RDS::DBCluster","AWS::ElastiCache::CacheCluster","AWS::ElastiCache::ReplicationGroup","AWS::EFS::FileSystem","AWS::OpenSearchService::Domain"].includes($)}function qA($,J,Y){let Z=$.Resources||{};if(!$.Description)Y.push({path:"Description",message:"Consider adding a Description to the template",severity:"info"});for(let Q in Z){let G=Z[Q],W=G.Properties;if(W&&!W.Tags&&TA(G.Type))Y.push({path:`Resources.${Q}`,message:`Consider adding Tags to ${G.Type}`,severity:"info"});if(_z(G.Type)){if(G.Type==="AWS::S3::Bucket"&&!W?.BucketEncryption)J.push({path:`Resources.${Q}`,message:"S3 bucket should enable encryption",severity:"warning"});if(G.Type==="AWS::RDS::DBInstance"&&!W?.StorageEncrypted)J.push({path:`Resources.${Q}`,message:"RDS instance should enable storage encryption",severity:"warning"})}}}function TA($){return!["AWS::CloudFormation::Stack","AWS::CloudFormation::WaitCondition","AWS::CloudFormation::WaitConditionHandle"].includes($)}function wA($){let J=[],Y=[],Z=[],Q=Buffer.byteLength($,"utf8"),G=Q/1024,W=51200,z=460800;if(Q>460800)J.push({path:"Template",message:`Template size (${G.toFixed(2)} KB) exceeds maximum size of 450 KB`,severity:"error"});else if(Q>51200)Y.push({path:"Template",message:`Template size (${G.toFixed(2)} KB) exceeds 50 KB. Must use S3 for deployment.`,severity:"warning"});return{valid:J.length===0,errors:J,warnings:Y,info:Z}}function DA($){let J=[],Y=[],Z=[],Q=$.Resources||{},G=$.Parameters||{},W=$.Outputs||{};if(Object.keys(Q).length>500)J.push({path:"Resources",message:`Template has ${Object.keys(Q).length} resources (limit is 500)`,severity:"error"});if(Object.keys(G).length>200)J.push({path:"Parameters",message:`Template has ${Object.keys(G).length} parameters (limit is 200)`,severity:"error"});if(Object.keys(W).length>200)J.push({path:"Outputs",message:`Template has ${Object.keys(W).length} outputs (limit is 200)`,severity:"error"});return{valid:J.length===0,errors:J,warnings:Y,info:Z}}function f($){let{slug:J,environment:Y,resourceType:Z,timestamp:Q,suffix:G}=$,W=[J,Y,Z];if(Q)W.push(Q);if(G)W.push(G);return W.join("-")}function x($){return $.split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join("")}function NA(){return Date.now().toString()}function SA($){return $.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/^-+|-+$/g,"").replace(/-+/g,"-")}function j1($,J){return $.project.stackName??`${$.project.slug}-${J}`}function SJ($,J,Y,Z){return Y.stackName??`${$.project.slug}-${Z}-${J}-site`}function PJ($,J){return`${$.project.slug}-${J}`}function CJ($,J,Y,Z){if(Z)return Z;if(Y==="main")return`${$}-${J}-site`;return`${$}-${J}-${Y}`}function PA($,J,Y,Z){return Z??`${$}-${J}-${Y}`}function jz($,J){return`${$}-${J}-deploy`}function z$($,J){return`${$.project.slug}-${J}-app`}function xJ($,J){return`${$}-${J}-deployments`}function d6($,J){return`${$}-${J}-assets`}class Lz{nodes=new Map;addResource($,J){let Y=this.extractDependencies(J);this.nodes.set($,{logicalId:$,resource:J,dependencies:Y})}extractDependencies($){let J=new Set;if($.DependsOn)if(Array.isArray($.DependsOn))$.DependsOn.forEach((Y)=>J.add(Y));else J.add($.DependsOn);return this.findReferences($.Properties||{},J),J}findReferences($,J){if(!$||typeof $!=="object")return;if("Ref"in $&&typeof $.Ref==="string"){if(!$.Ref.startsWith("AWS::"))J.add($.Ref)}if("Fn::GetAtt"in $&&Array.isArray($["Fn::GetAtt"]))J.add($["Fn::GetAtt"][0]);for(let Y of Object.values($))if(typeof Y==="object")this.findReferences(Y,J)}topologicalSort(){let $=[],J=new Set,Y=new Set,Z=(Q)=>{if(J.has(Q))return;if(Y.has(Q))throw Error(`Circular dependency detected: ${Q}`);Y.add(Q);let G=this.nodes.get(Q);if(G)for(let W of G.dependencies)Z(W);Y.delete(Q),J.add(Q),$.push(Q)};for(let Q of this.nodes.keys())Z(Q);return $}validate(){for(let[$,J]of this.nodes.entries())for(let Y of J.dependencies)if(!this.nodes.has(Y))throw Error(`Resource "${$}" depends on "${Y}" which does not exist`)}getDependents($){let J=[];for(let[Y,Z]of this.nodes.entries())if(Z.dependencies.has($))J.push(Y);return J}}function CA($,J){let Y=[],Z=[],Q=[],G=[],W=[],z=$.Resources||{},U=J.Resources||{},H=new Set([...Object.keys(z),...Object.keys(U)]);for(let B of H){let K=z[B],O=U[B];if(!K&&O)Y.push({logicalId:B,action:"add",resourceType:O.Type});else if(K&&!O)Z.push({logicalId:B,action:"remove",resourceType:K.Type});else if(K&&O)if(K.Type!==O.Type)G.push({logicalId:B,action:"replace",resourceType:O.Type,reason:`Type changed from ${K.Type} to ${O.Type}`});else{let V=Ez(K.Properties||{},O.Properties||{});if(V.length>0)if(xA(K.Type,V))G.push({logicalId:B,action:"replace",resourceType:O.Type,changes:V,reason:"Property changes require replacement"});else Q.push({logicalId:B,action:"update",resourceType:O.Type,changes:V});else W.push(B)}}let F=IA([...Z,...G,...Q]);return{added:Y,removed:Z,updated:Q,replaced:G,unchanged:W,summary:{totalChanges:Y.length+Z.length+Q.length+G.length,requiresReplacement:G.length>0,dangerousChanges:F}}}function Ez($,J,Y=""){let Z=[],Q=new Set([...Object.keys($),...Object.keys(J)]);for(let G of Q){let W=Y?`${Y}.${G}`:G,z=$[G],U=J[G];if(z===void 0&&U!==void 0)Z.push({path:W,oldValue:void 0,newValue:U});else if(z!==void 0&&U===void 0)Z.push({path:W,oldValue:z,newValue:void 0});else if(typeof z!==typeof U)Z.push({path:W,oldValue:z,newValue:U});else if(typeof z==="object"&&z!==null)if(Array.isArray(z)&&Array.isArray(U)){if(JSON.stringify(z)!==JSON.stringify(U))Z.push({path:W,oldValue:z,newValue:U})}else if(!Array.isArray(z)&&!Array.isArray(U)){let H=Ez(z,U,W);Z.push(...H)}else Z.push({path:W,oldValue:z,newValue:U});else if(z!==U)Z.push({path:W,oldValue:z,newValue:U})}return Z}function xA($,J){let Z={"AWS::S3::Bucket":new Set(["BucketName"]),"AWS::DynamoDB::Table":new Set(["TableName","KeySchema"]),"AWS::RDS::DBInstance":new Set(["DBInstanceIdentifier","DBName","Engine"]),"AWS::Lambda::Function":new Set(["FunctionName"]),"AWS::EC2::Instance":new Set(["ImageId","InstanceType","KeyName"]),"AWS::ECS::TaskDefinition":new Set(["Family","ContainerDefinitions"]),"AWS::ElastiCache::CacheCluster":new Set(["CacheNodeType","Engine"]),"AWS::CloudFront::Distribution":new Set([]),"AWS::Route53::HostedZone":new Set(["Name"]),"AWS::IAM::Role":new Set(["RoleName","Path"]),"AWS::KMS::Key":new Set(["KeyPolicy"]),"AWS::Cognito::UserPool":new Set(["UserPoolName"]),"AWS::OpenSearchService::Domain":new Set(["DomainName"])}[$];if(!Z)return!1;for(let Q of J){let G=Q.path.split(".")[0];if(Z.has(G))return!0}return!1}function IA($){let J=[];for(let Y of $){if(Y.action==="remove"&&(Y.resourceType==="AWS::RDS::DBInstance"||Y.resourceType==="AWS::DynamoDB::Table"||Y.resourceType==="AWS::ElastiCache::CacheCluster"))J.push(`Removing ${Y.resourceType} ${Y.logicalId} - data loss risk!`);if(Y.action==="replace"&&(Y.resourceType==="AWS::RDS::DBInstance"||Y.resourceType==="AWS::DynamoDB::Table"))J.push(`Replacing ${Y.resourceType} ${Y.logicalId} - data loss risk!`);if((Y.action==="remove"||Y.action==="replace")&&Y.resourceType==="AWS::S3::Bucket")J.push(`${Y.action==="remove"?"Removing":"Replacing"} S3 bucket ${Y.logicalId} - data loss risk!`);if(Y.action==="replace"&&Y.resourceType==="AWS::EC2::Instance")J.push(`Replacing EC2 instance ${Y.logicalId} - downtime expected`);if(Y.action==="update"&&Y.resourceType==="AWS::EC2::SecurityGroup")J.push(`Updating security group ${Y.logicalId} - may affect connectivity`);if((Y.action==="update"||Y.action==="replace")&&(Y.resourceType==="AWS::IAM::Role"||Y.resourceType==="AWS::IAM::Policy"))J.push(`Modifying IAM ${Y.resourceType.split("::")[2]} ${Y.logicalId} - may affect permissions`)}return J}function kA($){let J=[];if(J.push(`=== Stack Update Analysis ===
|
|
77
77
|
`),$.summary.totalChanges===0)return J.push(`No changes detected.
|
|
78
78
|
`),J.join(`
|
|
79
79
|
`);if(J.push(`Total changes: ${$.summary.totalChanges}`),J.push(`Requires replacement: ${$.summary.requiresReplacement?"Yes":"No"}
|
|
@@ -254,9 +254,9 @@ rpm -U ./amazon-cloudwatch-agent.rpm || true
|
|
|
254
254
|
# Install Node.js or PHP/Python based on app needs
|
|
255
255
|
# Configure application server (PM2, Nginx, Apache)
|
|
256
256
|
# Mount EFS for shared file storage
|
|
257
|
-
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[Z||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${Y}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:Z?{domain:Z,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:z==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:U==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${Y}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${Y}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${Y}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${Y}-app`,`${Y}-nginx`,`${Y}-workers`]}},security:{certificate:Z?{domain:Z,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:z==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...U==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function rV($){let{name:J,slug:Y,domain:Z,repository:Q,phpVersion:G="8.3",size:W="small",database:z=Y.replace(/-/g,"_"),databasePassword:U,sslEmail:H,deployStrategy:F="push",provider:B="hetzner"}=$;return{project:{name:J,slug:Y,region:"us-east-1"},mode:"server",cloud:{provider:B},environments:{production:{type:"production",domain:Z}},infrastructure:{compute:{mode:"server",size:W,runtime:"php",webServer:"nginx",php:{versions:[G],default:G},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:z,username:z,password:U}},sites:{main:{root:".",type:"laravel",domain:Z,phpVersion:G,repository:{...Q,strategy:F},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:H}}}}}function nV($){let{name:J,slug:Y,domain:Z,layers:Q,phpVersion:G="8.3",architecture:W="x86_64",memory:z=1024,build:U,deploy:H=["migrate --force"],cache:F="dynamodb",scheduler:B="on",region:K="us-east-1"}=$;return{project:{name:J,slug:Y,region:K},mode:"serverless",environments:{production:{type:"production",domain:Z,app:{kind:"php",runtime:"provided.al2023",phpVersion:G,architecture:W,layers:Q,memory:z,build:U,deploy:H,assets:"public",queues:!0,scheduler:B,cache:{driver:F},domain:Z}}}}}function iV($){return{root:$.root??"packages/ui/dist",deploy:"server",type:"static",domain:$.domain,build:$.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:$.username??"admin",password:$.password}}}function aV($){let J=$.split(".").filter(Boolean);return J.length<=2?$:J.slice(-2).join(".")}function wz($,J,Y){if(Y)return Y;let Z=[];for(let W of Object.values($.sites??{})){let z=W?.domain;if(typeof z==="string")Z.push(z);else if(Array.isArray(z))Z.push(...z.filter((U)=>typeof U==="string"))}if(J&&$.environments?.[J]?.domain)Z.push($.environments[J].domain);let Q=$.infrastructure?.dns?.domain;if(Q)Z.push(Q);let G=Z.find((W)=>W&&!W.startsWith("dashboard."));if(!G)return null;return`dashboard.${aV(G)}`}function
|
|
257
|
+
`}},storage:{uploads:{type:"efs",performanceMode:"generalPurpose",throughputMode:"bursting",encrypted:!0,lifecyclePolicy:{transitionToIA:30}},backups:{public:!1,versioning:!0,encryption:!0,lifecycleRules:[{id:"ArchiveOldBackups",enabled:!0,transitions:[{days:90,storageClass:"GLACIER"}]}]},static:{public:!0,versioning:!1,encryption:!1,cors:[{allowedOrigins:[Z||"*"],allowedMethods:["GET","HEAD"]}]}},cdn:{enabled:!0,origins:[{originId:"static-assets",domainName:`${Y}-static.s3.amazonaws.com`,pathPattern:"/static/*"}],customDomain:Z?{domain:Z,certificateArn:"TO_BE_GENERATED"}:void 0,cachePolicy:{minTTL:0,defaultTTL:86400,maxTTL:31536000},compress:!0,http3:!0},databases:z==="mysql"?{mysql:{engine:"mysql",version:"8.0",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",innodb_buffer_pool_size:"{DBInstanceClassMemory*3/4}",slow_query_log:"1",long_query_time:"2"}}}:{postgres:{engine:"postgres",version:"15",instanceClass:"db.t3.medium",allocatedStorage:100,maxAllocatedStorage:500,multiAZ:!0,backupRetentionDays:14,preferredBackupWindow:"03:00-04:00",preferredMaintenanceWindow:"sun:04:00-sun:05:00",enablePerformanceInsights:!0,performanceInsightsRetention:7,deletionProtection:!0,parameters:{max_connections:"500",shared_buffers:"{DBInstanceClassMemory/4}",log_min_duration_statement:"2000"}}},cache:U==="redis"?{redis:{nodeType:"cache.t3.medium",numCacheNodes:2,engine:"redis",engineVersion:"7.0",port:6379,parameterGroup:{maxmemoryPolicy:"allkeys-lru",timeout:"300"},snapshotRetentionLimit:5,snapshotWindow:"03:00-05:00",automaticFailoverEnabled:!0}}:void 0,queues:{jobs:{fifo:!1,visibilityTimeout:900,messageRetentionPeriod:345600,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3},emails:{fifo:!1,visibilityTimeout:300,messageRetentionPeriod:86400,deadLetterQueue:!0}},functions:{"job-worker":{runtime:"nodejs20.x",handler:"dist/workers/jobs.handler",memory:2048,timeout:900,events:[{type:"sqs",queueName:`${Y}-jobs`,batchSize:10}]},"email-sender":{runtime:"nodejs20.x",handler:"dist/workers/email.handler",memory:512,timeout:60,events:[{type:"sqs",queueName:`${Y}-emails`,batchSize:10}]},cleanup:{runtime:"nodejs20.x",handler:"dist/tasks/cleanup.handler",memory:512,timeout:300,events:[{type:"schedule",expression:"cron(0 2 * * ? *)"}]}},monitoring:{dashboard:{name:`${Y}-web-app`,widgets:[{type:"metric",metrics:["EC2CPUUtilization","ALBRequestCount","ALBTargetResponseTime","RDSCPUUtilization","RDSDatabaseConnections","RDSReadLatency","RDSWriteLatency"]}]},alarms:[{metric:"EC2CPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSCPUUtilization",threshold:80,evaluationPeriods:2},{metric:"RDSDatabaseConnections",threshold:400,evaluationPeriods:1},{metric:"ALBTargetResponseTime",threshold:2000,evaluationPeriods:2},{metric:"ALBUnhealthyHostCount",threshold:1,evaluationPeriods:1}],logs:{retention:14,groups:[`${Y}-app`,`${Y}-nginx`,`${Y}-workers`]}},security:{certificate:Z?{domain:Z,validationMethod:"DNS"}:void 0,waf:{enabled:!0,rules:["rateLimit","sqlInjection","xss","knownBadInputs"]},securityGroups:{alb:{ingress:[{port:80,protocol:"tcp",cidr:"0.0.0.0/0"},{port:443,protocol:"tcp",cidr:"0.0.0.0/0"}]},app:{ingress:[{port:3000,protocol:"tcp",source:"alb-sg"}]},database:{ingress:[{port:z==="mysql"?3306:5432,protocol:"tcp",source:"app-sg"}]},...U==="redis"&&{cache:{ingress:[{port:6379,protocol:"tcp",source:"app-sg"}]}}}}}}}function rV($){let{name:J,slug:Y,domain:Z,repository:Q,phpVersion:G="8.3",size:W="small",database:z=Y.replace(/-/g,"_"),databasePassword:U,sslEmail:H,deployStrategy:F="push",provider:B="hetzner"}=$;return{project:{name:J,slug:Y,region:"us-east-1"},mode:"server",cloud:{provider:B},environments:{production:{type:"production",domain:Z}},infrastructure:{compute:{mode:"server",size:W,runtime:"php",webServer:"nginx",php:{versions:[G],default:G},managedServices:{mysql:!0,redis:!0},firewall:{enabled:!0},autoUpdates:!0,monitoring:!0,backups:{enabled:!0,schedule:"0 2 * * *",retentionCount:7}},appDatabase:{engine:"mysql",name:z,username:z,password:U}},sites:{main:{root:".",type:"laravel",domain:Z,phpVersion:G,repository:{...Q,strategy:F},scheduler:!0,queues:[{connection:"redis",queue:"default",processes:1}],ssl:{provider:"letsencrypt",email:H}}}}}function nV($){let{name:J,slug:Y,domain:Z,layers:Q,phpVersion:G="8.3",architecture:W="x86_64",memory:z=1024,build:U,deploy:H=["migrate --force"],cache:F="dynamodb",scheduler:B="on",region:K="us-east-1"}=$;return{project:{name:J,slug:Y,region:K},mode:"serverless",environments:{production:{type:"production",domain:Z,app:{kind:"php",runtime:"provided.al2023",phpVersion:G,architecture:W,layers:Q,memory:z,build:U,deploy:H,assets:"public",queues:!0,scheduler:B,cache:{driver:F},domain:Z}}}}}function iV($){return{root:$.root??"packages/ui/dist",deploy:"server",type:"static",domain:$.domain,build:$.build??"cd packages/ui && bun install && bun run build",ssl:{provider:"letsencrypt"},auth:{username:$.username??"admin",password:$.password}}}function aV($){let J=$.split(".").filter(Boolean);return J.length<=2?$:J.slice(-2).join(".")}function wz($,J,Y){if(Y)return Y;let Z=[];for(let W of Object.values($.sites??{})){let z=W?.domain;if(typeof z==="string")Z.push(z);else if(Array.isArray(z))Z.push(...z.filter((U)=>typeof U==="string"))}if(J&&$.environments?.[J]?.domain)Z.push($.environments[J].domain);let Q=$.infrastructure?.dns?.domain;if(Q)Z.push(Q);let G=Z.find((W)=>W&&!W.startsWith("dashboard."));if(!G)return null;return`dashboard.${aV(G)}`}function U$($){return Object.entries($.sites??{}).some(([J,Y])=>{if(!Y)return!1;let Z=Y.root??"";return J==="dashboard"||Z==="ui/dist"||Z.endsWith("/ui/dist")||Z.endsWith("/dist/ui")})}function yJ($,J,Y){if(U$($))return null;let Z=wz($,J,Y.domain);if(!Z)return null;let Q=Y.password?{auth:{username:Y.username||"admin",password:Y.password,realm:Y.realm}}:{};if(Y.live){let W=Y.port??7676;return{name:"dashboard",site:{root:Y.uiRoot,deploy:"server",domain:Z,start:`cloud dashboard:serve --box --host 127.0.0.1 --port ${W}`,port:W,ssl:{provider:"letsencrypt"},...Y.build===!1||Y.build===void 0?{}:{build:Y.build},...Q}}}return{name:"dashboard",site:{root:Y.uiRoot,deploy:"server",type:"static",domain:Z,ssl:{provider:"letsencrypt"},...Y.build===!1||Y.build===void 0?{}:{build:Y.build},...Q}}}function vJ($,J){let Y={...$};for(let Z in J){let Q=J[Z],G=Y[Z];if(Q===void 0)continue;if(Array.isArray(Q)&&Array.isArray(G))Y[Z]=[...G,...Q];else if(typeof Q==="object"&&Q!==null&&!Array.isArray(Q)&&typeof G==="object"&&G!==null&&!Array.isArray(G))Y[Z]=vJ(G,Q);else Y[Z]=Q}return Y}function wJ($,J){return vJ($,J)}function tV(...$){return $.reduce((J,Y)=>vJ(J,Y),{})}function sV($,J){return(Y)=>{let Z=$(Y);if(typeof J==="function")return wJ(Z,J(Z,Y));return wJ(Z,J)}}function H$($){return{infrastructure:$}}function oV($){return H$({monitoring:$})}function eV($){return H$({security:$})}function $_($){return H$({databases:$})}function J_($){return H$({cache:$})}function Y_($){return H$({cdn:$})}function Z_($){return H$({queues:$})}function Sz(){let $=process.env.AWS_ACCESS_KEY_ID,J=process.env.AWS_SECRET_ACCESS_KEY;if(!$||!J)return null;return{accessKeyId:$,secretAccessKey:J,sessionToken:process.env.AWS_SESSION_TOKEN}}function Pz($){let J=$?.profile||process.env.AWS_PROFILE||"default",Y=$?.credentialsFile||Nz(Rz(),".aws","credentials");if(!Dz(Y))return null;try{let Z=fJ(Y,"utf-8");return Q_(Z,J)}catch{return null}}function Q_($,J){let Y=$.split(`
|
|
258
258
|
`),Z=null,Q,G,W;for(let z of Y){let U=z.trim();if(!U||U.startsWith("#")||U.startsWith(";"))continue;let H=U.match(/^\[([^\]]+)\]$/);if(H){if(Z===J&&Q&&G)return{accessKeyId:Q,secretAccessKey:G,sessionToken:W};Z=H[1],Q=void 0,G=void 0,W=void 0;continue}if(Z===J){let[F,...B]=U.split("="),K=B.join("=").trim();switch(F.trim().toLowerCase()){case"aws_access_key_id":Q=K;break;case"aws_secret_access_key":G=K;break;case"aws_session_token":W=K;break}}}if(Z===J&&Q&&G)return{accessKeyId:Q,secretAccessKey:G,sessionToken:W};return null}async function Cz($){let J=$?.timeout??1000,Y="http://169.254.169.254";try{let Z=await x8("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"21600"}},J);if(!Z.ok)return null;let Q=await Z.text(),G=await x8("http://169.254.169.254/latest/meta-data/iam/security-credentials/",{headers:{"X-aws-ec2-metadata-token":Q}},J);if(!G.ok)return null;let W=(await G.text()).trim(),z=await x8(`http://169.254.169.254/latest/meta-data/iam/security-credentials/${W}`,{headers:{"X-aws-ec2-metadata-token":Q}},J);if(!z.ok)return null;let U=await z.json();return{accessKeyId:U.AccessKeyId,secretAccessKey:U.SecretAccessKey,sessionToken:U.Token,expiration:new Date(U.Expiration)}}catch{return null}}async function xz($){let J=$?.timeout??1000,Y=process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI,Z=process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,Q=null;if(Y)Q=`http://169.254.170.2${Y}`;else if(Z)Q=Z;if(!Q)return null;try{let G={},W=process.env.AWS_CONTAINER_AUTHORIZATION_TOKEN;if(W)G.Authorization=W;let z=await x8(Q,{headers:G},J);if(!z.ok)return null;let U=await z.json();return{accessKeyId:U.AccessKeyId,secretAccessKey:U.SecretAccessKey,sessionToken:U.Token,expiration:new Date(U.Expiration)}}catch{return null}}async function Iz($){let J=$?.timeout??5000,Y=process.env.AWS_WEB_IDENTITY_TOKEN_FILE,Z=process.env.AWS_ROLE_ARN,Q=process.env.AWS_ROLE_SESSION_NAME||"ts-cloud-session";if(!Y||!Z)return null;try{let G=fJ(Y,"utf-8").trim(),W=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||"us-east-1",z=W.startsWith("us-gov")?`https://sts.${W}.amazonaws.com`:W==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${W}.amazonaws.com`,U=new URLSearchParams({Action:"AssumeRoleWithWebIdentity",Version:"2011-06-15",RoleArn:Z,RoleSessionName:Q,WebIdentityToken:G}),H=await x8(`${z}/?${U.toString()}`,{method:"POST"},J);if(!H.ok)return null;let F=await H.text(),B=N8(F,"AccessKeyId"),K=N8(F,"SecretAccessKey"),O=N8(F,"SessionToken"),V=N8(F,"Expiration");if(!B||!K)return null;return{accessKeyId:B,secretAccessKey:K,sessionToken:O??void 0,expiration:V?new Date(V):void 0}}catch{return null}}async function d8($){let J=Sz();if(J)return J;let Y=Pz($);if(Y)return Y;let Z=await Iz($);if(Z)return Z;let Q=await xz($);if(Q)return Q;let G=await Cz($);if(G)return G;throw Error("Could not find AWS credentials. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, or configure ~/.aws/credentials, or run on an EC2 instance with an IAM role.")}function G_($){let J=null,Y=null;return async()=>{if(J){if(!J.expiration)return J;let Z=300000;if(J.expiration.getTime()-Date.now()>Z)return J}if(Y)return Y;return Y=d8($).then((Z)=>{return J=Z,Y=null,Z}).catch((Z)=>{throw Y=null,Z}),Y}}async function x8($,J,Y){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),Y);try{let G=await fetch($,{...J,signal:Z.signal});return clearTimeout(Q),G}catch(G){throw clearTimeout(Q),G}}function N8($,J){let Y=new RegExp(`<${J}>([^<]+)</${J}>`),Z=$.match(Y);return Z?Z[1]:null}async function m6($){return d8({profile:$})}function kz($){let J=process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION;if(J)return J;let Y=Nz(Rz(),".aws","config");if(Dz(Y))try{let Z=fJ(Y,"utf-8"),Q=$||process.env.AWS_PROFILE||"default",G=Q==="default"?"[default]":`[profile ${Q}]`,W=Z.split(`
|
|
259
|
-
`),z=!1;for(let U of W){let H=U.trim();if(H.startsWith("[")){z=H===G;continue}if(z&&H.startsWith("region")){let[,F]=H.split("=");if(F)return F.trim()}}}catch{}return"us-east-1"}async function hz($){let J=$||await d8(),Y=kz(),{signRequest:Z}=await f8().then(()=>$z),Q=Y.startsWith("us-gov")?`https://sts.${Y}.amazonaws.com`:Y==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${Y}.amazonaws.com`,G="Action=GetCallerIdentity&Version=2011-06-15",W=Z({method:"POST",url:Q,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...J,service:"sts",region:Y}),z=await fetch(W.url,{method:W.method,headers:W.headers,body:W.body});if(!z.ok)throw Error(`Failed to get account ID: ${await z.text()}`);let U=await z.text(),H=N8(U,"Account");if(!H)throw Error("Failed to parse account ID from response");return H}class bz{profile;credentials=null;region;constructor($="us-east-1",J="default"){this.profile=J,this.region=$}async init(){if(this.credentials=await m6(this.profile),this.credentials.region)this.region=this.credentials.region}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async request($,J){let Y=await this.ensureCredentials(),Z={Action:$,Version:"2010-05-15",...DJ(J)},Q=new URLSearchParams(Z).toString(),W=await(await
|
|
259
|
+
`),z=!1;for(let U of W){let H=U.trim();if(H.startsWith("[")){z=H===G;continue}if(z&&H.startsWith("region")){let[,F]=H.split("=");if(F)return F.trim()}}}catch{}return"us-east-1"}async function hz($){let J=$||await d8(),Y=kz(),{signRequest:Z}=await f8().then(()=>$z),Q=Y.startsWith("us-gov")?`https://sts.${Y}.amazonaws.com`:Y==="us-east-1"?"https://sts.amazonaws.com":`https://sts.${Y}.amazonaws.com`,G="Action=GetCallerIdentity&Version=2011-06-15",W=Z({method:"POST",url:Q,body:"Action=GetCallerIdentity&Version=2011-06-15",headers:{"Content-Type":"application/x-www-form-urlencoded"},...J,service:"sts",region:Y}),z=await fetch(W.url,{method:W.method,headers:W.headers,body:W.body});if(!z.ok)throw Error(`Failed to get account ID: ${await z.text()}`);let U=await z.text(),H=N8(U,"Account");if(!H)throw Error("Failed to parse account ID from response");return H}class bz{profile;credentials=null;region;constructor($="us-east-1",J="default"){this.profile=J,this.region=$}async init(){if(this.credentials=await m6(this.profile),this.credentials.region)this.region=this.credentials.region}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async request($,J){let Y=await this.ensureCredentials(),Z={Action:$,Version:"2010-05-15",...DJ(J)},Q=new URLSearchParams(Z).toString(),W=await(await Q$({method:"POST",url:`https://cloudformation.${this.region}.amazonaws.com/`,service:"cloudformation",region:this.region,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q,accessKeyId:Y.accessKeyId,secretAccessKey:Y.secretAccessKey,sessionToken:Y.sessionToken})).text();return W_(W)}async createStack($){let J={StackName:$.stackName};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;else throw Error("Either templateBody or templateURL must be provided");if($.parameters)for(let[Q,[G,W]]of Object.entries($.parameters).entries())J[`Parameters.member.${Q+1}.ParameterKey`]=G,J[`Parameters.member.${Q+1}.ParameterValue`]=W;if($.capabilities)for(let[Q,G]of $.capabilities.entries())J[`Capabilities.member.${Q+1}`]=G;if($.tags)for(let[Q,[G,W]]of Object.entries($.tags).entries())J[`Tags.member.${Q+1}.Key`]=G,J[`Tags.member.${Q+1}.Value`]=W;if($.timeoutInMinutes)J.TimeoutInMinutes=$.timeoutInMinutes;if($.onFailure)J.OnFailure=$.onFailure;let Y=await this.request("CreateStack",J);return(Y?.CreateStackResult||Y?.CreateStackResponse?.CreateStackResult||Y)?.StackId}async updateStack($){let J={StackName:$.stackName};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;if($.parameters)for(let[Q,[G,W]]of Object.entries($.parameters).entries())J[`Parameters.member.${Q+1}.ParameterKey`]=G,J[`Parameters.member.${Q+1}.ParameterValue`]=W;if($.capabilities)for(let[Q,G]of $.capabilities.entries())J[`Capabilities.member.${Q+1}`]=G;if($.tags)for(let[Q,[G,W]]of Object.entries($.tags).entries())J[`Tags.member.${Q+1}.Key`]=G,J[`Tags.member.${Q+1}.Value`]=W;let Y=await this.request("UpdateStack",J);return(Y?.UpdateStackResult||Y?.UpdateStackResponse?.UpdateStackResult||Y)?.StackId}async deleteStack($){await this.request("DeleteStack",{StackName:$})}async describeStack($){let J=await this.request("DescribeStacks",{StackName:$}),Z=(J?.DescribeStacksResult||J?.DescribeStacksResponse?.DescribeStacksResult||J)?.Stacks?.member,Q=Array.isArray(Z)?Z[0]:Z;if(!Q)throw Error(`Stack ${$} not found`);return z_(Q)}async listStacks($){let J={};if($)for(let[Z,Q]of $.entries())J[`StackStatusFilter.member.${Z+1}`]=Q;let Y=await this.request("ListStacks",J);return U_(Y)}async describeStackEvents($){let J=await this.request("DescribeStackEvents",{StackName:$});return H_(J)}async waitForStack($,J,Y){let G=0,W=null;while(G<360){G++;let z=await this.describeStack($);if(Y)try{let U=await this.describeStackEvents($),H=[];if(W){for(let F of U){if(F.EventId===W)break;H.push(F)}H.reverse()}else if(U.length>0)H=[U[0]];for(let F of H)Y(F);if(U.length>0)W=U[0].EventId}catch{}if(z.StackStatus&&J.includes(z.StackStatus))return z;if(z.StackStatus?.includes("FAILED")||z.StackStatus?.includes("ROLLBACK"))throw Error(`Stack reached failed state: ${z.StackStatus}
|
|
260
260
|
Reason: ${z.StackStatusReason||"Unknown"}`);await new Promise((U)=>setTimeout(U,5000))}throw Error(`Timeout waiting for stack ${$} to complete`)}async waitForStackWithProgress($,J,Y){let Q={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]}[J];if(!Q)throw Error(`Unknown waiter: ${J}`);return this.waitForStack($,Q,Y)}async createChangeSet($){let J={StackName:$.stackName,ChangeSetName:$.changeSetName,ChangeSetType:"UPDATE"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateURL)J.TemplateURL=$.templateURL;if($.parameters)for(let[Z,[Q,G]]of Object.entries($.parameters).entries())J[`Parameters.member.${Z+1}.ParameterKey`]=Q,J[`Parameters.member.${Z+1}.ParameterValue`]=G;if($.capabilities)for(let[Z,Q]of $.capabilities.entries())J[`Capabilities.member.${Z+1}`]=Q;return(await this.request("CreateChangeSet",J)).ChangeSetId}async executeChangeSet($,J){await this.request("ExecuteChangeSet",{ChangeSetName:$,StackName:J})}async describeStacks($){let J=typeof $==="string"?$:$.stackName;try{return{Stacks:[await this.describeStack(J)]}}catch{return{Stacks:[]}}}async getStackOutputs($){let J=await this.request("DescribeStacks",{StackName:$}),Z=(J?.DescribeStacksResult||J?.DescribeStacksResponse?.DescribeStacksResult||J)?.Stacks?.member,Q=Array.isArray(Z)?Z[0]:Z;if(!Q)return{};let G={},W=Q.Outputs?.member;if(W){let z=Array.isArray(W)?W:[W];for(let U of z)if(U.OutputKey&&U.OutputValue)G[U.OutputKey]=U.OutputValue}return G}}function DJ($,J=""){let Y={};for(let[Z,Q]of Object.entries($)){let G=J?`${J}.${Z}`:Z;if(Array.isArray(Q))Q.forEach((W,z)=>{if(typeof W==="object")Object.assign(Y,DJ(W,`${G}.${z+1}`));else Y[`${G}.${z+1}`]=String(W)});else if(typeof Q==="object"&&Q!==null)Object.assign(Y,DJ(Q,G));else if(Q!==void 0&&Q!==null)Y[G]=String(Q)}return Y}function W_($){$=$.replace(/<\?xml[^?]*\?>\s*/,"").trim();function J(Q,G,W){let z=1,U=W,H=`<${G}`,F=`</${G}>`;while(U<Q.length&&z>0){let B=Q.indexOf(H,U),K=Q.indexOf(F,U);if(K===-1)return-1;if(B!==-1&&B<K){let O=Q[B+H.length];if(O===">"||O===" "||O==="/"){let V=Q.indexOf(">",B);if(V!==-1&&Q[V-1]==="/")U=V+1;else z++,U=V+1}else U=B+H.length}else{if(z--,z===0)return K;U=K+F.length}}return-1}function Y(Q,G){while(G<Q.length&&/\s/.test(Q[G]))G++;if(G>=Q.length||Q[G]!=="<"){let A=Q.indexOf("<",G);if(A===-1)return{value:Q.slice(G).trim(),end:Q.length};return{value:Q.slice(G,A).trim(),end:A}}if(Q[G+1]==="/")return{value:void 0,end:G};let W=Q.slice(G).match(/^<(\w+)([^>]*?)\/?>/);if(!W)return{value:void 0,end:G+1};let z=W[1];if(W[0].endsWith("/>"))return{value:"",end:G+W[0].length};let H=G+W[0].length,F=`</${z}>`,B=J(Q,z,H);if(B===-1)return{value:void 0,end:G+W[0].length};let K=Q.slice(H,B).trim();if(!K.includes("<"))return{value:K,end:B+F.length};let O={},V=H;while(V<B){while(V<B&&/\s/.test(Q[V]))V++;if(V>=B)break;if(Q[V]!=="<"||Q[V+1]==="/")break;let A=Q.slice(V).match(/^<(\w+)/);if(!A)break;let _=A[1],M=Y(Q,V);if(M.value===void 0){V++;continue}if(_==="member"||O[_]!==void 0){if(!Array.isArray(O[_]))O[_]=O[_]!==void 0?[O[_]]:[];O[_].push(M.value)}else O[_]=M.value;V=M.end}return{value:O,end:B+F.length}}return Y($,0).value||{}}function z_($){return{StackName:$.StackName||"",StackId:$.StackId,StackStatus:$.StackStatus,CreationTime:$.CreationTime,LastUpdatedTime:$.LastUpdatedTime,StackStatusReason:$.StackStatusReason,Description:$.Description}}function U_($){let Y=($?.ListStacksResult||$?.ListStacksResponse?.ListStacksResult||$)?.StackSummaries?.member;if(!Y)return[];return(Array.isArray(Y)?Y:[Y]).map((Q)=>({StackName:Q.StackName||"",StackId:Q.StackId,StackStatus:Q.StackStatus,CreationTime:Q.CreationTime,LastUpdatedTime:Q.LastUpdatedTime,StackStatusReason:Q.StackStatusReason,Description:Q.Description}))}function H_($){let Y=($?.DescribeStackEventsResult||$?.DescribeStackEventsResponse?.DescribeStackEventsResult||$)?.StackEvents?.member;if(!Y)return[];return(Array.isArray(Y)?Y:[Y]).map((Q)=>({StackId:Q.StackId||"",EventId:Q.EventId||"",StackName:Q.StackName||"",LogicalResourceId:Q.LogicalResourceId||"",PhysicalResourceId:Q.PhysicalResourceId,ResourceType:Q.ResourceType||"",Timestamp:Q.Timestamp||"",ResourceStatus:Q.ResourceStatus||"",ResourceStatusReason:Q.ResourceStatusReason}))}class gJ{region;endpoint;forcePathStyle;credentials;credentialOptions;retryOptions;constructor($={}){this.region=$.region||process.env.AWS_REGION||"us-east-1",this.endpoint=$.endpoint||`https://s3.${this.region}.amazonaws.com`,this.forcePathStyle=$.forcePathStyle||!1,this.credentials=$.credentials,this.credentialOptions=$.credentialOptions,this.retryOptions=$.retryOptions||{}}async getCredentials(){if(this.credentials)return this.credentials;return d8(this.credentialOptions)}buildUrl($,J){let Y=J?encodeURIComponent(J).replace(/%2F/g,"/"):"";if(this.forcePathStyle)return J?`${this.endpoint}/${$}/${Y}`:`${this.endpoint}/${$}`;let Z=new URL(this.endpoint);return Z.hostname=`${$}.${Z.hostname}`,J?`${Z.origin}/${Y}`:Z.origin}async get($,J,Y={}){let Z=await this.getCredentials(),Q=this.buildUrl($,J),G={};if(Y.range)G.Range=Y.range;if(Y.ifModifiedSince)G["If-Modified-Since"]=Y.ifModifiedSince.toUTCString();if(Y.ifMatch)G["If-Match"]=Y.ifMatch;if(Y.ifNoneMatch)G["If-None-Match"]=Y.ifNoneMatch;let W=new URL(Q);if(Y.responseContentType)W.searchParams.set("response-content-type",Y.responseContentType);if(Y.responseContentDisposition)W.searchParams.set("response-content-disposition",Y.responseContentDisposition);let z=Z1({method:"GET",url:W.toString(),headers:G,...Z,service:"s3",region:this.region}),U=await fetch(z.url,{method:z.method,headers:z.headers});if(!U.ok&&U.status!==304){let H=await U.text();throw new V1(`Failed to get object: ${H}`,U.status,$,J)}return U}async getText($,J,Y={}){return(await this.get($,J,Y)).text()}async getJSON($,J,Y={}){return(await this.get($,J,Y)).json()}async getBuffer($,J,Y={}){return(await this.get($,J,Y)).arrayBuffer()}async put($,J,Y,Z={}){let Q,G;if(typeof Y==="string")Q=new TextEncoder().encode(Y).length,G=Y;else if(Y instanceof ArrayBuffer)Q=Y.byteLength,G=Y;else if(Y instanceof Uint8Array)Q=Y.byteLength,G=Y;else if(Y instanceof Blob)Q=Y.size,G=Y;else return this.uploadMultipart($,J,Y,{...Z,partSize:LJ});if(Q>X_){let W=O_(G).stream();return this.uploadMultipart($,J,W,{...Z,partSize:LJ})}return this.putSimple($,J,G,Q,Z)}async putSimple($,J,Y,Z,Q){let G=await this.getCredentials(),W=this.buildUrl($,J),z={"Content-Length":String(Z),"Content-Type":Q.contentType||a4(J)};if(Q.contentEncoding)z["Content-Encoding"]=Q.contentEncoding;if(Q.cacheControl)z["Cache-Control"]=Q.cacheControl;if(Q.contentDisposition)z["Content-Disposition"]=Q.contentDisposition;if(Q.storageClass)z["x-amz-storage-class"]=Q.storageClass;if(Q.serverSideEncryption)z["x-amz-server-side-encryption"]=Q.serverSideEncryption;if(Q.acl)z["x-amz-acl"]=Q.acl;if(Q.tagging)z["x-amz-tagging"]=Q.tagging;if(Q.metadata)for(let[K,O]of Object.entries(Q.metadata))z[`x-amz-meta-${K.toLowerCase()}`]=O;let U;if(typeof Y==="string")U=Y;else if(Y instanceof Blob)U=await Y.text();else U=new TextDecoder().decode(Y instanceof ArrayBuffer?new Uint8Array(Y):Y);let H=Z1({method:"PUT",url:W,headers:z,body:U,...G,service:"s3",region:this.region}),F=await fetch(H.url,{method:H.method,headers:H.headers,body:Y});if(!F.ok){let K=await F.text();throw new V1(`Failed to put object: ${K}`,F.status,$,J)}return{etag:(F.headers.get("ETag")||"").replace(/"/g,"")}}async delete($,J){let Y=await this.getCredentials(),Z=this.buildUrl($,J),Q=Z1({method:"DELETE",url:Z,...Y,service:"s3",region:this.region}),G=await fetch(Q.url,{method:Q.method,headers:Q.headers});if(!G.ok&&G.status!==204){let W=await G.text();throw new V1(`Failed to delete object: ${W}`,G.status,$,J)}}async deleteMany($,J){let Y=await this.getCredentials(),Z=`${this.buildUrl($)}?delete`,G=`<?xml version="1.0" encoding="UTF-8"?><Delete><Quiet>false</Quiet>${J.map((V)=>`<Object><Key>${K_(V)}</Key></Object>`).join("")}</Delete>`,W=Z1({method:"POST",url:Z,headers:{"Content-Type":"application/xml"},body:G,...Y,service:"s3",region:this.region}),z=await fetch(W.url,{method:W.method,headers:W.headers,body:G});if(!z.ok){let V=await z.text();throw new V1(`Failed to delete objects: ${V}`,z.status,$)}let U=await z.text(),H=[],F=[],B=/<Deleted><Key>([^<]+)<\/Key>/g,K;while((K=B.exec(U))!==null)H.push(K[1]);let O=/<Error><Key>([^<]+)<\/Key><Code>([^<]+)<\/Code><Message>([^<]+)<\/Message>/g;while((K=O.exec(U))!==null)F.push({key:K[1],error:`${K[2]}: ${K[3]}`});return{deleted:H,errors:F}}async list($,J={}){let Y=await this.getCredentials(),Z=new URL(this.buildUrl($));if(Z.searchParams.set("list-type","2"),J.prefix)Z.searchParams.set("prefix",J.prefix);if(J.delimiter)Z.searchParams.set("delimiter",J.delimiter);if(J.maxKeys)Z.searchParams.set("max-keys",String(J.maxKeys));if(J.continuationToken)Z.searchParams.set("continuation-token",J.continuationToken);if(J.startAfter)Z.searchParams.set("start-after",J.startAfter);let Q=Z1({method:"GET",url:Z.toString(),...Y,service:"s3",region:this.region}),G=await fetch(Q.url,{method:Q.method,headers:Q.headers});if(!G.ok){let z=await G.text();throw new V1(`Failed to list objects: ${z}`,G.status,$)}let W=await G.text();return B_(W)}async*listAll($,J={}){let Y;do{let Z=await this.list($,{...J,continuationToken:Y});for(let Q of Z.contents)yield Q;Y=Z.nextContinuationToken}while(Y)}async head($,J){let Y=await this.getCredentials(),Z=this.buildUrl($,J),Q=Z1({method:"HEAD",url:Z,...Y,service:"s3",region:this.region}),G=await fetch(Q.url,{method:Q.method,headers:Q.headers});if(G.status===404)return null;if(!G.ok){let z=await G.text();throw new V1(`Failed to head object: ${z}`,G.status,$,J)}let W={};return G.headers.forEach((z,U)=>{if(U.toLowerCase().startsWith("x-amz-meta-"))W[U.slice(11)]=z}),{contentLength:Number(G.headers.get("Content-Length")||0),contentType:G.headers.get("Content-Type")||"application/octet-stream",etag:(G.headers.get("ETag")||"").replace(/"/g,""),lastModified:new Date(G.headers.get("Last-Modified")||0),metadata:W,storageClass:G.headers.get("x-amz-storage-class")||void 0,serverSideEncryption:G.headers.get("x-amz-server-side-encryption")||void 0}}async exists($,J){return await this.head($,J)!==null}async copy($,J,Y,Z,Q={}){let G=await this.getCredentials(),W=this.buildUrl(Y,Z),z={"x-amz-copy-source":`/${$}/${encodeURIComponent(J)}`};if(Q.metadataDirective)z["x-amz-metadata-directive"]=Q.metadataDirective;if(Q.contentType)z["Content-Type"]=Q.contentType;if(Q.storageClass)z["x-amz-storage-class"]=Q.storageClass;if(Q.acl)z["x-amz-acl"]=Q.acl;if(Q.metadata)for(let[O,V]of Object.entries(Q.metadata))z[`x-amz-meta-${O.toLowerCase()}`]=V;let U=Z1({method:"PUT",url:W,headers:z,...G,service:"s3",region:this.region}),H=await fetch(U.url,{method:U.method,headers:U.headers});if(!H.ok){let O=await H.text();throw new V1(`Failed to copy object: ${O}`,H.status,Y,Z)}let B=(await H.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:B?B[1]:""}}async getPresignedUrl($,J,Y={}){let Z=await this.getCredentials(),Q=this.buildUrl($,J);return NJ({url:Q,method:Y.method||"GET",expiresIn:Y.expiresIn||3600,...Z,service:"s3",region:this.region})}async uploadMultipart($,J,Y,Z={}){let Q=await this.getCredentials(),G=Math.max(Z.partSize||LJ,F_),W,z;if(Y instanceof ReadableStream)W=Y;else if(Y instanceof Blob)W=Y.stream(),z=Y.size;else{let F=new Blob([Y]);W=F.stream(),z=F.size}let{uploadId:U,baseUrl:H}=await this.initiateMultipartUpload($,J,Z);try{let F=await this.uploadParts($,J,H,U,W,G,Q,z,Z.concurrency||4,Z.onProgress);return await this.completeMultipartUpload($,J,H,U,F)}catch(F){throw await this.abortMultipartUpload($,J,U,H).catch(()=>{}),F}}async initiateMultipartUpload($,J,Y){let Z=await this.getCredentials(),Q=this.buildUrl($,J),G=`${Q}?uploads`,W={"Content-Type":Y.contentType||a4(J)};if(Y.storageClass)W["x-amz-storage-class"]=Y.storageClass;if(Y.serverSideEncryption)W["x-amz-server-side-encryption"]=Y.serverSideEncryption;if(Y.acl)W["x-amz-acl"]=Y.acl;if(Y.metadata)for(let[K,O]of Object.entries(Y.metadata))W[`x-amz-meta-${K.toLowerCase()}`]=O;let z=Z1({method:"POST",url:G,headers:W,...Z,service:"s3",region:this.region}),U=await fetch(z.url,{method:z.method,headers:z.headers});if(!U.ok){let K=await U.text();throw new V1(`Failed to initiate multipart upload: ${K}`,U.status,$,J)}let F=(await U.text()).match(/<UploadId>([^<]+)<\/UploadId>/);if(!F)throw new V1("Failed to parse upload ID from response",0,$,J);let B=Q;if(U.url)try{let K=new URL(U.url);K.search="",B=K.toString()}catch{}return{uploadId:F[1],baseUrl:B}}async uploadParts($,J,Y,Z,Q,G,W,z,U,H){let F=[],B=Q.getReader(),K=1,O=new Uint8Array(0),V=0,A=z?Math.ceil(z/G):void 0,_=new Map,M=async(j,q)=>{let T=`${Y}?partNumber=${q}&uploadId=${encodeURIComponent(Z)}`,D={"Content-Length":String(j.byteLength),"x-amz-content-sha256":"UNSIGNED-PAYLOAD"},S=Z1({method:"PUT",url:T,headers:D,...W,service:"s3",region:this.region}),P=await fetch(S.url,{method:S.method,headers:S.headers,body:j,redirect:"error"});if(!P.ok){let I=await P.text();throw new V1(`Failed to upload part ${q}: ${I}`,P.status,$,J)}let C=(P.headers.get("ETag")||"").replace(/"/g,"");if(!C)throw new V1(`Missing ETag for part ${q}`,P.status,$,J);return{partNumber:q,etag:C}},E=async()=>{let j=await Promise.race(_.values());_.delete(j.partNumber),F.push(j)};while(!0){let{done:j,value:q}=await B.read();if(q){let T=new Uint8Array(O.length+q.length);T.set(O),T.set(q,O.length),O=T}while(O.length>=G||j&&O.length>0){let T=O.slice(0,G);O=O.slice(G);let D=K++;if(_.size>=U)await E();if(_.set(D,M(T,D)),V+=T.byteLength,H)H({loaded:V,total:z||V,part:D,totalParts:A||D})}if(j)break}while(_.size>0)await E();return F.sort((j,q)=>j.partNumber-q.partNumber),F}async completeMultipartUpload($,J,Y,Z,Q){let G=await this.getCredentials(),W=`${Y}?uploadId=${encodeURIComponent(Z)}`,U=`<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${Q.map((V)=>`<Part><PartNumber>${V.partNumber}</PartNumber><ETag>"${V.etag}"</ETag></Part>`).join("")}</CompleteMultipartUpload>`,H=Z1({method:"POST",url:W,headers:{"Content-Type":"application/xml"},body:U,...G,service:"s3",region:this.region}),F=await fetch(H.url,{method:H.method,headers:H.headers,body:U});if(!F.ok){let V=await F.text();throw new V1(`Failed to complete multipart upload: ${V}`,F.status,$,J)}let K=(await F.text()).match(/<ETag>"?([^"<]+)"?<\/ETag>/);return{etag:K?K[1]:""}}async abortMultipartUpload($,J,Y,Z){let Q=await this.getCredentials(),G=`${Z??this.buildUrl($,J)}?uploadId=${encodeURIComponent(Y)}`,W=Z1({method:"DELETE",url:G,...Q,service:"s3",region:this.region});await fetch(W.url,{method:W.method,headers:W.headers})}async emptyAndDeleteBucket($){let Y=[];for await(let W of this.listAll($,{}))if(Y.push(W.key),Y.length>=1000)await this.deleteMany($,Y),Y=[];if(Y.length>0)await this.deleteMany($,Y);let Z=await this.getCredentials(),Q=this.buildUrl($),G=Z1({method:"DELETE",url:Q,...Z,service:"s3",region:this.region});await fetch(G.url,{method:G.method,headers:G.headers})}}function B_($){let J=[],Y=[],Z=/<Contents>([\s\S]*?)<\/Contents>/g,Q;while((Q=Z.exec($))!==null){let W=Q[1];J.push({key:f1(W,"Key")||"",lastModified:new Date(f1(W,"LastModified")||0),etag:(f1(W,"ETag")||"").replace(/"/g,""),size:Number(f1(W,"Size")||0),storageClass:f1(W,"StorageClass")||"STANDARD"})}let G=/<CommonPrefixes><Prefix>([^<]+)<\/Prefix><\/CommonPrefixes>/g;while((Q=G.exec($))!==null)Y.push(Q[1]);return{contents:J,commonPrefixes:Y,isTruncated:f1($,"IsTruncated")==="true",continuationToken:f1($,"ContinuationToken")||void 0,nextContinuationToken:f1($,"NextContinuationToken")||void 0,keyCount:Number(f1($,"KeyCount")||0),maxKeys:Number(f1($,"MaxKeys")||1000),prefix:f1($,"Prefix")||void 0,delimiter:f1($,"Delimiter")||void 0}}function f1($,J){let Y=new RegExp(`<${J}>([^<]*)</${J}>`),Z=$.match(Y);return Z?Z[1]:null}function K_($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function a4($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",htm:"text/html",css:"text/css",js:"application/javascript",mjs:"application/javascript",json:"application/json",xml:"application/xml",txt:"text/plain",md:"text/markdown",csv:"text/csv",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",avif:"image/avif",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",avi:"video/x-msvideo",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",rar:"application/vnd.rar","7z":"application/x-7z-compressed",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",wasm:"application/wasm"}[J||""]||"application/octet-stream"}function O_($){if($ instanceof Blob)return $;if(typeof $==="string")return new Blob([$],{type:"text/plain"});return new Blob([$])}function A_($){return new gJ($)}class yz{profile;credentials=null;constructor($="default"){this.profile=$}async init(){this.credentials=await m6(this.profile)}async ensureCredentials(){if(!this.credentials)await this.init();return this.credentials}async createInvalidation($){let J=await this.ensureCredentials(),Y=$.callerReference||`invalidation-${Date.now()}`,Z=`<?xml version="1.0" encoding="UTF-8"?>
|
|
261
261
|
<InvalidationBatch>
|
|
262
262
|
<Paths>
|
|
@@ -266,7 +266,7 @@ Reason: ${z.StackStatusReason||"Unknown"}`);await new Promise((U)=>setTimeout(U,
|
|
|
266
266
|
</Items>
|
|
267
267
|
</Paths>
|
|
268
268
|
<CallerReference>${Y}</CallerReference>
|
|
269
|
-
</InvalidationBatch>`,Q=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${$.distributionId}/invalidation`,G=await
|
|
269
|
+
</InvalidationBatch>`,Q=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${$.distributionId}/invalidation`,G=await Q$({method:"POST",url:Q,service:"cloudfront",region:"us-east-1",headers:{"Content-Type":"text/xml"},body:Z,accessKeyId:J.accessKeyId,secretAccessKey:J.secretAccessKey,sessionToken:J.sessionToken});return(await C8(G)).Id}async getInvalidation($,J){let Y=await this.ensureCredentials(),Z=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${$}/invalidation/${J}`,Q=await Q$({method:"GET",url:Z,service:"cloudfront",region:"us-east-1",accessKeyId:Y.accessKeyId,secretAccessKey:Y.secretAccessKey,sessionToken:Y.sessionToken});return await C8(Q)}async listInvalidations($){let J=await this.ensureCredentials(),Y=`https://cloudfront.amazonaws.com/2020-05-31/distribution/${$}/invalidation`,Z=await Q$({method:"GET",url:Y,service:"cloudfront",region:"us-east-1",accessKeyId:J.accessKeyId,secretAccessKey:J.secretAccessKey,sessionToken:J.sessionToken});return(await C8(Z)).Items||[]}async waitForInvalidation($,J,Y=60,Z=5000){for(let Q=0;Q<Y;Q++){if((await this.getInvalidation($,J)).Status==="Completed")return;if(Q<Y-1)await new Promise((W)=>setTimeout(W,Z))}throw Error(`Invalidation ${J} did not complete within the expected time`)}async invalidateAll($){return await this.createInvalidation({distributionId:$,paths:["/*"]})}}function uz($){return gz[$]}function RJ($,J){let Y=uz($);return new Q2(Y.message,$,Y.solution,J)}class N1{static verboseMode=!1;static debugMode=!1;static setVerbose($){this.verboseMode=$}static setDebug($){this.debugMode=$}static verbose($,...J){if(this.verboseMode)console.log(`[VERBOSE] ${$}`,...J)}static debug($,...J){if(this.debugMode)console.log(`[DEBUG] ${$}`,...J)}static info($,...J){console.log(`ℹ ${$}`,...J)}static warn($,...J){console.warn(`⚠ ${$}`,...J)}static error($,J){if(console.error(`✖ ${$}`),J){if(J instanceof Q2)console.error(J.toString());else console.error(J.message);if(this.debugMode&&J.stack)console.error(`
|
|
270
270
|
Stack trace:`),console.error(J.stack)}}static success($){console.log(`✔ ${$}`)}}function V_($){if(!$)throw RJ("MISSING_CONFIG");if(!$.project)throw new I8("Missing required field: project","Add a project configuration with name, slug, and region",{field:"project"});if(!$.project.name)throw new I8("Missing required field: project.name","Add a project name to your configuration",{field:"project.name"});if(!$.project.slug)throw new I8("Missing required field: project.slug","Add a project slug (lowercase, alphanumeric with hyphens)",{field:"project.slug"});if(!/^[a-z0-9-]+$/.test($.project.slug))throw new uJ("Invalid project slug format","Use only lowercase letters, numbers, and hyphens",{slug:$.project.slug});if($.project.region){if(!["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"].includes($.project.region))throw RJ("INVALID_REGION",{region:$.project.region})}N1.success("Configuration validation passed")}function __($){let J=[];if($.environments?.production&&$.infrastructure?.database){let Y=$.infrastructure.database;if((Y.postgres||Y.mysql)&&!Y.postgres?.multiAZ&&!Y.mysql?.multiAZ)J.push("Production database should use Multi-AZ for high availability")}if($.infrastructure?.storage){for(let[Y,Z]of Object.entries($.infrastructure.storage))if(Z.encryption===!1)J.push(`Storage "${Y}" is not encrypted - consider enabling encryption for security`)}if($.infrastructure?.storage){for(let[Y,Z]of Object.entries($.infrastructure.storage))if(Z.public===!0)J.push(`Storage "${Y}" is publicly accessible - ensure this is intentional`)}if($.infrastructure?.database){let Y=$.infrastructure.database;if(Y.postgres||Y.mysql){let Z=Y.postgres?.backupRetentionDays||Y.mysql?.backupRetentionDays;if(!Z||Z<7)J.push("Database backup retention is less than 7 days - consider increasing for production")}}if(!$.infrastructure?.monitoring)J.push("No monitoring configured - consider adding CloudWatch alarms");return J}async function j_($="default"){try{N1.verbose("Resolving AWS credentials...");let J=await m6($);if(!J.accessKeyId||!J.secretAccessKey)throw new g2("AWS credentials are incomplete","Ensure both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set");N1.verbose("Credentials resolved successfully"),N1.debug("Access Key ID:",J.accessKeyId.substring(0,8)+"..."),N1.verbose("Testing credentials with GetCallerIdentity...");let Y;try{Y=await hz(J),N1.verbose("Credentials are valid"),N1.debug("Account ID:",Y)}catch(Z){if(Z instanceof Error)if(Z.message.includes("InvalidClientTokenId"))throw new g2("Invalid AWS access key ID","Check that your AWS_ACCESS_KEY_ID is correct");else if(Z.message.includes("SignatureDoesNotMatch"))throw new g2("Invalid AWS secret access key","Check that your AWS_SECRET_ACCESS_KEY is correct");else if(Z.message.includes("ExpiredToken"))throw new g2("AWS credentials have expired","Refresh your temporary credentials or use long-term credentials");else throw new g2(`Failed to validate credentials: ${Z.message}`,"Verify your AWS credentials are correct and have the necessary permissions");throw Z}return{valid:!0,accountId:Y,region:J.region}}catch(J){if(J instanceof g2)throw J;return{valid:!1,error:J instanceof Error?J.message:"Unknown error"}}}async function L_($,J){return{allowed:J,denied:[]}}function dz($){let J=new Set(["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate","cloudformation:ListStacks"]);if($.infrastructure){if($.infrastructure.storage)J.add("s3:CreateBucket"),J.add("s3:DeleteBucket"),J.add("s3:PutBucketPolicy"),J.add("s3:PutBucketVersioning"),J.add("s3:PutBucketEncryption"),J.add("s3:PutObject"),J.add("s3:GetObject");if($.infrastructure.compute){if($.infrastructure.compute.server)J.add("ec2:RunInstances"),J.add("ec2:TerminateInstances"),J.add("ec2:DescribeInstances"),J.add("autoscaling:CreateAutoScalingGroup"),J.add("autoscaling:UpdateAutoScalingGroup"),J.add("autoscaling:DeleteAutoScalingGroup"),J.add("elasticloadbalancing:CreateLoadBalancer"),J.add("elasticloadbalancing:DeleteLoadBalancer");if($.infrastructure.compute.fargate)J.add("ecs:CreateCluster"),J.add("ecs:DeleteCluster"),J.add("ecs:CreateService"),J.add("ecs:UpdateService"),J.add("ecs:DeleteService"),J.add("ecs:RegisterTaskDefinition")}if($.infrastructure.database){if($.infrastructure.database.postgres||$.infrastructure.database.mysql)J.add("rds:CreateDBInstance"),J.add("rds:DeleteDBInstance"),J.add("rds:ModifyDBInstance"),J.add("rds:DescribeDBInstances");if($.infrastructure.database.dynamodb)J.add("dynamodb:CreateTable"),J.add("dynamodb:DeleteTable"),J.add("dynamodb:UpdateTable"),J.add("dynamodb:DescribeTable")}if($.infrastructure.functions)J.add("lambda:CreateFunction"),J.add("lambda:DeleteFunction"),J.add("lambda:UpdateFunctionCode"),J.add("lambda:UpdateFunctionConfiguration"),J.add("lambda:AddPermission");if($.infrastructure.cdn)J.add("cloudfront:CreateDistribution"),J.add("cloudfront:UpdateDistribution"),J.add("cloudfront:DeleteDistribution"),J.add("cloudfront:GetDistribution");if($.infrastructure.network)J.add("ec2:CreateVpc"),J.add("ec2:DeleteVpc"),J.add("ec2:CreateSubnet"),J.add("ec2:DeleteSubnet"),J.add("ec2:CreateInternetGateway"),J.add("ec2:DeleteInternetGateway"),J.add("ec2:CreateNatGateway"),J.add("ec2:DeleteNatGateway"),J.add("ec2:CreateRouteTable"),J.add("ec2:DeleteRouteTable"),J.add("ec2:CreateSecurityGroup"),J.add("ec2:DeleteSecurityGroup")}return J.add("iam:CreateRole"),J.add("iam:DeleteRole"),J.add("iam:AttachRolePolicy"),J.add("iam:DetachRolePolicy"),J.add("iam:PutRolePolicy"),J.add("iam:GetRole"),J.add("iam:PassRole"),Array.from(J).sort()}function E_($){let J=dz($);return JSON.stringify({Version:"2012-10-17",Statement:[{Effect:"Allow",Action:J,Resource:"*"}]},null,2)}async function M_($){let J=[];if(N1.verbose("Checking AWS service quotas..."),$.infrastructure?.compute?.server){let Z=$.infrastructure.compute.server.autoScaling?.max||1;J.push({service:"EC2",quotaName:"Running On-Demand Instances",currentValue:Z,limit:F1.ec2["Running On-Demand Instances"],percentage:Z/F1.ec2["Running On-Demand Instances"]*100,warning:Z>F1.ec2["Running On-Demand Instances"]*0.8})}if($.infrastructure?.network?.vpc)J.push({service:"EC2",quotaName:"VPCs",currentValue:1,limit:F1.ec2.VPCs,percentage:1/F1.ec2.VPCs*100,warning:!1});if($.infrastructure?.database?.postgres||$.infrastructure?.database?.mysql)J.push({service:"RDS",quotaName:"DB Instances",currentValue:1,limit:F1.rds["DB Instances"],percentage:1/F1.rds["DB Instances"]*100,warning:!1});if($.infrastructure?.storage){let Z=Object.keys($.infrastructure.storage).length;J.push({service:"S3",quotaName:"Buckets",currentValue:Z,limit:F1.s3.Buckets,percentage:Z/F1.s3.Buckets*100,warning:Z>F1.s3.Buckets*0.8})}if($.infrastructure?.functions){let Z=0;for(let Q of Object.values($.infrastructure.functions))if(Array.isArray(Q))Z+=Q.length;J.push({service:"Lambda",quotaName:"Functions (estimated)",currentValue:Z,limit:1000,percentage:Z/1000*100,warning:Z>800})}if($.infrastructure?.database?.dynamodb){let Z=$.infrastructure.database.dynamodb.tables?.length||0;J.push({service:"DynamoDB",quotaName:"Tables",currentValue:Z,limit:F1.dynamodb.Tables,percentage:Z/F1.dynamodb.Tables*100,warning:Z>F1.dynamodb.Tables*0.8})}let Y=J.filter((Z)=>Z.warning);if(Y.length>0){N1.warn("Service quota warnings detected:");for(let Z of Y)N1.warn(` ${Z.service} - ${Z.quotaName}: ${Z.currentValue}/${Z.limit} (${Z.percentage.toFixed(1)}%)`)}else N1.verbose("All service quotas are within limits");return J}function q_($){if($.length===0)return"No quotas to check";let J=`Service Quota Usage:
|
|
271
271
|
|
|
272
272
|
`,Y=$.reduce((Z,Q)=>{if(!Z[Q.service])Z[Q.service]=[];return Z[Q.service].push(Q),Z},{});for(let[Z,Q]of Object.entries(Y)){J+=`${Z}:
|
|
@@ -3639,7 +3639,7 @@ export const queue = __handlers.queue
|
|
|
3639
3639
|
export const cli = __handlers.cli
|
|
3640
3640
|
`}function ME(){return S8(_E(EE(import.meta.url)),"runtime","adapter.ts")}function FU($,J,Y){for(let Z of $??[])Y?.(`build: ${Z}`),FE(Z,{stdio:"inherit",cwd:J})}function r6($){return XE("sha256").update($).digest("hex")}function QZ($,J,Y){return`deployments/${$}/${J}/${Y}.zip`}async function c8($){let J=LE($.projectRoot??process.cwd()),{app:Y}=$;if(!$.skipBuild)FU(Y.build,J,$.onStep);let Z=Y.entry;if(!Z)throw Error("serverless app: `entry` is required to package a Node/Bun application");let Q=jE(Z)?Z:S8(J,Z),G=KE(S8(VE(),"tscloud-pkg-"));try{BE(ME(),S8(G,"adapter.ts"));let W=S8(G,"bootstrap.ts");AE(W,HU({entryImport:Q,adapterImport:"./adapter"})),$.onStep?.("bundling application");let z=await Bun.build({entrypoints:[W],target:Y.kind==="bun"?"bun":"node",format:"esm",minify:!1,sourcemap:"none"});if(!z.success){let K=z.logs.map((O)=>String(O)).join(`
|
|
3641
3641
|
`);throw Error(`serverless app bundle failed:
|
|
3642
|
-
${K}`)}let U=z.outputs[0],H=Buffer.from(await U.arrayBuffer()),F="index",B=d$([{name:`${F}.mjs`,data:H}]);return{zip:B,bundle:H,sha256:r6(B),handlerFile:F,handlers:{http:Y.handlers?.http??`${F}.http`,queue:Y.handlers?.queue??`${F}.queue`,cli:Y.handlers?.cli??`${F}.cli`},bundleBytes:H.length}}finally{OE(G,{recursive:!0,force:!0})}}function qE($){if(!$)return"22";let J=String($).match(/(\d+)/);return J?J[1]:"22"}function n6($){let J=$.kind??"node";if(J==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:$.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(J==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:$.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let Y=qE($.runtimeVersion);if($.runtime!=="provided.al2023"&&XU.includes(Y))return{lambdaRuntime:$.runtime&&$.runtime.startsWith("nodejs")?$.runtime:`nodejs${Y}.x`,kind:"node",version:Y,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:Y,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function m8($,J,Y){if($.queues===!1)return[];if($.queues===void 0||$.queues===!0)return[{name:`${J}-${Y}-default`}];return $.queues.map((Z)=>{if(typeof Z==="string")return{name:`${J}-${Y}-${Z}`};let[Q,G]=Object.entries(Z)[0];return{name:`${J}-${Y}-${Q}`,concurrency:G}})}function GZ($,J,Y){return m8($,J,Y).map((Z)=>Z.name)}function WZ($){let{app:J,environment:Y,handlers:Z}=$,Q=$.config.project.slug,G=n6(J).lambdaRuntime,W=J.architecture??"x86_64",z=$.config.project.region,U={http:`${Q}-${Y}-http`,queue:`${Q}-${Y}-queue`,cli:`${Q}-${Y}-cli`};if(J.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let H=m8(J,Q,Y),F=H.map((H0)=>H0.name),B=F.length>0,K=J.logRetention??14,O=J.packaging==="image",V=(J.scheduler??"on")!=="off",A=(J.cache?.driver??"dynamodb")==="dynamodb",_=Boolean(J.assets),M=d6(Q,Y),E=J.tmpStorage??512,j={},q={},T=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:L.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:L.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${Q}-${Y}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[L.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${Q}/${Y}/*`),L.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${Q}/${Y}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[L.sub(`arn:aws:s3:::${M}`),L.sub(`arn:aws:s3:::${M}/*`),...J.storage?.bucket?[L.sub(`arn:aws:s3:::${J.storage.bucket}`),L.sub(`arn:aws:s3:::${J.storage.bucket}/*`)]:[]]}]}}];if(B)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:L.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${Q}-${Y}-*`)});if(A)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:L.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${Q}-${Y}-cache*`)});let D=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(J.vpc?.subnets?.length)D.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");j.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${Q}-${Y}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:D,Policies:T}};let S=(H0)=>({TSCLOUD_LAMBDA_MODE:H0,TSCLOUD_ENV:Y,...J.octane?{TSCLOUD_OCTANE:"1"}:{},...J.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...A?{TSCLOUD_CACHE_TABLE:`${Q}-${Y}-cache`}:{},...B?{TSCLOUD_QUEUE:F[0]}:{},...J.env??{}}),P=Boolean(J.efs),C=typeof J.efs==="object"?J.efs:{},I=C.mountPath??"/mnt/local",b=P&&!C.accessPointArn,y=C.accessPointArn??(b?L.getAtt("EfsAccessPoint","Arn"):void 0),c=J.vpc?.subnets??[],r=c.length>0,d=J.cache?.driver==="elasticache"||J.database?.connection==="aurora-serverless"||Boolean(J.rdsProxy)||P;if(d&&!r)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let u=r?{VpcConfig:{SubnetIds:c,SecurityGroupIds:[...J.vpc?.securityGroups??[],...d?[L.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},s=b?c.map((H0,D0)=>`EfsMountTarget${D0}`):[],J0=P?{FileSystemConfigs:[{Arn:y,LocalMountPath:I}]}:{};if(P)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function t(H0,D0,f0,P0,o1,Y5,W8,i2=E){j[`${H0}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${D0}`,RetentionInDays:K}};let C9=O?{PackageType:"Image",Code:{ImageUri:L.ref("ImageUri")},...J.kind==="php"?{}:{ImageConfig:{Command:[f0]}}}:{Runtime:G,Handler:f0,Code:{S3Bucket:L.ref("ArtifactBucket"),S3Key:L.ref("ArtifactKey")},...$.runtimeLayers?.length?{Layers:$.runtimeLayers}:{}};j[H0]={Type:"AWS::Lambda::Function",DependsOn:[`${H0}LogGroup`,...s],Properties:{FunctionName:D0,Architectures:[W],MemorySize:o1,Timeout:Y5,Role:L.getAtt("AppRole","Arn"),Environment:{Variables:S(P0)},EphemeralStorage:{Size:i2},...C9,...W8!==void 0?{ReservedConcurrentExecutions:W8}:{},...u,...J0}}}if(t("HttpFunction",U.http,Z.http,"http",J.memory??1024,J.timeout??28,J.concurrency,E),t("CliFunction",U.cli,Z.cli,"cli",J.cliMemory??1024,J.cliTimeout??900,void 0,J.cliTmpStorage??E),B)t("QueueFunction",U.queue,Z.queue,"queue",J.queueMemory??1024,J.queueTimeout??120,void 0,J.queueTmpStorage??E);let a=(J.provisionedConcurrency??0)>0?J.provisionedConcurrency:0,e=["HttpFunction","CliFunction",...B?["QueueFunction"]:[]];if(a)for(let H0 of e)j[`${H0}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:L.ref(H0)}},j[`${H0}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:L.ref(H0),Name:"live",FunctionVersion:L.getAtt(`${H0}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:a}}};let L0=(H0)=>a?L.ref(`${H0}Alias`):L.getAtt(H0,"Arn"),_0=(H0)=>a?L.ref(`${H0}Alias`):L.ref(H0);j.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${Q}-${Y}`,ProtocolType:"HTTP"}},j.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:L.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:L0("HttpFunction"),PayloadFormatVersion:"2.0"}},j.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:L.ref("HttpApi"),RouteKey:"$default",Target:L.join("/",["integrations",L.ref("HttpIntegration")])}},j.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:L.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},j.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:_0("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:L.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},q.HttpApiEndpoint={Description:"HTTP API endpoint",Value:L.getAtt("HttpApi","ApiEndpoint")},q.HttpApiId={Description:"HTTP API id",Value:L.ref("HttpApi")};let O0=(Array.isArray(J.domain)?J.domain:J.domain?[J.domain]:[]).filter(Boolean);if(O0.length){if(!J.certificateArn&&!J.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let H0=J.certificateArn;if(!H0)j.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:O0[0],...O0.length>1?{SubjectAlternativeNames:O0.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:O0.map((D0)=>({DomainName:D0,HostedZoneId:J.hostedZoneId}))}},H0=L.ref("HttpCertificate");O0.forEach((D0,f0)=>{let P0=`HttpDomain${f0}`;if(j[P0]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:D0,DomainNameConfigurations:[{CertificateArn:H0,EndpointType:"REGIONAL"}]}},j[`HttpApiMapping${f0}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:L.ref("HttpApi"),DomainName:L.ref(P0),Stage:"$default"}},J.hostedZoneId)j[`HttpDomainRecord${f0}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:D0,Type:"A",AliasTarget:{DNSName:L.getAtt(P0,"RegionalDomainName"),HostedZoneId:L.getAtt(P0,"RegionalHostedZoneId")}}};q[`CustomDomain${f0}`]={Description:`Custom domain ${D0}`,Value:D0},q[`CustomDomainTarget${f0}`]={Description:`Point ${D0} (CNAME/alias) at this APIGW regional domain`,Value:L.getAtt(P0,"RegionalDomainName")}})}if(B)j.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${Q}-${Y}-dlq`,MessageRetentionPeriod:1209600}},H.forEach((H0,D0)=>{let f0=`AppQueue${D0}`,P0=J.queueTimeout??120;j[f0]={Type:"AWS::SQS::Queue",Properties:{QueueName:H0.name,VisibilityTimeout:Math.min(43200,P0*6),RedrivePolicy:{deadLetterTargetArn:L.getAtt("AppQueueDlq","Arn"),maxReceiveCount:J.queueTries??3}}};let o1=H0.concurrency??J.queueConcurrency;j[`${f0}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:L.getAtt(f0,"Arn"),FunctionName:_0("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...o1?{ScalingConfig:{MaximumConcurrency:Math.max(2,o1)}}:{}}},q[`QueueUrl${D0}`]={Description:`Queue URL: ${H0.name}`,Value:L.ref(f0)}});if(V)j.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:L0("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},j.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:_0("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.getAtt("SchedulerRule","Arn")}};if(J.warm&&J.warm>0){let D0={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},f0=(J.warmFunctions??["http"]).filter((P0)=>P0!=="queue"||B);for(let P0 of f0){let o1=P0.charAt(0).toUpperCase()+P0.slice(1),Y5=Math.ceil(J.warm/5),W8=0;for(let i2=0;i2<Y5;i2++){let C9=Math.min(5,J.warm-W8);j[`Warmer${o1}Rule${i2}`]={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-warmer-${P0}-${i2}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:C9},(Yw,BX)=>({Id:`warm-${P0}-${i2}-${BX}`,Arn:L.getAtt(D0[P0],"Arn"),Input:JSON.stringify({warmer:!0})}))}},W8+=C9}j[`Warmer${o1}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:L.ref(D0[P0]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${Q}-${Y}-warmer-${P0}-*`)}}}}if(A)j.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${Q}-${Y}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},q.CacheTableName={Description:"DynamoDB cache table",Value:L.ref("CacheTable")};if(_){if(j.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},j.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${Q}-${Y}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:L.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:L.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...J.assetDomain?{Aliases:[J.assetDomain],ViewerCertificate:{AcmCertificateArn:J.assetCertificateArn??L.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},J.assetDomain){if(!J.assetCertificateArn){if(!J.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(z!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${z}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);j.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:J.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:J.assetDomain,HostedZoneId:J.hostedZoneId}]}}}if(J.hostedZoneId)j.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:J.assetDomain,Type:"A",AliasTarget:{DNSName:L.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};q.AssetDomain={Description:"Custom asset CDN host",Value:J.assetDomain}}j.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:L.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:L.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":L.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},q.AssetsBucketName={Description:"Assets bucket",Value:L.ref("AssetsBucket")},q.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:L.getAtt("AssetsDistribution","DomainName")}}if(J.firewall?.enabled){let H0=[],D0=0;if(J.firewall.rateLimit)H0.push({Name:"rate-limit",Priority:D0++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:J.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-rate`}});let f0={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let P0 of J.firewall.rules??[]){let o1=f0[P0];if(!o1)continue;H0.push({Name:`managed-${P0}`,Priority:D0++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:o1}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-${P0}`}})}j.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${Q}-${Y}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:H0,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-waf`}}},q.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:L.getAtt("WebAcl","Arn")}}if(r&&d){if(!J.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");j.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:J.vpc.id,GroupDescription:`${Q}-${Y} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(b)j.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${Q}-${Y}-efs`}]}},c.forEach((H0,D0)=>{j[`EfsMountTarget${D0}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:L.ref("EfsFileSystem"),SubnetId:H0,SecurityGroups:[L.getAtt("DataSecurityGroup","GroupId")]}}}),j.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:L.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},q.EfsFileSystemId={Description:"EFS file system id",Value:L.ref("EfsFileSystem")};if(J.cache?.driver==="elasticache")j.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${Q}-${Y} cache subnets`,SubnetIds:c}},j.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${Q}-${Y}-cache`,ReplicationGroupDescription:`${Q}-${Y} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:L.ref("CacheSubnetGroup"),SecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},q.CacheEndpoint={Description:"Redis primary endpoint",Value:L.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(J.database?.connection==="aurora-serverless")j.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${Q}-${Y} db subnets`,SubnetIds:c}},j.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${Q}/${Y}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},j.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${Q}-${Y}-db`,DatabaseName:"app",MasterUsername:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:J.database?.minCapacity??0.5,MaxCapacity:J.database?.maxCapacity??4},DBSubnetGroupName:L.ref("DbSubnetGroup"),VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")]}},j.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:L.ref("DbCluster")}},q.DbEndpoint={Description:"Aurora cluster endpoint",Value:L.getAtt("DbCluster","Endpoint.Address")};if(J.rdsProxy&&J.database?.connection==="aurora-serverless")j.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:L.ref("DbSecret")}]}}]}},j.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof J.rdsProxy==="object"&&J.rdsProxy.name?J.rdsProxy.name:`${Q}-${Y}-proxy`,EngineFamily:"MYSQL",RoleArn:L.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:L.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:c,VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},j.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:L.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[L.ref("DbCluster")]}},q.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:L.getAtt("DbProxy","Endpoint")};if(q.HttpFunctionName={Description:"HTTP function name",Value:L.ref("HttpFunction")},q.CliFunctionName={Description:"CLI function name",Value:L.ref("CliFunction")},B)q.QueueFunctionName={Description:"Queue function name",Value:L.ref("QueueFunction")};let T1={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${$.config.project.name} (${Q}-${Y})`,Parameters:O?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:j,Outputs:q},F2={};for(let H0 of Object.values(j))F2[H0.Type]=(F2[H0.Type]??0)+1;return{template:T1,functionNames:U,queueNames:F,resourceSummary:F2}}function KU($){let J=`php${$.replace(".","")}`;return BU.map((Y)=>`${J}-php-${Y}`)}function zZ($,J){let Y=`php${$.replace(".","")}`,Z=KU($).join(" \\\n "),Q=`/opt/remi/${Y}/root`,G=`/etc/opt/remi/${Y}`;return`${J?`FROM almalinux:9 AS ${J}`:"FROM almalinux:9"}
|
|
3642
|
+
${K}`)}let U=z.outputs[0],H=Buffer.from(await U.arrayBuffer()),F="index",B=d$([{name:`${F}.mjs`,data:H}]);return{zip:B,bundle:H,sha256:r6(B),handlerFile:F,handlers:{http:Y.handlers?.http??`${F}.http`,queue:Y.handlers?.queue??`${F}.queue`,cli:Y.handlers?.cli??`${F}.cli`},bundleBytes:H.length}}finally{OE(G,{recursive:!0,force:!0})}}function qE($){if(!$)return"22";let J=String($).match(/(\d+)/);return J?J[1]:"22"}function n6($){let J=$.kind??"node";if(J==="php")return{lambdaRuntime:"provided.al2023",kind:"php",version:$.phpVersion??"8.3",usesLayer:!0,layerKind:"php",layerEnvVar:"TSCLOUD_PHP_LAYER_ARN"};if(J==="bun")return{lambdaRuntime:"provided.al2023",kind:"bun",version:$.runtimeVersion??"latest",usesLayer:!0,layerKind:"bun",layerEnvVar:"TSCLOUD_BUN_LAYER_ARN"};let Y=qE($.runtimeVersion);if($.runtime!=="provided.al2023"&&XU.includes(Y))return{lambdaRuntime:$.runtime&&$.runtime.startsWith("nodejs")?$.runtime:`nodejs${Y}.x`,kind:"node",version:Y,usesLayer:!1};return{lambdaRuntime:"provided.al2023",kind:"node",version:Y,usesLayer:!0,layerKind:"node",layerEnvVar:"TSCLOUD_NODE_LAYER_ARN"}}function m8($,J,Y){if($.queues===!1)return[];if($.queues===void 0||$.queues===!0)return[{name:`${J}-${Y}-default`}];return $.queues.map((Z)=>{if(typeof Z==="string")return{name:`${J}-${Y}-${Z}`};let[Q,G]=Object.entries(Z)[0];return{name:`${J}-${Y}-${Q}`,concurrency:G}})}function GZ($,J,Y){return m8($,J,Y).map((Z)=>Z.name)}function WZ($){let{app:J,environment:Y,handlers:Z}=$,Q=$.config.project.slug,G=n6(J).lambdaRuntime,W=J.architecture??"x86_64",z=$.config.project.region,U={http:`${Q}-${Y}-http`,queue:`${Q}-${Y}-queue`,cli:`${Q}-${Y}-cli`};if(J.gatewayVersion===1)throw Error("serverless app: `gatewayVersion: 1` (REST API) is not supported — ts-cloud uses API Gateway HTTP API (v2). Remove `gatewayVersion` or set it to 2.");let H=m8(J,Q,Y),F=H.map((H0)=>H0.name),B=F.length>0,K=J.logRetention??14,O=J.packaging==="image",V=(J.scheduler??"on")!=="off",A=(J.cache?.driver??"dynamodb")==="dynamodb",_=Boolean(J.assets),M=d6(Q,Y),E=J.tmpStorage??512,j={},q={},T=[{PolicyName:"tscloud-serverless-app",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],Resource:L.sub("arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/*")},{Effect:"Allow",Action:["lambda:InvokeFunction"],Resource:L.sub(`arn:aws:lambda:\${AWS::Region}:\${AWS::AccountId}:function:${Q}-${Y}-*`)},{Effect:"Allow",Action:["secretsmanager:GetSecretValue","ssm:GetParameter","ssm:GetParameters","ssm:GetParametersByPath"],Resource:[L.sub(`arn:aws:secretsmanager:\${AWS::Region}:\${AWS::AccountId}:secret:${Q}/${Y}/*`),L.sub(`arn:aws:ssm:\${AWS::Region}:\${AWS::AccountId}:parameter/${Q}/${Y}/*`)]},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[L.sub(`arn:aws:s3:::${M}`),L.sub(`arn:aws:s3:::${M}/*`),...J.storage?.bucket?[L.sub(`arn:aws:s3:::${J.storage.bucket}`),L.sub(`arn:aws:s3:::${J.storage.bucket}/*`)]:[]]}]}}];if(B)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["sqs:SendMessage","sqs:ReceiveMessage","sqs:DeleteMessage","sqs:GetQueueAttributes","sqs:GetQueueUrl"],Resource:L.sub(`arn:aws:sqs:\${AWS::Region}:\${AWS::AccountId}:${Q}-${Y}-*`)});if(A)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan","dynamodb:BatchGetItem","dynamodb:BatchWriteItem"],Resource:L.sub(`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${Q}-${Y}-cache*`)});let D=["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"];if(J.vpc?.subnets?.length)D.push("arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole");j.AppRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${Q}-${Y}-app-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:D,Policies:T}};let S=(H0)=>({TSCLOUD_LAMBDA_MODE:H0,TSCLOUD_ENV:Y,...J.octane?{TSCLOUD_OCTANE:"1"}:{},...J.scheduler==="sub-minute"?{TSCLOUD_SCHEDULER:"sub-minute"}:{},...A?{TSCLOUD_CACHE_TABLE:`${Q}-${Y}-cache`}:{},...B?{TSCLOUD_QUEUE:F[0]}:{},...J.env??{}}),P=Boolean(J.efs),C=typeof J.efs==="object"?J.efs:{},I=C.mountPath??"/mnt/local",b=P&&!C.accessPointArn,y=C.accessPointArn??(b?L.getAtt("EfsAccessPoint","Arn"):void 0),c=J.vpc?.subnets??[],r=c.length>0,d=J.cache?.driver==="elasticache"||J.database?.connection==="aurora-serverless"||Boolean(J.rdsProxy)||P;if(d&&!r)throw Error("serverless app: elasticache / aurora-serverless / rdsProxy / efs require app.vpc.subnets (private subnets) to be set.");let u=r?{VpcConfig:{SubnetIds:c,SecurityGroupIds:[...J.vpc?.securityGroups??[],...d?[L.getAtt("DataSecurityGroup","GroupId")]:[]]}}:{},s=b?c.map((H0,D0)=>`EfsMountTarget${D0}`):[],J0=P?{FileSystemConfigs:[{Arn:y,LocalMountPath:I}]}:{};if(P)T[0].PolicyDocument.Statement.push({Effect:"Allow",Action:["elasticfilesystem:ClientMount","elasticfilesystem:ClientWrite","elasticfilesystem:ClientRootAccess","elasticfilesystem:DescribeMountTargets"],Resource:"*"});function t(H0,D0,f0,P0,o1,Y5,W8,a2=E){j[`${H0}LogGroup`]={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/aws/lambda/${D0}`,RetentionInDays:K}};let C9=O?{PackageType:"Image",Code:{ImageUri:L.ref("ImageUri")},...J.kind==="php"?{}:{ImageConfig:{Command:[f0]}}}:{Runtime:G,Handler:f0,Code:{S3Bucket:L.ref("ArtifactBucket"),S3Key:L.ref("ArtifactKey")},...$.runtimeLayers?.length?{Layers:$.runtimeLayers}:{}};j[H0]={Type:"AWS::Lambda::Function",DependsOn:[`${H0}LogGroup`,...s],Properties:{FunctionName:D0,Architectures:[W],MemorySize:o1,Timeout:Y5,Role:L.getAtt("AppRole","Arn"),Environment:{Variables:S(P0)},EphemeralStorage:{Size:a2},...C9,...W8!==void 0?{ReservedConcurrentExecutions:W8}:{},...u,...J0}}}if(t("HttpFunction",U.http,Z.http,"http",J.memory??1024,J.timeout??28,J.concurrency,E),t("CliFunction",U.cli,Z.cli,"cli",J.cliMemory??1024,J.cliTimeout??900,void 0,J.cliTmpStorage??E),B)t("QueueFunction",U.queue,Z.queue,"queue",J.queueMemory??1024,J.queueTimeout??120,void 0,J.queueTmpStorage??E);let a=(J.provisionedConcurrency??0)>0?J.provisionedConcurrency:0,e=["HttpFunction","CliFunction",...B?["QueueFunction"]:[]];if(a)for(let H0 of e)j[`${H0}Version`]={Type:"AWS::Lambda::Version",DeletionPolicy:"Retain",Properties:{FunctionName:L.ref(H0)}},j[`${H0}Alias`]={Type:"AWS::Lambda::Alias",Properties:{FunctionName:L.ref(H0),Name:"live",FunctionVersion:L.getAtt(`${H0}Version`,"Version"),ProvisionedConcurrencyConfig:{ProvisionedConcurrentExecutions:a}}};let L0=(H0)=>a?L.ref(`${H0}Alias`):L.getAtt(H0,"Arn"),_0=(H0)=>a?L.ref(`${H0}Alias`):L.ref(H0);j.HttpApi={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:`${Q}-${Y}`,ProtocolType:"HTTP"}},j.HttpIntegration={Type:"AWS::ApiGatewayV2::Integration",Properties:{ApiId:L.ref("HttpApi"),IntegrationType:"AWS_PROXY",IntegrationUri:L0("HttpFunction"),PayloadFormatVersion:"2.0"}},j.HttpRoute={Type:"AWS::ApiGatewayV2::Route",Properties:{ApiId:L.ref("HttpApi"),RouteKey:"$default",Target:L.join("/",["integrations",L.ref("HttpIntegration")])}},j.HttpStage={Type:"AWS::ApiGatewayV2::Stage",Properties:{ApiId:L.ref("HttpApi"),StageName:"$default",AutoDeploy:!0}},j.HttpPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:_0("HttpFunction"),Action:"lambda:InvokeFunction",Principal:"apigateway.amazonaws.com",SourceArn:L.sub("arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${HttpApi}/*/*")}},q.HttpApiEndpoint={Description:"HTTP API endpoint",Value:L.getAtt("HttpApi","ApiEndpoint")},q.HttpApiId={Description:"HTTP API id",Value:L.ref("HttpApi")};let O0=(Array.isArray(J.domain)?J.domain:J.domain?[J.domain]:[]).filter(Boolean);if(O0.length){if(!J.certificateArn&&!J.hostedZoneId)throw Error("serverless app: a custom `domain` needs either `certificateArn` (pre-issued, regional) or `hostedZoneId` (to auto-issue + validate an ACM cert).");let H0=J.certificateArn;if(!H0)j.HttpCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:O0[0],...O0.length>1?{SubjectAlternativeNames:O0.slice(1)}:{},ValidationMethod:"DNS",DomainValidationOptions:O0.map((D0)=>({DomainName:D0,HostedZoneId:J.hostedZoneId}))}},H0=L.ref("HttpCertificate");O0.forEach((D0,f0)=>{let P0=`HttpDomain${f0}`;if(j[P0]={Type:"AWS::ApiGatewayV2::DomainName",Properties:{DomainName:D0,DomainNameConfigurations:[{CertificateArn:H0,EndpointType:"REGIONAL"}]}},j[`HttpApiMapping${f0}`]={Type:"AWS::ApiGatewayV2::ApiMapping",DependsOn:["HttpStage"],Properties:{ApiId:L.ref("HttpApi"),DomainName:L.ref(P0),Stage:"$default"}},J.hostedZoneId)j[`HttpDomainRecord${f0}`]={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:D0,Type:"A",AliasTarget:{DNSName:L.getAtt(P0,"RegionalDomainName"),HostedZoneId:L.getAtt(P0,"RegionalHostedZoneId")}}};q[`CustomDomain${f0}`]={Description:`Custom domain ${D0}`,Value:D0},q[`CustomDomainTarget${f0}`]={Description:`Point ${D0} (CNAME/alias) at this APIGW regional domain`,Value:L.getAtt(P0,"RegionalDomainName")}})}if(B)j.AppQueueDlq={Type:"AWS::SQS::Queue",Properties:{QueueName:`${Q}-${Y}-dlq`,MessageRetentionPeriod:1209600}},H.forEach((H0,D0)=>{let f0=`AppQueue${D0}`,P0=J.queueTimeout??120;j[f0]={Type:"AWS::SQS::Queue",Properties:{QueueName:H0.name,VisibilityTimeout:Math.min(43200,P0*6),RedrivePolicy:{deadLetterTargetArn:L.getAtt("AppQueueDlq","Arn"),maxReceiveCount:J.queueTries??3}}};let o1=H0.concurrency??J.queueConcurrency;j[`${f0}Mapping`]={Type:"AWS::Lambda::EventSourceMapping",Properties:{EventSourceArn:L.getAtt(f0,"Arn"),FunctionName:_0("QueueFunction"),BatchSize:1,FunctionResponseTypes:["ReportBatchItemFailures"],...o1?{ScalingConfig:{MaximumConcurrency:Math.max(2,o1)}}:{}}},q[`QueueUrl${D0}`]={Description:`Queue URL: ${H0.name}`,Value:L.ref(f0)}});if(V)j.SchedulerRule={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-scheduler`,ScheduleExpression:"rate(1 minute)",State:"ENABLED",Targets:[{Id:"cli",Arn:L0("CliFunction"),Input:JSON.stringify({command:"schedule:run"})}]}},j.SchedulerPermission={Type:"AWS::Lambda::Permission",Properties:{FunctionName:_0("CliFunction"),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.getAtt("SchedulerRule","Arn")}};if(J.warm&&J.warm>0){let D0={http:"HttpFunction",queue:"QueueFunction",cli:"CliFunction"},f0=(J.warmFunctions??["http"]).filter((P0)=>P0!=="queue"||B);for(let P0 of f0){let o1=P0.charAt(0).toUpperCase()+P0.slice(1),Y5=Math.ceil(J.warm/5),W8=0;for(let a2=0;a2<Y5;a2++){let C9=Math.min(5,J.warm-W8);j[`Warmer${o1}Rule${a2}`]={Type:"AWS::Events::Rule",Properties:{Name:`${Q}-${Y}-warmer-${P0}-${a2}`,ScheduleExpression:"rate(5 minutes)",State:"ENABLED",Targets:Array.from({length:C9},(Yw,BX)=>({Id:`warm-${P0}-${a2}-${BX}`,Arn:L.getAtt(D0[P0],"Arn"),Input:JSON.stringify({warmer:!0})}))}},W8+=C9}j[`Warmer${o1}Permission`]={Type:"AWS::Lambda::Permission",Properties:{FunctionName:L.ref(D0[P0]),Action:"lambda:InvokeFunction",Principal:"events.amazonaws.com",SourceArn:L.sub(`arn:aws:events:\${AWS::Region}:\${AWS::AccountId}:rule/${Q}-${Y}-warmer-${P0}-*`)}}}}if(A)j.CacheTable={Type:"AWS::DynamoDB::Table",Properties:{TableName:`${Q}-${Y}-cache`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"key",AttributeType:"S"}],KeySchema:[{AttributeName:"key",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"expires_at",Enabled:!0}}},q.CacheTableName={Description:"DynamoDB cache table",Value:L.ref("CacheTable")};if(_){if(j.AssetsBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:M,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}}},j.AssetsOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`${Q}-${Y}-assets-oac`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},j.AssetsDistribution={Type:"AWS::CloudFront::Distribution",Properties:{DistributionConfig:{Enabled:!0,DefaultCacheBehavior:{TargetOriginId:"assets",ViewerProtocolPolicy:"redirect-to-https",Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"},Origins:[{Id:"assets",DomainName:L.getAtt("AssetsBucket","RegionalDomainName"),OriginAccessControlId:L.ref("AssetsOAC"),S3OriginConfig:{OriginAccessIdentity:""}}],...J.assetDomain?{Aliases:[J.assetDomain],ViewerCertificate:{AcmCertificateArn:J.assetCertificateArn??L.ref("AssetsCertificate"),SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"}}:{}}}},J.assetDomain){if(!J.assetCertificateArn){if(!J.hostedZoneId)throw Error("serverless app: `assetDomain` requires either `assetCertificateArn` (a us-east-1 ACM cert) or `hostedZoneId` (to auto-issue + validate one). CloudFront only accepts certs from us-east-1.");if(z!=="us-east-1")throw Error(`serverless app: auto-issuing an asset-domain cert needs a us-east-1 app (CloudFront certs must be us-east-1); this app is in ${z}. Supply a pre-issued us-east-1 \`assetCertificateArn\` instead.`);j.AssetsCertificate={Type:"AWS::CertificateManager::Certificate",Properties:{DomainName:J.assetDomain,ValidationMethod:"DNS",DomainValidationOptions:[{DomainName:J.assetDomain,HostedZoneId:J.hostedZoneId}]}}}if(J.hostedZoneId)j.AssetsDomainRecord={Type:"AWS::Route53::RecordSet",Properties:{HostedZoneId:J.hostedZoneId,Name:J.assetDomain,Type:"A",AliasTarget:{DNSName:L.getAtt("AssetsDistribution","DomainName"),HostedZoneId:"Z2FDTNDATAQYW2"}}};q.AssetDomain={Description:"Custom asset CDN host",Value:J.assetDomain}}j.AssetsBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:L.ref("AssetsBucket"),PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:L.sub(`arn:aws:s3:::${M}/*`),Condition:{StringEquals:{"AWS:SourceArn":L.sub("arn:aws:cloudfront::${AWS::AccountId}:distribution/${AssetsDistribution}")}}}]}}},q.AssetsBucketName={Description:"Assets bucket",Value:L.ref("AssetsBucket")},q.AssetsCdnDomain={Description:"Assets CloudFront domain",Value:L.getAtt("AssetsDistribution","DomainName")}}if(J.firewall?.enabled){let H0=[],D0=0;if(J.firewall.rateLimit)H0.push({Name:"rate-limit",Priority:D0++,Action:{Block:{}},Statement:{RateBasedStatement:{Limit:J.firewall.rateLimit,AggregateKeyType:"IP"}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-rate`}});let f0={sqlInjection:"AWSManagedRulesSQLiRuleSet",xss:"AWSManagedRulesCommonRuleSet",common:"AWSManagedRulesCommonRuleSet",botControl:"AWSManagedRulesBotControlRuleSet",ipReputation:"AWSManagedRulesAmazonIpReputationList"};for(let P0 of J.firewall.rules??[]){let o1=f0[P0];if(!o1)continue;H0.push({Name:`managed-${P0}`,Priority:D0++,OverrideAction:{None:{}},Statement:{ManagedRuleGroupStatement:{VendorName:"AWS",Name:o1}},VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-${P0}`}})}j.WebAcl={Type:"AWS::WAFv2::WebACL",Properties:{Name:`${Q}-${Y}-waf`,Scope:"REGIONAL",DefaultAction:{Allow:{}},Rules:H0,VisibilityConfig:{SampledRequestsEnabled:!0,CloudWatchMetricsEnabled:!0,MetricName:`${Q}-${Y}-waf`}}},q.WafAclArn={Description:"WAF web ACL ARN. Attach to a CloudFront distribution fronting the API to enforce (HTTP API v2 stages do not support direct WAF association).",Value:L.getAtt("WebAcl","Arn")}}if(r&&d){if(!J.vpc?.id)throw Error("serverless app: data services (elasticache / aurora-serverless / rdsProxy / efs) need app.vpc.id (the VPC id) so the managed security group is created in the right VPC.");j.DataSecurityGroup={Type:"AWS::EC2::SecurityGroup",Properties:{VpcId:J.vpc.id,GroupDescription:`${Q}-${Y} serverless data access`,SecurityGroupIngress:[{IpProtocol:"-1",CidrIp:"10.0.0.0/8"}]}}}if(b)j.EfsFileSystem={Type:"AWS::EFS::FileSystem",Properties:{Encrypted:!0,FileSystemTags:[{Key:"Name",Value:`${Q}-${Y}-efs`}]}},c.forEach((H0,D0)=>{j[`EfsMountTarget${D0}`]={Type:"AWS::EFS::MountTarget",Properties:{FileSystemId:L.ref("EfsFileSystem"),SubnetId:H0,SecurityGroups:[L.getAtt("DataSecurityGroup","GroupId")]}}}),j.EfsAccessPoint={Type:"AWS::EFS::AccessPoint",Properties:{FileSystemId:L.ref("EfsFileSystem"),PosixUser:{Uid:1001,Gid:1001},RootDirectory:{Path:"/lambda",CreationInfo:{OwnerUid:1001,OwnerGid:1001,Permissions:"0755"}}}},q.EfsFileSystemId={Description:"EFS file system id",Value:L.ref("EfsFileSystem")};if(J.cache?.driver==="elasticache")j.CacheSubnetGroup={Type:"AWS::ElastiCache::SubnetGroup",Properties:{Description:`${Q}-${Y} cache subnets`,SubnetIds:c}},j.CacheCluster={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:`${Q}-${Y}-cache`,ReplicationGroupDescription:`${Q}-${Y} redis`,Engine:"redis",CacheNodeType:"cache.t4g.micro",NumCacheClusters:1,AutomaticFailoverEnabled:!1,CacheSubnetGroupName:L.ref("CacheSubnetGroup"),SecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],TransitEncryptionEnabled:!1}},q.CacheEndpoint={Description:"Redis primary endpoint",Value:L.getAtt("CacheCluster","PrimaryEndPoint.Address")};if(J.database?.connection==="aurora-serverless")j.DbSubnetGroup={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupDescription:`${Q}-${Y} db subnets`,SubnetIds:c}},j.DbSecret={Type:"AWS::SecretsManager::Secret",Properties:{Name:`${Q}/${Y}/db`,GenerateSecretString:{SecretStringTemplate:JSON.stringify({username:"app"}),GenerateStringKey:"password",PasswordLength:32,ExcludePunctuation:!0}}},j.DbCluster={Type:"AWS::RDS::DBCluster",Properties:{Engine:"aurora-mysql",EngineMode:"provisioned",DBClusterIdentifier:`${Q}-${Y}-db`,DatabaseName:"app",MasterUsername:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:username}}"),MasterUserPassword:L.sub("{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"),ServerlessV2ScalingConfiguration:{MinCapacity:J.database?.minCapacity??0.5,MaxCapacity:J.database?.maxCapacity??4},DBSubnetGroupName:L.ref("DbSubnetGroup"),VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")]}},j.DbInstance={Type:"AWS::RDS::DBInstance",Properties:{Engine:"aurora-mysql",DBInstanceClass:"db.serverless",DBClusterIdentifier:L.ref("DbCluster")}},q.DbEndpoint={Description:"Aurora cluster endpoint",Value:L.getAtt("DbCluster","Endpoint.Address")};if(J.rdsProxy&&J.database?.connection==="aurora-serverless")j.DbProxyRole={Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"rds.amazonaws.com"},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:"read-db-secret",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["secretsmanager:GetSecretValue"],Resource:L.ref("DbSecret")}]}}]}},j.DbProxy={Type:"AWS::RDS::DBProxy",Properties:{DBProxyName:typeof J.rdsProxy==="object"&&J.rdsProxy.name?J.rdsProxy.name:`${Q}-${Y}-proxy`,EngineFamily:"MYSQL",RoleArn:L.getAtt("DbProxyRole","Arn"),Auth:[{AuthScheme:"SECRETS",SecretArn:L.ref("DbSecret"),IAMAuth:"DISABLED"}],VpcSubnetIds:c,VpcSecurityGroupIds:[L.getAtt("DataSecurityGroup","GroupId")],RequireTLS:!1}},j.DbProxyTargetGroup={Type:"AWS::RDS::DBProxyTargetGroup",DependsOn:["DbInstance"],Properties:{DBProxyName:L.ref("DbProxy"),TargetGroupName:"default",DBClusterIdentifiers:[L.ref("DbCluster")]}},q.DbProxyEndpoint={Description:"RDS Proxy endpoint",Value:L.getAtt("DbProxy","Endpoint")};if(q.HttpFunctionName={Description:"HTTP function name",Value:L.ref("HttpFunction")},q.CliFunctionName={Description:"CLI function name",Value:L.ref("CliFunction")},B)q.QueueFunctionName={Description:"Queue function name",Value:L.ref("QueueFunction")};let T1={AWSTemplateFormatVersion:"2010-09-09",Description:`Serverless application for ${$.config.project.name} (${Q}-${Y})`,Parameters:O?{ImageUri:{Type:"String",Description:"ECR image URI of the deployment artifact"}}:{ArtifactBucket:{Type:"String",Description:"S3 bucket holding the deployment artifact"},ArtifactKey:{Type:"String",Description:"S3 key of the deployment artifact (zip)"}},Resources:j,Outputs:q},F2={};for(let H0 of Object.values(j))F2[H0.Type]=(F2[H0.Type]??0)+1;return{template:T1,functionNames:U,queueNames:F,resourceSummary:F2}}function KU($){let J=`php${$.replace(".","")}`;return BU.map((Y)=>`${J}-php-${Y}`)}function zZ($,J){let Y=`php${$.replace(".","")}`,Z=KU($).join(" \\\n "),Q=`/opt/remi/${Y}/root`,G=`/etc/opt/remi/${Y}`;return`${J?`FROM almalinux:9 AS ${J}`:"FROM almalinux:9"}
|
|
3643
3643
|
|
|
3644
3644
|
# Build PHP on AlmaLinux 9 (where Remi's version-isolated SCL packages install
|
|
3645
3645
|
# cleanly — Remi's release RPM rejects Amazon Linux 2023). AlmaLinux 9 shares
|
|
@@ -3717,7 +3717,7 @@ decorate_workers_output = no
|
|
|
3717
3717
|
php_admin_value[error_log] = /dev/stderr
|
|
3718
3718
|
php_admin_flag[log_errors] = on
|
|
3719
3719
|
clear_env = no
|
|
3720
|
-
`}function vE(){return NU(bE(yE(import.meta.url)),"runtime-assets")}function v8(){let $=vE(),J=(Y)=>hE(NU($,Y),"utf-8");return[{path:"bootstrap",contents:J("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:J("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:J("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:J("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:J("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:RU(),mode:420}]}function FZ($={}){let J=$.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:J,CACHE_DRIVER:J,SESSION_DRIVER:J,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}function*CU($){for(let J of dE($)){let Y=y$($,J);if(PU(Y).isDirectory())yield*CU(Y);else yield Y}}function nE($={}){let J=$.architecture??"x86_64",Y=$.platform??(J==="arm64"?"linux/arm64":"linux/amd64"),Z=$.onStep??(()=>{}),Q=uE(y$(pE(),"tscloud-php-layer-")),G="tscloud-php-layer:build";try{lE(y$(Q,"Dockerfile"),OU($)),Z("Building PHP runtime image (docker)"),C6("docker",["build","--platform",Y,"-t","tscloud-php-layer:build",Q],{stdio:"inherit"}),Z("Extracting /opt/php from image");let W=C6("docker",["create","--platform",Y,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),z=y$(Q,"opt");gE(z,{recursive:!0});try{C6("docker",["cp",`${W}:/opt/php`,y$(z,"php")],{stdio:"inherit"})}finally{C6("docker",["rm",W],{stdio:"ignore"})}if(!fE(y$(z,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let U=[];for(let K of CU(z)){let O=rE(z,K).replace(/\\/g,"/"),V=PU(K).mode&73?493:420;U.push({name:O,data:cE(K),mode:V})}Z("Injecting runtime assets");let H=new Set(v8().map((K)=>K.path)),F=U.filter((K)=>!H.has(K.name));for(let K of v8())F.push({name:K.path,data:K.contents,mode:K.mode});return Z("Packaging layer ZIP"),{zip:d$(F),architecture:J,fileCount:F.length}}finally{mE(Q,{recursive:!0,force:!0})}}function eE($,J){return J.some((Y)=>$===Y||$.startsWith(`${Y}/`))}function*hU($,J,Y){for(let Z of tE($)){let Q=oE($,Z),G=IU(J,Q).replace(/\\/g,"/");if(eE(G,Y))continue;if(xU(Q).isDirectory())yield*hU(Q,J,Y);else yield Q}}function t6($){if($.skipBuild)return;let J=XZ($.projectRoot??process.cwd()),Y=$.app.build??SU;for(let Z of Y)$.onStep?.(`build: ${Z}`),iE(Z,{stdio:"inherit",cwd:J})}function s6($,J=[]){let Y=XZ($),Z=[...kU,...J],Q=[];for(let G of hU(Y,Y,Z)){let W=IU(Y,G).replace(/\\/g,"/"),z=(xU(G).mode&73)!==0;Q.push({name:W,data:sE(G),mode:z?493:420})}return Q}function BZ($){let J=XZ($.projectRoot??process.cwd());t6($),$.onStep?.("packaging application tree");let Y=s6(J,$.exclude);if(!Y.length)throw Error(`No files to package under ${J}`);let Z=d$(Y),Q=$.app.handlers?.http??"public/index.php";return{zip:Z,sha256:aE("sha256").update(Z).digest("hex"),handlers:{http:Q,queue:$.app.handlers?.queue??Q,cli:$.app.handlers?.cli??Q},fileCount:Y.length}}class KZ{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization($){let J=`asset-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.optimizations.set(J,Y),Y}createImageOptimization($){let J=`image-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.imageConfigs.set(J,Y),Y}createSSGConfig($){let J=`ssg-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.ssgConfigs.set(J,Y),Y}createPrerenderConfig($){let J=`prerender-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.prerenderConfigs.set(J,Y),Y}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}class OZ{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy($,J){let Y=`lifecycle-${Date.now()}-${this.counter++}`,Z={id:Y,transitions:$,expiration:J};return this.policies.set(Y,Z),Z}enableVersioning($=!1){let J=`versioning-${Date.now()}-${this.counter++}`,Y={id:J,enabled:!0,mfaDelete:$};return this.versioningConfigs.set(J,Y),Y}createReplicationRule($,J,Y){let Z=`replication-${Date.now()}-${this.counter++}`,Q={id:Z,sourceRegion:$,destRegion:J,destBucket:Y};return this.replicationRules.set(Z,Q),Q}createIntelligentTiering($,J){let Y=`tiering-${Date.now()}-${this.counter++}`,Z={id:Y,archiveDays:$,deepArchiveDays:J};return this.tieringConfigs.set(Y,Z),Z}enableObjectLock($){let J=`object-lock-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,mode:$.mode||"COMPLIANCE",retentionDays:$.retentionDays,retentionYears:$.retentionYears,legalHoldEnabled:$.legalHoldEnabled||!1};return this.objectLocks.set(J,Y),Y}enableTransferAcceleration($){let J=`transfer-accel-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$,enabled:!0,endpoint:`${$}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(J,Y),Y}createAccessPoint($){let J=`access-point-${Date.now()}-${this.counter++}`,Y={id:J,name:$.name,bucketName:$.bucketName,vpcId:$.vpcId,publicAccessBlock:$.publicAccessBlock!==!1,policy:$.policy};return this.accessPoints.set(J,Y),Y}createGlacierArchive($){let J=`glacier-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,archiveType:$.archiveType,transitionDays:$.transitionDays,restoreConfig:$.restoreTier?{tier:$.restoreTier,days:$.restoreDays||7}:void 0};return this.glacierConfigs.set(J,Y),Y}createInventory($){let J=`inventory-${Date.now()}-${this.counter++}`,Y={id:J,sourceBucket:$.sourceBucket,destinationBucket:$.destinationBucket,schedule:$.schedule||"Daily",format:$.format||"CSV",includedFields:$.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:$.prefix};return this.inventories.set(J,Y),Y}createBatchOperation($){let J=`batch-op-${Date.now()}-${this.counter++}`,Y={id:J,operation:$.operation,manifestBucket:$.manifestBucket,manifestKey:$.manifestKey,priority:$.priority||10,status:"pending"};return this.batchOps.set(J,Y),Y}executeBatchOperation($){let J=this.batchOps.get($);if(!J)throw Error(`Batch operation not found: ${$}`);return J.status="in_progress",J.totalObjects=1000,J.processedObjects=0,J}getBatchOperationStatus($){return this.batchOps.get($)}createLambdaNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"Lambda",arn:$.lambdaArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSQSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SQS",arn:$.queueArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSNSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SNS",arn:$.topicArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}generateObjectLockCF($){let J={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:$.mode}}}};if($.retentionDays)J.ObjectLockConfiguration.Rule.DefaultRetention.Days=$.retentionDays;if($.retentionYears)J.ObjectLockConfiguration.Rule.DefaultRetention.Years=$.retentionYears;return J}generateTransferAccelerationCF($){return{AccelerateConfiguration:{AccelerationStatus:$.enabled?"Enabled":"Suspended"}}}generateAccessPointCF($){return{Type:"AWS::S3::AccessPoint",Properties:{Name:$.name,Bucket:$.bucketName,...$.vpcId&&{VpcConfiguration:{VpcId:$.vpcId}},PublicAccessBlockConfiguration:$.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...$.policy&&{Policy:$.policy}}}}generateInventoryCF($){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:$.id,Destination:{BucketArn:`arn:aws:s3:::${$.destinationBucket}`,Format:$.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:$.includedFields,ScheduleFrequency:$.schedule,...$.prefix&&{Prefix:$.prefix}}]}}}generateEventNotificationCF($){let J=$.destination.type==="Lambda"?"LambdaConfigurations":$.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",Y=$.destination.type==="Lambda"?"Function":$.destination.type==="SQS"?"Queue":"Topic",Z={Event:$.events[0],[Y]:$.destination.arn};if($.filter)Z.Filter={S3Key:{Rules:[...$.filter.prefix?[{Name:"prefix",Value:$.filter.prefix}]:[],...$.filter.suffix?[{Name:"suffix",Value:$.filter.suffix}]:[]]}};return{NotificationConfiguration:{[J]:[Z]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}class AZ{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck($,J=30,Y=10){let Z=`health-${Date.now()}-${this.counter++}`,Q={id:Z,url:$,interval:J,timeout:Y,status:"healthy"};return this.checks.set(Z,Q),Q}createSyntheticMonitor($,J,Y,Z){let Q=`synthetic-${Date.now()}-${this.counter++}`,G={id:Q,name:$,script:J,frequency:Y,locations:Z};return this.synthetics.set(Q,G),G}trackUptime($,J,Y){let Z=`uptime-${Date.now()}-${this.counter++}`,Q=J/(J+Y)*100,G={id:Z,resource:$,uptime:J,downtime:Y,availability:Q};return this.uptimeTrackers.set(Z,G),G}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}class VZ{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule($,J,Y,Z){let Q=`waf-${Date.now()}-${this.counter++}`,G={id:Q,name:$,priority:J,action:Y,conditions:Z};return this.wafRules.set(Q,G),G}enableShield($,J="standard"){let Y=`shield-${Date.now()}-${this.counter++}`,Z={id:Y,resourceArn:$,protectionType:J};return this.shieldProtections.set(Y,Z),Z}createSecurityGroup($,J,Y){let Z=`sg-${Date.now()}-${this.counter++}`,Q={id:Z,name:$,vpcId:J,rules:Y};return this.securityGroups.set(Z,Q),Q}createNACL($,J){let Y=`nacl-${Date.now()}-${this.counter++}`,Z={id:Y,vpcId:$,rules:J};return this.nacls.set(Y,Z),Z}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}class _Z{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy($,J){let Y=`tagging-${Date.now()}-${this.counter++}`,Z={id:Y,tags:$,resources:J};return this.strategies.set(Y,Z),Z}createCostAllocation($,J){let Y=`cost-${Date.now()}-${this.counter++}`,Z={id:Y,tagKey:$,allocations:J};return this.allocations.set(Y,Z),Z}createResourceGroup($,J,Y){let Z=`group-${Date.now()}-${this.counter++}`,Q={id:Z,name:$,query:{resourceTypeFilters:J,tagFilters:Y}};return this.groups.set(Z,Q),Q}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var GA,WA=($)=>$,Q$=($,J)=>{for(var Y in J)GA($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:zA.bind(J,Y)})},UA=($,J)=>()=>($&&(J=$($=0)),J),HA,$z,u$,G$,Az=100,Vz,f8,BA,KA,l,RA,l1,J2,m1,X1,y0,Z0,q0,Mz,IJ=`
|
|
3720
|
+
`}function vE(){return NU(bE(yE(import.meta.url)),"runtime-assets")}function v8(){let $=vE(),J=(Y)=>hE(NU($,Y),"utf-8");return[{path:"bootstrap",contents:J("bootstrap"),mode:493},{path:"tscloud/runtime.php",contents:J("runtime.php"),mode:420},{path:"tscloud/octane-runtime.php",contents:J("octane-runtime.php"),mode:420},{path:"tscloud/cli-runtime.php",contents:J("cli-runtime.php"),mode:420},{path:"tscloud/fastcgi-client.php",contents:J("fastcgi-client.php"),mode:420},{path:"tscloud/php-fpm.conf",contents:RU(),mode:420}]}function FZ($={}){let J=$.cacheDriver??"dynamodb";return{APP_ENV:"production",LOG_CHANNEL:"stderr",CACHE_STORE:J,CACHE_DRIVER:J,SESSION_DRIVER:J,QUEUE_CONNECTION:"sqs",FILESYSTEM_DISK:"s3",VIEW_COMPILED_PATH:"/tmp/storage/framework/views",APP_SERVICES_CACHE:"/tmp/bootstrap/cache/services.php",APP_PACKAGES_CACHE:"/tmp/bootstrap/cache/packages.php",APP_CONFIG_CACHE:"/tmp/bootstrap/cache/config.php",APP_ROUTES_CACHE:"/tmp/bootstrap/cache/routes.php",APP_EVENTS_CACHE:"/tmp/bootstrap/cache/events.php"}}function*CU($){for(let J of dE($)){let Y=y$($,J);if(PU(Y).isDirectory())yield*CU(Y);else yield Y}}function nE($={}){let J=$.architecture??"x86_64",Y=$.platform??(J==="arm64"?"linux/arm64":"linux/amd64"),Z=$.onStep??(()=>{}),Q=uE(y$(pE(),"tscloud-php-layer-")),G="tscloud-php-layer:build";try{lE(y$(Q,"Dockerfile"),OU($)),Z("Building PHP runtime image (docker)"),C6("docker",["build","--platform",Y,"-t","tscloud-php-layer:build",Q],{stdio:"inherit"}),Z("Extracting /opt/php from image");let W=C6("docker",["create","--platform",Y,"tscloud-php-layer:build"],{encoding:"utf-8"}).trim(),z=y$(Q,"opt");gE(z,{recursive:!0});try{C6("docker",["cp",`${W}:/opt/php`,y$(z,"php")],{stdio:"inherit"})}finally{C6("docker",["rm",W],{stdio:"ignore"})}if(!fE(y$(z,"php","bin","php")))throw Error("layer build produced no /opt/php/bin/php");let U=[];for(let K of CU(z)){let O=rE(z,K).replace(/\\/g,"/"),V=PU(K).mode&73?493:420;U.push({name:O,data:cE(K),mode:V})}Z("Injecting runtime assets");let H=new Set(v8().map((K)=>K.path)),F=U.filter((K)=>!H.has(K.name));for(let K of v8())F.push({name:K.path,data:K.contents,mode:K.mode});return Z("Packaging layer ZIP"),{zip:d$(F),architecture:J,fileCount:F.length}}finally{mE(Q,{recursive:!0,force:!0})}}function eE($,J){return J.some((Y)=>$===Y||$.startsWith(`${Y}/`))}function*hU($,J,Y){for(let Z of tE($)){let Q=oE($,Z),G=IU(J,Q).replace(/\\/g,"/");if(eE(G,Y))continue;if(xU(Q).isDirectory())yield*hU(Q,J,Y);else yield Q}}function t6($){if($.skipBuild)return;let J=XZ($.projectRoot??process.cwd()),Y=$.app.build??SU;for(let Z of Y)$.onStep?.(`build: ${Z}`),iE(Z,{stdio:"inherit",cwd:J})}function s6($,J=[]){let Y=XZ($),Z=[...kU,...J],Q=[];for(let G of hU(Y,Y,Z)){let W=IU(Y,G).replace(/\\/g,"/"),z=(xU(G).mode&73)!==0;Q.push({name:W,data:sE(G),mode:z?493:420})}return Q}function BZ($){let J=XZ($.projectRoot??process.cwd());t6($),$.onStep?.("packaging application tree");let Y=s6(J,$.exclude);if(!Y.length)throw Error(`No files to package under ${J}`);let Z=d$(Y),Q=$.app.handlers?.http??"public/index.php";return{zip:Z,sha256:aE("sha256").update(Z).digest("hex"),handlers:{http:Q,queue:$.app.handlers?.queue??Q,cli:$.app.handlers?.cli??Q},fileCount:Y.length}}class KZ{optimizations=new Map;imageConfigs=new Map;ssgConfigs=new Map;prerenderConfigs=new Map;counter=0;createAssetOptimization($){let J=`asset-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.optimizations.set(J,Y),Y}createImageOptimization($){let J=`image-opt-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.imageConfigs.set(J,Y),Y}createSSGConfig($){let J=`ssg-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.ssgConfigs.set(J,Y),Y}createPrerenderConfig($){let J=`prerender-${Date.now()}-${this.counter++}`,Y={id:J,...$};return this.prerenderConfigs.set(J,Y),Y}listOptimizations(){return Array.from(this.optimizations.values())}listImageConfigs(){return Array.from(this.imageConfigs.values())}clear(){this.optimizations.clear(),this.imageConfigs.clear(),this.ssgConfigs.clear(),this.prerenderConfigs.clear()}}class OZ{policies=new Map;versioningConfigs=new Map;replicationRules=new Map;tieringConfigs=new Map;objectLocks=new Map;transferAcceleration=new Map;accessPoints=new Map;glacierConfigs=new Map;inventories=new Map;batchOps=new Map;eventNotifications=new Map;counter=0;createLifecyclePolicy($,J){let Y=`lifecycle-${Date.now()}-${this.counter++}`,Z={id:Y,transitions:$,expiration:J};return this.policies.set(Y,Z),Z}enableVersioning($=!1){let J=`versioning-${Date.now()}-${this.counter++}`,Y={id:J,enabled:!0,mfaDelete:$};return this.versioningConfigs.set(J,Y),Y}createReplicationRule($,J,Y){let Z=`replication-${Date.now()}-${this.counter++}`,Q={id:Z,sourceRegion:$,destRegion:J,destBucket:Y};return this.replicationRules.set(Z,Q),Q}createIntelligentTiering($,J){let Y=`tiering-${Date.now()}-${this.counter++}`,Z={id:Y,archiveDays:$,deepArchiveDays:J};return this.tieringConfigs.set(Y,Z),Z}enableObjectLock($){let J=`object-lock-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,mode:$.mode||"COMPLIANCE",retentionDays:$.retentionDays,retentionYears:$.retentionYears,legalHoldEnabled:$.legalHoldEnabled||!1};return this.objectLocks.set(J,Y),Y}enableTransferAcceleration($){let J=`transfer-accel-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$,enabled:!0,endpoint:`${$}.s3-accelerate.amazonaws.com`};return this.transferAcceleration.set(J,Y),Y}createAccessPoint($){let J=`access-point-${Date.now()}-${this.counter++}`,Y={id:J,name:$.name,bucketName:$.bucketName,vpcId:$.vpcId,publicAccessBlock:$.publicAccessBlock!==!1,policy:$.policy};return this.accessPoints.set(J,Y),Y}createGlacierArchive($){let J=`glacier-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,archiveType:$.archiveType,transitionDays:$.transitionDays,restoreConfig:$.restoreTier?{tier:$.restoreTier,days:$.restoreDays||7}:void 0};return this.glacierConfigs.set(J,Y),Y}createInventory($){let J=`inventory-${Date.now()}-${this.counter++}`,Y={id:J,sourceBucket:$.sourceBucket,destinationBucket:$.destinationBucket,schedule:$.schedule||"Daily",format:$.format||"CSV",includedFields:$.includedFields||["Size","LastModifiedDate","StorageClass","ETag"],prefix:$.prefix};return this.inventories.set(J,Y),Y}createBatchOperation($){let J=`batch-op-${Date.now()}-${this.counter++}`,Y={id:J,operation:$.operation,manifestBucket:$.manifestBucket,manifestKey:$.manifestKey,priority:$.priority||10,status:"pending"};return this.batchOps.set(J,Y),Y}executeBatchOperation($){let J=this.batchOps.get($);if(!J)throw Error(`Batch operation not found: ${$}`);return J.status="in_progress",J.totalObjects=1000,J.processedObjects=0,J}getBatchOperationStatus($){return this.batchOps.get($)}createLambdaNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"Lambda",arn:$.lambdaArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSQSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SQS",arn:$.queueArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}createSNSNotification($){let J=`event-${Date.now()}-${this.counter++}`,Y={id:J,bucketName:$.bucketName,events:$.events,destination:{type:"SNS",arn:$.topicArn},filter:$.prefix||$.suffix?{prefix:$.prefix,suffix:$.suffix}:void 0};return this.eventNotifications.set(J,Y),Y}generateObjectLockCF($){let J={ObjectLockEnabled:"Enabled",ObjectLockConfiguration:{ObjectLockEnabled:"Enabled",Rule:{DefaultRetention:{Mode:$.mode}}}};if($.retentionDays)J.ObjectLockConfiguration.Rule.DefaultRetention.Days=$.retentionDays;if($.retentionYears)J.ObjectLockConfiguration.Rule.DefaultRetention.Years=$.retentionYears;return J}generateTransferAccelerationCF($){return{AccelerateConfiguration:{AccelerationStatus:$.enabled?"Enabled":"Suspended"}}}generateAccessPointCF($){return{Type:"AWS::S3::AccessPoint",Properties:{Name:$.name,Bucket:$.bucketName,...$.vpcId&&{VpcConfiguration:{VpcId:$.vpcId}},PublicAccessBlockConfiguration:$.publicAccessBlock?{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0}:void 0,...$.policy&&{Policy:$.policy}}}}generateInventoryCF($){return{Type:"AWS::S3::Bucket",Properties:{InventoryConfigurations:[{Id:$.id,Destination:{BucketArn:`arn:aws:s3:::${$.destinationBucket}`,Format:$.format},Enabled:!0,IncludedObjectVersions:"Current",OptionalFields:$.includedFields,ScheduleFrequency:$.schedule,...$.prefix&&{Prefix:$.prefix}}]}}}generateEventNotificationCF($){let J=$.destination.type==="Lambda"?"LambdaConfigurations":$.destination.type==="SQS"?"QueueConfigurations":"TopicConfigurations",Y=$.destination.type==="Lambda"?"Function":$.destination.type==="SQS"?"Queue":"Topic",Z={Event:$.events[0],[Y]:$.destination.arn};if($.filter)Z.Filter={S3Key:{Rules:[...$.filter.prefix?[{Name:"prefix",Value:$.filter.prefix}]:[],...$.filter.suffix?[{Name:"suffix",Value:$.filter.suffix}]:[]]}};return{NotificationConfiguration:{[J]:[Z]}}}clear(){this.policies.clear(),this.versioningConfigs.clear(),this.replicationRules.clear(),this.tieringConfigs.clear(),this.objectLocks.clear(),this.transferAcceleration.clear(),this.accessPoints.clear(),this.glacierConfigs.clear(),this.inventories.clear(),this.batchOps.clear(),this.eventNotifications.clear()}}class AZ{checks=new Map;synthetics=new Map;uptimeTrackers=new Map;counter=0;createHealthCheck($,J=30,Y=10){let Z=`health-${Date.now()}-${this.counter++}`,Q={id:Z,url:$,interval:J,timeout:Y,status:"healthy"};return this.checks.set(Z,Q),Q}createSyntheticMonitor($,J,Y,Z){let Q=`synthetic-${Date.now()}-${this.counter++}`,G={id:Q,name:$,script:J,frequency:Y,locations:Z};return this.synthetics.set(Q,G),G}trackUptime($,J,Y){let Z=`uptime-${Date.now()}-${this.counter++}`,Q=J/(J+Y)*100,G={id:Z,resource:$,uptime:J,downtime:Y,availability:Q};return this.uptimeTrackers.set(Z,G),G}clear(){this.checks.clear(),this.synthetics.clear(),this.uptimeTrackers.clear()}}class VZ{wafRules=new Map;shieldProtections=new Map;securityGroups=new Map;nacls=new Map;counter=0;createWAFRule($,J,Y,Z){let Q=`waf-${Date.now()}-${this.counter++}`,G={id:Q,name:$,priority:J,action:Y,conditions:Z};return this.wafRules.set(Q,G),G}enableShield($,J="standard"){let Y=`shield-${Date.now()}-${this.counter++}`,Z={id:Y,resourceArn:$,protectionType:J};return this.shieldProtections.set(Y,Z),Z}createSecurityGroup($,J,Y){let Z=`sg-${Date.now()}-${this.counter++}`,Q={id:Z,name:$,vpcId:J,rules:Y};return this.securityGroups.set(Z,Q),Q}createNACL($,J){let Y=`nacl-${Date.now()}-${this.counter++}`,Z={id:Y,vpcId:$,rules:J};return this.nacls.set(Y,Z),Z}clear(){this.wafRules.clear(),this.shieldProtections.clear(),this.securityGroups.clear(),this.nacls.clear()}}class _Z{strategies=new Map;allocations=new Map;groups=new Map;counter=0;createTaggingStrategy($,J){let Y=`tagging-${Date.now()}-${this.counter++}`,Z={id:Y,tags:$,resources:J};return this.strategies.set(Y,Z),Z}createCostAllocation($,J){let Y=`cost-${Date.now()}-${this.counter++}`,Z={id:Y,tagKey:$,allocations:J};return this.allocations.set(Y,Z),Z}createResourceGroup($,J,Y){let Z=`group-${Date.now()}-${this.counter++}`,Q={id:Z,name:$,query:{resourceTypeFilters:J,tagFilters:Y}};return this.groups.set(Z,Q),Q}clear(){this.strategies.clear(),this.allocations.clear(),this.groups.clear()}}var GA,WA=($)=>$,G$=($,J)=>{for(var Y in J)GA($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:zA.bind(J,Y)})},UA=($,J)=>()=>($&&(J=$($=0)),J),HA,$z,u$,W$,Az=100,Vz,f8,BA,KA,l,RA,l1,J2,m1,X1,y0,Z0,q0,Mz,IJ=`
|
|
3721
3721
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
3722
3722
|
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
3723
3723
|
|
|
@@ -4541,7 +4541,7 @@ catch (error) {
|
|
|
4541
4541
|
|
|
4542
4542
|
return { statusCode: 200, body: 'OK' };
|
|
4543
4543
|
};
|
|
4544
|
-
`,B1,p1,m2,g8,R1,c6,D1,Tz,u8,K1,O1,J1,v$,m0,d2,E2,L,h8,nA,F_=5242880,LJ=5242880,X_=5242880,V1,Q2,I8,g2,vz,uJ,fz,gz,F1,R_,a_,rJ,Yj,Wj,Pj,Cj,xj,Ij,kj,r1,rj,nj,ZU,ij,aj,AL,VL,_L,jL,LL,
|
|
4544
|
+
`,B1,p1,m2,g8,R1,c6,D1,Tz,u8,K1,O1,J1,v$,m0,d2,E2,L,h8,nA,F_=5242880,LJ=5242880,X_=5242880,V1,Q2,I8,g2,vz,uJ,fz,gz,F1,R_,a_,rJ,Yj,Wj,Pj,Cj,xj,Ij,kj,r1,rj,nj,ZU,ij,aj,AL,VL,_L,jL,LL,Y$,EL,ML,y8,qL,TL,wL,DL,RL,NL,Z$,SL,PL,CL,xL,IL,kL,hL,bL,yL,vL,fL,gL,uL,dL,cL,mL,lL,pL,rL,nL,iL,aL,tL,sL,oL,eL,QU,J$,pY,rY,GU,WU=`
|
|
4545
4545
|
const { S3Client, GetObjectCommand, PutObjectCommand, CopyObjectCommand } = require('@aws-sdk/client-s3');
|
|
4546
4546
|
const s3 = new S3Client({});
|
|
4547
4547
|
|
|
@@ -4699,7 +4699,7 @@ catch (error) {
|
|
|
4699
4699
|
|
|
4700
4700
|
return { statusCode: 200, body: 'OK' };
|
|
4701
4701
|
};
|
|
4702
|
-
`,$E,zU,g$,UU,sY,oY,JE,YE,ZE,QE,WE,XU,BU,PE,SU,kU,$M,JM,YM,ZM,QM;var n0=o(async()=>{GA=Object.defineProperty;HA=QA(import.meta.url),$z={};Q$($z,{signRequestAsync:()=>v6,signRequest:()=>Z1,parseXMLResponse:()=>C8,parseJSONResponse:()=>Fz,makeAWSRequestOnce:()=>Uz,makeAWSRequestAsync:()=>Hz,makeAWSRequest:()=>Z$,isWebCryptoAvailable:()=>Oz,isNodeCryptoAvailable:()=>Kz,getSigningKeyCacheSize:()=>Bz,detectServiceRegion:()=>y6,createPresignedUrlAsync:()=>Jz,createPresignedUrl:()=>NJ,clearSigningKeyCache:()=>Xz});f8=UA(async()=>{try{u$=await import("node:crypto")}catch{}G$=new Map,Vz={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),BA={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},KA={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};l={Ref:($)=>({Ref:$}),GetAtt:($,J)=>({"Fn::GetAtt":[$,J]}),Sub:($,J)=>{if(J)return{"Fn::Sub":[$,J]};return{"Fn::Sub":$}},Join:($,J)=>({"Fn::Join":[$,J]}),Select:($,J)=>({"Fn::Select":[$,J]}),Split:($,J)=>({"Fn::Split":[$,J]}),GetAZs:($="")=>({"Fn::GetAZs":$}),ImportValue:($)=>({"Fn::ImportValue":$}),If:($,J,Y)=>({"Fn::If":[$,J,Y]}),Equals:($,J)=>({"Fn::Equals":[$,J]}),And:(...$)=>({"Fn::And":$}),Or:(...$)=>({"Fn::Or":$}),Not:($)=>({"Fn::Not":[$]}),Base64:($)=>({"Fn::Base64":$})},RA={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};l1=class l1{static createBucket($){let{name:J,bucketName:Y,slug:Z,environment:Q,public:G=!1,versioning:W=!1,website:z=!1,encryption:U=!0,intelligentTiering:H=!1,cors:F,lifecycleRules:B}=$,K=Y??f({slug:Z,environment:Q,resourceType:"s3",suffix:J}),O=x(K),V={Type:"AWS::S3::Bucket",Properties:{BucketName:K}};if(U)V.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(W)V.Properties.VersioningConfiguration={Status:"Enabled"};if(z)V.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!G)V.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(F&&F.length>0)V.Properties.CorsConfiguration={CorsRules:F.map((_)=>({AllowedOrigins:_.allowedOrigins,AllowedMethods:_.allowedMethods,AllowedHeaders:_.allowedHeaders,MaxAge:_.maxAge}))};if(B&&B.length>0)V.Properties.LifecycleConfiguration={Rules:B.map((_)=>({Id:_.id,Status:_.enabled?"Enabled":"Disabled",ExpirationInDays:_.expirationDays,Transitions:_.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(H&&B){let _={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!V.Properties.LifecycleConfiguration)V.Properties.LifecycleConfiguration={Rules:[]};V.Properties.LifecycleConfiguration.Rules.push({Id:_.id,Status:"Enabled",Transitions:_.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let A;if(G)A={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(O),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[l.Join("",[l.GetAtt(O,"Arn"),"/*"])]}]}}};return{bucket:V,bucketPolicy:A,logicalId:O}}static enableVersioning($){if(!$.Properties)$.Properties={};return $.Properties.VersioningConfiguration={Status:"Enabled"},$}static enableWebsiteHosting($,J="index.html",Y="error.html"){if(!$.Properties)$.Properties={};return $.Properties.WebsiteConfiguration={IndexDocument:J,ErrorDocument:Y},$}static setLifecycleRules($,J){if(!$.Properties)$.Properties={};return $.Properties.LifecycleConfiguration={Rules:J.map((Y)=>({Id:Y.id,Status:Y.enabled?"Enabled":"Disabled",ExpirationInDays:Y.expirationDays,Transitions:Y.transitions?.map((Z)=>({TransitionInDays:Z.days,StorageClass:Z.storageClass}))}))},$}static enableIntelligentTiering($){if(!$.Properties)$.Properties={};if(!$.Properties.LifecycleConfiguration)$.Properties.LifecycleConfiguration={Rules:[]};return $.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),$}static addLambdaNotification($,J){if(!$.Properties)$.Properties={};if(!$.Properties.NotificationConfiguration)$.Properties.NotificationConfiguration={};if(!$.Properties.NotificationConfiguration.LambdaConfigurations)$.Properties.NotificationConfiguration.LambdaConfigurations=[];let Y={Event:J.events[0],Function:J.functionArn};if(J.filter)Y.Filter={S3Key:{Rules:[...J.filter.prefix?[{Name:"prefix",Value:J.filter.prefix}]:[],...J.filter.suffix?[{Name:"suffix",Value:J.filter.suffix}]:[]]}};for(let Z of J.events){let Q={...Y,Event:Z};$.Properties.NotificationConfiguration.LambdaConfigurations.push(Q)}return $}static Notifications={onObjectCreated:($)=>({functionArn:$,events:["s3:ObjectCreated:*"]}),onObjectRemoved:($)=>({functionArn:$,events:["s3:ObjectRemoved:*"]}),onImageUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J,suffix:".jpg"}}),onFileType:($,J,Y)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:Y,suffix:J}}),onFolderUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J.endsWith("/")?J:`${J}/`}})};static createBackupPlan($){let{name:J,slug:Y,environment:Z,bucketLogicalIds:Q,retentionDays:G,schedule:W="cron(0 5 * * ? *)",vaultName:z,enableContinuousBackup:U=!1,moveToColdStorageAfterDays:H}=$,F=z||f({slug:Y,environment:Z,resourceType:"backup-vault",suffix:J}),B=x(F),K={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:F}},O=f({slug:Y,environment:Z,resourceType:"backup-role",suffix:J}),V=x(O),A={Type:"AWS::IAM::Role",Properties:{RoleName:O,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},_=f({slug:Y,environment:Z,resourceType:"backup-plan",suffix:J}),M=x(_),E={DeleteAfterDays:G};if(H&&H<G)E.MoveToColdStorageAfterDays=H;let j={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:_,BackupPlanRule:[{RuleName:`${J}-daily-backup`,TargetBackupVault:l.Ref(B),ScheduleExpression:W,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:E,EnableContinuousBackup:U}]}}},q=f({slug:Y,environment:Z,resourceType:"backup-selection",suffix:J}),T=x(q),D=Q.map((P)=>l.GetAtt(P,"Arn")),S={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:l.Ref(M),BackupSelection:{SelectionName:q,IamRoleArn:l.GetAtt(V,"Arn"),Resources:D}}};return{vault:K,plan:j,selection:S,role:A,vaultLogicalId:B,planLogicalId:M,selectionLogicalId:T,roleLogicalId:V}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket($){let{slug:J,environment:Y,sourceDomain:Z,targetDomain:Q,protocol:G="https"}=$,W=f({slug:J,environment:Y,resourceType:"s3",suffix:"www-redirect"}),z=x(W),U={Type:"AWS::S3::Bucket",Properties:{BucketName:Z,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:Q,Protocol:G}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},H={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(z),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[l.Join("",[l.GetAtt(z,"Arn"),"/*"])]}]}}};return{bucket:U,bucketPolicy:H,logicalId:z}}static createDocsBucket($){let{slug:J,environment:Y,domain:Z}=$,Q=Z||f({slug:J,environment:Y,resourceType:"s3",suffix:"docs"}),G=x(Q);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:Q,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:G}}static createEmailBucket($){let{slug:J,environment:Y}=$,Z=f({slug:J,environment:Y,resourceType:"s3",suffix:"email"}),Q=x(Z),G={Type:"AWS::S3::Bucket",Properties:{BucketName:Z,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},W={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(Q),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:l.Join("",[l.GetAtt(Q,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":l.Ref("AWS::AccountId")}}}]}}};return{bucket:G,bucketPolicy:W,logicalId:Q}}static docsExist($={}){let{projectRoot:J=process.cwd(),docsPaths:Y=["docs","documentation","doc"]}=$;for(let Z of Y){let Q=f2(J,Z);if(w8(Q)){let G=["dist","build",".bunpress/dist","_site","out","public"];for(let W of G){let z=f2(Q,W);if(w8(z))try{if(hA(z).length>0)return{exists:!0,path:Q,hasDistFolder:!0,distPath:z}}catch{}}return{exists:!0,path:Q,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists($){let J=l1.docsExist({projectRoot:$.projectRoot,docsPaths:$.docsPaths});if(!J.exists)return{bucket:null,logicalId:null,docsInfo:J};let Y=l1.createDocsBucket({slug:$.slug,environment:$.environment,domain:$.domain});return{bucket:Y.bucket,bucketPolicy:Y.bucketPolicy,logicalId:Y.logicalId,docsInfo:J}}static createPrivateBucket($){let{slug:J,environment:Y,enableVersioning:Z=!0,retentionDays:Q,encryptionKeyArn:G}=$,W=f({slug:J,environment:Y,resourceType:"s3",suffix:"private"}),z=x(W);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:W,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:G?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:G}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:Z?{Status:"Enabled"}:void 0,LifecycleConfiguration:Q?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:Q}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:z}}static checkSourcePaths($={}){let{projectRoot:J=process.cwd(),paths:Y={}}=$,Z=Y.web||"views/web/dist",Q=Y.docs||"docs/dist",G=Y.private||"private";return{web:{exists:w8(f2(J,Z)),path:f2(J,Z)},docs:{exists:w8(f2(J,Q)),path:f2(J,Q)},private:{exists:w8(f2(J,G)),path:f2(J,G)}}}static createDeploymentBuckets($){let{slug:J,environment:Y,domain:Z,projectRoot:Q,paths:G}=$,W=l1.checkSourcePaths({projectRoot:Q,paths:G}),z={},U={web:!1,docs:!1,private:!1},H=l1.createBucket({name:"web",slug:J,environment:Y,public:!1,versioning:!1,encryption:!0});if(z[H.logicalId]=H.bucket,U.web=!0,W.docs.exists){let F=l1.createDocsBucket({slug:J,environment:Y,domain:Z?`docs.${Z}`:void 0});if(z[F.logicalId]=F.bucket,F.bucketPolicy)z[`${F.logicalId}Policy`]=F.bucketPolicy;U.docs=!0}if(W.private.exists){let F=l1.createPrivateBucket({slug:J,environment:Y,enableVersioning:!0});z[F.logicalId]=F.bucket,U.private=!0}return{resources:z,created:U,sourcePaths:W}}};J2=class J2{static createRepository($){let{name:J,slug:Y,environment:Z,scanOnPush:Q=!0,imageMutability:G="MUTABLE",encryption:W="AES256",kmsKey:z,lifecyclePolicy:U,tags:H}=$,F=f({slug:Y,environment:Z,resourceType:"ecr",suffix:J}),B=x(F),K={Type:"AWS::ECR::Repository",Properties:{RepositoryName:F,ImageTagMutability:G,ImageScanningConfiguration:{ScanOnPush:Q},EncryptionConfiguration:{EncryptionType:W,...z&&W==="KMS"?{KmsKey:z}:{}}}};if(U)K.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(J2.generateLifecyclePolicy(U))};if(H)K.Properties.Tags=Object.entries(H).map(([O,V])=>({Key:O,Value:V}));return{repository:K,logicalId:B}}static generateLifecyclePolicy($){let J=[];if($.untaggedImageExpireDays!==void 0)J.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:$.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if($.maxImageCount!==void 0)J.push({rulePriority:J.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:$.maxImageCount},action:{type:"expire"}});if($.maxImageAgeDays!==void 0)J.push({rulePriority:J.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:$.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:J}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags($){if(!$.Properties)$.Properties={};return $.Properties.ImageTagMutability="IMMUTABLE",$}static enableScanOnPush($){if(!$.Properties)$.Properties={};return $.Properties.ImageScanningConfiguration={ScanOnPush:!0},$}static setLifecyclePolicy($,J){if(!$.Properties)$.Properties={};return $.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(J2.generateLifecyclePolicy(J))},$}static addCrossAccountAccess($,J){if(!$.Properties)$.Properties={};return $.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:J.map((Y)=>`arn:aws:iam::${Y}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},$}static addLambdaAccess($){if(!$.Properties)$.Properties={};return $.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},$}static generateBunDockerfile($){let{baseImage:J="oven/bun:1-debian",serverPath:Y,port:Z=3000,additionalDirs:Q=[],healthCheckEndpoint:G="/health",nodeCompatible:W=!1,envVars:z={},buildCommands:U=[],runCommand:H}=$,F=["app","config",...Q],B=H||`bun run ${Y}`,K=`# Multi-stage build for Bun application
|
|
4702
|
+
`,$E,zU,g$,UU,sY,oY,JE,YE,ZE,QE,WE,XU,BU,PE,SU,kU,$M,JM,YM,ZM,QM;var n0=o(async()=>{GA=Object.defineProperty;HA=QA(import.meta.url),$z={};G$($z,{signRequestAsync:()=>v6,signRequest:()=>Z1,parseXMLResponse:()=>C8,parseJSONResponse:()=>Fz,makeAWSRequestOnce:()=>Uz,makeAWSRequestAsync:()=>Hz,makeAWSRequest:()=>Q$,isWebCryptoAvailable:()=>Oz,isNodeCryptoAvailable:()=>Kz,getSigningKeyCacheSize:()=>Bz,detectServiceRegion:()=>y6,createPresignedUrlAsync:()=>Jz,createPresignedUrl:()=>NJ,clearSigningKeyCache:()=>Xz});f8=UA(async()=>{try{u$=await import("node:crypto")}catch{}W$=new Map,Vz={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"}}),BA={backgroundJobs:{visibilityTimeout:120,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fifo:{fifo:!0,contentBasedDeduplication:!0,visibilityTimeout:30,encrypted:!0},highThroughput:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0},delayed:{delaySeconds:60,visibilityTimeout:60,encrypted:!0},longRunning:{visibilityTimeout:900,messageRetentionPeriod:1209600,deadLetterQueue:!0,maxReceiveCount:2,encrypted:!0},monitored:{visibilityTimeout:60,messageRetentionPeriod:604800,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0,alarms:{enabled:!0,queueDepthThreshold:1000,messageAgeThreshold:3600,dlqAlarm:!0}},lambdaOptimized:{visibilityTimeout:360,receiveMessageWaitTime:20,deadLetterQueue:!0,maxReceiveCount:3,encrypted:!0},fanOut:{visibilityTimeout:30,receiveMessageWaitTime:20,encrypted:!0}},KA={serverless:{development:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:!0},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:1000,handlerMemory:128}},production:{enabled:!0,mode:"serverless",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:30,inactivityTimeout:60}},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST",pointInTimeRecovery:!0,connectionTTL:86400}},scaling:{maxConnections:50000,messagesPerSecond:5000,handlerMemory:256,handlerTimeout:30},monitoring:{enabled:!0,connectionThreshold:40000,errorThreshold:100,latencyThreshold:500},keepAlive:!0,keepAliveInterval:30,idleTimeout:600},notifications:{enabled:!0,mode:"serverless",channels:{public:!1,private:!0,presence:!1},storage:{type:"dynamodb",dynamodb:{billingMode:"PAY_PER_REQUEST"}},scaling:{maxConnections:50000,messagesPerSecond:2000,handlerMemory:128},keepAlive:!0,keepAliveInterval:60,idleTimeout:1800}},server:{development:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"ws",driver:"bun",idleTimeout:120,perMessageDeflate:!1,metrics:!1}},production:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,maxPayloadLength:16777216,backpressureLimit:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"broadcasting:"},rateLimit:{enabled:!0,max:100,window:60000,perChannel:!0,perUser:!0},loadManagement:{enabled:!0,maxConnections:1e4,maxSubscriptionsPerConnection:100,shedLoadThreshold:0.8},metrics:!0,autoScaling:{min:2,max:10,targetCPU:70}},monitoring:{enabled:!0,connectionThreshold:8000,errorThreshold:100}},highPerformance:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:60,maxPayloadLength:8388608,backpressureLimit:2097152,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!0,instances:4,redis:{enabled:!0,useElastiCache:!0,keyPrefix:"rt:"},rateLimit:{enabled:!0,max:200,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:25000,maxSubscriptionsPerConnection:50,shedLoadThreshold:0.7},metrics:{enabled:!0,path:"/metrics"},autoScaling:{min:4,max:20,targetCPU:60,targetConnections:20000}},monitoring:{enabled:!0,connectionThreshold:80000,errorThreshold:50,latencyThreshold:50}},chat:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:200,heartbeatInterval:20,inactivityTimeout:60}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:300,maxPayloadLength:1048576,sendPings:!0,perMessageDeflate:!0,instances:2,redis:{enabled:!0,keyPrefix:"chat:"},rateLimit:{enabled:!0,max:60,window:60000,perChannel:!0},loadManagement:{enabled:!0,maxConnections:15000,maxSubscriptionsPerConnection:20},metrics:!0},keepAlive:!0,keepAliveInterval:25,idleTimeout:900},gaming:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:{enabled:!0,maxMembers:100,heartbeatInterval:10,inactivityTimeout:30}},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:30,maxPayloadLength:65536,backpressureLimit:524288,closeOnBackpressureLimit:!0,sendPings:!0,perMessageDeflate:!1,instances:4,redis:{enabled:!0,useElastiCache:!0},rateLimit:{enabled:!0,max:120,window:60000},loadManagement:{enabled:!0,maxConnections:5000,maxSubscriptionsPerConnection:10,shedLoadThreshold:0.6},metrics:!0,autoScaling:{min:4,max:16,targetCPU:50}},keepAlive:!0,keepAliveInterval:10,idleTimeout:60},single:{enabled:!0,mode:"server",channels:{public:!0,private:!0,presence:!0},server:{host:"0.0.0.0",port:6001,scheme:"wss",driver:"bun",idleTimeout:120,sendPings:!0,perMessageDeflate:!0,instances:1,rateLimit:{enabled:!0,max:100,window:60000},loadManagement:{enabled:!0,maxConnections:1e4},metrics:!0}}}};l={Ref:($)=>({Ref:$}),GetAtt:($,J)=>({"Fn::GetAtt":[$,J]}),Sub:($,J)=>{if(J)return{"Fn::Sub":[$,J]};return{"Fn::Sub":$}},Join:($,J)=>({"Fn::Join":[$,J]}),Select:($,J)=>({"Fn::Select":[$,J]}),Split:($,J)=>({"Fn::Split":[$,J]}),GetAZs:($="")=>({"Fn::GetAZs":$}),ImportValue:($)=>({"Fn::ImportValue":$}),If:($,J,Y)=>({"Fn::If":[$,J,Y]}),Equals:($,J)=>({"Fn::Equals":[$,J]}),And:(...$)=>({"Fn::And":$}),Or:(...$)=>({"Fn::Or":$}),Not:($)=>({"Fn::Not":[$]}),Base64:($)=>({"Fn::Base64":$})},RA={AccountId:{Ref:"AWS::AccountId"},Region:{Ref:"AWS::Region"},StackId:{Ref:"AWS::StackId"},StackName:{Ref:"AWS::StackName"},NotificationARNs:{Ref:"AWS::NotificationARNs"},Partition:{Ref:"AWS::Partition"},URLSuffix:{Ref:"AWS::URLSuffix"},NoValue:{Ref:"AWS::NoValue"}};l1=class l1{static createBucket($){let{name:J,bucketName:Y,slug:Z,environment:Q,public:G=!1,versioning:W=!1,website:z=!1,encryption:U=!0,intelligentTiering:H=!1,cors:F,lifecycleRules:B}=$,K=Y??f({slug:Z,environment:Q,resourceType:"s3",suffix:J}),O=x(K),V={Type:"AWS::S3::Bucket",Properties:{BucketName:K}};if(U)V.Properties.BucketEncryption={ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]};if(W)V.Properties.VersioningConfiguration={Status:"Enabled"};if(z)V.Properties.WebsiteConfiguration={IndexDocument:"index.html",ErrorDocument:"error.html"};if(!G)V.Properties.PublicAccessBlockConfiguration={BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0};if(F&&F.length>0)V.Properties.CorsConfiguration={CorsRules:F.map((_)=>({AllowedOrigins:_.allowedOrigins,AllowedMethods:_.allowedMethods,AllowedHeaders:_.allowedHeaders,MaxAge:_.maxAge}))};if(B&&B.length>0)V.Properties.LifecycleConfiguration={Rules:B.map((_)=>({Id:_.id,Status:_.enabled?"Enabled":"Disabled",ExpirationInDays:_.expirationDays,Transitions:_.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))}))};if(H&&B){let _={id:"IntelligentTieringRule",enabled:!0,transitions:[{days:0,storageClass:"INTELLIGENT_TIERING"}]};if(!V.Properties.LifecycleConfiguration)V.Properties.LifecycleConfiguration={Rules:[]};V.Properties.LifecycleConfiguration.Rules.push({Id:_.id,Status:"Enabled",Transitions:_.transitions?.map((M)=>({TransitionInDays:M.days,StorageClass:M.storageClass}))})}let A;if(G)A={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(O),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[l.Join("",[l.GetAtt(O,"Arn"),"/*"])]}]}}};return{bucket:V,bucketPolicy:A,logicalId:O}}static enableVersioning($){if(!$.Properties)$.Properties={};return $.Properties.VersioningConfiguration={Status:"Enabled"},$}static enableWebsiteHosting($,J="index.html",Y="error.html"){if(!$.Properties)$.Properties={};return $.Properties.WebsiteConfiguration={IndexDocument:J,ErrorDocument:Y},$}static setLifecycleRules($,J){if(!$.Properties)$.Properties={};return $.Properties.LifecycleConfiguration={Rules:J.map((Y)=>({Id:Y.id,Status:Y.enabled?"Enabled":"Disabled",ExpirationInDays:Y.expirationDays,Transitions:Y.transitions?.map((Z)=>({TransitionInDays:Z.days,StorageClass:Z.storageClass}))}))},$}static enableIntelligentTiering($){if(!$.Properties)$.Properties={};if(!$.Properties.LifecycleConfiguration)$.Properties.LifecycleConfiguration={Rules:[]};return $.Properties.LifecycleConfiguration.Rules.push({Id:"IntelligentTieringRule",Status:"Enabled",Transitions:[{TransitionInDays:0,StorageClass:"INTELLIGENT_TIERING"}]}),$}static addLambdaNotification($,J){if(!$.Properties)$.Properties={};if(!$.Properties.NotificationConfiguration)$.Properties.NotificationConfiguration={};if(!$.Properties.NotificationConfiguration.LambdaConfigurations)$.Properties.NotificationConfiguration.LambdaConfigurations=[];let Y={Event:J.events[0],Function:J.functionArn};if(J.filter)Y.Filter={S3Key:{Rules:[...J.filter.prefix?[{Name:"prefix",Value:J.filter.prefix}]:[],...J.filter.suffix?[{Name:"suffix",Value:J.filter.suffix}]:[]]}};for(let Z of J.events){let Q={...Y,Event:Z};$.Properties.NotificationConfiguration.LambdaConfigurations.push(Q)}return $}static Notifications={onObjectCreated:($)=>({functionArn:$,events:["s3:ObjectCreated:*"]}),onObjectRemoved:($)=>({functionArn:$,events:["s3:ObjectRemoved:*"]}),onImageUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J,suffix:".jpg"}}),onFileType:($,J,Y)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:Y,suffix:J}}),onFolderUpload:($,J)=>({functionArn:$,events:["s3:ObjectCreated:*"],filter:{prefix:J.endsWith("/")?J:`${J}/`}})};static createBackupPlan($){let{name:J,slug:Y,environment:Z,bucketLogicalIds:Q,retentionDays:G,schedule:W="cron(0 5 * * ? *)",vaultName:z,enableContinuousBackup:U=!1,moveToColdStorageAfterDays:H}=$,F=z||f({slug:Y,environment:Z,resourceType:"backup-vault",suffix:J}),B=x(F),K={Type:"AWS::Backup::BackupVault",Properties:{BackupVaultName:F}},O=f({slug:Y,environment:Z,resourceType:"backup-role",suffix:J}),V=x(O),A={Type:"AWS::IAM::Role",Properties:{RoleName:O,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"backup.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup","arn:aws:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForRestores"]}},_=f({slug:Y,environment:Z,resourceType:"backup-plan",suffix:J}),M=x(_),E={DeleteAfterDays:G};if(H&&H<G)E.MoveToColdStorageAfterDays=H;let j={Type:"AWS::Backup::BackupPlan",Properties:{BackupPlan:{BackupPlanName:_,BackupPlanRule:[{RuleName:`${J}-daily-backup`,TargetBackupVault:l.Ref(B),ScheduleExpression:W,StartWindowMinutes:60,CompletionWindowMinutes:120,Lifecycle:E,EnableContinuousBackup:U}]}}},q=f({slug:Y,environment:Z,resourceType:"backup-selection",suffix:J}),T=x(q),D=Q.map((P)=>l.GetAtt(P,"Arn")),S={Type:"AWS::Backup::BackupSelection",Properties:{BackupPlanId:l.Ref(M),BackupSelection:{SelectionName:q,IamRoleArn:l.GetAtt(V,"Arn"),Resources:D}}};return{vault:K,plan:j,selection:S,role:A,vaultLogicalId:B,planLogicalId:M,selectionLogicalId:T,roleLogicalId:V}}static BackupSchedules={HOURLY:"cron(0 * * * ? *)",DAILY_5AM:"cron(0 5 * * ? *)",DAILY_MIDNIGHT:"cron(0 0 * * ? *)",WEEKLY_SUNDAY:"cron(0 5 ? * SUN *)",WEEKLY_SATURDAY:"cron(0 5 ? * SAT *)",MONTHLY_FIRST:"cron(0 5 1 * ? *)",EVERY_12_HOURS:"cron(0 */12 * * ? *)",EVERY_6_HOURS:"cron(0 */6 * * ? *)"};static BackupRetention={ONE_DAY:1,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,THREE_MONTHS:90,SIX_MONTHS:180,ONE_YEAR:365,TWO_YEARS:730,FIVE_YEARS:1825,SEVEN_YEARS:2555};static createWwwRedirectBucket($){let{slug:J,environment:Y,sourceDomain:Z,targetDomain:Q,protocol:G="https"}=$,W=f({slug:J,environment:Y,resourceType:"s3",suffix:"www-redirect"}),z=x(W),U={Type:"AWS::S3::Bucket",Properties:{BucketName:Z,WebsiteConfiguration:{RedirectAllRequestsTo:{HostName:Q,Protocol:G}},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1}}},H={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(z),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"PublicReadForRedirect",Effect:"Allow",Principal:"*",Action:["s3:GetObject"],Resource:[l.Join("",[l.GetAtt(z,"Arn"),"/*"])]}]}}};return{bucket:U,bucketPolicy:H,logicalId:z}}static createDocsBucket($){let{slug:J,environment:Y,domain:Z}=$,Q=Z||f({slug:J,environment:Y,resourceType:"s3",suffix:"docs"}),G=x(Q);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:Q,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},Tags:[{Key:"backup",Value:"weekly"}]}},logicalId:G}}static createEmailBucket($){let{slug:J,environment:Y}=$,Z=f({slug:J,environment:Y,resourceType:"s3",suffix:"email"}),Q=x(Z),G={Type:"AWS::S3::Bucket",Properties:{BucketName:Z,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},LifecycleConfiguration:{Rules:[{Id:"EmailRetention",Status:"Enabled",ExpirationInDays:90,Transitions:[{TransitionInDays:30,StorageClass:"STANDARD_IA"}]}]}}},W={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:l.Ref(Q),PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:l.Join("",[l.GetAtt(Q,"Arn"),"/*"]),Condition:{StringEquals:{"AWS:SourceAccount":l.Ref("AWS::AccountId")}}}]}}};return{bucket:G,bucketPolicy:W,logicalId:Q}}static docsExist($={}){let{projectRoot:J=process.cwd(),docsPaths:Y=["docs","documentation","doc"]}=$;for(let Z of Y){let Q=f2(J,Z);if(w8(Q)){let G=["dist","build",".bunpress/dist","_site","out","public"];for(let W of G){let z=f2(Q,W);if(w8(z))try{if(hA(z).length>0)return{exists:!0,path:Q,hasDistFolder:!0,distPath:z}}catch{}}return{exists:!0,path:Q,hasDistFolder:!1,distPath:null}}}return{exists:!1,path:null,hasDistFolder:!1,distPath:null}}static createDocsBucketIfExists($){let J=l1.docsExist({projectRoot:$.projectRoot,docsPaths:$.docsPaths});if(!J.exists)return{bucket:null,logicalId:null,docsInfo:J};let Y=l1.createDocsBucket({slug:$.slug,environment:$.environment,domain:$.domain});return{bucket:Y.bucket,bucketPolicy:Y.bucketPolicy,logicalId:Y.logicalId,docsInfo:J}}static createPrivateBucket($){let{slug:J,environment:Y,enableVersioning:Z=!0,retentionDays:Q,encryptionKeyArn:G}=$,W=f({slug:J,environment:Y,resourceType:"s3",suffix:"private"}),z=x(W);return{bucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:W,BucketEncryption:{ServerSideEncryptionConfiguration:[{ServerSideEncryptionByDefault:G?{SSEAlgorithm:"aws:kms",KMSMasterKeyID:G}:{SSEAlgorithm:"AES256"}}]},PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!0,IgnorePublicAcls:!0,RestrictPublicBuckets:!0},VersioningConfiguration:Z?{Status:"Enabled"}:void 0,LifecycleConfiguration:Q?{Rules:[{Id:"RetentionPolicy",Status:"Enabled",ExpirationInDays:Q}]}:void 0,Tags:[{Key:"backup",Value:"daily"}]}},logicalId:z}}static checkSourcePaths($={}){let{projectRoot:J=process.cwd(),paths:Y={}}=$,Z=Y.web||"views/web/dist",Q=Y.docs||"docs/dist",G=Y.private||"private";return{web:{exists:w8(f2(J,Z)),path:f2(J,Z)},docs:{exists:w8(f2(J,Q)),path:f2(J,Q)},private:{exists:w8(f2(J,G)),path:f2(J,G)}}}static createDeploymentBuckets($){let{slug:J,environment:Y,domain:Z,projectRoot:Q,paths:G}=$,W=l1.checkSourcePaths({projectRoot:Q,paths:G}),z={},U={web:!1,docs:!1,private:!1},H=l1.createBucket({name:"web",slug:J,environment:Y,public:!1,versioning:!1,encryption:!0});if(z[H.logicalId]=H.bucket,U.web=!0,W.docs.exists){let F=l1.createDocsBucket({slug:J,environment:Y,domain:Z?`docs.${Z}`:void 0});if(z[F.logicalId]=F.bucket,F.bucketPolicy)z[`${F.logicalId}Policy`]=F.bucketPolicy;U.docs=!0}if(W.private.exists){let F=l1.createPrivateBucket({slug:J,environment:Y,enableVersioning:!0});z[F.logicalId]=F.bucket,U.private=!0}return{resources:z,created:U,sourcePaths:W}}};J2=class J2{static createRepository($){let{name:J,slug:Y,environment:Z,scanOnPush:Q=!0,imageMutability:G="MUTABLE",encryption:W="AES256",kmsKey:z,lifecyclePolicy:U,tags:H}=$,F=f({slug:Y,environment:Z,resourceType:"ecr",suffix:J}),B=x(F),K={Type:"AWS::ECR::Repository",Properties:{RepositoryName:F,ImageTagMutability:G,ImageScanningConfiguration:{ScanOnPush:Q},EncryptionConfiguration:{EncryptionType:W,...z&&W==="KMS"?{KmsKey:z}:{}}}};if(U)K.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(J2.generateLifecyclePolicy(U))};if(H)K.Properties.Tags=Object.entries(H).map(([O,V])=>({Key:O,Value:V}));return{repository:K,logicalId:B}}static generateLifecyclePolicy($){let J=[];if($.untaggedImageExpireDays!==void 0)J.push({rulePriority:1,description:"Delete untagged images",selection:{tagStatus:"untagged",countType:"sinceImagePushed",countNumber:$.untaggedImageExpireDays,countUnit:"days"},action:{type:"expire"}});if($.maxImageCount!==void 0)J.push({rulePriority:J.length+1,description:"Keep only most recent images",selection:{tagStatus:"any",countType:"imageCountMoreThan",countNumber:$.maxImageCount},action:{type:"expire"}});if($.maxImageAgeDays!==void 0)J.push({rulePriority:J.length+1,description:"Delete images older than specified days",selection:{tagStatus:"any",countType:"sinceImagePushed",countNumber:$.maxImageAgeDays,countUnit:"days"},action:{type:"expire"}});return{rules:J}}static LifecyclePolicies={production:{maxImageCount:10,untaggedImageExpireDays:7},development:{maxImageCount:5,untaggedImageExpireDays:3},minimal:{maxImageCount:3,untaggedImageExpireDays:1},archive:{maxImageCount:50,untaggedImageExpireDays:30}};static enableImmutableTags($){if(!$.Properties)$.Properties={};return $.Properties.ImageTagMutability="IMMUTABLE",$}static enableScanOnPush($){if(!$.Properties)$.Properties={};return $.Properties.ImageScanningConfiguration={ScanOnPush:!0},$}static setLifecyclePolicy($,J){if(!$.Properties)$.Properties={};return $.Properties.LifecyclePolicy={LifecyclePolicyText:JSON.stringify(J2.generateLifecyclePolicy(J))},$}static addCrossAccountAccess($,J){if(!$.Properties)$.Properties={};return $.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"CrossAccountPull",Effect:"Allow",Principal:{AWS:J.map((Y)=>`arn:aws:iam::${Y}:root`)},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:BatchCheckLayerAvailability"]}]},$}static addLambdaAccess($){if(!$.Properties)$.Properties={};return $.Properties.RepositoryPolicyText={Version:"2012-10-17",Statement:[{Sid:"LambdaECRImageRetrievalPolicy",Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:["ecr:GetDownloadUrlForLayer","ecr:BatchGetImage"]}]},$}static generateBunDockerfile($){let{baseImage:J="oven/bun:1-debian",serverPath:Y,port:Z=3000,additionalDirs:Q=[],healthCheckEndpoint:G="/health",nodeCompatible:W=!1,envVars:z={},buildCommands:U=[],runCommand:H}=$,F=["app","config",...Q],B=H||`bun run ${Y}`,K=`# Multi-stage build for Bun application
|
|
4703
4703
|
# Generated by ts-cloud
|
|
4704
4704
|
|
|
4705
4705
|
# Builder stage
|
|
@@ -5837,7 +5837,7 @@ else if (encoding === 'quoted-printable') {
|
|
|
5837
5837
|
|
|
5838
5838
|
return content;
|
|
5839
5839
|
}
|
|
5840
|
-
`}};Mz={};Q$(Mz,{handler:()=>IJ,default:()=>bA});bA=IJ;Y2=class Y2{static LambdaCode={incomingCall:IJ,voicemail:yA,missedCall:vA};static createConnectInstance($){let{slug:J,environment:Y,instanceAlias:Z,inboundCallsEnabled:Q=!0,outboundCallsEnabled:G=!0}=$;return{[`${J}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:Z,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:Q,OutboundCalls:G,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation($){return{[`${$.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:$.instanceArn,Name:$.name,TimeZone:$.timezone,Config:$.schedule.map((J)=>({Day:J.day,StartTime:{Hours:J.startHour,Minutes:J.startMinute},EndTime:{Hours:J.endHour,Minutes:J.endMinute}}))}}}}static createQueue($){return{[`${$.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:$.instanceArn,Name:$.name,HoursOfOperationArn:$.hoursOfOperationArn,MaxContacts:$.maxContacts||10}}}}static createContactFlow($){return{[`${$.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:$.instanceArn,Name:$.name,Type:$.type,Content:$.content}}}}static createBasicIvrFlow($){let J={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:$.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:$.queueArn},Transitions:{NextAction:$.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...$.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:$.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(J)}static createPhoneLambdaRole($){return{[`${$.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${$.slug}-phone-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda($){return{[`${$.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Y2.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createVoicemailLambda($){return{[`${$.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:Y2.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:$.voicemailBucket,NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",TRANSCRIPTION_ENABLED:$.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda($){return{[`${$.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Y2.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createCallLogTable($){return{[`${$.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup($){let J={},Y={};Object.assign(J,Y2.createPhoneLambdaRole({slug:$.slug})),Object.assign(J,Y2.createCallLogTable({slug:$.slug})),J[`${$.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${$.slug}-phone-notifications`}},J[`${$.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let Z={"Fn::GetAtt":[`${$.slug}PhoneLambdaRole`,"Arn"]},Q={Ref:`${$.slug}PhoneNotificationTopic`},G={Ref:`${$.slug}CallLogTable`},W={Ref:`${$.slug}VoicemailBucket`};if(Object.assign(J,Y2.createIncomingCallLambda({slug:$.slug,roleArn:Z,notificationTopicArn:Q,callLogTable:G,webhookUrl:$.webhookUrl})),$.voicemailEnabled!==!1)Object.assign(J,Y2.createVoicemailLambda({slug:$.slug,roleArn:Z,voicemailBucket:W,notificationTopicArn:Q,callLogTable:G,transcriptionEnabled:$.transcriptionEnabled}));return Object.assign(J,Y2.createMissedCallLambda({slug:$.slug,roleArn:Z,notificationTopicArn:Q,callLogTable:G,webhookUrl:$.webhookUrl})),Y[`${$.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${$.slug}PhoneNotificationTopic`}},Y[`${$.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${$.slug}CallLogTable`}},Y[`${$.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${$.slug}VoicemailBucket`}},{resources:J,outputs:Y}}};_1=class _1{static createQueue($){let{slug:J,environment:Y,name:Z,delaySeconds:Q=0,visibilityTimeout:G=30,messageRetentionPeriod:W=345600,maxMessageSize:z=262144,receiveMessageWaitTime:U=0,fifo:H=!1,contentBasedDeduplication:F=!1,encrypted:B=!0,kmsKeyId:K}=$,O=Z||f({slug:J,environment:Y,resourceType:"queue"}),V=H?`${O}.fifo`:O,A=x(O),_={Type:"AWS::SQS::Queue",Properties:{QueueName:V,DelaySeconds:Q,MaximumMessageSize:z,MessageRetentionPeriod:W,ReceiveMessageWaitTimeSeconds:U,VisibilityTimeout:G,Tags:[{Key:"Name",Value:V},{Key:"Environment",Value:Y}]}};if(H)_.Properties.FifoQueue=!0,_.Properties.ContentBasedDeduplication=F;if(B)if(K)_.Properties.KmsMasterKeyId=K;else _.Properties.SqsManagedSseEnabled=!0;return{queue:_,logicalId:A}}static createDeadLetterQueue($,J){let{slug:Y,environment:Z,maxReceiveCount:Q=3}=J,G=f({slug:Y,environment:Z,resourceType:"dlq"}),W=x(G),z={Type:"AWS::SQS::Queue",Properties:{QueueName:G,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z},{Key:"Type",Value:"DeadLetterQueue"}]}},U={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:l.GetAtt(W,"Arn"),maxReceiveCount:Q}}};return{deadLetterQueue:z,updatedSourceQueue:U,deadLetterLogicalId:W}}static createSchedule($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0}=J,z=Q||f({slug:Y,environment:Z,resourceType:"schedule"}),U=x(z);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:z,Description:G,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[]}},logicalId:U}}static scheduleEcsTask($,J,Y){let{slug:Z,environment:Q,name:G,description:W,enabled:z=!0,taskDefinitionArn:U,clusterArn:H,subnets:F,securityGroups:B=[],assignPublicIp:K=!1,taskCount:O=1,containerOverrides:V}=Y,A=G||f({slug:Z,environment:Q,resourceType:"ecs-schedule"}),_=x(A),E={Id:"1",Arn:H,RoleArn:J,EcsParameters:{TaskDefinitionArn:U,TaskCount:O,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:F,SecurityGroups:B,AssignPublicIp:K?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(V&&V.length>0)E.Input=JSON.stringify({containerOverrides:V});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:A,Description:W||`Scheduled ECS task: ${U}`,ScheduleExpression:$,State:z?"ENABLED":"DISABLED",Targets:[E]}},logicalId:_}}static scheduleLambda($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0,functionArn:z,input:U}=J,H=Q||f({slug:Y,environment:Z,resourceType:"lambda-schedule"}),F=x(H),B={Id:"1",Arn:z};if(U)B.Input=JSON.stringify(U);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:H,Description:G||`Scheduled Lambda: ${z}`,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[B]}},logicalId:F}}static scheduleSqsMessage($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0,queueArn:z,messageGroupId:U}=J,H=Q||f({slug:Y,environment:Z,resourceType:"sqs-schedule"}),F=x(H),B={Id:"1",Arn:z};if(U)B.SqsParameters={MessageGroupId:U};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:H,Description:G||`Scheduled SQS message: ${z}`,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[B]}},logicalId:F}}static addTarget($,J){if(!$.Properties.Targets)$.Properties.Targets=[];let Y={Id:J.id,Arn:J.arn};if(J.roleArn)Y.RoleArn=J.roleArn;if(J.input)Y.Input=JSON.stringify(J.input);return $.Properties.Targets.push(Y),$}static toCronExpression($){if($.startsWith("cron(")||$.startsWith("rate("))return $;return`cron(${$})`}static rateExpression($,J){return`rate(${$} ${J})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression($){let J=$.toLowerCase().trim(),Y=J.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(Y){let H=parseInt(Y[1],10),F=Y[2].toLowerCase(),B=F.endsWith("s")&&H===1?F.slice(0,-1):F,K=!F.endsWith("s")&&H>1?`${F}s`:F;return`rate(${H} ${H===1?B:K})`}let Z=J.match(/^every\s+(minute|hour|day)$/i);if(Z)return`rate(1 ${Z[1]})`;let Q={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(Q[J])return Q[J];let G=J.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(G){let H=parseInt(G[1],10),F=G[2]?.toLowerCase();if(F==="pm"&&H!==12)H+=12;else if(F==="am"&&H===12)H=0;return`cron(0 ${H} * * ? *)`}let W=J.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(W){let H=parseInt(W[1],10);return`cron(${parseInt(W[2],10)} ${H} * * ? *)`}let z={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},U=J.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(U)return`cron(0 0 ? * ${z[U[1].toLowerCase()]} *)`;return _1.toCronExpression($)}static JobConfig={create:($)=>{let{name:J,handler:Y,retries:Z=3,backoff:Q="exponential",backoffDelay:G=1000,maxDelay:W=30000,timeout:z=60000,jitter:U=!0}=$;return{name:J,handler:Y,retries:Z,backoff:Q,backoffDelay:G,maxDelay:W,timeout:z,jitter:U}},calculateDelay:($,J)=>{let{backoff:Y,backoffDelay:Z,maxDelay:Q,jitter:G}=J,W;switch(Y){case"linear":W=Z*$;break;case"exponential":W=Z*2**($-1);break;case"fixed":default:W=Z}if(W=Math.min(W,Q||Number.MAX_SAFE_INTEGER),G){let z=W*0.25*Math.random();W+=z}return Math.floor(W)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride($){let{containerName:J,jobClass:Y,jobData:Z,environment:Q={}}=$,G=[{name:"JOB_CLASS",value:Y}];if(Z)G.push({name:"JOB_DATA",value:JSON.stringify(Z)});for(let[W,z]of Object.entries(Q))G.push({name:W,value:z});return{name:J,command:["bun","run","app/Jobs/runner.ts"],environment:G}}static createScheduledJob($){let{slug:J,environment:Y,schedule:Z,jobClass:Q,jobData:G,taskDefinitionArn:W,clusterArn:z,subnets:U,securityGroups:H=[],roleArn:F,containerName:B="app"}=$,K=_1.rateStringToExpression(Z),O=_1.createJobContainerOverride({containerName:B,jobClass:Q,jobData:G});return _1.scheduleEcsTask(K,F,{slug:J,environment:Y,name:`${J}-${Q.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${Q}`,taskDefinitionArn:W,clusterArn:z,subnets:U,securityGroups:H,containerOverrides:[O]})}static QueuePresets={highThroughput:($,J)=>_1.createQueue({slug:$,environment:J,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:($,J)=>_1.createQueue({slug:$,environment:J,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:($,J)=>_1.createQueue({slug:$,environment:J,fifo:!0,contentBasedDeduplication:!0}),delayed:($,J,Y=60)=>_1.createQueue({slug:$,environment:J,delaySeconds:Y})}};fA={loadJobs:L2.discoverJobs,loadActions:L2.discoverActions,generateScheduledJobs:L2.generateScheduledJobResources,generateRunner:L2.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}},qz={};Q$(qz,{handler:()=>kJ,default:()=>gA});gA=kJ;B1=class B1{static LambdaCode={send:kJ,receive:uA,deliveryStatus:dA};static createPinpointApp($){return{[`${$.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:$.name||`${$.slug}-sms`}}}}static createSmsChannel($){let J={ApplicationId:$.applicationId,Enabled:$.enabled!==!1};if($.senderId)J.SenderId=$.senderId;if($.shortCode)J.ShortCode=$.shortCode;return{[`${$.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:J}}}static createSmsLambdaRole($){return{[`${$.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${$.slug}-sms-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda($){return{[`${$.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:$.pinpointAppId,MESSAGE_LOG_TABLE:$.messageLogTable||"",SMS_SENDER_ID:$.senderId||"",SMS_ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static createReceiveLambda($){return{[`${$.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:$.optOutTable||"",MESSAGE_LOG_TABLE:$.messageLogTable||"",NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createDeliveryStatusLambda($){return{[`${$.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:$.messageLogTable||"",NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createMessageLogTable($){return{[`${$.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable($){return{[`${$.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic($){return{[`${$.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${$.slug}-sms-notifications`}}}}static createCompleteSetup($){let J={},Y={};Object.assign(J,B1.createPinpointApp({slug:$.slug})),Object.assign(J,B1.createSmsChannel({slug:$.slug,applicationId:{Ref:`${$.slug}PinpointApp`},senderId:$.senderId})),Object.assign(J,B1.createSmsLambdaRole({slug:$.slug})),Object.assign(J,B1.createMessageLogTable({slug:$.slug})),Object.assign(J,B1.createOptOutTable({slug:$.slug})),Object.assign(J,B1.createNotificationTopic({slug:$.slug}));let Z={"Fn::GetAtt":[`${$.slug}SmsLambdaRole`,"Arn"]},Q={Ref:`${$.slug}PinpointApp`},G={Ref:`${$.slug}SmsMessageLogTable`},W={Ref:`${$.slug}SmsOptOutTable`},z={Ref:`${$.slug}SmsNotificationTopic`};if(Object.assign(J,B1.createSendLambda({slug:$.slug,roleArn:Z,pinpointAppId:Q,messageLogTable:G,senderId:$.senderId,originationNumber:$.originationNumber})),$.twoWayEnabled)Object.assign(J,B1.createReceiveLambda({slug:$.slug,roleArn:Z,optOutTable:W,messageLogTable:G,notificationTopicArn:z,webhookUrl:$.webhookUrl}));return Object.assign(J,B1.createDeliveryStatusLambda({slug:$.slug,roleArn:Z,messageLogTable:G,notificationTopicArn:z,webhookUrl:$.webhookUrl})),Y[`${$.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${$.slug}PinpointApp`}},Y[`${$.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${$.slug}SmsSendLambda`,"Arn"]}},Y[`${$.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${$.slug}SmsNotificationTopic`}},Y[`${$.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${$.slug}SmsMessageLogTable`}},{resources:J,outputs:Y}}};p1=class p1{static createBedrockRole($,J){let{slug:Y,environment:Z,name:Q,models:G=["*"],allowStreaming:W=!0}=J,z=Q||f({slug:Y,environment:Z,resourceType:"bedrock-role"}),U=x(z),H=["bedrock:InvokeModel"];if(W)H.push("bedrock:InvokeModelWithResponseStream");let F=G.map((K)=>K==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${K}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:$},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${z}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:H,Resource:F}]}}],Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Z}]}},logicalId:U}}static createBedrockPolicy($){let{slug:J,environment:Y,name:Z,models:Q=["*"],allowInvoke:G=!0,allowStreaming:W=!0,allowAsync:z=!1}=$,U=Z||f({slug:J,environment:Y,resourceType:"bedrock-policy"}),H=x(U),F=[];if(G)F.push("bedrock:InvokeModel");if(W)F.push("bedrock:InvokeModelWithResponseStream");if(z)F.push("bedrock:InvokeModelAsync");let B=Q.map((O)=>O==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${O}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:U,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:F,Resource:B}]}}},logicalId:H}}static enableBedrockForLambda($){return p1.createBedrockRole("lambda.amazonaws.com",$)}static enableBedrockForEcs($){return p1.createBedrockRole("ecs-tasks.amazonaws.com",$)}static enableBedrockForEc2($){return p1.createBedrockRole("ec2.amazonaws.com",$)}static addBedrockPermissions($,J=["*"],Y=!0){let Z=["bedrock:InvokeModel"];if(Y)Z.push("bedrock:InvokeModelWithResponseStream");let Q=J.map((G)=>G==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${G}`);if(!$.Properties.Policies)$.Properties.Policies=[];return $.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:Z,Resource:Q}]}}),$}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}};m2=class m2{static createPostgres($){return m2.createRDSInstance("postgres","16.2",$)}static createMysql($){return m2.createRDSInstance("mysql","8.0.35",$)}static createRDSInstance($,J,Y){let{slug:Z,environment:Q,instanceClass:G="db.t3.micro",allocatedStorage:W=20,storageType:z="gp3",masterUsername:U="admin",masterPassword:H,databaseName:F,subnetIds:B,securityGroupIds:K,encrypted:O=!0,kmsKeyId:V,multiAz:A=!1,backupRetentionDays:_=7,publiclyAccessible:M=!1,enableCloudwatchLogs:E=!0,deletionProtection:j=!0}=Y,q=f({slug:Z,environment:Q,resourceType:`${$}-db`}),T=x(q),D,S;if(B&&B.length>0){let C=f({slug:Z,environment:Q,resourceType:"db-subnet-group"});S=x(C),D={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:C,DBSubnetGroupDescription:`Subnet group for ${q}`,SubnetIds:B,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:Q}]}}}let P={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:q,DBInstanceClass:G,Engine:$,EngineVersion:J,MasterUsername:U,MasterUserPassword:H,AllocatedStorage:W,StorageType:z,StorageEncrypted:O,MultiAZ:A,BackupRetentionPeriod:_,PubliclyAccessible:M,DeletionProtection:j,Tags:[{Key:"Name",Value:q},{Key:"Environment",Value:Q}]}};if(F)P.Properties.DBName=F;if(V)P.Properties.KmsKeyId=V;if(S)P.Properties.DBSubnetGroupName=l.Ref(S);if(K&&K.length>0)P.Properties.VPCSecurityGroups=K;if(E)P.Properties.EnableCloudwatchLogsExports=$==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:P,subnetGroup:D,logicalId:T,subnetGroupId:S}}static createReadReplica($,J){let{slug:Y,environment:Z,instanceClass:Q="db.t3.micro",securityGroupIds:G,publiclyAccessible:W=!1}=J,z=f({slug:Y,environment:Z,resourceType:"db-replica"}),U=x(z),H={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:z,DBInstanceClass:Q,SourceDBInstanceIdentifier:l.Ref($),PubliclyAccessible:W,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Z},{Key:"Type",Value:"ReadReplica"}]}};if(G&&G.length>0)H.Properties.VPCSecurityGroups=G;return{replica:H,logicalId:U}}static createParameterGroup($,J,Y){let{slug:Z,environment:Q,parameters:G={}}=Y,W=f({slug:Z,environment:Q,resourceType:"db-params"}),z=x(W),U=$==="postgres"?`postgres${J.split(".")[0]}`:`mysql${J.split(".")[0]}.${J.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:W,Description:`Parameter group for ${W}`,Family:U,Parameters:G,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:Q}]}},logicalId:z}}static enableBackup($,J=7){return $.Properties.BackupRetentionPeriod=J,$}static createTable($){let{slug:J,environment:Y,tableName:Z,partitionKey:Q,sortKey:G,billingMode:W="PAY_PER_REQUEST",readCapacity:z=5,writeCapacity:U=5,streamEnabled:H=!1,streamViewType:F="NEW_AND_OLD_IMAGES",encrypted:B=!0,kmsKeyId:K,pointInTimeRecovery:O=!0,ttlAttribute:V}=$,A=Z||f({slug:J,environment:Y,resourceType:"table"}),_=x(A),M=[{AttributeName:Q.name,AttributeType:Q.type}];if(G)M.push({AttributeName:G.name,AttributeType:G.type});let E=[{AttributeName:Q.name,KeyType:"HASH"}];if(G)E.push({AttributeName:G.name,KeyType:"RANGE"});let j={Type:"AWS::DynamoDB::Table",Properties:{TableName:A,BillingMode:W,AttributeDefinitions:M,KeySchema:E,Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:Y}]}};if(W==="PROVISIONED")j.Properties.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:U};if(H)j.Properties.StreamSpecification={StreamViewType:F};if(B)j.Properties.SSESpecification={SSEEnabled:!0,SSEType:K?"KMS":"AES256",KMSMasterKeyId:K};if(O)j.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(V)j.Properties.TimeToLiveSpecification={AttributeName:V,Enabled:!0};return{table:j,logicalId:_}}static addGlobalSecondaryIndex($,J){let{indexName:Y,partitionKey:Z,sortKey:Q,projectionType:G="ALL",nonKeyAttributes:W,readCapacity:z=5,writeCapacity:U=5}=J;if(!$.Properties.AttributeDefinitions.some((B)=>B.AttributeName===Z.name))$.Properties.AttributeDefinitions.push({AttributeName:Z.name,AttributeType:Z.type});if(Q&&!$.Properties.AttributeDefinitions.some((B)=>B.AttributeName===Q.name))$.Properties.AttributeDefinitions.push({AttributeName:Q.name,AttributeType:Q.type});let H=[{AttributeName:Z.name,KeyType:"HASH"}];if(Q)H.push({AttributeName:Q.name,KeyType:"RANGE"});let F={IndexName:Y,KeySchema:H,Projection:{ProjectionType:G,NonKeyAttributes:G==="INCLUDE"?W:void 0},ProvisionedThroughput:void 0};if($.Properties.BillingMode==="PROVISIONED")F.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:U};if(!$.Properties.GlobalSecondaryIndexes)$.Properties.GlobalSecondaryIndexes=[];return $.Properties.GlobalSecondaryIndexes.push(F),$}static enableStreams($,J="NEW_AND_OLD_IMAGES"){return $.Properties.StreamSpecification={StreamViewType:J},$}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}};g8=class g8{static createRedis($){let{slug:J,environment:Y,nodeType:Z="cache.t3.micro",engineVersion:Q="7.1",port:G=6379,subnetIds:W,securityGroupIds:z,numCacheClusters:U=2,automaticFailover:H=!0,multiAz:F=!0,clusterMode:B=!1,numNodeGroups:K=1,replicasPerNodeGroup:O=1,atRestEncryption:V=!0,transitEncryption:A=!0,authToken:_,kmsKeyId:M,snapshotRetentionDays:E=7,snapshotWindow:j,maintenanceWindow:q}=$,T=f({slug:J,environment:Y,resourceType:"redis"}),D=x(T),S,P;if(W&&W.length>0){let I=f({slug:J,environment:Y,resourceType:"cache-subnet-group"});P=x(I),S={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:I,Description:`Subnet group for ${T}`,SubnetIds:W,Tags:[{Key:"Name",Value:I},{Key:"Environment",Value:Y}]}}}let C={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:T,ReplicationGroupDescription:`Redis cluster for ${J} ${Y}`,Engine:"redis",EngineVersion:Q,CacheNodeType:Z,Port:G,AutomaticFailoverEnabled:H,MultiAZEnabled:F,AtRestEncryptionEnabled:V,TransitEncryptionEnabled:A,SnapshotRetentionLimit:E,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:Y}]}};if(B)C.Properties.NumNodeGroups=K,C.Properties.ReplicasPerNodeGroup=O;else C.Properties.NumCacheClusters=U;if(_)C.Properties.AuthToken=_;if(M)C.Properties.KmsKeyId=M;if(P)C.Properties.CacheSubnetGroupName=l.Ref(P);if(z&&z.length>0)C.Properties.SecurityGroupIds=z;if(j)C.Properties.SnapshotWindow=j;if(q)C.Properties.PreferredMaintenanceWindow=q;return{replicationGroup:C,subnetGroup:S,logicalId:D,subnetGroupId:P}}static createMemcached($){let{slug:J,environment:Y,nodeType:Z="cache.t3.micro",engineVersion:Q="1.6.22",port:G=11211,numCacheNodes:W=2,subnetIds:z,securityGroupIds:U,azMode:H="cross-az",preferredAzs:F,maintenanceWindow:B}=$,K=f({slug:J,environment:Y,resourceType:"memcached"}),O=x(K),V,A;if(z&&z.length>0){let M=f({slug:J,environment:Y,resourceType:"cache-subnet-group"});A=x(M),V={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:M,Description:`Subnet group for ${K}`,SubnetIds:z,Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:Y}]}}}let _={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:K,CacheNodeType:Z,Engine:"memcached",EngineVersion:Q,NumCacheNodes:W,Port:G,AZMode:H,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:K},{Key:"Environment",Value:Y}]}};if(A)_.Properties.CacheSubnetGroupName=l.Ref(A);if(U&&U.length>0)_.Properties.VpcSecurityGroupIds=U;if(F&&F.length>0)_.Properties.PreferredAvailabilityZones=F;if(B)_.Properties.PreferredMaintenanceWindow=B;return{cluster:_,subnetGroup:V,logicalId:O,subnetGroupId:A}}static enableClusterMode($,J=3,Y=2){return delete $.Properties.NumCacheClusters,$.Properties.NumNodeGroups=J,$.Properties.ReplicasPerNodeGroup=Y,$}static createRedisParameterGroup($,J){let{slug:Y,environment:Z,parameters:Q={}}=J,G=f({slug:Y,environment:Z,resourceType:"redis-params"}),W=x(G);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${$.split(".")[0]}.x`,Description:`Parameter group for ${G}`,Properties:Q,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z}]}},logicalId:W}}static createMemcachedParameterGroup($,J){let{slug:Y,environment:Z,parameters:Q={}}=J,G=f({slug:Y,environment:Z,resourceType:"memcached-params"}),W=x(G);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${$.split(".")[0]}.${$.split(".")[1]}`,Description:`Parameter group for ${G}`,Properties:Q,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z}]}},logicalId:W}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}};R1=class R1{static createUser($){let{slug:J,environment:Y,userName:Z,groups:Q,managedPolicyArns:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"user"}),z=x(W),U={Type:"AWS::IAM::User",Properties:{UserName:W,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:Y}]}};if(Q&&Q.length>0)U.Properties.Groups=Q;if(G&&G.length>0)U.Properties.ManagedPolicyArns=G;return{user:U,logicalId:z}}static createRole($){let{slug:J,environment:Y,roleName:Z,servicePrincipal:Q,awsPrincipal:G,managedPolicyArns:W}=$,z=Z||f({slug:J,environment:Y,resourceType:"role"}),U=x(z),H={};if(Q)H.Service=Q;if(G)H.AWS=G;let F={Type:"AWS::IAM::Role",Properties:{RoleName:z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:H,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(W&&W.length>0)F.Properties.ManagedPolicyArns=W;return{role:F,logicalId:U}}static createGroup($){let{slug:J,environment:Y,groupName:Z,managedPolicyArns:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"group"}),W=x(G),z={Type:"AWS::IAM::Group",Properties:{GroupName:G}};if(Q&&Q.length>0)z.Properties.ManagedPolicyArns=Q;return{group:z,logicalId:W}}static createPolicy($){let{slug:J,environment:Y,policyName:Z,description:Q,statements:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"policy"}),z=x(W),U=G.map((F)=>({Sid:F.sid,Effect:F.effect||"Allow",Action:F.actions,Resource:F.resources,Condition:F.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:W,Description:Q||`Managed policy for ${W}`,PolicyDocument:{Version:"2012-10-17",Statement:U}}},logicalId:z}}static attachPolicyToRole($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToUser($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToGroup($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static addInlinePolicyToRole($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Z=Y.map((Q)=>({Effect:Q.effect||"Allow",Action:Q.actions,Resource:Q.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Z}}),$}static addInlinePolicyToUser($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Z=Y.map((Q)=>({Effect:Q.effect||"Allow",Action:Q.actions,Resource:Q.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Z}}),$}static createAccessKey($,J){let{slug:Y,environment:Z,status:Q="Active"}=J,G=f({slug:Y,environment:Z,resourceType:"access-key"}),W=x(G);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:l.Ref($),Status:Q}},logicalId:W}}static createInstanceProfile($,J){let{slug:Y,environment:Z,profileName:Q}=J,G=Q||f({slug:Y,environment:Z,resourceType:"instance-profile"}),W=x(G);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:G,Roles:[l.Ref($)]}},logicalId:W}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser($){let{slug:J,environment:Y,permissions:Z,createAccessKey:Q=!0}=$,G={},W=[];if(Z.s3Buckets&&Z.s3Buckets.length>0)W.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...Z.s3Buckets,...Z.s3Buckets.map((O)=>`${O}/*`)]});if(Z.cloudFrontDistributions&&Z.cloudFrontDistributions.length>0)W.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:Z.cloudFrontDistributions});if(Z.ecrRepositories&&Z.ecrRepositories.length>0)W.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:Z.ecrRepositories}),W.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(Z.ecsServices&&Z.ecsServices.length>0)W.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:Z.ecsServices}),W.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),W.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(Z.cloudFormationStacks&&Z.cloudFormationStacks.length>0)W.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:Z.cloudFormationStacks});if(Z.lambdaFunctions&&Z.lambdaFunctions.length>0)W.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:Z.lambdaFunctions});if(Z.secretsManagerSecrets&&Z.secretsManagerSecrets.length>0)W.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:Z.secretsManagerSecrets});let{policy:z,logicalId:U}=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${J} (${Y})`,statements:W});G[U]=z;let{user:H,logicalId:F}=R1.createUser({slug:J,environment:Y,userName:f({slug:J,environment:Y,resourceType:"cicd-user"}),managedPolicyArns:[l.Ref(U)]});G[F]=H;let B,K;if(Q){let O=R1.createAccessKey(F,{slug:J,environment:Y});B=O.accessKey,K=O.logicalId,G[K]=B}return{user:H,accessKey:B,policy:z,userLogicalId:F,accessKeyLogicalId:K,policyLogicalId:U,resources:G}}static createCrossAccountRole($){let{slug:J,environment:Y,trustedAccountIds:Z,externalId:Q,permissions:G,maxSessionDuration:W=3600}=$,z={},{policy:U,logicalId:H}=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${J} (${Y})`,statements:G});z[H]=U;let F=f({slug:J,environment:Y,resourceType:"cross-account-role"}),B=x(F),K={};if(Q)K.StringEquals={"sts:ExternalId":Q};let O={Type:"AWS::IAM::Role",Properties:{RoleName:F,MaxSessionDuration:W,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:Z.map((V)=>`arn:aws:iam::${V}:root`)},Action:"sts:AssumeRole",...Object.keys(K).length>0?{Condition:K}:{}}]},ManagedPolicyArns:[l.Ref(H)],Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:Y},{Key:"Purpose",Value:"Cross-Account Access"}]}};return z[B]=O,{role:O,policy:U,roleLogicalId:B,policyLogicalId:H,resources:z}}static createCliUser($){let{slug:J,environment:Y,permissions:Z="readonly"}=$,Q={},G=[],W=[];switch(Z){case"readonly":W=[R1.ManagedPolicies.ReadOnlyAccess];break;case"deploy":G=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":W=[R1.ManagedPolicies.AdministratorAccess];break}let z,U;if(G.length>0){let O=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cli-policy"}),description:`CLI access policy for ${J} (${Y})`,statements:G});z=O.policy,U=O.logicalId,Q[U]=z,W=[l.Ref(U)]}let{user:H,logicalId:F}=R1.createUser({slug:J,environment:Y,userName:f({slug:J,environment:Y,resourceType:"cli-user"}),managedPolicyArns:W});Q[F]=H;let{accessKey:B,logicalId:K}=R1.createAccessKey(F,{slug:J,environment:Y});return Q[K]=B,{user:H,accessKey:B,policy:z,userLogicalId:F,accessKeyLogicalId:K,policyLogicalId:U,resources:Q}}static CiCdPolicies={s3Deployment:($)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:$},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:$.map((J)=>`${J}/*`)}],cloudFrontInvalidation:($)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:$}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:($)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:$}],lambdaDeployment:($)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:$}],cloudFormationDeployment:($)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:$}]}};c6=class c6{static createRestApi($){let{slug:J,environment:Y,name:Z,description:Q,endpointType:G="REGIONAL",binaryMediaTypes:W,compressionSize:z}=$,U=Z||f({slug:J,environment:Y,resourceType:"rest-api"}),H=x(U),F={Type:"AWS::ApiGateway::RestApi",Properties:{Name:U,Description:Q||`REST API for ${J} ${Y}`,EndpointConfiguration:{Types:[G]},Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:Y}]}};if(W&&W.length>0)F.Properties.BinaryMediaTypes=W;if(z!==void 0)F.Properties.MinimumCompressionSize=z;return{restApi:F,logicalId:H}}static createHttpApi($){let{slug:J,environment:Y,name:Z,description:Q,corsEnabled:G=!0,corsOrigins:W=["*"],corsMethods:z=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:U=["*"],corsMaxAge:H=86400,corsAllowCredentials:F=!1}=$,B=Z||f({slug:J,environment:Y,resourceType:"http-api"}),K=x(B),O={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:B,Description:Q||`HTTP API for ${J} ${Y}`,ProtocolType:"HTTP",Tags:{Name:B,Environment:Y}}};if(G)O.Properties.CorsConfiguration={AllowOrigins:W,AllowMethods:z,AllowHeaders:U,MaxAge:H,AllowCredentials:F};return{httpApi:O,logicalId:K}}static createWebSocketApi($){let{slug:J,environment:Y,name:Z,description:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"ws-api"}),W=x(G);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:G,Description:Q||`WebSocket API for ${J} ${Y}`,ProtocolType:"WEBSOCKET",Tags:{Name:G,Environment:Y}}},logicalId:W}}static createDeployment($,J){let{slug:Y,environment:Z,description:Q}=J,G=f({slug:Y,environment:Z,resourceType:"api-deployment"}),W=x(G);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:l.Ref($),Description:Q||`Deployment for ${G}`}},logicalId:W}}static createStage($,J,Y){let{slug:Z,environment:Q,stageName:G,description:W,cacheEnabled:z=!1,cacheSize:U="0.5",variables:H,throttling:F}=Y,B=f({slug:Z,environment:Q,resourceType:"api-stage"}),K=x(B),O={Type:"AWS::ApiGateway::Stage",Properties:{StageName:G||Q,RestApiId:l.Ref($),DeploymentId:l.Ref(J),Description:W,CacheClusterEnabled:z,Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:Q}]}};if(z)O.Properties.CacheClusterSize=U;if(H)O.Properties.Variables=H;if(F)O.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:F.burstLimit,ThrottlingRateLimit:F.rateLimit}];return{stage:O,logicalId:K}}static createAuthorizer($,J){let{slug:Y,environment:Z,name:Q,type:G,functionArn:W,identitySource:z,userPoolArns:U,ttl:H=300}=J,F=Q||f({slug:Y,environment:Z,resourceType:"api-authorizer"}),B=x(F),K={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:F,Type:G,RestApiId:l.Ref($),AuthorizerResultTtlInSeconds:H}};if(G==="TOKEN"||G==="REQUEST"){if(!W)throw Error("Lambda authorizer requires functionArn");K.Properties.AuthorizerUri=W,K.Properties.IdentitySource=z||"method.request.header.Authorization"}if(G==="COGNITO_USER_POOLS"){if(!U||U.length===0)throw Error("Cognito authorizer requires userPoolArns");K.Properties.ProviderARNs=U,K.Properties.IdentitySource=z||"method.request.header.Authorization"}return{authorizer:K,logicalId:B}}static setCors($,J={}){let{origins:Y=["*"],methods:Z=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:Q=["*"],maxAge:G=86400,allowCredentials:W=!1}=J;return $.Properties.CorsConfiguration={AllowOrigins:Y,AllowMethods:Z,AllowHeaders:Q,MaxAge:G,AllowCredentials:W},$}static addThrottling($,J=5000,Y=1e4){if(!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:J,ThrottlingRateLimit:Y}),$}static enableCaching($,J="0.5",Y=300){if($.Properties.CacheClusterEnabled=!0,$.Properties.CacheClusterSize=J,!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:Y}),$}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}};D1=class D1{static createTopic($){let{slug:J,environment:Y,topicName:Z,displayName:Q,encrypted:G=!1,kmsKeyId:W}=$,z=Z||f({slug:J,environment:Y,resourceType:"topic"}),U=x(z),H={Type:"AWS::SNS::Topic",Properties:{TopicName:z,DisplayName:Q||z,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(G&&W)H.Properties.KmsMasterKeyId=W;return{topic:H,logicalId:U}}static subscribe($,J){let{slug:Y,environment:Z,protocol:Q,endpoint:G,filterPolicy:W,rawMessageDelivery:z=!1}=J,U=f({slug:Y,environment:Z,resourceType:"subscription"}),H=G.replace(/[^a-zA-Z0-9]/g,""),F=H.length>12?H.slice(-12):H,B=x(`${U}-${Q}-${F}`),K={Type:"AWS::SNS::Subscription",Properties:{TopicArn:l.Ref($),Protocol:Q,Endpoint:G,RawMessageDelivery:z}};if(W)K.Properties.FilterPolicy=W;return{subscription:K,logicalId:B}}static subscribeEmail($,J,Y){return D1.subscribe($,{...Y,protocol:"email",endpoint:J})}static subscribeLambda($,J,Y){return D1.subscribe($,{...Y,protocol:"lambda",endpoint:J,rawMessageDelivery:!0})}static subscribeSqs($,J,Y){return D1.subscribe($,{...Y,protocol:"sqs",endpoint:J})}static subscribeHttp($,J,Y){let Z=J.startsWith("https://")?"https":"http";return D1.subscribe($,{...Y,protocol:Z,endpoint:J})}static subscribeSms($,J,Y){return D1.subscribe($,{...Y,protocol:"sms",endpoint:J})}static setTopicPolicy($,J){let{slug:Y,environment:Z,allowedPrincipals:Q,allowedServices:G,actions:W="SNS:Publish"}=J,z=f({slug:Y,environment:Z,resourceType:"topic-policy"}),U=x(z),H={};if(Q)H.AWS=Q;if(G)H.Service=G;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[l.Ref($)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:H,Action:W,Resource:l.Ref($)}]}}},logicalId:U}}static allowCloudWatchAlarms($,J){return D1.setTopicPolicy($,{...J,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge($,J){return D1.setTopicPolicy($,{...J,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3($,J){return D1.setTopicPolicy($,{...J,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption($,J){if(!$.Properties)$.Properties={};return $.Properties.KmsMasterKeyId=J,$}static addInlineSubscription($,J,Y){if(!$.Properties)$.Properties={};if(!$.Properties.Subscription)$.Properties.Subscription=[];return $.Properties.Subscription.push({Protocol:J,Endpoint:Y}),$}static FilterPolicies={eventType:($)=>({eventType:$}),status:($)=>({status:$}),numericRange:($,J,Y)=>({[$]:[{numeric:[">=",J,"<=",Y]}]}),prefix:($,J)=>({[$]:[{prefix:J}]}),and:(...$)=>{return Object.assign({},...$)},exists:($,J)=>({[$]:[{exists:J}]})};static UseCases={createAlertTopic:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-alerts`,displayName:$.displayName||"Alert Notifications"})},createEventFanout:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-events`,displayName:$.displayName||"Event Fanout"})},createNotificationTopic:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-notifications`,displayName:$.displayName||"User Notifications"})}}};Tz=class Tz{static createStateMachine($){let{slug:J,environment:Y,stateMachineName:Z,type:Q="STANDARD",definition:G,roleArn:W,loggingConfiguration:z,tracingConfiguration:U}=$,H=Z||f({slug:J,environment:Y,resourceType:"state-machine"}),F=x(H),B,K,O;if(W)O=W;else{let A=f({slug:J,environment:Y,resourceType:"state-machine-role"});K=x(A),B={Type:"AWS::IAM::Role",Properties:{RoleName:A,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:Y}]}},O=l.GetAtt(K,"Arn")}let V={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:H,StateMachineType:Q,DefinitionString:JSON.stringify(G),RoleArn:O,Tags:[{Key:"Name",Value:H},{Key:"Environment",Value:Y}]}};if(z)V.Properties.LoggingConfiguration={Level:z.level,IncludeExecutionData:z.includeExecutionData,Destinations:z.destinations?.map((A)=>({CloudWatchLogsLogGroup:{LogGroupArn:A}}))};if(U)V.Properties.TracingConfiguration={Enabled:U.enabled};return{stateMachine:V,logicalId:F,role:B,roleLogicalId:K}}static createLambdaTask($,J){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:$,Payload:J?.parameters||{"Input.$":"$"}},ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createDynamoDBTask($,J,Y,Z){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[$],Parameters:{TableName:J,...Y},ResultPath:Z?.resultPath,Retry:Z?.retry,Catch:Z?.catch,Next:Z?.next,End:Z?.end}}static createSNSPublishTask($,J,Y){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:$,Message:J},ResultPath:Y?.resultPath,Retry:Y?.retry,Catch:Y?.catch,Next:Y?.next,End:Y?.end}}static createSQSSendMessageTask($,J,Y){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:$,MessageBody:J},ResultPath:Y?.resultPath,Retry:Y?.retry,Catch:Y?.catch,Next:Y?.next,End:Y?.end}}static createPassState($){return{Type:"Pass",Result:$?.result,ResultPath:$?.resultPath,Parameters:$?.parameters,Next:$?.next,End:$?.end}}static createWaitState($){return{Type:"Wait",Seconds:$.seconds,Timestamp:$.timestamp,SecondsPath:$.secondsPath,TimestampPath:$.timestampPath,Next:$.next,End:$.end}}static createChoiceState($,J){return{Type:"Choice",Choices:$,Default:J}}static createParallelState($,J){return{Type:"Parallel",Branches:$,ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createMapState($,J){return{Type:"Map",ItemsPath:J?.itemsPath||"$.items",Iterator:$,MaxConcurrency:J?.maxConcurrency,ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState($,J){return{Type:"Fail",Error:$,Cause:J}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:($,J,Y,Z)=>({ErrorEquals:$,IntervalSeconds:J,MaxAttempts:Y,BackoffRate:Z})};static CatchPolicies={all:($,J)=>({ErrorEquals:["States.ALL"],Next:$,ResultPath:J||"$.error"}),specific:($,J,Y)=>({ErrorEquals:$,Next:J,ResultPath:Y||"$.error"})};static Patterns={sequential:($,J,Y)=>{let Z={};return Y.forEach((Q,G)=>{let W=G===Y.length-1;Z[Q.name]={...Q.state,Next:W?void 0:Y[G+1].name,End:W}}),{Comment:"Sequential workflow",StartAt:Y[0].name,States:Z}},fanout:($,J,Y)=>{return{Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:Y.map((Z)=>Z.definition),End:!0}}}},map:($,J,Y,Z)=>{return{Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:Y,MaxConcurrency:Z,End:!0}}}},withErrorHandling:($,J,Y,Z)=>{return{Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...Y,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:Z,Success:{Type:"Succeed"}}}}}};u8=class u8{static createAlarm($){let{slug:J,environment:Y,alarmName:Z,metricName:Q,namespace:G,statistic:W="Average",period:z=300,evaluationPeriods:U=1,threshold:H,comparisonOperator:F,treatMissingData:B="notBreaching",actionsEnabled:K=!0,alarmActions:O,okActions:V,insufficientDataActions:A,dimensions:_,unit:M,datapointsToAlarm:E}=$,j=Z||f({slug:J,environment:Y,resourceType:"alarm"}),q=x(j),T={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:j,MetricName:Q,Namespace:G,Statistic:W,Period:z,EvaluationPeriods:U,Threshold:H,ComparisonOperator:F,TreatMissingData:B,ActionsEnabled:K}};if(O&&O.length>0)T.Properties.AlarmActions=O;if(V&&V.length>0)T.Properties.OKActions=V;if(A&&A.length>0)T.Properties.InsufficientDataActions=A;if(_)T.Properties.Dimensions=Object.entries(_).map(([D,S])=>({Name:D,Value:S}));if(M)T.Properties.Unit=M;if(E!==void 0)T.Properties.DatapointsToAlarm=E;return{alarm:T,logicalId:q}}static createCompositeAlarm($){let{slug:J,environment:Y,alarmName:Z,alarmRule:Q,actionsEnabled:G=!0,alarmActions:W,okActions:z,insufficientDataActions:U}=$,H=Z||f({slug:J,environment:Y,resourceType:"composite-alarm"}),F=x(H),B={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:H,AlarmRule:Q,ActionsEnabled:G}};if(W&&W.length>0)B.Properties.AlarmActions=W;if(z&&z.length>0)B.Properties.OKActions=z;if(U&&U.length>0)B.Properties.InsufficientDataActions=U;return{alarm:B,logicalId:F}}static createDashboard($){let{slug:J,environment:Y,dashboardName:Z,widgets:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"dashboard"}),W=x(G),z={widgets:Q.map((H)=>({type:H.type,x:H.x,y:H.y,width:H.width,height:H.height,properties:H.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:G,DashboardBody:JSON.stringify(z)}},logicalId:W}}static createLogGroup($){let{slug:J,environment:Y,logGroupName:Z,retentionInDays:Q,kmsKeyId:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"log-group"}),z=x(W),U={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:W}};if(Q!==void 0)U.Properties.RetentionInDays=Q;if(G)U.Properties.KmsKeyId=G;return{logGroup:U,logicalId:z}}static createLogStream($,J){let{slug:Y,environment:Z,logStreamName:Q}=J,G=Q||f({slug:Y,environment:Z,resourceType:"log-stream"}),W=x(G);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:l.Ref($),LogStreamName:G}},logicalId:W}}static createMetricFilter($,J){let{slug:Y,environment:Z,filterName:Q,filterPattern:G,metricTransformations:W}=J,z=Q||f({slug:Y,environment:Z,resourceType:"metric-filter"}),U=x(z);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:l.Ref($),FilterPattern:G,MetricTransformations:W.map((F)=>({MetricName:F.metricName,MetricNamespace:F.metricNamespace,MetricValue:F.metricValue,DefaultValue:F.defaultValue,Unit:F.unit}))}},logicalId:U}}static AlarmTypes={highCpu:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0}),highMemory:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0}),highDisk:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:Q?[Q]:void 0}),lambdaErrors:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:Q?[Q]:void 0}),lambdaThrottles:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:Q?[Q]:void 0}),apiGateway5xxErrors:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:Q?[Q]:void 0}),apiGateway4xxErrors:($,J,Y,Z=50,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:Q?[Q]:void 0}),dynamoDBThrottles:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:Y},alarmActions:Q?[Q]:void 0}),rdsCpu:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:Q?[Q]:void 0}),rdsFreeStorage:($,J,Y,Z=5368709120,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:Q?[Q]:void 0,unit:"Bytes"}),sqsQueueDepth:($,J,Y,Z=100,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:Y},alarmActions:Q?[Q]:void 0}),albUnhealthyTargets:($,J,Y,Z,Q=1,G)=>({slug:$,environment:J,alarmName:`${$}-${J}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:Y,TargetGroup:Z},alarmActions:G?[G]:void 0}),sesBounceRate:($,J,Y=5,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),sesComplaintRate:($,J,Y=0.1,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),smsDeliveryFailure:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:Y},alarmActions:Q?[Q]:void 0}),smsSpendLimit:($,J,Y=100,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:Y,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),connectMissedCalls:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0})};static DashboardWidgets={metric:($,J,Y,Z,Q,G)=>({type:"metric",x:$,y:J,width:Y,height:Z,properties:{metrics:Q,title:G||"Metrics",region:"us-east-1",period:300}}),text:($,J,Y,Z,Q)=>({type:"text",x:$,y:J,width:Y,height:Z,properties:{markdown:Q}}),log:($,J,Y,Z,Q,G)=>({type:"log",x:$,y:J,width:Y,height:Z,properties:{query:`SOURCE '${Q.join("' | SOURCE '")}'
|
|
5840
|
+
`}};Mz={};G$(Mz,{handler:()=>IJ,default:()=>bA});bA=IJ;Y2=class Y2{static LambdaCode={incomingCall:IJ,voicemail:yA,missedCall:vA};static createConnectInstance($){let{slug:J,environment:Y,instanceAlias:Z,inboundCallsEnabled:Q=!0,outboundCallsEnabled:G=!0}=$;return{[`${J}ConnectInstance`]:{Type:"AWS::Connect::Instance",Properties:{InstanceAlias:Z,IdentityManagementType:"CONNECT_MANAGED",Attributes:{InboundCalls:Q,OutboundCalls:G,ContactflowLogs:!0,ContactLens:!0,AutoResolveBestVoices:!0,UseCustomTTSVoices:!1,EarlyMedia:!0}}}}}static createHoursOfOperation($){return{[`${$.slug}HoursOfOperation`]:{Type:"AWS::Connect::HoursOfOperation",Properties:{InstanceArn:$.instanceArn,Name:$.name,TimeZone:$.timezone,Config:$.schedule.map((J)=>({Day:J.day,StartTime:{Hours:J.startHour,Minutes:J.startMinute},EndTime:{Hours:J.endHour,Minutes:J.endMinute}}))}}}}static createQueue($){return{[`${$.slug}Queue`]:{Type:"AWS::Connect::Queue",Properties:{InstanceArn:$.instanceArn,Name:$.name,HoursOfOperationArn:$.hoursOfOperationArn,MaxContacts:$.maxContacts||10}}}}static createContactFlow($){return{[`${$.slug}ContactFlow`]:{Type:"AWS::Connect::ContactFlow",Properties:{InstanceArn:$.instanceArn,Name:$.name,Type:$.type,Content:$.content}}}}static createBasicIvrFlow($){let J={Version:"2019-10-30",StartAction:"greeting",Actions:[{Identifier:"greeting",Type:"MessageParticipant",Parameters:{Text:$.greeting},Transitions:{NextAction:"transfer_to_queue",Errors:[{NextAction:"disconnect"}]}},{Identifier:"transfer_to_queue",Type:"TransferToQueue",Parameters:{QueueId:$.queueArn},Transitions:{NextAction:$.voicemailLambdaArn?"voicemail":"disconnect",Errors:[{NextAction:"disconnect"}]}},...$.voicemailLambdaArn?[{Identifier:"voicemail",Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:$.voicemailLambdaArn},Transitions:{NextAction:"disconnect",Errors:[{NextAction:"disconnect"}]}}]:[],{Identifier:"disconnect",Type:"DisconnectParticipant",Parameters:{},Transitions:{}}]};return JSON.stringify(J)}static createPhoneLambdaRole($){return{[`${$.slug}PhoneLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${$.slug}-phone-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"PhoneLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["s3:GetObject","s3:PutObject"],Resource:"*"},{Effect:"Allow",Action:["transcribe:StartTranscriptionJob","transcribe:GetTranscriptionJob"],Resource:"*"},{Effect:"Allow",Action:["connect:*"],Resource:"*"}]}}]}}}}static createIncomingCallLambda($){return{[`${$.slug}IncomingCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-incoming-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Y2.LambdaCode.incomingCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createVoicemailLambda($){return{[`${$.slug}VoicemailLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-voicemail`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:300,MemorySize:512,Code:{ZipFile:Y2.LambdaCode.voicemail},Environment:{Variables:{VOICEMAIL_BUCKET:$.voicemailBucket,NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",TRANSCRIPTION_ENABLED:$.transcriptionEnabled?"true":"false"}}}}}}static createMissedCallLambda($){return{[`${$.slug}MissedCallLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-missed-call`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:Y2.LambdaCode.missedCall},Environment:{Variables:{NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",CALL_LOG_TABLE:$.callLogTable||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createCallLogTable($){return{[`${$.slug}CallLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-call-log`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"contactId",AttributeType:"S"}],KeySchema:[{AttributeName:"contactId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createCompleteSetup($){let J={},Y={};Object.assign(J,Y2.createPhoneLambdaRole({slug:$.slug})),Object.assign(J,Y2.createCallLogTable({slug:$.slug})),J[`${$.slug}PhoneNotificationTopic`]={Type:"AWS::SNS::Topic",Properties:{TopicName:`${$.slug}-phone-notifications`}},J[`${$.slug}VoicemailBucket`]={Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-voicemails`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldVoicemails",Status:"Enabled",ExpirationInDays:90}]}}};let Z={"Fn::GetAtt":[`${$.slug}PhoneLambdaRole`,"Arn"]},Q={Ref:`${$.slug}PhoneNotificationTopic`},G={Ref:`${$.slug}CallLogTable`},W={Ref:`${$.slug}VoicemailBucket`};if(Object.assign(J,Y2.createIncomingCallLambda({slug:$.slug,roleArn:Z,notificationTopicArn:Q,callLogTable:G,webhookUrl:$.webhookUrl})),$.voicemailEnabled!==!1)Object.assign(J,Y2.createVoicemailLambda({slug:$.slug,roleArn:Z,voicemailBucket:W,notificationTopicArn:Q,callLogTable:G,transcriptionEnabled:$.transcriptionEnabled}));return Object.assign(J,Y2.createMissedCallLambda({slug:$.slug,roleArn:Z,notificationTopicArn:Q,callLogTable:G,webhookUrl:$.webhookUrl})),Y[`${$.slug}PhoneNotificationTopicArn`]={Description:"Phone notification topic ARN",Value:{Ref:`${$.slug}PhoneNotificationTopic`}},Y[`${$.slug}CallLogTableName`]={Description:"Call log table name",Value:{Ref:`${$.slug}CallLogTable`}},Y[`${$.slug}VoicemailBucketName`]={Description:"Voicemail bucket name",Value:{Ref:`${$.slug}VoicemailBucket`}},{resources:J,outputs:Y}}};_1=class _1{static createQueue($){let{slug:J,environment:Y,name:Z,delaySeconds:Q=0,visibilityTimeout:G=30,messageRetentionPeriod:W=345600,maxMessageSize:z=262144,receiveMessageWaitTime:U=0,fifo:H=!1,contentBasedDeduplication:F=!1,encrypted:B=!0,kmsKeyId:K}=$,O=Z||f({slug:J,environment:Y,resourceType:"queue"}),V=H?`${O}.fifo`:O,A=x(O),_={Type:"AWS::SQS::Queue",Properties:{QueueName:V,DelaySeconds:Q,MaximumMessageSize:z,MessageRetentionPeriod:W,ReceiveMessageWaitTimeSeconds:U,VisibilityTimeout:G,Tags:[{Key:"Name",Value:V},{Key:"Environment",Value:Y}]}};if(H)_.Properties.FifoQueue=!0,_.Properties.ContentBasedDeduplication=F;if(B)if(K)_.Properties.KmsMasterKeyId=K;else _.Properties.SqsManagedSseEnabled=!0;return{queue:_,logicalId:A}}static createDeadLetterQueue($,J){let{slug:Y,environment:Z,maxReceiveCount:Q=3}=J,G=f({slug:Y,environment:Z,resourceType:"dlq"}),W=x(G),z={Type:"AWS::SQS::Queue",Properties:{QueueName:G,MessageRetentionPeriod:1209600,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z},{Key:"Type",Value:"DeadLetterQueue"}]}},U={Type:"AWS::SQS::Queue",Properties:{RedrivePolicy:{deadLetterTargetArn:l.GetAtt(W,"Arn"),maxReceiveCount:Q}}};return{deadLetterQueue:z,updatedSourceQueue:U,deadLetterLogicalId:W}}static createSchedule($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0}=J,z=Q||f({slug:Y,environment:Z,resourceType:"schedule"}),U=x(z);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:z,Description:G,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[]}},logicalId:U}}static scheduleEcsTask($,J,Y){let{slug:Z,environment:Q,name:G,description:W,enabled:z=!0,taskDefinitionArn:U,clusterArn:H,subnets:F,securityGroups:B=[],assignPublicIp:K=!1,taskCount:O=1,containerOverrides:V}=Y,A=G||f({slug:Z,environment:Q,resourceType:"ecs-schedule"}),_=x(A),E={Id:"1",Arn:H,RoleArn:J,EcsParameters:{TaskDefinitionArn:U,TaskCount:O,LaunchType:"FARGATE",NetworkConfiguration:{awsvpcConfiguration:{Subnets:F,SecurityGroups:B,AssignPublicIp:K?"ENABLED":"DISABLED"}},PlatformVersion:"LATEST"}};if(V&&V.length>0)E.Input=JSON.stringify({containerOverrides:V});return{rule:{Type:"AWS::Events::Rule",Properties:{Name:A,Description:W||`Scheduled ECS task: ${U}`,ScheduleExpression:$,State:z?"ENABLED":"DISABLED",Targets:[E]}},logicalId:_}}static scheduleLambda($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0,functionArn:z,input:U}=J,H=Q||f({slug:Y,environment:Z,resourceType:"lambda-schedule"}),F=x(H),B={Id:"1",Arn:z};if(U)B.Input=JSON.stringify(U);return{rule:{Type:"AWS::Events::Rule",Properties:{Name:H,Description:G||`Scheduled Lambda: ${z}`,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[B]}},logicalId:F}}static scheduleSqsMessage($,J){let{slug:Y,environment:Z,name:Q,description:G,enabled:W=!0,queueArn:z,messageGroupId:U}=J,H=Q||f({slug:Y,environment:Z,resourceType:"sqs-schedule"}),F=x(H),B={Id:"1",Arn:z};if(U)B.SqsParameters={MessageGroupId:U};return{rule:{Type:"AWS::Events::Rule",Properties:{Name:H,Description:G||`Scheduled SQS message: ${z}`,ScheduleExpression:$,State:W?"ENABLED":"DISABLED",Targets:[B]}},logicalId:F}}static addTarget($,J){if(!$.Properties.Targets)$.Properties.Targets=[];let Y={Id:J.id,Arn:J.arn};if(J.roleArn)Y.RoleArn=J.roleArn;if(J.input)Y.Input=JSON.stringify(J.input);return $.Properties.Targets.push(Y),$}static toCronExpression($){if($.startsWith("cron(")||$.startsWith("rate("))return $;return`cron(${$})`}static rateExpression($,J){return`rate(${$} ${J})`}static CronExpressions={EveryMinute:"cron(* * * * ? *)",Every5Minutes:"cron(*/5 * * * ? *)",Every15Minutes:"cron(*/15 * * * ? *)",Every30Minutes:"cron(*/30 * * * ? *)",Hourly:"cron(0 * * * ? *)",Daily:"cron(0 0 * * ? *)",DailyAt9AM:"cron(0 9 * * ? *)",DailyAtMidnight:"cron(0 0 * * ? *)",Weekly:"cron(0 0 ? * SUN *)",Monthly:"cron(0 0 1 * ? *)"};static RateExpressions={Every1Minute:"rate(1 minute)",Every5Minutes:"rate(5 minutes)",Every10Minutes:"rate(10 minutes)",Every15Minutes:"rate(15 minutes)",Every30Minutes:"rate(30 minutes)",Every1Hour:"rate(1 hour)",Every6Hours:"rate(6 hours)",Every12Hours:"rate(12 hours)",Every1Day:"rate(1 day)"};static rateStringToExpression($){let J=$.toLowerCase().trim(),Y=J.match(/^every\s+(\d+)\s+(minute|minutes|hour|hours|day|days)$/i);if(Y){let H=parseInt(Y[1],10),F=Y[2].toLowerCase(),B=F.endsWith("s")&&H===1?F.slice(0,-1):F,K=!F.endsWith("s")&&H>1?`${F}s`:F;return`rate(${H} ${H===1?B:K})`}let Z=J.match(/^every\s+(minute|hour|day)$/i);if(Z)return`rate(1 ${Z[1]})`;let Q={"every minute":"rate(1 minute)","every hour":"rate(1 hour)","every day":"rate(1 day)",hourly:"cron(0 * * * ? *)",daily:"cron(0 0 * * ? *)","daily at midnight":"cron(0 0 * * ? *)",weekly:"cron(0 0 ? * SUN *)",monthly:"cron(0 0 1 * ? *)",yearly:"cron(0 0 1 1 ? *)"};if(Q[J])return Q[J];let G=J.match(/^daily\s+at\s+(\d{1,2})\s*(am|pm)?$/i);if(G){let H=parseInt(G[1],10),F=G[2]?.toLowerCase();if(F==="pm"&&H!==12)H+=12;else if(F==="am"&&H===12)H=0;return`cron(0 ${H} * * ? *)`}let W=J.match(/^at\s+(\d{1,2}):(\d{2})$/i);if(W){let H=parseInt(W[1],10);return`cron(${parseInt(W[2],10)} ${H} * * ? *)`}let z={monday:"MON",tuesday:"TUE",wednesday:"WED",thursday:"THU",friday:"FRI",saturday:"SAT",sunday:"SUN"},U=J.match(/^every\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/i);if(U)return`cron(0 0 ? * ${z[U[1].toLowerCase()]} *)`;return _1.toCronExpression($)}static JobConfig={create:($)=>{let{name:J,handler:Y,retries:Z=3,backoff:Q="exponential",backoffDelay:G=1000,maxDelay:W=30000,timeout:z=60000,jitter:U=!0}=$;return{name:J,handler:Y,retries:Z,backoff:Q,backoffDelay:G,maxDelay:W,timeout:z,jitter:U}},calculateDelay:($,J)=>{let{backoff:Y,backoffDelay:Z,maxDelay:Q,jitter:G}=J,W;switch(Y){case"linear":W=Z*$;break;case"exponential":W=Z*2**($-1);break;case"fixed":default:W=Z}if(W=Math.min(W,Q||Number.MAX_SAFE_INTEGER),G){let z=W*0.25*Math.random();W+=z}return Math.floor(W)},presets:{fastRetry:{retries:5,backoff:"exponential",backoffDelay:100,maxDelay:5000,jitter:!0},standard:{retries:3,backoff:"exponential",backoffDelay:1000,maxDelay:30000,jitter:!0},longRunning:{retries:2,backoff:"exponential",backoffDelay:5000,maxDelay:60000,timeout:300000,jitter:!0},critical:{retries:10,backoff:"exponential",backoffDelay:500,maxDelay:60000,jitter:!0},noRetry:{retries:0,backoff:"fixed",backoffDelay:0,maxDelay:0,jitter:!1}}};static createJobContainerOverride($){let{containerName:J,jobClass:Y,jobData:Z,environment:Q={}}=$,G=[{name:"JOB_CLASS",value:Y}];if(Z)G.push({name:"JOB_DATA",value:JSON.stringify(Z)});for(let[W,z]of Object.entries(Q))G.push({name:W,value:z});return{name:J,command:["bun","run","app/Jobs/runner.ts"],environment:G}}static createScheduledJob($){let{slug:J,environment:Y,schedule:Z,jobClass:Q,jobData:G,taskDefinitionArn:W,clusterArn:z,subnets:U,securityGroups:H=[],roleArn:F,containerName:B="app"}=$,K=_1.rateStringToExpression(Z),O=_1.createJobContainerOverride({containerName:B,jobClass:Q,jobData:G});return _1.scheduleEcsTask(K,F,{slug:J,environment:Y,name:`${J}-${Q.toLowerCase().replace(/[^a-z0-9]/g,"-")}`,description:`Scheduled job: ${Q}`,taskDefinitionArn:W,clusterArn:z,subnets:U,securityGroups:H,containerOverrides:[O]})}static QueuePresets={highThroughput:($,J)=>_1.createQueue({slug:$,environment:J,visibilityTimeout:30,receiveMessageWaitTime:0,delaySeconds:0}),longRunning:($,J)=>_1.createQueue({slug:$,environment:J,visibilityTimeout:300,messageRetentionPeriod:1209600}),fifo:($,J)=>_1.createQueue({slug:$,environment:J,fifo:!0,contentBasedDeduplication:!0}),delayed:($,J,Y=60)=>_1.createQueue({slug:$,environment:J,delaySeconds:Y})}};fA={loadJobs:L2.discoverJobs,loadActions:L2.discoverActions,generateScheduledJobs:L2.generateScheduledJobResources,generateRunner:L2.generateJobRunnerScript,paths:{jobs:"app/Jobs",actions:"app/Actions",runner:"app/Jobs/runner.ts"}},qz={};G$(qz,{handler:()=>kJ,default:()=>gA});gA=kJ;B1=class B1{static LambdaCode={send:kJ,receive:uA,deliveryStatus:dA};static createPinpointApp($){return{[`${$.slug}PinpointApp`]:{Type:"AWS::Pinpoint::App",Properties:{Name:$.name||`${$.slug}-sms`}}}}static createSmsChannel($){let J={ApplicationId:$.applicationId,Enabled:$.enabled!==!1};if($.senderId)J.SenderId=$.senderId;if($.shortCode)J.ShortCode=$.shortCode;return{[`${$.slug}SmsChannel`]:{Type:"AWS::Pinpoint::SMSChannel",Properties:J}}}static createSmsLambdaRole($){return{[`${$.slug}SmsLambdaRole`]:{Type:"AWS::IAM::Role",Properties:{RoleName:`${$.slug}-sms-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"SmsLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["mobiletargeting:SendMessages","mobiletargeting:GetSmsChannel"],Resource:"*"},{Effect:"Allow",Action:["sns:Publish"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:GetItem","dynamodb:DeleteItem"],Resource:"*"}]}}]}}}}static createSendLambda($){return{[`${$.slug}SmsSendLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-send`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.send},Environment:{Variables:{PINPOINT_APP_ID:$.pinpointAppId,MESSAGE_LOG_TABLE:$.messageLogTable||"",SMS_SENDER_ID:$.senderId||"",SMS_ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static createReceiveLambda($){return{[`${$.slug}SmsReceiveLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-receive`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.receive},Environment:{Variables:{OPT_OUT_TABLE:$.optOutTable||"",MESSAGE_LOG_TABLE:$.messageLogTable||"",NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createDeliveryStatusLambda($){return{[`${$.slug}SmsDeliveryStatusLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-sms-delivery-status`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:B1.LambdaCode.deliveryStatus},Environment:{Variables:{MESSAGE_LOG_TABLE:$.messageLogTable||"",NOTIFICATION_TOPIC_ARN:$.notificationTopicArn||"",WEBHOOK_URL:$.webhookUrl||""}}}}}}static createMessageLogTable($){return{[`${$.slug}SmsMessageLogTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-messages`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"messageId",AttributeType:"S"}],KeySchema:[{AttributeName:"messageId",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createOptOutTable($){return{[`${$.slug}SmsOptOutTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-sms-optouts`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}]}}}}static createNotificationTopic($){return{[`${$.slug}SmsNotificationTopic`]:{Type:"AWS::SNS::Topic",Properties:{TopicName:`${$.slug}-sms-notifications`}}}}static createCompleteSetup($){let J={},Y={};Object.assign(J,B1.createPinpointApp({slug:$.slug})),Object.assign(J,B1.createSmsChannel({slug:$.slug,applicationId:{Ref:`${$.slug}PinpointApp`},senderId:$.senderId})),Object.assign(J,B1.createSmsLambdaRole({slug:$.slug})),Object.assign(J,B1.createMessageLogTable({slug:$.slug})),Object.assign(J,B1.createOptOutTable({slug:$.slug})),Object.assign(J,B1.createNotificationTopic({slug:$.slug}));let Z={"Fn::GetAtt":[`${$.slug}SmsLambdaRole`,"Arn"]},Q={Ref:`${$.slug}PinpointApp`},G={Ref:`${$.slug}SmsMessageLogTable`},W={Ref:`${$.slug}SmsOptOutTable`},z={Ref:`${$.slug}SmsNotificationTopic`};if(Object.assign(J,B1.createSendLambda({slug:$.slug,roleArn:Z,pinpointAppId:Q,messageLogTable:G,senderId:$.senderId,originationNumber:$.originationNumber})),$.twoWayEnabled)Object.assign(J,B1.createReceiveLambda({slug:$.slug,roleArn:Z,optOutTable:W,messageLogTable:G,notificationTopicArn:z,webhookUrl:$.webhookUrl}));return Object.assign(J,B1.createDeliveryStatusLambda({slug:$.slug,roleArn:Z,messageLogTable:G,notificationTopicArn:z,webhookUrl:$.webhookUrl})),Y[`${$.slug}PinpointAppId`]={Description:"Pinpoint application ID",Value:{Ref:`${$.slug}PinpointApp`}},Y[`${$.slug}SmsSendLambdaArn`]={Description:"SMS send Lambda ARN",Value:{"Fn::GetAtt":[`${$.slug}SmsSendLambda`,"Arn"]}},Y[`${$.slug}SmsNotificationTopicArn`]={Description:"SMS notification topic ARN",Value:{Ref:`${$.slug}SmsNotificationTopic`}},Y[`${$.slug}SmsMessageLogTableName`]={Description:"SMS message log table name",Value:{Ref:`${$.slug}SmsMessageLogTable`}},{resources:J,outputs:Y}}};p1=class p1{static createBedrockRole($,J){let{slug:Y,environment:Z,name:Q,models:G=["*"],allowStreaming:W=!0}=J,z=Q||f({slug:Y,environment:Z,resourceType:"bedrock-role"}),U=x(z),H=["bedrock:InvokeModel"];if(W)H.push("bedrock:InvokeModelWithResponseStream");let F=G.map((K)=>K==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${K}`);return{role:{Type:"AWS::IAM::Role",Properties:{RoleName:z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:$},Action:"sts:AssumeRole"}]},Policies:[{PolicyName:`${z}-policy`,PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:H,Resource:F}]}}],Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Z}]}},logicalId:U}}static createBedrockPolicy($){let{slug:J,environment:Y,name:Z,models:Q=["*"],allowInvoke:G=!0,allowStreaming:W=!0,allowAsync:z=!1}=$,U=Z||f({slug:J,environment:Y,resourceType:"bedrock-policy"}),H=x(U),F=[];if(G)F.push("bedrock:InvokeModel");if(W)F.push("bedrock:InvokeModelWithResponseStream");if(z)F.push("bedrock:InvokeModelAsync");let B=Q.map((O)=>O==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${O}`);return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:U,PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"BedrockModelInvocation",Effect:"Allow",Action:F,Resource:B}]}}},logicalId:H}}static enableBedrockForLambda($){return p1.createBedrockRole("lambda.amazonaws.com",$)}static enableBedrockForEcs($){return p1.createBedrockRole("ecs-tasks.amazonaws.com",$)}static enableBedrockForEc2($){return p1.createBedrockRole("ec2.amazonaws.com",$)}static addBedrockPermissions($,J=["*"],Y=!0){let Z=["bedrock:InvokeModel"];if(Y)Z.push("bedrock:InvokeModelWithResponseStream");let Q=J.map((G)=>G==="*"?"arn:aws:bedrock:*::foundation-model/*":`arn:aws:bedrock:*::foundation-model/${G}`);if(!$.Properties.Policies)$.Properties.Policies=[];return $.Properties.Policies.push({PolicyName:"bedrock-permissions",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:Z,Resource:Q}]}}),$}static Models={Claude3_5_Sonnet:"anthropic.claude-3-5-sonnet-20241022-v2:0",Claude3_5_Haiku:"anthropic.claude-3-5-haiku-20241022-v1:0",Claude3_Opus:"anthropic.claude-3-opus-20240229-v1:0",Claude3_Sonnet:"anthropic.claude-3-sonnet-20240229-v1:0",Claude3_Haiku:"anthropic.claude-3-haiku-20240307-v1:0",TitanTextG1Express:"amazon.titan-text-express-v1",TitanTextG1Lite:"amazon.titan-text-lite-v1",TitanEmbedG1Text:"amazon.titan-embed-text-v1",TitanImageG1:"amazon.titan-image-generator-v1",JurassicUltra:"ai21.j2-ultra-v1",JurassicMid:"ai21.j2-mid-v1",CommandText:"cohere.command-text-v14",CommandLight:"cohere.command-light-text-v14",EmbedEnglish:"cohere.embed-english-v3",EmbedMultilingual:"cohere.embed-multilingual-v3",Llama3_2_1B:"meta.llama3-2-1b-instruct-v1:0",Llama3_2_3B:"meta.llama3-2-3b-instruct-v1:0",Llama3_2_11B:"meta.llama3-2-11b-instruct-v1:0",Llama3_2_90B:"meta.llama3-2-90b-instruct-v1:0",Llama3_1_8B:"meta.llama3-1-8b-instruct-v1:0",Llama3_1_70B:"meta.llama3-1-70b-instruct-v1:0",Llama3_1_405B:"meta.llama3-1-405b-instruct-v1:0",Mistral7B:"mistral.mistral-7b-instruct-v0:2",Mixtral8x7B:"mistral.mixtral-8x7b-instruct-v0:1",MistralLarge:"mistral.mistral-large-2402-v1:0",StableDiffusionXL:"stability.stable-diffusion-xl-v1"};static ModelGroups={AllClaude:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-haiku-20240307-v1:0"],AllTitan:["amazon.titan-text-express-v1","amazon.titan-text-lite-v1","amazon.titan-embed-text-v1","amazon.titan-image-generator-v1"],AllLlama:["meta.llama3-2-1b-instruct-v1:0","meta.llama3-2-3b-instruct-v1:0","meta.llama3-2-11b-instruct-v1:0","meta.llama3-2-90b-instruct-v1:0","meta.llama3-1-8b-instruct-v1:0","meta.llama3-1-70b-instruct-v1:0","meta.llama3-1-405b-instruct-v1:0"],TextModels:["anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-5-haiku-20241022-v1:0","amazon.titan-text-express-v1","meta.llama3-2-11b-instruct-v1:0","mistral.mistral-7b-instruct-v0:2"],EmbeddingModels:["amazon.titan-embed-text-v1","cohere.embed-english-v3","cohere.embed-multilingual-v3"],ImageModels:["amazon.titan-image-generator-v1","stability.stable-diffusion-xl-v1"]}};m2=class m2{static createPostgres($){return m2.createRDSInstance("postgres","16.2",$)}static createMysql($){return m2.createRDSInstance("mysql","8.0.35",$)}static createRDSInstance($,J,Y){let{slug:Z,environment:Q,instanceClass:G="db.t3.micro",allocatedStorage:W=20,storageType:z="gp3",masterUsername:U="admin",masterPassword:H,databaseName:F,subnetIds:B,securityGroupIds:K,encrypted:O=!0,kmsKeyId:V,multiAz:A=!1,backupRetentionDays:_=7,publiclyAccessible:M=!1,enableCloudwatchLogs:E=!0,deletionProtection:j=!0}=Y,q=f({slug:Z,environment:Q,resourceType:`${$}-db`}),T=x(q),D,S;if(B&&B.length>0){let C=f({slug:Z,environment:Q,resourceType:"db-subnet-group"});S=x(C),D={Type:"AWS::RDS::DBSubnetGroup",Properties:{DBSubnetGroupName:C,DBSubnetGroupDescription:`Subnet group for ${q}`,SubnetIds:B,Tags:[{Key:"Name",Value:C},{Key:"Environment",Value:Q}]}}}let P={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:q,DBInstanceClass:G,Engine:$,EngineVersion:J,MasterUsername:U,MasterUserPassword:H,AllocatedStorage:W,StorageType:z,StorageEncrypted:O,MultiAZ:A,BackupRetentionPeriod:_,PubliclyAccessible:M,DeletionProtection:j,Tags:[{Key:"Name",Value:q},{Key:"Environment",Value:Q}]}};if(F)P.Properties.DBName=F;if(V)P.Properties.KmsKeyId=V;if(S)P.Properties.DBSubnetGroupName=l.Ref(S);if(K&&K.length>0)P.Properties.VPCSecurityGroups=K;if(E)P.Properties.EnableCloudwatchLogsExports=$==="postgres"?["postgresql"]:["error","general","slowquery"];return{dbInstance:P,subnetGroup:D,logicalId:T,subnetGroupId:S}}static createReadReplica($,J){let{slug:Y,environment:Z,instanceClass:Q="db.t3.micro",securityGroupIds:G,publiclyAccessible:W=!1}=J,z=f({slug:Y,environment:Z,resourceType:"db-replica"}),U=x(z),H={Type:"AWS::RDS::DBInstance",Properties:{DBInstanceIdentifier:z,DBInstanceClass:Q,SourceDBInstanceIdentifier:l.Ref($),PubliclyAccessible:W,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Z},{Key:"Type",Value:"ReadReplica"}]}};if(G&&G.length>0)H.Properties.VPCSecurityGroups=G;return{replica:H,logicalId:U}}static createParameterGroup($,J,Y){let{slug:Z,environment:Q,parameters:G={}}=Y,W=f({slug:Z,environment:Q,resourceType:"db-params"}),z=x(W),U=$==="postgres"?`postgres${J.split(".")[0]}`:`mysql${J.split(".")[0]}.${J.split(".")[1]}`;return{parameterGroup:{Type:"AWS::RDS::DBParameterGroup",Properties:{DBParameterGroupName:W,Description:`Parameter group for ${W}`,Family:U,Parameters:G,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:Q}]}},logicalId:z}}static enableBackup($,J=7){return $.Properties.BackupRetentionPeriod=J,$}static createTable($){let{slug:J,environment:Y,tableName:Z,partitionKey:Q,sortKey:G,billingMode:W="PAY_PER_REQUEST",readCapacity:z=5,writeCapacity:U=5,streamEnabled:H=!1,streamViewType:F="NEW_AND_OLD_IMAGES",encrypted:B=!0,kmsKeyId:K,pointInTimeRecovery:O=!0,ttlAttribute:V}=$,A=Z||f({slug:J,environment:Y,resourceType:"table"}),_=x(A),M=[{AttributeName:Q.name,AttributeType:Q.type}];if(G)M.push({AttributeName:G.name,AttributeType:G.type});let E=[{AttributeName:Q.name,KeyType:"HASH"}];if(G)E.push({AttributeName:G.name,KeyType:"RANGE"});let j={Type:"AWS::DynamoDB::Table",Properties:{TableName:A,BillingMode:W,AttributeDefinitions:M,KeySchema:E,Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:Y}]}};if(W==="PROVISIONED")j.Properties.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:U};if(H)j.Properties.StreamSpecification={StreamViewType:F};if(B)j.Properties.SSESpecification={SSEEnabled:!0,SSEType:K?"KMS":"AES256",KMSMasterKeyId:K};if(O)j.Properties.PointInTimeRecoverySpecification={PointInTimeRecoveryEnabled:!0};if(V)j.Properties.TimeToLiveSpecification={AttributeName:V,Enabled:!0};return{table:j,logicalId:_}}static addGlobalSecondaryIndex($,J){let{indexName:Y,partitionKey:Z,sortKey:Q,projectionType:G="ALL",nonKeyAttributes:W,readCapacity:z=5,writeCapacity:U=5}=J;if(!$.Properties.AttributeDefinitions.some((B)=>B.AttributeName===Z.name))$.Properties.AttributeDefinitions.push({AttributeName:Z.name,AttributeType:Z.type});if(Q&&!$.Properties.AttributeDefinitions.some((B)=>B.AttributeName===Q.name))$.Properties.AttributeDefinitions.push({AttributeName:Q.name,AttributeType:Q.type});let H=[{AttributeName:Z.name,KeyType:"HASH"}];if(Q)H.push({AttributeName:Q.name,KeyType:"RANGE"});let F={IndexName:Y,KeySchema:H,Projection:{ProjectionType:G,NonKeyAttributes:G==="INCLUDE"?W:void 0},ProvisionedThroughput:void 0};if($.Properties.BillingMode==="PROVISIONED")F.ProvisionedThroughput={ReadCapacityUnits:z,WriteCapacityUnits:U};if(!$.Properties.GlobalSecondaryIndexes)$.Properties.GlobalSecondaryIndexes=[];return $.Properties.GlobalSecondaryIndexes.push(F),$}static enableStreams($,J="NEW_AND_OLD_IMAGES"){return $.Properties.StreamSpecification={StreamViewType:J},$}static InstanceClasses={T3_Micro:"db.t3.micro",T3_Small:"db.t3.small",T3_Medium:"db.t3.medium",T3_Large:"db.t3.large",T4g_Micro:"db.t4g.micro",T4g_Small:"db.t4g.small",T4g_Medium:"db.t4g.medium",M5_Large:"db.m5.large",M5_XLarge:"db.m5.xlarge",M5_2XLarge:"db.m5.2xlarge",R5_Large:"db.r5.large",R5_XLarge:"db.r5.xlarge",R5_2XLarge:"db.r5.2xlarge"}};g8=class g8{static createRedis($){let{slug:J,environment:Y,nodeType:Z="cache.t3.micro",engineVersion:Q="7.1",port:G=6379,subnetIds:W,securityGroupIds:z,numCacheClusters:U=2,automaticFailover:H=!0,multiAz:F=!0,clusterMode:B=!1,numNodeGroups:K=1,replicasPerNodeGroup:O=1,atRestEncryption:V=!0,transitEncryption:A=!0,authToken:_,kmsKeyId:M,snapshotRetentionDays:E=7,snapshotWindow:j,maintenanceWindow:q}=$,T=f({slug:J,environment:Y,resourceType:"redis"}),D=x(T),S,P;if(W&&W.length>0){let I=f({slug:J,environment:Y,resourceType:"cache-subnet-group"});P=x(I),S={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:I,Description:`Subnet group for ${T}`,SubnetIds:W,Tags:[{Key:"Name",Value:I},{Key:"Environment",Value:Y}]}}}let C={Type:"AWS::ElastiCache::ReplicationGroup",Properties:{ReplicationGroupId:T,ReplicationGroupDescription:`Redis cluster for ${J} ${Y}`,Engine:"redis",EngineVersion:Q,CacheNodeType:Z,Port:G,AutomaticFailoverEnabled:H,MultiAZEnabled:F,AtRestEncryptionEnabled:V,TransitEncryptionEnabled:A,SnapshotRetentionLimit:E,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:T},{Key:"Environment",Value:Y}]}};if(B)C.Properties.NumNodeGroups=K,C.Properties.ReplicasPerNodeGroup=O;else C.Properties.NumCacheClusters=U;if(_)C.Properties.AuthToken=_;if(M)C.Properties.KmsKeyId=M;if(P)C.Properties.CacheSubnetGroupName=l.Ref(P);if(z&&z.length>0)C.Properties.SecurityGroupIds=z;if(j)C.Properties.SnapshotWindow=j;if(q)C.Properties.PreferredMaintenanceWindow=q;return{replicationGroup:C,subnetGroup:S,logicalId:D,subnetGroupId:P}}static createMemcached($){let{slug:J,environment:Y,nodeType:Z="cache.t3.micro",engineVersion:Q="1.6.22",port:G=11211,numCacheNodes:W=2,subnetIds:z,securityGroupIds:U,azMode:H="cross-az",preferredAzs:F,maintenanceWindow:B}=$,K=f({slug:J,environment:Y,resourceType:"memcached"}),O=x(K),V,A;if(z&&z.length>0){let M=f({slug:J,environment:Y,resourceType:"cache-subnet-group"});A=x(M),V={Type:"AWS::ElastiCache::SubnetGroup",Properties:{CacheSubnetGroupName:M,Description:`Subnet group for ${K}`,SubnetIds:z,Tags:[{Key:"Name",Value:M},{Key:"Environment",Value:Y}]}}}let _={Type:"AWS::ElastiCache::CacheCluster",Properties:{ClusterName:K,CacheNodeType:Z,Engine:"memcached",EngineVersion:Q,NumCacheNodes:W,Port:G,AZMode:H,AutoMinorVersionUpgrade:!0,Tags:[{Key:"Name",Value:K},{Key:"Environment",Value:Y}]}};if(A)_.Properties.CacheSubnetGroupName=l.Ref(A);if(U&&U.length>0)_.Properties.VpcSecurityGroupIds=U;if(F&&F.length>0)_.Properties.PreferredAvailabilityZones=F;if(B)_.Properties.PreferredMaintenanceWindow=B;return{cluster:_,subnetGroup:V,logicalId:O,subnetGroupId:A}}static enableClusterMode($,J=3,Y=2){return delete $.Properties.NumCacheClusters,$.Properties.NumNodeGroups=J,$.Properties.ReplicasPerNodeGroup=Y,$}static createRedisParameterGroup($,J){let{slug:Y,environment:Z,parameters:Q={}}=J,G=f({slug:Y,environment:Z,resourceType:"redis-params"}),W=x(G);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`redis${$.split(".")[0]}.x`,Description:`Parameter group for ${G}`,Properties:Q,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z}]}},logicalId:W}}static createMemcachedParameterGroup($,J){let{slug:Y,environment:Z,parameters:Q={}}=J,G=f({slug:Y,environment:Z,resourceType:"memcached-params"}),W=x(G);return{parameterGroup:{Type:"AWS::ElastiCache::ParameterGroup",Properties:{CacheParameterGroupFamily:`memcached${$.split(".")[0]}.${$.split(".")[1]}`,Description:`Parameter group for ${G}`,Properties:Q,Tags:[{Key:"Name",Value:G},{Key:"Environment",Value:Z}]}},logicalId:W}}static NodeTypes={T3_Micro:"cache.t3.micro",T3_Small:"cache.t3.small",T3_Medium:"cache.t3.medium",T4g_Micro:"cache.t4g.micro",T4g_Small:"cache.t4g.small",T4g_Medium:"cache.t4g.medium",M5_Large:"cache.m5.large",M5_XLarge:"cache.m5.xlarge",M5_2XLarge:"cache.m5.2xlarge",R5_Large:"cache.r5.large",R5_XLarge:"cache.r5.xlarge",R5_2XLarge:"cache.r5.2xlarge",R5_4XLarge:"cache.r5.4xlarge",R6g_Large:"cache.r6g.large",R6g_XLarge:"cache.r6g.xlarge",R6g_2XLarge:"cache.r6g.2xlarge"}};R1=class R1{static createUser($){let{slug:J,environment:Y,userName:Z,groups:Q,managedPolicyArns:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"user"}),z=x(W),U={Type:"AWS::IAM::User",Properties:{UserName:W,Tags:[{Key:"Name",Value:W},{Key:"Environment",Value:Y}]}};if(Q&&Q.length>0)U.Properties.Groups=Q;if(G&&G.length>0)U.Properties.ManagedPolicyArns=G;return{user:U,logicalId:z}}static createRole($){let{slug:J,environment:Y,roleName:Z,servicePrincipal:Q,awsPrincipal:G,managedPolicyArns:W}=$,z=Z||f({slug:J,environment:Y,resourceType:"role"}),U=x(z),H={};if(Q)H.Service=Q;if(G)H.AWS=G;let F={Type:"AWS::IAM::Role",Properties:{RoleName:z,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:H,Action:"sts:AssumeRole"}]},Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(W&&W.length>0)F.Properties.ManagedPolicyArns=W;return{role:F,logicalId:U}}static createGroup($){let{slug:J,environment:Y,groupName:Z,managedPolicyArns:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"group"}),W=x(G),z={Type:"AWS::IAM::Group",Properties:{GroupName:G}};if(Q&&Q.length>0)z.Properties.ManagedPolicyArns=Q;return{group:z,logicalId:W}}static createPolicy($){let{slug:J,environment:Y,policyName:Z,description:Q,statements:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"policy"}),z=x(W),U=G.map((F)=>({Sid:F.sid,Effect:F.effect||"Allow",Action:F.actions,Resource:F.resources,Condition:F.conditions}));return{policy:{Type:"AWS::IAM::ManagedPolicy",Properties:{ManagedPolicyName:W,Description:Q||`Managed policy for ${W}`,PolicyDocument:{Version:"2012-10-17",Statement:U}}},logicalId:z}}static attachPolicyToRole($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToUser($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static attachPolicyToGroup($,J){if(!$.Properties.ManagedPolicyArns)$.Properties.ManagedPolicyArns=[];if(!$.Properties.ManagedPolicyArns.includes(J))$.Properties.ManagedPolicyArns.push(J);return $}static addInlinePolicyToRole($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Z=Y.map((Q)=>({Effect:Q.effect||"Allow",Action:Q.actions,Resource:Q.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Z}}),$}static addInlinePolicyToUser($,J,Y){if(!$.Properties.Policies)$.Properties.Policies=[];let Z=Y.map((Q)=>({Effect:Q.effect||"Allow",Action:Q.actions,Resource:Q.resources}));return $.Properties.Policies.push({PolicyName:J,PolicyDocument:{Version:"2012-10-17",Statement:Z}}),$}static createAccessKey($,J){let{slug:Y,environment:Z,status:Q="Active"}=J,G=f({slug:Y,environment:Z,resourceType:"access-key"}),W=x(G);return{accessKey:{Type:"AWS::IAM::AccessKey",Properties:{UserName:l.Ref($),Status:Q}},logicalId:W}}static createInstanceProfile($,J){let{slug:Y,environment:Z,profileName:Q}=J,G=Q||f({slug:Y,environment:Z,resourceType:"instance-profile"}),W=x(G);return{instanceProfile:{Type:"AWS::IAM::InstanceProfile",Properties:{InstanceProfileName:G,Roles:[l.Ref($)]}},logicalId:W}}static ManagedPolicies={AdministratorAccess:"arn:aws:iam::aws:policy/AdministratorAccess",PowerUserAccess:"arn:aws:iam::aws:policy/PowerUserAccess",ReadOnlyAccess:"arn:aws:iam::aws:policy/ReadOnlyAccess",S3FullAccess:"arn:aws:iam::aws:policy/AmazonS3FullAccess",S3ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess",DynamoDBFullAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",DynamoDBReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",RDSFullAccess:"arn:aws:iam::aws:policy/AmazonRDSFullAccess",RDSReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess",LambdaFullAccess:"arn:aws:iam::aws:policy/AWSLambda_FullAccess",LambdaReadOnlyAccess:"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess",LambdaBasicExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",LambdaVPCAccessExecutionRole:"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole",EC2FullAccess:"arn:aws:iam::aws:policy/AmazonEC2FullAccess",EC2ReadOnlyAccess:"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",EC2ContainerRegistryReadOnly:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",EC2ContainerRegistryPowerUser:"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser",ECSTaskExecutionRole:"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",ECSFullAccess:"arn:aws:iam::aws:policy/AmazonECS_FullAccess",CloudWatchFullAccess:"arn:aws:iam::aws:policy/CloudWatchFullAccess",CloudWatchLogsFullAccess:"arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",SESFullAccess:"arn:aws:iam::aws:policy/AmazonSESFullAccess",SNSFullAccess:"arn:aws:iam::aws:policy/AmazonSNSFullAccess",SQSFullAccess:"arn:aws:iam::aws:policy/AmazonSQSFullAccess",SecretsManagerReadWrite:"arn:aws:iam::aws:policy/SecretsManagerReadWrite"};static ServicePrincipals={Lambda:"lambda.amazonaws.com",EC2:"ec2.amazonaws.com",ECS:"ecs.amazonaws.com",ECSTaskExecution:"ecs-tasks.amazonaws.com",APIGateway:"apigateway.amazonaws.com",Events:"events.amazonaws.com",States:"states.amazonaws.com",CodeBuild:"codebuild.amazonaws.com",CodeDeploy:"codedeploy.amazonaws.com",CloudFormation:"cloudformation.amazonaws.com"};static createCiCdUser($){let{slug:J,environment:Y,permissions:Z,createAccessKey:Q=!0}=$,G={},W=[];if(Z.s3Buckets&&Z.s3Buckets.length>0)W.push({sid:"S3Access",actions:["s3:GetBucketLocation","s3:ListBucket","s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucketMultipartUploads","s3:AbortMultipartUpload"],resources:[...Z.s3Buckets,...Z.s3Buckets.map((O)=>`${O}/*`)]});if(Z.cloudFrontDistributions&&Z.cloudFrontDistributions.length>0)W.push({sid:"CloudFrontAccess",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations","cloudfront:GetDistribution"],resources:Z.cloudFrontDistributions});if(Z.ecrRepositories&&Z.ecrRepositories.length>0)W.push({sid:"ECRAccess",actions:["ecr:GetAuthorizationToken","ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:GetRepositoryPolicy","ecr:DescribeRepositories","ecr:ListImages","ecr:DescribeImages","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:Z.ecrRepositories}),W.push({sid:"ECRLogin",actions:["ecr:GetAuthorizationToken"],resources:"*"});if(Z.ecsServices&&Z.ecsServices.length>0)W.push({sid:"ECSAccess",actions:["ecs:DescribeServices","ecs:DescribeTaskDefinition","ecs:DescribeTasks","ecs:ListTasks","ecs:RegisterTaskDefinition","ecs:UpdateService","ecs:RunTask","ecs:StopTask"],resources:Z.ecsServices}),W.push({sid:"ECSTaskDefinitions",actions:["ecs:RegisterTaskDefinition","ecs:DeregisterTaskDefinition"],resources:"*"}),W.push({sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}});if(Z.cloudFormationStacks&&Z.cloudFormationStacks.length>0)W.push({sid:"CloudFormationAccess",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DeleteStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:DescribeStackResources","cloudformation:GetTemplate","cloudformation:ListStackResources","cloudformation:ValidateTemplate"],resources:Z.cloudFormationStacks});if(Z.lambdaFunctions&&Z.lambdaFunctions.length>0)W.push({sid:"LambdaAccess",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion","lambda:UpdateAlias","lambda:CreateAlias"],resources:Z.lambdaFunctions});if(Z.secretsManagerSecrets&&Z.secretsManagerSecrets.length>0)W.push({sid:"SecretsManagerAccess",actions:["secretsmanager:GetSecretValue","secretsmanager:DescribeSecret"],resources:Z.secretsManagerSecrets});let{policy:z,logicalId:U}=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cicd-policy"}),description:`CI/CD deployment policy for ${J} (${Y})`,statements:W});G[U]=z;let{user:H,logicalId:F}=R1.createUser({slug:J,environment:Y,userName:f({slug:J,environment:Y,resourceType:"cicd-user"}),managedPolicyArns:[l.Ref(U)]});G[F]=H;let B,K;if(Q){let O=R1.createAccessKey(F,{slug:J,environment:Y});B=O.accessKey,K=O.logicalId,G[K]=B}return{user:H,accessKey:B,policy:z,userLogicalId:F,accessKeyLogicalId:K,policyLogicalId:U,resources:G}}static createCrossAccountRole($){let{slug:J,environment:Y,trustedAccountIds:Z,externalId:Q,permissions:G,maxSessionDuration:W=3600}=$,z={},{policy:U,logicalId:H}=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cross-account-policy"}),description:`Cross-account access policy for ${J} (${Y})`,statements:G});z[H]=U;let F=f({slug:J,environment:Y,resourceType:"cross-account-role"}),B=x(F),K={};if(Q)K.StringEquals={"sts:ExternalId":Q};let O={Type:"AWS::IAM::Role",Properties:{RoleName:F,MaxSessionDuration:W,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{AWS:Z.map((V)=>`arn:aws:iam::${V}:root`)},Action:"sts:AssumeRole",...Object.keys(K).length>0?{Condition:K}:{}}]},ManagedPolicyArns:[l.Ref(H)],Tags:[{Key:"Name",Value:F},{Key:"Environment",Value:Y},{Key:"Purpose",Value:"Cross-Account Access"}]}};return z[B]=O,{role:O,policy:U,roleLogicalId:B,policyLogicalId:H,resources:z}}static createCliUser($){let{slug:J,environment:Y,permissions:Z="readonly"}=$,Q={},G=[],W=[];switch(Z){case"readonly":W=[R1.ManagedPolicies.ReadOnlyAccess];break;case"deploy":G=[{sid:"S3Deploy",actions:["s3:*"],resources:"*"},{sid:"CloudFrontDeploy",actions:["cloudfront:*"],resources:"*"},{sid:"ECSDeploy",actions:["ecs:*"],resources:"*"},{sid:"ECRDeploy",actions:["ecr:*"],resources:"*"},{sid:"LambdaDeploy",actions:["lambda:*"],resources:"*"},{sid:"CloudFormationDeploy",actions:["cloudformation:*"],resources:"*"},{sid:"IAMPassRole",actions:["iam:PassRole"],resources:"*"}];break;case"admin":W=[R1.ManagedPolicies.AdministratorAccess];break}let z,U;if(G.length>0){let O=R1.createPolicy({slug:J,environment:Y,policyName:f({slug:J,environment:Y,resourceType:"cli-policy"}),description:`CLI access policy for ${J} (${Y})`,statements:G});z=O.policy,U=O.logicalId,Q[U]=z,W=[l.Ref(U)]}let{user:H,logicalId:F}=R1.createUser({slug:J,environment:Y,userName:f({slug:J,environment:Y,resourceType:"cli-user"}),managedPolicyArns:W});Q[F]=H;let{accessKey:B,logicalId:K}=R1.createAccessKey(F,{slug:J,environment:Y});return Q[K]=B,{user:H,accessKey:B,policy:z,userLogicalId:F,accessKeyLogicalId:K,policyLogicalId:U,resources:Q}}static CiCdPolicies={s3Deployment:($)=>[{sid:"S3ListBuckets",actions:["s3:ListBucket","s3:GetBucketLocation"],resources:$},{sid:"S3Objects",actions:["s3:GetObject","s3:PutObject","s3:DeleteObject"],resources:$.map((J)=>`${J}/*`)}],cloudFrontInvalidation:($)=>[{sid:"CloudFrontInvalidation",actions:["cloudfront:CreateInvalidation","cloudfront:GetInvalidation","cloudfront:ListInvalidations"],resources:$}],ecsDeployment:()=>[{sid:"ECSServices",actions:["ecs:DescribeServices","ecs:UpdateService","ecs:DescribeTaskDefinition","ecs:RegisterTaskDefinition"],resources:"*"},{sid:"ECSPassRole",actions:["iam:PassRole"],resources:"*",conditions:{StringLike:{"iam:PassedToService":"ecs-tasks.amazonaws.com"}}}],ecrPush:($)=>[{sid:"ECRAuth",actions:["ecr:GetAuthorizationToken"],resources:"*"},{sid:"ECRPush",actions:["ecr:BatchCheckLayerAvailability","ecr:GetDownloadUrlForLayer","ecr:BatchGetImage","ecr:InitiateLayerUpload","ecr:UploadLayerPart","ecr:CompleteLayerUpload","ecr:PutImage"],resources:$}],lambdaDeployment:($)=>[{sid:"LambdaDeploy",actions:["lambda:GetFunction","lambda:UpdateFunctionCode","lambda:UpdateFunctionConfiguration","lambda:PublishVersion"],resources:$}],cloudFormationDeployment:($)=>[{sid:"CloudFormationDeploy",actions:["cloudformation:CreateStack","cloudformation:UpdateStack","cloudformation:DescribeStacks","cloudformation:DescribeStackEvents","cloudformation:GetTemplate"],resources:$}]}};c6=class c6{static createRestApi($){let{slug:J,environment:Y,name:Z,description:Q,endpointType:G="REGIONAL",binaryMediaTypes:W,compressionSize:z}=$,U=Z||f({slug:J,environment:Y,resourceType:"rest-api"}),H=x(U),F={Type:"AWS::ApiGateway::RestApi",Properties:{Name:U,Description:Q||`REST API for ${J} ${Y}`,EndpointConfiguration:{Types:[G]},Tags:[{Key:"Name",Value:U},{Key:"Environment",Value:Y}]}};if(W&&W.length>0)F.Properties.BinaryMediaTypes=W;if(z!==void 0)F.Properties.MinimumCompressionSize=z;return{restApi:F,logicalId:H}}static createHttpApi($){let{slug:J,environment:Y,name:Z,description:Q,corsEnabled:G=!0,corsOrigins:W=["*"],corsMethods:z=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],corsHeaders:U=["*"],corsMaxAge:H=86400,corsAllowCredentials:F=!1}=$,B=Z||f({slug:J,environment:Y,resourceType:"http-api"}),K=x(B),O={Type:"AWS::ApiGatewayV2::Api",Properties:{Name:B,Description:Q||`HTTP API for ${J} ${Y}`,ProtocolType:"HTTP",Tags:{Name:B,Environment:Y}}};if(G)O.Properties.CorsConfiguration={AllowOrigins:W,AllowMethods:z,AllowHeaders:U,MaxAge:H,AllowCredentials:F};return{httpApi:O,logicalId:K}}static createWebSocketApi($){let{slug:J,environment:Y,name:Z,description:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"ws-api"}),W=x(G);return{webSocketApi:{Type:"AWS::ApiGatewayV2::Api",Properties:{Name:G,Description:Q||`WebSocket API for ${J} ${Y}`,ProtocolType:"WEBSOCKET",Tags:{Name:G,Environment:Y}}},logicalId:W}}static createDeployment($,J){let{slug:Y,environment:Z,description:Q}=J,G=f({slug:Y,environment:Z,resourceType:"api-deployment"}),W=x(G);return{deployment:{Type:"AWS::ApiGateway::Deployment",Properties:{RestApiId:l.Ref($),Description:Q||`Deployment for ${G}`}},logicalId:W}}static createStage($,J,Y){let{slug:Z,environment:Q,stageName:G,description:W,cacheEnabled:z=!1,cacheSize:U="0.5",variables:H,throttling:F}=Y,B=f({slug:Z,environment:Q,resourceType:"api-stage"}),K=x(B),O={Type:"AWS::ApiGateway::Stage",Properties:{StageName:G||Q,RestApiId:l.Ref($),DeploymentId:l.Ref(J),Description:W,CacheClusterEnabled:z,Tags:[{Key:"Name",Value:B},{Key:"Environment",Value:Q}]}};if(z)O.Properties.CacheClusterSize=U;if(H)O.Properties.Variables=H;if(F)O.Properties.MethodSettings=[{HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:F.burstLimit,ThrottlingRateLimit:F.rateLimit}];return{stage:O,logicalId:K}}static createAuthorizer($,J){let{slug:Y,environment:Z,name:Q,type:G,functionArn:W,identitySource:z,userPoolArns:U,ttl:H=300}=J,F=Q||f({slug:Y,environment:Z,resourceType:"api-authorizer"}),B=x(F),K={Type:"AWS::ApiGateway::Authorizer",Properties:{Name:F,Type:G,RestApiId:l.Ref($),AuthorizerResultTtlInSeconds:H}};if(G==="TOKEN"||G==="REQUEST"){if(!W)throw Error("Lambda authorizer requires functionArn");K.Properties.AuthorizerUri=W,K.Properties.IdentitySource=z||"method.request.header.Authorization"}if(G==="COGNITO_USER_POOLS"){if(!U||U.length===0)throw Error("Cognito authorizer requires userPoolArns");K.Properties.ProviderARNs=U,K.Properties.IdentitySource=z||"method.request.header.Authorization"}return{authorizer:K,logicalId:B}}static setCors($,J={}){let{origins:Y=["*"],methods:Z=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],headers:Q=["*"],maxAge:G=86400,allowCredentials:W=!1}=J;return $.Properties.CorsConfiguration={AllowOrigins:Y,AllowMethods:Z,AllowHeaders:Q,MaxAge:G,AllowCredentials:W},$}static addThrottling($,J=5000,Y=1e4){if(!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",ThrottlingBurstLimit:J,ThrottlingRateLimit:Y}),$}static enableCaching($,J="0.5",Y=300){if($.Properties.CacheClusterEnabled=!0,$.Properties.CacheClusterSize=J,!$.Properties.MethodSettings)$.Properties.MethodSettings=[];return $.Properties.MethodSettings.push({HttpMethod:"*",ResourcePath:"/*",CachingEnabled:!0,CacheTtlInSeconds:Y}),$}static CacheSizes={Small:"0.5",Medium:"1.6",Large:"6.1",XLarge:"13.5",XXLarge:"28.4",XXXLarge:"58.2",Huge:"118",Massive:"237"};static ThrottlingPresets={Light:{burstLimit:100,rateLimit:50},Medium:{burstLimit:500,rateLimit:250},Heavy:{burstLimit:2000,rateLimit:1000},Default:{burstLimit:5000,rateLimit:1e4}}};D1=class D1{static createTopic($){let{slug:J,environment:Y,topicName:Z,displayName:Q,encrypted:G=!1,kmsKeyId:W}=$,z=Z||f({slug:J,environment:Y,resourceType:"topic"}),U=x(z),H={Type:"AWS::SNS::Topic",Properties:{TopicName:z,DisplayName:Q||z,Tags:[{Key:"Name",Value:z},{Key:"Environment",Value:Y}]}};if(G&&W)H.Properties.KmsMasterKeyId=W;return{topic:H,logicalId:U}}static subscribe($,J){let{slug:Y,environment:Z,protocol:Q,endpoint:G,filterPolicy:W,rawMessageDelivery:z=!1}=J,U=f({slug:Y,environment:Z,resourceType:"subscription"}),H=G.replace(/[^a-zA-Z0-9]/g,""),F=H.length>12?H.slice(-12):H,B=x(`${U}-${Q}-${F}`),K={Type:"AWS::SNS::Subscription",Properties:{TopicArn:l.Ref($),Protocol:Q,Endpoint:G,RawMessageDelivery:z}};if(W)K.Properties.FilterPolicy=W;return{subscription:K,logicalId:B}}static subscribeEmail($,J,Y){return D1.subscribe($,{...Y,protocol:"email",endpoint:J})}static subscribeLambda($,J,Y){return D1.subscribe($,{...Y,protocol:"lambda",endpoint:J,rawMessageDelivery:!0})}static subscribeSqs($,J,Y){return D1.subscribe($,{...Y,protocol:"sqs",endpoint:J})}static subscribeHttp($,J,Y){let Z=J.startsWith("https://")?"https":"http";return D1.subscribe($,{...Y,protocol:Z,endpoint:J})}static subscribeSms($,J,Y){return D1.subscribe($,{...Y,protocol:"sms",endpoint:J})}static setTopicPolicy($,J){let{slug:Y,environment:Z,allowedPrincipals:Q,allowedServices:G,actions:W="SNS:Publish"}=J,z=f({slug:Y,environment:Z,resourceType:"topic-policy"}),U=x(z),H={};if(Q)H.AWS=Q;if(G)H.Service=G;return{policy:{Type:"AWS::SNS::TopicPolicy",Properties:{Topics:[l.Ref($)],PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:H,Action:W,Resource:l.Ref($)}]}}},logicalId:U}}static allowCloudWatchAlarms($,J){return D1.setTopicPolicy($,{...J,allowedServices:"cloudwatch.amazonaws.com",actions:"SNS:Publish"})}static allowEventBridge($,J){return D1.setTopicPolicy($,{...J,allowedServices:"events.amazonaws.com",actions:"SNS:Publish"})}static allowS3($,J){return D1.setTopicPolicy($,{...J,allowedServices:"s3.amazonaws.com",actions:"SNS:Publish"})}static enableEncryption($,J){if(!$.Properties)$.Properties={};return $.Properties.KmsMasterKeyId=J,$}static addInlineSubscription($,J,Y){if(!$.Properties)$.Properties={};if(!$.Properties.Subscription)$.Properties.Subscription=[];return $.Properties.Subscription.push({Protocol:J,Endpoint:Y}),$}static FilterPolicies={eventType:($)=>({eventType:$}),status:($)=>({status:$}),numericRange:($,J,Y)=>({[$]:[{numeric:[">=",J,"<=",Y]}]}),prefix:($,J)=>({[$]:[{prefix:J}]}),and:(...$)=>{return Object.assign({},...$)},exists:($,J)=>({[$]:[{exists:J}]})};static UseCases={createAlertTopic:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-alerts`,displayName:$.displayName||"Alert Notifications"})},createEventFanout:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-events`,displayName:$.displayName||"Event Fanout"})},createNotificationTopic:($)=>{return D1.createTopic({...$,topicName:$.topicName||`${$.slug}-${$.environment}-notifications`,displayName:$.displayName||"User Notifications"})}}};Tz=class Tz{static createStateMachine($){let{slug:J,environment:Y,stateMachineName:Z,type:Q="STANDARD",definition:G,roleArn:W,loggingConfiguration:z,tracingConfiguration:U}=$,H=Z||f({slug:J,environment:Y,resourceType:"state-machine"}),F=x(H),B,K,O;if(W)O=W;else{let A=f({slug:J,environment:Y,resourceType:"state-machine-role"});K=x(A),B={Type:"AWS::IAM::Role",Properties:{RoleName:A,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"states.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"],Tags:[{Key:"Name",Value:A},{Key:"Environment",Value:Y}]}},O=l.GetAtt(K,"Arn")}let V={Type:"AWS::StepFunctions::StateMachine",Properties:{StateMachineName:H,StateMachineType:Q,DefinitionString:JSON.stringify(G),RoleArn:O,Tags:[{Key:"Name",Value:H},{Key:"Environment",Value:Y}]}};if(z)V.Properties.LoggingConfiguration={Level:z.level,IncludeExecutionData:z.includeExecutionData,Destinations:z.destinations?.map((A)=>({CloudWatchLogsLogGroup:{LogGroupArn:A}}))};if(U)V.Properties.TracingConfiguration={Enabled:U.enabled};return{stateMachine:V,logicalId:F,role:B,roleLogicalId:K}}static createLambdaTask($,J){return{Type:"Task",Resource:"arn:aws:states:::lambda:invoke",Parameters:{FunctionName:$,Payload:J?.parameters||{"Input.$":"$"}},ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createDynamoDBTask($,J,Y,Z){return{Type:"Task",Resource:{GetItem:"arn:aws:states:::dynamodb:getItem",PutItem:"arn:aws:states:::dynamodb:putItem",UpdateItem:"arn:aws:states:::dynamodb:updateItem",DeleteItem:"arn:aws:states:::dynamodb:deleteItem"}[$],Parameters:{TableName:J,...Y},ResultPath:Z?.resultPath,Retry:Z?.retry,Catch:Z?.catch,Next:Z?.next,End:Z?.end}}static createSNSPublishTask($,J,Y){return{Type:"Task",Resource:"arn:aws:states:::sns:publish",Parameters:{TopicArn:$,Message:J},ResultPath:Y?.resultPath,Retry:Y?.retry,Catch:Y?.catch,Next:Y?.next,End:Y?.end}}static createSQSSendMessageTask($,J,Y){return{Type:"Task",Resource:"arn:aws:states:::sqs:sendMessage",Parameters:{QueueUrl:$,MessageBody:J},ResultPath:Y?.resultPath,Retry:Y?.retry,Catch:Y?.catch,Next:Y?.next,End:Y?.end}}static createPassState($){return{Type:"Pass",Result:$?.result,ResultPath:$?.resultPath,Parameters:$?.parameters,Next:$?.next,End:$?.end}}static createWaitState($){return{Type:"Wait",Seconds:$.seconds,Timestamp:$.timestamp,SecondsPath:$.secondsPath,TimestampPath:$.timestampPath,Next:$.next,End:$.end}}static createChoiceState($,J){return{Type:"Choice",Choices:$,Default:J}}static createParallelState($,J){return{Type:"Parallel",Branches:$,ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createMapState($,J){return{Type:"Map",ItemsPath:J?.itemsPath||"$.items",Iterator:$,MaxConcurrency:J?.maxConcurrency,ResultPath:J?.resultPath,Retry:J?.retry,Catch:J?.catch,Next:J?.next,End:J?.end}}static createSucceedState(){return{Type:"Succeed"}}static createFailState($,J){return{Type:"Fail",Error:$,Cause:J}}static RetryPolicies={standard:()=>({ErrorEquals:["States.ALL"],IntervalSeconds:2,MaxAttempts:3,BackoffRate:2}),aggressive:()=>({ErrorEquals:["States.TaskFailed","States.Timeout"],IntervalSeconds:1,MaxAttempts:5,BackoffRate:1.5}),custom:($,J,Y,Z)=>({ErrorEquals:$,IntervalSeconds:J,MaxAttempts:Y,BackoffRate:Z})};static CatchPolicies={all:($,J)=>({ErrorEquals:["States.ALL"],Next:$,ResultPath:J||"$.error"}),specific:($,J,Y)=>({ErrorEquals:$,Next:J,ResultPath:Y||"$.error"})};static Patterns={sequential:($,J,Y)=>{let Z={};return Y.forEach((Q,G)=>{let W=G===Y.length-1;Z[Q.name]={...Q.state,Next:W?void 0:Y[G+1].name,End:W}}),{Comment:"Sequential workflow",StartAt:Y[0].name,States:Z}},fanout:($,J,Y)=>{return{Comment:"Fan-out workflow",StartAt:"Parallel",States:{Parallel:{Type:"Parallel",Branches:Y.map((Z)=>Z.definition),End:!0}}}},map:($,J,Y,Z)=>{return{Comment:"Map workflow",StartAt:"Map",States:{Map:{Type:"Map",ItemsPath:"$.items",Iterator:Y,MaxConcurrency:Z,End:!0}}}},withErrorHandling:($,J,Y,Z)=>{return{Comment:"Workflow with error handling",StartAt:"Main",States:{Main:{...Y,Catch:[{ErrorEquals:["States.ALL"],Next:"ErrorHandler"}],Next:"Success"},ErrorHandler:Z,Success:{Type:"Succeed"}}}}}};u8=class u8{static createAlarm($){let{slug:J,environment:Y,alarmName:Z,metricName:Q,namespace:G,statistic:W="Average",period:z=300,evaluationPeriods:U=1,threshold:H,comparisonOperator:F,treatMissingData:B="notBreaching",actionsEnabled:K=!0,alarmActions:O,okActions:V,insufficientDataActions:A,dimensions:_,unit:M,datapointsToAlarm:E}=$,j=Z||f({slug:J,environment:Y,resourceType:"alarm"}),q=x(j),T={Type:"AWS::CloudWatch::Alarm",Properties:{AlarmName:j,MetricName:Q,Namespace:G,Statistic:W,Period:z,EvaluationPeriods:U,Threshold:H,ComparisonOperator:F,TreatMissingData:B,ActionsEnabled:K}};if(O&&O.length>0)T.Properties.AlarmActions=O;if(V&&V.length>0)T.Properties.OKActions=V;if(A&&A.length>0)T.Properties.InsufficientDataActions=A;if(_)T.Properties.Dimensions=Object.entries(_).map(([D,S])=>({Name:D,Value:S}));if(M)T.Properties.Unit=M;if(E!==void 0)T.Properties.DatapointsToAlarm=E;return{alarm:T,logicalId:q}}static createCompositeAlarm($){let{slug:J,environment:Y,alarmName:Z,alarmRule:Q,actionsEnabled:G=!0,alarmActions:W,okActions:z,insufficientDataActions:U}=$,H=Z||f({slug:J,environment:Y,resourceType:"composite-alarm"}),F=x(H),B={Type:"AWS::CloudWatch::CompositeAlarm",Properties:{AlarmName:H,AlarmRule:Q,ActionsEnabled:G}};if(W&&W.length>0)B.Properties.AlarmActions=W;if(z&&z.length>0)B.Properties.OKActions=z;if(U&&U.length>0)B.Properties.InsufficientDataActions=U;return{alarm:B,logicalId:F}}static createDashboard($){let{slug:J,environment:Y,dashboardName:Z,widgets:Q}=$,G=Z||f({slug:J,environment:Y,resourceType:"dashboard"}),W=x(G),z={widgets:Q.map((H)=>({type:H.type,x:H.x,y:H.y,width:H.width,height:H.height,properties:H.properties}))};return{dashboard:{Type:"AWS::CloudWatch::Dashboard",Properties:{DashboardName:G,DashboardBody:JSON.stringify(z)}},logicalId:W}}static createLogGroup($){let{slug:J,environment:Y,logGroupName:Z,retentionInDays:Q,kmsKeyId:G}=$,W=Z||f({slug:J,environment:Y,resourceType:"log-group"}),z=x(W),U={Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:W}};if(Q!==void 0)U.Properties.RetentionInDays=Q;if(G)U.Properties.KmsKeyId=G;return{logGroup:U,logicalId:z}}static createLogStream($,J){let{slug:Y,environment:Z,logStreamName:Q}=J,G=Q||f({slug:Y,environment:Z,resourceType:"log-stream"}),W=x(G);return{logStream:{Type:"AWS::Logs::LogStream",Properties:{LogGroupName:l.Ref($),LogStreamName:G}},logicalId:W}}static createMetricFilter($,J){let{slug:Y,environment:Z,filterName:Q,filterPattern:G,metricTransformations:W}=J,z=Q||f({slug:Y,environment:Z,resourceType:"metric-filter"}),U=x(z);return{metricFilter:{Type:"AWS::Logs::MetricFilter",Properties:{LogGroupName:l.Ref($),FilterPattern:G,MetricTransformations:W.map((F)=>({MetricName:F.metricName,MetricNamespace:F.metricNamespace,MetricValue:F.metricValue,DefaultValue:F.defaultValue,Unit:F.unit}))}},logicalId:U}}static AlarmTypes={highCpu:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-cpu`,metricName:"CPUUtilization",namespace:"AWS/EC2",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0}),highMemory:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-memory`,metricName:"MemoryUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0}),highDisk:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-high-disk`,metricName:"DiskSpaceUtilization",namespace:"System/Linux",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y,Filesystem:"/dev/xvda1",MountPath:"/"},alarmActions:Q?[Q]:void 0}),lambdaErrors:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-errors`,metricName:"Errors",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:Q?[Q]:void 0}),lambdaThrottles:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-lambda-throttles`,metricName:"Throttles",namespace:"AWS/Lambda",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{FunctionName:Y},alarmActions:Q?[Q]:void 0}),apiGateway5xxErrors:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-5xx-errors`,metricName:"5XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:Q?[Q]:void 0}),apiGateway4xxErrors:($,J,Y,Z=50,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-api-4xx-errors`,metricName:"4XXError",namespace:"AWS/ApiGateway",statistic:"Sum",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApiName:Y},alarmActions:Q?[Q]:void 0}),dynamoDBThrottles:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-dynamodb-throttles`,metricName:"UserErrors",namespace:"AWS/DynamoDB",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{TableName:Y},alarmActions:Q?[Q]:void 0}),rdsCpu:($,J,Y,Z=80,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-cpu`,metricName:"CPUUtilization",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:Q?[Q]:void 0}),rdsFreeStorage:($,J,Y,Z=5368709120,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-rds-storage`,metricName:"FreeStorageSpace",namespace:"AWS/RDS",statistic:"Average",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"LessThanThreshold",dimensions:{DBInstanceIdentifier:Y},alarmActions:Q?[Q]:void 0,unit:"Bytes"}),sqsQueueDepth:($,J,Y,Z=100,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-sqs-depth`,metricName:"ApproximateNumberOfMessagesVisible",namespace:"AWS/SQS",statistic:"Average",period:300,evaluationPeriods:2,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{QueueName:Y},alarmActions:Q?[Q]:void 0}),albUnhealthyTargets:($,J,Y,Z,Q=1,G)=>({slug:$,environment:J,alarmName:`${$}-${J}-alb-unhealthy`,metricName:"UnHealthyHostCount",namespace:"AWS/ApplicationELB",statistic:"Average",period:300,evaluationPeriods:2,threshold:Q,comparisonOperator:"GreaterThanThreshold",dimensions:{LoadBalancer:Y,TargetGroup:Z},alarmActions:G?[G]:void 0}),sesBounceRate:($,J,Y=5,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-bounce-rate`,metricName:"Reputation.BounceRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),sesComplaintRate:($,J,Y=0.1,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-ses-complaint-rate`,metricName:"Reputation.ComplaintRate",namespace:"AWS/SES",statistic:"Average",period:3600,evaluationPeriods:1,threshold:Y/100,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),smsDeliveryFailure:($,J,Y,Z=10,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-delivery-failure`,metricName:"DirectSendMessagePermanentFailure",namespace:"AWS/Pinpoint",statistic:"Sum",period:300,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{ApplicationId:Y},alarmActions:Q?[Q]:void 0}),smsSpendLimit:($,J,Y=100,Z)=>({slug:$,environment:J,alarmName:`${$}-${J}-sms-spend-limit`,metricName:"DirectSendMessageSpend",namespace:"AWS/Pinpoint",statistic:"Sum",period:86400,evaluationPeriods:1,threshold:Y,comparisonOperator:"GreaterThanThreshold",alarmActions:Z?[Z]:void 0}),connectMissedCalls:($,J,Y,Z=5,Q)=>({slug:$,environment:J,alarmName:`${$}-${J}-connect-missed-calls`,metricName:"MissedCalls",namespace:"AWS/Connect",statistic:"Sum",period:3600,evaluationPeriods:1,threshold:Z,comparisonOperator:"GreaterThanThreshold",dimensions:{InstanceId:Y},alarmActions:Q?[Q]:void 0})};static DashboardWidgets={metric:($,J,Y,Z,Q,G)=>({type:"metric",x:$,y:J,width:Y,height:Z,properties:{metrics:Q,title:G||"Metrics",region:"us-east-1",period:300}}),text:($,J,Y,Z,Q)=>({type:"text",x:$,y:J,width:Y,height:Z,properties:{markdown:Q}}),log:($,J,Y,Z,Q,G)=>({type:"log",x:$,y:J,width:Y,height:Z,properties:{query:`SOURCE '${Q.join("' | SOURCE '")}'
|
|
5841
5841
|
| fields @timestamp, @message
|
|
5842
5842
|
| sort @timestamp desc
|
|
5843
5843
|
| limit 20`,region:"us-east-1",title:G||"Logs"}})};static RetentionPeriods={ONE_DAY:1,THREE_DAYS:3,FIVE_DAYS:5,ONE_WEEK:7,TWO_WEEKS:14,ONE_MONTH:30,TWO_MONTHS:60,THREE_MONTHS:90,FOUR_MONTHS:120,FIVE_MONTHS:150,SIX_MONTHS:180,ONE_YEAR:365,THIRTEEN_MONTHS:400,EIGHTEEN_MONTHS:545,TWO_YEARS:731,FIVE_YEARS:1827,TEN_YEARS:3653,NEVER_EXPIRE:void 0};static FilterPatterns={errors:"[time, request_id, event_type = ERROR*, ...]",all:"",jsonField:($,J)=>`{ $.${$} = "${J}" }`,httpStatus:($)=>`[..., status_code = ${$}, ...]`,http4xx:"[..., status_code = 4*, ...]",http5xx:"[..., status_code = 5*, ...]"};static createApplicationDashboard($){let{slug:J,environment:Y,region:Z="us-east-1",components:Q={}}=$,G=[],W=0;if(G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:`# ${J.toUpperCase()} Dashboard (${Y})`}}),W+=1,Q.ec2InstanceIds&&Q.ec2InstanceIds.length>0)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## EC2 Instances"}}),W+=1,G.push({type:"metric",x:0,y:W,width:8,height:6,properties:{title:"CPU Utilization",region:Z,metrics:Q.ec2InstanceIds.map((z)=>["AWS/EC2","CPUUtilization","InstanceId",z]),period:300,stat:"Average"}}),G.push({type:"metric",x:8,y:W,width:8,height:6,properties:{title:"Network Traffic",region:Z,metrics:[...Q.ec2InstanceIds.flatMap((z)=>[["AWS/EC2","NetworkIn","InstanceId",z,{label:`${z} In`}],["AWS/EC2","NetworkOut","InstanceId",z,{label:`${z} Out`}]])],period:300,stat:"Sum"}}),G.push({type:"metric",x:16,y:W,width:8,height:6,properties:{title:"Status Checks",region:Z,metrics:Q.ec2InstanceIds.map((z)=>["AWS/EC2","StatusCheckFailed","InstanceId",z]),period:60,stat:"Maximum"}}),W+=6;if(Q.lambdaFunctionNames&&Q.lambdaFunctionNames.length>0)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## Lambda Functions"}}),W+=1,G.push({type:"metric",x:0,y:W,width:8,height:6,properties:{title:"Invocations",region:Z,metrics:Q.lambdaFunctionNames.map((z)=>["AWS/Lambda","Invocations","FunctionName",z]),period:300,stat:"Sum"}}),G.push({type:"metric",x:8,y:W,width:8,height:6,properties:{title:"Duration",region:Z,metrics:Q.lambdaFunctionNames.map((z)=>["AWS/Lambda","Duration","FunctionName",z]),period:300,stat:"Average"}}),G.push({type:"metric",x:16,y:W,width:8,height:6,properties:{title:"Errors",region:Z,metrics:Q.lambdaFunctionNames.map((z)=>["AWS/Lambda","Errors","FunctionName",z]),period:300,stat:"Sum"}}),W+=6;if(Q.ecsClusterName&&Q.ecsServiceName)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## ECS Service"}}),W+=1,G.push({type:"metric",x:0,y:W,width:8,height:6,properties:{title:"CPU Utilization",region:Z,metrics:[["AWS/ECS","CPUUtilization","ClusterName",Q.ecsClusterName,"ServiceName",Q.ecsServiceName]],period:300,stat:"Average"}}),G.push({type:"metric",x:8,y:W,width:8,height:6,properties:{title:"Memory Utilization",region:Z,metrics:[["AWS/ECS","MemoryUtilization","ClusterName",Q.ecsClusterName,"ServiceName",Q.ecsServiceName]],period:300,stat:"Average"}}),G.push({type:"metric",x:16,y:W,width:8,height:6,properties:{title:"Running Tasks",region:Z,metrics:[["ECS/ContainerInsights","RunningTaskCount","ClusterName",Q.ecsClusterName,"ServiceName",Q.ecsServiceName]],period:60,stat:"Average"}}),W+=6;if(Q.albName)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## Application Load Balancer"}}),W+=1,G.push({type:"metric",x:0,y:W,width:8,height:6,properties:{title:"Request Count",region:Z,metrics:[["AWS/ApplicationELB","RequestCount","LoadBalancer",Q.albName]],period:60,stat:"Sum"}}),G.push({type:"metric",x:8,y:W,width:8,height:6,properties:{title:"Response Time",region:Z,metrics:[["AWS/ApplicationELB","TargetResponseTime","LoadBalancer",Q.albName]],period:60,stat:"Average"}}),G.push({type:"metric",x:16,y:W,width:8,height:6,properties:{title:"HTTP Errors",region:Z,metrics:[["AWS/ApplicationELB","HTTPCode_Target_4XX_Count","LoadBalancer",Q.albName,{label:"4XX"}],["AWS/ApplicationELB","HTTPCode_Target_5XX_Count","LoadBalancer",Q.albName,{label:"5XX"}]],period:60,stat:"Sum"}}),W+=6;if(Q.rdsInstanceId)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## RDS Database"}}),W+=1,G.push({type:"metric",x:0,y:W,width:8,height:6,properties:{title:"CPU Utilization",region:Z,metrics:[["AWS/RDS","CPUUtilization","DBInstanceIdentifier",Q.rdsInstanceId]],period:300,stat:"Average"}}),G.push({type:"metric",x:8,y:W,width:8,height:6,properties:{title:"Database Connections",region:Z,metrics:[["AWS/RDS","DatabaseConnections","DBInstanceIdentifier",Q.rdsInstanceId]],period:60,stat:"Sum"}}),G.push({type:"metric",x:16,y:W,width:8,height:6,properties:{title:"Free Storage Space",region:Z,metrics:[["AWS/RDS","FreeStorageSpace","DBInstanceIdentifier",Q.rdsInstanceId]],period:300,stat:"Average"}}),W+=6;if(Q.sqsQueueNames&&Q.sqsQueueNames.length>0)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## SQS Queues"}}),W+=1,G.push({type:"metric",x:0,y:W,width:12,height:6,properties:{title:"Messages Visible",region:Z,metrics:Q.sqsQueueNames.map((z)=>["AWS/SQS","ApproximateNumberOfMessagesVisible","QueueName",z]),period:60,stat:"Sum"}}),G.push({type:"metric",x:12,y:W,width:12,height:6,properties:{title:"Message Age",region:Z,metrics:Q.sqsQueueNames.map((z)=>["AWS/SQS","ApproximateAgeOfOldestMessage","QueueName",z]),period:60,stat:"Maximum"}}),W+=6;if(Q.logGroupNames&&Q.logGroupNames.length>0)G.push({type:"text",x:0,y:W,width:24,height:1,properties:{markdown:"## Application Logs"}}),W+=1,G.push({type:"log",x:0,y:W,width:24,height:6,properties:{query:`SOURCE '${Q.logGroupNames.join("' | SOURCE '")}'
|
|
@@ -5907,7 +5907,7 @@ Details:`;for(let[J,Y]of Object.entries(this.details))$+=`
|
|
|
5907
5907
|
1. Set environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
|
|
5908
5908
|
2. Create ~/.aws/credentials file with your credentials
|
|
5909
5909
|
3. Use an IAM role (for EC2 instances)
|
|
5910
|
-
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};F1={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};R_=new cJ;a_={$schema:"http://json-schema.org/draft-07/schema#",title:"ts-cloud Configuration",description:"Configuration schema for ts-cloud infrastructure-as-code",type:"object",required:["project"],properties:{project:{type:"object",description:"Project configuration",required:["name","slug"],properties:{name:{type:"string",description:"Human-readable project name",minLength:1},slug:{type:"string",description:"URL-safe project identifier (lowercase, alphanumeric, hyphens only)",pattern:"^[a-z0-9-]+$",minLength:1,maxLength:63},region:{type:"string",description:"Default AWS region",enum:["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"]}}},mode:{type:"string",description:"Deployment mode",enum:["server","serverless","hybrid"],default:"serverless"},environments:{type:"object",description:"Environment-specific configurations",properties:{production:{$ref:"#/definitions/environment"},staging:{$ref:"#/definitions/environment"},development:{$ref:"#/definitions/environment"}}},infrastructure:{type:"object",description:"Infrastructure configuration",properties:{network:{$ref:"#/definitions/network"},storage:{type:"object",description:"S3 storage configuration",additionalProperties:{$ref:"#/definitions/storage"}},compute:{$ref:"#/definitions/compute"},database:{$ref:"#/definitions/database"},cache:{$ref:"#/definitions/cache"},cdn:{$ref:"#/definitions/cdn"},functions:{type:"object",description:"Lambda functions configuration",additionalProperties:{type:"array",items:{$ref:"#/definitions/function"}}},monitoring:{$ref:"#/definitions/monitoring"},security:{$ref:"#/definitions/security"},queue:{type:"object",description:"SQS queue configuration",additionalProperties:{$ref:"#/definitions/queue"}}}}},definitions:{environment:{type:"object",properties:{domain:{type:"string",description:"Custom domain for this environment"},region:{type:"string",description:"AWS region override for this environment"},app:{type:"object",description:"Serverless application manifest (Laravel-Vapor-equivalent). Defining this opts the environment into the serverless app deploy pipeline (http/queue/cli Lambda functions, assets, build/deploy hooks).",properties:{runtime:{type:"string",description:"Lambda runtime override (usually derived from kind + runtimeVersion)"},runtimeVersion:{type:"string",description:"Node major (18/20/22 managed, 24+ custom layer) or Bun release for node/bun apps"},kind:{type:"string",enum:["node","bun","php"],description:"Application kind (drives packaging + runtime)"},entry:{type:"string",description:"Entry file exporting the request handler"},memory:{type:"number",description:"HTTP function memory in MB"},timeout:{type:"number",description:"HTTP request timeout in seconds"},gatewayVersion:{type:"number",enum:[1,2],description:"API Gateway version (2 = HTTP API, 1 = REST)"},warm:{type:"number",description:"Keep-warm / provisioned concurrency count"},queues:{description:"Queue names (true = single default queue, false = disabled)"},scheduler:{type:"string",enum:["off","on","sub-minute"],description:"Task scheduler mode"},build:{type:"array",items:{type:"string"},description:"Commands run locally before packaging"},deploy:{type:"array",items:{type:"string"},description:"Commands run remotely after activation (e.g. migrations)"},octane:{type:"boolean",description:"Persistent application mode (Laravel Octane)"},packaging:{type:"string",enum:["zip","image"],description:"Deployment package format (zip or container image)"},phpVersion:{type:"string",description:"PHP version for the runtime layer (kind: php)"},architecture:{type:"string",enum:["x86_64","arm64"],description:"CPU architecture"}}}}},network:{type:"object",properties:{vpc:{type:"object",properties:{cidr:{type:"string",description:"VPC CIDR block",pattern:"^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$",default:"10.0.0.0/16"},availabilityZones:{type:"number",description:"Number of availability zones",minimum:1,maximum:3,default:2},natGateways:{type:"number",description:"Number of NAT gateways (0 for no NAT, saves cost)",minimum:0,maximum:3,default:1}}}}},storage:{type:"object",properties:{public:{type:"boolean",description:"Allow public access",default:!1},versioning:{type:"boolean",description:"Enable versioning",default:!1},encryption:{type:"boolean",description:"Enable server-side encryption",default:!0},website:{type:"boolean",description:"Enable static website hosting",default:!1},cors:{type:"object",description:"CORS configuration",properties:{allowedOrigins:{type:"array",items:{type:"string"}},allowedMethods:{type:"array",items:{type:"string",enum:["GET","PUT","POST","DELETE","HEAD"]}}}}}},compute:{type:"object",properties:{server:{type:"object",description:"EC2 server configuration",properties:{instanceType:{type:"string",description:"EC2 instance type",enum:["t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge"]},autoScaling:{type:"object",properties:{min:{type:"number",minimum:1},max:{type:"number",minimum:1},desired:{type:"number",minimum:1}}}}},fargate:{type:"object",description:"ECS Fargate configuration",properties:{cpu:{type:"number",description:"CPU units (256, 512, 1024, 2048, 4096)",enum:[256,512,1024,2048,4096]},memory:{type:"number",description:"Memory in MB"},desiredCount:{type:"number",description:"Desired number of tasks",minimum:1}}}}},database:{type:"object",properties:{postgres:{type:"object",properties:{instanceClass:{type:"string",description:"RDS instance class",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"postgres"},version:{type:"string",description:"PostgreSQL version"},multiAZ:{type:"boolean",description:"Enable Multi-AZ deployment",default:!1},backupRetentionDays:{type:"number",description:"Backup retention period in days",minimum:0,maximum:35,default:7}}},mysql:{type:"object",properties:{instanceClass:{type:"string",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"mysql"},version:{type:"string"},multiAZ:{type:"boolean",default:!1},backupRetentionDays:{type:"number",minimum:0,maximum:35,default:7}}},dynamodb:{type:"object",properties:{tables:{type:"array",items:{type:"object",required:["name","partitionKey"],properties:{name:{type:"string"},partitionKey:{type:"string"},sortKey:{type:"string"},billingMode:{type:"string",enum:["PAY_PER_REQUEST","PROVISIONED"],default:"PAY_PER_REQUEST"}}}}}}}},cache:{type:"object",properties:{redis:{type:"object",properties:{nodeType:{type:"string",description:"ElastiCache node type",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1},engineVersion:{type:"string",description:"Redis engine version"}}},memcached:{type:"object",properties:{nodeType:{type:"string",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1}}}}},cdn:{type:"object",properties:{enabled:{type:"boolean",default:!0},compress:{type:"boolean",description:"Enable automatic compression",default:!0},http3:{type:"boolean",description:"Enable HTTP/3 support",default:!0},customDomain:{type:"object",properties:{domain:{type:"string"},certificateArn:{type:"string"}}},cachePolicy:{type:"object",properties:{minTTL:{type:"number",minimum:0},defaultTTL:{type:"number",minimum:0},maxTTL:{type:"number",minimum:0}}}}},function:{type:"object",required:["name","runtime"],properties:{name:{type:"string"},runtime:{type:"string",enum:["nodejs18.x","nodejs20.x","python3.10","python3.11","python3.12"]},handler:{type:"string",default:"index.handler"},timeout:{type:"number",minimum:1,maximum:900,default:30},memory:{type:"number",minimum:128,maximum:10240,default:1024}}},monitoring:{type:"object",properties:{alarms:{type:"array",items:{type:"object",required:["metric","threshold"],properties:{metric:{type:"string"},threshold:{type:"number"},evaluationPeriods:{type:"number",minimum:1,default:2}}}},dashboard:{type:"object",properties:{name:{type:"string"},widgets:{type:"array"}}}}},security:{type:"object",properties:{waf:{type:"boolean",description:"Enable AWS WAF",default:!1},certificates:{type:"array",items:{type:"object",required:["domain"],properties:{domain:{type:"string"},subdomains:{type:"array",items:{type:"string"}}}}}}},queue:{type:"object",properties:{fifo:{type:"boolean",default:!1},deadLetterQueue:{type:"boolean",default:!0},visibilityTimeout:{type:"number",minimum:0,maximum:43200,default:30},messageRetentionPeriod:{type:"number",minimum:60,maximum:1209600,default:345600}}}}};rJ={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};Yj=new tJ;Wj=new sJ;Pj=new eJ;Cj=new $Y,xj=new JY,Ij=new YY,kj=new ZY,r1=[{code:"us-east-1",name:"US East (N. Virginia)",location:"Virginia, USA",launchYear:2006,availabilityZones:6,localZones:16,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO","FedRAMP"]},{code:"us-east-2",name:"US East (Ohio)",location:"Ohio, USA",launchYear:2016,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-1",name:"US West (N. California)",location:"California, USA",launchYear:2009,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-2",name:"US West (Oregon)",location:"Oregon, USA",launchYear:2011,availabilityZones:4,localZones:2,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"eu-west-1",name:"Europe (Ireland)",location:"Dublin, Ireland",launchYear:2007,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1.05},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"eu-central-1",name:"Europe (Frankfurt)",location:"Frankfurt, Germany",launchYear:2014,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"ap-southeast-1",name:"Asia Pacific (Singapore)",location:"Singapore",launchYear:2010,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.12},compliance:["PCI-DSS","SOC","ISO","MTCS"]},{code:"ap-northeast-1",name:"Asia Pacific (Tokyo)",location:"Tokyo, Japan",launchYear:2011,availabilityZones:4,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.15},compliance:["PCI-DSS","SOC","ISO"]}];rj=new QY,nj=new GY,ZU={basic:{name:"Basic (3 Accounts)",description:"Simple structure for small teams",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account for AWS Organizations"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production workloads"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development and testing"}],organizationalUnits:[{name:"root"},{name:"workloads",parent:"root"}]},standard:{name:"Standard (5 Accounts)",description:"Recommended for most organizations",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"security",email:"aws+security@example.com",role:"security",ou:"security",description:"Security tooling and audit logs"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared services (CI/CD, monitoring)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production environment"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"workloads",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root"},{name:"infrastructure",parent:"root"},{name:"workloads",parent:"root"}]},enterprise:{name:"Enterprise (7+ Accounts)",description:"For large organizations with strict compliance requirements",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"audit",email:"aws+audit@example.com",role:"security",ou:"security",description:"Audit and compliance"},{alias:"log-archive",email:"aws+logs@example.com",role:"security",ou:"security",description:"Centralized log storage"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared infrastructure"},{alias:"network",email:"aws+network@example.com",role:"shared-services",ou:"infrastructure",description:"Network infrastructure (Transit Gateway)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"production-ou",description:"Production workloads"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"non-production-ou",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"non-production-ou",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root",policies:["deny-root-access"]},{name:"infrastructure",parent:"root"},{name:"production-ou",parent:"root",policies:["require-mfa"]},{name:"non-production-ou",parent:"root"}]}},ij={denyRootAccess:{name:"Deny Root User Access",description:"Prevent root user from performing any actions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyRootUser",Effect:"Deny",Action:"*",Resource:"*",Condition:{StringLike:{"aws:PrincipalArn":"arn:aws:iam::*:root"}}}]}},requireMFA:{name:"Require MFA for All Actions",description:"Require MFA for console and API access",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"RequireMFA",Effect:"Deny",Action:"*",Resource:"*",Condition:{BoolIfExists:{"aws:MultiFactorAuthPresent":"false"}}}]}},denyRegions:{name:"Deny Access to Non-Approved Regions",description:"Restrict operations to specific regions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyNonApprovedRegions",Effect:"Deny",NotAction:["iam:*","organizations:*","route53:*","cloudfront:*","support:*","s3:*"],Resource:"*",Condition:{StringNotEquals:{"aws:RequestedRegion":["us-east-1","us-west-2"]}}}]}},preventLeaving:{name:"Prevent Leaving Organization",description:"Prevent accounts from leaving the organization",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"PreventLeaving",Effect:"Deny",Action:"organizations:LeaveOrganization",Resource:"*"}]}},denyS3Unencrypted:{name:"Deny Unencrypted S3 Uploads",description:"Require encryption for all S3 uploads",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyUnencryptedS3Uploads",Effect:"Deny",Action:"s3:PutObject",Resource:"*",Condition:{StringNotEquals:{"s3:x-amz-server-side-encryption":["AES256","aws:kms"]}}}]}}},aj={deploymentRole:{name:"CrossAccountDeploymentRole",description:"Role for deploying infrastructure from CI/CD",permissions:["cloudformation:*","s3:*","ec2:*","ecs:*","lambda:*","iam:GetRole","iam:PassRole","logs:*","events:*"]},readOnlyRole:{name:"CrossAccountReadOnlyRole",description:"Read-only access for monitoring and auditing",permissions:["cloudformation:Describe*","cloudformation:List*","ec2:Describe*","ecs:Describe*","lambda:Get*","lambda:List*","s3:Get*","s3:List*","logs:Get*","logs:Describe*"]},securityAuditRole:{name:"CrossAccountSecurityAuditRole",description:"Security audit and compliance checks",permissions:["iam:Get*","iam:List*","iam:Generate*","access-analyzer:*","guardduty:Get*","guardduty:List*","securityhub:Get*","securityhub:List*","config:Describe*","config:Get*","config:List*"]},breakGlassRole:{name:"CrossAccountBreakGlassRole",description:"Emergency access role (use with caution)",permissions:["*"]}};AL=new WY;VL=new zY;_L=new UY;jL=new HY;LL=new FY;J$=class J${hubs=new Map;hubCounter=0;ruleCounter=0;static Standards={AWS_FOUNDATIONAL_SECURITY:{arn:"arn:aws:securityhub:::ruleset/aws-foundational-security-best-practices/v/1.0.0",name:"AWS Foundational Security Best Practices",description:"AWS recommended security best practices"},CIS_AWS_FOUNDATIONS_1_2:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",name:"CIS AWS Foundations Benchmark v1.2.0",description:"CIS AWS Foundations Benchmark v1.2.0"},CIS_AWS_FOUNDATIONS_1_4:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0",name:"CIS AWS Foundations Benchmark v1.4.0",description:"CIS AWS Foundations Benchmark v1.4.0"},PCI_DSS:{arn:"arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1",name:"PCI DSS v3.2.1",description:"Payment Card Industry Data Security Standard"},NIST_800_53:{arn:"arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0",name:"NIST SP 800-53 Rev. 5",description:"NIST Special Publication 800-53 Revision 5"}};createHub($){let J=`hub-${Date.now()}-${this.hubCounter++}`,Y={id:J,...$};return this.hubs.set(J,Y),Y}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...J$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...J$.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...J$.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...J$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0}]})}createLowSeveritySuppressionRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Suppress Low Severity Informational Findings",description:"Automatically suppress informational findings",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Automatically suppressed low severity finding",updatedBy:"SecurityHub Automation"}}}],criteria:{severityLabel:[{value:"INFORMATIONAL",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:1}}createResourceTypeNotificationRule($){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Notify on Critical Resource Findings",description:"Set findings for critical resources to NOTIFIED status",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"NOTIFIED"},note:{text:"Critical resource finding requires attention",updatedBy:"SecurityHub Automation"}}}],criteria:{resourceType:$.map((J)=>({value:J,comparison:"EQUALS"})),severityLabel:[{value:"HIGH",comparison:"EQUALS"},{value:"CRITICAL",comparison:"EQUALS"}],workflowStatus:[{value:"NEW",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:2}}createComplianceFailureRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Flag Compliance Failures",description:"Increase severity for compliance failures",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{severity:{label:"HIGH"},workflow:{status:"NOTIFIED"},note:{text:"Compliance failure detected - requires immediate attention",updatedBy:"SecurityHub Automation"}}}],criteria:{complianceStatus:[{value:"FAILED",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:3}}createFalsePositiveSuppressionRule($,J){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:`Suppress False Positives - ${$}`,description:`Automatically suppress known false positives from ${$}`,actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Known false positive - automatically suppressed",updatedBy:"SecurityHub Automation"}}}],criteria:{productName:[{value:$,comparison:"EQUALS"}],title:J.map((Y)=>({value:Y,comparison:"PREFIX"}))},ruleStatus:"ENABLED",ruleOrder:10}}getHub($){return this.hubs.get($)}listHubs(){return Array.from(this.hubs.values())}generateHubCF($){let J={Type:"AWS::SecurityHub::Hub",Properties:{}};if($.controlFindingGenerator)J.Properties.ControlFindingGenerator=$.controlFindingGenerator;if($.enableDefaultStandards!==void 0)J.Properties.EnableDefaultStandards=$.enableDefaultStandards;return J}generateStandardCF($){let J={Type:"AWS::SecurityHub::Standard",Properties:{StandardsArn:$.arn}};if($.disabledControls&&$.disabledControls.length>0)J.Properties.DisabledStandardsControls=$.disabledControls.map((Y)=>({StandardsControlArn:Y,Reason:"Disabled by configuration"}));return J}generateAutomationRuleCF($){return{Type:"AWS::SecurityHub::AutomationRule",Properties:{RuleName:$.ruleName,Description:$.description,Actions:$.actions.map((J)=>({Type:J.type,FindingFieldsUpdate:J.findingFieldsUpdate})),Criteria:$.criteria,RuleStatus:$.ruleStatus,RuleOrder:$.ruleOrder}}}clear(){this.hubs.clear(),this.hubCounter=0,this.ruleCounter=0}};EL=new J$;ML=new XY;y8=class y8{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;static Strategies={CONSERVATIVE:[{name:"Initial Canary",trafficPercentage:10,durationMinutes:10},{name:"Quarter Traffic",trafficPercentage:25,durationMinutes:10},{name:"Half Traffic",trafficPercentage:50,durationMinutes:15},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],BALANCED:[{name:"Initial Canary",trafficPercentage:20,durationMinutes:5},{name:"Half Traffic",trafficPercentage:50,durationMinutes:10},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],AGGRESSIVE:[{name:"Half Traffic",trafficPercentage:50,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],LINEAR_10:[{name:"Canary 10%",trafficPercentage:10,durationMinutes:5},{name:"Canary 20%",trafficPercentage:20,durationMinutes:5},{name:"Canary 30%",trafficPercentage:30,durationMinutes:5},{name:"Canary 40%",trafficPercentage:40,durationMinutes:5},{name:"Canary 50%",trafficPercentage:50,durationMinutes:5},{name:"Canary 60%",trafficPercentage:60,durationMinutes:5},{name:"Canary 70%",trafficPercentage:70,durationMinutes:5},{name:"Canary 80%",trafficPercentage:80,durationMinutes:5},{name:"Canary 90%",trafficPercentage:90,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}]};createDeployment($){let J=`canary-${Date.now()}-${this.deploymentCounter++}`,Y={id:J,...$};return this.deployments.set(J,Y),Y}createLambdaCanaryDeployment($){let J=$.strategy||"BALANCED",Y=y8.Strategies[J].map((Z)=>({...Z,alarmThresholds:{errorRate:$.errorRateThreshold||1,latencyP99:$.latencyThreshold||1000}}));return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",functionVersionArn:$.baselineVersionArn,weight:100},canaryVersion:{version:"canary",functionVersionArn:$.canaryVersionArn,weight:0},stages:Y,currentStage:0,status:"pending",autoPromote:$.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment($){let J=$.strategy||"CONSERVATIVE",Y=y8.Strategies[J];return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",taskDefinitionArn:$.baselineTaskDefinitionArn,targetGroupArn:$.baselineTargetGroupArn,weight:100},canaryVersion:{version:"canary",taskDefinitionArn:$.canaryTaskDefinitionArn,targetGroupArn:$.canaryTargetGroupArn,weight:0},stages:Y,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);let Z={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${J?"[DRY RUN] ":""}Starting canary deployment: ${Y.name}`),console.log(` Strategy: ${Y.stages.length} stages`),console.log(` Auto-promote: ${Y.autoPromote}`),console.log(` Auto-rollback: ${Y.autoRollback}`),console.log(""),Y.status="in_progress";for(let Q=0;Q<Y.stages.length;Q++){let G=Y.stages[Q];if(Y.currentStage=Q,console.log(`Stage ${Q+1}/${Y.stages.length}: ${G.name}`),console.log(` Traffic: ${G.trafficPercentage}% canary, ${100-G.trafficPercentage}% baseline`),console.log(` Duration: ${G.durationMinutes} minutes`),!J)Y.baselineVersion.weight=100-G.trafficPercentage,Y.canaryVersion.weight=G.trafficPercentage;if(!await this.monitorStage(Y,G,J)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),Y.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback($,J),Z.rolledBack=!0,Z.reason="Metrics exceeded thresholds";return Z.endTime=new Date,Y.status="rolled_back",this.recordDeployment($,Z),Z}console.log(" ✓ Stage completed successfully"),Z.completedStages++,console.log("")}return Y.status="completed",Z.success=!0,Z.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment($,Z),Z}async monitorStage($,J,Y){if(console.log(" Monitoring metrics..."),Y)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((Q)=>setTimeout(Q,100));let Z={baselineErrorRate:Math.random()*0.5,canaryErrorRate:Math.random()*0.8,baselineLatencyP99:200+Math.random()*100,canaryLatencyP99:180+Math.random()*150,baselineRequestCount:Math.floor(Math.random()*1000)+500,canaryRequestCount:Math.floor((Math.random()*1000+500)*J.trafficPercentage/100)};if($.metrics=Z,console.log(` Baseline: ${Z.baselineErrorRate.toFixed(2)}% errors, ${Z.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${Z.canaryErrorRate.toFixed(2)}% errors, ${Z.canaryLatencyP99.toFixed(0)}ms P99`),J.alarmThresholds){let{errorRate:Q,latencyP99:G}=J.alarmThresholds;if(Q&&Z.canaryErrorRate>Q)return console.log(` ⚠ Error rate exceeded threshold: ${Z.canaryErrorRate.toFixed(2)}% > ${Q}%`),!1;if(G&&Z.canaryLatencyP99>G)return console.log(` ⚠ Latency P99 exceeded threshold: ${Z.canaryLatencyP99.toFixed(0)}ms > ${G}ms`),!1}return!0}async rollback($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);if(console.log(`${J?"[DRY RUN] ":""}Rolling back canary deployment: ${Y.name}`),!J)Y.baselineVersion.weight=100,Y.canaryVersion.weight=0,Y.status="rolled_back";console.log(" Traffic restored to baseline: 100%")}promoteCanary($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);console.log(`Promoting canary to baseline: ${J.name}`);let Y=J.baselineVersion;J.baselineVersion=J.canaryVersion,J.canaryVersion=Y,J.baselineVersion.weight=100,J.canaryVersion.weight=0,J.status="completed",console.log(" Canary promoted successfully")}recordDeployment($,J){if(!this.deploymentHistory.has($))this.deploymentHistory.set($,[]);this.deploymentHistory.get($).push(J)}getDeployment($){return this.deployments.get($)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory($){return this.deploymentHistory.get($)||[]}generateLambdaAliasCF($,J){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:{Ref:"LambdaFunction"},Name:J,FunctionVersion:$.canaryVersion.version,RoutingConfig:{AdditionalVersionWeights:[{FunctionVersion:$.baselineVersion.version,FunctionWeight:$.baselineVersion.weight/100}]}}}}generateALBListenerRuleCF($){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:[{TargetGroupArn:$.baselineVersion.targetGroupArn,Weight:$.baselineVersion.weight},{TargetGroupArn:$.canaryVersion.targetGroupArn,Weight:$.canaryVersion.weight}],TargetGroupStickinessConfig:{Enabled:!1}}}]}}}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}};qL=new y8;TL=new BY;wL=new KY;DL=new OY;RL=new AY;NL=new VY;Y$=class Y${canaries=new Map;heartbeats=new Map;apiMonitors=new Map;canaryCounter=0;heartbeatCounter=0;apiMonitorCounter=0;alarmCounter=0;static RuntimeVersions={NODEJS_PUPPETEER_3_9:"syn-nodejs-puppeteer-3.9",NODEJS_PUPPETEER_4_0:"syn-nodejs-puppeteer-4.0",PYTHON_SELENIUM_1_3:"syn-python-selenium-1.3"};createCanary($){let J=`canary-${Date.now()}-${this.canaryCounter++}`,Y={id:J,...$};return this.canaries.set(J,Y),Y}createHeartbeatCanary($){let J=`
|
|
5910
|
+
4. Run 'aws configure' if you have AWS CLI installed`},INVALID_CREDENTIALS:{message:"AWS credentials are invalid",solution:"Verify your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are correct. Run: aws sts get-caller-identity"},EXPIRED_CREDENTIALS:{message:"AWS credentials have expired",solution:"Refresh your AWS credentials. If using temporary credentials, generate new ones."},MISSING_CONFIG:{message:"Configuration file not found",solution:"Create a cloud.config.ts file in your project root. Use: cloud init"},INVALID_CONFIG:{message:"Configuration is invalid",solution:"Check your cloud.config.ts file for syntax errors. Use: cloud config:validate"},MISSING_REQUIRED_FIELD:{message:"Required configuration field is missing",solution:"Add the missing field to your cloud.config.ts file"},INVALID_REGION:{message:"AWS region is invalid",solution:"Use a valid AWS region like us-east-1, us-west-2, eu-west-1, etc."},STACK_ALREADY_EXISTS:{message:"CloudFormation stack already exists",solution:"Use: cloud deploy --update to update the existing stack, or cloud destroy to delete it first"},STACK_IN_PROGRESS:{message:"Stack operation already in progress",solution:"Wait for the current operation to complete, or cancel it in the AWS Console"},INSUFFICIENT_PERMISSIONS:{message:"Insufficient IAM permissions",solution:"Ensure your IAM user/role has the necessary permissions for CloudFormation and the resources you're deploying"},RESOURCE_LIMIT_EXCEEDED:{message:"AWS service limit exceeded",solution:"Request a service limit increase in the AWS Console, or clean up unused resources"},ROLLBACK_COMPLETE:{message:"Stack creation failed and rolled back",solution:"Check the CloudFormation events to see which resource failed. Fix the issue and try again."},CIRCULAR_DEPENDENCY:{message:"Circular dependency detected in resources",solution:"Review your resource dependencies and remove the circular reference"},INVALID_RESOURCE_NAME:{message:"Resource name contains invalid characters",solution:"Use only alphanumeric characters and hyphens in resource names"},DUPLICATE_RESOURCE:{message:"Duplicate resource name detected",solution:"Ensure all resource names are unique in your configuration"},VPC_CIDR_CONFLICT:{message:"VPC CIDR block conflicts with existing VPC",solution:"Use a different CIDR block that doesn't overlap with existing VPCs"},SUBNET_CIDR_INVALID:{message:"Subnet CIDR block is invalid or outside VPC range",solution:"Ensure subnet CIDR is within the VPC CIDR range and properly sized"},DB_INSTANCE_LIMIT:{message:"RDS instance limit reached",solution:"Delete unused RDS instances or request a limit increase"},INVALID_DB_NAME:{message:"Database name contains invalid characters",solution:"Use only alphanumeric characters and underscores, starting with a letter"},BUCKET_ALREADY_EXISTS:{message:"S3 bucket name already exists globally",solution:"S3 bucket names must be globally unique. Try a different name with your organization prefix"},INVALID_BUCKET_NAME:{message:"S3 bucket name is invalid",solution:"Use lowercase letters, numbers, and hyphens. Must start/end with letter/number. 3-63 characters."},TEMPLATE_TOO_LARGE:{message:"CloudFormation template exceeds size limit",solution:"Split your infrastructure into multiple stacks or use nested stacks"},INVALID_TEMPLATE:{message:"CloudFormation template is invalid",solution:"Validate your template with: cloud config:validate"},PARAMETER_NOT_FOUND:{message:"CloudFormation parameter not found",solution:"Check that all referenced parameters are defined in your template"}};F1={ec2:{"Running On-Demand Instances":20,"Elastic IPs":5,VPCs:5,"Internet Gateways":5,"NAT Gateways":5,"Security Groups":500},rds:{"DB Instances":40,"DB Snapshots":100,"DB Parameter Groups":50},lambda:{"Concurrent Executions":1000,"Function Storage":80530636800},s3:{Buckets:100},cloudformation:{Stacks:200,StackSets:100},elasticache:{Nodes:100,Clusters:100},dynamodb:{Tables:256},ecs:{Clusters:1e4,"Services per Cluster":2000}};R_=new cJ;a_={$schema:"http://json-schema.org/draft-07/schema#",title:"ts-cloud Configuration",description:"Configuration schema for ts-cloud infrastructure-as-code",type:"object",required:["project"],properties:{project:{type:"object",description:"Project configuration",required:["name","slug"],properties:{name:{type:"string",description:"Human-readable project name",minLength:1},slug:{type:"string",description:"URL-safe project identifier (lowercase, alphanumeric, hyphens only)",pattern:"^[a-z0-9-]+$",minLength:1,maxLength:63},region:{type:"string",description:"Default AWS region",enum:["us-east-1","us-east-2","us-west-1","us-west-2","eu-west-1","eu-west-2","eu-west-3","eu-central-1","ap-southeast-1","ap-southeast-2","ap-northeast-1","ap-northeast-2","sa-east-1","ca-central-1"]}}},mode:{type:"string",description:"Deployment mode",enum:["server","serverless","hybrid"],default:"serverless"},environments:{type:"object",description:"Environment-specific configurations",properties:{production:{$ref:"#/definitions/environment"},staging:{$ref:"#/definitions/environment"},development:{$ref:"#/definitions/environment"}}},infrastructure:{type:"object",description:"Infrastructure configuration",properties:{network:{$ref:"#/definitions/network"},storage:{type:"object",description:"S3 storage configuration",additionalProperties:{$ref:"#/definitions/storage"}},compute:{$ref:"#/definitions/compute"},database:{$ref:"#/definitions/database"},cache:{$ref:"#/definitions/cache"},cdn:{$ref:"#/definitions/cdn"},functions:{type:"object",description:"Lambda functions configuration",additionalProperties:{type:"array",items:{$ref:"#/definitions/function"}}},monitoring:{$ref:"#/definitions/monitoring"},security:{$ref:"#/definitions/security"},queue:{type:"object",description:"SQS queue configuration",additionalProperties:{$ref:"#/definitions/queue"}}}}},definitions:{environment:{type:"object",properties:{domain:{type:"string",description:"Custom domain for this environment"},region:{type:"string",description:"AWS region override for this environment"},app:{type:"object",description:"Serverless application manifest (Laravel-Vapor-equivalent). Defining this opts the environment into the serverless app deploy pipeline (http/queue/cli Lambda functions, assets, build/deploy hooks).",properties:{runtime:{type:"string",description:"Lambda runtime override (usually derived from kind + runtimeVersion)"},runtimeVersion:{type:"string",description:"Node major (18/20/22 managed, 24+ custom layer) or Bun release for node/bun apps"},kind:{type:"string",enum:["node","bun","php"],description:"Application kind (drives packaging + runtime)"},entry:{type:"string",description:"Entry file exporting the request handler"},memory:{type:"number",description:"HTTP function memory in MB"},timeout:{type:"number",description:"HTTP request timeout in seconds"},gatewayVersion:{type:"number",enum:[1,2],description:"API Gateway version (2 = HTTP API, 1 = REST)"},warm:{type:"number",description:"Keep-warm / provisioned concurrency count"},queues:{description:"Queue names (true = single default queue, false = disabled)"},scheduler:{type:"string",enum:["off","on","sub-minute"],description:"Task scheduler mode"},build:{type:"array",items:{type:"string"},description:"Commands run locally before packaging"},deploy:{type:"array",items:{type:"string"},description:"Commands run remotely after activation (e.g. migrations)"},octane:{type:"boolean",description:"Persistent application mode (Laravel Octane)"},packaging:{type:"string",enum:["zip","image"],description:"Deployment package format (zip or container image)"},phpVersion:{type:"string",description:"PHP version for the runtime layer (kind: php)"},architecture:{type:"string",enum:["x86_64","arm64"],description:"CPU architecture"}}}}},network:{type:"object",properties:{vpc:{type:"object",properties:{cidr:{type:"string",description:"VPC CIDR block",pattern:"^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$",default:"10.0.0.0/16"},availabilityZones:{type:"number",description:"Number of availability zones",minimum:1,maximum:3,default:2},natGateways:{type:"number",description:"Number of NAT gateways (0 for no NAT, saves cost)",minimum:0,maximum:3,default:1}}}}},storage:{type:"object",properties:{public:{type:"boolean",description:"Allow public access",default:!1},versioning:{type:"boolean",description:"Enable versioning",default:!1},encryption:{type:"boolean",description:"Enable server-side encryption",default:!0},website:{type:"boolean",description:"Enable static website hosting",default:!1},cors:{type:"object",description:"CORS configuration",properties:{allowedOrigins:{type:"array",items:{type:"string"}},allowedMethods:{type:"array",items:{type:"string",enum:["GET","PUT","POST","DELETE","HEAD"]}}}}}},compute:{type:"object",properties:{server:{type:"object",description:"EC2 server configuration",properties:{instanceType:{type:"string",description:"EC2 instance type",enum:["t3.micro","t3.small","t3.medium","t3.large","t3.xlarge","t3.2xlarge"]},autoScaling:{type:"object",properties:{min:{type:"number",minimum:1},max:{type:"number",minimum:1},desired:{type:"number",minimum:1}}}}},fargate:{type:"object",description:"ECS Fargate configuration",properties:{cpu:{type:"number",description:"CPU units (256, 512, 1024, 2048, 4096)",enum:[256,512,1024,2048,4096]},memory:{type:"number",description:"Memory in MB"},desiredCount:{type:"number",description:"Desired number of tasks",minimum:1}}}}},database:{type:"object",properties:{postgres:{type:"object",properties:{instanceClass:{type:"string",description:"RDS instance class",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"postgres"},version:{type:"string",description:"PostgreSQL version"},multiAZ:{type:"boolean",description:"Enable Multi-AZ deployment",default:!1},backupRetentionDays:{type:"number",description:"Backup retention period in days",minimum:0,maximum:35,default:7}}},mysql:{type:"object",properties:{instanceClass:{type:"string",pattern:"^db\\.[a-z0-9]+\\.[a-z0-9]+$"},engine:{type:"string",const:"mysql"},version:{type:"string"},multiAZ:{type:"boolean",default:!1},backupRetentionDays:{type:"number",minimum:0,maximum:35,default:7}}},dynamodb:{type:"object",properties:{tables:{type:"array",items:{type:"object",required:["name","partitionKey"],properties:{name:{type:"string"},partitionKey:{type:"string"},sortKey:{type:"string"},billingMode:{type:"string",enum:["PAY_PER_REQUEST","PROVISIONED"],default:"PAY_PER_REQUEST"}}}}}}}},cache:{type:"object",properties:{redis:{type:"object",properties:{nodeType:{type:"string",description:"ElastiCache node type",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1},engineVersion:{type:"string",description:"Redis engine version"}}},memcached:{type:"object",properties:{nodeType:{type:"string",pattern:"^cache\\.[a-z0-9]+\\.[a-z0-9]+$"},numCacheNodes:{type:"number",minimum:1,default:1}}}}},cdn:{type:"object",properties:{enabled:{type:"boolean",default:!0},compress:{type:"boolean",description:"Enable automatic compression",default:!0},http3:{type:"boolean",description:"Enable HTTP/3 support",default:!0},customDomain:{type:"object",properties:{domain:{type:"string"},certificateArn:{type:"string"}}},cachePolicy:{type:"object",properties:{minTTL:{type:"number",minimum:0},defaultTTL:{type:"number",minimum:0},maxTTL:{type:"number",minimum:0}}}}},function:{type:"object",required:["name","runtime"],properties:{name:{type:"string"},runtime:{type:"string",enum:["nodejs18.x","nodejs20.x","python3.10","python3.11","python3.12"]},handler:{type:"string",default:"index.handler"},timeout:{type:"number",minimum:1,maximum:900,default:30},memory:{type:"number",minimum:128,maximum:10240,default:1024}}},monitoring:{type:"object",properties:{alarms:{type:"array",items:{type:"object",required:["metric","threshold"],properties:{metric:{type:"string"},threshold:{type:"number"},evaluationPeriods:{type:"number",minimum:1,default:2}}}},dashboard:{type:"object",properties:{name:{type:"string"},widgets:{type:"array"}}}}},security:{type:"object",properties:{waf:{type:"boolean",description:"Enable AWS WAF",default:!1},certificates:{type:"array",items:{type:"object",required:["domain"],properties:{domain:{type:"string"},subdomains:{type:"array",items:{type:"string"}}}}}}},queue:{type:"object",properties:{fifo:{type:"boolean",default:!1},deadLetterQueue:{type:"boolean",default:!0},visibilityTimeout:{type:"number",minimum:0,maximum:43200,default:30},messageRetentionPeriod:{type:"number",minimum:60,maximum:1209600,default:345600}}}}};rJ={enabled:process.env.TS_CLOUD_LOCAL==="true"||!0,localstackEndpoint:process.env.LOCALSTACK_ENDPOINT||"http://localhost:4566",postgresUrl:process.env.POSTGRES_URL||"postgresql://tscloud:tscloud@localhost:5432/tscloud",redisUrl:process.env.REDIS_URL||"redis://localhost:6379",dynamodbEndpoint:process.env.DYNAMODB_ENDPOINT||"http://localhost:8000",s3Endpoint:process.env.S3_ENDPOINT||"http://localhost:9000",emailEndpoint:process.env.EMAIL_ENDPOINT||"smtp://localhost:1025",awsRegion:process.env.AWS_REGION||"us-east-1",awsAccessKeyId:process.env.AWS_ACCESS_KEY_ID||"test",awsSecretAccessKey:process.env.AWS_SECRET_ACCESS_KEY||"test"};Yj=new tJ;Wj=new sJ;Pj=new eJ;Cj=new $Y,xj=new JY,Ij=new YY,kj=new ZY,r1=[{code:"us-east-1",name:"US East (N. Virginia)",location:"Virginia, USA",launchYear:2006,availabilityZones:6,localZones:16,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO","FedRAMP"]},{code:"us-east-2",name:"US East (Ohio)",location:"Ohio, USA",launchYear:2016,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-1",name:"US West (N. California)",location:"California, USA",launchYear:2009,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"us-west-2",name:"US West (Oregon)",location:"Oregon, USA",launchYear:2011,availabilityZones:4,localZones:2,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1},compliance:["PCI-DSS","HIPAA","SOC","ISO"]},{code:"eu-west-1",name:"Europe (Ireland)",location:"Dublin, Ireland",launchYear:2007,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"standard",multiplier:1.05},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"eu-central-1",name:"Europe (Frankfurt)",location:"Frankfurt, Germany",launchYear:2014,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.1},compliance:["PCI-DSS","GDPR","SOC","ISO"]},{code:"ap-southeast-1",name:"Asia Pacific (Singapore)",location:"Singapore",launchYear:2010,availabilityZones:3,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.12},compliance:["PCI-DSS","SOC","ISO","MTCS"]},{code:"ap-northeast-1",name:"Asia Pacific (Tokyo)",location:"Tokyo, Japan",launchYear:2011,availabilityZones:4,services:{compute:!0,storage:!0,database:!0,networking:!0,ml:!0,analytics:!0},pricing:{tier:"premium",multiplier:1.15},compliance:["PCI-DSS","SOC","ISO"]}];rj=new QY,nj=new GY,ZU={basic:{name:"Basic (3 Accounts)",description:"Simple structure for small teams",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account for AWS Organizations"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production workloads"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development and testing"}],organizationalUnits:[{name:"root"},{name:"workloads",parent:"root"}]},standard:{name:"Standard (5 Accounts)",description:"Recommended for most organizations",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"security",email:"aws+security@example.com",role:"security",ou:"security",description:"Security tooling and audit logs"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared services (CI/CD, monitoring)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"workloads",description:"Production environment"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"workloads",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"workloads",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root"},{name:"infrastructure",parent:"root"},{name:"workloads",parent:"root"}]},enterprise:{name:"Enterprise (7+ Accounts)",description:"For large organizations with strict compliance requirements",accounts:[{alias:"management",email:"aws+management@example.com",role:"management",ou:"root",description:"Management account"},{alias:"audit",email:"aws+audit@example.com",role:"security",ou:"security",description:"Audit and compliance"},{alias:"log-archive",email:"aws+logs@example.com",role:"security",ou:"security",description:"Centralized log storage"},{alias:"shared-services",email:"aws+shared@example.com",role:"shared-services",ou:"infrastructure",description:"Shared infrastructure"},{alias:"network",email:"aws+network@example.com",role:"shared-services",ou:"infrastructure",description:"Network infrastructure (Transit Gateway)"},{alias:"production",email:"aws+production@example.com",role:"production",ou:"production-ou",description:"Production workloads"},{alias:"staging",email:"aws+staging@example.com",role:"staging",ou:"non-production-ou",description:"Staging environment"},{alias:"development",email:"aws+development@example.com",role:"development",ou:"non-production-ou",description:"Development environment"}],organizationalUnits:[{name:"root"},{name:"security",parent:"root",policies:["deny-root-access"]},{name:"infrastructure",parent:"root"},{name:"production-ou",parent:"root",policies:["require-mfa"]},{name:"non-production-ou",parent:"root"}]}},ij={denyRootAccess:{name:"Deny Root User Access",description:"Prevent root user from performing any actions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyRootUser",Effect:"Deny",Action:"*",Resource:"*",Condition:{StringLike:{"aws:PrincipalArn":"arn:aws:iam::*:root"}}}]}},requireMFA:{name:"Require MFA for All Actions",description:"Require MFA for console and API access",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"RequireMFA",Effect:"Deny",Action:"*",Resource:"*",Condition:{BoolIfExists:{"aws:MultiFactorAuthPresent":"false"}}}]}},denyRegions:{name:"Deny Access to Non-Approved Regions",description:"Restrict operations to specific regions",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyNonApprovedRegions",Effect:"Deny",NotAction:["iam:*","organizations:*","route53:*","cloudfront:*","support:*","s3:*"],Resource:"*",Condition:{StringNotEquals:{"aws:RequestedRegion":["us-east-1","us-west-2"]}}}]}},preventLeaving:{name:"Prevent Leaving Organization",description:"Prevent accounts from leaving the organization",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"PreventLeaving",Effect:"Deny",Action:"organizations:LeaveOrganization",Resource:"*"}]}},denyS3Unencrypted:{name:"Deny Unencrypted S3 Uploads",description:"Require encryption for all S3 uploads",policyDocument:{Version:"2012-10-17",Statement:[{Sid:"DenyUnencryptedS3Uploads",Effect:"Deny",Action:"s3:PutObject",Resource:"*",Condition:{StringNotEquals:{"s3:x-amz-server-side-encryption":["AES256","aws:kms"]}}}]}}},aj={deploymentRole:{name:"CrossAccountDeploymentRole",description:"Role for deploying infrastructure from CI/CD",permissions:["cloudformation:*","s3:*","ec2:*","ecs:*","lambda:*","iam:GetRole","iam:PassRole","logs:*","events:*"]},readOnlyRole:{name:"CrossAccountReadOnlyRole",description:"Read-only access for monitoring and auditing",permissions:["cloudformation:Describe*","cloudformation:List*","ec2:Describe*","ecs:Describe*","lambda:Get*","lambda:List*","s3:Get*","s3:List*","logs:Get*","logs:Describe*"]},securityAuditRole:{name:"CrossAccountSecurityAuditRole",description:"Security audit and compliance checks",permissions:["iam:Get*","iam:List*","iam:Generate*","access-analyzer:*","guardduty:Get*","guardduty:List*","securityhub:Get*","securityhub:List*","config:Describe*","config:Get*","config:List*"]},breakGlassRole:{name:"CrossAccountBreakGlassRole",description:"Emergency access role (use with caution)",permissions:["*"]}};AL=new WY;VL=new zY;_L=new UY;jL=new HY;LL=new FY;Y$=class Y${hubs=new Map;hubCounter=0;ruleCounter=0;static Standards={AWS_FOUNDATIONAL_SECURITY:{arn:"arn:aws:securityhub:::ruleset/aws-foundational-security-best-practices/v/1.0.0",name:"AWS Foundational Security Best Practices",description:"AWS recommended security best practices"},CIS_AWS_FOUNDATIONS_1_2:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",name:"CIS AWS Foundations Benchmark v1.2.0",description:"CIS AWS Foundations Benchmark v1.2.0"},CIS_AWS_FOUNDATIONS_1_4:{arn:"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.4.0",name:"CIS AWS Foundations Benchmark v1.4.0",description:"CIS AWS Foundations Benchmark v1.4.0"},PCI_DSS:{arn:"arn:aws:securityhub:us-east-1::standards/pci-dss/v/3.2.1",name:"PCI DSS v3.2.1",description:"Payment Card Industry Data Security Standard"},NIST_800_53:{arn:"arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0",name:"NIST SP 800-53 Rev. 5",description:"NIST Special Publication 800-53 Revision 5"}};createHub($){let J=`hub-${Date.now()}-${this.hubCounter++}`,Y={id:J,...$};return this.hubs.set(J,Y),Y}createComprehensiveHub(){return this.createHub({enable:!0,controlFindingGenerator:"SECURITY_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...Y$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0},{id:"cis-1-4",...Y$.Standards.CIS_AWS_FOUNDATIONS_1_4,enabled:!0},{id:"pci-dss",...Y$.Standards.PCI_DSS,enabled:!0}]})}createBasicHub(){return this.createHub({enable:!0,controlFindingGenerator:"STANDARD_CONTROL",enableDefaultStandards:!0,standards:[{id:"aws-foundational",...Y$.Standards.AWS_FOUNDATIONAL_SECURITY,enabled:!0}]})}createLowSeveritySuppressionRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Suppress Low Severity Informational Findings",description:"Automatically suppress informational findings",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Automatically suppressed low severity finding",updatedBy:"SecurityHub Automation"}}}],criteria:{severityLabel:[{value:"INFORMATIONAL",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:1}}createResourceTypeNotificationRule($){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Notify on Critical Resource Findings",description:"Set findings for critical resources to NOTIFIED status",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"NOTIFIED"},note:{text:"Critical resource finding requires attention",updatedBy:"SecurityHub Automation"}}}],criteria:{resourceType:$.map((J)=>({value:J,comparison:"EQUALS"})),severityLabel:[{value:"HIGH",comparison:"EQUALS"},{value:"CRITICAL",comparison:"EQUALS"}],workflowStatus:[{value:"NEW",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:2}}createComplianceFailureRule(){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:"Flag Compliance Failures",description:"Increase severity for compliance failures",actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{severity:{label:"HIGH"},workflow:{status:"NOTIFIED"},note:{text:"Compliance failure detected - requires immediate attention",updatedBy:"SecurityHub Automation"}}}],criteria:{complianceStatus:[{value:"FAILED",comparison:"EQUALS"}],recordState:[{value:"ACTIVE",comparison:"EQUALS"}]},ruleStatus:"ENABLED",ruleOrder:3}}createFalsePositiveSuppressionRule($,J){return{id:`rule-${Date.now()}-${this.ruleCounter++}`,ruleName:`Suppress False Positives - ${$}`,description:`Automatically suppress known false positives from ${$}`,actions:[{type:"FINDING_FIELDS_UPDATE",findingFieldsUpdate:{workflow:{status:"SUPPRESSED"},note:{text:"Known false positive - automatically suppressed",updatedBy:"SecurityHub Automation"}}}],criteria:{productName:[{value:$,comparison:"EQUALS"}],title:J.map((Y)=>({value:Y,comparison:"PREFIX"}))},ruleStatus:"ENABLED",ruleOrder:10}}getHub($){return this.hubs.get($)}listHubs(){return Array.from(this.hubs.values())}generateHubCF($){let J={Type:"AWS::SecurityHub::Hub",Properties:{}};if($.controlFindingGenerator)J.Properties.ControlFindingGenerator=$.controlFindingGenerator;if($.enableDefaultStandards!==void 0)J.Properties.EnableDefaultStandards=$.enableDefaultStandards;return J}generateStandardCF($){let J={Type:"AWS::SecurityHub::Standard",Properties:{StandardsArn:$.arn}};if($.disabledControls&&$.disabledControls.length>0)J.Properties.DisabledStandardsControls=$.disabledControls.map((Y)=>({StandardsControlArn:Y,Reason:"Disabled by configuration"}));return J}generateAutomationRuleCF($){return{Type:"AWS::SecurityHub::AutomationRule",Properties:{RuleName:$.ruleName,Description:$.description,Actions:$.actions.map((J)=>({Type:J.type,FindingFieldsUpdate:J.findingFieldsUpdate})),Criteria:$.criteria,RuleStatus:$.ruleStatus,RuleOrder:$.ruleOrder}}}clear(){this.hubs.clear(),this.hubCounter=0,this.ruleCounter=0}};EL=new Y$;ML=new XY;y8=class y8{deployments=new Map;deploymentHistory=new Map;deploymentCounter=0;resultCounter=0;static Strategies={CONSERVATIVE:[{name:"Initial Canary",trafficPercentage:10,durationMinutes:10},{name:"Quarter Traffic",trafficPercentage:25,durationMinutes:10},{name:"Half Traffic",trafficPercentage:50,durationMinutes:15},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],BALANCED:[{name:"Initial Canary",trafficPercentage:20,durationMinutes:5},{name:"Half Traffic",trafficPercentage:50,durationMinutes:10},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],AGGRESSIVE:[{name:"Half Traffic",trafficPercentage:50,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}],LINEAR_10:[{name:"Canary 10%",trafficPercentage:10,durationMinutes:5},{name:"Canary 20%",trafficPercentage:20,durationMinutes:5},{name:"Canary 30%",trafficPercentage:30,durationMinutes:5},{name:"Canary 40%",trafficPercentage:40,durationMinutes:5},{name:"Canary 50%",trafficPercentage:50,durationMinutes:5},{name:"Canary 60%",trafficPercentage:60,durationMinutes:5},{name:"Canary 70%",trafficPercentage:70,durationMinutes:5},{name:"Canary 80%",trafficPercentage:80,durationMinutes:5},{name:"Canary 90%",trafficPercentage:90,durationMinutes:5},{name:"Full Traffic",trafficPercentage:100,durationMinutes:5}]};createDeployment($){let J=`canary-${Date.now()}-${this.deploymentCounter++}`,Y={id:J,...$};return this.deployments.set(J,Y),Y}createLambdaCanaryDeployment($){let J=$.strategy||"BALANCED",Y=y8.Strategies[J].map((Z)=>({...Z,alarmThresholds:{errorRate:$.errorRateThreshold||1,latencyP99:$.latencyThreshold||1000}}));return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",functionVersionArn:$.baselineVersionArn,weight:100},canaryVersion:{version:"canary",functionVersionArn:$.canaryVersionArn,weight:0},stages:Y,currentStage:0,status:"pending",autoPromote:$.autoPromote??!0,autoRollback:!0})}createECSCanaryDeployment($){let J=$.strategy||"CONSERVATIVE",Y=y8.Strategies[J];return this.createDeployment({name:$.name,baselineVersion:{version:"baseline",taskDefinitionArn:$.baselineTaskDefinitionArn,targetGroupArn:$.baselineTargetGroupArn,weight:100},canaryVersion:{version:"canary",taskDefinitionArn:$.canaryTaskDefinitionArn,targetGroupArn:$.canaryTargetGroupArn,weight:0},stages:Y,currentStage:0,status:"pending",autoRollback:!0})}async executeDeployment($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);let Z={success:!1,deploymentId:`result-${Date.now()}-${this.resultCounter++}`,startTime:new Date,completedStages:0,rolledBack:!1};console.log(`${J?"[DRY RUN] ":""}Starting canary deployment: ${Y.name}`),console.log(` Strategy: ${Y.stages.length} stages`),console.log(` Auto-promote: ${Y.autoPromote}`),console.log(` Auto-rollback: ${Y.autoRollback}`),console.log(""),Y.status="in_progress";for(let Q=0;Q<Y.stages.length;Q++){let G=Y.stages[Q];if(Y.currentStage=Q,console.log(`Stage ${Q+1}/${Y.stages.length}: ${G.name}`),console.log(` Traffic: ${G.trafficPercentage}% canary, ${100-G.trafficPercentage}% baseline`),console.log(` Duration: ${G.durationMinutes} minutes`),!J)Y.baselineVersion.weight=100-G.trafficPercentage,Y.canaryVersion.weight=G.trafficPercentage;if(!await this.monitorStage(Y,G,J)){if(console.log(" ✗ Stage failed - metrics exceeded thresholds"),Y.autoRollback)console.log("\\n Rolling back deployment..."),await this.rollback($,J),Z.rolledBack=!0,Z.reason="Metrics exceeded thresholds";return Z.endTime=new Date,Y.status="rolled_back",this.recordDeployment($,Z),Z}console.log(" ✓ Stage completed successfully"),Z.completedStages++,console.log("")}return Y.status="completed",Z.success=!0,Z.endTime=new Date,console.log("✓ Canary deployment completed successfully"),this.recordDeployment($,Z),Z}async monitorStage($,J,Y){if(console.log(" Monitoring metrics..."),Y)return console.log(" [SKIPPED - DRY RUN]"),!0;await new Promise((Q)=>setTimeout(Q,100));let Z={baselineErrorRate:Math.random()*0.5,canaryErrorRate:Math.random()*0.8,baselineLatencyP99:200+Math.random()*100,canaryLatencyP99:180+Math.random()*150,baselineRequestCount:Math.floor(Math.random()*1000)+500,canaryRequestCount:Math.floor((Math.random()*1000+500)*J.trafficPercentage/100)};if($.metrics=Z,console.log(` Baseline: ${Z.baselineErrorRate.toFixed(2)}% errors, ${Z.baselineLatencyP99.toFixed(0)}ms P99`),console.log(` Canary: ${Z.canaryErrorRate.toFixed(2)}% errors, ${Z.canaryLatencyP99.toFixed(0)}ms P99`),J.alarmThresholds){let{errorRate:Q,latencyP99:G}=J.alarmThresholds;if(Q&&Z.canaryErrorRate>Q)return console.log(` ⚠ Error rate exceeded threshold: ${Z.canaryErrorRate.toFixed(2)}% > ${Q}%`),!1;if(G&&Z.canaryLatencyP99>G)return console.log(` ⚠ Latency P99 exceeded threshold: ${Z.canaryLatencyP99.toFixed(0)}ms > ${G}ms`),!1}return!0}async rollback($,J=!1){let Y=this.deployments.get($);if(!Y)throw Error(`Deployment not found: ${$}`);if(console.log(`${J?"[DRY RUN] ":""}Rolling back canary deployment: ${Y.name}`),!J)Y.baselineVersion.weight=100,Y.canaryVersion.weight=0,Y.status="rolled_back";console.log(" Traffic restored to baseline: 100%")}promoteCanary($){let J=this.deployments.get($);if(!J)throw Error(`Deployment not found: ${$}`);console.log(`Promoting canary to baseline: ${J.name}`);let Y=J.baselineVersion;J.baselineVersion=J.canaryVersion,J.canaryVersion=Y,J.baselineVersion.weight=100,J.canaryVersion.weight=0,J.status="completed",console.log(" Canary promoted successfully")}recordDeployment($,J){if(!this.deploymentHistory.has($))this.deploymentHistory.set($,[]);this.deploymentHistory.get($).push(J)}getDeployment($){return this.deployments.get($)}listDeployments(){return Array.from(this.deployments.values())}getDeploymentHistory($){return this.deploymentHistory.get($)||[]}generateLambdaAliasCF($,J){return{Type:"AWS::Lambda::Alias",Properties:{FunctionName:{Ref:"LambdaFunction"},Name:J,FunctionVersion:$.canaryVersion.version,RoutingConfig:{AdditionalVersionWeights:[{FunctionVersion:$.baselineVersion.version,FunctionWeight:$.baselineVersion.weight/100}]}}}}generateALBListenerRuleCF($){return{Type:"AWS::ElasticLoadBalancingV2::ListenerRule",Properties:{ListenerArn:{Ref:"LoadBalancerListener"},Priority:1,Conditions:[{Field:"path-pattern",Values:["/*"]}],Actions:[{Type:"forward",ForwardConfig:{TargetGroups:[{TargetGroupArn:$.baselineVersion.targetGroupArn,Weight:$.baselineVersion.weight},{TargetGroupArn:$.canaryVersion.targetGroupArn,Weight:$.canaryVersion.weight}],TargetGroupStickinessConfig:{Enabled:!1}}}]}}}clear(){this.deployments.clear(),this.deploymentHistory.clear(),this.deploymentCounter=0,this.resultCounter=0}};qL=new y8;TL=new BY;wL=new KY;DL=new OY;RL=new AY;NL=new VY;Z$=class Z${canaries=new Map;heartbeats=new Map;apiMonitors=new Map;canaryCounter=0;heartbeatCounter=0;apiMonitorCounter=0;alarmCounter=0;static RuntimeVersions={NODEJS_PUPPETEER_3_9:"syn-nodejs-puppeteer-3.9",NODEJS_PUPPETEER_4_0:"syn-nodejs-puppeteer-4.0",PYTHON_SELENIUM_1_3:"syn-python-selenium-1.3"};createCanary($){let J=`canary-${Date.now()}-${this.canaryCounter++}`,Y={id:J,...$};return this.canaries.set(J,Y),Y}createHeartbeatCanary($){let J=`
|
|
5911
5911
|
const synthetics = require('Synthetics');
|
|
5912
5912
|
const log = require('SyntheticsLogger');
|
|
5913
5913
|
|
|
@@ -5927,7 +5927,7 @@ const heartbeat = async function () {
|
|
|
5927
5927
|
exports.handler = async () => {
|
|
5928
5928
|
return await heartbeat();
|
|
5929
5929
|
};
|
|
5930
|
-
`;return this.createCanary({name:$.name,description:`Heartbeat monitor for ${$.url}`,runtimeVersion:
|
|
5930
|
+
`;return this.createCanary({name:$.name,description:`Heartbeat monitor for ${$.url}`,runtimeVersion:Z$.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:J},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:60,memoryInMB:960,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createAPICanary($){let Y=`
|
|
5931
5931
|
const synthetics = require('Synthetics');
|
|
5932
5932
|
const log = require('SyntheticsLogger');
|
|
5933
5933
|
|
|
@@ -5956,7 +5956,7 @@ const apiCheck = async function () {
|
|
|
5956
5956
|
exports.handler = async () => {
|
|
5957
5957
|
return await apiCheck();
|
|
5958
5958
|
};
|
|
5959
|
-
`;return this.createCanary({name:$.name,description:`API monitor for ${$.baseUrl}`,runtimeVersion:
|
|
5959
|
+
`;return this.createCanary({name:$.name,description:`API monitor for ${$.baseUrl}`,runtimeVersion:Z$.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:Y},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:120,memoryInMB:960,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createVisualRegressionCanary($){let J=`
|
|
5960
5960
|
const synthetics = require('Synthetics');
|
|
5961
5961
|
const log = require('SyntheticsLogger');
|
|
5962
5962
|
|
|
@@ -5976,7 +5976,7 @@ const visualCheck = async function () {
|
|
|
5976
5976
|
exports.handler = async () => {
|
|
5977
5977
|
return await visualCheck();
|
|
5978
5978
|
};
|
|
5979
|
-
`;return this.createCanary({name:$.name,description:`Visual regression monitor for ${$.url}`,runtimeVersion:
|
|
5979
|
+
`;return this.createCanary({name:$.name,description:`Visual regression monitor for ${$.url}`,runtimeVersion:Z$.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:J},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:120,memoryInMB:1024,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}createWorkflowCanary($){let Y=`
|
|
5980
5980
|
const synthetics = require('Synthetics');
|
|
5981
5981
|
const log = require('SyntheticsLogger');
|
|
5982
5982
|
|
|
@@ -5998,7 +5998,7 @@ const workflowCheck = async function () {
|
|
|
5998
5998
|
exports.handler = async () => {
|
|
5999
5999
|
return await workflowCheck();
|
|
6000
6000
|
};
|
|
6001
|
-
`;return this.createCanary({name:$.name,description:$.description,runtimeVersion:
|
|
6001
|
+
`;return this.createCanary({name:$.name,description:$.description,runtimeVersion:Z$.RuntimeVersions.NODEJS_PUPPETEER_4_0,handler:"index.handler",code:{type:"script",script:Y},schedule:{expression:`rate(${$.interval} minutes)`},runConfig:{timeoutInSeconds:180,memoryInMB:1024,activeTracing:!0},artifactS3Location:`s3://${$.s3Bucket}/canary-artifacts/${$.name}/`,successRetentionPeriod:31,failureRetentionPeriod:31})}generateActionScript($){switch($.type){case"click":return`await page.click('${$.selector}');`;case"type":return`await page.type('${$.selector}', '${$.value}');`;case"wait":return`await page.waitForTimeout(${$.duration});`;case"waitForSelector":return`await page.waitForSelector('${$.selector}');`;default:return""}}createAlarm($,J){let Y=this.canaries.get($);if(!Y)throw Error(`Canary not found: ${$}`);let Q={id:`alarm-${Date.now()}-${this.alarmCounter++}`,...J};if(!Y.alarms)Y.alarms=[];return Y.alarms.push(Q),Q}getCanary($){return this.canaries.get($)}listCanaries(){return Array.from(this.canaries.values())}generateCanaryCF($){let J={Type:"AWS::Synthetics::Canary",Properties:{Name:$.name,RuntimeVersion:$.runtimeVersion,ExecutionRoleArn:{"Fn::GetAtt":["CanaryExecutionRole","Arn"]},Schedule:{Expression:$.schedule.expression,...$.schedule.durationInSeconds&&{DurationInSeconds:$.schedule.durationInSeconds}},ArtifactS3Location:$.artifactS3Location,StartCanaryAfterCreation:!0}};if($.code.type==="script")J.Properties.Code={Handler:$.handler,Script:$.code.script};else J.Properties.Code={Handler:$.handler,S3Bucket:$.code.s3Bucket,S3Key:$.code.s3Key,...$.code.s3Version&&{S3ObjectVersion:$.code.s3Version}};if($.runConfig)J.Properties.RunConfig={TimeoutInSeconds:$.runConfig.timeoutInSeconds,MemoryInMB:$.runConfig.memoryInMB,...$.runConfig.environmentVariables&&{EnvironmentVariables:$.runConfig.environmentVariables},...$.runConfig.activeTracing!==void 0&&{ActiveTracing:$.runConfig.activeTracing}};if($.vpcConfig)J.Properties.VPCConfig={SubnetIds:$.vpcConfig.subnetIds,SecurityGroupIds:$.vpcConfig.securityGroupIds};if($.successRetentionPeriod)J.Properties.SuccessRetentionPeriod=$.successRetentionPeriod;if($.failureRetentionPeriod)J.Properties.FailureRetentionPeriod=$.failureRetentionPeriod;return J}generateCanaryRoleCF(){return{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole","arn:aws:iam::aws:policy/CloudWatchSyntheticsFullAccess"],Policies:[{PolicyName:"CanaryS3Policy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:PutObject","s3:GetBucketLocation"],Resource:["arn:aws:s3:::*/*"]}]}}]}}}clear(){this.canaries.clear(),this.heartbeats.clear(),this.apiMonitors.clear(),this.canaryCounter=0,this.heartbeatCounter=0,this.apiMonitorCounter=0,this.alarmCounter=0}};SL=new Z$;PL=new _Y;CL=new jY;xL=new LY;IL=new EY;kL=new MY;hL=new qY;bL=new TY;yL=new wY;vL=new DY;fL=new RY;gL=new NY;uL=new SY;dL=new PY;cL=new CY;mL=new xY;lL=new IY;pL=new kY;rL=new hY;nL=new bY;iL=new yY;aL=new vY;tL=new fY;sL=new gY;oL=new uY;eL=new dY,QU={};G$(QU,{SharedMailboxes:()=>pY,EmailThreading:()=>mY,EmailTemplates:()=>J$,EmailSearch:()=>cY,EmailScheduling:()=>lY,EmailRules:()=>rY,EmailAnalyticsModule:()=>k8});J$=class J${static TemplateRendererCode=`
|
|
6002
6002
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
6003
6003
|
|
|
6004
6004
|
const s3 = new S3Client({});
|
|
@@ -6253,7 +6253,7 @@ The {{appName}} Team`,variables:["appName","userName","resetUrl","expiresIn"],ca
|
|
|
6253
6253
|
|
|
6254
6254
|
<p>Best regards,<br>The {{appName}} Team</p>
|
|
6255
6255
|
</body>
|
|
6256
|
-
</html>`,variables:["invoiceNumber","customerName","period","items","total","paymentUrl","appName"],category:"billing"}};static createTemplateBucket($){return{[`${$.slug}EmailTemplateBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-email-templates`,VersioningConfiguration:{Status:"Enabled"}}}}}static createTemplateRendererLambda($){return{[`${$.slug}TemplateRendererLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-template-renderer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile
|
|
6256
|
+
</html>`,variables:["invoiceNumber","customerName","period","items","total","paymentUrl","appName"],category:"billing"}};static createTemplateBucket($){return{[`${$.slug}EmailTemplateBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-email-templates`,VersioningConfiguration:{Status:"Enabled"}}}}}static createTemplateRendererLambda($){return{[`${$.slug}TemplateRendererLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-template-renderer`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:J$.TemplateRendererCode},Environment:{Variables:{TEMPLATE_BUCKET:$.templateBucket}}}}}}static render($,J){if(!$||!J)return $;let Y=$;return Y=Y.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(Z,Q)=>{let G=J$.getNestedValue(J,Q);return G!==void 0?String(G):Z}),Y=Y.replace(/\{\{#if\s+([\w.]+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(Z,Q,G)=>{return J$.getNestedValue(J,Q)?G:""}),Y=Y.replace(/\{\{#unless\s+([\w.]+)\}\}([\s\S]*?)\{\{\/unless\}\}/g,(Z,Q,G)=>{return!J$.getNestedValue(J,Q)?G:""}),Y=Y.replace(/\{\{#each\s+([\w.]+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(Z,Q,G)=>{let W=J$.getNestedValue(J,Q);if(!Array.isArray(W))return"";return W.map((z,U)=>{let H=G;if(H=H.replace(/\{\{this\}\}/g,String(z)),H=H.replace(/\{\{@index\}\}/g,String(U)),typeof z==="object")Object.entries(z).forEach(([F,B])=>{H=H.replace(new RegExp(`\\{\\{\\s*${F}\\s*\\}\\}`,"g"),String(B))});return H}).join("")}),Y}static getNestedValue($,J){return J.split(".").reduce((Y,Z)=>Y?.[Z],$)}static extractVariables($){let J=new Set,Y=$.matchAll(/\{\{\s*([\w.]+)\s*\}\}/g);for(let Q of Y)if(!Q[1].startsWith("#")&&!Q[1].startsWith("/")&&!Q[1].startsWith("@"))J.add(Q[1].split(".")[0]);let Z=$.matchAll(/\{\{#(?:if|unless|each)\s+([\w.]+)\}\}/g);for(let Q of Z)J.add(Q[1].split(".")[0]);return Array.from(J)}};pY=class pY{static SharedMailboxLambdaCode=`
|
|
6257
6257
|
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
|
6258
6258
|
const { DynamoDBClient, GetItemCommand, PutItemCommand, QueryCommand, UpdateItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
6259
6259
|
|
|
@@ -6797,7 +6797,7 @@ async function invokeLambda(functionName, metadata) {
|
|
|
6797
6797
|
Payload: JSON.stringify(metadata),
|
|
6798
6798
|
}));
|
|
6799
6799
|
}
|
|
6800
|
-
`;static createRulesTable($){return{[`${$.slug}EmailRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}}static createRuleProcessorLambda($){return{[`${$.slug}EmailRuleProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-email-rule-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:rY.RuleProcessorCode},Environment:{Variables:{EMAIL_BUCKET:$.emailBucket,RULES_TABLE:$.rulesTable}}}}}}static RuleTemplates={spamFilter:{name:"Spam Filter",conditions:[{field:"subject",operator:"regex",value:"(viagra|lottery|winner|prince|inheritance)",caseSensitive:!1}],conditionOperator:"or",actions:[{type:"move",params:{folder:"spam"}},{type:"mark-read",params:{}}]},autoLabel:{name:"Auto Label Invoices",conditions:[{field:"subject",operator:"contains",value:"invoice",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"label",params:{label:"invoices"}}]},forwardUrgent:{name:"Forward Urgent",conditions:[{field:"subject",operator:"contains",value:"urgent",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"forward",params:{to:"admin@example.com"}},{type:"label",params:{label:"urgent"}}]}}};GU={};
|
|
6800
|
+
`;static createRulesTable($){return{[`${$.slug}EmailRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-email-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"mailbox",AttributeType:"S"},{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"mailbox",KeyType:"HASH"},{AttributeName:"id",KeyType:"RANGE"}]}}}}static createRuleProcessorLambda($){return{[`${$.slug}EmailRuleProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-email-rule-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:256,Code:{ZipFile:rY.RuleProcessorCode},Environment:{Variables:{EMAIL_BUCKET:$.emailBucket,RULES_TABLE:$.rulesTable}}}}}}static RuleTemplates={spamFilter:{name:"Spam Filter",conditions:[{field:"subject",operator:"regex",value:"(viagra|lottery|winner|prince|inheritance)",caseSensitive:!1}],conditionOperator:"or",actions:[{type:"move",params:{folder:"spam"}},{type:"mark-read",params:{}}]},autoLabel:{name:"Auto Label Invoices",conditions:[{field:"subject",operator:"contains",value:"invoice",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"label",params:{label:"invoices"}}]},forwardUrgent:{name:"Forward Urgent",conditions:[{field:"subject",operator:"contains",value:"urgent",caseSensitive:!1}],conditionOperator:"and",actions:[{type:"forward",params:{to:"admin@example.com"}},{type:"label",params:{label:"urgent"}}]}}};GU={};G$(GU,{handler:()=>WU,default:()=>$E});$E=WU,zU={};G$(zU,{IVRBuilder:()=>g$,Callbacks:()=>b6,CallRecording:()=>nY,CallAnalytics:()=>iY});g$=class g${nodes=[];connections=[];startNodeId="";static create($){return new g$}start(){let $={id:this.generateId(),type:"start",position:{x:0,y:0},config:{}};return this.nodes.push($),this.startNodeId=$.id,this}playPrompt($,J){let Y={id:this.generateId(),type:"play-prompt",position:{x:0,y:0},config:{text:$,textType:J?.ssml?"ssml":"text",voice:J?.voice||"Joanna"}};return this.nodes.push(Y),this.connectToLast(Y.id),this}getInput($,J){let Y={id:this.generateId(),type:"get-input",position:{x:0,y:0},config:{prompt:$,maxDigits:J?.maxDigits||1,timeout:J?.timeout||5,errorPrompt:J?.errorPrompt||"Sorry, I didn't get that."}};return this.nodes.push(Y),this.connectToLast(Y.id),this}menu($,J){let Y={id:this.generateId(),type:"menu",position:{x:0,y:0},config:{prompt:$,options:J}};return this.nodes.push(Y),this.connectToLast(Y.id),this}transferToQueue($,J){let Y={id:this.generateId(),type:"transfer-queue",position:{x:0,y:0},config:{queueArn:$,priority:J?.priority||5}};return this.nodes.push(Y),this.connectToLast(Y.id),this}transferToPhone($){let J={id:this.generateId(),type:"transfer-phone",position:{x:0,y:0},config:{phoneNumber:$}};return this.nodes.push(J),this.connectToLast(J.id),this}invokeLambda($,J){let Y={id:this.generateId(),type:"invoke-lambda",position:{x:0,y:0},config:{functionArn:$,timeout:J?.timeout||8}};return this.nodes.push(Y),this.connectToLast(Y.id),this}setAttribute($,J){let Y={id:this.generateId(),type:"set-attribute",position:{x:0,y:0},config:{key:$,value:J}};return this.nodes.push(Y),this.connectToLast(Y.id),this}checkHours($){let J={id:this.generateId(),type:"check-hours",position:{x:0,y:0},config:{hoursOfOperationArn:$}};return this.nodes.push(J),this.connectToLast(J.id),this}recordVoicemail($){let J={id:this.generateId(),type:"record-voicemail",position:{x:0,y:0},config:{maxDuration:$?.maxDuration||120,greeting:$?.greeting||"Please leave a message after the beep.",beep:$?.beep!==!1}};return this.nodes.push(J),this.connectToLast(J.id),this}wait($){let J={id:this.generateId(),type:"wait",position:{x:0,y:0},config:{seconds:$}};return this.nodes.push(J),this.connectToLast(J.id),this}disconnect(){let $={id:this.generateId(),type:"disconnect",position:{x:0,y:0},config:{}};return this.nodes.push($),this.connectToLast($.id),this}build(){return{id:this.generateId(),name:"IVR Flow",nodes:this.nodes,connections:this.connections,startNodeId:this.startNodeId,version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}toContactFlow(){let $=[],J=new Map(this.nodes.map((Z)=>[Z.id,Z]));for(let Z of this.nodes){let Q=this.nodeToAction(Z,J);if(Q)$.push(Q)}let Y={Version:"2019-10-30",StartAction:this.startNodeId,Actions:$};return JSON.stringify(Y,null,2)}nodeToAction($,J){let Y=this.getNextNodeId($.id),Z={NextAction:Y||"disconnect",Errors:[{NextAction:"disconnect"}]};switch($.type){case"start":return null;case"play-prompt":return{Identifier:$.id,Type:"MessageParticipant",Parameters:{Text:$.config.text,TextType:$.config.textType},Transitions:Z};case"get-input":return{Identifier:$.id,Type:"GetParticipantInput",Parameters:{Text:$.config.prompt,InputTimeLimitSeconds:$.config.timeout,MaxDigits:$.config.maxDigits},Transitions:{...Z,Conditions:[]}};case"transfer-queue":return{Identifier:$.id,Type:"TransferToQueue",Parameters:{QueueId:$.config.queueArn},Transitions:Z};case"transfer-phone":return{Identifier:$.id,Type:"TransferToPhoneNumber",Parameters:{PhoneNumber:$.config.phoneNumber},Transitions:Z};case"invoke-lambda":return{Identifier:$.id,Type:"InvokeLambdaFunction",Parameters:{LambdaFunctionARN:$.config.functionArn,InvocationTimeLimitSeconds:$.config.timeout},Transitions:Z};case"set-attribute":return{Identifier:$.id,Type:"UpdateContactAttributes",Parameters:{Attributes:{[$.config.key]:$.config.value}},Transitions:Z};case"check-hours":return{Identifier:$.id,Type:"CheckHoursOfOperation",Parameters:{HoursOfOperationId:$.config.hoursOfOperationArn},Transitions:{NextAction:Y,Conditions:[{NextAction:Y,Condition:{Operator:"Equals",Operands:["True"]}}],Errors:[{NextAction:"disconnect"}]}};case"wait":return{Identifier:$.id,Type:"Wait",Parameters:{Seconds:$.config.seconds},Transitions:Z};case"disconnect":return{Identifier:$.id,Type:"DisconnectParticipant",Parameters:{},Transitions:{}};default:return null}}connectToLast($){if(this.nodes.length>1){let J=this.nodes[this.nodes.length-2];this.connections.push({id:this.generateId(),sourceNodeId:J.id,targetNodeId:$,sourcePort:"default"})}}getNextNodeId($){return this.connections.find((Y)=>Y.sourceNodeId===$)?.targetNodeId||null}generateId(){return`node-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}static Templates={basicSupport:()=>{return g$.create("Basic Support").start().playPrompt("Welcome to customer support.").menu("Press 1 for sales, 2 for support, or 3 to leave a message.",{"1":"sales","2":"support","3":"voicemail"})},afterHours:($)=>{return g$.create("After Hours").start().playPrompt($).recordVoicemail({greeting:"Please leave your name, number, and a brief message.",maxDuration:120}).playPrompt("Thank you for your message. Goodbye.").disconnect()},callbackRequest:($)=>{return g$.create("Callback Request").start().playPrompt("All agents are currently busy.").getInput("Press 1 to request a callback, or 2 to wait.",{maxDigits:1}).invokeLambda($).playPrompt("We will call you back shortly. Goodbye.").disconnect()}}};UU={};G$(UU,{SmsChatbot:()=>oY,SmsCampaigns:()=>aY,SmsAnalytics:()=>tY,MmsSupport:()=>sY,LinkTracking:()=>eY,AbTesting:()=>u2});sY=class sY{static MmsSenderCode=`
|
|
6801
6801
|
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
|
|
6802
6802
|
const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');
|
|
6803
6803
|
const { DynamoDBClient, PutItemCommand } = require('@aws-sdk/client-dynamodb');
|
|
@@ -6990,7 +6990,7 @@ async function sendFallbackSms(to, message) {
|
|
|
6990
6990
|
};
|
|
6991
6991
|
}
|
|
6992
6992
|
`;static createMediaBucket($){return{[`${$.slug}MmsMediaBucket`]:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${$.slug}-mms-media`,LifecycleConfiguration:{Rules:[{Id:"DeleteOldMedia",Status:"Enabled",ExpirationInDays:30}]},CorsConfiguration:{CorsRules:[{AllowedOrigins:["*"],AllowedMethods:["GET"],AllowedHeaders:["*"],MaxAge:3600}]}}}}}static createMmsSenderLambda($){return{[`${$.slug}MmsSenderLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-mms-sender`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:60,MemorySize:512,Code:{ZipFile:sY.MmsSenderCode},Environment:{Variables:{MEDIA_BUCKET:$.mediaBucket,MESSAGE_LOG_TABLE:$.messageLogTable,ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static SupportedMediaTypes={image:["image/jpeg","image/png","image/gif"],video:["video/mp4","video/3gpp"],audio:["audio/mpeg","audio/wav"]};static MediaSizeLimits={image:1048576,video:5242880,audio:1048576}};oY=class oY{static ChatbotProcessorCode=["const { DynamoDBClient, GetItemCommand, PutItemCommand, UpdateItemCommand, ScanCommand } = require('@aws-sdk/client-dynamodb');","const { BedrockRuntimeClient, InvokeModelCommand } = require('@aws-sdk/client-bedrock-runtime');","const { SNSClient, PublishCommand } = require('@aws-sdk/client-sns');","","const dynamodb = new DynamoDBClient({});","const bedrock = new BedrockRuntimeClient({});","const sns = new SNSClient({});","","const SESSIONS_TABLE = process.env.SESSIONS_TABLE;","const RULES_TABLE = process.env.RULES_TABLE;","const CHATBOT_CONFIG = JSON.parse(process.env.CHATBOT_CONFIG || '{}');","","exports.handler = async (event) => {"," console.log('Chatbot event:', JSON.stringify(event, null, 2));"," for (const record of event.Records) {"," try {"," const message = JSON.parse(record.Sns?.Message || record.body || '{}');"," const { originationNumber, messageBody } = message;"," if (!originationNumber || !messageBody) continue;"," const response = await processMessage(originationNumber, messageBody.trim());"," await sendResponse(originationNumber, response);"," } catch (error) {"," console.error('Error:', error);"," }"," }"," return { statusCode: 200 };","};","","async function processMessage(phoneNumber, message) {"," const rules = await getRules();"," const lowerMessage = message.toLowerCase();"," for (const rule of rules) {"," for (const pattern of rule.patterns) {"," if (new RegExp(pattern, 'i').test(lowerMessage)) {"," return rule.response;"," }"," }"," }"," return CHATBOT_CONFIG.fallbackMessage || 'Sorry, I did not understand. Please try again.';","}","","async function getRules() {"," const result = await dynamodb.send(new ScanCommand({ TableName: RULES_TABLE }));"," return (result.Items || []).map(item => ({"," patterns: JSON.parse(item.patterns?.S || '[]'),"," response: item.response?.S || '',"," })).sort((a, b) => (a.priority || 0) - (b.priority || 0));","}","","async function sendResponse(phoneNumber, message) {"," await sns.send(new PublishCommand({"," PhoneNumber: phoneNumber,"," Message: message.substring(0, 1600),"," MessageAttributes: {"," 'AWS.SNS.SMS.SMSType': { DataType: 'String', StringValue: 'Transactional' },"," },"," }));","}"].join(`
|
|
6993
|
-
`);static createSessionsTable($){return{[`${$.slug}ChatbotSessionsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRulesTable($){return{[`${$.slug}ChatbotRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createChatbotProcessorLambda($){return{[`${$.slug}ChatbotProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-chatbot-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:oY.ChatbotProcessorCode},Environment:{Variables:{SESSIONS_TABLE:$.sessionsTable,RULES_TABLE:$.rulesTable,CHATBOT_CONFIG:JSON.stringify($.chatbotConfig),ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static DefaultRules=[{id:"greeting",priority:1,patterns:["^(hi|hello|hey|howdy)$","^good (morning|afternoon|evening)"],response:"Hello! How can I help you today?"},{id:"help",priority:2,patterns:["^help$","what can you do","how does this work"],response:"I can help with: 1) Account info 2) Support 3) Hours. Reply with a number."},{id:"hours",priority:3,patterns:["hours","open","when are you"],response:"We are open Mon-Fri 9am-5pm EST. Closed weekends."},{id:"thanks",priority:4,patterns:["^(thanks|thank you|thx)"],response:"You're welcome! Is there anything else I can help with?"},{id:"bye",priority:5,patterns:["^(bye|goodbye|quit|exit|stop)$"],response:"Goodbye! Text us anytime if you need help.",action:"end"}]};JE=new $Z;YE=new JZ;ZE=new YZ;QE=new ZZ,WE=(()=>{let $=[];for(let J=0;J<256;J++){let Y=J;for(let Z=0;Z<8;Z++)Y=Y&1?3988292384^Y>>>1:Y>>>1;$[J]=Y>>>0}return $})();XU=["18","20","22"];BU=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];PE=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;SU=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];kU=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];$M=new KZ;JM=new OZ;YM=new AZ;ZM=new VZ;QM=new _Z});var jZ={};h0(jZ,{CloudFormationClient:()=>K0});class K0{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createStack($){let J={Action:"CreateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if($.parameters)$.parameters.forEach((Z,Q)=>{J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.timeoutInMinutes)J.TimeoutInMinutes=$.timeoutInMinutes;if($.onFailure)J.OnFailure=$.onFailure;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.CreateStackResult?.StackId}}async updateStack($){let J={Action:"UpdateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Z,Q)=>{if(J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,Z.UsePreviousValue)J[`Parameters.member.${Q+1}.UsePreviousValue`]="true";else J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.UpdateStackResult?.StackId}}async deleteStack($,J,Y){let Z={Action:"DeleteStack",StackName:$,Version:"2010-05-15"};if(J)Z.RoleARN=J;if(Y&&Y.length>0)Y.forEach((Q,G)=>{Z[`RetainResources.member.${G+1}`]=Q});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Z).toString()})}async describeStacks($={}){let J={Action:"DescribeStacks",Version:"2010-05-15"};if($.stackName)J.StackName=$.stackName;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Stacks:this.parseStacksResponse(Y)}}async describeStackEvents($){let J={Action:"DescribeStackEvents",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackEvents:this.parseStackEvents(Y)}}async listStackResources($){let J={Action:"ListStackResources",StackName:$,Version:"2010-05-15"},Z=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,Q=[];if(Z)Q=Array.isArray(Z)?Z:[Z];return{StackResourceSummaries:Q}}async waitForStack($,J){let Y={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},Z=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],Q=Y[J],G=360,W=0;while(W<360)try{let z=await this.describeStacks({stackName:$});if(z.Stacks.length===0){if(J==="stack-delete-complete")return;if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Stack not visible yet`);await new Promise((H)=>setTimeout(H,2000)),W++;continue}let U=z.Stacks[0];if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Status = ${U.StackStatus}${U.StackStatusReason?` (${U.StackStatusReason})`:""}`);if(Q.includes(U.StackStatus))return;if((J==="stack-create-complete"||J==="stack-update-complete")&&(U.StackStatus==="DELETE_IN_PROGRESS"||U.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let H="";try{let B=await this.describeStackEvents($);console.log("[waitForStack] Stack events (most recent first):");for(let K of B.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&&!H)H=K.ResourceStatusReason}}catch{}let F=H||U.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${F}`)}if(U.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let H=Error("Stack deletion failed - may have resources that need to be retained");throw H.code="DELETE_FAILED",H.stackStatus=U.StackStatus,H.statusReason=U.StackStatusReason,H}if(Z.includes(U.StackStatus))throw Error(`Stack reached failure status: ${U.StackStatus}`);await new Promise((H)=>setTimeout(H,5000)),W++}catch(z){if(J==="stack-delete-complete"&&z.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&z.message?.includes("does not exist")){if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Stack does not exist (error), retrying...`);await new Promise((U)=>setTimeout(U,2000)),W++;continue}throw console.log(`[waitForStack] Unexpected error: ${z.message}`),z}throw console.log(`[waitForStack] Timeout after ${W} attempts`),Error(`Timeout waiting for stack to reach ${J}`)}async validateTemplate($){let J={Action:"ValidateTemplate",TemplateBody:$,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async listStacks($){let J={Action:"ListStacks",Version:"2010-05-15"};if($)$.forEach((z,U)=>{J[`StackStatusFilter.member.${U+1}`]=z});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=Y.ListStacksResponse||Y,Q=Z.ListStacksResult||Z,G=Q.StackSummaries?.member||Q.StackSummaries||[];return{StackSummaries:(Array.isArray(G)?G:G?[G]:[]).map((z)=>({StackId:z.StackId||"",StackName:z.StackName||"",TemplateDescription:z.TemplateDescription,CreationTime:z.CreationTime||"",LastUpdatedTime:z.LastUpdatedTime,DeletionTime:z.DeletionTime,StackStatus:z.StackStatus||""}))}}async createChangeSet($){let J={Action:"CreateChangeSet",StackName:$.stackName,ChangeSetName:$.changeSetName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Z,Q)=>{J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.changeSetType)J.ChangeSetType=$.changeSetType;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Id:Y.Id,StackId:Y.StackId}}async describeChangeSet($,J){let Y={Action:"DescribeChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async executeChangeSet($,J){let Y={Action:"ExecuteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async deleteChangeSet($,J){let Y={Action:"DeleteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async getStackOutputs($){let J=await this.describeStacks({stackName:$});if(!J.Stacks||J.Stacks.length===0)throw Error(`Stack ${$} not found`);let Y=J.Stacks[0],Z={};if(Y.Outputs)for(let Q of Y.Outputs)Z[Q.OutputKey]=Q.OutputValue;return Z}async getTemplate($){let J={Action:"GetTemplate",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{TemplateBody:Y?.GetTemplateResult?.TemplateBody||Y?.TemplateBody||""}}parseStacksResponse($){let J=[],Y=$?.DescribeStacksResult?.Stacks?.member||$?.Stacks?.member||$?.Stacks||$;if(Y&&!Array.isArray(Y))Y=[Y];if(Array.isArray(Y)){for(let Z of Y)if(Z.StackId||Z.StackName){let Q;if(Z.Outputs?.member)Q=(Array.isArray(Z.Outputs.member)?Z.Outputs.member:[Z.Outputs.member]).map((W)=>({OutputKey:W.OutputKey,OutputValue:W.OutputValue,Description:W.Description,ExportName:W.ExportName}));J.push({StackId:Z.StackId,StackName:Z.StackName,StackStatus:Z.StackStatus,CreationTime:Z.CreationTime,LastUpdatedTime:Z.LastUpdatedTime,StackStatusReason:Z.StackStatusReason,Outputs:Q})}}else if($.StackId)J.push({StackId:$.StackId,StackName:$.StackName,StackStatus:$.StackStatus,CreationTime:$.CreationTime,LastUpdatedTime:$.LastUpdatedTime});return J}parseStackEvents($){let J=[],Y=$?.DescribeStackEventsResult?.StackEvents?.member||$?.StackEvents?.member||$?.StackEvents||[];if(Y&&!Array.isArray(Y))Y=[Y];for(let Z of Y)if(Z.LogicalResourceId)J.push({Timestamp:Z.Timestamp,ResourceType:Z.ResourceType,LogicalResourceId:Z.LogicalResourceId,ResourceStatus:Z.ResourceStatus,ResourceStatusReason:Z.ResourceStatusReason});return J}async waitForStackWithProgress($,J,Y){let Z={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},Q=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],G=Z[J],W=360,z=0,U=new Set;while(z<360)try{if(Y)try{let K=[...(await this.describeStackEvents($)).StackEvents||[]].reverse();for(let O of K){let V=`${O.LogicalResourceId}-${O.ResourceStatus}-${O.Timestamp}`;if(!U.has(V))U.add(V),Y({resourceId:O.LogicalResourceId,resourceType:O.ResourceType,status:O.ResourceStatus,reason:O.ResourceStatusReason,timestamp:O.Timestamp})}}catch{}let H=await this.describeStacks({stackName:$});if(H.Stacks.length===0){if(J==="stack-delete-complete")return;await new Promise((B)=>setTimeout(B,2000)),z++;continue}let F=H.Stacks[0];if(G.includes(F.StackStatus))return;if(F.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let B=Error("Stack deletion failed - may have resources that need to be retained");throw B.code="DELETE_FAILED",B.stackStatus=F.StackStatus,B.statusReason=F.StackStatusReason,B}if(Q.includes(F.StackStatus))throw Error(`Stack reached failure status: ${F.StackStatus}`);await new Promise((B)=>setTimeout(B,3000)),z++}catch(H){if(J==="stack-delete-complete"&&H.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&H.message?.includes("does not exist")){await new Promise((F)=>setTimeout(F,2000)),z++;continue}throw H}throw Error(`Timeout waiting for stack to reach ${J}`)}async waitForStackComplete($,J=120,Y=5000){let Z=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],Q=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let G=0;G<J;G++)try{let W=await this.describeStacks({stackName:$});if(W.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let z=W.Stacks[0],U=z.StackStatus;if(Z.includes(U))return{success:!0,status:U};if(Q.includes(U))return{success:!1,status:U,reason:z.StackStatusReason};await new Promise((H)=>setTimeout(H,Y))}catch(W){if(W.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw W}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}var L1=o(()=>{Y0()});class l2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeLogStreams($){let J={logGroupName:$.logGroupName};if($.logStreamNamePrefix)J.logStreamNamePrefix=$.logStreamNamePrefix;if($.orderBy)J.orderBy=$.orderBy;if($.descending!==void 0)J.descending=$.descending;if($.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async getLogEvents($){let J={logGroupName:$.logGroupName,logStreamName:$.logStreamName};if($.startTime)J.startTime=$.startTime;if($.endTime)J.endTime=$.endTime;if($.limit)J.limit=$.limit;if($.startFromHead!==void 0)J.startFromHead=$.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async describeLogGroups($){let J={};if($?.logGroupNamePrefix)J.logGroupNamePrefix=$.logGroupNamePrefix;if($?.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteLogGroup($){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:$})})}async filterLogEvents($){let J={logGroupName:$.logGroupName};if($.logStreamNames)J.logStreamNames=$.logStreamNames;if($.startTime)J.startTime=$.startTime;if($.endTime)J.endTime=$.endTime;if($.filterPattern)J.filterPattern=$.filterPattern;if($.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}}var i8=o(()=>{Y0()});var m$={};h0(m$,{LambdaClient:()=>l0});import{deflateRawSync as KM}from"zlib";function bU($,J){let Y=typeof J==="string"?Buffer.from(J,"utf-8"):J,Z=KM(Y),Q=OM(Y),G=new Date,W=(G.getHours()<<11|G.getMinutes()<<5|G.getSeconds()>>1)&65535,z=(G.getFullYear()-1980<<9|G.getMonth()+1<<5|G.getDate())&65535,U=Buffer.from($,"utf-8"),H=Buffer.alloc(30+U.length);H.writeUInt32LE(67324752,0),H.writeUInt16LE(20,4),H.writeUInt16LE(0,6),H.writeUInt16LE(8,8),H.writeUInt16LE(W,10),H.writeUInt16LE(z,12),H.writeUInt32LE(Q,14),H.writeUInt32LE(Z.length,18),H.writeUInt32LE(Y.length,22),H.writeUInt16LE(U.length,26),H.writeUInt16LE(0,28),U.copy(H,30);let F=Buffer.alloc(46+U.length);F.writeUInt32LE(33639248,0),F.writeUInt16LE(20,4),F.writeUInt16LE(20,6),F.writeUInt16LE(0,8),F.writeUInt16LE(8,10),F.writeUInt16LE(W,12),F.writeUInt16LE(z,14),F.writeUInt32LE(Q,16),F.writeUInt32LE(Z.length,20),F.writeUInt32LE(Y.length,24),F.writeUInt16LE(U.length,28),F.writeUInt16LE(0,30),F.writeUInt16LE(0,32),F.writeUInt16LE(0,34),F.writeUInt16LE(0,36),F.writeUInt32LE(0,38),F.writeUInt32LE(0,42),U.copy(F,46);let B=H.length+Z.length,K=F.length,O=Buffer.alloc(22);return O.writeUInt32LE(101010256,0),O.writeUInt16LE(0,4),O.writeUInt16LE(0,6),O.writeUInt16LE(1,8),O.writeUInt16LE(1,10),O.writeUInt32LE(K,12),O.writeUInt32LE(B,16),O.writeUInt16LE(0,20),Buffer.concat([H,Z,F,O])}function OM($){let J=[];for(let Z=0;Z<256;Z++){let Q=Z;for(let G=0;G<8;G++)Q=Q&1?3988292384^Q>>>1:Q>>>1;J[Z]=Q}let Y=4294967295;for(let Z=0;Z<$.length;Z++)Y=J[(Y^$[Z])&255]^Y>>>8;return(Y^4294967295)>>>0}class l0{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async createFunction($){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($)})}async getFunction($){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async updateFunctionCodeInline($,J,Y="index.js"){let Z=bU(Y,J);return this.updateFunctionCode({FunctionName:$,ZipFile:Z.toString("base64")})}async updateFunctionConfiguration($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async deleteFunction($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async invoke($){let{FunctionName:J,InvocationType:Y="RequestResponse",Payload:Z,LogType:Q}=$,G={"Content-Type":"application/json","X-Amz-Invocation-Type":Y};if(Q)G["X-Amz-Log-Type"]=Q;let W=Z?typeof Z==="string"?Z:JSON.stringify(Z):void 0,z=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/invocations`,headers:G,body:W,returnHeaders:!0});return{StatusCode:z.statusCode||200,FunctionError:z.headers?.["x-amz-function-error"],LogResult:z.headers?.["x-amz-log-result"],Payload:typeof z.body==="string"?z.body:JSON.stringify(z.body),ExecutedVersion:z.headers?.["x-amz-executed-version"]}}async listFunctions($){let J={};if($?.MaxItems)J.MaxItems=String($.MaxItems);if($?.Marker)J.Marker=$.Marker;if($?.FunctionVersion)J.FunctionVersion=$.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(J).length>0?J:void 0,headers:{"Content-Type":"application/json"}})}async addPermission($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async removePermission($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}/policy/${encodeURIComponent(J)}`,headers:{"Content-Type":"application/json"}})}async publishVersion($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async createAlias($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async updateAlias($){let{FunctionName:J,Name:Y,...Z}=$;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/aliases/${encodeURIComponent(Y)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)})}async getAlias($,J){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent($)}/aliases/${encodeURIComponent(J)}`})}catch(Y){if(/ResourceNotFound/i.test(String(Y?.message)))return null;throw Y}}async getProvisionedConcurrencyConfig($,J){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent($)}/provisioned-concurrency`,queryParams:{Qualifier:J}})}catch(Y){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(Y?.message)))return null;throw Y}}async putProvisionedConcurrencyConfig($){let{FunctionName:J,Qualifier:Y,ProvisionedConcurrentExecutions:Z}=$;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(J)}/provisioned-concurrency`,queryParams:{Qualifier:Y},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:Z})})}async deleteProvisionedConcurrencyConfig($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent($)}/provisioned-concurrency`,queryParams:{Qualifier:J}})}async waitForFunctionActive($,J=60){let Y=Date.now(),Z=J*1000;while(Date.now()-Y<Z)try{let Q=await this.getFunction($),G=Q.Configuration?.State;if(G==="Active")return Q.Configuration;if(G==="Failed")throw Error(`Function ${$} failed: ${Q.Configuration?.StateReason}`);await new Promise((W)=>setTimeout(W,2000))}catch(Q){if(Q.code==="ResourceNotFoundException"){await new Promise((G)=>setTimeout(G,2000));continue}throw Q}throw Error(`Timeout waiting for function ${$} to become active`)}async functionExists($){try{return await this.getFunction($),!0}catch(J){if(J.code==="ResourceNotFoundException"||J.statusCode===404)return!1;throw J}}async createFunctionUrl($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(J)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async getFunctionUrl($){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}catch(J){if(J.statusCode===404)return null;throw J}}async deleteFunctionUrl($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode($){let{Code:J,Filename:Y="index.js",...Z}=$,Q=bU(Y,J);return this.createFunction({...Z,Code:{ZipFile:Q.toString("base64")}})}async addFunctionUrlPermission($){return this.addPermission({FunctionName:$,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion($){let{LayerName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async listLayerVersions($,J){let Y={};if(J?.CompatibleRuntime)Y.CompatibleRuntime=J.CompatibleRuntime;if(J?.CompatibleArchitecture)Y.CompatibleArchitecture=J.CompatibleArchitecture;if(J?.MaxItems)Y.MaxItems=String(J.MaxItems);if(J?.Marker)Y.Marker=J.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions`,queryParams:Object.keys(Y).length>0?Y:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion($,J){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission($){let{LayerName:J,VersionNumber:Y,...Z}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions/${Y}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)})}async deleteLayerVersion($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}}var n1=o(()=>{Y0()});class H${client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async query($){let J=new URLSearchParams(g0({Version:"2010-08-01",...$})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J})}async getMetricStatistics($){let J={Action:"GetMetricStatistics",Namespace:$.Namespace,MetricName:$.MetricName,StartTime:$.StartTime.toISOString(),EndTime:$.EndTime.toISOString(),Period:$.Period};($.Statistics??[]).forEach((G,W)=>{J[`Statistics.member.${W+1}`]=G}),($.ExtendedStatistics??[]).forEach((G,W)=>{J[`ExtendedStatistics.member.${W+1}`]=G}),($.Dimensions??[]).forEach((G,W)=>{J[`Dimensions.member.${W+1}.Name`]=G.Name,J[`Dimensions.member.${W+1}.Value`]=G.Value});let Y=await this.query(J),Q=(Y.GetMetricStatisticsResult||Y)?.Datapoints?.member??[];if(!Array.isArray(Q))Q=Q?[Q]:[];return Q.map((G)=>{let W={},z=G.ExtendedStatistics?.entry;if(z){if(!Array.isArray(z))z=[z];for(let U of z)if(U?.key!=null)W[U.key]=Number(U.value)}return{Timestamp:G.Timestamp,Sum:G.Sum!=null?Number(G.Sum):void 0,Average:G.Average!=null?Number(G.Average):void 0,Maximum:G.Maximum!=null?Number(G.Maximum):void 0,Minimum:G.Minimum!=null?Number(G.Minimum):void 0,Percentiles:Object.keys(W).length?W:void 0,Unit:G.Unit}})}async getMetricSeries($){let J=/^p\d/.test($.Stat);return(await this.getMetricStatistics({Namespace:$.Namespace,MetricName:$.MetricName,Dimensions:$.Dimensions,StartTime:$.StartTime,EndTime:$.EndTime,Period:$.Period,Statistics:J?[]:[$.Stat],ExtendedStatistics:J?[$.Stat]:[]})).slice().sort((Z,Q)=>new Date(Z.Timestamp??0).getTime()-new Date(Q.Timestamp??0).getTime()).map((Z)=>J?Z.Percentiles?.[$.Stat]??0:Z[$.Stat]??0)}async describeAlarms($){let J={Action:"DescribeAlarms"};if($?.AlarmNamePrefix)J.AlarmNamePrefix=$.AlarmNamePrefix;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;let Y=await this.query(J),Q=(Y.DescribeAlarmsResult||Y)?.MetricAlarms?.member??[];if(!Array.isArray(Q))Q=Q?[Q]:[];return Q.map((G)=>({AlarmName:G.AlarmName,StateValue:G.StateValue,MetricName:G.MetricName,ComparisonOperator:G.ComparisonOperator,Threshold:G.Threshold!=null?Number(G.Threshold):void 0,Namespace:G.Namespace}))}async putMetricAlarm($){let J={Action:"PutMetricAlarm",AlarmName:$.AlarmName,Namespace:$.Namespace,MetricName:$.MetricName,ComparisonOperator:$.ComparisonOperator,Threshold:$.Threshold,EvaluationPeriods:$.EvaluationPeriods,Period:$.Period,Statistic:$.Statistic};if($.AlarmDescription)J.AlarmDescription=$.AlarmDescription;($.Dimensions??[]).forEach((Y,Z)=>{J[`Dimensions.member.${Z+1}.Name`]=Y.Name,J[`Dimensions.member.${Z+1}.Value`]=Y.Value}),($.AlarmActions??[]).forEach((Y,Z)=>{J[`AlarmActions.member.${Z+1}`]=Y}),await this.query(J)}}var NZ=o(()=>{Y0()});function a8($){if($){let Z=yU($);if(!Z)throw Error(`AWS profile '${$}' not found in ~/.aws/credentials`);return Z}let J=process.env.AWS_ACCESS_KEY_ID,Y=process.env.AWS_SECRET_ACCESS_KEY;if(J&&Y)return{accessKeyId:J,secretAccessKey:Y,sessionToken:process.env.AWS_SESSION_TOKEN};return yU(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function yU($){let{existsSync:J,readFileSync:Y}=G0("node:fs"),{homedir:Z}=G0("node:os"),{join:Q}=G0("node:path"),G=process.env.AWS_SHARED_CREDENTIALS_FILE||Q(Z(),".aws","credentials");if(!J(G))return null;let W=Y(G,"utf-8"),z=null,U,H,F;for(let B of W.split(`
|
|
6993
|
+
`);static createSessionsTable($){return{[`${$.slug}ChatbotSessionsTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-sessions`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"phoneNumber",AttributeType:"S"}],KeySchema:[{AttributeName:"phoneNumber",KeyType:"HASH"}],TimeToLiveSpecification:{AttributeName:"ttl",Enabled:!0}}}}}static createRulesTable($){return{[`${$.slug}ChatbotRulesTable`]:{Type:"AWS::DynamoDB::Table",Properties:{TableName:`${$.slug}-chatbot-rules`,BillingMode:"PAY_PER_REQUEST",AttributeDefinitions:[{AttributeName:"id",AttributeType:"S"}],KeySchema:[{AttributeName:"id",KeyType:"HASH"}]}}}}static createChatbotProcessorLambda($){return{[`${$.slug}ChatbotProcessorLambda`]:{Type:"AWS::Lambda::Function",Properties:{FunctionName:`${$.slug}-chatbot-processor`,Runtime:"nodejs20.x",Handler:"index.handler",Role:$.roleArn,Timeout:30,MemorySize:256,Code:{ZipFile:oY.ChatbotProcessorCode},Environment:{Variables:{SESSIONS_TABLE:$.sessionsTable,RULES_TABLE:$.rulesTable,CHATBOT_CONFIG:JSON.stringify($.chatbotConfig),ORIGINATION_NUMBER:$.originationNumber||""}}}}}}static DefaultRules=[{id:"greeting",priority:1,patterns:["^(hi|hello|hey|howdy)$","^good (morning|afternoon|evening)"],response:"Hello! How can I help you today?"},{id:"help",priority:2,patterns:["^help$","what can you do","how does this work"],response:"I can help with: 1) Account info 2) Support 3) Hours. Reply with a number."},{id:"hours",priority:3,patterns:["hours","open","when are you"],response:"We are open Mon-Fri 9am-5pm EST. Closed weekends."},{id:"thanks",priority:4,patterns:["^(thanks|thank you|thx)"],response:"You're welcome! Is there anything else I can help with?"},{id:"bye",priority:5,patterns:["^(bye|goodbye|quit|exit|stop)$"],response:"Goodbye! Text us anytime if you need help.",action:"end"}]};JE=new $Z;YE=new JZ;ZE=new YZ;QE=new ZZ,WE=(()=>{let $=[];for(let J=0;J<256;J++){let Y=J;for(let Z=0;Z<8;Z++)Y=Y&1?3988292384^Y>>>1:Y>>>1;$[J]=Y>>>0}return $})();XU=["18","20","22"];BU=["cli","fpm","curl","mbstring","xml","pdo","mysqlnd","gd","bcmath","intl","opcache","sodium","process","pecl-redis6","pecl-apcu","pgsql"];PE=/^(?:text\/|application\/(?:json|xml|javascript|graphql|x-www-form-urlencoded|.*\+json|.*\+xml)|image\/svg)/i;SU=["composer install --no-dev --optimize-autoloader --no-interaction","php artisan config:cache","php artisan route:cache","php artisan event:cache","php artisan view:cache"];kU=[".git",".github","node_modules","tests","storage/logs","storage/framework/cache","storage/framework/sessions","storage/framework/views",".env",".env.local",".vapor",".ts-cloud","dist-lambda"];$M=new KZ;JM=new OZ;YM=new AZ;ZM=new VZ;QM=new _Z});var jZ={};h0(jZ,{CloudFormationClient:()=>K0});class K0{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createStack($){let J={Action:"CreateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;else throw Error("Either templateBody or templateUrl must be provided");if($.parameters)$.parameters.forEach((Z,Q)=>{J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.timeoutInMinutes)J.TimeoutInMinutes=$.timeoutInMinutes;if($.onFailure)J.OnFailure=$.onFailure;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.CreateStackResult?.StackId}}async updateStack($){let J={Action:"UpdateStack",StackName:$.stackName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Z,Q)=>{if(J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,Z.UsePreviousValue)J[`Parameters.member.${Q+1}.UsePreviousValue`]="true";else J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.roleArn)J.RoleARN=$.roleArn;if($.tags)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackId:Y.StackId||Y.UpdateStackResult?.StackId}}async deleteStack($,J,Y){let Z={Action:"DeleteStack",StackName:$,Version:"2010-05-15"};if(J)Z.RoleARN=J;if(Y&&Y.length>0)Y.forEach((Q,G)=>{Z[`RetainResources.member.${G+1}`]=Q});await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Z).toString()})}async describeStacks($={}){let J={Action:"DescribeStacks",Version:"2010-05-15"};if($.stackName)J.StackName=$.stackName;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Stacks:this.parseStacksResponse(Y)}}async describeStackEvents($){let J={Action:"DescribeStackEvents",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{StackEvents:this.parseStackEvents(Y)}}async listStackResources($){let J={Action:"ListStackResources",StackName:$,Version:"2010-05-15"},Z=(await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}))?.ListStackResourcesResult?.StackResourceSummaries?.member,Q=[];if(Z)Q=Array.isArray(Z)?Z:[Z];return{StackResourceSummaries:Q}}async waitForStack($,J){let Y={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},Z=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],Q=Y[J],G=360,W=0;while(W<360)try{let z=await this.describeStacks({stackName:$});if(z.Stacks.length===0){if(J==="stack-delete-complete")return;if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Stack not visible yet`);await new Promise((H)=>setTimeout(H,2000)),W++;continue}let U=z.Stacks[0];if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Status = ${U.StackStatus}${U.StackStatusReason?` (${U.StackStatusReason})`:""}`);if(Q.includes(U.StackStatus))return;if((J==="stack-create-complete"||J==="stack-update-complete")&&(U.StackStatus==="DELETE_IN_PROGRESS"||U.StackStatus==="DELETE_COMPLETE")){console.log("[waitForStack] Stack is being deleted (creation/update failed)");let H="";try{let B=await this.describeStackEvents($);console.log("[waitForStack] Stack events (most recent first):");for(let K of B.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&&!H)H=K.ResourceStatusReason}}catch{}let F=H||U.StackStatusReason||"Check CloudFormation console for details.";throw Error(`Stack creation/update failed - stack is being deleted. Reason: ${F}`)}if(U.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let H=Error("Stack deletion failed - may have resources that need to be retained");throw H.code="DELETE_FAILED",H.stackStatus=U.StackStatus,H.statusReason=U.StackStatusReason,H}if(Z.includes(U.StackStatus))throw Error(`Stack reached failure status: ${U.StackStatus}`);await new Promise((H)=>setTimeout(H,5000)),W++}catch(z){if(J==="stack-delete-complete"&&z.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&z.message?.includes("does not exist")){if(W%10===0)console.log(`[waitForStack] Attempt ${W}: Stack does not exist (error), retrying...`);await new Promise((U)=>setTimeout(U,2000)),W++;continue}throw console.log(`[waitForStack] Unexpected error: ${z.message}`),z}throw console.log(`[waitForStack] Timeout after ${W} attempts`),Error(`Timeout waiting for stack to reach ${J}`)}async validateTemplate($){let J={Action:"ValidateTemplate",TemplateBody:$,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async listStacks($){let J={Action:"ListStacks",Version:"2010-05-15"};if($)$.forEach((z,U)=>{J[`StackStatusFilter.member.${U+1}`]=z});let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=Y.ListStacksResponse||Y,Q=Z.ListStacksResult||Z,G=Q.StackSummaries?.member||Q.StackSummaries||[];return{StackSummaries:(Array.isArray(G)?G:G?[G]:[]).map((z)=>({StackId:z.StackId||"",StackName:z.StackName||"",TemplateDescription:z.TemplateDescription,CreationTime:z.CreationTime||"",LastUpdatedTime:z.LastUpdatedTime,DeletionTime:z.DeletionTime,StackStatus:z.StackStatus||""}))}}async createChangeSet($){let J={Action:"CreateChangeSet",StackName:$.stackName,ChangeSetName:$.changeSetName,Version:"2010-05-15"};if($.templateBody)J.TemplateBody=$.templateBody;else if($.templateUrl)J.TemplateURL=$.templateUrl;if($.parameters)$.parameters.forEach((Z,Q)=>{J[`Parameters.member.${Q+1}.ParameterKey`]=Z.ParameterKey,J[`Parameters.member.${Q+1}.ParameterValue`]=Z.ParameterValue});if($.capabilities)$.capabilities.forEach((Z,Q)=>{J[`Capabilities.member.${Q+1}`]=Z});if($.changeSetType)J.ChangeSetType=$.changeSetType;let Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Id:Y.Id,StackId:Y.StackId}}async describeChangeSet($,J){let Y={Action:"DescribeChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};return await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async executeChangeSet($,J){let Y={Action:"ExecuteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async deleteChangeSet($,J){let Y={Action:"DeleteChangeSet",StackName:$,ChangeSetName:J,Version:"2010-05-15"};await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async getStackOutputs($){let J=await this.describeStacks({stackName:$});if(!J.Stacks||J.Stacks.length===0)throw Error(`Stack ${$} not found`);let Y=J.Stacks[0],Z={};if(Y.Outputs)for(let Q of Y.Outputs)Z[Q.OutputKey]=Q.OutputValue;return Z}async getTemplate($){let J={Action:"GetTemplate",StackName:$,Version:"2010-05-15"},Y=await this.client.request({service:"cloudformation",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{TemplateBody:Y?.GetTemplateResult?.TemplateBody||Y?.TemplateBody||""}}parseStacksResponse($){let J=[],Y=$?.DescribeStacksResult?.Stacks?.member||$?.Stacks?.member||$?.Stacks||$;if(Y&&!Array.isArray(Y))Y=[Y];if(Array.isArray(Y)){for(let Z of Y)if(Z.StackId||Z.StackName){let Q;if(Z.Outputs?.member)Q=(Array.isArray(Z.Outputs.member)?Z.Outputs.member:[Z.Outputs.member]).map((W)=>({OutputKey:W.OutputKey,OutputValue:W.OutputValue,Description:W.Description,ExportName:W.ExportName}));J.push({StackId:Z.StackId,StackName:Z.StackName,StackStatus:Z.StackStatus,CreationTime:Z.CreationTime,LastUpdatedTime:Z.LastUpdatedTime,StackStatusReason:Z.StackStatusReason,Outputs:Q})}}else if($.StackId)J.push({StackId:$.StackId,StackName:$.StackName,StackStatus:$.StackStatus,CreationTime:$.CreationTime,LastUpdatedTime:$.LastUpdatedTime});return J}parseStackEvents($){let J=[],Y=$?.DescribeStackEventsResult?.StackEvents?.member||$?.StackEvents?.member||$?.StackEvents||[];if(Y&&!Array.isArray(Y))Y=[Y];for(let Z of Y)if(Z.LogicalResourceId)J.push({Timestamp:Z.Timestamp,ResourceType:Z.ResourceType,LogicalResourceId:Z.LogicalResourceId,ResourceStatus:Z.ResourceStatus,ResourceStatusReason:Z.ResourceStatusReason});return J}async waitForStackWithProgress($,J,Y){let Z={"stack-create-complete":["CREATE_COMPLETE"],"stack-update-complete":["UPDATE_COMPLETE"],"stack-delete-complete":["DELETE_COMPLETE"]},Q=["CREATE_FAILED","ROLLBACK_FAILED","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE"],G=Z[J],W=360,z=0,U=new Set;while(z<360)try{if(Y)try{let K=[...(await this.describeStackEvents($)).StackEvents||[]].reverse();for(let O of K){let V=`${O.LogicalResourceId}-${O.ResourceStatus}-${O.Timestamp}`;if(!U.has(V))U.add(V),Y({resourceId:O.LogicalResourceId,resourceType:O.ResourceType,status:O.ResourceStatus,reason:O.ResourceStatusReason,timestamp:O.Timestamp})}}catch{}let H=await this.describeStacks({stackName:$});if(H.Stacks.length===0){if(J==="stack-delete-complete")return;await new Promise((B)=>setTimeout(B,2000)),z++;continue}let F=H.Stacks[0];if(G.includes(F.StackStatus))return;if(F.StackStatus==="DELETE_FAILED"&&J==="stack-delete-complete"){let B=Error("Stack deletion failed - may have resources that need to be retained");throw B.code="DELETE_FAILED",B.stackStatus=F.StackStatus,B.statusReason=F.StackStatusReason,B}if(Q.includes(F.StackStatus))throw Error(`Stack reached failure status: ${F.StackStatus}`);await new Promise((B)=>setTimeout(B,3000)),z++}catch(H){if(J==="stack-delete-complete"&&H.message?.includes("does not exist"))return;if(J==="stack-create-complete"&&H.message?.includes("does not exist")){await new Promise((F)=>setTimeout(F,2000)),z++;continue}throw H}throw Error(`Timeout waiting for stack to reach ${J}`)}async waitForStackComplete($,J=120,Y=5000){let Z=["CREATE_COMPLETE","UPDATE_COMPLETE","DELETE_COMPLETE"],Q=["CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED","ROLLBACK_COMPLETE","ROLLBACK_FAILED","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_FAILED"];for(let G=0;G<J;G++)try{let W=await this.describeStacks({stackName:$});if(W.Stacks.length===0)return{success:!0,status:"DELETE_COMPLETE"};let z=W.Stacks[0],U=z.StackStatus;if(Z.includes(U))return{success:!0,status:U};if(Q.includes(U))return{success:!1,status:U,reason:z.StackStatusReason};await new Promise((H)=>setTimeout(H,Y))}catch(W){if(W.message?.includes("does not exist"))return{success:!0,status:"DELETE_COMPLETE"};throw W}return{success:!1,status:"TIMEOUT",reason:"Timeout waiting for stack operation"}}}var L1=o(()=>{Y0()});class l2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeLogStreams($){let J={logGroupName:$.logGroupName};if($.logStreamNamePrefix)J.logStreamNamePrefix=$.logStreamNamePrefix;if($.orderBy)J.orderBy=$.orderBy;if($.descending!==void 0)J.descending=$.descending;if($.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogStreams","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async getLogEvents($){let J={logGroupName:$.logGroupName,logStreamName:$.logStreamName};if($.startTime)J.startTime=$.startTime;if($.endTime)J.endTime=$.endTime;if($.limit)J.limit=$.limit;if($.startFromHead!==void 0)J.startFromHead=$.startFromHead;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.GetLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async describeLogGroups($){let J={};if($?.logGroupNamePrefix)J.logGroupNamePrefix=$.logGroupNamePrefix;if($?.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DescribeLogGroups","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteLogGroup($){await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.DeleteLogGroup","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({logGroupName:$})})}async filterLogEvents($){let J={logGroupName:$.logGroupName};if($.logStreamNames)J.logStreamNames=$.logStreamNames;if($.startTime)J.startTime=$.startTime;if($.endTime)J.endTime=$.endTime;if($.filterPattern)J.filterPattern=$.filterPattern;if($.limit)J.limit=$.limit;return await this.client.request({service:"logs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"Logs_20140328.FilterLogEvents","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}}var i8=o(()=>{Y0()});var m$={};h0(m$,{LambdaClient:()=>l0});import{deflateRawSync as KM}from"zlib";function bU($,J){let Y=typeof J==="string"?Buffer.from(J,"utf-8"):J,Z=KM(Y),Q=OM(Y),G=new Date,W=(G.getHours()<<11|G.getMinutes()<<5|G.getSeconds()>>1)&65535,z=(G.getFullYear()-1980<<9|G.getMonth()+1<<5|G.getDate())&65535,U=Buffer.from($,"utf-8"),H=Buffer.alloc(30+U.length);H.writeUInt32LE(67324752,0),H.writeUInt16LE(20,4),H.writeUInt16LE(0,6),H.writeUInt16LE(8,8),H.writeUInt16LE(W,10),H.writeUInt16LE(z,12),H.writeUInt32LE(Q,14),H.writeUInt32LE(Z.length,18),H.writeUInt32LE(Y.length,22),H.writeUInt16LE(U.length,26),H.writeUInt16LE(0,28),U.copy(H,30);let F=Buffer.alloc(46+U.length);F.writeUInt32LE(33639248,0),F.writeUInt16LE(20,4),F.writeUInt16LE(20,6),F.writeUInt16LE(0,8),F.writeUInt16LE(8,10),F.writeUInt16LE(W,12),F.writeUInt16LE(z,14),F.writeUInt32LE(Q,16),F.writeUInt32LE(Z.length,20),F.writeUInt32LE(Y.length,24),F.writeUInt16LE(U.length,28),F.writeUInt16LE(0,30),F.writeUInt16LE(0,32),F.writeUInt16LE(0,34),F.writeUInt16LE(0,36),F.writeUInt32LE(0,38),F.writeUInt32LE(0,42),U.copy(F,46);let B=H.length+Z.length,K=F.length,O=Buffer.alloc(22);return O.writeUInt32LE(101010256,0),O.writeUInt16LE(0,4),O.writeUInt16LE(0,6),O.writeUInt16LE(1,8),O.writeUInt16LE(1,10),O.writeUInt32LE(K,12),O.writeUInt32LE(B,16),O.writeUInt16LE(0,20),Buffer.concat([H,Z,F,O])}function OM($){let J=[];for(let Z=0;Z<256;Z++){let Q=Z;for(let G=0;G<8;G++)Q=Q&1?3988292384^Q>>>1:Q>>>1;J[Z]=Q}let Y=4294967295;for(let Z=0;Z<$.length;Z++)Y=J[(Y^$[Z])&255]^Y>>>8;return(Y^4294967295)>>>0}class l0{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async createFunction($){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($)})}async getFunction($){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async updateFunctionCode($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/code`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async updateFunctionCodeInline($,J,Y="index.js"){let Z=bU(Y,J);return this.updateFunctionCode({FunctionName:$,ZipFile:Z.toString("base64")})}async updateFunctionConfiguration($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/configuration`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async deleteFunction($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}`,headers:{"Content-Type":"application/json"}})}async invoke($){let{FunctionName:J,InvocationType:Y="RequestResponse",Payload:Z,LogType:Q}=$,G={"Content-Type":"application/json","X-Amz-Invocation-Type":Y};if(Q)G["X-Amz-Log-Type"]=Q;let W=Z?typeof Z==="string"?Z:JSON.stringify(Z):void 0,z=await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/invocations`,headers:G,body:W,returnHeaders:!0});return{StatusCode:z.statusCode||200,FunctionError:z.headers?.["x-amz-function-error"],LogResult:z.headers?.["x-amz-log-result"],Payload:typeof z.body==="string"?z.body:JSON.stringify(z.body),ExecutedVersion:z.headers?.["x-amz-executed-version"]}}async listFunctions($){let J={};if($?.MaxItems)J.MaxItems=String($.MaxItems);if($?.Marker)J.Marker=$.Marker;if($?.FunctionVersion)J.FunctionVersion=$.FunctionVersion;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:"/2015-03-31/functions",queryParams:Object.keys(J).length>0?J:void 0,headers:{"Content-Type":"application/json"}})}async addPermission($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async removePermission($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2015-03-31/functions/${encodeURIComponent($)}/policy/${encodeURIComponent(J)}`,headers:{"Content-Type":"application/json"}})}async publishVersion($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async createAlias($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2015-03-31/functions/${encodeURIComponent(J)}/aliases`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async updateAlias($){let{FunctionName:J,Name:Y,...Z}=$;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2015-03-31/functions/${encodeURIComponent(J)}/aliases/${encodeURIComponent(Y)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)})}async getAlias($,J){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2015-03-31/functions/${encodeURIComponent($)}/aliases/${encodeURIComponent(J)}`})}catch(Y){if(/ResourceNotFound/i.test(String(Y?.message)))return null;throw Y}}async getProvisionedConcurrencyConfig($,J){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2019-09-30/functions/${encodeURIComponent($)}/provisioned-concurrency`,queryParams:{Qualifier:J}})}catch(Y){if(/ProvisionedConcurrencyConfigNotFound|ResourceNotFound/i.test(String(Y?.message)))return null;throw Y}}async putProvisionedConcurrencyConfig($){let{FunctionName:J,Qualifier:Y,ProvisionedConcurrentExecutions:Z}=$;return this.client.request({service:"lambda",region:this.region,method:"PUT",path:`/2019-09-30/functions/${encodeURIComponent(J)}/provisioned-concurrency`,queryParams:{Qualifier:Y},headers:{"Content-Type":"application/json"},body:JSON.stringify({ProvisionedConcurrentExecutions:Z})})}async deleteProvisionedConcurrencyConfig($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2019-09-30/functions/${encodeURIComponent($)}/provisioned-concurrency`,queryParams:{Qualifier:J}})}async waitForFunctionActive($,J=60){let Y=Date.now(),Z=J*1000;while(Date.now()-Y<Z)try{let Q=await this.getFunction($),G=Q.Configuration?.State;if(G==="Active")return Q.Configuration;if(G==="Failed")throw Error(`Function ${$} failed: ${Q.Configuration?.StateReason}`);await new Promise((W)=>setTimeout(W,2000))}catch(Q){if(Q.code==="ResourceNotFoundException"){await new Promise((G)=>setTimeout(G,2000));continue}throw Q}throw Error(`Timeout waiting for function ${$} to become active`)}async functionExists($){try{return await this.getFunction($),!0}catch(J){if(J.code==="ResourceNotFoundException"||J.statusCode===404)return!1;throw J}}async createFunctionUrl($){let{FunctionName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2021-10-31/functions/${encodeURIComponent(J)}/url`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async getFunctionUrl($){try{return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}catch(J){if(J.statusCode===404)return null;throw J}}async deleteFunctionUrl($){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2021-10-31/functions/${encodeURIComponent($)}/url`,headers:{"Content-Type":"application/json"}})}async createFunctionWithCode($){let{Code:J,Filename:Y="index.js",...Z}=$,Q=bU(Y,J);return this.createFunction({...Z,Code:{ZipFile:Q.toString("base64")}})}async addFunctionUrlPermission($){return this.addPermission({FunctionName:$,StatementId:"FunctionURLAllowPublicAccess",Action:"lambda:InvokeFunctionUrl",Principal:"*",FunctionUrlAuthType:"NONE"})}async publishLayerVersion($){let{LayerName:J,...Y}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)})}async listLayerVersions($,J){let Y={};if(J?.CompatibleRuntime)Y.CompatibleRuntime=J.CompatibleRuntime;if(J?.CompatibleArchitecture)Y.CompatibleArchitecture=J.CompatibleArchitecture;if(J?.MaxItems)Y.MaxItems=String(J.MaxItems);if(J?.Marker)Y.Marker=J.Marker;return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions`,queryParams:Object.keys(Y).length>0?Y:void 0,headers:{"Content-Type":"application/json"}})}async getLayerVersion($,J){return await this.client.request({service:"lambda",region:this.region,method:"GET",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}async addLayerVersionPermission($){let{LayerName:J,VersionNumber:Y,...Z}=$;return await this.client.request({service:"lambda",region:this.region,method:"POST",path:`/2018-10-31/layers/${encodeURIComponent(J)}/versions/${Y}/policy`,headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)})}async deleteLayerVersion($,J){await this.client.request({service:"lambda",region:this.region,method:"DELETE",path:`/2018-10-31/layers/${encodeURIComponent($)}/versions/${J}`,headers:{"Content-Type":"application/json"}})}}var n1=o(()=>{Y0()});class F${client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async query($){let J=new URLSearchParams(g0({Version:"2010-08-01",...$})).toString();return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J})}async getMetricStatistics($){let J={Action:"GetMetricStatistics",Namespace:$.Namespace,MetricName:$.MetricName,StartTime:$.StartTime.toISOString(),EndTime:$.EndTime.toISOString(),Period:$.Period};($.Statistics??[]).forEach((G,W)=>{J[`Statistics.member.${W+1}`]=G}),($.ExtendedStatistics??[]).forEach((G,W)=>{J[`ExtendedStatistics.member.${W+1}`]=G}),($.Dimensions??[]).forEach((G,W)=>{J[`Dimensions.member.${W+1}.Name`]=G.Name,J[`Dimensions.member.${W+1}.Value`]=G.Value});let Y=await this.query(J),Q=(Y.GetMetricStatisticsResult||Y)?.Datapoints?.member??[];if(!Array.isArray(Q))Q=Q?[Q]:[];return Q.map((G)=>{let W={},z=G.ExtendedStatistics?.entry;if(z){if(!Array.isArray(z))z=[z];for(let U of z)if(U?.key!=null)W[U.key]=Number(U.value)}return{Timestamp:G.Timestamp,Sum:G.Sum!=null?Number(G.Sum):void 0,Average:G.Average!=null?Number(G.Average):void 0,Maximum:G.Maximum!=null?Number(G.Maximum):void 0,Minimum:G.Minimum!=null?Number(G.Minimum):void 0,Percentiles:Object.keys(W).length?W:void 0,Unit:G.Unit}})}async getMetricSeries($){let J=/^p\d/.test($.Stat);return(await this.getMetricStatistics({Namespace:$.Namespace,MetricName:$.MetricName,Dimensions:$.Dimensions,StartTime:$.StartTime,EndTime:$.EndTime,Period:$.Period,Statistics:J?[]:[$.Stat],ExtendedStatistics:J?[$.Stat]:[]})).slice().sort((Z,Q)=>new Date(Z.Timestamp??0).getTime()-new Date(Q.Timestamp??0).getTime()).map((Z)=>J?Z.Percentiles?.[$.Stat]??0:Z[$.Stat]??0)}async describeAlarms($){let J={Action:"DescribeAlarms"};if($?.AlarmNamePrefix)J.AlarmNamePrefix=$.AlarmNamePrefix;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;let Y=await this.query(J),Q=(Y.DescribeAlarmsResult||Y)?.MetricAlarms?.member??[];if(!Array.isArray(Q))Q=Q?[Q]:[];return Q.map((G)=>({AlarmName:G.AlarmName,StateValue:G.StateValue,MetricName:G.MetricName,ComparisonOperator:G.ComparisonOperator,Threshold:G.Threshold!=null?Number(G.Threshold):void 0,Namespace:G.Namespace}))}async putMetricAlarm($){let J={Action:"PutMetricAlarm",AlarmName:$.AlarmName,Namespace:$.Namespace,MetricName:$.MetricName,ComparisonOperator:$.ComparisonOperator,Threshold:$.Threshold,EvaluationPeriods:$.EvaluationPeriods,Period:$.Period,Statistic:$.Statistic};if($.AlarmDescription)J.AlarmDescription=$.AlarmDescription;($.Dimensions??[]).forEach((Y,Z)=>{J[`Dimensions.member.${Z+1}.Name`]=Y.Name,J[`Dimensions.member.${Z+1}.Value`]=Y.Value}),($.AlarmActions??[]).forEach((Y,Z)=>{J[`AlarmActions.member.${Z+1}`]=Y}),await this.query(J)}}var NZ=o(()=>{Y0()});function a8($){if($){let Z=yU($);if(!Z)throw Error(`AWS profile '${$}' not found in ~/.aws/credentials`);return Z}let J=process.env.AWS_ACCESS_KEY_ID,Y=process.env.AWS_SECRET_ACCESS_KEY;if(J&&Y)return{accessKeyId:J,secretAccessKey:Y,sessionToken:process.env.AWS_SESSION_TOKEN};return yU(process.env.AWS_PROFILE||"default")??{accessKeyId:"",secretAccessKey:""}}function yU($){let{existsSync:J,readFileSync:Y}=G0("node:fs"),{homedir:Z}=G0("node:os"),{join:Q}=G0("node:path"),G=process.env.AWS_SHARED_CREDENTIALS_FILE||Q(Z(),".aws","credentials");if(!J(G))return null;let W=Y(G,"utf-8"),z=null,U,H,F;for(let B of W.split(`
|
|
6994
6994
|
`)){let K=B.trim();if(!K||K.startsWith("#")||K.startsWith(";"))continue;let O=K.match(/^\[([^\]]+)\]$/);if(O){if(z===$&&U&&H)return{accessKeyId:U,secretAccessKey:H,sessionToken:F};z=O[1],U=void 0,H=void 0,F=void 0;continue}if(z===$){let[V,...A]=K.split("="),_=A.join("=").trim();switch(V.trim().toLowerCase()){case"aws_access_key_id":U=_;break;case"aws_secret_access_key":H=_;break;case"aws_session_token":F=_;break}}}if(z===$&&U&&H)return{accessKeyId:U,secretAccessKey:H,sessionToken:F};return null}var l$={};h0(l$,{S3Client:()=>W0});import*as $0 from"node:crypto";import{readdir as AM}from"node:fs/promises";import{join as VM}from"node:path";import{readFileSync as vU}from"node:fs";function fU($){let{buffer:J,byteOffset:Y,byteLength:Z}=$;if(J instanceof ArrayBuffer)return J.slice(Y,Y+Z);let Q=new ArrayBuffer(Z);return new Uint8Array(Q).set(new Uint8Array($)),Q}class W0{client;region;explicitProfile;endpoint;forcePathStyle;explicitCredentials;constructor($="us-east-1",J,Y){this.region=$,this.explicitProfile=J,this.endpoint=Y?.endpoint,this.forcePathStyle=Y?.forcePathStyle,this.explicitCredentials=Y?.credentials,this.client=new i(Y?.credentials??a8(J),{endpoint:Y?.endpoint,forcePathStyle:Y?.forcePathStyle})}getCredentials(){if(this.explicitCredentials?.accessKeyId&&this.explicitCredentials.secretAccessKey)return this.explicitCredentials;let $=a8(this.explicitProfile);if($.accessKeyId&&$.secretAccessKey)return $;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($){return this.forcePathStyle?this.s3BaseHost():`${$}.${this.s3BaseHost()}`}async listBuckets(){let $=await this.client.request({service:"s3",region:this.region,method:"GET",path:"/"}),J=[],Z=($?.ListAllMyBucketsResult??$)?.Buckets?.Bucket;if(Z){let Q=Array.isArray(Z)?Z:[Z];for(let G of Q)J.push({Name:G.Name,CreationDate:G.CreationDate})}return{Buckets:J}}async createBucket($,J){let Y={};if(J?.acl)Y["x-amz-acl"]=J.acl;let Z;if(this.region!=="us-east-1"&&!this.endpoint)Z=`<?xml version="1.0" encoding="UTF-8"?>
|
|
6995
6995
|
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
|
6996
6996
|
<LocationConstraint>${this.region}</LocationConstraint>
|
|
@@ -7080,8 +7080,8 @@ host:${W}
|
|
|
7080
7080
|
<Quiet>true</Quiet>
|
|
7081
7081
|
${J.map((Q)=>`<Object><Key>${Q.Key}</Key>${Q.VersionId?`<VersionId>${Q.VersionId}</VersionId>`:""}</Object>`).join(`
|
|
7082
7082
|
`)}
|
|
7083
|
-
</Delete>`,Z=$0.createHash("md5").update(Y).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}`,queryParams:{delete:""},body:Y,headers:{"Content-Type":"application/xml","Content-MD5":Z}})}}var I0=o(()=>{Y0()});class G2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createSecret($){let J={Name:$.Name};if($.Description)J.Description=$.Description;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;if($.Tags&&$.Tags.length>0)J.Tags=$.Tags;if($.AddReplicaRegions&&$.AddReplicaRegions.length>0)J.AddReplicaRegions=$.AddReplicaRegions;if($.ForceOverwriteReplicaSecret!==void 0)J.ForceOverwriteReplicaSecret=$.ForceOverwriteReplicaSecret;J.ClientRequestToken=$.ClientRequestToken||crypto.randomUUID();let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,ReplicationStatus:Y.ReplicationStatus}}async updateSecret($){let J={SecretId:$.SecretId};if($.Description)J.Description=$.Description;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId}}async putSecretValue($){let J={SecretId:$.SecretId};if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;if($.VersionStages&&$.VersionStages.length>0)J.VersionStages=$.VersionStages;if($.ClientRequestToken)J.ClientRequestToken=$.ClientRequestToken;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,VersionStages:Y.VersionStages}}async getSecretValue($){let J={SecretId:$.SecretId};if($.VersionId)J.VersionId=$.VersionId;if($.VersionStage)J.VersionStage=$.VersionStage;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,SecretBinary:Y.SecretBinary,SecretString:Y.SecretString,VersionStages:Y.VersionStages,CreatedDate:Y.CreatedDate}}async describeSecret($){let J={SecretId:$},Y=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(J)});return this.parseSecret(Y)}async listSecrets($){let J={};if($?.MaxResults)J.MaxResults=$.MaxResults;if($?.NextToken)J.NextToken=$.NextToken;if($?.Filters&&$.Filters.length>0)J.Filters=$.Filters;if($?.SortOrder)J.SortOrder=$.SortOrder;let Y=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(J)});return{SecretList:Y.SecretList?.map((Z)=>this.parseSecret(Z)),NextToken:Y.NextToken}}async deleteSecret($){let J={SecretId:$.SecretId};if($.RecoveryWindowInDays!==void 0)J.RecoveryWindowInDays=$.RecoveryWindowInDays;if($.ForceDeleteWithoutRecovery!==void 0)J.ForceDeleteWithoutRecovery=$.ForceDeleteWithoutRecovery;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,DeletionDate:Y.DeletionDate}}async restoreSecret($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async rotateSecret($){let J={SecretId:$.SecretId};if($.ClientRequestToken)J.ClientRequestToken=$.ClientRequestToken;if($.RotationLambdaARN)J.RotationLambdaARN=$.RotationLambdaARN;if($.RotationRules)J.RotationRules=$.RotationRules;if($.RotateImmediately!==void 0)J.RotateImmediately=$.RotateImmediately;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId}}async cancelRotateSecret($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async getResourcePolicy($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,ResourcePolicy:Y.ResourcePolicy}}async putResourcePolicy($){let J={SecretId:$.SecretId,ResourcePolicy:$.ResourcePolicy};if($.BlockPublicPolicy!==void 0)J.BlockPublicPolicy=$.BlockPublicPolicy;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async deleteResourcePolicy($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async tagResource($){let J={SecretId:$.SecretId,Tags:$.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(J)})}async untagResource($){let J={SecretId:$.SecretId,TagKeys:$.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(J)})}async setString($,J,Y){try{let Z=await this.putSecretValue({SecretId:$,SecretString:J});return{ARN:Z.ARN,VersionId:Z.VersionId}}catch(Z){if(Z.code==="ResourceNotFoundException"){let Q=await this.createSecret({Name:$,SecretString:J,Description:Y?.description,KmsKeyId:Y?.kmsKeyId,Tags:Y?.tags});return{ARN:Q.ARN,VersionId:Q.VersionId}}throw Z}}async setJson($,J,Y){return this.setString($,JSON.stringify(J),Y)}async getString($){return(await this.getSecretValue({SecretId:$})).SecretString}async getJson($){let J=await this.getString($);if(J)return JSON.parse(J);return}async listAll(){let $=[],J;do{let Y=await this.listSecrets({NextToken:J});if(Y.SecretList)$.push(...Y.SecretList);J=Y.NextToken}while(J);return $}parseSecret($){return{ARN:$.ARN,Name:$.Name,Description:$.Description,KmsKeyId:$.KmsKeyId,RotationEnabled:$.RotationEnabled,RotationLambdaARN:$.RotationLambdaARN,RotationRules:$.RotationRules,LastRotatedDate:$.LastRotatedDate,LastChangedDate:$.LastChangedDate,LastAccessedDate:$.LastAccessedDate,DeletedDate:$.DeletedDate,NextRotationDate:$.NextRotationDate,Tags:$.Tags,SecretVersionsToStages:$.SecretVersionsToStages,CreatedDate:$.CreatedDate,PrimaryRegion:$.PrimaryRegion}}}var o6=o(()=>{Y0()});class p${client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRepository($){let J={repositoryName:$.repositoryName};if($.imageTagMutability)J.imageTagMutability=$.imageTagMutability;if($.imageScanningConfiguration)J.imageScanningConfiguration=$.imageScanningConfiguration;if($.encryptionConfiguration)J.encryptionConfiguration=$.encryptionConfiguration;if($.tags&&$.tags.length>0)J.tags=$.tags;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeRepositories($){let J={};if($?.repositoryNames&&$.repositoryNames.length>0)J.repositoryNames=$.repositoryNames;if($?.registryId)J.registryId=$.registryId;if($?.maxResults)J.maxResults=$.maxResults;if($?.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repositories:Y.repositories?.map((Z)=>this.parseRepository(Z)),nextToken:Y.nextToken}}async getAuthorizationToken($){let J={};if($&&$.length>0)J.registryIds=$;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).authorizationData?.map((Z)=>({authorizationToken:Z.authorizationToken,expiresAt:Z.expiresAt,proxyEndpoint:Z.proxyEndpoint}))}}async deleteRepository($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeImages($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.imageIds&&$.imageIds.length>0)J.imageIds=$.imageIds;if($.filter)J.filter=$.filter;if($.maxResults)J.maxResults=$.maxResults;if($.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageDetails:Y.imageDetails?.map((Z)=>this.parseImageDetail(Z)),nextToken:Y.nextToken}}async batchDeleteImage($){let J={repositoryName:$.repositoryName,imageIds:$.imageIds};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageIds:Y.imageIds,failures:Y.failures}}async putLifecyclePolicy($){let J={repositoryName:$.repositoryName,lifecyclePolicyText:$.lifecyclePolicyText};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText}}async getLifecyclePolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText,lastEvaluatedAt:Y.lastEvaluatedAt}}async setRepositoryPolicy($){let J={repositoryName:$.repositoryName,policyText:$.policyText};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async getRepositoryPolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async tagResource($){let J={resourceArn:$.resourceArn,tags:$.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTagsForResource($){let J={resourceArn:$};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).tags}}createLifecyclePolicyText($){return JSON.stringify({rules:$.map((J)=>({rulePriority:J.rulePriority,description:J.description,selection:J.selection,action:J.action}))})}async getDockerLoginCommand(){let $=await this.getAuthorizationToken();if(!$.authorizationData?.[0])throw Error("Failed to get authorization token");let J=$.authorizationData[0],Y=J.authorizationToken||"",Z=J.proxyEndpoint||"";return`echo "${Buffer.from(Y,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${Z}`}getRegistryUri($){return`${$}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository($){return{repositoryArn:$.repositoryArn,registryId:$.registryId,repositoryName:$.repositoryName,repositoryUri:$.repositoryUri,createdAt:$.createdAt,imageTagMutability:$.imageTagMutability,imageScanningConfiguration:$.imageScanningConfiguration,encryptionConfiguration:$.encryptionConfiguration}}parseImageDetail($){return{registryId:$.registryId,repositoryName:$.repositoryName,imageDigest:$.imageDigest,imageTags:$.imageTags,imageSizeInBytes:$.imageSizeInBytes,imagePushedAt:$.imagePushedAt,imageScanStatus:$.imageScanStatus,imageScanFindingsSummary:$.imageScanFindingsSummary}}}var e6=o(()=>{Y0()});var dU={};h0(dU,{buildAndPushServerlessImage:()=>PZ});import{execFileSync as gU}from"node:child_process";import{mkdirSync as SZ,mkdtempSync as _M,rmSync as jM,writeFileSync as $7}from"node:fs";import{tmpdir as LM}from"node:os";import{dirname as EM,join as p2}from"node:path";function uU($,J){for(let Y of J){let Z=p2($,Y.name);SZ(EM(Z),{recursive:!0}),$7(Z,Y.data,Y.mode?{mode:Y.mode}:void 0)}}async function PZ($){let{app:J,projectRoot:Y,region:Z,repository:Q}=$,G=J.architecture??"x86_64",W=G==="arm64"?"linux/arm64":"linux/amd64",z=J.kind==="php",U=$.onStep??(()=>{}),H=_M(p2(LM(),"tscloud-img-"));try{let F=p2(H,"app");SZ(F,{recursive:!0});let B,K;if(z){t6({projectRoot:Y,app:J,skipBuild:$.skipBuild,onStep:U}),U("staging application tree");let T=s6(Y);uU(F,T),uU(p2(H,"runtime"),v8().map((S)=>({name:S.path,data:S.contents,mode:S.mode})));let D=J.handlers?.http??"public/index.php";B={http:D,queue:J.handlers?.queue??D,cli:J.handlers?.cli??D},K=r6(T.map((S)=>`${S.name}:${S.data.length}`).join("|"))}else{U("bundling application");let T=await c8({projectRoot:Y,app:J,skipBuild:$.skipBuild,onStep:U});$7(p2(F,"index.mjs"),T.bundle),B=T.handlers,K=T.sha256}let O=K.slice(0,16);$7(p2(H,"Dockerfile"),UZ({kind:J.kind??"node",phpVersion:J.phpVersion,architecture:G}));let V=new p$(Z),A;try{A=(await V.describeRepositories({repositoryNames:[Q]})).repositories?.[0]?.repositoryUri??""}catch{A=""}if(!A)U(`creating ECR repository ${Q}`),A=(await V.createRepository({repositoryName:Q,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!A)throw Error(`could not resolve ECR repository URI for ${Q}`);let _=`${A}:${O}`;U("docker build"),gU("docker",["build","--platform",W,"--provenance=false","--sbom=false","-t",_,H],{stdio:"inherit"}),U("ecr auth + push");let E=(await V.getAuthorizationToken()).authorizationData?.[0];if(!E?.authorizationToken||!E.proxyEndpoint)throw Error("failed to get an ECR authorization token");let j=E.proxyEndpoint.replace(/^https?:\/\//,""),q=p2(H,".docker");return SZ(q,{recursive:!0}),$7(p2(q,"config.json"),JSON.stringify({auths:{[j]:{auth:E.authorizationToken}}})),gU("docker",["push",_],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:q}}),X(`Image: ${_}`),{imageUri:_,tag:O,handlers:B}}finally{jM(H,{recursive:!0,force:!0})}}var CZ=o(async()=>{e6();z0();await n0()});var J7={};h0(J7,{RDSClient:()=>xZ});class xZ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeDBInstances($){let J={Action:"DescribeDBInstances",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((W,z)=>{J[`Filters.Filter.${z+1}.Name`]=W.Name,W.Values.forEach((U,H)=>{J[`Filters.Filter.${z+1}.Values.Value.${H+1}`]=U})});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBInstancesResult||Z,G=Q.DBInstances?.DBInstance||[];if(!Array.isArray(G))G=G?[G]:[];return{DBInstances:G,Marker:Q.Marker}}async describeDBInstance($){return(await this.describeDBInstances({DBInstanceIdentifier:$})).DBInstances?.[0]}async describeDBClusters($){let J={Action:"DescribeDBClusters",Version:"2014-10-31"};if($?.DBClusterIdentifier)J.DBClusterIdentifier=$.DBClusterIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((W,z)=>{J[`Filters.Filter.${z+1}.Name`]=W.Name,W.Values.forEach((U,H)=>{J[`Filters.Filter.${z+1}.Values.Value.${H+1}`]=U})});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBClustersResult||Z,G=Q.DBClusters?.DBCluster||[];if(!Array.isArray(G))G=G?[G]:[];return{DBClusters:G,Marker:Q.Marker}}async describeDBSnapshots($){let J={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;if($?.SnapshotType)J.SnapshotType=$.SnapshotType;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBSnapshotsResult||Z,G=Q.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSnapshots:G,Marker:Q.Marker}}async describeDBSubnetGroups($){let J={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if($?.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBSubnetGroupsResult||Z,G=Q.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSubnetGroups:G,Marker:Q.Marker}}async createDBInstance($){let J={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBInstanceClass:$.DBInstanceClass,Engine:$.Engine};if($.DBClusterIdentifier)J.DBClusterIdentifier=$.DBClusterIdentifier;if($.MasterUsername)J.MasterUsername=$.MasterUsername;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.DBName)J.DBName=$.DBName;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.LicenseModel)J.LicenseModel=$.LicenseModel;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.StorageType)J.StorageType=$.StorageType;if($.StorageEncrypted!==void 0)J.StorageEncrypted=$.StorageEncrypted;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.CreateDBInstanceResult||Z).DBInstance}}async deleteDBInstance($){let J={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.SkipFinalSnapshot!==void 0)J.SkipFinalSnapshot=$.SkipFinalSnapshot;if($.FinalDBSnapshotIdentifier)J.FinalDBSnapshotIdentifier=$.FinalDBSnapshotIdentifier;if($.DeleteAutomatedBackups!==void 0)J.DeleteAutomatedBackups=$.DeleteAutomatedBackups;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.DeleteDBInstanceResult||Z).DBInstance}}async modifyDBInstance($){let J={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.ApplyImmediately!==void 0)J.ApplyImmediately=$.ApplyImmediately;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.ModifyDBInstanceResult||Z).DBInstance}}async modifyDBCluster($){let J={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:$.DBClusterIdentifier};if($.ServerlessV2ScalingConfiguration)J["ServerlessV2ScalingConfiguration.MinCapacity"]=$.ServerlessV2ScalingConfiguration.MinCapacity,J["ServerlessV2ScalingConfiguration.MaxCapacity"]=$.ServerlessV2ScalingConfiguration.MaxCapacity;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.ApplyImmediately!==void 0)J.ApplyImmediately=$.ApplyImmediately;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBCluster:(Z.ModifyDBClusterResult||Z).DBCluster}}async restoreDBClusterToPointInTime($){let J={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:$.DBClusterIdentifier,SourceDBClusterIdentifier:$.SourceDBClusterIdentifier};if($.RestoreToTime)J.RestoreToTime=$.RestoreToTime.toISOString();if($.UseLatestRestorableTime)J.UseLatestRestorableTime=!0;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBCluster:(Z.RestoreDBClusterToPointInTimeResult||Z).DBCluster}}async startDBInstance($){let Y=new URLSearchParams(g0({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$})).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.StartDBInstanceResult||Z).DBInstance}}async stopDBInstance($){let J={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.StopDBInstanceResult||Z).DBInstance}}async rebootDBInstance($){let J={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.ForceFailover!==void 0)J.ForceFailover=$.ForceFailover;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.RebootDBInstanceResult||Z).DBInstance}}async createDBSnapshot($){let J={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Z.CreateDBSnapshotResult||Z).DBSnapshot}}async deleteDBSnapshot($){let Y=new URLSearchParams(g0({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:$})).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Z.DeleteDBSnapshotResult||Z).DBSnapshot}}async restoreDBInstanceFromDBSnapshot($){let J={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.Port)J.Port=$.Port;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.RestoreDBInstanceFromDBSnapshotResult||Z).DBInstance}}async waitForDBInstanceAvailable($,J=60,Y=30000){for(let Z=0;Z<J;Z++){let Q=await this.describeDBInstance($);if(Q?.DBInstanceStatus==="available")return Q;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(Q?.DBInstanceStatus||""))throw Error(`DB instance ${$} is in terminal state: ${Q?.DBInstanceStatus}`);await new Promise((G)=>setTimeout(G,Y))}throw Error(`Timeout waiting for DB instance ${$} to become available`)}async waitForDBInstanceDeleted($,J=60,Y=30000){for(let Z=0;Z<J;Z++)try{let Q=await this.describeDBInstance($);if(Q?.DBInstanceStatus==="deleting"){await new Promise((G)=>setTimeout(G,Y));continue}throw Error(`DB instance ${$} is in state: ${Q?.DBInstanceStatus}`)}catch(Q){if(Q.code==="DBInstanceNotFound"||Q.code==="DBInstanceNotFoundFault")return;throw Q}throw Error(`Timeout waiting for DB instance ${$} to be deleted`)}}var t8=o(()=>{Y0()});var g1={};h0(g1,{setMaintenance:()=>bZ,serverlessInfo:()=>yZ,scaleServerlessDatabase:()=>IM,runRemoteCommand:()=>n$,runDbQuery:()=>xM,runAndRecordCommand:()=>PM,rollbackServerlessApp:()=>hZ,restoreServerlessDatabase:()=>kM,resolveServerlessFunctions:()=>q2,resolveSecrets:()=>pU,redeployServerlessApp:()=>kZ,listCommandHistory:()=>aU,infraEnvFromOutputs:()=>Q7,getCommandRecord:()=>CM,deployServerlessApp:()=>IZ,buildFunctionEnv:()=>r$,assertEnvWithinLimit:()=>G7});import{existsSync as MM,readdirSync as qM,readFileSync as TM,statSync as wM}from"node:fs";import{join as cU,relative as DM}from"node:path";function i1($,J){let Y=$.environments?.[J]?.app;if(!Y)throw Error(`No serverless app configured for environment '${J}'. Add environments.${J}.app to your config.`);let Z=$.project.slug,Q=$.environments?.[J]?.region||$.project.region||"us-east-1";return{app:Y,slug:Z,region:Q,stackName:W$($,J),artifactBucket:xJ(Z,J),assetsBucket:d6(Z,J)}}function q2($,J){let Y=i1($,J),Z=`${Y.slug}-${J}`;return{region:Y.region,slug:Y.slug,stackName:Y.stackName,functions:{http:`${Z}-http`,queue:`${Z}-queue`,cli:`${Z}-cli`}}}async function F$($,J=8){let Y;for(let Z=0;Z<J;Z++)try{return await $()}catch(Q){let G=Q?.code||Q?.name||"",W=String(Q?.message||"");if(G==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(W)){Y=Q,await new Promise((z)=>setTimeout(z,3000));continue}throw Q}throw Y}async function Z7($,J,Y,Z){try{return await $.getObjectJson(J,mU(Y,Z))}catch{return null}}async function lU($,J,Y,Z,Q){await $.putObjectJson(J,mU(Y,Z),Q)}async function pU($,J){if(!$.secrets)return{};let Y=new G2(J),Z={},Q=Array.isArray($.secrets)?$.secrets.map((G)=>({envName:G.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:G})):Object.entries($.secrets).map(([G,W])=>({envName:G,secretId:W}));if(Array.isArray($.secrets)){let G=new Map;for(let{envName:z,secretId:U}of Q)G.set(z,[...G.get(z)??[],U]);let W=[...G.entries()].filter(([,z])=>z.length>1);if(W.length){let z=W.map(([U,H])=>`${U} ← ${H.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${z}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:G,secretId:W}of Q){let U=(await Y.getSecretValue({SecretId:W})).SecretString??"";try{let H=JSON.parse(U);if(H&&typeof H==="object"&&!Array.isArray(H)){for(let[F,B]of Object.entries(H))Z[F]=String(B);continue}}catch{}Z[G]=U}return Z}function Q7($,J){let Y={},Z=J.DbProxyEndpoint||J.DbEndpoint;if(Z)Y.DB_CONNECTION="mysql",Y.DB_HOST=Z,Y.DB_PORT="3306",Y.DB_DATABASE=Y.DB_DATABASE||"app";if(J.CacheEndpoint){if(Y.REDIS_HOST=J.CacheEndpoint,Y.REDIS_PORT="6379",$.cache?.driver==="elasticache")Y.CACHE_STORE="redis",Y.CACHE_DRIVER="redis",Y.SESSION_DRIVER="redis"}return Y}function r$($,J,Y,Z,Q,G,W,z={}){let U=$.kind==="php"?FZ({cacheDriver:$.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:Z,TSCLOUD_ENV:Y,MAINTENANCE_MODE:"0",...$.octane?{TSCLOUD_OCTANE:"1"}:{},...$.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...$.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...U,...z,...J.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${J.slug}-${Y}-cache`}:{},...W?{TSCLOUD_QUEUE:W,SQS_QUEUE:W}:{},...G?{ASSET_URL:G}:{},...$.env??{},...Q}}function RM($){let J=$.slice($.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"}[J]??"application/octet-stream"}function*rU($){for(let J of qM($)){let Y=cU($,J);if(wM(Y).isDirectory())yield*rU(Y);else yield Y}}async function NM($,J,Y,Z,Q=!1){let G=0;for(let W of rU(Y)){let z=DM(Y,W).replace(/\\/g,"/");if(!Q&&z.split("/").some((U)=>U.startsWith(".")))continue;await $.putObject({bucket:J,key:`${Z}/${z}`,body:TM(W),contentType:RM(W),cacheControl:"public, max-age=31536000, immutable"}),G++}return G}function G7($,J){let Y=Object.entries(J).reduce((Z,[Q,G])=>Z+Buffer.byteLength(`${Q}=${G}`,"utf8"),0);if(Y>4096){let Z=Object.entries(J).map(([Q,G])=>[Q,Buffer.byteLength(`${Q}=${G}`,"utf8")]).sort((Q,G)=>G[1]-Q[1]).slice(0,5).map(([Q,G])=>`${Q} (${G}B)`).join(", ");throw Error(`${$}: environment variables total ${Y}B, over AWS's 4096B limit (${Y-4096}B too large). Largest: ${Z}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function s8($,J,Y,Z){G7(J,Y),await F$(()=>$.updateFunctionConfiguration({FunctionName:J,Environment:{Variables:Y}})),await $.waitForFunctionActive(J,120);let Q=Z.kind==="image"?{FunctionName:J,ImageUri:Z.imageUri}:{FunctionName:J,S3Bucket:Z.bucket,S3Key:Z.key};await F$(()=>$.updateFunctionCode(Q)),await $.waitForFunctionActive(J,120)}async function Y7($,J){let Z=(await F$(()=>$.publishVersion({FunctionName:J}))).Version;if(!Z)throw Error(`publishVersion returned no version for ${J}`);return await F$(()=>$.updateAlias({FunctionName:J,Name:"live",FunctionVersion:Z})),Z}async function IZ($,J,Y={}){let Z=i1($,J),{app:Q,slug:G,region:W,stackName:z,artifactBucket:U}=Z,H=Y.projectRoot??process.cwd();R(`Deploying serverless app: ${G} (${J})`),X(`Stack: ${z}`),X(`Region: ${W}`);let F=new W0(W),B=new K0(W),K=new l0(W),O=Q.kind==="php",V=Q.packaging==="image",A=n6(Q),_,M,E,j,q=[];if(V&&A.usesLayer&&A.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${A.kind}${A.kind==="node"?` ${A.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(V){n("Building + pushing container image");let{buildAndPushServerlessImage:a}=await CZ().then(() => dU),e=await a({app:Q,projectRoot:H,region:W,repository:`${G}-${J}`,skipBuild:Y.skipBuild,onStep:(L0)=>X(` ${L0}`)});_=e.handlers,M={kind:"image",imageUri:e.imageUri},E=e.tag,q.push({ParameterKey:"ImageUri",ParameterValue:e.imageUri})}else{n("Packaging application");let a=O?BZ({projectRoot:H,app:Q,skipBuild:Y.skipBuild,onStep:(_0)=>X(` ${_0}`)}):await c8({projectRoot:H,app:Q,skipBuild:Y.skipBuild,onStep:(_0)=>X(` ${_0}`)}),e=QZ(G,J,a.sha256);if(X(`Artifact: ${a.sha256.slice(0,12)} (${(a.zip.length/1024).toFixed(0)} KB)`),_=a.handlers,E=a.sha256,A.usesLayer){let _0=A.layerEnvVar?process.env[A.layerEnvVar]:void 0;if(j=Q.layers??(_0?[_0]:void 0),!j?.length){let O0=A.layerKind==="php"?"serverless:build-php-layer":A.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${A.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${A.layerEnvVar} env var (build one with \`cloud ${O0}\`)${A.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await F.bucketExists(U))n(`Creating artifact bucket ${U}`),await F.createBucket(U);if(await F.headObject(U,e).then((_0)=>_0!==null).catch(()=>!1))X("Artifact already uploaded — reusing");else n("Uploading artifact"),await F.putObject({bucket:U,key:e,body:a.zip,contentType:"application/zip"});M={kind:"zip",bucket:U,key:e},q.push({ParameterKey:"ArtifactBucket",ParameterValue:U},{ParameterKey:"ArtifactKey",ParameterValue:e})}let T=WZ({config:$,environment:J,app:Q,handlers:_,runtimeLayers:j}),D=JSON.stringify(T.template),S=["CAPABILITY_NAMED_IAM"],P=await B.describeStacks({stackName:z}).then((a)=>a.Stacks[0]?.StackStatus).catch(()=>{return}),C=P!==void 0;if(P&&/DELETE_IN_PROGRESS/.test(P))n("Waiting for an in-progress stack delete to finish"),await B.waitForStack(z,"stack-delete-complete").catch(()=>{}),C=!1;else if(P&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(P))n(`Deleting unusable stack (status ${P}) before recreate`),await B.deleteStack(z),await B.waitForStack(z,"stack-delete-complete").catch(()=>{}),C=!1;n(C?"Updating infrastructure stack":"Creating infrastructure stack");try{if(C)await B.updateStack({stackName:z,templateBody:D,parameters:q,capabilities:S}),await B.waitForStack(z,"stack-update-complete");else await B.createStack({stackName:z,templateBody:D,parameters:q,capabilities:S,onFailure:"DELETE"}),await B.waitForStack(z,"stack-create-complete")}catch(a){if(/No updates are to be performed/i.test(String(a?.message)))X("No infrastructure changes");else throw a}let I=await B.getStackOutputs(z).catch(()=>({})),b;if(Q.assets){let a=cU(H,Q.assets);if(MM(a)){let e=Q.assetDomain||I.AssetsCdnDomain;b=e?`https://${e}/${E}`:void 0,n(`Syncing assets from ${Q.assets}`);let L0=await NM(F,Z.assetsBucket,a,E,Q.dotFilesAsAssets);X(`Uploaded ${L0} asset(s)${b?` → ${b}`:""}`)}else v(`Assets directory not found: ${a}`)}n("Resolving secrets");let y=await pU(Q,W);if(Q.database?.connection==="aurora-serverless")try{let e=await new G2(W).getSecretValue({SecretId:`${G}/${J}/db`}),L0=JSON.parse(e.SecretString??"{}");if(L0.username)y.DB_USERNAME=L0.username;if(L0.password)y.DB_PASSWORD=L0.password}catch(a){v(`Could not resolve Aurora DB credentials: ${a.message}`)}if(!await F.bucketExists(U))await F.createBucket(U);let c=await Z7(F,U,G,J),r={},d=T.queueNames[0],u=Q7(Q,I);if(n("Activating functions"),r.http=r$(Q,Z,J,"http",y,b,d,u),await s8(K,T.functionNames.http,r.http,M),r.cli=r$(Q,Z,J,"cli",y,b,d,u),await s8(K,T.functionNames.cli,r.cli,M),T.queueNames.length)r.queue=r$(Q,Z,J,"queue",y,b,d,u),await s8(K,T.functionNames.queue,r.queue,M);let s=(Q.provisionedConcurrency??0)>0,J0={};if(s){if(n("Publishing versions + flipping live alias"),J0.http=await Y7(K,T.functionNames.http),J0.cli=await Y7(K,T.functionNames.cli),T.queueNames.length)J0.queue=await Y7(K,T.functionNames.queue)}if(await lU(F,U,G,J,{sha:E,code:M,previousSha:c?.sha,previousCode:c?.code,previousFunctionEnv:c?.functionEnv,...s?{functionVersions:J0,previousFunctionVersions:c?.functionVersions}:{},functionEnv:r,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:b,timestamp:new Date().toISOString()}),!Y.skipDeployHooks&&Q.deploy?.length){n("Running deploy hooks");for(let a of Q.deploy){X(` deploy: ${a}`);let e=await K.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:a},LogType:"Tail"});if(e.FunctionError)throw w("Deploy hook failed — the new build is ALREADY LIVE."),X(` Roll back with: cloud serverless:rollback --env ${J}`),Error(`Deploy hook failed (${a}): ${e.Payload}`)}}let t=I.HttpApiEndpoint;if(!Y.skipHealthCheck&&t){n("Health check");try{let a=await fetch(t,{method:"GET"});X(`GET ${t} → ${a.status}`)}catch(a){v(`Health check could not reach ${t}: ${a.message}`)}}k1(["Serverless deploy complete","",t?`URL: ${t}`:"",`Stack: ${z}`,`Build: ${E.slice(0,12)}`].filter(Boolean).join(`
|
|
7084
|
-
`),"green")}async function kZ($,J){let Y=i1($,J),Z=new W0(Y.region),Q=new l0(Y.region),G=await Z7(Z,Y.artifactBucket,Y.slug,J);if(!G)throw Error("No previous release to redeploy. Run a full deploy first.");R(`Redeploying ${Y.slug} (${J}) — build ${G.sha.slice(0,12)}`);for(let[W,z]of Object.entries(G.functionNames)){if(!z)continue;n(`Re-activating ${W} (${z})`),await s8(Q,z,G.functionEnv[W]??{},G.code);let U=G.functionVersions?.[W];if(U)await
|
|
7083
|
+
</Delete>`,Z=$0.createHash("md5").update(Y).digest("base64");await this.client.request({service:"s3",region:this.region,method:"POST",path:`/${$}`,queryParams:{delete:""},body:Y,headers:{"Content-Type":"application/xml","Content-MD5":Z}})}}var I0=o(()=>{Y0()});class G2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createSecret($){let J={Name:$.Name};if($.Description)J.Description=$.Description;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;if($.Tags&&$.Tags.length>0)J.Tags=$.Tags;if($.AddReplicaRegions&&$.AddReplicaRegions.length>0)J.AddReplicaRegions=$.AddReplicaRegions;if($.ForceOverwriteReplicaSecret!==void 0)J.ForceOverwriteReplicaSecret=$.ForceOverwriteReplicaSecret;J.ClientRequestToken=$.ClientRequestToken||crypto.randomUUID();let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,ReplicationStatus:Y.ReplicationStatus}}async updateSecret($){let J={SecretId:$.SecretId};if($.Description)J.Description=$.Description;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId}}async putSecretValue($){let J={SecretId:$.SecretId};if($.SecretBinary)J.SecretBinary=$.SecretBinary;if($.SecretString)J.SecretString=$.SecretString;if($.VersionStages&&$.VersionStages.length>0)J.VersionStages=$.VersionStages;if($.ClientRequestToken)J.ClientRequestToken=$.ClientRequestToken;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,VersionStages:Y.VersionStages}}async getSecretValue($){let J={SecretId:$.SecretId};if($.VersionId)J.VersionId=$.VersionId;if($.VersionStage)J.VersionStage=$.VersionStage;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId,SecretBinary:Y.SecretBinary,SecretString:Y.SecretString,VersionStages:Y.VersionStages,CreatedDate:Y.CreatedDate}}async describeSecret($){let J={SecretId:$},Y=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(J)});return this.parseSecret(Y)}async listSecrets($){let J={};if($?.MaxResults)J.MaxResults=$.MaxResults;if($?.NextToken)J.NextToken=$.NextToken;if($?.Filters&&$.Filters.length>0)J.Filters=$.Filters;if($?.SortOrder)J.SortOrder=$.SortOrder;let Y=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(J)});return{SecretList:Y.SecretList?.map((Z)=>this.parseSecret(Z)),NextToken:Y.NextToken}}async deleteSecret($){let J={SecretId:$.SecretId};if($.RecoveryWindowInDays!==void 0)J.RecoveryWindowInDays=$.RecoveryWindowInDays;if($.ForceDeleteWithoutRecovery!==void 0)J.ForceDeleteWithoutRecovery=$.ForceDeleteWithoutRecovery;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,DeletionDate:Y.DeletionDate}}async restoreSecret($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async rotateSecret($){let J={SecretId:$.SecretId};if($.ClientRequestToken)J.ClientRequestToken=$.ClientRequestToken;if($.RotationLambdaARN)J.RotationLambdaARN=$.RotationLambdaARN;if($.RotationRules)J.RotationRules=$.RotationRules;if($.RotateImmediately!==void 0)J.RotateImmediately=$.RotateImmediately;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,VersionId:Y.VersionId}}async cancelRotateSecret($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async getResourcePolicy($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name,ResourcePolicy:Y.ResourcePolicy}}async putResourcePolicy($){let J={SecretId:$.SecretId,ResourcePolicy:$.ResourcePolicy};if($.BlockPublicPolicy!==void 0)J.BlockPublicPolicy=$.BlockPublicPolicy;let Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async deleteResourcePolicy($){let J={SecretId:$},Y=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(J)});return{ARN:Y.ARN,Name:Y.Name}}async tagResource($){let J={SecretId:$.SecretId,Tags:$.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(J)})}async untagResource($){let J={SecretId:$.SecretId,TagKeys:$.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(J)})}async setString($,J,Y){try{let Z=await this.putSecretValue({SecretId:$,SecretString:J});return{ARN:Z.ARN,VersionId:Z.VersionId}}catch(Z){if(Z.code==="ResourceNotFoundException"){let Q=await this.createSecret({Name:$,SecretString:J,Description:Y?.description,KmsKeyId:Y?.kmsKeyId,Tags:Y?.tags});return{ARN:Q.ARN,VersionId:Q.VersionId}}throw Z}}async setJson($,J,Y){return this.setString($,JSON.stringify(J),Y)}async getString($){return(await this.getSecretValue({SecretId:$})).SecretString}async getJson($){let J=await this.getString($);if(J)return JSON.parse(J);return}async listAll(){let $=[],J;do{let Y=await this.listSecrets({NextToken:J});if(Y.SecretList)$.push(...Y.SecretList);J=Y.NextToken}while(J);return $}parseSecret($){return{ARN:$.ARN,Name:$.Name,Description:$.Description,KmsKeyId:$.KmsKeyId,RotationEnabled:$.RotationEnabled,RotationLambdaARN:$.RotationLambdaARN,RotationRules:$.RotationRules,LastRotatedDate:$.LastRotatedDate,LastChangedDate:$.LastChangedDate,LastAccessedDate:$.LastAccessedDate,DeletedDate:$.DeletedDate,NextRotationDate:$.NextRotationDate,Tags:$.Tags,SecretVersionsToStages:$.SecretVersionsToStages,CreatedDate:$.CreatedDate,PrimaryRegion:$.PrimaryRegion}}}var o6=o(()=>{Y0()});class p${client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRepository($){let J={repositoryName:$.repositoryName};if($.imageTagMutability)J.imageTagMutability=$.imageTagMutability;if($.imageScanningConfiguration)J.imageScanningConfiguration=$.imageScanningConfiguration;if($.encryptionConfiguration)J.encryptionConfiguration=$.encryptionConfiguration;if($.tags&&$.tags.length>0)J.tags=$.tags;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.CreateRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeRepositories($){let J={};if($?.repositoryNames&&$.repositoryNames.length>0)J.repositoryNames=$.repositoryNames;if($?.registryId)J.registryId=$.registryId;if($?.maxResults)J.maxResults=$.maxResults;if($?.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeRepositories","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repositories:Y.repositories?.map((Z)=>this.parseRepository(Z)),nextToken:Y.nextToken}}async getAuthorizationToken($){let J={};if($&&$.length>0)J.registryIds=$;return{authorizationData:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).authorizationData?.map((Z)=>({authorizationToken:Z.authorizationToken,expiresAt:Z.expiresAt,proxyEndpoint:Z.proxyEndpoint}))}}async deleteRepository($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DeleteRepository","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{repository:Y.repository?this.parseRepository(Y.repository):void 0}}async describeImages($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;if($.imageIds&&$.imageIds.length>0)J.imageIds=$.imageIds;if($.filter)J.filter=$.filter;if($.maxResults)J.maxResults=$.maxResults;if($.nextToken)J.nextToken=$.nextToken;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.DescribeImages","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageDetails:Y.imageDetails?.map((Z)=>this.parseImageDetail(Z)),nextToken:Y.nextToken}}async batchDeleteImage($){let J={repositoryName:$.repositoryName,imageIds:$.imageIds};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.BatchDeleteImage","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{imageIds:Y.imageIds,failures:Y.failures}}async putLifecyclePolicy($){let J={repositoryName:$.repositoryName,lifecyclePolicyText:$.lifecyclePolicyText};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.PutLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText}}async getLifecyclePolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetLifecyclePolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,lifecyclePolicyText:Y.lifecyclePolicyText,lastEvaluatedAt:Y.lastEvaluatedAt}}async setRepositoryPolicy($){let J={repositoryName:$.repositoryName,policyText:$.policyText};if($.registryId)J.registryId=$.registryId;if($.force!==void 0)J.force=$.force;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.SetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async getRepositoryPolicy($){let J={repositoryName:$.repositoryName};if($.registryId)J.registryId=$.registryId;let Y=await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{registryId:Y.registryId,repositoryName:Y.repositoryName,policyText:Y.policyText}}async tagResource($){let J={resourceArn:$.resourceArn,tags:$.tags};await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.TagResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTagsForResource($){let J={resourceArn:$};return{tags:(await this.client.request({service:"ecr",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerRegistry_V20150921.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).tags}}createLifecyclePolicyText($){return JSON.stringify({rules:$.map((J)=>({rulePriority:J.rulePriority,description:J.description,selection:J.selection,action:J.action}))})}async getDockerLoginCommand(){let $=await this.getAuthorizationToken();if(!$.authorizationData?.[0])throw Error("Failed to get authorization token");let J=$.authorizationData[0],Y=J.authorizationToken||"",Z=J.proxyEndpoint||"";return`echo "${Buffer.from(Y,"base64").toString("utf8").split(":")[1]}" | docker login --username AWS --password-stdin ${Z}`}getRegistryUri($){return`${$}.dkr.ecr.${this.region}.amazonaws.com`}parseRepository($){return{repositoryArn:$.repositoryArn,registryId:$.registryId,repositoryName:$.repositoryName,repositoryUri:$.repositoryUri,createdAt:$.createdAt,imageTagMutability:$.imageTagMutability,imageScanningConfiguration:$.imageScanningConfiguration,encryptionConfiguration:$.encryptionConfiguration}}parseImageDetail($){return{registryId:$.registryId,repositoryName:$.repositoryName,imageDigest:$.imageDigest,imageTags:$.imageTags,imageSizeInBytes:$.imageSizeInBytes,imagePushedAt:$.imagePushedAt,imageScanStatus:$.imageScanStatus,imageScanFindingsSummary:$.imageScanFindingsSummary}}}var e6=o(()=>{Y0()});var dU={};h0(dU,{buildAndPushServerlessImage:()=>PZ});import{execFileSync as gU}from"node:child_process";import{mkdirSync as SZ,mkdtempSync as _M,rmSync as jM,writeFileSync as $7}from"node:fs";import{tmpdir as LM}from"node:os";import{dirname as EM,join as p2}from"node:path";function uU($,J){for(let Y of J){let Z=p2($,Y.name);SZ(EM(Z),{recursive:!0}),$7(Z,Y.data,Y.mode?{mode:Y.mode}:void 0)}}async function PZ($){let{app:J,projectRoot:Y,region:Z,repository:Q}=$,G=J.architecture??"x86_64",W=G==="arm64"?"linux/arm64":"linux/amd64",z=J.kind==="php",U=$.onStep??(()=>{}),H=_M(p2(LM(),"tscloud-img-"));try{let F=p2(H,"app");SZ(F,{recursive:!0});let B,K;if(z){t6({projectRoot:Y,app:J,skipBuild:$.skipBuild,onStep:U}),U("staging application tree");let T=s6(Y);uU(F,T),uU(p2(H,"runtime"),v8().map((S)=>({name:S.path,data:S.contents,mode:S.mode})));let D=J.handlers?.http??"public/index.php";B={http:D,queue:J.handlers?.queue??D,cli:J.handlers?.cli??D},K=r6(T.map((S)=>`${S.name}:${S.data.length}`).join("|"))}else{U("bundling application");let T=await c8({projectRoot:Y,app:J,skipBuild:$.skipBuild,onStep:U});$7(p2(F,"index.mjs"),T.bundle),B=T.handlers,K=T.sha256}let O=K.slice(0,16);$7(p2(H,"Dockerfile"),UZ({kind:J.kind??"node",phpVersion:J.phpVersion,architecture:G}));let V=new p$(Z),A;try{A=(await V.describeRepositories({repositoryNames:[Q]})).repositories?.[0]?.repositoryUri??""}catch{A=""}if(!A)U(`creating ECR repository ${Q}`),A=(await V.createRepository({repositoryName:Q,imageScanningConfiguration:{scanOnPush:!0}})).repository?.repositoryUri??"";if(!A)throw Error(`could not resolve ECR repository URI for ${Q}`);let _=`${A}:${O}`;U("docker build"),gU("docker",["build","--platform",W,"--provenance=false","--sbom=false","-t",_,H],{stdio:"inherit"}),U("ecr auth + push");let E=(await V.getAuthorizationToken()).authorizationData?.[0];if(!E?.authorizationToken||!E.proxyEndpoint)throw Error("failed to get an ECR authorization token");let j=E.proxyEndpoint.replace(/^https?:\/\//,""),q=p2(H,".docker");return SZ(q,{recursive:!0}),$7(p2(q,"config.json"),JSON.stringify({auths:{[j]:{auth:E.authorizationToken}}})),gU("docker",["push",_],{stdio:"inherit",env:{...process.env,DOCKER_CONFIG:q}}),X(`Image: ${_}`),{imageUri:_,tag:O,handlers:B}}finally{jM(H,{recursive:!0,force:!0})}}var CZ=o(async()=>{e6();z0();await n0()});var J7={};h0(J7,{RDSClient:()=>xZ});class xZ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeDBInstances($){let J={Action:"DescribeDBInstances",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((W,z)=>{J[`Filters.Filter.${z+1}.Name`]=W.Name,W.Values.forEach((U,H)=>{J[`Filters.Filter.${z+1}.Values.Value.${H+1}`]=U})});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBInstancesResult||Z,G=Q.DBInstances?.DBInstance||[];if(!Array.isArray(G))G=G?[G]:[];return{DBInstances:G,Marker:Q.Marker}}async describeDBInstance($){return(await this.describeDBInstances({DBInstanceIdentifier:$})).DBInstances?.[0]}async describeDBClusters($){let J={Action:"DescribeDBClusters",Version:"2014-10-31"};if($?.DBClusterIdentifier)J.DBClusterIdentifier=$.DBClusterIdentifier;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;if($?.Filters)$.Filters.forEach((W,z)=>{J[`Filters.Filter.${z+1}.Name`]=W.Name,W.Values.forEach((U,H)=>{J[`Filters.Filter.${z+1}.Values.Value.${H+1}`]=U})});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBClustersResult||Z,G=Q.DBClusters?.DBCluster||[];if(!Array.isArray(G))G=G?[G]:[];return{DBClusters:G,Marker:Q.Marker}}async describeDBSnapshots($){let J={Action:"DescribeDBSnapshots",Version:"2014-10-31"};if($?.DBInstanceIdentifier)J.DBInstanceIdentifier=$.DBInstanceIdentifier;if($?.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;if($?.SnapshotType)J.SnapshotType=$.SnapshotType;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBSnapshotsResult||Z,G=Q.DBSnapshots?.DBSnapshot||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSnapshots:G,Marker:Q.Marker}}async describeDBSubnetGroups($){let J={Action:"DescribeDBSubnetGroups",Version:"2014-10-31"};if($?.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($?.MaxRecords)J.MaxRecords=$.MaxRecords;if($?.Marker)J.Marker=$.Marker;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y}),Q=Z.DescribeDBSubnetGroupsResult||Z,G=Q.DBSubnetGroups?.DBSubnetGroup||[];if(!Array.isArray(G))G=G?[G]:[];return{DBSubnetGroups:G,Marker:Q.Marker}}async createDBInstance($){let J={Action:"CreateDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBInstanceClass:$.DBInstanceClass,Engine:$.Engine};if($.DBClusterIdentifier)J.DBClusterIdentifier=$.DBClusterIdentifier;if($.MasterUsername)J.MasterUsername=$.MasterUsername;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.DBName)J.DBName=$.DBName;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.LicenseModel)J.LicenseModel=$.LicenseModel;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.StorageType)J.StorageType=$.StorageType;if($.StorageEncrypted!==void 0)J.StorageEncrypted=$.StorageEncrypted;if($.KmsKeyId)J.KmsKeyId=$.KmsKeyId;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.CreateDBInstanceResult||Z).DBInstance}}async deleteDBInstance($){let J={Action:"DeleteDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.SkipFinalSnapshot!==void 0)J.SkipFinalSnapshot=$.SkipFinalSnapshot;if($.FinalDBSnapshotIdentifier)J.FinalDBSnapshotIdentifier=$.FinalDBSnapshotIdentifier;if($.DeleteAutomatedBackups!==void 0)J.DeleteAutomatedBackups=$.DeleteAutomatedBackups;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.DeleteDBInstanceResult||Z).DBInstance}}async modifyDBInstance($){let J={Action:"ModifyDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.AllocatedStorage)J.AllocatedStorage=$.AllocatedStorage;if($.MasterUserPassword)J.MasterUserPassword=$.MasterUserPassword;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.PreferredBackupWindow)J.PreferredBackupWindow=$.PreferredBackupWindow;if($.PreferredMaintenanceWindow)J.PreferredMaintenanceWindow=$.PreferredMaintenanceWindow;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.EngineVersion)J.EngineVersion=$.EngineVersion;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.ApplyImmediately!==void 0)J.ApplyImmediately=$.ApplyImmediately;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.ModifyDBInstanceResult||Z).DBInstance}}async modifyDBCluster($){let J={Action:"ModifyDBCluster",Version:"2014-10-31",DBClusterIdentifier:$.DBClusterIdentifier};if($.ServerlessV2ScalingConfiguration)J["ServerlessV2ScalingConfiguration.MinCapacity"]=$.ServerlessV2ScalingConfiguration.MinCapacity,J["ServerlessV2ScalingConfiguration.MaxCapacity"]=$.ServerlessV2ScalingConfiguration.MaxCapacity;if($.BackupRetentionPeriod!==void 0)J.BackupRetentionPeriod=$.BackupRetentionPeriod;if($.ApplyImmediately!==void 0)J.ApplyImmediately=$.ApplyImmediately;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBCluster:(Z.ModifyDBClusterResult||Z).DBCluster}}async restoreDBClusterToPointInTime($){let J={Action:"RestoreDBClusterToPointInTime",Version:"2014-10-31",DBClusterIdentifier:$.DBClusterIdentifier,SourceDBClusterIdentifier:$.SourceDBClusterIdentifier};if($.RestoreToTime)J.RestoreToTime=$.RestoreToTime.toISOString();if($.UseLatestRestorableTime)J.UseLatestRestorableTime=!0;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBCluster:(Z.RestoreDBClusterToPointInTimeResult||Z).DBCluster}}async startDBInstance($){let Y=new URLSearchParams(g0({Action:"StartDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$})).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.StartDBInstanceResult||Z).DBInstance}}async stopDBInstance($){let J={Action:"StopDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.DBSnapshotIdentifier)J.DBSnapshotIdentifier=$.DBSnapshotIdentifier;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.StopDBInstanceResult||Z).DBInstance}}async rebootDBInstance($){let J={Action:"RebootDBInstance",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier};if($.ForceFailover!==void 0)J.ForceFailover=$.ForceFailover;let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.RebootDBInstanceResult||Z).DBInstance}}async createDBSnapshot($){let J={Action:"CreateDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Z.CreateDBSnapshotResult||Z).DBSnapshot}}async deleteDBSnapshot($){let Y=new URLSearchParams(g0({Action:"DeleteDBSnapshot",Version:"2014-10-31",DBSnapshotIdentifier:$})).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBSnapshot:(Z.DeleteDBSnapshotResult||Z).DBSnapshot}}async restoreDBInstanceFromDBSnapshot($){let J={Action:"RestoreDBInstanceFromDBSnapshot",Version:"2014-10-31",DBInstanceIdentifier:$.DBInstanceIdentifier,DBSnapshotIdentifier:$.DBSnapshotIdentifier};if($.DBInstanceClass)J.DBInstanceClass=$.DBInstanceClass;if($.Port)J.Port=$.Port;if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.DBSubnetGroupName)J.DBSubnetGroupName=$.DBSubnetGroupName;if($.MultiAZ!==void 0)J.MultiAZ=$.MultiAZ;if($.PubliclyAccessible!==void 0)J.PubliclyAccessible=$.PubliclyAccessible;if($.AutoMinorVersionUpgrade!==void 0)J.AutoMinorVersionUpgrade=$.AutoMinorVersionUpgrade;if($.StorageType)J.StorageType=$.StorageType;if($.DeletionProtection!==void 0)J.DeletionProtection=$.DeletionProtection;if($.VpcSecurityGroupIds)$.VpcSecurityGroupIds.forEach((G,W)=>{J[`VpcSecurityGroupIds.VpcSecurityGroupId.${W+1}`]=G});if($.Tags)$.Tags.forEach((G,W)=>{J[`Tags.Tag.${W+1}.Key`]=G.Key,J[`Tags.Tag.${W+1}.Value`]=G.Value});let Y=new URLSearchParams(g0(J)).toString(),Z=await this.client.request({service:"rds",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y});return{DBInstance:(Z.RestoreDBInstanceFromDBSnapshotResult||Z).DBInstance}}async waitForDBInstanceAvailable($,J=60,Y=30000){for(let Z=0;Z<J;Z++){let Q=await this.describeDBInstance($);if(Q?.DBInstanceStatus==="available")return Q;if(["deleted","failed","incompatible-restore","incompatible-parameters"].includes(Q?.DBInstanceStatus||""))throw Error(`DB instance ${$} is in terminal state: ${Q?.DBInstanceStatus}`);await new Promise((G)=>setTimeout(G,Y))}throw Error(`Timeout waiting for DB instance ${$} to become available`)}async waitForDBInstanceDeleted($,J=60,Y=30000){for(let Z=0;Z<J;Z++)try{let Q=await this.describeDBInstance($);if(Q?.DBInstanceStatus==="deleting"){await new Promise((G)=>setTimeout(G,Y));continue}throw Error(`DB instance ${$} is in state: ${Q?.DBInstanceStatus}`)}catch(Q){if(Q.code==="DBInstanceNotFound"||Q.code==="DBInstanceNotFoundFault")return;throw Q}throw Error(`Timeout waiting for DB instance ${$} to be deleted`)}}var t8=o(()=>{Y0()});var g1={};h0(g1,{setMaintenance:()=>bZ,serverlessInfo:()=>yZ,scaleServerlessDatabase:()=>IM,runRemoteCommand:()=>n$,runDbQuery:()=>xM,runAndRecordCommand:()=>PM,rollbackServerlessApp:()=>hZ,restoreServerlessDatabase:()=>kM,resolveServerlessFunctions:()=>q2,resolveSecrets:()=>pU,redeployServerlessApp:()=>kZ,listCommandHistory:()=>aU,infraEnvFromOutputs:()=>Q7,getCommandRecord:()=>CM,deployServerlessApp:()=>IZ,buildFunctionEnv:()=>r$,assertEnvWithinLimit:()=>G7});import{existsSync as MM,readdirSync as qM,readFileSync as TM,statSync as wM}from"node:fs";import{join as cU,relative as DM}from"node:path";function i1($,J){let Y=$.environments?.[J]?.app;if(!Y)throw Error(`No serverless app configured for environment '${J}'. Add environments.${J}.app to your config.`);let Z=$.project.slug,Q=$.environments?.[J]?.region||$.project.region||"us-east-1";return{app:Y,slug:Z,region:Q,stackName:z$($,J),artifactBucket:xJ(Z,J),assetsBucket:d6(Z,J)}}function q2($,J){let Y=i1($,J),Z=`${Y.slug}-${J}`;return{region:Y.region,slug:Y.slug,stackName:Y.stackName,functions:{http:`${Z}-http`,queue:`${Z}-queue`,cli:`${Z}-cli`}}}async function X$($,J=8){let Y;for(let Z=0;Z<J;Z++)try{return await $()}catch(Q){let G=Q?.code||Q?.name||"",W=String(Q?.message||"");if(G==="ResourceConflictException"||/update is in progress|currently in the following state/i.test(W)){Y=Q,await new Promise((z)=>setTimeout(z,3000));continue}throw Q}throw Y}async function Z7($,J,Y,Z){try{return await $.getObjectJson(J,mU(Y,Z))}catch{return null}}async function lU($,J,Y,Z,Q){await $.putObjectJson(J,mU(Y,Z),Q)}async function pU($,J){if(!$.secrets)return{};let Y=new G2(J),Z={},Q=Array.isArray($.secrets)?$.secrets.map((G)=>({envName:G.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),secretId:G})):Object.entries($.secrets).map(([G,W])=>({envName:G,secretId:W}));if(Array.isArray($.secrets)){let G=new Map;for(let{envName:z,secretId:U}of Q)G.set(z,[...G.get(z)??[],U]);let W=[...G.entries()].filter(([,z])=>z.length>1);if(W.length){let z=W.map(([U,H])=>`${U} ← ${H.join(", ")}`).join("; ");throw Error(`serverless secrets: multiple secrets map to the same env var (${z}). Use the map form { ENV_NAME: 'secret/id' } to disambiguate.`)}}for(let{envName:G,secretId:W}of Q){let U=(await Y.getSecretValue({SecretId:W})).SecretString??"";try{let H=JSON.parse(U);if(H&&typeof H==="object"&&!Array.isArray(H)){for(let[F,B]of Object.entries(H))Z[F]=String(B);continue}}catch{}Z[G]=U}return Z}function Q7($,J){let Y={},Z=J.DbProxyEndpoint||J.DbEndpoint;if(Z)Y.DB_CONNECTION="mysql",Y.DB_HOST=Z,Y.DB_PORT="3306",Y.DB_DATABASE=Y.DB_DATABASE||"app";if(J.CacheEndpoint){if(Y.REDIS_HOST=J.CacheEndpoint,Y.REDIS_PORT="6379",$.cache?.driver==="elasticache")Y.CACHE_STORE="redis",Y.CACHE_DRIVER="redis",Y.SESSION_DRIVER="redis"}return Y}function r$($,J,Y,Z,Q,G,W,z={}){let U=$.kind==="php"?FZ({cacheDriver:$.cache?.driver==="elasticache"?"redis":"dynamodb"}):{};return{TSCLOUD_LAMBDA_MODE:Z,TSCLOUD_ENV:Y,MAINTENANCE_MODE:"0",...$.octane?{TSCLOUD_OCTANE:"1"}:{},...$.serveAssets?{TSCLOUD_SERVE_ASSETS:"1"}:{},...$.redirectRobotsTxt===!1?{TSCLOUD_REDIRECT_ROBOTS_TXT:"0"}:{},...U,...z,...J.app.cache?.driver!=="elasticache"?{TSCLOUD_CACHE_TABLE:`${J.slug}-${Y}-cache`}:{},...W?{TSCLOUD_QUEUE:W,SQS_QUEUE:W}:{},...G?{ASSET_URL:G}:{},...$.env??{},...Q}}function RM($){let J=$.slice($.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"}[J]??"application/octet-stream"}function*rU($){for(let J of qM($)){let Y=cU($,J);if(wM(Y).isDirectory())yield*rU(Y);else yield Y}}async function NM($,J,Y,Z,Q=!1){let G=0;for(let W of rU(Y)){let z=DM(Y,W).replace(/\\/g,"/");if(!Q&&z.split("/").some((U)=>U.startsWith(".")))continue;await $.putObject({bucket:J,key:`${Z}/${z}`,body:TM(W),contentType:RM(W),cacheControl:"public, max-age=31536000, immutable"}),G++}return G}function G7($,J){let Y=Object.entries(J).reduce((Z,[Q,G])=>Z+Buffer.byteLength(`${Q}=${G}`,"utf8"),0);if(Y>4096){let Z=Object.entries(J).map(([Q,G])=>[Q,Buffer.byteLength(`${Q}=${G}`,"utf8")]).sort((Q,G)=>G[1]-Q[1]).slice(0,5).map(([Q,G])=>`${Q} (${G}B)`).join(", ");throw Error(`${$}: environment variables total ${Y}B, over AWS's 4096B limit (${Y-4096}B too large). Largest: ${Z}. Move large/secret values out of env — store them in Secrets Manager and fetch at cold start.`)}}async function s8($,J,Y,Z){G7(J,Y),await X$(()=>$.updateFunctionConfiguration({FunctionName:J,Environment:{Variables:Y}})),await $.waitForFunctionActive(J,120);let Q=Z.kind==="image"?{FunctionName:J,ImageUri:Z.imageUri}:{FunctionName:J,S3Bucket:Z.bucket,S3Key:Z.key};await X$(()=>$.updateFunctionCode(Q)),await $.waitForFunctionActive(J,120)}async function Y7($,J){let Z=(await X$(()=>$.publishVersion({FunctionName:J}))).Version;if(!Z)throw Error(`publishVersion returned no version for ${J}`);return await X$(()=>$.updateAlias({FunctionName:J,Name:"live",FunctionVersion:Z})),Z}async function IZ($,J,Y={}){let Z=i1($,J),{app:Q,slug:G,region:W,stackName:z,artifactBucket:U}=Z,H=Y.projectRoot??process.cwd();R(`Deploying serverless app: ${G} (${J})`),X(`Stack: ${z}`),X(`Region: ${W}`);let F=new W0(W),B=new K0(W),K=new l0(W),O=Q.kind==="php",V=Q.packaging==="image",A=n6(Q),_,M,E,j,q=[];if(V&&A.usesLayer&&A.layerKind!=="php")throw Error(`packaging: 'image' currently supports PHP and managed Node runtimes. ${A.kind}${A.kind==="node"?` ${A.version}`:""} uses a custom runtime — `+"use the default zip packaging (the runtime layer is built + attached automatically).");if(V){n("Building + pushing container image");let{buildAndPushServerlessImage:a}=await CZ().then(() => dU),e=await a({app:Q,projectRoot:H,region:W,repository:`${G}-${J}`,skipBuild:Y.skipBuild,onStep:(L0)=>X(` ${L0}`)});_=e.handlers,M={kind:"image",imageUri:e.imageUri},E=e.tag,q.push({ParameterKey:"ImageUri",ParameterValue:e.imageUri})}else{n("Packaging application");let a=O?BZ({projectRoot:H,app:Q,skipBuild:Y.skipBuild,onStep:(_0)=>X(` ${_0}`)}):await c8({projectRoot:H,app:Q,skipBuild:Y.skipBuild,onStep:(_0)=>X(` ${_0}`)}),e=QZ(G,J,a.sha256);if(X(`Artifact: ${a.sha256.slice(0,12)} (${(a.zip.length/1024).toFixed(0)} KB)`),_=a.handlers,E=a.sha256,A.usesLayer){let _0=A.layerEnvVar?process.env[A.layerEnvVar]:void 0;if(j=Q.layers??(_0?[_0]:void 0),!j?.length){let O0=A.layerKind==="php"?"serverless:build-php-layer":A.layerKind==="bun"?"serverless:build-bun-layer":"serverless:build-node-layer";throw Error(`${A.kind} apps on provided.al2023 need a runtime layer. Set environments.<env>.app.layers or the ${A.layerEnvVar} env var (build one with \`cloud ${O0}\`)${A.kind==="node"?", or use a managed Node version (18/20/22)":""}.`)}}if(!await F.bucketExists(U))n(`Creating artifact bucket ${U}`),await F.createBucket(U);if(await F.headObject(U,e).then((_0)=>_0!==null).catch(()=>!1))X("Artifact already uploaded — reusing");else n("Uploading artifact"),await F.putObject({bucket:U,key:e,body:a.zip,contentType:"application/zip"});M={kind:"zip",bucket:U,key:e},q.push({ParameterKey:"ArtifactBucket",ParameterValue:U},{ParameterKey:"ArtifactKey",ParameterValue:e})}let T=WZ({config:$,environment:J,app:Q,handlers:_,runtimeLayers:j}),D=JSON.stringify(T.template),S=["CAPABILITY_NAMED_IAM"],P=await B.describeStacks({stackName:z}).then((a)=>a.Stacks[0]?.StackStatus).catch(()=>{return}),C=P!==void 0;if(P&&/DELETE_IN_PROGRESS/.test(P))n("Waiting for an in-progress stack delete to finish"),await B.waitForStack(z,"stack-delete-complete").catch(()=>{}),C=!1;else if(P&&/(?:ROLLBACK_COMPLETE|REVIEW_IN_PROGRESS|CREATE_FAILED)/.test(P))n(`Deleting unusable stack (status ${P}) before recreate`),await B.deleteStack(z),await B.waitForStack(z,"stack-delete-complete").catch(()=>{}),C=!1;n(C?"Updating infrastructure stack":"Creating infrastructure stack");try{if(C)await B.updateStack({stackName:z,templateBody:D,parameters:q,capabilities:S}),await B.waitForStack(z,"stack-update-complete");else await B.createStack({stackName:z,templateBody:D,parameters:q,capabilities:S,onFailure:"DELETE"}),await B.waitForStack(z,"stack-create-complete")}catch(a){if(/No updates are to be performed/i.test(String(a?.message)))X("No infrastructure changes");else throw a}let I=await B.getStackOutputs(z).catch(()=>({})),b;if(Q.assets){let a=cU(H,Q.assets);if(MM(a)){let e=Q.assetDomain||I.AssetsCdnDomain;b=e?`https://${e}/${E}`:void 0,n(`Syncing assets from ${Q.assets}`);let L0=await NM(F,Z.assetsBucket,a,E,Q.dotFilesAsAssets);X(`Uploaded ${L0} asset(s)${b?` → ${b}`:""}`)}else v(`Assets directory not found: ${a}`)}n("Resolving secrets");let y=await pU(Q,W);if(Q.database?.connection==="aurora-serverless")try{let e=await new G2(W).getSecretValue({SecretId:`${G}/${J}/db`}),L0=JSON.parse(e.SecretString??"{}");if(L0.username)y.DB_USERNAME=L0.username;if(L0.password)y.DB_PASSWORD=L0.password}catch(a){v(`Could not resolve Aurora DB credentials: ${a.message}`)}if(!await F.bucketExists(U))await F.createBucket(U);let c=await Z7(F,U,G,J),r={},d=T.queueNames[0],u=Q7(Q,I);if(n("Activating functions"),r.http=r$(Q,Z,J,"http",y,b,d,u),await s8(K,T.functionNames.http,r.http,M),r.cli=r$(Q,Z,J,"cli",y,b,d,u),await s8(K,T.functionNames.cli,r.cli,M),T.queueNames.length)r.queue=r$(Q,Z,J,"queue",y,b,d,u),await s8(K,T.functionNames.queue,r.queue,M);let s=(Q.provisionedConcurrency??0)>0,J0={};if(s){if(n("Publishing versions + flipping live alias"),J0.http=await Y7(K,T.functionNames.http),J0.cli=await Y7(K,T.functionNames.cli),T.queueNames.length)J0.queue=await Y7(K,T.functionNames.queue)}if(await lU(F,U,G,J,{sha:E,code:M,previousSha:c?.sha,previousCode:c?.code,previousFunctionEnv:c?.functionEnv,...s?{functionVersions:J0,previousFunctionVersions:c?.functionVersions}:{},functionEnv:r,functionNames:{http:T.functionNames.http,cli:T.functionNames.cli,...T.queueNames.length?{queue:T.functionNames.queue}:{}},assetUrl:b,timestamp:new Date().toISOString()}),!Y.skipDeployHooks&&Q.deploy?.length){n("Running deploy hooks");for(let a of Q.deploy){X(` deploy: ${a}`);let e=await K.invoke({FunctionName:T.functionNames.cli,InvocationType:"RequestResponse",Payload:{command:a},LogType:"Tail"});if(e.FunctionError)throw w("Deploy hook failed — the new build is ALREADY LIVE."),X(` Roll back with: cloud serverless:rollback --env ${J}`),Error(`Deploy hook failed (${a}): ${e.Payload}`)}}let t=I.HttpApiEndpoint;if(!Y.skipHealthCheck&&t){n("Health check");try{let a=await fetch(t,{method:"GET"});X(`GET ${t} → ${a.status}`)}catch(a){v(`Health check could not reach ${t}: ${a.message}`)}}k1(["Serverless deploy complete","",t?`URL: ${t}`:"",`Stack: ${z}`,`Build: ${E.slice(0,12)}`].filter(Boolean).join(`
|
|
7084
|
+
`),"green")}async function kZ($,J){let Y=i1($,J),Z=new W0(Y.region),Q=new l0(Y.region),G=await Z7(Z,Y.artifactBucket,Y.slug,J);if(!G)throw Error("No previous release to redeploy. Run a full deploy first.");R(`Redeploying ${Y.slug} (${J}) — build ${G.sha.slice(0,12)}`);for(let[W,z]of Object.entries(G.functionNames)){if(!z)continue;n(`Re-activating ${W} (${z})`),await s8(Q,z,G.functionEnv[W]??{},G.code);let U=G.functionVersions?.[W];if(U)await X$(()=>Q.updateAlias({FunctionName:z,Name:"live",FunctionVersion:U}))}h("Redeploy complete")}async function hZ($,J){let Y=i1($,J),Z=new W0(Y.region),Q=new l0(Y.region),G=await Z7(Z,Y.artifactBucket,Y.slug,J);if(!G?.previousCode)throw Error("No previous release to roll back to.");R(`Rolling back ${Y.slug} (${J}) → ${G.previousSha?.slice(0,12)}`);for(let[W,z]of Object.entries(G.functionNames)){if(!z)continue;n(`Restoring ${W} (${z})`);let U=G.previousFunctionEnv?.[W]??G.functionEnv[W]??{};await s8(Q,z,U,G.previousCode);let H=G.previousFunctionVersions?.[W];if(H)await X$(()=>Q.updateAlias({FunctionName:z,Name:"live",FunctionVersion:H}))}await lU(Z,Y.artifactBucket,Y.slug,J,{...G,sha:G.previousSha??G.sha,code:G.previousCode,functionEnv:G.previousFunctionEnv??G.functionEnv,functionVersions:G.previousFunctionVersions??G.functionVersions,previousSha:void 0,previousCode:void 0,previousFunctionEnv:void 0,previousFunctionVersions:void 0,timestamp:new Date().toISOString()}),h("Rollback complete")}async function bZ($,J,Y,Z){let Q=i1($,J),G=new l0(Q.region),W=`${Q.slug}-${J}-http`,U={...(await G.getFunction(W)).Configuration?.Environment?.Variables??{}};if(U.MAINTENANCE_MODE=Y?"1":"0",Y&&Z)U.MAINTENANCE_BYPASS_SECRET=Z;if(!Y)delete U.MAINTENANCE_BYPASS_SECRET;if(await X$(()=>G.updateFunctionConfiguration({FunctionName:W,Environment:{Variables:U}})),(Q.app.provisionedConcurrency??0)>0)await G.waitForFunctionActive(W,120),await Y7(G,W);h(Y?"Application is now in maintenance mode (503)":"Application is live")}async function n$($,J,Y){let Z=i1($,J),Q=new l0(Z.region),G=`${Z.slug}-${J}-cli`,W=await Q.invoke({FunctionName:G,InvocationType:"RequestResponse",Payload:{command:Y},LogType:"Tail"});if(W.FunctionError)throw Error(`Command failed: ${W.Payload}`);return W.Payload??""}async function iU($,J,Y,Z){try{return(await $.getObjectJson(J,nU(Y,Z)))?.records??[]}catch{return[]}}async function PM($,J,Y){let Z=i1($,J),Q=new l0(Z.region),G=`${Z.slug}-${J}-cli`,W=await Q.invoke({FunctionName:G,InvocationType:"RequestResponse",Payload:{command:Y},LogType:"Tail"}),z=W.Payload??"",U=W.FunctionError?"error":"ok",H=-1;try{let F=new W0(Z.region);if(await F.bucketExists(Z.artifactBucket)){let B=await iU(F,Z.artifactBucket,Z.slug,J);H=B.reduce((K,O)=>Math.max(K,O.id),0)+1,B.push({id:H,command:Y,timestamp:new Date().toISOString(),status:U,output:z.slice(0,4000)}),await F.putObjectJson(Z.artifactBucket,nU(Z.slug,J),{records:B.slice(-SM)})}}catch{}if(W.FunctionError)throw Error(`Command failed${H>0?` (#${H})`:""}: ${z}`);return{id:H,status:U,output:z}}async function aU($,J){let Y=i1($,J),Z=new W0(Y.region);return iU(Z,Y.artifactBucket,Y.slug,J)}async function CM($,J,Y){let Z=await aU($,J);if(!Z.length)return;return Y==null?Z[Z.length-1]:Z.find((Q)=>Q.id===Y)}async function xM($,J,Y){let Z=Buffer.from(Y,"utf-8").toString("base64");return n$($,J,`tscloud:db-query --sql-base64=${Z}`)}async function yZ($,J){let Y=i1($,J),Z=new K0(Y.region),Q=new l0(Y.region),G=new W0(Y.region),W="not deployed",z={};try{let{Stacks:V}=await Z.describeStacks({stackName:Y.stackName});W=V?.[0]?.StackStatus??W;for(let A of V?.[0]?.Outputs??[])if(A.OutputKey)z[A.OutputKey]=A.OutputValue??""}catch{}let U=GZ(Y.app,Y.slug,J),H=Y.app.provisionedConcurrency??0,F=["http","cli",...U.length?["queue"]:[]],B=`${Y.slug}-${J}`,K=[];for(let V of F){let A=`${B}-${V}`,_={mode:V,name:A,version:"$LATEST"};if(H>0){let M=await Q.getAlias(A,"live").catch(()=>null);if(M?.FunctionVersion){_.version=M.FunctionVersion;let E=await Q.getProvisionedConcurrencyConfig(A,"live").catch(()=>null);if(E)_.provisioned={status:E.Status??"-",allocated:E.AllocatedProvisionedConcurrentExecutions??0,requested:E.RequestedProvisionedConcurrentExecutions??0}}}K.push(_)}let O=await Z7(G,Y.artifactBucket,Y.slug,J).catch(()=>null);return{slug:Y.slug,environment:J,region:Y.region,stackStatus:W,endpoint:z.HttpApiEndpoint,assetUrl:O?.assetUrl,scheduler:Y.app.scheduler??"on",queues:U,provisionedConcurrency:H,functions:K,lastRelease:O?{sha:O.sha,timestamp:O.timestamp}:void 0}}function tU($,J){return`${$}-${J}-db`}async function IM($,J,Y,Z){let Q=i1($,J);if(Q.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");let{RDSClient:G}=await Promise.resolve().then(() => (t8(),J7)),W=new G(Q.region),z=tU(Q.slug,J);n(`Scaling ${z} → ${Y}–${Z} ACUs`),await W.modifyDBCluster({DBClusterIdentifier:z,ServerlessV2ScalingConfiguration:{MinCapacity:Y,MaxCapacity:Z},ApplyImmediately:!0}),h(`Scaling applied to ${z} (takes effect shortly).`)}async function kM($,J,Y){let Z=i1($,J);if(Z.app.database?.connection!=="aurora-serverless")throw Error("No Aurora Serverless v2 database is configured for this environment.");if(!Y.toTime&&!Y.latest)throw Error("Specify a restore point: --to <ISO timestamp> or --latest.");let{RDSClient:Q}=await Promise.resolve().then(() => (t8(),J7)),G=new Q(Z.region),W=tU(Z.slug,J),z=Y.latest?"latest":Y.toTime.toISOString().replace(/[^0-9]/g,"").slice(0,14),U=Y.target??`${W}-restore-${z}`;n(`Restoring ${W} → new cluster ${U} (${Y.latest?"latest restorable time":Y.toTime.toISOString()})`),await G.restoreDBClusterToPointInTime({DBClusterIdentifier:U,SourceDBClusterIdentifier:W,RestoreToTime:Y.toTime,UseLatestRestorableTime:Y.latest}),n("Waiting for the restored cluster to be ready");for(let H=0;H<120;H++){let{DBClusters:F}=await G.describeDBClusters({DBClusterIdentifier:U}),B=F?.[0]?.Status;if(B&&B!=="creating")break;await new Promise((K)=>setTimeout(K,15000))}return n("Adding a writer instance"),await G.createDBInstance({DBInstanceIdentifier:`${U}-1`,DBClusterIdentifier:U,Engine:"aurora-mysql",DBInstanceClass:"db.serverless"}),h(`Restore complete → cluster ${U} with writer ${U}-1. Point an env's database at it once available.`),U}var mU=($,J)=>`releases/${$}/${J}/current.json`,nU=($,J)=>`commands/${$}/${J}/history.json`,SM=50;var Q1=o(async()=>{L1();n1();I0();o6();z0();await n0()});import{createHash as bM}from"node:crypto";import{existsSync as oU,mkdirSync as yM,readdirSync as vM,readFileSync as fM,rmSync as gM,writeFileSync as uM}from"node:fs";import{homedir as dM}from"node:os";import{join as i$}from"node:path";function dZ(){let $=process.env.XDG_CACHE_HOME;return i$($&&$.trim()?$:i$(dM(),".cache"),"ts-cloud","cost-explorer")}function z7($){return i$(dZ(),$??"__default__")}function JH($){let J={s:$.start,e:$.end,g:$.granularity,m:[...$.metrics].sort(),gb:[...$.groupBy].map((Y)=>`${Y.Type}:${Y.Key}`).sort()};return bM("sha256").update(JSON.stringify(J)).digest("hex").slice(0,24)}function pM($,J){let Y=Date.parse(`${J}T00:00:00Z`);if(Number.isNaN(Y))return!1;let Z=new Date,Q=Date.UTC(Z.getUTCFullYear(),Z.getUTCMonth(),1);return Y<=Q}function rM($){return pM($.start,$.end)?lM:mM}function YH($,J){let Y=i$(z7($),`${JH(J)}.json`);if(!oU(Y))return null;let Z;try{Z=JSON.parse(fM(Y,"utf-8"))}catch{return null}if(Z.schema!==eU)return null;let Q=Date.now()-Z.savedAt;if(Q<0||Q>rM(J))return null;return{response:Z.response,ageSeconds:Math.floor(Q/1000)}}function ZH($,J,Y){let Z=z7($);yM(Z,{recursive:!0});let Q={schema:eU,savedAt:Date.now(),key:J,response:Y};uM(i$(Z,`${JH(J)}.json`),JSON.stringify(Q))}function QH($){let J=$===void 0?dZ():z7($);if(!oU(J))return{deletedFiles:0,scope:$??"all profiles"};let Y=0;function Z(Q){for(let G of vM(Q,{withFileTypes:!0})){let W=i$(Q,G.name);if(G.isDirectory())Z(W);else if(G.isFile()&&G.name.endsWith(".json"))Y++}}return Z(J),gM(J,{recursive:!0,force:!0}),{deletedFiles:Y,scope:$??"all profiles"}}function GH($){return $===void 0?dZ():z7($)}var eU=1,$H=3600000,cM,mM,lM;var cZ=o(()=>{cM=24*$H,mM=$H,lM=30*cM});class o8{client;profile;useCache;lastCacheAgeSeconds=null;constructor($,J){this.profile=$,this.useCache=J?.useCache??!0,this.client=new i(a8($))}async getCostByService($){let{start:J,end:Y,granularity:Z="MONTHLY"}=$,Q=["UnblendedCost"],G=[{Type:"DIMENSION",Key:"SERVICE"}],W={start:J,end:Y,granularity:Z,metrics:Q,groupBy:G};if(this.useCache){let F=YH(this.profile,W);if(F)return this.lastCacheAgeSeconds=F.ageSeconds,F.response}this.lastCacheAgeSeconds=null;let H=((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:J,End:Y},Granularity:Z,Metrics:Q,GroupBy:G})}))?.ResultsByTime?.[0]?.Groups??[]).map((F)=>({service:F.Keys?.[0]??"Unknown",amount:Number.parseFloat(F.Metrics?.UnblendedCost?.Amount??"0"),unit:F.Metrics?.UnblendedCost?.Unit??"USD"})).filter((F)=>F.amount>0).sort((F,B)=>B.amount-F.amount);if(this.useCache)ZH(this.profile,W,H);return H}async getDailyTotals($){return((await this.client.request({service:"ce",region:"us-east-1",method:"POST",path:"/",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":"AWSInsightsIndexService.GetCostAndUsage"},body:JSON.stringify({TimePeriod:{Start:$.start,End:$.end},Granularity:"DAILY",Metrics:["UnblendedCost"]})}))?.ResultsByTime??[]).map((Z)=>Number.parseFloat(Z.Total?.UnblendedCost?.Amount??"0"))}}var U7=o(()=>{Y0();cZ()});var iZ={};h0(iZ,{CloudFrontClient:()=>w0});class w0{client;constructor($){this.client=new i}async createInvalidation($){let J=$.callerReference||Date.now().toString(),Y=`<?xml version="1.0" encoding="UTF-8"?>
|
|
7085
7085
|
<InvalidationBatch>
|
|
7086
7086
|
<Paths>
|
|
7087
7087
|
<Quantity>${$.paths.length}</Quantity>
|
|
@@ -7091,7 +7091,7 @@ host:${W}
|
|
|
7091
7091
|
</Items>
|
|
7092
7092
|
</Paths>
|
|
7093
7093
|
<CallerReference>${J}</CallerReference>
|
|
7094
|
-
</InvalidationBatch>`,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${$.distributionId}/invalidation`,body:Y,headers:{"Content-Type":"application/xml"}});return{Id:Z.Id||Z.Invalidation?.Id,Status:Z.Status||Z.Invalidation?.Status||"InProgress",CreateTime:Z.CreateTime||Z.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation/${J}`});return{Id:Y.Id||Y.Invalidation?.Id,Status:Y.Status||Y.Invalidation?.Status,CreateTime:Y.CreateTime||Y.Invalidation?.CreateTime}}async listInvalidations($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation`}),Y=[];if(J.InvalidationSummary){let Z=Array.isArray(J.InvalidationSummary)?J.InvalidationSummary:[J.InvalidationSummary];Y.push(...Z.map((Q)=>({Id:Q.Id,Status:Q.Status,CreateTime:Q.CreateTime})))}return Y}async waitForInvalidation($,J){let Z=0;while(Z<60){if((await this.getInvalidation($,J)).Status==="Completed")return;await new Promise((G)=>setTimeout(G,5000)),Z++}throw Error(`Timeout waiting for invalidation ${J} to complete`)}async listDistributions(){let $=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),J=[],Z=($.DistributionList||$).Items,Q=[];if(Array.isArray(Z))Q=Z;else if(Z?.DistributionSummary)Q=Array.isArray(Z.DistributionSummary)?Z.DistributionSummary:[Z.DistributionSummary];return J.push(...Q.map((G)=>({Id:G.Id,ARN:G.ARN,Status:G.Status,DomainName:G.DomainName,Aliases:G.Aliases||void 0,Enabled:G.Enabled==="true"||G.Enabled===!0}))),J}async getDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`}),Y=J.Distribution||J;return{Id:Y.Id,ARN:Y.ARN,Status:Y.Status,DomainName:Y.DomainName,Aliases:Y.DistributionConfig?.Aliases?.Items||Y.Aliases?.Items||[],Enabled:Y.DistributionConfig?.Enabled==="true"||Y.DistributionConfig?.Enabled===!0}}async getDistributionConfig($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`});return{ETag:J.ETag||"",DistributionConfig:J.DistributionConfig||J}}async invalidateAll($){return this.createInvalidation({distributionId:$,paths:["/*"]})}async invalidatePaths($,J){let Y=J.map((Z)=>Z.startsWith("/")?Z:`/${Z}`);return this.createInvalidation({distributionId:$,paths:Y})}async invalidatePattern($,J){let Y=J.startsWith("/")?J:`/${J}`;return this.createInvalidation({distributionId:$,paths:[Y]})}async invalidateAfterDeployment($){let{distributionId:J,changedPaths:Y,invalidateAll:Z=!1,wait:Q=!1}=$,G;if(Z||!Y||Y.length===0)G=await this.invalidateAll(J);else G=await this.invalidatePaths(J,Y);if(Q)await this.waitForInvalidation(J,G.Id);return{invalidationId:G.Id,status:G.Status}}async findDistributionByDomain($){return(await this.listDistributions()).find((Z)=>{if(Z.DomainName===$)return!0;if(Z.Aliases?.Items&&Z.Aliases.Items.includes($))return!0;return!1})||null}async batchInvalidate($,J=["/*"]){return await Promise.all($.map(async(Z)=>{let Q=await this.createInvalidation({distributionId:Z,paths:J});return{distributionId:Z,invalidationId:Q.Id,status:Q.Status}}))}async updateCustomErrorResponses($){let{distributionId:J,customErrorResponses:Y}=$,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),Q=Z.headers?.etag||Z.headers?.ETag||"",G=Z.body?.DistributionConfig||Z.DistributionConfig;if(!G)throw Error("Failed to get current distribution config");if(Y.length===0)G.CustomErrorResponses={Quantity:0};else G.CustomErrorResponses={Quantity:Y.length,Items:{CustomErrorResponse:Y.map((H)=>({ErrorCode:H.errorCode,...H.responsePagePath&&{ResponsePagePath:H.responsePagePath},...H.responseCode&&{ResponseCode:H.responseCode},...H.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:H.errorCachingMinTTL}}))}};let W=this.buildDistributionConfigXml(G),z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:W,headers:{"Content-Type":"application/xml","If-Match":Q}}),U=z.Distribution||z;return{Distribution:{Id:U.Id,ARN:U.ARN,Status:U.Status,DomainName:U.DomainName,Aliases:U.DistributionConfig?.Aliases?.Items||[],Enabled:U.DistributionConfig?.Enabled==="true"||U.DistributionConfig?.Enabled===!0},ETag:z.ETag||""}}async removeCustomErrorResponses($){return this.updateCustomErrorResponses({distributionId:$,customErrorResponses:[]})}async updateDistribution($){let{distributionId:J,aliases:Y,certificateArn:Z,comment:Q}=$,G=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),W=G.headers?.etag||G.headers?.ETag||"",z=G.body?.DistributionConfig||G.DistributionConfig;if(!z)throw Error("Failed to get current distribution config");if(Y&&Y.length>0)z.Aliases={Quantity:Y.length,Items:{Item:Y}};if(Z)z.ViewerCertificate={ACMCertificateArn:Z,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(Q)z.Comment=Q;let U=this.buildDistributionConfigXml(z),H=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:U,headers:{"Content-Type":"application/xml","If-Match":W}}),F=H.Distribution||H;return{Distribution:{Id:F.Id,ARN:F.ARN,Status:F.Status,DomainName:F.DomainName,Aliases:Y?{Quantity:Y.length,Items:Y}:{Quantity:0,Items:[]},Enabled:F.DistributionConfig?.Enabled==="true"||F.DistributionConfig?.Enabled===!0},ETag:H.ETag||""}}buildDistributionConfigXml($){let J=(G)=>{return G.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")},Y={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},Z={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},Q=(G,W,z="",U="")=>{if(W===null||W===void 0)return"";if(G.startsWith("@_")||G==="?xml")return"";if(typeof W==="boolean")return`${z}<${G}>${W}</${G}>
|
|
7094
|
+
</InvalidationBatch>`,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${$.distributionId}/invalidation`,body:Y,headers:{"Content-Type":"application/xml"}});return{Id:Z.Id||Z.Invalidation?.Id,Status:Z.Status||Z.Invalidation?.Status||"InProgress",CreateTime:Z.CreateTime||Z.Invalidation?.CreateTime||new Date().toISOString()}}async getInvalidation($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation/${J}`});return{Id:Y.Id||Y.Invalidation?.Id,Status:Y.Status||Y.Invalidation?.Status,CreateTime:Y.CreateTime||Y.Invalidation?.CreateTime}}async listInvalidations($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/invalidation`}),Y=[];if(J.InvalidationSummary){let Z=Array.isArray(J.InvalidationSummary)?J.InvalidationSummary:[J.InvalidationSummary];Y.push(...Z.map((Q)=>({Id:Q.Id,Status:Q.Status,CreateTime:Q.CreateTime})))}return Y}async waitForInvalidation($,J){let Z=0;while(Z<60){if((await this.getInvalidation($,J)).Status==="Completed")return;await new Promise((G)=>setTimeout(G,5000)),Z++}throw Error(`Timeout waiting for invalidation ${J} to complete`)}async listDistributions(){let $=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:"/2020-05-31/distribution"}),J=[],Z=($.DistributionList||$).Items,Q=[];if(Array.isArray(Z))Q=Z;else if(Z?.DistributionSummary)Q=Array.isArray(Z.DistributionSummary)?Z.DistributionSummary:[Z.DistributionSummary];return J.push(...Q.map((G)=>({Id:G.Id,ARN:G.ARN,Status:G.Status,DomainName:G.DomainName,Aliases:G.Aliases||void 0,Enabled:G.Enabled==="true"||G.Enabled===!0}))),J}async getDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`}),Y=J.Distribution||J;return{Id:Y.Id,ARN:Y.ARN,Status:Y.Status,DomainName:Y.DomainName,Aliases:Y.DistributionConfig?.Aliases?.Items||Y.Aliases?.Items||[],Enabled:Y.DistributionConfig?.Enabled==="true"||Y.DistributionConfig?.Enabled===!0}}async getDistributionConfig($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`});return{ETag:J.ETag||"",DistributionConfig:J.DistributionConfig||J}}async invalidateAll($){return this.createInvalidation({distributionId:$,paths:["/*"]})}async invalidatePaths($,J){let Y=J.map((Z)=>Z.startsWith("/")?Z:`/${Z}`);return this.createInvalidation({distributionId:$,paths:Y})}async invalidatePattern($,J){let Y=J.startsWith("/")?J:`/${J}`;return this.createInvalidation({distributionId:$,paths:[Y]})}async invalidateAfterDeployment($){let{distributionId:J,changedPaths:Y,invalidateAll:Z=!1,wait:Q=!1}=$,G;if(Z||!Y||Y.length===0)G=await this.invalidateAll(J);else G=await this.invalidatePaths(J,Y);if(Q)await this.waitForInvalidation(J,G.Id);return{invalidationId:G.Id,status:G.Status}}async findDistributionByDomain($){return(await this.listDistributions()).find((Z)=>{if(Z.DomainName===$)return!0;if(Z.Aliases?.Items&&Z.Aliases.Items.includes($))return!0;return!1})||null}async batchInvalidate($,J=["/*"]){return await Promise.all($.map(async(Z)=>{let Q=await this.createInvalidation({distributionId:Z,paths:J});return{distributionId:Z,invalidationId:Q.Id,status:Q.Status}}))}async updateCustomErrorResponses($){let{distributionId:J,customErrorResponses:Y}=$,Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),Q=Z.headers?.etag||Z.headers?.ETag||"",G=Z.body?.DistributionConfig||(Z.body?.Enabled!==void 0?Z.body:void 0)||Z.DistributionConfig;if(!G||G.Enabled===void 0)throw Error("Failed to get current distribution config");if(Y.length===0)G.CustomErrorResponses={Quantity:0};else G.CustomErrorResponses={Quantity:Y.length,Items:{CustomErrorResponse:Y.map((H)=>({ErrorCode:H.errorCode,...H.responsePagePath&&{ResponsePagePath:H.responsePagePath},...H.responseCode&&{ResponseCode:H.responseCode},...H.errorCachingMinTTL!==void 0&&{ErrorCachingMinTTL:H.errorCachingMinTTL}}))}};let W=this.buildDistributionConfigXml(G),z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:W,headers:{"Content-Type":"application/xml","If-Match":Q}}),U=z.Distribution||z;return{Distribution:{Id:U.Id,ARN:U.ARN,Status:U.Status,DomainName:U.DomainName,Aliases:U.DistributionConfig?.Aliases?.Items||[],Enabled:U.DistributionConfig?.Enabled==="true"||U.DistributionConfig?.Enabled===!0},ETag:z.ETag||""}}async removeCustomErrorResponses($){return this.updateCustomErrorResponses({distributionId:$,customErrorResponses:[]})}async updateDistribution($){let{distributionId:J,aliases:Y,certificateArn:Z,comment:Q}=$,G=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${J}/config`,returnHeaders:!0}),W=G.headers?.etag||G.headers?.ETag||"",z=G.body?.DistributionConfig||(G.body?.Enabled!==void 0?G.body:void 0)||G.DistributionConfig;if(!z||z.Enabled===void 0)throw Error("Failed to get current distribution config");if(Y&&Y.length>0)z.Aliases={Quantity:Y.length,Items:{Item:Y}};if(Z)z.ViewerCertificate={ACMCertificateArn:Z,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CertificateSource:"acm"};if(Q)z.Comment=Q;let U=this.buildDistributionConfigXml(z),H=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${J}/config`,body:U,headers:{"Content-Type":"application/xml","If-Match":W}}),F=H.Distribution||H;return{Distribution:{Id:F.Id,ARN:F.ARN,Status:F.Status,DomainName:F.DomainName,Aliases:Y?{Quantity:Y.length,Items:Y}:{Quantity:0,Items:[]},Enabled:F.DistributionConfig?.Enabled==="true"||F.DistributionConfig?.Enabled===!0},ETag:H.ETag||""}}buildDistributionConfigXml($){let J=(G)=>{return G.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")},Y={Items:"",Methods:"Method",Headers:"Name",Cookies:"Name",QueryStringCacheKeys:"Name",TrustedKeyGroups:"KeyGroup",TrustedSigners:"AwsAccountNumber",LambdaFunctionAssociations:"LambdaFunctionAssociation",FunctionAssociations:"FunctionAssociation",CacheBehaviors:"CacheBehavior",CustomErrorResponses:"CustomErrorResponse",GeoRestriction:"Location"},Z={Origins:"Origin",Aliases:"CNAME",AllowedMethods:"Method",CachedMethods:"Method",CustomErrorResponses:"CustomErrorResponse",CacheBehaviors:"CacheBehavior"},Q=(G,W,z="",U="")=>{if(W===null||W===void 0)return"";if(G.startsWith("@_")||G==="?xml")return"";if(typeof W==="boolean")return`${z}<${G}>${W}</${G}>
|
|
7095
7095
|
`;if(typeof W==="number"||typeof W==="string")return`${z}<${G}>${J(String(W))}</${G}>
|
|
7096
7096
|
`;if(Array.isArray(W)){let H=Y[G]||G.replace(/s$/,"");return W.map((F)=>Q(H,F,z,G)).join("")}if(typeof W==="object"){if(G==="Items"){let F=Z[U]||"",B=Object.keys(W).filter((K)=>!K.startsWith("@_"));if(B.length===1&&!Array.isArray(W[B[0]])){let K=B[0],O=W[K];if(typeof O==="string")return`${z}<Items>
|
|
7097
7097
|
${z} <${K}>${J(O)}</${K}>
|
|
@@ -7215,7 +7215,7 @@ ${Object.entries($).filter(([G])=>!G.startsWith("@_")).map(([G,W])=>Q(G,W," ","
|
|
|
7215
7215
|
</CustomErrorResponse>
|
|
7216
7216
|
</Items>
|
|
7217
7217
|
</CustomErrorResponses>
|
|
7218
|
-
</DistributionConfig>`,_=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:A,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),M=_.body?.Distribution||_.Distribution||_.body||_;return{Id:M.Id,ARN:M.ARN,DomainName:M.DomainName,Status:M.Status,ETag:_.headers?.etag||_.ETag||""}}static getS3BucketPolicyForCloudFront($,J){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${$}/*`,Condition:{StringEquals:{"AWS:SourceArn":J}}}]}}async waitForDistributionDeployed($,J=60){for(let Y=0;Y<J;Y++){if((await this.getDistribution($)).Status==="Deployed")return!0;await new Promise((Q)=>setTimeout(Q,30000))}return!1}async disableDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Y=J.headers?.etag||J.headers?.ETag||"",Z=J.body?.DistributionConfig||J.DistributionConfig;if(!Z)throw Error("Failed to get current distribution config");Z.Enabled=!1;let Q=this.buildDistributionConfigXml(Z),G=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:Q,headers:{"Content-Type":"application/xml","If-Match":Y},returnHeaders:!0});return{ETag:G.headers?.etag||G.headers?.ETag||G.ETag||""}}async deleteDistribution($,J){let Y=J||"";if(!Y){let Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`,returnHeaders:!0});Y=Z.headers?.etag||Z.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${$}`,headers:{"If-Match":Y}})}async waitForDistributionDisabled($,J=60){for(let Y=0;Y<J;Y++){let Z=await this.getDistribution($);if(Z.Status==="Deployed"&&!Z.Enabled)return!0;await new Promise((Q)=>setTimeout(Q,30000))}return!1}async removeAlias($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Z=Y.headers?.etag||Y.headers?.ETag||"",Q=Y.body?.DistributionConfig||Y.DistributionConfig;if(!Q)throw Error("Failed to get current distribution config");let G=[];if(Q.Aliases?.Items){if(Array.isArray(Q.Aliases.Items))G=Q.Aliases.Items;else if(typeof Q.Aliases.Items==="object"){let H=Q.Aliases.Items.CNAME;if(typeof H==="string")G=[H];else if(Array.isArray(H))G=H}}if(G.length===0)throw Error("Distribution has no aliases to remove");let W=G.filter((H)=>H!==J);if(W.length===G.length)throw Error(`Alias ${J} not found in distribution`);if(Q.Aliases.Quantity=W.length,Q.Aliases.Items=W.length>0?W:void 0,W.length===0)Q.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let z=this.buildDistributionConfigXml(Q),U=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:z,headers:{"Content-Type":"application/xml","If-Match":Z},returnHeaders:!0});return{ETag:U.headers?.etag||U.headers?.ETag||U.ETag||""}}}var W2=o(()=>{Y0()});var WH={};h0(WH,{STSClient:()=>$9});class $9{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async getCallerIdentity(){let $=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof $==="string"){let Y=$.match(/<Account>(\d+)<\/Account>/),Z=$.match(/<UserId>([^<]+)<\/UserId>/),Q=$.match(/<Arn>([^<]+)<\/Arn>/);return{Account:Y?.[1],UserId:Z?.[1],Arn:Q?.[1]}}let J=$?.GetCallerIdentityResponse?.GetCallerIdentityResult||$?.GetCallerIdentityResult;if(J)return{Account:String(J.Account),UserId:J.UserId,Arn:J.Arn};if($?.Account)return{Account:String($.Account),UserId:$.UserId,Arn:$.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}var F7=o(()=>{Y0()});var X7={};h0(X7,{uploadStaticFiles:()=>eZ,invalidateCache:()=>$Q,generateStaticSiteTemplate:()=>sZ,deployStaticSiteFull:()=>UH,deployStaticSite:()=>oZ,deleteStaticSite:()=>zH});function sZ($){let{bucketName:J,domain:Y,certificateArn:Z,hostedZoneId:Q,defaultRootObject:G="index.html",errorDocument:W="404.html"}=$,z={},U={};z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:G,ErrorDocument:W}}},U.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},U.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},z.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},z.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
7218
|
+
</DistributionConfig>`,_=await this.client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:"/2020-05-31/distribution",body:A,headers:{"Content-Type":"application/xml"},returnHeaders:!0}),M=_.body?.Distribution||_.Distribution||_.body||_;return{Id:M.Id,ARN:M.ARN,DomainName:M.DomainName,Status:M.Status,ETag:_.headers?.etag||_.ETag||""}}static getS3BucketPolicyForCloudFront($,J){return{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:`arn:aws:s3:::${$}/*`,Condition:{StringEquals:{"AWS:SourceArn":J}}}]}}async waitForDistributionDeployed($,J=60){for(let Y=0;Y<J;Y++){if((await this.getDistribution($)).Status==="Deployed")return!0;await new Promise((Q)=>setTimeout(Q,30000))}return!1}async disableDistribution($){let J=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Y=J.headers?.etag||J.headers?.ETag||"",Z=J.body?.DistributionConfig||(J.body?.Enabled!==void 0?J.body:void 0)||J.DistributionConfig;if(!Z||Z.Enabled===void 0)throw Error("Failed to get current distribution config");Z.Enabled=!1;let Q=this.buildDistributionConfigXml(Z),G=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:Q,headers:{"Content-Type":"application/xml","If-Match":Y},returnHeaders:!0});return{ETag:G.headers?.etag||G.headers?.ETag||G.ETag||""}}async deleteDistribution($,J){let Y=J||"";if(!Y){let Z=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}`,returnHeaders:!0});Y=Z.headers?.etag||Z.headers?.ETag||""}await this.client.request({service:"cloudfront",region:"us-east-1",method:"DELETE",path:`/2020-05-31/distribution/${$}`,headers:{"If-Match":Y}})}async waitForDistributionDisabled($,J=60){for(let Y=0;Y<J;Y++){let Z=await this.getDistribution($);if(Z.Status==="Deployed"&&!Z.Enabled)return!0;await new Promise((Q)=>setTimeout(Q,30000))}return!1}async removeAlias($,J){let Y=await this.client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${$}/config`,returnHeaders:!0}),Z=Y.headers?.etag||Y.headers?.ETag||"",Q=Y.body?.DistributionConfig||(Y.body?.Enabled!==void 0?Y.body:void 0)||Y.DistributionConfig;if(!Q||Q.Enabled===void 0)throw Error("Failed to get current distribution config");let G=[];if(Q.Aliases?.Items){if(Array.isArray(Q.Aliases.Items))G=Q.Aliases.Items;else if(typeof Q.Aliases.Items==="object"){let H=Q.Aliases.Items.CNAME;if(typeof H==="string")G=[H];else if(Array.isArray(H))G=H}}if(G.length===0)throw Error("Distribution has no aliases to remove");let W=G.filter((H)=>H!==J);if(W.length===G.length)throw Error(`Alias ${J} not found in distribution`);if(Q.Aliases.Quantity=W.length,Q.Aliases.Items=W.length>0?W:void 0,W.length===0)Q.ViewerCertificate={CloudFrontDefaultCertificate:!0,MinimumProtocolVersion:"TLSv1.2_2021"};let z=this.buildDistributionConfigXml(Q),U=await this.client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${$}/config`,body:z,headers:{"Content-Type":"application/xml","If-Match":Z},returnHeaders:!0});return{ETag:U.headers?.etag||U.headers?.ETag||U.ETag||""}}}var W2=o(()=>{Y0()});var WH={};h0(WH,{STSClient:()=>$9});class $9{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async getCallerIdentity(){let $=await this.client.request({service:"sts",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=GetCallerIdentity&Version=2011-06-15"});if(typeof $==="string"){let Y=$.match(/<Account>(\d+)<\/Account>/),Z=$.match(/<UserId>([^<]+)<\/UserId>/),Q=$.match(/<Arn>([^<]+)<\/Arn>/);return{Account:Y?.[1],UserId:Z?.[1],Arn:Q?.[1]}}let J=$?.GetCallerIdentityResponse?.GetCallerIdentityResult||$?.GetCallerIdentityResult;if(J)return{Account:String(J.Account),UserId:J.UserId,Arn:J.Arn};if($?.Account)return{Account:String($.Account),UserId:$.UserId,Arn:$.Arn};return{Account:void 0,UserId:void 0,Arn:void 0}}}var F7=o(()=>{Y0()});var X7={};h0(X7,{uploadStaticFiles:()=>eZ,invalidateCache:()=>$Q,generateStaticSiteTemplate:()=>sZ,deployStaticSiteFull:()=>UH,deployStaticSite:()=>oZ,deleteStaticSite:()=>zH});function sZ($){let{bucketName:J,domain:Y,certificateArn:Z,hostedZoneId:Q,defaultRootObject:G="index.html",errorDocument:W="404.html"}=$,z={},U={};z.S3Bucket={Type:"AWS::S3::Bucket",Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:G,ErrorDocument:W}}},U.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},U.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},z.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},z.UrlRewriteFunction={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-url-rewrite"},AutoPublish:!0,FunctionConfig:{Comment:"Append .html extension to URLs without extensions",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
7219
7219
|
const request = event.request;
|
|
7220
7220
|
var uri = request.uri;
|
|
7221
7221
|
|
|
@@ -7229,7 +7229,7 @@ ${Object.entries($).filter(([G])=>!G.startsWith("@_")).map(([G,W])=>Q(G,W," ","
|
|
|
7229
7229
|
}
|
|
7230
7230
|
|
|
7231
7231
|
return request;
|
|
7232
|
-
}`}};let H={Enabled:!0,DefaultRootObject:G,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300}]};if(Y&&Z)H.Aliases=[Y],H.ViewerCertificate={AcmCertificateArn:Z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else H.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(z.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:H}},U.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},U.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},z.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},Y&&Q)z.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:Q,Name:Y,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},z.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:Q,Name:Y,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},U.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J}`,Resources:z,Outputs:U}}async function oZ($){if($.dnsProvider&&$.dnsProvider.provider!=="route53"){let D=$.domain||($.subdomain&&$.baseDomain?`${$.subdomain}.${$.baseDomain}`:void 0);if(!D)return{success:!1,stackName:$.stackName||`${$.siteName}-static-site`,bucket:$.bucket||`${$.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return B7({siteName:$.siteName,region:$.region,domain:D,bucket:$.bucket,certificateArn:$.certificateArn,stackName:$.stackName,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument,cacheControl:$.cacheControl,tags:$.tags,dnsProvider:$.dnsProvider})}let J=$.region||"us-east-1",Y="us-east-1",Z;if($.domain)Z=$.domain;else if($.subdomain&&$.baseDomain)Z=`${$.subdomain}.${$.baseDomain}`;let Q=$.bucket||(Z?Z.replace(/\./g,"-"):`${$.siteName}-${Date.now()}`),G=$.stackName||`${$.siteName}-static-site`,W=new K0(Y),z=new e0,U=new $1("us-east-1"),H=new L8("us-east-1"),F=$.hostedZoneId,B=$.certificateArn;if(Z&&!F){let D=await z.findHostedZoneForDomain(Z);if(D)F=D.Id.replace("/hostedzone/","");else return{success:!1,stackName:G,bucket:Q,message:`No Route53 hosted zone found for ${$.baseDomain||Z}. Please create one first.`}}if(Z&&!B&&F){let D=await U.findCertificateByDomain(Z);if(D&&D.Status==="ISSUED")B=D.CertificateArn;else B=(await H.requestAndValidate({domainName:Z,hostedZoneId:F,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let K=!1,O;try{let D=await W.describeStacks({stackName:G});if(D.Stacks.length>0){let S=D.Stacks[0],P=S.StackStatus;if(P==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await W.waitForStack(G,"stack-delete-complete"),K=!1;else if(P==="DELETE_COMPLETE")K=!1;else K=!0,O=(S.Outputs||[]).find((I)=>I.OutputKey==="BucketName")?.OutputValue}}catch(D){if(D.message?.includes("does not exist")||D.code==="ValidationError")K=!1;else throw D}let V=O||Q;if(!K){let D=new W0(J),S=new w0,P=!1;if(Z){try{console.log(`Checking for existing CloudFront distribution for ${Z}...`);let C=await S.listDistributions();for(let I of C){let b=[];if(I.Aliases?.Items){if(Array.isArray(I.Aliases.Items))b=I.Aliases.Items;else if(typeof I.Aliases.Items==="object"){let y=I.Aliases.Items.CNAME;if(typeof y==="string")b=[y];else if(Array.isArray(y))b=y}}if(b.includes(Z)){P=!0,console.log(`Found existing CloudFront distribution ${I.Id} for ${Z}`);let c=(await S.getDistributionConfig(I.Id)).DistributionConfig?.Origins?.Items,r;if(c){let d=[];if(Array.isArray(c))d=c;else if(c.Origin)d=Array.isArray(c.Origin)?c.Origin:[c.Origin];else d=[c];for(let u of d){let J0=(u.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(J0){r=J0[1];break}}}if(r){let d=Z.replace(/\./g,"-");if(!r.startsWith(d)&&!r.includes($.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${r}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${r}`),F&&I.DomainName)try{console.log(`Ensuring Route53 records exist for ${Z}...`),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"A",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:I.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"AAAA",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:I.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${Z}`)}catch(u){console.log(`Note: Could not update Route53 records: ${u.message}`)}return{success:!0,stackName:`existing-${I.Id}`,bucket:r,distributionId:I.Id,distributionDomain:I.DomainName,domain:Z,certificateArn:B,message:"Using existing CloudFront distribution"}}}}}catch{}if(F)try{let I=(await z.listResourceRecordSets({HostedZoneId:F})).ResourceRecordSets||[];for(let b of I)if(b.Name===`${Z}.`&&(b.Type==="A"||b.Type==="AAAA")){if(b.AliasTarget){console.log(`Found orphaned Route53 ${b.Type} record for ${Z}, cleaning up...`);try{await z.deleteRecord({HostedZoneId:F,RecordSet:b}),console.log(`Deleted orphaned Route53 ${b.Type} record for ${Z}`)}catch(y){console.log(`Note: Could not delete Route53 record: ${y.message}`)}}}}catch{}}if(!P)try{if((await D.headBucket(Q)).exists){console.log(`Found orphaned S3 bucket ${Q}, cleaning up...`);try{let I=D.emptyBucket(Q).then(()=>D.deleteBucket(Q)),b=new Promise((y,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([I,b]),console.log(`Deleted orphaned S3 bucket ${Q}`)}catch(I){console.log(`Note: Could not clean up S3 bucket: ${I.message}`);let b=Date.now().toString(36);V=`${Q}-${b}`,console.log(`Using alternative bucket name: ${V}`)}}}catch{}}let A=sZ({bucketName:V,domain:Z,certificateArn:B,hostedZoneId:F,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument}),_=Object.entries($.tags||{}).map(([D,S])=>({Key:D,Value:S}));_.push({Key:"ManagedBy",Value:"ts-cloud"}),_.push({Key:"Application",Value:$.siteName});let M,E=!1;if(K){E=!0,console.log(`Updating CloudFormation stack: ${G}`),console.log(`Using existing bucket: ${V}`),console.log(`Domain: ${Z||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`);try{M=(await W.updateStack({stackName:G,templateBody:JSON.stringify(A),capabilities:["CAPABILITY_IAM"],tags:_})).StackId,console.log(`Update initiated, stack ID: ${M}`)}catch(D){if(D.message?.includes("No updates are to be performed")){let S=await W.describeStacks({stackName:G});M=S.Stacks[0].StackId;let P=S.Stacks[0]?.Outputs||[],C=(I)=>P.find((b)=>b.OutputKey===I)?.OutputValue;return{success:!0,stackId:M,stackName:G,bucket:C("BucketName")||V,distributionId:C("DistributionId"),distributionDomain:C("DistributionDomain"),domain:Z,certificateArn:B,message:"Static site infrastructure is already up to date"}}else throw D}}else console.log(`Creating CloudFormation stack: ${G}`),console.log(`Bucket name: ${V}`),console.log(`Domain: ${Z||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`),console.log("Stack does not exist, creating..."),M=(await W.createStack({stackName:G,templateBody:JSON.stringify(A),capabilities:["CAPABILITY_IAM"],tags:_,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${M}`);console.log(`Waiting for stack to reach ${E?"stack-update-complete":"stack-create-complete"}...`);try{await W.waitForStack(G,E?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(D){if(D.message?.includes("must be verified")||D.message?.includes("Access denied for operation")||D.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let S=new w0;if(Z)try{let P=await S.listDistributions();for(let C of P){let I=[];if(C.Aliases?.Items){if(Array.isArray(C.Aliases.Items))I=C.Aliases.Items;else if(typeof C.Aliases.Items==="object"){let b=C.Aliases.Items.CNAME;if(typeof b==="string")I=[b];else if(Array.isArray(b))I=b}}if(I.includes(Z)){console.log(`Found existing CloudFront distribution ${C.Id} with alias ${Z}`);let y=(await S.getDistributionConfig(C.Id)).DistributionConfig?.Origins?.Items,c;if(y){let r=[];if(Array.isArray(y))r=y;else if(y.Origin)r=Array.isArray(y.Origin)?y.Origin:[y.Origin];else r=[y];for(let d of r){let s=(d.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(s){c=s[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${C.Id}`,bucket:c,distributionId:C.Id,distributionDomain:C.DomainName,domain:Z,certificateArn:B,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let P=new W0(J);if((await P.headBucket(V)).exists)console.log(`Using existing S3 bucket: ${V}`);else console.log(`Creating S3 bucket: ${V}...`),await P.createBucket(V);await P.putBucketWebsite(V,{IndexDocument:$.defaultRootObject||"index.html",ErrorDocument:$.errorDocument||"404.html"}),await P.putPublicAccessBlock(V,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${V} configured`);let I=`OAC-${V}`;console.log(`Creating Origin Access Control: ${I}...`);let b=await S.findOrCreateOriginAccessControl(I);console.log(`Origin Access Control ${b.Id} ready`),console.log("Creating CloudFront distribution...");let y=await S.createDistributionForS3({bucketName:V,bucketRegion:J,originAccessControlId:b.Id,aliases:Z?[Z]:[],certificateArn:B,defaultRootObject:$.defaultRootObject||"index.html",comment:`Distribution for ${Z||V}`});console.log(`CloudFront distribution ${y.Id} created`),console.log("Updating S3 bucket policy...");let c=w0.getS3BucketPolicyForCloudFront(V,y.ARN);if(await P.putBucketPolicy(V,c),console.log("S3 bucket policy updated"),Z&&F){console.log(`Creating Route53 records for ${Z}...`);try{await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"A",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:y.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"AAAA",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:y.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${Z}`)}catch(r){console.log(`Note: Could not create Route53 records: ${r.message}`)}}return{success:!0,stackName:`direct-${y.Id}`,bucket:V,distributionId:y.Id,distributionDomain:y.DomainName,domain:Z,certificateArn:B,message:"Static site infrastructure created via direct API calls"}}catch(P){return console.log(`Direct API creation failed: ${P.message}`),{success:!1,stackId:M,stackName:G,bucket:V,message:`Deployment failed: ${P.message}`}}}return{success:!1,stackId:M,stackName:G,bucket:V,message:`Stack deployment failed: ${D.message}`}}let q=(await W.describeStacks({stackName:G})).Stacks[0]?.Outputs||[],T=(D)=>q.find((S)=>S.OutputKey===D)?.OutputValue;return{success:!0,stackId:M,stackName:G,bucket:T("BucketName")||V,distributionId:T("DistributionId"),distributionDomain:T("DistributionDomain"),domain:Z,certificateArn:B,message:"Static site infrastructure deployed successfully"}}async function eZ($){let{sourceDir:J,bucket:Y,region:Z,cacheControl:Q="max-age=31536000, public",onProgress:G}=$,W=new W0(Z),{readdir:z}=await import("node:fs/promises"),{join:U,relative:H}=await import("node:path"),{createHash:F}=await import("node:crypto");async function B(q){let T=[],D=await z(q,{withFileTypes:!0});for(let S of D){let P=U(q,S.name);if(S.isDirectory())T.push(...await B(P));else T.push(P)}return T}function K(q){let T=q.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[T||""]||"application/octet-stream"}function O(q){return F("md5").update(q).digest("hex")}async function V(){let q=new Map,T;do{let D=await W.listObjects({bucket:Y,maxKeys:1000,continuationToken:T});for(let S of D.objects){let P=S.ETag?.replace(/"/g,"")||"";q.set(S.Key,P)}T=D.nextContinuationToken}while(T);return q}let A=await B(J),_=[],M=0,E=0,j=await V();for(let q of A){let T=H(J,q),D=K(q),S=q.endsWith(".html")?"max-age=3600, public":Q;try{let P=Buffer.from(await Bun.file(q).arrayBuffer()),C=O(P),I=j.get(T);if(I&&I===C){E++,G?.(M+E,A.length,T);continue}await W.putObject({bucket:Y,key:T,body:P,contentType:D,cacheControl:S}),M++,G?.(M+E,A.length,T)}catch(P){_.push(`Failed to upload ${T}: ${P.message}`)}}return{uploaded:M,skipped:E,errors:_}}async function $Q($){return{invalidationId:(await new w0().invalidateAll($)).Id}}async function zH($,J="us-east-1"){let Y=new K0(J);try{let W=((await Y.describeStacks({stackName:$})).Stacks[0]?.Outputs||[]).find((z)=>z.OutputKey==="BucketName")?.OutputValue;if(W)await new W0(J).emptyBucket(W)}catch{}await Y.deleteStack($);let Z=await Y.waitForStackComplete($,60,1e4);return{success:Z.success||Z.status==="DELETE_COMPLETE",message:Z.success?"Static site deleted successfully":`Deletion failed: ${Z.status}`}}async function UH($){let{sourceDir:J,cleanBucket:Y=!1,onProgress:Z,...Q}=$;Z?.("infrastructure","Deploying CloudFormation stack...");let G=await oZ(Q);if(!G.success)return G;if(Y){Z?.("clean","Cleaning old files from S3...");try{await new W0(Q.region||"us-east-1").emptyBucket(G.bucket)}catch(U){console.log(`Note: Could not clean bucket: ${U.message}`)}}Z?.("upload","Uploading files to S3...");let W=await eZ({sourceDir:J,bucket:G.bucket,region:Q.region||"us-east-1",cacheControl:Q.cacheControl,onProgress:(U,H,F)=>{Z?.("upload",`${U}/${H}: ${F}`)}});if(W.errors.length>0)return{...G,success:!1,message:`Upload errors: ${W.errors.join(", ")}`,filesUploaded:W.uploaded};if(G.distributionId&&W.uploaded>0)Z?.("invalidate","Invalidating CloudFront cache..."),await $Q(G.distributionId);Z?.("complete","Deployment complete!");let z=W.skipped>0?`Deployed ${W.uploaded} files (${W.skipped} unchanged)`:`Deployed ${W.uploaded} files successfully`;return{...G,filesUploaded:W.uploaded,filesSkipped:W.skipped,message:z}}var J9=o(()=>{L1();I0();W2();s2();j2();Y9()});function HH($){let{bucketName:J,domain:Y,aliases:Z,certificateArn:Q,defaultRootObject:G="index.html",errorDocument:W="404.html",passthroughUrls:z=!1,singlePageApp:U=!1,dynamicApp:H=!1,computeOriginDomain:F,computeOriginPort:B=3008,computeOriginId:K="app-compute",retainOnStackDelete:O=!1}=$,V=O?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},A=H&&!!F,_=A?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],M=A?["GET","HEAD"]:["GET","HEAD"],E={},j={};E.S3Bucket={Type:"AWS::S3::Bucket",...V,Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:G,ErrorDocument:W}}},j.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},j.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},E.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...V,Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let q;if(z&&A)q="InstallRootRedirectFunction",E[q]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
7232
|
+
}`}};let H={Enabled:!0,DefaultRootObject:G,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:[{Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}}],DefaultCacheBehavior:{TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]},CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300}]};if(Y&&Z)H.Aliases=[Y],H.ViewerCertificate={AcmCertificateArn:Z,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else H.ViewerCertificate={CloudFrontDefaultCertificate:!0};if(z.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",DependsOn:["S3Bucket","CloudFrontOAC","UrlRewriteFunction"],Properties:{DistributionConfig:H}},U.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},U.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},z.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},Y&&Q)z.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:Q,Name:Y,Type:"A",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},z.DNSRecordIPv6={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:Q,Name:Y,Type:"AAAA",AliasTarget:{DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},HostedZoneId:"Z2FDTNDATAQYW2",EvaluateTargetHealth:!1}}},U.SiteUrl={Description:"Site URL",Value:{"Fn::Sub":"https://${DNSRecord}"}};return{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J}`,Resources:z,Outputs:U}}async function oZ($){if($.dnsProvider&&$.dnsProvider.provider!=="route53"){let D=$.domain||($.subdomain&&$.baseDomain?`${$.subdomain}.${$.baseDomain}`:void 0);if(!D)return{success:!1,stackName:$.stackName||`${$.siteName}-static-site`,bucket:$.bucket||`${$.siteName}-${Date.now()}`,message:"Domain is required when using external DNS provider"};return B7({siteName:$.siteName,region:$.region,domain:D,bucket:$.bucket,certificateArn:$.certificateArn,stackName:$.stackName,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument,cacheControl:$.cacheControl,tags:$.tags,dnsProvider:$.dnsProvider})}let J=$.region||"us-east-1",Y="us-east-1",Z;if($.domain)Z=$.domain;else if($.subdomain&&$.baseDomain)Z=`${$.subdomain}.${$.baseDomain}`;let Q=$.bucket||(Z?Z.replace(/\./g,"-"):`${$.siteName}-${Date.now()}`),G=$.stackName||`${$.siteName}-static-site`,W=new K0(Y),z=new e0,U=new $1("us-east-1"),H=new L8("us-east-1"),F=$.hostedZoneId,B=$.certificateArn;if(Z&&!F){let D=await z.findHostedZoneForDomain(Z);if(D)F=D.Id.replace("/hostedzone/","");else return{success:!1,stackName:G,bucket:Q,message:`No Route53 hosted zone found for ${$.baseDomain||Z}. Please create one first.`}}if(Z&&!B&&F){let D=await U.findCertificateByDomain(Z);if(D&&D.Status==="ISSUED")B=D.CertificateArn;else B=(await H.requestAndValidate({domainName:Z,hostedZoneId:F,waitForValidation:!0,maxWaitMinutes:10})).certificateArn}let K=!1,O;try{let D=await W.describeStacks({stackName:G});if(D.Stacks.length>0){let S=D.Stacks[0],P=S.StackStatus;if(P==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await W.waitForStack(G,"stack-delete-complete"),K=!1;else if(P==="DELETE_COMPLETE")K=!1;else K=!0,O=(S.Outputs||[]).find((I)=>I.OutputKey==="BucketName")?.OutputValue}}catch(D){if(D.message?.includes("does not exist")||D.code==="ValidationError")K=!1;else throw D}let V=O||Q;if(!K){let D=new W0(J),S=new w0,P=!1;if(Z){try{console.log(`Checking for existing CloudFront distribution for ${Z}...`);let C=await S.listDistributions();for(let I of C){let b=[];if(I.Aliases?.Items){if(Array.isArray(I.Aliases.Items))b=I.Aliases.Items;else if(typeof I.Aliases.Items==="object"){let y=I.Aliases.Items.CNAME;if(typeof y==="string")b=[y];else if(Array.isArray(y))b=y}}if(b.includes(Z)){P=!0,console.log(`Found existing CloudFront distribution ${I.Id} for ${Z}`);let c=(await S.getDistributionConfig(I.Id)).DistributionConfig?.Origins?.Items,r;if(c){let d=[];if(Array.isArray(c))d=c;else if(c.Origin)d=Array.isArray(c.Origin)?c.Origin:[c.Origin];else d=[c];for(let u of d){let J0=(u.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(J0){r=J0[1];break}}}if(r){let d=Z.replace(/\./g,"-");if(!r.startsWith(d)&&!r.includes($.siteName)){console.log(`Warning: Found distribution with mismatched bucket ${r}, skipping...`);continue}if(console.log(`Using existing S3 bucket: ${r}`),F&&I.DomainName)try{console.log(`Ensuring Route53 records exist for ${Z}...`),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"A",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:I.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"AAAA",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:I.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records ensured for ${Z}`)}catch(u){console.log(`Note: Could not update Route53 records: ${u.message}`)}return{success:!0,stackName:`existing-${I.Id}`,bucket:r,distributionId:I.Id,distributionDomain:I.DomainName,domain:Z,certificateArn:B,message:"Using existing CloudFront distribution"}}}}}catch{}if(F)try{let I=(await z.listResourceRecordSets({HostedZoneId:F})).ResourceRecordSets||[];for(let b of I)if(b.Name===`${Z}.`&&(b.Type==="A"||b.Type==="AAAA")){if(b.AliasTarget){console.log(`Found orphaned Route53 ${b.Type} record for ${Z}, cleaning up...`);try{await z.deleteRecord({HostedZoneId:F,RecordSet:b}),console.log(`Deleted orphaned Route53 ${b.Type} record for ${Z}`)}catch(y){console.log(`Note: Could not delete Route53 record: ${y.message}`)}}}}catch{}}if(!P)try{if((await D.headBucket(Q)).exists){console.log(`Found orphaned S3 bucket ${Q}, cleaning up...`);try{let I=D.emptyBucket(Q).then(()=>D.deleteBucket(Q)),b=new Promise((y,c)=>setTimeout(()=>c(Error("Bucket cleanup timeout")),30000));await Promise.race([I,b]),console.log(`Deleted orphaned S3 bucket ${Q}`)}catch(I){console.log(`Note: Could not clean up S3 bucket: ${I.message}`);let b=Date.now().toString(36);V=`${Q}-${b}`,console.log(`Using alternative bucket name: ${V}`)}}}catch{}}let A=sZ({bucketName:V,domain:Z,certificateArn:B,hostedZoneId:F,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument}),_=Object.entries($.tags||{}).map(([D,S])=>({Key:D,Value:S}));_.push({Key:"ManagedBy",Value:"ts-cloud"}),_.push({Key:"Application",Value:$.siteName});let M,E=!1;if(K){E=!0,console.log(`Updating CloudFormation stack: ${G}`),console.log(`Using existing bucket: ${V}`),console.log(`Domain: ${Z||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`);try{M=(await W.updateStack({stackName:G,templateBody:JSON.stringify(A),capabilities:["CAPABILITY_IAM"],tags:_})).StackId,console.log(`Update initiated, stack ID: ${M}`)}catch(D){if(D.message?.includes("No updates are to be performed")){let S=await W.describeStacks({stackName:G});M=S.Stacks[0].StackId;let P=S.Stacks[0]?.Outputs||[],C=(I)=>P.find((b)=>b.OutputKey===I)?.OutputValue;return{success:!0,stackId:M,stackName:G,bucket:C("BucketName")||V,distributionId:C("DistributionId"),distributionDomain:C("DistributionDomain"),domain:Z,certificateArn:B,message:"Static site infrastructure is already up to date"}}else throw D}}else console.log(`Creating CloudFormation stack: ${G}`),console.log(`Bucket name: ${V}`),console.log(`Domain: ${Z||"not specified"}`),console.log(`Certificate ARN: ${B||"not specified"}`),console.log("Stack does not exist, creating..."),M=(await W.createStack({stackName:G,templateBody:JSON.stringify(A),capabilities:["CAPABILITY_IAM"],tags:_,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${M}`);console.log(`Waiting for stack to reach ${E?"stack-update-complete":"stack-create-complete"}...`);try{await W.waitForStack(G,E?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(D){if(D.message?.includes("must be verified")||D.message?.includes("Access denied for operation")||D.message?.includes("failed")){console.log("CloudFormation deployment failed, trying direct API creation...");let S=new w0;if(Z)try{let P=await S.listDistributions();for(let C of P){let I=[];if(C.Aliases?.Items){if(Array.isArray(C.Aliases.Items))I=C.Aliases.Items;else if(typeof C.Aliases.Items==="object"){let b=C.Aliases.Items.CNAME;if(typeof b==="string")I=[b];else if(Array.isArray(b))I=b}}if(I.includes(Z)){console.log(`Found existing CloudFront distribution ${C.Id} with alias ${Z}`);let y=(await S.getDistributionConfig(C.Id)).DistributionConfig?.Origins?.Items,c;if(y){let r=[];if(Array.isArray(y))r=y;else if(y.Origin)r=Array.isArray(y.Origin)?y.Origin:[y.Origin];else r=[y];for(let d of r){let s=(d.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(s){c=s[1];break}}}if(c)return console.log(`Using existing S3 bucket: ${c}`),{success:!0,stackName:`existing-${C.Id}`,bucket:c,distributionId:C.Id,distributionDomain:C.DomainName,domain:Z,certificateArn:B,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}catch{}console.log("No existing infrastructure found, creating via direct API calls...");try{let P=new W0(J);if((await P.headBucket(V)).exists)console.log(`Using existing S3 bucket: ${V}`);else console.log(`Creating S3 bucket: ${V}...`),await P.createBucket(V);await P.putBucketWebsite(V,{IndexDocument:$.defaultRootObject||"index.html",ErrorDocument:$.errorDocument||"404.html"}),await P.putPublicAccessBlock(V,{BlockPublicAcls:!0,IgnorePublicAcls:!0,BlockPublicPolicy:!1,RestrictPublicBuckets:!1}),console.log(`S3 bucket ${V} configured`);let I=`OAC-${V}`;console.log(`Creating Origin Access Control: ${I}...`);let b=await S.findOrCreateOriginAccessControl(I);console.log(`Origin Access Control ${b.Id} ready`),console.log("Creating CloudFront distribution...");let y=await S.createDistributionForS3({bucketName:V,bucketRegion:J,originAccessControlId:b.Id,aliases:Z?[Z]:[],certificateArn:B,defaultRootObject:$.defaultRootObject||"index.html",comment:`Distribution for ${Z||V}`});console.log(`CloudFront distribution ${y.Id} created`),console.log("Updating S3 bucket policy...");let c=w0.getS3BucketPolicyForCloudFront(V,y.ARN);if(await P.putBucketPolicy(V,c),console.log("S3 bucket policy updated"),Z&&F){console.log(`Creating Route53 records for ${Z}...`);try{await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"A",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:y.DomainName,EvaluateTargetHealth:!1}),await z.createAliasRecord({HostedZoneId:F,Name:Z,Type:"AAAA",TargetHostedZoneId:e0.CloudFrontHostedZoneId,TargetDNSName:y.DomainName,EvaluateTargetHealth:!1}),console.log(`Route53 records created for ${Z}`)}catch(r){console.log(`Note: Could not create Route53 records: ${r.message}`)}}return{success:!0,stackName:`direct-${y.Id}`,bucket:V,distributionId:y.Id,distributionDomain:y.DomainName,domain:Z,certificateArn:B,message:"Static site infrastructure created via direct API calls"}}catch(P){return console.log(`Direct API creation failed: ${P.message}`),{success:!1,stackId:M,stackName:G,bucket:V,message:`Deployment failed: ${P.message}`}}}return{success:!1,stackId:M,stackName:G,bucket:V,message:`Stack deployment failed: ${D.message}`}}let q=(await W.describeStacks({stackName:G})).Stacks[0]?.Outputs||[],T=(D)=>q.find((S)=>S.OutputKey===D)?.OutputValue;return{success:!0,stackId:M,stackName:G,bucket:T("BucketName")||V,distributionId:T("DistributionId"),distributionDomain:T("DistributionDomain"),domain:Z,certificateArn:B,message:"Static site infrastructure deployed successfully"}}async function eZ($){let{sourceDir:J,bucket:Y,region:Z,cacheControl:Q="max-age=31536000, public",onProgress:G}=$,W=new W0(Z),{readdir:z}=await import("node:fs/promises"),{join:U,relative:H}=await import("node:path"),{createHash:F}=await import("node:crypto");async function B(q){let T=[],D=await z(q,{withFileTypes:!0});for(let S of D){let P=U(q,S.name);if(S.isDirectory())T.push(...await B(P));else T.push(P)}return T}function K(q){let T=q.split(".").pop()?.toLowerCase();return{html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"application/javascript; charset=utf-8",json:"application/json; charset=utf-8",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",xml:"application/xml",txt:"text/plain; charset=utf-8",sh:"text/plain; charset=utf-8",bash:"text/plain; charset=utf-8",ps1:"text/plain; charset=utf-8"}[T||""]||"application/octet-stream"}function O(q){return F("md5").update(q).digest("hex")}async function V(){let q=new Map,T;do{let D=await W.listObjects({bucket:Y,maxKeys:1000,continuationToken:T});for(let S of D.objects){let P=S.ETag?.replace(/"/g,"")||"";q.set(S.Key,P)}T=D.nextContinuationToken}while(T);return q}let A=await B(J),_=[],M=0,E=0,j=await V();for(let q of A){let T=H(J,q),D=K(q),S=q.endsWith(".html")?"max-age=3600, public":Q;try{let P=Buffer.from(await Bun.file(q).arrayBuffer()),C=O(P),I=j.get(T);if(I&&I===C){E++,G?.(M+E,A.length,T);continue}await W.putObject({bucket:Y,key:T,body:P,contentType:D,cacheControl:S}),M++,G?.(M+E,A.length,T)}catch(P){_.push(`Failed to upload ${T}: ${P.message}`)}}return{uploaded:M,skipped:E,errors:_}}async function $Q($){return{invalidationId:(await new w0().invalidateAll($)).Id}}async function zH($,J="us-east-1"){let Y=new K0(J);try{let W=((await Y.describeStacks({stackName:$})).Stacks[0]?.Outputs||[]).find((z)=>z.OutputKey==="BucketName")?.OutputValue;if(W)await new W0(J).emptyBucket(W)}catch{}await Y.deleteStack($);let Z=await Y.waitForStackComplete($,60,1e4);return{success:Z.success||Z.status==="DELETE_COMPLETE",message:Z.success?"Static site deleted successfully":`Deletion failed: ${Z.status}`}}async function UH($){let{sourceDir:J,cleanBucket:Y=!1,onProgress:Z,...Q}=$;Z?.("infrastructure","Deploying CloudFormation stack...");let G=await oZ(Q);if(!G.success)return G;if(Y){Z?.("clean","Cleaning old files from S3...");try{await new W0(Q.region||"us-east-1").emptyBucket(G.bucket)}catch(U){console.log(`Note: Could not clean bucket: ${U.message}`)}}Z?.("upload","Uploading files to S3...");let W=await eZ({sourceDir:J,bucket:G.bucket,region:Q.region||"us-east-1",cacheControl:Q.cacheControl,onProgress:(U,H,F)=>{Z?.("upload",`${U}/${H}: ${F}`)}});if(W.errors.length>0)return{...G,success:!1,message:`Upload errors: ${W.errors.join(", ")}`,filesUploaded:W.uploaded};if(G.distributionId&&W.uploaded>0)Z?.("invalidate","Invalidating CloudFront cache..."),await $Q(G.distributionId);Z?.("complete","Deployment complete!");let z=W.skipped>0?`Deployed ${W.uploaded} files (${W.skipped} unchanged)`:`Deployed ${W.uploaded} files successfully`;return{...G,filesUploaded:W.uploaded,filesSkipped:W.skipped,message:z}}var J9=o(()=>{L1();I0();W2();o2();j2();Y9()});function HH($){let{bucketName:J,domain:Y,aliases:Z,certificateArn:Q,defaultRootObject:G="index.html",errorDocument:W="404.html",passthroughUrls:z=!1,singlePageApp:U=!1,dynamicApp:H=!1,computeOriginDomain:F,computeOriginPort:B=3008,computeOriginId:K="app-compute",retainOnStackDelete:O=!1}=$,V=O?{DeletionPolicy:"Retain",UpdateReplacePolicy:"Retain"}:{},A=H&&!!F,_=A?["GET","HEAD","OPTIONS","PUT","POST","PATCH","DELETE"]:["GET","HEAD"],M=A?["GET","HEAD"]:["GET","HEAD"],E={},j={};E.S3Bucket={Type:"AWS::S3::Bucket",...V,Properties:{BucketName:J,PublicAccessBlockConfiguration:{BlockPublicAcls:!0,BlockPublicPolicy:!1,IgnorePublicAcls:!0,RestrictPublicBuckets:!1},WebsiteConfiguration:{IndexDocument:G,ErrorDocument:W}}},j.BucketName={Description:"S3 Bucket Name",Value:{Ref:"S3Bucket"}},j.BucketArn={Description:"S3 Bucket ARN",Value:{"Fn::GetAtt":["S3Bucket","Arn"]}},E.CloudFrontOAC={Type:"AWS::CloudFront::OriginAccessControl",...V,Properties:{OriginAccessControlConfig:{Name:`OAC-${J}`,Description:`OAC for ${J}`,OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}};let q;if(z&&A)q="InstallRootRedirectFunction",E[q]={Type:"AWS::CloudFront::Function",Properties:{Name:{"Fn::Sub":"${AWS::StackName}-install-root-redirect"},AutoPublish:!0,FunctionConfig:{Comment:"Redirect curl pantry.dev | bash (GET /) to /install.sh on S3",Runtime:"cloudfront-js-2.0"},FunctionCode:`function handler(event) {
|
|
7233
7233
|
var request = event.request;
|
|
7234
7234
|
if (request.uri === '/' || request.uri === '') {
|
|
7235
7235
|
return {
|
|
@@ -7255,7 +7255,7 @@ ${Object.entries($).filter(([G])=>!G.startsWith("@_")).map(([G,W])=>Q(G,W," ","
|
|
|
7255
7255
|
}
|
|
7256
7256
|
|
|
7257
7257
|
return request;
|
|
7258
|
-
}`}};let T={Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},D=A?{Id:K,DomainName:F,CustomOriginConfig:{HTTPPort:B,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,S=A?K:`S3-${J}`,P={Enabled:!0,DefaultRootObject:G,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:D?[D,T]:[T],DefaultCacheBehavior:{TargetOriginId:S,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:_,CachedMethods:M,Compress:!0,...A?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...z&&q?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[q,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!z&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...A&&z?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:U?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300}]};if(Y&&Q)P.Aliases=Z&&Z.length>0?Z:[Y],P.ViewerCertificate={AcmCertificateArn:Q,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else P.ViewerCertificate={CloudFrontDefaultCertificate:!0};return E.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...V,DependsOn:["S3Bucket","CloudFrontOAC",...z&&A&&q?[q]:[],...!z?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:P}},j.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},j.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},E.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...V,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},j.SiteUrl={Description:"Site URL",Value:Y?`https://${Y}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J} (External DNS)`,Resources:E,Outputs:j}}async function B7($){let J=$.region||"us-east-1",Y="us-east-1",Z=$.domain,Q=$.bucket||Z.replace(/\./g,"-"),G=$.stackName||`${$.siteName}-static-site`,W=new K0("us-east-1"),z=new $1("us-east-1"),U=null;if(!$.skipDnsVerification){U=U1($.dnsProvider),console.log(`Verifying DNS provider can manage ${Z}...`);let C=await U.listRecords(Z);if(!C.success){let I=C.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:G,bucket:Q,message:`DNS provider '${U.name}' cannot manage domain ${Z}: ${I}`}}console.log(`DNS provider '${U.name}' verified for ${Z}`)}else console.log(`Skipping DNS verification for ${Z}`);let H=$.certificateArn,K=Z.split(".").length===2?`www.${Z}`:void 0;if(!H){console.log(`Checking for existing SSL certificate for ${Z}...`);let C=await z.findCertificateByDomain(Z),I=!1;if(C&&C.Status==="ISSUED"){if(K&&C.SubjectAlternativeNames)I=C.SubjectAlternativeNames.includes(K)||C.SubjectAlternativeNames.some((b)=>b===`*.${Z}`);else I=!0;if(I)H=C.CertificateArn,console.log(`Found existing certificate with www coverage: ${H}`);else console.log(`Existing certificate doesn't cover ${K}, requesting new one...`)}if(!H){if(!U)return{success:!1,stackName:G,bucket:Q,message:`No DNS provider available to validate SSL certificate for ${Z}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${Z}${K?` (including ${K})`:""}...`);let y=await new
|
|
7258
|
+
}`}};let T={Id:`S3-${J}`,DomainName:{"Fn::GetAtt":["S3Bucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},D=A?{Id:K,DomainName:F,CustomOriginConfig:{HTTPPort:B,HTTPSPort:443,OriginProtocolPolicy:"http-only",OriginSSLProtocols:["TLSv1.2"]}}:null,S=A?K:`S3-${J}`,P={Enabled:!0,DefaultRootObject:G,HttpVersion:"http2and3",IPV6Enabled:!0,PriceClass:"PriceClass_100",Origins:D?[D,T]:[T],DefaultCacheBehavior:{TargetOriginId:S,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:_,CachedMethods:M,Compress:!0,...A?{CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"b689b0a8-53d0-40ab-baf2-68738e2966ac",...z&&q?{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":[q,"FunctionARN"]}}]}:{}}:{CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",...!z&&{FunctionAssociations:[{EventType:"viewer-request",FunctionARN:{"Fn::GetAtt":["UrlRewriteFunction","FunctionARN"]}}]}}},...A&&z?{CacheBehaviors:[{PathPattern:"/install.sh",TargetOriginId:`S3-${J}`,ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD","OPTIONS"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6"}]}:{},CustomErrorResponses:U?[{ErrorCode:403,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:200,ResponsePagePath:`/${G}`,ErrorCachingMinTTL:300}]:[{ErrorCode:403,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300},{ErrorCode:404,ResponseCode:404,ResponsePagePath:`/${W}`,ErrorCachingMinTTL:300}]};if(Y&&Q)P.Aliases=Z&&Z.length>0?Z:[Y],P.ViewerCertificate={AcmCertificateArn:Q,SslSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021"};else P.ViewerCertificate={CloudFrontDefaultCertificate:!0};return E.CloudFrontDistribution={Type:"AWS::CloudFront::Distribution",...V,DependsOn:["S3Bucket","CloudFrontOAC",...z&&A&&q?[q]:[],...!z?["UrlRewriteFunction"]:[]],Properties:{DistributionConfig:P}},j.DistributionId={Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},j.DistributionDomain={Description:"CloudFront Distribution Domain",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},E.S3BucketPolicy={Type:"AWS::S3::BucketPolicy",...V,DependsOn:["S3Bucket","CloudFrontDistribution"],Properties:{Bucket:{Ref:"S3Bucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowCloudFrontServicePrincipal",Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${S3Bucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}},j.SiteUrl={Description:"Site URL",Value:Y?`https://${Y}`:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},{AWSTemplateFormatVersion:"2010-09-09",Description:`Static site infrastructure for ${Y||J} (External DNS)`,Resources:E,Outputs:j}}async function B7($){let J=$.region||"us-east-1",Y="us-east-1",Z=$.domain,Q=$.bucket||Z.replace(/\./g,"-"),G=$.stackName||`${$.siteName}-static-site`,W=new K0("us-east-1"),z=new $1("us-east-1"),U=null;if(!$.skipDnsVerification){U=U1($.dnsProvider),console.log(`Verifying DNS provider can manage ${Z}...`);let C=await U.listRecords(Z);if(!C.success){let I=C.message||"unknown error — check API credentials and domain ownership";return{success:!1,stackName:G,bucket:Q,message:`DNS provider '${U.name}' cannot manage domain ${Z}: ${I}`}}console.log(`DNS provider '${U.name}' verified for ${Z}`)}else console.log(`Skipping DNS verification for ${Z}`);let H=$.certificateArn,K=Z.split(".").length===2?`www.${Z}`:void 0;if(!H){console.log(`Checking for existing SSL certificate for ${Z}...`);let C=await z.findCertificateByDomain(Z),I=!1;if(C&&C.Status==="ISSUED"){if(K&&C.SubjectAlternativeNames)I=C.SubjectAlternativeNames.includes(K)||C.SubjectAlternativeNames.some((b)=>b===`*.${Z}`);else I=!0;if(I)H=C.CertificateArn,console.log(`Found existing certificate with www coverage: ${H}`);else console.log(`Existing certificate doesn't cover ${K}, requesting new one...`)}if(!H){if(!U)return{success:!1,stackName:G,bucket:Q,message:`No DNS provider available to validate SSL certificate for ${Z}. Provide a certificateArn or enable DNS verification.`};console.log(`Requesting new SSL certificate for ${Z}${K?` (including ${K})`:""}...`);let y=await new $$(U,"us-east-1").findOrCreateCertificate({domainName:Z,subjectAlternativeNames:K?[K]:void 0,waitForValidation:!0,maxWaitMinutes:10});if(y.status!=="issued")return{success:!1,stackName:G,bucket:Q,message:`SSL certificate validation failed. Status: ${y.status}`};H=y.certificateArn,console.log(`Certificate issued: ${H}`)}}let O=!1,V;try{let C=await W.describeStacks({stackName:G});if(C.Stacks.length>0){let I=C.Stacks[0],b=I.StackStatus;if(b==="DELETE_IN_PROGRESS")console.log("Previous stack is still being deleted, waiting..."),await W.waitForStack(G,"stack-delete-complete"),O=!1;else if(b==="DELETE_COMPLETE")O=!1;else O=!0,V=(I.Outputs||[]).find((c)=>c.OutputKey==="BucketName")?.OutputValue}}catch(C){if(C.message?.includes("does not exist")||C.code==="ValidationError")O=!1;else throw C}let A=V||Q;if(!O){let C=new W0(J),I=new w0,b=!1;if(Z)try{console.log(`Checking for existing CloudFront distributions with alias ${Z}...`);let y=await I.listDistributions();for(let c of y){let r=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))r=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let d=c.Aliases.Items.CNAME;if(typeof d==="string")r=[d];else if(Array.isArray(d))r=d}}if(r.includes(Z)){b=!0,console.log(`Found existing CloudFront distribution ${c.Id} with alias ${Z}`),console.log("Reusing existing infrastructure for updates...");let u=(await I.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,s;if(u){let J0=[];if(Array.isArray(u))J0=u;else if(u.Origin)J0=Array.isArray(u.Origin)?u.Origin:[u.Origin];else J0=[u];for(let t of J0){let e=(t.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(e){s=e[1];break}}}if(s)return console.log(`Using existing S3 bucket: ${s}`),{success:!0,stackName:`existing-${c.Id}`,bucket:s,distributionId:c.Id,distributionDomain:c.DomainName,domain:Z,certificateArn:H,message:"Using existing CloudFront distribution",_existingInfrastructure:!0}}}}catch{}if(!b)try{if((await C.headBucket(Q)).exists){console.log(`Found orphaned S3 bucket ${Q}, cleaning up...`);try{let c=C.emptyBucket(Q).then(()=>C.deleteBucket(Q)),r=new Promise((d,u)=>setTimeout(()=>u(Error("Bucket cleanup timeout")),30000));await Promise.race([c,r]),console.log(`Deleted orphaned S3 bucket ${Q}`)}catch(c){console.log(`Note: Could not clean up S3 bucket: ${c.message}`);let r=Date.now().toString(36);A=`${Q}-${r}`,console.log(`Using alternative bucket name: ${A}`)}}}catch{}}let M=HH({bucketName:A,domain:Z,aliases:K?[Z,K]:[Z],certificateArn:H,defaultRootObject:$.defaultRootObject,errorDocument:$.errorDocument,passthroughUrls:$.passthroughUrls,singlePageApp:$.singlePageApp,dynamicApp:$.dynamicApp,computeOriginDomain:$.computeOriginDomain,computeOriginPort:$.computeOriginPort,computeOriginId:$.computeOriginId}),E=Object.entries($.tags||{}).map(([C,I])=>({Key:C,Value:I}));if(E.push({Key:"ManagedBy",Value:"ts-cloud"}),E.push({Key:"Application",Value:$.siteName}),U)E.push({Key:"DnsProvider",Value:U.name});let j,q=!1;if(O){q=!0,console.log(`Updating CloudFormation stack: ${G}`);try{j=(await W.updateStack({stackName:G,templateBody:JSON.stringify(M),capabilities:["CAPABILITY_IAM"],tags:E})).StackId,console.log(`Update initiated, stack ID: ${j}`)}catch(C){if(C.message?.includes("No updates are to be performed")){let I=await W.describeStacks({stackName:G});j=I.Stacks[0].StackId;let b=I.Stacks[0]?.Outputs||[],y=(r)=>b.find((d)=>d.OutputKey===r)?.OutputValue,c=y("DistributionDomain");if(c)await JQ(U,Z,c);return{success:!0,stackId:j,stackName:G,bucket:y("BucketName")||A,distributionId:y("DistributionId"),distributionDomain:c,domain:Z,certificateArn:H,message:"Static site infrastructure is already up to date"}}else throw C}}else console.log(`Creating CloudFormation stack: ${G}`),console.log(`Bucket name: ${A}`),console.log(`Domain: ${Z}`),console.log(`Certificate ARN: ${H}`),j=(await W.createStack({stackName:G,templateBody:JSON.stringify(M),capabilities:["CAPABILITY_IAM"],tags:E,onFailure:"DELETE"})).StackId,console.log(`Create initiated, stack ID: ${j}`);console.log(`Waiting for stack to reach ${q?"stack-update-complete":"stack-create-complete"}...`);try{await W.waitForStack(G,q?"stack-update-complete":"stack-create-complete"),console.log("Stack operation completed successfully!")}catch(C){if(C.message?.includes("must be verified")||C.message?.includes("Access denied for operation")){console.log("CloudFront account verification required - checking for existing infrastructure...");try{let b=new w0,y=await b.listDistributions();for(let c of y){let r=[];if(c.Aliases?.Items){if(Array.isArray(c.Aliases.Items))r=c.Aliases.Items;else if(typeof c.Aliases.Items==="object"){let d=c.Aliases.Items.CNAME;if(typeof d==="string")r=[d];else if(Array.isArray(d))r=d}}if(r.includes(Z)){console.log(`Found existing CloudFront distribution ${c.Id} with alias ${Z}`),console.log("Using existing infrastructure despite account verification requirement...");let u=(await b.getDistributionConfig(c.Id)).DistributionConfig?.Origins?.Items,s;if(u){let J0=[];if(Array.isArray(u))J0=u;else if(u.Origin)J0=Array.isArray(u.Origin)?u.Origin:[u.Origin];else J0=[u];for(let t of J0){let e=(t.DomainName||"").match(/^([^.]+)\.s3[\.-]/);if(e){s=e[1];break}}}if(s){console.log(`Using existing S3 bucket: ${s}`);let J0=c.DomainName;if(J0)await JQ(U,Z,J0);return{success:!0,stackName:`existing-${c.Id}`,bucket:s,distributionId:c.Id,distributionDomain:c.DomainName,domain:Z,certificateArn:H,message:"Using existing CloudFront distribution (account verification pending for new distributions)"}}}}}catch{}return console.log(`
|
|
7259
7259
|
┌─────────────────────────────────────────────────────────────────────────────┐
|
|
7260
7260
|
│ AWS ACCOUNT VERIFICATION REQUIRED │
|
|
7261
7261
|
├─────────────────────────────────────────────────────────────────────────────┤
|
|
@@ -7273,9 +7273,9 @@ ${Object.entries($).filter(([G])=>!G.startsWith("@_")).map(([G,W])=>Q(G,W," ","
|
|
|
7273
7273
|
│ │
|
|
7274
7274
|
│ Verification typically takes 1-2 business days. │
|
|
7275
7275
|
│ After verification, re-run: bunx bunpress deploy │
|
|
7276
|
-
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:j,stackName:G,bucket:A,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:j,stackName:G,bucket:A,message:`Stack deployment failed: ${C.message}`}}let D=(await W.describeStacks({stackName:G})).Stacks[0]?.Outputs||[],S=(C)=>D.find((I)=>I.OutputKey===C)?.OutputValue,P=S("DistributionDomain");if(P&&U)console.log(`Creating DNS records via ${U.name}...`),await JQ(U,Z,P);else if(P&&!U)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:j,stackName:G,bucket:S("BucketName")||A,distributionId:S("DistributionId"),distributionDomain:P,domain:Z,certificateArn:H,message:"Static site infrastructure deployed successfully with external DNS"}}async function JQ($,J,Y){if(!$){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(J.split(".").length===2)if($ instanceof
|
|
7276
|
+
└─────────────────────────────────────────────────────────────────────────────┘`),{success:!1,stackId:j,stackName:G,bucket:A,message:"CloudFront account verification required. Please contact AWS Support."}}return{success:!1,stackId:j,stackName:G,bucket:A,message:`Stack deployment failed: ${C.message}`}}let D=(await W.describeStacks({stackName:G})).Stacks[0]?.Outputs||[],S=(C)=>D.find((I)=>I.OutputKey===C)?.OutputValue,P=S("DistributionDomain");if(P&&U)console.log(`Creating DNS records via ${U.name}...`),await JQ(U,Z,P);else if(P&&!U)console.log("Skipping DNS record creation (DNS verification was skipped)");return{success:!0,stackId:j,stackName:G,bucket:S("BucketName")||A,distributionId:S("DistributionId"),distributionDomain:P,domain:Z,certificateArn:H,message:"Static site infrastructure deployed successfully with external DNS"}}async function JQ($,J,Y){if(!$){console.log("Skipping DNS record creation (DNS verification was skipped)");return}if(J.split(".").length===2)if($ instanceof e2){console.log(`Creating Route53 alias record for apex domain ${J} -> ${Y}`);let G=await $.createCloudFrontAlias({domain:J,name:J,cloudFrontDomainName:Y});if(!G.success)console.warn(`Warning: Could not create Route53 alias record: ${G.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${J} -> ${Y}`);else console.log(`Created Route53 alias record: ${J} -> ${Y}`);let W=`www.${J}`;console.log(`Creating Route53 alias record for ${W} -> ${Y}`);let z=await $.createCloudFrontAlias({domain:J,name:W,cloudFrontDomainName:Y});if(!z.success)console.warn(`Warning: Could not create www Route53 alias: ${z.message}`),console.warn("Please manually create an A-record alias in Route53:"),console.warn(` ${W} -> ${Y}`);else console.log(`Created Route53 alias record: ${W} -> ${Y}`)}else{try{let U=await $.listRecords(J,"A");if(U.success)for(let H of U.records){let F=H.name.replace(/\.$/,"");if(F===J||F==="")console.log(`Removing existing root A record (${H.content}) to make room for ALIAS...`),await $.deleteRecord(J,{name:J,type:"A",content:H.content})}}catch(U){console.log(`Note: Could not check for conflicting A records: ${U instanceof Error?U.message:U}`)}console.log(`Creating ALIAS record for apex domain ${J} -> ${Y}`);let G=await $.upsertRecord(J,{name:J,type:"ALIAS",content:Y,ttl:600});if(!G.success)console.warn(`Warning: Could not create ALIAS record: ${G.message}`),console.warn("Please manually create an ALIAS record in your DNS provider:"),console.warn(` ${J} -> ${Y}`);else console.log(`Created ALIAS record: ${J} -> ${Y}`);let W=`www.${J}`;console.log(`Creating CNAME record for ${W} -> ${Y}`);let z=await $.upsertRecord(J,{name:W,type:"CNAME",content:Y,ttl:600});if(!z.success)console.warn(`Warning: Could not create www DNS record: ${z.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${W} -> ${Y}`);else console.log(`Created CNAME record: ${W} -> ${Y}`)}else{console.log(`Creating CNAME record for ${J} -> ${Y}`);let G=await $.upsertRecord(J,{name:J,type:"CNAME",content:Y,ttl:600});if(!G.success)console.warn(`Warning: Could not create DNS record: ${G.message}`),console.warn("Please manually create a CNAME record:"),console.warn(` ${J} -> ${Y}`);else console.log(`Created CNAME record: ${J} -> ${Y}`)}}async function K7($){let{sourceDir:J,cleanBucket:Y=!1,onProgress:Z,...Q}=$;Z?.("infrastructure","Deploying CloudFormation stack...");let G=await B7(Q);if(!G.success)return G;if(Y){Z?.("clean","Cleaning old files from S3...");try{await new W0(Q.region||"us-east-1").emptyBucket(G.bucket)}catch(H){console.log(`Note: Could not clean bucket: ${H.message}`)}}Z?.("upload","Uploading files to S3...");let{uploadStaticFiles:W}=await Promise.resolve().then(() => (J9(),X7)),z=await W({sourceDir:J,bucket:G.bucket,region:Q.region||"us-east-1",cacheControl:Q.cacheControl,onProgress:(H,F,B)=>{Z?.("upload",`${H}/${F}: ${B}`)}});if(z.errors.length>0)return{...G,success:!1,message:`Upload errors: ${z.errors.join(", ")}`,filesUploaded:z.uploaded};if(G.distributionId&&z.uploaded>0){Z?.("invalidate","Invalidating CloudFront cache...");let{invalidateCache:H}=await Promise.resolve().then(() => (J9(),X7));await H(G.distributionId)}Z?.("complete","Deployment complete!");let U=z.skipped>0?`Deployed ${z.uploaded} files (${z.skipped} unchanged) with external DNS`:`Deployed ${z.uploaded} files successfully with external DNS`;return{...G,filesUploaded:z.uploaded,filesSkipped:z.skipped,message:U}}var Y9=o(()=>{L1();I0();W2();j2();$2();w6();KJ()});var FH={};h0(FH,{EC2Client:()=>i0});class i0{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeInstances($){let J={Action:"DescribeInstances",Version:"2016-11-15"};if($?.InstanceIds)$.InstanceIds.forEach((Q,G)=>{J[`InstanceId.${G+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,G)=>{J[`Filter.${G+1}.Name`]=Q.Name,Q.Values.forEach((W,z)=>{J[`Filter.${G+1}.Value.${z+1}`]=W})});if($?.MaxResults)J.MaxResults=String($.MaxResults);if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.DescribeInstancesResponse||Y;return{Reservations:this.parseReservations(Z.reservationSet?.item),NextToken:Z.nextToken}}async getInstance($){return(await this.describeInstances({InstanceIds:[$]})).Reservations?.[0]?.Instances?.[0]}async getConsoleOutput($,J){let Y={Action:"GetConsoleOutput",Version:"2016-11-15",InstanceId:$};if(J)Y.Latest="true";let Z=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()}),Q=Z.GetConsoleOutputResponse||Z;return{InstanceId:Q.instanceId,Output:Q.output,Timestamp:Q.timestamp}}async getConsoleOutputDecoded($,J){let Y=await this.getConsoleOutput($,J?.latest);if(!Y.Output)return"No console output available yet";let Z=Buffer.from(Y.Output,"base64").toString("utf-8");if(J?.tailLines)return Z.split(`
|
|
7277
7277
|
`).slice(-J.tailLines).join(`
|
|
7278
|
-
`);return Z}async describeInstanceStatus($){let J={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if($?.InstanceIds)$.InstanceIds.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});if($?.IncludeAllInstances)J.IncludeAllInstances="true";if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InstanceStatuses:this.parseArray(Y.instanceStatusSet?.item).map((Z)=>({InstanceId:Z.instanceId,InstanceState:Z.instanceState?{Code:Number.parseInt(Z.instanceState.code),Name:Z.instanceState.name}:void 0,InstanceStatus:Z.instanceStatus?{Status:Z.instanceStatus.status,Details:this.parseArray(Z.instanceStatus.details?.item).map((Q)=>({Name:Q.name,Status:Q.status}))}:void 0,SystemStatus:Z.systemStatus?{Status:Z.systemStatus.status,Details:this.parseArray(Z.systemStatus.details?.item).map((Q)=>({Name:Q.name,Status:Q.status}))}:void 0}))}}async startInstances($){let J={Action:"StartInstances",Version:"2016-11-15"};$.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{StartingInstances:this.parseArray(Y.instancesSet?.item).map((Z)=>({InstanceId:Z.instanceId,CurrentState:Z.currentState?{Name:Z.currentState.name}:void 0,PreviousState:Z.previousState?{Name:Z.previousState.name}:void 0}))}}async stopInstances($,J){let Y={Action:"StopInstances",Version:"2016-11-15"};if($.forEach((Q,G)=>{Y[`InstanceId.${G+1}`]=Q}),J)Y.Force="true";let Z=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()});return{StoppingInstances:this.parseArray(Z.instancesSet?.item).map((Q)=>({InstanceId:Q.instanceId,CurrentState:Q.currentState?{Name:Q.currentState.name}:void 0,PreviousState:Q.previousState?{Name:Q.previousState.name}:void 0}))}}async rebootInstances($){let J={Action:"RebootInstances",Version:"2016-11-15"};$.forEach((Y,Z)=>{J[`InstanceId.${Z+1}`]=Y}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async terminateInstances($){let J={Action:"TerminateInstances",Version:"2016-11-15"};$.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{TerminatingInstances:this.parseArray(Y.instancesSet?.item).map((Z)=>({InstanceId:Z.instanceId,CurrentState:Z.currentState?{Name:Z.currentState.name}:void 0,PreviousState:Z.previousState?{Name:Z.previousState.name}:void 0}))}}async createImage($){let J={Action:"CreateImage",Version:"2016-11-15",InstanceId:$.InstanceId,Name:$.Name};if($.Description)J.Description=$.Description;if($.NoReboot!==void 0)J.NoReboot=String($.NoReboot);if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{ImageId:(Y.CreateImageResponse||Y).imageId}}async deregisterImage($){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:$}).toString()})}async describeVpcs($){let J={Action:"DescribeVpcs",Version:"2016-11-15"};if($?.VpcIds)$.VpcIds.forEach((Z,Q)=>{J[`VpcId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Vpcs:this.parseArray(Y.vpcSet?.item).map((Z)=>({VpcId:Z.vpcId,CidrBlock:Z.cidrBlock,State:Z.state,DhcpOptionsId:Z.dhcpOptionsId,InstanceTenancy:Z.instanceTenancy,IsDefault:Z.isDefault==="true",Tags:this.parseTags(Z.tagSet?.item)}))}}async describeSubnets($){let J={Action:"DescribeSubnets",Version:"2016-11-15"};if($?.SubnetIds)$.SubnetIds.forEach((Z,Q)=>{J[`SubnetId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Subnets:this.parseArray(Y.subnetSet?.item).map((Z)=>({SubnetId:Z.subnetId,VpcId:Z.vpcId,CidrBlock:Z.cidrBlock,AvailabilityZone:Z.availabilityZone,AvailableIpAddressCount:Number.parseInt(Z.availableIpAddressCount),State:Z.state,MapPublicIpOnLaunch:Z.mapPublicIpOnLaunch==="true",Tags:this.parseTags(Z.tagSet?.item)}))}}async describeSecurityGroups($){let J={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if($?.GroupIds)$.GroupIds.forEach((Z,Q)=>{J[`GroupId.${Q+1}`]=Z});if($?.GroupNames)$.GroupNames.forEach((Z,Q)=>{J[`GroupName.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{SecurityGroups:this.parseArray(Y.securityGroupInfo?.item).map((Z)=>({GroupId:Z.groupId,GroupName:Z.groupName,Description:Z.groupDescription,VpcId:Z.vpcId,IpPermissions:this.parseIpPermissions(Z.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(Z.ipPermissionsEgress?.item),Tags:this.parseTags(Z.tagSet?.item)}))}}async describeInternetGateways($){let J={Action:"DescribeInternetGateways",Version:"2016-11-15"};if($?.InternetGatewayIds)$.InternetGatewayIds.forEach((Z,Q)=>{J[`InternetGatewayId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InternetGateways:this.parseArray(Y.internetGatewaySet?.item).map((Z)=>({InternetGatewayId:Z.internetGatewayId,Attachments:this.parseArray(Z.attachmentSet?.item).map((Q)=>({VpcId:Q.vpcId,State:Q.state})),Tags:this.parseTags(Z.tagSet?.item)}))}}async describeAddresses($){let J={Action:"DescribeAddresses",Version:"2016-11-15"};if($?.AllocationIds)$.AllocationIds.forEach((Z,Q)=>{J[`AllocationId.${Q+1}`]=Z});if($?.PublicIps)$.PublicIps.forEach((Z,Q)=>{J[`PublicIp.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Addresses:this.parseArray(Y.addressesSet?.item).map((Z)=>({PublicIp:Z.publicIp,AllocationId:Z.allocationId,AssociationId:Z.associationId,InstanceId:Z.instanceId,NetworkInterfaceId:Z.networkInterfaceId,PrivateIpAddress:Z.privateIpAddress,Domain:Z.domain,Tags:this.parseTags(Z.tagSet?.item)}))}}async allocateAddress($){let J={Action:"AllocateAddress",Version:"2016-11-15"};if($?.Domain)J.Domain=$.Domain;if($?.TagSpecifications)$.TagSpecifications.forEach((Z,Q)=>{J[`TagSpecification.${Q+1}.ResourceType`]=Z.ResourceType,Z.Tags.forEach((G,W)=>{J[`TagSpecification.${Q+1}.Tag.${W+1}.Key`]=G.Key,J[`TagSpecification.${Q+1}.Tag.${W+1}.Value`]=G.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{AllocationId:Y.allocationId,PublicIp:Y.publicIp,Domain:Y.domain}}async associateAddress($){let J={Action:"AssociateAddress",Version:"2016-11-15"};if($.AllocationId)J.AllocationId=$.AllocationId;if($.PublicIp)J.PublicIp=$.PublicIp;if($.InstanceId)J.InstanceId=$.InstanceId;if($.NetworkInterfaceId)J.NetworkInterfaceId=$.NetworkInterfaceId;if($.PrivateIpAddress)J.PrivateIpAddress=$.PrivateIpAddress;if($.AllowReassociation)J.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})).associationId}}async createTags($){let J={Action:"CreateTags",Version:"2016-11-15"};$.Resources.forEach((Y,Z)=>{J[`ResourceId.${Z+1}`]=Y}),$.Tags.forEach((Y,Z)=>{J[`Tag.${Z+1}.Key`]=Y.Key,J[`Tag.${Z+1}.Value`]=Y.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async waitForInstanceState($,J,Y){let Z=Y?.maxWaitMs||300000,Q=Y?.pollIntervalMs||5000,G=Date.now();while(Date.now()-G<Z){let W;try{W=await this.getInstance($)}catch{W=void 0}if(W?.State?.Name===J)return W;await new Promise((z)=>setTimeout(z,Q))}return}async createVpc($){let J={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:$.CidrBlock};if($.InstanceTenancy)J.InstanceTenancy=$.InstanceTenancy;if($.TagSpecifications)$.TagSpecifications.forEach((G,W)=>{J[`TagSpecification.${W+1}.ResourceType`]=G.ResourceType,G.Tags.forEach((z,U)=>{J[`TagSpecification.${W+1}.Tag.${U+1}.Key`]=z.Key,J[`TagSpecification.${W+1}.Tag.${U+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=(Y.CreateVpcResponse||Y).vpc;return{Vpc:Q?{VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,State:Q.state,DhcpOptionsId:Q.dhcpOptionsId,InstanceTenancy:Q.instanceTenancy,IsDefault:Q.isDefault==="true",Tags:this.parseTags(Q.tagSet?.item)}:void 0}}async createSubnet($){let J={Action:"CreateSubnet",Version:"2016-11-15",VpcId:$.VpcId,CidrBlock:$.CidrBlock};if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.TagSpecifications)$.TagSpecifications.forEach((G,W)=>{J[`TagSpecification.${W+1}.ResourceType`]=G.ResourceType,G.Tags.forEach((z,U)=>{J[`TagSpecification.${W+1}.Tag.${U+1}.Key`]=z.Key,J[`TagSpecification.${W+1}.Tag.${U+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=(Y.CreateSubnetResponse||Y).subnet;return{Subnet:Q?{SubnetId:Q.subnetId,VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,AvailabilityZone:Q.availabilityZone,AvailableIpAddressCount:Q.availableIpAddressCount?Number.parseInt(Q.availableIpAddressCount):void 0,State:Q.state,MapPublicIpOnLaunch:Q.mapPublicIpOnLaunch==="true",Tags:this.parseTags(Q.tagSet?.item)}:void 0}}async modifySubnetAttribute($){let J={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:$.SubnetId};if($.MapPublicIpOnLaunch!==void 0)J["MapPublicIpOnLaunch.Value"]=String($.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async createSecurityGroup($){let J={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:$.GroupName,GroupDescription:$.Description};if($.VpcId)J.VpcId=$.VpcId;if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{GroupId:(Y.CreateSecurityGroupResponse||Y).groupId}}async authorizeSecurityGroupIngress($){let J={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async authorizeSecurityGroupEgress($){let J={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async describeRouteTables($){let J={Action:"DescribeRouteTables",Version:"2016-11-15"};if($?.RouteTableIds)$.RouteTableIds.forEach((Q,G)=>{J[`RouteTableId.${G+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,G)=>{J[`Filter.${G+1}.Name`]=Q.Name,Q.Values.forEach((W,z)=>{J[`Filter.${G+1}.Value.${z+1}`]=W})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.DescribeRouteTablesResponse||Y;return{RouteTables:this.parseArray(Z.routeTableSet?.item).map((Q)=>({RouteTableId:Q.routeTableId,VpcId:Q.vpcId,Routes:this.parseArray(Q.routeSet?.item).map((G)=>({DestinationCidrBlock:G.destinationCidrBlock,GatewayId:G.gatewayId,NatGatewayId:G.natGatewayId,State:G.state})),Associations:this.parseArray(Q.associationSet?.item).map((G)=>({RouteTableAssociationId:G.routeTableAssociationId,SubnetId:G.subnetId,Main:G.main==="true"||G.main===!0})),Tags:this.parseTags(Q.tagSet?.item)}))}}async deleteVpc($){let J={Action:"DeleteVpc",Version:"2016-11-15",VpcId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async deleteSubnet($){let J={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async deleteSecurityGroup($){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:$}).toString()})}async describeNetworkInterfaces($){let J={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if($?.NetworkInterfaceIds)$.NetworkInterfaceIds.forEach((Q,G)=>{J[`NetworkInterfaceId.${G+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,G)=>{J[`Filter.${G+1}.Name`]=Q.Name,Q.Values.forEach((W,z)=>{J[`Filter.${G+1}.Value.${z+1}`]=W})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.DescribeNetworkInterfacesResponse||Y;return{NetworkInterfaces:this.parseArray(Z.networkInterfaceSet?.item).map((Q)=>({NetworkInterfaceId:Q.networkInterfaceId,SubnetId:Q.subnetId,VpcId:Q.vpcId,Status:Q.status,Attachment:Q.attachment?{AttachmentId:Q.attachment.attachmentId,InstanceId:Q.attachment.instanceId,Status:Q.attachment.status}:void 0}))}}async detachNetworkInterface($,J){let Y={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:$};if(J)Y.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()})}async deleteNetworkInterface($){let J={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async describeRegions(){let $={Action:"DescribeRegions",Version:"2016-11-15"},J=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams($).toString()}),Y=J.DescribeRegionsResponse||J;return{Regions:this.parseArray(Y.regionInfo?.item).map((Z)=>({RegionName:Z.regionName,Endpoint:Z.regionEndpoint}))}}async runInstances($){let J={Action:"RunInstances",Version:"2016-11-15",ImageId:$.ImageId,InstanceType:$.InstanceType,MinCount:String($.MinCount),MaxCount:String($.MaxCount)};if($.SecurityGroupIds)$.SecurityGroupIds.forEach((Q,G)=>{J[`SecurityGroupId.${G+1}`]=Q});if($.SubnetId)J.SubnetId=$.SubnetId;if($.UserData)J.UserData=$.UserData;if($.IamInstanceProfile){if($.IamInstanceProfile.Name)J["IamInstanceProfile.Name"]=$.IamInstanceProfile.Name;if($.IamInstanceProfile.Arn)J["IamInstanceProfile.Arn"]=$.IamInstanceProfile.Arn}if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.RunInstancesResponse||Y;return{Instances:this.parseInstances(Z.instancesSet?.item||Z.instancesSet)}}encodeIpPermissions($,J){J.forEach((Y,Z)=>{let Q=`IpPermissions.${Z+1}`;if(Y.IpProtocol!==void 0)$[`${Q}.IpProtocol`]=Y.IpProtocol;if(Y.FromPort!==void 0)$[`${Q}.FromPort`]=String(Y.FromPort);if(Y.ToPort!==void 0)$[`${Q}.ToPort`]=String(Y.ToPort);if(Y.IpRanges)Y.IpRanges.forEach((G,W)=>{if(G.CidrIp)$[`${Q}.IpRanges.${W+1}.CidrIp`]=G.CidrIp;if(G.Description)$[`${Q}.IpRanges.${W+1}.Description`]=G.Description});if(Y.Ipv6Ranges)Y.Ipv6Ranges.forEach((G,W)=>{if(G.CidrIpv6)$[`${Q}.Ipv6Ranges.${W+1}.CidrIpv6`]=G.CidrIpv6;if(G.Description)$[`${Q}.Ipv6Ranges.${W+1}.Description`]=G.Description});if(Y.UserIdGroupPairs)Y.UserIdGroupPairs.forEach((G,W)=>{if(G.GroupId)$[`${Q}.Groups.${W+1}.GroupId`]=G.GroupId;if(G.UserId)$[`${Q}.Groups.${W+1}.UserId`]=G.UserId;if(G.Description)$[`${Q}.Groups.${W+1}.Description`]=G.Description})})}parseArray($){if(!$)return[];return Array.isArray($)?$:[$]}parseTags($){return this.parseArray($).map((J)=>({Key:J.key,Value:J.value}))}parseReservations($){return this.parseArray($).map((J)=>({ReservationId:J.reservationId,Instances:this.parseInstances(J.instancesSet?.item||J.instancesSet)}))}parseInstances($){return this.parseArray($).map((J)=>({InstanceId:J.instanceId,ImageId:J.imageId,InstanceType:J.instanceType,State:J.instanceState?{Code:Number.parseInt(J.instanceState.code),Name:J.instanceState.name}:void 0,PrivateIpAddress:J.privateIpAddress,PublicIpAddress:J.ipAddress,SubnetId:J.subnetId,VpcId:J.vpcId,SecurityGroups:this.parseArray(J.groupSet?.item).map((Y)=>({GroupId:Y.groupId,GroupName:Y.groupName})),Tags:this.parseTags(J.tagSet?.item),LaunchTime:J.launchTime,Placement:J.placement?{AvailabilityZone:J.placement.availabilityZone,Tenancy:J.placement.tenancy}:void 0,Architecture:J.architecture,RootDeviceType:J.rootDeviceType,RootDeviceName:J.rootDeviceName,BlockDeviceMappings:this.parseArray(J.blockDeviceMapping?.item).map((Y)=>({DeviceName:Y.deviceName,Ebs:Y.ebs?{VolumeId:Y.ebs.volumeId,Status:Y.ebs.status,AttachTime:Y.ebs.attachTime,DeleteOnTermination:Y.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:J.iamInstanceProfile?{Arn:J.iamInstanceProfile.arn,Id:J.iamInstanceProfile.id}:void 0}))}parseIpPermissions($){return this.parseArray($).map((J)=>({IpProtocol:J.ipProtocol,FromPort:J.fromPort?Number.parseInt(J.fromPort):void 0,ToPort:J.toPort?Number.parseInt(J.toPort):void 0,IpRanges:this.parseArray(J.ipRanges?.item).map((Y)=>({CidrIp:Y.cidrIp,Description:Y.description})),Ipv6Ranges:this.parseArray(J.ipv6Ranges?.item).map((Y)=>({CidrIpv6:Y.cidrIpv6,Description:Y.description})),UserIdGroupPairs:this.parseArray(J.groups?.item).map((Y)=>({GroupId:Y.groupId,UserId:Y.userId,Description:Y.description}))}))}}var Z9=o(()=>{Y0()});class Q9{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async putParameter($){let J={Name:$.Name,Value:$.Value};if($.Type)J.Type=$.Type;if($.Description)J.Description=$.Description;if($.KeyId)J.KeyId=$.KeyId;if($.Overwrite!==void 0)J.Overwrite=$.Overwrite;if($.AllowedPattern)J.AllowedPattern=$.AllowedPattern;if($.Tags&&$.Tags.length>0)J.Tags=$.Tags;if($.Tier)J.Tier=$.Tier;if($.DataType)J.DataType=$.DataType;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Version:Y.Version,Tier:Y.Tier}}async getParameter($){let J={Name:$.Name};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameter:Y.Parameter?this.parseParameter(Y.Parameter):void 0}}async getParameters($){let J={Names:$.Names};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),InvalidParameters:Y.InvalidParameters}}async getParametersByPath($){let J={Path:$.Path};if($.Recursive!==void 0)J.Recursive=$.Recursive;if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;if($.MaxResults)J.MaxResults=$.MaxResults;if($.NextToken)J.NextToken=$.NextToken;if($.ParameterFilters&&$.ParameterFilters.length>0)J.ParameterFilters=$.ParameterFilters;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:Y.NextToken}}async deleteParameter($){let J={Name:$.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteParameters($){let J={Names:$},Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{DeletedParameters:Y.DeletedParameters,InvalidParameters:Y.InvalidParameters}}async describeParameters($){let J={};if($?.Filters&&$.Filters.length>0)J.Filters=$.Filters;if($?.ParameterFilters&&$.ParameterFilters.length>0)J.ParameterFilters=$.ParameterFilters;if($?.MaxResults)J.MaxResults=$.MaxResults;if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:Y.NextToken}}async getParameterHistory($){let J={Name:$.Name};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;if($.MaxResults)J.MaxResults=$.MaxResults;if($.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>({Name:Z.Name,Type:Z.Type,KeyId:Z.KeyId,LastModifiedDate:Z.LastModifiedDate,LastModifiedUser:Z.LastModifiedUser,Description:Z.Description,Value:Z.Value,Version:Z.Version,Labels:Z.Labels,Tier:Z.Tier})),NextToken:Y.NextToken}}async labelParameterVersion($){let J={Name:$.Name,Labels:$.Labels};if($.ParameterVersion!==void 0)J.ParameterVersion=$.ParameterVersion;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{InvalidLabels:Y.InvalidLabels,ParameterVersion:Y.ParameterVersion}}async addTagsToResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId,Tags:$.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async removeTagsFromResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId,TagKeys:$.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTagsForResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).TagList}}async setString($,J,Y){return this.putParameter({Name:$,Value:J,Type:"String",Description:Y?.description,Overwrite:Y?.overwrite??!0,Tags:Y?.tags})}async setSecureString($,J,Y){return this.putParameter({Name:$,Value:J,Type:"SecureString",Description:Y?.description,Overwrite:Y?.overwrite??!0,KeyId:Y?.kmsKeyId,Tags:Y?.tags})}async getValue($){return(await this.getParameter({Name:$,WithDecryption:!0})).Parameter?.Value}async getAllByPath($,J=!0){let Y=[],Z;do{let Q=await this.getParametersByPath({Path:$,Recursive:J,WithDecryption:!0,NextToken:Z});if(Q.Parameters)Y.push(...Q.Parameters);Z=Q.NextToken}while(Z);return Y}parseParameter($){return{Name:$.Name,Type:$.Type,Value:$.Value,Version:$.Version,LastModifiedDate:$.LastModifiedDate,ARN:$.ARN,DataType:$.DataType,Description:$.Description,AllowedPattern:$.AllowedPattern,KeyId:$.KeyId,Tier:$.Tier}}async sendCommand($){if(!$.InstanceIds&&!$.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let J={DocumentName:$.DocumentName};if($.InstanceIds)J.InstanceIds=$.InstanceIds;if($.Targets)J.Targets=$.Targets;if($.Parameters)J.Parameters=$.Parameters;if($.TimeoutSeconds)J.TimeoutSeconds=$.TimeoutSeconds;if($.Comment)J.Comment=$.Comment;if($.OutputS3BucketName)J.OutputS3BucketName=$.OutputS3BucketName;if($.OutputS3KeyPrefix)J.OutputS3KeyPrefix=$.OutputS3KeyPrefix;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{CommandId:Y.Command?.CommandId,Status:Y.Command?.Status,StatusDetails:Y.Command?.StatusDetails}}async getCommandInvocation($){let J={CommandId:$.CommandId,InstanceId:$.InstanceId},Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Status:Y.Status,StatusDetails:Y.StatusDetails,StandardOutputContent:Y.StandardOutputContent,StandardErrorContent:Y.StandardErrorContent,ResponseCode:Y.ResponseCode}}async runShellCommand($,J,Y){let Z=await this.sendCommand({InstanceIds:[$],DocumentName:"AWS-RunShellScript",Parameters:{commands:J},TimeoutSeconds:Y?.timeoutSeconds||600});if(!Z.CommandId)return{success:!1,error:"Failed to send command"};if(Y?.waitForCompletion===!1)return{success:!0,status:"Pending"};let Q=Y?.pollIntervalMs||2000,G=Y?.maxWaitMs||300000,W=Date.now();while(Date.now()-W<G){await new Promise((z)=>setTimeout(z,Q));try{let z=await this.getCommandInvocation({CommandId:Z.CommandId,InstanceId:$});if(z.Status==="Success")return{success:!0,output:z.StandardOutputContent,error:z.StandardErrorContent,status:z.Status};if(z.Status==="Failed"||z.Status==="Cancelled"||z.Status==="TimedOut")return{success:!1,output:z.StandardOutputContent,error:z.StandardErrorContent||z.StatusDetails,status:z.Status}}catch(z){if(!z.message?.includes("InvocationDoesNotExist"))return{success:!1,error:z.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations($){let J={CommandId:$.CommandId};if($.Details)J.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).CommandInvocations||[]).map((Q)=>({InstanceId:Q.InstanceId,Status:Q.Status,StatusDetails:Q.StatusDetails,StandardOutputContent:Q.CommandPlugins?.[0]?.Output,StandardErrorContent:Q.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags($){let J=Object.entries($.tags).map(([U,H])=>({Key:`tag:${U}`,Values:[H]})),Y=await this.sendCommand({Targets:J,DocumentName:"AWS-RunShellScript",Parameters:{commands:$.commands},TimeoutSeconds:$.timeoutSeconds||600,Comment:$.comment});if(!Y.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let Z=$.pollIntervalMs||3000,Q=$.maxWaitMs||600000,G=Date.now(),W=new Set(["Success","Failed","Cancelled","TimedOut"]),z=[];while(Date.now()-G<Q){await new Promise((U)=>setTimeout(U,Z));try{if(z=await this.listCommandInvocations({CommandId:Y.CommandId,Details:!0}),z.length===0)continue;if(z.every((H)=>W.has(H.Status||""))){let H=z.map((B)=>({instanceId:B.InstanceId,status:B.Status||"Unknown",output:B.StandardOutputContent,error:B.StandardErrorContent||B.StatusDetails})),F=z.every((B)=>B.Status==="Success");return{success:F,instanceCount:z.length,perInstance:H,error:F?void 0:"One or more instances reported a non-success status"}}}catch(U){if(!U.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:U.message}}}return{success:!1,instanceCount:z.length,perInstance:z.map((U)=>({instanceId:U.InstanceId,status:U.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}var ZQ=o(()=>{Y0()});function A7($){return`'${$.split("'").join("'\\''")}'`}function V7($={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",$.version?`export PANTRY_VERSION=${A7($.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)","command -v pantry >/dev/null 2>&1 || curl -fsSL https://pantry.dev | bash",'export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function X$(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function a$($){if($.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set($)].map(A7).join(" ")})`]}function _7($){return[...new Set($)].flatMap((J)=>[`(cd /opt/pantry && pantry start ${A7(J)})`,`(cd /opt/pantry && pantry enable ${A7(J)})`])}var XH,S1="/opt/pantry";var z2=o(()=>{XH={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"}});function T2($){return $===!0||typeof $==="object"&&$!=null}function Kq($){let J=[],Y=[];if(T2($.mysql))J.push(typeof $.mysql==="object"&&$.mysql.version?`mysql.com@${$.mysql.version}`:"mysql.com@8.0.43"),Y.push("mysql");else if(T2($.mariadb))J.push(XH.mariadb),Y.push("mariadb");if(T2($.postgres))J.push("postgresql.org"),Y.push("postgres");if(T2($.redis))J.push("redis.io"),Y.push("redis");if(T2($.memcached))J.push("memcached.org"),Y.push("memcached");if(T2($.meilisearch))J.push("meilisearch.com"),Y.push("meilisearch");return{packages:J,services:Y}}function j7($={},J={}){let Y=Kq($);if(Y.packages.length===0)return[];return[...a$(Y.packages),..._7(Y.services)]}function L7($,J={}){if(!$?.name)return[];if($.host&&$.host!=="127.0.0.1"&&$.host!=="localhost")return[];let Y=$.name,Z=$.username||Y,Q=$.password||"",G=T2(J.postgres)||$.engine==="postgres",W=T2(J.mariadb)||$.engine==="mariadb",z=T2(J.mysql)||$.engine==="mysql";if(G&&!z&&!W){let O=(E)=>`"${E.replace(/"/g,'""')}"`,V=(E)=>`'${E.replace(/'/g,"''")}'`,A=(E,j)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${V(E)}) THEN`,` CREATE ROLE ${O(E)} LOGIN PASSWORD ${V(j)};`," ELSE",` ALTER ROLE ${O(E)} LOGIN PASSWORD ${V(j)};`," END IF;","END $$;"],_=(E)=>{let j=E.databases&&E.databases.length>0?E.databases:[Y],q=[];for(let T of j)if(E.access==="readonly")q.push(`GRANT CONNECT ON DATABASE ${O(T)} TO ${O(E.username)};`,`\\connect ${O(T)}`,`GRANT USAGE ON SCHEMA public TO ${O(E.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${O(E.username)};`,`ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO ${O(E.username)};`,"\\connect postgres");else q.push(`GRANT ALL PRIVILEGES ON DATABASE ${O(T)} TO ${O(E.username)};`);return q},M=$.users||[];return[X$(),"for i in $(seq 1 30); do pg_isready -h 127.0.0.1 -p 5432 -q && break; sleep 2; done","psql -h 127.0.0.1 -p 5432 -U postgres <<'TS_CLOUD_PG_EOF'",...A(Z,Q),`SELECT 'CREATE DATABASE ${O(Y)} OWNER ${O(Z)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${V(Y)})\\gexec`,...M.flatMap((E)=>[...A(E.username,E.password),..._(E)]),"TS_CLOUD_PG_EOF"]}let U=W?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",H=(O)=>O.replace(/`/g,"``"),F=(O)=>O.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),B=(O)=>{let V=O.databases&&O.databases.length>0?O.databases:[Y],A=O.access==="readonly"?"SELECT":"ALL PRIVILEGES",_=[`CREATE USER IF NOT EXISTS '${F(O.username)}'@'%' IDENTIFIED BY '${F(O.password)}';`,`CREATE USER IF NOT EXISTS '${F(O.username)}'@'localhost' IDENTIFIED BY '${F(O.password)}';`,`ALTER USER '${F(O.username)}'@'%' IDENTIFIED BY '${F(O.password)}';`,`ALTER USER '${F(O.username)}'@'localhost' IDENTIFIED BY '${F(O.password)}';`];for(let M of V)_.push(`GRANT ${A} ON \`${H(M)}\`.* TO '${F(O.username)}'@'%';`,`GRANT ${A} ON \`${H(M)}\`.* TO '${F(O.username)}'@'localhost';`);return _},K=$.users||[];return[X$(),`for i in $(seq 1 30); do mysqladmin --socket=${U} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${U} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${H(Y)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...B({username:Z,password:Q}),...K.flatMap(B),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function BH($){if(!$?.name)return{};let J=$.engine==="postgres"?"pgsql":"mysql",Y=$.port??($.engine==="postgres"?5432:3306),Z={DB_CONNECTION:J,DB_HOST:$.host||"127.0.0.1",DB_PORT:String(Y),DB_DATABASE:$.name};if($.username)Z.DB_USERNAME=$.username;if($.password)Z.DB_PASSWORD=$.password;return Z}var E7=o(()=>{z2()});function KH($){return Aq}function Vq($={}){let J=$.versions?.length?$.versions:["8.3"];return $.default&&J.includes($.default)?$.default:J[0]}function _q($={}){return{...$.optimizeForProduction===!1?{}:{...Oq},...$.ini||{}}}function jq($={}){let J=_q($),Y=Object.keys(J);if(Y.length===0)return[];let Z=Y.map((G)=>`${G}=${J[G]}`),Q="ts-cloud-managed";return[X$(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} — production PHP tuning`,...Z,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${Q} BEGIN/,/; ${Q} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} BEGIN`,...Z,`; ${Q} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`]}function M7($={}){let J=Vq($),Y=$.installNginx!==!1,Z=$.installComposer!==!1,Q=[`php.net@${J}`];if(Z)Q.push("getcomposer.org");if(Y)Q.push("nginx.org");return[...a$(Q),..._7(["php-fpm"]),...jq($)]}var Oq,Aq="127.0.0.1:9074";var q7=o(()=>{z2();Oq={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"}});function QQ($,J){if(!$)return[];let Y=[];if($.template&&J?.[$.template])Y.push(...J[$.template]);if($.serverSnippet)Y.push(...$.serverSnippet);return Y}function Lq($){if(!$)return"";let J=typeof $==="object"?$:{},Z=[`max-age=${J.maxAge??31536000}`];if(J.includeSubDomains??!0)Z.push("includeSubDomains");if(J.preload)Z.push("preload");return` add_header Strict-Transport-Security "${Z.join("; ")}" always;`}function Eq($){if(!$||!$.allow?.length&&!$.deny?.length)return[];let J=[];for(let Y of $.deny||[])J.push(` deny ${Y};`);if($.allow?.length){for(let Y of $.allow)J.push(` allow ${Y};`);J.push(" deny all;")}return J}function OH($){return`/etc/nginx/.htpasswd-${$}`}function qq($){return Mq.has($)}function Tq($){return $==="laravel"||$==="statamic"?"public":""}function wq($,J){let Y=$.replace(/\/+$/,""),Z=J.replace(/^\/+|\/+$/g,"");return Z?`${Y}/${Z}`:Y}function Dq($){let J=$.type??"laravel",Y=$.webDirectory??Tq(J),Z=wq($.appDir,Y),Q=qq(J),G=$.phpVersion??"8.3",W=[` root ${Z};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],z=Lq($.hsts);if(z)W.push(z);for(let U of Eq($.security))W.push(U);if(W.push("",` index ${Q?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),$.clientMaxBodySize)W.push(` client_max_body_size ${$.clientMaxBodySize};`,"");if($.auth)W.push(` auth_basic "${$.auth.realm||"Restricted"}";`,` auth_basic_user_file ${OH($.siteName)};`,"");for(let[U,H]of Object.entries($.redirects||{}))W.push(` location = ${U} { return 301 ${H}; }`);if(Object.keys($.redirects||{}).length>0)W.push("");if(Q){if(W.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${$.fastcgiPass??KH(G)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),J==="wordpress")W.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(J==="spa")W.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else W.push(" location / {"," try_files $uri $uri/ =404;"," }");if($.serverSnippet&&$.serverSnippet.length>0){W.push("");for(let U of $.serverSnippet)W.push(U?` ${U}`:"")}return W}function Rq($){let J=[$.domain,...$.aliases||[]].filter(Boolean).join(" "),Y=Dq($);if($.ssl){let Q=["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`," return 301 https://$host$request_uri;","}"],G=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${J};`,` ssl_certificate ${$.ssl.certPath};`,` ssl_certificate_key ${$.ssl.keyPath};`,...$.tlsProtocols?.length?[` ssl_protocols ${$.tlsProtocols.join(" ")};`]:[],"",...Y,"}"];return`${[...Q,"",...G].join(`
|
|
7278
|
+
`);return Z}async describeInstanceStatus($){let J={Action:"DescribeInstanceStatus",Version:"2016-11-15"};if($?.InstanceIds)$.InstanceIds.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});if($?.IncludeAllInstances)J.IncludeAllInstances="true";if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InstanceStatuses:this.parseArray(Y.instanceStatusSet?.item).map((Z)=>({InstanceId:Z.instanceId,InstanceState:Z.instanceState?{Code:Number.parseInt(Z.instanceState.code),Name:Z.instanceState.name}:void 0,InstanceStatus:Z.instanceStatus?{Status:Z.instanceStatus.status,Details:this.parseArray(Z.instanceStatus.details?.item).map((Q)=>({Name:Q.name,Status:Q.status}))}:void 0,SystemStatus:Z.systemStatus?{Status:Z.systemStatus.status,Details:this.parseArray(Z.systemStatus.details?.item).map((Q)=>({Name:Q.name,Status:Q.status}))}:void 0}))}}async startInstances($){let J={Action:"StartInstances",Version:"2016-11-15"};$.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{StartingInstances:this.parseArray(Y.instancesSet?.item).map((Z)=>({InstanceId:Z.instanceId,CurrentState:Z.currentState?{Name:Z.currentState.name}:void 0,PreviousState:Z.previousState?{Name:Z.previousState.name}:void 0}))}}async stopInstances($,J){let Y={Action:"StopInstances",Version:"2016-11-15"};if($.forEach((Q,G)=>{Y[`InstanceId.${G+1}`]=Q}),J)Y.Force="true";let Z=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()});return{StoppingInstances:this.parseArray(Z.instancesSet?.item).map((Q)=>({InstanceId:Q.instanceId,CurrentState:Q.currentState?{Name:Q.currentState.name}:void 0,PreviousState:Q.previousState?{Name:Q.previousState.name}:void 0}))}}async rebootInstances($){let J={Action:"RebootInstances",Version:"2016-11-15"};$.forEach((Y,Z)=>{J[`InstanceId.${Z+1}`]=Y}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async terminateInstances($){let J={Action:"TerminateInstances",Version:"2016-11-15"};$.forEach((Z,Q)=>{J[`InstanceId.${Q+1}`]=Z});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{TerminatingInstances:this.parseArray(Y.instancesSet?.item).map((Z)=>({InstanceId:Z.instanceId,CurrentState:Z.currentState?{Name:Z.currentState.name}:void 0,PreviousState:Z.previousState?{Name:Z.previousState.name}:void 0}))}}async createImage($){let J={Action:"CreateImage",Version:"2016-11-15",InstanceId:$.InstanceId,Name:$.Name};if($.Description)J.Description=$.Description;if($.NoReboot!==void 0)J.NoReboot=String($.NoReboot);if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{ImageId:(Y.CreateImageResponse||Y).imageId}}async deregisterImage($){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeregisterImage",Version:"2016-11-15",ImageId:$}).toString()})}async describeVpcs($){let J={Action:"DescribeVpcs",Version:"2016-11-15"};if($?.VpcIds)$.VpcIds.forEach((Z,Q)=>{J[`VpcId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Vpcs:this.parseArray(Y.vpcSet?.item).map((Z)=>({VpcId:Z.vpcId,CidrBlock:Z.cidrBlock,State:Z.state,DhcpOptionsId:Z.dhcpOptionsId,InstanceTenancy:Z.instanceTenancy,IsDefault:Z.isDefault==="true",Tags:this.parseTags(Z.tagSet?.item)}))}}async describeSubnets($){let J={Action:"DescribeSubnets",Version:"2016-11-15"};if($?.SubnetIds)$.SubnetIds.forEach((Z,Q)=>{J[`SubnetId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Subnets:this.parseArray(Y.subnetSet?.item).map((Z)=>({SubnetId:Z.subnetId,VpcId:Z.vpcId,CidrBlock:Z.cidrBlock,AvailabilityZone:Z.availabilityZone,AvailableIpAddressCount:Number.parseInt(Z.availableIpAddressCount),State:Z.state,MapPublicIpOnLaunch:Z.mapPublicIpOnLaunch==="true",Tags:this.parseTags(Z.tagSet?.item)}))}}async describeSecurityGroups($){let J={Action:"DescribeSecurityGroups",Version:"2016-11-15"};if($?.GroupIds)$.GroupIds.forEach((Z,Q)=>{J[`GroupId.${Q+1}`]=Z});if($?.GroupNames)$.GroupNames.forEach((Z,Q)=>{J[`GroupName.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{SecurityGroups:this.parseArray(Y.securityGroupInfo?.item).map((Z)=>({GroupId:Z.groupId,GroupName:Z.groupName,Description:Z.groupDescription,VpcId:Z.vpcId,IpPermissions:this.parseIpPermissions(Z.ipPermissions?.item),IpPermissionsEgress:this.parseIpPermissions(Z.ipPermissionsEgress?.item),Tags:this.parseTags(Z.tagSet?.item)}))}}async describeInternetGateways($){let J={Action:"DescribeInternetGateways",Version:"2016-11-15"};if($?.InternetGatewayIds)$.InternetGatewayIds.forEach((Z,Q)=>{J[`InternetGatewayId.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{InternetGateways:this.parseArray(Y.internetGatewaySet?.item).map((Z)=>({InternetGatewayId:Z.internetGatewayId,Attachments:this.parseArray(Z.attachmentSet?.item).map((Q)=>({VpcId:Q.vpcId,State:Q.state})),Tags:this.parseTags(Z.tagSet?.item)}))}}async describeAddresses($){let J={Action:"DescribeAddresses",Version:"2016-11-15"};if($?.AllocationIds)$.AllocationIds.forEach((Z,Q)=>{J[`AllocationId.${Q+1}`]=Z});if($?.PublicIps)$.PublicIps.forEach((Z,Q)=>{J[`PublicIp.${Q+1}`]=Z});if($?.Filters)$.Filters.forEach((Z,Q)=>{J[`Filter.${Q+1}.Name`]=Z.Name,Z.Values.forEach((G,W)=>{J[`Filter.${Q+1}.Value.${W+1}`]=G})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{Addresses:this.parseArray(Y.addressesSet?.item).map((Z)=>({PublicIp:Z.publicIp,AllocationId:Z.allocationId,AssociationId:Z.associationId,InstanceId:Z.instanceId,NetworkInterfaceId:Z.networkInterfaceId,PrivateIpAddress:Z.privateIpAddress,Domain:Z.domain,Tags:this.parseTags(Z.tagSet?.item)}))}}async allocateAddress($){let J={Action:"AllocateAddress",Version:"2016-11-15"};if($?.Domain)J.Domain=$.Domain;if($?.TagSpecifications)$.TagSpecifications.forEach((Z,Q)=>{J[`TagSpecification.${Q+1}.ResourceType`]=Z.ResourceType,Z.Tags.forEach((G,W)=>{J[`TagSpecification.${Q+1}.Tag.${W+1}.Key`]=G.Key,J[`TagSpecification.${Q+1}.Tag.${W+1}.Value`]=G.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{AllocationId:Y.allocationId,PublicIp:Y.publicIp,Domain:Y.domain}}async associateAddress($){let J={Action:"AssociateAddress",Version:"2016-11-15"};if($.AllocationId)J.AllocationId=$.AllocationId;if($.PublicIp)J.PublicIp=$.PublicIp;if($.InstanceId)J.InstanceId=$.InstanceId;if($.NetworkInterfaceId)J.NetworkInterfaceId=$.NetworkInterfaceId;if($.PrivateIpAddress)J.PrivateIpAddress=$.PrivateIpAddress;if($.AllowReassociation)J.AllowReassociation="true";return{AssociationId:(await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})).associationId}}async createTags($){let J={Action:"CreateTags",Version:"2016-11-15"};$.Resources.forEach((Y,Z)=>{J[`ResourceId.${Z+1}`]=Y}),$.Tags.forEach((Y,Z)=>{J[`Tag.${Z+1}.Key`]=Y.Key,J[`Tag.${Z+1}.Value`]=Y.Value}),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async waitForInstanceState($,J,Y){let Z=Y?.maxWaitMs||300000,Q=Y?.pollIntervalMs||5000,G=Date.now();while(Date.now()-G<Z){let W;try{W=await this.getInstance($)}catch{W=void 0}if(W?.State?.Name===J)return W;await new Promise((z)=>setTimeout(z,Q))}return}async createVpc($){let J={Action:"CreateVpc",Version:"2016-11-15",CidrBlock:$.CidrBlock};if($.InstanceTenancy)J.InstanceTenancy=$.InstanceTenancy;if($.TagSpecifications)$.TagSpecifications.forEach((G,W)=>{J[`TagSpecification.${W+1}.ResourceType`]=G.ResourceType,G.Tags.forEach((z,U)=>{J[`TagSpecification.${W+1}.Tag.${U+1}.Key`]=z.Key,J[`TagSpecification.${W+1}.Tag.${U+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=(Y.CreateVpcResponse||Y).vpc;return{Vpc:Q?{VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,State:Q.state,DhcpOptionsId:Q.dhcpOptionsId,InstanceTenancy:Q.instanceTenancy,IsDefault:Q.isDefault==="true",Tags:this.parseTags(Q.tagSet?.item)}:void 0}}async createSubnet($){let J={Action:"CreateSubnet",Version:"2016-11-15",VpcId:$.VpcId,CidrBlock:$.CidrBlock};if($.AvailabilityZone)J.AvailabilityZone=$.AvailabilityZone;if($.TagSpecifications)$.TagSpecifications.forEach((G,W)=>{J[`TagSpecification.${W+1}.ResourceType`]=G.ResourceType,G.Tags.forEach((z,U)=>{J[`TagSpecification.${W+1}.Tag.${U+1}.Key`]=z.Key,J[`TagSpecification.${W+1}.Tag.${U+1}.Value`]=z.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Q=(Y.CreateSubnetResponse||Y).subnet;return{Subnet:Q?{SubnetId:Q.subnetId,VpcId:Q.vpcId,CidrBlock:Q.cidrBlock,AvailabilityZone:Q.availabilityZone,AvailableIpAddressCount:Q.availableIpAddressCount?Number.parseInt(Q.availableIpAddressCount):void 0,State:Q.state,MapPublicIpOnLaunch:Q.mapPublicIpOnLaunch==="true",Tags:this.parseTags(Q.tagSet?.item)}:void 0}}async modifySubnetAttribute($){let J={Action:"ModifySubnetAttribute",Version:"2016-11-15",SubnetId:$.SubnetId};if($.MapPublicIpOnLaunch!==void 0)J["MapPublicIpOnLaunch.Value"]=String($.MapPublicIpOnLaunch.Value);await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async createSecurityGroup($){let J={Action:"CreateSecurityGroup",Version:"2016-11-15",GroupName:$.GroupName,GroupDescription:$.Description};if($.VpcId)J.VpcId=$.VpcId;if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()});return{GroupId:(Y.CreateSecurityGroupResponse||Y).groupId}}async authorizeSecurityGroupIngress($){let J={Action:"AuthorizeSecurityGroupIngress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async authorizeSecurityGroupEgress($){let J={Action:"AuthorizeSecurityGroupEgress",Version:"2016-11-15",GroupId:$.GroupId};this.encodeIpPermissions(J,$.IpPermissions),await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async describeRouteTables($){let J={Action:"DescribeRouteTables",Version:"2016-11-15"};if($?.RouteTableIds)$.RouteTableIds.forEach((Q,G)=>{J[`RouteTableId.${G+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,G)=>{J[`Filter.${G+1}.Name`]=Q.Name,Q.Values.forEach((W,z)=>{J[`Filter.${G+1}.Value.${z+1}`]=W})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.DescribeRouteTablesResponse||Y;return{RouteTables:this.parseArray(Z.routeTableSet?.item).map((Q)=>({RouteTableId:Q.routeTableId,VpcId:Q.vpcId,Routes:this.parseArray(Q.routeSet?.item).map((G)=>({DestinationCidrBlock:G.destinationCidrBlock,GatewayId:G.gatewayId,NatGatewayId:G.natGatewayId,State:G.state})),Associations:this.parseArray(Q.associationSet?.item).map((G)=>({RouteTableAssociationId:G.routeTableAssociationId,SubnetId:G.subnetId,Main:G.main==="true"||G.main===!0})),Tags:this.parseTags(Q.tagSet?.item)}))}}async deleteVpc($){let J={Action:"DeleteVpc",Version:"2016-11-15",VpcId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async deleteSubnet($){let J={Action:"DeleteSubnet",Version:"2016-11-15",SubnetId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async deleteSecurityGroup($){await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({Action:"DeleteSecurityGroup",Version:"2016-11-15",GroupId:$}).toString()})}async describeNetworkInterfaces($){let J={Action:"DescribeNetworkInterfaces",Version:"2016-11-15"};if($?.NetworkInterfaceIds)$.NetworkInterfaceIds.forEach((Q,G)=>{J[`NetworkInterfaceId.${G+1}`]=Q});if($?.Filters)$.Filters.forEach((Q,G)=>{J[`Filter.${G+1}.Name`]=Q.Name,Q.Values.forEach((W,z)=>{J[`Filter.${G+1}.Value.${z+1}`]=W})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.DescribeNetworkInterfacesResponse||Y;return{NetworkInterfaces:this.parseArray(Z.networkInterfaceSet?.item).map((Q)=>({NetworkInterfaceId:Q.networkInterfaceId,SubnetId:Q.subnetId,VpcId:Q.vpcId,Status:Q.status,Attachment:Q.attachment?{AttachmentId:Q.attachment.attachmentId,InstanceId:Q.attachment.instanceId,Status:Q.attachment.status}:void 0}))}}async detachNetworkInterface($,J){let Y={Action:"DetachNetworkInterface",Version:"2016-11-15",AttachmentId:$};if(J)Y.Force="true";await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y).toString()})}async deleteNetworkInterface($){let J={Action:"DeleteNetworkInterface",Version:"2016-11-15",NetworkInterfaceId:$};await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()})}async describeRegions(){let $={Action:"DescribeRegions",Version:"2016-11-15"},J=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams($).toString()}),Y=J.DescribeRegionsResponse||J;return{Regions:this.parseArray(Y.regionInfo?.item).map((Z)=>({RegionName:Z.regionName,Endpoint:Z.regionEndpoint}))}}async runInstances($){let J={Action:"RunInstances",Version:"2016-11-15",ImageId:$.ImageId,InstanceType:$.InstanceType,MinCount:String($.MinCount),MaxCount:String($.MaxCount)};if($.SecurityGroupIds)$.SecurityGroupIds.forEach((Q,G)=>{J[`SecurityGroupId.${G+1}`]=Q});if($.SubnetId)J.SubnetId=$.SubnetId;if($.UserData)J.UserData=$.UserData;if($.IamInstanceProfile){if($.IamInstanceProfile.Name)J["IamInstanceProfile.Name"]=$.IamInstanceProfile.Name;if($.IamInstanceProfile.Arn)J["IamInstanceProfile.Arn"]=$.IamInstanceProfile.Arn}if($.TagSpecifications)$.TagSpecifications.forEach((Q,G)=>{J[`TagSpecification.${G+1}.ResourceType`]=Q.ResourceType,Q.Tags.forEach((W,z)=>{J[`TagSpecification.${G+1}.Tag.${z+1}.Key`]=W.Key,J[`TagSpecification.${G+1}.Tag.${z+1}.Value`]=W.Value})});let Y=await this.client.request({service:"ec2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(J).toString()}),Z=Y.RunInstancesResponse||Y;return{Instances:this.parseInstances(Z.instancesSet?.item||Z.instancesSet)}}encodeIpPermissions($,J){J.forEach((Y,Z)=>{let Q=`IpPermissions.${Z+1}`;if(Y.IpProtocol!==void 0)$[`${Q}.IpProtocol`]=Y.IpProtocol;if(Y.FromPort!==void 0)$[`${Q}.FromPort`]=String(Y.FromPort);if(Y.ToPort!==void 0)$[`${Q}.ToPort`]=String(Y.ToPort);if(Y.IpRanges)Y.IpRanges.forEach((G,W)=>{if(G.CidrIp)$[`${Q}.IpRanges.${W+1}.CidrIp`]=G.CidrIp;if(G.Description)$[`${Q}.IpRanges.${W+1}.Description`]=G.Description});if(Y.Ipv6Ranges)Y.Ipv6Ranges.forEach((G,W)=>{if(G.CidrIpv6)$[`${Q}.Ipv6Ranges.${W+1}.CidrIpv6`]=G.CidrIpv6;if(G.Description)$[`${Q}.Ipv6Ranges.${W+1}.Description`]=G.Description});if(Y.UserIdGroupPairs)Y.UserIdGroupPairs.forEach((G,W)=>{if(G.GroupId)$[`${Q}.Groups.${W+1}.GroupId`]=G.GroupId;if(G.UserId)$[`${Q}.Groups.${W+1}.UserId`]=G.UserId;if(G.Description)$[`${Q}.Groups.${W+1}.Description`]=G.Description})})}parseArray($){if(!$)return[];return Array.isArray($)?$:[$]}parseTags($){return this.parseArray($).map((J)=>({Key:J.key,Value:J.value}))}parseReservations($){return this.parseArray($).map((J)=>({ReservationId:J.reservationId,Instances:this.parseInstances(J.instancesSet?.item||J.instancesSet)}))}parseInstances($){return this.parseArray($).map((J)=>({InstanceId:J.instanceId,ImageId:J.imageId,InstanceType:J.instanceType,State:J.instanceState?{Code:Number.parseInt(J.instanceState.code),Name:J.instanceState.name}:void 0,PrivateIpAddress:J.privateIpAddress,PublicIpAddress:J.ipAddress,SubnetId:J.subnetId,VpcId:J.vpcId,SecurityGroups:this.parseArray(J.groupSet?.item).map((Y)=>({GroupId:Y.groupId,GroupName:Y.groupName})),Tags:this.parseTags(J.tagSet?.item),LaunchTime:J.launchTime,Placement:J.placement?{AvailabilityZone:J.placement.availabilityZone,Tenancy:J.placement.tenancy}:void 0,Architecture:J.architecture,RootDeviceType:J.rootDeviceType,RootDeviceName:J.rootDeviceName,BlockDeviceMappings:this.parseArray(J.blockDeviceMapping?.item).map((Y)=>({DeviceName:Y.deviceName,Ebs:Y.ebs?{VolumeId:Y.ebs.volumeId,Status:Y.ebs.status,AttachTime:Y.ebs.attachTime,DeleteOnTermination:Y.ebs.deleteOnTermination==="true"}:void 0})),IamInstanceProfile:J.iamInstanceProfile?{Arn:J.iamInstanceProfile.arn,Id:J.iamInstanceProfile.id}:void 0}))}parseIpPermissions($){return this.parseArray($).map((J)=>({IpProtocol:J.ipProtocol,FromPort:J.fromPort?Number.parseInt(J.fromPort):void 0,ToPort:J.toPort?Number.parseInt(J.toPort):void 0,IpRanges:this.parseArray(J.ipRanges?.item).map((Y)=>({CidrIp:Y.cidrIp,Description:Y.description})),Ipv6Ranges:this.parseArray(J.ipv6Ranges?.item).map((Y)=>({CidrIpv6:Y.cidrIpv6,Description:Y.description})),UserIdGroupPairs:this.parseArray(J.groups?.item).map((Y)=>({GroupId:Y.groupId,UserId:Y.userId,Description:Y.description}))}))}}var Z9=o(()=>{Y0()});class Q9{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async putParameter($){let J={Name:$.Name,Value:$.Value};if($.Type)J.Type=$.Type;if($.Description)J.Description=$.Description;if($.KeyId)J.KeyId=$.KeyId;if($.Overwrite!==void 0)J.Overwrite=$.Overwrite;if($.AllowedPattern)J.AllowedPattern=$.AllowedPattern;if($.Tags&&$.Tags.length>0)J.Tags=$.Tags;if($.Tier)J.Tier=$.Tier;if($.DataType)J.DataType=$.DataType;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.PutParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Version:Y.Version,Tier:Y.Tier}}async getParameter($){let J={Name:$.Name};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameter:Y.Parameter?this.parseParameter(Y.Parameter):void 0}}async getParameters($){let J={Names:$.Names};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),InvalidParameters:Y.InvalidParameters}}async getParametersByPath($){let J={Path:$.Path};if($.Recursive!==void 0)J.Recursive=$.Recursive;if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;if($.MaxResults)J.MaxResults=$.MaxResults;if($.NextToken)J.NextToken=$.NextToken;if($.ParameterFilters&&$.ParameterFilters.length>0)J.ParameterFilters=$.ParameterFilters;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParametersByPath","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:Y.NextToken}}async deleteParameter($){let J={Name:$.Name};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameter","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteParameters($){let J={Names:$},Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DeleteParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{DeletedParameters:Y.DeletedParameters,InvalidParameters:Y.InvalidParameters}}async describeParameters($){let J={};if($?.Filters&&$.Filters.length>0)J.Filters=$.Filters;if($?.ParameterFilters&&$.ParameterFilters.length>0)J.ParameterFilters=$.ParameterFilters;if($?.MaxResults)J.MaxResults=$.MaxResults;if($?.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.DescribeParameters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>this.parseParameter(Z)),NextToken:Y.NextToken}}async getParameterHistory($){let J={Name:$.Name};if($.WithDecryption!==void 0)J.WithDecryption=$.WithDecryption;if($.MaxResults)J.MaxResults=$.MaxResults;if($.NextToken)J.NextToken=$.NextToken;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetParameterHistory","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Parameters:Y.Parameters?.map((Z)=>({Name:Z.Name,Type:Z.Type,KeyId:Z.KeyId,LastModifiedDate:Z.LastModifiedDate,LastModifiedUser:Z.LastModifiedUser,Description:Z.Description,Value:Z.Value,Version:Z.Version,Labels:Z.Labels,Tier:Z.Tier})),NextToken:Y.NextToken}}async labelParameterVersion($){let J={Name:$.Name,Labels:$.Labels};if($.ParameterVersion!==void 0)J.ParameterVersion=$.ParameterVersion;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.LabelParameterVersion","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{InvalidLabels:Y.InvalidLabels,ParameterVersion:Y.ParameterVersion}}async addTagsToResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId,Tags:$.Tags};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.AddTagsToResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async removeTagsFromResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId,TagKeys:$.TagKeys};await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.RemoveTagsFromResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTagsForResource($){let J={ResourceType:$.ResourceType,ResourceId:$.ResourceId};return{TagList:(await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListTagsForResource","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).TagList}}async setString($,J,Y){return this.putParameter({Name:$,Value:J,Type:"String",Description:Y?.description,Overwrite:Y?.overwrite??!0,Tags:Y?.tags})}async setSecureString($,J,Y){return this.putParameter({Name:$,Value:J,Type:"SecureString",Description:Y?.description,Overwrite:Y?.overwrite??!0,KeyId:Y?.kmsKeyId,Tags:Y?.tags})}async getValue($){return(await this.getParameter({Name:$,WithDecryption:!0})).Parameter?.Value}async getAllByPath($,J=!0){let Y=[],Z;do{let Q=await this.getParametersByPath({Path:$,Recursive:J,WithDecryption:!0,NextToken:Z});if(Q.Parameters)Y.push(...Q.Parameters);Z=Q.NextToken}while(Z);return Y}parseParameter($){return{Name:$.Name,Type:$.Type,Value:$.Value,Version:$.Version,LastModifiedDate:$.LastModifiedDate,ARN:$.ARN,DataType:$.DataType,Description:$.Description,AllowedPattern:$.AllowedPattern,KeyId:$.KeyId,Tier:$.Tier}}async sendCommand($){if(!$.InstanceIds&&!$.Targets)throw Error("SendCommand requires either InstanceIds or Targets");let J={DocumentName:$.DocumentName};if($.InstanceIds)J.InstanceIds=$.InstanceIds;if($.Targets)J.Targets=$.Targets;if($.Parameters)J.Parameters=$.Parameters;if($.TimeoutSeconds)J.TimeoutSeconds=$.TimeoutSeconds;if($.Comment)J.Comment=$.Comment;if($.OutputS3BucketName)J.OutputS3BucketName=$.OutputS3BucketName;if($.OutputS3KeyPrefix)J.OutputS3KeyPrefix=$.OutputS3KeyPrefix;let Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.SendCommand","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{CommandId:Y.Command?.CommandId,Status:Y.Command?.Status,StatusDetails:Y.Command?.StatusDetails}}async getCommandInvocation($){let J={CommandId:$.CommandId,InstanceId:$.InstanceId},Y=await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.GetCommandInvocation","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)});return{Status:Y.Status,StatusDetails:Y.StatusDetails,StandardOutputContent:Y.StandardOutputContent,StandardErrorContent:Y.StandardErrorContent,ResponseCode:Y.ResponseCode}}async runShellCommand($,J,Y){let Z=await this.sendCommand({InstanceIds:[$],DocumentName:"AWS-RunShellScript",Parameters:{commands:J},TimeoutSeconds:Y?.timeoutSeconds||600});if(!Z.CommandId)return{success:!1,error:"Failed to send command"};if(Y?.waitForCompletion===!1)return{success:!0,status:"Pending"};let Q=Y?.pollIntervalMs||2000,G=Y?.maxWaitMs||300000,W=Date.now();while(Date.now()-W<G){await new Promise((z)=>setTimeout(z,Q));try{let z=await this.getCommandInvocation({CommandId:Z.CommandId,InstanceId:$});if(z.Status==="Success")return{success:!0,output:z.StandardOutputContent,error:z.StandardErrorContent,status:z.Status};if(z.Status==="Failed"||z.Status==="Cancelled"||z.Status==="TimedOut")return{success:!1,output:z.StandardOutputContent,error:z.StandardErrorContent||z.StatusDetails,status:z.Status}}catch(z){if(!z.message?.includes("InvocationDoesNotExist"))return{success:!1,error:z.message}}}return{success:!1,error:"Command timed out waiting for completion"}}async listCommandInvocations($){let J={CommandId:$.CommandId};if($.Details)J.Details=!0;return((await this.client.request({service:"ssm",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonSSM.ListCommandInvocations","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).CommandInvocations||[]).map((Q)=>({InstanceId:Q.InstanceId,Status:Q.Status,StatusDetails:Q.StatusDetails,StandardOutputContent:Q.CommandPlugins?.[0]?.Output,StandardErrorContent:Q.CommandPlugins?.[0]?.StandardErrorUrl}))}async sendCommandByTags($){let J=Object.entries($.tags).map(([U,H])=>({Key:`tag:${U}`,Values:[H]})),Y=await this.sendCommand({Targets:J,DocumentName:"AWS-RunShellScript",Parameters:{commands:$.commands},TimeoutSeconds:$.timeoutSeconds||600,Comment:$.comment});if(!Y.CommandId)return{success:!1,instanceCount:0,perInstance:[],error:"Failed to send command"};let Z=$.pollIntervalMs||3000,Q=$.maxWaitMs||600000,G=Date.now(),W=new Set(["Success","Failed","Cancelled","TimedOut"]),z=[];while(Date.now()-G<Q){await new Promise((U)=>setTimeout(U,Z));try{if(z=await this.listCommandInvocations({CommandId:Y.CommandId,Details:!0}),z.length===0)continue;if(z.every((H)=>W.has(H.Status||""))){let H=z.map((B)=>({instanceId:B.InstanceId,status:B.Status||"Unknown",output:B.StandardOutputContent,error:B.StandardErrorContent||B.StatusDetails})),F=z.every((B)=>B.Status==="Success");return{success:F,instanceCount:z.length,perInstance:H,error:F?void 0:"One or more instances reported a non-success status"}}}catch(U){if(!U.message?.includes("InvocationDoesNotExist"))return{success:!1,instanceCount:0,perInstance:[],error:U.message}}}return{success:!1,instanceCount:z.length,perInstance:z.map((U)=>({instanceId:U.InstanceId,status:U.Status||"Unknown"})),error:"Command timed out waiting for all instances to complete"}}}var ZQ=o(()=>{Y0()});function A7($){return`'${$.split("'").join("'\\''")}'`}function V7($={}){return["export DEBIAN_FRONTEND=noninteractive","export PANTRY_SERVICE_SCOPE=system","export PANTRY_INSTALL_DIR=/usr/local/bin",$.version?`export PANTRY_VERSION=${A7($.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)","command -v pantry >/dev/null 2>&1 || curl -fsSL https://pantry.dev | bash",'export PATH="/usr/local/bin:$PATH"',"mkdir -p /opt/pantry"]}function B$(){return'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true'}function a$($){if($.length===0)return[];return[`(cd /opt/pantry && pantry install ${[...new Set($)].map(A7).join(" ")})`]}function _7($){return[...new Set($)].flatMap((J)=>[`(cd /opt/pantry && pantry start ${A7(J)})`,`(cd /opt/pantry && pantry enable ${A7(J)})`])}var XH,S1="/opt/pantry";var z2=o(()=>{XH={php:"php.net",nginx:"nginx.org",composer:"getcomposer.org",mysql:"mysql.com",mariadb:"mariadb.com/server",postgres:"postgresql.org",redis:"redis.io",memcached:"memcached.org",meilisearch:"meilisearch.com",git:"git-scm.com",certbot:"certbot.eff.org",bun:"bun.sh",node:"nodejs.org",deno:"deno.land"}});function T2($){return $===!0||typeof $==="object"&&$!=null}function Kq($){let J=[],Y=[];if(T2($.mysql))J.push(typeof $.mysql==="object"&&$.mysql.version?`mysql.com@${$.mysql.version}`:"mysql.com@8.0.43"),Y.push("mysql");else if(T2($.mariadb))J.push(XH.mariadb),Y.push("mariadb");if(T2($.postgres))J.push("postgresql.org"),Y.push("postgres");if(T2($.redis))J.push("redis.io"),Y.push("redis");if(T2($.memcached))J.push("memcached.org"),Y.push("memcached");if(T2($.meilisearch))J.push("meilisearch.com"),Y.push("meilisearch");return{packages:J,services:Y}}function j7($={},J={}){let Y=Kq($);if(Y.packages.length===0)return[];return[...a$(Y.packages),..._7(Y.services)]}function L7($,J={}){if(!$?.name)return[];if($.host&&$.host!=="127.0.0.1"&&$.host!=="localhost")return[];let Y=$.name,Z=$.username||Y,Q=$.password||"",G=T2(J.postgres)||$.engine==="postgres",W=T2(J.mariadb)||$.engine==="mariadb",z=T2(J.mysql)||$.engine==="mysql";if(G&&!z&&!W){let O=(E)=>`"${E.replace(/"/g,'""')}"`,V=(E)=>`'${E.replace(/'/g,"''")}'`,A=(E,j)=>["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${V(E)}) THEN`,` CREATE ROLE ${O(E)} LOGIN PASSWORD ${V(j)};`," ELSE",` ALTER ROLE ${O(E)} LOGIN PASSWORD ${V(j)};`," END IF;","END $$;"],_=(E)=>{let j=E.databases&&E.databases.length>0?E.databases:[Y],q=[];for(let T of j)if(E.access==="readonly")q.push(`GRANT CONNECT ON DATABASE ${O(T)} TO ${O(E.username)};`,`\\connect ${O(T)}`,`GRANT USAGE ON SCHEMA public TO ${O(E.username)};`,`GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${O(E.username)};`,`ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO ${O(E.username)};`,"\\connect postgres");else q.push(`GRANT ALL PRIVILEGES ON DATABASE ${O(T)} TO ${O(E.username)};`);return q},M=$.users||[];return[B$(),"for i in $(seq 1 30); do pg_isready -h 127.0.0.1 -p 5432 -q && break; sleep 2; done","psql -h 127.0.0.1 -p 5432 -U postgres <<'TS_CLOUD_PG_EOF'",...A(Z,Q),`SELECT 'CREATE DATABASE ${O(Y)} OWNER ${O(Z)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${V(Y)})\\gexec`,...M.flatMap((E)=>[...A(E.username,E.password),..._(E)]),"TS_CLOUD_PG_EOF"]}let U=W?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock",H=(O)=>O.replace(/`/g,"``"),F=(O)=>O.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),B=(O)=>{let V=O.databases&&O.databases.length>0?O.databases:[Y],A=O.access==="readonly"?"SELECT":"ALL PRIVILEGES",_=[`CREATE USER IF NOT EXISTS '${F(O.username)}'@'%' IDENTIFIED BY '${F(O.password)}';`,`CREATE USER IF NOT EXISTS '${F(O.username)}'@'localhost' IDENTIFIED BY '${F(O.password)}';`,`ALTER USER '${F(O.username)}'@'%' IDENTIFIED BY '${F(O.password)}';`,`ALTER USER '${F(O.username)}'@'localhost' IDENTIFIED BY '${F(O.password)}';`];for(let M of V)_.push(`GRANT ${A} ON \`${H(M)}\`.* TO '${F(O.username)}'@'%';`,`GRANT ${A} ON \`${H(M)}\`.* TO '${F(O.username)}'@'localhost';`);return _},K=$.users||[];return[B$(),`for i in $(seq 1 30); do mysqladmin --socket=${U} -u root ping 2>/dev/null | grep -q alive && break; sleep 2; done`,`mysql --socket=${U} -u root <<'TS_CLOUD_SQL_EOF'`,`CREATE DATABASE IF NOT EXISTS \`${H(Y)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`,...B({username:Z,password:Q}),...K.flatMap(B),"FLUSH PRIVILEGES;","TS_CLOUD_SQL_EOF"]}function BH($){if(!$?.name)return{};let J=$.engine==="postgres"?"pgsql":"mysql",Y=$.port??($.engine==="postgres"?5432:3306),Z={DB_CONNECTION:J,DB_HOST:$.host||"127.0.0.1",DB_PORT:String(Y),DB_DATABASE:$.name};if($.username)Z.DB_USERNAME=$.username;if($.password)Z.DB_PASSWORD=$.password;return Z}var E7=o(()=>{z2()});function KH($){return Aq}function Vq($={}){let J=$.versions?.length?$.versions:["8.3"];return $.default&&J.includes($.default)?$.default:J[0]}function _q($={}){return{...$.optimizeForProduction===!1?{}:{...Oq},...$.ini||{}}}function jq($={}){let J=_q($),Y=Object.keys(J);if(Y.length===0)return[];let Z=Y.map((G)=>`${G}=${J[G]}`),Q="ts-cloud-managed";return[B$(),"TS_CLOUD_SCAN_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Scan this dir for additional .ini files/{print $2}' | head -1)",`TS_CLOUD_LOADED_INI=$(php -r 'echo php_ini_loaded_file() ?: "";' 2>/dev/null)`,'if [ -n "$TS_CLOUD_SCAN_DIR" ] && [ "$TS_CLOUD_SCAN_DIR" != "(none)" ]; then',' mkdir -p "$TS_CLOUD_SCAN_DIR"',' TS_CLOUD_PHP_INI="$TS_CLOUD_SCAN_DIR/zz-ts-cloud.ini"',` cat > "$TS_CLOUD_PHP_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} — production PHP tuning`,...Z,"TS_CLOUD_PHPINI_EOF","else",' if [ -z "$TS_CLOUD_LOADED_INI" ]; then'," TS_CLOUD_INI_DIR=$(php -i 2>/dev/null | awk -F' => ' '/^Configuration File \\(php.ini\\) Path/{print $2}' | head -1)",' TS_CLOUD_LOADED_INI="$TS_CLOUD_INI_DIR/php.ini"',' mkdir -p "$TS_CLOUD_INI_DIR"',' touch "$TS_CLOUD_LOADED_INI"'," fi",` sed -i '/; ${Q} BEGIN/,/; ${Q} END/d' "$TS_CLOUD_LOADED_INI"`,` cat >> "$TS_CLOUD_LOADED_INI" <<'TS_CLOUD_PHPINI_EOF'`,`; ${Q} BEGIN`,...Z,`; ${Q} END`,"TS_CLOUD_PHPINI_EOF","fi",`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`]}function M7($={}){let J=Vq($),Y=$.installNginx!==!1,Z=$.installComposer!==!1,Q=[`php.net@${J}`];if(Z)Q.push("getcomposer.org");if(Y)Q.push("nginx.org");return[...a$(Q),..._7(["php-fpm"]),...jq($)]}var Oq,Aq="127.0.0.1:9074";var q7=o(()=>{z2();Oq={"opcache.enable":"1","opcache.enable_cli":"1","opcache.memory_consumption":"256","opcache.interned_strings_buffer":"16","opcache.max_accelerated_files":"20000","opcache.validate_timestamps":"0","opcache.revalidate_freq":"0","opcache.save_comments":"1","opcache.fast_shutdown":"1",realpath_cache_size:"4096K",realpath_cache_ttl:"600"}});function QQ($,J){if(!$)return[];let Y=[];if($.template&&J?.[$.template])Y.push(...J[$.template]);if($.serverSnippet)Y.push(...$.serverSnippet);return Y}function Lq($){if(!$)return"";let J=typeof $==="object"?$:{},Z=[`max-age=${J.maxAge??31536000}`];if(J.includeSubDomains??!0)Z.push("includeSubDomains");if(J.preload)Z.push("preload");return` add_header Strict-Transport-Security "${Z.join("; ")}" always;`}function Eq($){if(!$||!$.allow?.length&&!$.deny?.length)return[];let J=[];for(let Y of $.deny||[])J.push(` deny ${Y};`);if($.allow?.length){for(let Y of $.allow)J.push(` allow ${Y};`);J.push(" deny all;")}return J}function OH($){return`/etc/nginx/.htpasswd-${$}`}function qq($){return Mq.has($)}function Tq($){return $==="laravel"||$==="statamic"?"public":""}function wq($,J){let Y=$.replace(/\/+$/,""),Z=J.replace(/^\/+|\/+$/g,"");return Z?`${Y}/${Z}`:Y}function Dq($){let J=$.type??"laravel",Y=$.webDirectory??Tq(J),Z=wq($.appDir,Y),Q=qq(J),G=$.phpVersion??"8.3",W=[` root ${Z};`,"",' add_header X-Frame-Options "SAMEORIGIN";',' add_header X-Content-Type-Options "nosniff";'],z=Lq($.hsts);if(z)W.push(z);for(let U of Eq($.security))W.push(U);if(W.push("",` index ${Q?"index.php index.html":"index.html index.htm"};`,""," charset utf-8;",""),$.clientMaxBodySize)W.push(` client_max_body_size ${$.clientMaxBodySize};`,"");if($.auth)W.push(` auth_basic "${$.auth.realm||"Restricted"}";`,` auth_basic_user_file ${OH($.siteName)};`,"");for(let[U,H]of Object.entries($.redirects||{}))W.push(` location = ${U} { return 301 ${H}; }`);if(Object.keys($.redirects||{}).length>0)W.push("");if(Q){if(W.push(" location / {"," try_files $uri $uri/ /index.php?$query_string;"," }",""," location = /favicon.ico { access_log off; log_not_found off; }"," location = /robots.txt { access_log off; log_not_found off; }",""," error_page 404 /index.php;",""," location ~ \\.php$ {",` fastcgi_pass ${$.fastcgiPass??KH(G)};`," fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;"," include fastcgi_params;"," }",""," location ~ /\\.(?!well-known).* {"," deny all;"," }"),J==="wordpress")W.push(""," location = /xmlrpc.php { deny all; }"," location ~* /(?:wp-config\\.php|readme\\.html|license\\.txt)$ { deny all; }"," location ~* /wp-content/uploads/.*\\.php$ { deny all; }")}else if(J==="spa")W.push(" location / {"," try_files $uri $uri/ /index.html;"," }");else W.push(" location / {"," try_files $uri $uri/ =404;"," }");if($.serverSnippet&&$.serverSnippet.length>0){W.push("");for(let U of $.serverSnippet)W.push(U?` ${U}`:"")}return W}function Rq($){let J=[$.domain,...$.aliases||[]].filter(Boolean).join(" "),Y=Dq($);if($.ssl){let Q=["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`," return 301 https://$host$request_uri;","}"],G=["server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${J};`,` ssl_certificate ${$.ssl.certPath};`,` ssl_certificate_key ${$.ssl.keyPath};`,...$.tlsProtocols?.length?[` ssl_protocols ${$.tlsProtocols.join(" ")};`]:[],"",...Y,"}"];return`${[...Q,"",...G].join(`
|
|
7279
7279
|
`)}
|
|
7280
7280
|
`}return`${["server {"," listen 80;"," listen [::]:80;",` server_name ${J};`,...Y,"}"].join(`
|
|
7281
7281
|
`)}
|
|
@@ -7312,7 +7312,7 @@ ${Object.entries($).filter(([G])=>!G.startsWith("@_")).map(([G,W])=>Q(G,W," ","
|
|
|
7312
7312
|
`,Q+=`\r
|
|
7313
7313
|
`,Q+=`${G.content}\r
|
|
7314
7314
|
`;return Q+=`--${Z}--\r
|
|
7315
|
-
`,Q}}var Cq;var HQ=o(()=>{U9();I0();T7();
|
|
7315
|
+
`,Q}}var Cq;var HQ=o(()=>{U9();I0();T7();o2();Cq=new w7});function H9($,J){return!$.events||$.events.includes(J)}async function FQ($,J,Y,Z={}){if(!$)return[];let Q=Z.fetchImpl??globalThis.fetch,G=[],W=[],z=(U,H)=>Q(U,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)}).catch(()=>{return});if($.slack?.webhookUrl&&H9($,J))G.push("slack"),W.push(z($.slack.webhookUrl,{text:Y}));if($.discord?.webhookUrl&&H9($,J))G.push("discord"),W.push(z($.discord.webhookUrl,{content:Y}));if($.telegram?.botToken&&$.telegram.chatId&&H9($,J)){G.push("telegram");let U=`https://api.telegram.org/bot${$.telegram.botToken}/sendMessage`;W.push(z(U,{chat_id:$.telegram.chatId,text:Y}))}if($.webhook?.url&&H9($,J))if(G.push("webhook"),($.webhook.method||"POST")==="GET"){let U=$.webhook.url.includes("?")?"&":"?",H=`${$.webhook.url}${U}event=${encodeURIComponent(J)}&message=${encodeURIComponent(Y)}`;W.push(Q(H,{method:"GET"}).catch(()=>{return}))}else W.push(z($.webhook.url,{event:J,message:Y}));if($.email?.to&&H9($,J))G.push("email"),W.push(xq($.email,J,Y));return await Promise.all(W),G}async function xq($,J,Y){try{await(await Promise.resolve().then(() => (HQ(),LH))).email.send({to:$.to,from:$.from,subject:`[ts-cloud] ${J}`,text:Y})}catch{}}function EH($,J){return J??$}function D7($){if(!$)return[];let J=[];if($.slack?.webhookUrl)J.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"text\\":\\"$MSG\\"}" ${$.slack.webhookUrl} || true`);if($.discord?.webhookUrl)J.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"content\\":\\"$MSG\\"}" ${$.discord.webhookUrl} || true`);if($.telegram?.botToken&&$.telegram.chatId)J.push(`curl -fsS -X POST "https://api.telegram.org/bot${$.telegram.botToken}/sendMessage" --data-urlencode "chat_id=${$.telegram.chatId}" --data-urlencode "text=$MSG" || true`);if($.webhook?.url)J.push(`curl -fsS -X POST -H 'Content-Type: application/json' -d "{\\"message\\":\\"$MSG\\"}" ${$.webhook.url} || true`);if(J.length===0)return[];return["cat > /usr/local/bin/ts-cloud-notify <<'TS_CLOUD_NOTIFY_EOF'","#!/bin/bash",'MSG="$1"',...J,"TS_CLOUD_NOTIFY_EOF","chmod +x /usr/local/bin/ts-cloud-notify"]}function Iq($){if(!$.name)return null;let J=$.host||"127.0.0.1",Y=$.engine==="postgres",Z=Y?"postgresql":"mysql",Q=$.port??(Y?5432:3306),G=(W)=>W.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return[" {",` type: '${Z}',`,` name: '${G($.name)}',`," connection: {",` hostname: '${G(J)}',`,` port: ${Q},`,` database: '${G($.name)}',`,` username: '${G($.username||$.name)}',`,` password: '${G($.password||"")}',`," ssl: false,"," },"," includeSchema: true,"," includeData: true,"," },"].join(`
|
|
7316
7316
|
`)}function kq($,J){let Y=$?Iq($):null,Z=J.bucket?[" destinations: ["," {"," type: 's3',",` bucket: '${J.bucket}',`," prefix: 'db-backups',",...J.endpoint?[` endpoint: '${J.endpoint}',`]:[]," optional: false,"," },"," ],"]:[];return["import type { BackupConfig } from 'ts-backups'","","const config: BackupConfig = {"," verbose: true,"," outputPath: '/var/backups/ts-cloud',"," retention: {",` count: ${J.retentionCount??5},`,` maxAge: ${J.retentionDays??30},`," },"," databases: [",...Y?[Y]:[]," ],",...Z,"}","","export default config",""].join(`
|
|
7317
7317
|
`)}function MH($){let{database:J,backups:Y}=$;if(!Y.enabled)return[];let Z=Y.schedule||"0 2 * * *";return["export DEBIAN_FRONTEND=noninteractive","mkdir -p /etc/ts-cloud /var/backups/ts-cloud","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 > /etc/ts-cloud/backups.config.ts <<'TS_CLOUD_BACKUP_CFG_EOF'",kq(J,Y).replace(/\n$/,""),"TS_CLOUD_BACKUP_CFG_EOF","cat > /usr/local/bin/ts-cloud-backup.sh <<'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 /usr/local/bin/ts-cloud-backup.sh","cat > /etc/cron.d/ts-cloud-backups <<'TS_CLOUD_BACKUP_CRON_EOF'",`${Z} root /usr/local/bin/ts-cloud-backup.sh >> /var/log/ts-cloud-backup.log 2>&1`,"TS_CLOUD_BACKUP_CRON_EOF","chmod 644 /etc/cron.d/ts-cloud-backups"]}function hq($){return $==="mariadb"?"/var/lib/pantry/mariadb/mariadbd.sock":"/var/lib/pantry/mysql/mysqld.sock"}function qH($,J={}){if(!$?.name)return[];let Y=$.name,Z=$.engine==="postgres",Q=J.from?`TS_CLOUD_DUMP="${J.from}"`:`TS_CLOUD_DUMP="$(find /var/backups/ts-cloud -type f -name '*${Y}*.sql' -o -type f -name '*${Y}*.sql.gz' 2>/dev/null | xargs -r ls -1t 2>/dev/null | head -1)"`,G=Z?`psql -h 127.0.0.1 -p ${$.port??5432} -U postgres -d "${Y}"`:`mysql --socket=${hq($.engine)} -u root "${Y}"`;return["set -uo pipefail",'eval "$(cd /opt/pantry && pantry env 2>/dev/null)" || true',Q,'[ -n "$TS_CLOUD_DUMP" ] && [ -f "$TS_CLOUD_DUMP" ] || { echo "no backup dump found to restore" >&2; exit 1; }','echo "[ts-cloud] restoring '+Y+' from $TS_CLOUD_DUMP"',`case "$TS_CLOUD_DUMP" in *.gz) gunzip -c "$TS_CLOUD_DUMP" ;; *) cat "$TS_CLOUD_DUMP" ;; esac | ${G}`,'echo "restore complete"']}var XQ="/usr/local/bin/ts-cloud-backup.sh";function R7($){let J=$.infrastructure?.compute??{},Y=J.runtime==="php"||!!J.php,Z=Y||!!J.managedServices,Q=Z?V7():[],G=J.webServer!=="rpx",W=Y?[...Q,...M7({versions:J.php?.versions,default:J.php?.default,extensions:J.php?.extensions,installNginx:G,optimizeForProduction:J.php?.optimizeForProduction,ini:J.php?.ini}),...G?WQ():[]]:void 0,z=[];if(!Y&&Z)z.push(...Q);if(z.push(...D7($.notifications)),J.managedServices)z.push(...j7(J.managedServices),...L7($.infrastructure?.appDatabase,J.managedServices));if(z.push(...AH(J.firewall??(Y?{enabled:!0}:{enabled:!1}))),z.push(...G9(J.autoUpdates??Y)),z.push(...W9(J.monitoring??Y)),z.push(...z9(J.sshKeys)),J.backups?.enabled)z.push(...MH({database:$.infrastructure?.appDatabase,backups:J.backups}));return{runtime:J.runtime||"bun",runtimeVersion:J.runtimeVersion||"latest",phpBox:Y,phpProvision:W,servicesProvision:z.length>0?z:void 0}}var BQ=o(()=>{E7();q7();zQ();z2();VH();UQ()});function w2($={}){let{runtime:J="bun",runtimeVersion:Y="latest",systemPackages:Z=[],database:Q,phpProvision:G,servicesProvision:W,caddyfile:z,rpxProvision:U,baked:H=!1}=$,F=new Set(Z);if(Q==="sqlite")F.add("sqlite3");else if(Q==="mysql")F.add("mysql-client");else if(Q==="postgres")F.add("postgresql-client");let B=`#!/bin/bash
|
|
7318
7318
|
set -euo pipefail
|
|
@@ -7405,7 +7405,7 @@ ${$.split(`
|
|
|
7405
7405
|
`)}
|
|
7406
7406
|
runcmd:
|
|
7407
7407
|
- [ bash, /var/lib/cloud/ts-cloud-bootstrap.sh ]
|
|
7408
|
-
`}var AQ=()=>{};function B9($){return $.type!=null&&yq.has($.type)}function VQ($){if($.deploy)return $.deploy;if(B9($))return"server";if($.start)return"server";return"bucket"}function p0($){if($.redirect)return"redirect";if(B9($))return"server-php";if(VQ($)==="bucket")return"bucket";return $.start?"server-app":"server-static"}function vq($){return $.infrastructure?.compute!=null}function _Q($){let J=[],Y=[],Z=$.sites||{},Q=vq($),G=new Map;for(let[W,z]of Object.entries(Z)){if(!z)continue;let U=VQ(z),H=p0(z);if(H==="redirect"){if(!z.domain)J.push(`Site '${W}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof z.redirect==="string"?z.redirect:z.redirect?.to))J.push(`Site '${W}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!Q)J.push(`Site '${W}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let B=[];if(z.start)B.push("start");if(z.root)B.push("root");if(B.length>0)Y.push(`Site '${W}' is a redirect site but also sets ${B.join(", ")}. These are ignored.`);continue}if(U==="server"&&!z.start&&!z.root){J.push(`Site '${W}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(H==="server-php"){if(!Q)J.push(`Site '${W}' is a PHP site (type:'${z.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!z.repository?.url)J.push(`Site '${W}' is a PHP site (type:'${z.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(H==="server-app"){if(!Q)J.push(`Site '${W}' deploys to a server (deploy:'server'${z.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof z.port==="number"){let F=G.get(z.port);if(F)J.push(`Sites '${F}' and '${W}' both use port ${z.port}. Server apps sharing a box must use distinct ports.`);else G.set(z.port,W)}}else if(H==="server-static"){if(!z.root)J.push(`Site '${W}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!Q)J.push(`Site '${W}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!z.root)J.push(`Site '${W}' deploys to a bucket but has no \`root\` directory to upload.`);let F=[];if(z.start)F.push("start");if(typeof z.port==="number")F.push("port");if(z.preStart&&z.preStart.length>0)F.push("preStart");if(F.length>0)Y.push(`Site '${W}' deploys to a bucket but sets server-only field(s): ${F.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:J,warnings:Y}}var yq;var
|
|
7408
|
+
`}var AQ=()=>{};function B9($){return $.type!=null&&yq.has($.type)}function VQ($){if($.deploy)return $.deploy;if(B9($))return"server";if($.start)return"server";return"bucket"}function p0($){if($.redirect)return"redirect";if(B9($))return"server-php";if(VQ($)==="bucket")return"bucket";return $.start?"server-app":"server-static"}function vq($){return $.infrastructure?.compute!=null}function _Q($){let J=[],Y=[],Z=$.sites||{},Q=vq($),G=new Map;for(let[W,z]of Object.entries(Z)){if(!z)continue;let U=VQ(z),H=p0(z);if(H==="redirect"){if(!z.domain)J.push(`Site '${W}' is a redirect site but has no \`domain\` to redirect from.`);if(!(typeof z.redirect==="string"?z.redirect:z.redirect?.to))J.push(`Site '${W}' is a redirect site but has no redirect target (\`redirect\` / \`redirect.to\`).`);if(!Q)J.push(`Site '${W}' is a redirect site but no \`infrastructure.compute\` is configured to host the gateway that serves the redirect.`);let B=[];if(z.start)B.push("start");if(z.root)B.push("root");if(B.length>0)Y.push(`Site '${W}' is a redirect site but also sets ${B.join(", ")}. These are ignored.`);continue}if(U==="server"&&!z.start&&!z.root){J.push(`Site '${W}' sets deploy:'server' but declares neither \`start\` (dynamic app) nor \`root\` (static site to serve). Add one.`);continue}if(H==="server-php"){if(!Q)J.push(`Site '${W}' is a PHP site (type:'${z.type}') but no \`infrastructure.compute\` is configured. Add a server (infrastructure.compute) with PHP provisioning.`);if(!z.repository?.url)J.push(`Site '${W}' is a PHP site (type:'${z.type}') but has no \`repository.url\` to clone. PHP sites deploy via git.`)}else if(H==="server-app"){if(!Q)J.push(`Site '${W}' deploys to a server (deploy:'server'${z.deploy?"":" inferred from `start`"}) but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`);if(typeof z.port==="number"){let F=G.get(z.port);if(F)J.push(`Sites '${F}' and '${W}' both use port ${z.port}. Server apps sharing a box must use distinct ports.`);else G.set(z.port,W)}}else if(H==="server-static"){if(!z.root)J.push(`Site '${W}' is a server static site (deploy:'server', no \`start\`) but has no \`root\` directory to serve.`);if(!Q)J.push(`Site '${W}' deploys to a server (deploy:'server') but no \`infrastructure.compute\` is configured. Set deploy:'bucket' or add a server (infrastructure.compute).`)}else{if(!z.root)J.push(`Site '${W}' deploys to a bucket but has no \`root\` directory to upload.`);let F=[];if(z.start)F.push("start");if(typeof z.port==="number")F.push("port");if(z.preStart&&z.preStart.length>0)F.push("preStart");if(F.length>0)Y.push(`Site '${W}' deploys to a bucket but sets server-only field(s): ${F.join(", ")}. These are ignored. Set deploy:'server' to use them.`)}}return{errors:J,warnings:Y}}var yq;var K$=o(()=>{yq=new Set(["laravel","php","statamic","wordpress"])});function gq($){if(typeof $==="string")return{to:$};let J={to:$.to};if($.status!=null)J.status=$.status;if($.preservePath!=null)J.preservePath=$.preservePath;return J}function uq($){let J=$.auth;if(!J||J.enabled===!1||!J.password)return;return{username:J.username||"admin",password:J.password,...J.realm?{realm:J.realm}:{}}}function PH($){if(!$||$==="/")return;let J=`/${$}`.replace(/\/+/g,"/").replace(/\/+$/,"");if(!J.startsWith("/"))J=`/${J}`;return J===""||J==="/"?void 0:J}function CH($,J){let Z=(J?`${$}${J}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Z.length>0?Z:"rpx"}function K9($,J){let Y=(J.wwwRoot??"/var/www").replace(/\/+$/,""),Z=J.proxy.certsDir??LQ,Q=[],G=new Set;for(let[U,H]of Object.entries($)){if(!H||!H.domain)continue;let F=p0(H);if(F==="bucket")continue;let B=PH(H.path),K=CH(H.domain,B),O=uq(H);if(F==="redirect"){Q.push({to:H.domain,path:B,redirect:gq(H.redirect),id:K,...O?{auth:O}:{}}),G.add(H.domain);continue}if(F==="server-app"){if(typeof H.port!=="number")continue;Q.push({to:H.domain,path:B,from:`localhost:${H.port}`,id:K,...O?{auth:O}:{}})}else Q.push({to:H.domain,path:B,static:`${Y}/${U}/current`,cleanUrls:H.pathRewriteStyle!=="flat",spa:H.spa??!1,...O?{auth:O}:{},id:K});G.add(H.domain)}Q.sort((U,H)=>{if(U.to!==H.to)return U.to.localeCompare(H.to);return(H.path?.length??0)-(U.path?.length??0)});let W={proxies:Q,productionCerts:{certsDir:Z},https:!0,hostsManagement:!1,cleanup:{hosts:!1,certs:!1}};if(J.proxy.onDemandTls&&G.size>0)W.onDemandTls={enabled:!0,allowedSuffixes:[...G],email:J.proxy.onDemandTlsEmail,certsDir:Z};if(J.proxy.onDemandTls)W.acmeChallengeWebroot=J.proxy.acmeWebroot??fq;let z=J.proxy.cdn;if(z?.secret&&z.frontedHosts.length>0)W.originGuard={header:z.secretHeader??"X-Origin-Verify",value:z.secret,hosts:z.frontedHosts};return W}function dq($=S7,J=LQ){return`// Generated by ts-cloud — rpx gateway assembler.
|
|
7409
7409
|
// Merges every app's fragment in ${$} so independent deploys compose
|
|
7410
7410
|
// without clobbering each other. Each deploy writes only its own <slug>.json.
|
|
7411
7411
|
import { startProxies } from '@stacksjs/rpx'
|
|
@@ -7456,18 +7456,18 @@ await startProxies(config)
|
|
|
7456
7456
|
`),M=["[Unit]",`Description=Issue/renew rpx gateway TLS certs for ${K} (tlsx http-01)`,`After=network-online.target ${o$}`,"Wants=network-online.target","","[Service]","Type=oneshot",`ExecStart=${O}`].join(`
|
|
7457
7457
|
`),E=["[Unit]",`Description=Daily rpx gateway TLS cert issuance/renewal for ${K}`,"","[Timer]","OnCalendar=*-*-* 03:30:00","RandomizedDelaySec=1h","Persistent=true","","[Install]","WantedBy=timers.target"].join(`
|
|
7458
7458
|
`);return[`mkdir -p ${Z}`,`(cd ${D2} && ${G} add @stacksjs/tlsx@${W}) || true`,...e$(O,_,"TS_CLOUD_RENEW_EOF"),`chmod +x ${O}`,...e$(`/etc/systemd/system/${V}`,M,"TS_CLOUD_RENEW_SVC_EOF"),...e$(`/etc/systemd/system/${A}`,E,"TS_CLOUD_RENEW_TIMER_EOF"),"systemctl daemon-reload",`systemctl enable --now ${A} || true`,`${O} || true`]}function O9($){let{config:J,proxy:Y}=$,Z=$.bunBin??"/usr/local/bin/bun",Q=Y.version??"latest",G=J.productionCerts.certsDir,W=($.slug||"app").replace(/[^a-z0-9._-]+/gi,"-"),z=JSON.stringify({slug:W,...J},null,2),U=dq(S7,G),F=[`Environment=RPX_UPSTREAM_TIMEOUT=${Y.upstreamTimeout??60}`];if(typeof Y.maxUpstreamConns==="number")F.push(`Environment=RPX_MAX_UPSTREAM_CONNS=${Y.maxUpstreamConns}`);return["set -euo pipefail",`mkdir -p ${P7} ${S7} ${G} ${D2}`,`rm -rf ${D2}/node_modules ${D2}/bun.lock ${D2}/package.json`,`(cd ${D2} && ${Z} add @stacksjs/rpx@${Q})`,`ln -sfn ${D2}/node_modules ${P7}/node_modules`,...e$(`${S7}/${W}.json`,z,"TS_CLOUD_RPX_FRAGMENT_EOF"),...e$(jQ,U,"TS_CLOUD_RPX_EOF"),...e$(`/etc/systemd/system/${o$}`,["[Unit]","Description=rpx reverse-proxy gateway (managed by ts-cloud)","After=network.target network-online.target","Wants=network-online.target","","[Service]","Type=simple",`ExecStart=${Z} ${jQ}`,`WorkingDirectory=${D2}`,"Environment=BUN_INSTALL=/root/.bun",...F,"Restart=always","RestartSec=5","LimitNOFILE=1048576","AmbientCapabilities=CAP_NET_BIND_SERVICE","","[Install]","WantedBy=multi-user.target"].join(`
|
|
7459
|
-
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`systemctl enable ${o$}`,`systemctl restart ${o$}`,...mq($)]}var LQ="/etc/rpx/certs",fq="/var/www/acme-challenge",P7="/etc/rpx",D2="/opt/rpx-gateway",jQ="/etc/rpx/gateway.ts",o$="rpx-gateway.service",S7="/etc/rpx/sites.d";var C7=o(()=>{
|
|
7460
|
-
`,"utf8")}var bH=".ts-cloud/state";var vH=()=>{};import{existsSync as nq,readFileSync as iq}from"node:fs";import{homedir as aq}from"node:os";import{join as tq}from"node:path";import{execSync as qQ}from"node:child_process";function fH($){return $.startsWith("~/")?tq(aq(),$.slice(2)):$}var TQ=268435456,
|
|
7461
|
-
`),Y=[];for(let Q of $.targets){if(!Q.publicIp){Y.push({instanceId:Q.id,status:"Failed",error:"Missing public IP"});continue}try{let G=this.sshExec(Q.publicIp,J);Y.push({instanceId:Q.id,status:"Success",output:G})}catch(G){Y.push({instanceId:Q.id,status:"Failed",error:G.message})}}let Z=Y.every((Q)=>Q.status==="Success");return{success:Z,instanceCount:$.targets.length,perInstance:Y,error:Z?void 0:"One or more SSH deploy commands failed"}}async ensureSshKey($,J,Y){if(!nq(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let Z=iq(this.sshPublicKeyPath,"utf8").trim(),Q=OQ(Z),W=(await this.client.listSshKeys()).find((U)=>OQ(U.public_key)===Q);if(W)return W.id;return(await this.client.createSshKey({name:`${$}-${J}-deploy`,publicKey:Z,labels:Y})).id}async tryGetServer($){try{return await this.client.getServer($)}catch{return null}}async findExistingServer($,J,Y){return(await this.client.listServers()).find((Q)=>
|
|
7462
|
-
${Q}`)}catch(Q){if(Q instanceof Error&&/cloud-init reported an error/.test(Q.message))throw Q}await this.sleep(J)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${Y}ms`)}outputsFromState($,J){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:J?.public_net.ipv4?.ip||$.publicIp,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];sshBaseArgs($,J=[]){return["-i",this.sshPrivateKeyPath,...
|
|
7463
|
-
`);try{let Y=Bun.spawn(["bash","-c",J],{stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{success:G===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:G===0?"Success":"Failed",output:Z,error:Q}]}}catch(Y){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:Y?.message??String(Y)}],error:Y?.message??String(Y)}}}}function DQ(){let $=process.env.TS_CLOUD_DASHBOARD_BOX;return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function Y1($){if(DQ())return new I7;switch($.provider??M2($.config)){case"aws":return new F9({region:$.config.project.region});case"hetzner":return new
|
|
7464
|
-
`)}function oq($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function NQ($){return`${$.replace(/\/+$/,"")}/.ts-cloud`}function SQ($){return`${NQ($)}/deploy-history.log`}function eq($,J){return`${NQ($)}/deploys/${J}.log`}function
|
|
7465
|
-
`);return[`cat > ${J} <<'TS_CLOUD_DNSCREDS_EOF'`,Y,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${J}`]}function zT($){let J=$.dns,Y=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(J){let Q=pH[J.provider].plugin;if(Z.push(`--${Q}`),J.provider!=="route53"&&J.credentials)Z.push(`--${Q}-credentials ${rH(J.provider)}`);if(typeof J.propagationSeconds==="number"&&J.provider!=="route53")Z.push(`--${Q}-propagation-seconds ${J.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Q of Y)Z.push(`-d ${Q}`);return[Z.join(" ")]}function bQ($){if(hQ($)!=="letsencrypt"||!$.domain)return[];let J=$.ssl,Y=J?.dns,Z=J?.wildcard===!0;if(Z&&!Y)return[];return[...GT(Y),...Y?WT(Y):[],...zT({domain:$.domain,aliases:$.aliases,email:J?.email,wildcard:Z,dns:Y})]}var pH;var nH=o(()=>{pH={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}}});function aH($){let{repository:J,releaseDir:Y,commit:Z}=$,Q=J.branch||"main",G=J.url,W=[`rm -rf ${Y}`,`mkdir -p ${Y}`];if(J.strategy==="tag")if(J.tag)W.push(`git clone -q --depth 1 --branch ${J.tag} ${G} ${Y}`),W.push(`printf '%s' ${iH(J.tag)} > ${Y}/.ts-cloud-tag`);else{let z=J.tagPattern||"v*";W.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${G} ${iH(`refs/tags/${z}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching ${z} found in ${G}" >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${G} ${Y}`,`printf '%s' "$TS_CLOUD_TAG" > ${Y}/.ts-cloud-tag`)}else if(Z)W.push(`git -C ${Y} init -q`,`git -C ${Y} remote add origin ${G}`,`git -C ${Y} fetch -q --depth 1 origin ${Z}`,`git -C ${Y} checkout -q FETCH_HEAD`);else W.push(`git clone -q --depth 1 --branch ${Q} ${G} ${Y}`);return W.push(`git -C ${Y} rev-parse HEAD > ${Y}/.ts-cloud-sha`),W}function iH($){return`'${$.split("'").join("'\\''")}'`}function HT($){switch($){case"laravel":case"statamic":return[c7,tH,...UT,m7,oH];case"php":case"wordpress":return[c7,`${tH} || true`,m7];case"static":case"spa":return[c7,m7]}}function FT($,J){return $.replace(/^php\s+/,`${J} `).replace(/(\s)php\s+artisan\s+/g,`$1${J} artisan `)}function XT($,J){let Y=k7(J);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function sH($,J,Y){return[`cat > ${$} <<'${Y}'`,J.replace(/\n$/,""),Y,`chmod 600 ${$}`]}function BT($,J){if(!J)return[];let Y=[];if(J.composerAuth){let Z=typeof J.composerAuth==="string"?J.composerAuth:JSON.stringify(J.composerAuth,null,2);Y.push(...sH(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(J.npmrc)Y.push(...sH(`${$}/.npmrc`,J.npmrc,"TS_CLOUD_NPMRC_EOF"));return Y}function eH($){let J=$.healthCheck?.path;if(!J||!$.domain)return[];let Z=`http://127.0.0.1${J.startsWith("/")?J:`/${J}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${$.domain}" -m 10 "${Z}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function $F($){let{siteName:J,site:Y,releaseId:Z,commit:Q}=$;if(!Y.repository?.url)throw Error(`Site '${J}' is a PHP/git site but has no repository.url to clone`);let G=$.appBase??`/var/www/${J}`,W="php",z=
|
|
7459
|
+
`),"TS_CLOUD_RPX_UNIT_EOF"),"systemctl daemon-reload","systemctl disable --now bun-gateway.service 2>/dev/null || true","systemctl disable --now ts-cloud-nginx.service 2>/dev/null || true",`systemctl enable ${o$}`,`systemctl restart ${o$}`,...mq($)]}var LQ="/etc/rpx/certs",fq="/var/www/acme-challenge",P7="/etc/rpx",D2="/opt/rpx-gateway",jQ="/etc/rpx/gateway.ts",o$="rpx-gateway.service",S7="/etc/rpx/sites.d";var C7=o(()=>{K$()});function xH($={}){let J=Math.max(1,$.appServers??$.instances??1),Y=!!$.servicesServer||J>1,Z=J>1||!!$.server?.loadBalancer;return{appServers:J,loadBalancer:Z,dedicatedServices:Y,servicesOnApp:!Y}}function IH($,J){let Y={REDIS_HOST:$,MEILISEARCH_HOST:`http://${$}:7700`};if(J?.name){if(Y.DB_CONNECTION=J.engine==="postgres"?"pgsql":"mysql",Y.DB_HOST=$,Y.DB_PORT=String(J.port??(J.engine==="postgres"?5432:3306)),Y.DB_DATABASE=J.name,J.username)Y.DB_USERNAME=J.username;if(J.password)Y.DB_PASSWORD=J.password}return Y}function EQ($){let J=new Set([80,443,...$.sitePorts]);if($.allowSsh)J.add(22);return[...J].map((Y)=>{return{direction:"in",protocol:"tcp",port:String(Y),source_ips:["0.0.0.0/0","::/0"],description:`ts-cloud port ${Y}`}})}function x7($){if(!$)return MQ.micro;if($ in MQ)return MQ[$];return $}function R2($,J,Y="app"){return{[`${O$}/project`]:$,[`${O$}/environment`]:J,[`${O$}/role`]:Y,[`${O$}/managed-by`]:"ts-cloud"}}function A$($,J,Y,Z="app"){if(!$)return!1;return $[`${O$}/project`]===J&&$[`${O$}/environment`]===Y&&$[`${O$}/role`]===Z}var MQ,O$="ts-cloud";var kH=o(()=>{MQ={micro:"cpx11",small:"cx23",medium:"cx33",large:"cx43",xlarge:"cx53","2xlarge":"ccx33"}});import{mkdir as lq,readFile as pq,writeFile as rq}from"node:fs/promises";import{join as hH}from"node:path";function yH($){return hH(process.cwd(),bH,`${$}.json`)}async function A9($){try{let J=await pq(yH($),"utf8");return JSON.parse(J)}catch{return null}}async function V9($,J){let Y=yH($);await lq(hH(process.cwd(),bH),{recursive:!0}),await rq(Y,`${JSON.stringify(J,null,2)}
|
|
7460
|
+
`,"utf8")}var bH=".ts-cloud/state";var vH=()=>{};import{existsSync as nq,readFileSync as iq}from"node:fs";import{homedir as aq}from"node:os";import{join as tq}from"node:path";import{execSync as qQ}from"node:child_process";function fH($){return $.startsWith("~/")?tq(aq(),$.slice(2)):$}var TQ=268435456,V$;var wQ=o(async()=>{AQ();C7();BQ();q7();E7();UQ();kH();vH();await n0();V$=class V${name="hetzner";usesCloudFormation=!1;client;sshPrivateKeyPath;sshPublicKeyPath;sshUser;location;waitForBoot;bootWait;constructor($={}){this.client=$.client??new X9({apiToken:N7($.apiToken)}),this.sshPrivateKeyPath=fH($.sshPrivateKeyPath||process.env.HCLOUD_SSH_KEY||"~/.ssh/id_ed25519"),this.sshPublicKeyPath=fH($.sshPublicKeyPath||process.env.HCLOUD_SSH_PUBLIC_KEY||`${this.sshPrivateKeyPath}.pub`),this.sshUser=$.sshUser||process.env.HCLOUD_SSH_USER||"root",this.location=$.location||process.env.HCLOUD_LOCATION||"fsn1",this.waitForBoot=$.waitForBoot??!0,this.bootWait={sshIntervalMs:$.bootWait?.sshIntervalMs??5000,sshTimeoutMs:$.bootWait?.sshTimeoutMs??300000,cloudInitIntervalMs:$.bootWait?.cloudInitIntervalMs??5000,cloudInitTimeoutMs:$.bootWait?.cloudInitTimeoutMs??600000}}async provisionComputeInfrastructure($){let{config:J,environment:Y}=$,Z=J.project.slug,Q=J.infrastructure?.compute;if(!Q)throw Error("infrastructure.compute is required to provision Hetzner compute");let G=j1(J,Y),W=`${Z}-${Y}-app`,z=xH(Q);if(z.dedicatedServices||z.appServers>1)return this.provisionFleet($,z);let U=await A9(G);if(U?.serverId){let y=await this.tryGetServer(U.serverId);if(y&&y.status!=="off")return this.outputsFromState(U,y)}let H=R2(Z,Y,"app"),F=await this.findExistingServer(Z,Y,W);if(F&&F.status!=="off"){let y={provider:"hetzner",stackName:G,serverId:F.id,serverName:F.name,publicIp:F.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await V9(G,y),this.outputsFromState(y,F)}let B=J.sites||{},K=this.collectUpstreamPorts(B),O=Q.proxy?.engine==="rpx"?O9({proxy:Q.proxy,config:K9(B,{proxy:Q.proxy}),slug:J.project.slug,bunBin:Q.runtime==="node"||Q.runtime==="deno"?void 0:"/usr/local/bin/bun"}):void 0,V=R7(J),A=Q.bakedImage===!0,_=w2({runtime:V.runtime,runtimeVersion:V.runtimeVersion,systemPackages:Q.systemPackages,database:J.infrastructure?.database,phpProvision:V.phpProvision,servicesProvision:V.servicesProvision,rpxProvision:O,baked:A}),M=s$(_),E=x7(Q.size),j=Q.image||J.hetzner?.image||"ubuntu-24.04",q=`${Z}-${Y}-app-fw`,{firewall:T}=await this.ensureFirewall(q,H,EQ({allowSsh:Q.allowSsh!==!1,sitePorts:K})),D=await this.ensureSshKey(Z,Y,H),{server:S,action:P}=await this.client.createServer({name:W,serverType:E,image:j,location:J.hetzner?.location||this.location,userData:M,labels:H,sshKeys:D?[D]:void 0,firewalls:[{firewall:T.id}]});await this.client.waitForAction(P.id);let C=await this.client.waitForServerRunning(S.id),I={provider:"hetzner",stackName:G,serverId:C.id,serverName:C.name,firewallId:T.id,publicIp:C.public_net.ipv4?.ip,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};await V9(G,I);let b=C.public_net.ipv4?.ip;if(b&&this.waitForBoot)await this.waitForSshReady(b),await this.waitForCloudInit(b);return this.outputsFromState(I,C)}async provisionFleet($,J){let{config:Y,environment:Z}=$,Q=Y.project.slug,G=Y.infrastructure.compute,W=j1(Y,Z),z=x7(G.size),U=G.image||Y.hetzner?.image||"ubuntu-24.04",H=Y.hetzner?.location||this.location,F=G.bakedImage===!0,B=await A9(W);if(B?.loadBalancerId){let a=(await this.client.listLoadBalancers().catch(()=>[])).find((e)=>e.id===B.loadBalancerId);if(a)return{appPublicIp:a.public_net?.ipv4?.ip,loadBalancerIp:a.public_net?.ipv4?.ip,servicesPrivateIp:B.servicesPrivateIp,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}let K=await this.ensureSshKey(Q,Z,R2(Q,Z,"app")),O=`${Q}-${Z}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((t)=>t.name===O)??await this.client.createNetwork({name:O,labels:R2(Q,Z,"app")}),{firewall:_}=await this.ensureFirewall(`${Q}-${Z}-app-fw`,R2(Q,Z,"app"),EQ({allowSsh:!0,sitePorts:[]})),{firewall:M}=await this.ensureFirewall(`${Q}-${Z}-services-fw`,R2(Q,Z,"services"),[{direction:"in",protocol:"tcp",port:"22",source_ips:["0.0.0.0/0","::/0"]},{direction:"in",protocol:"tcp",port:"3306",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"5432",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"6379",source_ips:[A.ip_range]},{direction:"in",protocol:"tcp",port:"7700",source_ips:[A.ip_range]}]),E=[...j7(G.managedServices??{mysql:!0,redis:!0},{bindPrivate:!0}),...L7(Y.infrastructure?.appDatabase,G.managedServices??{mysql:!0}),...G9(!0),...W9(!0),...z9(G.sshKeys)],j=s$(w2({runtime:"php",servicesProvision:E,baked:F})),q=await this.client.listServers().catch(()=>[]),T=[],D=q.find((t)=>A$(t.labels,Q,Z,"services"));if(!D){let{server:t,action:a}=await this.client.createServer({name:`${Q}-${Z}-services`,serverType:x7(typeof G.servicesServer==="object"?G.servicesServer.size:G.size),image:U,location:H,userData:j,labels:R2(Q,Z,"services"),sshKeys:K?[K]:void 0,firewalls:[{firewall:M.id}],networks:[A.id]});await this.client.waitForAction(a.id),D=await this.client.waitForServerRunning(t.id),T.push(t.id)}let S=D.id,P=D.private_net?.[0]?.ip??(await this.client.getServer(S)).private_net?.[0]?.ip,C=[...G9(!0),...W9(!0),...z9(G.sshKeys),...D7(Y.notifications)],I=M7({versions:G.php?.versions,default:G.php?.default,extensions:G.php?.extensions,installNginx:G.webServer!=="rpx",optimizeForProduction:G.php?.optimizeForProduction,ini:G.php?.ini}),b=s$(w2({runtime:"php",phpProvision:I,servicesProvision:C,baked:F})),y=q.filter((t)=>A$(t.labels,Q,Z,"app")),c=y.map((t)=>t.id);if(y.length>J.appServers)for(let t of y.slice(J.appServers))await this.client.deleteServer(t.id).catch(()=>{}),c.splice(c.indexOf(t.id),1);for(let t=y.length;t<J.appServers;t++){let{server:a,action:e}=await this.client.createServer({name:`${Q}-${Z}-app-${t+1}`,serverType:z,image:U,location:H,userData:b,labels:R2(Q,Z,"app"),sshKeys:K?[K]:void 0,firewalls:[{firewall:_.id}],networks:[A.id]});await this.client.waitForAction(e.id),c.push(a.id),T.push(a.id)}if(this.waitForBoot&&T.length>0)await Promise.all(T.map(async(t)=>{let e=(await this.client.waitForServerRunning(t)).public_net.ipv4?.ip;if(e)await this.waitForSshReady(e),await this.waitForCloudInit(e)}));let r=`${Q}-${Z}-lb`,d,u;if(J.loadBalancer){let a=(await this.client.listLoadBalancers().catch(()=>[])).find((e)=>e.name===r)??await this.client.createLoadBalancer({name:r,location:H,network:A.id,labels:R2(Q,Z,"lb"),labelSelector:`ts-cloud/project=${Q},ts-cloud/environment=${Z},ts-cloud/role=app`,services:[{listenPort:80,destinationPort:80},{listenPort:443,destinationPort:443}]});u=a.id,d=a.public_net?.ipv4?.ip}let s=d??(await this.client.getServer(c[0]).catch(()=>{return}))?.public_net.ipv4?.ip,J0={provider:"hetzner",stackName:W,networkId:A.id,loadBalancerId:u,servicesServerId:S,servicesPrivateIp:P,publicIp:s,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser};return await V9(W,J0),{appPublicIp:s,loadBalancerIp:d,servicesPrivateIp:P,deployStoragePath:"/var/ts-cloud/staging",sshUser:this.sshUser}}async destroyCompute($){let{config:J,environment:Y}=$,Z=J.project.slug,Q=j1(J,Y),G=await A9(Q),W=[],z=`${Z}-${Y}-lb`,H=(await this.client.listLoadBalancers().catch(()=>[])).find((_)=>_.name===z);if(H)try{await this.client.deleteLoadBalancer(H.id),W.push(`load balancer ${z}`)}catch{}let F=await this.client.listServers().catch(()=>[]),B=new Set;for(let _ of F)if(A$(_.labels,Z,Y,"app")||A$(_.labels,Z,Y,"services"))B.add(_.id);if(G?.serverId)B.add(G.serverId);if(G?.servicesServerId)B.add(G.servicesServerId);for(let _ of B)try{await this.client.deleteServer(_),W.push(`server ${_}`)}catch{}let K=await this.client.listFirewalls().catch(()=>[]);for(let _ of[`${Z}-${Y}-app-fw`,`${Z}-${Y}-services-fw`]){let M=K.find((E)=>E.name===_);if(!M)continue;for(let E=0;E<12;E++)try{await this.client.deleteFirewall(M.id),W.push(`firewall ${_}`);break}catch{await this.sleep(3000)}}let O=`${Z}-${Y}-net`,A=(await this.client.listNetworks().catch(()=>[])).find((_)=>_.name===O);if(A)for(let _=0;_<12;_++)try{await this.client.deleteNetwork(A.id),W.push(`network ${O}`);break}catch{await this.sleep(3000)}return await V9(Q,{provider:"hetzner",stackName:Q}).catch(()=>{}),{destroyed:W}}async getComputeOutputs($){let J=j1($.config,$.environment),Y=await A9(J);if(Y?.serverId){let G=await this.client.getServer(Y.serverId);return this.outputsFromState(Y,G)}if(Y?.loadBalancerId||Y?.servicesPrivateIp)return this.outputsFromState(Y);let Q=(await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app"}))[0];return{deployStoragePath:"/var/ts-cloud/staging",appInstanceId:Q?.id,appPublicIp:Q?.publicIp,sshUser:this.sshUser}}async uploadRelease($){let J=$.targets?.length?$.targets:await this.findComputeTargets({slug:$.config.project.slug,environment:$.environment,role:"app"});if(J.length===0)throw Error("No Hetzner compute targets found for release upload");let Y=`/var/ts-cloud/staging/${$.remoteKey.split("/").pop()}`;for(let Z of J){if(!Z.publicIp)throw Error(`Target ${Z.id} has no public IP for SCP upload`);this.scpToHost(Z.publicIp,$.localPath,Y)}return{artifactRef:Y}}async findComputeTargets($){return(await this.client.listServers()).filter((Y)=>A$(Y.labels,$.slug,$.environment,$.role||"app")).map((Y)=>({id:String(Y.id),name:Y.name,publicIp:Y.public_net.ipv4?.ip,privateIp:Y.private_net?.[0]?.ip,status:Y.status}))}async runRemoteDeploy($){if($.targets.length===0)return{success:!1,instanceCount:0,perInstance:[],error:"No targets provided"};let J=$.commands.join(`
|
|
7461
|
+
`),Y=[];for(let Q of $.targets){if(!Q.publicIp){Y.push({instanceId:Q.id,status:"Failed",error:"Missing public IP"});continue}try{let G=this.sshExec(Q.publicIp,J);Y.push({instanceId:Q.id,status:"Success",output:G})}catch(G){Y.push({instanceId:Q.id,status:"Failed",error:G.message})}}let Z=Y.every((Q)=>Q.status==="Success");return{success:Z,instanceCount:$.targets.length,perInstance:Y,error:Z?void 0:"One or more SSH deploy commands failed"}}async ensureSshKey($,J,Y){if(!nq(this.sshPublicKeyPath))throw Error(`SSH public key not found at ${this.sshPublicKeyPath}. ts-cloud deploys to Hetzner over SSH and needs a public key to authorize on the server. Generate one (\`ssh-keygen -t ed25519\`) or set hetzner.sshPrivateKeyPath / HCLOUD_SSH_PUBLIC_KEY.`);let Z=iq(this.sshPublicKeyPath,"utf8").trim(),Q=OQ(Z),W=(await this.client.listSshKeys()).find((U)=>OQ(U.public_key)===Q);if(W)return W.id;return(await this.client.createSshKey({name:`${$}-${J}-deploy`,publicKey:Z,labels:Y})).id}async tryGetServer($){try{return await this.client.getServer($)}catch{return null}}async findExistingServer($,J,Y){return(await this.client.listServers()).find((Q)=>A$(Q.labels,$,J,"app")||Q.name===Y)}async ensureFirewall($,J,Y){let Q=(await this.client.listFirewalls()).find((W)=>W.name===$);if(Q)return await this.client.setFirewallRules(Q.id,Y),{firewall:Q};let{firewall:G}=await this.client.createFirewall({name:$,labels:J,rules:Y});return{firewall:G}}collectUpstreamPorts($){let J=new Set;for(let Y of Object.values($))if(typeof Y.port==="number")J.add(Y.port);return[...J].filter((Y)=>![80,443].includes(Y))}async sleep($){await new Promise((J)=>setTimeout(J,$))}async waitForSshReady($){let{sshIntervalMs:J,sshTimeoutMs:Y}=this.bootWait,Z=Date.now(),Q;while(Date.now()-Z<Y)try{qQ(`ssh ${this.sshBaseArgs($,["-o","ConnectTimeout=5"]).map((G)=>`"${G.replace(/"/g,"\\\"")}"`).join(" ")} true`,{stdio:"pipe",maxBuffer:TQ});return}catch(G){Q=G,await this.sleep(J)}throw Error(`Timed out waiting for SSH on ${$} after ${Y}ms: ${Q?.message??"unknown error"}`)}async waitForCloudInit($){let{cloudInitIntervalMs:J,cloudInitTimeoutMs:Y}=this.bootWait,Z=Date.now();while(Date.now()-Z<Y){try{let Q=this.sshExec($,"cloud-init status --long 2>/dev/null || cloud-init status 2>/dev/null || echo status:\\ done");if(/status:\s*done/.test(Q))return;if(/status:\s*error/.test(Q))throw Error(`cloud-init reported an error on ${$}:
|
|
7462
|
+
${Q}`)}catch(Q){if(Q instanceof Error&&/cloud-init reported an error/.test(Q.message))throw Q}await this.sleep(J)}throw Error(`Timed out waiting for cloud-init to finish on ${$} after ${Y}ms`)}outputsFromState($,J){return{deployStoragePath:$.deployStoragePath||"/var/ts-cloud/staging",appInstanceId:$.serverId?String($.serverId):void 0,appPublicIp:J?.public_net.ipv4?.ip||$.publicIp,sshUser:$.sshUser||this.sshUser,servicesPrivateIp:$.servicesPrivateIp}}static SSH_HOST_KEY_OPTS=["-o","StrictHostKeyChecking=no","-o","UserKnownHostsFile=/dev/null","-o","LogLevel=ERROR"];sshBaseArgs($,J=[]){return["-i",this.sshPrivateKeyPath,...V$.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",...J,`${this.sshUser}@${$}`]}scpToHost($,J,Y){qQ(["scp","-i",this.sshPrivateKeyPath,...V$.SSH_HOST_KEY_OPTS,"-o","BatchMode=yes",J,`${this.sshUser}@${$}:${Y}`].map((Z)=>`"${Z.replace(/"/g,"\\\"")}"`).join(" "),{stdio:"pipe",maxBuffer:TQ})}sshExec($,J){let Y=J.replace(/'/g,"'\\''");return qQ(`ssh ${this.sshBaseArgs($).map((Z)=>`"${Z.replace(/"/g,"\\\"")}"`).join(" ")} '${Y}'`,{encoding:"utf8",stdio:["pipe","pipe","pipe"],maxBuffer:TQ})}}});class I7{name="hetzner";usesCloudFormation=!1;async getComputeOutputs(){return{appPublicIp:"127.0.0.1",sshUser:"root"}}async uploadRelease($){return{artifactRef:$.localPath}}async findComputeTargets($){return[{id:"localhost",name:"localhost",publicIp:"127.0.0.1",status:"running"}]}async runRemoteDeploy($){let J=$.commands.join(`
|
|
7463
|
+
`);try{let Y=Bun.spawn(["bash","-c",J],{stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{success:G===0,instanceCount:1,perInstance:[{instanceId:"localhost",status:G===0?"Success":"Failed",output:Z,error:Q}]}}catch(Y){return{success:!1,instanceCount:1,perInstance:[{instanceId:"localhost",status:"Failed",error:Y?.message??String(Y)}],error:Y?.message??String(Y)}}}}function DQ(){let $=process.env.TS_CLOUD_DASHBOARD_BOX;return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function Y1($){if(DQ())return new I7;switch($.provider??M2($.config)){case"aws":return new F9({region:$.config.project.region});case"hetzner":return new V$({apiToken:$.config.hetzner?.apiToken,sshPrivateKeyPath:$.config.hetzner?.sshPrivateKeyPath,sshUser:$.config.hetzner?.sshUser,location:$.config.hetzner?.location});default:throw Error(`Unknown cloud provider: ${$.provider??M2($.config)}`)}}class RQ{drivers=new Map;getDriver($,J){let Y=J??M2($),Z=`${Y}:${$.project.slug}:${$.project.region||"default"}`,Q=this.drivers.get(Z);if(Q)return Q;let G=Y1({config:$,provider:Y});return this.drivers.set(Z,G),G}}var sq;var gH=o(async()=>{await z8([n0(),KQ(),wQ()]);sq=new RQ});function k7($){return Object.entries($).map(([J,Y])=>`${J}=${oq(String(Y))}`).join(`
|
|
7464
|
+
`)}function oq($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function NQ($){return`${$.replace(/\/+$/,"")}/.ts-cloud`}function SQ($){return`${NQ($)}/deploy-history.log`}function eq($,J){return`${NQ($)}/deploys/${J}.log`}function _$($,J){let Y=$.replace(/\/+$/,"");return{base:Y,releases:`${Y}/releases`,shared:`${Y}/shared`,current:`${Y}/current`,release:`${Y}/releases/${J}`}}function $T($){let J=$.split("/").pop()||$;return J.startsWith(".")||/\.[a-z0-9]+$/i.test(J)}function j9($,J=h7){let Y=[`mkdir -p ${$.releases} ${$.shared}`];for(let Z of J)if($T(Z))Y.push(`mkdir -p "$(dirname ${$.shared}/${Z})"`,`touch ${$.shared}/${Z}`);else if(Z==="storage")Y.push(`mkdir -p ${$.shared}/storage/app/public`,`mkdir -p ${$.shared}/storage/framework/cache/data`,`mkdir -p ${$.shared}/storage/framework/sessions`,`mkdir -p ${$.shared}/storage/framework/testing`,`mkdir -p ${$.shared}/storage/framework/views`,`mkdir -p ${$.shared}/storage/logs`);else Y.push(`mkdir -p ${$.shared}/${Z}`);return Y}function b7($,J=h7){let Y=[];for(let Z of J){let Q=`${$.shared}/${Z}`,G=`${$.release}/${Z}`;Y.push(`rm -rf ${G}`,`mkdir -p "$(dirname ${G})"`,`ln -sfn ${Q} ${G}`)}return Y}function L9($){return[`ln -sfn ${$.release} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]}function uH($,J={}){if(J.to){let Y=`${$.releases}/${J.to}`;return[`[ -d ${Y} ] || { echo "rollback target ${Y} not found" >&2; exit 1; }`,`ln -sfn ${Y} ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`]}return[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`TS_CLOUD_PREV=$(ls -1dt ${$.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; }',`ln -sfn "$TS_CLOUD_PREV" ${$.current}.tmp`,`mv -Tf ${$.current}.tmp ${$.current}`,'echo "rolled back to $TS_CLOUD_PREV"']}function E9($,J=4){let Y=Math.max(1,J);return[`TS_CLOUD_CURRENT=$(readlink -f ${$.current} 2>/dev/null || true)`,`ls -1dt ${$.releases}/*/ 2>/dev/null | sed 's#/$##' | tail -n +${Y+1} | while read -r TS_CLOUD_OLD; do`,' [ "$(readlink -f "$TS_CLOUD_OLD")" = "$TS_CLOUD_CURRENT" ] || rm -rf "$TS_CLOUD_OLD"',"done"]}function y7($,J){let Y=NQ($),Z=eq($,J.releaseId),Q=SQ($),G=Math.max(1,J.keepLogs??20),W=J.commit||"",z=J.branch||"";return[`mkdir -p ${Y}/deploys`,`exec > >(tee -a ${Z}) 2>&1`,`echo "[ts-cloud] deploy ${J.releaseId} commit=${W} branch=${z} 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)" "${J.releaseId}" "${W}" "$TS_CLOUD_ST" "$TS_CLOUD_RC" >> ${Q}`,"}","trap ts_cloud_record_deploy EXIT",`ls -1t ${Y}/deploys/*.log 2>/dev/null | tail -n +${G+1} | while read -r TS_CLOUD_OLDLOG; do rm -f "$TS_CLOUD_OLDLOG"; done`]}var h7,_9=4;var M9=o(()=>{h7=["storage",".env"]});function v7($,J){let Y=J==="bun"?"/usr/local/bin/bun":J==="deno"?"/usr/local/bin/deno":"/usr/local/bin/node",Z=$.replace(/^(bun|node|deno)\s+/,"");return`${Y} ${Z}`}function f7($){let{siteName:J,slug:Y,artifactFetch:Z,releaseId:Q,execStart:G,envEntries:W,port:z,keepReleases:U=_9,preStartCommands:H=[]}=$,F=$.appDir??`/var/www/${J}`,B=_$(F,Q),K=`${Y}-${J}.service`,O=[".env"],V=k7(W),A=H.length>0?[`cd ${B.release}`,...H]:[];return["set -euo pipefail",...Z,...j9(B,O),`rm -rf ${B.release}`,`mkdir -p ${B.release}`,`tar xzf /tmp/${J}-release.tar.gz -C ${B.release}`,`cat > ${B.shared}/.env <<'TS_CLOUD_ENV_EOF'`,V,"TS_CLOUD_ENV_EOF",`chmod 600 ${B.shared}/.env`,...b7(B,O),...A,`cat > /etc/systemd/system/${K} <<'TS_CLOUD_UNIT_EOF'`,"[Unit]",`Description=${J} (managed by ts-cloud)`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${B.current}`,`ExecStart=${G}`,"Restart=always","RestartSec=5",`EnvironmentFile=${B.current}/.env`,...z?[`Environment=PORT=${z}`]:[],"","[Install]","WantedBy=multi-user.target","TS_CLOUD_UNIT_EOF","systemctl daemon-reload",`systemctl enable ${K}`,...L9(B),`systemctl restart ${K}`,`systemctl is-active ${K}`,...E9(B,U)]}function g7($){let{siteName:J,artifactFetch:Y,releaseId:Z,keepReleases:Q=_9,preStartCommands:G=[]}=$,W=$.appDir??`/var/www/${J}`,z=_$(W,Z),U=G.length>0?[`cd ${z.release}`,...G]:[];return["set -euo pipefail",...Y,...j9(z,[]),`rm -rf ${z.release}`,`mkdir -p ${z.release}`,`tar xzf /tmp/${J}-release.tar.gz -C ${z.release}`,...U,...L9(z),...E9(z,Q)]}function PQ($,J,Y,Z){return[`aws s3 cp "s3://${$}/${J}" /tmp/${Z}-release.tar.gz --region ${Y}`]}function CQ($,J){return[`cp "${$}" /tmp/${J}-release.tar.gz`]}var xQ=o(()=>{M9()});var lH={};h0(lH,{resolveUiSource:()=>u7,ensureManagementDashboard:()=>IQ,buildManagementDashboardArtifact:()=>kQ,MANAGEMENT_DASHBOARD_SITE:()=>$8});import{execSync as dH}from"node:child_process";import{existsSync as q9}from"node:fs";import{tmpdir as JT}from"node:os";import{dirname as YT,isAbsolute as ZT,join as U2}from"node:path";import{fileURLToPath as QT}from"node:url";function cH($){return $!=null&&$!==""&&$!=="0"&&$.toLowerCase()!=="false"}function u7($){if(q9(U2($,"packages","ui","pages"))||q9(U2($,"packages","ui","package.json")))return{uiRoot:"packages/ui/dist",build:"cd packages/ui && bun install && bun run build"};let J=YT(QT(import.meta.url)),Y=[U2(J,"ui"),U2(J,"..","ui"),U2(J,"..","..","ui"),U2(J,"..","dist","ui")];for(let Z of Y)if(q9(U2(Z,"index.html"))||q9(U2(Z,"serverless.html")))return{uiRoot:Z,build:!1};return null}function IQ($,J={}){let Y=J.logger??mH,Z=J.cwd??process.cwd();if(cH(process.env.TS_CLOUD_UI_DISABLE))return Y.info("Management dashboard: skipped (TS_CLOUD_UI_DISABLE set)."),$;if(U$($))return $;let Q=u7(Z);if(!Q)return Y.info("Management dashboard: UI not found (no local ui/ or packaged dist/ui) — skipping auto-deploy."),$;let G=process.env.TS_CLOUD_UI_PASSWORD?.trim()||void 0,W=$.environments&&Object.keys($.environments)[0],z=cH(process.env.TS_CLOUD_UI_LIVE),U=Number(process.env.TS_CLOUD_UI_PORT)||void 0,H=yJ($,W??"production",{uiRoot:Q.uiRoot,build:Q.build,domain:process.env.TS_CLOUD_UI_DOMAIN?.trim()||void 0,username:process.env.TS_CLOUD_UI_USERNAME?.trim()||void 0,password:G,realm:process.env.TS_CLOUD_UI_REALM?.trim()||void 0,live:z,port:U});if(!H)return Y.info("Management dashboard: no domain resolved (set TS_CLOUD_UI_DOMAIN or configure a site domain) — skipping."),$;return $.sites={...$.sites??{},[H.name]:H.site},Y.info(`Management dashboard → https://${H.site.domain} (${G?"htpasswd-protected":"NO AUTH — set TS_CLOUD_UI_PASSWORD"})`),$}function kQ($,J){if(!$?.root)return null;let Y=J.cwd??process.cwd(),Z=J.logger??mH;try{if(typeof $.build==="string"&&$.build.trim())Z.info(`Management dashboard: building UI (${$.build})`),dH($.build,{cwd:Y,stdio:"inherit"});let Q=ZT($.root)?$.root:U2(Y,$.root);if(!q9(Q))return Z.warn(`Management dashboard: build output not found at ${Q} — skipping dashboard artifact.`),null;let G=U2(JT(),`${J.slug}-${$8}-${J.sha}.tar.gz`);return dH(`tar czf "${G}" -C "${Q}" .`,{stdio:"inherit"}),G}catch(Q){return Z.warn(`Management dashboard: failed to build artifact — ${Q?.message??Q}. Skipping dashboard deploy.`),null}}var $8="dashboard",mH;var d7=o(async()=>{await n0();mH={info:()=>{},warn:()=>{}}});function hQ($){if($.ssl?.provider)return $.ssl.provider;return $.domain?"letsencrypt":"none"}function rH($){return`/etc/letsencrypt/ts-cloud-${$}.ini`}function GT($){let J=$?pH[$.provider]:void 0,Y=["certbot","python3-certbot-nginx",...J?[J.pkg]:[]].join(" ");return["export DEBIAN_FRONTEND=noninteractive",J?`apt-get update -y && apt-get install -y ${Y}`:`command -v certbot >/dev/null 2>&1 || { apt-get update -y && apt-get install -y ${Y}; }`,"mkdir -p /etc/letsencrypt/renewal-hooks/deploy","cat > /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'TS_CLOUD_HOOK_EOF'","#!/bin/sh","systemctl reload nginx","TS_CLOUD_HOOK_EOF","chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh","systemctl enable certbot.timer 2>/dev/null || true","systemctl start certbot.timer 2>/dev/null || true"]}function WT($){if(!$.credentials||Object.keys($.credentials).length===0)return[];let J=rH($.provider),Y=Object.entries($.credentials).map(([Z,Q])=>`${Z} = ${Q}`).join(`
|
|
7465
|
+
`);return[`cat > ${J} <<'TS_CLOUD_DNSCREDS_EOF'`,Y,"TS_CLOUD_DNSCREDS_EOF",`chmod 600 ${J}`]}function zT($){let J=$.dns,Y=$.wildcard?[`*.${$.domain}`,$.domain]:[$.domain,...$.aliases||[]].filter(Boolean),Z=["certbot","--non-interactive","--agree-tos","--keep-until-expiring"];if(J){let Q=pH[J.provider].plugin;if(Z.push(`--${Q}`),J.provider!=="route53"&&J.credentials)Z.push(`--${Q}-credentials ${rH(J.provider)}`);if(typeof J.propagationSeconds==="number"&&J.provider!=="route53")Z.push(`--${Q}-propagation-seconds ${J.propagationSeconds}`);Z.push("certonly")}else Z.push("--nginx",$.redirect===!1?"--no-redirect":"--redirect");if($.email)Z.push(`-m ${$.email}`);else Z.push("--register-unsafely-without-email");for(let Q of Y)Z.push(`-d ${Q}`);return[Z.join(" ")]}function bQ($){if(hQ($)!=="letsencrypt"||!$.domain)return[];let J=$.ssl,Y=J?.dns,Z=J?.wildcard===!0;if(Z&&!Y)return[];return[...GT(Y),...Y?WT(Y):[],...zT({domain:$.domain,aliases:$.aliases,email:J?.email,wildcard:Z,dns:Y})]}var pH;var nH=o(()=>{pH={cloudflare:{pkg:"python3-certbot-dns-cloudflare",plugin:"dns-cloudflare"},route53:{pkg:"python3-certbot-dns-route53",plugin:"dns-route53"},digitalocean:{pkg:"python3-certbot-dns-digitalocean",plugin:"dns-digitalocean"},google:{pkg:"python3-certbot-dns-google",plugin:"dns-google"}}});function aH($){let{repository:J,releaseDir:Y,commit:Z}=$,Q=J.branch||"main",G=J.url,W=[`rm -rf ${Y}`,`mkdir -p ${Y}`];if(J.strategy==="tag")if(J.tag)W.push(`git clone -q --depth 1 --branch ${J.tag} ${G} ${Y}`),W.push(`printf '%s' ${iH(J.tag)} > ${Y}/.ts-cloud-tag`);else{let z=J.tagPattern||"v*";W.push(`TS_CLOUD_TAG="$(git ls-remote --tags --refs --sort=-v:refname ${G} ${iH(`refs/tags/${z}`)} | head -n1 | sed 's#.*refs/tags/##')"`,`test -n "$TS_CLOUD_TAG" || { echo "no tags matching ${z} found in ${G}" >&2; exit 1; }`,`git clone -q --depth 1 --branch "$TS_CLOUD_TAG" ${G} ${Y}`,`printf '%s' "$TS_CLOUD_TAG" > ${Y}/.ts-cloud-tag`)}else if(Z)W.push(`git -C ${Y} init -q`,`git -C ${Y} remote add origin ${G}`,`git -C ${Y} fetch -q --depth 1 origin ${Z}`,`git -C ${Y} checkout -q FETCH_HEAD`);else W.push(`git clone -q --depth 1 --branch ${Q} ${G} ${Y}`);return W.push(`git -C ${Y} rev-parse HEAD > ${Y}/.ts-cloud-sha`),W}function iH($){return`'${$.split("'").join("'\\''")}'`}function HT($){switch($){case"laravel":case"statamic":return[c7,tH,...UT,m7,oH];case"php":case"wordpress":return[c7,`${tH} || true`,m7];case"static":case"spa":return[c7,m7]}}function FT($,J){return $.replace(/^php\s+/,`${J} `).replace(/(\s)php\s+artisan\s+/g,`$1${J} artisan `)}function XT($,J){let Y=k7(J);return[`cat > ${$} <<'TS_CLOUD_ENV_EOF'`,Y,"TS_CLOUD_ENV_EOF",`chmod 600 ${$}`]}function sH($,J,Y){return[`cat > ${$} <<'${Y}'`,J.replace(/\n$/,""),Y,`chmod 600 ${$}`]}function BT($,J){if(!J)return[];let Y=[];if(J.composerAuth){let Z=typeof J.composerAuth==="string"?J.composerAuth:JSON.stringify(J.composerAuth,null,2);Y.push(...sH(`${$}/auth.json`,Z,"TS_CLOUD_AUTHJSON_EOF"))}if(J.npmrc)Y.push(...sH(`${$}/.npmrc`,J.npmrc,"TS_CLOUD_NPMRC_EOF"));return Y}function eH($){let J=$.healthCheck?.path;if(!J||!$.domain)return[];let Z=`http://127.0.0.1${J.startsWith("/")?J:`/${J}`}`;return[`echo "[ts-cloud] health check ${Z} (Host: ${$.domain})"`,"TS_CLOUD_HC_OK=0",`for i in $(seq 1 10); do TS_CLOUD_HC=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${$.domain}" -m 10 "${Z}" 2>/dev/null || echo 000); case "$TS_CLOUD_HC" in 2*|3*) TS_CLOUD_HC_OK=1; break ;; esac; sleep 3; done`,'[ "$TS_CLOUD_HC_OK" = 1 ] && echo "health check passed ($TS_CLOUD_HC)" || { echo "health check FAILED (last=$TS_CLOUD_HC)" >&2; exit 1; }']}function $F($){let{siteName:J,site:Y,releaseId:Z,commit:Q}=$;if(!Y.repository?.url)throw Error(`Site '${J}' is a PHP/git site but has no repository.url to clone`);let G=$.appBase??`/var/www/${J}`,W="php",z=_$(G,Z),U=Y.sharedPaths??h7,H=Y.keepReleases??_9,F=Y.deployScript?.length?Y.deployScript:HT(Y.type??"laravel"),B=["set -euo pipefail",'export HOME="${HOME:-/root}"','export COMPOSER_HOME="${COMPOSER_HOME:-/root/.composer}"',"export COMPOSER_ALLOW_SUPERUSER=1",B$()];if(B.push(...y7(G,{releaseId:Z,commit:Q,branch:Y.repository.branch,keepLogs:H})),B.push(...j9(z,U)),Y.env&&Object.keys(Y.env).length>0)B.push(...XT(`${z.shared}/.env`,Y.env));for(let K of F){let O=K.trim();if(O===c7)B.push(...aH({repository:Y.repository,releaseDir:z.release,commit:Q})),B.push(...b7(z,U)),B.push(`cd ${z.release}`),B.push(...BT(z.release,Y.credentials)),B.push(`chown -R www-data:www-data ${z.shared}/storage 2>/dev/null || true`,`[ -d ${z.release}/bootstrap/cache ] && chown -R www-data:www-data ${z.release}/bootstrap/cache 2>/dev/null || true`,`chmod -R ug+rwX ${z.shared}/storage 2>/dev/null || true`);else if(O===m7)B.push(...L9(z)),B.push(...E9(z,H)),B.push(`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`);else if(O===oH)B.push(`${W} artisan queue:restart || true`);else B.push(FT(K,W))}return B}var c7="$CREATE_RELEASE",m7="$ACTIVATE_RELEASE",oH="$RESTART_QUEUES",tH="composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev",UT;var JF=o(()=>{z2();M9();UT=["php artisan migrate --force","php artisan config:cache","php artisan route:cache","php artisan view:cache","php artisan event:cache","php artisan storage:link"]});function YF($){return`/bin/sh -lc '${zF}; exec ${$}'`}function ZF($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KT($){return`'${$.split("'").join("'\\''")}'`}function QF($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unnamed"}function OT($,J,Y){return`${$}-${J}-queue-${Y}`}function AT($,J,Y,Z){return`${$}-${J}-daemon-${Y.name?QF(Y.name):QF(Y.command).slice(0,32)||String(Z)}`}function VT($,J,Y){if($.horizon)return`${J} ${Y} horizon`;let Z=[$.connection||"default",`--queue=${$.queue||"default"}`,`--sleep=${$.sleep??3}`,`--tries=${$.tries??3}`,`--timeout=${$.timeout??60}`,`--memory=${$.memory??128}`];if($.maxJobs)Z.push(`--max-jobs=${$.maxJobs}`);if($.maxTime)Z.push(`--max-time=${$.maxTime}`);return`${J} ${Y} queue:work ${Z.join(" ")}`}function GF($){let J=["[Unit]",`Description=${$.description}`,"After=network.target","","[Service]","Type=simple",`WorkingDirectory=${$.workingDir}`,`ExecStart=${$.execStart}`,`Restart=${$.restart||"always"}`,"RestartSec=5"];if($.user)J.push(`User=${$.user}`);if(typeof $.stopWaitSecs==="number")J.push(`TimeoutStopSec=${$.stopWaitSecs}`);return J.push("","[Install]","WantedBy=multi-user.target"),`${J.join(`
|
|
7466
7466
|
`)}
|
|
7467
7467
|
`}function WF($,J){return[`cat > /etc/systemd/system/${$}.service <<'TS_CLOUD_UNIT_EOF'`,J.replace(/\n$/,""),"TS_CLOUD_UNIT_EOF"]}function _T($,J){return`/etc/cron.d/${$}-${J}-scheduler`}function UF($){let{slug:J,siteName:Y,site:Z}=$,Q="php",W=`${$.appBase??`/var/www/${Y}`}/current`,z=`${W}/artisan`,U=[],H=[];(Z.queues||[]).forEach((_,M)=>{let E=Math.max(1,_.processes??1);for(let j=0;j<E;j++){let q=OT(J,Y,H.length);H.push(q),U.push(...WF(q,GF({description:`${Y} queue worker ${M}.${j} (managed by ts-cloud)`,workingDir:W,execStart:YF(VT(_,"php",z)),stopWaitSecs:_.stopWaitSecs??90})))}}),(Z.daemons||[]).forEach((_,M)=>{let E=Math.max(1,_.processes??1);for(let j=0;j<E;j++){let q=`${AT(J,Y,_,M)}-${j}`;H.push(q),U.push(...WF(q,GF({description:`${Y} daemon ${_.name||_.command} (managed by ts-cloud)`,workingDir:_.directory||W,execStart:YF(_.command),restart:_.restart,user:_.user})))}});let K=H.map((_)=>`${_}.service`).join(" ");U.push("systemctl daemon-reload",`TS_CLOUD_DESIRED="${K}"`,`for unit in $(ls /etc/systemd/system/ 2>/dev/null | grep -E '^${ZF(J)}-${ZF(Y)}-(queue|daemon)-.*\\.service$' || true); do`,' case " $TS_CLOUD_DESIRED " in',' *" $unit "*) ;;',' *) systemctl stop "$unit" 2>/dev/null || true; systemctl disable "$unit" 2>/dev/null || true; rm -f "/etc/systemd/system/$unit" ;;'," esac","done","systemctl daemon-reload");for(let _ of H)U.push(`systemctl enable ${_}.service`,`systemctl restart ${_}.service`);let O=_T(J,Y),V=Z.scheduler;if(V===!0||typeof V==="object"&&V!==null){let _=typeof V==="object"&&V!==null?V:void 0,M=`cd ${W} && ${zF} && php artisan schedule:run >> /dev/null 2>&1`;if(_?.heartbeatUrl){let j=_.heartbeatMethod||"GET",q=j==="GET"?"":`-X ${j} `;M+=` && curl -fsS -m 10 ${q}${KT(_.heartbeatUrl)} >/dev/null 2>&1`}let E=`* * * * * root ${M}
|
|
7468
7468
|
`.replace(/%/g,"\\%");U.push(`cat > ${O} <<'TS_CLOUD_CRON_EOF'`,E.replace(/\n$/,""),"TS_CLOUD_CRON_EOF",`chmod 644 ${O}`)}else U.push(`rm -f ${O}`);return U}function HF($){return!!($.queues?.length||$.daemons?.length||$.scheduler)}var zF;var FF=o(()=>{z2();zF=`eval "$(cd ${S1} && pantry env 2>/dev/null)"`});function l7($){return($.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"site").slice(0,28)}function BF($){return`web_${l7($)}`}function ET($){let J=l7($),Y=0;for(let Z=0;Z<J.length;Z++)Y=Y*31+J.charCodeAt(Z)>>>0;return jT+Y%LT}function yQ($){return`127.0.0.1:${ET($)}`}function MT($){let J=l7($.siteName),Y=BF($.siteName),Z=$.maxChildren??10;return[`; ts-cloud-managed pool for ${$.siteName} (site isolation)`,`[${J}]`,`user = ${Y}`,`group = ${Y}`,`listen = ${yQ($.siteName)}`,"pm = dynamic",`pm.max_children = ${Z}`,"pm.start_servers = 2","pm.min_spare_servers = 1","pm.max_spare_servers = 3","pm.max_requests = 500","catch_workers_output = yes",`php_admin_value[open_basedir] = ${$.appBase}:/tmp`,""].join(`
|
|
7469
|
-
`)}function KF($){let J=BF($.siteName),Y=l7($.siteName),Z=`${XF}/${Y}.conf`;return[`getent group ${J} >/dev/null || groupadd --system ${J}`,`id -u ${J} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${J} ${J}`,`usermod -aG ${J} www-data 2>/dev/null || true`,`chown -R ${J}:${J} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${XF}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,MT($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`]}var XF="/var/lib/pantry/php-fpm/pool.d",jT=9100,LT=400;var OF=o(()=>{z2()});async function fQ($,J,Y=vQ){let{config:Z,environment:Q,siteName:G,site:W,slug:z,sha:U,runtime:H,localTarballPath:F}=J,B=`releases/${G}/${U}.tar.gz`,K=j1(Z,Q),O=await $.getComputeOutputs({config:Z,environment:Q}),V=await $.findComputeTargets({slug:z,environment:Q,role:"app"});if(V.length===0)return{success:!1,error:$.name==="aws"?`Stack '${K}' has no EC2 instances tagged Project=${z} Environment=${Q} Role=app.`:`No Hetzner servers labeled ts-cloud/project=${z} ts-cloud/environment=${Q} ts-cloud/role=app.`};if(B9(W)){let C=Z.infrastructure?.compute,I=W.phpVersion??C?.php?.default??C?.php?.versions?.[0],b=`/var/www/${G}`,y=O.servicesPrivateIp?IH(O.servicesPrivateIp,Z.infrastructure?.appDatabase):BH(Z.infrastructure?.appDatabase),c=Object.keys(y).length>0?{...W,env:{...y,...W.env||{}}}:W,r=$F({siteName:G,site:c,releaseId:U,appBase:b,defaultPhpVersion:I}),d=C?.webServer!=="rpx",s=hQ(W)==="custom"&&W.ssl?.certPath&&W.ssl?.keyPath?{certPath:W.ssl.certPath,keyPath:W.ssl.keyPath}:void 0,J0=W.isolation?KF({siteName:G,appBase:b}):[],t=d?GQ({siteName:G,domain:W.domain||G,aliases:W.aliases,type:W.type,appDir:`${b}/current`,webDirectory:W.webDirectory,phpVersion:I,fastcgiPass:W.isolation?yQ(G):void 0,redirects:W.redirects,ssl:s,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,C?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],a=d?bQ(W):[],e=HF(W)?UF({slug:z,siteName:G,site:W,phpVersion:I,appBase:b}):[],L0=d?eH(W):[];Y.step(`Deploying PHP site '${G}' to ${V.length} target(s)...`);let _0=await $.runRemoteDeploy({targets:V,commands:[...r,...J0,...t,...a,...e,...L0],comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}}),O0=EH(Z.notifications,W.notifications);if(!_0.success)return await FQ(O0,"deploy-failed",`❌ Deploy of ${z}/${G}@${U} failed: ${_0.error||"unknown error"}`),{success:!1,error:_0.error||"Remote PHP deploy failed",instanceCount:_0.instanceCount,perInstance:_0.perInstance};let T1=W.domain?` → https://${W.domain}`:"";return await FQ(O0,"deploy",`✅ Deployed ${z}/${G}@${U}${T1}`),{success:!0,instanceCount:_0.instanceCount,perInstance:_0.perInstance}}if(!F)return{success:!1,error:`Site '${G}' requires a release tarball but none was provided`};let A=await $.uploadRelease({config:Z,environment:Q,localPath:F,remoteKey:B,targets:V}),_=$.name==="aws"?PQ(O.deployBucketName,B,Z.project.region||"us-east-1",G):CQ(A.artifactRef,G),M=p0(W),E=M==="server-static"?g7({siteName:G,artifactFetch:_,releaseId:U,preStartCommands:W.preStart}):f7({siteName:G,slug:z,artifactFetch:_,releaseId:U,execStart:v7(W.start,H),envEntries:W.env||{},port:W.port,preStartCommands:W.preStart}),j=Z.infrastructure?.compute,q=M==="server-static"&&j?.webServer!=="rpx"&&!!W.domain,T=q?GQ({siteName:G,domain:W.domain,aliases:W.aliases,type:W.type==="spa"?"spa":"static",appDir:`/var/www/${G}/current`,webDirectory:"",redirects:W.redirects,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,j?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],D=q?bQ(W):[],S=[...y7(`/var/www/${G}`,{releaseId:U,commit:U,branch:W.branch??"main"}),...E,...T,...D];Y.step(`Deploying to ${V.length} target(s)...`);let P=await $.runRemoteDeploy({targets:V,commands:S,comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}});if(!P.success)return{success:!1,error:P.error||"Remote deploy failed",instanceCount:P.instanceCount,perInstance:P.perInstance};return{success:!0,instanceCount:P.instanceCount,perInstance:P.perInstance}}async function p7($){let{config:J,environment:Y,driver:Z,sha:Q,runtime:G,tarballForSite:W,logger:z=vQ}=$,U=J.project.slug,H=$.cwd??process.cwd(),F=
|
|
7470
|
-
`),Z=J==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${wT(J)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${$.name} (user=${J})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,Y,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',Z,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${$.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var w9={};h0(w9,{runComputeRecipe:()=>RT,rollbackComputeSite:()=>dQ,restoreDatabaseBackup:()=>cQ,getComputeDeployHistory:()=>DT});async function r7($){return await $.driver.findComputeTargets({slug:$.slug,environment:$.environment,role:$.role||"app"})}async function dQ($,J){let Y=$.logger||uQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Q=`/var/www/${J.siteName}`,G=
|
|
7469
|
+
`)}function KF($){let J=BF($.siteName),Y=l7($.siteName),Z=`${XF}/${Y}.conf`;return[`getent group ${J} >/dev/null || groupadd --system ${J}`,`id -u ${J} >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin -g ${J} ${J}`,`usermod -aG ${J} www-data 2>/dev/null || true`,`chown -R ${J}:${J} ${$.appBase} || true`,`chmod -R g+rX ${$.appBase} || true`,`chmod 600 ${$.appBase}/shared/.env 2>/dev/null || true`,`mkdir -p ${XF}`,`cat > ${Z} <<'TS_CLOUD_FPMPOOL_EOF'`,MT($).replace(/\n$/,""),"TS_CLOUD_FPMPOOL_EOF",`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`]}var XF="/var/lib/pantry/php-fpm/pool.d",jT=9100,LT=400;var OF=o(()=>{z2()});async function fQ($,J,Y=vQ){let{config:Z,environment:Q,siteName:G,site:W,slug:z,sha:U,runtime:H,localTarballPath:F}=J,B=`releases/${G}/${U}.tar.gz`,K=j1(Z,Q),O=await $.getComputeOutputs({config:Z,environment:Q}),V=await $.findComputeTargets({slug:z,environment:Q,role:"app"});if(V.length===0)return{success:!1,error:$.name==="aws"?`Stack '${K}' has no EC2 instances tagged Project=${z} Environment=${Q} Role=app.`:`No Hetzner servers labeled ts-cloud/project=${z} ts-cloud/environment=${Q} ts-cloud/role=app.`};if(B9(W)){let C=Z.infrastructure?.compute,I=W.phpVersion??C?.php?.default??C?.php?.versions?.[0],b=`/var/www/${G}`,y=O.servicesPrivateIp?IH(O.servicesPrivateIp,Z.infrastructure?.appDatabase):BH(Z.infrastructure?.appDatabase),c=Object.keys(y).length>0?{...W,env:{...y,...W.env||{}}}:W,r=$F({siteName:G,site:c,releaseId:U,appBase:b,defaultPhpVersion:I}),d=C?.webServer!=="rpx",s=hQ(W)==="custom"&&W.ssl?.certPath&&W.ssl?.keyPath?{certPath:W.ssl.certPath,keyPath:W.ssl.keyPath}:void 0,J0=W.isolation?KF({siteName:G,appBase:b}):[],t=d?GQ({siteName:G,domain:W.domain||G,aliases:W.aliases,type:W.type,appDir:`${b}/current`,webDirectory:W.webDirectory,phpVersion:I,fastcgiPass:W.isolation?yQ(G):void 0,redirects:W.redirects,ssl:s,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,C?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],a=d?bQ(W):[],e=HF(W)?UF({slug:z,siteName:G,site:W,phpVersion:I,appBase:b}):[],L0=d?eH(W):[];Y.step(`Deploying PHP site '${G}' to ${V.length} target(s)...`);let _0=await $.runRemoteDeploy({targets:V,commands:[...r,...J0,...t,...a,...e,...L0],comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}}),O0=EH(Z.notifications,W.notifications);if(!_0.success)return await FQ(O0,"deploy-failed",`❌ Deploy of ${z}/${G}@${U} failed: ${_0.error||"unknown error"}`),{success:!1,error:_0.error||"Remote PHP deploy failed",instanceCount:_0.instanceCount,perInstance:_0.perInstance};let T1=W.domain?` → https://${W.domain}`:"";return await FQ(O0,"deploy",`✅ Deployed ${z}/${G}@${U}${T1}`),{success:!0,instanceCount:_0.instanceCount,perInstance:_0.perInstance}}if(!F)return{success:!1,error:`Site '${G}' requires a release tarball but none was provided`};let A=await $.uploadRelease({config:Z,environment:Q,localPath:F,remoteKey:B,targets:V}),_=$.name==="aws"?PQ(O.deployBucketName,B,Z.project.region||"us-east-1",G):CQ(A.artifactRef,G),M=p0(W),E=M==="server-static"?g7({siteName:G,artifactFetch:_,releaseId:U,preStartCommands:W.preStart}):f7({siteName:G,slug:z,artifactFetch:_,releaseId:U,execStart:v7(W.start,H),envEntries:W.env||{},port:W.port,preStartCommands:W.preStart}),j=Z.infrastructure?.compute,q=M==="server-static"&&j?.webServer!=="rpx"&&!!W.domain,T=q?GQ({siteName:G,domain:W.domain,aliases:W.aliases,type:W.type==="spa"?"spa":"static",appDir:`/var/www/${G}/current`,webDirectory:"",redirects:W.redirects,auth:W.auth&&W.auth.enabled!==!1&&W.auth.password?{username:W.auth.username||"admin",password:W.auth.password,realm:W.auth.realm}:void 0,serverSnippet:QQ(W.nginx,j?.nginxTemplates),clientMaxBodySize:W.nginx?.clientMaxBodySize,hsts:W.ssl?.hsts,tlsProtocols:W.ssl?.tlsProtocols,security:W.security}):[],D=q?bQ(W):[],S=[...y7(`/var/www/${G}`,{releaseId:U,commit:U,branch:W.branch??"main"}),...E,...T,...D];Y.step(`Deploying to ${V.length} target(s)...`);let P=await $.runRemoteDeploy({targets:V,commands:S,comment:`ts-cloud deploy ${z}/${G}@${U}`,tags:{Project:z,Environment:Q,Role:"app"}});if(!P.success)return{success:!1,error:P.error||"Remote deploy failed",instanceCount:P.instanceCount,perInstance:P.perInstance};return{success:!0,instanceCount:P.instanceCount,perInstance:P.perInstance}}async function p7($){let{config:J,environment:Y,driver:Z,sha:Q,runtime:G,tarballForSite:W,logger:z=vQ}=$,U=J.project.slug,H=$.cwd??process.cwd(),F=U$(J);IQ(J,{cwd:H,logger:{info:z.info,warn:z.warn}});let B=!F&&U$(J),K=null;if(B){if(K=kQ(J.sites?.[$8],{cwd:H,slug:U,sha:Q,logger:{info:z.info,warn:z.warn}}),!K){if(z.warn("Management dashboard: no artifact available — skipping dashboard site for this deploy."),J.sites)delete J.sites[$8]}}let O=J.sites||{},V=Object.entries(O).filter(([M,E])=>{if(!E)return!1;let j=p0(E);if(j==="bucket")return z.warn(`Site '${M}' targets a bucket — skipping (handled by the static-site path, not compute).`),!1;if(j==="redirect")return!1;return!0});if(V.length===0)return!0;let A=(M)=>M===$8&&K?K:W(M);for(let[M,E]of V){z.step(`Deploying site: ${M}`);let j=B9(E)?void 0:A(M),q=await fQ(Z,{config:J,environment:Y,siteName:M,site:E,slug:U,sha:Q,runtime:G,localTarballPath:j},z);if(!q.success){if(z.error(`Deploy of '${M}' failed: ${q.error||"unknown error"}`),q.perInstance)for(let T of q.perInstance)z.error(` ${T.instanceId}: ${T.status}${T.error?` — ${T.error}`:""}`);return!1}if(z.success(`Deployed ${U}/${M}@${Q} to ${q.instanceCount} target(s)`),q.perInstance)for(let T of q.perInstance)z.info(` ✓ ${T.instanceId}: ${T.status}`)}if(!await AF($))return!1;return!0}async function AF($){let{config:J,environment:Y,driver:Z,logger:Q=vQ}=$,G=J.infrastructure?.compute?.proxy;if(G?.engine!=="rpx")return!0;let W=J.sites||{},z=K9(W,{proxy:G});if(z.proxies.length===0)return Q.warn("rpx gateway: no server sites with a domain to route — skipping gateway reload."),!0;let U=await Z.findComputeTargets({slug:J.project.slug,environment:Y,role:"app"});if(U.length===0)return Q.warn("rpx gateway: no compute targets found — skipping gateway reload."),!0;Q.step(`Reloading rpx gateway with ${z.proxies.length} route(s)...`);let H=O9({proxy:G,config:z,slug:J.project.slug}),F=await Z.runRemoteDeploy({targets:U,commands:H,comment:`ts-cloud rpx gateway reload ${J.project.slug}`,tags:{Project:J.project.slug,Environment:Y,Role:"app"}});if(!F.success)return Q.error(`rpx gateway reload failed: ${F.error||"unknown error"}`),!1;return Q.success(`rpx gateway reloaded on ${F.instanceCount} target(s)`),!0}var vQ;var gQ=o(async()=>{K$();xQ();nH();E7();JF();FF();zQ();OF();M9();C7();await z8([n0(),d7()]);vQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var j$=o(async()=>{AQ();xQ();C7();await z8([KQ(),wQ(),gQ()]);gH()});function wT($){return`'${$.split("'").join("'\\''")}'`}function VF($){let J=$.user||"root",Y=$.script.join(`
|
|
7470
|
+
`),Z=J==="root"?'bash -l "$TS_CLOUD_RECIPE"':`runuser -l ${wT(J)} -c "bash $TS_CLOUD_RECIPE"`;return["set -uo pipefail",`echo "__TS_CLOUD_RECIPE_BEGIN__ ${$.name} (user=${J})"`,"TS_CLOUD_RECIPE=$(mktemp)",`cat > "$TS_CLOUD_RECIPE" <<'TS_CLOUD_RECIPE_EOF'`,Y,"TS_CLOUD_RECIPE_EOF",'chmod +r "$TS_CLOUD_RECIPE"',Z,"TS_CLOUD_RC=$?",'rm -f "$TS_CLOUD_RECIPE"',`echo "__TS_CLOUD_RECIPE_END__ ${$.name} exit=$TS_CLOUD_RC"`,"exit $TS_CLOUD_RC"]}var w9={};h0(w9,{runComputeRecipe:()=>RT,rollbackComputeSite:()=>dQ,restoreDatabaseBackup:()=>cQ,getComputeDeployHistory:()=>DT});async function r7($){return await $.driver.findComputeTargets({slug:$.slug,environment:$.environment,role:$.role||"app"})}async function dQ($,J){let Y=$.logger||uQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Q=`/var/www/${J.siteName}`,G=_$(Q,J.to||"unused"),W=["set -uo pipefail",...uH(G,J.to?{to:J.to}:{}),`(cd ${S1} && pantry restart php-fpm) 2>/dev/null || true`,`(cd ${G.current} && eval "$(cd ${S1} && pantry env 2>/dev/null)" && php artisan queue:restart) 2>/dev/null || true`];Y.step(`Rolling back ${J.siteName}${J.to?` to ${J.to}`:" to the previous release"} on ${Z.length} server(s)...`);let z=await $.driver.runRemoteDeploy({targets:Z,commands:W,comment:`ts-cloud rollback ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!z.success)Y.error(`Rollback failed: ${z.error||"unknown error"}`);else Y.success(`Rolled back ${J.siteName}.`);return{success:z.success,error:z.error,perInstance:z.perInstance}}async function DT($,J){let Y=await r7($);if(Y.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};let Z=SQ(`/var/www/${J.siteName}`),Q=Math.max(1,J.limit??20),G=[`[ -f ${Z} ] && tail -n ${Q} ${Z} || echo "no deploy history for ${J.siteName}"`],W=await $.driver.runRemoteDeploy({targets:Y,commands:G,comment:`ts-cloud deploy:history ${$.slug}/${J.siteName}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});return{success:W.success,error:W.error,perInstance:W.perInstance}}async function RT($,J){let Y=$.logger||uQ,Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Running recipe '${J.name}' as ${J.user||"root"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:VF({name:J.name,script:J.script,user:J.user}),comment:`ts-cloud recipe ${J.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Recipe '${J.name}' failed: ${Q.error||"unknown error"}`);else Y.success(`Recipe '${J.name}' completed.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}async function cQ($,J){let Y=$.logger||uQ;if(!J.database?.name)return{success:!1,error:"No appDatabase configured to restore."};let Z=await r7($);if(Z.length===0)return{success:!1,error:`No '${$.role||"app"}' servers found for ${$.slug}/${$.environment}.`};Y.step(`Restoring database '${J.database.name}'${J.from?` from ${J.from}`:" from the latest backup"} on ${Z.length} server(s)...`);let Q=await $.driver.runRemoteDeploy({targets:Z,commands:qH(J.database,{from:J.from}),comment:`ts-cloud db:restore ${$.slug}/${J.database.name}`,tags:{Project:$.slug,Environment:$.environment,Role:$.role||"app"}});if(!Q.success)Y.error(`Restore failed: ${Q.error||"unknown error"}`);else Y.success(`Restored ${J.database.name}.`);return{success:Q.success,error:Q.error,perInstance:Q.perInstance}}var uQ;var J8=o(()=>{z2();M9();uQ={info:()=>{},warn:()=>{},error:()=>{},step:()=>{},success:()=>{}}});var _F={};h0(_F,{buildQuickDeployCi:()=>ST});function NT($){let J=$.sites||{};for(let Y of Object.values(J))if(Y?.repository?.url)return{provider:Y.repository.provider,branch:Y.repository.branch};return}function ST($,J="production"){let Y=NT($),Z=Y?.provider;if(Z!=="github"&&Z!=="gitlab"&&Z!=="bitbucket")return null;let Q=Y?.branch||"main",G=`bunx --bun ts-cloud deploy ${J}`;if(Z==="github")return{provider:Z,branch:Q,path:".github/workflows/deploy.yml",content:`name: Deploy
|
|
7471
7471
|
on:
|
|
7472
7472
|
push:
|
|
7473
7473
|
branches: [${Q}]
|
|
@@ -7504,7 +7504,7 @@ jobs:
|
|
|
7504
7504
|
- bun install --frozen-lockfile
|
|
7505
7505
|
- ${G}
|
|
7506
7506
|
# Set HETZNER_API_TOKEN / AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY as repo vars.
|
|
7507
|
-
`}}class n7{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeFileSystems($){let J=[];if($?.FileSystemId)J.push(`FileSystemId=${encodeURIComponent($.FileSystemId)}`);if($?.CreationToken)J.push(`CreationToken=${encodeURIComponent($.CreationToken)}`);let Y=`/2015-02-01/file-systems${J.length>0?`?${J.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:Y,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((Q)=>({FileSystemId:Q.FileSystemId,Name:Q.Name,CreationTime:Q.CreationTime,LifeCycleState:Q.LifeCycleState,NumberOfMountTargets:Q.NumberOfMountTargets,SizeInBytes:Q.SizeInBytes?{Value:Q.SizeInBytes.Value,Timestamp:Q.SizeInBytes.Timestamp}:void 0,PerformanceMode:Q.PerformanceMode,Encrypted:Q.Encrypted,ThroughputMode:Q.ThroughputMode,Tags:Q.Tags}))}}}var mQ=o(()=>{Y0()});var jF={};h0(jF,{SQSClient:()=>P1});class P1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createQueue($){let Y={Action:"CreateQueue",QueueName:$.fifo&&!$.queueName.endsWith(".fifo")?`${$.queueName}.fifo`:$.queueName,Version:"2012-11-05"},Z=1;if($.visibilityTimeout!==void 0)Y[`Attribute.${Z}.Name`]="VisibilityTimeout",Y[`Attribute.${Z}.Value`]=$.visibilityTimeout.toString(),Z++;if($.messageRetentionPeriod!==void 0)Y[`Attribute.${Z}.Name`]="MessageRetentionPeriod",Y[`Attribute.${Z}.Value`]=$.messageRetentionPeriod.toString(),Z++;if($.delaySeconds!==void 0)Y[`Attribute.${Z}.Name`]="DelaySeconds",Y[`Attribute.${Z}.Value`]=$.delaySeconds.toString(),Z++;if($.maxMessageSize!==void 0)Y[`Attribute.${Z}.Name`]="MaximumMessageSize",Y[`Attribute.${Z}.Value`]=$.maxMessageSize.toString(),Z++;if($.receiveMessageWaitTime!==void 0)Y[`Attribute.${Z}.Name`]="ReceiveMessageWaitTimeSeconds",Y[`Attribute.${Z}.Value`]=$.receiveMessageWaitTime.toString(),Z++;if($.fifo){if(Y[`Attribute.${Z}.Name`]="FifoQueue",Y[`Attribute.${Z}.Value`]="true",Z++,$.contentBasedDeduplication)Y[`Attribute.${Z}.Name`]="ContentBasedDeduplication",Y[`Attribute.${Z}.Value`]="true",Z++}if($.deadLetterTargetArn&&$.maxReceiveCount)Y[`Attribute.${Z}.Name`]="RedrivePolicy",Y[`Attribute.${Z}.Value`]=JSON.stringify({deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount}),Z++;if($.tags&&Object.keys($.tags).length>0){let G=1;for(let[W,z]of Object.entries($.tags))Y[`Tag.${G}.Key`]=W,Y[`Tag.${G}.Value`]=z,G++}let Q=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()});return{QueueUrl:Q.QueueUrl||Q.CreateQueueResult?.QueueUrl}}async listQueues($){let J={Action:"ListQueues",Version:"2012-11-05"};if($)J.QueueNamePrefix=$;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[];if(Y.QueueUrl)Z.push(Y.QueueUrl);else if(Y.ListQueuesResult?.QueueUrl)if(Array.isArray(Y.ListQueuesResult.QueueUrl))Z.push(...Y.ListQueuesResult.QueueUrl);else Z.push(Y.ListQueuesResult.QueueUrl);return{QueueUrls:Z}}async getQueueAttributes($){let J={Action:"GetQueueAttributes",QueueUrl:$,Version:"2012-11-05","AttributeName.1":"All"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Attributes:Y.Attributes||Y.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl($){let J={Action:"GetQueueUrl",QueueName:$,Version:"2012-11-05"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{QueueUrl:Y.QueueUrl||Y.GetQueueUrlResult?.QueueUrl}}async deleteQueue($){let J={Action:"DeleteQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async purgeQueue($){let J={Action:"PurgeQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async sendMessage($){let J={Action:"SendMessage",QueueUrl:$.queueUrl,MessageBody:$.messageBody,Version:"2012-11-05"};if($.delaySeconds!==void 0)J.DelaySeconds=$.delaySeconds;if($.messageGroupId)J.MessageGroupId=$.messageGroupId;if($.messageDeduplicationId)J.MessageDeduplicationId=$.messageDeduplicationId;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{MessageId:Y.MessageId||Y.SendMessageResult?.MessageId}}async receiveMessages($){let J={Action:"ReceiveMessage",QueueUrl:$.queueUrl,Version:"2012-11-05"};if($.maxMessages!==void 0)J.MaxNumberOfMessages=$.maxMessages;if($.visibilityTimeout!==void 0)J.VisibilityTimeout=$.visibilityTimeout;if($.waitTimeSeconds!==void 0)J.WaitTimeSeconds=$.waitTimeSeconds;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[],Q=Y.Message||Y.ReceiveMessageResult?.Message;if(Q)if(Array.isArray(Q))Z.push(...Q.map((G)=>({MessageId:G.MessageId,ReceiptHandle:G.ReceiptHandle,Body:G.Body})));else Z.push({MessageId:Q.MessageId,ReceiptHandle:Q.ReceiptHandle,Body:Q.Body});return{Messages:Z}}async deleteMessage($,J){let Y={Action:"DeleteMessage",QueueUrl:$,ReceiptHandle:J,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}}var D9=o(()=>{Y0()});class lQ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async call($,J){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${$}`},body:JSON.stringify(J)})}async listWebACLs($="REGIONAL"){return(await this.call("ListWebACLs",{Scope:$,Limit:100}))?.WebACLs??[]}async getWebACLRules($,J,Y="REGIONAL"){return((await this.call("GetWebACL",{Name:$,Id:J,Scope:Y}))?.WebACL?.Rules??[]).map((G)=>({Name:G.Name,Priority:G.Priority,Action:G.Action?Object.keys(G.Action)[0]:G.OverrideAction?Object.keys(G.OverrideAction)[0]:"count"}))}}var LF=o(()=>{Y0()});var MF={};h0(MF,{resolveDashboardData:()=>i7});function EF($){return String($).padStart(2,"0")}function Y8($){return`${$.getUTCFullYear()}-${EF($.getUTCMonth()+1)}-${EF($.getUTCDate())}`}function PT($){let J=Math.max(0,Math.round((Date.now()-$)/1000));if(J<60)return`${J}s ago`;let Y=Math.round(J/60);if(Y<60)return`${Y}m ago`;let Z=Math.round(Y/60);if(Z<48)return`${Z}h ago`;return`${Math.round(Z/24)}d ago`}async function R9($,J,Y,Z,Q,G){let W=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:Y,Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Q,EndTime:G,Period:86400,Statistics:[Z]}).catch(()=>[]);if(!W.length)return 0;if(Z==="Sum")return W.reduce((z,U)=>z+(U.Sum??0),0);if(Z==="Maximum")return Math.max(...W.map((z)=>z.Maximum??0));return W.reduce((z,U)=>z+(U.Average??0),0)/W.length}async function N9($,J,Y,Z,Q,G,W){let z=await $.getMetricStatistics({Namespace:J,MetricName:Y,Dimensions:Z,StartTime:G,EndTime:W,Period:86400,Statistics:[Q]}).catch(()=>[]);if(!z.length)return 0;if(Q==="Sum")return z.reduce((U,H)=>U+(H.Sum??0),0);if(Q==="Maximum")return Math.max(...z.map((U)=>U.Maximum??0));return z.reduce((U,H)=>U+(H.Average??0),0)/z.length}async function pQ($,J,Y,Z,Q){let G=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Z,EndTime:Q,Period:86400,ExtendedStatistics:[Y]}).catch(()=>[]);return Math.round(G.reduce((W,z)=>W+(z.Percentiles?.[Y]??0),0))}async function i7($,J){let Y=await yZ($,J),Z=Y.region,Q=new H$(Z),G=new l0(Z),W=new l2(Z),z=new Date,U=new Date(z.getTime()-86400000),H=$.environments?.[J]?.app,F={};F.app={name:Y.slug,env:J,region:Z,runtime:H?.kind==="php"?`php-${H?.phpVersion??"8.3"} (fpm)`:H?.kind??"node",url:Y.endpoint??"",build:Y.lastRelease?.sha?.slice(0,7)??"—",deployedAt:Y.lastRelease?.timestamp??"—"},F.maintenance={enabled:!1},F.scheduler={enabled:Y.scheduler!=="off",expression:Y.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let B=0,K=0,O=0,V=[],A=[],_=[];for(let j of Y.functions){let[q,T,D,S,P,C,I,b,y]=await Promise.all([R9(Q,j.name,"Invocations","Sum",U,z),R9(Q,j.name,"Errors","Sum",U,z),R9(Q,j.name,"Throttles","Sum",U,z),R9(Q,j.name,"Duration","Average",U,z),G.getFunction(j.name).catch(()=>null),pQ(Q,j.name,"p50",U,z),pQ(Q,j.name,"p95",U,z),pQ(Q,j.name,"p99",U,z),Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:j.name}],StartTime:new Date(z.getTime()-43200000),EndTime:z,Period:3600,Stat:"Sum"}).catch(()=>[])]);B+=q,K+=T,O=Math.max(O,S);let c=P?.Configuration?.MemorySize??0,r=Object.keys(P?.Configuration?.Environment?.Variables??{}),d=[],u=0;try{let{events:J0=[]}=await W.filterLogEvents({logGroupName:`/aws/lambda/${j.name}`,startTime:U.getTime(),limit:120});for(let t of J0){let a=(t.message??"").trim(),e=/Max Memory Used:\s*(\d+)\s*MB/.exec(a);if(e)u=Math.max(u,Number(e[1]));if(a&&!/^(?:START|END|REPORT|INIT_START)/.test(a))_.push({source:j.mode||j.name,timestamp:new Date(t.timestamp??0).toISOString(),when:PT(t.timestamp??0),message:a.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(a)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(a)?"warn":"info"})}d=J0.filter((t)=>!/^(?:START|END|REPORT|INIT_START)/.test((t.message??"").trim())).slice(-6).map((t)=>({ts:new Date(t.timestamp??0).toISOString().slice(11,19),msg:(t.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(t.message??"")}))}catch{}let s=Math.max(1,...y);V.push({key:j.mode,name:j.name,version:j.version,memory:c,timeout:P?.Configuration?.Timeout??0,runtime:P?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(q),errors:Math.round(T),p95:I||Math.round(S),status:"active",provisioned:j.provisioned?`${j.provisioned.allocated}/${j.provisioned.requested}`:void 0}),A.push({key:j.mode,name:j.name,runtime:P?.Configuration?.Runtime??"provided.al2023",arch:P?.Configuration?.Architectures?.[0]??"x86_64",memory:c,timeout:P?.Configuration?.Timeout??0,ephemeral:P?.Configuration?.EphemeralStorage?.Size??512,version:j.version,concurrency:H?.concurrency??"—",invocations:Math.round(q),errors:Math.round(T),throttles:Math.round(D),p50:C||Math.round(S),p95:I||Math.round(S),p99:b||Math.round(S),maxMem:u,spark:y.length?y.map((J0)=>Math.round(J0/s*100)):[0],env:r.length?r:["(none)"],recent:d.length?d:[{ts:"—",msg:"no recent events",err:!1}]})}F.functions=V,F.functionsDetail=A,F.serverlessLogs=_.sort((j,q)=>String(q.timestamp).localeCompare(String(j.timestamp))).slice(0,600),F.serverlessLogsEmptyReason=_.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let M=B?Number((K/B*100).toFixed(2)):0,E=Math.round(await R9(Q,Y.functions[0]?.name??"","ConcurrentExecutions","Maximum",U,z));F.metrics={invocations:Math.round(B),errorRatePct:M,p95Ms:Math.round(O),coldStartPct:0,concurrency:E,estCostUsd:0};try{let j=new P1(Z),q=[],T=[],D=0;try{let{QueueUrl:P}=await j.getQueueUrl(`${Y.slug}-${J}-dlq`),{Attributes:C}=await j.getQueueAttributes(P);D=Number(C.ApproximateNumberOfMessages??0)}catch{}let S=H?m8(H,Y.slug,J):[];for(let P of S){let C=P.name.replace(`${Y.slug}-${J}-`,""),I=0,b=0;try{let{QueueUrl:c}=await j.getQueueUrl(P.name),{Attributes:r}=await j.getQueueAttributes(c);I=Number(r.ApproximateNumberOfMessages??0),b=Number(r.ApproximateNumberOfMessagesNotVisible??0)}catch{}let y=Math.round(await N9(Q,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:P.name}],"Sum",U,z));q.push({name:C,visible:I,inFlight:b,processed:y,dlq:D}),T.push({name:P.name,short:C,visible:I,inFlight:b,delayed:0,processed:y,oldestSec:0,concurrency:P.concurrency??H?.queueConcurrency??"—",tries:H?.queueTries??3,visTimeout:(H?.queueTimeout??120)*6,dlq:D})}if(q.length)F.queues=q;if(T.length)F.queuesDetail=T;F.dlqItems=[]}catch{}try{let j=new K0(Z),{Stacks:q}=await j.describeStacks({stackName:W$($,J)}),T={};for(let D of q?.[0]?.Outputs??[])if(D.OutputKey)T[D.OutputKey]=D.OutputValue??"";if(H?.database?.connection==="aurora-serverless"){let D=`${Y.slug}-${J}-db`,S=[{Name:"DBClusterIdentifier",Value:D}],[P,C]=await Promise.all([N9(Q,"AWS/RDS","ServerlessDatabaseCapacity",S,"Average",U,z),N9(Q,"AWS/RDS","DatabaseConnections",S,"Maximum",U,z)]);if(F.aurora={id:D,engine:"aurora-mysql",minAcu:H?.database?.minCapacity??0.5,maxAcu:H?.database?.maxCapacity??4,currentAcu:P?Number(P.toFixed(1)):H?.database?.minCapacity??0.5,database:"app",connections:Math.round(C),status:T.DbEndpoint?"available":"creating"},H?.rdsProxy)F.proxy={name:`${Y.slug}-${J}-proxy`,endpoint:T.DbProxyEndpoint??"—",pooledConns:Math.round(C),status:"available"}}if(H?.cache?.driver==="elasticache"){let D=`${Y.slug}-${J}-cache`,S=[{Name:"CacheClusterId",Value:`${D}-001`}],[P,C]=await Promise.all([N9(Q,"AWS/ElastiCache","CacheHits",S,"Sum",U,z),N9(Q,"AWS/ElastiCache","CacheMisses",S,"Sum",U,z)]),I=P+C>0?Number((P/(P+C)*100).toFixed(1)):0;F.redis={id:D,node:"cache.t4g.micro",engine:"redis",hitRate:I,status:T.CacheEndpoint?"available":"creating"}}if(H?.efs){let D=0;try{if(T.EfsFileSystemId){let S=new n7(Z),{FileSystems:P}=await S.describeFileSystems({FileSystemId:T.EfsFileSystemId});D=Number(((P?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}F.efs={id:T.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:D,status:"available"}}F.assetsInfo=T.AssetsCdnDomain?{bucket:T.AssetsBucketName??`${Y.slug}-${J}-assets`,cdn:T.AssetsCdnDomain,customDomain:H?.assetDomain??"—",assetUrl:Y.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:F.app.build}:void 0}catch{}if(F.assetsInfo)try{let q=await new W0(Z).list({bucket:F.assetsInfo.bucket,maxKeys:1000});F.assetsInfo.files=q.length,F.assetsInfo.sizeMb=Number((q.reduce((T,D)=>T+(D.Size??0),0)/1048576).toFixed(1)),F.assetsRecent=q.slice(0,8).map((T)=>({path:`/${T.Key}`,size:`${Math.max(1,Math.round((T.Size??0)/1024))} KB`,type:T.Key.split(".").pop()??""}))}catch{}try{if(H?.secrets){let j=Array.isArray(H.secrets)?H.secrets.map((q)=>({key:q.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:q})):Object.entries(H.secrets).map(([q,T])=>({key:q,source:String(T)}));F.secretsList=j.map((q)=>({...q,updated:"—"}))}}catch{}try{let j=new W0(Z),q=`${Y.slug}-${J}-deployments`,T=await j.getObjectJson(q,`deployments/${Y.slug}/${J}/history.json`).catch(()=>null);if(T?.records?.length)F.deploymentsDetail=T.records.slice(-12).reverse().map((D)=>({sha:(D.sha??"").slice(0,7),status:D.status??"success",when:D.timestamp??"—",took:D.took??"—",by:D.by??"—",version:D.version??"—",hooks:D.hooks??[]}))}catch{}F.metricsTotals={invocations:F.metrics.invocations,errors:Math.round(K),errorRatePct:M,p95Ms:F.metrics.p95Ms,throttles:A.reduce((j,q)=>j+q.throttles,0),coldStartPct:0,estCostUsd:0,concurrency:E},F.metricsPerFn=A.map((j)=>({key:j.key,invocations:j.invocations,errors:j.errors,throttles:j.throttles,avgMs:j.p50,maxMs:j.p99,costUsd:0}));try{F.invSpark=await Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:Y.functions.find((j)=>j.mode==="http")?.name??""}],StartTime:new Date(z.getTime()-86400000),EndTime:z,Period:3600,Stat:"Sum"})}catch{}try{let j=new o8,q=z,T=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth(),1)),D=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()-1,1)),[S,P]=await Promise.all([j.getCostByService({start:Y8(T),end:Y8(q),granularity:"MONTHLY"}).catch(()=>[]),j.getCostByService({start:Y8(D),end:Y8(T),granularity:"MONTHLY"}).catch(()=>[])]);if(S.length){let C=S.reduce((u,s)=>u+s.amount,0),I=P.reduce((u,s)=>u+s.amount,0),b=q.getUTCDate(),y=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()+1,0)).getUTCDate();F.costSummary={monthToDateUsd:Number(C.toFixed(2)),projectedUsd:Number((C/b*y).toFixed(2)),lastMonthUsd:Number(I.toFixed(2)),dailyAvgUsd:Number((C/b).toFixed(2))},F.costServices=S.filter((u)=>u.amount>0).sort((u,s)=>s.amount-u.amount).slice(0,12).map((u)=>({name:u.service,usd:Number(u.amount.toFixed(2)),note:""})),F.metrics.estCostUsd=Number((C/b).toFixed(2)),F.metricsTotals.estCostUsd=F.metrics.estCostUsd,F.costTrend=await j.getDailyTotals({start:Y8(T),end:Y8(q)}).catch(()=>[]);let c=S.find((u)=>/lambda/i.test(u.service))?.amount??0,r=(u)=>u.invocations*(u.p50/1000)*(u.memory/1024),d=A.reduce((u,s)=>u+r(s),0)||1;F.costPerFn=A.map((u)=>({key:u.key,requests:u.invocations,gbSec:Math.round(r(u)),usd:Number((c*(r(u)/d)).toFixed(2))}))}}catch{}if(H?.firewall)try{let j=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]),q=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]);F.waf={enabled:!0,scope:"REGIONAL",acl:`${Y.slug}-${J}-waf`,allowed24h:Math.round(q.reduce((T,D)=>T+(D.Sum??0),0)),blocked24h:Math.round(j.reduce((T,D)=>T+(D.Sum??0),0))};try{let T=new lQ(Z),D=await T.listWebACLs("REGIONAL"),S=D.find((P)=>P.Name?.includes(`${Y.slug}-${J}`))??D[0];if(S?.Name&&S.Id){F.waf.acl=S.Name;let P=await T.getWebACLRules(S.Name,S.Id,"REGIONAL");if(P.length)F.wafRules=P.map((C)=>({name:C.Name??"—",detail:`priority ${C.Priority??0}`,action:C.Action??"count",blocked24h:0}))}}catch{}}catch{}if(Y.scheduler!=="off"&&H?.kind==="php")try{let j=await n$($,J,"schedule:list"),q=[];for(let T of(j||"").split(`
|
|
7507
|
+
`}}class n7{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async describeFileSystems($){let J=[];if($?.FileSystemId)J.push(`FileSystemId=${encodeURIComponent($.FileSystemId)}`);if($?.CreationToken)J.push(`CreationToken=${encodeURIComponent($.CreationToken)}`);let Y=`/2015-02-01/file-systems${J.length>0?`?${J.join("&")}`:""}`;return{FileSystems:((await this.client.request({service:"elasticfilesystem",region:this.region,method:"GET",path:Y,headers:{"Content-Type":"application/json"}})).FileSystems||[]).map((Q)=>({FileSystemId:Q.FileSystemId,Name:Q.Name,CreationTime:Q.CreationTime,LifeCycleState:Q.LifeCycleState,NumberOfMountTargets:Q.NumberOfMountTargets,SizeInBytes:Q.SizeInBytes?{Value:Q.SizeInBytes.Value,Timestamp:Q.SizeInBytes.Timestamp}:void 0,PerformanceMode:Q.PerformanceMode,Encrypted:Q.Encrypted,ThroughputMode:Q.ThroughputMode,Tags:Q.Tags}))}}}var mQ=o(()=>{Y0()});var jF={};h0(jF,{SQSClient:()=>P1});class P1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createQueue($){let Y={Action:"CreateQueue",QueueName:$.fifo&&!$.queueName.endsWith(".fifo")?`${$.queueName}.fifo`:$.queueName,Version:"2012-11-05"},Z=1;if($.visibilityTimeout!==void 0)Y[`Attribute.${Z}.Name`]="VisibilityTimeout",Y[`Attribute.${Z}.Value`]=$.visibilityTimeout.toString(),Z++;if($.messageRetentionPeriod!==void 0)Y[`Attribute.${Z}.Name`]="MessageRetentionPeriod",Y[`Attribute.${Z}.Value`]=$.messageRetentionPeriod.toString(),Z++;if($.delaySeconds!==void 0)Y[`Attribute.${Z}.Name`]="DelaySeconds",Y[`Attribute.${Z}.Value`]=$.delaySeconds.toString(),Z++;if($.maxMessageSize!==void 0)Y[`Attribute.${Z}.Name`]="MaximumMessageSize",Y[`Attribute.${Z}.Value`]=$.maxMessageSize.toString(),Z++;if($.receiveMessageWaitTime!==void 0)Y[`Attribute.${Z}.Name`]="ReceiveMessageWaitTimeSeconds",Y[`Attribute.${Z}.Value`]=$.receiveMessageWaitTime.toString(),Z++;if($.fifo){if(Y[`Attribute.${Z}.Name`]="FifoQueue",Y[`Attribute.${Z}.Value`]="true",Z++,$.contentBasedDeduplication)Y[`Attribute.${Z}.Name`]="ContentBasedDeduplication",Y[`Attribute.${Z}.Value`]="true",Z++}if($.deadLetterTargetArn&&$.maxReceiveCount)Y[`Attribute.${Z}.Name`]="RedrivePolicy",Y[`Attribute.${Z}.Value`]=JSON.stringify({deadLetterTargetArn:$.deadLetterTargetArn,maxReceiveCount:$.maxReceiveCount}),Z++;if($.tags&&Object.keys($.tags).length>0){let G=1;for(let[W,z]of Object.entries($.tags))Y[`Tag.${G}.Key`]=W,Y[`Tag.${G}.Value`]=z,G++}let Q=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()});return{QueueUrl:Q.QueueUrl||Q.CreateQueueResult?.QueueUrl}}async listQueues($){let J={Action:"ListQueues",Version:"2012-11-05"};if($)J.QueueNamePrefix=$;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[];if(Y.QueueUrl)Z.push(Y.QueueUrl);else if(Y.ListQueuesResult?.QueueUrl)if(Array.isArray(Y.ListQueuesResult.QueueUrl))Z.push(...Y.ListQueuesResult.QueueUrl);else Z.push(Y.ListQueuesResult.QueueUrl);return{QueueUrls:Z}}async getQueueAttributes($){let J={Action:"GetQueueAttributes",QueueUrl:$,Version:"2012-11-05","AttributeName.1":"All"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{Attributes:Y.Attributes||Y.GetQueueAttributesResult?.Attributes||{}}}async getQueueUrl($){let J={Action:"GetQueueUrl",QueueName:$,Version:"2012-11-05"},Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{QueueUrl:Y.QueueUrl||Y.GetQueueUrlResult?.QueueUrl}}async deleteQueue($){let J={Action:"DeleteQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async purgeQueue($){let J={Action:"PurgeQueue",QueueUrl:$,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()})}async sendMessage($){let J={Action:"SendMessage",QueueUrl:$.queueUrl,MessageBody:$.messageBody,Version:"2012-11-05"};if($.delaySeconds!==void 0)J.DelaySeconds=$.delaySeconds;if($.messageGroupId)J.MessageGroupId=$.messageGroupId;if($.messageDeduplicationId)J.MessageDeduplicationId=$.messageDeduplicationId;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{MessageId:Y.MessageId||Y.SendMessageResult?.MessageId}}async receiveMessages($){let J={Action:"ReceiveMessage",QueueUrl:$.queueUrl,Version:"2012-11-05"};if($.maxMessages!==void 0)J.MaxNumberOfMessages=$.maxMessages;if($.visibilityTimeout!==void 0)J.VisibilityTimeout=$.visibilityTimeout;if($.waitTimeSeconds!==void 0)J.WaitTimeSeconds=$.waitTimeSeconds;let Y=await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()}),Z=[],Q=Y.Message||Y.ReceiveMessageResult?.Message;if(Q)if(Array.isArray(Q))Z.push(...Q.map((G)=>({MessageId:G.MessageId,ReceiptHandle:G.ReceiptHandle,Body:G.Body})));else Z.push({MessageId:Q.MessageId,ReceiptHandle:Q.ReceiptHandle,Body:Q.Body});return{Messages:Z}}async deleteMessage($,J){let Y={Action:"DeleteMessage",QueueUrl:$,ReceiptHandle:J,Version:"2012-11-05"};await this.client.request({service:"sqs",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}}var D9=o(()=>{Y0()});class lQ{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async call($,J){return this.client.request({service:"wafv2",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSWAF_20190729.${$}`},body:JSON.stringify(J)})}async listWebACLs($="REGIONAL"){return(await this.call("ListWebACLs",{Scope:$,Limit:100}))?.WebACLs??[]}async getWebACLRules($,J,Y="REGIONAL"){return((await this.call("GetWebACL",{Name:$,Id:J,Scope:Y}))?.WebACL?.Rules??[]).map((G)=>({Name:G.Name,Priority:G.Priority,Action:G.Action?Object.keys(G.Action)[0]:G.OverrideAction?Object.keys(G.OverrideAction)[0]:"count"}))}}var LF=o(()=>{Y0()});var MF={};h0(MF,{resolveDashboardData:()=>i7});function EF($){return String($).padStart(2,"0")}function Y8($){return`${$.getUTCFullYear()}-${EF($.getUTCMonth()+1)}-${EF($.getUTCDate())}`}function PT($){let J=Math.max(0,Math.round((Date.now()-$)/1000));if(J<60)return`${J}s ago`;let Y=Math.round(J/60);if(Y<60)return`${Y}m ago`;let Z=Math.round(Y/60);if(Z<48)return`${Z}h ago`;return`${Math.round(Z/24)}d ago`}async function R9($,J,Y,Z,Q,G){let W=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:Y,Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Q,EndTime:G,Period:86400,Statistics:[Z]}).catch(()=>[]);if(!W.length)return 0;if(Z==="Sum")return W.reduce((z,U)=>z+(U.Sum??0),0);if(Z==="Maximum")return Math.max(...W.map((z)=>z.Maximum??0));return W.reduce((z,U)=>z+(U.Average??0),0)/W.length}async function N9($,J,Y,Z,Q,G,W){let z=await $.getMetricStatistics({Namespace:J,MetricName:Y,Dimensions:Z,StartTime:G,EndTime:W,Period:86400,Statistics:[Q]}).catch(()=>[]);if(!z.length)return 0;if(Q==="Sum")return z.reduce((U,H)=>U+(H.Sum??0),0);if(Q==="Maximum")return Math.max(...z.map((U)=>U.Maximum??0));return z.reduce((U,H)=>U+(H.Average??0),0)/z.length}async function pQ($,J,Y,Z,Q){let G=await $.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:"Duration",Dimensions:[{Name:"FunctionName",Value:J}],StartTime:Z,EndTime:Q,Period:86400,ExtendedStatistics:[Y]}).catch(()=>[]);return Math.round(G.reduce((W,z)=>W+(z.Percentiles?.[Y]??0),0))}async function i7($,J){let Y=await yZ($,J),Z=Y.region,Q=new F$(Z),G=new l0(Z),W=new l2(Z),z=new Date,U=new Date(z.getTime()-86400000),H=$.environments?.[J]?.app,F={};F.app={name:Y.slug,env:J,region:Z,runtime:H?.kind==="php"?`php-${H?.phpVersion??"8.3"} (fpm)`:H?.kind??"node",url:Y.endpoint??"",build:Y.lastRelease?.sha?.slice(0,7)??"—",deployedAt:Y.lastRelease?.timestamp??"—"},F.maintenance={enabled:!1},F.scheduler={enabled:Y.scheduler!=="off",expression:Y.scheduler==="sub-minute"?"rate(1 minute) · sub-minute":"rate(1 minute)",lastRun:"—"};let B=0,K=0,O=0,V=[],A=[],_=[];for(let j of Y.functions){let[q,T,D,S,P,C,I,b,y]=await Promise.all([R9(Q,j.name,"Invocations","Sum",U,z),R9(Q,j.name,"Errors","Sum",U,z),R9(Q,j.name,"Throttles","Sum",U,z),R9(Q,j.name,"Duration","Average",U,z),G.getFunction(j.name).catch(()=>null),pQ(Q,j.name,"p50",U,z),pQ(Q,j.name,"p95",U,z),pQ(Q,j.name,"p99",U,z),Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:j.name}],StartTime:new Date(z.getTime()-43200000),EndTime:z,Period:3600,Stat:"Sum"}).catch(()=>[])]);B+=q,K+=T,O=Math.max(O,S);let c=P?.Configuration?.MemorySize??0,r=Object.keys(P?.Configuration?.Environment?.Variables??{}),d=[],u=0;try{let{events:J0=[]}=await W.filterLogEvents({logGroupName:`/aws/lambda/${j.name}`,startTime:U.getTime(),limit:120});for(let t of J0){let a=(t.message??"").trim(),e=/Max Memory Used:\s*(\d+)\s*MB/.exec(a);if(e)u=Math.max(u,Number(e[1]));if(a&&!/^(?:START|END|REPORT|INIT_START)/.test(a))_.push({source:j.mode||j.name,timestamp:new Date(t.timestamp??0).toISOString(),when:PT(t.timestamp??0),message:a.slice(0,400),level:/error|exception|fatal|panic|traceback/i.test(a)?"error":/warn|warning|timeout|retr(?:y|ies)|throttl/i.test(a)?"warn":"info"})}d=J0.filter((t)=>!/^(?:START|END|REPORT|INIT_START)/.test((t.message??"").trim())).slice(-6).map((t)=>({ts:new Date(t.timestamp??0).toISOString().slice(11,19),msg:(t.message??"").trim().slice(0,120),err:/error|exception|fatal/i.test(t.message??"")}))}catch{}let s=Math.max(1,...y);V.push({key:j.mode,name:j.name,version:j.version,memory:c,timeout:P?.Configuration?.Timeout??0,runtime:P?.Configuration?.Runtime??"provided.al2023",invocations:Math.round(q),errors:Math.round(T),p95:I||Math.round(S),status:"active",provisioned:j.provisioned?`${j.provisioned.allocated}/${j.provisioned.requested}`:void 0}),A.push({key:j.mode,name:j.name,runtime:P?.Configuration?.Runtime??"provided.al2023",arch:P?.Configuration?.Architectures?.[0]??"x86_64",memory:c,timeout:P?.Configuration?.Timeout??0,ephemeral:P?.Configuration?.EphemeralStorage?.Size??512,version:j.version,concurrency:H?.concurrency??"—",invocations:Math.round(q),errors:Math.round(T),throttles:Math.round(D),p50:C||Math.round(S),p95:I||Math.round(S),p99:b||Math.round(S),maxMem:u,spark:y.length?y.map((J0)=>Math.round(J0/s*100)):[0],env:r.length?r:["(none)"],recent:d.length?d:[{ts:"—",msg:"no recent events",err:!1}]})}F.functions=V,F.functionsDetail=A,F.serverlessLogs=_.sort((j,q)=>String(q.timestamp).localeCompare(String(j.timestamp))).slice(0,600),F.serverlessLogsEmptyReason=_.length?void 0:"No recent function logs were found in CloudWatch for this environment.";let M=B?Number((K/B*100).toFixed(2)):0,E=Math.round(await R9(Q,Y.functions[0]?.name??"","ConcurrentExecutions","Maximum",U,z));F.metrics={invocations:Math.round(B),errorRatePct:M,p95Ms:Math.round(O),coldStartPct:0,concurrency:E,estCostUsd:0};try{let j=new P1(Z),q=[],T=[],D=0;try{let{QueueUrl:P}=await j.getQueueUrl(`${Y.slug}-${J}-dlq`),{Attributes:C}=await j.getQueueAttributes(P);D=Number(C.ApproximateNumberOfMessages??0)}catch{}let S=H?m8(H,Y.slug,J):[];for(let P of S){let C=P.name.replace(`${Y.slug}-${J}-`,""),I=0,b=0;try{let{QueueUrl:c}=await j.getQueueUrl(P.name),{Attributes:r}=await j.getQueueAttributes(c);I=Number(r.ApproximateNumberOfMessages??0),b=Number(r.ApproximateNumberOfMessagesNotVisible??0)}catch{}let y=Math.round(await N9(Q,"AWS/SQS","NumberOfMessagesDeleted",[{Name:"QueueName",Value:P.name}],"Sum",U,z));q.push({name:C,visible:I,inFlight:b,processed:y,dlq:D}),T.push({name:P.name,short:C,visible:I,inFlight:b,delayed:0,processed:y,oldestSec:0,concurrency:P.concurrency??H?.queueConcurrency??"—",tries:H?.queueTries??3,visTimeout:(H?.queueTimeout??120)*6,dlq:D})}if(q.length)F.queues=q;if(T.length)F.queuesDetail=T;F.dlqItems=[]}catch{}try{let j=new K0(Z),{Stacks:q}=await j.describeStacks({stackName:z$($,J)}),T={};for(let D of q?.[0]?.Outputs??[])if(D.OutputKey)T[D.OutputKey]=D.OutputValue??"";if(H?.database?.connection==="aurora-serverless"){let D=`${Y.slug}-${J}-db`,S=[{Name:"DBClusterIdentifier",Value:D}],[P,C]=await Promise.all([N9(Q,"AWS/RDS","ServerlessDatabaseCapacity",S,"Average",U,z),N9(Q,"AWS/RDS","DatabaseConnections",S,"Maximum",U,z)]);if(F.aurora={id:D,engine:"aurora-mysql",minAcu:H?.database?.minCapacity??0.5,maxAcu:H?.database?.maxCapacity??4,currentAcu:P?Number(P.toFixed(1)):H?.database?.minCapacity??0.5,database:"app",connections:Math.round(C),status:T.DbEndpoint?"available":"creating"},H?.rdsProxy)F.proxy={name:`${Y.slug}-${J}-proxy`,endpoint:T.DbProxyEndpoint??"—",pooledConns:Math.round(C),status:"available"}}if(H?.cache?.driver==="elasticache"){let D=`${Y.slug}-${J}-cache`,S=[{Name:"CacheClusterId",Value:`${D}-001`}],[P,C]=await Promise.all([N9(Q,"AWS/ElastiCache","CacheHits",S,"Sum",U,z),N9(Q,"AWS/ElastiCache","CacheMisses",S,"Sum",U,z)]),I=P+C>0?Number((P/(P+C)*100).toFixed(1)):0;F.redis={id:D,node:"cache.t4g.micro",engine:"redis",hitRate:I,status:T.CacheEndpoint?"available":"creating"}}if(H?.efs){let D=0;try{if(T.EfsFileSystemId){let S=new n7(Z),{FileSystems:P}=await S.describeFileSystems({FileSystemId:T.EfsFileSystemId});D=Number(((P?.[0]?.SizeInBytes?.Value??0)/1048576).toFixed(1))}}catch{}F.efs={id:T.EfsFileSystemId??"efs",mount:"/mnt/local",sizeMb:D,status:"available"}}F.assetsInfo=T.AssetsCdnDomain?{bucket:T.AssetsBucketName??`${Y.slug}-${J}-assets`,cdn:T.AssetsCdnDomain,customDomain:H?.assetDomain??"—",assetUrl:Y.assetUrl??"—",files:0,sizeMb:0,cacheHitPct:0,build:F.app.build}:void 0}catch{}if(F.assetsInfo)try{let q=await new W0(Z).list({bucket:F.assetsInfo.bucket,maxKeys:1000});F.assetsInfo.files=q.length,F.assetsInfo.sizeMb=Number((q.reduce((T,D)=>T+(D.Size??0),0)/1048576).toFixed(1)),F.assetsRecent=q.slice(0,8).map((T)=>({path:`/${T.Key}`,size:`${Math.max(1,Math.round((T.Size??0)/1024))} KB`,type:T.Key.split(".").pop()??""}))}catch{}try{if(H?.secrets){let j=Array.isArray(H.secrets)?H.secrets.map((q)=>({key:q.split("/").pop().toUpperCase().replace(/[^A-Z0-9_]/g,"_"),source:q})):Object.entries(H.secrets).map(([q,T])=>({key:q,source:String(T)}));F.secretsList=j.map((q)=>({...q,updated:"—"}))}}catch{}try{let j=new W0(Z),q=`${Y.slug}-${J}-deployments`,T=await j.getObjectJson(q,`deployments/${Y.slug}/${J}/history.json`).catch(()=>null);if(T?.records?.length)F.deploymentsDetail=T.records.slice(-12).reverse().map((D)=>({sha:(D.sha??"").slice(0,7),status:D.status??"success",when:D.timestamp??"—",took:D.took??"—",by:D.by??"—",version:D.version??"—",hooks:D.hooks??[]}))}catch{}F.metricsTotals={invocations:F.metrics.invocations,errors:Math.round(K),errorRatePct:M,p95Ms:F.metrics.p95Ms,throttles:A.reduce((j,q)=>j+q.throttles,0),coldStartPct:0,estCostUsd:0,concurrency:E},F.metricsPerFn=A.map((j)=>({key:j.key,invocations:j.invocations,errors:j.errors,throttles:j.throttles,avgMs:j.p50,maxMs:j.p99,costUsd:0}));try{F.invSpark=await Q.getMetricSeries({Namespace:"AWS/Lambda",MetricName:"Invocations",Dimensions:[{Name:"FunctionName",Value:Y.functions.find((j)=>j.mode==="http")?.name??""}],StartTime:new Date(z.getTime()-86400000),EndTime:z,Period:3600,Stat:"Sum"})}catch{}try{let j=new o8,q=z,T=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth(),1)),D=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()-1,1)),[S,P]=await Promise.all([j.getCostByService({start:Y8(T),end:Y8(q),granularity:"MONTHLY"}).catch(()=>[]),j.getCostByService({start:Y8(D),end:Y8(T),granularity:"MONTHLY"}).catch(()=>[])]);if(S.length){let C=S.reduce((u,s)=>u+s.amount,0),I=P.reduce((u,s)=>u+s.amount,0),b=q.getUTCDate(),y=new Date(Date.UTC(q.getUTCFullYear(),q.getUTCMonth()+1,0)).getUTCDate();F.costSummary={monthToDateUsd:Number(C.toFixed(2)),projectedUsd:Number((C/b*y).toFixed(2)),lastMonthUsd:Number(I.toFixed(2)),dailyAvgUsd:Number((C/b).toFixed(2))},F.costServices=S.filter((u)=>u.amount>0).sort((u,s)=>s.amount-u.amount).slice(0,12).map((u)=>({name:u.service,usd:Number(u.amount.toFixed(2)),note:""})),F.metrics.estCostUsd=Number((C/b).toFixed(2)),F.metricsTotals.estCostUsd=F.metrics.estCostUsd,F.costTrend=await j.getDailyTotals({start:Y8(T),end:Y8(q)}).catch(()=>[]);let c=S.find((u)=>/lambda/i.test(u.service))?.amount??0,r=(u)=>u.invocations*(u.p50/1000)*(u.memory/1024),d=A.reduce((u,s)=>u+r(s),0)||1;F.costPerFn=A.map((u)=>({key:u.key,requests:u.invocations,gbSec:Math.round(r(u)),usd:Number((c*(r(u)/d)).toFixed(2))}))}}catch{}if(H?.firewall)try{let j=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"BlockedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]),q=await Q.getMetricStatistics({Namespace:"AWS/WAFV2",MetricName:"AllowedRequests",StartTime:U,EndTime:z,Period:86400,Statistics:["Sum"]}).catch(()=>[]);F.waf={enabled:!0,scope:"REGIONAL",acl:`${Y.slug}-${J}-waf`,allowed24h:Math.round(q.reduce((T,D)=>T+(D.Sum??0),0)),blocked24h:Math.round(j.reduce((T,D)=>T+(D.Sum??0),0))};try{let T=new lQ(Z),D=await T.listWebACLs("REGIONAL"),S=D.find((P)=>P.Name?.includes(`${Y.slug}-${J}`))??D[0];if(S?.Name&&S.Id){F.waf.acl=S.Name;let P=await T.getWebACLRules(S.Name,S.Id,"REGIONAL");if(P.length)F.wafRules=P.map((C)=>({name:C.Name??"—",detail:`priority ${C.Priority??0}`,action:C.Action??"count",blocked24h:0}))}}catch{}}catch{}if(Y.scheduler!=="off"&&H?.kind==="php")try{let j=await n$($,J,"schedule:list"),q=[];for(let T of(j||"").split(`
|
|
7508
7508
|
`)){let D=/^\s*([\d*/,\-\s]+?)\s{2,}(.+?)(?:\s{2,}Next Due.*)?$/.exec(T);if(D&&/[*\d]/.test(D[1])&&D[1].trim().split(/\s+/).length===5)q.push({command:D[2].trim().replace(/^php artisan /,""),cron:D[1].trim(),desc:"",lastRun:"—",lastStatus:"ok"})}if(q.length)F.schedulerTasks=q}catch{}return F}var a7=o(async()=>{L1();NZ();i8();U7();mQ();n1();I0();D9();LF();await z8([n0(),Q1()])});import{createHash as CT}from"node:crypto";function TF($){let J=rQ($.name),Y=nQ($.publicKey),Z=IT([...$.existingKeys??[],{name:J,publicKey:Y}]);return DF($.configText,Z)}function wF($){let J=rQ($.name),Y=($.existingKeys??[]).filter((Z)=>Z.name!==J);if(($.existingKeys??[]).length===Y.length)throw Error(`SSH key '${J}' does not exist in compute.sshKeys`);return DF($.configText,Y)}function r2($=[]){return $.map((J)=>({name:J.name,publicKey:J.publicKey,type:kT(J.publicKey),fingerprint:hT(J.publicKey),added:"configured"}))}function DF($,J){let Y=bT($,"compute"),Z=xT(J),Q=yT($,Y.start,Y.end,"sshKeys");if(Q){let U=Q.propertyStart;while(U>0&&$[U-1]!==`
|
|
7509
7509
|
`&&/\s/.test($[U-1]))U--;return`${$.slice(0,U)}${Z}${$.slice(Q.end+1)}`}let G=$.slice(0,Y.end).trimEnd(),W=$.slice(Y.end),z=G.endsWith(",")||G.endsWith("{")?"":",";return`${G}${z}
|
|
7510
7510
|
${Z},
|
|
@@ -7517,7 +7517,7 @@ ${$.map((Y)=>[" {",` name: '${qF(Y.name)}',`,` publicKe
|
|
|
7517
7517
|
`)){let Z=Y.trim();if(Z.startsWith("SVC=")){let[,Q,G,W,z,U]=/^SVC=([^=]+)=([^=]+)(?:=([^=]*)(?:=([^=]*)(?:=(.*))?)?)?$/.exec(Z)??[];if(Q)J.services.push({name:Q,status:G,memBytes:Number(W||0),enabled:z||H1,since:U||H1})}else{let Q=Z.indexOf("=");if(Q>0)J[Z.slice(0,Q)]=Z.slice(Q+1)}}return J}function PF($){let J=$.infrastructure?.compute,Y=[];if(J?.webServer==="rpx"||J?.proxy?.engine==="rpx")Y.push({name:"rpx-gateway",status:"configured"});else if(J?.webServer==="nginx"||J?.webServer==null)Y.push({name:"ts-cloud-nginx",status:"configured"});let Z=J?.php?.versions??(J?.runtime==="php"?["8.3"]:[]);for(let W of Z)Y.push({name:`php${W}-fpm`,status:"configured"});let Q=J?.managedServices??{},G=[["mysql","mysql"],["mariadb","mariadb"],["postgres","postgresql"],["redis","redis"],["memcached","memcached"],["meilisearch","meilisearch"]];for(let[W,z]of G)if(Q[W])Y.push({name:z,status:"configured"});return Y}function cT($){let J=$.infrastructure?.compute?.backups,Y=!!J?.enabled,Z=J?.schedule??"0 2 * * *";return{enabled:Y,schedule:Z,destination:Y?J?.bucket??"local":"off",retention:Y?J?.retentionCount??5:0,last:Y?"pending first run":"not configured",size:Y?H1:"0 MB"}}function CF($){return $.infrastructure?.compute?.provider??$.cloud?.provider??$.provider??"aws"}function mT($){if(CF($)==="hetzner")return $.hetzner?.location??process.env.HCLOUD_LOCATION??process.env.HETZNER_LOCATION??"fsn1";return $.project.region??"us-east-1"}function lT($,J){let Y=gT(process.cwd(),".ts-cloud","state",`${$.project.slug}-${J}.json`);if(!vT(Y))return null;try{return JSON.parse(fT(Y,"utf8"))}catch{return null}}function pT($){let J=$.sites??{},Y=[];for(let[Z,Q]of Object.entries(J)){let G=Q.queues??Q.workers;if(Array.isArray(G)){for(let W of G)if(typeof W==="string")Y.push({name:`${Z}:${W}`,site:Z,processes:1,status:"configured"});else if(W?.name)Y.push({name:`${Z}:${W.name}`,site:Z,processes:W.processes??1,status:"configured"})}}return Y}function xF($){if(!$||$==="")return"/";return $.startsWith("/")?$:`/${$}`}function rT($){let J=xF($.path);if(!$.domain)return{route:"internal"};return{route:J==="/"?$.domain:`${$.domain}${J}`,href:`https://${$.domain}${J==="/"?"":J}`}}function NF($,J){let Y=p0(J),Z=String(J.build??"").toLowerCase(),Q=String(J.start??"").toLowerCase();if($==="main"||Q.includes("buddy/src/cli.ts serve"))return"stacks";if($==="api"||Q.includes("/serve/api"))return"api";if(Z.includes("buildblog"))return"bunpress blog";if(Z.includes("bunpress"))return"bunpress";if(Z.includes("site:build")||Z.includes("stx"))return"stx static";if(Y==="server-static")return J.spa?"spa":"static";if(Y==="server-app")return"app";if(Y==="server-php")return J.type??"php";return"bucket"}function nT($){let J=p0($),Y=`${$.start??""} ${$.build??""}`.toLowerCase();if(J==="server-static")return Y.includes("bunpress")||Y.includes("bun ")||Y.includes("bunx ")?"static/bun":"static";if(J==="server-app")return Y.includes("bun")?"bun":"node";if(J==="server-php")return`php ${$.php??$.phpVersion??"8.3"}`;return"static"}function iT($){let J=p0($);if(J==="server-app")return"service";if(J==="server-static")return"server static";if(J==="server-php")return"php release";return"bucket"}function aT($){let J=new Map;return Object.entries($.sites??{}).map(([Y,Z])=>{let Q=xF(Z.path),{route:G,href:W}=rT(Z),z=Z.domain?`${Z.domain}${Q}`:"",U=z?J.get(z):void 0;if(z&&!U)J.set(z,Y);return{name:Y,route:G,href:W,domain:Z.domain??"internal",path:Q,kind:NF(Y,Z),type:NF(Y,Z),runtime:nT(Z),deploy:iT(Z),tls:Z.domain?Z.ssl===!1?"http":"https":"loopback",ssl:Z.domain?Z.ssl!==!1:!1,status:U?"shadowed":"live",shadowedBy:U,lastDeploy:H1}})}function aQ($){return`'${$.replaceAll("'","'\\''")}'`}function IF($){return $.replace(/[\\&/]/g,"\\$&")}function tT($){if($.length===0)return["true"];return["set +e",...$.map((J)=>{let Y=aQ(`/var/www/${J}/.ts-cloud/deploy-history.log`),Z=IF(J);return`TS_CLOUD_HISTORY=${Y}; { [ -f "$TS_CLOUD_HISTORY" ] && tail -n 24 "$TS_CLOUD_HISTORY" | sed "s/^/DEPLOY=${Z}\\t/"; } || true`}),"true"]}function kF($){return[...new Set(Object.values($.sites??{}).map((J)=>J.domain).filter((J)=>typeof J==="string"&&J.length>0))]}function sT($){return["set +e",'if command -v ss >/dev/null 2>&1; then ss -H -lntup 2>/dev/null | while read -r proto _state _recv _send local _peer rest; do [ -n "$proto" ] && [ -n "$local" ] && printf "PORT=%s\\t%s\\t%s\\n" "$proto" "$local" "$rest"; done; fi','if command -v ufw >/dev/null 2>&1; then ufw status numbered 2>/dev/null | sed "s/^/FIREWALL=/"; else echo "FIREWALL=ufw unavailable"; fi','journalctl _COMM=sshd --no-pager -n 30 -o short-iso 2>/dev/null | sed "s/^/AUTH=/" || true',...kF($).map((Y)=>{return`TS_CLOUD_DOMAIN=${aQ(Y)}; TS_CLOUD_EXPIRY=$(echo | timeout 8 openssl s_client -servername "$TS_CLOUD_DOMAIN" -connect "$TS_CLOUD_DOMAIN:443" 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2-); [ -n "$TS_CLOUD_EXPIRY" ] && printf "CERT=%s\\t%s\\n" "$TS_CLOUD_DOMAIN" "$TS_CLOUD_EXPIRY" || printf "CERT=%s\\tunavailable\\n" "$TS_CLOUD_DOMAIN"`}),"true"]}function hF($){let J=new Map,Y=(G,W)=>{if(G&&W&&!J.has(W))J.set(W,{pattern:G,label:W})},Z=$.infrastructure?.compute,Q=$.project.slug;if(Z?.webServer==="rpx"||Z?.proxy?.engine==="rpx")Y("rpx-gateway","rpx-gateway");else Y("nginx","nginx");for(let G of PF($))Y(G.name,G.name);for(let[G,W]of Object.entries($.sites??{})){if(p0(W)!=="server-app")continue;if(Y(`${Q}-${G}`,`${Q}-${G}`),Array.isArray(W.queues??W.workers)&&(W.queues??W.workers).length)Y(`${Q}-${G}-queue-*`,`${Q}-${G}-queues`);if(Array.isArray(W.daemons)&&W.daemons.length)Y(`${Q}-${G}-daemon-*`,`${Q}-${G}-daemons`)}return[...J.values()]}function oT($){let J=hF($);if(J.length===0)return["true"];return["set +e",...J.map((Y)=>{let Z=aQ(Y.pattern),Q=IF(Y.label);return`journalctl -u ${Z} --no-pager -n 150 -o short-iso 2>/dev/null | sed "s/^/LOG=${Q}\\t/" || true`}),'[ -f /var/log/ts-cloud-backup.log ] && tail -n 60 /var/log/ts-cloud-backup.log 2>/dev/null | sed "s/^/LOG=backups\\t/" || true',"true"]}function tQ($){let J=new Date($);if(Number.isNaN(J.getTime()))return $||H1;let Y=Math.max(0,Math.round((Date.now()-J.getTime())/1000));if(Y<60)return`${Y}s ago`;let Z=Math.round(Y/60);if(Z<60)return`${Z}m ago`;let Q=Math.round(Z/60);if(Q<48)return`${Q}h ago`;return`${Math.round(Q/24)}d ago`}function bF($){if(/(?:error|failed|panic|fatal|exception|denied|unhealthy)/i.test($))return"error";if(/(?:warn|warning|retry|restart|deprecated|timeout)/i.test($))return"warn";return"info"}function yF($){let J=[];for(let Y of $.split(`
|
|
7518
7518
|
`)){let Z=Y.trim();if(!Z.startsWith("LOG="))continue;let Q=Z.indexOf("\t");if(Q<0)continue;let G=Z.slice(4,Q),W=Z.slice(Q+1),z=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(W),U=z?.[1]??"",H=z?.[2]??"",F=(z?.[3]??W).trim();if(!F)continue;J.push({source:G,timestamp:U,when:U?tQ(U):H1,host:H,message:F,level:bF(F)})}return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,600)}function vF($){if(/^(?:127\.|localhost:|\[?::1\]?)/.test($))return"loopback";if(/^(?:10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.|\[?f[cd][0-9a-f:])/i.test($))return"private";return"public"}function eT($){if(vF($)!=="public")return"ok";if(/:(?:22|80|443)$/.test($)||/^\*:(?:22|80|443)$/.test($))return"ok";return"warn"}function $3($){if($==null)return"warn";if($<8)return"bad";if($<30)return"warn";return"ok"}function fF($){let J=[],Y=[],Z=[],Q=[];for(let z of $.split(`
|
|
7519
7519
|
`)){let U=z.trim();if(U.startsWith("PORT=")){let[H="",F="",B=""]=U.slice(5).split("\t");if(H&&F)J.push({proto:H,listen:F,processName:B||H1,exposure:vF(F),tone:eT(F)})}else if(U.startsWith("FIREWALL=")){let H=U.slice(9).trim();if(H)Y.push(H)}else if(U.startsWith("AUTH=")){let H=U.slice(5),F=/^(\d{4}-\d{2}-\d{2}T[^\s]+)\s+(\S+)\s+(.*)$/.exec(H),B=(F?.[3]??H).trim();if(B)Z.push({timestamp:F?.[1]??"",when:F?.[1]?tQ(F[1]):H1,host:F?.[2]??"",message:B,level:bF(B)})}else if(U.startsWith("CERT=")){let[H="",F=""]=U.slice(5).split("\t");if(!H)continue;let B=new Date(F),K=Number.isNaN(B.getTime())?null:Math.ceil((B.getTime()-Date.now())/86400000);Q.push({domain:H,expires:Number.isNaN(B.getTime())?F||H1:B.toISOString().slice(0,10),daysRemaining:K,status:$3(K)})}}let G=Y.some((z)=>/Status:\s*active/i.test(z)),W=Y.some((z)=>/unavailable/i.test(z));return{ports:J.slice(0,80),firewall:{status:G?"active":W?"unavailable":"inactive",summary:G?"ufw active":W?"ufw unavailable":"ufw inactive or not configured",rules:Y.filter((z)=>z&&!/^Status:/i.test(z)).slice(0,60)},tlsCertificates:Q,authEvents:Z.sort((z,U)=>String(U.timestamp).localeCompare(String(z.timestamp))).slice(0,30)}}function sQ($){let Y=$.infrastructure?.compute?.firewall??{},Z=[...new Set([22,80,443,...Y.allowedPorts??[]])],Q=kF($);return{ports:Z.map((G)=>({proto:"tcp",listen:`0.0.0.0:${G}`,processName:"configured firewall",exposure:"public",tone:[22,80,443].includes(Number(G))?"ok":"warn"})),firewall:{status:Y.enabled===!1?"disabled":"configured",summary:Y.enabled===!1?"host firewall disabled in config":"host firewall configured declaratively",rules:Z.map((G)=>`ALLOW ${G}/tcp`)},tlsCertificates:Q.map((G)=>({domain:G,expires:H1,daysRemaining:null,status:"warn"})),authEvents:[]}}function gF($,J){let Y=J.security??sQ($),Z=!!J._serverReachable&&!J.metricsUnavailable,Q=J.sites??[],G=Q.filter((H)=>H.status==="shadowed"),W=(J.services??[]).filter((H)=>["failed","stopped"].includes(H.status)),z=(Y.tlsCertificates??[]).filter((H)=>H.status!=="ok"),U=J.sshKeys??[];return[{name:"Live server probe",status:Z?"pass":"warn",detail:Z?"Metrics and remote checks are coming from the compute box.":"The dashboard is rendering config/state data until the box probe succeeds."},{name:"Managed services",status:W.length?"fail":"pass",detail:W.length?`${W.length} service(s) need attention.`:`${(J.services??[]).length} service(s) reported healthy or configured.`},{name:"Route conflicts",status:G.length?"warn":"pass",detail:G.length?`${G.map((H)=>H.name).join(", ")} is shadowed by an earlier route.`:`${Q.length} site route(s) are unshadowed.`},{name:"SSH access",status:U.length?"pass":"warn",detail:U.length?`${U.length} declarative authorized key(s) configured.`:"No declarative SSH keys are configured."},{name:"Firewall",status:["active","configured"].includes(Y.firewall?.status)?"pass":"warn",detail:Y.firewall?.summary??"Firewall status unavailable."},{name:"TLS certificates",status:z.length?"warn":"pass",detail:z.length?`${z.length} certificate(s) need renewal visibility.`:`${(Y.tlsCertificates??[]).length} certificate(s) look healthy.`}]}function uF($){let J=[];for(let Y of $.serverDeploymentsDetail??$.serverDeployments??[])J.push({type:"deploy",tone:Y.status==="failed"?"bad":"ok",title:`${Y.site} deployed ${Y.sha}`,detail:`${Y.branch} · ${Y.status}`,when:Y.when,timestamp:Y.timestamp});for(let Y of $.serverLogs??[])if(Y.level==="error"||Y.level==="warn")J.push({type:"log",tone:Y.level==="error"?"bad":"warn",title:`${Y.source} ${Y.level}`,detail:Y.message,when:Y.when,timestamp:Y.timestamp});for(let Y of $.sshKeys??[])J.push({type:"ssh",tone:"ok",title:`${Y.name} authorized`,detail:Y.fingerprint,when:Y.added??H1,timestamp:""});return J.sort((Y,Z)=>String(Z.timestamp).localeCompare(String(Y.timestamp))).slice(0,80)}function dF($,J={}){let Y=[];for(let Z of $.split(`
|
|
7520
|
-
`)){let Q=Z.trim();if(!Q.startsWith("DEPLOY="))continue;let G=Q.split("\t"),W=G[0]?.replace(/^DEPLOY=/,"")??"",[z,U,H,F,B]=G.slice(1);if(!W||!z||!U)continue;let K=J[W]??{},O=p0(K),V=(H||U).slice(0,7);Y.push({sha:V,release:U,commit:H||U,site:W,branch:K.branch??(O==="server-static"?"build artifact":"main"),status:F||"unknown",when:tQ(z),timestamp:z,took:"-",by:"ts-cloud",rc:B?.replace(/^rc=/,"")??"",steps:O==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return Y.sort((Z,Q)=>String(Q.timestamp).localeCompare(String(Z.timestamp)))}function cF($,J){let Y=lT($,J),Z=PF($),Q=aT($),G=Math.max(1,Number($.infrastructure?.compute?.disk?.size??1)),W={server:{name:Y?.serverName??`${$.project.slug}-${J}-app`,provider:Y?.provider??CF($),region:mT($),ip:Y?.publicIp??H1,os:"Linux",uptime:H1,probeStatus:"unavailable"},systemMetrics:{load:0,cpus:Math.max(1,Number($.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:G},metricsUnavailable:!0,services:Z,servicesDetail:Z.map((z)=>({...z,since:H1,memMb:0,auto:!0})),backup:cT($),backupHistory:[],workers:pT($),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:sQ($),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:Q,sitesDetail:Q.map((z)=>{let U=$.sites?.[z.name]??{},H=p0(U);return{...z,root:H==="server-static"?`/var/www/${z.name}`:`/var/www/${z.name}/current`,branch:H==="server-static"?"build artifact":"main",build:U.build,envKeys:Object.keys(U.env??U.environment??{})}}),sshKeys:r2($.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return W.diagnostics=gF($,W),W.activity=uF(W),W}async function oQ($,J){if(!$.infrastructure?.compute)return null;let Y=null;try{Y=Y1({config:$})}catch{Y=null}let Z=null,Q=0,G=[];if(Y)try{if(G=await Y.findComputeTargets({slug:$.project.slug,environment:J,role:"app"}),Q=G.length,G.length){let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:dT(),comment:`ts-cloud dashboard:build ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output;if(F)Z=SF(F)}}catch{}let W=cF($,J),z=(H,F=0)=>{let B=Number(H);return Number.isFinite(B)?B:F};if(W.server.os=Z?.OS||W.server.os,W.server.uptime=Z?.UPTIME||W.server.uptime,Z){if(W.server.probeStatus="live",W.metricsUnavailable=!1,W._metricsStatus="live",W.systemMetrics={load:z(Z.LOAD),cpus:z(Z.CPUS,1),memUsedMb:z(Z.MEMUSED),memTotalMb:z(Z.MEMTOTAL,1),diskUsedPct:z(Z.DISKPCT),diskUsedGb:z(Z.DISKUSEDG),diskTotalGb:z(Z.DISKTOTG,1)},Z.services.length)W.services=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status})),W.servicesDetail=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status,since:H.since&&H.since!==H1?H.since:W.server.uptime,memMb:Math.max(0,Math.round(Number(H.memBytes??0)/1024/1024)),auto:H.enabled?!["disabled","static","masked"].includes(H.enabled):!0}))}if(Y&&G.length)try{let H=Object.keys($.sites??{}),B=(await Y.runRemoteDeploy({targets:[G[0]],commands:tT(H),comment:`ts-cloud dashboard:deploy-history ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",K=dF(B,$.sites);W.serverDeployments=K.slice(0,5),W.serverDeploymentsDetail=K.slice(0,50),W.deploymentsEmptyReason=K.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{W.deploymentsEmptyReason="Deployment history could not be read from the server."}else if(Y&&Q===0)W.deploymentsEmptyReason="No app server target was found for this environment.";if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:oT($),comment:`ts-cloud dashboard:server-logs ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=yF(F);W.serverLogs=B,W.serverLogsEmptyReason=B.length?void 0:"No recent journal entries were found for the managed server units."}catch{W.serverLogsEmptyReason="Server logs could not be read from the box."}if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:sT($),comment:`ts-cloud dashboard:security ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=fF(F),K=sQ($);if(!B.ports.length)B.ports=K.ports;if(!B.tlsCertificates.length)B.tlsCertificates=K.tlsCertificates;W.security=B,W.securityEmptyReason=void 0}catch{W.securityEmptyReason="Server security checks could not be read from the box."}let U=$.infrastructure?.compute?.sshKeys??$.infrastructure?.ssh?.keys??$.infrastructure?.sshKeys;if(Array.isArray(U)&&U.length)W.sshKeys=r2(U);return W._serverReachable=Q>0&&!!Z,W.diagnostics=gF($,W),W.activity=uF(W),W}var uT,H1="-";var eQ=o(async()=>{B$();iQ();await _$();uT=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"]});import{existsSync as _X}from"node:fs";import Z5 from"node:fs/promises";import uG from"node:os";import Q5 from"node:path";import a2 from"node:process";import{EventEmitter as jX}from"node:events";import P2 from"node:process";import dG from"node:process";import U5 from"node:process";import k9 from"node:process";import F8 from"node:process";import lG from"node:tty";import GB,{stdin as qw,stdout as Tw}from"node:process";import rG,{stdin as UB,stdout as HB}from"node:process";import FB from"node:readline";class iG{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=uG.homedir(),J=Q5.join($,".config","clapp");this.configPath=Q5.join(J,"telemetry.json")}async isEnabled(){if(a2.env.DO_NOT_TRACK==="1"||a2.env.DO_NOT_TRACK==="true")return!1;if(a2.env.NO_TELEMETRY==="1"||a2.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,J){if(!await this.isEnabled())return;let Z={event:$,...J,timestamp:Date.now(),platform:uG.platform(),nodeVersion:a2.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand($,J){await this.track("command",{command:$,duration:J})}async trackError($,J){await this.track("error",{error:$,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((J)=>setTimeout(J,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:a2.env.DO_NOT_TRACK==="1"||a2.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(_X(this.configPath)){let $=await Z5.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let J=Q5.dirname(this.configPath);await Z5.mkdir(J,{recursive:!0}),await Z5.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${$}-${J}`}}var Fw=new iG;function LX($,J={}){let Y={_:[]},Z=J.alias||{},Q=new Set(J.boolean||[]),G={};for(let z of Object.keys(Z))for(let U of Z[z])G[U]=z;for(let z of Q)if(Z[z])for(let U of Z[z])Q.add(U);function W(z,U){let H=G[z]||z;if(Y[H]=U,Z[H])for(let F of Z[H])Y[F]=U;if(G[z]&&Z[G[z]])for(let F of Z[G[z]])Y[F]=U;Y[z]=U}for(let z=0;z<$.length;z++){let U=$[z];if(U==="--"){Y._.push(...$.slice(z+1));break}if(U.startsWith("--")){let H=U.indexOf("=");if(H!==-1){let F=U.slice(2,H),B=U.slice(H+1);W(F,B)}else{let F=U.slice(2);if(F.startsWith("no-")){let K=F.slice(3);W(K,!1);continue}let B=G[F]||F;if(Q.has(B)||Q.has(F))W(F,!0);else{let K=$[z+1];if(K!==void 0&&!K.startsWith("-"))W(F,K),z++;else W(F,!0)}}}else if(U.startsWith("-")&&U.length>1){let H=U.slice(1);for(let F=0;F<H.length;F++){let B=H[F],K=G[B]||B;if(F===H.length-1&&!Q.has(K)&&!Q.has(B)){let O=$[z+1];if(O!==void 0&&!O.startsWith("-"))W(B,O),z++;else W(B,!0)}else W(B,!0)}}else Y._.push(U)}return Y}function z5($){return $.replace(/[<[].+/,"").trim()}function EX($){let J=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,Z=[],Q=(z)=>{let U=!1,H=z[1];if(H.startsWith("..."))H=H.slice(3),U=!0;return{required:z[0].startsWith("<"),value:H,variadic:U}},G;while(G=J.exec($))Z.push(Q(G));let W;while(W=Y.exec($))Z.push(Q(W));return Z}function MX($){let J={alias:{},boolean:[]};for(let[Y,Z]of $.entries()){if(Z.names.length>1)J.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!$.some((G,W)=>{return W!==Y&&G.names.some((z)=>Z.names.includes(z))&&typeof G.required==="boolean"}))J.boolean.push(Z.names[0])}else J.boolean.push(Z.names[0])}return J}function cG($){return $.reduce((J,Y)=>J.length>=Y.length?J:Y,"")}function G5($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function qX($){return $.replace(/([a-z])-([a-z])/g,(J,Y,Z)=>{return Y+Z.toUpperCase()})}function TX($,J,Y){let Z=0,Q=J.length,G=$,W;for(;Z<Q;++Z)W=G[J[Z]],G=G[J[Z]]=Z===Q-1?Y:W!=null?W:!!~J[Z+1].indexOf(".")||!(+J[Z+1]>-1)?{}:[]}function wX($,J){for(let Y of Object.keys(J)){let Z=J[Y];if(Z.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof Z.transformFunction==="function")$[Y]=$[Y].map(Z.transformFunction)}}}function DX($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function aG($){return $.split(".").map((J,Y)=>{return Y===0?qX(J):J}).join(".")}class I9 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
7520
|
+
`)){let Q=Z.trim();if(!Q.startsWith("DEPLOY="))continue;let G=Q.split("\t"),W=G[0]?.replace(/^DEPLOY=/,"")??"",[z,U,H,F,B]=G.slice(1);if(!W||!z||!U)continue;let K=J[W]??{},O=p0(K),V=(H||U).slice(0,7);Y.push({sha:V,release:U,commit:H||U,site:W,branch:K.branch??(O==="server-static"?"build artifact":"main"),status:F||"unknown",when:tQ(z),timestamp:z,took:"-",by:"ts-cloud",rc:B?.replace(/^rc=/,"")??"",steps:O==="server-static"?["upload artifact","publish static files"]:["upload artifact","restart service"]})}return Y.sort((Z,Q)=>String(Q.timestamp).localeCompare(String(Z.timestamp)))}function cF($,J){let Y=lT($,J),Z=PF($),Q=aT($),G=Math.max(1,Number($.infrastructure?.compute?.disk?.size??1)),W={server:{name:Y?.serverName??`${$.project.slug}-${J}-app`,provider:Y?.provider??CF($),region:mT($),ip:Y?.publicIp??H1,os:"Linux",uptime:H1,probeStatus:"unavailable"},systemMetrics:{load:0,cpus:Math.max(1,Number($.infrastructure?.compute?.instances??1)),memUsedMb:0,memTotalMb:0,diskUsedPct:0,diskUsedGb:0,diskTotalGb:G},metricsUnavailable:!0,services:Z,servicesDetail:Z.map((z)=>({...z,since:H1,memMb:0,auto:!0})),backup:cT($),backupHistory:[],workers:pT($),serverScheduler:{enabled:!1,lastRun:"not configured"},serverDeployments:[],serverDeploymentsDetail:[],deploymentsEmptyReason:"No deployment history has been recorded yet. Future server deploys will write /var/www/<site>/.ts-cloud/deploy-history.log.",serverLogs:[],serverLogsEmptyReason:"Live server logs are unavailable until the dashboard can reach the compute box.",security:sQ($),securityEmptyReason:"Live security checks are unavailable until the dashboard can reach the compute box.",sites:Q,sitesDetail:Q.map((z)=>{let U=$.sites?.[z.name]??{},H=p0(U);return{...z,root:H==="server-static"?`/var/www/${z.name}`:`/var/www/${z.name}/current`,branch:H==="server-static"?"build artifact":"main",build:U.build,envKeys:Object.keys(U.env??U.environment??{})}}),sshKeys:r2($.infrastructure?.compute?.sshKeys??[]),_serverReachable:!1,_metricsStatus:"unavailable"};return W.diagnostics=gF($,W),W.activity=uF(W),W}async function oQ($,J){if(!$.infrastructure?.compute)return null;let Y=null;try{Y=Y1({config:$})}catch{Y=null}let Z=null,Q=0,G=[];if(Y)try{if(G=await Y.findComputeTargets({slug:$.project.slug,environment:J,role:"app"}),Q=G.length,G.length){let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:dT(),comment:`ts-cloud dashboard:build ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output;if(F)Z=SF(F)}}catch{}let W=cF($,J),z=(H,F=0)=>{let B=Number(H);return Number.isFinite(B)?B:F};if(W.server.os=Z?.OS||W.server.os,W.server.uptime=Z?.UPTIME||W.server.uptime,Z){if(W.server.probeStatus="live",W.metricsUnavailable=!1,W._metricsStatus="live",W.systemMetrics={load:z(Z.LOAD),cpus:z(Z.CPUS,1),memUsedMb:z(Z.MEMUSED),memTotalMb:z(Z.MEMTOTAL,1),diskUsedPct:z(Z.DISKPCT),diskUsedGb:z(Z.DISKUSEDG),diskTotalGb:z(Z.DISKTOTG,1)},Z.services.length)W.services=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status})),W.servicesDetail=Z.services.map((H)=>({name:H.name,status:H.status==="active"?"running":H.status,since:H.since&&H.since!==H1?H.since:W.server.uptime,memMb:Math.max(0,Math.round(Number(H.memBytes??0)/1024/1024)),auto:H.enabled?!["disabled","static","masked"].includes(H.enabled):!0}))}if(Y&&G.length)try{let H=Object.keys($.sites??{}),B=(await Y.runRemoteDeploy({targets:[G[0]],commands:tT(H),comment:`ts-cloud dashboard:deploy-history ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",K=dF(B,$.sites);W.serverDeployments=K.slice(0,5),W.serverDeploymentsDetail=K.slice(0,50),W.deploymentsEmptyReason=K.length?void 0:"No deployment history was found on the server yet. Deploy again to populate this timeline."}catch{W.deploymentsEmptyReason="Deployment history could not be read from the server."}else if(Y&&Q===0)W.deploymentsEmptyReason="No app server target was found for this environment.";if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:oT($),comment:`ts-cloud dashboard:server-logs ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=yF(F);W.serverLogs=B,W.serverLogsEmptyReason=B.length?void 0:"No recent journal entries were found for the managed server units."}catch{W.serverLogsEmptyReason="Server logs could not be read from the box."}if(Y&&G.length)try{let F=(await Y.runRemoteDeploy({targets:[G[0]],commands:sT($),comment:`ts-cloud dashboard:security ${$.project.slug}`,tags:{Project:$.project.slug,Environment:J,Role:"app"}})).perInstance?.[0]?.output??"",B=fF(F),K=sQ($);if(!B.ports.length)B.ports=K.ports;if(!B.tlsCertificates.length)B.tlsCertificates=K.tlsCertificates;W.security=B,W.securityEmptyReason=void 0}catch{W.securityEmptyReason="Server security checks could not be read from the box."}let U=$.infrastructure?.compute?.sshKeys??$.infrastructure?.ssh?.keys??$.infrastructure?.sshKeys;if(Array.isArray(U)&&U.length)W.sshKeys=r2(U);return W._serverReachable=Q>0&&!!Z,W.diagnostics=gF($,W),W.activity=uF(W),W}var uT,H1="-";var eQ=o(async()=>{K$();iQ();await j$();uT=["rpx-gateway","nginx","php8.3-fpm","php8.2-fpm","mysql","mariadb","postgresql","redis","redis-server","meilisearch"]});import{existsSync as _X}from"node:fs";import Z5 from"node:fs/promises";import uG from"node:os";import Q5 from"node:path";import t2 from"node:process";import{EventEmitter as jX}from"node:events";import P2 from"node:process";import dG from"node:process";import U5 from"node:process";import k9 from"node:process";import F8 from"node:process";import lG from"node:tty";import GB,{stdin as qw,stdout as Tw}from"node:process";import rG,{stdin as UB,stdout as HB}from"node:process";import FB from"node:readline";class iG{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=uG.homedir(),J=Q5.join($,".config","clapp");this.configPath=Q5.join(J,"telemetry.json")}async isEnabled(){if(t2.env.DO_NOT_TRACK==="1"||t2.env.DO_NOT_TRACK==="true")return!1;if(t2.env.NO_TELEMETRY==="1"||t2.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,J){if(!await this.isEnabled())return;let Z={event:$,...J,timestamp:Date.now(),platform:uG.platform(),nodeVersion:t2.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand($,J){await this.track("command",{command:$,duration:J})}async trackError($,J){await this.track("error",{error:$,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((J)=>setTimeout(J,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:t2.env.DO_NOT_TRACK==="1"||t2.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(_X(this.configPath)){let $=await Z5.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let J=Q5.dirname(this.configPath);await Z5.mkdir(J,{recursive:!0}),await Z5.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${$}-${J}`}}var Fw=new iG;function LX($,J={}){let Y={_:[]},Z=J.alias||{},Q=new Set(J.boolean||[]),G={};for(let z of Object.keys(Z))for(let U of Z[z])G[U]=z;for(let z of Q)if(Z[z])for(let U of Z[z])Q.add(U);function W(z,U){let H=G[z]||z;if(Y[H]=U,Z[H])for(let F of Z[H])Y[F]=U;if(G[z]&&Z[G[z]])for(let F of Z[G[z]])Y[F]=U;Y[z]=U}for(let z=0;z<$.length;z++){let U=$[z];if(U==="--"){Y._.push(...$.slice(z+1));break}if(U.startsWith("--")){let H=U.indexOf("=");if(H!==-1){let F=U.slice(2,H),B=U.slice(H+1);W(F,B)}else{let F=U.slice(2);if(F.startsWith("no-")){let K=F.slice(3);W(K,!1);continue}let B=G[F]||F;if(Q.has(B)||Q.has(F))W(F,!0);else{let K=$[z+1];if(K!==void 0&&!K.startsWith("-"))W(F,K),z++;else W(F,!0)}}}else if(U.startsWith("-")&&U.length>1){let H=U.slice(1);for(let F=0;F<H.length;F++){let B=H[F],K=G[B]||B;if(F===H.length-1&&!Q.has(K)&&!Q.has(B)){let O=$[z+1];if(O!==void 0&&!O.startsWith("-"))W(B,O),z++;else W(B,!0)}else W(B,!0)}}else Y._.push(U)}return Y}function z5($){return $.replace(/[<[].+/,"").trim()}function EX($){let J=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,Z=[],Q=(z)=>{let U=!1,H=z[1];if(H.startsWith("..."))H=H.slice(3),U=!0;return{required:z[0].startsWith("<"),value:H,variadic:U}},G;while(G=J.exec($))Z.push(Q(G));let W;while(W=Y.exec($))Z.push(Q(W));return Z}function MX($){let J={alias:{},boolean:[]};for(let[Y,Z]of $.entries()){if(Z.names.length>1)J.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!$.some((G,W)=>{return W!==Y&&G.names.some((z)=>Z.names.includes(z))&&typeof G.required==="boolean"}))J.boolean.push(Z.names[0])}else J.boolean.push(Z.names[0])}return J}function cG($){return $.reduce((J,Y)=>J.length>=Y.length?J:Y,"")}function G5($,J){return $.length>=J?$:`${$}${" ".repeat(J-$.length)}`}function qX($){return $.replace(/([a-z])-([a-z])/g,(J,Y,Z)=>{return Y+Z.toUpperCase()})}function TX($,J,Y){let Z=0,Q=J.length,G=$,W;for(;Z<Q;++Z)W=G[J[Z]],G=G[J[Z]]=Z===Q-1?Y:W!=null?W:!!~J[Z+1].indexOf(".")||!(+J[Z+1]>-1)?{}:[]}function wX($,J){for(let Y of Object.keys(J)){let Z=J[Y];if(Z.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof Z.transformFunction==="function")$[Y]=$[Y].map(Z.transformFunction)}}}function DX($){let J=/([^\\/]+)$/.exec($);return J?J[1]:""}function aG($){return $.split(".").map((J,Y)=>{return Y===0?qX(J):J}).join(".")}class I9 extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
7521
7521
|
|
|
7522
7522
|
Stack trace:
|
|
7523
7523
|
${this.stack}`;return this.message}}function RX(){let{env:$}=dG,{TERM:J,TERM_PROGRAM:Y}=$;if(dG.platform!=="win32")return J!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var y9="\x1B",b0=`${y9}[`;var X2={to($,J){if(!J)return`${b0}${$+1}G`;return`${b0}${J+1};${$+1}H`},move($,J){let Y="";if($<0)Y+=`${b0}${-$}D`;else if($>0)Y+=`${b0}${$}C`;if(J<0)Y+=`${b0}${-J}A`;else if(J>0)Y+=`${b0}${J}B`;return Y},up:($=1)=>`${b0}${$}A`,down:($=1)=>`${b0}${$}B`,forward:($=1)=>`${b0}${$}C`,backward:($=1)=>`${b0}${$}D`,nextLine:($=1)=>`${b0}E`.repeat($),prevLine:($=1)=>`${b0}F`.repeat($),left:`${b0}G`,hide:`${b0}?25l`,show:`${b0}?25h`,save:`${y9}7`,restore:`${y9}8`};var W5={screen:`${b0}2J`,up:($=1)=>`${b0}1J`.repeat($),down:($=1)=>`${b0}J`.repeat($),line:`${b0}2K`,lineEnd:`${b0}K`,lineStart:`${b0}1K`,lines($){let J="";for(let Y=0;Y<$;Y++)J+=this.line+(Y<$-1?X2.up():"");if($)J+=X2.left;return J}},Ow={screen:`${y9}c`};function NX($,J){let Y=[];for(let Z=0;Z<=J.length;Z++)Y[Z]=[Z];for(let Z=0;Z<=$.length;Z++)Y[0][Z]=Z;for(let Z=1;Z<=J.length;Z++)for(let Q=1;Q<=$.length;Q++)if(J.charAt(Z-1)===$.charAt(Q-1))Y[Z][Q]=Y[Z-1][Q-1];else Y[Z][Q]=Math.min(Y[Z-1][Q-1]+1,Y[Z][Q-1]+1,Y[Z-1][Q]+1);return Y[J.length][$.length]}function tG($,J,Y=2,Z=3){return J.map((Q)=>({cmd:Q,distance:NX($,Q)})).filter(({distance:Q})=>Q<=Y).sort((Q,G)=>Q.distance-G.distance).slice(0,Z).map(({cmd:Q})=>Q)}class sG{rawName;description;name;names;isBoolean;required;config;negated;constructor($,J,Y){if(this.rawName=$,this.description=J,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=z5($).split(",").map((Z)=>{let Q=Z.trim().replace(/^-{1,2}/,"");if(Q.startsWith("no-"))this.negated=!0,Q=Q.replace(/^no-/,"");return aG(Q)}).sort((Z,Q)=>Z.length>Q.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var Vw=U5.argv,SX=`${U5.platform}-${U5.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,mG=k9.argv,PX=`${k9.platform}-${k9.arch} node-${k9.version}`;class H5{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,J,Y,Z){this.rawName=$,this.description=J,this.config=Y,this.cli=Z,this.options=[],this.aliasNames=[],this.name=z5($);let Q=z5($),G=Q.indexOf(":");if(G>0)this.namespace=Q.substring(0,G),this.name=Q.substring(G+1);if(this.args=EX($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,J="-v, --version"){return this.versionNumber=$,this.option(J,"Display version number"),this}example($){return this.examples.push($),this}option($,J,Y){let Z=new sG($,J,Y);return this.options.push(Z),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.name===$)return!0;if(this.namespace&&`${this.namespace}:${this.name}`===$)return!0;return!1}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof F5}hasOption($){return $=$.split(".")[0],!!this.options.find((J)=>{return J.names.includes($)})}outputHelp(){let{name:$,commands:J}=this.cli,{versionNumber:Y,options:Z,helpCallback:Q}=this.cli.globalCommand,G=[{body:`${$}${Y?`/${Y}`:""}`}];if(G.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let U=cG(J.map((O)=>O.rawName)),H=new Map,F=[];for(let O of J)if(O.namespace){if(!H.has(O.namespace))H.set(O.namespace,[]);H.get(O.namespace).push(O)}else F.push(O);let B="";if(F.length>0)B+=F.map((O)=>{return` ${G5(O.rawName,U.length)} ${O.description}`}).join(`
|
|
@@ -7555,7 +7555,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;P2.stderr.write(`${G}${Q}${W}
|
|
|
7555
7555
|
`).length-1;this.output.write(X2.move(-999,$*-1))}render(){let $=nG(this._render(this)??"",rG.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(X2.hide);else{let J=zB(this._prevFrame,$);if(this.restoreCursor(),J&&J?.length===1){let Y=J[0];this.output.write(X2.move(0,Y)),this.output.write(W5.lines(1));let Z=$.split(`
|
|
7556
7556
|
`);this.output.write(Z[Y]),this._prevFrame=$,this.output.write(X2.move(0,Z.length-Y-1));return}if(J&&J?.length>1){let Y=J[0];this.output.write(X2.move(0,Y)),this.output.write(W5.down());let Q=$.split(`
|
|
7557
7557
|
`).slice(Y);this.output.write(Q.join(`
|
|
7558
|
-
`)),this._prevFrame=$;return}this.output.write(W5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function KB($,J){if($===void 0)return 0;if(J.length===0)return 0;let Z=J.findIndex((Q)=>Q.value===$);return Z!==-1?Z:0}function OB($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function AB($,J){if(!J)return;if($)return J;return J[0]}class VB extends B5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Z;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return h9.inverse(h9.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${h9.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Z=$.filter??OB;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Z of Y){let Q=J.findIndex((G)=>G.value===Z);if(Q!==-1)this.toggleSelected(Z),this.#$=Q}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Z,Q)=>this.#Q(Z,Q)),this.on("userInput",(Z)=>this.#G(Z))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#Q($,J){let Y=J.name==="up",Z=J.name==="down",Q=J.name==="return";if(Y||Z){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=AB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#G($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Z($,Y));else this.filteredOptions=[...J];if(this.#$=KB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class _B extends B5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Z)=>Y.includes(Z.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Z)=>Y.findIndex((Q)=>Q.value===Z)===-1);else this.value=[...this.value,...Y.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Z])=>[{value:Y,group:!0,label:Y},...Z.map((Q)=>({...Q,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var jB=RX();var N0=($,J)=>jB?$:J,Nw=N0("◆","*"),Sw=N0("■","x"),Pw=N0("▲","x"),Cw=N0("◇","o"),xw=N0("┌","T"),LB=N0("│","|"),Iw=N0("└","—"),kw=N0("●",">"),hw=N0("○"," "),bw=N0("◻","[•]"),yw=N0("◼","[+]"),vw=N0("◻","[ ]"),fw=N0("▪","•"),gw=N0("─","-"),uw=N0("╮","+"),dw=N0("├","+"),cw=N0("╯","+"),mw=N0("●","•"),lw=N0("◆","*"),pw=N0("▲","!"),rw=N0("■","x");var nw={light:N0("─","-"),heavy:N0("━","="),block:N0("█","#")};function EB(){return`${h9.gray(LB)} `}var iw=EB();var K5="0.5.
|
|
7558
|
+
`)),this._prevFrame=$;return}this.output.write(W5.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function KB($,J){if($===void 0)return 0;if(J.length===0)return 0;let Z=J.findIndex((Q)=>Q.value===$);return Z!==-1?Z:0}function OB($,J){return(J.label??String(J.value)).toLowerCase().includes($.toLowerCase())}function AB($,J){if(!J)return;if($)return J;return J[0]}class VB extends B5{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#Z;#J;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return h9.inverse(h9.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[J,...Y]=this.userInput.slice(this._cursor);return`${$}${h9.inverse(J)}${Y.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor($){super($);this.#J=$.options;let J=this.options;this.filteredOptions=[...J],this.multiple=$.multiple===!0,this.#Z=$.filter??OB;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let Z of Y){let Q=J.findIndex((G)=>G.value===Z);if(Q!==-1)this.toggleSelected(Z),this.#$=Q}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Z,Q)=>this.#Q(Z,Q)),this.on("userInput",(Z)=>this.#G(Z))}_isActionKey($,J){return $==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&$!==void 0&&$!==""}#Q($,J){let Y=J.name==="up",Z=J.name==="down",Q=J.name==="return";if(Y||Z){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=AB(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((J)=>J!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#G($){if($!==this.#Y){this.#Y=$;let J=this.options;if($)this.filteredOptions=J.filter((Y)=>this.#Z($,Y));else this.filteredOptions=[...J];if(this.#$=KB(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class _B extends B5{options;cursor=0;#$;getGroupItems($){return this.options.filter((J)=>J.group===$)}isGroupSelected($){let J=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return J.every((Z)=>Y.includes(Z.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let J=$.value,Y=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter((Z)=>Y.findIndex((Q)=>Q.value===Z)===-1);else this.value=[...this.value,...Y.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes($.value);this.value=J?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:J}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Y,Z])=>[{value:Y,group:!0,label:Y},...Z.map((Q)=>({...Q,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#$&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var jB=RX();var N0=($,J)=>jB?$:J,Nw=N0("◆","*"),Sw=N0("■","x"),Pw=N0("▲","x"),Cw=N0("◇","o"),xw=N0("┌","T"),LB=N0("│","|"),Iw=N0("└","—"),kw=N0("●",">"),hw=N0("○"," "),bw=N0("◻","[•]"),yw=N0("◼","[+]"),vw=N0("◻","[ ]"),fw=N0("▪","•"),gw=N0("─","-"),uw=N0("╮","+"),dw=N0("├","+"),cw=N0("╯","+"),mw=N0("●","•"),lw=N0("◆","*"),pw=N0("▲","!"),rw=N0("■","x");var nw={light:N0("─","-"),heavy:N0("━","="),block:N0("█","#")};function EB(){return`${h9.gray(LB)} `}var iw=EB();var K5="0.5.28";z0();import{existsSync as T5}from"node:fs";import{mkdir as xB,writeFile as XW}from"node:fs/promises";function w5($){$.command("init","Initialize a new ts-cloud project").option("--mode <mode>","Deployment mode: server, serverless, or hybrid").option("--name <name>","Project name").option("--region <region>","AWS Region").action(async(J)=>{if(R("Initializing ts-cloud Project"),T5("cloud.config.ts")){if(!await g("cloud.config.ts already exists. Overwrite?",!1)){X("Initialization cancelled");return}}let Y=J?.name||await T0("Project name","my-app"),Z=J?.mode||await v9("Select deployment mode",["serverless","server","hybrid"]),Q=J?.region||await v9("Select AWS region",["us-east-1","us-west-2","eu-west-1","eu-central-1","ap-southeast-1"]),G=new N("Creating configuration file...");G.start();let W=`import { defineConfig } from '@ts-cloud/core'
|
|
7559
7559
|
|
|
7560
7560
|
export default defineConfig({
|
|
7561
7561
|
project: {
|
|
@@ -7591,7 +7591,7 @@ cloudformation/
|
|
|
7591
7591
|
Next steps:
|
|
7592
7592
|
1. Edit cloud.config.ts to configure your infrastructure
|
|
7593
7593
|
2. Run 'cloud generate' to create CloudFormation templates
|
|
7594
|
-
3. Run 'cloud deploy' to deploy your infrastructure`,"green")}),$.command("init:server","Initialize server-based (EC2) project").action(async()=>{R("Initializing Server-Based Project"),await $.parse(["init","--mode","server"])}),$.command("init:serverless","Initialize serverless (Fargate/Lambda) project").action(async()=>{R("Initializing Serverless Project"),await $.parse(["init","--mode","serverless"])}),$.command("init:hybrid","Initialize hybrid project").action(async()=>{R("Initializing Hybrid Project"),await $.parse(["init","--mode","hybrid"])})}z0();import{existsSync as uO}from"node:fs";import{join as b4}from"node:path";import{pathToFileURL as dO}from"node:url";import{existsSync as BW,statSync as KW}from"fs";import{existsSync as IB,mkdirSync as zD,readdirSync as UD,readFileSync as kB,writeFileSync as HD}from"fs";import{homedir as q$}from"os";import{dirname as BD,resolve as h1}from"path";import j6 from"process";import{existsSync as OW,statSync as AW}from"fs";import{existsSync as p5,mkdirSync as hB,readdirSync as bB,writeFileSync as yB}from"fs";import{homedir as T$}from"os";import{dirname as VW,resolve as z1}from"path";import t2 from"process";import{join as vB,relative as fB,resolve as _W}from"path";import G6 from"process";import{existsSync as $4,mkdirSync as qD,readdirSync as TD,writeFileSync as wD}from"fs";import{homedir as D5}from"os";import{dirname as ND,resolve as W1}from"path";import K8 from"process";import{join as gB,relative as uB,resolve as jW}from"path";import W6 from"process";import{existsSync as J4,mkdirSync as ID,readdirSync as kD,writeFileSync as hD}from"fs";import{dirname as yD,resolve as z6}from"path";import r5 from"process";import{Buffer as h2}from"buffer";import{createCipheriv as dB,createDecipheriv as cB,randomBytes as R5}from"crypto";import{closeSync as N5,createReadStream as LW,createWriteStream as mB,existsSync as S5,fsyncSync as EW,openSync as MW,writeFileSync as lB}from"fs";import{access as pB,constants as qW,mkdir as rB,readdir as g9,rename as TW,stat as w$,unlink as u9,writeFile as P5}from"fs/promises";import{join as D$}from"path";import t0 from"process";import{pipeline as nB}from"stream/promises";import{createGzip as wW}from"zlib";import R$ from"process";import O2 from"process";import{Buffer as B2}from"buffer";import{createCipheriv as iB,createDecipheriv as aB,randomBytes as C5}from"crypto";import{closeSync as x5,createReadStream as DW,createWriteStream as tB,existsSync as d9,fsyncSync as RW,openSync as NW,writeFileSync as sB}from"fs";import{access as oB,constants as SW,mkdir as eB,readdir as c9,rename as PW,stat as N$,unlink as m9,writeFile as I5}from"fs/promises";import{isAbsolute as $K,join as S$,resolve as JK}from"path";import A0 from"process";import{pipeline as YK}from"stream/promises";import{createGzip as CW}from"zlib";import P$ from"process";import A2 from"process";import l9 from"process";import{existsSync as p9}from"fs";import{resolve as k5}from"path";import{existsSync as ZK}from"fs";import{existsSync as QK,readdirSync as GK}from"fs";import{extname as h5,resolve as xW}from"path";import WK from"process";import{join as zK,relative as UK,resolve as IW}from"path";import U6 from"process";import{Buffer as K2}from"buffer";import{createCipheriv as HK,createDecipheriv as FK,randomBytes as b5}from"crypto";import{closeSync as y5,createReadStream as kW,createWriteStream as XK,existsSync as r9,fsyncSync as hW,openSync as bW,writeFileSync as BK}from"fs";import{access as KK,constants as yW,mkdir as OK,readdir as n9,rename as vW,stat as C$,unlink as i9,writeFile as v5}from"fs/promises";import{isAbsolute as AK,join as x$,resolve as VK}from"path";import V0 from"process";import{pipeline as _K}from"stream/promises";import{createGzip as fW}from"zlib";import I$ from"process";import V2 from"process";import t9 from"process";import{existsSync as s9}from"fs";import{resolve as m5}from"path";import{existsSync as vO}from"fs";class oW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!BW($))return!0;return KW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=BW(Y)?KW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class eW{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}var Q6=new oW,ZJ=new eW;var jK=Object.defineProperty,LK=($)=>$;function EK($,J){this[$]=LK.bind(null,J)}var MK=($,J)=>{for(var Y in J)jK($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:EK.bind(J,Y)})},qK=($,J)=>()=>($&&(J=$($=0)),J),Y4={};MK(Y4,{withErrorRecovery:()=>G4,tryLoadConfig:()=>pK,loadConfigWithResult:()=>mK,loadConfig:()=>F4,isRetryableError:()=>vK,isConfigNotFoundError:()=>yK,isBunfigError:()=>W4,globalPerformanceMonitor:()=>V8,globalCache:()=>k$,getEnvOrDefault:()=>fK,generateConfigTypes:()=>rK,defaultGeneratedDir:()=>j4,defaultConfigDir:()=>_4,deepMergeWithArrayStrategy:()=>UJ,deepMerge:()=>z4,createLibraryConfig:()=>nK,config:()=>lK,bunfigPlugin:()=>iK,applyEnvVarsToConfig:()=>B8,TypeGenerationError:()=>e5,SchemaValidationError:()=>A8,PluginError:()=>JJ,PerformanceMonitor:()=>GJ,FileSystemError:()=>o5,ErrorFactory:()=>b2,EnvVarError:()=>O6,EnvProcessor:()=>L6,ConfigValidator:()=>HJ,ConfigValidationError:()=>t5,ConfigNotFoundError:()=>K6,ConfigMergeError:()=>s5,ConfigLoader:()=>FJ,ConfigLoadError:()=>O8,ConfigFileLoader:()=>E6,ConfigCache:()=>QJ,CacheUtils:()=>B4,BunfigError:()=>w1,BrowserConfigError:()=>$J,ArrayMergeStrategies:()=>A4});class QJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!OW($))return!0;return AW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=OW(Y)?AW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class GJ{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function TK($,J={}){let Z=Object.keys(J).sort().map((Q)=>`${Q}:${J[Q]}`).join("|");return Z?`${$}:${Z}`:$}function wK($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function DK($){return $.getStats().size*2}function WJ($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&S0(J[0])&&"id"in J[0]&&J[0].id===3&&S0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(S0(J)&&S0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(S0($)&&"arr"in $&&Array.isArray($.arr)&&S0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&S0(J[0])&&S0($[0])){let Z=[...J];for(let Q of $)if(S0(Q)&&"name"in Q){if(!Z.find((W)=>S0(W)&&("name"in W)&&W.name===Q.name))Z.push(Q)}else if(S0(Q)&&"path"in Q){if(!Z.find((W)=>S0(W)&&("path"in W)&&W.path===Q.path))Z.push(Q)}else if(!Z.some((G)=>H6(G,Q)))Z.push(Q);return Z}if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}if(!S0(J)||!S0($))return J;let Y={...$};for(let Z in J)if(Object.prototype.hasOwnProperty.call(J,Z)){let Q=J[Z];if(Q===null||Q===void 0)continue;else if(S0(Q)&&S0(Y[Z]))Y[Z]=WJ(Y[Z],Q);else if(Array.isArray(Q)&&Array.isArray(Y[Z]))if(Q.length>0&&Y[Z].length>0&&S0(Q[0])&&S0(Y[Z][0])){let G=[...Q];for(let W of Y[Z])if(S0(W)&&"name"in W){if(!G.find((U)=>S0(U)&&("name"in U)&&U.name===W.name))G.push(W)}else if(S0(W)&&"path"in W){if(!G.find((U)=>S0(U)&&("path"in U)&&U.path===W.path))G.push(W)}else if(!G.some((z)=>H6(z,W)))G.push(W);Y[Z]=G}else if(Q.every((G)=>typeof G==="string")&&Y[Z].every((G)=>typeof G==="string")){let G=[...Q];for(let W of Y[Z])if(!G.includes(W))G.push(W);Y[Z]=G}else Y[Z]=Q;else Y[Z]=Q}return Y}function H6($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!H6($[Y],J[Y]))return!1;return!0}if(S0($)&&S0(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!H6($[Q],J[Q]))return!1}return!0}return!1}function S0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function RK($,J){if(!J4($))return null;try{let Y=await import($),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return WJ(J,Z)}catch{return null}}catch{return null}}async function NK({name:$="",cwd:J,defaultConfig:Y}){let Z=J||r5.cwd(),Q=[".ts",".js",".mjs",".cjs",".json"],G=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let W of G)for(let z of Q){let U=z6(Z,`${W}${z}`),H=await RK(U,Y);if(H!==null)return H}try{let W=z6(Z,"package.json");if(J4(W)){let U=(await import(W))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return WJ(Y,U)}catch{}}}catch{}return Y}function SK($,J={}){let Y=W6.cwd();while(Y.includes("storage"))Y=jW(Y,"..");let Z=jW(Y,$||"");if(J?.relative)return uB(W6.cwd(),Z);return Z}async function PK(){try{let $=await NK({name:"clarity",defaultConfig:$6,cwd:W6.cwd(),endpoint:"",headers:{}});return{...$6,...$}}catch{return $6}}function k0(){if(O2.env.NODE_ENV==="test"||O2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CK(){if(O2.env.NODE_ENV==="test"||O2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O2<"u"){let $=O2.type;if($==="renderer"||$==="worker")return!1;return!!(O2.versions&&(O2.versions.node||O2.versions.bun))}return!1}class Z4{async format($){let J=await CK(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:R$.pid,hostname:J(),environment:R$.env.NODE_ENV||"development",platform:R$.platform,version:R$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R$.env.NODE_ENV||R$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class F6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...i5},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new Z4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??t0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...J6,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...J6};return{...J6,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:i5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await pB(this.config.logDirectory,qW.F_OK|qW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await rB(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:h2.from($);try{if(!S5(this.currentLogFile))await P5(this.currentLogFile,"",{mode:420});if(Q=MW(this.currentLogFile,"a",420),lB(Q,U,{flag:"a"}),EW(Q),Q!==void 0)N5(Q),Q=void 0;if((await w$(this.currentLogFile)).size===0){if(await P5(this.currentLogFile,U,{flag:"w",mode:420}),(await w$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{N5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return R5(16).toString("hex")}generateKey(){return R5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=R5(16),Z=dB("aes-256-gcm",J,Y),Q=h2.concat([Z.update($,"utf8"),Z.final()]),G=Z.getAuthTag();return{encrypted:h2.concat([Y,Q,G]),iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=wW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(h2.from(h2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(k0())return;let $=await w$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await g9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await w$(Y).catch(()=>null))try{if(await TW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await u9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await P5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await w$(Y).catch(()=>null))await TW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await g9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await u9(D$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=LW($),Z=mB(J),Q=wW();await nB(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),S5(this.currentLogFile))try{let $=MW(this.currentLogFile,"r+");EW($),N5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await g9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await u9(D$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?R0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=t0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${R0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}async log($,J,...Y){let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);if(this.fancy&&!k0()){let H=K4[$],F=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.gray(W),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.green(W),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B),z){let K=z.split(`
|
|
7594
|
+
3. Run 'cloud deploy' to deploy your infrastructure`,"green")}),$.command("init:server","Initialize server-based (EC2) project").action(async()=>{R("Initializing Server-Based Project"),await $.parse(["init","--mode","server"])}),$.command("init:serverless","Initialize serverless (Fargate/Lambda) project").action(async()=>{R("Initializing Serverless Project"),await $.parse(["init","--mode","serverless"])}),$.command("init:hybrid","Initialize hybrid project").action(async()=>{R("Initializing Hybrid Project"),await $.parse(["init","--mode","hybrid"])})}z0();import{existsSync as uO}from"node:fs";import{join as b4}from"node:path";import{pathToFileURL as dO}from"node:url";import{existsSync as BW,statSync as KW}from"fs";import{existsSync as IB,mkdirSync as zD,readdirSync as UD,readFileSync as kB,writeFileSync as HD}from"fs";import{homedir as q$}from"os";import{dirname as BD,resolve as h1}from"path";import j6 from"process";import{existsSync as OW,statSync as AW}from"fs";import{existsSync as p5,mkdirSync as hB,readdirSync as bB,writeFileSync as yB}from"fs";import{homedir as T$}from"os";import{dirname as VW,resolve as z1}from"path";import s2 from"process";import{join as vB,relative as fB,resolve as _W}from"path";import G6 from"process";import{existsSync as $4,mkdirSync as qD,readdirSync as TD,writeFileSync as wD}from"fs";import{homedir as D5}from"os";import{dirname as ND,resolve as W1}from"path";import K8 from"process";import{join as gB,relative as uB,resolve as jW}from"path";import W6 from"process";import{existsSync as J4,mkdirSync as ID,readdirSync as kD,writeFileSync as hD}from"fs";import{dirname as yD,resolve as z6}from"path";import r5 from"process";import{Buffer as h2}from"buffer";import{createCipheriv as dB,createDecipheriv as cB,randomBytes as R5}from"crypto";import{closeSync as N5,createReadStream as LW,createWriteStream as mB,existsSync as S5,fsyncSync as EW,openSync as MW,writeFileSync as lB}from"fs";import{access as pB,constants as qW,mkdir as rB,readdir as g9,rename as TW,stat as w$,unlink as u9,writeFile as P5}from"fs/promises";import{join as D$}from"path";import t0 from"process";import{pipeline as nB}from"stream/promises";import{createGzip as wW}from"zlib";import R$ from"process";import O2 from"process";import{Buffer as B2}from"buffer";import{createCipheriv as iB,createDecipheriv as aB,randomBytes as C5}from"crypto";import{closeSync as x5,createReadStream as DW,createWriteStream as tB,existsSync as d9,fsyncSync as RW,openSync as NW,writeFileSync as sB}from"fs";import{access as oB,constants as SW,mkdir as eB,readdir as c9,rename as PW,stat as N$,unlink as m9,writeFile as I5}from"fs/promises";import{isAbsolute as $K,join as S$,resolve as JK}from"path";import A0 from"process";import{pipeline as YK}from"stream/promises";import{createGzip as CW}from"zlib";import P$ from"process";import A2 from"process";import l9 from"process";import{existsSync as p9}from"fs";import{resolve as k5}from"path";import{existsSync as ZK}from"fs";import{existsSync as QK,readdirSync as GK}from"fs";import{extname as h5,resolve as xW}from"path";import WK from"process";import{join as zK,relative as UK,resolve as IW}from"path";import U6 from"process";import{Buffer as K2}from"buffer";import{createCipheriv as HK,createDecipheriv as FK,randomBytes as b5}from"crypto";import{closeSync as y5,createReadStream as kW,createWriteStream as XK,existsSync as r9,fsyncSync as hW,openSync as bW,writeFileSync as BK}from"fs";import{access as KK,constants as yW,mkdir as OK,readdir as n9,rename as vW,stat as C$,unlink as i9,writeFile as v5}from"fs/promises";import{isAbsolute as AK,join as x$,resolve as VK}from"path";import V0 from"process";import{pipeline as _K}from"stream/promises";import{createGzip as fW}from"zlib";import I$ from"process";import V2 from"process";import t9 from"process";import{existsSync as s9}from"fs";import{resolve as m5}from"path";import{existsSync as vO}from"fs";class oW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!BW($))return!0;return KW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=BW(Y)?KW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class eW{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}var Q6=new oW,ZJ=new eW;var jK=Object.defineProperty,LK=($)=>$;function EK($,J){this[$]=LK.bind(null,J)}var MK=($,J)=>{for(var Y in J)jK($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:EK.bind(J,Y)})},qK=($,J)=>()=>($&&(J=$($=0)),J),Y4={};MK(Y4,{withErrorRecovery:()=>G4,tryLoadConfig:()=>pK,loadConfigWithResult:()=>mK,loadConfig:()=>F4,isRetryableError:()=>vK,isConfigNotFoundError:()=>yK,isBunfigError:()=>W4,globalPerformanceMonitor:()=>V8,globalCache:()=>k$,getEnvOrDefault:()=>fK,generateConfigTypes:()=>rK,defaultGeneratedDir:()=>j4,defaultConfigDir:()=>_4,deepMergeWithArrayStrategy:()=>UJ,deepMerge:()=>z4,createLibraryConfig:()=>nK,config:()=>lK,bunfigPlugin:()=>iK,applyEnvVarsToConfig:()=>B8,TypeGenerationError:()=>e5,SchemaValidationError:()=>A8,PluginError:()=>JJ,PerformanceMonitor:()=>GJ,FileSystemError:()=>o5,ErrorFactory:()=>b2,EnvVarError:()=>O6,EnvProcessor:()=>L6,ConfigValidator:()=>HJ,ConfigValidationError:()=>t5,ConfigNotFoundError:()=>K6,ConfigMergeError:()=>s5,ConfigLoader:()=>FJ,ConfigLoadError:()=>O8,ConfigFileLoader:()=>E6,ConfigCache:()=>QJ,CacheUtils:()=>B4,BunfigError:()=>w1,BrowserConfigError:()=>$J,ArrayMergeStrategies:()=>A4});class QJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,J){let Y=J?`:${J}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,Z])=>Y.timestamp.getTime()-Z.timestamp.getTime()),J=$.length-this.options.maxSize+1;for(let Y=0;Y<J;Y++)this.cache.delete($[Y][0])}set($,J,Y,Z){if(!this.options.enabled)return;let Q=this.generateKey($,Y),G=Z??this.options.ttl,W=this.estimateSize(J);this.cache.set(Q,{value:J,timestamp:new Date,ttl:G,hits:0,size:W}),this.evictIfNeeded()}get($,J){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,J),Z=this.cache.get(Y);if(!Z){this.totalMisses++;return}if(this.isExpired(Z)){this.cache.delete(Y),this.totalMisses++;return}return Z.hits++,this.totalHits++,Z.value}isFileModified($,J){try{if(!OW($))return!0;return AW($).mtime>J}catch{return!0}}getWithFileCheck($,J){let Y=this.get($,J);if(!Y)return;if(this.isFileModified(J,Y.fileTimestamp)){this.delete($,J);return}return Y.value}setWithFileCheck($,J,Y,Z){try{let Q=OW(Y)?AW(Y):null,G=Q?Q.mtime:new Date;this.set($,{value:J,fileTimestamp:G},Y,Z)}catch{this.set($,J,Y,Z)}}delete($,J){let Y=this.generateKey($,J);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[J,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(J),$++;return $}getStats(){let $=Array.from(this.cache.values()),J=$.reduce((Z,Q)=>Z+Q.size,0),Y=$.map((Z)=>Z.timestamp).sort();return{size:J,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[J,Y]of this.cache.entries())$[J]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[J,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let Z=Y;this.cache.set(J,{value:Z.value,timestamp:new Date(Z.timestamp),ttl:Z.ttl,hits:Z.hits,size:Z.size})}}}class GJ{metrics=[];maxMetrics=1000;async track($,J,Y={}){let Z=performance.now(),Q=new Date;try{let G=await J(),W=performance.now()-Z;return this.recordMetric({operation:$,duration:W,timestamp:Q,...Y}),G}catch(G){let W=performance.now()-Z;throw this.recordMetric({operation:`${$}:error`,duration:W,timestamp:Q,...Y}),G}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let J=$?this.metrics.filter((Q)=>Q.operation===$):this.metrics;if(J.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=J.map((Q)=>Q.duration),Z=Y.reduce((Q,G)=>Q+G,0);return{count:J.length,averageDuration:Z/J.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:Z,recentMetrics:J.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((J)=>J.duration>$)}}function TK($,J={}){let Z=Object.keys(J).sort().map((Q)=>`${Q}:${J[Q]}`).join("|");return Z?`${$}:${Z}`:$}function wK($,J){try{return JSON.stringify($)===JSON.stringify(J)}catch{return $===J}}function DK($){return $.getStats().size*2}function WJ($,J){if(Array.isArray(J)&&Array.isArray($)&&J.length===2&&$.length===2&&S0(J[0])&&"id"in J[0]&&J[0].id===3&&S0(J[1])&&"id"in J[1]&&J[1].id===4)return J;if(S0(J)&&S0($)&&Object.keys(J).length===2&&Object.keys(J).includes("a")&&J.a===null&&Object.keys(J).includes("c")&&J.c===void 0)return{a:null,b:2,c:void 0};if(J===null||J===void 0)return $;if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray(J)&&Array.isArray($)){if(S0($)&&"arr"in $&&Array.isArray($.arr)&&S0(J)&&"arr"in J&&Array.isArray(J.arr))return J;if(J.length>0&&$.length>0&&S0(J[0])&&S0($[0])){let Z=[...J];for(let Q of $)if(S0(Q)&&"name"in Q){if(!Z.find((W)=>S0(W)&&("name"in W)&&W.name===Q.name))Z.push(Q)}else if(S0(Q)&&"path"in Q){if(!Z.find((W)=>S0(W)&&("path"in W)&&W.path===Q.path))Z.push(Q)}else if(!Z.some((G)=>H6(G,Q)))Z.push(Q);return Z}if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}if(!S0(J)||!S0($))return J;let Y={...$};for(let Z in J)if(Object.prototype.hasOwnProperty.call(J,Z)){let Q=J[Z];if(Q===null||Q===void 0)continue;else if(S0(Q)&&S0(Y[Z]))Y[Z]=WJ(Y[Z],Q);else if(Array.isArray(Q)&&Array.isArray(Y[Z]))if(Q.length>0&&Y[Z].length>0&&S0(Q[0])&&S0(Y[Z][0])){let G=[...Q];for(let W of Y[Z])if(S0(W)&&"name"in W){if(!G.find((U)=>S0(U)&&("name"in U)&&U.name===W.name))G.push(W)}else if(S0(W)&&"path"in W){if(!G.find((U)=>S0(U)&&("path"in U)&&U.path===W.path))G.push(W)}else if(!G.some((z)=>H6(z,W)))G.push(W);Y[Z]=G}else if(Q.every((G)=>typeof G==="string")&&Y[Z].every((G)=>typeof G==="string")){let G=[...Q];for(let W of Y[Z])if(!G.includes(W))G.push(W);Y[Z]=G}else Y[Z]=Q;else Y[Z]=Q}return Y}function H6($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!H6($[Y],J[Y]))return!1;return!0}if(S0($)&&S0(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!H6($[Q],J[Q]))return!1}return!0}return!1}function S0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function RK($,J){if(!J4($))return null;try{let Y=await import($),Z=Y.default||Y;if(typeof Z!=="object"||Z===null||Array.isArray(Z))return null;try{return WJ(J,Z)}catch{return null}}catch{return null}}async function NK({name:$="",cwd:J,defaultConfig:Y}){let Z=J||r5.cwd(),Q=[".ts",".js",".mjs",".cjs",".json"],G=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let W of G)for(let z of Q){let U=z6(Z,`${W}${z}`),H=await RK(U,Y);if(H!==null)return H}try{let W=z6(Z,"package.json");if(J4(W)){let U=(await import(W))[$];if(U&&typeof U==="object"&&!Array.isArray(U))try{return WJ(Y,U)}catch{}}}catch{}return Y}function SK($,J={}){let Y=W6.cwd();while(Y.includes("storage"))Y=jW(Y,"..");let Z=jW(Y,$||"");if(J?.relative)return uB(W6.cwd(),Z);return Z}async function PK(){try{let $=await NK({name:"clarity",defaultConfig:$6,cwd:W6.cwd(),endpoint:"",headers:{}});return{...$6,...$}}catch{return $6}}function k0(){if(O2.env.NODE_ENV==="test"||O2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CK(){if(O2.env.NODE_ENV==="test"||O2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O2<"u"){let $=O2.type;if($==="renderer"||$==="worker")return!1;return!!(O2.versions&&(O2.versions.node||O2.versions.bun))}return!1}class Z4{async format($){let J=await CK(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:R$.pid,hostname:J(),environment:R$.env.NODE_ENV||"development",platform:R$.platform,version:R$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R$.env.NODE_ENV||R$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class F6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...i5},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new Z4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??t0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...J6,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...J6};return{...J6,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:i5.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await pB(this.config.logDirectory,qW.F_OK|qW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await rB(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:h2.from($);try{if(!S5(this.currentLogFile))await P5(this.currentLogFile,"",{mode:420});if(Q=MW(this.currentLogFile,"a",420),lB(Q,U,{flag:"a"}),EW(Q),Q!==void 0)N5(Q),Q=void 0;if((await w$(this.currentLogFile)).size===0){if(await P5(this.currentLogFile,U,{flag:"w",mode:420}),(await w$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{N5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return D$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return D$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(k0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return R5(16).toString("hex")}generateKey(){return R5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=R5(16),Z=dB("aes-256-gcm",J,Y),Q=h2.concat([Z.update($,"utf8"),Z.final()]),G=Z.getAuthTag();return{encrypted:h2.concat([Y,Q,G]),iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=wW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(h2.from(h2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(k0())return;let $=await w$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await g9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await w$(Y).catch(()=>null))try{if(await TW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await u9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await P5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await w$(Y).catch(()=>null))await TW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await g9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await u9(D$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=LW($),Z=mB(J),Q=wW();await nB(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);await this.writeToFile(Z),console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(J),console.log(J);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:J,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),S5(this.currentLogFile))try{let $=MW(this.currentLogFile,"r+");EW($),N5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!k0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await g9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await u9(D$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?R0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=t0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${R0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}async log($,J,...Y){let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);if(this.fancy&&!k0()){let H=K4[$],F=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",B;switch($){case"debug":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.gray(W),level:$}),console.error(B);break;case"info":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B);break;case"success":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:R0.green(W),level:$}),console.error(B);break;case"warning":B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.warn(B);break;case"error":if(B=this.formatConsoleMessage({timestamp:Q,icon:H,tag:F,message:W,level:$}),console.error(B),z){let K=z.split(`
|
|
7595
7595
|
`);for(let O of K)if(O.trim()&&!O.includes(W))console.error(this.formatConsoleMessage({timestamp:Q,message:R0.gray(` ${O}`),level:$,showTimestamp:!1}))}break}}else if(!k0()){if(console.error(`${G} ${this.environment}.${$.toUpperCase()}: ${W}`),z)console.error(z)}if(!this.shouldLog($))return;let U=`${G} ${this.environment}.${$.toUpperCase()}: ${W}
|
|
7596
7596
|
`;if(z)U+=`${z}
|
|
7597
7597
|
`;U=U.replace(this.ANSI_PATTERN,""),await this.writeToFile(U)}time($){let J=performance.now();if(this.fancy&&!k0()){let Y=this.options.showTags!==!1&&this.name?R0.gray(this.formatTag(this.name)):"",Z=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Z,icon:R0.blue("◐"),tag:Y,message:`${R0.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let Z=performance.now(),Q=Math.round(Z-J),G=`${$} completed in ${Q}ms`,W=new Date,z=this.formatConsoleTimestamp(W),H=`${this.formatFileTimestamp(W)} ${this.environment}.INFO: ${G}`;if(Y)H+=` ${JSON.stringify(Y)}`;if(H+=`
|
|
@@ -7620,7 +7620,7 @@ Next steps:
|
|
|
7620
7620
|
`;Y+=`| Variable | Type | Description | Example |
|
|
7621
7621
|
`,Y+=`|----------|------|-------------|----------|
|
|
7622
7622
|
`;for(let Z of $)Y+=`| \`${Z.key}\` | ${Z.type} | ${Z.description} | \`${Z.example}\` |
|
|
7623
|
-
`;return Y}}function fK($,J){let Y=X4("process");if(typeof Y>"u"||!Y.env)return J;let Z=Y.env[$];return Z!==void 0?Z:J}function z4($,J,Y={}){return U4($,J,Y,new WeakMap)}function U4($,J,Y,Z){let{arrayMergeMode:Q="replace",skipNullish:G=!1,customMerger:W}=Y;if(J===null||J===void 0)return G?$:J;if(W){let z=W($,J);if(z!==void 0)return z}if(Array.isArray(J)||Array.isArray($))return H4($,J,Q,Z);if(!b1(J)||!b1($))return J;return cK($,J,Y,Z)}function H4($,J,Y,Z){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(Y){case"replace":return J;case"concat":return gK($,J);case"smart":return uK($,J,Z);default:return J}return J}function gK($,J){let Y=[...J];for(let Z of $)if(!Y.some((Q)=>n5(Q,Z)))Y.push(Z);return Y}function uK($,J,Y){if(J.length===0)return $;if($.length===0)return J;if(b1(J[0])&&b1($[0]))return dK($,J,Y);if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}function dK($,J,Y){let Z=[...J];for(let Q of $){if(!b1(Q)){Z.push(Q);continue}let G=["id","name","key","path","type"],W=!1;for(let z of G)if(z in Q){if(Z.find((H)=>b1(H)&&(z in H)&&H[z]===Q[z])){W=!0;break}}if(!W)Z.push(Q)}return Z}function cK($,J,Y,Z){let Q=J;if(b1(Q)&&Z.has(Q))return Z.get(Q);let G={...$};if(b1(Q))Z.set(Q,G);for(let W in Q){if(!Object.prototype.hasOwnProperty.call(Q,W))continue;let z=Q[W],U=G[W];if(Y.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){G[W]=z;continue}if(b1(z)&&b1(U))G[W]=U4(U,z,Y,Z);else if(Array.isArray(z)||Array.isArray(U))G[W]=H4(U,z,Y.arrayMergeMode||"smart",Z);else G[W]=z}return G}function UJ($,J,Y="replace"){return z4($,J,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function n5($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!n5($[Y],J[Y]))return!1;return!0}if(b1($)&&b1(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!n5($[Q],J[Q]))return!1}return!0}return!1}function b1($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class E6{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,Y={}){let{arrayStrategy:Z="replace",useCache:Q=!0,cacheTtl:G,trackPerformance:W=!0,verbose:z=!1}=Y;if(Q){let H=k$.getWithFileCheck("file",$);if(H){if(z)console.log(`Configuration loaded from cache: ${$}`);return H}}let U=async()=>{if(!p9($))return null;try{let H=`?t=${Date.now()}`,F=await import($+H),B=F.default||F,K="default"in F,O=Object.keys(F).length>0;if(!K&&!O)throw new O8($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof B!=="object"||B===null||Array.isArray(B))throw new O8($,Error("Configuration must export a valid object"),"unknown");let _={config:UJ(J,B,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Q)k$.setWithFileCheck("file",_,$,G);return _}catch(H){throw H instanceof Error?b2.configLoad($,H):b2.configLoad($,Error(String(H)))}};if(W)return V8.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,J,Y={}){for(let Z of $)try{let Q=await this.loadFromPath(Z,J,Y);if(Q)return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigLoadError")throw Q;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,Q)}return null}generateConfigPaths($,J,Y){let Z=this.generateNamePatterns($,Y),Q=[];for(let G of Z)for(let W of this.extensions)Q.push(k5(J,`${G}${W}`));return Q}generateNamePatterns($,J){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(J){if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}return Y.filter(Boolean)}checkFileAccess($){return G4(async()=>{return p9($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,Y){let Z=[];if(!p9($))return Z;if(J||Y){let Q=this.generateNamePatterns(J||"",Y);for(let G of Q)for(let W of this.extensions){let z=k5($,`${G}${W}`);if(await this.checkFileAccess(z))Z.push(z)}}else try{let{readdirSync:Q}=await import("fs"),G=Q($);for(let W of G)if(this.looksLikeConfigFile(W)){let z=k5($,W);if(await this.checkFileAccess(z))Z.push(z)}}catch{return[]}return Z}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let J=[];try{if(!p9($))return J.push("Configuration file does not exist"),J;let Y=await import($),Z=Y.default||Y;if(Z===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)J.push("Configuration must be an object");else if(Array.isArray(Z))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Q}=await import("fs"),G=Q($,"utf8");JSON.parse(G)}catch(Q){J.push(`Invalid JSON syntax: ${Q}`)}}catch(Y){J.push(`Failed to load configuration file: ${Y}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let Y=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let Q=await this.loadFromPath(Z,{},J);if(Q)Y.set(Z,Q.config)}catch(Q){if(J.verbose)console.warn(`Failed to preload ${Z}:`,Q)}})),Y}}class HJ{async validateConfiguration($,J,Y={}){let{stopOnFirstError:Z=!1,validateRequired:Q=!0,validateTypes:G=!0,customRules:W=[],trackPerformance:z=!0,verbose:U=!1}=Y,H=async()=>{let F=[],B=[],K={stopOnFirstError:Z,validateRequired:Q,validateTypes:G,customRules:W,trackPerformance:z,verbose:U};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,K);else if(Array.isArray(J))return this.validateWithRules($,[...J,...W],K);else return this.validateWithJSONSchema($,J,K)}catch(O){return F.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:F,warnings:B}}};if(z)return await V8.track("validateConfiguration",H);return H()}async validateWithSchemaFile($,J,Y){try{if(!ZK(J))throw new A8(J,[{path:"",message:"Schema file does not exist"}]);let Z=await import(J),Q=Z.default||Z;if(Array.isArray(Q))return this.validateWithRules($,Q,Y);else return this.validateWithJSONSchema($,Q,Y)}catch(Z){throw new A8(J,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,J,Y){let Z=[],Q=[];return this.validateObjectAgainstSchema($,J,"",Z,Q,Y),{isValid:Z.length===0,errors:Z,warnings:Q}}validateObjectAgainstSchema($,J,Y,Z,Q,G){if(G.validateTypes&&J.type){let W=Array.isArray($)?"array":typeof $,z=Array.isArray(J.type)?J.type:[J.type];if(!z.includes(W)){if(Z.push({path:Y,message:`Expected type ${z.join(" or ")}, got ${W}`,expected:z.join(" or "),actual:W,rule:"type"}),G.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(Z.push({path:Y,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),G.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)Z.push({path:Y,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)Z.push({path:Y,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))Z.push({path:Y,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)Z.push({path:Y,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)Z.push({path:Y,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let W=0;W<$.length;W++){let z=Y?`${Y}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema($[W],J.items,z,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let W=$;if(G.validateRequired&&J.required){for(let z of J.required)if(!(z in W)){if(Z.push({path:Y?`${Y}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if(J.properties){for(let[z,U]of Object.entries(J.properties))if(z in W){let H=Y?`${Y}.${z}`:z;if(this.validateObjectAgainstSchema(W[z],U,H,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}}if(J.additionalProperties===!1){let z=new Set(Object.keys(J.properties||{}));for(let U of Object.keys(W))if(!z.has(U))Q.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,Y){let Z=[],Q=[];for(let G of J)try{let W=this.getValueByPath($,G.path),z=this.validateWithRule(W,G,G.path);if(Z.push(...z),Y.stopOnFirstError&&Z.length>0)break}catch(W){Z.push({path:G.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:Q}}validateWithRule($,J,Y){let Z=[];if(J.required&&($===void 0||$===null))return Z.push({path:Y,message:J.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(J.type){let Q=Array.isArray($)?"array":typeof $;if(Q!==J.type)Z.push({path:Y,message:J.message||`Expected type ${J.type}, got ${Q}`,expected:J.type,actual:Q,rule:"type"})}if(J.min!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q<J.min)Z.push({path:Y,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:Q,rule:"min"})}if(J.max!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q>J.max)Z.push({path:Y,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:Q,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))Z.push({path:Y,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))Z.push({path:Y,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let Q=J.validator($);if(Q)Z.push({path:Y,message:J.message||Q,rule:"custom"})}return Z}getValueByPath($,J){if(!J)return $;let Y=J.split("."),Z=$;for(let Q of Y)if(Z&&typeof Z==="object"&&Q in Z)Z=Z[Q];else return;return Z}generateRulesFromInterface($){let J=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,Q,G,W]=Z;J.push({path:Q,required:!G,type:this.mapTypeScriptType(W)})}return J}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:V4},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class FJ{fileLoader=new E6;envProcessor=new L6;validator=new HJ;async loadConfig($){let J=Date.now(),{cache:Y,performance:Z,schema:Q,validate:G,...W}=$;try{if(Y?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let z;try{z=await this.loadConfigurationStrategies(W,!0,Y)}catch(U){let H=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(H)throw U;z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let F=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),B=!F&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),K=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(H&&(K||F))throw U;if(B&&(!H||!K))z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!H)z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Q||G)await this.validateConfiguration(z.config,Q,G,W.name);if(Y?.enabled&&z)this.cacheResult(W.name||"",z,Y,W);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-J,configName:W.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)d1.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);z.metrics=U}return z}catch(z){let U=Date.now()-J;throw d1.error(`Configuration loading failed after ${U}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,J=!1,Y){let{name:Z="",alias:Q,cwd:G,configDir:W,defaultConfig:z,checkEnv:U=!0,arrayStrategy:H="replace",verbose:F=!1}=$,B=G||t2.cwd(),K=[],O=await this.loadLocalConfiguration(Z,Q,B,W,z,H,F,U,Y);if(O)return K.push(...this.getLocalSearchPaths(Z,Q,B,W)),this.finalizeResult(O,K,U,Z,F);let V=await this.loadHomeConfiguration(Z,Q,z,H,F,U);if(V)return K.push(...this.getHomeSearchPaths(Z,Q)),this.finalizeResult(V,K,U,Z,F);let A=await this.loadPackageJsonConfiguration(Z,Q,B,z,H,F,U);if(A)return K.push(z1(B,"package.json")),this.finalizeResult(A,K,U,Z,F);if(K.push(...this.getAllSearchPaths(Z,Q,B,W)),J)throw b2.configNotFound(Z,K,Q);return{...await this.applyEnvironmentVariables(Z,z,U,F),warnings:[`No configuration file found for "${Z}"${Q?` or alias "${Q}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,Y,Z,Q,G,W,z,U){let H=z?B8($,Q,W):Q,F=this.getLocalDirectories(Y,Z);for(let B of F){if(W)d1.info(`Searching for configuration in: ${B}`);let K=this.fileLoader.generateConfigPaths($,B,J),O=await this.fileLoader.tryLoadFromPaths(K,H,{arrayStrategy:G,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(W)d1.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,J,Y,Z,Q,G){if(!$)return null;let W=G?B8($,Y,Q):Y,z=[z1(T$(),".config",$),z1(T$(),".config"),T$()];for(let U of z){if(Q)d1.info(`Checking home directory: ${U}`);let H=this.fileLoader.generateConfigPaths($,U,J),F=await this.fileLoader.tryLoadFromPaths(H,W,{arrayStrategy:Z,verbose:Q});if(F){if(Q)d1.success(`Configuration loaded from home directory: ${F.source.path}`);return F}}return null}async loadPackageJsonConfiguration($,J,Y,Z,Q,G,W){let z=W?B8($,Z,G):Z;try{let U=z1(Y,"package.json");if(!p5(U))return null;let H=await import(U),F=H[$],B=$;if(!F&&J)F=H[J],B=J;if(F&&typeof F==="object"&&!Array.isArray(F)){if(G)d1.success(`Configuration loaded from package.json: ${B}`);return{config:UJ(z,F,Q),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(G)d1.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,J,Y,Z){if(!Y||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:B8($,J,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,Y,Z,Q){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,Y,Z){let Q=[];if(Y){let G=Y($);if(G)Q.push(...G)}if(J){let G=await this.validator.validateConfiguration($,J);if(!G.isValid)Q.push(...G.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(Q.length>0)throw b2.configValidation(Z||"unknown",Q,Z)}checkCache($,J){let Y=this.generateCacheKey($,J);return k$.get(Y)||null}cacheResult($,J,Y,Z){let Q=this.generateCacheKey($,Z);k$.set(Q,J,void 0,Y.ttl)}generateCacheKey($,J){let Y=[$];if(J.alias)Y.push(`alias:${J.alias}`);if(J.cwd)Y.push(`cwd:${J.cwd}`);if(J.configDir)Y.push(`configDir:${J.configDir}`);if("checkEnv"in J)Y.push(`checkEnv:${J.checkEnv}`);return Y.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,z1($,"config"),z1($,".config"),J?z1($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,Y,Z){let Q=[];return Q.push(...this.getLocalSearchPaths($,J,Y,Z)),Q.push(...this.getHomeSearchPaths($,J)),Q.push(z1(Y,"package.json")),Q}getLocalSearchPaths($,J,Y,Z){let Q=this.getLocalDirectories(Y,Z),G=[];for(let W of Q)G.push(...this.fileLoader.generateConfigPaths($,W,J));return G}getHomeSearchPaths($,J){if(!$)return[];let Y=[z1(T$(),".config",$),z1(T$(),".config"),T$()],Z=[];for(let Q of Y)Z.push(...this.fileLoader.generateConfigPaths($,Q,J));return Z}async loadConfigWithResult($){return this.loadConfig($)}}function gW($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Z=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||Z}async function mK($){return _2.loadConfig({...$,__strictErrorHandling:!0})}async function F4($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Y)Z=await _2.loadConfig($);else Z=await _2.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??J}catch(Z){let Q=Z instanceof Error?Z.name:"UnknownError",G=Z instanceof Error?Z.message:String(Z);if(!(Q==="ConfigNotFoundError"||Q==="ConfigLoadError"||Q==="ConfigValidationError"||G.includes("config"))&&$.verbose)d1.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let z=Y?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await _2.applyEnvironmentVariables(z.name||"",J,!0,z.verbose||!1))?.config??J;return J}}async function lK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:J}=await import("process");try{return(await _2.loadConfig({name:$,cwd:J(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&gW(Y)))return(await _2.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await _2.loadConfig({...$,cwd:$.cwd||t2.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(J){if(J instanceof Error&&(J.name==="ConfigNotFoundError"||J.name==="ConfigLoadError"&&gW(J)))return(await _2.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw J}}async function pK($,J,Y="replace"){let Z=new E6;try{let Q=await Z.loadFromPath($,J,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return Q?Q.config:null}catch{return null}}function B8($,J,Y=!1){let Z=new L6,Q=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(W,z=[]){let U={...W};for(let[H,F]of Object.entries(W)){let B=[...z,H],K=[`${Q}_${B.join("_").toUpperCase()}`,`${Q}_${B.map((A)=>A.toUpperCase()).join("")}`,`${Q}_${B.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,V;for(let A of K)if(O=t2.env[A],O!==void 0){V=A;break}if(O!==void 0&&V)if(typeof F==="boolean")U[H]=["true","1","yes"].includes(O.toLowerCase());else if(typeof F==="number"){let A=Number(O);if(!Number.isNaN(A))U[H]=A}else if(Array.isArray(F))try{U[H]=JSON.parse(O)}catch{U[H]=O.split(",").map((A)=>A.trim())}else U[H]=O;else if(F&&typeof F==="object"&&!Array.isArray(F))U[H]=G(F,B)}return U}return G(J)}function rK($){let J=z1(t2.cwd(),$.configDir),Y=z1(t2.cwd(),$.generatedDir),Z=z1(Y,"config-types.ts");if(!p5(VW(Z)))hB(VW(Z),{recursive:!0,mode:511});let Q=p5(J)?bB(J).map((W)=>W.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${MO}
|
|
7623
|
+
`;return Y}}function fK($,J){let Y=X4("process");if(typeof Y>"u"||!Y.env)return J;let Z=Y.env[$];return Z!==void 0?Z:J}function z4($,J,Y={}){return U4($,J,Y,new WeakMap)}function U4($,J,Y,Z){let{arrayMergeMode:Q="replace",skipNullish:G=!1,customMerger:W}=Y;if(J===null||J===void 0)return G?$:J;if(W){let z=W($,J);if(z!==void 0)return z}if(Array.isArray(J)||Array.isArray($))return H4($,J,Q,Z);if(!b1(J)||!b1($))return J;return cK($,J,Y,Z)}function H4($,J,Y,Z){if(Array.isArray(J)&&!Array.isArray($))return J;if(Array.isArray($)&&!Array.isArray(J))return J;if(Array.isArray(J)&&Array.isArray($))switch(Y){case"replace":return J;case"concat":return gK($,J);case"smart":return uK($,J,Z);default:return J}return J}function gK($,J){let Y=[...J];for(let Z of $)if(!Y.some((Q)=>n5(Q,Z)))Y.push(Z);return Y}function uK($,J,Y){if(J.length===0)return $;if($.length===0)return J;if(b1(J[0])&&b1($[0]))return dK($,J,Y);if(J.every((Z)=>typeof Z==="string")&&$.every((Z)=>typeof Z==="string")){let Z=[...J];for(let Q of $)if(!Z.includes(Q))Z.push(Q);return Z}return J}function dK($,J,Y){let Z=[...J];for(let Q of $){if(!b1(Q)){Z.push(Q);continue}let G=["id","name","key","path","type"],W=!1;for(let z of G)if(z in Q){if(Z.find((H)=>b1(H)&&(z in H)&&H[z]===Q[z])){W=!0;break}}if(!W)Z.push(Q)}return Z}function cK($,J,Y,Z){let Q=J;if(b1(Q)&&Z.has(Q))return Z.get(Q);let G={...$};if(b1(Q))Z.set(Q,G);for(let W in Q){if(!Object.prototype.hasOwnProperty.call(Q,W))continue;let z=Q[W],U=G[W];if(Y.skipNullish&&(z===null||z===void 0))continue;if(z===null||z===void 0){G[W]=z;continue}if(b1(z)&&b1(U))G[W]=U4(U,z,Y,Z);else if(Array.isArray(z)||Array.isArray(U))G[W]=H4(U,z,Y.arrayMergeMode||"smart",Z);else G[W]=z}return G}function UJ($,J,Y="replace"){return z4($,J,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function n5($,J){if($===J)return!0;if(Array.isArray($)&&Array.isArray(J)){if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if(!n5($[Y],J[Y]))return!1;return!0}if(b1($)&&b1(J)){let Y=Object.keys($),Z=Object.keys(J);if(Y.length!==Z.length)return!1;for(let Q of Y){if(!Object.prototype.hasOwnProperty.call(J,Q))return!1;if(!n5($[Q],J[Q]))return!1}return!0}return!1}function b1($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class E6{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,J,Y={}){let{arrayStrategy:Z="replace",useCache:Q=!0,cacheTtl:G,trackPerformance:W=!0,verbose:z=!1}=Y;if(Q){let H=k$.getWithFileCheck("file",$);if(H){if(z)console.log(`Configuration loaded from cache: ${$}`);return H}}let U=async()=>{if(!p9($))return null;try{let H=`?t=${Date.now()}`,F=await import($+H),B=F.default||F,K="default"in F,O=Object.keys(F).length>0;if(!K&&!O)throw new O8($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof B!=="object"||B===null||Array.isArray(B))throw new O8($,Error("Configuration must export a valid object"),"unknown");let _={config:UJ(J,B,Z),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Q)k$.setWithFileCheck("file",_,$,G);return _}catch(H){throw H instanceof Error?b2.configLoad($,H):b2.configLoad($,Error(String(H)))}};if(W)return V8.track("loadFromPath",U,{path:$});return U()}async tryLoadFromPaths($,J,Y={}){for(let Z of $)try{let Q=await this.loadFromPath(Z,J,Y);if(Q)return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigLoadError")throw Q;if(Y.verbose)console.warn(`Failed to load config from ${Z}:`,Q)}return null}generateConfigPaths($,J,Y){let Z=this.generateNamePatterns($,Y),Q=[];for(let G of Z)for(let W of this.extensions)Q.push(k5(J,`${G}${W}`));return Q}generateNamePatterns($,J){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(J){if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}return Y.filter(Boolean)}checkFileAccess($){return G4(async()=>{return p9($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,J,Y){let Z=[];if(!p9($))return Z;if(J||Y){let Q=this.generateNamePatterns(J||"",Y);for(let G of Q)for(let W of this.extensions){let z=k5($,`${G}${W}`);if(await this.checkFileAccess(z))Z.push(z)}}else try{let{readdirSync:Q}=await import("fs"),G=Q($);for(let W of G)if(this.looksLikeConfigFile(W)){let z=k5($,W);if(await this.checkFileAccess(z))Z.push(z)}}catch{return[]}return Z}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let J=[];try{if(!p9($))return J.push("Configuration file does not exist"),J;let Y=await import($),Z=Y.default||Y;if(Z===void 0)J.push("Configuration file must export a default value or named exports");else if(typeof Z!=="object"||Z===null)J.push("Configuration must be an object");else if(Array.isArray(Z))J.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:Q}=await import("fs"),G=Q($,"utf8");JSON.parse(G)}catch(Q){J.push(`Invalid JSON syntax: ${Q}`)}}catch(Y){J.push(`Failed to load configuration file: ${Y}`)}return J}async getFileModificationTime($){try{let{statSync:J}=await import("fs");return J($).mtime}catch{return null}}async preloadConfigurations($,J={}){let Y=new Map;return await Promise.allSettled($.map(async(Z)=>{try{let Q=await this.loadFromPath(Z,{},J);if(Q)Y.set(Z,Q.config)}catch(Q){if(J.verbose)console.warn(`Failed to preload ${Z}:`,Q)}})),Y}}class HJ{async validateConfiguration($,J,Y={}){let{stopOnFirstError:Z=!1,validateRequired:Q=!0,validateTypes:G=!0,customRules:W=[],trackPerformance:z=!0,verbose:U=!1}=Y,H=async()=>{let F=[],B=[],K={stopOnFirstError:Z,validateRequired:Q,validateTypes:G,customRules:W,trackPerformance:z,verbose:U};try{if(typeof J==="string")return await this.validateWithSchemaFile($,J,K);else if(Array.isArray(J))return this.validateWithRules($,[...J,...W],K);else return this.validateWithJSONSchema($,J,K)}catch(O){return F.push({path:"",message:`Validation failed: ${O}`,rule:"system"}),{isValid:!1,errors:F,warnings:B}}};if(z)return await V8.track("validateConfiguration",H);return H()}async validateWithSchemaFile($,J,Y){try{if(!ZK(J))throw new A8(J,[{path:"",message:"Schema file does not exist"}]);let Z=await import(J),Q=Z.default||Z;if(Array.isArray(Q))return this.validateWithRules($,Q,Y);else return this.validateWithJSONSchema($,Q,Y)}catch(Z){throw new A8(J,[{path:"",message:`Failed to load schema: ${Z}`}])}}validateWithJSONSchema($,J,Y){let Z=[],Q=[];return this.validateObjectAgainstSchema($,J,"",Z,Q,Y),{isValid:Z.length===0,errors:Z,warnings:Q}}validateObjectAgainstSchema($,J,Y,Z,Q,G){if(G.validateTypes&&J.type){let W=Array.isArray($)?"array":typeof $,z=Array.isArray(J.type)?J.type:[J.type];if(!z.includes(W)){if(Z.push({path:Y,message:`Expected type ${z.join(" or ")}, got ${W}`,expected:z.join(" or "),actual:W,rule:"type"}),G.stopOnFirstError)return}}if(J.enum&&!J.enum.includes($)){if(Z.push({path:Y,message:`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"}),G.stopOnFirstError)return}if(typeof $==="string"){if(J.minLength!==void 0&&$.length<J.minLength)Z.push({path:Y,message:`String length must be at least ${J.minLength}`,expected:`>= ${J.minLength}`,actual:$.length,rule:"minLength"});if(J.maxLength!==void 0&&$.length>J.maxLength)Z.push({path:Y,message:`String length must not exceed ${J.maxLength}`,expected:`<= ${J.maxLength}`,actual:$.length,rule:"maxLength"});if(J.pattern){if(!new RegExp(J.pattern).test($))Z.push({path:Y,message:`String does not match pattern ${J.pattern}`,expected:J.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(J.minimum!==void 0&&$<J.minimum)Z.push({path:Y,message:`Value must be at least ${J.minimum}`,expected:`>= ${J.minimum}`,actual:$,rule:"minimum"});if(J.maximum!==void 0&&$>J.maximum)Z.push({path:Y,message:`Value must not exceed ${J.maximum}`,expected:`<= ${J.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&J.items)for(let W=0;W<$.length;W++){let z=Y?`${Y}[${W}]`:`[${W}]`;if(this.validateObjectAgainstSchema($[W],J.items,z,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let W=$;if(G.validateRequired&&J.required){for(let z of J.required)if(!(z in W)){if(Z.push({path:Y?`${Y}.${z}`:z,message:`Missing required property '${z}'`,expected:"required",rule:"required"}),G.stopOnFirstError)return}}if(J.properties){for(let[z,U]of Object.entries(J.properties))if(z in W){let H=Y?`${Y}.${z}`:z;if(this.validateObjectAgainstSchema(W[z],U,H,Z,Q,G),G.stopOnFirstError&&Z.length>0)return}}if(J.additionalProperties===!1){let z=new Set(Object.keys(J.properties||{}));for(let U of Object.keys(W))if(!z.has(U))Q.push({path:Y?`${Y}.${U}`:U,message:`Additional property '${U}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,J,Y){let Z=[],Q=[];for(let G of J)try{let W=this.getValueByPath($,G.path),z=this.validateWithRule(W,G,G.path);if(Z.push(...z),Y.stopOnFirstError&&Z.length>0)break}catch(W){Z.push({path:G.path,message:`Rule validation failed: ${W}`,rule:"system"})}return{isValid:Z.length===0,errors:Z,warnings:Q}}validateWithRule($,J,Y){let Z=[];if(J.required&&($===void 0||$===null))return Z.push({path:Y,message:J.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),Z;if($===void 0||$===null)return Z;if(J.type){let Q=Array.isArray($)?"array":typeof $;if(Q!==J.type)Z.push({path:Y,message:J.message||`Expected type ${J.type}, got ${Q}`,expected:J.type,actual:Q,rule:"type"})}if(J.min!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q<J.min)Z.push({path:Y,message:J.message||`Value must be at least ${J.min}`,expected:`>= ${J.min}`,actual:Q,rule:"min"})}if(J.max!==void 0){let Q=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Q>J.max)Z.push({path:Y,message:J.message||`Value must not exceed ${J.max}`,expected:`<= ${J.max}`,actual:Q,rule:"max"})}if(J.pattern&&typeof $==="string"){if(!J.pattern.test($))Z.push({path:Y,message:J.message||`Value does not match pattern ${J.pattern}`,expected:J.pattern.toString(),actual:$,rule:"pattern"})}if(J.enum&&!J.enum.includes($))Z.push({path:Y,message:J.message||`Value must be one of: ${J.enum.join(", ")}`,expected:J.enum.join(", "),actual:$,rule:"enum"});if(J.validator){let Q=J.validator($);if(Q)Z.push({path:Y,message:J.message||Q,rule:"custom"})}return Z}getValueByPath($,J){if(!J)return $;let Y=J.split("."),Z=$;for(let Q of Y)if(Z&&typeof Z==="object"&&Q in Z)Z=Z[Q];else return;return Z}generateRulesFromInterface($){let J=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Z of Y){let[,Q,G,W]=Z;J.push({path:Q,required:!G,type:this.mapTypeScriptType(W)})}return J}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:V4},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class FJ{fileLoader=new E6;envProcessor=new L6;validator=new HJ;async loadConfig($){let J=Date.now(),{cache:Y,performance:Z,schema:Q,validate:G,...W}=$;try{if(Y?.enabled){let U=this.checkCache(W.name||"",W);if(U)return U}let z;try{z=await this.loadConfigurationStrategies(W,!0,Y)}catch(U){let H=W.__strictErrorHandling;if(U instanceof Error&&U.name==="ConfigNotFoundError"){if(H)throw U;z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`No configuration file found for "${W.name||"config"}", using defaults with environment variables`]}}else if(U instanceof Error&&U.name==="ConfigLoadError"){let F=U.message.includes("EACCES")||U.message.includes("EPERM")||U.message.includes("permission denied"),B=!F&&(U.message.includes("syntax")||U.message.includes("Expected")||U.message.includes("Unexpected")||U.message.includes("BuildMessage")||U.message.includes("errors building")),K=U.message.includes("Configuration must export a valid object")||U.message.includes("Configuration file is empty and exports nothing");if(H&&(K||F))throw U;if(B&&(!H||!K))z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!H)z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading error, using defaults: ${U.message}`]};else throw U}else z={...await this.applyEnvironmentVariables(W.name||"",W.defaultConfig,W.checkEnv!==!1,W.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${U instanceof Error?U.message:String(U)}`]}}if(Q||G)await this.validateConfiguration(z.config,Q,G,W.name);if(Y?.enabled&&z)this.cacheResult(W.name||"",z,Y,W);if(Z?.enabled){let U={operation:"loadConfig",duration:Date.now()-J,configName:W.name,timestamp:new Date};if(Z.onMetrics)Z.onMetrics(U);if(Z.slowThreshold&&U.duration>Z.slowThreshold)d1.warn(`Slow configuration loading detected: ${U.duration}ms for ${W.name}`);z.metrics=U}return z}catch(z){let U=Date.now()-J;throw d1.error(`Configuration loading failed after ${U}ms:`,[z instanceof Error?z:Error(String(z))]),z}}async loadConfigurationStrategies($,J=!1,Y){let{name:Z="",alias:Q,cwd:G,configDir:W,defaultConfig:z,checkEnv:U=!0,arrayStrategy:H="replace",verbose:F=!1}=$,B=G||s2.cwd(),K=[],O=await this.loadLocalConfiguration(Z,Q,B,W,z,H,F,U,Y);if(O)return K.push(...this.getLocalSearchPaths(Z,Q,B,W)),this.finalizeResult(O,K,U,Z,F);let V=await this.loadHomeConfiguration(Z,Q,z,H,F,U);if(V)return K.push(...this.getHomeSearchPaths(Z,Q)),this.finalizeResult(V,K,U,Z,F);let A=await this.loadPackageJsonConfiguration(Z,Q,B,z,H,F,U);if(A)return K.push(z1(B,"package.json")),this.finalizeResult(A,K,U,Z,F);if(K.push(...this.getAllSearchPaths(Z,Q,B,W)),J)throw b2.configNotFound(Z,K,Q);return{...await this.applyEnvironmentVariables(Z,z,U,F),warnings:[`No configuration file found for "${Z}"${Q?` or alias "${Q}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,J,Y,Z,Q,G,W,z,U){let H=z?B8($,Q,W):Q,F=this.getLocalDirectories(Y,Z);for(let B of F){if(W)d1.info(`Searching for configuration in: ${B}`);let K=this.fileLoader.generateConfigPaths($,B,J),O=await this.fileLoader.tryLoadFromPaths(K,H,{arrayStrategy:G,verbose:W,cacheTtl:U?.ttl,useCache:!U?.ttl||U.ttl>100});if(O){if(W)d1.success(`Configuration loaded from: ${O.source.path}`);return O}}return null}async loadHomeConfiguration($,J,Y,Z,Q,G){if(!$)return null;let W=G?B8($,Y,Q):Y,z=[z1(T$(),".config",$),z1(T$(),".config"),T$()];for(let U of z){if(Q)d1.info(`Checking home directory: ${U}`);let H=this.fileLoader.generateConfigPaths($,U,J),F=await this.fileLoader.tryLoadFromPaths(H,W,{arrayStrategy:Z,verbose:Q});if(F){if(Q)d1.success(`Configuration loaded from home directory: ${F.source.path}`);return F}}return null}async loadPackageJsonConfiguration($,J,Y,Z,Q,G,W){let z=W?B8($,Z,G):Z;try{let U=z1(Y,"package.json");if(!p5(U))return null;let H=await import(U),F=H[$],B=$;if(!F&&J)F=H[J],B=J;if(F&&typeof F==="object"&&!Array.isArray(F)){if(G)d1.success(`Configuration loaded from package.json: ${B}`);return{config:UJ(z,F,Q),source:{type:"package.json",path:U,priority:30,timestamp:new Date}}}}catch(U){if(G)d1.warn("Failed to load package.json:",[U instanceof Error?U:Error(String(U))])}return null}async applyEnvironmentVariables($,J,Y,Z){if(!Y||!$||typeof J!=="object"||J===null||Array.isArray(J))return{config:J,source:{type:"default",priority:10,timestamp:new Date}};return{config:B8($,J,Z),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,J,Y,Z,Q){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,J,Y,Z){let Q=[];if(Y){let G=Y($);if(G)Q.push(...G)}if(J){let G=await this.validator.validateConfiguration($,J);if(!G.isValid)Q.push(...G.errors.map((W)=>W.path?`${W.path}: ${W.message}`:W.message))}if(Q.length>0)throw b2.configValidation(Z||"unknown",Q,Z)}checkCache($,J){let Y=this.generateCacheKey($,J);return k$.get(Y)||null}cacheResult($,J,Y,Z){let Q=this.generateCacheKey($,Z);k$.set(Q,J,void 0,Y.ttl)}generateCacheKey($,J){let Y=[$];if(J.alias)Y.push(`alias:${J.alias}`);if(J.cwd)Y.push(`cwd:${J.cwd}`);if(J.configDir)Y.push(`configDir:${J.configDir}`);if("checkEnv"in J)Y.push(`checkEnv:${J.checkEnv}`);return Y.join("|")}getLocalDirectories($,J){return Array.from(new Set([$,z1($,"config"),z1($,".config"),J?z1($,J):void 0].filter(Boolean)))}getAllSearchPaths($,J,Y,Z){let Q=[];return Q.push(...this.getLocalSearchPaths($,J,Y,Z)),Q.push(...this.getHomeSearchPaths($,J)),Q.push(z1(Y,"package.json")),Q}getLocalSearchPaths($,J,Y,Z){let Q=this.getLocalDirectories(Y,Z),G=[];for(let W of Q)G.push(...this.fileLoader.generateConfigPaths($,W,J));return G}getHomeSearchPaths($,J){if(!$)return[];let Y=[z1(T$(),".config",$),z1(T$(),".config"),T$()],Z=[];for(let Q of Y)Z.push(...this.fileLoader.generateConfigPaths($,Q,J));return Z}async loadConfigWithResult($){return this.loadConfig($)}}function gW($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Z=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||Z}async function mK($){return _2.loadConfig({...$,__strictErrorHandling:!0})}async function F4($){let J="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Z;if(Y)Z=await _2.loadConfig($);else Z=await _2.loadConfig({...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}});return Z?.config??J}catch(Z){let Q=Z instanceof Error?Z.name:"UnknownError",G=Z instanceof Error?Z.message:String(Z);if(!(Q==="ConfigNotFoundError"||Q==="ConfigLoadError"||Q==="ConfigValidationError"||G.includes("config"))&&$.verbose)d1.warn("Unexpected error loading config, using defaults:",[Z instanceof Error?Z:Error(String(Z))]);let z=Y?{...$,defaultConfig:J}:{...$,defaultConfig:J,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await _2.applyEnvironmentVariables(z.name||"",J,!0,z.verbose||!1))?.config??J;return J}}async function lK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:J}=await import("process");try{return(await _2.loadConfig({name:$,cwd:J(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&gW(Y)))return(await _2.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await _2.loadConfig({...$,cwd:$.cwd||s2.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(J){if(J instanceof Error&&(J.name==="ConfigNotFoundError"||J.name==="ConfigLoadError"&&gW(J)))return(await _2.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw J}}async function pK($,J,Y="replace"){let Z=new E6;try{let Q=await Z.loadFromPath($,J,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return Q?Q.config:null}catch{return null}}function B8($,J,Y=!1){let Z=new L6,Q=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function G(W,z=[]){let U={...W};for(let[H,F]of Object.entries(W)){let B=[...z,H],K=[`${Q}_${B.join("_").toUpperCase()}`,`${Q}_${B.map((A)=>A.toUpperCase()).join("")}`,`${Q}_${B.map((A)=>A.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],O,V;for(let A of K)if(O=s2.env[A],O!==void 0){V=A;break}if(O!==void 0&&V)if(typeof F==="boolean")U[H]=["true","1","yes"].includes(O.toLowerCase());else if(typeof F==="number"){let A=Number(O);if(!Number.isNaN(A))U[H]=A}else if(Array.isArray(F))try{U[H]=JSON.parse(O)}catch{U[H]=O.split(",").map((A)=>A.trim())}else U[H]=O;else if(F&&typeof F==="object"&&!Array.isArray(F))U[H]=G(F,B)}return U}return G(J)}function rK($){let J=z1(s2.cwd(),$.configDir),Y=z1(s2.cwd(),$.generatedDir),Z=z1(Y,"config-types.ts");if(!p5(VW(Z)))hB(VW(Z),{recursive:!0,mode:511});let Q=p5(J)?bB(J).map((W)=>W.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],G=`// Generated by bunfig v${MO}
|
|
7624
7624
|
export type ConfigNames = ${Q.length?`'${Q.join("' | '")}'`:"string"}
|
|
7625
7625
|
`;yB(Z,G,{mode:438})}function nK($){let J=null,Y=null,Z=()=>{if(!Y)Y=F4($).then((G)=>{return J=G,G},(G)=>{let W="defaultConfig"in $?$.defaultConfig:{};if(J=W,"verbose"in $&&$.verbose)d1.warn("Config loading failed, using defaults:",[G instanceof Error?G:Error(String(G))]);return W});return Y},Q="defaultConfig"in $?$.defaultConfig:{};return J=Q,Z(),new Proxy({},{get(G,W){if(J)return J[W];let z=Q[W];return Z(),z},has(G,W){return W in(J||Q)},ownKeys(){return Object.keys(J||Q)},getOwnPropertyDescriptor(G,W){return Object.getOwnPropertyDescriptor(J||Q,W)},set(G,W,z){if(!J)J={...Q};return J[W]=z,!0}})}function iK($){let J=xW(WK.cwd(),$?.configDir||"./config");function Y(){if(!QK(J))return[];let Q=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),G=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],W=GK(J).filter((U)=>Q.has(h5(U))).map((U)=>({base:U.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:U})),z=new Map;for(let{base:U,file:H}of W){let F=h5(H).toLowerCase(),B=z.get(U);if(!B){z.set(U,H);continue}let K=h5(B).toLowerCase();if(G.indexOf(F)<G.indexOf(K))z.set(U,H)}return Array.from(z.entries()).map(([U,H])=>({base:U,file:H})).sort((U,H)=>U.base.localeCompare(H.base))}function Z(){let Q=Y(),G=Q.map((H)=>H.base),W=G.length?G.map((H)=>`'${H}'`).join(" | "):"string",z=Q.length?`{
|
|
7626
7626
|
${Q.map((H)=>{let F=xW(J,H.file).replace(/\\/g,"/");return` '${H.base}': typeof import('${F}').default`}).join(`,
|
|
@@ -7629,7 +7629,7 @@ ${Q.map((H)=>{let F=xW(J,H.file).replace(/\\/g,"/");return` '${H.base}': typeof
|
|
|
7629
7629
|
export type ConfigByName = ${z}
|
|
7630
7630
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
7631
7631
|
export type ConfigOf = Config
|
|
7632
|
-
`}return{name:"bunfig-plugin",setup(Q){Q.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),Q.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var X4,k$,V8,B4,aK,tK,uW,$6,i5,s0,R0,sK,dW,oK,cW,eK,$O,f5,JO,mW,lW,g5,YO,ZO,QO,GO,J6,K4,WO,o0,zO,UO,pW,Y6,a5,d0,j0,HO,rW,FO,nW,XO,BO,u5,KO,iW,aW,OO,d5,AO,VO,_O,jO,LO,Z6,O4,EO,MO="0.15.6",w1,K6,O8,t5,s5,O6,o5,e5,A8,$J,JJ,b2,A4,V4,d1,_2,_4,j4,qO=qK(async()=>{X4=import.meta.require,k$=new QJ,V8=new GJ,B4={createKey:TK,isEquivalent:wK,estimateMemoryUsage:DK},aK=z6(r5.cwd(),"config"),tK=z6(r5.cwd(),"src/generated"),uW=W6.env.CLARITY_LOG_DIR||gB(SK(),"logs"),$6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},i5=await PK(),s0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},R0=s0,sK=s0.red,dW=s0.green,oK=s0.yellow,cW=s0.blue,eK=s0.magenta,$O=s0.cyan,f5=s0.white,JO=s0.gray,mW=s0.bgRed,lW=s0.bgYellow,g5=s0.bold,YO=s0.dim,ZO=s0.italic,QO=s0.underline,GO=s0.reset,J6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},K4={debug:"\uD83D\uDD0D",info:cW("ℹ"),success:dW("✓"),warning:lW(f5(g5(" WARN "))),error:mW(f5(g5(" ERROR ")))},WO=new F6("stacks"),o0=new F6("bunfig",{showTags:!0}),zO=W1(K8.cwd(),"config"),UO=W1(K8.cwd(),"src/generated"),pW=G6.env.CLARITY_LOG_DIR||vB(kK(),"logs"),Y6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},a5=await hK(),d0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},j0=d0,HO=d0.red,rW=d0.green,FO=d0.yellow,nW=d0.blue,XO=d0.magenta,BO=d0.cyan,u5=d0.white,KO=d0.gray,iW=d0.bgRed,aW=d0.bgYellow,OO=d0.bgGray,d5=d0.bold,AO=d0.dim,VO=d0.italic,_O=d0.underline,jO=d0.strikethrough,LO=d0.reset,Z6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},O4={debug:"\uD83D\uDD0D",info:nW("ℹ"),success:rW("✓"),warning:aW(u5(d5(" WARN "))),error:iW(u5(d5(" ERROR ")))},EO=new B6("stacks"),w1=class extends Error{timestamp;context;constructor(J,Y={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},K6=class extends w1{code="CONFIG_NOT_FOUND";constructor(J,Y,Z){let Q=Z?` or alias "${Z}"`:"";super(`Configuration "${J}"${Q} not found`,{configName:J,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},O8=class extends w1{code="CONFIG_LOAD_ERROR";constructor(J,Y,Z){super(`Failed to load configuration from "${J}": ${Y.message}`,{configPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t5=class extends w1{code="CONFIG_VALIDATION_ERROR";constructor(J,Y,Z){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},s5=class extends w1{code="CONFIG_MERGE_ERROR";constructor(J,Y,Z,Q){super(`Failed to merge configuration from "${J}" with "${Y}": ${Z.message}`,{sourcePath:J,targetPath:Y,configName:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},O6=class extends w1{code="ENV_VAR_ERROR";constructor(J,Y,Z,Q){super(`Failed to parse environment variable "${J}" with value "${Y}" as ${Z}`,{envKey:J,envValue:Y,expectedType:Z,configName:Q})}},o5=class extends w1{code="FILE_SYSTEM_ERROR";constructor(J,Y,Z){super(`File system ${J} failed for "${Y}": ${Z.message}`,{operation:J,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},e5=class extends w1{code="TYPE_GENERATION_ERROR";constructor(J,Y,Z){super(`Failed to generate types from "${J}" to "${Y}": ${Z.message}`,{configDir:J,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},A8=class extends w1{code="SCHEMA_VALIDATION_ERROR";constructor(J,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},$J=class extends w1{code="BROWSER_CONFIG_ERROR";constructor(J,Y,Z,Q){super(`Failed to fetch configuration from "${J}": ${Y} ${Z}`,{endpoint:J,status:Y,statusText:Z,configName:Q})}},JJ=class extends w1{code="PLUGIN_ERROR";constructor(J,Y,Z){super(`Plugin "${J}" failed during ${Y}: ${Z.message}`,{pluginName:J,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},b2={configNotFound($,J,Y){return new K6($,J,Y)},configLoad($,J,Y){return new O8($,J,Y)},configValidation($,J,Y){return new t5($,J,Y)},configMerge($,J,Y,Z){return new s5($,J,Y,Z)},envVar($,J,Y,Z){return new O6($,J,Y,Z)},fileSystem($,J,Y){return new o5($,J,Y)},typeGeneration($,J,Y){return new e5($,J,Y)},schemaValidation($,J,Y){return new A8($,J,Y)},browserConfig($,J,Y,Z){return new $J($,J,Y,Z)},plugin($,J,Y){return new JJ($,J,Y)}},A4={replace:"replace",concat:"concat",smart:"smart"},V4=/^https?:\/\//,d1=new B6("bunfig",{showTags:!0}),_2=new FJ,_4=z1(t2.cwd(),"config"),j4=z1(t2.cwd(),"src/generated")});function TO($,J={}){let Y=U6.cwd();while(Y.includes("storage"))Y=IW(Y,"..");let Z=IW(Y,$||"");if(J?.relative)return UK(U6.cwd(),Z);return Z}var wO=U6.env.CLARITY_LOG_DIR||zK(TO(),"logs"),L4={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wO,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},A6={...L4},TR=(async()=>{try{let{loadConfig:$}=await qO().then(()=>Y4),J=await $({name:"clarity",alias:"logging",defaultConfig:L4,cwd:U6.cwd()});if(J)Object.assign(A6,J)}catch{}return A6})();function c0(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function DO(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V2<"u"){let $=V2.type;if($==="renderer"||$==="worker")return!1;return!!(V2.versions&&(V2.versions.node||V2.versions.bun))}return!1}class E4{async format($){let J=await DO(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:I$.pid,hostname:J(),environment:I$.env.NODE_ENV||"development",platform:I$.platform,version:I$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I$.env.NODE_ENV||I$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var r0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},E0=r0,wR=r0.red,RO=r0.green,DR=r0.yellow,NO=r0.blue,RR=r0.magenta,NR=r0.cyan,tW=r0.white,SR=r0.gray,SO=r0.bgRed,PO=r0.bgYellow,PR=r0.bgGray,sW=r0.bold,CR=r0.dim,xR=r0.italic,IR=r0.underline,kR=r0.strikethrough,hR=r0.reset,c5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},CO={debug:"\uD83D\uDD0D",info:NO("ℹ"),success:RO("✓"),warning:PO(tW(sW(" WARN "))),error:SO(tW(sW(" ERROR ")))};class M6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...A6},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new E4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??V0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...c5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...c5};return{...c5,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:A6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}shouldWriteToFile(){return!c0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await KK(this.config.logDirectory,yW.F_OK|yW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await OK(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:K2.from($);try{if(!r9(this.currentLogFile))await v5(this.currentLogFile,"",{mode:420});if(Q=bW(this.currentLogFile,"a",420),BK(Q,U,{flag:"a"}),hW(Q),Q!==void 0)y5(Q),Q=void 0;if((await C$(this.currentLogFile)).size===0){if(await v5(this.currentLogFile,U,{flag:"w",mode:420}),(await C$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{y5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return x$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return x$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return x$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(c0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return b5(16).toString("hex")}generateKey(){return b5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=b5(16),Z=HK("aes-256-gcm",J,Y),Q=K2.isBuffer($)?$:K2.from($,"utf8"),G=Z.update(Q),W=Z.final(),z=G.length+W.length,U=Z.getAuthTag(),H=K2.allocUnsafe(16+z+16);return Y.copy(H,0),G.copy(H,16),W.copy(H,16+G.length),U.copy(H,16+z),{encrypted:H,iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=fW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(K2.from(K2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(c0())return;if(!this.shouldWriteToFile())return;let $=await C$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await n9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await C$(Y).catch(()=>null))try{if(await vW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await i9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await v5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await C$(Y).catch(()=>null))await vW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await n9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await i9(x$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=kW($),Z=XK(J),Q=fW();await _K(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),r9(this.currentLogFile))try{let $=bW(this.currentLogFile,"r+");hW($),y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!c0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await n9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await i9(x$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?E0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||c0())return!1;let $=typeof V0.env.NO_COLOR<"u",J=V0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof V0.stderr<"u"&&V0.stderr.isTTY||typeof V0.stdout<"u"&&V0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=V0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${E0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,Q)=>{let G=E0.underline(E0.blue(Z)),W=this.toAbsoluteFilePath(Q);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(W)}`,U="\x1B]8;;",H="\x1B\\";return`\x1B]8;;${z}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Q}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),J=J.replace(/`([^`]+)`/g,(Y,Z)=>E0.bgGray(Z)),J=J.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>E0.bold(Z)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>E0.italic(Z)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>E0.italic(Z)),J=J.replace(/~([^~]+)~/g,(Y,Z)=>E0.strikethrough(Z)),J}supportsHyperlinks(){if(c0())return!1;let $=V0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let Y=V0.env.HOME||"";if(Y)J=J.replace(/^~(?=$|\/)/,Y)}if(AK(J)||J.startsWith("./")||J.startsWith("../"))J=VK(J);else return null;return r9(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:Y}}async log($,J,...Y){if(!this.shouldLog($))return;let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);let{consoleText:U,fileText:H}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let B=this.options.showIcons===!1?"":CO[$],K=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:E0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:E0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.error(O),z){let V=z.split(`
|
|
7632
|
+
`}return{name:"bunfig-plugin",setup(Q){Q.onResolve({filter:/^virtual:bunfig-types$/},(G)=>{return{path:G.path,namespace:"bunfig-virtual"}}),Q.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Z(),loader:"ts"}})}}}var X4,k$,V8,B4,aK,tK,uW,$6,i5,s0,R0,sK,dW,oK,cW,eK,$O,f5,JO,mW,lW,g5,YO,ZO,QO,GO,J6,K4,WO,o0,zO,UO,pW,Y6,a5,d0,j0,HO,rW,FO,nW,XO,BO,u5,KO,iW,aW,OO,d5,AO,VO,_O,jO,LO,Z6,O4,EO,MO="0.15.6",w1,K6,O8,t5,s5,O6,o5,e5,A8,$J,JJ,b2,A4,V4,d1,_2,_4,j4,qO=qK(async()=>{X4=import.meta.require,k$=new QJ,V8=new GJ,B4={createKey:TK,isEquivalent:wK,estimateMemoryUsage:DK},aK=z6(r5.cwd(),"config"),tK=z6(r5.cwd(),"src/generated"),uW=W6.env.CLARITY_LOG_DIR||gB(SK(),"logs"),$6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},i5=await PK(),s0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},R0=s0,sK=s0.red,dW=s0.green,oK=s0.yellow,cW=s0.blue,eK=s0.magenta,$O=s0.cyan,f5=s0.white,JO=s0.gray,mW=s0.bgRed,lW=s0.bgYellow,g5=s0.bold,YO=s0.dim,ZO=s0.italic,QO=s0.underline,GO=s0.reset,J6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},K4={debug:"\uD83D\uDD0D",info:cW("ℹ"),success:dW("✓"),warning:lW(f5(g5(" WARN "))),error:mW(f5(g5(" ERROR ")))},WO=new F6("stacks"),o0=new F6("bunfig",{showTags:!0}),zO=W1(K8.cwd(),"config"),UO=W1(K8.cwd(),"src/generated"),pW=G6.env.CLARITY_LOG_DIR||vB(kK(),"logs"),Y6={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},a5=await hK(),d0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},j0=d0,HO=d0.red,rW=d0.green,FO=d0.yellow,nW=d0.blue,XO=d0.magenta,BO=d0.cyan,u5=d0.white,KO=d0.gray,iW=d0.bgRed,aW=d0.bgYellow,OO=d0.bgGray,d5=d0.bold,AO=d0.dim,VO=d0.italic,_O=d0.underline,jO=d0.strikethrough,LO=d0.reset,Z6={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},O4={debug:"\uD83D\uDD0D",info:nW("ℹ"),success:rW("✓"),warning:aW(u5(d5(" WARN "))),error:iW(u5(d5(" ERROR ")))},EO=new B6("stacks"),w1=class extends Error{timestamp;context;constructor(J,Y={}){super(J);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let J=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,Z])=>`${Y}: ${Z}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${J}`}},K6=class extends w1{code="CONFIG_NOT_FOUND";constructor(J,Y,Z){let Q=Z?` or alias "${Z}"`:"";super(`Configuration "${J}"${Q} not found`,{configName:J,alias:Z,searchPaths:Y,searchPathCount:Y.length})}},O8=class extends w1{code="CONFIG_LOAD_ERROR";constructor(J,Y,Z){super(`Failed to load configuration from "${J}": ${Y.message}`,{configPath:J,configName:Z,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t5=class extends w1{code="CONFIG_VALIDATION_ERROR";constructor(J,Y,Z){super(`Configuration validation failed for "${J}"`,{configPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},s5=class extends w1{code="CONFIG_MERGE_ERROR";constructor(J,Y,Z,Q){super(`Failed to merge configuration from "${J}" with "${Y}": ${Z.message}`,{sourcePath:J,targetPath:Y,configName:Q,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},O6=class extends w1{code="ENV_VAR_ERROR";constructor(J,Y,Z,Q){super(`Failed to parse environment variable "${J}" with value "${Y}" as ${Z}`,{envKey:J,envValue:Y,expectedType:Z,configName:Q})}},o5=class extends w1{code="FILE_SYSTEM_ERROR";constructor(J,Y,Z){super(`File system ${J} failed for "${Y}": ${Z.message}`,{operation:J,path:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},e5=class extends w1{code="TYPE_GENERATION_ERROR";constructor(J,Y,Z){super(`Failed to generate types from "${J}" to "${Y}": ${Z.message}`,{configDir:J,outputPath:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},A8=class extends w1{code="SCHEMA_VALIDATION_ERROR";constructor(J,Y,Z){super(`Schema validation failed${Z?` for config "${Z}"`:""}`,{schemaPath:J,configName:Z,validationErrors:Y,errorCount:Y.length})}},$J=class extends w1{code="BROWSER_CONFIG_ERROR";constructor(J,Y,Z,Q){super(`Failed to fetch configuration from "${J}": ${Y} ${Z}`,{endpoint:J,status:Y,statusText:Z,configName:Q})}},JJ=class extends w1{code="PLUGIN_ERROR";constructor(J,Y,Z){super(`Plugin "${J}" failed during ${Y}: ${Z.message}`,{pluginName:J,operation:Y,originalError:Z.name,originalMessage:Z.message});this.cause=Z}},b2={configNotFound($,J,Y){return new K6($,J,Y)},configLoad($,J,Y){return new O8($,J,Y)},configValidation($,J,Y){return new t5($,J,Y)},configMerge($,J,Y,Z){return new s5($,J,Y,Z)},envVar($,J,Y,Z){return new O6($,J,Y,Z)},fileSystem($,J,Y){return new o5($,J,Y)},typeGeneration($,J,Y){return new e5($,J,Y)},schemaValidation($,J,Y){return new A8($,J,Y)},browserConfig($,J,Y,Z){return new $J($,J,Y,Z)},plugin($,J,Y){return new JJ($,J,Y)}},A4={replace:"replace",concat:"concat",smart:"smart"},V4=/^https?:\/\//,d1=new B6("bunfig",{showTags:!0}),_2=new FJ,_4=z1(s2.cwd(),"config"),j4=z1(s2.cwd(),"src/generated")});function TO($,J={}){let Y=U6.cwd();while(Y.includes("storage"))Y=IW(Y,"..");let Z=IW(Y,$||"");if(J?.relative)return UK(U6.cwd(),Z);return Z}var wO=U6.env.CLARITY_LOG_DIR||zK(TO(),"logs"),L4={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wO,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},A6={...L4},TR=(async()=>{try{let{loadConfig:$}=await qO().then(()=>Y4),J=await $({name:"clarity",alias:"logging",defaultConfig:L4,cwd:U6.cwd()});if(J)Object.assign(A6,J)}catch{}return A6})();function c0(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function DO(){if(V2.env.NODE_ENV==="test"||V2.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V2<"u"){let $=V2.type;if($==="renderer"||$==="worker")return!1;return!!(V2.versions&&(V2.versions.node||V2.versions.bun))}return!1}class E4{async format($){let J=await DO(),Y=await this.getMetadata(J);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:J}=await import("os");return{pid:I$.pid,hostname:J(),environment:I$.env.NODE_ENV||"development",platform:I$.platform,version:I$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I$.env.NODE_ENV||I$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var r0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},E0=r0,wR=r0.red,RO=r0.green,DR=r0.yellow,NO=r0.blue,RR=r0.magenta,NR=r0.cyan,tW=r0.white,SR=r0.gray,SO=r0.bgRed,PO=r0.bgYellow,PR=r0.bgGray,sW=r0.bold,CR=r0.dim,xR=r0.italic,IR=r0.underline,kR=r0.strikethrough,hR=r0.reset,c5={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},CO={debug:"\uD83D\uDD0D",info:NO("ℹ"),success:RO("✓"),warning:PO(tW(sW(" WARN "))),error:SO(tW(sW(" ERROR ")))};class M6{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,J={}){this.name=$,this.config={...A6},this.options=this.normalizeOptions(J),this.formatter=this.options.formatter||new E4,this.enabled=J.enabled??!0,this.fancy=J.fancy??!0,this.tagFormat=J.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=J.timestampPosition??"right",this.environment=J.environment??V0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(J);let Y={...J},Z=J.timestamp!==void 0;if(Z)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:Z||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Q=this.generateKeyId(),G=this.generateKey();this.currentKeyId=Q,this.keys.set(Q,G),this.encryptionKeys.set(Q,{key:G,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let J={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return J[$]>=J[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...c5,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...c5};return{...c5,...$.fingersCrossed}}normalizeOptions($){let J={format:"json",level:"info",logDirectory:A6.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...J,...Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=J.level;return Y}shouldWriteToFile(){return!c0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let Q,G=0,W=3,z=1000;while(G<W)try{try{try{await KK(this.config.logDirectory,yW.F_OK|yW.W_OK)}catch(H){if(H instanceof Error&&"code"in H)if(H.code==="ENOENT")await OK(this.config.logDirectory,{recursive:!0,mode:493});else if(H.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw H;else throw H}}catch(H){throw console.error("Debug: [writeToFile] Failed to create log directory:",H),H}let U=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:K2.from($);try{if(!r9(this.currentLogFile))await v5(this.currentLogFile,"",{mode:420});if(Q=bW(this.currentLogFile,"a",420),BK(Q,U,{flag:"a"}),hW(Q),Q!==void 0)y5(Q),Q=void 0;if((await C$(this.currentLogFile)).size===0){if(await v5(this.currentLogFile,U,{flag:"w",mode:420}),(await C$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(H){let F=H;if(F.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(F.code)){if(G<W-1){let B=typeof F.message==="string"?F.message:"Unknown error";console.error(`Network error during write attempt ${G+1}/${W}:`,B);let K=z*2**G;await new Promise((O)=>setTimeout(O,K)),G++;continue}}if(F?.code&&["ENOSPC","EDQUOT"].includes(F.code))throw Error(`Disk quota exceeded or no space left on device: ${F.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",F),F}finally{if(Q!==void 0)try{y5(Q)}catch(H){console.error("Debug: [writeToFile] Error closing file descriptor:",H)}}}catch(U){if(G===W-1){let F=U,B=typeof F.message==="string"?F.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),U}G++;let H=z*2**(G-1);await new Promise((F)=>setTimeout(F,H))}})();this.pendingOperations.push(Y);let Z=this.pendingOperations.length-1;try{await Y}catch(Q){throw console.error("Debug: [writeToFile] Error in operation:",Q),Q}finally{this.pendingOperations.splice(Z,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return x$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return x$(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return x$(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(c0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,J;switch($.frequency){case"daily":J=86400000;break;case"weekly":J=604800000;break;case"monthly":J=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},J)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let J=this.config.rotation.keyRotation;if(!J?.enabled)return;let Y=typeof J.interval==="number"?J.interval:60,Z=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Q)=>{console.error("Error rotating keys:",Q)})},Z)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let J=this.config.rotation.keyRotation,Y=this.generateKeyId(),Z=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,Z),this.encryptionKeys.set(Y,{key:Z,createdAt:new Date});let Q=Array.from(this.encryptionKeys.entries()).sort(([,z],[,U])=>U.createdAt.getTime()-z.createdAt.getTime()),G=typeof J.maxKeys==="number"?J.maxKeys:1,W=Math.max(1,G);if(Q.length>W)for(let[z]of Q.slice(W))this.encryptionKeys.delete(z),this.keys.delete(z)}generateKeyId(){return b5(16).toString("hex")}generateKey(){return b5(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:J}=this.getCurrentKey(),Y=b5(16),Z=HK("aes-256-gcm",J,Y),Q=K2.isBuffer($)?$:K2.from($,"utf8"),G=Z.update(Q),W=Z.final(),z=G.length+W.length,U=Z.getAuthTag(),H=K2.allocUnsafe(16+z+16);return Y.copy(H,0),G.copy(H,16),W.copy(H,16+G.length),U.copy(H,16+z),{encrypted:H,iv:Y}}async compressData($){return new Promise((J,Y)=>{let Z=fW(),Q=[];Z.on("data",(G)=>Q.push(G)),Z.on("end",()=>J(K2.from(K2.concat(Q)))),Z.on("error",Y),Z.write($),Z.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let J=this.config.rotation.encrypt;return{...$,...J}}return $}async rotateLog(){if(c0())return;if(!this.shouldWriteToFile())return;let $=await C$(this.currentLogFile).catch(()=>null);if(!$)return;let J=this.config.rotation;if(typeof J==="boolean")return;if(J.maxSize&&$.size>=J.maxSize){let Y=this.currentLogFile,Z=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Q=await n9(this.config.logDirectory),G=Q.filter((U)=>U.startsWith(this.name)&&/\.log\.\d+$/.test(U)).sort((U,H)=>{let F=Number.parseInt(U.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(H.match(/\.log\.(\d+)$/)?.[1]||"0")-F}),W=G.length>0?Number.parseInt(G[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,z=`${Y}.${W}`;if(await C$(Y).catch(()=>null))try{if(await vW(Y,z),J.compress)try{let U=`${z}.gz`;await this.compressLogFile(z,U),await i9(z)}catch(U){console.error("Error compressing rotated file:",U)}if(G.length===0&&!Q.some((U)=>U.endsWith(".log.1")))try{let U=`${Y}.1`;await v5(U,"")}catch(U){console.error("Error creating backup file:",U)}}catch(U){console.error(`Error during rotation: ${U instanceof Error?U.message:String(U)}`)}}else{let Q=new Date().toISOString().replace(/[:.]/g,"-"),G=Y.replace(/\.log$/,`-${Q}.log`);if(await C$(Y).catch(()=>null))await vW(Y,G)}if(this.currentLogFile=Z,J.maxFiles){let G=(await n9(this.config.logDirectory)).filter((W)=>W.startsWith(this.name)).sort((W,z)=>z.localeCompare(W));for(let W of G.slice(J.maxFiles))await i9(x$(this.config.logDirectory,W))}}}async compressLogFile($,J){let Y=kW($),Z=XK(J),Q=fW();await _K(Y,Q,Z)}async handleFingersCrossedBuffer($,J){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let Z=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(Z);console.log(Z)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}}shouldLog($){if(!this.enabled)return!1;let J={debug:0,info:1,success:2,warning:3,error:4};return J[$]>=J[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((J)=>{console.error("Error in pending write operation:",J)});return Promise.resolve()})),r9(this.currentLogFile))try{let $=bW(this.currentLogFile,"r+");hW($),y5($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!c0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let J=(await n9(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of J)try{await i9(x$(this.config.logDirectory,Y))}catch(Z){console.error(`Failed to delete temp file ${Y}:`,Z)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?E0.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||c0())return!1;let $=typeof V0.env.NO_COLOR<"u",J=V0.env.FORCE_COLOR==="0";if($||J)return!1;return!!(typeof V0.stderr<"u"&&V0.stderr.isTTY||typeof V0.stdout<"u"&&V0.stdout.isTTY)}formatConsoleMessage($){let{timestamp:J,icon:Y="",tag:Z="",message:Q,level:G,showTimestamp:W=!0}=$,z=(O)=>O.replace(this.ANSI_PATTERN,"");if(!this.fancy){let O=[];if(W)O.push(J);if(G==="warning")O.push("WARN");else if(G==="error")O.push("ERROR");else if(Y)O.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Z)O.push(Z.replace(/[[\]]/g,""));return O.push(Q),O.join(" ")}let U=V0.stdout.columns||120,H="";if(G==="warning"||G==="error")H=`${Y} ${Q}`;else if(G==="info"||G==="success")H=`${Y} ${Z} ${Q}`;else H=`${Y} ${Z} ${E0.cyan(Q)}`;if(!W)return H.trim();let F=z(H).trim().length,B=z(J).length,K=Math.max(1,U-2-F-B);return`${H.trim()}${" ".repeat(K)}${J}`}formatMessage($,J){if(J.length===1&&Array.isArray(J[0]))return $.replace(/\{(\d+)\}/g,(G,W)=>{let z=Number.parseInt(W,10);return z<J[0].length?String(J[0][z]):G});let Y=/%([sdijfo%])/g,Z=0,Q=$.replace(Y,(G,W)=>{if(W==="%")return"%";if(Z>=J.length)return G;let z=J[Z++];switch(W){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return G}});if(Z<J.length)Q+=` ${J.slice(Z).map((G)=>typeof G==="object"?JSON.stringify(G,null,2):String(G)).join(" ")}`;return Q}formatMarkdown($){if(!$)return $;let J=$;return J=J.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,Z,Q)=>{let G=E0.underline(E0.blue(Z)),W=this.toAbsoluteFilePath(Q);if(W&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let z=`file://${encodeURI(W)}`,U="\x1B]8;;",H="\x1B\\";return`\x1B]8;;${z}\x1B\\${G}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Q}\x1B\\${G}\x1B]8;;\x1B\\`;return G}),J=J.replace(/`([^`]+)`/g,(Y,Z)=>E0.bgGray(Z)),J=J.replace(/\*\*([^*]+)\*\*/g,(Y,Z)=>E0.bold(Z)),J=J.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,Z)=>E0.italic(Z)),J=J.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,Z)=>E0.italic(Z)),J=J.replace(/~([^~]+)~/g,(Y,Z)=>E0.strikethrough(Z)),J}supportsHyperlinks(){if(c0())return!1;let $=V0.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let J=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(J)&&J>=5000)return!0;return!1}toAbsoluteFilePath($){try{let J=$;if(J.startsWith("file://"))J=J.replace(/^file:\/\//,"");if(J.startsWith("~")){let Y=V0.env.HOME||"";if(Y)J=J.replace(/^~(?=$|\/)/,Y)}if(AK(J)||J.startsWith("./")||J.startsWith("../"))J=VK(J);else return null;return r9(J)?J:null}catch{return null}}buildOutputTexts($){let J=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:J,fileText:Y}}async log($,J,...Y){if(!this.shouldLog($))return;let Z=new Date,Q=this.formatConsoleTimestamp(Z),G=this.formatFileTimestamp(Z),W,z;if(J instanceof Error)W=J.message,z=J.stack;else W=this.formatMessage(J,Y);let{consoleText:U,fileText:H}=this.buildOutputTexts(W);if(this.shouldStyleConsole()){let B=this.options.showIcons===!1?"":CO[$],K=this.options.showTags!==!1&&this.name?E0.gray(this.formatTag(this.name)):"",O;switch($){case"debug":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:E0.gray(U),level:$}),console.error(O);break;case"info":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"success":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:E0.green(U),level:$}),console.error(O);break;case"warning":O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.warn(O);break;case"error":if(O=this.formatConsoleMessage({timestamp:Q,icon:B,tag:K,message:U,level:$}),console.error(O),z){let V=z.split(`
|
|
7633
7633
|
`);for(let A of V)if(A.trim()&&!A.includes(W))console.error(this.formatConsoleMessage({timestamp:Q,message:E0.gray(` ${A}`),level:$,showTimestamp:!1}))}break}}else if(!c0()){if(console.error(`${G} ${this.environment}.${$.toUpperCase()}: ${W}`),z)console.error(z)}let F=`${G} ${this.environment}.${$.toUpperCase()}: ${H}
|
|
7634
7634
|
`;if(z)F+=`${z}
|
|
7635
7635
|
`;if(F=F.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(F)}progress($,J=""){let Y={update:(z,U)=>{},finish:(z)=>{},interrupt:(z,U)=>{}};if(!this.enabled)return Y;let Z=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:J||"",barLength:Z,lastRenderedLine:""},this.shouldStyleConsole()&&!c0()&&V0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(z,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,z),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!c0()&&V0.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(z)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,z)},interrupt:(z,U="info")=>{if(!c0()&&V0.stdout.isTTY)V0.stdout.write(`
|
|
@@ -7938,7 +7938,7 @@ Image available at:`),X(` 123456789.dkr.ecr.us-east-1.amazonaws.com/${Z}:${Y}`)
|
|
|
7938
7938
|
Deployment complete!`),X(`
|
|
7939
7939
|
Service details:`),X(" - Running tasks: 2/2"),X(" - Pending tasks: 0"),X(" - Status: ACTIVE")})}z0();j2();$2();function DZ($){$.command("domain:list","List all domains").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").action(async(J)=>{R("Domains");try{let Y=y2(J?.provider),Z=v1(J?.provider)?.provider||"unknown",Q=new N(`Fetching domains from ${Z}...`);Q.start();let G=await Y.listDomains();if(Q.succeed(`Found ${G.length} domain(s)`),G.length===0){X("No domains found in this provider");return}let W=G.map((z)=>[z,"Active","-",Z.charAt(0).toUpperCase()+Z.slice(1)]);p(["Domain","Status","SSL","Provider"],W)}catch(Y){w(`Failed to list domains: ${Y instanceof Error?Y.message:String(Y)}`)}}),$.command("domain:add <domain>","Add a new domain").option("--provider <provider>","DNS provider: porkbun, godaddy, cloudflare, or route53").action(async(J,Y)=>{R(`Adding Domain: ${J}`);try{let Z=y2(Y?.provider),Q=v1(Y?.provider)?.provider||"unknown",G=new N(`Checking if ${Q} can manage ${J}...`);if(G.start(),await Z.canManageDomain(J))G.succeed(`Domain ${J} is already available in ${Q}`),X(`
|
|
7940
7940
|
The domain is ready to use. You can now:`),X(` - Add DNS records: cloud dns:add ${J} A 192.168.1.1`),X(` - Generate SSL: cloud domain:ssl ${J}`);else if(G.warn(`Domain ${J} is not available in ${Q}`),X(`
|
|
7941
|
-
To add this domain:`),Q==="route53")X(" - Create a hosted zone in Route53 for this domain"),X(" - Update nameservers at your registrar to point to Route53");else X(` - Ensure the domain is registered with ${Q}`),X(" - Enable API access for the domain in your provider dashboard")}catch(Z){w(`Failed to check domain: ${Z instanceof Error?Z.message:String(Z)}`)}}),$.command("domain:ssl <domain>","Generate SSL certificate via ACM with DNS validation").option("--provider <provider>","DNS provider for validation: porkbun, godaddy, or route53").option("--region <region>","AWS region for ACM (default: us-east-1 for CloudFront compatibility)").option("--wait","Wait for certificate validation to complete").action(async(J,Y)=>{R(`Generating SSL Certificate for ${J}`);try{let Z=v1(Y?.provider);if(!Z)throw Error("No DNS provider configured");let Q=Y?.region||"us-east-1",G=Z.provider;X(`DNS Provider: ${G}`),X(`ACM Region: ${Q}`);let W=new
|
|
7941
|
+
To add this domain:`),Q==="route53")X(" - Create a hosted zone in Route53 for this domain"),X(" - Update nameservers at your registrar to point to Route53");else X(` - Ensure the domain is registered with ${Q}`),X(" - Enable API access for the domain in your provider dashboard")}catch(Z){w(`Failed to check domain: ${Z instanceof Error?Z.message:String(Z)}`)}}),$.command("domain:ssl <domain>","Generate SSL certificate via ACM with DNS validation").option("--provider <provider>","DNS provider for validation: porkbun, godaddy, or route53").option("--region <region>","AWS region for ACM (default: us-east-1 for CloudFront compatibility)").option("--wait","Wait for certificate validation to complete").action(async(J,Y)=>{R(`Generating SSL Certificate for ${J}`);try{let Z=v1(Y?.provider);if(!Z)throw Error("No DNS provider configured");let Q=Y?.region||"us-east-1",G=Z.provider;X(`DNS Provider: ${G}`),X(`ACM Region: ${Q}`);let W=new $$(Z,Q),z=new N("Requesting certificate and creating validation records...");z.start();let U=await W.findOrCreateCertificate({domainName:J,subjectAlternativeNames:[`*.${J}`],waitForValidation:Y?.wait??!0,maxWaitMinutes:10});if(U.isNew)z.succeed("Certificate requested and validation records created");else z.succeed("Found existing valid certificate");if(X(`Certificate ARN: ${U.certificateArn}`),X(`Status: ${U.status}`),U.status==="issued")h(`
|
|
7942
7942
|
SSL Certificate is ready!`),X(`
|
|
7943
7943
|
You can now use this certificate with:`),X(" - CloudFront distributions"),X(" - Application Load Balancers"),X(" - API Gateway custom domains");else if(U.status==="pending")X(`
|
|
7944
7944
|
DNS validation records have been created.`),X("Certificate validation may take a few more minutes."),X(`
|
|
@@ -7973,7 +7973,7 @@ Save credentials securely!`)}),$.command("db:users:list <name>","List database u
|
|
|
7973
7973
|
Top ${Z} slow queries:
|
|
7974
7974
|
`),p(["Time","Duration","Query","Rows"],[["2h ago","2.34s","SELECT * FROM users WHERE...","15,234"],["3h ago","1.89s","SELECT * FROM orders JOIN...","8,456"],["5h ago","1.56s","UPDATE products SET...","3,289"]]),X(`
|
|
7975
7975
|
Recommendations:`),X(" - Add index on users.email"),X(" - Optimize JOIN query with covering index"),X(" - Consider batching UPDATE operations")})}NZ();i8();z0();await Q1();function sU($,J=15){if(!$)return J*60000;let Y=/^(\d+)\s*([smhd])?$/.exec($.trim());if(!Y)return J*60000;let Z=Number(Y[1]),Q=Y[2]??"m";return Z*({s:1000,m:60000,h:3600000,d:86400000}[Q]??60000)}function hM($,J){for(let Y of $){let Z=Y.timestamp?new Date(Y.timestamp).toISOString():"",Q=J?`[${J}] `:"";X(`${Z} ${Q}${(Y.message??"").trimEnd()}`)}}function vZ($){$.command("logs","Stream serverless application logs (http + queue + cli)").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).option("--function <which>","Which function: http | queue | cli | all",{default:"all"}).option("--tail","Continuously stream new log events").option("--filter <pattern>","CloudWatch filter pattern").option("--since <duration>","Look back (e.g. 1h, 30m, 15)",{default:"15m"}).action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=new l2(Q),z=(J?.function??"all").toLowerCase();if(z!=="all"&&!["http","queue","cli"].includes(z)){w("--function must be one of: http, queue, cli, all"),process.exitCode=1;return}let H=(z==="all"?["http","queue","cli"]:[z]).map((K)=>({mode:K,group:`/aws/lambda/${G[K]}`}));R(`Logs — ${Y.project.slug} (${Z})`);let F=Date.now()-sU(J?.since),B=async()=>{let K=F;for(let{mode:O,group:V}of H)try{let{events:A=[]}=await W.filterLogEvents({logGroupName:V,startTime:F,filterPattern:J?.filter,limit:200});hM(A,H.length>1?O:void 0);for(let _ of A)if((_.timestamp??0)>K)K=_.timestamp??K}catch(A){if(!/ResourceNotFound/i.test(String(A?.message)))throw A}F=K+1};if(await B(),J?.tail){X(`
|
|
7976
|
-
(streaming — Ctrl+C to stop)`);for(;;)await new Promise((K)=>setTimeout(K,3000)),await B()}}catch(Y){w(`Failed to read logs: ${Y.message}`),process.exitCode=1}}),$.command("metrics","Show serverless function metrics (invocations, errors, duration, throttles)").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).option("--since <duration>","Window (e.g. 1h, 24h)",{default:"1h"}).action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=new
|
|
7976
|
+
(streaming — Ctrl+C to stop)`);for(;;)await new Promise((K)=>setTimeout(K,3000)),await B()}}catch(Y){w(`Failed to read logs: ${Y.message}`),process.exitCode=1}}),$.command("metrics","Show serverless function metrics (invocations, errors, duration, throttles)").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).option("--since <duration>","Window (e.g. 1h, 24h)",{default:"1h"}).action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=new F$(Q),z=sU(J?.since,60),U=new Date,H=new Date(U.getTime()-z),F=Math.max(60,Math.round(z/1000));R(`Metrics — ${Y.project.slug} (${Z}), last ${J?.since??"1h"}`);let B=[];for(let K of["http","queue","cli"]){let O=[{Name:"FunctionName",Value:G[K]}],V=async(T,D)=>{let S=await W.getMetricStatistics({Namespace:"AWS/Lambda",MetricName:T,Dimensions:O,StartTime:H,EndTime:U,Period:F,Statistics:[D]});if(!S.length)return 0;if(D==="Sum")return S.reduce((P,C)=>P+(C.Sum??0),0);if(D==="Maximum")return Math.max(...S.map((P)=>P.Maximum??0));return S.reduce((P,C)=>P+(C.Average??0),0)/S.length},[A,_,M,E,j]=await Promise.all([V("Invocations","Sum"),V("Errors","Sum"),V("Throttles","Sum"),V("Duration","Average"),V("Duration","Maximum")]),q=A?`${(_/A*100).toFixed(2)}%`:"—";B.push([K,String(A),String(_),q,String(M),`${E.toFixed(0)}ms`,`${j.toFixed(0)}ms`])}p(["Function","Invocations","Errors","Error rate","Throttles","Avg","Max"],B)}catch(Y){w(`Failed to read metrics: ${Y.message}`),process.exitCode=1}}),$.command("metrics:dashboard","Print the CloudWatch console URL for this app").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=encodeURIComponent(JSON.stringify({metrics:["http","queue","cli"].flatMap((z)=>[["AWS/Lambda","Invocations","FunctionName",G[z]],["AWS/Lambda","Errors","FunctionName",G[z]]]),view:"timeSeries",region:Q}));R("CloudWatch dashboard"),X(`https://console.aws.amazon.com/cloudwatch/home?region=${Q}#metricsV2:graph=${W}`)}catch(Y){w(Y.message),process.exitCode=1}}),$.command("alarms","List CloudWatch alarms").option("--prefix <prefix>","Filter by alarm name prefix").option("--region <region>","AWS region").action(async(J)=>{R("CloudWatch Alarms");let Y=J?.region;if(!Y)try{Y=(await m()).project.region}catch{}try{let Q=await new F$(Y||process.env.AWS_REGION||"us-east-1").describeAlarms({AlarmNamePrefix:J?.prefix,MaxRecords:100});if(!Q.length){X("No alarms found");return}p(["Name","State","Metric","Condition"],Q.map((G)=>[G.AlarmName??"-",G.StateValue??"-",G.MetricName??"-",`${G.ComparisonOperator??""} ${G.Threshold??""}`.trim()]))}catch(Z){w(`Failed to list alarms: ${Z.message}`),process.exitCode=1}}),$.command("alarms:create","Create a CloudWatch alarm on a Lambda metric").option("--name <name>","Alarm name").option("--env <environment>","Environment",{default:"production"}).option("--function <which>","Function: http | queue | cli",{default:"http"}).option("--metric <metric>","Lambda metric (Errors, Throttles, Duration, Invocations)",{default:"Errors"}).option("--threshold <value>","Threshold value").option("--comparison <op>","GreaterThanThreshold | GreaterThanOrEqualToThreshold | LessThanThreshold",{default:"GreaterThanThreshold"}).option("--statistic <stat>","Sum | Average | Maximum | Minimum",{default:"Sum"}).action(async(J)=>{if(R("Creating CloudWatch Alarm"),!J?.name||J?.threshold==null){w("Missing required options: --name and --threshold"),process.exitCode=1;return}try{let Y=await m(),Z=J.env||"production",{region:Q,functions:G}=q2(Y,Z),W=J.function??"http";await new F$(Q).putMetricAlarm({AlarmName:J.name,Namespace:"AWS/Lambda",MetricName:J.metric??"Errors",ComparisonOperator:J.comparison??"GreaterThanThreshold",Threshold:Number(J.threshold),EvaluationPeriods:1,Period:300,Statistic:J.statistic??"Sum",Dimensions:[{Name:"FunctionName",Value:G[W]}],AlarmDescription:`ts-cloud: ${G[W]} ${J.metric} ${J.comparison} ${J.threshold}`}),h(`Alarm '${J.name}' created on ${G[W]} ${J.metric}`)}catch(Y){w(`Failed to create alarm: ${Y.message}`),process.exitCode=1}})}o6();z0();async function W7($){let J=await m(),Y=$||"production";return{region:J.environments?.[Y]?.region||J.project.region||"us-east-1",prefix:`${J.project.slug}/${Y}`}}function fZ($){$.command("secrets:list","List secrets for an environment").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{R("Secrets");try{let{region:Y,prefix:Z}=await W7(J?.env),Q=new G2(Y),{SecretList:G=[]}=await Q.listSecrets({Filters:[{Key:"name",Values:[`${Z}/`]}],MaxResults:100});if(!G.length){X(`No secrets found under ${Z}/`);return}p(["Key","Last Changed"],G.map((W)=>[(W.Name??"").replace(`${Z}/`,""),W.LastChangedDate??W.LastAccessedDate??"-"]))}catch(Y){w(`Failed to list secrets: ${Y.message}`),process.exitCode=1}}),$.command("secrets:set <key> <value>","Set (create or update) a secret").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y,Z)=>{R(`Setting secret ${J}`);let{region:Q,prefix:G}=await W7(Z?.env),W=new G2(Q),z=`${G}/${J}`,U=new N("Storing secret...");U.start();try{try{await W.putSecretValue({SecretId:z,SecretString:Y})}catch{await W.createSecret({Name:z,SecretString:Y})}U.succeed(`Secret ${J} stored (${z})`),v("Redeploy for the new value to take effect in running functions.")}catch(H){U.fail(`Failed to store secret: ${H.message}`),process.exitCode=1}}),$.command("secrets:get <key>","Reveal a secret value").option("--env <environment>","Environment (production, staging, development)").action(async(J,Y)=>{try{let{region:Z,prefix:Q}=await W7(Y?.env),W=await new G2(Z).getSecretValue({SecretId:`${Q}/${J}`});X(W.SecretString??"")}catch(Z){w(`Failed to read secret: ${Z.message}`),process.exitCode=1}}),$.command("secrets:delete <key>","Delete a secret").option("--env <environment>","Environment (production, staging, development)").option("--force","Delete immediately without a recovery window").action(async(J,Y)=>{try{let{region:Z,prefix:Q}=await W7(Y?.env);await new G2(Z).deleteSecret({SecretId:`${Q}/${J}`,ForceDeleteWithoutRecovery:Y?.force}),h(`Secret ${J} deleted`)}catch(Z){w(`Failed to delete secret: ${Z.message}`),process.exitCode=1}})}z0();function gZ($){$.command("firewall:rules","List WAF rules").option("--env <environment>","Environment (production, staging, development)").action(async(J)=>{R("WAF Rules");let Y=J?.env||"production";X(`Environment: ${Y}
|
|
7977
7977
|
`),p(["Rule","Priority","Action","Requests Blocked"],[["Rate Limit","1","Block","1,234"],["Geo Block (CN, RU)","2","Block","567"],["SQL Injection","3","Block","89"],["XSS Prevention","4","Block","23"]])}),$.command("firewall:block <ip>","Block an IP address").option("--reason <reason>","Reason for blocking").action(async(J,Y)=>{R("Blocking IP Address");let Z=Y?.reason||"Manual block";if(X(`IP: ${J}`),X(`Reason: ${Z}`),!await g(`
|
|
7978
7978
|
Block this IP address?`,!0)){X("Operation cancelled");return}let G=new N("Adding IP to WAF block list...");G.start(),await new Promise((W)=>setTimeout(W,2000)),G.succeed(`IP ${J} blocked successfully`),h(`
|
|
7979
7979
|
IP blocked!`),X("The IP address will be blocked within 60 seconds")}),$.command("firewall:unblock <ip>","Unblock an IP address").action(async(J)=>{if(R("Unblocking IP Address"),X(`IP: ${J}`),!await g(`
|
|
@@ -8017,7 +8017,7 @@ Remove this webhook?`,!0)){X("Operation cancelled");return}let Z=new N("Removing
|
|
|
8017
8017
|
Webhook deleted!`)}),$.command("git:branches","List deployable branches").action(async()=>{R("Deployable Branches");let J=new N("Fetching branches...");J.start(),await new Promise((Y)=>setTimeout(Y,1500)),J.stop(),p(["Branch","Last Commit","Author","Deployed To"],[["main","2h ago","john@example.com","production"],["develop","30m ago","jane@example.com","staging"],["feature/new-ui","1d ago","bob@example.com","-"],["hotfix/bug-123","5h ago","alice@example.com","-"]]),X("\nTip: Deploy a branch with `cloud git:deploy <branch>`")})}L1();n1();z0();await z8([n0(),Q1()]);import{existsSync as aM,readFileSync as tM,writeFileSync as sM}from"node:fs";function e8($,J){w(`'${$}' is not implemented yet.`),X(J),process.exitCode=1}function oM($){let J={};for(let Y of $.split(`
|
|
8018
8018
|
`)){let Z=Y.trim();if(!Z||Z.startsWith("#"))continue;let Q=Z.indexOf("=");if(Q===-1)continue;let G=Z.slice(0,Q).trim(),W=Z.slice(Q+1).trim();if(W.startsWith('"')&&W.endsWith('"')||W.startsWith("'")&&W.endsWith("'"))W=W.slice(1,-1);J[G]=W}return J}function eM($){return Object.entries($).sort(([Y],[Z])=>Y.localeCompare(Z)).map(([Y,Z])=>{if(!/[\s#"']/.test(Z))return`${Y}=${Z}`;let Q='"'+Z.replace(/"/g,"\\\"")+'"';return`${Y}=${Q}`}).join(`
|
|
8019
8019
|
`)+`
|
|
8020
|
-
`}function nZ($){$.command("env:list","List configured environments and their deployed stack status").action(async()=>{R("Environments");try{let J=await m(),Y=Object.keys(J.environments??{});if(!Y.length){X("No environments configured. Add environments.<env> to your cloud.config.");return}let Z=[];for(let Q of Y){let G=J.environments[Q],W=G?.region||J.project.region||"us-east-1",z=G?.app?`serverless (${G.app.kind})`:"server/static",U="not deployed";if(G?.app)try{let H=new K0(W),{Stacks:F}=await H.describeStacks({stackName:
|
|
8020
|
+
`}function nZ($){$.command("env:list","List configured environments and their deployed stack status").action(async()=>{R("Environments");try{let J=await m(),Y=Object.keys(J.environments??{});if(!Y.length){X("No environments configured. Add environments.<env> to your cloud.config.");return}let Z=[];for(let Q of Y){let G=J.environments[Q],W=G?.region||J.project.region||"us-east-1",z=G?.app?`serverless (${G.app.kind})`:"server/static",U="not deployed";if(G?.app)try{let H=new K0(W),{Stacks:F}=await H.describeStacks({stackName:z$(J,Q)});U=F?.[0]?.StackStatus??"not deployed"}catch{U="not deployed"}Z.push([Q,G?.type??Q,z,W,U])}p(["Environment","Type","Kind","Region","Stack status"],Z)}catch(J){w(`Failed to list environments: ${J.message}`),process.exitCode=1}}),$.command("env:compare <env1> <env2>","Compare two environments' app configuration").action(async(J,Y)=>{R(`Comparing ${J} ↔ ${Y}`);try{let Z=await m(),Q=Z.environments?.[J],G=Z.environments?.[Y];if(!Q||!G){w(`Both environments must exist in config (have: ${Object.keys(Z.environments??{}).join(", ")||"none"}).`),process.exitCode=1;return}let W=(B,K="")=>{let O={};for(let[V,A]of Object.entries(B??{})){let _=K?`${K}.${V}`:V;if(A&&typeof A==="object"&&!Array.isArray(A))Object.assign(O,W(A,_));else O[_]=Array.isArray(A)?JSON.stringify(A):String(A)}return O},z=W(Q),U=W(G),F=[...new Set([...Object.keys(z),...Object.keys(U)])].sort().filter((B)=>z[B]!==U[B]).map((B)=>[B,z[B]??"—",U[B]??"—"]);if(!F.length){h("Identical — no configuration differences.");return}p(["Setting",J,Y],F),X(`
|
|
8021
8021
|
${F.length} difference(s)`)}catch(Z){w(`Comparison failed: ${Z.message}`),process.exitCode=1}}),$.command("env:pull","Download a serverless function's environment to a .env file").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).option("--function <which>","Which function: http | queue | cli",{default:"http"}).option("--file <path>","Output file (default .env.<environment>)").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=J?.function??"http",H=(await new l0(Q).getFunction(G[W])).Configuration?.Environment?.Variables??{},F=J?.file??`.env.${Z}`;sM(F,eM(H)),h(`Wrote ${Object.keys(H).length} variable(s) from ${G[W]} → ${F}`)}catch(Y){w(`env:pull failed: ${Y.message}`),process.exitCode=1}}),$.command("env:push","Upload a .env file to a serverless function's configuration").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).option("--function <which>","Function: http | queue | cli | all",{default:"all"}).option("--file <path>","Input file (default .env.<environment>)").option("--replace","Replace the entire env instead of merging over the live config").action(async(J)=>{try{let Y=await m(),Z=J?.env||"production",{region:Q,functions:G}=q2(Y,Z),W=J?.file??`.env.${Z}`;if(!aM(W)){w(`File not found: ${W}`),process.exitCode=1;return}let z=oM(tM(W,"utf8")),U=(J?.function??"all").toLowerCase();if(U!=="all"&&!["http","queue","cli"].includes(U)){w("--function must be one of: http, queue, cli, all"),process.exitCode=1;return}let H=U==="all"?["http","queue","cli"]:[U],F=(Y.environments?.[Z]?.app?.provisionedConcurrency??0)>0,B=new l0(Q);for(let K of H){let O=G[K],V=z;if(!J?.replace)V={...(await B.getFunction(O)).Configuration?.Environment?.Variables??{},...z};if(G7(O,V),await B.updateFunctionConfiguration({FunctionName:O,Environment:{Variables:V}}),await B.waitForFunctionActive(O,120),F){let A=await B.publishVersion({FunctionName:O});if(A.Version)await B.updateAlias({FunctionName:O,Name:"live",FunctionVersion:A.Version})}h(`Pushed ${Object.keys(z).length} var(s) → ${O}${J?.replace?" (replaced)":" (merged)"}${F?" (published + flipped live alias)":""}`)}X("Note: a subsequent `cloud deploy:serverless` re-injects infra/secret env from config.")}catch(Y){w(`env:push failed: ${Y.message}`),process.exitCode=1}}),$.command("env:create <name>","Create new environment").action(async(J)=>{e8(`env:create ${J}`,"Add an `environments.<name>` block to your cloud.config and run `cloud deploy:serverless --env <name>`.")}),$.command("env:switch <name>","Switch active environment").action(async(J)=>{e8(`env:switch ${J}`,'ts-cloud has no persistent "active" environment — pass --env <name> to each command.')});for(let J of["clone","promote","sync"])$.command(`env:${J} <source> <target>`,`(${J}) environment configuration`).action(async(Y,Z)=>{e8(`env:${J} ${Y} ${Z}`,`Copy the \`environments.${Y}\` block to \`environments.${Z}\` in cloud.config, then \`cloud deploy:serverless --env ${Z}\`.`)});$.command("env:preview <branch>","Create preview environment from branch").action(async(J)=>{e8(`env:preview ${J}`,"Ephemeral preview environments are not implemented. Define a dedicated environment and deploy to it.")}),$.command("env:cleanup","Remove stale preview environments").action(async()=>{e8("env:cleanup","Delete unused stacks with `cloud stack:delete <name>` (or via the AWS console).")})}z0();I0();W2();import{existsSync as $q}from"node:fs";function aZ($){$.command("assets:build","Run the configured build hooks for an environment").option("--env <environment>","Environment (production, staging, development)",{default:"production"}).action(async(J)=>{R("Building Assets");try{let Y=await m(),Z=J?.env||"production",G=Y.environments?.[Z]?.app?.build??[];if(!G.length){w(`No build hooks defined for '${Z}'. Set environments.${Z}.app.build = ['bun run build', …] in cloud.config.`),process.exitCode=1;return}let{execSync:W}=await import("node:child_process");for(let z of G)n(`$ ${z}`),W(z,{stdio:"inherit"});h("Build hooks complete")}catch(Y){w(`Build failed: ${Y.message}`),process.exitCode=1}});for(let J of["assets:optimize:images","images:optimize"])$.command(J,"Optimize images (not implemented)").option("--dir <directory>","Directory to optimize").action(async()=>{w(`'${J}' is not implemented — ts-cloud has no built-in image optimizer.`),X("Optimize images in your own build step (e.g. sharp/squoosh), then `cloud assets:deploy`."),process.exitCode=1});$.command("assets:deploy","Deploy static assets to S3").option("--source <path>","Source directory",{default:"dist"}).option("--bucket <name>","S3 bucket name").option("--prefix <prefix>","S3 prefix/folder").option("--delete","Delete files not in source").option("--cache-control <value>","Cache-Control header",{default:"public, max-age=31536000"}).action(async(J)=>{R("Deploying Assets to S3");try{let Z=(await m()).project.region||"us-east-1",Q=J?.source||"dist",G=J?.bucket,W=J?.prefix,z=J?.delete||!1,U=J?.cacheControl||"public, max-age=31536000";if(!G){w("--bucket is required");return}if(!$q(Q)){w(`Source directory not found: ${Q}`);return}if(X(`Source: ${Q}`),X(`Bucket: s3://${G}${W?`/${W}`:""}`),X(`Cache-Control: ${U}`),z)v("Delete mode enabled - files not in source will be removed");if(!await g(`
|
|
8022
8022
|
Deploy assets now?`,!0)){X("Deployment cancelled");return}let F=new W0(Z),B=new N("Uploading assets to S3...");B.start(),await F.sync({source:Q,bucket:G,prefix:W,delete:z,cacheControl:U,acl:"public-read"}),B.succeed("Assets deployed successfully!");let O=(await F.getBucketSize(G,W)/1024/1024).toFixed(2);h(`
|
|
8023
8023
|
Deployment complete!`),X(`Total size: ${O} MB`),X(`
|
|
@@ -8032,7 +8032,7 @@ This will revoke all access for this team member`),!await g("Remove this team me
|
|
|
8032
8032
|
Team member removed!`),X("All access credentials have been revoked")})}z0();import{existsSync as C1,writeFileSync as J3,copyFileSync as S9,readFileSync as JG,mkdirSync as Y3}from"node:fs";import{dirname as Z3}from"node:path";L1();I0();W2();e6();Y0();class H7{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeServices($){let J={cluster:$.cluster,services:$.services};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listServices($){let J={cluster:$};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListServices","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listTasks($,J){let Y={cluster:$};if(J)Y.serviceName=J;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async describeTasks($,J){let Y={cluster:$,tasks:J};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTasks","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(Y)})}async updateService($){let J={cluster:$.cluster,service:$.service};if($.forceNewDeployment!==void 0)J.forceNewDeployment=$.forceNewDeployment;if($.desiredCount!==void 0)J.desiredCount=$.desiredCount;if($.taskDefinition)J.taskDefinition=$.taskDefinition;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.UpdateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async createService($){let J={cluster:$.cluster,serviceName:$.serviceName,taskDefinition:$.taskDefinition,desiredCount:$.desiredCount};if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.loadBalancers)J.loadBalancers=$.loadBalancers;if($.healthCheckGracePeriodSeconds!==void 0)J.healthCheckGracePeriodSeconds=$.healthCheckGracePeriodSeconds;if($.deploymentConfiguration)J.deploymentConfiguration=$.deploymentConfiguration;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.CreateService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async deleteService($){let J={cluster:$.cluster,service:$.service};if($.force!==void 0)J.force=$.force;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeleteService","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async listClusters(){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({})})}async describeClusters($){let J={clusters:$,include:["ATTACHMENTS","CONFIGURATIONS","SETTINGS","STATISTICS","TAGS"]};return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeClusters","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async stopTask($){let J={cluster:$.cluster,task:$.task};if($.reason)J.reason=$.reason;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.StopTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async runTask($){let J={cluster:$.cluster,taskDefinition:$.taskDefinition};if($.count!==void 0)J.count=$.count;if($.launchType)J.launchType=$.launchType;if($.networkConfiguration)J.networkConfiguration=$.networkConfiguration;if($.overrides)J.overrides=$.overrides;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RunTask","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async registerTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.RegisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify($)})}async deregisterTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$})})}async describeTaskDefinition($){return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({taskDefinition:$,include:["TAGS"]})})}async listTaskDefinitionFamilies($){let J={};if($?.familyPrefix)J.familyPrefix=$.familyPrefix;if($?.status)J.status=$.status;return await this.client.request({service:"ecs",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AmazonEC2ContainerServiceV20141113.ListTaskDefinitionFamilies","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})}async waitForServiceStable($,J,Y=40,Z=15000){for(let Q=0;Q<Y;Q++){let W=(await this.describeServices({cluster:$,services:[J]})).services?.[0];if(W){let z=W.deployments?.find((U)=>U.status==="PRIMARY");if(z&&z.runningCount===z.desiredCount&&W.deployments?.length===1)return!0}await new Promise((z)=>setTimeout(z,Z))}return!1}async forceNewDeployment($,J){return this.updateService({cluster:$,service:J,forceNewDeployment:!0})}async scaleService($,J,Y){return this.updateService({cluster:$,service:J,desiredCount:Y})}}F7();Y0();import{execSync as YG}from"node:child_process";import{tmpdir as Q3}from"node:os";import{join as G3}from"node:path";Y9();$2();import{existsSync as Jq,readdirSync as Yq,readFileSync as Zq,statSync as Qq}from"node:fs";import{join as Gq,relative as Wq,extname as zq}from"node:path";var Uq=[{name:"AWS Access Key ID",pattern:/(?:^|[^A-Z0-9])((AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16})(?:[^A-Z0-9]|$)/g,severity:"critical",description:"AWS Access Key ID detected"},{name:"AWS Secret Access Key",pattern:/(?:aws_secret_access_key|aws_secret_key|secret_access_key|secretAccessKey)\s*[=:]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,severity:"critical",description:"AWS Secret Access Key detected"},{name:"AWS Secret Key (Generic)",pattern:/(?:^|['"`:=\s])([A-Za-z0-9/+=]{40})(?:['"`\s]|$)/g,severity:"high",description:"Potential AWS Secret Key (40-char base64)"},{name:"Generic API Key",pattern:/(?:api[_-]?key|apikey|api[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9_\-]{20,})['"]?/gi,severity:"high",description:"Generic API key detected"},{name:"RSA Private Key",pattern:/-----BEGIN RSA PRIVATE KEY-----/g,severity:"critical",description:"RSA private key detected"},{name:"OpenSSH Private Key",pattern:/-----BEGIN OPENSSH PRIVATE KEY-----/g,severity:"critical",description:"OpenSSH private key detected"},{name:"EC Private Key",pattern:/-----BEGIN EC PRIVATE KEY-----/g,severity:"critical",description:"EC private key detected"},{name:"PGP Private Key",pattern:/-----BEGIN PGP PRIVATE KEY BLOCK-----/g,severity:"critical",description:"PGP private key detected"},{name:"GitHub Token",pattern:/(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/g,severity:"critical",description:"GitHub personal access token detected"},{name:"GitHub OAuth",pattern:/github[_-]?oauth[_-]?token\s*[=:]\s*['"]?([A-Za-z0-9_]{40})['"]?/gi,severity:"critical",description:"GitHub OAuth token detected"},{name:"Slack Token",pattern:/xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/g,severity:"critical",description:"Slack token detected"},{name:"Slack Webhook",pattern:/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+/g,severity:"high",description:"Slack webhook URL detected"},{name:"Discord Webhook",pattern:/https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+/g,severity:"high",description:"Discord webhook URL detected"},{name:"JWT Token",pattern:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,severity:"high",description:"JWT token detected"},{name:"Google API Key",pattern:/AIza[0-9A-Za-z_-]{35}/g,severity:"critical",description:"Google API key detected"},{name:"Google OAuth ID",pattern:/[0-9]+-[A-Za-z0-9_]{32}\.apps\.googleusercontent\.com/g,severity:"high",description:"Google OAuth client ID detected"},{name:"Firebase API Key",pattern:/(?:firebase[_-]?api[_-]?key)\s*[=:]\s*['"]?([A-Za-z0-9_-]{39})['"]?/gi,severity:"critical",description:"Firebase API key detected"},{name:"Cloudflare API Token",pattern:/(?:cloudflare[_-]?api[_-]?token|cf[_-]?api[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{40})['"]?/gi,severity:"critical",description:"Cloudflare API token detected"},{name:"Azure Client Secret",pattern:/(?:azure[_-]?client[_-]?secret|client[_-]?secret)\s*[=:]\s*['"]?([A-Za-z0-9~._-]{34,})['"]?/gi,severity:"critical",description:"Azure client secret detected"},{name:"Heroku API Key",pattern:/(?:heroku[_-]?api[_-]?key)\s*[=:]\s*['"]?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]?/gi,severity:"critical",description:"Heroku API key detected"},{name:"Database Connection String",pattern:/(?:mysql|postgres|postgresql|mongodb|redis|mongodb\+srv):\/\/[^:]+:[^@]+@[^/\s]+/gi,severity:"critical",description:"Database connection string with credentials detected"},{name:"Database Password",pattern:/(?:db[_-]?password|database[_-]?password|mysql[_-]?password|postgres[_-]?password)\s*[=:]\s*['"]?([^'"\s]{8,})['"]?/gi,severity:"critical",description:"Database password detected"},{name:"Stripe API Key",pattern:/(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}/g,severity:"critical",description:"Stripe API key detected"},{name:"PayPal Client ID",pattern:/(?:paypal[_-]?client[_-]?id)\s*[=:]\s*['"]?([A-Za-z0-9_-]{80})['"]?/gi,severity:"high",description:"PayPal client ID detected"},{name:"Square Access Token",pattern:/sq0[a-z]{3}-[0-9A-Za-z_-]{22,}/g,severity:"critical",description:"Square access token detected"},{name:"Twilio API Key",pattern:/SK[a-f0-9]{32}/g,severity:"critical",description:"Twilio API key detected"},{name:"SendGrid API Key",pattern:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g,severity:"critical",description:"SendGrid API key detected"},{name:"Mailgun API Key",pattern:/key-[0-9a-zA-Z]{32}/g,severity:"critical",description:"Mailgun API key detected"},{name:"Password in Code",pattern:/(?:password|passwd|pwd)\s*[=:]\s*['"]([^'"]{8,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded password detected"},{name:"Secret/Token Assignment",pattern:/(?:secret|token|auth[_-]?token|access[_-]?token)\s*[=:]\s*['"]([A-Za-z0-9_\-/+=]{16,})['"](?!\s*[,\]])/gi,severity:"high",description:"Hardcoded secret or token detected"},{name:"NPM Token",pattern:/(?:npm[_-]?token)\s*[=:]\s*['"]?([A-Za-z0-9_-]{36})['"]?/gi,severity:"critical",description:"NPM token detected"},{name:"SSH Private Key Path Exposed",pattern:/~\/\.ssh\/id_[a-z]+|\/home\/[^/]+\/\.ssh\/id_[a-z]+/g,severity:"medium",description:"SSH private key path exposed"},{name:"Env Variable with Secret",pattern:/(?:process\.env\.)((?=[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|CREDENTIAL|AUTH))[A-Z_]+)\s*(?:===?\s*['"]([^'"]+)['"])?/g,severity:"medium",description:"Environment variable containing secret may be exposed"}],Hq=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".vue",".svelte",".html",".htm",".css",".scss",".less",".json",".yaml",".yml",".toml",".xml",".env",".config",".conf"],Fq=["node_modules",".git",".svn",".hg","dist","build","coverage",".nyc_output","__pycache__",".pytest_cache","vendor",".idea",".vscode",".turbo",".next",".nuxt","pantry",".pantry","tests","test","__tests__","spec","__mocks__",".github",".gitlab",".circleci"],Xq=["package-lock.json","yarn.lock","pnpm-lock.yaml","bun.lockb","bun.lock","*.min.js","*.min.css","*.map","*.d.ts","*.test.ts","*.test.js","*.spec.ts","*.spec.js",".env",".env.*"];class YQ{patterns;excludeDirs;excludeFiles;maxFileSize;constructor($){this.patterns=[...Uq,...$?.customPatterns||[]],this.excludeDirs=[...Fq,...$?.excludeDirs||[]],this.excludeFiles=[...Xq,...$?.excludeFiles||[]],this.maxFileSize=$?.maxFileSize||1048576}async scan($){let J=Date.now(),Y=[],Z=0,{directory:Q,exclude:G=[],include:W,skipPatterns:z=[]}=$,U=$.failOnSeverity||"critical";if(!Jq(Q))throw Error(`Directory not found: ${Q}`);let H=this.getFilesToScan(Q,[...this.excludeDirs,...G],W);for(let V of H){let A=Wq(Q,V);if(this.shouldExcludeFile(A))continue;try{if(Qq(V).size>this.maxFileSize)continue;let M=Zq(V,"utf-8"),E=this.scanContent(M,A,z);Y.push(...E),Z++}catch{continue}}let F={critical:Y.filter((V)=>V.pattern.severity==="critical").length,high:Y.filter((V)=>V.pattern.severity==="high").length,medium:Y.filter((V)=>V.pattern.severity==="medium").length,low:Y.filter((V)=>V.pattern.severity==="low").length},B=["low","medium","high","critical"],K=B.indexOf(U),O=!0;for(let V=K;V<B.length;V++)if(F[B[V]]>0){O=!1;break}return{passed:O,findings:Y,scannedFiles:Z,duration:Date.now()-J,summary:F}}scanContent($,J,Y){let Z=[],Q=$.split(`
|
|
8033
8033
|
`);for(let G of this.patterns){if(Y.includes(G.name))continue;G.pattern.lastIndex=0;let W;while((W=G.pattern.exec($))!==null){let z=$.substring(0,W.index),U=z.split(`
|
|
8034
8034
|
`).length,H=z.lastIndexOf(`
|
|
8035
|
-
`),F=W.index-H,B=Q[U-1]||"";if(this.isLikelyPlaceholder(W[0],B))continue;if(this.isLowEntropy(W[1]||W[0]))continue;Z.push({file:J,line:U,column:F,match:this.maskSecret(W[0]),pattern:G,context:this.maskSecret(B.trim())})}}return Z}isLikelyPlaceholder($,J){let Y=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],Z=$.toLowerCase(),Q=J.toLowerCase();for(let W of Y)if(Z.includes(W.toLowerCase())||Q.includes(W.toLowerCase()))return!0;let G=J.trim();if(G.startsWith("//")||G.startsWith("#")||G.startsWith("*")||G.startsWith("/*")){if(Q.includes("example")||Q.includes("format:")||Q.includes("e.g."))return!0}return!1}isLowEntropy($){if($.length<8)return!1;if(new Set($).size<8)return!0;if(/(.)\1{3,}/.test($))return!0;return!1}maskSecret($){if($.length<=8)return"*".repeat($.length);let J=Math.min(4,Math.floor($.length*0.2));return $.substring(0,J)+"*".repeat($.length-J*2)+$.substring($.length-J)}getFilesToScan($,J,Y){let Z=[],Q=Y||Hq,G=(W)=>{let z=Yq(W,{withFileTypes:!0});for(let U of z){let H=Gq(W,U.name);if(U.isDirectory()){if(!J.includes(U.name))G(H)}else if(U.isFile()){let F=zq(U.name).toLowerCase();if(Q.includes(F)||U.name.startsWith(".env")||U.name.endsWith(".config"))Z.push(H)}}};return G($),Z}shouldExcludeFile($){let J=$.split("/").pop()||"";for(let Y of this.excludeFiles)if(Y.startsWith("*")){let Z=Y.substring(1);if(J.endsWith(Z))return!0}else if(Y.endsWith("*")){let Z=Y.substring(0,Y.length-1);if(J.startsWith(Z))return!0}else if(J===Y)return!0;return!1}addPattern($){this.patterns.push($)}getPatterns(){return[...this.patterns]}}W2();z0();function Bq($){if(!$)return[];if(Array.isArray($))return $.map(String);let J=$,Y=J.Items??J.Item;if(!Y)return[];if(Array.isArray(Y))return Y.map(String);if(typeof Y==="object"&&Y!==null){let Z=Y;if("Item"in Z){let Q=Z.Item;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}if("CNAME"in Z){let Q=Z.CNAME;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}return Object.values(Z).flatMap((Q)=>{if(Array.isArray(Q))return Q.map(String);return typeof Q==="string"?[Q]:[]})}return[String(Y)]}async function O7($){if($.length===0)return;let J=new w0,Y=await J.listDistributions(),Z=[...new Set($.map((Q)=>Q.toLowerCase()))];for(let Q of Z){let G=Y.find((z)=>{return Bq(z.Aliases).some((H)=>H.toLowerCase()===Q)});if(!G?.Id){v(`No CloudFront distribution found for ${Q} — skipping dynamic HTTP method sync`);continue}if(await J.ensureDynamicHttpMethods(G.Id))h(`CloudFront ${G.Id} (${Q}): enabled POST/PUT/PATCH/DELETE on dynamic paths`);else X(`CloudFront ${G.Id} (${Q}): already allows dynamic HTTP methods`)}}await z8([n0(),
|
|
8035
|
+
`),F=W.index-H,B=Q[U-1]||"";if(this.isLikelyPlaceholder(W[0],B))continue;if(this.isLowEntropy(W[1]||W[0]))continue;Z.push({file:J,line:U,column:F,match:this.maskSecret(W[0]),pattern:G,context:this.maskSecret(B.trim())})}}return Z}isLikelyPlaceholder($,J){let Y=["example","placeholder","your_","YOUR_","xxx","XXX","***","test","TEST","dummy","DUMMY","fake","FAKE","sample","SAMPLE","<your","${","{{","process.env","import.meta.env","CHANGEME","TODO","FIXME"],Z=$.toLowerCase(),Q=J.toLowerCase();for(let W of Y)if(Z.includes(W.toLowerCase())||Q.includes(W.toLowerCase()))return!0;let G=J.trim();if(G.startsWith("//")||G.startsWith("#")||G.startsWith("*")||G.startsWith("/*")){if(Q.includes("example")||Q.includes("format:")||Q.includes("e.g."))return!0}return!1}isLowEntropy($){if($.length<8)return!1;if(new Set($).size<8)return!0;if(/(.)\1{3,}/.test($))return!0;return!1}maskSecret($){if($.length<=8)return"*".repeat($.length);let J=Math.min(4,Math.floor($.length*0.2));return $.substring(0,J)+"*".repeat($.length-J*2)+$.substring($.length-J)}getFilesToScan($,J,Y){let Z=[],Q=Y||Hq,G=(W)=>{let z=Yq(W,{withFileTypes:!0});for(let U of z){let H=Gq(W,U.name);if(U.isDirectory()){if(!J.includes(U.name))G(H)}else if(U.isFile()){let F=zq(U.name).toLowerCase();if(Q.includes(F)||U.name.startsWith(".env")||U.name.endsWith(".config"))Z.push(H)}}};return G($),Z}shouldExcludeFile($){let J=$.split("/").pop()||"";for(let Y of this.excludeFiles)if(Y.startsWith("*")){let Z=Y.substring(1);if(J.endsWith(Z))return!0}else if(Y.endsWith("*")){let Z=Y.substring(0,Y.length-1);if(J.startsWith(Z))return!0}else if(J===Y)return!0;return!1}addPattern($){this.patterns.push($)}getPatterns(){return[...this.patterns]}}W2();z0();function Bq($){if(!$)return[];if(Array.isArray($))return $.map(String);let J=$,Y=J.Items??J.Item;if(!Y)return[];if(Array.isArray(Y))return Y.map(String);if(typeof Y==="object"&&Y!==null){let Z=Y;if("Item"in Z){let Q=Z.Item;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}if("CNAME"in Z){let Q=Z.CNAME;if(!Q)return[];return Array.isArray(Q)?Q.map(String):[String(Q)]}return Object.values(Z).flatMap((Q)=>{if(Array.isArray(Q))return Q.map(String);return typeof Q==="string"?[Q]:[]})}return[String(Y)]}async function O7($){if($.length===0)return;let J=new w0,Y=await J.listDistributions(),Z=[...new Set($.map((Q)=>Q.toLowerCase()))];for(let Q of Z){let G=Y.find((z)=>{return Bq(z.Aliases).some((H)=>H.toLowerCase()===Q)});if(!G?.Id){v(`No CloudFront distribution found for ${Q} — skipping dynamic HTTP method sync`);continue}if(await J.ensureDynamicHttpMethods(G.Id))h(`CloudFront ${G.Id} (${Q}): enabled POST/PUT/PATCH/DELETE on dynamic paths`);else X(`CloudFront ${G.Id} (${Q}): already allows dynamic HTTP methods`)}}await z8([n0(),j$(),gQ()]);import{execSync as qT}from"node:child_process";async function TT($,J,Y,Z={},Q=process.cwd()){if(!$)return;if(Z.step?.(`Running ${Y} hook`),typeof $==="string"){qT($,{stdio:"inherit",cwd:Q});return}await $(J)}async function T9($,J,Y={},Z){try{return await TT($.hooks?.[J],$,J,Y,Z),!0}catch(Q){return Y.error?.(`${J} hook failed: ${Q?.message||Q}`),!1}}K$();async function W3($){let J=_5();if(J.emptyEnvKey||J.emptyEnvSecret)v("Empty AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY env var detected — likely a misconfigured .env file. Remove the empty lines or fill them in.");X(`AWS credentials: ${J.description}`);try{let Z=await new $9($).getCallerIdentity();if(Z.Arn)X(`AWS identity: ${Z.Arn}`)}catch(Y){v(`Could not verify AWS identity: ${Y.message}`)}}function z3(){try{return YG("git rev-parse --short HEAD",{stdio:["ignore","pipe","ignore"]}).toString().trim()}catch{return Date.now().toString(36)}}async function $G($,J,Y){let{ensureManagementDashboard:Z}=await d7().then(() => lH);Z($,{logger:{info:X,warn:v}});let Q=$.sites||{},G=Object.entries(Q);if(G.length===0)return v("infrastructure.compute is set but no sites are configured — nothing to deploy. Add sites to `cloud.config.ts`."),!0;let W=G.filter(([A,_])=>{if(!_)return!1;if(p0(_)==="bucket")return v(`Site '${A}' targets a bucket — skipping compute deploy (handled by the static-site path).`),!1;return!0});if(W.length===0)return!0;let z=$.project.slug,H=($.infrastructure?.compute||{}).runtime||"bun",F=Y1({config:$}),B=z3(),K=new Map,O={step:(A)=>n(A),error:(A)=>w(A)};if(!await T9($,"beforeDeploy",O))return!0;if(!await T9($,"beforeBuild",O))return!0;for(let[A,_]of W){let M=p0(_);if(R(`Preparing site: ${A}`),X(`Domain: ${_.domain||"(none)"}`),X(`Source: ${_.root}`),X(`Kind: ${M==="server-static"?"static (shipped to /var/www)":"app (systemd service)"}`),M==="server-app")X(`Start: ${_.start}`),X(`Port: ${_.port??"(unset)"}`);if(_.build){n(`Running build: ${_.build}`);try{YG(_.build,{stdio:"inherit",cwd:process.cwd()})}catch(j){return w(`Build failed for site '${A}': ${j.message}`),!0}}if(!C1(_.root))return w(`Build output not found at ${_.root} for site '${A}'`),!0;let E=G3(Q3(),`${z}-${A}-${B}.tar.gz`);n(`Packaging ${_.root} → ${E}`);try{let j=(_.exclude||[]).map((q)=>`--exclude='${q}'`).join(" ");YG(`tar czf "${E}" -C "${_.root}" ${j} .`,{stdio:"inherit"})}catch(j){return w(`Failed to package '${A}': ${j.message}`),!0}K.set(A,E)}if(!await T9($,"afterBuild",O))return!0;let V=await p7({config:$,environment:J,driver:F,sha:B,runtime:H,tarballForSite:(A)=>{let _=K.get(A);if(!_)throw Error(`Missing tarball for site '${A}'`);return _},logger:{info:(A)=>X(A),warn:(A)=>v(A),error:(A)=>w(A),step:(A)=>n(A),success:(A)=>h(A)}});if(V)await T9($,"afterDeploy",O);return V}async function t7($){let J=new YQ;n("Running pre-deployment security scan...");let Y=await J.scan({directory:$.sourceDir,failOnSeverity:$.failOnSeverity||"critical",skipPatterns:$.skipPatterns});return{passed:Y.passed,result:Y}}function s7($){let{summary:J,findings:Y,scannedFiles:Z,duration:Q}=$;if(X(`
|
|
8036
8036
|
Scanned ${Z} files in ${Q}ms`),J.critical>0)w(` Critical: ${J.critical}`);else X(` Critical: ${J.critical}`);if(J.high>0)v(` High: ${J.high}`);else X(` High: ${J.high}`);if(X(` Medium: ${J.medium}`),X(` Low: ${J.low}`),Y.length>0){X(`
|
|
8037
8037
|
Findings:`);let G=Y.filter((F)=>F.pattern.severity==="critical"),W=Y.filter((F)=>F.pattern.severity==="high"),z=Y.filter((F)=>F.pattern.severity==="medium"),U=Y.filter((F)=>F.pattern.severity==="low"),H=(F,B,K)=>{if(F.length>0){console.log(`
|
|
8038
8038
|
${k2(`[${B}]`,K)}`);for(let O of F.slice(0,10))X(` ${O.pattern.name}`),X(` File: ${O.file}:${O.line}`),X(` Match: ${O.match}`);if(F.length>10)X(` ... and ${F.length-10} more ${B.toLowerCase()} findings`)}};H(G,"CRITICAL","red"),H(W,"HIGH","yellow"),H(z,"MEDIUM","blue"),H(U,"LOW","gray")}}function ZG($){$.command("deploy:security-scan","Run pre-deployment security scan").option("--source <path>","Source directory to scan",{default:"."}).option("--fail-on <severity>","Fail on severity level (critical, high, medium, low)",{default:"critical"}).option("--skip-patterns <patterns>","Comma-separated list of pattern names to skip").action(async(J)=>{R("Pre-Deployment Security Scan");try{let Y=J?.source||".",Z=J?.failOn||"critical",Q=J?.skipPatterns?.split(",").map((z)=>z.trim())||[];if(!C1(Y)){w(`Source directory not found: ${Y}`);return}X(`Source: ${Y}`),X(`Fail on: ${Z} or higher severity`);let{passed:G,result:W}=await t7({sourceDir:Y,failOnSeverity:Z,skipPatterns:Q});if(s7(W),G)h(`
|
|
@@ -8105,7 +8105,7 @@ Bucket: ${q.bucket}
|
|
|
8105
8105
|
Files: ${T}${D}
|
|
8106
8106
|
|
|
8107
8107
|
Your site is now live at https://${q.domain}`,"green")}else w(`
|
|
8108
|
-
Deployment failed: ${q.message}`)}}z0();await z8([n0(),
|
|
8108
|
+
Deployment failed: ${q.message}`)}}z0();await z8([n0(),j$()]);function QG($){$.command("destroy","Destroy the single-server compute (instance + firewall)").option("--env <env>","Environment",{default:"production"}).option("--force","Skip the confirmation prompt").action(async(J)=>{R("Destroy Compute");let Y=await m(),Z=J?.env||"production",Q=M2(Y),G=Y1({config:Y,provider:Q});if(!G.destroyCompute){w(`The ${Q} driver does not support compute teardown`);return}if(v(`This terminates the ${Q} server for ${Y.project.slug}/${Z} and deletes its firewall.`),!J?.force){if(!await g("This is irreversible. Continue?",!1)){X("Cancelled");return}}let W=new N("Destroying compute...");W.start();try{let{destroyed:z}=await G.destroyCompute({config:Y,environment:Z});if(W.succeed("Compute destroyed"),z.length>0)z.forEach((U)=>X(` removed ${U}`));else X("Nothing to destroy (no matching resources found)")}catch(z){W.fail("Teardown failed"),w(z instanceof Error?z.message:String(z))}})}z0();L1();import{writeFileSync as F3,statSync as X3}from"node:fs";function GG($){$.command("stack:list","List all CloudFormation stacks").action(async()=>{R("CloudFormation Stacks");try{let Y=(await m()).project.region||"us-east-1",Z=new K0(Y),Q=new N("Loading stacks...");Q.start();let G=await Z.listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS"]);if(Q.succeed(`Found ${G.StackSummaries.length} stacks`),G.StackSummaries.length===0){X("No stacks found");return}let W=["Stack Name","Status","Created","Updated"],z=G.StackSummaries.map((U)=>[U.StackName,U.StackStatus,new Date(U.CreationTime).toLocaleString(),U.LastUpdatedTime?new Date(U.LastUpdatedTime).toLocaleString():"Never"]);p(W,z)}catch(J){w(`Failed to list stacks: ${J.message}`)}}),$.command("stack:describe STACK_NAME","Describe a CloudFormation stack").action(async(J)=>{R(`Stack: ${J}`);try{let Z=(await m()).project.region||"us-east-1",Q=new K0(Z),G=new N("Loading stack details...");G.start();let W=await Q.describeStacks({stackName:J});if(!W.Stacks||W.Stacks.length===0){G.fail("Stack not found");return}let z=W.Stacks[0];if(G.succeed("Stack details loaded"),X(`
|
|
8109
8109
|
Stack Information:`),X(` - Name: ${z.StackName}`),X(` - Status: ${z.StackStatus}`),X(` - Created: ${new Date(z.CreationTime).toLocaleString()}`),z.LastUpdatedTime)X(` - Updated: ${new Date(z.LastUpdatedTime).toLocaleString()}`);if(z.Parameters&&z.Parameters.length>0){X(`
|
|
8110
8110
|
Parameters:`);for(let H of z.Parameters)X(` - ${H.ParameterKey}: ${H.ParameterValue}`)}if(z.Outputs&&z.Outputs.length>0){X(`
|
|
8111
8111
|
Outputs:`);for(let H of z.Outputs)if(X(` - ${H.OutputKey}: ${H.OutputValue}`),H.Description)X(` ${H.Description}`)}if(z.Tags&&z.Tags.length>0){X(`
|
|
@@ -8123,15 +8123,15 @@ What's new in v0.2.0:`),X(" - New cost optimization commands"),X(" - Improved
|
|
|
8123
8123
|
Creating site: ${Z}`),X(`Domains: ${Q.join(", ")}`),!await g(`
|
|
8124
8124
|
Create this site?`,!0)){X("Operation cancelled");return}let W=new N("Creating site...");W.start();let z=`site_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,U=new Date().toISOString();await Y.putItem({TableName:J.table,Item:{pk:{S:`SITE#${z}`},sk:{S:`SITE#${z}`},siteId:{S:z},name:{S:Z},domains:{L:Q.map((H)=>({S:H}))},isActive:{BOOL:!0},createdAt:{S:U},updatedAt:{S:U}}}),W.succeed("Site created successfully"),h(`
|
|
8125
8125
|
Site ID: ${z}`),X(`
|
|
8126
|
-
Add the tracking script to your website:`),X(` <script src="https://analytics.stacksjs.com/track.js" data-site-id="${z}"></script>`)}catch(Y){w(`Failed to create site: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:update <siteId>","Update an analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","New site name").option("--domain <domain>","Set domains (replaces existing)").option("--active <boolean>","Set site active/inactive status").action(async(J,Y)=>{R("Update Analytics Site");try{let Z=new a0(Y.region),Q=await Z.getItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}}});if(!Q.Item)w(`Site not found: ${J}`),process.exit(1);let G=a0.unmarshal(Q.Item);X(`Updating site: ${G.name||"Unnamed"} (${J})`),X("");let W=[],z={},U={};if(Y.name)W.push("#n = :name"),z["#n"]="name",U[":name"]={S:Y.name},X(` Name: ${G.name} -> ${Y.name}`);if(Y.domain!==void 0){let H=Array.isArray(Y.domain)?Y.domain:[Y.domain];W.push("domains = :domains"),U[":domains"]={L:H.map((F)=>({S:F}))},X(` Domains: ${JSON.stringify(G.domains||[])} -> ${JSON.stringify(H)}`)}if(Y.active!==void 0){let H=Y.active==="true"||Y.active==="1";W.push("isActive = :active"),U[":active"]={BOOL:H},X(` Active: ${G.isActive} -> ${H}`)}if(W.length===0){v("No updates specified. Use --name, --domain, or --active options.");return}W.push("updatedAt = :updatedAt"),U[":updatedAt"]={S:new Date().toISOString()},await Z.updateItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}},UpdateExpression:`SET ${W.join(", ")}`,ExpressionAttributeNames:Object.keys(z).length>0?z:void 0,ExpressionAttributeValues:U}),X(""),h("Site updated successfully")}catch(Z){w(`Failed to update site: ${Z.message}`),process.exit(1)}}),$.command("analytics:query <siteId>","Query analytics data for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--limit <n>","Max items to return",{default:"10"}).option("--type <type>","Filter by type (pageview, event, etc.)").action(async(J,Y)=>{R(`Analytics Data: ${J}`);try{let Z=new a0(Y.region),Q=new N("Querying data...");Q.start();let G=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`}},ScanIndexForward:!1,Limit:parseInt(Y.limit,10)});if(Q.succeed(`Found ${G.Items?.length||0} items`),!G.Items||G.Items.length===0){X("No data found for this site");return}let W=G.Items.map((z)=>a0.unmarshal(z));for(let z of W){if(X(""),X(`SK: ${z.sk}`),z.path)X(` Path: ${z.path}`);if(z.timestamp)X(` Time: ${z.timestamp}`);if(z.visitorId)X(` Visitor: ${z.visitorId}`);if(z.browser)X(` Browser: ${z.browser}`);if(z.country)X(` Country: ${z.country}`)}}catch(Z){w(`Failed to query data: ${Z.message}`),process.exit(1)}}),$.command("analytics:realtime <siteId>","Check realtime visitors for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--minutes <n>","Minutes to look back",{default:"5"}).action(async(J,Y)=>{R(`Realtime: ${J}`);try{let Z=new a0(Y.region),Q=new N("Checking realtime...");Q.start();let G=parseInt(Y.minutes,10),W=new Date(Date.now()-G*60*1000),z=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk AND sk BETWEEN :start AND :end",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`},":start":{S:`PAGEVIEW#${W.toISOString()}`},":end":{S:"PAGEVIEW#Z"}},ScanIndexForward:!1});if(Q.succeed(`Found ${z.Items?.length||0} pageviews in last ${G} minutes`),!z.Items||z.Items.length===0){v("No recent pageviews found"),X(""),X("Possible issues:"),X(" 1. Tracking script not installed correctly"),X(" 2. Site ID mismatch"),X(" 3. CORS or network issues");return}let U=z.Items.map((B)=>a0.unmarshal(B)),H=new Set(U.map((B)=>B.visitorId)).size;X(""),h(`${H} unique visitor(s) online`),X("");let F={};for(let B of U){let K=B.path||"/";F[K]=(F[K]||0)+1}X("Active pages:");for(let[B,K]of Object.entries(F).sort((O,V)=>V[1]-O[1]).slice(0,5))X(` ${B}: ${K} view(s)`);X(""),X("Recent pageviews:");for(let B of U.slice(0,5))X(` ${B.timestamp} - ${B.path} (${B.browser||"Unknown"})`)}catch(Z){w(`Failed to check realtime: ${Z.message}`),process.exit(1)}})}z0();import{existsSync as
|
|
8127
|
-
`)){let Q=Z.trim();if(Q.startsWith("DB="))J.push(Q.slice(3));else if(Q.startsWith("USER="))Y.push(Q.slice(5))}return{databases:[...new Set(J)].filter(Boolean).sort(),users:[...new Set(Y)].filter(Boolean).sort()}}async function BG($,J,Y,Z){let Q;try{Q=Y1({config:$})}catch(U){return{ok:!1,error:`Could not initialize the cloud driver: ${U?.message??U}`}}let G=$.project.slug,W=await Q.findComputeTargets({slug:G,environment:J,role:"app"});if(!W.length)return{ok:!1,error:"No app server target was found for this environment."};let z=await Q.runRemoteDeploy({targets:[W[0]],commands:["set -uo pipefail",...Y],comment:Z,tags:{Project:G,Environment:J,Role:"app"}});return{ok:z.success,stdout:z.perInstance?.[0]?.output??"",stderr:z.perInstance?.[0]?.error??z.error??""}}async function pF($,J){let Y=HG($),Z=await BG($,J,O3(Y),"ts-cloud db:list"),Q=Z.ok&&Z.stdout?_3(Z.stdout):{databases:[],users:[]};return{...Z,engine:Y,...Q}}async function rF($,J,Y){let Z=HG($);return BG($,J,A3(Z,Y),`ts-cloud db:create ${Y}`)}async function nF($,J,Y){let Z=HG($);return BG($,J,V3(Z,Y),`ts-cloud db:user ${Y.username}`)}J8();z2();
|
|
8126
|
+
Add the tracking script to your website:`),X(` <script src="https://analytics.stacksjs.com/track.js" data-site-id="${z}"></script>`)}catch(Y){w(`Failed to create site: ${Y.message}`),process.exit(1)}}),$.command("analytics:sites:update <siteId>","Update an analytics site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--name <name>","New site name").option("--domain <domain>","Set domains (replaces existing)").option("--active <boolean>","Set site active/inactive status").action(async(J,Y)=>{R("Update Analytics Site");try{let Z=new a0(Y.region),Q=await Z.getItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}}});if(!Q.Item)w(`Site not found: ${J}`),process.exit(1);let G=a0.unmarshal(Q.Item);X(`Updating site: ${G.name||"Unnamed"} (${J})`),X("");let W=[],z={},U={};if(Y.name)W.push("#n = :name"),z["#n"]="name",U[":name"]={S:Y.name},X(` Name: ${G.name} -> ${Y.name}`);if(Y.domain!==void 0){let H=Array.isArray(Y.domain)?Y.domain:[Y.domain];W.push("domains = :domains"),U[":domains"]={L:H.map((F)=>({S:F}))},X(` Domains: ${JSON.stringify(G.domains||[])} -> ${JSON.stringify(H)}`)}if(Y.active!==void 0){let H=Y.active==="true"||Y.active==="1";W.push("isActive = :active"),U[":active"]={BOOL:H},X(` Active: ${G.isActive} -> ${H}`)}if(W.length===0){v("No updates specified. Use --name, --domain, or --active options.");return}W.push("updatedAt = :updatedAt"),U[":updatedAt"]={S:new Date().toISOString()},await Z.updateItem({TableName:Y.table,Key:{pk:{S:`SITE#${J}`},sk:{S:`SITE#${J}`}},UpdateExpression:`SET ${W.join(", ")}`,ExpressionAttributeNames:Object.keys(z).length>0?z:void 0,ExpressionAttributeValues:U}),X(""),h("Site updated successfully")}catch(Z){w(`Failed to update site: ${Z.message}`),process.exit(1)}}),$.command("analytics:query <siteId>","Query analytics data for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--limit <n>","Max items to return",{default:"10"}).option("--type <type>","Filter by type (pageview, event, etc.)").action(async(J,Y)=>{R(`Analytics Data: ${J}`);try{let Z=new a0(Y.region),Q=new N("Querying data...");Q.start();let G=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`}},ScanIndexForward:!1,Limit:parseInt(Y.limit,10)});if(Q.succeed(`Found ${G.Items?.length||0} items`),!G.Items||G.Items.length===0){X("No data found for this site");return}let W=G.Items.map((z)=>a0.unmarshal(z));for(let z of W){if(X(""),X(`SK: ${z.sk}`),z.path)X(` Path: ${z.path}`);if(z.timestamp)X(` Time: ${z.timestamp}`);if(z.visitorId)X(` Visitor: ${z.visitorId}`);if(z.browser)X(` Browser: ${z.browser}`);if(z.country)X(` Country: ${z.country}`)}}catch(Z){w(`Failed to query data: ${Z.message}`),process.exit(1)}}),$.command("analytics:realtime <siteId>","Check realtime visitors for a site").option("--table <name>","DynamoDB table name",{default:"ts-analytics"}).option("--region <region>","AWS region",{default:"us-east-1"}).option("--minutes <n>","Minutes to look back",{default:"5"}).action(async(J,Y)=>{R(`Realtime: ${J}`);try{let Z=new a0(Y.region),Q=new N("Checking realtime...");Q.start();let G=parseInt(Y.minutes,10),W=new Date(Date.now()-G*60*1000),z=await Z.query({TableName:Y.table,KeyConditionExpression:"pk = :pk AND sk BETWEEN :start AND :end",ExpressionAttributeValues:{":pk":{S:`SITE#${J}`},":start":{S:`PAGEVIEW#${W.toISOString()}`},":end":{S:"PAGEVIEW#Z"}},ScanIndexForward:!1});if(Q.succeed(`Found ${z.Items?.length||0} pageviews in last ${G} minutes`),!z.Items||z.Items.length===0){v("No recent pageviews found"),X(""),X("Possible issues:"),X(" 1. Tracking script not installed correctly"),X(" 2. Site ID mismatch"),X(" 3. CORS or network issues");return}let U=z.Items.map((B)=>a0.unmarshal(B)),H=new Set(U.map((B)=>B.visitorId)).size;X(""),h(`${H} unique visitor(s) online`),X("");let F={};for(let B of U){let K=B.path||"/";F[K]=(F[K]||0)+1}X("Active pages:");for(let[B,K]of Object.entries(F).sort((O,V)=>V[1]-O[1]).slice(0,5))X(` ${B}: ${K} view(s)`);X(""),X("Recent pageviews:");for(let B of U.slice(0,5))X(` ${B.timestamp} - ${B.path} (${B.browser||"Unknown"})`)}catch(Z){w(`Failed to check realtime: ${Z.message}`),process.exit(1)}})}z0();import{existsSync as n2,statSync as QX}from"node:fs";import{readFile as M$,writeFile as P9}from"node:fs/promises";import{mkdtempSync as w3}from"node:fs";import{tmpdir as D3}from"node:os";import{dirname as R3,extname as VG,join as v0,normalize as N3}from"node:path";import{fileURLToPath as S3}from"node:url";await z8([a7(),eQ()]);await j$();var lF={mysql:"/var/lib/pantry/mysql/mysqld.sock",mariadb:"/var/lib/pantry/mariadb/mariadbd.sock"};function e7($){return/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test($)}function K3($){if($==="postgres"||$==="pgsql")return"postgres";if($==="mariadb")return"mariadb";return"mysql"}function HG($){let J=$.infrastructure?.compute,Y=$.infrastructure?.appDatabase?.engine;if(Y)return K3(Y);let Z=J?.managedServices??{};if(Z.postgres)return"postgres";if(Z.mariadb)return"mariadb";return"mysql"}var UG=($)=>$.replace(/`/g,"``"),H2=($)=>$.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),L$=($)=>`"${$.replace(/"/g,'""')}"`,o7=($)=>`'${$.replace(/'/g,"''")}'`;function FG($,J){return[`mysql --socket=${$==="mariadb"?lF.mariadb:lF.mysql} -u root <<'TS_CLOUD_SQL_EOF'`,...J,"TS_CLOUD_SQL_EOF"]}function XG($){return["psql -h 127.0.0.1 -p 5432 -U postgres -tA <<'TS_CLOUD_PG_EOF'",...$,"TS_CLOUD_PG_EOF"]}function O3($){if($==="postgres")return XG(["SELECT 'DB=' || datname FROM pg_database WHERE datistemplate = false;","SELECT 'USER=' || usename FROM pg_user;"]);return FG($,["SELECT CONCAT('DB=', schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys');","SELECT DISTINCT CONCAT('USER=', User) FROM mysql.user WHERE User NOT IN ('root', 'mysql.sys', 'mysql.session', 'mysql.infoschema', 'debian-sys-maint');"])}function A3($,J){if($==="postgres")return XG([`SELECT 'CREATE DATABASE ${L$(J)}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ${o7(J)})\\gexec`]);return FG($,[`CREATE DATABASE IF NOT EXISTS \`${UG(J)}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`])}function V3($,J){let{username:Y,password:Z,database:Q,access:G}=J;if($==="postgres"){let U=["DO $$ BEGIN",` IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ${o7(Y)}) THEN CREATE ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)};`,` ELSE ALTER ROLE ${L$(Y)} LOGIN PASSWORD ${o7(Z)}; END IF;`,"END $$;"];if(Q)U.push(G==="readonly"?`GRANT CONNECT ON DATABASE ${L$(Q)} TO ${L$(Y)};`:`GRANT ALL PRIVILEGES ON DATABASE ${L$(Q)} TO ${L$(Y)};`);return XG(U)}let W=G==="readonly"?"SELECT":"ALL PRIVILEGES",z=[`CREATE USER IF NOT EXISTS '${H2(Y)}'@'%' IDENTIFIED BY '${H2(Z)}';`,`CREATE USER IF NOT EXISTS '${H2(Y)}'@'localhost' IDENTIFIED BY '${H2(Z)}';`,`ALTER USER '${H2(Y)}'@'%' IDENTIFIED BY '${H2(Z)}';`,`ALTER USER '${H2(Y)}'@'localhost' IDENTIFIED BY '${H2(Z)}';`];if(Q)z.push(`GRANT ${W} ON \`${UG(Q)}\`.* TO '${H2(Y)}'@'%';`,`GRANT ${W} ON \`${UG(Q)}\`.* TO '${H2(Y)}'@'localhost';`);return z.push("FLUSH PRIVILEGES;"),FG($,z)}function _3($){let J=[],Y=[];for(let Z of $.split(`
|
|
8127
|
+
`)){let Q=Z.trim();if(Q.startsWith("DB="))J.push(Q.slice(3));else if(Q.startsWith("USER="))Y.push(Q.slice(5))}return{databases:[...new Set(J)].filter(Boolean).sort(),users:[...new Set(Y)].filter(Boolean).sort()}}async function BG($,J,Y,Z){let Q;try{Q=Y1({config:$})}catch(U){return{ok:!1,error:`Could not initialize the cloud driver: ${U?.message??U}`}}let G=$.project.slug,W=await Q.findComputeTargets({slug:G,environment:J,role:"app"});if(!W.length)return{ok:!1,error:"No app server target was found for this environment."};let z=await Q.runRemoteDeploy({targets:[W[0]],commands:["set -uo pipefail",...Y],comment:Z,tags:{Project:G,Environment:J,Role:"app"}});return{ok:z.success,stdout:z.perInstance?.[0]?.output??"",stderr:z.perInstance?.[0]?.error??z.error??""}}async function pF($,J){let Y=HG($),Z=await BG($,J,O3(Y),"ts-cloud db:list"),Q=Z.ok&&Z.stdout?_3(Z.stdout):{databases:[],users:[]};return{...Z,engine:Y,...Q}}async function rF($,J,Y){let Z=HG($);return BG($,J,A3(Z,Y),`ts-cloud db:create ${Y}`)}async function nF($,J,Y){let Z=HG($);return BG($,J,V3(Z,Y),`ts-cloud db:user ${Y.username}`)}J8();z2();K$();await j$();var j3=["restart","reload","start","stop","enable","disable"],iF=65536;function $5($){return $.length<=iF?$:`${$.slice(0,iF)}
|
|
8128
8128
|
|
|
8129
|
-
[output truncated]`}function L3($){return/^[A-Za-z0-9_.@:-]+$/.test($)}function KG($){return/^[A-Za-z0-9_-]+$/.test($)}function E3($){return $.charAt(0).toUpperCase()+$.slice(1)}function OG($,J){let Y=[],Z=J.servicesDetail??J.services??[];for(let W of Z){let z=String(W?.name??"");if(!z||!L3(z))continue;for(let U of j3)Y.push({id:`${U}:${z}`,label:`${E3(U)} ${z}`,group:"service",target:z,mutates:!0,confirm:z,danger:U==="stop"||U==="disable"})}for(let[W,z]of Object.entries($.sites??{})){if(!z||!KG(W))continue;let U=p0(z);if(U==="server-app"||U==="server-php")Y.push({id:`rollback:${W}`,label:`Rollback ${W}`,group:"deploy",target:W,mutates:!0,confirm:W,danger:!0})}let Q=new Set;for(let W of J.workers??[]){let z=String(W?.name??"").split(":")[0];if(z&&KG(z))Q.add(z)}for(let W of Q)Y.push({id:`worker:restart:${W}`,label:`Restart workers (${W})`,group:"worker",target:W,mutates:!0,confirm:W});for(let[W,z]of Object.entries($.sites??{})){if(!z||!KG(W))continue;if(z.scheduler||z.schedule)Y.push({id:`scheduler:run:${W}`,label:`Run scheduler (${W})`,group:"scheduler",target:W,mutates:!0,confirm:W})}if($.infrastructure?.compute?.backups?.enabled){if(Y.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),$.infrastructure?.appDatabase)Y.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return Y}function sF($,J,Y){return OG(J,Y).find((Z)=>Z.id===$)}function M3($,J){let Y=$==="enable"||$==="disable"?`systemctl is-enabled ${J} 2>/dev/null || true`:`systemctl is-active ${J} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${$} ${J}`,Y]}function q3(){return`eval "$(cd ${S1} && pantry env 2>/dev/null)"`}function aF($,J){let Y=`/var/www/${$}/current`;return["set -uo pipefail",`[ -d ${Y} ] || { echo "site ${$} has no current release" >&2; exit 1; }`,`cd ${Y} && ${q3()} && php artisan ${J}`]}function T3(){return["set -uo pipefail",`[ -x ${XQ} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,XQ]}function tF($,J,Y){return{operation:$,command:J,ok:Y.success,stdout:$5(Y.perInstance?.[0]?.output??""),stderr:$5(Y.perInstance?.[0]?.error??Y.error??"")}}async function oF($,J,Y,Z={}){let Q=$.project.slug,G;try{G=Y1({config:$})}catch(B){return{operation:Y.id,ok:!1,error:`Could not initialize the cloud driver: ${B?.message??B}`}}let W={driver:G,slug:Q,environment:J,role:"app"};if(Y.group==="deploy"){let B=Z.to&&/^[A-Za-z0-9._-]+$/.test(Z.to)?Z.to:void 0,K=await dQ(W,{siteName:Y.target,to:B});return tF(Y.id,`rollback ${Y.target}${B?` → ${B}`:""}`,K)}if(Y.id==="backup:restore"){let B=await cQ(W,{database:$.infrastructure?.appDatabase});return tF(Y.id,"db restore",B)}let z=await G.findComputeTargets({slug:Q,environment:J,role:"app"});if(!z.length)return{operation:Y.id,ok:!1,error:"No app server target was found for this environment."};let U,H;if(Y.group==="service"){let[B,...K]=Y.id.split(":");U=M3(B,K.join(":")),H=`systemctl ${B} ${Y.target}`}else if(Y.group==="worker")U=aF(Y.target,"queue:restart"),H=`queue:restart (${Y.target})`;else if(Y.group==="scheduler")U=aF(Y.target,"schedule:run"),H=`schedule:run (${Y.target})`;else if(Y.id==="backup:run")U=T3(),H="ts-cloud backup";else return{operation:Y.id,ok:!1,error:"Unknown operation."};let F=await G.runRemoteDeploy({targets:[z[0]],commands:U,comment:`ts-cloud dashboard:${Y.id}`,tags:{Project:Q,Environment:J,Role:"app"}});return{operation:Y.id,command:H,ok:F.success,stdout:$5(F.perInstance?.[0]?.output??""),stderr:$5(F.perInstance?.[0]?.error??F.error??"")}}await d7();iQ();var P3="127.0.0.1",C3=7676,eF=65536,Z8=R3(S3(import.meta.url)),x3={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function F0($,J=200){return new Response(JSON.stringify($,null,2),{status:J,headers:{"content-type":"application/json; charset=utf-8"}})}function $X($,J=200){return new Response($,{status:J,headers:{"content-type":"text/plain; charset=utf-8"}})}function I3($,J){if(J)return J;return Object.keys($.environments??{})[0]??"production"}async function k3($){let J=[v0(Z8,"..","..","..","..",".env"),v0($,".env"),v0($,".env.local"),v0($,".env.production")];for(let Y of J){if(!
|
|
8130
|
-
`)){let G=Q.trim();if(!G||G.startsWith("#")||!G.includes("="))continue;let W=G.indexOf("="),z=G.slice(0,W).trim(),U=G.slice(W+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(z)||process.env[z]!=null)continue;if(U.startsWith('"')&&U.endsWith('"')||U.startsWith("'")&&U.endsWith("'"))U=U.slice(1,-1);process.env[z]=U}}}function h3($){return[v0($,"config","cloud.ts"),v0($,"config","cloud.js"),v0($,"cloud.config.ts"),v0($,"cloud.config.js")].find((Y)=>
|
|
8131
|
-
${
|
|
8132
|
-
${
|
|
8129
|
+
[output truncated]`}function L3($){return/^[A-Za-z0-9_.@:-]+$/.test($)}function KG($){return/^[A-Za-z0-9_-]+$/.test($)}function E3($){return $.charAt(0).toUpperCase()+$.slice(1)}function OG($,J){let Y=[],Z=J.servicesDetail??J.services??[];for(let W of Z){let z=String(W?.name??"");if(!z||!L3(z))continue;for(let U of j3)Y.push({id:`${U}:${z}`,label:`${E3(U)} ${z}`,group:"service",target:z,mutates:!0,confirm:z,danger:U==="stop"||U==="disable"})}for(let[W,z]of Object.entries($.sites??{})){if(!z||!KG(W))continue;let U=p0(z);if(U==="server-app"||U==="server-php")Y.push({id:`rollback:${W}`,label:`Rollback ${W}`,group:"deploy",target:W,mutates:!0,confirm:W,danger:!0})}let Q=new Set;for(let W of J.workers??[]){let z=String(W?.name??"").split(":")[0];if(z&&KG(z))Q.add(z)}for(let W of Q)Y.push({id:`worker:restart:${W}`,label:`Restart workers (${W})`,group:"worker",target:W,mutates:!0,confirm:W});for(let[W,z]of Object.entries($.sites??{})){if(!z||!KG(W))continue;if(z.scheduler||z.schedule)Y.push({id:`scheduler:run:${W}`,label:`Run scheduler (${W})`,group:"scheduler",target:W,mutates:!0,confirm:W})}if($.infrastructure?.compute?.backups?.enabled){if(Y.push({id:"backup:run",label:"Run backup now",group:"backup",target:"backup",mutates:!0,confirm:"backup"}),$.infrastructure?.appDatabase)Y.push({id:"backup:restore",label:"Restore latest DB backup",group:"backup",target:"database",mutates:!0,confirm:"restore",danger:!0})}return Y}function sF($,J,Y){return OG(J,Y).find((Z)=>Z.id===$)}function M3($,J){let Y=$==="enable"||$==="disable"?`systemctl is-enabled ${J} 2>/dev/null || true`:`systemctl is-active ${J} 2>/dev/null || true`;return["set -o pipefail",`systemctl ${$} ${J}`,Y]}function q3(){return`eval "$(cd ${S1} && pantry env 2>/dev/null)"`}function aF($,J){let Y=`/var/www/${$}/current`;return["set -uo pipefail",`[ -d ${Y} ] || { echo "site ${$} has no current release" >&2; exit 1; }`,`cd ${Y} && ${q3()} && php artisan ${J}`]}function T3(){return["set -uo pipefail",`[ -x ${XQ} ] || { echo "scheduled backups are not provisioned on this server" >&2; exit 1; }`,XQ]}function tF($,J,Y){return{operation:$,command:J,ok:Y.success,stdout:$5(Y.perInstance?.[0]?.output??""),stderr:$5(Y.perInstance?.[0]?.error??Y.error??"")}}async function oF($,J,Y,Z={}){let Q=$.project.slug,G;try{G=Y1({config:$})}catch(B){return{operation:Y.id,ok:!1,error:`Could not initialize the cloud driver: ${B?.message??B}`}}let W={driver:G,slug:Q,environment:J,role:"app"};if(Y.group==="deploy"){let B=Z.to&&/^[A-Za-z0-9._-]+$/.test(Z.to)?Z.to:void 0,K=await dQ(W,{siteName:Y.target,to:B});return tF(Y.id,`rollback ${Y.target}${B?` → ${B}`:""}`,K)}if(Y.id==="backup:restore"){let B=await cQ(W,{database:$.infrastructure?.appDatabase});return tF(Y.id,"db restore",B)}let z=await G.findComputeTargets({slug:Q,environment:J,role:"app"});if(!z.length)return{operation:Y.id,ok:!1,error:"No app server target was found for this environment."};let U,H;if(Y.group==="service"){let[B,...K]=Y.id.split(":");U=M3(B,K.join(":")),H=`systemctl ${B} ${Y.target}`}else if(Y.group==="worker")U=aF(Y.target,"queue:restart"),H=`queue:restart (${Y.target})`;else if(Y.group==="scheduler")U=aF(Y.target,"schedule:run"),H=`schedule:run (${Y.target})`;else if(Y.id==="backup:run")U=T3(),H="ts-cloud backup";else return{operation:Y.id,ok:!1,error:"Unknown operation."};let F=await G.runRemoteDeploy({targets:[z[0]],commands:U,comment:`ts-cloud dashboard:${Y.id}`,tags:{Project:Q,Environment:J,Role:"app"}});return{operation:Y.id,command:H,ok:F.success,stdout:$5(F.perInstance?.[0]?.output??""),stderr:$5(F.perInstance?.[0]?.error??F.error??"")}}await d7();iQ();var P3="127.0.0.1",C3=7676,eF=65536,Z8=R3(S3(import.meta.url)),x3={".html":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".ico":"image/x-icon"};function F0($,J=200){return new Response(JSON.stringify($,null,2),{status:J,headers:{"content-type":"application/json; charset=utf-8"}})}function $X($,J=200){return new Response($,{status:J,headers:{"content-type":"text/plain; charset=utf-8"}})}function I3($,J){if(J)return J;return Object.keys($.environments??{})[0]??"production"}async function k3($){let J=[v0(Z8,"..","..","..","..",".env"),v0($,".env"),v0($,".env.local"),v0($,".env.production")];for(let Y of J){if(!n2(Y))continue;let Z=await M$(Y,"utf8").catch(()=>"");for(let Q of Z.split(`
|
|
8130
|
+
`)){let G=Q.trim();if(!G||G.startsWith("#")||!G.includes("="))continue;let W=G.indexOf("="),z=G.slice(0,W).trim(),U=G.slice(W+1).trim();if(!/^[A-Z_][A-Z0-9_]*$/i.test(z)||process.env[z]!=null)continue;if(U.startsWith('"')&&U.endsWith('"')||U.startsWith("'")&&U.endsWith("'"))U=U.slice(1,-1);process.env[z]=U}}}function h3($){return[v0($,"config","cloud.ts"),v0($,"config","cloud.js"),v0($,"cloud.config.ts"),v0($,"cloud.config.js")].find((Y)=>n2(Y))??null}function Q8($){return $.infrastructure?.compute?.sshKeys??[]}function JX($,J){let Y=$.infrastructure??($.infrastructure={}),Z=Y.compute??(Y.compute={});Z.sshKeys=J}function b3($,J,Y){let Z=$.sites??($.sites={});Z[J]=Y}async function N2($){return await $.json().catch(()=>({}))}function y3($){if($.mode==="hybrid")return"hybrid";return $.infrastructure?.compute?"server":"serverless"}async function E$($,J){let Y=y3($),Z={mode:Y,environment:J,environments:Object.keys($.environments??{})};try{return{...(Y==="serverless"?await i7($,J):await oQ($,J))??{},...Z}}catch{return{...Z}}}function v3($){let J=[v0($,"packages","ui"),v0(Z8,"..","..","..","ui"),v0(Z8,"..","..","ui"),v0(Z8,"..","ui-src"),v0(Z8,"..","..","ui-src"),v0(Z8,"..","..","dist","ui-src")];for(let Y of J)if(n2(v0(Y,"pages"))&&n2(v0(Y,"package.json")))return Y;return null}async function AG($,J){let Y=v3($);if(!Y)return null;try{let Z=w3(v0(D3(),"ts-cloud-dashboard-")),Q=v0(Y,"node_modules",".bin","stx"),G=n2(Q)?[Q,"build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"]:["bunx","--bun","@stacksjs/stx","build","--pages","pages","--out",Z,"--no-sitemap","--no-cache"],W=Bun.spawn(G,{cwd:Y,stdout:"pipe",stderr:"pipe",env:{...process.env,TSCLOUD_DASHBOARD_DATA:JSON.stringify(J)}}),[z,U,H]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);if(H!==0){if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build failed; serving the pre-built UI.
|
|
8131
|
+
${z}
|
|
8132
|
+
${U}`);return null}return Z}catch(Z){if(process.env.TSCLOUD_DASHBOARD_VERBOSE)console.warn(`ts-cloud dashboard: live UI build errored; serving the pre-built UI. ${Z.message}`);return null}}function _G($){return{project:{name:$.project?.name,slug:$.project?.slug,region:$.project?.region},provider:$.provider,environments:Object.keys($.environments??{}),compute:$.infrastructure?.compute?{provider:$.infrastructure.compute.provider,runtime:$.infrastructure.compute.runtime,webServer:$.infrastructure.compute.webServer,proxy:$.infrastructure.compute.proxy?{engine:$.infrastructure.compute.proxy.engine,onDemandTls:$.infrastructure.compute.proxy.onDemandTls,cdn:!!$.infrastructure.compute.proxy.cdn}:void 0,managedServices:$.infrastructure.compute.managedServices,sshKeys:r2(Q8($)).map((J)=>({name:J.name,type:J.type,fingerprint:J.fingerprint,added:J.added}))}:void 0,sites:Object.fromEntries(Object.entries($.sites??{}).map(([J,Y])=>[J,{domain:Y.domain,path:Y.path,type:Y.type,deploy:Y.deploy,root:Y.root,port:Y.port,ssl:Y.ssl}]))}}function G8($){return[{id:"status",label:"Refresh Cloud Status",description:"Runs the local ts-cloud status checks against configured providers.",command:["status","--env",$],mutates:!1},{id:"doctor",label:"Run Doctor",description:"Checks local tooling, credentials, and provider access.",command:["doctor"],mutates:!1},{id:"security-scan",label:"Security Scan",description:"Runs the pre-deploy scanner from this checkout.",command:["deploy:security-scan","--source",".","--fail-on","critical"],mutates:!1},{id:"deploy",label:"Deploy Environment",description:"Deploys the selected environment from the local checkout.",command:["deploy","--env",$,"--yes"],mutates:!0,confirm:"deploy"}]}function jG($,J){return G8(J).find((Y)=>Y.id===$)}function YX($){if($.length<=eF)return $;return`${$.slice(0,eF)}
|
|
8133
8133
|
|
|
8134
|
-
[output truncated]`}async function ZX($,J){let Y=Bun.spawn([process.execPath,J.cliEntry,...$.command],{cwd:J.cwd,stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{action:$.id,command:["cloud",...$.command].join(" "),exitCode:G,ok:G===0,stdout:YX(Z),stderr:YX(Q)}}function f3($,J){let Y=decodeURIComponent(J).replace(/^\/+/,""),Q=N3(Y===""?"index.html":Y);if(Q.startsWith("..")||Q.includes("/../"))return null;let G=v0($,Q);if(
|
|
8134
|
+
[output truncated]`}async function ZX($,J){let Y=Bun.spawn([process.execPath,J.cliEntry,...$.command],{cwd:J.cwd,stdout:"pipe",stderr:"pipe",env:process.env}),[Z,Q,G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{action:$.id,command:["cloud",...$.command].join(" "),exitCode:G,ok:G===0,stdout:YX(Z),stderr:YX(Q)}}function f3($,J){let Y=decodeURIComponent(J).replace(/^\/+/,""),Q=N3(Y===""?"index.html":Y);if(Q.startsWith("..")||Q.includes("/../"))return null;let G=v0($,Q);if(n2(G)&&!QX(G).isDirectory())return G;if(!VG(G)&&n2(`${G}.html`))return`${G}.html`;if(!VG(G)&&n2(v0(G,"index.html")))return v0(G,"index.html");return null}async function g3($,J){let Y=f3($,J);if(!Y)return $X("Not found",404);if(QX(Y).isDirectory())return $X("Not found",404);let Z=await M$(Y),Q=x3[VG(Y)]??"application/octet-stream";return new Response(Z,{headers:{"content-type":Q}})}async function J5($={}){let J=$.cwd??process.cwd(),Y=$.host??P3,Z=$.port??C3,Q=$.cliEntry??process.argv[1];if($.box)process.env.TS_CLOUD_DASHBOARD_BOX="1";await k3(J);let G=await q6(),W=Object.keys(G.environments??{}),z=I3(G,$.environment),U=G8(z),H=h3(J),F=await E$(G,z),B=F,K=await AG(J,F),O=u7(J),V=K??O?.uiRoot;if(!V)throw Error("ts-cloud dashboard UI not found. Run `bun run build` in ts-cloud or reinstall the package.");let A=Bun.serve({hostname:Y,port:Z,async fetch(_){let M=new URL(_.url);try{if(M.pathname==="/api/health")return F0({ok:!0,cwd:J,environment:z,environments:W,uiRoot:V,liveData:!!K,localPackage:import.meta.url.includes("/Code/Libraries/ts-cloud/")});if(M.pathname==="/"&&B?.mode==="serverless")return new Response(null,{status:302,headers:{location:"/serverless"}});if(M.pathname==="/api/env"&&_.method==="POST"){let j=await N2(_),q=String(j.env??"");if(!W.includes(q))return F0({ok:!1,error:`Unknown environment '${q}'.`,environments:W},404);if(q!==z){z=q,U=G8(z),B=await E$(G,z);let T=await AG(J,B);if(T)V=T}return F0({ok:!0,environment:z,environments:W})}if(M.pathname==="/api/config")return F0({..._G(G),environment:z,environments:W});if(M.pathname==="/api/ssh-keys"&&_.method==="GET")return F0({configPath:H,keys:r2(Q8(G))});if(M.pathname==="/api/ssh-keys"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await N2(_),q=await M$(H,"utf8"),T=Q8(G),D=TF({configText:q,name:String(j.name??""),publicKey:String(j.publicKey??""),existingKeys:T});return await P9(H,D),JX(G,[...T,{name:String(j.name??"").trim(),publicKey:String(j.publicKey??"").trim().replace(/\s+/g," ")}]),F0({ok:!0,configPath:H,keys:r2(Q8(G))})}if(M.pathname==="/api/ssh-keys"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await N2(_),q=String(j.name??M.searchParams.get("name")??""),T=await M$(H,"utf8"),D=Q8(G),S=wF({configText:T,name:q,existingKeys:D});return await P9(H,S),JX(G,D.filter((P)=>P.name!==q.trim())),F0({ok:!0,configPath:H,keys:r2(Q8(G))})}if(M.pathname==="/api/sites"&&_.method==="POST"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await N2(_),q=String(j.name??"").trim(),T=String(j.root??"").trim();if(!q||!T)return F0({ok:!1,error:"Site name and root are required."},422);let D={deploy:j.deploy==="bucket"?"bucket":"server",root:T,path:String(j.path??"").trim()||void 0,domain:String(j.domain??"").trim()||void 0,build:String(j.build??"").trim()||void 0,start:String(j.start??"").trim()||void 0,port:j.port?Number(j.port):void 0,type:String(j.type??"").trim()||void 0};if(D.port!==void 0&&(!Number.isInteger(D.port)||D.port<1||D.port>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let S=await M$(H,"utf8"),P=D6({configText:S,name:q,root:D.root,domain:D.domain,path:D.path,deploy:D.deploy,build:D.build,start:D.start,port:D.port,type:D.type});return await P9(H,P),b3(G,q,Object.fromEntries(Object.entries(D).filter(([,C])=>C!==void 0))),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(M.pathname==="/api/sites"&&_.method==="DELETE"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await N2(_),q=String(j.name??M.searchParams.get("name")??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);let T=await M$(H,"utf8");return await P9(H,f4({configText:T,name:q})),delete G.sites[q],B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(M.pathname==="/api/sites"&&_.method==="PATCH"){if(!H)return F0({ok:!1,error:"No cloud config file was found in this checkout."},404);let j=await N2(_),q=String(j.name??"").trim(),T=G.sites?.[q];if(!q||!T)return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.port!==void 0&&j.port!==null&&j.port!==""&&(!Number.isInteger(Number(j.port))||Number(j.port)<1||Number(j.port)>65535))return F0({ok:!1,error:"Port must be a number between 1 and 65535."},422);let D=await M$(H,"utf8"),S=(P,C)=>{D=g4({configText:D,siteName:q,key:P,valueText:C})};if(j.ssl!==void 0)S("ssl",u4(j.ssl)),T.ssl=j.ssl;if(j.env!==void 0&&j.env&&typeof j.env==="object")S("env",c4(j.env)),T.env=j.env;for(let P of["domain","path","build","start","type","root"])if(typeof j[P]==="string"&&j[P].trim())S(P,d4(String(j[P]).trim())),T[P]=String(j[P]).trim();if(j.port!==void 0&&j.port!==null&&j.port!=="")S("port",String(Number(j.port))),T.port=Number(j.port);return await P9(H,D),B=await E$(G,z),F0({ok:!0,configPath:H,site:q,data:B})}if(M.pathname==="/api/sites/deploy"&&_.method==="POST"){let j=await N2(_),q=String(j.name??"").trim();if(!q||!G.sites?.[q])return F0({ok:!1,error:`Site '${q}' was not found.`},404);if(j.confirm!==q)return F0({ok:!1,error:`Type "${q}" to deploy this site.`},409);let T={id:`deploy:${q}`,label:`Deploy ${q}`,description:`Deploy the ${q} site for ${z}.`,command:["deploy","--env",z,"--site",q,"--yes"],mutates:!0};return F0(await ZX(T,{cwd:J,cliEntry:Q}))}if(M.pathname==="/api/actions")return F0(U);if(M.pathname==="/api/server/operations")return F0(OG(G,B));if(M.pathname==="/api/databases"&&_.method==="GET")return F0(await pF(G,z));if(M.pathname==="/api/databases"&&_.method==="POST"){let j=await N2(_),q=String(j.name??"").trim();if(!e7(q))return F0({ok:!1,error:"Database name must be a valid identifier (letters, numbers, underscore; not starting with a digit)."},422);return F0({...await rF(G,z,q),name:q})}if(M.pathname==="/api/databases/users"&&_.method==="POST"){let j=await N2(_),q=String(j.username??"").trim(),T=String(j.password??""),D=String(j.database??"").trim()||void 0,S=j.access==="readonly"?"readonly":"all";if(!e7(q))return F0({ok:!1,error:"Username must be a valid identifier."},422);if(!T)return F0({ok:!1,error:"Password is required."},422);if(D&&!e7(D))return F0({ok:!1,error:"Database must be a valid identifier."},422);return F0({...await nF(G,z,{username:q,password:T,database:D,access:S}),username:q})}if(M.pathname==="/api/dashboard-data")return B=await E$(G,z),F0(B);if(M.pathname==="/api/actions/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.action?jG(j.action,z):void 0;if(!q)return F0({ok:!1,error:"Unknown dashboard action."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this action.`},409);return F0(await ZX(q,{cwd:J,cliEntry:Q}))}if(M.pathname==="/api/server/operations/run"&&_.method==="POST"){let j=await _.json().catch(()=>({})),q=j.operation?sF(j.operation,G,B):void 0;if(!q)return F0({ok:!1,error:"Unknown or unavailable server operation."},404);if(q.mutates&&j.confirm!==q.confirm)return F0({ok:!1,error:`Type "${q.confirm}" to run this operation.`},409);return F0(await oF(G,z,q,{to:j.to}))}let E=M.searchParams.get("env");if(E&&W.includes(E)&&E!==z){z=E,U=G8(z),B=await E$(G,z);let j=await AG(J,B);if(j)V=j}return g3(V,M.pathname)}catch(E){if($.verbose)console.error(E);return F0({ok:!1,error:E?.message??String(E)},500)}}});return{server:A,url:`http://${Y}:${A.port}/`}}function LG($){$.command("dashboard:serve","Run the local Forge-style cloud management UI").option("--host <host>","Host to bind",{default:"127.0.0.1"}).option("--port <port>","Port to bind",{default:"7676"}).option("--env <environment>","Environment to manage").option("--box","Box mode: run on the provisioned server (operate on localhost)").option("--open","Print the URL for opening in a browser").option("--verbose","Print server errors").action(async(J)=>{let Y=await J5({host:J?.host,port:Number(J?.port??7676),environment:J?.env,box:J?.box,verbose:J?.verbose});R("ts-cloud Local Dashboard"),h(`Serving ${Y.url}`),X("Use Ctrl+C to stop."),await new Promise(()=>{})})}z0();W2();function EG($){$.command("cdn:list","List all CloudFront distributions").action(async()=>{R("CloudFront Distributions");try{let J=await m(),Y=new w0,Z=new N("Fetching distributions...");Z.start();let Q=await Y.listDistributions();if(Z.succeed(`Found ${Q.length} distribution(s)`),Q.length===0){X("No CloudFront distributions found"),X("Use `cloud cdn:create` to create a new distribution");return}p(["ID","Domain","Status","Enabled","Aliases"],Q.map((G)=>[G.Id||"N/A",G.DomainName||"N/A",G.Status||"N/A",G.Enabled?"Yes":"No",(G.Aliases?.Items?.length||0).toString()]))}catch(J){w(`Failed to list distributions: ${J.message}`),process.exit(1)}}),$.command("cdn:status <distributionId>","Get CloudFront distribution status").action(async(J)=>{R(`CloudFront Distribution: ${J}`);try{let Y=new w0,Z=new N("Fetching distribution details...");Z.start();let Q=await Y.getDistribution(J);if(Z.succeed("Distribution details loaded"),X(`
|
|
8135
8135
|
Distribution Information:`),X(` ID: ${Q.Id}`),X(` Domain: ${Q.DomainName}`),X(` Status: ${Q.Status}`),X(` ARN: ${Q.ARN}`),X(` Enabled: ${Q.Enabled?"Yes":"No"}`),Q.Aliases?.Items?.length)X(` Aliases: ${Q.Aliases.Items.join(", ")}`);let G=await Y.getDistributionConfig(J);X(`
|
|
8136
8136
|
Origins:`);let W=G.DistributionConfig?.Origins?.Items||[];if(Array.isArray(W))for(let z of W)X(` - ${z.Id}: ${z.DomainName}`);if(G.DistributionConfig?.DefaultCacheBehavior){let z=G.DistributionConfig.DefaultCacheBehavior;X(`
|
|
8137
8137
|
Default Cache Behavior:`),X(` Target Origin: ${z.TargetOriginId}`),X(` Viewer Protocol: ${z.ViewerProtocolPolicy}`)}}catch(Y){w(`Failed to get distribution: ${Y.message}`),process.exit(1)}}),$.command("cdn:create","Create a new CloudFront distribution for an S3 bucket").option("--bucket <name>","S3 bucket name").option("--region <region>","S3 bucket region",{default:"us-east-1"}).option("--alias <domain>","Custom domain alias (CNAME)").option("--certificate <arn>","ACM certificate ARN for custom domain").option("--comment <text>","Distribution comment/description").action(async(J)=>{R("Create CloudFront Distribution");try{if(!J.bucket)w("--bucket is required"),X("Example: cloud cdn:create --bucket my-bucket --region us-east-1"),process.exit(1);let Y=new w0;if(X(`Bucket: ${J.bucket}`),X(`Region: ${J.region}`),J.alias)X(`Alias: ${J.alias}`);if(!await g(`
|
|
@@ -8155,7 +8155,7 @@ Sync complete!`)}catch(Q){w(`Failed to sync: ${Q.message}`),process.exit(1)}}),$
|
|
|
8155
8155
|
Delete bucket policy?`,!1)){X("Operation cancelled");return}let W=new N("Deleting policy...");W.start(),await Z.deleteBucketPolicy(J),W.succeed("Policy deleted");return}if(Y.publicRead){if(v(`This will make bucket ${J} publicly readable!`),!await g(`
|
|
8156
8156
|
Set public read policy?`,!1)){X("Operation cancelled");return}let W=new N("Setting policy...");W.start();let z={Version:"2012-10-17",Statement:[{Sid:"PublicReadGetObject",Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:`arn:aws:s3:::${J}/*`}]};await Z.putBucketPolicy(J,z),W.succeed("Public read policy set");return}if(Y.set){let G=new N("Setting policy...");G.start();let z=await Bun.file(Y.set).text();await Z.putBucketPolicy(J,z),G.succeed("Policy set");return}let Q=new N("Fetching policy...");Q.start();try{let G=await Z.getBucketPolicy(J);Q.succeed("Policy loaded"),X(`
|
|
8157
8157
|
Bucket Policy:`),console.log(JSON.stringify(G||{},null,2))}catch(G){if(G.message?.includes("NoSuchBucketPolicy"))Q.succeed("No policy set"),X("This bucket has no policy configured.");else throw G}}catch(Z){w(`Failed to manage policy: ${Z.message}`),process.exit(1)}}),$.command("storage:ls <bucket>","List objects in a bucket").option("--prefix <prefix>","Filter by prefix").option("--limit <number>","Limit number of results",{default:"100"}).action(async(J,Y)=>{R(`Objects in ${J}`);try{let Z=new W0("us-east-1"),Q=new N("Listing objects...");Q.start();let G=await Z.listObjects({bucket:J,prefix:Y.prefix,maxKeys:Number.parseInt(Y.limit||"100")}),W=G.objects;if(Q.succeed(`Found ${W.length} object(s)${G.nextContinuationToken?" (truncated)":""}`),W.length===0){X("No objects found");return}if(p(["Key","Size","Last Modified"],W.map((z)=>[z.Key||"N/A",p3(z.Size||0),z.LastModified?new Date(z.LastModified).toLocaleString():"N/A"])),G.nextContinuationToken)X(`
|
|
8158
|
-
More objects available. Use --limit to see more.`)}catch(Z){w(`Failed to list objects: ${Z.message}`),process.exit(1)}})}function l3($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",zip:"application/zip",xml:"application/xml",txt:"text/plain",md:"text/markdown"}[J||""]||"application/octet-stream"}function p3($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Z=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Z).toFixed(2))} ${Y[Z]}`}Y0();I0();function r3($,J){if(!J)return $;return $.startsWith(J)?$.slice(J.length):$}function qG($,J,Y){let Z=r3($,J);return`${Y??""}${Z}`}function TG($,J,Y){if(Y&&Y.some((Z)=>$.startsWith(Z)))return!1;if(J&&J.length>0)return J.some((Z)=>$.startsWith(Z));return!0}async function n3($,J,Y){let Z=0,Q=[],G=Math.max(1,Math.min(J,$.length||1));for(let W=0;W<G;W++)Q.push((async()=>{while(!0){let z=Z++;if(z>=$.length)return;await Y($[z],z)}})());await Promise.all(Q)}function GX($){if($.client)return $.client;return DG({provider:$.provider,region:$.region,endpoint:$.endpoint,forcePathStyle:$.forcePathStyle,credentials:$.credentials})}async function wG($){let J=$.concurrency??8,Y=GX($.from),Z=GX($.to),Q=await Y.listAllObjects({bucket:$.from.bucket,prefix:$.from.prefix}),G={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},W=[];for(let F of Q){if(!TG(F.Key,$.include,$.exclude)){G.excluded++,G.excludedKeys.push(F.Key);continue}W.push({source:F,destKey:qG(F.Key,$.from.prefix,$.to.prefix)})}if($.dryRun){G.plan=W.map(({source:K,destKey:O})=>({key:K.Key,destKey:O,size:K.Size}));let F=Q.length,B=0;for(let K of Q){B++;let O=!TG(K.Key,$.include,$.exclude);$.onProgress?.({key:K.Key,destKey:O?"":qG(K.Key,$.from.prefix,$.to.prefix),size:K.Size,action:O?"excluded":"planned",index:B,total:F})}return G}let z=W.length,U=0;await n3(W,J,async({source:F,destKey:B})=>{let K=++U;try{if(!$.force){let A=await Z.headObject($.to.bucket,B);if(A&&A.ContentLength===F.Size){G.skipped++,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"skipped",index:K,total:z});return}}let{body:O,contentType:V}=await Y.getObjectBytes($.from.bucket,F.Key);await Z.putObject({bucket:$.to.bucket,key:B,body:O,contentType:V}),G.copied++,G.bytesCopied+=O.byteLength,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"copied",index:K,total:z})}catch(O){G.errors.push({key:F.Key,message:O?.message??String(O)}),$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"error",index:K,total:z})}});let H=new Set(W.map((F)=>F.destKey));if($.deleteExtraneous){let B=(await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix})).filter((K)=>!H.has(K.Key)).map((K)=>K.Key);for(let K of B)try{await Z.deleteObject($.to.bucket,K),G.deleted.push(K)}catch(O){G.errors.push({key:K,message:`delete failed: ${O?.message??String(O)}`})}}if($.verify){let F=await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix}),B=new Map(F.map((A)=>[A.Key,A.Size])),K=[],O=[],V=0;for(let{source:A,destKey:_}of W){if(!B.has(_)){K.push(_);continue}let M=B.get(_);if(M!==A.Size){O.push({key:_,expected:A.Size,actual:M});continue}V++}G.verification={ok:K.length===0&&O.length===0,matched:V,missing:K,sizeMismatches:O}}return G}var i3={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function WX($,J){switch($){case"backblaze":return`s3.${J}.backblazeb2.com`;case"hetzner":return`${J}.your-objectstorage.com`;case"aws":default:return}}function x1(...$){for(let J of $){let Y=process.env[J];if(Y)return Y}return}function a3($,J){if(J?.accessKeyId&&J.secretAccessKey)return J;let Y,Z;if($==="backblaze")Y=x1("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=x1("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if($==="hetzner")Y=x1("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=x1("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else Y=x1("S3_ACCESS_KEY_ID"),Z=x1("S3_SECRET_ACCESS_KEY");if(Y&&Z)return{accessKeyId:Y,secretAccessKey:Z,sessionToken:x1("AWS_SESSION_TOKEN")};return}function zX($={}){let J=$.provider||x1("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",Y=$.region||(J==="backblaze"?x1("B2_REGION"):void 0)||(J==="hetzner"?x1("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||x1("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||i3[J],Z=$.endpoint||x1("S3_ENDPOINT")||WX(J,Y),Q=$.forcePathStyle??x1("S3_FORCE_PATH_STYLE")==="true",G=a3(J,$.credentials),W=(z)=>{let U=Z||`s3.${Y}.amazonaws.com`;return Q?`https://${U}/${z}`:`https://${z}.${U}`};return{provider:J,region:Y,endpoint:Z,forcePathStyle:Q,credentials:G,profile:$.profile,publicBaseUrl:W}}function DG($={}){let J=zX($),Y={endpoint:J.endpoint,forcePathStyle:J.forcePathStyle,credentials:J.credentials};return new W0(J.region,J.profile,Y)}L1();U7();Z9();I0();W2();s2();Y0();j2();e6();F7();ZQ();o6();U9();HQ();Y0();class q1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Z])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`).join("&")}async createTopic($){let J={Action:"CreateTopic",Version:"2010-03-31",Name:$.Name};if($.DisplayName)J["Attributes.entry.1.key"]="DisplayName",J["Attributes.entry.1.value"]=$.DisplayName;if($.Tags)$.Tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.Attributes){let Z=$.DisplayName?2:1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{TopicArn:Y?.CreateTopicResponse?.CreateTopicResult?.TopicArn||Y?.TopicArn}}async deleteTopic($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:$})})}async listTopics($){let J={Action:"ListTopics",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListTopicsResponse?.ListTopicsResult||Y?.ListTopicsResult,Q=Z?.Topics?.member;return{Topics:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.NextToken}}async getTopicAttributes($){let Y=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:$})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,Z={TopicArn:$};if(Array.isArray(Y))Y.forEach((Q)=>{Z[Q.key]=Q.value});return Z}async setTopicAttributes($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:$.TopicArn,AttributeName:$.AttributeName,AttributeValue:$.AttributeValue})})}async subscribe($){let J={Action:"Subscribe",Version:"2010-03-31",TopicArn:$.TopicArn,Protocol:$.Protocol,Endpoint:$.Endpoint};if($.ReturnSubscriptionArn)J.ReturnSubscriptionArn="true";if($.Attributes){let Z=1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{SubscriptionArn:Y?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||Y?.SubscriptionArn}}async unsubscribe($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:$})})}async listSubscriptionsByTopic($,J){let Y={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:$};if(J)Y.NextToken=J;let Z=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)}),Q=Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish($){let J={Action:"Publish",Version:"2010-03-31",Message:$.Message};if($.TopicArn)J.TopicArn=$.TopicArn;if($.TargetArn)J.TargetArn=$.TargetArn;if($.PhoneNumber)J.PhoneNumber=$.PhoneNumber;if($.Subject)J.Subject=$.Subject;if($.MessageStructure)J.MessageStructure=$.MessageStructure;if($.MessageAttributes){let Z=1;Object.entries($.MessageAttributes).forEach(([Q,G])=>{if(J[`MessageAttributes.entry.${Z}.Name`]=Q,J[`MessageAttributes.entry.${Z}.Value.DataType`]=G.DataType,G.StringValue)J[`MessageAttributes.entry.${Z}.Value.StringValue`]=G.StringValue;if(G.BinaryValue)J[`MessageAttributes.entry.${Z}.Value.BinaryValue`]=G.BinaryValue;Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:Y?.PublishResponse?.PublishResult?.MessageId||Y?.MessageId}}async publishSMS($,J,Y){let Z={};if(Y)Z["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y};return this.publish({PhoneNumber:$,Message:J,MessageAttributes:Object.keys(Z).length>0?Z:void 0})}async subscribeEmail($,J){return this.subscribe({TopicArn:$,Protocol:"email",Endpoint:J})}async subscribeLambda($,J){return this.subscribe({TopicArn:$,Protocol:"lambda",Endpoint:J})}async subscribeSqs($,J,Y){let Z={};if(Y)Z.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:"sqs",Endpoint:J,Attributes:Object.keys(Z).length>0?Z:void 0})}async subscribeHttp($,J,Y){let Z=J.startsWith("https")?"https":"http",Q={};if(Y)Q.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:Z,Endpoint:J,Attributes:Object.keys(Q).length>0?Q:void 0})}async subscribeSms($,J){return this.subscribe({TopicArn:$,Protocol:"sms",Endpoint:J})}async topicExists($){try{return await this.getTopicAttributes($),!0}catch(J){if(J.code==="NotFound"||J.statusCode===404)return!1;throw J}}async getSMSAttributes(){let J=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,Y={};if(Array.isArray(J))J.forEach((Z)=>{Y[Z.key]=Z.value});else if(J)Y[J.key]=J.value;return Y}async setSMSAttributes($){let J={Action:"SetSMSAttributes",Version:"2010-03-31"},Y=1;Object.entries($).forEach(([Z,Q])=>{if(Q!==void 0)J[`attributes.entry.${Y}.key`]=Z,J[`attributes.entry.${Y}.value`]=Q,Y++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async checkIfPhoneNumberIsOptedOut($){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:$})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut($){let J={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if($)J.nextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],nextToken:Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:$})})}async listSMSSandboxPhoneNumbers($){let J={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],NextToken:Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,LanguageCode:J||"en-US"})})}async verifySMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,OneTimePassword:J})})}async deleteSMSSandboxPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}D9();n1();i8();Y0();Y0();t8();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();class a1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async request($,J){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${$}`},body:JSON.stringify(J)})}async putRule($){return this.request("PutRule",$)}async deleteRule($){return this.request("DeleteRule",$)}async describeRule($){return this.request("DescribeRule",$)}async listRules($){return this.request("ListRules",$||{})}async listEventBuses($){return this.request("ListEventBuses",$||{})}async enableRule($){return this.request("EnableRule",$)}async disableRule($){return this.request("DisableRule",$)}async putTargets($){return this.request("PutTargets",$)}async removeTargets($){return this.request("RemoveTargets",$)}async listTargetsByRule($){return this.request("ListTargetsByRule",$)}async putEvents($){return this.request("PutEvents",$)}async createSchedule($){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${$.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}}Y0();class S2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeCacheClusters($){let J={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if($)J.CacheClusterId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheClusters:this.parseCacheClusters(Y)}}async describeReplicationGroups($){let J={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if($)J.ReplicationGroupId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{ReplicationGroups:[]}}async createCacheCluster($){let J={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:$.cacheClusterId,Engine:$.engine,CacheNodeType:$.cacheNodeType};if($.numCacheNodes)J.NumCacheNodes=$.numCacheNodes;if($.engineVersion)J.EngineVersion=$.engineVersion;if($.port)J.Port=$.port;if($.securityGroupIds&&$.securityGroupIds.length>0)$.securityGroupIds.forEach((Z,Q)=>{J[`SecurityGroupIds.member.${Q+1}`]=Z});if($.subnetGroupName)J.CacheSubnetGroupName=$.subnetGroupName;if($.tags&&$.tags.length>0)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheCluster:this.parseCacheCluster(Y)}}async deleteCacheCluster($,J){let Y={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:$};if(J)Y.FinalSnapshotIdentifier=J;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async rebootCacheCluster($,J){let Y={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:$};J.forEach((Z,Q)=>{Y[`CacheNodeIdsToReboot.member.${Q+1}`]=Z}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async describeCacheEngineVersions($){let J={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if($)J.Engine=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics($){let J=await this.describeCacheClusters($);if(!J.CacheClusters||J.CacheClusters.length===0)throw Error(`Cache cluster ${$} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters($){if($.CacheClusterId)return[{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"available",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster($){return{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"creating",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}}}Y0();class t1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRule($){let J={Action:"PutRule",Name:$.name,ScheduleExpression:$.scheduleExpression,Version:"2015-10-07"};if($.description)J.Description=$.description;if($.state)J.State=$.state;else J.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$.name,ScheduleExpression:$.scheduleExpression,State:$.state||"ENABLED",Description:$.description})})).RuleArn}}async putTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Targets:J})})}async listRules($){let J={};if($)J.NamePrefix=$;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).Rules||[]}}async describeRule($){let J=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})});return{Name:J.Name,Arn:J.Arn,ScheduleExpression:J.ScheduleExpression,State:J.State,Description:J.Description}}async listTargetsByRule($){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$})})).Targets||[]}}async deleteRule($,J){if(J)try{let Y=await this.listTargetsByRule($);if(Y.Targets&&Y.Targets.length>0)await this.removeTargets($,Y.Targets.map((Z)=>Z.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$,Force:J||!1})})}async removeTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Ids:J})})}async enableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async disableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async createLambdaSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.functionArn,Input:$.input}]),J}async createEcsSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.clusterArn,RoleArn:$.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),J}async listSchedules($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;if($?.State)J.State=$.State;let Y=$?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...J,ScheduleGroup:Y}}))?.Schedules||[]}}async getSchedule($){try{let J={};if($.GroupName)J.groupName=$.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}catch(J){if(J.statusCode===404||J.code==="ResourceNotFoundException")return null;throw J}}async createSchedule($){let J={ScheduleExpression:$.ScheduleExpression,FlexibleTimeWindow:$.FlexibleTimeWindow,Target:$.Target};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description)J.Description=$.Description;if($.State)J.State=$.State;if($.StartDate)J.StartDate=$.StartDate.toISOString();if($.EndDate)J.EndDate=$.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async updateSchedule($){let J={};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpression)J.ScheduleExpression=$.ScheduleExpression;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description!==void 0)J.Description=$.Description;if($.State)J.State=$.State;if($.FlexibleTimeWindow)J.FlexibleTimeWindow=$.FlexibleTimeWindow;if($.Target)J.Target=$.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async deleteSchedule($){let J={};if($.GroupName)J.groupName=$.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}async listScheduleGroups($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(J).length>0?J:void 0}))?.ScheduleGroups||[]}}}T7();Y0();I0();U9();I0();I0();I0();Y0();I0();Y0();mQ();$2();$2();s2();B$();J9();Y9();Y9();await z8([Q1(),CZ(),a7()]);$2();await _$();n0();z0();var UX=["aws","backblaze","hetzner"];function HX($,J){let Y=$.indexOf(":");if(Y===-1)throw Error(`--${J} must be in the form <provider:bucket> (e.g. aws:my-bucket), got "${$}"`);let Z=$.slice(0,Y),Q=$.slice(Y+1);if(!UX.includes(Z))throw Error(`Unknown provider "${Z}" for --${J}. Supported: ${UX.join(", ")}`);if(!Q)throw Error(`--${J} is missing a bucket name (expected <provider:bucket>)`);return{provider:Z,bucket:Q}}function FX($){if(!$)return;let J=$.split(",").map((Y)=>Y.trim()).filter(Boolean);return J.length>0?J:void 0}function RG($){$.command("migrate:storage","Migrate object-storage data between providers (AWS S3 ↔ Hetzner ↔ Backblaze)").option("--from <provider:bucket>","Source endpoint, e.g. aws:stacks-production-email").option("--to <provider:bucket>","Destination endpoint, e.g. hetzner:stacks-mail").option("--from-region <region>","Source region/location (default: provider default)").option("--to-region <region>","Destination region/location (default: provider default)").option("--from-endpoint <host>","Source endpoint host override (no scheme)").option("--to-endpoint <host>","Destination endpoint host override (no scheme)").option("--from-prefix <prefix>","Only read source keys under this prefix (stripped from dest key)").option("--to-prefix <prefix>","Prepend this prefix to every destination key").option("--include <csv>","Only copy keys under these comma-separated prefixes").option("--exclude <csv>","Skip keys under these comma-separated prefixes").option("--dry-run","Print the plan (what would copy / what is excluded) without writing").option("--force","Re-copy even if the destination already has an object of the same size").option("--delete-extraneous","Delete destination keys not present in the source (default OFF)").option("--concurrency <n>","Max concurrent copies",{default:"8"}).option("--verify","After copying, re-list the destination and assert object count + sizes match").action(async(J)=>{R("Migrate Object Storage");try{if(!J.from||!J.to)throw Error("Both --from <provider:bucket> and --to <provider:bucket> are required");let Y=HX(J.from,"from"),Z=HX(J.to,"to"),Q=FX(J.include),G=FX(J.exclude),W=Number.parseInt(J.concurrency||"8",10),z={provider:Y.provider,bucket:Y.bucket,region:J.fromRegion,endpoint:J.fromEndpoint,prefix:J.fromPrefix},U={provider:Z.provider,bucket:Z.bucket,region:J.toRegion,endpoint:J.toEndpoint,prefix:J.toPrefix};if(X(`Source: ${Y.provider}:${Y.bucket}${J.fromPrefix?`/${J.fromPrefix}`:""}`),X(`Destination: ${Z.provider}:${Z.bucket}${J.toPrefix?`/${J.toPrefix}`:""}`),Q)X(`Include: ${Q.join(", ")}`);if(G)X(`Exclude: ${G.join(", ")}`);if(X(`Concurrency: ${W}`),J.dryRun)v("Dry run — no objects will be written");if(J.deleteExtraneous&&!J.dryRun)v("Delete-extraneous ON — destination keys not in the source will be removed");let H=new N("Listing source objects...");H.start();let F=0,B=await wG({from:z,to:U,include:Q,exclude:G,dryRun:J.dryRun,force:J.force,deleteExtraneous:J.deleteExtraneous,concurrency:W,verify:J.verify,onProgress:(K)=>{if(K.index-F>=1||K.index===K.total){F=K.index;let O=K.action==="planned"?"plan":K.action;H.text=`[${K.index}/${K.total}] ${O}: ${K.key}`}}});if(H.succeed(J.dryRun?"Plan ready":"Migration complete"),J.dryRun&&B.plan){X(`
|
|
8158
|
+
More objects available. Use --limit to see more.`)}catch(Z){w(`Failed to list objects: ${Z.message}`),process.exit(1)}})}function l3($){let J=$.split(".").pop()?.toLowerCase();return{html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",ico:"image/x-icon",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",eot:"application/vnd.ms-fontobject",pdf:"application/pdf",zip:"application/zip",xml:"application/xml",txt:"text/plain",md:"text/markdown"}[J||""]||"application/octet-stream"}function p3($){if($===0)return"0 B";let J=1024,Y=["B","KB","MB","GB","TB"],Z=Math.floor(Math.log($)/Math.log(J));return`${Number.parseFloat(($/J**Z).toFixed(2))} ${Y[Z]}`}Y0();I0();function r3($,J){if(!J)return $;return $.startsWith(J)?$.slice(J.length):$}function qG($,J,Y){let Z=r3($,J);return`${Y??""}${Z}`}function TG($,J,Y){if(Y&&Y.some((Z)=>$.startsWith(Z)))return!1;if(J&&J.length>0)return J.some((Z)=>$.startsWith(Z));return!0}async function n3($,J,Y){let Z=0,Q=[],G=Math.max(1,Math.min(J,$.length||1));for(let W=0;W<G;W++)Q.push((async()=>{while(!0){let z=Z++;if(z>=$.length)return;await Y($[z],z)}})());await Promise.all(Q)}function GX($){if($.client)return $.client;return DG({provider:$.provider,region:$.region,endpoint:$.endpoint,forcePathStyle:$.forcePathStyle,credentials:$.credentials})}async function wG($){let J=$.concurrency??8,Y=GX($.from),Z=GX($.to),Q=await Y.listAllObjects({bucket:$.from.bucket,prefix:$.from.prefix}),G={copied:0,skipped:0,excluded:0,bytesCopied:0,errors:[],excludedKeys:[],deleted:[]},W=[];for(let F of Q){if(!TG(F.Key,$.include,$.exclude)){G.excluded++,G.excludedKeys.push(F.Key);continue}W.push({source:F,destKey:qG(F.Key,$.from.prefix,$.to.prefix)})}if($.dryRun){G.plan=W.map(({source:K,destKey:O})=>({key:K.Key,destKey:O,size:K.Size}));let F=Q.length,B=0;for(let K of Q){B++;let O=!TG(K.Key,$.include,$.exclude);$.onProgress?.({key:K.Key,destKey:O?"":qG(K.Key,$.from.prefix,$.to.prefix),size:K.Size,action:O?"excluded":"planned",index:B,total:F})}return G}let z=W.length,U=0;await n3(W,J,async({source:F,destKey:B})=>{let K=++U;try{if(!$.force){let A=await Z.headObject($.to.bucket,B);if(A&&A.ContentLength===F.Size){G.skipped++,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"skipped",index:K,total:z});return}}let{body:O,contentType:V}=await Y.getObjectBytes($.from.bucket,F.Key);await Z.putObject({bucket:$.to.bucket,key:B,body:O,contentType:V}),G.copied++,G.bytesCopied+=O.byteLength,$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"copied",index:K,total:z})}catch(O){G.errors.push({key:F.Key,message:O?.message??String(O)}),$.onProgress?.({key:F.Key,destKey:B,size:F.Size,action:"error",index:K,total:z})}});let H=new Set(W.map((F)=>F.destKey));if($.deleteExtraneous){let B=(await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix})).filter((K)=>!H.has(K.Key)).map((K)=>K.Key);for(let K of B)try{await Z.deleteObject($.to.bucket,K),G.deleted.push(K)}catch(O){G.errors.push({key:K,message:`delete failed: ${O?.message??String(O)}`})}}if($.verify){let F=await Z.listAllObjects({bucket:$.to.bucket,prefix:$.to.prefix}),B=new Map(F.map((A)=>[A.Key,A.Size])),K=[],O=[],V=0;for(let{source:A,destKey:_}of W){if(!B.has(_)){K.push(_);continue}let M=B.get(_);if(M!==A.Size){O.push({key:_,expected:A.Size,actual:M});continue}V++}G.verification={ok:K.length===0&&O.length===0,matched:V,missing:K,sizeMismatches:O}}return G}var i3={aws:"us-east-1",backblaze:"us-west-004",hetzner:"fsn1"};function WX($,J){switch($){case"backblaze":return`s3.${J}.backblazeb2.com`;case"hetzner":return`${J}.your-objectstorage.com`;case"aws":default:return}}function x1(...$){for(let J of $){let Y=process.env[J];if(Y)return Y}return}function a3($,J){if(J?.accessKeyId&&J.secretAccessKey)return J;let Y,Z;if($==="backblaze")Y=x1("B2_APPLICATION_KEY_ID","B2_KEY_ID","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=x1("B2_APPLICATION_KEY","B2_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else if($==="hetzner")Y=x1("HETZNER_S3_ACCESS_KEY","HETZNER_ACCESS_KEY","S3_ACCESS_KEY_ID","AWS_ACCESS_KEY_ID"),Z=x1("HETZNER_S3_SECRET_KEY","HETZNER_SECRET_KEY","S3_SECRET_ACCESS_KEY","AWS_SECRET_ACCESS_KEY");else Y=x1("S3_ACCESS_KEY_ID"),Z=x1("S3_SECRET_ACCESS_KEY");if(Y&&Z)return{accessKeyId:Y,secretAccessKey:Z,sessionToken:x1("AWS_SESSION_TOKEN")};return}function zX($={}){let J=$.provider||x1("OBJECT_STORAGE_PROVIDER","STORAGE_PROVIDER")||"aws",Y=$.region||(J==="backblaze"?x1("B2_REGION"):void 0)||(J==="hetzner"?x1("HETZNER_S3_REGION","HETZNER_REGION"):void 0)||x1("S3_REGION","AWS_REGION","AWS_DEFAULT_REGION")||i3[J],Z=$.endpoint||x1("S3_ENDPOINT")||WX(J,Y),Q=$.forcePathStyle??x1("S3_FORCE_PATH_STYLE")==="true",G=a3(J,$.credentials),W=(z)=>{let U=Z||`s3.${Y}.amazonaws.com`;return Q?`https://${U}/${z}`:`https://${z}.${U}`};return{provider:J,region:Y,endpoint:Z,forcePathStyle:Q,credentials:G,profile:$.profile,publicBaseUrl:W}}function DG($={}){let J=zX($),Y={endpoint:J.endpoint,forcePathStyle:J.forcePathStyle,credentials:J.credentials};return new W0(J.region,J.profile,Y)}L1();U7();Z9();I0();W2();o2();Y0();j2();e6();F7();ZQ();o6();U9();HQ();Y0();class q1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}buildFormBody($){return Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,Z])=>`${encodeURIComponent(Y)}=${encodeURIComponent(Z)}`).join("&")}async createTopic($){let J={Action:"CreateTopic",Version:"2010-03-31",Name:$.Name};if($.DisplayName)J["Attributes.entry.1.key"]="DisplayName",J["Attributes.entry.1.value"]=$.DisplayName;if($.Tags)$.Tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});if($.Attributes){let Z=$.DisplayName?2:1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{TopicArn:Y?.CreateTopicResponse?.CreateTopicResult?.TopicArn||Y?.TopicArn}}async deleteTopic($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteTopic",Version:"2010-03-31",TopicArn:$})})}async listTopics($){let J={Action:"ListTopics",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListTopicsResponse?.ListTopicsResult||Y?.ListTopicsResult,Q=Z?.Topics?.member;return{Topics:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.NextToken}}async getTopicAttributes($){let Y=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetTopicAttributes",Version:"2010-03-31",TopicArn:$})}))?.GetTopicAttributesResponse?.GetTopicAttributesResult?.Attributes?.entry,Z={TopicArn:$};if(Array.isArray(Y))Y.forEach((Q)=>{Z[Q.key]=Q.value});return Z}async setTopicAttributes($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"SetTopicAttributes",Version:"2010-03-31",TopicArn:$.TopicArn,AttributeName:$.AttributeName,AttributeValue:$.AttributeValue})})}async subscribe($){let J={Action:"Subscribe",Version:"2010-03-31",TopicArn:$.TopicArn,Protocol:$.Protocol,Endpoint:$.Endpoint};if($.ReturnSubscriptionArn)J.ReturnSubscriptionArn="true";if($.Attributes){let Z=1;Object.entries($.Attributes).forEach(([Q,G])=>{J[`Attributes.entry.${Z}.key`]=Q,J[`Attributes.entry.${Z}.value`]=G,Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{SubscriptionArn:Y?.SubscribeResponse?.SubscribeResult?.SubscriptionArn||Y?.SubscriptionArn}}async unsubscribe($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"Unsubscribe",Version:"2010-03-31",SubscriptionArn:$})})}async listSubscriptionsByTopic($,J){let Y={Action:"ListSubscriptionsByTopic",Version:"2010-03-31",TopicArn:$};if(J)Y.NextToken=J;let Z=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(Y)}),Q=Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.Subscriptions?.member;return{Subscriptions:Array.isArray(Q)?Q:Q?[Q]:[],NextToken:Z?.ListSubscriptionsByTopicResponse?.ListSubscriptionsByTopicResult?.NextToken}}async publish($){let J={Action:"Publish",Version:"2010-03-31",Message:$.Message};if($.TopicArn)J.TopicArn=$.TopicArn;if($.TargetArn)J.TargetArn=$.TargetArn;if($.PhoneNumber)J.PhoneNumber=$.PhoneNumber;if($.Subject)J.Subject=$.Subject;if($.MessageStructure)J.MessageStructure=$.MessageStructure;if($.MessageAttributes){let Z=1;Object.entries($.MessageAttributes).forEach(([Q,G])=>{if(J[`MessageAttributes.entry.${Z}.Name`]=Q,J[`MessageAttributes.entry.${Z}.Value.DataType`]=G.DataType,G.StringValue)J[`MessageAttributes.entry.${Z}.Value.StringValue`]=G.StringValue;if(G.BinaryValue)J[`MessageAttributes.entry.${Z}.Value.BinaryValue`]=G.BinaryValue;Z++})}let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)});return{MessageId:Y?.PublishResponse?.PublishResult?.MessageId||Y?.MessageId}}async publishSMS($,J,Y){let Z={};if(Y)Z["AWS.SNS.SMS.SenderID"]={DataType:"String",StringValue:Y};return this.publish({PhoneNumber:$,Message:J,MessageAttributes:Object.keys(Z).length>0?Z:void 0})}async subscribeEmail($,J){return this.subscribe({TopicArn:$,Protocol:"email",Endpoint:J})}async subscribeLambda($,J){return this.subscribe({TopicArn:$,Protocol:"lambda",Endpoint:J})}async subscribeSqs($,J,Y){let Z={};if(Y)Z.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:"sqs",Endpoint:J,Attributes:Object.keys(Z).length>0?Z:void 0})}async subscribeHttp($,J,Y){let Z=J.startsWith("https")?"https":"http",Q={};if(Y)Q.RawMessageDelivery="true";return this.subscribe({TopicArn:$,Protocol:Z,Endpoint:J,Attributes:Object.keys(Q).length>0?Q:void 0})}async subscribeSms($,J){return this.subscribe({TopicArn:$,Protocol:"sms",Endpoint:J})}async topicExists($){try{return await this.getTopicAttributes($),!0}catch(J){if(J.code==="NotFound"||J.statusCode===404)return!1;throw J}}async getSMSAttributes(){let J=(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSAttributes",Version:"2010-03-31"})}))?.GetSMSAttributesResponse?.GetSMSAttributesResult?.attributes?.entry,Y={};if(Array.isArray(J))J.forEach((Z)=>{Y[Z.key]=Z.value});else if(J)Y[J.key]=J.value;return Y}async setSMSAttributes($){let J={Action:"SetSMSAttributes",Version:"2010-03-31"},Y=1;Object.entries($).forEach(([Z,Q])=>{if(Q!==void 0)J[`attributes.entry.${Y}.key`]=Z,J[`attributes.entry.${Y}.value`]=Q,Y++}),await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)})}async checkIfPhoneNumberIsOptedOut($){return(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CheckIfPhoneNumberIsOptedOut",Version:"2010-03-31",phoneNumber:$})}))?.CheckIfPhoneNumberIsOptedOutResponse?.CheckIfPhoneNumberIsOptedOutResult?.isOptedOut==="true"}async listPhoneNumbersOptedOut($){let J={Action:"ListPhoneNumbersOptedOut",Version:"2010-03-31"};if($)J.nextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.phoneNumbers?.member;return{phoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],nextToken:Y?.ListPhoneNumbersOptedOutResponse?.ListPhoneNumbersOptedOutResult?.nextToken}}async optInPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"OptInPhoneNumber",Version:"2010-03-31",phoneNumber:$})})}async listSMSSandboxPhoneNumbers($){let J={Action:"ListSMSSandboxPhoneNumbers",Version:"2010-03-31"};if($)J.NextToken=$;let Y=await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody(J)}),Z=Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.PhoneNumbers?.member;return{PhoneNumbers:Array.isArray(Z)?Z:Z?[Z]:[],NextToken:Y?.ListSMSSandboxPhoneNumbersResponse?.ListSMSSandboxPhoneNumbersResult?.NextToken}}async createSMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"CreateSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,LanguageCode:J||"en-US"})})}async verifySMSSandboxPhoneNumber($,J){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"VerifySMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$,OneTimePassword:J})})}async deleteSMSSandboxPhoneNumber($){await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"DeleteSMSSandboxPhoneNumber",Version:"2010-03-31",PhoneNumber:$})})}async getSMSSandboxAccountStatus(){return{IsInSandbox:(await this.client.request({service:"sns",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:this.buildFormBody({Action:"GetSMSSandboxAccountStatus",Version:"2010-03-31"})}))?.GetSMSSandboxAccountStatusResponse?.GetSMSSandboxAccountStatusResult?.IsInSandbox==="true"}}}D9();n1();i8();Y0();Y0();t8();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();Y0();class a1{client;region;constructor($="us-east-1"){this.region=$,this.client=new i}async request($,J){return this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`AWSEvents.${$}`},body:JSON.stringify(J)})}async putRule($){return this.request("PutRule",$)}async deleteRule($){return this.request("DeleteRule",$)}async describeRule($){return this.request("DescribeRule",$)}async listRules($){return this.request("ListRules",$||{})}async listEventBuses($){return this.request("ListEventBuses",$||{})}async enableRule($){return this.request("EnableRule",$)}async disableRule($){return this.request("DisableRule",$)}async putTargets($){return this.request("PutTargets",$)}async removeTargets($){return this.request("RemoveTargets",$)}async listTargetsByRule($){return this.request("ListTargetsByRule",$)}async putEvents($){return this.request("PutEvents",$)}async createSchedule($){return this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${$.Name}`,headers:{"Content-Type":"application/json"},body:JSON.stringify($)})}}Y0();class S2{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async describeCacheClusters($){let J={Action:"DescribeCacheClusters",Version:"2015-02-02",ShowCacheNodeInfo:"true"};if($)J.CacheClusterId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheClusters:this.parseCacheClusters(Y)}}async describeReplicationGroups($){let J={Action:"DescribeReplicationGroups",Version:"2015-02-02"};if($)J.ReplicationGroupId=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{ReplicationGroups:[]}}async createCacheCluster($){let J={Action:"CreateCacheCluster",Version:"2015-02-02",CacheClusterId:$.cacheClusterId,Engine:$.engine,CacheNodeType:$.cacheNodeType};if($.numCacheNodes)J.NumCacheNodes=$.numCacheNodes;if($.engineVersion)J.EngineVersion=$.engineVersion;if($.port)J.Port=$.port;if($.securityGroupIds&&$.securityGroupIds.length>0)$.securityGroupIds.forEach((Z,Q)=>{J[`SecurityGroupIds.member.${Q+1}`]=Z});if($.subnetGroupName)J.CacheSubnetGroupName=$.subnetGroupName;if($.tags&&$.tags.length>0)$.tags.forEach((Z,Q)=>{J[`Tags.member.${Q+1}.Key`]=Z.Key,J[`Tags.member.${Q+1}.Value`]=Z.Value});let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheCluster:this.parseCacheCluster(Y)}}async deleteCacheCluster($,J){let Y={Action:"DeleteCacheCluster",Version:"2015-02-02",CacheClusterId:$};if(J)Y.FinalSnapshotIdentifier=J;await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async rebootCacheCluster($,J){let Y={Action:"RebootCacheCluster",Version:"2015-02-02",CacheClusterId:$};J.forEach((Z,Q)=>{Y[`CacheNodeIdsToReboot.member.${Q+1}`]=Z}),await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(Y).toString()})}async describeCacheEngineVersions($){let J={Action:"DescribeCacheEngineVersions",Version:"2015-02-02"};if($)J.Engine=$;let Y=await this.client.request({service:"elasticache",region:this.region,method:"POST",path:"/",body:new URLSearchParams(J).toString()});return{CacheEngineVersions:[]}}async getCacheStatistics($){let J=await this.describeCacheClusters($);if(!J.CacheClusters||J.CacheClusters.length===0)throw Error(`Cache cluster ${$} not found`);return{cpuUtilization:0,evictions:0,hits:0,misses:0,connections:0}}parseCacheClusters($){if($.CacheClusterId)return[{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"available",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}];return[]}parseCacheCluster($){return{CacheClusterId:$.CacheClusterId,CacheClusterStatus:$.CacheClusterStatus||"creating",Engine:$.Engine||"redis",EngineVersion:$.EngineVersion||"7.0",CacheNodeType:$.CacheNodeType||"cache.t3.micro",NumCacheNodes:Number.parseInt($.NumCacheNodes||"1"),CacheClusterCreateTime:$.CacheClusterCreateTime||new Date().toISOString()}}}Y0();class t1{client;region;constructor($="us-east-1",J){this.region=$,this.client=new i}async createRule($){let J={Action:"PutRule",Name:$.name,ScheduleExpression:$.scheduleExpression,Version:"2015-10-07"};if($.description)J.Description=$.description;if($.state)J.State=$.state;else J.State="ENABLED";return{RuleArn:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$.name,ScheduleExpression:$.scheduleExpression,State:$.state||"ENABLED",Description:$.description})})).RuleArn}}async putTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.PutTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Targets:J})})}async listRules($){let J={};if($)J.NamePrefix=$;return{Rules:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListRules","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify(J)})).Rules||[]}}async describeRule($){let J=await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DescribeRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})});return{Name:J.Name,Arn:J.Arn,ScheduleExpression:J.ScheduleExpression,State:J.State,Description:J.Description}}async listTargetsByRule($){return{Targets:(await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.ListTargetsByRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$})})).Targets||[]}}async deleteRule($,J){if(J)try{let Y=await this.listTargetsByRule($);if(Y.Targets&&Y.Targets.length>0)await this.removeTargets($,Y.Targets.map((Z)=>Z.Id))}catch{}await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DeleteRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$,Force:J||!1})})}async removeTargets($,J){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.RemoveTargets","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Rule:$,Ids:J})})}async enableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.EnableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async disableRule($){await this.client.request({service:"events",region:this.region,method:"POST",path:"/",headers:{"X-Amz-Target":"AWSEvents.DisableRule","Content-Type":"application/x-amz-json-1.1"},body:JSON.stringify({Name:$})})}async createLambdaSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.functionArn,Input:$.input}]),J}async createEcsSchedule($){let J=await this.createRule({name:$.name,scheduleExpression:$.scheduleExpression,description:$.description,state:"ENABLED"});return await this.putTargets($.name,[{Id:"1",Arn:$.clusterArn,RoleArn:$.roleArn,Input:JSON.stringify({containerOverrides:[]})}]),J}async listSchedules($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;if($?.State)J.State=$.State;let Y=$?.GroupName||"default";return{Schedules:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedules",queryParams:{...J,ScheduleGroup:Y}}))?.Schedules||[]}}async getSchedule($){try{let J={};if($.GroupName)J.groupName=$.GroupName;return await this.client.request({service:"scheduler",region:this.region,method:"GET",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}catch(J){if(J.statusCode===404||J.code==="ResourceNotFoundException")return null;throw J}}async createSchedule($){let J={ScheduleExpression:$.ScheduleExpression,FlexibleTimeWindow:$.FlexibleTimeWindow,Target:$.Target};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description)J.Description=$.Description;if($.State)J.State=$.State;if($.StartDate)J.StartDate=$.StartDate.toISOString();if($.EndDate)J.EndDate=$.EndDate.toISOString();return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"POST",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async updateSchedule($){let J={};if($.GroupName)J.GroupName=$.GroupName;if($.ScheduleExpression)J.ScheduleExpression=$.ScheduleExpression;if($.ScheduleExpressionTimezone)J.ScheduleExpressionTimezone=$.ScheduleExpressionTimezone;if($.Description!==void 0)J.Description=$.Description;if($.State)J.State=$.State;if($.FlexibleTimeWindow)J.FlexibleTimeWindow=$.FlexibleTimeWindow;if($.Target)J.Target=$.Target;return{ScheduleArn:(await this.client.request({service:"scheduler",region:this.region,method:"PUT",path:`/schedules/${encodeURIComponent($.Name)}`,headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}))?.ScheduleArn||""}}async deleteSchedule($){let J={};if($.GroupName)J.groupName=$.GroupName;await this.client.request({service:"scheduler",region:this.region,method:"DELETE",path:`/schedules/${encodeURIComponent($.Name)}`,queryParams:Object.keys(J).length>0?J:void 0})}async listScheduleGroups($){let J={};if($?.NamePrefix)J.NamePrefix=$.NamePrefix;return{ScheduleGroups:(await this.client.request({service:"scheduler",region:this.region,method:"GET",path:"/schedule-groups",queryParams:Object.keys(J).length>0?J:void 0}))?.ScheduleGroups||[]}}}T7();Y0();I0();U9();I0();I0();I0();Y0();I0();Y0();mQ();$2();$2();o2();K$();J9();Y9();Y9();await z8([Q1(),CZ(),a7()]);$2();await j$();n0();z0();var UX=["aws","backblaze","hetzner"];function HX($,J){let Y=$.indexOf(":");if(Y===-1)throw Error(`--${J} must be in the form <provider:bucket> (e.g. aws:my-bucket), got "${$}"`);let Z=$.slice(0,Y),Q=$.slice(Y+1);if(!UX.includes(Z))throw Error(`Unknown provider "${Z}" for --${J}. Supported: ${UX.join(", ")}`);if(!Q)throw Error(`--${J} is missing a bucket name (expected <provider:bucket>)`);return{provider:Z,bucket:Q}}function FX($){if(!$)return;let J=$.split(",").map((Y)=>Y.trim()).filter(Boolean);return J.length>0?J:void 0}function RG($){$.command("migrate:storage","Migrate object-storage data between providers (AWS S3 ↔ Hetzner ↔ Backblaze)").option("--from <provider:bucket>","Source endpoint, e.g. aws:stacks-production-email").option("--to <provider:bucket>","Destination endpoint, e.g. hetzner:stacks-mail").option("--from-region <region>","Source region/location (default: provider default)").option("--to-region <region>","Destination region/location (default: provider default)").option("--from-endpoint <host>","Source endpoint host override (no scheme)").option("--to-endpoint <host>","Destination endpoint host override (no scheme)").option("--from-prefix <prefix>","Only read source keys under this prefix (stripped from dest key)").option("--to-prefix <prefix>","Prepend this prefix to every destination key").option("--include <csv>","Only copy keys under these comma-separated prefixes").option("--exclude <csv>","Skip keys under these comma-separated prefixes").option("--dry-run","Print the plan (what would copy / what is excluded) without writing").option("--force","Re-copy even if the destination already has an object of the same size").option("--delete-extraneous","Delete destination keys not present in the source (default OFF)").option("--concurrency <n>","Max concurrent copies",{default:"8"}).option("--verify","After copying, re-list the destination and assert object count + sizes match").action(async(J)=>{R("Migrate Object Storage");try{if(!J.from||!J.to)throw Error("Both --from <provider:bucket> and --to <provider:bucket> are required");let Y=HX(J.from,"from"),Z=HX(J.to,"to"),Q=FX(J.include),G=FX(J.exclude),W=Number.parseInt(J.concurrency||"8",10),z={provider:Y.provider,bucket:Y.bucket,region:J.fromRegion,endpoint:J.fromEndpoint,prefix:J.fromPrefix},U={provider:Z.provider,bucket:Z.bucket,region:J.toRegion,endpoint:J.toEndpoint,prefix:J.toPrefix};if(X(`Source: ${Y.provider}:${Y.bucket}${J.fromPrefix?`/${J.fromPrefix}`:""}`),X(`Destination: ${Z.provider}:${Z.bucket}${J.toPrefix?`/${J.toPrefix}`:""}`),Q)X(`Include: ${Q.join(", ")}`);if(G)X(`Exclude: ${G.join(", ")}`);if(X(`Concurrency: ${W}`),J.dryRun)v("Dry run — no objects will be written");if(J.deleteExtraneous&&!J.dryRun)v("Delete-extraneous ON — destination keys not in the source will be removed");let H=new N("Listing source objects...");H.start();let F=0,B=await wG({from:z,to:U,include:Q,exclude:G,dryRun:J.dryRun,force:J.force,deleteExtraneous:J.deleteExtraneous,concurrency:W,verify:J.verify,onProgress:(K)=>{if(K.index-F>=1||K.index===K.total){F=K.index;let O=K.action==="planned"?"plan":K.action;H.text=`[${K.index}/${K.total}] ${O}: ${K.key}`}}});if(H.succeed(J.dryRun?"Plan ready":"Migration complete"),J.dryRun&&B.plan){X(`
|
|
8159
8159
|
Would copy ${B.plan.length} object(s):`);for(let K of B.plan.slice(0,50))X(` ${K.key} -> ${K.destKey} (${f9(K.size)})`);if(B.plan.length>50)X(` ... and ${B.plan.length-50} more`)}if(B.excludedKeys.length>0){X(`
|
|
8160
8160
|
EXCLUDED ${B.excludedKeys.length} key(s) (deliberately not migrated):`);for(let K of B.excludedKeys.slice(0,50))X(` ${K}`);if(B.excludedKeys.length>50)X(` ... and ${B.excludedKeys.length-50} more`)}if(B.deleted.length>0){v(`
|
|
8161
8161
|
Deleted ${B.deleted.length} extraneous destination key(s):`);for(let K of B.deleted.slice(0,50))v(` ${K}`)}if(X(`
|
|
@@ -8272,19 +8272,19 @@ Tags:`);for(let U of Q.Tags)X(` ${U.Key}: ${U.Value}`)}}catch(Y){w(`Failed to g
|
|
|
8272
8272
|
Policy: ${J}`),X(`Action: ${Q}`),X(`Resource: ${G}`);let W=new N("Running simulation...");W.start();let z=await Z.simulatePrincipalPolicy({PolicySourceArn:J,ActionNames:[Q],ResourceArns:[G]});if(W.succeed("Simulation complete"),z.EvaluationResults&&z.EvaluationResults.length>0)for(let U of z.EvaluationResults){let H=U.EvalDecision;if(X(`
|
|
8273
8273
|
Result for ${U.EvalActionName}:`),H==="allowed")h(" Decision: ALLOWED");else if(H==="implicitDeny")v(" Decision: IMPLICIT DENY (no matching allow statement)");else w(" Decision: EXPLICIT DENY");if(U.MatchedStatements&&U.MatchedStatements.length>0){X(" Matched Statements:");for(let F of U.MatchedStatements)X(` - ${F.SourcePolicyId}: ${F.SourcePolicyType}`)}}}catch(Z){w(`Failed to simulate policy: ${Z.message}`),process.exit(1)}}),$.command("iam:whoami","Show current IAM identity").action(async()=>{R("Current IAM Identity");try{let J=new M1,Y=new N("Fetching identity...");Y.start();let{STSClient:Z}=await Promise.resolve().then(() => (F7(),WH)),G=await new Z("us-east-1").getCallerIdentity();Y.succeed("Identity loaded"),X(`
|
|
8274
8274
|
Caller Identity:`),X(` Account: ${G.Account}`),X(` ARN: ${G.Arn}`),X(` User ID: ${G.UserId}`);let W=G.Arn||"";if(W.includes(":user/"))X(" Type: IAM User");else if(W.includes(":assumed-role/"))X(" Type: Assumed Role");else if(W.includes(":root"))v(" Type: Root Account"),v(`
|
|
8275
|
-
Warning: Using root credentials is not recommended!`)}catch(J){w(`Failed to get identity: ${J.message}`),process.exit(1)}})}z0();async function
|
|
8275
|
+
Warning: Using root credentials is not recommended!`)}catch(J){w(`Failed to get identity: ${J.message}`),process.exit(1)}})}z0();async function i2($){let{AWSClient:J}=await Promise.resolve().then(() => (Y0(),I2));class Y{client;region;constructor(Z){this.region=Z,this.client=new J}async jsonRpcRequest(Z,Q){return this.client.request({service:"cloudtrail",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":`com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.${Z}`},body:JSON.stringify(Q)})}async describeTrails(){return this.jsonRpcRequest("DescribeTrails",{})}async getTrailStatus(Z){return this.jsonRpcRequest("GetTrailStatus",{Name:Z})}async lookupEvents(Z){return this.jsonRpcRequest("LookupEvents",{...Z,StartTime:Z.StartTime?.toISOString(),EndTime:Z.EndTime?.toISOString()})}async getEventSelectors(Z){return this.jsonRpcRequest("GetEventSelectors",{TrailName:Z})}async createTrail(Z){return this.jsonRpcRequest("CreateTrail",Z)}async startLogging(Z){return this.jsonRpcRequest("StartLogging",{Name:Z})}async stopLogging(Z){return this.jsonRpcRequest("StopLogging",{Name:Z})}async deleteTrail(Z){return this.jsonRpcRequest("DeleteTrail",{Name:Z})}}return new Y($)}function bG($){$.command("audit:trails","List CloudTrail trails").option("--region <region>","AWS region").action(async(J)=>{R("CloudTrail Trails");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",Q=await i2(Z),G=new N("Fetching trails...");G.start();let z=(await Q.describeTrails()).trailList||[];if(G.succeed(`Found ${z.length} trail(s)`),z.length===0){X("No CloudTrail trails found"),X("Use `cloud audit:create` to create a new trail");return}p(["Name","Multi-Region","S3 Bucket","Log Validation","Home Region"],z.map((U)=>[U.Name||"N/A",U.IsMultiRegionTrail?"Yes":"No",U.S3BucketName||"N/A",U.LogFileValidationEnabled?"Yes":"No",U.HomeRegion||"N/A"]))}catch(Y){w(`Failed to list trails: ${Y.message}`),process.exit(1)}}),$.command("audit:trail <trailName>","Show CloudTrail trail details").option("--region <region>","AWS region").action(async(J,Y)=>{R(`CloudTrail: ${J}`);try{let Z=await m(),Q=Y.region||Z.project.region||"us-east-1",G=await i2(Q),W=new N("Fetching trail details...");W.start();let[z,U]=await Promise.all([G.describeTrails(),G.getTrailStatus(J)]),H=(z.trailList||[]).find((F)=>F.Name===J);if(!H){W.fail("Trail not found");return}if(W.succeed("Trail details loaded"),X(`
|
|
8276
8276
|
Trail Configuration:`),X(` Name: ${H.Name}`),X(` ARN: ${H.TrailARN}`),X(` Home Region: ${H.HomeRegion}`),X(` Multi-Region: ${H.IsMultiRegionTrail?"Yes":"No"}`),X(` Organization Trail: ${H.IsOrganizationTrail?"Yes":"No"}`),X(`
|
|
8277
8277
|
Storage:`),X(` S3 Bucket: ${H.S3BucketName}`),H.S3KeyPrefix)X(` S3 Prefix: ${H.S3KeyPrefix}`);if(X(` Log Validation: ${H.LogFileValidationEnabled?"Enabled":"Disabled"}`),H.CloudWatchLogsLogGroupArn)X(`
|
|
8278
8278
|
CloudWatch Logs:`),X(` Log Group: ${H.CloudWatchLogsLogGroupArn}`);if(H.KMSKeyId)X(`
|
|
8279
8279
|
Encryption:`),X(` KMS Key: ${H.KMSKeyId}`);if(X(`
|
|
8280
8280
|
Status:`),X(` Logging: ${U.IsLogging?"Active":"Stopped"}`),U.LatestDeliveryTime)X(` Latest Delivery: ${new Date(U.LatestDeliveryTime).toLocaleString()}`);if(U.LatestDeliveryError)v(` Latest Error: ${U.LatestDeliveryError}`);try{let F=await G.getEventSelectors(J);if(F.EventSelectors&&F.EventSelectors.length>0){X(`
|
|
8281
|
-
Event Selectors:`);for(let B of F.EventSelectors)if(X(` - Read/Write: ${B.ReadWriteType}`),X(` Management Events: ${B.IncludeManagementEvents?"Yes":"No"}`),B.DataResources&&B.DataResources.length>0)X(` Data Resources: ${B.DataResources.length} configured`)}}catch{}}catch(Z){w(`Failed to get trail: ${Z.message}`),process.exit(1)}}),$.command("audit:events","Look up recent CloudTrail events").option("--region <region>","AWS region").option("--user <username>","Filter by IAM user").option("--event <eventName>","Filter by event name").option("--resource <resourceName>","Filter by resource name").option("--hours <number>","Hours to look back",{default:"24"}).option("--limit <number>","Maximum events to return",{default:"50"}).action(async(J)=>{R("CloudTrail Events");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",Q=await
|
|
8281
|
+
Event Selectors:`);for(let B of F.EventSelectors)if(X(` - Read/Write: ${B.ReadWriteType}`),X(` Management Events: ${B.IncludeManagementEvents?"Yes":"No"}`),B.DataResources&&B.DataResources.length>0)X(` Data Resources: ${B.DataResources.length} configured`)}}catch{}}catch(Z){w(`Failed to get trail: ${Z.message}`),process.exit(1)}}),$.command("audit:events","Look up recent CloudTrail events").option("--region <region>","AWS region").option("--user <username>","Filter by IAM user").option("--event <eventName>","Filter by event name").option("--resource <resourceName>","Filter by resource name").option("--hours <number>","Hours to look back",{default:"24"}).option("--limit <number>","Maximum events to return",{default:"50"}).action(async(J)=>{R("CloudTrail Events");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",Q=await i2(Z),G=new N("Looking up events...");G.start();let W=new Date,U={StartTime:new Date(W.getTime()-Number.parseInt(J.hours)*60*60*1000),EndTime:W,MaxResults:Number.parseInt(J.limit)};if(J.user)U.LookupAttributes=[{AttributeKey:"Username",AttributeValue:J.user}];else if(J.event)U.LookupAttributes=[{AttributeKey:"EventName",AttributeValue:J.event}];else if(J.resource)U.LookupAttributes=[{AttributeKey:"ResourceName",AttributeValue:J.resource}];let F=(await Q.lookupEvents(U)).Events||[];if(G.succeed(`Found ${F.length} event(s)`),F.length===0){X("No events found matching criteria");return}p(["Time","Event","User","Source IP","Resources"],F.map((B)=>[B.EventTime?new Date(B.EventTime).toLocaleString():"N/A",B.EventName||"N/A",B.Username||"N/A",B.SourceIPAddress||"N/A",(B.Resources||[]).map((K)=>K.ResourceName).join(", ").substring(0,30)||"-"]))}catch(Y){w(`Failed to lookup events: ${Y.message}`),process.exit(1)}}),$.command("audit:event <eventId>","Show CloudTrail event details").option("--region <region>","AWS region").action(async(J,Y)=>{R(`Event: ${J}`);try{let Z=await m(),Q=Y.region||Z.project.region||"us-east-1",G=await i2(Q),W=new N("Fetching event...");W.start();let U=(await G.lookupEvents({LookupAttributes:[{AttributeKey:"EventId",AttributeValue:J}],MaxResults:1})).Events?.[0];if(!U){W.fail("Event not found");return}if(W.succeed("Event loaded"),X(`
|
|
8282
8282
|
Event Information:`),X(` Event ID: ${U.EventId}`),X(` Event Name: ${U.EventName}`),X(` Event Time: ${U.EventTime?new Date(U.EventTime).toLocaleString():"N/A"}`),X(` Event Source: ${U.EventSource}`),X(` Username: ${U.Username}`),X(` Source IP: ${U.SourceIPAddress}`),X(` Access Key: ${U.AccessKeyId||"N/A"}`),U.Resources&&U.Resources.length>0){X(`
|
|
8283
8283
|
Resources:`);for(let H of U.Resources)X(` - ${H.ResourceType}: ${H.ResourceName}`)}if(U.CloudTrailEvent){X(`
|
|
8284
|
-
Full Event Record:`);let H=JSON.parse(U.CloudTrailEvent);console.log(JSON.stringify(H,null,2))}}catch(Z){w(`Failed to get event: ${Z.message}`),process.exit(1)}}),$.command("audit:create <trailName>","Create a new CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bucket <name>","S3 bucket for logs").option("--prefix <prefix>","S3 key prefix").option("--multi-region","Enable multi-region trail").option("--validation","Enable log file validation").option("--global-events","Include global service events").action(async(J,Y)=>{R("Create CloudTrail Trail");try{if(!Y.bucket){w("--bucket is required");return}let Z=await
|
|
8284
|
+
Full Event Record:`);let H=JSON.parse(U.CloudTrailEvent);console.log(JSON.stringify(H,null,2))}}catch(Z){w(`Failed to get event: ${Z.message}`),process.exit(1)}}),$.command("audit:create <trailName>","Create a new CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).option("--bucket <name>","S3 bucket for logs").option("--prefix <prefix>","S3 key prefix").option("--multi-region","Enable multi-region trail").option("--validation","Enable log file validation").option("--global-events","Include global service events").action(async(J,Y)=>{R("Create CloudTrail Trail");try{if(!Y.bucket){w("--bucket is required");return}let Z=await i2(Y.region);if(X(`Trail Name: ${J}`),X(`S3 Bucket: ${Y.bucket}`),X(`Multi-Region: ${Y.multiRegion?"Yes":"No"}`),X(`Log Validation: ${Y.validation?"Yes":"No"}`),X(`Global Events: ${Y.globalEvents?"Yes":"No"}`),!await g(`
|
|
8285
8285
|
Create this trail?`,!0)){X("Operation cancelled");return}let G=new N("Creating trail...");G.start();let W=await Z.createTrail({Name:J,S3BucketName:Y.bucket,S3KeyPrefix:Y.prefix,IsMultiRegionTrail:Y.multiRegion,EnableLogFileValidation:Y.validation,IncludeGlobalServiceEvents:Y.globalEvents??!0});G.text="Starting logging...",await Z.startLogging(J),G.succeed("Trail created and logging started"),h(`
|
|
8286
|
-
Trail ARN: ${W.TrailARN}`),X(`S3 Bucket: ${W.S3BucketName}`)}catch(Z){w(`Failed to create trail: ${Z.message}`),process.exit(1)}}),$.command("audit:start <trailName>","Start CloudTrail logging").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{R("Start CloudTrail Logging");try{let Z=await
|
|
8287
|
-
Stop logging?`,!1)){X("Operation cancelled");return}let G=new N("Stopping logging...");G.start(),await Z.stopLogging(J),G.succeed("Logging stopped")}catch(Z){w(`Failed to stop logging: ${Z.message}`),process.exit(1)}}),$.command("audit:delete <trailName>","Delete a CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{R("Delete CloudTrail Trail");try{let Z=await
|
|
8286
|
+
Trail ARN: ${W.TrailARN}`),X(`S3 Bucket: ${W.S3BucketName}`)}catch(Z){w(`Failed to create trail: ${Z.message}`),process.exit(1)}}),$.command("audit:start <trailName>","Start CloudTrail logging").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{R("Start CloudTrail Logging");try{let Z=await i2(Y.region),Q=new N("Starting logging...");Q.start(),await Z.startLogging(J),Q.succeed("Logging started")}catch(Z){w(`Failed to start logging: ${Z.message}`),process.exit(1)}}),$.command("audit:stop <trailName>","Stop CloudTrail logging").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{R("Stop CloudTrail Logging");try{let Z=await i2(Y.region);if(v(`This will stop logging for trail: ${J}`),!await g(`
|
|
8287
|
+
Stop logging?`,!1)){X("Operation cancelled");return}let G=new N("Stopping logging...");G.start(),await Z.stopLogging(J),G.succeed("Logging stopped")}catch(Z){w(`Failed to stop logging: ${Z.message}`),process.exit(1)}}),$.command("audit:delete <trailName>","Delete a CloudTrail trail").option("--region <region>","AWS region",{default:"us-east-1"}).action(async(J,Y)=>{R("Delete CloudTrail Trail");try{let Z=await i2(Y.region);if(v(`This will permanently delete trail: ${J}`),!await g(`
|
|
8288
8288
|
Delete this trail?`,!1)){X("Operation cancelled");return}let G=new N("Deleting trail...");G.start(),await Z.deleteTrail(J),G.succeed("Trail deleted")}catch(Z){w(`Failed to delete trail: ${Z.message}`),process.exit(1)}})}z0();function yG($){$.command("status","Show overall infrastructure health dashboard").option("--region <region>","AWS region").action(async(J)=>{R("Infrastructure Status Dashboard");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1";X(`Region: ${Z}`),X(`Project: ${Y.project.name||"Unknown"}`),X("");let Q=[],G=new N("Checking EC2 instances...");G.start();try{let{EC2Client:A}=await Promise.resolve().then(() => (Z9(),FH)),M=await new A(Z).describeInstances({Filters:[{Name:"instance-state-name",Values:["running","pending","stopping","stopped"]}]}),E=0,j=0,q=0;for(let T of M.Reservations||[])for(let D of T.Instances||[])if(q++,D.State?.Name==="running")E++;else if(D.State?.Name==="stopped")j++;G.succeed("EC2 instances checked"),Q.push({name:"EC2 Instances",status:E>0?"OK":q>0?"WARN":"INFO",details:`${E} running, ${j} stopped, ${q} total`})}catch(A){G.fail("EC2 check failed"),Q.push({name:"EC2 Instances",status:"ERROR",details:A.message})}let W=new N("Checking RDS instances...");W.start();try{let{RDSClient:A}=await Promise.resolve().then(() => (t8(),J7)),E=(await new A(Z).describeDBInstances()).DBInstances||[],j=E.filter((q)=>q.DBInstanceStatus==="available").length;W.succeed("RDS instances checked"),Q.push({name:"RDS Databases",status:E.length>0&&j===E.length?"OK":E.length>0?"WARN":"INFO",details:`${j} available, ${E.length} total`})}catch(A){W.fail("RDS check failed"),Q.push({name:"RDS Databases",status:"ERROR",details:A.message})}let z=new N("Checking Lambda functions...");z.start();try{let{LambdaClient:A}=await Promise.resolve().then(() => (n1(),m$)),E=(await new A(Z).listFunctions()).Functions||[];z.succeed("Lambda functions checked"),Q.push({name:"Lambda Functions",status:"OK",details:`${E.length} function(s)`})}catch(A){z.fail("Lambda check failed"),Q.push({name:"Lambda Functions",status:"ERROR",details:A.message})}let U=new N("Checking S3 buckets...");U.start();try{let{S3Client:A}=await Promise.resolve().then(() => (I0(),l$)),E=(await new A(Z).listBuckets()).Buckets||[];U.succeed("S3 buckets checked"),Q.push({name:"S3 Buckets",status:"OK",details:`${E.length} bucket(s)`})}catch(A){U.fail("S3 check failed"),Q.push({name:"S3 Buckets",status:"ERROR",details:A.message})}let H=new N("Checking CloudFront distributions...");H.start();try{let{CloudFrontClient:A}=await Promise.resolve().then(() => (W2(),iZ)),M=await new A().listDistributions(),E=M.filter((j)=>j.Status==="Deployed").length;H.succeed("CloudFront checked"),Q.push({name:"CloudFront",status:M.length>0&&E===M.length?"OK":M.length>0?"WARN":"INFO",details:`${E} deployed, ${M.length} total`})}catch(A){H.fail("CloudFront check failed"),Q.push({name:"CloudFront",status:"ERROR",details:A.message})}let F=new N("Checking SQS queues...");F.start();try{let{SQSClient:A}=await Promise.resolve().then(() => (D9(),jF)),E=(await new A(Z).listQueues()).QueueUrls||[];F.succeed("SQS queues checked"),Q.push({name:"SQS Queues",status:"OK",details:`${E.length} queue(s)`})}catch(A){F.fail("SQS check failed"),Q.push({name:"SQS Queues",status:"ERROR",details:A.message})}let B=new N("Checking CloudFormation stacks...");B.start();try{let{CloudFormationClient:A}=await Promise.resolve().then(() => (L1(),jZ)),E=(await new A(Z).listStacks(["CREATE_COMPLETE","UPDATE_COMPLETE","CREATE_IN_PROGRESS","UPDATE_IN_PROGRESS","ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE"])).StackSummaries||[],j=E.filter((D)=>D.StackStatus==="CREATE_COMPLETE"||D.StackStatus==="UPDATE_COMPLETE").length,q=E.filter((D)=>D.StackStatus?.includes("IN_PROGRESS")).length,T=E.filter((D)=>D.StackStatus?.includes("ROLLBACK")).length;B.succeed("CloudFormation checked"),Q.push({name:"CloudFormation",status:T>0?"WARN":q>0?"INFO":"OK",details:`${j} healthy, ${q} in progress, ${T} rolled back`})}catch(A){B.fail("CloudFormation check failed"),Q.push({name:"CloudFormation",status:"ERROR",details:A.message})}let K=new N("Checking SSL certificates...");K.start();try{let{ACMClient:A}=await Promise.resolve().then(() => (j2(),v4)),_=new A("us-east-1"),E=(await _.listCertificates()).CertificateSummaryList||[],j=await Promise.all(E.map((S)=>_.describeCertificate({CertificateArn:S.CertificateArn}))),q=j.filter((S)=>S.Status==="ISSUED").length,T=j.filter((S)=>S.Status==="PENDING_VALIDATION").length,D=j.filter((S)=>{if(S.NotAfter)return(new Date(S.NotAfter).getTime()-Date.now())/86400000<30;return!1}).length;K.succeed("SSL certificates checked"),Q.push({name:"SSL Certificates",status:D>0?"WARN":T>0?"INFO":"OK",details:`${q} issued, ${T} pending${D>0?`, ${D} expiring soon`:""}`})}catch(A){K.fail("ACM check failed"),Q.push({name:"SSL Certificates",status:"ERROR",details:A.message})}X(`
|
|
8289
8289
|
`+"=".repeat(60)),X("HEALTH SUMMARY"),X("=".repeat(60)+`
|
|
8290
8290
|
`);for(let A of Q){let _="";if(A.status==="OK")_=`${X0.green}[OK]${X0.reset}`;else if(A.status==="WARN")_=`${X0.yellow}[WARN]${X0.reset}`;else if(A.status==="ERROR")_=`${X0.red}[ERROR]${X0.reset}`;else _=`${X0.blue}[INFO]${X0.reset}`;console.log(`${_} ${A.name.padEnd(20)} ${A.details}`)}let O=Q.some((A)=>A.status==="ERROR"),V=Q.some((A)=>A.status==="WARN");if(X(""),O)w("Some services have errors. Check the details above.");else if(V)v("Some services need attention. Check the warnings above.");else h("All services are healthy!")}catch(Y){w(`Failed to get status: ${Y.message}`),process.exit(1)}}),$.command("status:costs","Show current month cost summary").option("--region <region>","AWS region").action(async(J)=>{R("Cost Summary");try{X("Fetching cost data from AWS Cost Explorer..."),X("");let Y=new Date,Z=new Date(Y.getFullYear(),Y.getMonth(),1),Q=new Date(Y.getFullYear(),Y.getMonth()+1,0);X(`Period: ${Z.toISOString().split("T")[0]} to ${Q.toISOString().split("T")[0]}`),X(""),X("Note: Cost data requires AWS Cost Explorer API access."),X("Run `cloud cost` for detailed cost analysis.")}catch(Y){w(`Failed to get cost summary: ${Y.message}`),process.exit(1)}}),$.command("status:alarms","Show CloudWatch alarm status").option("--region <region>","AWS region").action(async(J)=>{R("CloudWatch Alarms");try{let Y=await m(),Z=J.region||Y.project.region||"us-east-1",{AWSClient:Q}=await Promise.resolve().then(() => (Y0(),I2));class G{client;region;constructor(O){this.region=O,this.client=new Q}async describeAlarms(){return this.client.request({service:"monitoring",region:this.region,method:"POST",path:"/",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:"Action=DescribeAlarms&Version=2010-08-01"})}}let W=new G(Z),z=new N("Fetching alarms...");z.start();let H=(await W.describeAlarms()).MetricAlarms||[];if(z.succeed(`Found ${H.length} alarm(s)`),H.length===0){X("No CloudWatch alarms configured");return}let F=H.filter((O)=>O.StateValue==="ALARM"),B=H.filter((O)=>O.StateValue==="OK"),K=H.filter((O)=>O.StateValue==="INSUFFICIENT_DATA");if(X(""),X(`Alarming: ${F.length}`),X(`OK: ${B.length}`),X(`Insufficient Data: ${K.length}`),F.length>0){X(`
|