@stacksjs/actions 0.70.258 → 0.70.260

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/action.js +1 -80
  2. package/dist/actions.js +1 -2
  3. package/dist/add.js +1 -20
  4. package/dist/ai/request-model-access.js +1 -10
  5. package/dist/auth/client.js +2 -44
  6. package/dist/auth/prune.js +1 -35
  7. package/dist/auth/setup.js +33 -153
  8. package/dist/auth/token.js +1 -10
  9. package/dist/blog-admin.js +3 -151
  10. package/dist/blog.js +33 -271
  11. package/dist/build/cli.js +1 -6
  12. package/dist/build/component-library.js +1 -36
  13. package/dist/build/component-libs.js +1 -2
  14. package/dist/build/core.js +1 -55
  15. package/dist/build/desktop.js +4 -61
  16. package/dist/build/dmg.js +4 -68
  17. package/dist/build/docs.js +1 -5
  18. package/dist/build/frontend-static.js +6 -122
  19. package/dist/build/server.js +1 -6
  20. package/dist/build/stacks.js +1 -8
  21. package/dist/build/views.js +1 -16
  22. package/dist/build-web-component-lib.js +1 -2
  23. package/dist/build.js +1 -57
  24. package/dist/bump.js +9 -210
  25. package/dist/changelog.js +1 -27
  26. package/dist/check/ports.js +1 -16
  27. package/dist/clean.js +1 -4
  28. package/dist/commit.js +1 -12
  29. package/dist/copy-types.js +1 -9
  30. package/dist/database/seed.js +1 -26
  31. package/dist/deploy/create-receipt-rule.js +1 -36
  32. package/dist/deploy/index.js +29 -1306
  33. package/dist/dev/api.js +3 -94
  34. package/dist/dev/components.js +1 -7
  35. package/dist/dev/csrf.js +1 -28
  36. package/dist/dev/dashboard-request-routing.js +1 -10
  37. package/dist/dev/dashboard-utils.js +1 -380
  38. package/dist/dev/dashboard.js +7 -422
  39. package/dist/dev/desktop.js +1 -1
  40. package/dist/dev/docs.js +1 -24
  41. package/dist/dev/exit-with-parent.d.ts +6 -0
  42. package/dist/dev/exit-with-parent.js +1 -0
  43. package/dist/dev/index.js +1 -29
  44. package/dist/dev/migrate-watcher.js +1 -74
  45. package/dist/dev/system-tray.js +2 -172
  46. package/dist/dev/views.js +1 -169
  47. package/dist/discover-packages.js +1 -32
  48. package/dist/domains/add.js +1 -61
  49. package/dist/domains/purchase.js +1 -66
  50. package/dist/domains/remove.js +1 -24
  51. package/dist/examples.js +1 -34
  52. package/dist/find-projects.js +1 -16
  53. package/dist/fresh.js +1 -17
  54. package/dist/generate/action-types.js +3 -9
  55. package/dist/generate/component-meta.js +1 -9
  56. package/dist/generate/custom-cli-file.js +2 -20
  57. package/dist/generate/env-files.js +5 -46
  58. package/dist/generate/ide-helpers.js +1 -8
  59. package/dist/generate/images.js +1 -26
  60. package/dist/generate/index.js +1 -166
  61. package/dist/generate/lib-entries.js +1 -16
  62. package/dist/generate/pantry-file.js +1 -46
  63. package/dist/generate/symlink-core.js +1 -2
  64. package/dist/generate/types.js +1 -3
  65. package/dist/generate/vschema.js +2 -47
  66. package/dist/generate/vscode-custom-data.js +1 -9
  67. package/dist/helpers/api-host.js +1 -7
  68. package/dist/helpers/component-meta.js +5 -295
  69. package/dist/helpers/index.js +1 -1
  70. package/dist/helpers/lib-entries.js +3 -73
  71. package/dist/helpers/package-json.js +2 -34
  72. package/dist/helpers/utils.js +1 -130
  73. package/dist/helpers/vscode-custom-data.js +3 -57
  74. package/dist/index.js +1 -51
  75. package/dist/key-generate.js +1 -24
  76. package/dist/lint/fix.js +1 -4
  77. package/dist/lint/index.js +1 -4
  78. package/dist/lint/lint.js +1 -34
  79. package/dist/lint/stx-gate.js +3 -175
  80. package/dist/make-command.js +4 -55
  81. package/dist/make-job.js +3 -29
  82. package/dist/make-policy.js +4 -53
  83. package/dist/make-resource.js +3 -33
  84. package/dist/make.js +7 -323
  85. package/dist/migrate/database.js +1 -16
  86. package/dist/migrate/fresh.js +1 -36
  87. package/dist/prepublish.js +1 -16
  88. package/dist/queue/clear.js +1 -42
  89. package/dist/queue/dlq-purge.js +1 -28
  90. package/dist/queue/dlq-retry.js +1 -35
  91. package/dist/queue/dlq.js +4 -55
  92. package/dist/queue/failed.js +4 -69
  93. package/dist/queue/flush.js +2 -49
  94. package/dist/queue/inspect.js +7 -154
  95. package/dist/queue/list.js +4 -69
  96. package/dist/queue/monitor.js +5 -94
  97. package/dist/queue/pause.js +1 -28
  98. package/dist/queue/quarantine.js +2 -42
  99. package/dist/queue/resume.js +1 -27
  100. package/dist/queue/retry.js +1 -41
  101. package/dist/queue/schedule-list.js +4 -33
  102. package/dist/queue/schedule.js +1 -12
  103. package/dist/queue/status.js +4 -68
  104. package/dist/queue/table.js +1 -10
  105. package/dist/queue/unquarantine.js +1 -27
  106. package/dist/queue/work.js +1 -57
  107. package/dist/release-preflight.js +3 -61
  108. package/dist/release.js +1 -29
  109. package/dist/route/list.js +2 -78
  110. package/dist/run-action.js +1 -1
  111. package/dist/saas/setup.js +1 -9
  112. package/dist/scaffold-crud.js +12 -137
  113. package/dist/schedule/run.js +1 -7
  114. package/dist/search/flush.js +1 -10
  115. package/dist/search/import.js +1 -10
  116. package/dist/search/settings-list.js +1 -10
  117. package/dist/search/settings.js +1 -9
  118. package/dist/serve/api.js +1 -37
  119. package/dist/setup/index.js +1 -1
  120. package/dist/setup/ssl.js +2 -268
  121. package/dist/stacks.js +1 -316
  122. package/dist/templates.js +20 -40
  123. package/dist/test/feature.js +1 -2
  124. package/dist/test/index.js +1 -2
  125. package/dist/test/runner.js +1 -38
  126. package/dist/test/runner.test.js +1 -29
  127. package/dist/test/ui.js +1 -2
  128. package/dist/test/unit.js +1 -2
  129. package/dist/typecheck.js +1 -4
  130. package/dist/types.js +1 -16
  131. package/dist/upgrade/binary.js +1 -29
  132. package/dist/upgrade/framework-hooks.js +1 -40
  133. package/dist/upgrade/framework-utils.js +2 -259
  134. package/dist/upgrade/framework.js +11 -484
  135. package/dist/upgrade/index.js +1 -17
  136. package/dist/upgrade/package-project.js +1 -150
  137. package/dist/upgrade/packages.js +17 -243
  138. package/dist/upgrade/shell.js +3 -40
  139. package/dist/upgrade.js +1 -38
  140. package/package.json +18 -18
