@stacksjs/buddy 0.75.256 → 0.75.258

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.
@@ -13,6 +13,11 @@ export declare function appStoreConnectToken(credentials: AppStoreConnectCredent
13
13
  export declare function buildsToExpire(builds: TestFlightBuild[], keep?: number): TestFlightBuild[];
14
14
  /** The tag for the build Xcode Cloud is about to number, given its newest run. */
15
15
  export declare function tagForXcodeCloudRun(version: string, latestRun: number): string;
16
+ /**
17
+ * The build once App Store Connect lists it: Xcode Cloud uploads it some
18
+ * minutes after the tag is pushed. Null when it has not appeared in time.
19
+ */
20
+ export declare function waitForBuild(api: Pick<AppStoreConnect, 'build'>, appId: string, version: string, number: number, options: WaitForBuildOptions): Promise<TestFlightBuild | null>;
16
21
  export declare interface AppStoreConnectCredentials {
17
22
  keyId: string
18
23
  issuerId: string
@@ -25,6 +30,13 @@ export declare interface TestFlightBuild {
25
30
  processingState: string
26
31
  expired: boolean
27
32
  }
33
+ export declare interface WaitForBuildOptions {
34
+ timeoutMs: number
35
+ intervalMs?: number
36
+ sleep?: (ms: number) => Promise<void>
37
+ now?: () => number
38
+ onWait?: (elapsedMs: number) => void
39
+ }
28
40
  declare type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
29
41
  export declare class AppStoreConnect {
30
42
  constructor(token: string, fetchImpl?: Fetch);
@@ -32,5 +44,7 @@ export declare class AppStoreConnect {
32
44
  appId(bundleId: string): Promise<string>;
33
45
  latestXcodeCloudRun(appId: string): Promise<number | null>;
34
46
  builds(appId: string): Promise<TestFlightBuild[]>;
47
+ build(appId: string, version: string, number: number): Promise<TestFlightBuild | null>;
48
+ setWhatToTest(buildId: string, notes: Record<string, string>): Promise<void>;
35
49
  expire(buildId: string): Promise<void>;
36
50
  }
@@ -1,2 +1,2 @@
1
1
  import{existsSync,readFileSync}from"node:fs";import{nextBuildNumber}from"@stacksjs/bumpx";const API="https://api.appstoreconnect.apple.com";export function appStoreConnectCredentials(env=process.env){const keyId=env.APP_STORE_CONNECT_KEY_ID?.trim(),issuerId=env.APP_STORE_CONNECT_ISSUER_ID?.trim();let privateKey=env.APP_STORE_CONNECT_PRIVATE_KEY?.trim();const keyPath=env.APP_STORE_CONNECT_PRIVATE_KEY_PATH?.trim();if(!privateKey&&keyPath&&existsSync(keyPath))privateKey=readFileSync(keyPath,"utf8").trim();if(!keyId||!issuerId||!privateKey)return null;return{keyId,issuerId,privateKey:privateKey.replace(/\\n/g,`
2
- `)}}function base64url(bytes){return(typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,""),key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),iat=Math.floor(now/1000),header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"})),payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+1200,aud:"appstoreconnect-v1"})),signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){return new AppStoreConnect(await appStoreConnectToken(credentials),fetchImpl)}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async appId(bundleId){const id=(await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`))?.data?.[0]?.id;if(!id)throw Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const productId=(await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`))?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`),number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){return((await this.request(`/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=50&fields[builds]=version,uploadedDate,processingState,expired`))?.data??[]).map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:!0}}})})}}export function buildsToExpire(builds,keep=1){return builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number).slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}
2
+ `)}}function base64url(bytes){return(typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,""),key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),iat=Math.floor(now/1000),header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"})),payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+1200,aud:"appstoreconnect-v1"})),signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){return new AppStoreConnect(await appStoreConnectToken(credentials),fetchImpl)}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async appId(bundleId){const id=(await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`))?.data?.[0]?.id;if(!id)throw Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const productId=(await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`))?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`),number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){return((await this.request(`/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=50&fields[builds]=version,uploadedDate,processingState,expired`))?.data??[]).map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async build(appId,version,number){const query=`filter[app]=${appId}&filter[version]=${encodeURIComponent(String(number))}&filter[preReleaseVersion.version]=${encodeURIComponent(version)}&limit=1&fields[builds]=version,uploadedDate,processingState,expired`,build=(await this.request(`/v1/builds?${query}`))?.data?.[0];return build?{id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}:null}async setWhatToTest(buildId,notes){const existing=await this.request(`/v1/builds/${buildId}/betaBuildLocalizations?limit=50&fields[betaBuildLocalizations]=locale,whatsNew`),byLocale=new Map((existing?.data??[]).map((row)=>[String(row.attributes?.locale),String(row.id)]));for(const[locale,whatsNew]of Object.entries(notes)){const id=byLocale.get(locale);if(id)await this.request(`/v1/betaBuildLocalizations/${id}`,{method:"PATCH",body:JSON.stringify({data:{type:"betaBuildLocalizations",id,attributes:{whatsNew}}})});else await this.request("/v1/betaBuildLocalizations",{method:"POST",body:JSON.stringify({data:{type:"betaBuildLocalizations",attributes:{locale,whatsNew},relationships:{build:{data:{type:"builds",id:buildId}}}}})})}}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:!0}}})})}}export function buildsToExpire(builds,keep=1){return builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number).slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}export async function waitForBuild(api,appId,version,number,options){const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms))),now=options.now??Date.now,interval=options.intervalMs??30000,start=now();for(;;){const build=await api.build(appId,version,number);if(build)return build;const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}
@@ -1,4 +1,4 @@
1
- import{existsSync,mkdirSync,readFileSync,readdirSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorCode,getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}from"./setup";import{resultFailed}from"../result";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("\u2139",...args),success:(...args)=>console.log("\u2713",...args),warn:(...args)=>console.log("\u26A0",...args),error:(...args)=>console.error("\u2717",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v"))console.log("\uD83D\uDD0D",...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"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0),pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++)if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0);return!0}export function resolveTsCloudCliPath(tsCloudEntry=import.meta.resolve("@stacksjs/ts-cloud")){return resolve(dirname(new URL(tsCloudEntry).pathname),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{return await Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env}),command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"],newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` \u27A1\uFE0F bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const 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(entry))matches.push(fullPath)}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"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=join(homedir(),".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"),pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates)if(existsSync(candidate)&&isElfBinary(candidate))return candidate;for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")])for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES))if(isElfBinary(candidate))return candidate;return null}async function ensureDeployPrerequisites(verbose=!1,environment="production"){const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials"),configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath))return{};try{const lines=readFileSync(credentialsPath,"utf-8").split(`
1
+ import{existsSync,mkdirSync,readFileSync,readdirSync,statSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,isAbsolute,join,relative,resolve}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{runAction}from"@stacksjs/actions";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{italic,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{app,dns as dnsConfig,email as emailConfig}from"@stacksjs/config";import{addDomain,hasUserDomainBeenAddedToCloud,syncDnsConfig}from"@stacksjs/dns";import{loadProjectDnsConfig}from"../config";import{env}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{getErrorCode,getErrorMessage}from"@stacksjs/utils";import{withDeployNotification}from"../deploy-notify";import{assertCurrentDeploymentRevision,assertNotBehindLiveRelease,automatedDeploymentRevision,liveReleasesCommand}from"../deployment-revision";import{dnsCredentialFix,envFileForEnvironment,resolveZoneNameservers}from"../dns-credentials";import{ensureAppKey,ensureDeployEnvIsSet,ensureEnvIsSet}from"./setup";import{resultFailed}from"../result";import{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}from"../unbacked-data";import{applyDeploymentDomainOverride,createDeploymentPreview,deploymentPreviewJsonPrefix,formatDeploymentPreview,resolveDeploymentEnvironment}from"./deploy-preview";import{buildPreviewTeardownScript,derivePreviewConfig,previewDomain,previewPort,previewTarget}from"./preview-deploy";import{deployTargetLabel,dnsPublishingAllowed,hetznerTarget,isSshPipelineProvider,lanUrls,mergeSshStatePin,remoteExecOptions,resolveSshTarget,sshCliArgs,sshStatePin,toSshTarget}from"./deploy-ssh-target";const log={info:(...args)=>console.log("\u2139",...args),success:(...args)=>console.log("\u2713",...args),warn:(...args)=>console.log("\u26A0",...args),error:(...args)=>console.error("\u2717",...args),debug:(...args)=>{if(process.argv.includes("--verbose")||process.argv.includes("-v"))console.log("\uD83D\uDD0D",...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"];export const ROLLBACK_FLAGS_SINCE="0.16.34";export function installedTsCloudVersion(cliPath=resolveTsCloudCliPath()){try{const pkg=JSON.parse(readFileSync(resolve(dirname(cliPath),"..","..","package.json"),"utf8"));return typeof pkg.version==="string"?pkg.version:null}catch{return null}}export function versionAtLeast(a,b){const pa=a.split(".").map((n)=>Number.parseInt(n,10)||0),pb=b.split(".").map((n)=>Number.parseInt(n,10)||0);for(let i=0;i<3;i++)if((pa[i]??0)!==(pb[i]??0))return(pa[i]??0)>(pb[i]??0);return!0}export function resolveTsCloudCliPath(tsCloudEntry=import.meta.resolve("@stacksjs/ts-cloud")){return resolve(dirname(new URL(tsCloudEntry).pathname),"bin/cli.js")}export async function runDeployRollback(site,options,execute=async(command)=>{return await Bun.spawn(command,{cwd:p.projectPath(),env:process.env,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited},tsCloudVersion=installedTsCloudVersion()){const environment=resolveDeploymentEnvironment({option:options.env}),command=[process.execPath,resolveTsCloudCliPath(),"deploy:rollback"],newFlags=[options.dryRun&&"--dry-run",options.all&&"--all",options.onlyIfLive&&"--only-if-live"].filter(Boolean);if(newFlags.length>0&&!(tsCloudVersion&&versionAtLeast(tsCloudVersion,ROLLBACK_FLAGS_SINCE))){log.error(`${newFlags.join(", ")} needs @stacksjs/ts-cloud ${ROLLBACK_FLAGS_SINCE} or newer (installed: ${tsCloudVersion??"unknown"}). An older one ignores it and rolls back for real.`);log.info(` \u27A1\uFE0F bun add @stacksjs/ts-cloud@^${ROLLBACK_FLAGS_SINCE}`);return ExitCode.InvalidArgument}if(site)command.push(site);command.push("--env",environment);if(options.to)command.push("--to",options.to);if(options.dryRun)command.push("--dry-run");if(options.all)command.push("--all");if(options.onlyIfLive)command.push("--only-if-live",options.onlyIfLive);if(options.verbose)command.push("--verbose");return await execute(command)}function collectMatchingFiles(root,names,maxDepth=8){const 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(entry))matches.push(fullPath)}}walk(root,0);return matches}function isElfBinary(filePath){const header=readFileSync(filePath).slice(0,4);return header[0]===127&&header[1]===69&&header[2]===76&&header[3]===70}function resolvePantryInstallCommand(){const localPantryCli=join(homedir(),"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=join(homedir(),".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"),pantry=resolvePantryInstallCommand();execFileSync(pantry.command,[...pantry.args,"install",MAIL_PACKAGE_SPEC,"--install-dir",p.projectPath("pantry"),"--platform",MAIL_TARGET_PLATFORM,"--quiet"],{cwd:p.projectPath(),stdio:process.argv.includes("--verbose")||process.argv.includes("-v")?"inherit":"pipe",env:process.env})}async function findPantryMailBinary(){const directCandidates=[...MAIL_BINARY_NAMES.map((name)=>p.projectPath(`pantry/.bin/${name}`)),...MAIL_BINARY_NAMES.map((name)=>join(homedir(),".local","share","pantry","global","bin",name))];for(const candidate of directCandidates)if(existsSync(candidate)&&isElfBinary(candidate))return candidate;for(const root of[p.projectPath("pantry"),join(homedir(),".local","share","pantry")])for(const candidate of collectMatchingFiles(root,MAIL_BINARY_NAMES))if(isElfBinary(candidate))return candidate;return null}async function ensureDeployPrerequisites(verbose=!1,environment="production"){const cwd=p.projectPath();await ensureEnvIsSet({cwd,verbose});await ensureDeployEnvIsSet(cwd,environment);await ensureAppKey(cwd)}function loadAwsCredentialsFromFile(){const credentialsPath=join(homedir(),".aws","credentials"),configPath=join(homedir(),".aws","config");if(!existsSync(credentialsPath))return{};try{const lines=readFileSync(credentialsPath,"utf-8").split(`
2
2
  `),profiles=["default","stacks"];let currentProfile="",credentials={};const profileCredentials={};for(const line of lines){const trimmed=line.trim(),profileMatch=trimmed.match(/^\[(.+)\]$/);if(profileMatch?.[1]){currentProfile=profileMatch[1];profileCredentials[currentProfile]={};continue}const keyValue=trimmed.match(/^(\w+)\s*=\s*(.+)$/);if(keyValue&&currentProfile){const[,key,value]=keyValue,target=profileCredentials[currentProfile];if(!target||value===void 0)continue;if(key==="aws_access_key_id")target.accessKeyId=value;else if(key==="aws_secret_access_key")target.secretAccessKey=value}}for(const profile of profiles)if(profileCredentials[profile]?.accessKeyId&&profileCredentials[profile]?.secretAccessKey){credentials=profileCredentials[profile];log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}if(!credentials.accessKeyId){for(const[profile,creds]of Object.entries(profileCredentials))if(creds.accessKeyId&&creds.secretAccessKey){credentials=creds;log.debug(`Using AWS credentials from ~/.aws/credentials [${profile}] profile`);break}}let region;if(existsSync(configPath)){const regionMatch=readFileSync(configPath,"utf-8").match(/region\s*=\s*(.+)/);if(regionMatch?.[1])region=regionMatch[1].trim()}return{...credentials,region}}catch(error){log.debug("Failed to read AWS credentials file:",error);return{}}}async function setupEmailDnsRecords(emailDomain,region,logger,options){logger.info("Setting up email DNS records...");try{const{SESClient}=await import("@stacksjs/ts-cloud"),{Route53Client}=await import("@stacksjs/ts-cloud"),ses=new SESClient(region),route53=new Route53Client(region);logger.info(`Getting DKIM tokens for ${emailDomain}...`);const tokens=(await ses.getEmailIdentity(emailDomain)).DkimAttributes?.Tokens||[];if(tokens.length===0){logger.warn("No DKIM tokens found - domain may not be set up in SES yet");return}logger.info(`Found ${tokens.length} DKIM tokens`);const zone=(await route53.listHostedZones()).HostedZones?.find((z)=>z.Name===`${emailDomain}.`);if(!zone){logger.warn(`Hosted zone not found for ${emailDomain} - DNS records must be added manually`);logger.info("DKIM records needed:");for(const token of tokens)logger.info(` CNAME: ${token}._domainkey.${emailDomain} -> ${token}.dkim.amazonses.com`);logger.info(` MX: ${emailDomain} -> 10 inbound-smtp.${region}.amazonaws.com`);return}const hostedZoneId=zone.Id?.replace("/hostedzone/","");logger.info(`Found hosted zone: ${hostedZoneId}`);for(const token of tokens){const recordName=`${token}._domainkey.${emailDomain}`,recordValue=`${token}.dkim.amazonses.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:recordName,Type:"CNAME",TTL:300,ResourceRecords:[{Value:recordValue}]}}]}});logger.success(`Added DKIM record: ${token}._domainkey`)}catch(e){logger.warn(`Failed to add DKIM record: ${getErrorMessage(e)}`)}}const mailSubdomain=options?.mailSubdomain||"mail",mxTarget=options?.mode==="server"?`10 ${mailSubdomain}.${emailDomain}`:`10 inbound-smtp.${region}.amazonaws.com`;try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"MX",TTL:300,ResourceRecords:[{Value:mxTarget}]}}]}});logger.success(`Added MX record: ${mxTarget}`)}catch(e){logger.warn(`Failed to add MX record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:emailDomain,Type:"TXT",TTL:300,ResourceRecords:[{Value:'"v=spf1 include:amazonses.com ~all"'}]}}]}});logger.success("Added SPF record")}catch(e){logger.warn(`Failed to add SPF record: ${getErrorMessage(e)}`)}try{await route53.changeResourceRecordSets({HostedZoneId:hostedZoneId,ChangeBatch:{Changes:[{Action:"UPSERT",ResourceRecordSet:{Name:`_dmarc.${emailDomain}`,Type:"TXT",TTL:300,ResourceRecords:[{Value:`"v=DMARC1;p=quarantine;pct=25;rua=mailto:dmarcreports@${emailDomain}"`}]}}]}});logger.success("Added DMARC record")}catch(e){logger.warn(`Failed to add DMARC record: ${getErrorMessage(e)}`)}try{const ruleSetName=`${process.env.APP_NAME?.toLowerCase().replace(/[^a-z0-9]/g,"-")||"stacks"}-email-rules`;await ses.setActiveReceiptRuleSet(ruleSetName);logger.success(`Activated email receipt rule set: ${ruleSetName}`)}catch(e){logger.warn(`Failed to activate receipt rule set: ${getErrorMessage(e)}`)}logger.success("Email DNS records configured!");logger.info("Note: DKIM verification may take 5-15 minutes to complete")}catch(error){logger.warn(`Failed to set up email DNS records: ${getErrorMessage(error)}`);logger.info("You can manually set up DNS records using: buddy email:verify")}}async function createDefaultMailUser(appName,emailDomain,region,logger){try{const{DynamoDBClient}=await import("@stacksjs/ts-cloud"),crypto=await import("crypto"),dynamodb=new DynamoDBClient(region),tableName=`${appName}-mail-users`,mailboxes=emailConfig?.mailboxes||[];if(mailboxes.length===0){const defaultEmail=`admin@${emailDomain}`,defaultPassword=crypto.randomBytes(16).toString("hex"),passwordHash=crypto.createHash("sha256").update(defaultPassword).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:defaultEmail},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:"Admin"}}});logger.success(`Created default mail user: ${defaultEmail}`);logger.info(`Password: ${defaultPassword}`);logger.info("Save this password - it will not be shown again!")}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException")||msg.includes("already exists"))logger.debug("Default mail user already exists");else throw e}}else for(const mailbox of mailboxes){const mb=typeof mailbox==="object"&&mailbox!==null?mailbox:null,configured=mb?.email,email=mb?configured?.includes("@")?configured:`${configured??""}@${emailDomain}`:`${mailbox}@${emailDomain}`,password=mb?.password?mb.password:crypto.randomBytes(16).toString("hex"),passwordHash=crypto.createHash("sha256").update(password).digest("hex");try{await dynamodb.putItem({TableName:tableName,Item:{email:{S:email},passwordHash:{S:passwordHash},createdAt:{S:new Date().toISOString()},displayName:{S:mb?mb.displayName||email:String(mailbox)}}});logger.success(`Created mail user: ${email}`);if(!mb?.password)logger.info(` Password: ${password}`)}catch(e){const msg=getErrorMessage(e);if(msg.includes("ConditionalCheckFailedException"))logger.debug(`Mail user ${email} already exists`);else logger.warn(`Failed to create mail user ${email}: ${msg}`)}}}catch(error){logger.warn(`Failed to create mail users: ${getErrorMessage(error)}`)}}async function uploadMailServerToS3(bucketName,region,mode){try{const{S3Client:S3}=await import("@stacksjs/ts-cloud"),s3Client=new S3(region);if(mode==="serverless"){const serverTsPath=p.frameworkPath("core/mail-server/server.ts");if(existsSync(serverTsPath)){const serverCode=readFileSync(serverTsPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/server.ts",body:serverCode,contentType:"text/typescript"});log.success("Uploaded serverless mail server code to S3")}const pkgPath=p.frameworkPath("core/mail-server/package.json");if(existsSync(pkgPath)){const pkgJson=readFileSync(pkgPath,"utf-8");await s3Client.putObject({bucket:bucketName,key:"mail-server/package.json",body:pkgJson,contentType:"application/json"})}return}let binaryUploaded=!1;try{await installMailBinaryWithPantry();const linuxBinaryPath=await findPantryMailBinary();if(linuxBinaryPath&&existsSync(linuxBinaryPath)&&isElfBinary(linuxBinaryPath)){log.info(`Uploading Pantry mail binary: ${linuxBinaryPath}`);const binaryContent=readFileSync(linuxBinaryPath);await s3Client.putObject({bucket:bucketName,key:"mail-server/smtp-server",body:binaryContent,contentType:"application/octet-stream"});log.success("Uploaded Linux x86_64 mail server binary to S3");binaryUploaded=!0}}catch(error){log.debug(`Pantry mail install failed: ${getErrorMessage(error)}`)}if(!binaryUploaded)log.warn(`No Pantry-provided ${MAIL_TARGET_PLATFORM} mail binary found. Release ${MAIL_PACKAGE_DOMAIN}, then run the Pantry binary sync for that package.`)}catch(uploadErr){log.debug(`Could not upload mail server to S3 (bucket may not exist yet): ${uploadErr.message}`)}}export async function loadTsCloudConfig(envName){try{const base=p.projectPath("config/cloud.ts");return(await import(envName?`${base}?env=${envName}`:base)).tsCloud}catch(err){log.debug("Could not load config/cloud.ts tsCloud export:",err);return}}export function resolveProvider(tsCloudConfig){return tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws"}function readWaitSecs(name,defaultSecs){const secs=process.env[name]?Number.parseInt(process.env[name],10):Number.NaN;return Number.isFinite(secs)&&secs>0?secs:defaultSecs}function fmtDuration(secs){const m=Math.floor(secs/60),s=secs%60;return m?s?`${m}m${s}s`:`${m}m`:`${s}s`}export function pollFailureDetail(error){const collapsed=(error instanceof Error?error.message:typeof error==="string"?error:"").replace(/\s+/g," ").trim();if(!collapsed)return;return collapsed.length>300?`${collapsed.slice(0,297)}...`:collapsed}export function sshUnreachableMessage(opts){const detail=pollFailureDetail(opts.lastError);return`SSH did not become reachable on ${opts.ip} within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
3
3
  Last attempt: ${detail}`:"")+`
4
4
  A connection timeout means the box is probably still booting, so raise TS_CLOUD_SSH_WAIT_SECS and retry. "Permission denied" means the key is not authorized, and a refused or reset connection (especially after earlier attempts got further) usually means fail2ban banned this IP. Waiting longer fixes neither.`}export function bunRuntimeMissingMessage(opts){const detail=pollFailureDetail(opts.lastError);return`bun runtime did not appear at /usr/local/bin/bun within ${fmtDuration(opts.waitSecs)} (waited ${opts.elapsedSecs}s).`+(detail?`
@@ -408,6 +408,11 @@ EOF
408
408
  cat > /usr/local/sbin/mail-health-check <<'EOF'
409
409
  #!/bin/sh
410
410
  set -eu
411
+ # The mail release owns the protocol checker and alert state. A tenant deploy
412
+ # must never downgrade it to listener-only checks or take its lock twice.
413
+ if [ -x /usr/local/sbin/mail-protocol-health-check ]; then
414
+ exec /usr/local/sbin/mail-protocol-health-check
415
+ fi
411
416
  exec 9>/run/mail-health-check.lock
412
417
  flock -n 9 || exit 0
413
418
  restart_mail() {
@@ -426,7 +431,7 @@ restart_mail() {
426
431
  if ! systemctl is-active --quiet mail; then
427
432
  restart_mail "mail service is inactive"
428
433
  fi
429
- for port in 25 143 587 993; do
434
+ for port in 25 143 465 587 993; do
430
435
  if ! ss -H -ltn "sport = :$port" | grep -q .; then
431
436
  restart_mail "required TCP port $port is not listening"
432
437
  ss -H -ltn "sport = :$port" | grep -q . || {
@@ -439,7 +444,7 @@ EOF
439
444
  chmod 755 /usr/local/sbin/mail-health-check
440
445
  cat > /etc/systemd/system/mail-health.service <<'EOF'
441
446
  [Unit]
442
- Description=Check the Stacks mail daemon listeners
447
+ Description=Verify mail delivery health
443
448
  After=mail.service
444
449
 
445
450
  [Service]
@@ -462,6 +467,6 @@ EOF
462
467
  systemctl daemon-reload
463
468
  systemctl enable --now mail-health.timer >/dev/null 2>&1
464
469
  # 6) Restart only when the startup-read env actually changed (domain or DKIM key).
465
- if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execSync(`ssh ${sshArgs.map((a)=>`'${a}'`).join(" ")} bash -s`,{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]}),line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done",mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim(),mailHost=mailHostFromOut||`mail.${domain}`,dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||void 0,dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||void 0,dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) \u2014 rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy \u2014 nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])),migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])),updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[])),updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]),createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address)),created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]),unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():void 0}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud"),provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers),providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):void 0}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:void 0}export function postmasterHint(domain,postmaster){if(postmaster===!1)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase(),n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone),ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:!1};return{remove:ours,create:!0}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns"),own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`,cfg=emailConfig||{},firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address,fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:void 0,dmarcCfg=cfg.server?.dmarc||{},rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`,dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`,dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:void 0,postmasterCfg=cfg.server?.postmaster,postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):void 0;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production"),byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]})),provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(" Or add these records by hand at the DNS host:");logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)},declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return})),providerConfigs=dnsProviderConfigsFromEnv(declared),declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand("no configured DNS provider administers this zone");const apex=domain.toLowerCase(),dkimFqdn=`${dkimName}.${domain}`,dmarcFqdn=`_dmarc.${domain}`,mailFqdn=`mail.${domain}`,recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)},replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT"),{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===!1)throw Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX"),staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} \u2192 ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>!0);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain),anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX\u2192${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}\u2192${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites))if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""));const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it \u2014 upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved \u2014 skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId}),report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe});for(const record of report.records)logger.success(` ${record.host} ${record.type} \u2192 ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} \u2192 ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason} \u2014 re-run the deploy once TLS is issued.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN,accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||void 0,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN,accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||void 0,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);if(["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0)===0)return;for(const domain of configDnsDomains(sites))try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} \u2192 ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud"),result=await delegateZoneFromConfig(dns);for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[],{gatewayHostnames}=await import("@stacksjs/ts-cloud"),hostnames=gatewayHostnames(sites,{autoWww}),byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,""),group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig),providerConfigs=dnsProviderConfigsFromEnv(declared),declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/\u2026); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} \u2192 ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} \u2192 ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} \u2192 ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} \u2192 ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} \u2192 ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base}),envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:!0,quiet:!0})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null,lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig),host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host),{sshExecOrThrow}=await import("@stacksjs/ts-cloud"),runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64"),privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud"),owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript()))),port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===!0,yes:!0},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
466
- `,{flag:"a"})}async function removePreview(target,base,runRemote){log.info(`Removing preview ${target.slug} (${target.host})`);await runRemote(buildPreviewTeardownScript(target.slug,target.site));log.success(`Removed ${target.slug} from the box`);const tsCloudConfig=await loadTsCloudConfig(base).catch(()=>{return}),providerConfigs=dnsProviderConfigsFromEnv(declaredDnsProvider(tsCloudConfig)),zone=target.host,provider=providerConfigs.length>0?await resolveZoneDnsProvider(zone,providerConfigs,log):void 0;if(!provider)log.warn(`DNS: no configured provider manages ${zone}; remove the A/AAAA records for ${target.host} by hand.`);else{const{removeAddressRecords}=await import("@stacksjs/ts-cloud"),{removed,warnings}=await removeAddressRecords(provider,zone,target.host);for(const record of removed)log.success(`DNS: deleted ${record.type} ${target.host} (${provider.name})`);for(const warning of warnings)log.warn(`DNS: ${warning}`)}const pin=join(process.cwd(),"storage","cloud","state",`${target.slug}-${base}.json`);if(existsSync(pin)){const{rmSync}=await import("node:fs");rmSync(pin)}log.success(`Preview ${target.slug} removed`)}async function deployToFlyProvider(tsCloudConfig,environment,verbose){const{FlyDeployError,runFlyDeploy}=await import("./deploy-fly"),api=await loadTsCloudDeployApi();if(typeof api.deployToFly!=="function"){log.error("This @stacksjs/ts-cloud cannot deploy to Fly.io: upgrade it to 0.16.45 or newer.");process.exit(ExitCode.FatalError)}const{execSync}=await import("node:child_process");let release;try{release=execSync("git rev-parse --short=12 HEAD",{cwd:p.projectPath(),stdio:"pipe"}).toString().trim()}catch{release=`build-${Date.now()}`}const deployEnv=environment==="prod"?"production":environment;try{const result=await runFlyDeploy({config:tsCloudConfig,environment:deployEnv,token:process.env.FLY_API_TOKEN,release,envValues:await resolveDeployEnvValues(deployEnv,tsCloudConfig),projectRoot:p.projectPath()},{api,run:(command,options)=>{const child=Bun.spawnSync(command,{cwd:options.cwd,stdin:options.stdin===void 0?"inherit":new TextEncoder().encode(options.stdin),stdout:verbose?"inherit":"pipe",stderr:verbose?"inherit":"pipe"});return{exitCode:child.exitCode,output:`${child.stdout??""}${child.stderr??""}`}},exists:existsSync,log:(line)=>log.info(line)});log.success(`Deployed to ${result.url}`);if(result.untouched.length>0)log.warn(`Left ${result.untouched.length} Machine(s) the config no longer accounts for: ${result.untouched.join(", ")}. Remove them with \`fly machine destroy\` once nothing needs their data.`);for(const certificate of result.certificates){if(certificate.configured)continue;const needs=certificate.dns_requirements,target=needs?.cname?`a CNAME to ${needs.cname}`:[...needs?.a??[],...needs?.aaaa??[]].join(", ")||"Fly's addresses";log.info(`${certificate.hostname}: point it at ${target}; Fly issues the certificate once it resolves.`)}}catch(error){if(error instanceof FlyDeployError){log.error(error.message);if(error.hint)log.info(error.hint);process.exit(ExitCode.FatalError)}throw error}}async function buildContainerImageWithPantry(args){const{slug,sites,verbose}=args,{execSync}=await import("node:child_process");let cli;for(const candidate of["pantry","ts-pantry"])try{execSync(`command -v ${candidate}`,{stdio:"pipe"});cli=candidate;break}catch{}if(!cli){log.warn("pantry CLI not found on PATH - skipping container image build. Install pantry to enable `--docker`.");return}const dockerfile="storage/framework/Dockerfile",canPush=Boolean(process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN);for(const[siteName,site]of Object.entries(sites)){if(!site?.start)continue;const tag=`${slug}-${siteName}:latest`;log.info(`[${siteName}] building image ${tag} with pantry (native, no Docker daemon)...`);const flags=["build",".","-t",tag,"-f",dockerfile,"--run-mode","skip"];if(canPush)flags.push("--push");execSync(`${cli} ${flags.map((f)=>f.includes(" ")?`'${f}'`:f).join(" ")}`,{stdio:verbose?"inherit":"pipe",maxBuffer:536870912});log.success(`[${siteName}] image built${canPush?" + pushed to the pantry registry":""}`)}}export function deploy(buddy){const descriptions={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};buddy.command("deploy [env]",descriptions.deploy).option("--domain <domain>",descriptions.domain,{default:void 0}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--prod",descriptions.production,{default:!1}).option("--dev",descriptions.development,{default:!1}).option("--yes",descriptions.yes,{default:!1}).option("--site <name>","Deploy only this one site to the existing server (multi-tenant surgical add)",{default:void 0}).option("--staging",descriptions.staging,{default:!1}).option("--dry-run","Preview the deployment and change nothing",{default:!1}).option("--docker","Also build an OCI image with pantry (native, no Docker daemon) and push it to the pantry registry",{default:!1}).option("-J, --json","Emit a machine-readable deployment preview",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(withDeployNotification(async(envArg,options)=>{log.debug("Running `buddy deploy` ...",options);const askedForDryRun=process.argv.includes("--dry-run")||options.dryRun===!0,optionEnvironment=options.env,deployEnvName=resolveDeploymentEnvironment({positional:envArg,option:optionEnvironment,staging:options.staging,development:options.dev}),deployEnv=deployEnvName;try{applyDeploymentDomainOverride({},options.domain)}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(askedForDryRun){process.env.APP_ENV=deployEnvName;const envFile=deployEnvName==="production"?".env.production":`.env.${deployEnvName}`;if(existsSync(p.projectPath(envFile)))try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:!0,quiet:!0})}catch(error){log.debug(`Could not load ${envFile} for preview: ${getErrorMessage(error)}`)}const tsCloudConfig=await loadTsCloudConfig(deployEnvName),{resolveSiteKind}=await loadTsCloudDeployApi(),unbacked=tsCloudConfig?findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination()):[];let plan;try{plan=createDeploymentPreview({config:tsCloudConfig,environment:deployEnvName,site:options.site,domain:options.domain,docker:options.docker===!0,fallbackProjectName:app.name,fallbackProjectSlug:app.name?.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"app",fallbackProvider:"aws",fallbackMode:tsCloudConfig?.mode||"server",fallbackRegion:process.env.AWS_REGION||"us-east-1",resolveSiteKind,applyEnvironmentToSites,warnings:unbacked.length>0?[unbackedDataMessage(unbacked)]:[]})}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(options.json||process.argv.includes("--json"))console.log(`${deploymentPreviewJsonPrefix}${JSON.stringify(plan)}`);else process.stdout.write(formatDeploymentPreview(plan));return}const automatedRevision=automatedDeploymentRevision(deployEnvName);automatedRevisionCheck=await assertCurrentDeploymentRevision(automatedRevision,p.projectPath());await ensureDeployPrerequisites(options.verbose===!0,deployEnvName);process.env.APP_ENV=deployEnvName;{const envFile=deployEnvName==="production"?".env.production":`.env.${deployEnvName}`;if(existsSync(p.projectPath(envFile)))try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:!0,quiet:!0})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}const tsCloudConfig=await loadTsCloudConfig(deployEnvName);if(tsCloudConfig&&resolveProvider(tsCloudConfig)==="fly"){await deployToFlyProvider(tsCloudConfig,deployEnvName,options.verbose===!0);return}if(tsCloudConfig&&isSshPipelineProvider(resolveProvider(tsCloudConfig))){await deployOverSsh(applyDeploymentDomainOverride(tsCloudConfig,options.domain),deployEnv,options);return}if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)delete process.env.AWS_PROFILE;const startTime=performance.now();console.log("");console.log("\uD83D\uDE80 Deploy");console.log("");let productionUrl;if(deployEnv==="production"||deployEnv==="prod"){productionUrl=(await resolveDeployEnvValues("production",tsCloudConfig)).APP_URL?.trim()||void 0;if(productionUrl)log.debug("Using APP_URL from .env.production:",productionUrl)}const envUrl=env.APP_URL,domain=options.domain||productionUrl||envUrl||app.url;if(deployEnvName==="production"&&!options.yes)await confirmProductionDeployment();if(!domain){log.info("No domain found in your .env.production or ./config/app.ts");log.info("Please ensure your domain is properly configured.");log.info("For more info, check out the docs or join our Discord.");process.exit(ExitCode.FatalError)}log.info(`Deploying to ${italic(domain)} (${deployEnv})`);await checkIfAwsIsBootstrapped(options);options.domain=await configureDomain(domain,options,startTime);const result=await runAction(Action.Deploy,options);if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Project deployed.",{startTime,useSeconds:!0})}));buddy.command("deploy:rollback [site]","Roll back a deployment to a preserved release").option("--env <environment>","Environment to roll back",{default:"production"}).option("--to <release>","Preserved release id to activate",{default:void 0}).option("--dry-run","Preview the rollback without changing the active release",{default:!1}).option("--all","Every configured site, instead of one",{default:!1}).option("--only-if-live <release>","Only roll back a site whose live release is this commit (what a failed deploy switched)",{default:void 0}).option("--verbose",descriptions.verbose,{default:!1}).action(async(site,options)=>{const exitCode=await runDeployRollback(site,options);if(exitCode!==ExitCode.Success)process.exit(exitCode)});buddy.command("deploy:preview <name>","Deploy a preview (e.g. pr-123) as its own tenant on the app's box, at <name>.<preview domain>").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await runPreviewCommand(name,options,"deploy")});buddy.command("deploy:preview:remove <name>","Remove a preview from the app's box: its services, gateway route, certificate, files and DNS records").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await runPreviewCommand(name,options,"remove")});onUnknownSubcommand(buddy,"deploy")}async function confirmProductionDeployment(){if(!process.stdin.isTTY){log.error("Refusing to deploy to production from a non-interactive shell without confirmation.");log.info(" \u27A1\uFE0F Re-run with `--yes` to confirm (e.g. in CI): `buddy deploy --prod --yes`");process.exit(ExitCode.InvalidArgument)}if(!await prompts.confirm({message:"Are you sure you want to deploy to production?",initial:!0})){log.info("Aborting deployment...");process.exit(ExitCode.InvalidArgument)}}async function configureDomain(domain,options,startTime){log.debug("Configuring domain...",domain);if(!domain){log.info("We could not identify a domain to deploy to.");log.warn("Please set your .env or ./config/app.ts properly.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(domain.includes("localhost")){log.info("You are deploying to a local environment.");log.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(await hasUserDomainBeenAddedToCloud(domain)){log.info("Domain is properly configured");log.info("Your cloud is deploying...");log.info(`${italic("This may take a while...")}`);return domain}console.log("");log.info(` \uD83D\uDC4B It appears to be your first ${italic(domain)} deployment.`);console.log("");log.info(italic("Let\u2019s ensure it is all connected properly."));log.info(italic("One moment..."));console.log("");const result=await addDomain({...options,deploy:!0,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}async function promptAndSaveCredentials(){const accessKeyId=await prompts.text({message:"AWS Access Key ID:",validate:(value)=>value.length>0?!0:"Access Key ID is required"});if(!accessKeyId){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const secretAccessKey=await prompts.password({message:"AWS Secret Access Key:",validate:(value)=>value.length>0?!0:"Secret Access Key is required"});if(!secretAccessKey){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const region=await prompts.text({message:"AWS Region:",initial:"us-east-1"});if(!region){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const{setEnv}=await import("@stacksjs/env");await setEnv("AWS_ACCESS_KEY_ID",accessKeyId,{file:".env.production"});await setEnv("AWS_SECRET_ACCESS_KEY",secretAccessKey,{file:".env.production"});await setEnv("AWS_REGION",region||"us-east-1",{file:".env.production"});process.env.AWS_ACCESS_KEY_ID=accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=secretAccessKey;process.env.AWS_REGION=region||"us-east-1";log.success("AWS credentials saved securely to .env.production");console.log("")}function loadAwsCredentialsFromEnv(){const 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))continue;try{const lines=readFileSync(envPath,"utf-8").split(`
470
+ if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execSync(`ssh ${sshArgs.map((a)=>`'${a}'`).join(" ")} bash -s`,{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]}),line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done",mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim(),mailHost=mailHostFromOut||`mail.${domain}`,dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||void 0,dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||void 0,dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) \u2014 rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy \u2014 nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])),migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])),updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[])),updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]),createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address)),created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]),unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():void 0}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud"),provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers),providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):void 0}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:void 0}export function postmasterHint(domain,postmaster){if(postmaster===!1)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase(),n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone),ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:!1};return{remove:ours,create:!0}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns"),own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`,cfg=emailConfig||{},firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address,fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:void 0,dmarcCfg=cfg.server?.dmarc||{},rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`,dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`,dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:void 0,postmasterCfg=cfg.server?.postmaster,postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):void 0;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production"),byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]})),provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(" Or add these records by hand at the DNS host:");logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)},declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return})),providerConfigs=dnsProviderConfigsFromEnv(declared),declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand("no configured DNS provider administers this zone");const apex=domain.toLowerCase(),dkimFqdn=`${dkimName}.${domain}`,dmarcFqdn=`_dmarc.${domain}`,mailFqdn=`mail.${domain}`,recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)},replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT"),{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===!1)throw Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX"),staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} \u2192 ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>!0);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain),anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX\u2192${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}\u2192${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites))if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""));const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it \u2014 upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved \u2014 skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId}),report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe});for(const record of report.records)logger.success(` ${record.host} ${record.type} \u2192 ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} \u2192 ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason} \u2014 re-run the deploy once TLS is issued.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN,accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||void 0,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN,accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||void 0,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);if(["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0)===0)return;for(const domain of configDnsDomains(sites))try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} \u2192 ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud"),result=await delegateZoneFromConfig(dns);for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[],{gatewayHostnames}=await import("@stacksjs/ts-cloud"),hostnames=gatewayHostnames(sites,{autoWww}),byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,""),group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig),providerConfigs=dnsProviderConfigsFromEnv(declared),declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/\u2026); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} \u2192 ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} \u2192 ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} \u2192 ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} \u2192 ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} \u2192 ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:!0,quiet:!0})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null,lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig),host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host),{sshExecOrThrow}=await import("@stacksjs/ts-cloud"),runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64"),privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud"),owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript()))),port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===!0,yes:!0},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
471
+ `,{flag:"a"})}async function removePreview(target,base,runRemote){log.info(`Removing preview ${target.slug} (${target.host})`);await runRemote(buildPreviewTeardownScript(target.slug,target.site));log.success(`Removed ${target.slug} from the box`);const tsCloudConfig=await loadTsCloudConfig(base).catch(()=>{return}),providerConfigs=dnsProviderConfigsFromEnv(declaredDnsProvider(tsCloudConfig)),zone=target.host,provider=providerConfigs.length>0?await resolveZoneDnsProvider(zone,providerConfigs,log):void 0;if(!provider)log.warn(`DNS: no configured provider manages ${zone}; remove the A/AAAA records for ${target.host} by hand.`);else{const{removeAddressRecords}=await import("@stacksjs/ts-cloud"),{removed,warnings}=await removeAddressRecords(provider,zone,target.host);for(const record of removed)log.success(`DNS: deleted ${record.type} ${target.host} (${provider.name})`);for(const warning of warnings)log.warn(`DNS: ${warning}`)}const pin=join(process.cwd(),"storage","cloud","state",`${target.slug}-${base}.json`);if(existsSync(pin)){const{rmSync}=await import("node:fs");rmSync(pin)}log.success(`Preview ${target.slug} removed`)}async function deployToFlyProvider(tsCloudConfig,environment,verbose){const{FlyDeployError,runFlyDeploy}=await import("./deploy-fly"),api=await loadTsCloudDeployApi();if(typeof api.deployToFly!=="function"){log.error("This @stacksjs/ts-cloud cannot deploy to Fly.io: upgrade it to 0.16.45 or newer.");process.exit(ExitCode.FatalError)}const{execSync}=await import("node:child_process");let release;try{release=execSync("git rev-parse --short=12 HEAD",{cwd:p.projectPath(),stdio:"pipe"}).toString().trim()}catch{release=`build-${Date.now()}`}const deployEnv=environment==="prod"?"production":environment;try{const result=await runFlyDeploy({config:tsCloudConfig,environment:deployEnv,token:process.env.FLY_API_TOKEN,release,envValues:await resolveDeployEnvValues(deployEnv,tsCloudConfig),projectRoot:p.projectPath()},{api,run:(command,options)=>{const child=Bun.spawnSync(command,{cwd:options.cwd,stdin:options.stdin===void 0?"inherit":new TextEncoder().encode(options.stdin),stdout:verbose?"inherit":"pipe",stderr:verbose?"inherit":"pipe"});return{exitCode:child.exitCode,output:`${child.stdout??""}${child.stderr??""}`}},exists:existsSync,log:(line)=>log.info(line)});log.success(`Deployed to ${result.url}`);if(result.untouched.length>0)log.warn(`Left ${result.untouched.length} Machine(s) the config no longer accounts for: ${result.untouched.join(", ")}. Remove them with \`fly machine destroy\` once nothing needs their data.`);for(const certificate of result.certificates){if(certificate.configured)continue;const needs=certificate.dns_requirements,target=needs?.cname?`a CNAME to ${needs.cname}`:[...needs?.a??[],...needs?.aaaa??[]].join(", ")||"Fly's addresses";log.info(`${certificate.hostname}: point it at ${target}; Fly issues the certificate once it resolves.`)}}catch(error){if(error instanceof FlyDeployError){log.error(error.message);if(error.hint)log.info(error.hint);process.exit(ExitCode.FatalError)}throw error}}async function buildContainerImageWithPantry(args){const{slug,sites,verbose}=args,{execSync}=await import("node:child_process");let cli;for(const candidate of["pantry","ts-pantry"])try{execSync(`command -v ${candidate}`,{stdio:"pipe"});cli=candidate;break}catch{}if(!cli){log.warn("pantry CLI not found on PATH - skipping container image build. Install pantry to enable `--docker`.");return}const dockerfile="storage/framework/Dockerfile",canPush=Boolean(process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN);for(const[siteName,site]of Object.entries(sites)){if(!site?.start)continue;const tag=`${slug}-${siteName}:latest`;log.info(`[${siteName}] building image ${tag} with pantry (native, no Docker daemon)...`);const flags=["build",".","-t",tag,"-f",dockerfile,"--run-mode","skip"];if(canPush)flags.push("--push");execSync(`${cli} ${flags.map((f)=>f.includes(" ")?`'${f}'`:f).join(" ")}`,{stdio:verbose?"inherit":"pipe",maxBuffer:536870912});log.success(`[${siteName}] image built${canPush?" + pushed to the pantry registry":""}`)}}export function deploy(buddy){const descriptions={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};buddy.command("deploy [env]",descriptions.deploy).option("--domain <domain>",descriptions.domain,{default:void 0}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--prod",descriptions.production,{default:!1}).option("--dev",descriptions.development,{default:!1}).option("--yes",descriptions.yes,{default:!1}).option("--site <name>","Deploy only this one site to the existing server (multi-tenant surgical add)",{default:void 0}).option("--staging",descriptions.staging,{default:!1}).option("--dry-run","Preview the deployment and change nothing",{default:!1}).option("--docker","Also build an OCI image with pantry (native, no Docker daemon) and push it to the pantry registry",{default:!1}).option("-J, --json","Emit a machine-readable deployment preview",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(withDeployNotification(async(envArg,options)=>{log.debug("Running `buddy deploy` ...",options);const askedForDryRun=process.argv.includes("--dry-run")||options.dryRun===!0,optionEnvironment=options.env,deployEnvName=resolveDeploymentEnvironment({positional:envArg,option:optionEnvironment,staging:options.staging,development:options.dev}),deployEnv=deployEnvName;try{applyDeploymentDomainOverride({},options.domain)}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(askedForDryRun){process.env.APP_ENV=deployEnvName;const envFile=deployEnvName==="production"?".env.production":`.env.${deployEnvName}`;if(existsSync(p.projectPath(envFile)))try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:!0,quiet:!0})}catch(error){log.debug(`Could not load ${envFile} for preview: ${getErrorMessage(error)}`)}const tsCloudConfig=await loadTsCloudConfig(deployEnvName),{resolveSiteKind}=await loadTsCloudDeployApi(),unbacked=tsCloudConfig?findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination()):[];let plan;try{plan=createDeploymentPreview({config:tsCloudConfig,environment:deployEnvName,site:options.site,domain:options.domain,docker:options.docker===!0,fallbackProjectName:app.name,fallbackProjectSlug:app.name?.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"app",fallbackProvider:"aws",fallbackMode:tsCloudConfig?.mode||"server",fallbackRegion:process.env.AWS_REGION||"us-east-1",resolveSiteKind,applyEnvironmentToSites,warnings:unbacked.length>0?[unbackedDataMessage(unbacked)]:[]})}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(options.json||process.argv.includes("--json"))console.log(`${deploymentPreviewJsonPrefix}${JSON.stringify(plan)}`);else process.stdout.write(formatDeploymentPreview(plan));return}await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const automatedRevision=automatedDeploymentRevision(deployEnvName);automatedRevisionCheck=await assertCurrentDeploymentRevision(automatedRevision,p.projectPath());await ensureDeployPrerequisites(options.verbose===!0,deployEnvName);process.env.APP_ENV=deployEnvName;{const envFile=deployEnvName==="production"?".env.production":`.env.${deployEnvName}`;if(existsSync(p.projectPath(envFile)))try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:!0,quiet:!0})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}const tsCloudConfig=await loadTsCloudConfig(deployEnvName);if(tsCloudConfig&&resolveProvider(tsCloudConfig)==="fly"){await deployToFlyProvider(tsCloudConfig,deployEnvName,options.verbose===!0);return}if(tsCloudConfig&&isSshPipelineProvider(resolveProvider(tsCloudConfig))){await deployOverSsh(applyDeploymentDomainOverride(tsCloudConfig,options.domain),deployEnv,options);return}if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY)delete process.env.AWS_PROFILE;const startTime=performance.now();console.log("");console.log("\uD83D\uDE80 Deploy");console.log("");let productionUrl;if(deployEnv==="production"||deployEnv==="prod"){productionUrl=(await resolveDeployEnvValues("production",tsCloudConfig)).APP_URL?.trim()||void 0;if(productionUrl)log.debug("Using APP_URL from .env.production:",productionUrl)}const envUrl=env.APP_URL,domain=options.domain||productionUrl||envUrl||app.url;if(deployEnvName==="production"&&!options.yes)await confirmProductionDeployment();if(!domain){log.info("No domain found in your .env.production or ./config/app.ts");log.info("Please ensure your domain is properly configured.");log.info("For more info, check out the docs or join our Discord.");process.exit(ExitCode.FatalError)}log.info(`Deploying to ${italic(domain)} (${deployEnv})`);await checkIfAwsIsBootstrapped(options);options.domain=await configureDomain(domain,options,startTime);const result=await runAction(Action.Deploy,options);if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Project deployed.",{startTime,useSeconds:!0})}));buddy.command("deploy:rollback [site]","Roll back a deployment to a preserved release").option("--env <environment>","Environment to roll back",{default:"production"}).option("--to <release>","Preserved release id to activate",{default:void 0}).option("--dry-run","Preview the rollback without changing the active release",{default:!1}).option("--all","Every configured site, instead of one",{default:!1}).option("--only-if-live <release>","Only roll back a site whose live release is this commit (what a failed deploy switched)",{default:void 0}).option("--verbose",descriptions.verbose,{default:!1}).action(async(site,options)=>{const exitCode=await runDeployRollback(site,options);if(exitCode!==ExitCode.Success)process.exit(exitCode)});buddy.command("deploy:preview <name>","Deploy a preview (e.g. pr-123) as its own tenant on the app's box, at <name>.<preview domain>").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await runPreviewCommand(name,options,"deploy")});buddy.command("deploy:preview:remove <name>","Remove a preview from the app's box: its services, gateway route, certificate, files and DNS records").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{await runPreviewCommand(name,options,"remove")});onUnknownSubcommand(buddy,"deploy")}async function confirmProductionDeployment(){if(!process.stdin.isTTY){log.error("Refusing to deploy to production from a non-interactive shell without confirmation.");log.info(" \u27A1\uFE0F Re-run with `--yes` to confirm (e.g. in CI): `buddy deploy --prod --yes`");process.exit(ExitCode.InvalidArgument)}if(!await prompts.confirm({message:"Are you sure you want to deploy to production?",initial:!0})){log.info("Aborting deployment...");process.exit(ExitCode.InvalidArgument)}}async function configureDomain(domain,options,startTime){log.debug("Configuring domain...",domain);if(!domain){log.info("We could not identify a domain to deploy to.");log.warn("Please set your .env or ./config/app.ts properly.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(domain.includes("localhost")){log.info("You are deploying to a local environment.");log.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" \u27A1\uFE0F Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(await hasUserDomainBeenAddedToCloud(domain)){log.info("Domain is properly configured");log.info("Your cloud is deploying...");log.info(`${italic("This may take a while...")}`);return domain}console.log("");log.info(` \uD83D\uDC4B It appears to be your first ${italic(domain)} deployment.`);console.log("");log.info(italic("Let\u2019s ensure it is all connected properly."));log.info(italic("One moment..."));console.log("");const result=await addDomain({...options,deploy:!0,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}async function promptAndSaveCredentials(){const accessKeyId=await prompts.text({message:"AWS Access Key ID:",validate:(value)=>value.length>0?!0:"Access Key ID is required"});if(!accessKeyId){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const secretAccessKey=await prompts.password({message:"AWS Secret Access Key:",validate:(value)=>value.length>0?!0:"Secret Access Key is required"});if(!secretAccessKey){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const region=await prompts.text({message:"AWS Region:",initial:"us-east-1"});if(!region){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const{setEnv}=await import("@stacksjs/env");await setEnv("AWS_ACCESS_KEY_ID",accessKeyId,{file:".env.production"});await setEnv("AWS_SECRET_ACCESS_KEY",secretAccessKey,{file:".env.production"});await setEnv("AWS_REGION",region||"us-east-1",{file:".env.production"});process.env.AWS_ACCESS_KEY_ID=accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=secretAccessKey;process.env.AWS_REGION=region||"us-east-1";log.success("AWS credentials saved securely to .env.production");console.log("")}function loadAwsCredentialsFromEnv(){const 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))continue;try{const lines=readFileSync(envPath,"utf-8").split(`
467
472
  `);let accessKeyId,secretAccessKey,region,accountId;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("="),value=valueParts.join("=").trim();if(key==="AWS_ACCESS_KEY_ID"&&value)accessKeyId=value;else if(key==="AWS_SECRET_ACCESS_KEY"&&value)secretAccessKey=value;else if(key==="AWS_REGION"&&value)region=value;else if(key==="AWS_ACCOUNT_ID"&&value)accountId=value}if(accessKeyId&&secretAccessKey){log.debug(`Found AWS credentials in ${envPath}`);return{accessKeyId,secretAccessKey,region,accountId}}}catch(error){log.debug(`Failed to read ${envPath} file:`,error)}}return{}}async function checkIfAwsIsBootstrapped(options){let handlingAlreadyExists=!1;try{log.info("Ensuring AWS cloud stack exists...");let hasCredentials=process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY;if(!hasCredentials){const envCredentials=loadAwsCredentialsFromEnv();if(envCredentials.accessKeyId&&envCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=envCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=envCredentials.secretAccessKey;if(envCredentials.region&&!process.env.AWS_REGION)process.env.AWS_REGION=envCredentials.region;if(envCredentials.accountId&&!process.env.AWS_ACCOUNT_ID)process.env.AWS_ACCOUNT_ID=envCredentials.accountId;hasCredentials=!0;const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";log.success(`Using AWS credentials from .env.${environment}`)}}if(!hasCredentials){const fileCredentials=loadAwsCredentialsFromFile();if(fileCredentials.accessKeyId&&fileCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=fileCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=fileCredentials.secretAccessKey;if(fileCredentials.region&&!process.env.AWS_REGION)process.env.AWS_REGION=fileCredentials.region;hasCredentials=!0;log.success("Using AWS credentials from ~/.aws/credentials")}}if(!hasCredentials){log.info("AWS credentials not found in .env or ~/.aws/credentials.");log.info("You can either:");log.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production");log.info(" 2. Add credentials to ~/.aws/credentials");log.info(" 3. Configure them interactively below");console.log("");if(options?.yes){log.info("Skipping credential setup (--yes flag provided)");process.exit(ExitCode.FatalError)}const setupCredentials=await prompts.confirm({message:"Would you like to configure AWS credentials now?",initial:!0});log.debug("setupCredentials response:",setupCredentials,typeof setupCredentials);if(setupCredentials===void 0||setupCredentials===!1){if(setupCredentials===void 0){console.log("");log.info("Deployment cancelled");process.exit(ExitCode.Success)}console.log("");log.info("Skipping cloud infrastructure check");log.info("You can configure AWS credentials later by running: buddy configure:aws");return!0}await promptAndSaveCredentials()}else log.success("AWS credentials found");const appName=(process.env.APP_NAME||app.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),stackName=await stacksCloudName(),{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),cfnClient=new AWSCloudFormationClient(await stacksCloudRegion());let stackExists=!1,needsEmailUpdate=!1;try{const stack=(await cfnClient.describeStacks({stackName})).Stacks?.[0];if(stack){stackExists=!0;log.success("Cloud stack exists");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),resources=await new AWSCloudFormationClient(process.env.AWS_REGION||"us-east-1").listStackResources(stackName),hasEmailBucket=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailBucket"),hasOutboundLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="OutboundEmailLambda"),hasConversionLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailConversionLambda"),hasNotificationTopic=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailNotificationTopic"),hasMailApiLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailApiLambda"),hasMailUsersTable=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailUsersTable"),hasMailServerInstance=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailServerInstance"),currentEmailDomain=stack.Outputs?.find((o)=>o.OutputKey==="EmailDomain")?.OutputValue,configuredDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:void 0)||"stacksjs.com";if(!hasEmailBucket&&emailConfig?.server?.scan!==void 0){log.info("Email infrastructure not found in stack, will update...");needsEmailUpdate=!0}else if(currentEmailDomain&&currentEmailDomain!==configuredDomain){log.info(`Email domain changed: ${currentEmailDomain} -> ${configuredDomain}, will update...`);needsEmailUpdate=!0}else if(hasEmailBucket&&(!hasOutboundLambda||!hasConversionLambda||!hasNotificationTopic)){log.info("Email infrastructure incomplete, will update...");needsEmailUpdate=!0}else if(hasEmailBucket&&(!hasMailApiLambda||!hasMailUsersTable)){log.info("Mail API infrastructure missing, will update...");needsEmailUpdate=!0}else if(hasEmailBucket&&!hasMailServerInstance&&emailConfig?.server?.enabled){log.info("Mail server EC2 instance missing, will update...");needsEmailUpdate=!0}const currentMode=(stack.Outputs||[]).find((o)=>o.OutputKey==="MailServerMode")?.OutputValue,configuredMode=emailConfig?.server?.mode||"serverless";if(currentMode&&currentMode!==configuredMode){log.info(`Mail server mode changed: ${currentMode} -> ${configuredMode}, will update...`);needsEmailUpdate=!0}if(hasMailServerInstance&&emailConfig?.server?.enabled){if(process.env.FORCE_MAIL_UPDATE==="true"){log.info("Forcing mail server update...");needsEmailUpdate=!0}}if(!needsEmailUpdate)return!0}}catch(error){const caught=error&&typeof error==="object"?error:{message:String(error)};log.debug(`Stack not found: ${getErrorMessage(error)}`)}if(!stackExists)log.info("Cloud stack not found, will be created by deploy action");return!0}catch(err){if(!handlingAlreadyExists){log.error("Error checking cloud infrastructure");log.error(`Error: ${getErrorMessage(err)}`);if(options?.verbose)console.error(err)}process.exit(ExitCode.FatalError)}}
