@stacksjs/actions 0.75.514 → 0.75.518
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/action.js +1 -1
- package/dist/auth/client-options.js +1 -1
- package/dist/auth/client.js +1 -1
- package/dist/auth/prune.js +1 -1
- package/dist/auth/setup.js +2 -2
- package/dist/blog-admin.js +3 -3
- package/dist/blog.js +23 -23
- package/dist/build/android-config.js +1 -1
- package/dist/build/android-icons.js +1 -1
- package/dist/build/android.js +1 -1
- package/dist/build/component-library.js +1 -1
- package/dist/build/core.js +1 -1
- package/dist/build/craft-entry.js +1 -1
- package/dist/build/craft-provenance.js +1 -1
- package/dist/build/desktop-macos.js +2 -2
- package/dist/build/desktop.js +2 -2
- package/dist/build/dmg-macos.js +1 -1
- package/dist/build/dmg.js +1 -1
- package/dist/build/docs.js +1 -1
- package/dist/build/frontend-static.js +5 -5
- package/dist/build/ios-config.js +3 -3
- package/dist/build/ios-shell.js +3 -3
- package/dist/build/ios-toolchain.js +2 -2
- package/dist/build/ios.js +2 -2
- package/dist/build/macos-native.js +3 -3
- package/dist/build/mobile-splash.js +1 -1
- package/dist/build/mobile-target.js +1 -1
- package/dist/build/native-screens.js +1 -1
- package/dist/build/native-sensors.js +1 -1
- package/dist/build/notarize.js +2 -2
- package/dist/build/run-build-step.js +1 -1
- package/dist/build/stacks.js +1 -1
- package/dist/build/views.js +1 -1
- package/dist/build.js +1 -1
- package/dist/bump.js +7 -7
- package/dist/calendar-version.js +1 -1
- package/dist/changelog.js +1 -1
- package/dist/check/ports.js +1 -1
- package/dist/commit.js +1 -1
- package/dist/database/seed.js +1 -1
- package/dist/deploy/create-receipt-rule.js +1 -1
- package/dist/deploy/hooks.js +1 -1
- package/dist/deploy/index.js +17 -17
- package/dist/deploy/stack.js +6 -6
- package/dist/dev/api.js +1 -1
- package/dist/dev/components.js +1 -1
- package/dist/dev/csrf.js +1 -1
- package/dist/dev/dashboard-native.js +1 -1
- package/dist/dev/dashboard-request-routing.js +1 -1
- package/dist/dev/dashboard-supervisor.js +2 -2
- package/dist/dev/dashboard-utils.js +1 -1
- package/dist/dev/dashboard.js +4 -4
- package/dist/dev/defaults-resources.js +1 -1
- package/dist/dev/docs.js +1 -1
- package/dist/dev/exit-with-parent.js +1 -1
- package/dist/dev/migrate-watcher.js +1 -1
- package/dist/dev/system-tray.js +2 -2
- package/dist/dev/tray-origin.js +1 -1
- package/dist/dev/views.js +1 -1
- package/dist/discover-packages.js +1 -1
- package/dist/domains/add.js +1 -1
- package/dist/domains/purchase.js +1 -1
- package/dist/domains/remove.js +1 -1
- package/dist/examples.js +1 -1
- package/dist/find-projects.js +1 -1
- package/dist/generate/action-types.js +3 -3
- package/dist/generate/erd.js +2 -2
- package/dist/generate/ide-helpers.js +1 -1
- package/dist/generate/images.js +1 -1
- package/dist/generate/index.js +1 -1
- package/dist/generate/lib-entries.js +1 -1
- package/dist/generate/vschema.js +2 -2
- package/dist/github-release.js +5 -5
- package/dist/helpers/api-host.js +3 -3
- package/dist/helpers/api-shutdown.js +1 -1
- package/dist/helpers/component-meta.js +3 -3
- package/dist/helpers/utils.js +1 -1
- package/dist/helpers/vscode-custom-data.js +1 -1
- package/dist/key-generate.js +1 -1
- package/dist/library/build.js +2 -2
- package/dist/library/entries.js +1 -1
- package/dist/library/globals.js +1 -1
- package/dist/library/manifest.js +2 -2
- package/dist/library/packages.js +1 -1
- package/dist/library/publish.js +2 -2
- package/dist/library-publish.js +1 -1
- package/dist/lint/files.js +1 -1
- package/dist/lint/lint.js +1 -1
- package/dist/lint/stx-gate.js +3 -3
- package/dist/make-command.js +2 -2
- package/dist/make-job.js +2 -2
- package/dist/make-policy.js +2 -2
- package/dist/make-resource.js +1 -1
- package/dist/make.js +7 -7
- package/dist/migrate/database.js +1 -1
- package/dist/migrate/fresh.js +1 -1
- package/dist/pantry-lock.js +1 -1
- package/dist/pantry-toolchain.js +1 -1
- package/dist/project-scripts.js +1 -1
- package/dist/publication-preflight.js +1 -1
- package/dist/queue/clear.js +1 -1
- package/dist/queue/dlq-purge.js +1 -1
- package/dist/queue/dlq-retry.js +1 -1
- package/dist/queue/dlq.js +2 -2
- package/dist/queue/failed.js +2 -2
- package/dist/queue/flush.js +1 -1
- package/dist/queue/inspect.js +6 -6
- package/dist/queue/list.js +2 -2
- package/dist/queue/monitor.js +5 -5
- package/dist/queue/options.js +1 -1
- package/dist/queue/pause.js +1 -1
- package/dist/queue/quarantine.js +1 -1
- package/dist/queue/resume.js +1 -1
- package/dist/queue/retry.js +1 -1
- package/dist/queue/schedule-list.js +2 -2
- package/dist/queue/status.js +2 -2
- package/dist/queue/unquarantine.js +1 -1
- package/dist/queue/work.js +1 -1
- package/dist/release-evidence.js +1 -1
- package/dist/release-notes.js +5 -5
- package/dist/release-preflight.js +2 -2
- package/dist/release-push-target.js +3 -3
- package/dist/release.js +1 -1
- package/dist/reviewos-evidence.js +1 -1
- package/dist/route/list.js +1 -1
- package/dist/saas/setup.js +1 -1
- package/dist/scaffold-crud.js +7 -7
- package/dist/search/flush.js +1 -1
- package/dist/search/import.js +1 -1
- package/dist/search/settings-list.js +1 -1
- package/dist/seo.js +4 -4
- package/dist/serve/api.js +1 -1
- package/dist/serve/dashboard-gate.js +1 -1
- package/dist/serve/dashboard.js +1 -1
- package/dist/setup/ssl.js +2 -2
- package/dist/stacks.js +1 -1
- package/dist/stx-source.js +1 -1
- package/dist/test/feature.js +1 -1
- package/dist/test/runner.js +1 -1
- package/dist/test/unit.js +1 -1
- package/dist/upgrade/binary.js +1 -1
- package/dist/upgrade/framework-hooks.d.ts +6 -0
- package/dist/upgrade/framework-hooks.js +1 -1
- package/dist/upgrade/framework-utils.js +2 -2
- package/dist/upgrade/framework.js +10 -10
- package/dist/upgrade/package-project.js +2 -2
- package/dist/upgrade/packages.js +23 -22
- package/dist/upgrade/route-actions.js +3 -3
- package/dist/upgrade/shell.js +4 -4
- package/dist/upgrade.js +1 -1
- package/package.json +40 -40
package/dist/deploy/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{existsSync,readFileSync,statSync}from"node:fs";import process from"node:process";import{runCommand,spinner}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{path as p}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{assertPublicationAllowed}from"../publication-preflight";import{runBeforeDeployHook}from"./hooks";await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const log={debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v"))console.log("\uD83D\uDD0D",...args)},success:(...args)=>console.log("
|
|
1
|
+
import{existsSync,readFileSync,statSync}from"node:fs";import process from"node:process";import{runCommand,spinner}from"@stacksjs/cli";import{config}from"@stacksjs/config";import{path as p}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{assertPublicationAllowed}from"../publication-preflight";import{runBeforeDeployHook}from"./hooks";await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const log={debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v")){console.log("\uD83D\uDD0D",...args)}},success:(...args)=>console.log("✓",...args),error:(...args)=>console.error("✗",...args)};const MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail";const MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`;const MAIL_TARGET_PLATFORM="linux-x86_64";const MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"];const isVerbose=process.argv.includes("--verbose")||process.argv.includes("-v");async function collectMatchingFiles(root,names,maxDepth=8){const{existsSync,readdirSync,statSync}=await import("node:fs");const{join,basename}=await import("node:path");const nameSet=new Set(names);const matches=[];if(!existsSync(root))return matches;function walk(dir,depth){if(depth>maxDepth)return;for(const entry of readdirSync(dir)){if(entry===".git"||entry==="node_modules")continue;const fullPath=join(dir,entry);const stat=statSync(fullPath);if(stat.isDirectory()){walk(fullPath,depth+1)}else if(stat.isFile()&&nameSet.has(basename(fullPath))){matches.push(fullPath)}}}walk(root,0);return matches}async function isElfBinary(filePath){const{readFileSync}=await import("node:fs");const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}async function resolvePantryInstallCommand(){const{existsSync}=await import("node:fs");const localPantryCli=`${process.env.HOME}/Code/Tools/pantry/packages/ts-pantry/bin/cli.ts`;if(existsSync(localPantryCli)){return{command:"bun",args:[localPantryCli]}}const projectPantry=p.projectPath("pantry/.bin/pantry");if(existsSync(projectPantry)){return{command:projectPantry,args:[]}}const globalPantry=`${process.env.HOME}/.local/share/pantry/global/bin/pantry`;if(existsSync(globalPantry)){return{command:globalPantry,args:[]}}return{command:"pantry",args:[]}}async function installMailBinaryWithPantry(){const{execFileSync}=await import("node:child_process");const installDir=p.projectPath("pantry");const pantry=await resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",installDir,"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:isVerbose?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const{existsSync}=await import("node:fs");const{join}=await import("node:path");const pantryRoots=[p.projectPath("pantry"),`${process.env.HOME}/.local/share/pantry`];const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(`${process.env.HOME}/.local/share/pantry/global/bin`,name))];for(const candidate of directCandidates){if(existsSync(candidate)&&await isElfBinary(candidate))return candidate}for(const root of pantryRoots){const candidates=await collectMatchingFiles(root,MAIL_BINARY_NAMES);for(const candidate of candidates){if(await isElfBinary(candidate))return candidate}}return null}const MIME_TYPES={".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".otf":"font/otf",".webp":"image/webp",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".pdf":"application/pdf",".xml":"application/xml",".txt":"text/plain"};function getMimeType(filePath){const dotIndex=filePath.lastIndexOf(".");const ext=dotIndex>=0?filePath.slice(dotIndex).toLowerCase():"";return MIME_TYPES[ext]||"application/octet-stream"}async function traverseDirectory(dir,callback,prefix="",skipPatterns=[".DS_Store"]){const{readdirSync,statSync}=await import("node:fs");const{join}=await import("node:path");const items=readdirSync(dir);for(const item of items){if(skipPatterns.includes(item))continue;const filePath=join(dir,item);const key=prefix?`${prefix}/${item}`:item;if(statSync(filePath).isDirectory()){await traverseDirectory(filePath,callback,key,skipPatterns)}else{await callback(filePath,key)}}}async function withS3Retry(fn,label="s3 operation"){const maxRetries=3;for(let attempt=0;attempt<=maxRetries;attempt++){try{return await fn()}catch(error){if(attempt>=maxRetries)throw error;const delay=Math.min(500*2**attempt+Math.random()*200,5000);if(isVerbose)log.debug(` Retrying ${label} (attempt ${attempt+2}/${maxRetries+1}) in ${Math.round(delay)}ms...`);await new Promise((resolve)=>setTimeout(resolve,delay))}}throw new Error(`${label} failed after ${maxRetries+1} attempts`)}function normalizeArray(value){if(!value)return[];return Array.isArray(value)?value:[value]}function buildCloudFrontXmlElement(name,value,indent=""){if(value===null||value===undefined)return"";if(typeof value==="boolean")return`${indent}<${name}>${value}</${name}>
|
|
2
2
|
`;if(typeof value==="number"||typeof value==="string")return`${indent}<${name}>${value}</${name}>
|
|
3
|
-
`;if(Array.isArray(value))return value.map((item)=>buildCloudFrontXmlElement(name,item,indent)).join("");if(typeof value==="object"){if(name.startsWith("@_")||name==="?xml")return"";let children="";for(const[key,val]of Object.entries(value))if(!key.startsWith("@_")&&key!=="#text")children+=buildCloudFrontXmlElement(key,val,`${indent} `)
|
|
3
|
+
`;if(Array.isArray(value))return value.map((item)=>buildCloudFrontXmlElement(name,item,indent)).join("");if(typeof value==="object"){if(name.startsWith("@_")||name==="?xml")return"";let children="";for(const[key,val]of Object.entries(value)){if(!key.startsWith("@_")&&key!=="#text"){children+=buildCloudFrontXmlElement(key,val,`${indent} `)}}if(value["#text"]!==undefined)return`${indent}<${name}>${value["#text"]}</${name}>
|
|
4
4
|
`;return`${indent}<${name}>
|
|
5
5
|
${children}${indent}</${name}>
|
|
6
6
|
`}return""}function buildCloudFrontDistributionConfigXml(config){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
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
|
-
`}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 ${
|
|
10
|
-
`)){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const eqIndex=trimmed.indexOf("=")
|
|
11
|
-
Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`)
|
|
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";const args=uniquePorts.map((port)=>`--add-port=${port}/tcp`).join(" ");return`if command -v firewall-cmd >/dev/null 2>&1; then firewall-cmd --permanent ${args} && firewall-cmd --reload; fi`}async function ensureSecurityGroupPort(ec2,securityGroupId,port){if(!securityGroupId)return;const securityGroups=await ec2.describeSecurityGroups({GroupIds:[securityGroupId]});const permissions=securityGroups?.SecurityGroups?.[0]?.IpPermissions||[];const alreadyOpen=permissions.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")});if(alreadyOpen)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:true});const etag=getResult.headers?.etag||getResult.headers?.ETag||"";const currentConfig=getResult.body?.DistributionConfig||getResult.DistributionConfig||getResult.body;if(!etag||!currentConfig?.Origins?.Items)return;const origins=normalizeArray(currentConfig.Origins.Items.Origin);const apiOrigin=origins.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";const{stacksCloudRegion:hookRegion}=await import("@stacksjs/cloud");await runBeforeDeployHook(p.projectPath(),{environment:hookEnvironment,region:await hookRegion(undefined,hookEnvironment)});const frameworkBuildSpinner=spinner("Building framework...");frameworkBuildSpinner.start();const frameworkBuilt=await runCommand("bun run build",{cwd:p.frameworkPath("core"),quiet:false});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");const 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");const localBunpressCli=`${process.env.HOME}/Code/Tools/bunpress/packages/bunpress/bin/cli.ts`;const installedBunpressCli=p.projectPath("node_modules/@stacksjs/bunpress/dist/bin/cli.js");const hasLocalBunpress=await Bun.file(localBunpressCli).exists();const hasInstalledBunpress=await Bun.file(installedBunpressCli).exists();const 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:true,force:true});await runCommand(command,{cwd:p.projectPath(),quiet:!isVerbose});docsSpinner.succeed(`Documentation built with BunPress${hasLocalBunpress?" (local checkout)":""}`)}catch(docsError){docsSpinner.stop();console.log(`⚠ 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"));const blogFontAssetsExist=["CampmateScript-Regular.woff2","SequoiaSans-Regular.woff2","Switchback-Regular.woff2"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/fonts/nps/${file}`)));const blogImageAssetsExist=["topography.svg","park-ridge.svg"].every((file)=>existsSync(p.projectPath(`dist/blog/assets/images/${file}`)));const blogIndexPath=p.projectPath("dist/blog/index.html");const blogIndexHtml=existsSync(blogIndexPath)?readFileSync(blogIndexPath,"utf8"):"";const blogHtmlUsesCurrentFontFormat=blogIndexHtml.length>0&&!blogIndexHtml.includes("woff2-variations");const blogHtmlUsesCurrentParkTheme=blogIndexHtml.includes("--on-primary")&&blogIndexHtml.includes("--newsletter-bg");const blogHtmlUsesCurrentParkImages=blogIndexHtml.includes("topography.svg")&&blogIndexHtml.includes("park-ridge.svg");const blogHtmlOmitsRetiredDecorations=!blogIndexHtml.includes("stamp-trail")&&!blogIndexHtml.includes("blog-sign-tree.svg");const blogBuilderPath=p.frameworkPath("core/cms/src/build.ts");const blogConfigPath=p.projectPath("config/blog.ts");const 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;const{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(`⚠ 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"));const earlyDeploymentMode=earlyCloudConfig?.tsCloud?.mode||"server";if(earlyDeploymentMode==="serverless"){const serverSpinner=spinner("Building server...");serverSpinner.start();const serverBuilt=await runCommand("bun build.ts",{cwd:p.frameworkPath("server"),quiet:!isVerbose});if(serverBuilt.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();const packaged=await runCommand("bun zip.ts",{cwd:p.corePath("cloud"),quiet:!isVerbose});if(packaged.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");const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";const 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("=");const 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");const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const region=await stacksCloudRegion(undefined,environment);const cloudStackName=await stacksCloudName();const cloudConfigModule=await import(p.projectPath("config/cloud"));const deploymentMode=cloudConfigModule?.tsCloud?.mode||"server";const 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 new Error(`Invalid AWS Account ID: "${accountId||"(empty)"}"
|
|
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`;const 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");const{promisify}=await import("node:util");const execAsync=promisify(exec);const buildCmd=`docker build --platform linux/amd64 -t ${imageTag} -f Dockerfile .`;const{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");const ecr=new ECRClient(region);const 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:true},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");const ecr=new ECRClient(region);const authData=await ecr.getAuthorizationToken();const token=authData.authorizationData?.[0];if(!token?.authorizationToken){throw new Error("No authorization token received from ECR")}const decoded=Buffer.from(token.authorizationToken,"base64").toString("utf-8");const colonIndex=decoded.indexOf(":");if(colonIndex===-1){throw new Error("ECR authorization token has unexpected format (missing colon separator)")}const password=decoded.slice(colonIndex+1);const 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 new 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");const{promisify}=await import("node:util");const execAsync=promisify(exec);const 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");const sts=new STSClient(region);const identity=await sts.getCallerIdentity();const accountId=identity.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:true,verbose:isVerbose});try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.afterDeploy==="function"){const{CloudFormationClient}=await import("@stacksjs/ts-cloud");const cf=new CloudFormationClient(region);const 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(`⚠ 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(`⚠ 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");const failures=[];const 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(`⚠ 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(`⚠ 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");const cf=new CloudFormationClient(region);const stackName=cloudStackName;const 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(`⚠ 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");const{readFileSync:readServerFile,existsSync:serverFileExists}=await import("node:fs");const{resolve}=await import("node:path");const s3=new S3Client(region);const cf=new CloudFormationClient(region);const awsClient=new AWSClient;const stackName=cloudStackName;const outputs=await cf.getStackOutputs(stackName);const bucketName=outputs.FrontendBucketName;const 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");const ec2=new EC2Client(region);const instanceData=await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[instanceId]}]});const securityGroups=instanceData?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups;securityGroupId=securityGroups?.[0]?.GroupId;await ensureSecurityGroupPort(ec2,securityGroupId,apiServerPort)}if(!instanceId||!bucketName){serverDeploySpinner.stop();if(!instanceId)console.log("⚠ No EC2 instance found in stack outputs, skipping server deploy");if(!bucketName)console.log("⚠ 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
|
|
|
14
14
|
const db = new Database("/var/www/api/stacks.db");
|
|
@@ -146,7 +146,7 @@ Environment=NODE_ENV=production
|
|
|
146
146
|
WantedBy=multi-user.target
|
|
147
147
|
SERVICEFILE
|
|
148
148
|
systemctl daemon-reload
|
|
149
|
-
systemctl enable stacks-api`,"systemctl reset-failed stacks-api || true","systemctl restart stacks-api",`for i in $(seq 1 20); do curl -fsS http://127.0.0.1:${apiServerPort}/api/health && break; sleep 1; done`,`curl -fsS http://127.0.0.1:${apiServerPort}/api/health`,`echo "API server deployed and restarted on port ${apiServerPort}"`].join(" && ")
|
|
149
|
+
systemctl enable stacks-api`,"systemctl reset-failed stacks-api || true","systemctl restart stacks-api",`for i in $(seq 1 20); do curl -fsS http://127.0.0.1:${apiServerPort}/api/health && break; sleep 1; done`,`curl -fsS http://127.0.0.1:${apiServerPort}/api/health`,`echo "API server deployed and restarted on port ${apiServerPort}"`].join(" && ");const ssmResult=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[instanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[ssmCommand]},TimeoutSeconds:120})});const commandId=ssmResult?.Command?.CommandId;if(commandId){let attempts=0;while(attempts<30){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:commandId,InstanceId:instanceId})});const status=invocation?.Status;if(status==="Success"){serverDeploySpinner.succeed("API server deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){const errOutput=invocation?.StandardErrorContent||"Unknown error";serverDeploySpinner.fail(`API server deploy failed: ${errOutput}`);break}}catch{}attempts++}if(attempts>=30){serverDeploySpinner.fail("API server deploy timed out waiting for SSM command")}}else{serverDeploySpinner.fail("Failed to send SSM command")}try{await s3.deleteObject(bucketName,"_deploy/ts-cloud-dist.js");await s3.deleteObject(bucketName,"_deploy/server.ts")}catch{}}}catch(serverDeployError){serverDeploySpinner.fail(`API server deployment failed: ${serverDeployError.message}`);if(isVerbose)log.debug(`Server deploy error: ${serverDeployError.stack}`)}const emailConfig=config.email;if(emailConfig?.server?.enabled){const mailServerMode=emailConfig?.server?.mode||"server";const smtpSpinner=spinner(`Deploying mail server (${mailServerMode} mode) to EC2...`);smtpSpinner.start();try{const{S3Client,AWSClient,EC2Client}=await import("@stacksjs/ts-cloud");const{readFileSync:readSmtpFile,existsSync:smtpFileExists}=await import("node:fs");const{resolve:resolvePath,join:joinPath}=await import("node:path");const{execSync}=await import("node:child_process");const s3=new S3Client(region);const awsClient=new AWSClient;const ec2=new EC2Client(region);const stackName=cloudStackName;let smtpInstanceId;let smtpBucketName;let emailBucketName;let securityGroupId;try{const{AWSCloudFormationClient:CfnClient}=await import("@stacksjs/ts-cloud");const cfn=new CfnClient(region);const cfnOutputs=await cfn.getStackOutputs(stackName);for(const[key,value]of Object.entries(cfnOutputs)){if(key.endsWith("InstanceId")&&typeof value==="string"){smtpInstanceId=value}if(key==="FrontendBucketName"&&typeof value==="string"){smtpBucketName=value}if(key==="emailBucketName"&&typeof value==="string"){emailBucketName=value}}}catch{}if(!emailBucketName){emailBucketName=`${projectName}-production-s3-email`}if(smtpInstanceId&&smtpBucketName){const mailPorts=[25,80,110,143,465,587,993,995];try{const instanceData=await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[smtpInstanceId]}]});const sgs=instanceData?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups;if(sgs?.[0]?.GroupId){securityGroupId=sgs[0].GroupId}}catch{if(isVerbose)log.debug("Could not get security group for instance")}if(securityGroupId){for(const port of mailPorts){try{await ec2.authorizeSecurityGroupIngress({GroupId:securityGroupId,IpPermissions:[{IpProtocol:"tcp",FromPort:port,ToPort:port,IpRanges:[{CidrIp:"0.0.0.0/0",Description:`Mail port ${port}`}]}]});if(isVerbose)log.debug(` Opened port ${port} on security group ${securityGroupId}`)}catch(e){if(!e.message?.includes("already exists")){if(isVerbose)log.debug(` Port ${port}: ${e.message}`)}}}}const domain=emailConfig.domain||"stacksjs.com";const mailSubdomain=emailConfig?.server?.subdomain||"mail";if(mailServerMode==="server"){if(isVerbose)log.debug("Deploying Zig mail server binary...");try{await installMailBinaryWithPantry()}catch(error){if(isVerbose)log.debug(` Pantry mail install failed: ${error.message}`)}const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&smtpFileExists(linuxBinaryPath)){if(!await isElfBinary(linuxBinaryPath)){smtpSpinner.fail(`Pantry installed ${MAIL_PACKAGE_DOMAIN}, but the ${MAIL_TARGET_PLATFORM} binary is not an ELF file.`);throw new Error("Linux binary is not a valid ELF file")}const binaryContent=readSmtpFile(linuxBinaryPath);await s3.putObject({bucket:emailBucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});if(isVerbose)log.debug(` Uploaded Zig binary (${(binaryContent.length/1024/1024).toFixed(1)}MB) to S3`);const zigSsmCommand=["systemctl stop stacks-mail 2>/dev/null || true","systemctl disable stacks-mail 2>/dev/null || true","systemctl stop stacks-smtp 2>/dev/null || true","systemctl disable stacks-smtp 2>/dev/null || true","systemctl stop smtp-server 2>/dev/null || true","mkdir -p /opt/smtp-server /var/lib/smtp-server /var/log/smtp-server /var/spool/mail /etc/smtp-server /var/lib/smtp-server/backups",`aws s3 cp s3://${emailBucketName}/mail-server/smtp-server /opt/smtp-server/smtp-server --region ${region}`,"chmod +x /opt/smtp-server/smtp-server",'file /opt/smtp-server/smtp-server | grep -q ELF || { echo "Binary is not ELF"; exit 1; }',firewallOpenCommand(mailPorts),`cat > /etc/smtp-server/smtp-server.env << 'ENVEOF'
|
|
150
150
|
SMTP_PROFILE=production
|
|
151
151
|
SMTP_HOST=0.0.0.0
|
|
152
152
|
SMTP_PORT=25
|
|
@@ -184,8 +184,8 @@ SyslogIdentifier=smtp-server
|
|
|
184
184
|
|
|
185
185
|
[Install]
|
|
186
186
|
WantedBy=multi-user.target
|
|
187
|
-
SVCEOF`,"systemctl daemon-reload","systemctl enable smtp-server","systemctl restart smtp-server","sleep 3",'systemctl is-active smtp-server && echo "Mail server is running" || echo "Mail server failed to start"','ss -tlnp | grep -E "(25|143)" || echo "Warning: mail ports not listening yet"'].join(" && ")
|
|
188
|
-
`)
|
|
187
|
+
SVCEOF`,"systemctl daemon-reload","systemctl enable smtp-server","systemctl restart smtp-server","sleep 3",'systemctl is-active smtp-server && echo "Mail server is running" || echo "Mail server failed to start"','ss -tlnp | grep -E "(25|143)" || echo "Warning: mail ports not listening yet"'].join(" && ");const ssmResult=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[smtpInstanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[zigSsmCommand]},TimeoutSeconds:300})});const cmdId=ssmResult?.Command?.CommandId;if(cmdId){let ssmAttempts=0;while(ssmAttempts<100){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:cmdId,InstanceId:smtpInstanceId})});const status=invocation?.Status;if(status==="Success"){smtpSpinner.succeed("Zig mail server deployed to EC2");if(isVerbose&&invocation?.StandardOutputContent){console.log(invocation.StandardOutputContent)}break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){const errOutput=invocation?.StandardErrorContent||invocation?.StandardOutputContent||"Unknown error";smtpSpinner.fail(`Zig mail server deploy failed: ${errOutput.slice(0,500)}`);break}}catch{}ssmAttempts++}if(ssmAttempts>=100){smtpSpinner.fail("Zig mail server deploy timed out")}}else{smtpSpinner.fail("Failed to send SSM command for mail server")}}else{smtpSpinner.fail(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`)}}else{const smtpServerSrc=resolvePath(p.projectPath("storage/framework/core/cloud/src/imap/smtp-server.ts"));const bundleOutDir=p.frameworkRuntimePath("tmp/smtp-bundle");execSync(`bun build ${smtpServerSrc} --target=bun --outdir=${bundleOutDir}`,{stdio:"pipe"});const bundlePath=joinPath(bundleOutDir,"smtp-server.js");if(smtpFileExists(bundlePath)){const smtpBundle=readSmtpFile(bundlePath);const mailboxes=emailConfig.mailboxes||["chris","blake","glenn"];const usersEntries=mailboxes.map((name)=>{const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;return` "${name}": { password: process.env["${envKey}"] || "", email: "${name}@${domain}" }`}).join(`,
|
|
188
|
+
`);const entryPoint=`import { SmtpServer } from "./smtp-server.js";
|
|
189
189
|
import * as fs from "fs";
|
|
190
190
|
const domain = "${domain}";
|
|
191
191
|
const users = { ${usersEntries} };
|
|
@@ -197,7 +197,7 @@ if (fs.existsSync(\`\${certDir}/privkey.pem\`)) {
|
|
|
197
197
|
const server = new SmtpServer({ port: 587, tlsPort: 465, host: "0.0.0.0", domain, users, tls: tlsConfig, sentBucket: "${projectName}-production-email", sentPrefix: "sent/" });
|
|
198
198
|
await server.start();
|
|
199
199
|
`;await s3.putObject({bucket:smtpBucketName,key:"_deploy/smtp-server.js",body:smtpBundle,contentType:"application/javascript"});await s3.putObject({bucket:smtpBucketName,key:"_deploy/smtp-entry.ts",body:Buffer.from(entryPoint),contentType:"application/typescript"});const envLines=mailboxes.map((name)=>{const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;return`Environment=${envKey}=${process.env[envKey]||""}`}).join(`
|
|
200
|
-
`)
|
|
200
|
+
`);const smtpSsmCommand=["mkdir -p /var/www/smtp",`aws s3 cp s3://${smtpBucketName}/_deploy/smtp-server.js /var/www/smtp/smtp-server.js`,`aws s3 cp s3://${smtpBucketName}/_deploy/smtp-entry.ts /var/www/smtp/smtp-entry.ts`,firewallOpenCommand(mailPorts),`if ! command -v certbot &> /dev/null; then dnf install -y certbot || yum install -y certbot || apt-get install -y certbot || true; fi`,`if [ ! -d /etc/letsencrypt/live/mail.${domain} ]; then certbot certonly --standalone --non-interactive --agree-tos --email admin@${domain} -d mail.${domain} --http-01-port 80 || echo "Certbot failed"; fi`,`cat > /etc/systemd/system/stacks-smtp.service << 'SERVICEFILE'
|
|
201
201
|
[Unit]
|
|
202
202
|
Description=Stacks SMTP Proxy Server
|
|
203
203
|
After=network.target
|
|
@@ -212,7 +212,7 @@ Environment=AWS_REGION=${region}
|
|
|
212
212
|
${envLines}
|
|
213
213
|
[Install]
|
|
214
214
|
WantedBy=multi-user.target
|
|
215
|
-
SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl restart stacks-smtp"].join(" && ")
|
|
215
|
+
SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl restart stacks-smtp"].join(" && ");const ssmResult=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.SendCommand"},body:JSON.stringify({InstanceIds:[smtpInstanceId],DocumentName:"AWS-RunShellScript",Parameters:{commands:[smtpSsmCommand]},TimeoutSeconds:180})});const cmdId=ssmResult?.Command?.CommandId;if(cmdId){let ssmAttempts=0;while(ssmAttempts<60){await new Promise((resolve)=>setTimeout(resolve,3000));try{const invocation=await awsClient.request({service:"ssm",region,method:"POST",path:"/",headers:{"Content-Type":"application/x-amz-json-1.1","X-Amz-Target":"AmazonSSM.GetCommandInvocation"},body:JSON.stringify({CommandId:cmdId,InstanceId:smtpInstanceId})});const status=invocation?.Status;if(status==="Success"){smtpSpinner.succeed("SMTP proxy deployed to EC2");break}else if(status==="Failed"||status==="Cancelled"||status==="TimedOut"){smtpSpinner.fail(`SMTP proxy deploy failed: ${invocation?.StandardErrorContent||"Unknown"}`);break}}catch{}ssmAttempts++}if(ssmAttempts>=60)smtpSpinner.fail("SMTP proxy deploy timed out")}else{smtpSpinner.fail("Failed to send SSM command for SMTP proxy")}try{await s3.deleteObject(smtpBucketName,"_deploy/smtp-server.js");await s3.deleteObject(smtpBucketName,"_deploy/smtp-entry.ts")}catch{}}else{smtpSpinner.stop();if(isVerbose)log.debug("SMTP server bundle not found, skipping")}}}else{smtpSpinner.stop();if(isVerbose)log.debug("No EC2 instance or bucket found, skipping mail server deploy")}}catch(smtpDeployError){smtpSpinner.fail(`Mail server deployment failed: ${smtpDeployError.message}`);if(isVerbose)log.debug(`Mail server deploy error: ${smtpDeployError.stack}`)}}}const frontendSpinner=spinner("Deploying frontend to S3...");frontendSpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud");const{readFileSync}=await import("node:fs");const{buildFrontendStatic}=await import("../build/frontend-static");const s3=new S3Client(region);const cf=new CloudFormationClient(region);const stackName=cloudStackName;const stackOutputs=await cf.getStackOutputs(stackName);const bucketName=stackOutputs.FrontendBucketName;if(!bucketName){frontendSpinner.stop();console.log("⚠ Frontend bucket not found in stack outputs (add storage.public to infrastructure config)")}else{const buildDir=await buildFrontendStatic();const uploadDir=async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath);const contentType=getMimeType(filePath);const cacheControl=key==="index.html"||key.endsWith("/index.html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>s3.putObject({bucket:bucketName,key,body:content,contentType,cacheControl}),`upload ${key}`);if(isVerbose)log.debug(` Uploaded: ${key}`)})};await uploadDir(buildDir);const bootstrapPath=p.projectPath("bootstrap");if(existsSync(bootstrapPath)){const bootstrapContent=readFileSync(bootstrapPath);await withS3Retry(()=>s3.putObject({bucket:bucketName,key:"install",body:bootstrapContent,contentType:"text/plain",cacheControl:"no-cache, no-store, must-revalidate"}),"upload bootstrap install script");if(isVerbose)log.debug(" Uploaded bootstrap install script")}const distributionId=stackOutputs.publicCloudFrontDistributionId||stackOutputs.CloudFrontDistributionId;if(distributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache...");const{AWSClient}=await import("@stacksjs/ts-cloud");const client=new AWSClient;await client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${distributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
216
216
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
217
217
|
<CallerReference>${Date.now()}</CallerReference>
|
|
218
218
|
<Paths>
|
|
@@ -221,7 +221,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
221
221
|
<Path>/*</Path>
|
|
222
222
|
</Items>
|
|
223
223
|
</Paths>
|
|
224
|
-
</InvalidationBatch>`})}frontendSpinner.succeed(`Frontend deployed to S3 (${bucketName})`)}}catch(frontendError){frontendSpinner.fail(`Frontend deployment failed: ${frontendError.message}`);if(isVerbose)log.debug(`Frontend error: ${frontendError.stack}`)}const docsDistPath=p.projectPath("dist/docs/.bunpress")
|
|
224
|
+
</InvalidationBatch>`})}frontendSpinner.succeed(`Frontend deployed to S3 (${bucketName})`)}}catch(frontendError){frontendSpinner.fail(`Frontend deployment failed: ${frontendError.message}`);if(isVerbose)log.debug(`Frontend error: ${frontendError.stack}`)}const docsDistPath=p.projectPath("dist/docs/.bunpress");const{existsSync:docsExists}=await import("node:fs");if(docsExists(docsDistPath)){const docsDeploySpinner=spinner("Deploying documentation to S3...");docsDeploySpinner.start();try{const{S3Client,CloudFormationClient}=await import("@stacksjs/ts-cloud");const{readFileSync}=await import("node:fs");const s3=new S3Client(region);const cf=new CloudFormationClient(region);const stackName=cloudStackName;const docsOutputs=await cf.getStackOutputs(stackName);const docsBucketName=docsOutputs.DocsBucketName;if(!docsBucketName){docsDeploySpinner.stop();console.log("⚠ Docs bucket not found in stack outputs (infrastructure may not be updated yet)")}else{const uploadDocsDir=async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath);const contentType=getMimeType(filePath);const cacheControl=key.endsWith(".html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>s3.putObject({bucket:docsBucketName,key,body:content,contentType,cacheControl}),`upload docs ${key}`);if(isVerbose)log.debug(` Uploaded docs: ${key}`)},"",[".DS_Store",".bunpress"])};await uploadDocsDir(docsDistPath);const docsDistributionId=docsOutputs.docsCloudFrontDistributionId||docsOutputs.publicCloudFrontDistributionId||docsOutputs.CloudFrontDistributionId;if(docsDistributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache for docs...");const{AWSClient}=await import("@stacksjs/ts-cloud");const client=new AWSClient;const docsInvalidationPaths=docsOutputs.docsCloudFrontDistributionId?["/*"]:["/docs","/docs/*"];await client.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${docsDistributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
225
225
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
226
226
|
<CallerReference>docs-${Date.now()}</CallerReference>
|
|
227
227
|
<Paths>
|
|
@@ -231,7 +231,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
231
231
|
`)}
|
|
232
232
|
</Items>
|
|
233
233
|
</Paths>
|
|
234
|
-
</InvalidationBatch>`})}docsDeploySpinner.succeed(`Documentation deployed to S3 (${docsBucketName})`)}}catch(docsDeployError){docsDeploySpinner.fail(`Documentation deployment failed: ${docsDeployError.message}`);if(isVerbose)log.debug(`Docs deploy error: ${docsDeployError.stack}`)}}else
|
|
234
|
+
</InvalidationBatch>`})}docsDeploySpinner.succeed(`Documentation deployed to S3 (${docsBucketName})`)}}catch(docsDeployError){docsDeploySpinner.fail(`Documentation deployment failed: ${docsDeployError.message}`);if(isVerbose)log.debug(`Docs deploy error: ${docsDeployError.stack}`)}}else{if(isVerbose)log.debug("No docs build found at dist/docs, skipping docs deployment")}const blogDistPath=p.projectPath("dist/blog");const{existsSync:blogExists}=await import("node:fs");if(blogExists(blogDistPath)){const blogDeploySpinner=spinner("Deploying blog to S3...");blogDeploySpinner.start();try{const{S3Client:BlogS3Client,CloudFormationClient:BlogCFClient}=await import("@stacksjs/ts-cloud");const{readFileSync:readBlogFile}=await import("node:fs");const blogS3=new BlogS3Client(region);const blogCf=new BlogCFClient(region);const stackName=cloudStackName;const outputs=await blogCf.getStackOutputs(stackName);const blogBucketName=outputs.BlogBucketName;if(!blogBucketName){blogDeploySpinner.stop();console.log("⚠ Blog bucket not found in stack outputs")}else{await traverseDirectory(blogDistPath,async(filePath,key)=>{const content=readBlogFile(filePath);const contentType=getMimeType(filePath);const cacheControl=key.endsWith(".html")?"no-cache, no-store, must-revalidate":"public, max-age=31536000, immutable";await withS3Retry(()=>blogS3.putObject({bucket:blogBucketName,key,body:content,contentType,cacheControl}),`upload blog ${key}`);if(isVerbose)log.debug(` Uploaded blog: ${key}`)},"",[".DS_Store"]);const blogDistributionId=outputs.blogCloudFrontDistributionId||outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId;if(blogDistributionId){if(isVerbose)log.debug(" Invalidating CloudFront cache for blog...");const{AWSClient:BlogAWSClient}=await import("@stacksjs/ts-cloud");const blogClient=new BlogAWSClient;const blogInvalidationPaths=outputs.blogCloudFrontDistributionId?["/*"]:["/blog","/blog/*"];await blogClient.request({service:"cloudfront",region:"us-east-1",method:"POST",path:`/2020-05-31/distribution/${blogDistributionId}/invalidation`,headers:{"Content-Type":"application/xml"},body:`<?xml version="1.0" encoding="UTF-8"?>
|
|
235
235
|
<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
236
236
|
<CallerReference>blog-${Date.now()}</CallerReference>
|
|
237
237
|
<Paths>
|
|
@@ -241,7 +241,7 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
241
241
|
`)}
|
|
242
242
|
</Items>
|
|
243
243
|
</Paths>
|
|
244
|
-
</InvalidationBatch>`})}blogDeploySpinner.succeed(`Blog deployed to S3 (${blogBucketName})`)}}catch(blogDeployError){blogDeploySpinner.fail(`Blog deployment failed: ${blogDeployError.message}`);if(isVerbose)log.debug(`Blog deploy error: ${blogDeployError.stack}`)}}else
|
|
244
|
+
</InvalidationBatch>`})}blogDeploySpinner.succeed(`Blog deployed to S3 (${blogBucketName})`)}}catch(blogDeployError){blogDeploySpinner.fail(`Blog deployment failed: ${blogDeployError.message}`);if(isVerbose)log.debug(`Blog deploy error: ${blogDeployError.stack}`)}}else{if(isVerbose)log.debug("No blog build found at dist/blog, skipping blog deployment")}const errorPageSpinner=spinner("Configuring 404 error page...");errorPageSpinner.start();try{const{S3Client,CloudFormationClient,AWSClient}=await import("@stacksjs/ts-cloud");const{existsSync:exists404,readFileSync:read404}=await import("node:fs");const s3=new S3Client(region);const cf=new CloudFormationClient(region);const awsClient=new AWSClient;const stackName=cloudStackName;const outputs=await cf.getStackOutputs(stackName);const frontendBucket=outputs.FrontendBucketName;const docsBucket=outputs.DocsBucketName;const distributionId=outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId;const docs404Path=p.projectPath("dist/docs/.bunpress/404.html");let html404Content;if(exists404(docs404Path)){html404Content=read404(docs404Path,"utf-8");if(isVerbose)log.debug(" Using BunPress-generated 404.html")}else{html404Content=`<!DOCTYPE html>
|
|
245
245
|
<html lang="en">
|
|
246
246
|
<head>
|
|
247
247
|
<meta charset="UTF-8">
|
|
@@ -288,12 +288,12 @@ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl
|
|
|
288
288
|
<div class="action"><a class="link" href="/docs/">Take me home</a></div>
|
|
289
289
|
</div>
|
|
290
290
|
</body>
|
|
291
|
-
</html>`;if(isVerbose)log.debug(" Using default 404.html template")}if(frontendBucket){await withS3Retry(()=>s3.putObject({bucket:frontendBucket,key:"404.html",body:html404Content,contentType:"text/html",cacheControl:"no-cache, no-store, must-revalidate"}),"upload 404.html to frontend bucket");if(isVerbose)log.debug(` Uploaded 404.html to frontend bucket: ${frontendBucket}`)}if(docsBucket){await withS3Retry(()=>s3.putObject({bucket:docsBucket,key:"404.html",body:html404Content,contentType:"text/html",cacheControl:"no-cache, no-store, must-revalidate"}),"upload 404.html to docs bucket");if(isVerbose)log.debug(` Uploaded 404.html to docs bucket: ${docsBucket}`)}if(distributionId){if(isVerbose)log.debug(" Configuring CloudFront custom error responses...");const getResult=await awsClient.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${distributionId}/config`,returnHeaders
|
|
291
|
+
</html>`;if(isVerbose)log.debug(" Using default 404.html template")}if(frontendBucket){await withS3Retry(()=>s3.putObject({bucket:frontendBucket,key:"404.html",body:html404Content,contentType:"text/html",cacheControl:"no-cache, no-store, must-revalidate"}),"upload 404.html to frontend bucket");if(isVerbose)log.debug(` Uploaded 404.html to frontend bucket: ${frontendBucket}`)}if(docsBucket){await withS3Retry(()=>s3.putObject({bucket:docsBucket,key:"404.html",body:html404Content,contentType:"text/html",cacheControl:"no-cache, no-store, must-revalidate"}),"upload 404.html to docs bucket");if(isVerbose)log.debug(` Uploaded 404.html to docs bucket: ${docsBucket}`)}if(distributionId){if(isVerbose)log.debug(" Configuring CloudFront custom error responses...");const getResult=await awsClient.request({service:"cloudfront",region:"us-east-1",method:"GET",path:`/2020-05-31/distribution/${distributionId}/config`,returnHeaders:true});const etag=getResult.headers?.etag||getResult.headers?.ETag||"";const currentConfig=getResult.body?.DistributionConfig||getResult.DistributionConfig;if(currentConfig&&etag){const existingErrors=currentConfig.CustomErrorResponses?.Quantity||0;const has404Config=existingErrors>0&¤tConfig.CustomErrorResponses?.Items?.CustomErrorResponse?.some?.((err)=>err.ErrorCode===404&&err.ResponsePagePath==="/404.html");if(!has404Config){currentConfig.CustomErrorResponses={Quantity:2,Items:{CustomErrorResponse:[{ErrorCode:403,ResponsePagePath:"/404.html",ResponseCode:404,ErrorCachingMinTTL:10},{ErrorCode:404,ResponsePagePath:"/404.html",ResponseCode:404,ErrorCachingMinTTL:10}]}};const buildXmlElement=(name,value,indent="")=>{if(value===null||value===undefined)return"";if(typeof value==="boolean")return`${indent}<${name}>${value}</${name}>
|
|
292
292
|
`;if(typeof value==="number"||typeof value==="string")return`${indent}<${name}>${value}</${name}>
|
|
293
|
-
`;if(Array.isArray(value))return value.map((item)=>buildXmlElement(name,item,indent)).join("");if(typeof value==="object"){if(name.startsWith("@_")||name==="?xml")return"";let children="";for(const[key,val]of Object.entries(value))if(!key.startsWith("@_")&&key!=="#text")children+=buildXmlElement(key,val,`${indent} `)
|
|
293
|
+
`;if(Array.isArray(value))return value.map((item)=>buildXmlElement(name,item,indent)).join("");if(typeof value==="object"){if(name.startsWith("@_")||name==="?xml")return"";let children="";for(const[key,val]of Object.entries(value)){if(!key.startsWith("@_")&&key!=="#text"){children+=buildXmlElement(key,val,`${indent} `)}}if(value["#text"]!==undefined)return`${indent}<${name}>${value["#text"]}</${name}>
|
|
294
294
|
`;return`${indent}<${name}>
|
|
295
295
|
${children}${indent}</${name}>
|
|
296
|
-
`}return""}
|
|
296
|
+
`}return""};const xml=`<?xml version="1.0" encoding="UTF-8"?>
|
|
297
297
|
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
|
|
298
298
|
${Object.entries(currentConfig).filter(([key])=>!key.startsWith("@_")).map(([key,val])=>buildXmlElement(key,val," ")).join("")}</DistributionConfig>
|
|
299
|
-
`;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:xml,headers:{"Content-Type":"application/xml","If-Match":etag}});if(isVerbose)log.debug(" CloudFront custom error responses configured")}else
|
|
299
|
+
`;await awsClient.request({service:"cloudfront",region:"us-east-1",method:"PUT",path:`/2020-05-31/distribution/${distributionId}/config`,body:xml,headers:{"Content-Type":"application/xml","If-Match":etag}});if(isVerbose)log.debug(" CloudFront custom error responses configured")}else{if(isVerbose)log.debug(" CloudFront custom error responses already configured")}}}errorPageSpinner.succeed("404 error page configured")}catch(errorPageError){errorPageSpinner.stop();console.log(`⚠ 404 page configuration skipped: ${errorPageError.message}`);if(isVerbose)log.debug(`Error page config error: ${errorPageError.stack}`)}try{const tunnelCloudConfig=await import(p.projectPath("config/cloud"));const tunnelConfig=tunnelCloudConfig?.tsCloud?.infrastructure?.tunnel;if(tunnelConfig?.enabled){const tunnelDomain=tunnelConfig.domain||"";if(!tunnelDomain||tunnelDomain==="localtunnel.dev"||tunnelDomain==="api.localtunnel.dev"){console.log("ℹ Tunnel: Using shared localtunnel.dev (no custom tunnel deployment needed)")}else{const tunnelSpinner=spinner(`Deploying tunnel server to ${tunnelDomain}...`);tunnelSpinner.start();try{const{deployTunnelServer}=await import("@stacksjs/tunnel");await deployTunnelServer({domain:tunnelDomain,region:tunnelConfig.region||tunnelCloudConfig?.tsCloud?.project?.region||"us-east-1",instanceType:tunnelConfig.instanceType,prefix:tunnelConfig.prefix,enableSsl:tunnelConfig.ssl?.enabled,porkbunApiKey:tunnelConfig.ssl?.porkbunApiKey,porkbunSecretKey:tunnelConfig.ssl?.porkbunSecretKey,verbose:isVerbose});tunnelSpinner.succeed(`Tunnel server deployed to ${tunnelDomain}`)}catch(tunnelError){tunnelSpinner.stop();console.log(`⚠ Tunnel deployment skipped: ${tunnelError.message}`);if(isVerbose)log.debug(`Tunnel deploy error: ${tunnelError.stack}`)}}}}catch{}const dnsSpinner=spinner("Reconciling DNS records...");dnsSpinner.start();try{const{Route53Client,CloudFormationClient:DnsCfClient}=await import("@stacksjs/ts-cloud");const dnsCf=new DnsCfClient(region);const dnsStackName=cloudStackName;const dnsOutputs=await dnsCf.getStackOutputs(dnsStackName);const dnsCloudConfig=await import(p.projectPath("config/cloud"));const hostedZoneId=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.hostedZoneId;const siteDomain=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.domain||"stacksjs.com";if(hostedZoneId){const route53=new Route53Client(region);const cfHostedZoneId="Z2FDTNDATAQYW2";const domainMappings=[{domain:siteDomain,cfDomain:dnsOutputs.publicCloudFrontDomain},{domain:`www.${siteDomain}`,cfDomain:dnsOutputs.publicCloudFrontDomain},{domain:`docs.${siteDomain}`,cfDomain:dnsOutputs.docsCloudFrontDomain},{domain:`blog.${siteDomain}`,cfDomain:dnsOutputs.blogCloudFrontDomain}];let recordsCreated=0;for(const{domain,cfDomain}of domainMappings){if(!cfDomain)continue;try{const existing=await route53.listResourceRecordSets({HostedZoneId:hostedZoneId,StartRecordName:domain,StartRecordType:"A",MaxItems:"1"});const records=existing?.ResourceRecordSets||[];const hasARecord=records.some((r)=>r.Name===`${domain}.`&&r.Type==="A");if(!hasARecord){await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"A",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:false}}},{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"AAAA",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:false}}}]}});recordsCreated++;if(isVerbose)log.debug(` Created DNS records: ${domain} -> ${cfDomain}`)}else{if(isVerbose)log.debug(` DNS record exists: ${domain}`)}}catch(dnsErr){if(isVerbose)log.debug(` DNS check/create failed for ${domain}: ${dnsErr.message}`)}}if(recordsCreated>0){dnsSpinner.succeed(`DNS records reconciled (${recordsCreated} created)`)}else{dnsSpinner.succeed("DNS records verified")}}else{dnsSpinner.stop();if(isVerbose)log.debug("No hosted zone ID configured, skipping DNS reconciliation")}}catch(dnsError){dnsSpinner.stop();console.log(`⚠ DNS reconciliation skipped: ${dnsError.message}`);if(isVerbose)log.debug(`DNS error: ${dnsError.stack}`)}console.log("");log.success("Deployment completed successfully!")}catch(error){log.error("Deployment failed:",error);process.exit(ExitCode.FatalError)}
|