@@ -1,615 +1,14 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
2
- import process from "node:process";
3
- import { runCommand, spinner } from "@stacksjs/cli";
4
- import { config } from "@stacksjs/config";
5
- import { path as p } from "@stacksjs/path";
6
- import { storage } from "@stacksjs/storage";
7
- import { ExitCode } from "@stacksjs/types";
8
- const log = {
9
- debug: (...args) => {
10
- if (process.argv.includes("--verbose") || process.argv.includes("-v"))
11
- console.log("\uD83D\uDD0D", ...args);
12
- },
13
- success: (...args) => console.log("\u2713", ...args),
14
- error: (...args) => console.error("\u2717", ...args)
15
- }, MAIL_PACKAGE_DOMAIN = "github.com/mail-os/mail", MAIL_PACKAGE_SPEC = `${MAIL_PACKAGE_DOMAIN}@0.1.0`, MAIL_TARGET_PLATFORM = "linux-x86_64", MAIL_BINARY_NAMES = ["mail", "mail-x86_64-linux", "mail-x86_64-linux-gnu"], isVerbose = process.argv.includes("--verbose") || process.argv.includes("-v");
16
- async function collectMatchingFiles(root, names, maxDepth = 8) {
17
- const { existsSync, readdirSync, statSync } = await import("node:fs"), { join, basename } = await import("node:path"), nameSet = new Set(names), matches = [];
18
- if (!existsSync(root))
19
- return matches;
20
- function walk(dir, depth) {
21
- if (depth > maxDepth)
22
- return;
23
- for (const entry of readdirSync(dir)) {
24
- if (entry === ".git" || entry === "node_modules")
25
- continue;
26
- const fullPath = join(dir, entry), stat = statSync(fullPath);
27
- if (stat.isDirectory())
28
- walk(fullPath, depth + 1);
29
- else if (stat.isFile() && nameSet.has(basename(fullPath)))
30
- matches.push(fullPath);
31
- }
32
- }
33
- walk(root, 0);
34
- return matches;
35
- }
36
- async function isElfBinary(filePath) {
37
- const { readFileSync } = await import("node:fs"), header = readFileSync(filePath).slice(0, 4);
38
- return header[0] === 127 && header[1] === 69 && header[2] === 76 && header[3] === 70;
39
- }
40
- async function resolvePantryInstallCommand() {
41
- const { existsSync } = await import("node:fs"), localPantryCli = `${process.env.HOME}/Code/Tools/pantry/packages/ts-pantry/bin/cli.ts`;
42
- if (existsSync(localPantryCli))
43
- return { command: "bun", args: [localPantryCli] };
44
- const projectPantry = p.projectPath("pantry/.bin/pantry");
45
- if (existsSync(projectPantry))
46
- return { command: projectPantry, args: [] };
47
- const globalPantry = `${process.env.HOME}/.local/share/pantry/global/bin/pantry`;
48
- if (existsSync(globalPantry))
49
- return { command: globalPantry, args: [] };
50
- return { command: "pantry", args: [] };
51
- }
52
- async function installMailBinaryWithPantry() {
53
- const { execFileSync } = await import("node:child_process"), installDir = p.projectPath("pantry"), pantry = await resolvePantryInstallCommand();
54
- execFileSync(pantry.command, [
55
- ...pantry.args,
56
- "install",
57
- MAIL_PACKAGE_SPEC,
58
- "--install-dir",
59
- installDir,
60
- "--platform",
61
- MAIL_TARGET_PLATFORM,
62
- "--quiet"
63
- ], {
64
- cwd: p.projectPath(),
65
- stdio: isVerbose ? "inherit" : "pipe",
66
- env: process.env
67
- });
68
- }
69
- async function findPantryMailBinary() {
70
- const { existsSync } = await import("node:fs"), { join } = await import("node:path"), pantryRoots = [
71
- p.projectPath("pantry"),
72
- `${process.env.HOME}/.local/share/pantry`
73
- ], directCandidates = [
74
- ...MAIL_BINARY_NAMES.map((name) => p.projectPath(`pantry/.bin/${name}`)),
75
- ...MAIL_BINARY_NAMES.map((name) => join(`${process.env.HOME}/.local/share/pantry/global/bin`, name))
76
- ];
77
- for (const candidate of directCandidates)
78
- if (existsSync(candidate) && await isElfBinary(candidate))
79
- return candidate;
80
- for (const root of pantryRoots) {
81
- const candidates = await collectMatchingFiles(root, MAIL_BINARY_NAMES);
82
- for (const candidate of candidates)
83
- if (await isElfBinary(candidate))
84
- return candidate;
85
- }
86
- return null;
87
- }
88
- const MIME_TYPES = {
89
- ".html": "text/html",
90
- ".css": "text/css",
91
- ".js": "application/javascript",
92
- ".json": "application/json",
93
- ".png": "image/png",
94
- ".jpg": "image/jpeg",
95
- ".jpeg": "image/jpeg",
96
- ".gif": "image/gif",
97
- ".svg": "image/svg+xml",
98
- ".ico": "image/x-icon",
99
- ".woff": "font/woff",
100
- ".woff2": "font/woff2",
101
- ".ttf": "font/ttf",
102
- ".eot": "application/vnd.ms-fontobject",
103
- ".otf": "font/otf",
104
- ".webp": "image/webp",
105
- ".mp4": "video/mp4",
106
- ".webm": "video/webm",
107
- ".mp3": "audio/mpeg",
108
- ".wav": "audio/wav",
109
- ".pdf": "application/pdf",
110
- ".xml": "application/xml",
111
- ".txt": "text/plain"
112
- };
113
- function getMimeType(filePath) {
114
- const dotIndex = filePath.lastIndexOf("."), ext = dotIndex >= 0 ? filePath.slice(dotIndex).toLowerCase() : "";
115
- return MIME_TYPES[ext] || "application/octet-stream";
116
- }
117
- async function traverseDirectory(dir, callback, prefix = "", skipPatterns = [".DS_Store"]) {
118
- const { readdirSync, statSync } = await import("node:fs"), { join } = await import("node:path"), items = readdirSync(dir);
119
- for (const item of items) {
120
- if (skipPatterns.includes(item))
121
- continue;
122
- const filePath = join(dir, item), key = prefix ? `${prefix}/${item}` : item;
123
- if (statSync(filePath).isDirectory())
124
- await traverseDirectory(filePath, callback, key, skipPatterns);
125
- else
126
- await callback(filePath, key);
127
- }
128
- }
129
- async function withS3Retry(fn, label = "s3 operation") {
130
- const maxRetries = 3;
131
- for (let attempt = 0;attempt <= maxRetries; attempt++)
132
- try {
133
- return await fn();
134
- } catch (error) {
135
- if (attempt >= maxRetries)
136
- throw error;
137
- const delay = Math.min(500 * 2 ** attempt + Math.random() * 200, 5000);
138
- if (isVerbose)
139
- log.debug(` Retrying ${label} (attempt ${attempt + 2}/${maxRetries + 1}) in ${Math.round(delay)}ms...`);
140
- await new Promise((resolve) => setTimeout(resolve, delay));
141
- }
142
- throw Error(`${label} failed after ${maxRetries + 1} attempts`);
143
- }
144
- function normalizeArray(value) {
145
- if (!value)
146
- return [];
147
- return Array.isArray(value) ? value : [value];
148
- }
149
- function buildCloudFrontXmlElement(name, value, indent = "") {
150
- if (value === null || value === void 0)
151
- return "";
152
- if (typeof value === "boolean")
153
- return `${indent}<${name}>${value}</${name}>
154
- `;
155
- if (typeof value === "number" || typeof value === "string")
156
- return `${indent}<${name}>${value}</${name}>
157
- `;
158
- if (Array.isArray(value))
159
- return value.map((item) => buildCloudFrontXmlElement(name, item, indent)).join("");
160
- if (typeof value === "object") {
161
- if (name.startsWith("@_") || name === "?xml")
162
- return "";
163
- let children = "";
164
- for (const [key, val] of Object.entries(value))
165
- if (!key.startsWith("@_") && key !== "#text")
166
- children += buildCloudFrontXmlElement(key, val, `${indent} `);
167
- if (value["#text"] !== void 0)
168
- return `${indent}<${name}>${value["#text"]}</${name}>
169
- `;
170
- return `${indent}<${name}>
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";const log={debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v"))console.log("\uD83D\uDD0D",...args)},success:(...args)=>console.log("\u2713",...args),error:(...args)=>console.error("\u2717",...args)},MAIL_PACKAGE_DOMAIN="github.com/mail-os/mail",MAIL_PACKAGE_SPEC=`${MAIL_PACKAGE_DOMAIN}@0.1.0`,MAIL_TARGET_PLATFORM="linux-x86_64",MAIL_BINARY_NAMES=["mail","mail-x86_64-linux","mail-x86_64-linux-gnu"],isVerbose=process.argv.includes("--verbose")||process.argv.includes("-v");async function collectMatchingFiles(root,names,maxDepth=8){const{existsSync,readdirSync,statSync}=await import("node:fs"),{join,basename}=await import("node:path"),nameSet=new Set(names),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),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"),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"),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"),installDir=p.projectPath("pantry"),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"),{join}=await import("node:path"),pantryRoots=[p.projectPath("pantry"),`${process.env.HOME}/.local/share/pantry`],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("."),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"),{join}=await import("node:path"),items=readdirSync(dir);for(const item of items){if(skipPatterns.includes(item))continue;const filePath=join(dir,item),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 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===void 0)return"";if(typeof value==="boolean")return`${indent}<${name}>${value}</${name}>
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} `);if(value["#text"]!==void 0)return`${indent}<${name}>${value["#text"]}</${name}>
4
+ `;return`${indent}<${name}>
171
5
  ${children}${indent}</${name}>
172
- `;
173
- }
174
- return "";
175
- }
176
- function buildCloudFrontDistributionConfigXml(config) {
177
- return `<?xml version="1.0" encoding="UTF-8"?>
6
+ `}return""}function buildCloudFrontDistributionConfigXml(config){return`<?xml version="1.0" encoding="UTF-8"?>
178
7
  <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
179
- ${Object.entries(config).filter(([key]) => !key.startsWith("@_")).map(([key, val]) => buildCloudFrontXmlElement(key, val, " ")).join("")}</DistributionConfig>
180
- `;
181
- }
182
- function firewallOpenCommand(ports) {
183
- const uniquePorts = [...new Set(ports)].filter((port) => Number.isFinite(port) && port > 0).sort((a, b) => a - b);
184
- if (uniquePorts.length === 0)
185
- return "true";
186
- 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`;
187
- }
188
- async function ensureSecurityGroupPort(ec2, securityGroupId, port) {
189
- if (!securityGroupId)
190
- return;
191
- if (((await ec2.describeSecurityGroups({ GroupIds: [securityGroupId] }))?.SecurityGroups?.[0]?.IpPermissions || []).some((permission) => {
192
- return permission.IpProtocol === "tcp" && Number(permission.FromPort) <= port && Number(permission.ToPort) >= port && normalizeArray(permission.IpRanges).some((range) => range.CidrIp === "0.0.0.0/0");
193
- }))
194
- return;
195
- try {
196
- await ec2.authorizeSecurityGroupIngress({
197
- GroupId: securityGroupId,
198
- IpPermissions: [{
199
- IpProtocol: "tcp",
200
- FromPort: port,
201
- ToPort: port,
202
- IpRanges: [{ CidrIp: "0.0.0.0/0", Description: `Stacks API port ${port}` }]
203
- }]
204
- });
205
- } catch (error) {
206
- if (!String(error?.message || "").includes("InvalidPermission.Duplicate"))
207
- throw error;
208
- }
209
- }
210
- async function ensureCloudFrontApiOriginPort(awsClient, distributionId, port) {
211
- if (!distributionId)
212
- return;
213
- const getResult = await awsClient.request({
214
- service: "cloudfront",
215
- region: "us-east-1",
216
- method: "GET",
217
- path: `/2020-05-31/distribution/${distributionId}/config`,
218
- returnHeaders: !0
219
- }), etag = getResult.headers?.etag || getResult.headers?.ETag || "", currentConfig = getResult.body?.DistributionConfig || getResult.DistributionConfig || getResult.body;
220
- if (!etag || !currentConfig?.Origins?.Items)
221
- return;
222
- const apiOrigin = normalizeArray(currentConfig.Origins.Items.Origin).find((origin) => String(origin.Id || "").includes("-api"));
223
- if (!apiOrigin?.CustomOriginConfig)
224
- return;
225
- if (Number(apiOrigin.CustomOriginConfig.HTTPPort) === port)
226
- return;
227
- apiOrigin.CustomOriginConfig.HTTPPort = port;
228
- await awsClient.request({
229
- service: "cloudfront",
230
- region: "us-east-1",
231
- method: "PUT",
232
- path: `/2020-05-31/distribution/${distributionId}/config`,
233
- body: buildCloudFrontDistributionConfigXml(currentConfig),
234
- headers: {
235
- "Content-Type": "application/xml",
236
- "If-Match": etag
237
- }
238
- });
239
- }
240
- const frameworkBuildSpinner = spinner("Building framework...");
241
- frameworkBuildSpinner.start();
242
- await runCommand("bun run build", {
243
- cwd: p.frameworkPath("core"),
244
- quiet: !1
245
- });
246
- frameworkBuildSpinner.succeed("Framework built");
247
- const docsDir = p.projectPath("docs"), docsBuildDir = p.projectPath("dist/docs/.bunpress");
248
- if (storage.hasFiles(docsDir)) {
249
- const docsSpinner = spinner("Building documentation with BunPress...");
250
- docsSpinner.start();
251
- try {
252
- 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";
253
- await rm(docsBuildDir, { recursive: !0, force: !0 });
254
- await runCommand(command, {
255
- cwd: p.projectPath(),
256
- quiet: !isVerbose
257
- });
258
- docsSpinner.succeed(`Documentation built with BunPress${hasLocalBunpress ? " (local checkout)" : ""}`);
259
- } catch (docsError) {
260
- docsSpinner.stop();
261
- console.log(`\u26A0 Documentation build skipped: ${docsError.message}`);
262
- if (isVerbose)
263
- 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");
264
- }
265
- } else if (isVerbose)
266
- log.debug("No docs directory found, skipping documentation build");
267
- const blogDistExists = storage.hasFiles(p.projectPath("dist/blog")), blogFontAssetsExist = [
268
- "CampmateScript-Regular.woff2",
269
- "SequoiaSans-Regular.woff2",
270
- "Switchback-Regular.woff2"
271
- ].every((file) => existsSync(p.projectPath(`dist/blog/assets/fonts/nps/${file}`))), blogImageAssetsExist = [
272
- "topography.svg",
273
- "park-ridge.svg"
274
- ].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);
275
- if (!blogDistExists || !blogFontAssetsExist || !blogImageAssetsExist || !blogHtmlUsesCurrentFontFormat || !blogHtmlUsesCurrentParkTheme || !blogHtmlUsesCurrentParkImages || !blogHtmlOmitsRetiredDecorations || !blogHtmlIsFresh) {
276
- const blogBuildSpinner = spinner("Building blog...");
277
- blogBuildSpinner.start();
278
- try {
279
- const blogConfig = (await import(p.projectPath("config/blog"))).default, { buildBlogSite } = await import(p.frameworkPath("core/cms/src/build"));
280
- await buildBlogSite({ config: blogConfig, outDir: p.projectPath("dist/blog") });
281
- blogBuildSpinner.succeed("Blog built successfully");
282
- } catch (blogBuildError) {
283
- blogBuildSpinner.stop();
284
- console.log(`\u26A0 Blog build skipped: ${blogBuildError.message}`);
285
- if (isVerbose)
286
- log.debug(`Blog build error: ${blogBuildError.stack}`);
287
- }
288
- } else if (isVerbose)
289
- log.debug("Pre-built blog found at dist/blog, skipping build");
290
- if (isVerbose)
291
- log.debug("Skipping views build (vite-config not configured)");
292
- const earlyCloudConfig = await import(p.projectPath("config/cloud")), earlyDeploymentMode = earlyCloudConfig?.tsCloud?.mode || "server";
293
- if (earlyDeploymentMode === "serverless") {
294
- const serverSpinner = spinner("Building server...");
295
- serverSpinner.start();
296
- await runCommand("bun build.ts", {
297
- cwd: p.frameworkPath("server"),
298
- quiet: !isVerbose
299
- });
300
- serverSpinner.succeed("Server built");
301
- const packageSpinner = spinner("Packaging for deployment...");
302
- packageSpinner.start();
303
- await runCommand("bun zip.ts", {
304
- cwd: p.corePath("cloud"),
305
- quiet: !isVerbose
306
- });
307
- packageSpinner.succeed("Package ready");
308
- } else if (isVerbose)
309
- log.debug("Skipping server build and packaging (server mode)");
310
- if (!process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY) {
311
- const { existsSync, readFileSync } = await import("node:fs"), environment = process.env.APP_ENV || process.env.NODE_ENV || "production", envFiles = [
312
- p.projectPath(`.env.${environment}`),
313
- p.projectPath(".env")
314
- ];
315
- for (const envPath of envFiles)
316
- if (existsSync(envPath)) {
317
- const content = readFileSync(envPath, "utf-8");
318
- for (const line of content.split(`
319
- `)) {
320
- const trimmed = line.trim();
321
- if (trimmed.startsWith("#") || !trimmed.includes("="))
322
- continue;
323
- const eqIndex = trimmed.indexOf("="), key = trimmed.slice(0, eqIndex).trim();
324
- let value = trimmed.slice(eqIndex + 1).trim();
325
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))
326
- value = value.slice(1, -1);
327
- if (key === "AWS_ACCESS_KEY_ID" && value)
328
- process.env.AWS_ACCESS_KEY_ID = value;
329
- else if (key === "AWS_SECRET_ACCESS_KEY" && value)
330
- process.env.AWS_SECRET_ACCESS_KEY = value;
331
- else if (key === "AWS_REGION" && value && !process.env.AWS_REGION)
332
- process.env.AWS_REGION = value;
333
- else if (key === "AWS_ACCOUNT_ID" && value && !process.env.AWS_ACCOUNT_ID)
334
- process.env.AWS_ACCOUNT_ID = value;
335
- else if (key.startsWith("MAIL_PASSWORD_") && value && !process.env[key])
336
- process.env[key] = value;
337
- }
338
- if (isVerbose)
339
- log.debug(`Loaded AWS credentials from ${envPath}`);
340
- break;
341
- }
342
- }
343
- try {
344
- const { deployStack, deployFrontend: _deployFrontend } = await import("../../deploy"), environment = process.env.APP_ENV || process.env.NODE_ENV || "production", region = process.env.AWS_REGION || "us-east-1", cloudConfigModule = await import(p.projectPath("config/cloud")), deploymentMode = cloudConfigModule?.tsCloud?.mode || "server", projectName = cloudConfigModule?.tsCloud?.project?.name || cloudConfigModule?.tsCloud?.project?.slug || "stacks";
345
- if (deploymentMode === "serverless") {
346
- console.log("");
347
- console.log("Serverless deployment mode detected");
348
- console.log("Building and pushing container image...");
349
- console.log("");
350
- const accountId = process.env.AWS_ACCOUNT_ID || await getAwsAccountId(region);
351
- if (!accountId || accountId.length < 10)
352
- throw Error(`Invalid AWS Account ID: "${accountId || "(empty)"}"
353
- Set AWS_ACCOUNT_ID in your .env file or ensure valid AWS credentials are configured.`);
354
- const ecrRepository = `${accountId}.dkr.ecr.${region}.amazonaws.com/${projectName}-${environment}-api`, imageTag = `${ecrRepository}:latest`;
355
- if (isVerbose)
356
- log.debug(`ECR repository: ${ecrRepository}`);
357
- if (isVerbose)
358
- log.debug("ECR credentials will be validated before push...");
359
- const buildSpinner = spinner("Building Docker image...");
360
- buildSpinner.start();
361
- try {
362
- 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, {
363
- cwd: p.projectPath(),
364
- env: process.env,
365
- maxBuffer: 10485760,
366
- timeout: 900000
367
- });
368
- if (isVerbose && stdout)
369
- log.debug(stdout);
370
- if (isVerbose && stderr)
371
- log.debug(stderr);
372
- buildSpinner.succeed(`Docker image built: ${imageTag}`);
373
- } catch (error) {
374
- buildSpinner.fail("Docker build failed");
375
- if (isVerbose)
376
- log.debug(`Docker build error: ${error.message}`);
377
- throw error;
378
- }
379
- const repoSpinner = spinner("Checking ECR repository...");
380
- repoSpinner.start();
381
- try {
382
- const { ECRClient } = await import("@stacksjs/ts-cloud"), ecr = new ECRClient(region), repoName = `${projectName}-${environment}-api`;
383
- try {
384
- await ecr.describeRepositories({ repositoryNames: [repoName] });
385
- repoSpinner.succeed(`ECR repository exists: ${repoName}`);
386
- } catch (err) {
387
- if (err.code === "RepositoryNotFoundException" || err.message?.includes("RepositoryNotFoundException")) {
388
- repoSpinner.text = `Creating ECR repository: ${repoName}...`;
389
- await ecr.createRepository({
390
- repositoryName: repoName,
391
- imageScanningConfiguration: { scanOnPush: !0 },
392
- imageTagMutability: "MUTABLE"
393
- });
394
- repoSpinner.succeed(`ECR repository created: ${repoName}`);
395
- } else
396
- throw err;
397
- }
398
- } catch (error) {
399
- repoSpinner.fail("ECR repository check failed");
400
- if (isVerbose)
401
- log.debug(`ECR repository error: ${error.message}`);
402
- throw error;
403
- }
404
- const authSpinner = spinner("Authenticating to ECR...");
405
- authSpinner.start();
406
- try {
407
- const { ECRClient } = await import("@stacksjs/ts-cloud"), token = (await new ECRClient(region).getAuthorizationToken()).authorizationData?.[0];
408
- if (!token?.authorizationToken)
409
- throw Error("No authorization token received from ECR");
410
- const decoded = Buffer.from(token.authorizationToken, "base64").toString("utf-8"), colonIndex = decoded.indexOf(":");
411
- if (colonIndex === -1)
412
- throw Error("ECR authorization token has unexpected format (missing colon separator)");
413
- const password = decoded.slice(colonIndex + 1), loginResult = Bun.spawnSync([
414
- "docker",
415
- "login",
416
- "--username",
417
- "AWS",
418
- "--password-stdin",
419
- `${accountId}.dkr.ecr.${region}.amazonaws.com`
420
- ], {
421
- stdin: new TextEncoder().encode(password),
422
- stdout: "pipe",
423
- stderr: "pipe"
424
- });
425
- if (loginResult.exitCode !== 0) {
426
- const loginError = new TextDecoder().decode(loginResult.stderr);
427
- throw Error(`Docker login failed: ${loginError}`);
428
- }
429
- authSpinner.succeed("Authenticated to ECR");
430
- } catch (error) {
431
- authSpinner.fail("ECR authentication failed");
432
- if (isVerbose)
433
- log.debug(`ECR auth error: ${error.message}`);
434
- throw error;
435
- }
436
- console.log("");
437
- const pushSpinner = spinner("Pushing image to ECR...");
438
- pushSpinner.start();
439
- try {
440
- const { exec } = await import("node:child_process"), { promisify } = await import("node:util"), execAsync = promisify(exec), pushCmd = `docker push ${imageTag}`;
441
- await execAsync(pushCmd, { env: process.env });
442
- pushSpinner.succeed(`Image pushed: ${imageTag}`);
443
- } catch (error) {
444
- pushSpinner.fail("Docker push failed");
445
- if (isVerbose)
446
- log.debug(`Push error: ${error.message}`);
447
- throw error;
448
- }
449
- console.log("");
450
- console.log("Container image ready in ECR. CloudFormation will use this image.");
451
- console.log("");
452
- } else {
453
- console.log("");
454
- console.log("Server deployment mode detected");
455
- console.log("Deploying EC2 infrastructure via CloudFormation...");
456
- console.log("");
457
- }
458
- async function getAwsAccountId(region) {
459
- try {
460
- const { STSClient } = await import("@stacksjs/ts-cloud"), accountId = (await new STSClient(region).getCallerIdentity()).Account || process.env.AWS_ACCOUNT_ID || "";
461
- if (isVerbose)
462
- log.debug(`Retrieved AWS Account ID: ${accountId || "(empty)"}`);
463
- return accountId;
464
- } catch (error) {
465
- if (isVerbose)
466
- log.debug(`Failed to get AWS Account ID: ${error.message}`);
467
- return process.env.AWS_ACCOUNT_ID || "";
468
- }
469
- }
470
- try {
471
- const deployScript = await import(p.projectPath("cloud/deploy-script"));
472
- if (typeof deployScript.beforeDeploy === "function")
473
- await deployScript.beforeDeploy({ environment, region });
474
- } catch (hookError) {
475
- if (hookError.code === "ERR_MODULE_NOT_FOUND" || hookError.code === "MODULE_NOT_FOUND") {
476
- if (isVerbose)
477
- log.debug("No beforeDeploy hook found (cloud/deploy-script not found)");
478
- } else {
479
- console.warn(`\u26A0 beforeDeploy hook failed: ${hookError.message}`);
480
- if (isVerbose)
481
- log.debug(`beforeDeploy error stack: ${hookError.stack}`);
482
- }
483
- }
484
- await deployStack({
485
- environment,
486
- region,
487
- waitForCompletion: !0,
488
- verbose: isVerbose
489
- });
490
- try {
491
- const deployScript = await import(p.projectPath("cloud/deploy-script"));
492
- if (typeof deployScript.afterDeploy === "function") {
493
- const { CloudFormationClient } = await import("@stacksjs/ts-cloud"), cf = new CloudFormationClient(region), stackName = `${projectName}-cloud`;
494
- let stackOutputs = {};
495
- try {
496
- stackOutputs = await cf.getStackOutputs(stackName);
497
- } catch (e) {
498
- if (isVerbose)
499
- log.debug(`Failed to get stack outputs: ${e instanceof Error ? e.message : String(e)}`);
500
- }
501
- await deployScript.afterDeploy({ environment, region, outputs: stackOutputs });
502
- }
503
- } catch (hookError) {
504
- if (hookError.code === "ERR_MODULE_NOT_FOUND" || hookError.code === "MODULE_NOT_FOUND") {
505
- if (isVerbose)
506
- log.debug("No afterDeploy hook found (cloud/deploy-script not found)");
507
- } else {
508
- console.warn(`\u26A0 afterDeploy hook failed: ${hookError.message}`);
509
- if (isVerbose)
510
- log.debug(`afterDeploy error stack: ${hookError.stack}`);
511
- }
512
- }
513
- const migrateSpinner = spinner("Running database migrations...");
514
- migrateSpinner.start();
515
- try {
516
- const { generateMigrations, runDatabaseMigration } = await import("@stacksjs/database");
517
- await generateMigrations();
518
- await runDatabaseMigration();
519
- migrateSpinner.succeed("Database migrations completed");
520
- } catch (migrationError) {
521
- migrateSpinner.stop();
522
- console.log(`\u26A0 Database migrations skipped: ${migrationError.message}`);
523
- if (isVerbose)
524
- log.debug(`Migration error: ${migrationError.stack}`);
525
- }
526
- const frameworkTablesSpinner = spinner("Ensuring framework tables (auth, notifications, RBAC, traits)...");
527
- frameworkTablesSpinner.start();
528
- try {
529
- const { ensureUtcDatetimeColumns, migrateAuthTables, migrateNotificationTables, migrateRbacTables, migrateTraitTables } = await import("@stacksjs/database"), failures = [], steps = [
530
- ["auth", migrateAuthTables],
531
- ["notification", migrateNotificationTables],
532
- ["RBAC", migrateRbacTables],
533
- ["trait", migrateTraitTables],
534
- ["utc-datetime", ensureUtcDatetimeColumns]
535
- ];
536
- for (const [name, migrateTables] of steps) {
537
- const result = await migrateTables({ verbose: isVerbose });
538
- if (!result.success)
539
- failures.push(`${name}: ${result.error}`);
540
- }
541
- if (failures.length > 0) {
542
- frameworkTablesSpinner.stop();
543
- console.log(`\u26A0 Some framework tables could not be migrated: ${failures.join("; ")}`);
544
- } else
545
- frameworkTablesSpinner.succeed("Framework tables ensured (auth, notifications, RBAC, traits)");
546
- } catch (frameworkTablesError) {
547
- frameworkTablesSpinner.stop();
548
- console.log(`\u26A0 Framework table migrations skipped: ${frameworkTablesError.message}`);
549
- if (isVerbose)
550
- log.debug(`Framework table migration error: ${frameworkTablesError.stack}`);
551
- }
552
- if (deploymentMode === "server") {
553
- const serverOutputSpinner = spinner("Retrieving server instance details...");
554
- serverOutputSpinner.start();
555
- try {
556
- const { CloudFormationClient } = await import("@stacksjs/ts-cloud"), cf = new CloudFormationClient(region), stackName = `${projectName}-cloud`, outputs = await cf.getStackOutputs(stackName);
557
- serverOutputSpinner.succeed("Server instances deployed");
558
- console.log("");
559
- console.log("Server instances:");
560
- for (const [key, value] of Object.entries(outputs)) {
561
- if (key.endsWith("PublicIp"))
562
- console.log(` ${key}: ${value}`);
563
- if (key.endsWith("InstanceId"))
564
- console.log(` ${key}: ${value}`);
565
- }
566
- console.log("");
567
- } catch (outputError) {
568
- serverOutputSpinner.stop();
569
- console.log(`\u26A0 Could not retrieve server details: ${outputError.message}`);
570
- if (isVerbose)
571
- log.debug(`Output retrieval error: ${outputError.stack}`);
572
- }
573
- const serverDeploySpinner = spinner("Deploying API server to EC2...");
574
- serverDeploySpinner.start();
575
- try {
576
- 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 = `${projectName}-cloud`, outputs = await cf.getStackOutputs(stackName), bucketName = outputs.FrontendBucketName, apiServerPort = Number(config.ports?.api || 3008);
577
- let instanceId;
578
- for (const [key, value] of Object.entries(outputs))
579
- if (key.endsWith("InstanceId") && typeof value === "string") {
580
- instanceId = value;
581
- break;
582
- }
583
- let securityGroupId;
584
- if (instanceId) {
585
- const { EC2Client } = await import("@stacksjs/ts-cloud"), ec2 = new EC2Client(region);
586
- securityGroupId = (await ec2.describeInstances({
587
- Filters: [{ Name: "instance-id", Values: [instanceId] }]
588
- }))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups?.[0]?.GroupId;
589
- await ensureSecurityGroupPort(ec2, securityGroupId, apiServerPort);
590
- }
591
- if (!instanceId || !bucketName) {
592
- serverDeploySpinner.stop();
593
- if (!instanceId)
594
- console.log("\u26A0 No EC2 instance found in stack outputs, skipping server deploy");
595
- if (!bucketName)
596
- console.log("\u26A0 No S3 bucket found for staging server artifacts");
597
- } else {
598
- const publicDistributionId = outputs.publicCloudFrontDistributionId || outputs.CloudFrontDistributionId;
599
- await ensureCloudFrontApiOriginPort(awsClient, publicDistributionId, apiServerPort);
600
- const tsCloudDistPath = resolve(p.projectPath("node_modules/@stacksjs/ts-cloud/dist/index.js"));
601
- if (serverFileExists(tsCloudDistPath)) {
602
- const tsCloudDist = readServerFile(tsCloudDistPath);
603
- await withS3Retry(() => s3.putObject({
604
- bucket: bucketName,
605
- key: "_deploy/ts-cloud-dist.js",
606
- body: tsCloudDist,
607
- contentType: "application/javascript"
608
- }), "upload ts-cloud dist");
609
- if (isVerbose)
610
- log.debug(" Uploaded ts-cloud dist to S3");
611
- }
612
- const serverCode = `import { Database } from "bun:sqlite";
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 ${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 frameworkBuildSpinner=spinner("Building framework...");frameworkBuildSpinner.start();await runCommand("bun run build",{cwd:p.frameworkPath("core"),quiet:!1});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();await runCommand("bun build.ts",{cwd:p.frameworkPath("server"),quiet:!isVerbose});serverSpinner.succeed("Server built");const packageSpinner=spinner("Packaging for deployment...");packageSpinner.start();await runCommand("bun zip.ts",{cwd:p.corePath("cloud"),quiet:!isVerbose});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("../../deploy"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production",region=process.env.AWS_REGION||"us-east-1",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
+ 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||""}}try{const deployScript=await import(p.projectPath("cloud/deploy-script"));if(typeof deployScript.beforeDeploy==="function")await deployScript.beforeDeploy({environment,region})}catch(hookError){if(hookError.code==="ERR_MODULE_NOT_FOUND"||hookError.code==="MODULE_NOT_FOUND"){if(isVerbose)log.debug("No beforeDeploy hook found (cloud/deploy-script not found)")}else{console.warn(`\u26A0 beforeDeploy hook failed: ${hookError.message}`);if(isVerbose)log.debug(`beforeDeploy error stack: ${hookError.stack}`)}}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=`${projectName}-cloud`;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}`)}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=`${projectName}-cloud`,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=`${projectName}-cloud`,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";
613
12
  import { SESClient } from "./ts-cloud-dist.js";
614
13
 
615
14
  const db = new Database("/var/www/api/stacks.db");
@@ -730,21 +129,7 @@ const server = Bun.serve({
730
129
  });
731
130
 
732
131
  console.log(\`Stacks API server running on port \${server.port}\`);
733
- `;
734
- await withS3Retry(() => s3.putObject({
735
- bucket: bucketName,
736
- key: "_deploy/server.ts",
737
- body: Buffer.from(serverCode),
738
- contentType: "application/typescript"
739
- }), "upload server.ts");
740
- if (isVerbose)
741
- log.debug(" Uploaded server.ts to S3");
742
- const ssmCommand = [
743
- "mkdir -p /var/www/api",
744
- `aws s3 cp s3://${bucketName}/_deploy/ts-cloud-dist.js /var/www/api/ts-cloud-dist.js`,
745
- `aws s3 cp s3://${bucketName}/_deploy/server.ts /var/www/api/server.ts`,
746
- firewallOpenCommand([apiServerPort]),
747
- `cat > /etc/systemd/system/stacks-api.service << 'SERVICEFILE'
132
+ `;await withS3Retry(()=>s3.putObject({bucket:bucketName,key:"_deploy/server.ts",body:Buffer.from(serverCode),contentType:"application/typescript"}),"upload server.ts");if(isVerbose)log.debug(" Uploaded server.ts to S3");const ssmCommand=["mkdir -p /var/www/api",`aws s3 cp s3://${bucketName}/_deploy/ts-cloud-dist.js /var/www/api/ts-cloud-dist.js`,`aws s3 cp s3://${bucketName}/_deploy/server.ts /var/www/api/server.ts`,firewallOpenCommand([apiServerPort]),`cat > /etc/systemd/system/stacks-api.service << 'SERVICEFILE'
748
133
  [Unit]
749
134
  Description=Stacks Bun API Server
750
135
  After=network.target
@@ -761,163 +146,7 @@ Environment=NODE_ENV=production
761
146
  WantedBy=multi-user.target
762
147
  SERVICEFILE
763
148
  systemctl daemon-reload
764
- systemctl enable stacks-api`,
765
- "systemctl reset-failed stacks-api || true",
766
- "systemctl restart stacks-api",
767
- `for i in $(seq 1 20); do curl -fsS http://127.0.0.1:${apiServerPort}/api/health && break; sleep 1; done`,
768
- `curl -fsS http://127.0.0.1:${apiServerPort}/api/health`,
769
- `echo "API server deployed and restarted on port ${apiServerPort}"`
770
- ].join(" && "), commandId = (await awsClient.request({
771
- service: "ssm",
772
- region,
773
- method: "POST",
774
- path: "/",
775
- headers: {
776
- "Content-Type": "application/x-amz-json-1.1",
777
- "X-Amz-Target": "AmazonSSM.SendCommand"
778
- },
779
- body: JSON.stringify({
780
- InstanceIds: [instanceId],
781
- DocumentName: "AWS-RunShellScript",
782
- Parameters: {
783
- commands: [ssmCommand]
784
- },
785
- TimeoutSeconds: 120
786
- })
787
- }))?.Command?.CommandId;
788
- if (commandId) {
789
- let attempts = 0;
790
- while (attempts < 30) {
791
- await new Promise((resolve) => setTimeout(resolve, 3000));
792
- try {
793
- const invocation = await awsClient.request({
794
- service: "ssm",
795
- region,
796
- method: "POST",
797
- path: "/",
798
- headers: {
799
- "Content-Type": "application/x-amz-json-1.1",
800
- "X-Amz-Target": "AmazonSSM.GetCommandInvocation"
801
- },
802
- body: JSON.stringify({
803
- CommandId: commandId,
804
- InstanceId: instanceId
805
- })
806
- }), status = invocation?.Status;
807
- if (status === "Success") {
808
- serverDeploySpinner.succeed("API server deployed to EC2");
809
- break;
810
- } else if (status === "Failed" || status === "Cancelled" || status === "TimedOut") {
811
- const errOutput = invocation?.StandardErrorContent || "Unknown error";
812
- serverDeploySpinner.fail(`API server deploy failed: ${errOutput}`);
813
- break;
814
- }
815
- } catch {}
816
- attempts++;
817
- }
818
- if (attempts >= 30)
819
- serverDeploySpinner.fail("API server deploy timed out waiting for SSM command");
820
- } else
821
- serverDeploySpinner.fail("Failed to send SSM command");
822
- try {
823
- await s3.deleteObject({ bucket: bucketName, key: "_deploy/ts-cloud-dist.js" });
824
- await s3.deleteObject({ bucket: bucketName, key: "_deploy/server.ts" });
825
- } catch {}
826
- }
827
- } catch (serverDeployError) {
828
- serverDeploySpinner.fail(`API server deployment failed: ${serverDeployError.message}`);
829
- if (isVerbose)
830
- log.debug(`Server deploy error: ${serverDeployError.stack}`);
831
- }
832
- const emailConfig = config.email;
833
- if (emailConfig?.server?.enabled) {
834
- const mailServerMode = emailConfig?.server?.mode || "server", smtpSpinner = spinner(`Deploying mail server (${mailServerMode} mode) to EC2...`);
835
- smtpSpinner.start();
836
- try {
837
- const { S3Client, AWSClient, EC2Client } = await import("@stacksjs/ts-cloud"), { readFileSync: readSmtpFile, existsSync: smtpFileExists } = await import("node:fs"), { resolve: resolvePath, join: joinPath } = await import("node:path"), { execSync } = await import("node:child_process"), s3 = new S3Client(region), awsClient = new AWSClient, ec2 = new EC2Client(region), stackName = `${projectName}-cloud`;
838
- let smtpInstanceId, smtpBucketName, emailBucketName, securityGroupId;
839
- try {
840
- const { AWSCloudFormationClient: CfnClient } = await import("@stacksjs/ts-cloud"), cfnOutputs = await new CfnClient(region).getStackOutputs(stackName);
841
- for (const [key, value] of Object.entries(cfnOutputs)) {
842
- if (key.endsWith("InstanceId") && typeof value === "string")
843
- smtpInstanceId = value;
844
- if (key === "FrontendBucketName" && typeof value === "string")
845
- smtpBucketName = value;
846
- if (key === "emailBucketName" && typeof value === "string")
847
- emailBucketName = value;
848
- }
849
- } catch {}
850
- if (!emailBucketName)
851
- emailBucketName = `${projectName}-production-s3-email`;
852
- if (smtpInstanceId && smtpBucketName) {
853
- const mailPorts = [25, 80, 110, 143, 465, 587, 993, 995];
854
- try {
855
- const sgs = (await ec2.describeInstances({
856
- Filters: [{ Name: "instance-id", Values: [smtpInstanceId] }]
857
- }))?.Reservations?.[0]?.Instances?.[0]?.SecurityGroups;
858
- if (sgs?.[0]?.GroupId)
859
- securityGroupId = sgs[0].GroupId;
860
- } catch {
861
- if (isVerbose)
862
- log.debug("Could not get security group for instance");
863
- }
864
- if (securityGroupId)
865
- for (const port of mailPorts)
866
- try {
867
- await ec2.authorizeSecurityGroupIngress({
868
- GroupId: securityGroupId,
869
- IpPermissions: [{
870
- IpProtocol: "tcp",
871
- FromPort: port,
872
- ToPort: port,
873
- IpRanges: [{ CidrIp: "0.0.0.0/0", Description: `Mail port ${port}` }]
874
- }]
875
- });
876
- if (isVerbose)
877
- log.debug(` Opened port ${port} on security group ${securityGroupId}`);
878
- } catch (e) {
879
- if (!e.message?.includes("already exists")) {
880
- if (isVerbose)
881
- log.debug(` Port ${port}: ${e.message}`);
882
- }
883
- }
884
- const domain = emailConfig.domain || "stacksjs.com", mailSubdomain = emailConfig?.server?.subdomain || "mail";
885
- if (mailServerMode === "server") {
886
- if (isVerbose)
887
- log.debug("Deploying Zig mail server binary...");
888
- try {
889
- await installMailBinaryWithPantry();
890
- } catch (error) {
891
- if (isVerbose)
892
- log.debug(` Pantry mail install failed: ${error.message}`);
893
- }
894
- const linuxBinaryPath = await findPantryMailBinary();
895
- if (linuxBinaryPath && smtpFileExists(linuxBinaryPath)) {
896
- if (!await isElfBinary(linuxBinaryPath)) {
897
- smtpSpinner.fail(`Pantry installed ${MAIL_PACKAGE_DOMAIN}, but the ${MAIL_TARGET_PLATFORM} binary is not an ELF file.`);
898
- throw Error("Linux binary is not a valid ELF file");
899
- }
900
- const binaryContent = readSmtpFile(linuxBinaryPath);
901
- await s3.putObject({
902
- bucket: emailBucketName,
903
- key: "mail-server/smtp-server",
904
- body: binaryContent,
905
- contentType: "application/octet-stream"
906
- });
907
- if (isVerbose)
908
- log.debug(` Uploaded Zig binary (${(binaryContent.length / 1024 / 1024).toFixed(1)}MB) to S3`);
909
- const zigSsmCommand = [
910
- "systemctl stop stacks-mail 2>/dev/null || true",
911
- "systemctl disable stacks-mail 2>/dev/null || true",
912
- "systemctl stop stacks-smtp 2>/dev/null || true",
913
- "systemctl disable stacks-smtp 2>/dev/null || true",
914
- "systemctl stop smtp-server 2>/dev/null || true",
915
- "mkdir -p /opt/smtp-server /var/lib/smtp-server /var/log/smtp-server /var/spool/mail /etc/smtp-server /var/lib/smtp-server/backups",
916
- `aws s3 cp s3://${emailBucketName}/mail-server/smtp-server /opt/smtp-server/smtp-server --region ${region}`,
917
- "chmod +x /opt/smtp-server/smtp-server",
918
- 'file /opt/smtp-server/smtp-server | grep -q ELF || { echo "Binary is not ELF"; exit 1; }',
919
- firewallOpenCommand(mailPorts),
920
- `cat > /etc/smtp-server/smtp-server.env << 'ENVEOF'
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(" && "),commandId=(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})}))?.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})}),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({bucket:bucketName,key:"_deploy/ts-cloud-dist.js"});await s3.deleteObject({bucket:bucketName,key:"_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",smtpSpinner=spinner(`Deploying mail server (${mailServerMode} mode) to EC2...`);smtpSpinner.start();try{const{S3Client,AWSClient,EC2Client}=await import("@stacksjs/ts-cloud"),{readFileSync:readSmtpFile,existsSync:smtpFileExists}=await import("node:fs"),{resolve:resolvePath,join:joinPath}=await import("node:path"),{execSync}=await import("node:child_process"),s3=new S3Client(region),awsClient=new AWSClient,ec2=new EC2Client(region),stackName=`${projectName}-cloud`;let smtpInstanceId,smtpBucketName,emailBucketName,securityGroupId;try{const{AWSCloudFormationClient:CfnClient}=await import("@stacksjs/ts-cloud"),cfnOutputs=await new CfnClient(region).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 sgs=(await ec2.describeInstances({Filters:[{Name:"instance-id",Values:[smtpInstanceId]}]}))?.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",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 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'
921
150
  SMTP_PROFILE=production
922
151
  SMTP_HOST=0.0.0.0
923
152
  SMTP_PORT=25
@@ -937,9 +166,7 @@ SMTP_MAX_RECIPIENTS=100
937
166
  SMTP_RATE_LIMIT_PER_IP=100
938
167
  SMTP_RATE_LIMIT_PER_USER=200
939
168
  SMTP_IO_MODE=epoll
940
- ENVEOF`,
941
- "chmod 600 /etc/smtp-server/smtp-server.env",
942
- `cat > /etc/systemd/system/smtp-server.service << 'SVCEOF'
169
+ ENVEOF`,"chmod 600 /etc/smtp-server/smtp-server.env",`cat > /etc/systemd/system/smtp-server.service << 'SVCEOF'
943
170
  [Unit]
944
171
  Description=Stacks Mail Server (Zig)
945
172
  After=network.target
@@ -957,74 +184,8 @@ SyslogIdentifier=smtp-server
957
184
 
958
185
  [Install]
959
186
  WantedBy=multi-user.target
960
- SVCEOF`,
961
- "systemctl daemon-reload",
962
- "systemctl enable smtp-server",
963
- "systemctl restart smtp-server",
964
- "sleep 3",
965
- 'systemctl is-active smtp-server && echo "Mail server is running" || echo "Mail server failed to start"',
966
- 'ss -tlnp | grep -E "(25|143)" || echo "Warning: mail ports not listening yet"'
967
- ].join(" && "), cmdId = (await awsClient.request({
968
- service: "ssm",
969
- region,
970
- method: "POST",
971
- path: "/",
972
- headers: {
973
- "Content-Type": "application/x-amz-json-1.1",
974
- "X-Amz-Target": "AmazonSSM.SendCommand"
975
- },
976
- body: JSON.stringify({
977
- InstanceIds: [smtpInstanceId],
978
- DocumentName: "AWS-RunShellScript",
979
- Parameters: { commands: [zigSsmCommand] },
980
- TimeoutSeconds: 300
981
- })
982
- }))?.Command?.CommandId;
983
- if (cmdId) {
984
- let ssmAttempts = 0;
985
- while (ssmAttempts < 100) {
986
- await new Promise((resolve) => setTimeout(resolve, 3000));
987
- try {
988
- const invocation = await awsClient.request({
989
- service: "ssm",
990
- region,
991
- method: "POST",
992
- path: "/",
993
- headers: {
994
- "Content-Type": "application/x-amz-json-1.1",
995
- "X-Amz-Target": "AmazonSSM.GetCommandInvocation"
996
- },
997
- body: JSON.stringify({ CommandId: cmdId, InstanceId: smtpInstanceId })
998
- }), status = invocation?.Status;
999
- if (status === "Success") {
1000
- smtpSpinner.succeed("Zig mail server deployed to EC2");
1001
- if (isVerbose && invocation?.StandardOutputContent)
1002
- console.log(invocation.StandardOutputContent);
1003
- break;
1004
- } else if (status === "Failed" || status === "Cancelled" || status === "TimedOut") {
1005
- const errOutput = invocation?.StandardErrorContent || invocation?.StandardOutputContent || "Unknown error";
1006
- smtpSpinner.fail(`Zig mail server deploy failed: ${errOutput.slice(0, 500)}`);
1007
- break;
1008
- }
1009
- } catch {}
1010
- ssmAttempts++;
1011
- }
1012
- if (ssmAttempts >= 100)
1013
- smtpSpinner.fail("Zig mail server deploy timed out");
1014
- } else
1015
- smtpSpinner.fail("Failed to send SSM command for mail server");
1016
- } else
1017
- smtpSpinner.fail(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`);
1018
- } else {
1019
- const smtpServerSrc = resolvePath(p.projectPath("storage/framework/core/cloud/src/imap/smtp-server.ts")), bundleOutDir = p.frameworkRuntimePath("tmp/smtp-bundle");
1020
- execSync(`bun build ${smtpServerSrc} --target=bun --outdir=${bundleOutDir}`, { stdio: "pipe" });
1021
- const bundlePath = joinPath(bundleOutDir, "smtp-server.js");
1022
- if (smtpFileExists(bundlePath)) {
1023
- const smtpBundle = readSmtpFile(bundlePath), mailboxes = emailConfig.mailboxes || ["chris", "blake", "glenn"], usersEntries = mailboxes.map((name) => {
1024
- const envKey = `MAIL_PASSWORD_${name.toUpperCase()}`;
1025
- return ` "${name}": { password: process.env["${envKey}"] || "", email: "${name}@${domain}" }`;
1026
- }).join(`,
1027
- `), entryPoint = `import { SmtpServer } from "./smtp-server.js";
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(" && "),cmdId=(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})}))?.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})}),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")),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),mailboxes=emailConfig.mailboxes||["chris","blake","glenn"],usersEntries=mailboxes.map((name)=>{const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;return` "${name}": { password: process.env["${envKey}"] || "", email: "${name}@${domain}" }`}).join(`,
188
+ `),entryPoint=`import { SmtpServer } from "./smtp-server.js";
1028
189
  import * as fs from "fs";