@@ -1 +1 @@
1
- import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,getEnv,getKeypair,resolveEnvFile,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:!1}).option("-t, --pretty",descriptions.pretty,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").action(async(key,value,options)=>{log.debug("Running `buddy env:set` ...",options);if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(value===void 0){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}const result=setEnv(key,value,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:!1}).option("--dry-run",descriptions.rotateDryRun,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli"),{storage}=await import("@stacksjs/storage"),{existsSync}=await import("node:fs"),{resolve}=await import("node:path");await intro("buddy env:check");const checks=[],envFile=options.file||".env",envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath),contentStr=typeof envContent==="string"?envContent:envContent.data,values=parseEnvAssignments(contentStr),keys=Object.keys(values),varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});if("APP_KEY"in values)if((values.APP_KEY??"").length>0)checks.push({name:"APP_KEY",status:"pass",message:"Set"});else checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"});else checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"});const hasPublicKey=keys.some((key)=>key.startsWith("DOTENV_PUBLIC_KEY")),hasPrivateKey=keys.some((key)=>key.startsWith("DOTENV_PRIVATE_KEY"))||existsSync(resolve(process.cwd(),".env.keys"));if(hasPublicKey&&hasPrivateKey)checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"});else if(hasPublicKey||hasPrivateKey)checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"});else checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"});const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0)checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"});else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env"),foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants)),isShipped=/^\.env\.[a-z]+$/.test(envFile),total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0)checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`});else if(!isShipped)checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`});else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign)checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");if(!trackedEnvFiles(gitLsFiles()).includes(envFile))checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`});else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const leaked=plaintextSecrets(values,{placeholders,strict:options.strict});if(leaked.length===0)checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`});else checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else checks.push({name:`${envFile} file`,status:"fail",message:"Not found"});const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath))checks.push({name:".env.keys file",status:"pass",message:"Found"});else checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"});console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("\u2500".repeat(60)));console.log("");let hasFailures=!1,hasWarnings=!1;for(const check of checks){let statusIcon="",statusColor=(text)=>text;if(check.status==="pass"){statusIcon="\u2713";statusColor=green}else if(check.status==="warn"){statusIcon="\u26A0";statusColor=yellow;hasWarnings=!0}else{statusIcon="\u2717";statusColor=red;hasFailures=!0}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("\u2500".repeat(60)));console.log("");if(hasFailures){console.log(red("\u2717 Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("\u26A0 Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("\u2713 All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config"),{cloud,app}=config,tenants=Array.isArray(cloud?.tenants)?cloud.tenants.filter((slug)=>typeof slug==="string"):[];return{self:app?.name,tenants}}catch{return{tenants:[]}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={},assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i,lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:void 0;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else raw=raw.replace(/\s+#.*$/,"").trim();values[key]=raw}return values}
1
+ import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:!1}).option("-t, --pretty",descriptions.pretty,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:!1}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==void 0){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===void 0){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:!1}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:!1}).option("--dry-run",descriptions.rotateDryRun,{default:!1}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli"),{storage}=await import("@stacksjs/storage"),{existsSync}=await import("node:fs"),{resolve}=await import("node:path");await intro("buddy env:check");const checks=[],envFile=resolveEnvFile(options.file,options.env)||".env",envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath),contentStr=typeof envContent==="string"?envContent:envContent.data,values=parseEnvAssignments(contentStr),varCount=Object.keys(values).length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});if("APP_KEY"in values)if((values.APP_KEY??"").length>0)checks.push({name:"APP_KEY",status:"pass",message:"Set"});else checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"});else checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"});const{publicKeyName,privateKeyName}=envKeyNames(envFile),privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"],publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY,hasPublicKey=Boolean(publicKey),privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean),hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey))checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`});if(hasPublicKey&&hasPrivateKey)checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"});else if(hasPublicKey||hasPrivateKey)checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"});else checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"});const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0)checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"});else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env"),foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants)),isShipped=/^\.env\.[a-z]+$/.test(envFile),total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0)checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`});else if(!isShipped)checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`});else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign)checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");if(!trackedEnvFiles(gitLsFiles()).includes(envFile))checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`});else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict}),metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material"),leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length)checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`});if(leaked.length===0)checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`});else checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else checks.push({name:`${envFile} file`,status:"fail",message:"Not found"});const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath))checks.push({name:".env.keys file",status:"pass",message:"Found"});else checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"});console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("\u2500".repeat(60)));console.log("");let hasFailures=!1,hasWarnings=!1;for(const check of checks){let statusIcon="",statusColor=(text)=>text;if(check.status==="pass"){statusIcon="\u2713";statusColor=green}else if(check.status==="warn"){statusIcon="\u26A0";statusColor=yellow;hasWarnings=!0}else{statusIcon="\u2717";statusColor=red;hasFailures=!0}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("\u2500".repeat(60)));console.log("");if(hasFailures){console.log(red("\u2717 Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("\u26A0 Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("\u2713 All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config"),{cloud,app}=config,tenants=Array.isArray(cloud?.tenants)?cloud.tenants.filter((slug)=>typeof slug==="string"):[];return{self:app?.name,tenants}}catch{return{tenants:[]}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={},assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i,lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:void 0;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else raw=raw.replace(/\s+#.*$/,"").trim();values[key]=raw}return values}
@@ -58,7 +58,7 @@ var {require}=import.meta;import{log}from"@stacksjs/cli";import{ExitCode}from"@s
58
58
  `;if(spawnSync("/usr/bin/swift",["-e",keychainWriter],{input:`${encoded}
59
59
  `,maxBuffer:1048576}).status!==0)throw Error("macOS Keychain write failed");console.log(`keychain_service=${service}`);console.log("recovery_keyslot=verified");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to add recovery key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{currentKey?.fill(0);recoveryKey?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:recovery:verify","Verify the Keychain recovery key against the live LUKS header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options);key=readMailRecoveryKey();runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log("Keychain recovery key unlocks the live mail volume.");process.exit(ExitCode.Success)}catch(error){console.error(`Recovery key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:key:slot:remove","Remove an unusable non-primary LUKS keyslot")).option("--slot <number>","LUKS keyslot number to remove").action(async(options)=>{let key;try{const slot=Number.parseInt(options.slot||"",10);if(!Number.isInteger(slot)||slot<1||slot>31)throw Error("Pass a non-primary keyslot from 1 through 31.");const host=await mailStorageHost(options);key=(await getMailStorageSecret(options)).key;const output=runMailStorageSsh(host,`${mailStorageRemote} remove-keyslot ${slot}`,key).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to remove LUKS keyslot: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:restic:configure","Configure client-encrypted Restic backups to S3")).option("--force","Rotate an existing dedicated IAM access key",{default:!1}).action(async(options)=>{try{const result=await configureMailRestic(options);console.log(`repository=${result.repository}`);console.log(`recovery_secret=${result.secretId}`);console.log("restore_check=ok");process.exit(ExitCode.Success)}catch(error){console.error(`Failed to configure Restic mail backups: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:restore:check","Restore and validate the newest off-host mail snapshot")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,"/usr/local/sbin/mail-restic-restore-check").toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Mail restore check failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:maildir:migrate","Migrate live mailboxes to canonical Maildir++ layout")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate migrate").toString("utf8").trim();console.log(output);const status=runMailStorageSsh(host,"/usr/local/sbin/maildir-migrate status").toString("utf8").trim();console.log(status);process.exit(ExitCode.Success)}catch(error){console.error(`Maildir++ migration failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:forward:compile","Compile and validate the live RFC 5228 forwarding script")).action(async(options)=>{try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,'/usr/local/sbin/mail-forward-compile /opt/mail/forwards.json /opt/mail/forwards.sieve && sed -n "1,160p" /opt/mail/forwards.sieve').toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Forwarding script compilation failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:escrow","Copy the machine-bound LUKS key to AWS Secrets Manager")).option("--force","Replace a different existing secret",{default:!1}).action(async(options)=>{try{const result=await escrowMailStorageKey(options);console.log(`Mail storage key verified in AWS Secrets Manager: ${result.secretId}`);console.log(`Host: ${result.host}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to escrow mail storage key: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:key:verify","Verify the external key against the LUKS2 header")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;runMailStorageSsh(host,"cryptsetup open --test-passphrase --type luks2 --key-file - /var/lib/mail-storage.luks",key);console.log(`External key ${secret.secretId} unlocks the mail volume.`);process.exit(ExitCode.Success)}catch(error){console.error(`Mail storage key verification failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:unlock","Unlock external mail storage and start mail")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,`${mailStorageRemote} unlock`,key).toString("utf8").trim();console.log(output);console.log(`External key: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to unlock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:machine-bind","Enable unattended reboot recovery with a machine-bound encrypted LUKS credential")).action(async(options)=>{let key;try{const host=await mailStorageHost(options),secret=await getMailStorageSecret(options);key=secret.key;const output=runMailStorageSsh(host,machineBindMailStorageCommand(),key).toString("utf8").trim();if(output)console.log(output);const status=runMailStorageSsh(host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`Recovery secret retained: ${secret.secretId}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to machine-bind mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});addMailStorageOptions(buddy.command("mail:storage:lock","Stop mail and lock external mail storage")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,`${mailStorageRemote} lock`).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to lock mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:backup","Create and verify an encrypted local mail backup")).action(async(options)=>{loadEnvFiles();try{const host=await mailStorageHost(options),output=runMailStorageSsh(host,["set -eu","systemctl reset-failed mail-backup.service 2>/dev/null || true","systemctl start mail-backup.service",'latest=$(find -L /opt/mail/backups -maxdepth 1 -type f -name "mail-backup-*.tgz" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-)','test -n "$latest"','tar -tzf "$latest" >/dev/null','printf "backup=%s\\n" "$latest"','stat -c "mode=%a owner=%U:%G size=%s" "$latest"'].join("; ")).toString("utf8").trim();console.log(output);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to create mail backup: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:header:backup","Stream a LUKS header backup to S3 with KMS encryption")).option("--bucket <bucket>","Recovery bucket (defaults to <app>-<env>-s3-backups)").action(async(options)=>{try{const{region}=loadMailStorageAws(options),host=await mailStorageHost(options),app=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-"),environment=(process.env.APP_ENV||"production").toLowerCase().replace(/[^a-z0-9-]/g,"-"),bucket=options.bucket||`${app}-${environment}-s3-backups`;if(!/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/.test(bucket))throw Error(`Unsafe S3 bucket name: ${bucket}`);const objectKey=`luks-headers/mail-storage-${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}.header`,{AWSClient}=await import("@stacksjs/cloud"),{S3Client}=await import("@stacksjs/cloud"),kms=await ensureMailKmsKey(options),s3=new S3Client(region);await s3.putBucketEncryption(bucket,"aws:kms",kms.arn);const uploadUrl=s3.generatePresignedPutUrl(bucket,objectKey,"application/octet-stream",600),remoteCommand=["set -eu","tmp_dir=$(mktemp -d /run/mail-storage-header.XXXXXX)",'tmp="$tmp_dir/header"',`trap 'shred -u "$tmp" 2>/dev/null || rm -f "$tmp"; rmdir "$tmp_dir"' EXIT`,'cryptsetup luksHeaderBackup /var/lib/mail-storage.luks --header-backup-file "$tmp"',`curl --fail-with-body --silent --show-error -H 'Content-Type: application/octet-stream' --upload-file "$tmp" ${shellQuote(uploadUrl)} 1>&2`].join("; ");runMailStorageSsh(host,remoteCommand);const object=await s3.headObject(bucket,objectKey);if(!object?.ContentLength||object.ContentLength<1048576)throw Error("The uploaded LUKS header size did not verify.");const head=await new AWSClient().request({service:"s3",region,method:"HEAD",path:`/${bucket}/${objectKey}`,returnHeaders:!0}),encryption=head?.headers?.["x-amz-server-side-encryption"];if(encryption!=="aws:kms")throw Error(`The LUKS header object reported unexpected encryption: ${encryption||"none"}`);const keyId=head?.headers?.["x-amz-server-side-encryption-aws-kms-key-id"];if(keyId!==kms.arn)throw Error(`The LUKS header object used an unexpected KMS key: ${keyId||"none"}`);console.log(`header=s3://${bucket}/${objectKey}`);console.log("encryption=aws:kms");console.log(`kms_key=${kms.arn}`);process.exit(ExitCode.Success)}catch(error){console.error(`Failed to back up the LUKS header: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});addMailStorageOptions(buddy.command("mail:storage:externalize","Move the LUKS key off-host and require external unlocks")).option("--force","Replace a different existing secret",{default:!1}).action(async(options)=>{let configured=!1,key;try{const escrow=await escrowMailStorageKey(options);key=(await getMailStorageSecret(options)).key;runMailStorageSsh(escrow.host,`${mailStorageRemote} configure-external`);configured=!0;runMailStorageSsh(escrow.host,`${mailStorageRemote} unlock`,key);runMailStorageSsh(escrow.host,`${mailStorageRemote} finalize-external`);const status=runMailStorageSsh(escrow.host,`${mailStorageRemote} status`).toString("utf8").trim();console.log(status);console.log(`External key: ${escrow.secretId}`);process.exit(ExitCode.Success)}catch(error){if(configured)try{const host=await mailStorageHost(options);runMailStorageSsh(host,`${mailStorageRemote} rollback-machine`)}catch(rollbackError){console.error(`Automatic rollback also failed: ${getErrorMessage(rollbackError)}`)}console.error(`Failed to externalize mail storage: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}finally{key?.fill(0)}});buddy.command("mail:user:add <email>","Add a mail user").option("--password <password>","Deprecated: use --password-stdin to avoid exposing secrets in process arguments").option("--password-stdin","Read the mailbox password from standard input without printing it").action(async(email,options)=>{try{const settings=await mailboxUserSettings();resolveMailUserBackend(settings);if(options.password!==void 0||!options.passwordStdin||process.stdin.isTTY)throw Error("Pipe a password from your secret manager using --password-stdin. Password arguments and generated credential output are no longer supported.");await addMailUser(email,await Bun.stdin.text(),settings);log.success(`User ${email} added successfully!`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to add user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:list","List mail users").action(async()=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings()),result=await client.scan({TableName:table});console.log("");console.log("Mail Users:");console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");if(!result.Items||result.Items.length===0)console.log(" No users found");else for(const item of result.Items){const email=item.email?.S||"unknown",createdAt=item.createdAt?.S||"unknown";console.log(` \uD83D\uDCE7 ${email}`);console.log(` Created: ${createdAt}`)}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to list users: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:user:delete <email>","Delete a mail user").action(async(email)=>{try{const{client,table}=await mailUserClient(await mailboxUserSettings());await client.deleteItem({TableName:table,Key:{email:{S:email.toLowerCase()}}});log.success(`User ${email} deleted`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to delete user: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:proxy","Start local IMAP proxy for Mail.app").option("--port <port>","IMAP proxy port",{default:"1993"}).option("--api <url>","Mail API URL").action(async(options)=>{log.info("Starting IMAP proxy...");try{let apiUrl=options.api;if(!apiUrl){const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),cfn=new AWSCloudFormationClient(await stacksCloudRegion()),stackName=await stacksCloudName();try{apiUrl=((await cfn.describeStacks({stackName})).Stacks?.[0]?.Outputs||[]).find((o)=>o.OutputKey==="MailApiUrl")?.OutputValue}catch(e){}}if(!apiUrl){await log.error("Mail API URL not found. Run `buddy deploy` first to create the mail infrastructure.");process.exit(ExitCode.FatalError)}console.log("");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log(" IMAP PROXY");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");console.log(` API URL: ${apiUrl}`);console.log(` Port: ${options.port}`);console.log("");console.log(" Configure Mail.app with:");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(" Account Type: IMAP");console.log(" Incoming Server: localhost");console.log(` Incoming Port: ${options.port}`);console.log(" SSL: No (local connection)");console.log(" Outgoing Server: localhost");console.log(` Outgoing Port: ${options.port}`);console.log(" Username: your-email@stacksjs.com");console.log(" Password: your-password");console.log("\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550");console.log("");process.env.MAIL_API_URL=apiUrl;process.env.IMAP_PORT=options.port;const{ImapProxy}=await import("../../mail-server/src/proxy/imap-proxy"),proxy=new ImapProxy(Number.parseInt(options.port,10),apiUrl);await proxy.start();process.on("SIGINT",()=>{console.log(`
60
60
  Shutting down proxy...`);proxy.stop();process.exit(0)})}catch(error){await log.error(`Failed to start proxy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:test","Test mail API connection").action(async()=>{try{const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud"),{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud"),cfn=new AWSCloudFormationClient(await stacksCloudRegion()),stackName=await stacksCloudName(),mailApiOutput=((await cfn.describeStacks({stackName})).Stacks?.[0]?.Outputs||[]).find((o)=>o.OutputKey==="MailApiUrl");if(!mailApiOutput?.OutputValue){await log.error("Mail API not deployed. Run `buddy deploy` first.");process.exit(ExitCode.FatalError)}const apiUrl=mailApiOutput.OutputValue;log.info(`Testing Mail API at ${apiUrl}`);const response=await fetch(`${apiUrl}/mailboxes`,{headers:{Authorization:`Basic ${Buffer.from("test@stacksjs.com:test").toString("base64")}`}});if(response.status===401)log.success("Mail API is responding (auth required)");else if(response.ok){log.success("Mail API is working!");const data=await response.json();console.log("Response:",JSON.stringify(data,null,2))}else log.warn(`Mail API returned status ${response.status}`);await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to test API: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:credentials [email]","Show SMTP credentials for email access").action(async(emailAddress)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",mailHost=`mail.${domain}`,email=emailAddress||`chris@${domain}`,localPart=email.includes("@")?email.split("@")[0]:email,username=email,envKey=`MAIL_PASSWORD_${localPart.toUpperCase().replace(/[^A-Z0-9]/g,"_")}`,rawPassword=process.env[envKey],isCiphertext=typeof rawPassword==="string"&&rawPassword.replace(/^["']/,"").startsWith("encrypted:"),password=isCiphertext?void 0:rawPassword;console.log("");console.log("==========================================================");console.log(` EMAIL CREDENTIALS - ${email}`);console.log("==========================================================");console.log("");console.log(` Email: ${email}`);console.log(` Host: ${mailHost}`);console.log(" Port: 587");console.log(" Security: STARTTLS");console.log(` Username: ${username}`);if(password)console.log(` Password: ${password}`);else if(isCiphertext)console.log(" Password: (encrypted - this machine has no private key for .env.production)");else console.log(` Password: (not set - add ${envKey} to .env.production)`);console.log("");console.log("==========================================================");console.log("");process.exit(ExitCode.Success)});buddy.command("mail:logs","Show mail server logs from production").option("-n, --lines <count>","Number of log lines to show",{default:"50"}).option("-f, --follow","Follow log output (poll every 5s)").option("--filter <pattern>","Filter logs by pattern (e.g. AUTH, LOGIN, error)").action(async(options)=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const lines=sanitizeLineCount(options.lines),filter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"",command=`journalctl -u mail --no-pager -n ${lines}${filter?` | grep -iE ${shellQuote(filter)}`:""}`;try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs from ${directHost}: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region);log.info("Finding mail server...");const instanceId=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}log.info(`Found instance: ${instanceId}`);const lines=sanitizeLineCount(options.lines),sanitizedFilter=options.filter?options.filter.replace(/[^a-zA-Z0-9_.@\s-]/g,""):"",filterCmd=sanitizedFilter?` | grep -iE '${sanitizedFilter}'`:"",fetchLogs=async()=>{const cmd=`journalctl -u smtp-server -u mail-server --no-pager -n ${lines} --since "10 minutes ago" 2>&1${filterCmd}`,result=await ssm.runShellCommand(instanceId,[cmd],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});if(!result.success){log.error(`Failed to fetch logs: ${result.error||"Unknown error"}`);return!1}if(result.output){const logLines=result.output.trim().split(`
61
- `);for(const line of logLines)if(line.includes("error")||line.includes("Error")||line.includes("AUTH failed"))console.log(` \x1B[31m${line}\x1B[0m`);else if(line.includes("warning")||line.includes("Warning"))console.log(` \x1B[33m${line}\x1B[0m`);else if(line.includes("AUTH success")||line.includes("LOGIN completed")||line.includes("authenticated"))console.log(` \x1B[32m${line}\x1B[0m`);else console.log(` ${line}`)}else console.log(" No log entries found.");return!0};console.log("");console.log("==========================================================");console.log(" MAIL SERVER LOGS");console.log("==========================================================");console.log("");await fetchLogs();if(options.follow){console.log("");log.info("Following logs (Ctrl+C to stop)...");let polling=!1;const poll=setInterval(()=>{if(polling)return;polling=!0;console.log("");fetchLogs().catch((e)=>log.error("Log polling failed:",e)).finally(()=>{polling=!1})},5000);await new Promise((resolve)=>{process.on("SIGINT",()=>{clearInterval(poll);resolve()})})}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:status","Show mail server status").action(async()=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const command='systemctl is-active mail; systemctl show mail -p NRestarts -p ActiveEnterTimestamp --value; ss -H -ltn | grep -E "(:(25|143|465|587|993))\\b"; systemctl is-enabled mail-health.timer; systemctl is-active mail-health.timer';try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Mail server ${directHost} is unhealthy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region),instanceId=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}const result=await ssm.runShellCommand(instanceId,["echo === Service ===","(systemctl status smtp-server --no-pager 2>&1 || systemctl status mail-server --no-pager 2>&1) | head -15","echo === Ports ===",'ss -tlnp 2>&1 | grep -E "(25|587|465|993|143|110|995)" || echo "No mail ports listening"',"echo === Memory ===",`ps aux | grep -E "(smtp-server|bun|mail)" | grep -v grep | awk '{print $6/1024 "MB", $11}'`],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});console.log("");console.log("==========================================================");console.log(" MAIL SERVER STATUS");console.log("==========================================================");console.log("");if(result.success&&result.output)for(const line of result.output.trim().split(`
61
+ `);for(const line of logLines)if(line.includes("error")||line.includes("Error")||line.includes("AUTH failed"))console.log(` \x1B[31m${line}\x1B[0m`);else if(line.includes("warning")||line.includes("Warning"))console.log(` \x1B[33m${line}\x1B[0m`);else if(line.includes("AUTH success")||line.includes("LOGIN completed")||line.includes("authenticated"))console.log(` \x1B[32m${line}\x1B[0m`);else console.log(` ${line}`)}else console.log(" No log entries found.");return!0};console.log("");console.log("==========================================================");console.log(" MAIL SERVER LOGS");console.log("==========================================================");console.log("");await fetchLogs();if(options.follow){console.log("");log.info("Following logs (Ctrl+C to stop)...");let polling=!1;const poll=setInterval(()=>{if(polling)return;polling=!0;console.log("");fetchLogs().catch((e)=>log.error("Log polling failed:",e)).finally(()=>{polling=!1})},5000);await new Promise((resolve)=>{process.on("SIGINT",()=>{clearInterval(poll);resolve()})})}console.log("");process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to fetch logs: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:status","Show mail server status").action(async()=>{loadEnvFiles();const directHost=await resolveOperationalMailHost();if(directHost){const command='set -eu; systemctl is-active --quiet mail; systemctl is-enabled --quiet mail-health.timer; systemctl is-active --quiet mail-health.timer; test -x /usr/local/sbin/mail-protocol-health-check || { echo "Protocol monitoring is missing. Deploy the current mail release."; exit 1; }; systemctl start mail-health.service; systemctl show mail-health.service -p Result -p ExecMainStatus; cat /var/lib/mail-health/public/status.json';try{const output=execSync(`ssh -o BatchMode=yes -o ConnectTimeout=10 root@${shellQuote(directHost)} ${shellQuote(command)}`,{encoding:"utf8"});console.log(output);process.exit(ExitCode.Success)}catch(error){await log.error(`Mail server ${directHost} is unhealthy: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}}const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region),instanceId=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0]?.InstanceId;if(!instanceId){await log.error("No running mail server found.");log.info(`Looked for instances tagged: ${appName}-mail-server`);await log.flush();process.exit(ExitCode.FatalError)}const result=await ssm.runShellCommand(instanceId,["echo === Service ===","(systemctl status smtp-server --no-pager 2>&1 || systemctl status mail-server --no-pager 2>&1) | head -15","echo === Ports ===",'ss -tlnp 2>&1 | grep -E "(25|587|465|993|143|110|995)" || echo "No mail ports listening"',"echo === Memory ===",`ps aux | grep -E "(smtp-server|bun|mail)" | grep -v grep | awk '{print $6/1024 "MB", $11}'`],{timeoutSeconds:30,maxWaitMs:30000,pollIntervalMs:2000});console.log("");console.log("==========================================================");console.log(" MAIL SERVER STATUS");console.log("==========================================================");console.log("");if(result.success&&result.output)for(const line of result.output.trim().split(`
62
62
  `))console.log(` ${line}`);else log.error(`Failed: ${result.error}`);console.log("");await log.flush();process.exit(ExitCode.Success)}catch(error){await log.error(`Failed to get status: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:request","Request port 25 unblock for direct SMTP delivery").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).option("--instance-id <id>","AWS EC2 instance ID (auto-detected if not provided)").option("--server-id <id>","Hetzner server ID (auto-detected if not provided)").option("--elastic-ip <ip>","AWS Elastic IP address").option("--rdns <hostname>","Reverse DNS hostname (e.g. mail.stacksjs.com)").option("--use-case <text>","Description of email use case").action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",provider=options.provider.toLowerCase();if(provider==="aws")await requestAwsPort25(options,domain);else if(provider==="hetzner")await requestHetznerPort25(options,domain);else{await log.error(`Unknown provider: ${provider}. Use 'aws' or 'hetzner'.`);process.exit(ExitCode.FatalError)}});buddy.command("mail:port25:status","Check outbound port 25 status on the mail server").option("--provider <provider>","Cloud provider: aws or hetzner",{default:"aws"}).action(async(options)=>{loadEnvFiles();const region=process.env.AWS_REGION||"us-east-1",appName=(process.env.APP_NAME||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");if(options.provider==="hetzner"){const hetznerToken=process.env.HETZNER_API_TOKEN;if(!hetznerToken){await log.error("HETZNER_API_TOKEN not set");process.exit(ExitCode.FatalError)}try{const ip=(await(await fetch("https://api.hetzner.cloud/v1/servers?label_selector=service=mail",{headers:{Authorization:`Bearer ${hetznerToken}`}})).json()).servers?.[0]?.public_net?.ipv4?.ip;if(!ip){const mailServer=(await(await fetch("https://api.hetzner.cloud/v1/servers",{headers:{Authorization:`Bearer ${hetznerToken}`}})).json()).servers?.find((s)=>s.name?.includes("mail"));if(mailServer){const serverIp=mailServer.public_net?.ipv4?.ip;log.info(`Found Hetzner server: ${mailServer.name} (${serverIp})`);const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${serverIp} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",serverIp)}else log.error("No mail server found on Hetzner")}else{const result=execSync(`ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@${ip} "timeout 5 bash -c 'echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25' 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED"`,{encoding:"utf-8"});printPort25Status(result.trim(),"Hetzner",ip)}}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`)}process.exit(ExitCode.Success)}try{const{EC2Client,SSMClient}=await import("@stacksjs/ts-cloud"),ec2=new EC2Client(region),ssm=new SSMClient(region),instance=(await ec2.describeInstances({Filters:[{Name:"tag:Name",Values:[`${appName}-mail-server`]},{Name:"instance-state-name",Values:["running"]}]})).Reservations?.[0]?.Instances?.[0],instanceId=instance?.InstanceId;if(!instanceId){await log.error("No running mail server found.");process.exit(ExitCode.FatalError)}const publicIp=instance?.PublicIpAddress||"unknown";log.info(`Testing port 25 on ${instanceId} (${publicIp})...`);const result=await ssm.runShellCommand(instanceId,['timeout 5 bash -c "echo QUIT > /dev/tcp/gmail-smtp-in.l.google.com/25" 2>&1 && echo PORT_25_OPEN || echo PORT_25_BLOCKED'],{timeoutSeconds:15,maxWaitMs:20000,pollIntervalMs:2000});printPort25Status(result.output?.trim()||"PORT_25_BLOCKED","AWS",publicIp);process.exit(ExitCode.Success)}catch(error){await log.error(`Failed: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:server","Start SMTP relay server").option("--port <port>","SMTP port",{default:"587"}).action(async(options)=>{loadEnvFiles();const domain=process.env.APP_DOMAIN||process.env.MAIL_DOMAIN||"stacksjs.com",port=Number.parseInt(options.port,10),mailboxes=["chris","blake","glenn"],users={},generated=[];for(const name of mailboxes){const envKey=`MAIL_PASSWORD_${name.toUpperCase()}`;let password=process.env[envKey];if(!password){password=randomBytes(16).toString("base64url");generated.push(`${envKey}=${password}`)}users[name]={password,email:`${name}@${domain}`}}if(generated.length>0){console.log("");log.warn("Generated missing passwords. Add these to .env.production:");for(const line of generated)console.log(` ${line}`)}console.log("");console.log("==========================================================");console.log(" SMTP RELAY SERVER");console.log("==========================================================");console.log("");console.log(` Host: mail.${domain}`);console.log(` Port: ${port}`);console.log(` Domain: ${domain}`);console.log("");console.log(" Mailboxes:");for(const[name,user]of Object.entries(users))console.log(` ${name} (${user.email})`);console.log("");console.log(" Relaying through AWS SES");console.log("==========================================================");console.log("");try{const{SmtpServer}=await import("@stacksjs/cloud"),server=new SmtpServer({port,host:"0.0.0.0",domain,users,sentBucket:"stacks-production-email",sentPrefix:"sent/"});await server.start();await new Promise((resolve)=>{process.on("SIGINT",async()=>{console.log(`
63
63
  Shutting down SMTP server...`);await server.stop();resolve()})});process.exit(0)}catch(error){await log.error(`Failed to start SMTP server: ${getErrorMessage(error)}`);process.exit(ExitCode.FatalError)}});buddy.command("mail:preview","Open the dev-only Mailable preview UI in your browser").option("--no-open","Print the URL but skip the browser-open step").option("--port <port>","Override the API port (default: from config.ports.api / PORT_API)").example("buddy mail:preview").example("buddy mail:preview --no-open").example("buddy mail:preview --port 4000").action(async(options)=>{const{config}=await import("@stacksjs/config"),portFromOption=options.port?Number(options.port):void 0,portFromEnv=process.env.PORT_API?Number(process.env.PORT_API):void 0,url=`http://localhost:${portFromOption||portFromEnv||config.ports?.api||3008}/_stacks/mail/preview`;log.info(`Mailable preview: ${url}`);log.info("(Make sure `./buddy dev:api` is running.)");if(options.open!==!1)try{execSync(`open "${url}" 2>/dev/null || xdg-open "${url}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}await log.flush();process.exit(ExitCode.Success)});buddy.command("mail:dev","Run the local mail catcher: accepts every message, delivers none, shows them in the webmail UI").option("--port <port>",`SMTP port (default: ${LOCAL_MAIL_SMTP_PORT})`).option("--ui-port <port>",`Webmail UI port (default: ${LOCAL_MAIL_UI_PORT})`).option("--no-open","Do not open the webmail UI in a browser").example("buddy mail:dev").example("buddy mail:dev --port 2525 --ui-port 8080").action(async(options)=>{loadEnvFiles();await runLocalMailCatcher({smtpPort:Number(options.port)||LOCAL_MAIL_SMTP_PORT,uiPort:Number(options.uiPort)||LOCAL_MAIL_UI_PORT,open:options.open!==!1})})}export const LOCAL_MAIL_SMTP_PORT=1025,LOCAL_MAIL_UI_PORT=8025,LOCAL_MAIL_DIR="storage/framework/mail";export function resolveMailBinary(root=process.cwd()){const local=`${root}/pantry/.bin/mail`;if(existsSync(local))return local;try{const found=execSync("command -v mail 2>/dev/null",{encoding:"utf-8"}).trim();if(found&&isMailServer(found))return found}catch{}return}function isMailServer(binary){try{return execSync(`${shellQuote(binary)} </dev/null 2>&1 || true`,{encoding:"utf-8",timeout:5000}).includes("Mail server management CLI")}catch{return!1}}export function buildLocalMailConfig(options){return["# Generated by `buddy mail:dev`. Edits are overwritten on the next run.","","[server]",'host = "127.0.0.1"',`port = ${options.smtpPort}`,'hostname = "localhost"',"catch_all = true","","[tls]","enabled = false","","[auth]","enabled = false","","[antispam]","spam_filter = false","dnsbl = false","greylist = false",""].join(`
64
64
  `)}async function runLocalMailCatcher(options){const binary=resolveMailBinary();if(!binary){await log.error("The mail server is not installed.");log.info("Install it with: pantry install github.com/mail-os/mail");log.info("(It is declared in config/deps.ts, so `pantry install` on its own is enough.)");await log.flush();process.exit(ExitCode.FatalError)}const dir=`${process.cwd()}/${LOCAL_MAIL_DIR}`,configPath=`${dir}/catcher.toml`;mkdirSync(dir,{recursive:!0});await Bun.write(configPath,buildLocalMailConfig({smtpPort:options.smtpPort}));console.log("");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(" Local mail catcher");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log(` SMTP 127.0.0.1:${options.smtpPort}`);console.log(` Webmail http://localhost:${options.uiPort} (sign in: dev / dev)`);console.log(` Mailbox ${LOCAL_MAIL_DIR}`);console.log("");console.log(" Every recipient is accepted; nothing is delivered onward.");console.log(" Ctrl-C to stop.");console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");console.log("");if(options.open)try{execSync(`open "http://localhost:${options.uiPort}" 2>/dev/null || xdg-open "http://localhost:${options.uiPort}" 2>/dev/null || true`,{encoding:"utf-8"})}catch{}const child=Bun.spawn([binary,"serve","--config",configPath],{cwd:dir,env:{...process.env,SMTP_DB_PATH:`${dir}/catcher.db`,SMTP_ENABLE_WEBMAIL:"true",SMTP_WEBMAIL_PORT:String(options.uiPort),SMTP_WEBMAIL_SECURE_COOKIES:"false"},stdout:"inherit",stderr:"inherit"});process.on("SIGINT",()=>{child.kill();process.exit(ExitCode.Success)});process.exit(await child.exited)}function loadEnvFiles(){const envPath=".env.production";if(existsSync(envPath))try{const{loadEnv}=require("@stacksjs/env");loadEnv({path:envPath,env:"production",keysFile:".env.keys",overload:!1,quiet:!0})}catch{const content=readFileSync(envPath,"utf-8");for(const line of content.split(`
@@ -14,7 +14,7 @@ import type { CLI } from '@stacksjs/types';
14
14
  * any action subprocess starts, so a mismatch cannot drop the framework tables
15
15
  * and only then discover it has nothing to rebuild them with.
16
16
  */
17
- export declare function validateMigrationDialect(cwd?: unknown, options?: { driver?: string }): { valid: boolean, error?: string };
17
+ export declare function validateMigrationDialect(cwd?: unknown, options?: { driver?: string, only?: readonly string[] }): { valid: boolean, error?: string };
18
18
  /**
19
19
  * Whether this run is a preview. `--diff` is the migrate flag, but buddy also
20
20
  * registers `--dry-run` for every command ("Preview actions without making
@@ -1,4 +1,4 @@
1
- import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,isLibsqlDriver,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"||isLibsqlDriver(driver)){const audit=auditMigrationCorpus({dir,target});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportMissingRecordedTables(){try{const{missingRecordedTables}=await import("@stacksjs/database"),missing=await missingRecordedTables();if(missing.length===0)return!0;log.warn(`${missing.length} table${missing.length===1?"":"s"} the migrations table says ${missing.length===1?"was":"were"} created ${missing.length===1?"is":"are"} missing from the database: ${missing.slice(0,10).join(", ")}${missing.length>10?`, +${missing.length-10} more`:""}.`);return!1}catch(err){log.debug(`[migrate] recorded-table check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function logDriftRemedy(){log.info("`buddy migrate` only runs files the migrations table does not list, so it will not repair this on its own.");log.info(" A table that is missing although its migration is recorded: `./buddy migrate:status --reconcile --requeue-reverted`, then `./buddy migrate`.");log.info(" Anything else: `./buddy migrate:status` compares the corpus, the ledger and the live schema. Pass --strict to fail on drift in CI.")}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportDuplicateMigrationNumbers(options){try{const{activeMigrationDirectory,duplicateMigrationOrdinalsIn}=await import("@stacksjs/database"),groups=duplicateMigrationOrdinalsIn(await activeMigrationDirectory()),reported=options.strict?groups:groups.filter((group)=>group.generated);if(reported.length===0)return!0;const lines=reported.slice(0,10).map((group)=>` \u2022 ${group.ordinal}: ${group.files.join(", ")}`);if(reported.length>10)lines.push(` \u2022 \u2026 +${reported.length-10} more`);const message=`${reported.length} migration number${reported.length===1?" is":"s are"} used by more than one file:
1
+ import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,isLibsqlDriver,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"||isLibsqlDriver(driver)){const audit=auditMigrationCorpus({dir,target,only:options.only});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportMissingRecordedTables(){try{const{missingRecordedTables}=await import("@stacksjs/database"),missing=await missingRecordedTables();if(missing.length===0)return!0;log.warn(`${missing.length} table${missing.length===1?"":"s"} the migrations table says ${missing.length===1?"was":"were"} created ${missing.length===1?"is":"are"} missing from the database: ${missing.slice(0,10).join(", ")}${missing.length>10?`, +${missing.length-10} more`:""}.`);return!1}catch(err){log.debug(`[migrate] recorded-table check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function logDriftRemedy(){log.info("`buddy migrate` only runs files the migrations table does not list, so it will not repair this on its own.");log.info(" A table that is missing although its migration is recorded: `./buddy migrate:status --reconcile --requeue-reverted`, then `./buddy migrate`.");log.info(" Anything else: `./buddy migrate:status` compares the corpus, the ledger and the live schema. Pass --strict to fail on drift in CI.")}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportDuplicateMigrationNumbers(options){try{const{activeMigrationDirectory,duplicateMigrationOrdinalsIn}=await import("@stacksjs/database"),groups=duplicateMigrationOrdinalsIn(await activeMigrationDirectory()),reported=options.strict?groups:groups.filter((group)=>group.generated);if(reported.length===0)return!0;const lines=reported.slice(0,10).map((group)=>` \u2022 ${group.ordinal}: ${group.files.join(", ")}`);if(reported.length>10)lines.push(` \u2022 \u2026 +${reported.length-10} more`);const message=`${reported.length} migration number${reported.length===1?" is":"s are"} used by more than one file:
2
2
  ${lines.join(`
3
3
  `)}`,remedy=" The runner orders same-numbered files alphabetically, not by intent. Renumber the file(s) nothing has applied yet past the highest number, or regenerate them with `./buddy generate:migrations`.";if(options.strict){log.syncError(`--strict: ${message}
4
4
  ${remedy}`);return!1}log.warn(message);log.info(remedy);return!0}catch(err){log.debug(`[migrate] duplicate migration number check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportHandWrittenMigrations(options={}){try{const{handWrittenMigrations}=await import("@stacksjs/database"),{files}=await handWrittenMigrations();if(files.length===0)return!0;log.warn(`${files.length} hand-written migration${files.length===1?"":"s"} - no \`-- qb:generated\` marker, so the models do not describe ${files.length===1?"it":"them"}${options.list?`:
@@ -14,7 +14,7 @@ The model-backed create migrations may be stale for this database - run \`./budd
14
14
  ${sample}${more}
15
15
  These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" \u2192 "${op.to}"`;case"rename_table":return`rename table "${op.from}" \u2192 "${op.to}"`;case"add_enum_value":return`add value(s) to the enum type of "${op.table}"."${op.column}"`;case"create_enum":return`create the enum type for "${op.table}"${op.column?`."${op.column}"`:""}`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database"),dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return!0}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);for(const op of operations.filter((o)=>o.warning))log.warn(`${describeOp(op)}: ${op.warning}`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return!0;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` \u2022 ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return!0;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return!1}return confirm({message:"Apply these destructive changes?",initial:!1})}export function isMigratePreview(options,argv=process.argv){return options.diff===!0||options.dryRun===!0||options.pretend===!0||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return!0;if(v==="0"||v==="false"||v==="no"||v==="off")return!1;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:void 0}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");cfg=(await awaitConfig()).database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??!0,migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",noGenerate:"Apply committed migration files only; do not generate new ones from your models"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("--dry-run","Same as --diff: preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:!1}).option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("--from-db",descriptions.fromDb,{default:!1}).option("--no-rename",descriptions.noRename).option("--no-generate",descriptions.noGenerate).option("--strict","Fail when the schema has drifted from the models, a migration is git-ignored or hand-written, or two migrations share a number (for CI)",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate"),validation=validateModelsExist();if(!validation.valid){console.error(`
16
16
  \u274C Error: ${validation.error}
17
- `);process.exit(ExitCode.FatalError)}const dialectCheck=validateMigrationDialect();if(!dialectCheck.valid){console.error(`
17
+ `);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=void 0}const dialectCheck=validateMigrationDialect(process.cwd(),{only:willRun});if(!dialectCheck.valid){console.error(`
18
18
  \u274C Error: ${dialectCheck.error}
19
19
  `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===!1?!1:void 0;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===!1)process.env.STACKS_MIGRATE_NO_RENAME="1";if(options.generate===!1)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=!1,files=[];try{files=await pendingMigrationFiles()}catch(error){failed=!0;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` \u2022 ${file}`);if(files.length>10)log.info(` \u2022 \u2026 +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=!0;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` \u2022 ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift(),modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});if((await resolveMigrationGuards()).confirmMigrate&&!options.force)if(isCI||!hasTTY)log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.");else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();if(!await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:!0})){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(options.generate!==!1){if(!await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames})){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`)}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result))log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.");if(options.auth!==!1)try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`);const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success)log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`);const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success)log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}catch(error){log.error("Failed to migrate notification/RBAC/trait tables:",error)}if(resultFailed(result)){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(options.auth!==!1)try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift(),tablesPresent=await reportMissingRecordedTables(),schemaMatches=modelsMatch&&tablesPresent,allCommittable=await reportIgnoredMigrations(),allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){console.error(`
20
20
  \u274C --strict: ${!allCommittable?"a migration is git-ignored":!allGenerated?"a migration was written by hand rather than generated from the models":"the live schema does not match the models"} (see above).
@@ -1,3 +1,14 @@
1
1
  import type { CLI } from '@stacksjs/types';
2
+ /** `--wait` as minutes, or null when the release should not wait. */
3
+ export declare function waitMinutes(value: IosReleaseOptions['wait']): number | null;
2
4
  export declare function release(buddy: CLI): void;
3
5
  export declare function resolveGitHubActionsUrl(remoteUrl?: string, repository?: unknown, serverUrl?: unknown): string;
6
+ declare interface IosReleaseOptions {
7
+ bump?: string
8
+ dryRun?: boolean
9
+ keepBuilds?: number | string
10
+ skipGithubRelease?: boolean
11
+ notes?: string
12
+ notesFile?: string
13
+ wait?: boolean | number | string
14
+ }
@@ -1,6 +1,13 @@
1
- import{execFileSync}from"node:child_process";import{existsSync,readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";import process from"node:process";import{resolveXcodegen}from"@stacksjs/actions/build/ios-toolchain";import{describeGitHubRelease,publishGitHubRelease}from"@stacksjs/actions/github-release";import{runAction}from"@stacksjs/actions/run-action";import{intro,italic,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{AppStoreConnect,appStoreConnectCredentials,buildsToExpire}from"../app-store-connect";import{bumpedVersion,iosReleaseSummary,iosVersionIn,nextBuildTag,withIosVersion}from"../release-ios";import{resultFailed}from"../result";const descriptions={release:"Release a new version of your libraries/packages",project:"Target a specific project",dryRun:"Run the release without actually releasing",bump:"Non-interactive bump: patch | minor | major | prepatch | preminor | premajor | prerelease | pre | release | build | calendar | x.y.z",verbose:"Enable verbose output",skipGithubRelease:"Push the tag without creating its GitHub release"};export function release(buddy){buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease channel, for example beta or rc").option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release"),result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:!0});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","TestFlight builds to keep besides the new one; older ones are expired (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--dry-run",descriptions.dryRun,{default:!1}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:`Released ${tag}`,{startTime,useSeconds:!0});if(!options.dryRun)log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--dry-run","Print the release instead of creating it",{default:!1}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null,result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary:ios?.body,dryRun:options.dryRun});if(result.status==="failed")throw Error(describeGitHubRelease(target,result));log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
1
+ import{execFileSync}from"node:child_process";import{existsSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";import process from"node:process";import{resolveXcodegen}from"@stacksjs/actions/build/ios-toolchain";import{describeGitHubRelease,publishGitHubRelease,resolveGitHubToken}from"@stacksjs/actions/github-release";import{validateReleaseEvidencePlan,verifyReleaseEvidence}from"@stacksjs/actions/release-evidence";import{assertPublicationAllowed}from"@stacksjs/actions/publication-preflight";import{runAction}from"@stacksjs/actions/run-action";import{intro,italic,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{printAsync}from"@stacksjs/cli/output";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{AppStoreConnect,appStoreConnectCredentials,buildsToExpire,waitForBuild}from"../app-store-connect";import{bumpedVersion,iosReleaseSummary,iosVersionIn,nextBuildTag,withIosVersion}from"../release-ios";import{appStoreLocales,commitsBetween,committedWhatToTest,fitNotes,NO_VISIBLE_CHANGES,PLAY_NOTES_LIMIT,previousMobileTag,resolveNotes,TESTFLIGHT_NOTES_LIMIT,testerNotes,writeWhatToTest,XCODE_CLOUD_NOTES_LIMIT}from"@stacksjs/actions/release-notes";import{resultFailed}from"../result";const descriptions={release:"Release a new version of your libraries/packages",project:"Target a specific project",dryRun:"Run the release without actually releasing",bump:"Non-interactive bump: patch | minor | major | prepatch | preminor | premajor | prerelease | pre | release | build | calendar | x.y.z",verbose:"Enable verbose output",skipGithubRelease:"Push the tag without creating its GitHub release"},IOS_PROJECT_DIR="storage/framework/mobile/ios",DEFAULT_WAIT_MINUTES=60;async function loadMobileConfig(configPath){return(await import(pathToFileURL(configPath).href)).default??{}}export function waitMinutes(value){if(value===void 0||value===!1)return null;if(value===!0||value==="")return DEFAULT_WAIT_MINUTES;const minutes=Number(value);if(!Number.isFinite(minutes)||minutes<0)throw Error(`--wait takes minutes, not ${String(value)}`);return minutes}function buildNumberOf(tag){const match=/^v(\d+\.\d+\.\d+)-build\.(\d+)$/.exec(tag);if(!match)throw Error(`${tag} is not an iOS build tag (v<version>-build.<n>)`);return{version:match[1],number:Number(match[2])}}function notesLocales(mobile){return mobile.release?.locales?.length?[...new Set(mobile.release.locales)]:appStoreLocales(mobile.ios?.nativeMessages?.languages)}async function applyWhatToTest(store,tag,notes,locales,minutes){try{const{version,number}=buildNumberOf(tag);if(minutes>0)log.info(`Waiting up to ${minutes} min for TestFlight build ${number} to reach App Store Connect\u2026`);const build=await waitForBuild(store.api,store.appId,version,number,{timeoutMs:minutes*60000,onWait:(elapsed)=>log.debug(`TestFlight build ${number} not there yet (${Math.round(elapsed/1000)}s)`)});if(!build){log.warn(`TestFlight build ${number} is not in App Store Connect yet; once it is, run \`buddy release:notes ${tag} --testflight\`.`);return!1}const text=fitNotes(notes,TESTFLIGHT_NOTES_LIMIT);await store.api.setWhatToTest(build.id,Object.fromEntries(locales.map((locale)=>[locale,text])));log.info(`Set What to Test on TestFlight build ${number} (${locales.join(", ")})`);return!0}catch(error){log.warn(`Could not set What to Test: ${error instanceof Error?error.message:String(error)}. Retry with \`buddy release:notes ${tag} --testflight\`.`);return!1}}function githubSummary(summary,notes){return`${summary.trim()}
2
2
 
3
- ${result.draft.body}`:describeGitHubRelease(target,result));await outro(options.dryRun?"Dry run complete. Nothing was created.":`GitHub release for ${target}`,{startTime,useSeconds:!0})}catch(error){await log.error("Failed to create the GitHub release",error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"release")}function git(...args){return execFileSync("git",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}async function releaseIos(options){const root=process.cwd(),configPath=join(root,"config/mobile.ts");if(!existsSync(configPath))throw Error("config/mobile.ts not found: run this in a Stacks app with a mobile config");const xcodegen=await resolveXcodegen(root);log.info(`xcodegen ${xcodegen.version} from Pantry (${xcodegen.path})`);const branch=git("rev-parse","--abbrev-ref","HEAD");if(branch!=="main")throw Error(`releases are cut from main; this is ${branch}`);if(git("status","--porcelain","--untracked-files=no"))throw Error("commit or stash your changes first, so the release is exactly what is on main");git("pull","--quiet","--rebase","origin","main");git("fetch","--quiet","--tags","origin");const source=readFileSync(configPath,"utf8"),current=iosVersionIn(source);if(!current)throw Error("config/mobile.ts declares no iOS `version`");const version=options.bump?bumpedVersion(current,options.bump):current,existingTags=git("tag","--list",`v${version}-build.*`).split(`
4
- `).filter(Boolean);let tag=nextBuildTag(version,existingTags);const credentials=appStoreConnectCredentials();let store=null;if(credentials){const bundleId=(await import(pathToFileURL(configPath).href)).default.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);store={api,appId:await api.appId(bundleId)};const latestRun=await api.latestXcodeCloudRun(store.appId);if(latestRun!==null)tag=nextBuildTag(version,existingTags,latestRun)}else log.warn("No App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH): the tag counts releases, not the build number TestFlight will show, and older builds stay listed.");log.info(`Releasing ${tag}${version===current?"":` (version ${current} \u2192 ${version})`}`);const keep=Math.max(0,Number(options.keepBuilds??1)||0),summary=iosReleaseSummary(tag,{numberedByXcodeCloud:store!==null});if(options.dryRun){if(store){const retiring=buildsToExpire(await store.api.builds(store.appId),keep);log.info(retiring.length?`Would expire TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`:"No TestFlight builds to expire")}if(!options.skipGithubRelease){const preview=await publishGitHubRelease({cwd:root,tag,ref:"HEAD",name:summary.name,summary:summary.body,dryRun:!0});log.info(preview.draft?`Would create the GitHub release ${tag} (${preview.draft.name}):
3
+ ## What to Test
5
4
 
6
- ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}for(const key of["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"])delete process.env[key];const result=await runAction(Action.BuildIos,{});if(resultFailed(result))throw result.error??Error("the iOS build failed");git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);git("tag","-a",tag,"-m",tag);git("push","--quiet","--atomic","origin","main",tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:summary.body});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store)try{const retiring=buildsToExpire(await store.api.builds(store.appId),keep);for(const build of retiring)await store.api.expire(build.id);if(retiring.length)log.info(`Expired TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`)}catch(error){log.warn(`Could not expire older TestFlight builds: ${error instanceof Error?error.message:String(error)}`)}return tag}export function resolveGitHubActionsUrl(remoteUrl,repository=process.env.GITHUB_REPOSITORY,serverUrl=process.env.GITHUB_SERVER_URL??"https://github.com"){const repo=repository?.trim()||remoteUrl?.trim().match(/github\.com[/:]([^/\s]+\/[^/\s]+?)(?:\.git)?$/)?.[1];return repo?`${serverUrl.replace(/\/$/,"")}/${repo}/actions`:"https://github.com/stacksjs/stacks/actions"}function readOriginRemote(){try{return execFileSync("git",["config","--get","remote.origin.url"],{encoding:"utf8"}).trim()}catch{return}}
5
+ ${notes.trim()}`}function git(...args){return execFileSync("git",args,{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}async function releaseIos(options){const root=process.cwd();if(!options.dryRun)await assertPublicationAllowed({cwd:root,channel:"ios"});const configPath=join(root,"config/mobile.ts");if(!existsSync(configPath))throw Error("config/mobile.ts not found: run this in a Stacks app with a mobile config");const xcodegen=await resolveXcodegen(root);log.info(`xcodegen ${xcodegen.version} from Pantry (${xcodegen.path})`);const branch=git("rev-parse","--abbrev-ref","HEAD");if(branch!=="main")throw Error(`releases are cut from main; this is ${branch}`);if(git("status","--porcelain","--untracked-files=no"))throw Error("commit or stash your changes first, so the release is exactly what is on main");if(!options.dryRun){git("pull","--quiet","--rebase","origin","main");git("fetch","--quiet","--tags","origin");await assertPublicationAllowed({cwd:root,channel:"ios"})}const source=readFileSync(configPath,"utf8"),current=iosVersionIn(source);if(!current)throw Error("config/mobile.ts declares no iOS `version`");const version=options.bump?bumpedVersion(current,options.bump):current,existingTags=git("tag","--list",`v${version}-build.*`).split(`
6
+ `).filter(Boolean);let tag=nextBuildTag(version,existingTags);const wait=waitMinutes(options.wait),mobile=await loadMobileConfig(configPath),credentials=appStoreConnectCredentials();let store=null,numberedByXcodeCloud=!1;if(credentials){const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials);store={api,appId:await api.appId(bundleId)};const latestRun=await api.latestXcodeCloudRun(store.appId);if(latestRun!==null){tag=nextBuildTag(version,existingTags,latestRun);numberedByXcodeCloud=!0}}else log.warn("No App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH): the tag counts releases, not the build number TestFlight will show, and older builds stay listed.");log.info(`Releasing ${tag}${version===current?"":` (version ${current} \u2192 ${version})`}`);const keep=Math.max(0,Number(options.keepBuilds??1)||0),summary=iosReleaseSummary(tag,{numberedByXcodeCloud:store!==null}),releaseConfig=mobile.release??{},previous=previousMobileTag(root,"HEAD"),commits=commitsBetween(root,previous,"HEAD"),generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>testerNotes(commits,generateOptions)}),githubNotes=notes.source==="generated"?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:notes.text,locales=notesLocales(mobile),origin=notes.source==="generated"?`${commits.length} commits since ${previous??"the first commit"}`:{flag:"--notes",env:"RELEASE_NOTES",config:"config/mobile.ts release.notes"}[notes.source];if(wait!==null&&!numberedByXcodeCloud)log.warn("--wait needs an App Store Connect API key and an Xcode Cloud product to know the TestFlight build; Xcode Cloud still reads the What to Test file.");if(options.dryRun){log.info(`What to Test (${origin}; ${locales.map((locale)=>`TestFlight/WhatToTest.${locale}.txt`).join(", ")}):
7
+
8
+ ${fitNotes(notes.text,XCODE_CLOUD_NOTES_LIMIT)}`);if(store){const retiring=buildsToExpire(await store.api.builds(store.appId),keep);log.info(retiring.length?`Would expire TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`:"No TestFlight builds to expire")}if(!options.skipGithubRelease){const preview=await publishGitHubRelease({cwd:root,tag,ref:"HEAD",name:summary.name,summary:githubSummary(summary.body,githubNotes),dryRun:!0});log.info(preview.draft?`Would create the GitHub release ${tag} (${preview.draft.name}):
9
+
10
+ ${preview.draft.body}`:describeGitHubRelease(tag,preview))}return tag}const paths=["config/mobile.ts","storage/framework/mobile/ios"];if(version!==current){writeFileSync(configPath,withIosVersion(source,version));const pkgPath=join(root,"package.json");if(existsSync(pkgPath)){const pkg=readFileSync(pkgPath,"utf8");writeFileSync(pkgPath,pkg.replace(/("version"\s*:\s*)"[^"]*"/,`$1"${version}"`));paths.push("package.json")}}for(const key of["MOBILE_URL","IOS_APP_VERSION","IOS_BUILD_NUMBER"])delete process.env[key];const result=await runAction(Action.BuildIos,{});if(resultFailed(result))throw result.error??Error("the iOS build failed");const written=writeWhatToTest(root,IOS_PROJECT_DIR,notes.text,locales);log.info(`What to Test from ${origin}: ${written.join(", ")}`);git("add","--",...paths);if(git("diff","--cached","--name-only"))git("commit","--quiet","-m",`chore(release): ${tag}`);git("tag","-a",tag,"-m",tag);git("push","--quiet","--atomic","origin","main",tag);if(!options.skipGithubRelease){const published=await publishGitHubRelease({cwd:root,tag,name:summary.name,summary:githubSummary(summary.body,githubNotes)});if(published.status==="failed")log.warn(describeGitHubRelease(tag,published));else log.info(describeGitHubRelease(tag,published))}if(store){try{const retiring=buildsToExpire(await store.api.builds(store.appId),keep);for(const build of retiring)await store.api.expire(build.id);if(retiring.length)log.info(`Expired TestFlight builds ${retiring.map((b)=>b.number).join(", ")}`)}catch(error){log.warn(`Could not expire older TestFlight builds: ${error instanceof Error?error.message:String(error)}`)}if(wait!==null&&numberedByXcodeCloud)await applyWhatToTest(store,tag,notes.text,locales,wait)}return tag}function notesForTag(root,tag,mobile,options){const releaseConfig=mobile.release??{},generateOptions={types:releaseConfig.noteTypes,excludeScopes:releaseConfig.excludeScopes},from=options.from||previousMobileTag(root,`${tag}^`),commits=commitsBetween(root,from,tag),plainGenerated=testerNotes(commits,generateOptions)||NO_VISIBLE_CHANGES,committed=options.from?null:committedWhatToTest(root,tag,IOS_PROJECT_DIR),handWritten=committed&&committed.trim()!==fitNotes(plainGenerated,XCODE_CLOUD_NOTES_LIMIT)?committed.trim():null,notes=resolveNotes({cwd:root,flags:options,config:releaseConfig,generate:()=>handWritten??plainGenerated});if(notes.source!=="generated"||handWritten)return{text:notes.text,plain:notes.text};return{text:options.markdown?testerNotes(commits,{...generateOptions,markdown:!0})||NO_VISIBLE_CHANGES:plainGenerated,plain:plainGenerated}}async function releaseNotesCommand(tagArgument,options){const root=process.cwd(),configPath=join(root,"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{},tag=tagArgument||previousMobileTag(root,"HEAD");if(!tag||!git("tag","--list",tag))throw Error(tagArgument?`there is no tag ${tagArgument}`:"there is no mobile release tag (v*-build.*) yet");const notes=notesForTag(root,tag,mobile,options);if(options.testflight){const credentials=appStoreConnectCredentials();if(!credentials)throw Error("--testflight needs an App Store Connect API key (APP_STORE_CONNECT_KEY_ID, _ISSUER_ID, _PRIVATE_KEY_PATH)");const bundleId=mobile.ios?.bundleId;if(!bundleId)throw Error("config/mobile.ts declares no ios.bundleId");const api=await AppStoreConnect.connect(credentials),store={api,appId:await api.appId(bundleId)};if(!await applyWhatToTest(store,tag,notes.plain,notesLocales(mobile),waitMinutes(options.wait)??0))process.exitCode=ExitCode.FatalError;return}const limit=options.play?PLAY_NOTES_LIMIT:options.markdown?Number.POSITIVE_INFINITY:TESTFLIGHT_NOTES_LIMIT;await printAsync(Number.isFinite(limit)?fitNotes(notes.text,limit):notes.text)}export function release(buddy){buddy.command("release",descriptions.release).option("--dry-run",descriptions.dryRun,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--bump <type>",descriptions.bump).option("--preid <identifier>","Prerelease channel, for example beta or rc").option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy release` ...",options);if(options.dryRun)log.warn("Dry run enabled. No changes will be made or committed.");const startTime=await intro("buddy release"),result=await runAction(Action.Release,options);if(resultFailed(result)){await log.error("Failed to release",result.error);process.exit(ExitCode.FatalError)}await outro(options.dryRun?"Dry run complete. Nothing was committed, tagged or pushed.":"Triggered CI/CD Release via GitHub Actions",{startTime,useSeconds:!0});if(!options.dryRun)log.info(`Follow along: ${italic(resolveGitHubActionsUrl(readOriginRemote()))}`)});buddy.command("release:ios","Ship the iOS app: regenerate its project for production, commit, tag and push").option("--bump <type>","build | patch | minor | major | x.y.z (default: a new build of the current marketing version)").option("--keep-builds <n>","TestFlight builds to keep besides the new one; older ones are expired (needs an App Store Connect API key)",{default:1}).option("--skip-github-release",descriptions.skipGithubRelease,{default:!1}).option("--notes <text>","What to Test for this build, instead of the notes generated from the commits since the previous build").option("--notes-file <path>","Read What to Test from a file (also RELEASE_NOTES / RELEASE_NOTES_FILE, or release.notes in config/mobile.ts)").option("--wait [minutes]","Wait for the build to reach App Store Connect, then set its What to Test there too (default 60 minutes; needs an App Store Connect API key)").option("--dry-run",descriptions.dryRun,{default:!1}).action(async(options)=>{const startTime=await intro("buddy release:ios");try{const tag=await releaseIos(options);await outro(options.dryRun?`Dry run complete: would release ${tag}`:`Released ${tag}`,{startTime,useSeconds:!0});if(!options.dryRun)log.info('A CI that builds tags (Xcode Cloud: Tag Changes, prefix "v") turns it into a TestFlight build now.')}catch(error){await log.error("Failed to release the iOS app",error);process.exit(ExitCode.FatalError)}});buddy.command("release:notes [tag]","Print the tester notes of a mobile release tag (default: the newest v*-build.* tag), or set them as its TestFlight What to Test").option("--from <ref>","Generate from the commits since this ref instead of the previous build tag").option("--play","Fit the notes to Google Play's 500-character What's new",{default:!1}).option("--markdown","Markdown, as the GitHub release shows the notes",{default:!1}).option("--testflight","Set the notes as the TestFlight build's What to Test through App Store Connect",{default:!1}).option("--wait [minutes]","With --testflight: wait this long for the build to appear (default 60)").option("--notes <text>","Use this text instead").option("--notes-file <path>","Read the text from a file instead").action(async(tag,options)=>{try{await releaseNotesCommand(tag,options)}catch(error){await log.error("Failed to produce the release notes",error);process.exit(ExitCode.FatalError)}});buddy.command("release:github [tag]","Create the GitHub release for a pushed tag (default: the newest), with the changes since the tag before it").option("--dry-run","Print the release instead of creating it",{default:!1}).action(async(tag,options)=>{const startTime=await intro("buddy release:github");try{if(!options.dryRun)await assertPublicationAllowed({cwd:process.cwd(),channel:"github-release"});const target=tag||git("describe","--tags","--abbrev=0");if(!git("tag","--list",target))throw Error(`there is no tag ${target}`);const ios=/^v\d+\.\d+\.\d+-build\.\d+$/.test(target)?iosReleaseSummary(target,{numberedByXcodeCloud:appStoreConnectCredentials()!==null}):null;let summary=ios?.body;if(ios){const configPath=join(process.cwd(),"config/mobile.ts"),mobile=existsSync(configPath)?await loadMobileConfig(configPath):{};summary=githubSummary(ios.body,notesForTag(process.cwd(),target,mobile,{markdown:!0}).text)}const result=await publishGitHubRelease({cwd:process.cwd(),tag:target,name:ios?.name,summary,dryRun:options.dryRun});if(result.status==="failed")throw Error(describeGitHubRelease(target,result));log.info(options.dryRun&&result.draft?`Would create the GitHub release ${target} (${result.draft.name}):
11
+
12
+ ${result.draft.body}`:describeGitHubRelease(target,result));await outro(options.dryRun?"Dry run complete. Nothing was created.":`GitHub release for ${target}`,{startTime,useSeconds:!0})}catch(error){await log.error("Failed to create the GitHub release",error);process.exit(ExitCode.FatalError)}});buddy.command("release:verify <plan>","Verify exact source gates, published archives and installed consumer checks").option("--output <path>","Save the successful verification receipt as JSON").action(async(planPath,options)=>{let temporary;try{const plan=JSON.parse(readFileSync(planPath,"utf8"));validateReleaseEvidencePlan(plan);const receipt=await verifyReleaseEvidence(plan,{cwd:process.cwd(),token:resolveGitHubToken()??void 0}),json=`${JSON.stringify(receipt,null,2)}
13
+ `;if(options.output){temporary=`${options.output}.${crypto.randomUUID()}.tmp`;writeFileSync(temporary,json,{flag:"wx",mode:384});renameSync(temporary,options.output);temporary=void 0;await printAsync(`Verified release evidence saved to ${options.output}`)}else await printAsync(json.trimEnd())}catch(error){if(temporary)rmSync(temporary,{force:!0});await log.error("Release verification failed",error);process.exitCode=ExitCode.FatalError}});onUnknownSubcommand(buddy,"release")}export function resolveGitHubActionsUrl(remoteUrl,repository=process.env.GITHUB_REPOSITORY,serverUrl=process.env.GITHUB_SERVER_URL??"https://github.com"){const repo=repository?.trim()||remoteUrl?.trim().match(/github\.com[/:]([^/\s]+\/[^/\s]+?)(?:\.git)?$/)?.[1];return repo?`${serverUrl.replace(/\/$/,"")}/${repo}/actions`:"https://github.com/stacksjs/stacks/actions"}function readOriginRemote(){try{return execFileSync("git",["config","--get","remote.origin.url"],{encoding:"utf8"}).trim()}catch{return}}
@@ -10,7 +10,7 @@ exec bun "$BUDDY_NATIVE_ENTRY" "$@"
10
10
  bundleId: ${JSON.stringify(`com.example.${basename(root).toLowerCase().replace(/[^a-z0-9-]/g,"-")}`)},
11
11
  window: { title: ${JSON.stringify(name)}, width: 640, height: 480 },
12
12
  }
13
- `);writeMissing("src/app.stx",`<!doctype html>
13
+ `);if(!options.adopt)writeMissing("src/app.stx",`<!doctype html>
14
14
  <html lang="en">
15
15
  <head><meta charset="utf-8"><title>${name.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</title></head>
16
16
  <body><h1>${name.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</h1><p>Your Stacks native app is ready.</p></body>
@@ -19,9 +19,9 @@ exec bun "$BUDDY_NATIVE_ENTRY" "$@"
19
19
  dist/
20
20
  .stx/
21
21
  `);writeFileSync(manifest,`${JSON.stringify(pkg,null,2)}
22
- `)}export async function buildNativeProject(root,args=[]){const pkg=await Bun.file(join(root,"package.json")).json(),loaded=await import(pathToFileURL(join(root,"craft.config.ts")).href),config=loaded.default??loaded.config;if(!config||typeof config!=="object")throw Error("craft.config.ts must export a native build configuration.");const{buildNative}=await import(pathToFileURL(Bun.resolveSync("@stacksjs/stx/craft",root)).href),output=resolve(root,config.output??"dist");if(output===root||!output.startsWith(`${root}/`))throw Error("Native output must be a directory inside the app.");const result=await buildNative({...config,input:resolve(root,config.input??"src/app.stx"),output,version:pkg.version,description:pkg.description,author:pkg.author,...config.icon?{icon:resolve(root,config.icon)}:{},...args.includes("--dmg")?{format:"dmg"}:{},verbose:args.includes("--verbose")});if(!result.success||!result.outputPath)throw Error(result.error??"Native build produced no artifact.");return result.outputPath}export async function runNativeProjectCommand(root,args){const[command="help",...flags]=args;if(!["build","build:desktop","build:native","package","dev","dev:desktop","dev:native","upgrade","update"].includes(command))return!1;if(flags.includes("--help")||flags.includes("-h")){console.log(`buddy ${command} (native app)
22
+ `)}export async function buildNativeProject(root,args=[]){const pkg=await Bun.file(join(root,"package.json")).json(),loaded=await import(pathToFileURL(join(root,"craft.config.ts")).href),config=loaded.default??loaded.config;if(!config||typeof config!=="object")throw Error("craft.config.ts must export a native build configuration.");const{buildNative}=await import(pathToFileURL(Bun.resolveSync("@stacksjs/stx/craft",root)).href),output=resolve(root,config.output??"dist");if(output===root||!output.startsWith(`${root}/`))throw Error("Native output must be a directory inside the app.");const result=await buildNative({...config,input:resolve(root,config.input??"src/app.stx"),output,version:pkg.version,description:pkg.description,author:pkg.author,...config.icon?{icon:resolve(root,config.icon)}:{},...config.backend?{backend:{...config.backend,entry:resolve(root,config.backend.entry)}}:{},...args.includes("--dmg")?{format:"dmg"}:{},verbose:args.includes("--verbose")});if(!result.success||!result.outputPath)throw Error(result.error??"Native build produced no artifact.");return result.outputPath}export async function runNativeProjectCommand(root,args){const[command="help",...flags]=args;if(!["build","build:desktop","build:native","package","dev","dev:desktop","dev:native","upgrade","update"].includes(command))return!1;if(flags.includes("--help")||flags.includes("-h")){console.log(`buddy ${command} (native app)
23
23
 
24
24
  Build: --dmg --verbose
25
25
  Upgrade: --dry-run
26
26
 
27
- Configuration: craft.config.ts. Runtime: craft on PATH, or CRAFT_BIN.`);return!0}if(command==="upgrade"||command==="update"){if(flags.some((flag)=>flag!=="--dry-run"&&flag!=="--verbose"))throw Error("Native upgrades support --dry-run and --verbose. Use bun add to select a specific package version.");if(flags.includes("--dry-run"))console.log("Would run bun update for the native app; no files changed.");else if(await Bun.spawn(["bun","update"],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw Error("Native dependency upgrade failed.");return!0}const artifact=await buildNativeProject(root,command==="package"?[...flags,"--dmg"]:flags);console.log(`Built ${artifact}`);if(command.startsWith("dev")){const config=(await import(pathToFileURL(join(root,"craft.config.ts")).href)).default;if(process.platform!=="darwin")throw Error("Native development launch currently requires macOS.");const executable=join(artifact,"Contents","MacOS",config.name),child=Bun.spawn([executable],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"}),stop=()=>child.kill("SIGTERM");process.once("SIGINT",stop);process.once("SIGTERM",stop);try{const code=await child.exited;if(code!==0&&child.signalCode===null)throw Error(`Native app exited with code ${code}.`)}finally{process.removeListener("SIGINT",stop);process.removeListener("SIGTERM",stop)}}return!0}
27
+ Configuration: craft.config.ts. Runtime: craft on PATH, or CRAFT_BIN.`);return!0}if(command==="upgrade"||command==="update"){if(flags.some((flag)=>flag!=="--dry-run"&&flag!=="--verbose"))throw Error("Native upgrades support --dry-run and --verbose. Use bun add to select a specific package version.");if(flags.includes("--dry-run"))console.log("Would run bun update for the native app; no files changed.");else if(await Bun.spawn(["bun","update"],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0)throw Error("Native dependency upgrade failed.");return!0}const artifact=await buildNativeProject(root,command==="package"?[...flags,"--dmg"]:flags);console.log(`Built ${artifact}`);if(command.startsWith("dev")){const config=(await import(pathToFileURL(join(root,"craft.config.ts")).href)).default;if(process.platform!=="darwin")throw Error("Native development launch currently requires macOS.");const executable=join(artifact,"Contents","MacOS",config.name),child=Bun.spawn([executable],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});let interrupted=!1;const stop=()=>{interrupted=!0;child.kill("SIGTERM")};process.once("SIGINT",stop);process.once("SIGTERM",stop);try{const code=await child.exited;if(code!==0&&!interrupted)throw Error(`Native app exited with ${child.signalCode??`code ${code}`}.`)}finally{process.removeListener("SIGINT",stop);process.removeListener("SIGTERM",stop)}}return!0}
@@ -1 +1 @@
1
- const APP_KEY_OPTIONAL_COMMANDS=["env","build","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
1
+ const APP_KEY_OPTIONAL_COMMANDS=["env","desktop:apple","build","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.256",
5
+ "version": "0.75.258",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -96,72 +96,72 @@
96
96
  },
97
97
  "dependencies": {
98
98
  "@stacksjs/bumpx": "^0.2.25",
99
- "@stacksjs/actions": "0.75.256",
100
- "@stacksjs/ai": "0.75.256",
101
- "@stacksjs/alias": "0.75.256",
102
- "@stacksjs/analytics": "0.75.256",
103
- "@stacksjs/api": "0.75.256",
104
- "@stacksjs/arrays": "0.75.256",
105
- "@stacksjs/auth": "0.75.256",
106
- "@stacksjs/browser-extension": "0.75.256",
107
- "@stacksjs/build": "0.75.256",
108
- "@stacksjs/cache": "0.75.256",
109
- "@stacksjs/chat": "0.75.256",
99
+ "@stacksjs/actions": "0.75.258",
100
+ "@stacksjs/ai": "0.75.258",
101
+ "@stacksjs/alias": "0.75.258",
102
+ "@stacksjs/analytics": "0.75.258",
103
+ "@stacksjs/api": "0.75.258",
104
+ "@stacksjs/arrays": "0.75.258",
105
+ "@stacksjs/auth": "0.75.258",
106
+ "@stacksjs/browser-extension": "0.75.258",
107
+ "@stacksjs/build": "0.75.258",
108
+ "@stacksjs/cache": "0.75.258",
109
+ "@stacksjs/chat": "0.75.258",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.256",
112
- "@stacksjs/cloud": "0.75.256",
113
- "@stacksjs/cms": "0.75.256",
114
- "@stacksjs/collections": "0.75.256",
115
- "@stacksjs/commerce": "0.75.256",
116
- "@stacksjs/config": "0.75.256",
117
- "@stacksjs/database": "0.75.256",
118
- "@stacksjs/desktop-build": "0.75.256",
119
- "@stacksjs/dns": "0.75.256",
111
+ "@stacksjs/cli": "0.75.258",
112
+ "@stacksjs/cloud": "0.75.258",
113
+ "@stacksjs/cms": "0.75.258",
114
+ "@stacksjs/collections": "0.75.258",
115
+ "@stacksjs/commerce": "0.75.258",
116
+ "@stacksjs/config": "0.75.258",
117
+ "@stacksjs/database": "0.75.258",
118
+ "@stacksjs/desktop-build": "0.75.258",
119
+ "@stacksjs/dns": "0.75.258",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.256",
122
- "@stacksjs/enums": "0.75.256",
123
- "@stacksjs/env": "0.75.256",
124
- "@stacksjs/error-handling": "0.75.256",
125
- "@stacksjs/events": "0.75.256",
126
- "@stacksjs/features": "0.75.256",
127
- "@stacksjs/git": "0.75.256",
121
+ "@stacksjs/email": "0.75.258",
122
+ "@stacksjs/enums": "0.75.258",
123
+ "@stacksjs/env": "0.75.258",
124
+ "@stacksjs/error-handling": "0.75.258",
125
+ "@stacksjs/events": "0.75.258",
126
+ "@stacksjs/features": "0.75.258",
127
+ "@stacksjs/git": "0.75.258",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.256",
129
+ "@stacksjs/health": "0.75.258",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.256",
132
- "@stacksjs/lint": "0.75.256",
133
- "@stacksjs/logging": "0.75.256",
134
- "@stacksjs/notifications": "0.75.256",
135
- "@stacksjs/objects": "0.75.256",
136
- "@stacksjs/orm": "0.75.256",
137
- "@stacksjs/path": "0.75.256",
138
- "@stacksjs/payments": "0.75.256",
139
- "@stacksjs/realtime": "0.75.256",
140
- "@stacksjs/router": "0.75.256",
131
+ "@stacksjs/image": "0.75.258",
132
+ "@stacksjs/lint": "0.75.258",
133
+ "@stacksjs/logging": "0.75.258",
134
+ "@stacksjs/notifications": "0.75.258",
135
+ "@stacksjs/objects": "0.75.258",
136
+ "@stacksjs/orm": "0.75.258",
137
+ "@stacksjs/path": "0.75.258",
138
+ "@stacksjs/payments": "0.75.258",
139
+ "@stacksjs/realtime": "0.75.258",
140
+ "@stacksjs/router": "0.75.258",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.256",
143
- "@stacksjs/search-engine": "0.75.256",
144
- "@stacksjs/security": "0.75.256",
145
- "@stacksjs/server": "0.75.256",
146
- "@stacksjs/sites": "0.75.256",
147
- "@stacksjs/skills": "0.75.256",
148
- "@stacksjs/socials": "0.75.256",
149
- "@stacksjs/storage": "0.75.256",
150
- "@stacksjs/strings": "0.75.256",
151
- "@stacksjs/stx": "^0.2.631",
152
- "@stacksjs/testing": "0.75.256",
153
- "@stacksjs/tinker": "0.75.256",
142
+ "@stacksjs/scheduler": "0.75.258",
143
+ "@stacksjs/search-engine": "0.75.258",
144
+ "@stacksjs/security": "0.75.258",
145
+ "@stacksjs/server": "0.75.258",
146
+ "@stacksjs/sites": "0.75.258",
147
+ "@stacksjs/skills": "0.75.258",
148
+ "@stacksjs/socials": "0.75.258",
149
+ "@stacksjs/storage": "0.75.258",
150
+ "@stacksjs/strings": "0.75.258",
151
+ "@stacksjs/stx": "0.2.644",
152
+ "@stacksjs/testing": "0.75.258",
153
+ "@stacksjs/tinker": "0.75.258",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
155
  "@stacksjs/ts-cloud": "^0.16.58",
156
- "@stacksjs/tunnel": "0.75.256",
157
- "@stacksjs/types": "0.75.256",
158
- "@stacksjs/ui": "0.75.256",
159
- "@stacksjs/utils": "0.75.256",
160
- "@stacksjs/validation": "0.75.256",
156
+ "@stacksjs/tunnel": "0.75.258",
157
+ "@stacksjs/types": "0.75.258",
158
+ "@stacksjs/ui": "0.75.258",
159
+ "@stacksjs/utils": "0.75.258",
160
+ "@stacksjs/validation": "0.75.258",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
- "bun-plugin-stx": "^0.2.631",
164
- "ts-pantry": "^0.11.105"
163
+ "bun-plugin-stx": "0.2.644",
164
+ "ts-pantry": "^0.11.113"
165
165
  },
166
166
  "devDependencies": {
167
167
  "better-dx": "^0.2.24"