@stacksjs/actions 0.75.439 → 0.75.445
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/blog-admin.d.ts +1 -1
- package/dist/bump.js +1 -1
- package/dist/deploy/index.js +1 -1
- package/dist/deploy/stack.d.ts +35 -0
- package/dist/deploy/stack.js +92 -0
- package/dist/release-push-target.d.ts +2 -2
- package/dist/release-push-target.js +2 -2
- package/dist/release.js +1 -1
- package/package.json +43 -43
package/dist/blog-admin.d.ts
CHANGED
package/dist/bump.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions(),rawBump=options?.bump?.toString(),bumpArg=rawBump?isReleaseType(rawBump)||isCalendarBump(rawBump)||isValidVersion(rawBump)?rawBump:null:null;if(rawBump&&!bumpArg)throw Error(`Invalid --bump "${rawBump}"; expected a Bumpx release type, calendar, or semantic version`);const isDryRun=options?.dryRun===!0,isVerbose=options?.verbose===!0;async function readPackage(file){if(!existsSync(file))return;return await Bun.file(file).json()}const rootManifest=p.projectPath("package.json"),rootPkg=await readPackage(rootManifest),isFrameworkRelease=rootPkg?.name==="stacks"&&existsSync(p.frameworkPath("core/package.json")),bumpCwd=isFrameworkRelease?p.frameworkPath("core"):p.projectPath(),primaryManifest=isFrameworkRelease?p.frameworkPath("core/package.json"):rootManifest;async function resolveBumpArg(bump){if(!bump)return bump;if(isCalendarBump(bump)){const pkg=await readPackage(primaryManifest);return nextCalendarVersion(pkg?.version)}const pkg=await readPackage(primaryManifest);if(!pkg?.version)throw Error(`${primaryManifest} declares no version`);return incrementVersion(pkg.version,bump,options?.preid)}const resolvedBumpArg=await resolveBumpArg(bumpArg);async function git(args,cwd=p.projectPath(),options={}){return await execSync(["git",...args],{cwd,stdin:"inherit",stderr:"pipe",throwOnError:options.throwOnError??!0})}const pushTarget=isDryRun?void 0:releasePushTarget(p.projectPath());async function isGitIgnored(file){return(await git(["check-ignore","--",file],p.projectPath(),{throwOnError:!1})).trim().length>0}async function readVersion(file){const pkg=await readPackage(file);if(!pkg?.version||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version))throw Error(`Invalid version in ${file}: ${pkg?.version??"<missing>"}`);return pkg.version}function lockfileVersion(contents){const match=contents.match(/"lockfileVersion"\s*:\s*(\d+)/);return match?Number(match[1]):null}async function packageFilesFor(pattern,cwd){const glob=new Bun.Glob(pattern),files=[];for await(const file of glob.scan({cwd,absolute:!0,onlyFiles:!0})){if(file.includes("/node_modules/")||file.includes("/dist/")||file.includes("/pantry/"))continue;files.push(`./${relative(bumpCwd,file)}`)}return files}async function existingPackageFiles(files){const existing=[];for(const file of files){const absolutePath=join(bumpCwd,file);if(await Bun.file(absolutePath).exists())existing.push(file)}return existing}async function frameworkBumpFiles(){return Array.from(new Set([...await packageFilesFor("package.json",bumpCwd),...await packageFilesFor("*/package.json",bumpCwd),...await packageFilesFor("*/*/package.json",bumpCwd),...await existingPackageFiles(["../package.json","../defaults/ide/vscode/package.json","../api/package.json","../cloud/package.json","../docs/package.json","../orm/package.json","../server/package.json"]),...await packageFilesFor("../libs/**/package.json",bumpCwd)]))}const bumpFiles=isFrameworkRelease?await frameworkBumpFiles():["./package.json"],pantryToolchain=!isDryRun&&existsSync(p.projectPath("pantry.lock"))?resolvePantryToolchain({cwd:p.projectPath()}):void 0;if(pantryToolchain&&!pantryToolchain.ok)throw Error(pantryToolchain.message);log.debug(`Release mode: ${isFrameworkRelease?"framework monorepo":"consumer app"} (${rootPkg?.name??"unknown"})`);log.debug(`Bumping ${bumpFiles.length} package manifest(s) in ${bumpCwd}`);await versionBump({release:resolvedBumpArg??void 0,preid:options?.preid,files:bumpFiles,cwd:bumpCwd,recursive:!1,commit:!1,tag:!1,push:!1,changelog:!1,noGitCheck:!0,dryRun:isDryRun,yes:Boolean(resolvedBumpArg),verbose:isVerbose});const nextVersion=isDryRun&&resolvedBumpArg&&isValidVersion(resolvedBumpArg)?resolvedBumpArg:await readVersion(primaryManifest),latestTag=(await git(["describe","--abbrev=0","--tags"],p.projectPath(),{throwOnError:!1}).catch(()=>"")).trim();async function writeChangelog(){const config=await loadLogsmithConfig({dir:p.projectPath(),from:latestTag||void 0,to:"HEAD",output:isDryRun?!1:"CHANGELOG.md",theme:"github",verbose:isVerbose}),result=await generateChangelog(config);if(isDryRun){log.info(result.content);return}const changelogPath=p.projectPath("CHANGELOG.md");if(!existsSync(changelogPath))return;let content=readFileSync(changelogPath,"utf-8");const versionSeen=new RegExp(`\\bv?${nextVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);if(/\/compare\/[^)\s]+\.\.\.HEAD\)/.test(content))content=content.replace(/(\/compare\/[^)\s]+\.\.\.)HEAD(\))/,`$1v${nextVersion}$2`);else if(!versionSeen.test(content.split(`
|
|
1
|
+
import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions(),rawBump=options?.bump?.toString(),bumpArg=rawBump?isReleaseType(rawBump)||isCalendarBump(rawBump)||isValidVersion(rawBump)?rawBump:null:null;if(rawBump&&!bumpArg)throw Error(`Invalid --bump "${rawBump}"; expected a Bumpx release type, calendar, or semantic version`);const isDryRun=options?.dryRun===!0,isVerbose=options?.verbose===!0;async function readPackage(file){if(!existsSync(file))return;return await Bun.file(file).json()}const rootManifest=p.projectPath("package.json"),rootPkg=await readPackage(rootManifest),isFrameworkRelease=rootPkg?.name==="stacks"&&existsSync(p.frameworkPath("core/package.json")),bumpCwd=isFrameworkRelease?p.frameworkPath("core"):p.projectPath(),primaryManifest=isFrameworkRelease?p.frameworkPath("core/package.json"):rootManifest;async function resolveBumpArg(bump){if(!bump)return bump;if(isCalendarBump(bump)){const pkg=await readPackage(primaryManifest);return nextCalendarVersion(pkg?.version)}const pkg=await readPackage(primaryManifest);if(!pkg?.version)throw Error(`${primaryManifest} declares no version`);return incrementVersion(pkg.version,bump,options?.preid)}const resolvedBumpArg=await resolveBumpArg(bumpArg);async function git(args,cwd=p.projectPath(),options={}){return await execSync(["git",...args],{cwd,stdin:"inherit",stderr:"pipe",throwOnError:options.throwOnError??!0})}const pushTarget=isDryRun?void 0:releasePushTarget(p.projectPath(),isFrameworkRelease?"main":void 0);async function isGitIgnored(file){return(await git(["check-ignore","--",file],p.projectPath(),{throwOnError:!1})).trim().length>0}async function readVersion(file){const pkg=await readPackage(file);if(!pkg?.version||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version))throw Error(`Invalid version in ${file}: ${pkg?.version??"<missing>"}`);return pkg.version}function lockfileVersion(contents){const match=contents.match(/"lockfileVersion"\s*:\s*(\d+)/);return match?Number(match[1]):null}async function packageFilesFor(pattern,cwd){const glob=new Bun.Glob(pattern),files=[];for await(const file of glob.scan({cwd,absolute:!0,onlyFiles:!0})){if(file.includes("/node_modules/")||file.includes("/dist/")||file.includes("/pantry/"))continue;files.push(`./${relative(bumpCwd,file)}`)}return files}async function existingPackageFiles(files){const existing=[];for(const file of files){const absolutePath=join(bumpCwd,file);if(await Bun.file(absolutePath).exists())existing.push(file)}return existing}async function frameworkBumpFiles(){return Array.from(new Set([...await packageFilesFor("package.json",bumpCwd),...await packageFilesFor("*/package.json",bumpCwd),...await packageFilesFor("*/*/package.json",bumpCwd),...await existingPackageFiles(["../package.json","../defaults/ide/vscode/package.json","../api/package.json","../cloud/package.json","../docs/package.json","../orm/package.json","../server/package.json"]),...await packageFilesFor("../libs/**/package.json",bumpCwd)]))}const bumpFiles=isFrameworkRelease?await frameworkBumpFiles():["./package.json"],pantryToolchain=!isDryRun&&existsSync(p.projectPath("pantry.lock"))?resolvePantryToolchain({cwd:p.projectPath()}):void 0;if(pantryToolchain&&!pantryToolchain.ok)throw Error(pantryToolchain.message);log.debug(`Release mode: ${isFrameworkRelease?"framework monorepo":"consumer app"} (${rootPkg?.name??"unknown"})`);log.debug(`Bumping ${bumpFiles.length} package manifest(s) in ${bumpCwd}`);await versionBump({release:resolvedBumpArg??void 0,preid:options?.preid,files:bumpFiles,cwd:bumpCwd,recursive:!1,commit:!1,tag:!1,push:!1,changelog:!1,noGitCheck:!0,dryRun:isDryRun,yes:Boolean(resolvedBumpArg),verbose:isVerbose});const nextVersion=isDryRun&&resolvedBumpArg&&isValidVersion(resolvedBumpArg)?resolvedBumpArg:await readVersion(primaryManifest),latestTag=(await git(["describe","--abbrev=0","--tags"],p.projectPath(),{throwOnError:!1}).catch(()=>"")).trim();async function writeChangelog(){const config=await loadLogsmithConfig({dir:p.projectPath(),from:latestTag||void 0,to:"HEAD",output:isDryRun?!1:"CHANGELOG.md",theme:"github",verbose:isVerbose}),result=await generateChangelog(config);if(isDryRun){log.info(result.content);return}const changelogPath=p.projectPath("CHANGELOG.md");if(!existsSync(changelogPath))return;let content=readFileSync(changelogPath,"utf-8");const versionSeen=new RegExp(`\\bv?${nextVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);if(/\/compare\/[^)\s]+\.\.\.HEAD\)/.test(content))content=content.replace(/(\/compare\/[^)\s]+\.\.\.)HEAD(\))/,`$1v${nextVersion}$2`);else if(!versionSeen.test(content.split(`
|
|
2
2
|
`).slice(0,4).join(`
|
|
3
3
|
`)))content=content.replace(/^(#\s.*\n+)?/,(match)=>`${match??""}## v${nextVersion}
|
|
4
4
|
|
package/dist/deploy/index.js
CHANGED
|
@@ -7,7 +7,7 @@ ${children}${indent}</${name}>
|
|
|
7
7
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
8
8
|
${Object.entries(config).filter(([key])=>!key.startsWith("@_")).map(([key,val])=>buildCloudFrontXmlElement(key,val," ")).join("")}</DistributionConfig>
|
|
9
9
|
`}function firewallOpenCommand(ports){const uniquePorts=[...new Set(ports)].filter((port)=>Number.isFinite(port)&&port>0).sort((a,b)=>a-b);if(uniquePorts.length===0)return"true";return`if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --permanent ${uniquePorts.map((port)=>`--add-port=${port}/tcp`).join(" ")} && firewall-cmd --reload; fi`}async function ensureSecurityGroupPort(ec2,securityGroupId,port){if(!securityGroupId)return;if(((await ec2.describeSecurityGroups({GroupIds:[securityGroupId]}))?.SecurityGroups?.[0]?.IpPermissions||[]).some((permission)=>{return permission.IpProtocol==="tcp"&&Number(permission.FromPort)<=port&&Number(permission.ToPort)>=port&&normalizeArray(permission.IpRanges).some((range)=>range.CidrIp==="0.0.0.0/0")}))return;try{await ec2.authorizeSecurityGroupIngress({GroupId:securityGroupId,IpPermissions:[{IpProtocol:"tcp",FromPort:port,ToPort:port,IpRanges:[{CidrIp:"0.0.0.0/0",Description:`Stacks API port ${port}`}]}]})}catch(error){if(!String(error?.message||"").includes("InvalidPermission.Duplicate"))throw error}}async function ensureCloudFrontApiOriginPort(awsClient,distributionId,port){if(!distributionId)return;const getResult=await awsClient.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${distributionId}/config`,returnHeaders:!0}),etag=getResult.headers?.etag||getResult.headers?.ETag||"",currentConfig=getResult.body?.DistributionConfig||getResult.DistributionConfig||getResult.body;if(!etag||!currentConfig?.Origins?.Items)return;const apiOrigin=normalizeArray(currentConfig.Origins.Items.Origin).find((origin)=>String(origin.Id||"").includes("-api"));if(!apiOrigin?.CustomOriginConfig)return;if(Number(apiOrigin.CustomOriginConfig.HTTPPort)===port)return;apiOrigin.CustomOriginConfig.HTTPPort=port;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:buildCloudFrontDistributionConfigXml(currentConfig),headers:{"Content-Type":"application/xml","If-Match":etag}})}const hookEnvironment=process.env.APP_ENV||process.env.NODE_ENV||"production",{stacksCloudRegion:hookRegion}=await import("@stacksjs/cloud");await runBeforeDeployHook(p.projectPath(),{environment:hookEnvironment,region:await hookRegion(void 0,hookEnvironment)});const frameworkBuildSpinner=spinner("Building framework...");frameworkBuildSpinner.start();const frameworkBuilt=await runCommand("bun run build",{cwd:p.frameworkPath("core"),quiet:!1});if(frameworkBuilt.isErr){frameworkBuildSpinner.fail("Framework build failed - see the output above");process.exit(ExitCode.FatalError)}frameworkBuildSpinner.succeed("Framework built");const docsDir=p.projectPath("docs"),docsBuildDir=p.projectPath("dist/docs/.bunpress");if(storage.hasFiles(docsDir)){const docsSpinner=spinner("Building documentation with BunPress...");docsSpinner.start();try{const{rm}=await import("node:fs/promises"),localBunpressCli=`${process.env.HOME}/Code/Tools/bunpress/packages/bunpress/bin/cli.ts`,installedBunpressCli=p.projectPath("node_modules/@stacksjs/bunpress/dist/bin/cli.js"),hasLocalBunpress=await Bun.file(localBunpressCli).exists(),hasInstalledBunpress=await Bun.file(installedBunpressCli).exists(),command=hasLocalBunpress?`bun ${localBunpressCli} build --dir ${docsDir} --outdir ${p.projectPath("dist/docs")}`:hasInstalledBunpress?`bun ${installedBunpressCli} build --dir ${docsDir} --outdir ${p.projectPath("dist/docs")}`:"bunx @stacksjs/bunpress@0.1.5 build --dir ./docs --outdir ./dist/docs";await rm(docsBuildDir,{recursive:!0,force:!0});await runCommand(command,{cwd:p.projectPath(),quiet:!isVerbose});docsSpinner.succeed(`Documentation built with BunPress${hasLocalBunpress?" (local checkout)":""}`)}catch(docsError){docsSpinner.stop();console.log(`\u26A0 Documentation build skipped: ${docsError.message}`);if(isVerbose)log.debug("To build docs manually: cd ~/Code/Tools/bunpress && bun packages/bunpress/bin/cli.ts build --dir /path/to/docs --outdir /path/to/dist/docs")}}else if(isVerbose)log.debug("No docs directory found, skipping documentation build");const blogDistExists=storage.hasFiles(p.projectPath("dist/blog")),blogFontAssetsExist=["CampmateScript-Regular.woff2","SequoiaSans-Regular.woff2","Switchback-Regular.woff2"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/fonts/nps/${file}`))),blogImageAssetsExist=["topography.svg","park-ridge.svg"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/images/${file}`))),blogIndexPath=p.projectPath("dist/blog/index.html"),blogIndexHtml=existsSync(blogIndexPath)?readFileSync(blogIndexPath,"utf8"):"",blogHtmlUsesCurrentFontFormat=blogIndexHtml.length>0&&!blogIndexHtml.includes("woff2-variations"),blogHtmlUsesCurrentParkTheme=blogIndexHtml.includes("--on-primary")&&blogIndexHtml.includes("--newsletter-bg"),blogHtmlUsesCurrentParkImages=blogIndexHtml.includes("topography.svg")&&blogIndexHtml.includes("park-ridge.svg"),blogHtmlOmitsRetiredDecorations=!blogIndexHtml.includes("stamp-trail")&&!blogIndexHtml.includes("blog-sign-tree.svg"),blogBuilderPath=p.frameworkPath("core/cms/src/build.ts"),blogConfigPath=p.projectPath("config/blog.ts"),blogHtmlIsFresh=existsSync(blogIndexPath)&&[blogBuilderPath,blogConfigPath].filter((path)=>existsSync(path)).every((path)=>statSync(blogIndexPath).mtimeMs>=statSync(path).mtimeMs);if(!blogDistExists||!blogFontAssetsExist||!blogImageAssetsExist||!blogHtmlUsesCurrentFontFormat||!blogHtmlUsesCurrentParkTheme||!blogHtmlUsesCurrentParkImages||!blogHtmlOmitsRetiredDecorations||!blogHtmlIsFresh){const blogBuildSpinner=spinner("Building blog...");blogBuildSpinner.start();try{const blogConfig=(await import(p.projectPath("config/blog"))).default,{buildBlogSite}=await import(p.frameworkPath("core/cms/src/build"));await buildBlogSite({config:blogConfig,outDir:p.projectPath("dist/blog")});blogBuildSpinner.succeed("Blog built successfully")}catch(blogBuildError){blogBuildSpinner.stop();console.log(`\u26A0 Blog build skipped: ${blogBuildError.message}`);if(isVerbose)log.debug(`Blog build error: ${blogBuildError.stack}`)}}else if(isVerbose)log.debug("Pre-built blog found at dist/blog, skipping build");if(isVerbose)log.debug("Skipping views build (vite-config not configured)");const earlyCloudConfig=await import(p.projectPath("config/cloud")),earlyDeploymentMode=earlyCloudConfig?.tsCloud?.mode||"server";if(earlyDeploymentMode==="serverless"){const serverSpinner=spinner("Building server...");serverSpinner.start();if((await runCommand("bun build.ts",{cwd:p.frameworkPath("server"),quiet:!isVerbose})).isErr){serverSpinner.fail("Server build failed - rerun with --verbose to see its output");process.exit(ExitCode.FatalError)}serverSpinner.succeed("Server built");const packageSpinner=spinner("Packaging for deployment...");packageSpinner.start();if((await runCommand("bun zip.ts",{cwd:p.corePath("cloud"),quiet:!isVerbose})).isErr){packageSpinner.fail("Packaging failed - rerun with --verbose to see its output");process.exit(ExitCode.FatalError)}packageSpinner.succeed("Package ready")}else if(isVerbose)log.debug("Skipping server build and packaging (server mode)");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",envFiles=[p.projectPath(`.env.${environment}`),p.projectPath(".env")];for(const envPath of envFiles)if(existsSync(envPath)){const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
|
|
10
|
-
`)){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const eqIndex=trimmed.indexOf("="),key=trimmed.slice(0,eqIndex).trim();let value=trimmed.slice(eqIndex+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key==="AWS_ACCESS_KEY_ID"&&value)process.env.AWS_ACCESS_KEY_ID=value;else if(key==="AWS_SECRET_ACCESS_KEY"&&value)process.env.AWS_SECRET_ACCESS_KEY=value;else if(key==="AWS_REGION"&&value&&!process.env.AWS_REGION)process.env.AWS_REGION=value;else if(key==="AWS_ACCOUNT_ID"&&value&&!process.env.AWS_ACCOUNT_ID)process.env.AWS_ACCOUNT_ID=value;else if(key.startsWith("MAIL_PASSWORD_")&&value&&!process.env[key])process.env[key]=value}if(isVerbose)log.debug(`Loaded AWS credentials from ${envPath}`);break}}try{const{deployStack,deployFrontend:_deployFrontend}=await import("
|
|
10
|
+
`)){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const eqIndex=trimmed.indexOf("="),key=trimmed.slice(0,eqIndex).trim();let value=trimmed.slice(eqIndex+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key==="AWS_ACCESS_KEY_ID"&&value)process.env.AWS_ACCESS_KEY_ID=value;else if(key==="AWS_SECRET_ACCESS_KEY"&&value)process.env.AWS_SECRET_ACCESS_KEY=value;else if(key==="AWS_REGION"&&value&&!process.env.AWS_REGION)process.env.AWS_REGION=value;else if(key==="AWS_ACCOUNT_ID"&&value&&!process.env.AWS_ACCOUNT_ID)process.env.AWS_ACCOUNT_ID=value;else if(key.startsWith("MAIL_PASSWORD_")&&value&&!process.env[key])process.env[key]=value}if(isVerbose)log.debug(`Loaded AWS credentials from ${envPath}`);break}}try{const{deployStack,deployFrontend:_deployFrontend}=await import("./stack"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),region=await stacksCloudRegion(void 0,environment),cloudStackName=await stacksCloudName(),cloudConfigModule=await import(p.projectPath("config/cloud")),deploymentMode=cloudConfigModule?.tsCloud?.mode||"server",projectName=cloudConfigModule?.tsCloud?.project?.name||cloudConfigModule?.tsCloud?.project?.slug||"stacks";if(deploymentMode==="serverless"){console.log("");console.log("Serverless deployment mode detected");console.log("Building and pushing container image...");console.log("");const accountId=process.env.AWS_ACCOUNT_ID||await getAwsAccountId(region);if(!accountId||accountId.length<10)throw Error(`Invalid AWS Account ID: "${accountId||"(empty)"}"
|
|
11
11
|
Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`);const ecrRepository=`${accountId}.dkr.ecr.${region}.amazonaws.com/${projectName}-${environment}-api`,imageTag=`${ecrRepository}:latest`;if(isVerbose)log.debug(`ECR repository: ${ecrRepository}`);if(isVerbose)log.debug("ECR credentials will be validated before push...");const buildSpinner=spinner("Building Docker image...");buildSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),buildCmd=`docker build --platform linux/amd64 -t ${imageTag} -f Dockerfile .`,{stdout,stderr}=await execAsync(buildCmd,{cwd:p.projectPath(),env:process.env,maxBuffer:10485760,timeout:900000});if(isVerbose&&stdout)log.debug(stdout);if(isVerbose&&stderr)log.debug(stderr);buildSpinner.succeed(`Docker image built: ${imageTag}`)}catch(error){buildSpinner.fail("Docker build failed");if(isVerbose)log.debug(`Docker build error: ${error.message}`);throw error}const repoSpinner=spinner("Checking ECR repository...");repoSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),ecr=new ECRClient(region),repoName=`${projectName}-${environment}-api`;try{await ecr.describeRepositories({repositoryNames:[repoName]});repoSpinner.succeed(`ECR repository exists: ${repoName}`)}catch(err){if(err.code==="RepositoryNotFoundException"||err.message?.includes("RepositoryNotFoundException")){repoSpinner.text=`Creating ECR repository: ${repoName}...`;await ecr.createRepository({repositoryName:repoName,imageScanningConfiguration:{scanOnPush:!0},imageTagMutability:"MUTABLE"});repoSpinner.succeed(`ECR repository created: ${repoName}`)}else throw err}}catch(error){repoSpinner.fail("ECR repository check failed");if(isVerbose)log.debug(`ECR repository error: ${error.message}`);throw error}const authSpinner=spinner("Authenticating to ECR...");authSpinner.start();try{const{ECRClient}=await import("@stacksjs/ts-cloud"),token=(await new ECRClient(region).getAuthorizationToken()).authorizationData?.[0];if(!token?.authorizationToken)throw Error("No authorization token received from ECR");const decoded=Buffer.from(token.authorizationToken,"base64").toString("utf-8"),colonIndex=decoded.indexOf(":");if(colonIndex===-1)throw Error("ECR authorization token has unexpected format (missing colon separator)");const password=decoded.slice(colonIndex+1),loginResult=Bun.spawnSync(["docker","login","--username","AWS","--password-stdin",`${accountId}.dkr.ecr.${region}.amazonaws.com`],{stdin:new TextEncoder().encode(password),stdout:"pipe",stderr:"pipe"});if(loginResult.exitCode!==0){const loginError=new TextDecoder().decode(loginResult.stderr);throw Error(`Docker login failed: ${loginError}`)}authSpinner.succeed("Authenticated to ECR")}catch(error){authSpinner.fail("ECR authentication failed");if(isVerbose)log.debug(`ECR auth error: ${error.message}`);throw error}console.log("");const pushSpinner=spinner("Pushing image to ECR...");pushSpinner.start();try{const{exec}=await import("node:child_process"),{promisify}=await import("node:util"),execAsync=promisify(exec),pushCmd=`docker push ${imageTag}`;await execAsync(pushCmd,{env:process.env});pushSpinner.succeed(`Image pushed: ${imageTag}`)}catch(error){pushSpinner.fail("Docker push failed");if(isVerbose)log.debug(`Push error: ${error.message}`);throw error}console.log("");console.log("Container image ready in ECR. CloudFormation will use this image.");console.log("")}else{console.log("");console.log("Server deployment mode detected");console.log("Deploying EC2 infrastructure via CloudFormation...");console.log("")}async function getAwsAccountId(region){try{const{STSClient}=await import("@stacksjs/ts-cloud"),accountId=(await new STSClient(region).getCallerIdentity()).Account||process.env.AWS_ACCOUNT_ID||"";if(isVerbose)log.debug(`Retrieved AWS Account ID: ${accountId||"(empty)"}`);return accountId}catch(error){if(isVerbose)log.debug(`Failed to get AWS Account ID: ${error.message}`);return process.env.AWS_ACCOUNT_ID||""}}await deployStack({environment,region,waitForCompletion:!0,verbose:isVerbose});try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.afterDeploy==="function"){const{CloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new CloudFormationClient(region),stackName=cloudStackName;let stackOutputs={};try{stackOutputs=await cf.getStackOutputs(stackName)}catch(e){if(isVerbose)log.debug(`Failed to get stack outputs: ${e instanceof Error?e.message:String(e)}`)}await deployScript.afterDeploy({environment,region,outputs:stackOutputs})}}catch(hookError){if(hookError.code==="ERR_MODULE_NOT_FOUND"||hookError.code==="MODULE_NOT_FOUND"){if(isVerbose)log.debug("No afterDeploy hook found (cloud/deploy-script not found)")}else{console.warn(`\u26A0 afterDeploy hook failed: ${hookError.message}`);if(isVerbose)log.debug(`afterDeploy error stack: ${hookError.stack}`)}}const migrateSpinner=spinner("Running database migrations...");migrateSpinner.start();try{const{generateMigrations,runDatabaseMigration}=await import("@stacksjs/database");await generateMigrations();await runDatabaseMigration();migrateSpinner.succeed("Database migrations completed")}catch(migrationError){migrateSpinner.stop();console.log(`\u26A0 Database migrations skipped: ${migrationError.message}`);if(isVerbose)log.debug(`Migration error: ${migrationError.stack}`)}const frameworkTablesSpinner=spinner("Ensuring framework tables (auth, notifications, RBAC, traits)...");frameworkTablesSpinner.start();try{const{ensureUtcDatetimeColumns,migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),failures=[],steps=[["auth",migrateAuthTables],["notification",migrateNotificationTables],["RBAC",migrateRbacTables],["trait",migrateTraitTables],["utc-datetime",ensureUtcDatetimeColumns]];for(const[name,migrateTables]of steps){const result=await migrateTables({verbose:isVerbose});if(!result.success)failures.push(`${name}: ${result.error}`)}const{migrateEnabledImpersonationTables}=await import("@stacksjs/auth/impersonation-store");await migrateEnabledImpersonationTables();if(failures.length>0){frameworkTablesSpinner.stop();console.log(`\u26A0 Some framework tables could not be migrated: ${failures.join("; ")}`)}else frameworkTablesSpinner.succeed("Framework tables ensured (auth, notifications, RBAC, traits)")}catch(frameworkTablesError){frameworkTablesSpinner.stop();console.log(`\u26A0 Framework table migrations skipped: ${frameworkTablesError.message}`);if(isVerbose)log.debug(`Framework table migration error: ${frameworkTablesError.stack}`)}if(deploymentMode==="server"){const serverOutputSpinner=spinner("Retrieving server instance details...");serverOutputSpinner.start();try{const{CloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new CloudFormationClient(region),stackName=cloudStackName,outputs=await cf.getStackOutputs(stackName);serverOutputSpinner.succeed("Server instances deployed");console.log("");console.log("Server instances:");for(const[key,value]of Object.entries(outputs)){if(key.endsWith("PublicIp"))console.log(` ${key}: ${value}`);if(key.endsWith("InstanceId"))console.log(` ${key}: ${value}`)}console.log("")}catch(outputError){serverOutputSpinner.stop();console.log(`\u26A0 Could not retrieve server details: ${outputError.message}`);if(isVerbose)log.debug(`Output retrieval error: ${outputError.stack}`)}const serverDeploySpinner=spinner("Deploying API server to EC2...");serverDeploySpinner.start();try{const{S3Client,CloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud"),{readFileSync:readServerFile,existsSync:serverFileExists}=await import("node:fs"),{resolve}=await import("node:path"),s3=new S3Client(region),cf=new CloudFormationClient(region),awsClient=new AWSClient,stackName=cloudStackName,outputs=await cf.getStackOutputs(stackName),bucketName=outputs.FrontendBucketName,apiServerPort=Number(config.ports?.api||3008);let instanceId;for(const[key,value]of Object.entries(outputs))if(key.endsWith("InstanceId")&&typeof value==="string"){instanceId=value;break}let securityGroupId;if(instanceId){const{EC2Client}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region);securityGroupId=(await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[instanceId]}]}))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups?.[0]?.GroupId;await ensureSecurityGroupPort(ec2,securityGroupId,apiServerPort)}if(!instanceId||!bucketName){serverDeploySpinner.stop();if(!instanceId)console.log("\u26A0 No EC2 instance found in stack outputs, skipping server deploy");if(!bucketName)console.log("\u26A0 No S3 bucket found for staging server artifacts")}else{const publicDistributionId=outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId;await ensureCloudFrontApiOriginPort(awsClient,publicDistributionId,apiServerPort);const tsCloudDistPath=resolve(p.projectPath("node_modules/@stacksjs/ts-cloud/dist/index.js"));if(serverFileExists(tsCloudDistPath)){const tsCloudDist=readServerFile(tsCloudDistPath);await withS3Retry(()=>s3.putObject({bucket:bucketName,key:"_deploy/ts-cloud-dist.js",body:tsCloudDist,contentType:"application/javascript"}),"upload ts-cloud dist");if(isVerbose)log.debug(" Uploaded ts-cloud dist to S3")}const serverCode=`import { Database } from "bun:sqlite";
|
|
12
12
|
import { SESClient } from "./ts-cloud-dist.js";
|
|
13
13
|
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deploy the infrastructure stack using ts-cloud
|
|
3
|
+
*/
|
|
4
|
+
export declare function deployStack(options: DeployStackOptions): Promise<void>;
|
|
5
|
+
/**
|
|
6
|
+
* Deploy frontend assets to S3
|
|
7
|
+
*/
|
|
8
|
+
export declare function deployFrontend(options: DeployFrontendOptions): Promise<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Get deployment status and outputs
|
|
11
|
+
*/
|
|
12
|
+
export declare function getDeploymentStatus(_options: { environment: string, region: string }): Promise<{
|
|
13
|
+
status: string
|
|
14
|
+
outputs: Record<string, string>
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* Undeploy the infrastructure stack using ts-cloud with CDK-style status updates
|
|
18
|
+
*/
|
|
19
|
+
export declare function undeployStack(options: UndeployStackOptions): Promise<void>;
|
|
20
|
+
declare interface DeployStackOptions {
|
|
21
|
+
environment: string
|
|
22
|
+
region: string
|
|
23
|
+
waitForCompletion?: boolean
|
|
24
|
+
verbose?: boolean
|
|
25
|
+
}
|
|
26
|
+
declare interface DeployFrontendOptions {
|
|
27
|
+
environment: string
|
|
28
|
+
region: string
|
|
29
|
+
buildDir: string
|
|
30
|
+
}
|
|
31
|
+
declare interface UndeployStackOptions {
|
|
32
|
+
environment: string
|
|
33
|
+
region: string
|
|
34
|
+
verbose?: boolean
|
|
35
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";import{path}from"@stacksjs/path";import{getErrorMessage}from"@stacksjs/utils";async function getCloudConfig(){try{return(await import(path.projectPath("config/cloud"))).tsCloud||null}catch{return null}}async function getProjectConfig(){const config=await getCloudConfig();return{name:config?.project?.name||"stacks",region:config?.project?.region||"us-east-1"}}function mapSizeToAwsInstanceType(size){return{nano:"t3.nano",micro:"t3.micro",small:"t3.small",medium:"t3.medium",large:"t3.large",xlarge:"t3.xlarge","2xlarge":"t3.2xlarge"}[size]||size}function mapDiskTypeToAwsVolumeType(diskType){return{standard:"gp2",ssd:"gp3",premium:"io2"}[diskType]||diskType}async function getAwsAccountId(region){try{const{AWSClient}=await import("@stacksjs/ts-cloud"),client=new AWSClient,params=new URLSearchParams({Action:"GetCallerIdentity",Version:"2011-06-15"}),result=await client.request({service:"sts",region,method:"POST",path:"/",body:params.toString()}),accountMatch=String(result).match(/<Account>(\d+)<\/Account>/);if(accountMatch&&accountMatch[1])return accountMatch[1];return process.env.AWS_ACCOUNT_ID||""}catch(error){return process.env.AWS_ACCOUNT_ID||""}}async function generateTemplate(options){const{environment}=options,cloudConfig=await getCloudConfig();if(!cloudConfig)throw Error("Cloud configuration not found. Ensure config/cloud.ts exports tsCloud.");const{InfrastructureGenerator}=await import("@stacksjs/ts-cloud"),template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().getBuilder().build();return JSON.stringify(template)}async function generateServerlessTemplate(options){const{environment,projectName,domain,imageUri}=options,stackSlug=`${projectName}-${environment}`,cloudConfig=await getCloudConfig(),siteDomain=domain||cloudConfig?.infrastructure?.dns?.domain||"stacksjs.com",sslConfig=cloudConfig?.infrastructure?.ssl||{enabled:!0,provider:"acm"},computeConfig=cloudConfig?.infrastructure?.compute,serverlessConfig=computeConfig?.serverless||{cpu:512,memory:1024,desiredCount:2},cpu=serverlessConfig.cpu||512,memory=serverlessConfig.memory||1024,port=3000,desiredCount=serverlessConfig.desiredCount||2,healthCheckPath="/health",rawAutoScaling=computeConfig?.autoScaling,autoScalingConfig={min:rawAutoScaling?.min??1,max:rawAutoScaling?.max??10,targetCpuUtilization:rawAutoScaling?.scaleUpThreshold??70,targetMemoryUtilization:80},hostedZoneId=(cloudConfig?.infrastructure?.dns||{}).hostedZoneId||"",sslDomains=sslConfig.domains||[siteDomain,`www.${siteDomain}`];log.debug(" Mode: Serverless (ECS Fargate + S3 + CloudFront)");log.debug(` Container: ${cpu} CPU, ${memory}MB memory`);log.debug(` Desired count: ${desiredCount}`);log.debug(` Auto Scaling: ${autoScalingConfig.min}-${autoScalingConfig.max} tasks`);const resources={VPC:{Type:"AWS::EC2::VPC",Properties:{CidrBlock:"10.0.0.0/16",EnableDnsHostnames:!0,EnableDnsSupport:!0,Tags:[{Key:"Name",Value:`${stackSlug}-vpc`},{Key:"Environment",Value:environment}]}},InternetGateway:{Type:"AWS::EC2::InternetGateway",Properties:{Tags:[{Key:"Name",Value:`${stackSlug}-igw`},{Key:"Environment",Value:environment}]}},AttachGateway:{Type:"AWS::EC2::VPCGatewayAttachment",Properties:{VpcId:{Ref:"VPC"},InternetGatewayId:{Ref:"InternetGateway"}}},PublicSubnet1:{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:"10.0.1.0/24",AvailabilityZone:{"Fn::Select":[0,{"Fn::GetAZs":""}]},MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${stackSlug}-public-1`},{Key:"Environment",Value:environment}]}},PublicSubnet2:{Type:"AWS::EC2::Subnet",Properties:{VpcId:{Ref:"VPC"},CidrBlock:"10.0.2.0/24",AvailabilityZone:{"Fn::Select":[1,{"Fn::GetAZs":""}]},MapPublicIpOnLaunch:!0,Tags:[{Key:"Name",Value:`${stackSlug}-public-2`},{Key:"Environment",Value:environment}]}},PublicRouteTable:{Type:"AWS::EC2::RouteTable",Properties:{VpcId:{Ref:"VPC"},Tags:[{Key:"Name",Value:`${stackSlug}-public-rt`}]}},PublicRoute:{Type:"AWS::EC2::Route",DependsOn:"AttachGateway",Properties:{RouteTableId:{Ref:"PublicRouteTable"},DestinationCidrBlock:"0.0.0.0/0",GatewayId:{Ref:"InternetGateway"}}},SubnetRouteTableAssociation1:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:"PublicSubnet1"},RouteTableId:{Ref:"PublicRouteTable"}}},SubnetRouteTableAssociation2:{Type:"AWS::EC2::SubnetRouteTableAssociation",Properties:{SubnetId:{Ref:"PublicSubnet2"},RouteTableId:{Ref:"PublicRouteTable"}}},ECSCluster:{Type:"AWS::ECS::Cluster",Properties:{ClusterName:`${stackSlug}-cluster`,Tags:[{Key:"Environment",Value:environment}]}},ECSTaskExecutionRole:{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"]}},ECSTaskRole:{Type:"AWS::IAM::Role",Properties:{AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"ecs-tasks.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess","arn:aws:iam::aws:policy/CloudWatchLogsFullAccess"]}},ECSLogGroup:{Type:"AWS::Logs::LogGroup",Properties:{LogGroupName:`/ecs/${stackSlug}-api`,RetentionInDays:7}},ECSTaskDefinition:{Type:"AWS::ECS::TaskDefinition",Properties:{Family:`${stackSlug}-api`,NetworkMode:"awsvpc",RequiresCompatibilities:["FARGATE"],Cpu:String(cpu),Memory:String(memory),ExecutionRoleArn:{"Fn::GetAtt":["ECSTaskExecutionRole","Arn"]},TaskRoleArn:{"Fn::GetAtt":["ECSTaskRole","Arn"]},ContainerDefinitions:[{Name:"api",Image:imageUri||{"Fn::Sub":`\${AWS::AccountId}.dkr.ecr.\${AWS::Region}.amazonaws.com/${stackSlug}-api:latest`},PortMappings:[{ContainerPort:port,Protocol:"tcp"}],Environment:[{Name:"APP_ENV",Value:environment},{Name:"NODE_ENV",Value:environment},{Name:"PORT",Value:String(port)}],LogConfiguration:{LogDriver:"awslogs",Options:{"awslogs-group":{Ref:"ECSLogGroup"},"awslogs-region":{Ref:"AWS::Region"},"awslogs-stream-prefix":"api"}},HealthCheck:{Command:["CMD-SHELL",`wget --quiet --tries=1 --spider http://localhost:${port}${healthCheckPath} || exit 1`],Interval:30,Timeout:5,Retries:3,StartPeriod:120}}],Tags:[{Key:"Environment",Value:environment}]}},ALBSecurityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:"Security group for Application Load Balancer",VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:80,ToPort:80,CidrIp:"0.0.0.0/0"},{IpProtocol:"tcp",FromPort:443,ToPort:443,CidrIp:"0.0.0.0/0"}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:`${stackSlug}-alb-sg`},{Key:"Environment",Value:environment}]}},ECSSecurityGroup:{Type:"AWS::EC2::SecurityGroup",Properties:{GroupDescription:"Security group for ECS tasks",VpcId:{Ref:"VPC"},SecurityGroupIngress:[{IpProtocol:"tcp",FromPort:port,ToPort:port,SourceSecurityGroupId:{Ref:"ALBSecurityGroup"}}],SecurityGroupEgress:[{IpProtocol:"-1",CidrIp:"0.0.0.0/0"}],Tags:[{Key:"Name",Value:`${stackSlug}-ecs-sg`},{Key:"Environment",Value:environment}]}},ApplicationLoadBalancer:{Type:"AWS::ElasticLoadBalancingV2::LoadBalancer",Properties:{Name:`${stackSlug}-alb`,Type:"application",Scheme:"internet-facing",IpAddressType:"ipv4",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:"ALBSecurityGroup"}],Tags:[{Key:"Environment",Value:environment}]}},ECSTargetGroup:{Type:"AWS::ElasticLoadBalancingV2::TargetGroup",Properties:{Name:`${stackSlug}-tg`,Port:port,Protocol:"HTTP",VpcId:{Ref:"VPC"},TargetType:"ip",HealthCheckEnabled:!0,HealthCheckPath:healthCheckPath,HealthCheckProtocol:"HTTP",HealthCheckIntervalSeconds:30,HealthCheckTimeoutSeconds:5,HealthyThresholdCount:2,UnhealthyThresholdCount:5,Matcher:{HttpCode:"200"},TargetGroupAttributes:[{Key:"deregistration_delay.timeout_seconds",Value:"30"}],Tags:[{Key:"Environment",Value:environment}]}},ALBListener:{Type:"AWS::ElasticLoadBalancingV2::Listener",Properties:{LoadBalancerArn:{Ref:"ApplicationLoadBalancer"},Port:80,Protocol:"HTTP",DefaultActions:[{Type:"forward",TargetGroupArn:{Ref:"ECSTargetGroup"}}]}},ECSService:{Type:"AWS::ECS::Service",DependsOn:"ALBListener",Properties:{ServiceName:`${stackSlug}-api-service`,Cluster:{Ref:"ECSCluster"},TaskDefinition:{Ref:"ECSTaskDefinition"},DesiredCount:desiredCount,LaunchType:"FARGATE",NetworkConfiguration:{AwsvpcConfiguration:{AssignPublicIp:"ENABLED",Subnets:[{Ref:"PublicSubnet1"},{Ref:"PublicSubnet2"}],SecurityGroups:[{Ref:"ECSSecurityGroup"}]}},LoadBalancers:[{ContainerName:"api",ContainerPort:port,TargetGroupArn:{Ref:"ECSTargetGroup"}}],HealthCheckGracePeriodSeconds:300,Tags:[{Key:"Environment",Value:environment}]}},ECSAutoScalingTarget:{Type:"AWS::ApplicationAutoScaling::ScalableTarget",Properties:{MaxCapacity:autoScalingConfig.max,MinCapacity:autoScalingConfig.min,ResourceId:{"Fn::Sub":"service/${ECSCluster}/${ECSService.Name}"},RoleARN:{"Fn::Sub":"arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService"},ScalableDimension:"ecs:service:DesiredCount",ServiceNamespace:"ecs"}},ECSAutoScalingPolicyCPU:{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${stackSlug}-cpu-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:"ECSAutoScalingTarget"},TargetTrackingScalingPolicyConfiguration:{TargetValue:autoScalingConfig.targetCpuUtilization,PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageCPUUtilization"},ScaleInCooldown:300,ScaleOutCooldown:60}}},ECSAutoScalingPolicyMemory:{Type:"AWS::ApplicationAutoScaling::ScalingPolicy",Properties:{PolicyName:`${stackSlug}-memory-scaling`,PolicyType:"TargetTrackingScaling",ScalingTargetId:{Ref:"ECSAutoScalingTarget"},TargetTrackingScalingPolicyConfiguration:{TargetValue:autoScalingConfig.targetMemoryUtilization,PredefinedMetricSpecification:{PredefinedMetricType:"ECSServiceAverageMemoryUtilization"},ScaleInCooldown:300,ScaleOutCooldown:60}}},FrontendBucket:{Type:"AWS::S3::Bucket",DeletionPolicy:"Retain",Properties:{BucketName:{"Fn::Sub":`${stackSlug}-frontend-\${AWS::AccountId}`},WebsiteConfiguration:{IndexDocument:"index.html",ErrorDocument:"index.html"},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},CorsConfiguration:{CorsRules:[{AllowedHeaders:["*"],AllowedMethods:["GET","HEAD"],AllowedOrigins:["*"],MaxAge:3600}]},Tags:[{Key:"Environment",Value:environment}]}},FrontendBucketPolicy:{Type:"AWS::S3::BucketPolicy",Properties:{Bucket:{Ref:"FrontendBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${FrontendBucket}/*"}}]}}},AssetsBucket:{Type:"AWS::S3::Bucket",DeletionPolicy:"Retain",Properties:{BucketName:{"Fn::Sub":`${stackSlug}-assets-\${AWS::AccountId}`},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},CorsConfiguration:{CorsRules:[{AllowedHeaders:["*"],AllowedMethods:["GET","HEAD"],AllowedOrigins:["*"],MaxAge:3600}]},Tags:[{Key:"Environment",Value:environment}]}},AssetsBucketPolicy:{Type:"AWS::S3::BucketPolicy",Properties:{Bucket:{Ref:"AssetsBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:"*",Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${AssetsBucket}/*"}}]}}},DocsBucket:{Type:"AWS::S3::Bucket",DeletionPolicy:"Retain",Properties:{BucketName:{"Fn::Sub":`${stackSlug}-docs-\${AWS::AccountId}`},WebsiteConfiguration:{IndexDocument:"index.html",ErrorDocument:"404.html"},PublicAccessBlockConfiguration:{BlockPublicAcls:!1,BlockPublicPolicy:!1,IgnorePublicAcls:!1,RestrictPublicBuckets:!1},CorsConfiguration:{CorsRules:[{AllowedHeaders:["*"],AllowedMethods:["GET","HEAD"],AllowedOrigins:["*"],MaxAge:3600}]},Tags:[{Key:"Environment",Value:environment},{Key:"Purpose",Value:"documentation"}]}},CloudFrontOAC:{Type:"AWS::CloudFront::OriginAccessControl",Properties:{OriginAccessControlConfig:{Name:{"Fn::Sub":`${stackSlug}-oac`},OriginAccessControlOriginType:"s3",SigningBehavior:"always",SigningProtocol:"sigv4"}}},CloudFrontDistribution:{Type:"AWS::CloudFront::Distribution",DependsOn:["FrontendBucket","ApplicationLoadBalancer"],Properties:{DistributionConfig:{Enabled:!0,Comment:{"Fn::Sub":`${stackSlug} CloudFront Distribution`},DefaultRootObject:"index.html",PriceClass:"PriceClass_100",HttpVersion:"http2and3",IPV6Enabled:!0,Origins:[{Id:"S3Origin",DomainName:{"Fn::GetAtt":["FrontendBucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},{Id:"DocsS3Origin",DomainName:{"Fn::GetAtt":["DocsBucket","RegionalDomainName"]},S3OriginConfig:{OriginAccessIdentity:""},OriginAccessControlId:{"Fn::GetAtt":["CloudFrontOAC","Id"]}},{Id:"ALBOrigin",DomainName:{"Fn::GetAtt":["ApplicationLoadBalancer","DNSName"]},CustomOriginConfig:{HTTPPort:80,HTTPSPort:443,OriginProtocolPolicy:"https-only",OriginSSLProtocols:["TLSv1.2"]}}],DefaultCacheBehavior:{TargetOriginId:"S3Origin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",OriginRequestPolicyId:"88a5eaf4-2fd4-4709-b370-b4c650ea3fcf"},CacheBehaviors:[{PathPattern:"/docs/*",TargetOriginId:"DocsS3Origin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",OriginRequestPolicyId:"88a5eaf4-2fd4-4709-b370-b4c650ea3fcf"},{PathPattern:"/docs",TargetOriginId:"DocsS3Origin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],Compress:!0,CachePolicyId:"658327ea-f89d-4fab-a63d-7e88639e58f6",OriginRequestPolicyId:"88a5eaf4-2fd4-4709-b370-b4c650ea3fcf"},{PathPattern:"/api/*",TargetOriginId:"ALBOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT"],CachedMethods:["GET","HEAD"],CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"216adef6-5c7f-47e4-b989-5492eafa07d3"},{PathPattern:"/health",TargetOriginId:"ALBOrigin",ViewerProtocolPolicy:"redirect-to-https",AllowedMethods:["GET","HEAD","OPTIONS"],CachedMethods:["GET","HEAD"],CachePolicyId:"4135ea2d-6df8-44a3-9df3-4b5a84be39ad",OriginRequestPolicyId:"216adef6-5c7f-47e4-b989-5492eafa07d3"}],CustomErrorResponses:[{ErrorCode:403,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:10},{ErrorCode:404,ResponseCode:200,ResponsePagePath:"/index.html",ErrorCachingMinTTL:10}],ViewerCertificate:{CloudFrontDefaultCertificate:!0}},Tags:[{Key:"Environment",Value:environment}]}}};resources.FrontendBucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:"CloudFrontOAC",Properties:{Bucket:{Ref:"FrontendBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${FrontendBucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}};resources.DocsBucketPolicy={Type:"AWS::S3::BucketPolicy",DependsOn:"CloudFrontOAC",Properties:{Bucket:{Ref:"DocsBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudfront.amazonaws.com"},Action:"s3:GetObject",Resource:{"Fn::Sub":"arn:aws:s3:::${DocsBucket}/*"},Condition:{StringEquals:{"AWS:SourceArn":{"Fn::Sub":"arn:aws:cloudfront::${AWS::AccountId}:distribution/${CloudFrontDistribution}"}}}}]}}};if(hostedZoneId){const cloudFrontHostedZoneId="Z2FDTNDATAQYW2";resources.DNSRecord={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:hostedZoneId,Name:siteDomain,Type:"A",AliasTarget:{HostedZoneId:cloudFrontHostedZoneId,DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},EvaluateTargetHealth:!1}}};if(sslDomains.includes(`www.${siteDomain}`))resources.DNSRecordWww={Type:"AWS::Route53::RecordSet",DependsOn:"CloudFrontDistribution",Properties:{HostedZoneId:hostedZoneId,Name:`www.${siteDomain}`,Type:"A",AliasTarget:{HostedZoneId:cloudFrontHostedZoneId,DNSName:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]},EvaluateTargetHealth:!1}}}}const outputs={VpcId:{Description:"VPC ID",Value:{Ref:"VPC"},Export:{Name:{"Fn::Sub":"${AWS::StackName}-VpcId"}}},ECSClusterName:{Description:"ECS Cluster Name",Value:{Ref:"ECSCluster"},Export:{Name:{"Fn::Sub":"${AWS::StackName}-ECSCluster"}}},LoadBalancerDNS:{Description:"ALB DNS Name",Value:{"Fn::GetAtt":["ApplicationLoadBalancer","DNSName"]}},ApplicationURL:{Description:"URL to access the API",Value:{"Fn::Sub":"http://${ApplicationLoadBalancer.DNSName}"}},CloudFrontDomainName:{Description:"CloudFront Distribution Domain Name",Value:{"Fn::GetAtt":["CloudFrontDistribution","DomainName"]}},CloudFrontDistributionId:{Description:"CloudFront Distribution ID",Value:{Ref:"CloudFrontDistribution"}},FrontendBucketName:{Description:"S3 bucket for frontend",Value:{Ref:"FrontendBucket"},Export:{Name:{"Fn::Sub":"${AWS::StackName}-FrontendBucket"}}},FrontendURL:{Description:"Frontend website URL",Value:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}"}},AssetsBucketName:{Description:"S3 bucket for static assets",Value:{Ref:"AssetsBucket"},Export:{Name:{"Fn::Sub":"${AWS::StackName}-AssetsBucket"}}},DocsBucketName:{Description:"S3 bucket for documentation",Value:{Ref:"DocsBucket"},Export:{Name:{"Fn::Sub":"${AWS::StackName}-DocsBucket"}}},DocsURL:{Description:"Documentation URL",Value:{"Fn::Sub":"https://${CloudFrontDistribution.DomainName}/docs"}}};if(hostedZoneId)outputs.DomainURL={Description:"Domain URL",Value:`https://${siteDomain}`};const template={AWSTemplateFormatVersion:"2010-09-09",Description:`Stacks Serverless Infrastructure (ECS + S3 + CloudFront) for ${projectName} (${environment})`,Parameters:{Environment:{Type:"String",Default:environment,Description:"Deployment environment"},DomainName:{Type:"String",Default:siteDomain,Description:"Domain name for the application"}},Resources:resources,Outputs:outputs};return JSON.stringify(template,null,2)}function formatResourceStatus(status){const colors={green:"\x1B[32m",yellow:"\x1B[33m",red:"\x1B[31m",cyan:"\x1B[36m",gray:"\x1B[90m",reset:"\x1B[0m"};if(status.includes("COMPLETE")&&!status.includes("ROLLBACK"))return`${colors.green}${status}${colors.reset}`;if(status.includes("IN_PROGRESS"))return`${colors.yellow}${status}${colors.reset}`;if(status.includes("FAILED")||status.includes("ROLLBACK"))return`${colors.red}${status}${colors.reset}`;if(status.includes("DELETE"))return`${colors.gray}${status}${colors.reset}`;return status}function getShortResourceType(resourceType){return resourceType.replace("AWS::","").replace("EC2::","").replace("ElasticLoadBalancingV2::","ELB::").replace("AutoScaling::","ASG::").replace("IAM::","").replace("S3::","S3::")}function createProgressCallback(filter){const maxIdLength=35,maxTypeLength=30,seenEvents=new Set;return(event)=>{const{ResourceStatus:eventStatus,LogicalResourceId:eventResourceId,ResourceType:eventResourceType,ResourceStatusReason:eventReason}=event;if(filter==="delete"&&!eventStatus.includes("DELETE"))return;if(filter==="create"&&!eventStatus.includes("CREATE"))return;if(filter==="update"&&!eventStatus.includes("UPDATE")&&!eventStatus.includes("CREATE"))return;const eventKey=`${eventResourceId}:${eventStatus}`;if(seenEvents.has(eventKey))return;seenEvents.add(eventKey);const resourceId=eventResourceId.padEnd(maxIdLength).substring(0,maxIdLength),resourceType=getShortResourceType(eventResourceType).padEnd(maxTypeLength).substring(0,maxTypeLength),status=formatResourceStatus(eventStatus),line=` ${resourceId} ${resourceType} ${status}`;console.log(line);if(eventReason&&(eventStatus.includes("FAILED")||eventStatus.includes("ROLLBACK")))console.log(` \u2514\u2500 ${eventReason}`)}}async function setupDnsAndSsl(options){const{region,domain,sslDomains,hostedZoneId,albDnsName,stackName}=options;console.log("");console.log("Setting up SSL certificate...");try{const{Route53Client,ACMClient,AWSClient}=await import("@stacksjs/ts-cloud"),r53=new Route53Client(region),acm=new ACMClient(region),client=new AWSClient;console.log(` Requesting SSL certificate for ${domain}...`);const certResult=await acm.requestCertificate({DomainName:sslDomains[0]??domain,SubjectAlternativeNames:sslDomains.length>1?sslDomains.slice(1):void 0,ValidationMethod:"DNS"});console.log(` Certificate ARN: ${certResult.CertificateArn}`);await new Promise((r)=>setTimeout(r,5000));const cert=await acm.describeCertificate({CertificateArn:certResult.CertificateArn});console.log(" Adding DNS validation records...");for(const opt of cert.DomainValidationOptions||[])if(opt.ResourceRecord)await r53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:opt.ResourceRecord.Name,Type:"CNAME",TTL:300,ResourceRecords:[{Value:opt.ResourceRecord.Value}]}}]}});console.log("\u2713 Validation records added");console.log(" Waiting for certificate validation (this may take 1-5 minutes)...");for(let i=0;i<30;i++){const c=await acm.describeCertificate({CertificateArn:certResult.CertificateArn});if(c.Status==="ISSUED"){console.log("\u2713 Certificate issued!");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),resources=await new AWSCloudFormationClient(region).listStackResources(stackName),albArn=resources.StackResourceSummaries.find((r)=>r.LogicalResourceId==="ApplicationLoadBalancer")?.PhysicalResourceId,tgArn=resources.StackResourceSummaries.find((r)=>r.LogicalResourceId==="ECSTargetGroup")?.PhysicalResourceId||resources.StackResourceSummaries.find((r)=>r.LogicalResourceId==="WebTargetGroup")?.PhysicalResourceId;if(albArn&&tgArn){console.log(" Creating HTTPS listener...");const createParams=new URLSearchParams({Action:"CreateListener",LoadBalancerArn:albArn,Protocol:"HTTPS",Port:"443","Certificates.member.1.CertificateArn":certResult.CertificateArn,"DefaultActions.member.1.Type":"forward","DefaultActions.member.1.TargetGroupArn":tgArn,Version:"2015-12-01"});await client.request({service:"elasticloadbalancing",region,method:"POST",path:"/",body:createParams.toString()});console.log("\u2713 HTTPS listener created!");console.log(" Configuring HTTP to HTTPS redirect...");const listParams=new URLSearchParams({Action:"DescribeListeners",LoadBalancerArn:albArn,Version:"2015-12-01"}),listResult=await client.request({service:"elasticloadbalancing",region,method:"POST",path:"/",body:listParams.toString()}),listeners=listResult?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member||listResult?.DescribeListenersResult?.Listeners?.member,httpListener=(Array.isArray(listeners)?listeners:listeners?[listeners]:[]).find((l)=>l.Port==="80"||l.Port===80);if(httpListener){const modifyParams=new URLSearchParams({Action:"ModifyListener",ListenerArn:httpListener.ListenerArn,"DefaultActions.member.1.Type":"redirect","DefaultActions.member.1.RedirectConfig.Protocol":"HTTPS","DefaultActions.member.1.RedirectConfig.Port":"443","DefaultActions.member.1.RedirectConfig.StatusCode":"HTTP_301",Version:"2015-12-01"});await client.request({service:"elasticloadbalancing",region,method:"POST",path:"/",body:modifyParams.toString()});console.log("\u2713 HTTP to HTTPS redirect configured!")}}const cfDistId=resources.StackResourceSummaries.find((r)=>r.LogicalResourceId==="CloudFrontDistribution")?.PhysicalResourceId;if(cfDistId){console.log(" Updating CloudFront distribution with SSL certificate...");const getDistResult=await client.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${cfDistId}/config`}),etag=getDistResult._headers?.etag||getDistResult._headers?.ETag,distConfig=getDistResult.DistributionConfig;if(distConfig&&etag){distConfig.Aliases={Quantity:sslDomains.length,Items:sslDomains};distConfig.ViewerCertificate={ACMCertificateArn:certResult.CertificateArn,SSLSupportMethod:"sni-only",MinimumProtocolVersion:"TLSv1.2_2021",CloudFrontDefaultCertificate:!1};const xmlConfig=`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
|
+
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
3
|
+
<CallerReference>${distConfig.CallerReference}</CallerReference>
|
|
4
|
+
<Aliases>
|
|
5
|
+
<Quantity>${sslDomains.length}</Quantity>
|
|
6
|
+
<Items>
|
|
7
|
+
${sslDomains.map((d)=>` <CNAME>${d}</CNAME>`).join(`
|
|
8
|
+
`)}
|
|
9
|
+
</Items>
|
|
10
|
+
</Aliases>
|
|
11
|
+
<DefaultRootObject>${distConfig.DefaultRootObject||"index.html"}</DefaultRootObject>
|
|
12
|
+
<Origins>
|
|
13
|
+
<Quantity>${distConfig.Origins?.Quantity||0}</Quantity>
|
|
14
|
+
<Items>
|
|
15
|
+
${(distConfig.Origins?.Items||[]).map((o)=>` <Origin>
|
|
16
|
+
<Id>${o.Id}</Id>
|
|
17
|
+
<DomainName>${o.DomainName}</DomainName>
|
|
18
|
+
${o.OriginPath?`<OriginPath>${o.OriginPath}</OriginPath>`:"<OriginPath></OriginPath>"}
|
|
19
|
+
${o.S3OriginConfig?`<S3OriginConfig><OriginAccessIdentity>${o.S3OriginConfig.OriginAccessIdentity||""}</OriginAccessIdentity></S3OriginConfig>`:""}
|
|
20
|
+
${o.CustomOriginConfig?`<CustomOriginConfig>
|
|
21
|
+
<HTTPPort>${o.CustomOriginConfig.HTTPPort}</HTTPPort>
|
|
22
|
+
<HTTPSPort>${o.CustomOriginConfig.HTTPSPort}</HTTPSPort>
|
|
23
|
+
<OriginProtocolPolicy>${o.CustomOriginConfig.OriginProtocolPolicy}</OriginProtocolPolicy>
|
|
24
|
+
<OriginSslProtocols><Quantity>${o.CustomOriginConfig.OriginSslProtocols?.Quantity||1}</Quantity><Items>${(o.CustomOriginConfig.OriginSslProtocols?.Items||["TLSv1.2"]).map((p)=>`<SslProtocol>${p}</SslProtocol>`).join("")}</Items></OriginSslProtocols>
|
|
25
|
+
</CustomOriginConfig>`:""}
|
|
26
|
+
${o.OriginAccessControlId?`<OriginAccessControlId>${o.OriginAccessControlId}</OriginAccessControlId>`:""}
|
|
27
|
+
<ConnectionAttempts>${o.ConnectionAttempts||3}</ConnectionAttempts>
|
|
28
|
+
<ConnectionTimeout>${o.ConnectionTimeout||10}</ConnectionTimeout>
|
|
29
|
+
</Origin>`).join(`
|
|
30
|
+
`)}
|
|
31
|
+
</Items>
|
|
32
|
+
</Origins>
|
|
33
|
+
<DefaultCacheBehavior>
|
|
34
|
+
<TargetOriginId>${distConfig.DefaultCacheBehavior?.TargetOriginId}</TargetOriginId>
|
|
35
|
+
<ViewerProtocolPolicy>${distConfig.DefaultCacheBehavior?.ViewerProtocolPolicy||"redirect-to-https"}</ViewerProtocolPolicy>
|
|
36
|
+
<AllowedMethods>
|
|
37
|
+
<Quantity>${distConfig.DefaultCacheBehavior?.AllowedMethods?.Quantity||3}</Quantity>
|
|
38
|
+
<Items>${(distConfig.DefaultCacheBehavior?.AllowedMethods?.Items||["GET","HEAD","OPTIONS"]).map((m)=>`<Method>${m}</Method>`).join("")}</Items>
|
|
39
|
+
<CachedMethods>
|
|
40
|
+
<Quantity>${distConfig.DefaultCacheBehavior?.AllowedMethods?.CachedMethods?.Quantity||2}</Quantity>
|
|
41
|
+
<Items>${(distConfig.DefaultCacheBehavior?.AllowedMethods?.CachedMethods?.Items||["GET","HEAD"]).map((m)=>`<Method>${m}</Method>`).join("")}</Items>
|
|
42
|
+
</CachedMethods>
|
|
43
|
+
</AllowedMethods>
|
|
44
|
+
<Compress>${distConfig.DefaultCacheBehavior?.Compress!==!1}</Compress>
|
|
45
|
+
<CachePolicyId>${distConfig.DefaultCacheBehavior?.CachePolicyId||"658327ea-f89d-4fab-a63d-7e88639e58f6"}</CachePolicyId>
|
|
46
|
+
${distConfig.DefaultCacheBehavior?.OriginRequestPolicyId?`<OriginRequestPolicyId>${distConfig.DefaultCacheBehavior.OriginRequestPolicyId}</OriginRequestPolicyId>`:""}
|
|
47
|
+
</DefaultCacheBehavior>
|
|
48
|
+
<CacheBehaviors>
|
|
49
|
+
<Quantity>${distConfig.CacheBehaviors?.Quantity||0}</Quantity>
|
|
50
|
+
${distConfig.CacheBehaviors?.Quantity>0?`<Items>
|
|
51
|
+
${(distConfig.CacheBehaviors?.Items||[]).map((cb)=>` <CacheBehavior>
|
|
52
|
+
<PathPattern>${cb.PathPattern}</PathPattern>
|
|
53
|
+
<TargetOriginId>${cb.TargetOriginId}</TargetOriginId>
|
|
54
|
+
<ViewerProtocolPolicy>${cb.ViewerProtocolPolicy}</ViewerProtocolPolicy>
|
|
55
|
+
<AllowedMethods>
|
|
56
|
+
<Quantity>${cb.AllowedMethods?.Quantity||3}</Quantity>
|
|
57
|
+
<Items>${(cb.AllowedMethods?.Items||["GET","HEAD","OPTIONS"]).map((m)=>`<Method>${m}</Method>`).join("")}</Items>
|
|
58
|
+
<CachedMethods>
|
|
59
|
+
<Quantity>${cb.AllowedMethods?.CachedMethods?.Quantity||2}</Quantity>
|
|
60
|
+
<Items>${(cb.AllowedMethods?.CachedMethods?.Items||["GET","HEAD"]).map((m)=>`<Method>${m}</Method>`).join("")}</Items>
|
|
61
|
+
</CachedMethods>
|
|
62
|
+
</AllowedMethods>
|
|
63
|
+
<Compress>${cb.Compress!==!1}</Compress>
|
|
64
|
+
<CachePolicyId>${cb.CachePolicyId}</CachePolicyId>
|
|
65
|
+
${cb.OriginRequestPolicyId?`<OriginRequestPolicyId>${cb.OriginRequestPolicyId}</OriginRequestPolicyId>`:""}
|
|
66
|
+
</CacheBehavior>`).join(`
|
|
67
|
+
`)}
|
|
68
|
+
</Items>`:""}
|
|
69
|
+
</CacheBehaviors>
|
|
70
|
+
<CustomErrorResponses>
|
|
71
|
+
<Quantity>${distConfig.CustomErrorResponses?.Quantity||0}</Quantity>
|
|
72
|
+
${distConfig.CustomErrorResponses?.Quantity>0?`<Items>
|
|
73
|
+
${(distConfig.CustomErrorResponses?.Items||[]).map((e)=>` <CustomErrorResponse>
|
|
74
|
+
<ErrorCode>${e.ErrorCode}</ErrorCode>
|
|
75
|
+
<ResponsePagePath>${e.ResponsePagePath}</ResponsePagePath>
|
|
76
|
+
<ResponseCode>${e.ResponseCode}</ResponseCode>
|
|
77
|
+
<ErrorCachingMinTTL>${e.ErrorCachingMinTTL}</ErrorCachingMinTTL>
|
|
78
|
+
</CustomErrorResponse>`).join(`
|
|
79
|
+
`)}
|
|
80
|
+
</Items>`:""}
|
|
81
|
+
</CustomErrorResponses>
|
|
82
|
+
<Comment>${distConfig.Comment||""}</Comment>
|
|
83
|
+
<PriceClass>${distConfig.PriceClass||"PriceClass_100"}</PriceClass>
|
|
84
|
+
<Enabled>${distConfig.Enabled!==!1}</Enabled>
|
|
85
|
+
<ViewerCertificate>
|
|
86
|
+
<ACMCertificateArn>${certResult.CertificateArn}</ACMCertificateArn>
|
|
87
|
+
<SSLSupportMethod>sni-only</SSLSupportMethod>
|
|
88
|
+
<MinimumProtocolVersion>TLSv1.2_2021</MinimumProtocolVersion>
|
|
89
|
+
</ViewerCertificate>
|
|
90
|
+
<HttpVersion>${distConfig.HttpVersion||"http2and3"}</HttpVersion>
|
|
91
|
+
<IsIPV6Enabled>${distConfig.IsIPV6Enabled!==!1}</IsIPV6Enabled>
|
|
92
|
+
</DistributionConfig>`;await client.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${cfDistId}/config`,headers:{"Content-Type":"application/xml","If-Match":etag},body:xmlConfig});console.log("\u2713 CloudFront distribution updated with SSL certificate!")}}console.log("");console.log(`\u2713 SSL setup complete! https://${domain} should be accessible shortly.`);console.log("");return}if(c.Status==="FAILED"){console.log("\u2717 Certificate validation failed!");return}await new Promise((r)=>setTimeout(r,1e4))}console.log("\u26A0 Certificate validation timed out. Please check AWS Console.")}catch(error){console.log(`\u2717 DNS/SSL setup failed: ${getErrorMessage(error)}`);console.log(" You can manually set up DNS and SSL using ./buddy cloud:ssl")}}export async function deployStack(options){const{environment,region,waitForCompletion=!0,verbose=!1}=options,projectName=(await getProjectConfig()).name,{stacksCloudName}=await import("@stacksjs/cloud"),stackName=await stacksCloudName();if(verbose)console.log(`Deploying ${stackName} to ${region}...`);try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new AWSCloudFormationClient(region),cloudConfig=await getCloudConfig(),deploymentMode=cloudConfig?.infrastructure?.compute?.mode||cloudConfig?.mode||"server";if(verbose)console.log(`Generating CloudFormation template (${deploymentMode} mode)...`);const templateBody=await generateTemplate({environment,projectName}),{ensureFailoverReplicaBuckets,grantFailoverReplicaAccess,seedFailoverReplicas,storageFailoverReplicasFromTemplate}=await import("@stacksjs/ts-cloud"),failoverReplicas=storageFailoverReplicasFromTemplate(templateBody);if(failoverReplicas.length>0){console.log(`Ensuring ${failoverReplicas.length} failover replica bucket(s)...`);await ensureFailoverReplicaBuckets(failoverReplicas,(message)=>console.log(` ${message}`))}const CF_INLINE_LIMIT=51200;let templateUrl;if(Buffer.byteLength(templateBody,"utf-8")>CF_INLINE_LIMIT){if(verbose)console.log(`Template exceeds inline limit (${Buffer.byteLength(templateBody,"utf-8")} bytes), uploading to S3...`);const{S3Client:S3,AWSClient}=await import("@stacksjs/ts-cloud"),s3=new S3(region),awsClient=new AWSClient,templateBucket=`${projectName}-cf-templates-${region}`;try{await awsClient.request({service:"s3",region,method:"HEAD",path:`/${templateBucket}`,bucket:templateBucket})}catch{const createBody=region==="us-east-1"?"":`<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>${region}</LocationConstraint></CreateBucketConfiguration>`;await awsClient.request({service:"s3",region,method:"PUT",path:`/${templateBucket}`,bucket:templateBucket,body:createBody||void 0})}const templateKey=`${stackName}/template-${Date.now()}.json`;await s3.putObject({bucket:templateBucket,key:templateKey,body:templateBody,contentType:"application/json"});templateUrl=`https://${templateBucket}.s3.${region}.amazonaws.com/${templateKey}`;if(verbose)console.log(`Template uploaded to: ${templateUrl}`)}const _templateParam=templateUrl?{templateUrl}:{templateBody};let stackExists=!1,_isUpdate=!1;try{const stack=(await cf.describeStacks({stackName})).Stacks?.[0];if(stack&&stack.StackStatus){if(verbose)console.log(`Current status: ${formatResourceStatus(stack.StackStatus)}`);stackExists=!0;_isUpdate=!0;if(stack.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Stack is busy (${stack.StackStatus}). Waiting for current operation to finish...`);const waitType=stack.StackStatus.startsWith("DELETE")?"stack-delete-complete":stack.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await cf.waitForStack(stackName,waitType)}catch{}try{const refreshedStack=(await cf.describeStacks({stackName})).Stacks?.[0];if(!refreshedStack||!refreshedStack.StackStatus){stackExists=!1;_isUpdate=!1}else{if(verbose)console.log(`Stack settled to: ${formatResourceStatus(refreshedStack.StackStatus)}`);stack.StackStatus=refreshedStack.StackStatus}}catch{stackExists=!1;_isUpdate=!1}}if(stack.StackStatus==="UPDATE_ROLLBACK_COMPLETE")console.log("Stack rolled back from a previous update. Re-deploying...");else if(stack.StackStatus==="DELETE_COMPLETE"){stackExists=!1;_isUpdate=!1}else if(stack.StackStatus==="ROLLBACK_COMPLETE"||stack.StackStatus==="ROLLBACK_FAILED"||stack.StackStatus==="CREATE_FAILED"){console.log(`Stack is in ${stack.StackStatus} state. Deleting before recreating...`);await cf.deleteStack(stackName);await cf.waitForStack(stackName,"stack-delete-complete");console.log("Cleaning up retained resources...");try{const{S3Client}=await import("@stacksjs/ts-cloud"),s3=new S3Client(region),accountId=await getAwsAccountId(region),assetsBucketName=`${projectName}-${environment}-assets-${accountId}`,frontendBucketName=`${projectName}-${environment}-frontend-${accountId}`;if(verbose)console.log(` Checking bucket: ${assetsBucketName}`);try{await s3.emptyAndDeleteBucket(assetsBucketName);console.log(`\u2713 Deleted retained bucket: ${assetsBucketName}`)}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${bucketError.message}`);else if(verbose)console.log(" No retained assets bucket to clean up")}if(verbose)console.log(` Checking bucket: ${frontendBucketName}`);try{await s3.emptyAndDeleteBucket(frontendBucketName);console.log(`\u2713 Deleted retained bucket: ${frontendBucketName}`)}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${bucketError.message}`);else if(verbose)console.log(" No retained frontend bucket to clean up")}}catch(cleanupError){console.log(`\u26A0 Cleanup error: ${cleanupError.message}`)}stackExists=!1;_isUpdate=!1}}}catch{stackExists=!1}if(stackExists){console.log("Updating stack...");console.log("");try{const updateParam=templateUrl?{templateURL:templateUrl}:{templateBody};await cf.updateStack({stackName,...updateParam,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:environment},{Key:"Project",Value:projectName},{Key:"ManagedBy",Value:"stacks"}]});if(waitForCompletion){console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`);console.log(" "+"\u2500".repeat(85));await cf.waitForStack(stackName,"stack-update-complete");console.log("")}}catch(error){if(getErrorMessage(error)?.includes("No updates are to be performed"))console.log("\u2713 Stack is up to date (no changes)");else throw error}}else{console.log("Checking for retained resources...");try{const{S3Client}=await import("@stacksjs/ts-cloud"),s3=new S3Client(region),accountId=await getAwsAccountId(region),assetsBucketName=`${projectName}-${environment}-assets-${accountId}`,frontendBucketName=`${projectName}-${environment}-frontend-${accountId}`;if(verbose)console.log(` Checking bucket: ${assetsBucketName}`);try{await s3.emptyAndDeleteBucket(assetsBucketName);console.log(`\u2713 Cleaned up existing bucket: ${assetsBucketName}`)}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${bucketError.message}`);else if(verbose)console.log(" No existing assets bucket to clean up")}if(verbose)console.log(` Checking bucket: ${frontendBucketName}`);try{await s3.emptyAndDeleteBucket(frontendBucketName);console.log(`\u2713 Cleaned up existing bucket: ${frontendBucketName}`)}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${bucketError.message}`);else if(verbose)console.log(" No existing frontend bucket to clean up")}}catch(cleanupError){console.log(`\u26A0 Pre-deployment cleanup error: ${cleanupError.message}`)}console.log("Creating stack...");console.log("");const createParam=templateUrl?{templateURL:templateUrl}:{templateBody},stackId=await cf.createStack({stackName,...createParam,capabilities:["CAPABILITY_IAM","CAPABILITY_NAMED_IAM"],tags:[{Key:"Environment",Value:environment},{Key:"Project",Value:projectName},{Key:"ManagedBy",Value:"stacks"}],onFailure:"ROLLBACK",timeoutInMinutes:30});if(verbose)console.log(`Stack ID: ${stackId}`);if(waitForCompletion){console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`);console.log(" "+"\u2500".repeat(85));await cf.waitForStack(stackName,"stack-create-complete");console.log("")}}if(failoverReplicas.length>0){const failoverOutputs={};for(const output of(await cf.describeStacks({stackName})).Stacks?.[0]?.Outputs||[])if(output.OutputKey&&output.OutputValue)failoverOutputs[output.OutputKey]=output.OutputValue;await grantFailoverReplicaAccess(failoverReplicas,failoverOutputs,(message)=>console.log(` ${message}`));await seedFailoverReplicas(failoverReplicas,(message)=>console.log(` ${message}`))}const siteDomain=cloudConfig?.infrastructure?.dns?.domain||"stacksjs.com",sslConfig=cloudConfig?.infrastructure?.ssl||{enabled:!0,domains:[]},sslDomains=sslConfig.domains||[siteDomain,`www.${siteDomain}`];try{const stack=(await cf.describeStacks({stackName})).Stacks?.[0];if(stack&&stack.StackStatus){const outputs={};for(const output of stack.Outputs||[])if(output.OutputKey&&output.OutputValue)outputs[output.OutputKey]=output.OutputValue;console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");console.log(" \u2713 Infrastructure deployed successfully");console.log("");console.log(` Stack: ${stackName}`);console.log(` Status: ${stack.StackStatus}`);console.log(` Domain: https://${siteDomain}`);if(outputs.LoadBalancerDNS)console.log(` Load Balancer: ${outputs.LoadBalancerDNS}`);if(outputs.WebServerPublicIP)console.log(` Server IP: ${outputs.WebServerPublicIP}`);if(outputs.AssetsBucketName&&verbose)console.log(` Assets: ${outputs.AssetsBucketName}`);console.log("");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");if(sslConfig.enabled&&cloudConfig?.infrastructure?.dns?.hostedZoneId&&outputs.LoadBalancerDNS)await setupDnsAndSsl({region,domain:siteDomain,sslDomains,hostedZoneId:cloudConfig.infrastructure.dns.hostedZoneId,albDnsName:outputs.LoadBalancerDNS,stackName});else if(!sslConfig.certificateArn&&verbose){console.log(" Next steps:");console.log(" 1. DNS records need to be updated to point to the ALB");console.log(" 2. SSL certificate needs to be requested and attached");console.log(` Run: ./buddy cloud:ssl to set up SSL for ${siteDomain}`);console.log("")}}}catch{}}catch(error){console.error(`Stack deployment failed: ${getErrorMessage(error)}`);throw error}}export async function deployFrontend(options){const{environment,region,buildDir}=options;log.info(`Deploying frontend from ${buildDir} to ${environment} in ${region}...`);try{const{S3Client,AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),s3=new S3Client(region),cf=new AWSCloudFormationClient(region),{stacksCloudName}=await import("@stacksjs/cloud"),stackName=await stacksCloudName(),bucketName=(await cf.describeStacks({stackName})).Stacks?.[0]?.Outputs?.find((o)=>o.OutputKey==="AssetsBucketName")?.OutputValue;if(!bucketName)throw Error("Assets bucket not found in stack outputs");log.info(`Syncing ${buildDir} to s3://${bucketName}/...`);await s3.sync({source:buildDir,bucket:bucketName,delete:!0,cacheControl:"max-age=31536000"});log.success("Frontend deployment completed!")}catch(error){log.error(`Frontend deployment failed: ${getErrorMessage(error)}`);throw error}}export async function getDeploymentStatus(_options){const{environment,region}=_options,{stacksCloudName}=await import("@stacksjs/cloud"),stackName=await stacksCloudName(),{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),cf=new AWSCloudFormationClient(region);try{const stack=(await cf.describeStacks({stackName})).Stacks?.[0];if(!stack||!stack.StackStatus)return{status:"NOT_FOUND",outputs:{}};const outputs={};for(const output of stack.Outputs||[])if(output.OutputKey&&output.OutputValue)outputs[output.OutputKey]=output.OutputValue;return{status:stack.StackStatus,outputs}}catch{return{status:"NOT_FOUND",outputs:{}}}}export async function undeployStack(options){const{environment,region,verbose}=options,projectConfig=await getProjectConfig(),{stacksCloudName}=await import("@stacksjs/cloud"),stackName=await stacksCloudName();console.log(`Undeploying ${stackName} from ${region}...`);console.log("");try{const{AWSCloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud"),cf=new AWSCloudFormationClient(region);let stackExists=!1;try{const stack=(await cf.describeStacks({stackName})).Stacks?.[0];if(stack&&stack.StackStatus){console.log(`Current status: ${formatResourceStatus(stack.StackStatus)}`);stackExists=!0;if(stack.StackStatus.endsWith("_IN_PROGRESS")){console.log(`Waiting for current operation (${stack.StackStatus}) to finish...`);const waitType=stack.StackStatus.startsWith("DELETE")?"stack-delete-complete":stack.StackStatus.startsWith("CREATE")?"stack-create-complete":"stack-update-complete";try{await cf.waitForStack(stackName,waitType)}catch{}try{const refreshedStack=(await cf.describeStacks({stackName})).Stacks?.[0];if(!refreshedStack||!refreshedStack.StackStatus||refreshedStack.StackStatus==="DELETE_COMPLETE"){console.log("Stack was already deleted during the in-progress operation.");return}}catch{console.log("Stack was already deleted during the in-progress operation.");return}}if(stack.StackStatus==="DELETE_COMPLETE")stackExists=!1}}catch{stackExists=!1}if(!stackExists){console.log(`Stack ${stackName} does not exist. Nothing to undeploy.`);return}if(verbose)console.log("Checking for resources to clean up before deletion...");try{const client=new AWSClient,{AWSCloudFormationClient:AwsCfn}=await import("@stacksjs/ts-cloud"),albResource=((await new AwsCfn(region).listStackResources(stackName)).StackResourceSummaries||[]).find((r)=>r.LogicalResourceId==="ApplicationLoadBalancer");if(albResource?.PhysicalResourceId){const listParams={Action:"DescribeListeners",LoadBalancerArn:albResource.PhysicalResourceId,Version:"2015-12-01"},listResult=await client.request({service:"elasticloadbalancing",region,method:"POST",path:"/",body:new URLSearchParams(listParams).toString()}),listeners=listResult?.DescribeListenersResult?.Listeners?.member||listResult?.DescribeListenersResponse?.DescribeListenersResult?.Listeners?.member,listenerList=Array.isArray(listeners)?listeners:listeners?[listeners]:[];let deletedListeners=0;for(const listener of listenerList)if(listener.Protocol==="HTTPS"){if(verbose)console.log(` Removing HTTPS listener on port ${listener.Port}...`);const deleteParams={Action:"DeleteListener",ListenerArn:listener.ListenerArn,Version:"2015-12-01"};await client.request({service:"elasticloadbalancing",region,method:"POST",path:"/",body:new URLSearchParams(deleteParams).toString()});deletedListeners++}if(deletedListeners>0&&verbose){console.log(`\u2713 Cleaned up ${deletedListeners} HTTPS listener(s)`);await new Promise((resolve)=>setTimeout(resolve,2000))}}}catch(cleanupError){if(verbose)console.log(`Warning: ${cleanupError.message}`)}console.log("Deleting stack...");console.log("");await cf.deleteStack(stackName);console.log(` ${"Resource".padEnd(35)} ${"Type".padEnd(30)} Status`);console.log(" "+"\u2500".repeat(85));await cf.waitForStack(stackName,"stack-delete-complete");try{const{S3Client}=await import("@stacksjs/ts-cloud"),s3=new S3Client(region),accountId=await getAwsAccountId(region),assetsBucketName=`${projectConfig.name}-${environment}-assets-${accountId}`,frontendBucketName=`${projectConfig.name}-${environment}-frontend-${accountId}`;console.log("Cleaning up retained buckets...");try{await s3.emptyAndDeleteBucket(assetsBucketName);console.log("\u2713 Assets bucket deleted successfully")}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete assets bucket: ${bucketError.message}`);else console.log("\u2713 No retained assets bucket to clean up")}try{await s3.emptyAndDeleteBucket(frontendBucketName);console.log("\u2713 Frontend bucket deleted successfully")}catch(bucketError){if(!bucketError.message?.includes("NoSuchBucket")&&!bucketError.message?.includes("does not exist"))console.log(`\u26A0 Could not delete frontend bucket: ${bucketError.message}`);else console.log("\u2713 No retained frontend bucket to clean up")}}catch(cleanupError){console.log(`\u26A0 Cleanup error: ${cleanupError.message}`)}console.log("");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");console.log(" \u2713 Infrastructure removed successfully");console.log("");console.log(` Stack: ${stackName}`);console.log(` Environment: ${environment}`);console.log(` Region: ${region}`);console.log("");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("")}catch(error){const errorStr=String(getErrorMessage(error)||error);if(errorStr.includes("does not exist")){console.log("");console.log("\u2713 Stack already deleted or does not exist.");return}if(error.code==="DELETE_FAILED"||errorStr.includes("DELETE_FAILED")){console.log("");console.log("Some resources could not be deleted automatically");console.log("Identifying resources to retain...");const{AWSCloudFormationClient:AwsCfnRetry}=await import("@stacksjs/ts-cloud"),awsCfnRetry=new AwsCfnRetry(region);try{const failedResources=((await awsCfnRetry.listStackResources(stackName)).StackResourceSummaries||[]).filter((r)=>r.ResourceStatus==="DELETE_FAILED").map((r)=>r.LogicalResourceId);if(failedResources.length>0){console.log(`Retaining ${failedResources.length} resource(s):`);failedResources.forEach((r)=>console.log(` - ${r}`));console.log("");console.log("Retrying deletion with retained resources...");await awsCfnRetry.deleteStack(stackName,void 0,failedResources);const{AWSCloudFormationClient:CfRetry}=await import("@stacksjs/ts-cloud");await new CfRetry(region).waitForStack(stackName,"stack-delete-complete");console.log("");console.log("\u2713 Stack removed (with retained resources)");console.log("");console.log("Note: Some resources were retained and may need manual cleanup.");console.log("Run `./buddy cloud:cleanup` to clean up remaining resources.");return}}catch(retryError){if(String(retryError.message||retryError).includes("does not exist")){console.log("");console.log("\u2713 Stack deleted successfully!");return}throw retryError}}console.error(`Stack deletion failed: ${getErrorMessage(error)}`);throw error}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/** Resolve the configured upstream
|
|
2
|
-
export declare function releasePushTarget(cwd?: unknown): { remote: string, ref: string };
|
|
1
|
+
/** Resolve the configured upstream and required source-CI branch before release writes. */
|
|
2
|
+
export declare function releasePushTarget(cwd?: unknown, requiredBranch?: string): { remote: string, ref: string };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFileSync}from"node:child_process";import process from"node:process";export function releasePushTarget(cwd=process.cwd()){const git=(args,optional=!1)=>{try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch(error){if(optional&&error instanceof Error&&"status"in error&&error.status===1)return"";throw Error("Cannot resolve the release branch and remote. Release requires a valid Git checkout on a branch.")}},branch=git(["symbolic-ref","--short","HEAD"]),remote=git(["config","--get-all",`branch.${branch}.remote`],!0),ref=git(["config","--get-all",`branch.${branch}.merge`],!0);if(Boolean(remote)!==Boolean(ref))throw Error("The release branch has an incomplete upstream configuration.");const target={remote:remote||"origin",ref:ref||`refs/heads/${branch}`};if(target.remote==="."||!git(["remote"]).split(`
|
|
1
|
+
import{execFileSync}from"node:child_process";import process from"node:process";export function releasePushTarget(cwd=process.cwd(),requiredBranch){const git=(args,optional=!1)=>{try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch(error){if(optional&&error instanceof Error&&"status"in error&&error.status===1)return"";throw Error("Cannot resolve the release branch and remote. Release requires a valid Git checkout on a branch.")}},branch=git(["symbolic-ref","--short","HEAD"]),remote=git(["config","--get-all",`branch.${branch}.remote`],!0),ref=git(["config","--get-all",`branch.${branch}.merge`],!0);if(Boolean(remote)!==Boolean(ref))throw Error("The release branch has an incomplete upstream configuration.");const target={remote:remote||"origin",ref:ref||`refs/heads/${branch}`};if(target.remote==="."||!git(["remote"]).split(`
|
|
2
2
|
`).includes(target.remote))throw Error("The release destination must name a configured remote.");if(!target.ref.startsWith("refs/heads/")||target.ref.includes(`
|
|
3
|
-
`))throw Error("The release upstream must be a single branch.");git(["check-ref-format",target.ref]);return target}
|
|
3
|
+
`))throw Error("The release upstream must be a single branch.");git(["check-ref-format",target.ref]);if(requiredBranch&&target.ref!==`refs/heads/${requiredBranch}`)throw Error(`Release requires upstream branch refs/heads/${requiredBranch}; configure this branch to track ${target.remote}/${requiredBranch} before releasing.`);return target}
|
package/dist/release.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{assertPublicationAllowed}from"./publication-preflight";import{runActions}from"./helpers/utils";import{resolvePantryToolchain}from"./pantry-toolchain";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=isDryRun?[Action.Bump]:[Action.GenerateLibraryEntries,Action.Bump];if(!isDryRun)await assertPublicationAllowed({cwd:projectPath(),channel:"github-release"});const preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const pantryToolchain=resolvePantryToolchain({cwd:projectPath()});if(!pantryToolchain.ok){await log.flush();await log.exit(pantryToolchain.message,1)}else log.info(`Pantry ${pantryToolchain.version} (${pantryToolchain.bin})${pantryToolchain.declared?` satisfies ts-pantry ${pantryToolchain.declared}`:""}`);const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
|
|
1
|
+
import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{assertPublicationAllowed}from"./publication-preflight";import{runActions}from"./helpers/utils";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=isDryRun?[Action.Bump]:[Action.GenerateLibraryEntries,Action.Bump];if(!isDryRun){await assertPublicationAllowed({cwd:projectPath(),channel:"github-release"});if((await Bun.file(projectPath("package.json")).json()).name==="stacks"&&await Bun.file(projectPath("storage/framework/core/package.json")).exists())releasePushTarget(projectPath(),"main")}const preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const pantryToolchain=resolvePantryToolchain({cwd:projectPath()});if(!pantryToolchain.ok){await log.flush();await log.exit(pantryToolchain.message,1)}else log.info(`Pantry ${pantryToolchain.version} (${pantryToolchain.bin})${pantryToolchain.declared?` satisfies ts-pantry ${pantryToolchain.declared}`:""}`);const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.445",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,55 +66,55 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/action-runner": "0.75.
|
|
70
|
-
"@stacksjs/ai": "0.75.
|
|
71
|
-
"@stacksjs/analytics": "0.75.
|
|
72
|
-
"@stacksjs/api": "0.75.
|
|
73
|
-
"@stacksjs/auth": "0.75.
|
|
74
|
-
"@stacksjs/build": "0.75.
|
|
69
|
+
"@stacksjs/action-runner": "0.75.445",
|
|
70
|
+
"@stacksjs/ai": "0.75.445",
|
|
71
|
+
"@stacksjs/analytics": "0.75.445",
|
|
72
|
+
"@stacksjs/api": "0.75.445",
|
|
73
|
+
"@stacksjs/auth": "0.75.445",
|
|
74
|
+
"@stacksjs/build": "0.75.445",
|
|
75
75
|
"@stacksjs/bumpx": "^0.2.26",
|
|
76
76
|
"@stacksjs/bunpress": "^0.2.15",
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/cloud": "0.75.
|
|
79
|
-
"@stacksjs/cms": "0.75.
|
|
80
|
-
"@stacksjs/components": "0.2.
|
|
81
|
-
"@stacksjs/config": "0.75.
|
|
82
|
-
"@stacksjs/database": "0.75.
|
|
83
|
-
"@stacksjs/desktop-build": "0.75.
|
|
84
|
-
"@stacksjs/dns": "0.75.
|
|
85
|
-
"@stacksjs/enums": "0.75.
|
|
86
|
-
"@stacksjs/env": "0.75.
|
|
87
|
-
"@stacksjs/error-handling": "0.75.
|
|
88
|
-
"@stacksjs/github": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.445",
|
|
78
|
+
"@stacksjs/cloud": "0.75.445",
|
|
79
|
+
"@stacksjs/cms": "0.75.445",
|
|
80
|
+
"@stacksjs/components": "0.2.789",
|
|
81
|
+
"@stacksjs/config": "0.75.445",
|
|
82
|
+
"@stacksjs/database": "0.75.445",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.445",
|
|
84
|
+
"@stacksjs/dns": "0.75.445",
|
|
85
|
+
"@stacksjs/enums": "0.75.445",
|
|
86
|
+
"@stacksjs/env": "0.75.445",
|
|
87
|
+
"@stacksjs/error-handling": "0.75.445",
|
|
88
|
+
"@stacksjs/github": "0.75.445",
|
|
89
89
|
"@stacksjs/gitit": "^0.2.5",
|
|
90
|
-
"@stacksjs/i18n": "0.75.
|
|
91
|
-
"@stacksjs/image": "0.75.
|
|
92
|
-
"@stacksjs/logging": "0.75.
|
|
90
|
+
"@stacksjs/i18n": "0.75.445",
|
|
91
|
+
"@stacksjs/image": "0.75.445",
|
|
92
|
+
"@stacksjs/logging": "0.75.445",
|
|
93
93
|
"@stacksjs/logsmith": "^0.2.11",
|
|
94
|
-
"@stacksjs/mobile": "0.75.
|
|
95
|
-
"@stacksjs/orm": "0.75.
|
|
96
|
-
"@stacksjs/path": "0.75.
|
|
97
|
-
"@stacksjs/payments": "0.75.
|
|
98
|
-
"@stacksjs/queue": "0.75.
|
|
99
|
-
"@stacksjs/registry": "0.75.
|
|
100
|
-
"@stacksjs/router": "0.75.
|
|
94
|
+
"@stacksjs/mobile": "0.75.445",
|
|
95
|
+
"@stacksjs/orm": "0.75.445",
|
|
96
|
+
"@stacksjs/path": "0.75.445",
|
|
97
|
+
"@stacksjs/payments": "0.75.445",
|
|
98
|
+
"@stacksjs/queue": "0.75.445",
|
|
99
|
+
"@stacksjs/registry": "0.75.445",
|
|
100
|
+
"@stacksjs/router": "0.75.445",
|
|
101
101
|
"@stacksjs/rpx": "^0.11.54",
|
|
102
|
-
"@stacksjs/scheduler": "0.75.
|
|
103
|
-
"@stacksjs/search-engine": "0.75.
|
|
104
|
-
"@stacksjs/security": "0.75.
|
|
105
|
-
"@stacksjs/server": "0.75.
|
|
106
|
-
"@stacksjs/sites": "0.75.
|
|
107
|
-
"@stacksjs/storage": "0.75.
|
|
108
|
-
"@stacksjs/strings": "0.75.
|
|
109
|
-
"@stacksjs/stx": "0.2.
|
|
102
|
+
"@stacksjs/scheduler": "0.75.445",
|
|
103
|
+
"@stacksjs/search-engine": "0.75.445",
|
|
104
|
+
"@stacksjs/security": "0.75.445",
|
|
105
|
+
"@stacksjs/server": "0.75.445",
|
|
106
|
+
"@stacksjs/sites": "0.75.445",
|
|
107
|
+
"@stacksjs/storage": "0.75.445",
|
|
108
|
+
"@stacksjs/strings": "0.75.445",
|
|
109
|
+
"@stacksjs/stx": "0.2.789",
|
|
110
110
|
"@stacksjs/tlsx": "^0.13.19",
|
|
111
111
|
"@stacksjs/ts-cloud": "^0.16.91",
|
|
112
112
|
"@stacksjs/ts-md": "^0.1.1",
|
|
113
|
-
"@stacksjs/tunnel": "0.75.
|
|
114
|
-
"@stacksjs/types": "0.75.
|
|
115
|
-
"@stacksjs/utils": "0.75.
|
|
116
|
-
"@stacksjs/whois": "0.75.
|
|
117
|
-
"bun-plugin-stx": "0.2.
|
|
113
|
+
"@stacksjs/tunnel": "0.75.445",
|
|
114
|
+
"@stacksjs/types": "0.75.445",
|
|
115
|
+
"@stacksjs/utils": "0.75.445",
|
|
116
|
+
"@stacksjs/whois": "0.75.445",
|
|
117
|
+
"bun-plugin-stx": "0.2.789"
|
|
118
118
|
},
|
|
119
119
|
"peerDependencies": {
|
|
120
120
|
"craft-native": ">=0.0.424",
|
|
@@ -129,7 +129,7 @@
|
|
|
129
129
|
}
|
|
130
130
|
},
|
|
131
131
|
"devDependencies": {
|
|
132
|
-
"@stacksjs/validation": "0.75.
|
|
132
|
+
"@stacksjs/validation": "0.75.445",
|
|
133
133
|
"better-dx": "^0.2.24"
|
|
134
134
|
}
|
|
135
135
|
}
|