1029
190
  const domain = "${domain}";
1030
191
  const users = { ${usersEntries} };
@@ -1035,21 +196,8 @@ if (fs.existsSync(\`\${certDir}/privkey.pem\`)) {
1035
196
  }
1036
197
  const server = new SmtpServer({ port: 587, tlsPort: 465, host: "0.0.0.0", domain, users, tls: tlsConfig, sentBucket: "${projectName}-production-email", sentPrefix: "sent/" });
1037
198
  await server.start();
1038
- `;
1039
- await s3.putObject({ bucket: smtpBucketName, key: "_deploy/smtp-server.js", body: smtpBundle, contentType: "application/javascript" });
1040
- await s3.putObject({ bucket: smtpBucketName, key: "_deploy/smtp-entry.ts", body: Buffer.from(entryPoint), contentType: "application/typescript" });
1041
- const envLines = mailboxes.map((name) => {
1042
- const envKey = `MAIL_PASSWORD_${name.toUpperCase()}`;
1043
- return `Environment=${envKey}=${process.env[envKey] || ""}`;
1044
- }).join(`
1045
- `), smtpSsmCommand = [
1046
- "mkdir -p /var/www/smtp",
1047
- `aws s3 cp s3://${smtpBucketName}/_deploy/smtp-server.js /var/www/smtp/smtp-server.js`,
1048
- `aws s3 cp s3://${smtpBucketName}/_deploy/smtp-entry.ts /var/www/smtp/smtp-entry.ts`,
1049
- firewallOpenCommand(mailPorts),
1050
- "if ! command -v certbot &> /dev/null; then dnf install -y certbot || yum install -y certbot || apt-get install -y certbot || true; fi",
1051
- `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`,
1052
- `cat > /etc/systemd/system/stacks-smtp.service << 'SERVICEFILE'
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
+ `),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'
1053
201
  [Unit]
1054
202
  Description=Stacks SMTP Proxy Server
1055
203
  After=network.target
@@ -1064,111 +212,7 @@ Environment=AWS_REGION=${region}
1064
212
  ${envLines}
1065
213
  [Install]
1066
214
  WantedBy=multi-user.target
1067
- SERVICEFILE`,
1068
- "systemctl daemon-reload",
1069
- "systemctl enable stacks-smtp",
1070
- "systemctl restart stacks-smtp"
1071
- ].join(" && "), cmdId = (await awsClient.request({
1072
- service: "ssm",
1073
- region,
1074
- method: "POST",
1075
- path: "/",
1076
- headers: { "Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": "AmazonSSM.SendCommand" },
1077
- body: JSON.stringify({ InstanceIds: [smtpInstanceId], DocumentName: "AWS-RunShellScript", Parameters: { commands: [smtpSsmCommand] }, TimeoutSeconds: 180 })
1078
- }))?.Command?.CommandId;
1079
- if (cmdId) {
1080
- let ssmAttempts = 0;
1081
- while (ssmAttempts < 60) {
1082
- await new Promise((resolve) => setTimeout(resolve, 3000));
1083
- try {
1084
- const invocation = await awsClient.request({
1085
- service: "ssm",
1086
- region,
1087
- method: "POST",
1088
- path: "/",
1089
- headers: { "Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": "AmazonSSM.GetCommandInvocation" },
1090
- body: JSON.stringify({ CommandId: cmdId, InstanceId: smtpInstanceId })
1091
- }), status = invocation?.Status;
1092
- if (status === "Success") {
1093
- smtpSpinner.succeed("SMTP proxy deployed to EC2");
1094
- break;
1095
- } else if (status === "Failed" || status === "Cancelled" || status === "TimedOut") {
1096
- smtpSpinner.fail(`SMTP proxy deploy failed: ${invocation?.StandardErrorContent || "Unknown"}`);
1097
- break;
1098
- }
1099
- } catch {}
1100
- ssmAttempts++;
1101
- }
1102
- if (ssmAttempts >= 60)
1103
- smtpSpinner.fail("SMTP proxy deploy timed out");
1104
- } else
1105
- smtpSpinner.fail("Failed to send SSM command for SMTP proxy");
1106
- try {
1107
- await s3.deleteObject({ bucket: smtpBucketName, key: "_deploy/smtp-server.js" });
1108
- await s3.deleteObject({ bucket: smtpBucketName, key: "_deploy/smtp-entry.ts" });
1109
- } catch {}
1110
- } else {
1111
- smtpSpinner.stop();
1112
- if (isVerbose)
1113
- log.debug("SMTP server bundle not found, skipping");
1114
- }
1115
- }
1116
- } else {
1117
- smtpSpinner.stop();
1118
- if (isVerbose)
1119
- log.debug("No EC2 instance or bucket found, skipping mail server deploy");
1120
- }
1121
- } catch (smtpDeployError) {
1122
- smtpSpinner.fail(`Mail server deployment failed: ${smtpDeployError.message}`);
1123
- if (isVerbose)
1124
- log.debug(`Mail server deploy error: ${smtpDeployError.stack}`);
1125
- }
1126
- }
1127
- }
1128
- const frontendSpinner = spinner("Deploying frontend to S3...");
1129
- frontendSpinner.start();
1130
- try {
1131
- const { S3Client, CloudFormationClient } = await import("@stacksjs/ts-cloud"), { readFileSync } = await import("node:fs"), { buildFrontendStatic } = await import("../build/frontend-static"), s3 = new S3Client(region), cf = new CloudFormationClient(region), stackName = `${projectName}-cloud`, stackOutputs = await cf.getStackOutputs(stackName), bucketName = stackOutputs.FrontendBucketName;
1132
- if (!bucketName) {
1133
- frontendSpinner.stop();
1134
- console.log("\u26A0 Frontend bucket not found in stack outputs (add storage.public to infrastructure config)");
1135
- } else {
1136
- const buildDir = await buildFrontendStatic();
1137
- await (async (dir, _prefix = "") => {
1138
- await traverseDirectory(dir, async (filePath, key) => {
1139
- const content = readFileSync(filePath), contentType = getMimeType(filePath), cacheControl = key === "index.html" || key.endsWith("/index.html") ? "no-cache, no-store, must-revalidate" : "public, max-age=31536000, immutable";
1140
- await withS3Retry(() => s3.putObject({ bucket: bucketName, key, body: content, contentType, cacheControl }), `upload ${key}`);
1141
- if (isVerbose)
1142
- log.debug(` Uploaded: ${key}`);
1143
- });
1144
- })(buildDir);
1145
- const bootstrapPath = p.projectPath("bootstrap");
1146
- if (existsSync(bootstrapPath)) {
1147
- const bootstrapContent = readFileSync(bootstrapPath);
1148
- await withS3Retry(() => s3.putObject({
1149
- bucket: bucketName,
1150
- key: "install",
1151
- body: bootstrapContent,
1152
- contentType: "text/plain",
1153
- cacheControl: "no-cache, no-store, must-revalidate"
1154
- }), "upload bootstrap install script");
1155
- if (isVerbose)
1156
- log.debug(" Uploaded bootstrap install script");
1157
- }
1158
- const distributionId = stackOutputs.publicCloudFrontDistributionId || stackOutputs.CloudFrontDistributionId;
1159
- if (distributionId) {
1160
- if (isVerbose)
1161
- log.debug(" Invalidating CloudFront cache...");
1162
- const { AWSClient } = await import("@stacksjs/ts-cloud");
1163
- await new AWSClient().request({
1164
- service: "cloudfront",
1165
- region: "us-east-1",
1166
- method: "POST",
1167
- path: `/2020-05-31/distribution/${distributionId}/invalidation`,
1168
- headers: {
1169
- "Content-Type": "application/xml"
1170
- },
1171
- body: `<?xml version="1.0" encoding="UTF-8"?>
215
+ SERVICEFILE`,"systemctl daemon-reload","systemctl enable stacks-smtp","systemctl restart stacks-smtp"].join(" && "),cmdId=(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})}))?.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})}),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({bucket:smtpBucketName,key:"_deploy/smtp-server.js"});await s3.deleteObject({bucket:smtpBucketName,key:"_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"),{readFileSync}=await import("node:fs"),{buildFrontendStatic}=await import("../build/frontend-static"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName=`${projectName}-cloud`,stackOutputs=await cf.getStackOutputs(stackName),bucketName=stackOutputs.FrontendBucketName;if(!bucketName){frontendSpinner.stop();console.log("\u26A0 Frontend bucket not found in stack outputs (add storage.public to infrastructure config)")}else{const buildDir=await buildFrontendStatic();await(async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath),contentType=getMimeType(filePath),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}`)})})(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");await new AWSClient().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"?>
1172
216
  <InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
1173
217
  <CallerReference>${Date.now()}</CallerReference>
1174
218
  <Paths>
@@ -1177,131 +221,27 @@ SERVICEFILE`,
1177
221
  <Path>/*</Path>
1178
222
  </Items>
1179
223
  </Paths>
1180
- </InvalidationBatch>`
1181
- });
1182
- }
1183
- frontendSpinner.succeed(`Frontend deployed to S3 (${bucketName})`);
1184
- }
1185
- } catch (frontendError) {
1186
- frontendSpinner.fail(`Frontend deployment failed: ${frontendError.message}`);
1187
- if (isVerbose)
1188
- log.debug(`Frontend error: ${frontendError.stack}`);
1189
- }
1190
- const docsDistPath = p.projectPath("dist/docs/.bunpress"), { existsSync: docsExists } = await import("node:fs");
1191
- if (docsExists(docsDistPath)) {
1192
- const docsDeploySpinner = spinner("Deploying documentation to S3...");
1193
- docsDeploySpinner.start();
1194
- try {
1195
- const { S3Client, CloudFormationClient } = await import("@stacksjs/ts-cloud"), { readFileSync } = await import("node:fs"), s3 = new S3Client(region), cf = new CloudFormationClient(region), stackName = `${projectName}-cloud`, docsOutputs = await cf.getStackOutputs(stackName), docsBucketName = docsOutputs.DocsBucketName;
1196
- if (!docsBucketName) {
1197
- docsDeploySpinner.stop();
1198
- console.log("\u26A0 Docs bucket not found in stack outputs (infrastructure may not be updated yet)");
1199
- } else {
1200
- await (async (dir, _prefix = "") => {
1201
- await traverseDirectory(dir, async (filePath, key) => {
1202
- const content = readFileSync(filePath), contentType = getMimeType(filePath), cacheControl = key.endsWith(".html") ? "no-cache, no-store, must-revalidate" : "public, max-age=31536000, immutable";
1203
- await withS3Retry(() => s3.putObject({ bucket: docsBucketName, key, body: content, contentType, cacheControl }), `upload docs ${key}`);
1204
- if (isVerbose)
1205
- log.debug(` Uploaded docs: ${key}`);
1206
- }, "", [".DS_Store", ".bunpress"]);
1207
- })(docsDistPath);
1208
- const docsDistributionId = docsOutputs.docsCloudFrontDistributionId || docsOutputs.publicCloudFrontDistributionId || docsOutputs.CloudFrontDistributionId;
1209
- if (docsDistributionId) {
1210
- if (isVerbose)
1211
- log.debug(" Invalidating CloudFront cache for docs...");
1212
- const { AWSClient } = await import("@stacksjs/ts-cloud"), client = new AWSClient, docsInvalidationPaths = docsOutputs.docsCloudFrontDistributionId ? ["/*"] : ["/docs", "/docs/*"];
1213
- await client.request({
1214
- service: "cloudfront",
1215
- region: "us-east-1",
1216
- method: "POST",
1217
- path: `/2020-05-31/distribution/${docsDistributionId}/invalidation`,
1218
- headers: {
1219
- "Content-Type": "application/xml"
1220
- },
1221
- body: `<?xml version="1.0" encoding="UTF-8"?>
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"),{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"),{readFileSync}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),stackName=`${projectName}-cloud`,docsOutputs=await cf.getStackOutputs(stackName),docsBucketName=docsOutputs.DocsBucketName;if(!docsBucketName){docsDeploySpinner.stop();console.log("\u26A0 Docs bucket not found in stack outputs (infrastructure may not be updated yet)")}else{await(async(dir,_prefix="")=>{await traverseDirectory(dir,async(filePath,key)=>{const content=readFileSync(filePath),contentType=getMimeType(filePath),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"])})(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"),client=new AWSClient,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"?>
1222
225
  <InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
1223
226
  <CallerReference>docs-${Date.now()}</CallerReference>
1224
227
  <Paths>
1225
228
  <Quantity>${docsInvalidationPaths.length}</Quantity>
1226
229
  <Items>
1227
- ${docsInvalidationPaths.map((path) => `<Path>${path}</Path>`).join(`
230
+ ${docsInvalidationPaths.map((path)=>`<Path>${path}</Path>`).join(`
1228
231
  `)}
1229
232
  </Items>
1230
233
  </Paths>
1231
- </InvalidationBatch>`
1232
- });
1233
- }
1234
- docsDeploySpinner.succeed(`Documentation deployed to S3 (${docsBucketName})`);
1235
- }
1236
- } catch (docsDeployError) {
1237
- docsDeploySpinner.fail(`Documentation deployment failed: ${docsDeployError.message}`);
1238
- if (isVerbose)
1239
- log.debug(`Docs deploy error: ${docsDeployError.stack}`);
1240
- }
1241
- } else if (isVerbose)
1242
- log.debug("No docs build found at dist/docs, skipping docs deployment");
1243
- const blogDistPath = p.projectPath("dist/blog"), { existsSync: blogExists } = await import("node:fs");
1244
- if (blogExists(blogDistPath)) {
1245
- const blogDeploySpinner = spinner("Deploying blog to S3...");
1246
- blogDeploySpinner.start();
1247
- try {
1248
- const { S3Client: BlogS3Client, CloudFormationClient: BlogCFClient } = await import("@stacksjs/ts-cloud"), { readFileSync: readBlogFile } = await import("node:fs"), blogS3 = new BlogS3Client(region), blogCf = new BlogCFClient(region), stackName = `${projectName}-cloud`, outputs = await blogCf.getStackOutputs(stackName), blogBucketName = outputs.BlogBucketName;
1249
- if (!blogBucketName) {
1250
- blogDeploySpinner.stop();
1251
- console.log("\u26A0 Blog bucket not found in stack outputs");
1252
- } else {
1253
- await traverseDirectory(blogDistPath, async (filePath, key) => {
1254
- const content = readBlogFile(filePath), contentType = getMimeType(filePath), cacheControl = key.endsWith(".html") ? "no-cache, no-store, must-revalidate" : "public, max-age=31536000, immutable";
1255
- await withS3Retry(() => blogS3.putObject({ bucket: blogBucketName, key, body: content, contentType, cacheControl }), `upload blog ${key}`);
1256
- if (isVerbose)
1257
- log.debug(` Uploaded blog: ${key}`);
1258
- }, "", [".DS_Store"]);
1259
- const blogDistributionId = outputs.blogCloudFrontDistributionId || outputs.publicCloudFrontDistributionId || outputs.CloudFrontDistributionId;
1260
- if (blogDistributionId) {
1261
- if (isVerbose)
1262
- log.debug(" Invalidating CloudFront cache for blog...");
1263
- const { AWSClient: BlogAWSClient } = await import("@stacksjs/ts-cloud"), blogClient = new BlogAWSClient, blogInvalidationPaths = outputs.blogCloudFrontDistributionId ? ["/*"] : ["/blog", "/blog/*"];
1264
- await blogClient.request({
1265
- service: "cloudfront",
1266
- region: "us-east-1",
1267
- method: "POST",
1268
- path: `/2020-05-31/distribution/${blogDistributionId}/invalidation`,
1269
- headers: {
1270
- "Content-Type": "application/xml"
1271
- },
1272
- body: `<?xml version="1.0" encoding="UTF-8"?>
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"),{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"),{readFileSync:readBlogFile}=await import("node:fs"),blogS3=new BlogS3Client(region),blogCf=new BlogCFClient(region),stackName=`${projectName}-cloud`,outputs=await blogCf.getStackOutputs(stackName),blogBucketName=outputs.BlogBucketName;if(!blogBucketName){blogDeploySpinner.stop();console.log("\u26A0 Blog bucket not found in stack outputs")}else{await traverseDirectory(blogDistPath,async(filePath,key)=>{const content=readBlogFile(filePath),contentType=getMimeType(filePath),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"),blogClient=new BlogAWSClient,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"?>
1273
235
  <InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
1274
236
  <CallerReference>blog-${Date.now()}</CallerReference>
1275
237
  <Paths>
1276
238
  <Quantity>${blogInvalidationPaths.length}</Quantity>
1277
239
  <Items>
1278
- ${blogInvalidationPaths.map((path) => `<Path>${path}</Path>`).join(`
240
+ ${blogInvalidationPaths.map((path)=>`<Path>${path}</Path>`).join(`
1279
241
  `)}
1280
242
  </Items>
1281
243
  </Paths>
1282
- </InvalidationBatch>`
1283
- });
1284
- }
1285
- blogDeploySpinner.succeed(`Blog deployed to S3 (${blogBucketName})`);
1286
- }
1287
- } catch (blogDeployError) {
1288
- blogDeploySpinner.fail(`Blog deployment failed: ${blogDeployError.message}`);
1289
- if (isVerbose)
1290
- log.debug(`Blog deploy error: ${blogDeployError.stack}`);
1291
- }
1292
- } else if (isVerbose)
1293
- log.debug("No blog build found at dist/blog, skipping blog deployment");
1294
- const errorPageSpinner = spinner("Configuring 404 error page...");
1295
- errorPageSpinner.start();
1296
- try {
1297
- const { S3Client, CloudFormationClient, AWSClient } = await import("@stacksjs/ts-cloud"), { existsSync: exists404, readFileSync: read404 } = await import("node:fs"), s3 = new S3Client(region), cf = new CloudFormationClient(region), awsClient = new AWSClient, stackName = `${projectName}-cloud`, outputs = await cf.getStackOutputs(stackName), frontendBucket = outputs.FrontendBucketName, docsBucket = outputs.DocsBucketName, distributionId = outputs.publicCloudFrontDistributionId || outputs.CloudFrontDistributionId, docs404Path = p.projectPath("dist/docs/.bunpress/404.html");
1298
- let html404Content;
1299
- if (exists404(docs404Path)) {
1300
- html404Content = read404(docs404Path, "utf-8");
1301
- if (isVerbose)
1302
- log.debug(" Using BunPress-generated 404.html");
1303
- } else {
1304
- html404Content = `<!DOCTYPE html>
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"),{existsSync:exists404,readFileSync:read404}=await import("node:fs"),s3=new S3Client(region),cf=new CloudFormationClient(region),awsClient=new AWSClient,stackName=`${projectName}-cloud`,outputs=await cf.getStackOutputs(stackName),frontendBucket=outputs.FrontendBucketName,docsBucket=outputs.DocsBucketName,distributionId=outputs.publicCloudFrontDistributionId||outputs.CloudFrontDistributionId,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>
1305
245
  <html lang="en">
1306
246
  <head>
1307
247
  <meta charset="UTF-8">
@@ -1348,229 +288,12 @@ SERVICEFILE`,
1348
288
  <div class="action"><a class="link" href="/docs/">Take me home</a></div>
1349
289
  </div>
1350
290
  </body>
1351
- </html>`;
1352
- if (isVerbose)
1353
- log.debug(" Using default 404.html template");
1354
- }
1355
- if (frontendBucket) {
1356
- await withS3Retry(() => s3.putObject({
1357
- bucket: frontendBucket,
1358
- key: "404.html",
1359
- body: html404Content,
1360
- contentType: "text/html",
1361
- cacheControl: "no-cache, no-store, must-revalidate"
1362
- }), "upload 404.html to frontend bucket");
1363
- if (isVerbose)
1364
- log.debug(` Uploaded 404.html to frontend bucket: ${frontendBucket}`);
1365
- }
1366
- if (docsBucket) {
1367
- await withS3Retry(() => s3.putObject({
1368
- bucket: docsBucket,
1369
- key: "404.html",
1370
- body: html404Content,
1371
- contentType: "text/html",
1372
- cacheControl: "no-cache, no-store, must-revalidate"
1373
- }), "upload 404.html to docs bucket");
1374
- if (isVerbose)
1375
- log.debug(` Uploaded 404.html to docs bucket: ${docsBucket}`);
1376
- }
1377
- if (distributionId) {
1378
- if (isVerbose)
1379
- log.debug(" Configuring CloudFront custom error responses...");
1380
- const getResult = await awsClient.request({
1381
- service: "cloudfront",
1382
- region: "us-east-1",
1383
- method: "GET",
1384
- path: `/2020-05-31/distribution/${distributionId}/config`,
1385
- returnHeaders: !0
1386
- }), etag = getResult.headers?.etag || getResult.headers?.ETag || "", currentConfig = getResult.body?.DistributionConfig || getResult.DistributionConfig;
1387
- if (currentConfig && etag) {
1388
- if (!((currentConfig.CustomErrorResponses?.Quantity || 0) > 0 && currentConfig.CustomErrorResponses?.Items?.CustomErrorResponse?.some?.((err) => err.ErrorCode === 404 && err.ResponsePagePath === "/404.html"))) {
1389
- currentConfig.CustomErrorResponses = {
1390
- Quantity: 2,
1391
- Items: {
1392
- CustomErrorResponse: [
1393
- {
1394
- ErrorCode: 403,
1395
- ResponsePagePath: "/404.html",
1396
- ResponseCode: 404,
1397
- ErrorCachingMinTTL: 10
1398
- },
1399
- {
1400
- ErrorCode: 404,
1401
- ResponsePagePath: "/404.html",
1402
- ResponseCode: 404,
1403
- ErrorCachingMinTTL: 10
1404
- }
1405
- ]
1406
- }
1407
- };
1408
- const buildXmlElement = (name, value, indent = "") => {
1409
- if (value === null || value === void 0)
1410
- return "";
1411
- if (typeof value === "boolean")
1412
- return `${indent}<${name}>${value}</${name}>
1413
- `;
1414
- if (typeof value === "number" || typeof value === "string")
1415
- return `${indent}<${name}>${value}</${name}>
1416
- `;
1417
- if (Array.isArray(value))
1418
- return value.map((item) => buildXmlElement(name, item, indent)).join("");
1419
- if (typeof value === "object") {
1420
- if (name.startsWith("@_") || name === "?xml")
1421
- return "";
1422
- let children = "";
1423
- for (const [key, val] of Object.entries(value))
1424
- if (!key.startsWith("@_") && key !== "#text")
1425
- children += buildXmlElement(key, val, `${indent} `);
1426
- if (value["#text"] !== void 0)
1427
- return `${indent}<${name}>${value["#text"]}</${name}>
1428
- `;
1429
- return `${indent}<${name}>
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:!0}),etag=getResult.headers?.etag||getResult.headers?.ETag||"",currentConfig=getResult.body?.DistributionConfig||getResult.DistributionConfig;if(currentConfig&&etag){if(!((currentConfig.CustomErrorResponses?.Quantity||0)>0&&currentConfig.CustomErrorResponses?.Items?.CustomErrorResponse?.some?.((err)=>err.ErrorCode===404&&err.ResponsePagePath==="/404.html"))){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===void 0)return"";if(typeof value==="boolean")return`${indent}<${name}>${value}</${name}>
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} `);if(value["#text"]!==void 0)return`${indent}<${name}>${value["#text"]}</${name}>
294
+ `;return`${indent}<${name}>
1430
295
  ${children}${indent}</${name}>
1431
- `;
1432
- }
1433
- return "";
1434
- }, xml = `<?xml version="1.0" encoding="UTF-8"?>
296
+ `}return""},xml=`<?xml version="1.0" encoding="UTF-8"?>
1435
297
  <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
1436
- ${Object.entries(currentConfig).filter(([key]) => !key.startsWith("@_")).map(([key, val]) => buildXmlElement(key, val, " ")).join("")}</DistributionConfig>
1437
- `;
1438
- await awsClient.request({
1439
- service: "cloudfront",
1440
- region: "us-east-1",
1441
- method: "PUT",
1442
- path: `/2020-05-31/distribution/${distributionId}/config`,
1443
- body: xml,
1444
- headers: {
1445
- "Content-Type": "application/xml",
1446
- "If-Match": etag
1447
- }
1448
- });
1449
- if (isVerbose)
1450
- log.debug(" CloudFront custom error responses configured");
1451
- } else if (isVerbose)
1452
- log.debug(" CloudFront custom error responses already configured");
1453
- }
1454
- }
1455
- errorPageSpinner.succeed("404 error page configured");
1456
- } catch (errorPageError) {
1457
- errorPageSpinner.stop();
1458
- console.log(`\u26A0 404 page configuration skipped: ${errorPageError.message}`);
1459
- if (isVerbose)
1460
- log.debug(`Error page config error: ${errorPageError.stack}`);
1461
- }
1462
- try {
1463
- const tunnelCloudConfig = await import(p.projectPath("config/cloud")), tunnelConfig = tunnelCloudConfig?.tsCloud?.infrastructure?.tunnel;
1464
- if (tunnelConfig?.enabled) {
1465
- const tunnelDomain = tunnelConfig.domain || "";
1466
- if (!tunnelDomain || tunnelDomain === "localtunnel.dev" || tunnelDomain === "api.localtunnel.dev")
1467
- console.log("\u2139 Tunnel: Using shared localtunnel.dev (no custom tunnel deployment needed)");
1468
- else {
1469
- const tunnelSpinner = spinner(`Deploying tunnel server to ${tunnelDomain}...`);
1470
- tunnelSpinner.start();
1471
- try {
1472
- const { deployTunnelServer } = await import("@stacksjs/tunnel");
1473
- await deployTunnelServer({
1474
- domain: tunnelDomain,
1475
- region: tunnelConfig.region || tunnelCloudConfig?.tsCloud?.project?.region || "us-east-1",
1476
- instanceType: tunnelConfig.instanceType,
1477
- prefix: tunnelConfig.prefix,
1478
- enableSsl: tunnelConfig.ssl?.enabled,
1479
- porkbunApiKey: tunnelConfig.ssl?.porkbunApiKey,
1480
- porkbunSecretKey: tunnelConfig.ssl?.porkbunSecretKey,
1481
- verbose: isVerbose
1482
- });
1483
- tunnelSpinner.succeed(`Tunnel server deployed to ${tunnelDomain}`);
1484
- } catch (tunnelError) {
1485
- tunnelSpinner.stop();
1486
- console.log(`\u26A0 Tunnel deployment skipped: ${tunnelError.message}`);
1487
- if (isVerbose)
1488
- log.debug(`Tunnel deploy error: ${tunnelError.stack}`);
1489
- }
1490
- }
1491
- }
1492
- } catch {}
1493
- const dnsSpinner = spinner("Reconciling DNS records...");
1494
- dnsSpinner.start();
1495
- try {
1496
- const { Route53Client, CloudFormationClient: DnsCfClient } = await import("@stacksjs/ts-cloud"), dnsCf = new DnsCfClient(region), dnsStackName = `${projectName}-cloud`, dnsOutputs = await dnsCf.getStackOutputs(dnsStackName), dnsCloudConfig = await import(p.projectPath("config/cloud")), hostedZoneId = dnsCloudConfig?.tsCloud?.infrastructure?.dns?.hostedZoneId, siteDomain = dnsCloudConfig?.tsCloud?.infrastructure?.dns?.domain || "stacksjs.com";
1497
- if (hostedZoneId) {
1498
- const route53 = new Route53Client(region), cfHostedZoneId = "Z2FDTNDATAQYW2", domainMappings = [
1499
- { domain: siteDomain, cfDomain: dnsOutputs.publicCloudFrontDomain },
1500
- { domain: `www.${siteDomain}`, cfDomain: dnsOutputs.publicCloudFrontDomain },
1501
- { domain: `docs.${siteDomain}`, cfDomain: dnsOutputs.docsCloudFrontDomain },
1502
- { domain: `blog.${siteDomain}`, cfDomain: dnsOutputs.blogCloudFrontDomain }
1503
- ];
1504
- let recordsCreated = 0;
1505
- for (const { domain, cfDomain } of domainMappings) {
1506
- if (!cfDomain)
1507
- continue;
1508
- try {
1509
- if (!((await route53.listResourceRecordSets({
1510
- HostedZoneId: hostedZoneId,
1511
- StartRecordName: domain,
1512
- StartRecordType: "A",
1513
- MaxItems: "1"
1514
- }))?.ResourceRecordSets || []).some((r) => r.Name === `${domain}.` && r.Type === "A")) {
1515
- await route53.changeResourceRecordSets({
1516
- HostedZoneId: hostedZoneId,
1517
- ChangeBatch: {
1518
- Changes: [
1519
- {
1520
- Action: "UPSERT",
1521
- ResourceRecordSet: {
1522
- Name: domain,
1523
- Type: "A",
1524
- AliasTarget: {
1525
- HostedZoneId: cfHostedZoneId,
1526
- DNSName: cfDomain,
1527
- EvaluateTargetHealth: !1
1528
- }
1529
- }
1530
- },
1531
- {
1532
- Action: "UPSERT",
1533
- ResourceRecordSet: {
1534
- Name: domain,
1535
- Type: "AAAA",
1536
- AliasTarget: {
1537
- HostedZoneId: cfHostedZoneId,
1538
- DNSName: cfDomain,
1539
- EvaluateTargetHealth: !1
1540
- }
1541
- }
1542
- }
1543
- ]
1544
- }
1545
- });
1546
- recordsCreated++;
1547
- if (isVerbose)
1548
- log.debug(` Created DNS records: ${domain} -> ${cfDomain}`);
1549
- } else if (isVerbose)
1550
- log.debug(` DNS record exists: ${domain}`);
1551
- } catch (dnsErr) {
1552
- if (isVerbose)
1553
- log.debug(` DNS check/create failed for ${domain}: ${dnsErr.message}`);
1554
- }
1555
- }
1556
- if (recordsCreated > 0)
1557
- dnsSpinner.succeed(`DNS records reconciled (${recordsCreated} created)`);
1558
- else
1559
- dnsSpinner.succeed("DNS records verified");
1560
- } else {
1561
- dnsSpinner.stop();
1562
- if (isVerbose)
1563
- log.debug("No hosted zone ID configured, skipping DNS reconciliation");
1564
- }
1565
- } catch (dnsError) {
1566
- dnsSpinner.stop();
1567
- console.log(`\u26A0 DNS reconciliation skipped: ${dnsError.message}`);
1568
- if (isVerbose)
1569
- log.debug(`DNS error: ${dnsError.stack}`);
1570
- }
1571
- console.log("");
1572
- log.success("Deployment completed successfully!");
1573
- } catch (error) {
1574
- log.error("Deployment failed:", error);
1575
- process.exit(ExitCode.FatalError);
1576
- }
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 if(isVerbose)log.debug(" CloudFront custom error responses already configured")}}errorPageSpinner.succeed("404 error page configured")}catch(errorPageError){errorPageSpinner.stop();console.log(`\u26A0 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")),tunnelConfig=tunnelCloudConfig?.tsCloud?.infrastructure?.tunnel;if(tunnelConfig?.enabled){const tunnelDomain=tunnelConfig.domain||"";if(!tunnelDomain||tunnelDomain==="localtunnel.dev"||tunnelDomain==="api.localtunnel.dev")console.log("\u2139 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(`\u26A0 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"),dnsCf=new DnsCfClient(region),dnsStackName=`${projectName}-cloud`,dnsOutputs=await dnsCf.getStackOutputs(dnsStackName),dnsCloudConfig=await import(p.projectPath("config/cloud")),hostedZoneId=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.hostedZoneId,siteDomain=dnsCloudConfig?.tsCloud?.infrastructure?.dns?.domain||"stacksjs.com";if(hostedZoneId){const route53=new Route53Client(region),cfHostedZoneId="Z2FDTNDATAQYW2",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{if(!((await route53.listResourceRecordSets({HostedZoneId:hostedZoneId,StartRecordName:domain,StartRecordType:"A",MaxItems:"1"}))?.ResourceRecordSets||[]).some((r)=>r.Name===`${domain}.`&&r.Type==="A")){await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"A",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:!1}}},{Action:"UPSERT",ResourceRecordSet:{Name:domain,Type:"AAAA",AliasTarget:{HostedZoneId:cfHostedZoneId,DNSName:cfDomain,EvaluateTargetHealth:!1}}}]}});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(`\u26A0 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)}