@stacksjs/buddy 0.75.85 → 0.75.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ curl -Ssf stacksjs.com/install | sh # wip
35
35
 
36
36
  # alternatively, if Bun >= v1.1.11 is installed already
37
37
  # you may also get started via
38
- panx @stacksjs/buddy new my-project
38
+ panx buddy new my-project
39
39
  ```
40
40
 
41
41
  ## Usage
@@ -77,6 +77,15 @@ export declare function serverServing(servers: any[], hosts: string[], probe: (s
77
77
  */
78
78
  export declare function onBoxDatabase(tsCloudConfig: any): Promise<{ name: string } | undefined>;
79
79
  export declare function cloud(buddy: CLI): void;
80
+ /**
81
+ * Ask before invalidating the CDN cache, unless `--yes` says not to.
82
+ *
83
+ * Neither command had any way to skip the question, so neither could run in
84
+ * CI, and the global `--force` they appeared to offer was never read
85
+ * (stacksjs/stacks#2869). A shell that cannot answer is refused with the
86
+ * flag to use, rather than left waiting on a prompt.
87
+ */
88
+ export declare function confirmInvalidation(options: { yes?: boolean }, retry: string, question: string): Promise<boolean>;
80
89
  /**
81
90
  * What tearing a server down needs, so the plan can be built without a provider.
82
91
  *
@@ -1,7 +1,7 @@
1
1
  import{existsSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{intro,italic,log,onUnknownSubcommand,outro,prompts,runCommand,text,underline}from"@stacksjs/cli";import{addJumpBox,deleteCdkRemnants,deleteIamUsers,deleteJumpBox,deleteLogGroups,deleteParameterStore,deleteStacksBuckets,deleteStacksFunctions,deleteSubnets,deleteVpcs,cloudEnvironment,diffStackTemplate,getCloudFrontDistributionId,stacksCloudRegion}from"@stacksjs/cloud";import{hasTTY,isCI}from"@stacksjs/env";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";import{isSshPipelineProvider,sshFleetFromConfigAndState}from"./deploy-ssh-target";async function createTemporaryCdkRole(roleName){const{AWSClient}=await import("@stacksjs/ts-cloud"),client=new AWSClient,trustPolicy={Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"cloudformation.amazonaws.com"},Action:"sts:AssumeRole"}]};try{try{const getRoleParams=new URLSearchParams({Action:"GetRole",RoleName:roleName,Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:getRoleParams.toString()});log.debug(`Role ${roleName} already exists`);return}catch(e){if(!e.message?.includes("NoSuchEntity")&&!e.message?.includes("cannot be found"))throw e}log.info("Creating temporary IAM role to enable stack deletion...");const createRoleParams=new URLSearchParams({Action:"CreateRole",RoleName:roleName,AssumeRolePolicyDocument:JSON.stringify(trustPolicy),Description:"Temporary role to allow CloudFormation to delete stuck stack",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:createRoleParams.toString()});log.success("Created IAM role");log.info("Attaching permissions...");const attachPolicyParams=new URLSearchParams({Action:"AttachRolePolicy",RoleName:roleName,PolicyArn:"arn:aws:iam::aws:policy/AdministratorAccess",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:attachPolicyParams.toString()});log.success("IAM role ready for stack deletion");log.info("Waiting for IAM role to propagate...");await new Promise((resolve)=>setTimeout(resolve,1e4))}catch(error){if(error.message?.includes("EntityAlreadyExists"))log.debug("Role already exists");else throw error}}async function deleteTemporaryCdkRole(roleName){const{AWSClient}=await import("@stacksjs/ts-cloud"),client=new AWSClient;try{const detachPolicyParams=new URLSearchParams({Action:"DetachRolePolicy",RoleName:roleName,PolicyArn:"arn:aws:iam::aws:policy/AdministratorAccess",Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:detachPolicyParams.toString()});const deleteRoleParams=new URLSearchParams({Action:"DeleteRole",RoleName:roleName,Version:"2010-05-08"});await client.request({service:"iam",region:"us-east-1",method:"POST",path:"/",body:deleteRoleParams.toString()});log.success("Cleaned up temporary IAM role")}catch(error){log.debug(`Could not clean up temporary role: ${error.message}`)}}function isResultError(result){return resultFailed(result)}function getResultError(result){if(!result||typeof result!=="object")return"Unknown error";return String(result.error||"Unknown error")}function getResultValue(result){if(!result||typeof result!=="object")return;return result.value}async function refuse(...messages){for(const message of messages.slice(0,-1))await log.error(message);return log.exit(messages[messages.length-1],ExitCode.FatalError)}async function driverStatePins(){const{driverStatePath}=await import("@stacksjs/ts-cloud"),dir=join(driverStatePath("probe"),"..");let files;try{files=readdirSync(dir).filter((name)=>name.endsWith(".json"))}catch{return[]}const pins=[];for(const name of files){const file=join(dir,name);try{const state=JSON.parse(readFileSync(file,"utf8"));if(typeof state?.serverName==="string")pins.push({file,state})}catch{}}return pins}function writePinName(file,next){const state=JSON.parse(readFileSync(file,"utf8"));writeFileSync(file,`${JSON.stringify({...state,serverName:next},null,2)}
2
2
  `)}export async function renameEffects(tsCloudConfig,servers,current){const taken=servers.map((s)=>String(s?.name)).filter(Boolean),effects={takenNames:async()=>taken,inventoryName:()=>String(current?.name??""),renameInventory:(next)=>{current.name=next}},pinned=(await driverStatePins()).filter((pin)=>pin.state.serverName===current?.name);if(pinned.length>0){effects.stateName=async()=>{const stale=(await driverStatePins()).find((pin)=>pin.state.serverName===current?.name);return stale?String(stale.state.serverName):void 0};effects.writeStateName=async(next)=>{for(const pin of pinned)writePinName(pin.file,next)}}const host=current?.ipv4;if(host){const{sshExec,buildSetHostnameScript}=await import("@stacksjs/ts-cloud"),ssh={user:"root",connectTimeoutSec:10};effects.remoteHostname=async()=>{const result=await sshExec(host,"hostname",ssh);if(result.code!==0)throw Error(result.stderr.trim()||`Could not reach ${host} over SSH.`);return result.stdout.trim()};effects.setRemoteHostname=async(next)=>{const result=await sshExec(host,buildSetHostnameScript(next),ssh);if(result.code!==0)throw Error(result.stderr.trim()||`Setting the hostname on ${host} failed.`)}}if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws")!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud"),{resolveHetznerApiToken}=await import("./deploy"),apiToken=resolveHetznerApiToken(tsCloudConfig),serverId=Number(current?.id);if(!apiToken||!Number.isFinite(serverId))return effects;const client=new HetznerClient({apiToken});effects.providerName=async()=>(await client.getServer(serverId))?.name;effects.renameProvider=async(next)=>{await client.renameServer(serverId,next)};return effects}export function planServerDestroy(name,effects){const steps=[{id:"provider:delete",title:`Delete the server ${name}`,change:{from:name,to:"gone"},destructive:!0,satisfied:async()=>!await effects.providerExists(),apply:async()=>await effects.deleteProvider()}];if(effects.pinnedName&&effects.clearPin)steps.push({id:"state:clear",title:"Clear the state pin that names it",change:{from:name,to:"none"},satisfied:async()=>await effects.pinnedName()!==name,apply:async()=>await effects.clearPin()});return{operation:"server:destroy",target:name,steps}}export async function destroyEffects(tsCloudConfig,current){const pinned=(await driverStatePins()).filter((pin)=>pin.state.serverName===current?.name),effects={providerExists:async()=>!0,deleteProvider:async()=>{throw Error(`No provider API for this fleet, so ${current?.name} cannot be deleted from here.`)}};if(pinned.length>0){effects.pinnedName=async()=>{const stale=(await driverStatePins()).find((pin)=>pin.state.serverName===current?.name);return stale?String(stale.state.serverName):void 0};effects.clearPin=async()=>{for(const pin of pinned){const{serverId:_id,serverName:_name,...rest}=JSON.parse(readFileSync(pin.file,"utf8"));writeFileSync(pin.file,`${JSON.stringify(rest,null,2)}
3
3
  `)}}}if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws")!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud"),{resolveHetznerApiToken}=await import("./deploy"),apiToken=resolveHetznerApiToken(tsCloudConfig),serverId=Number(current?.id);if(!apiToken||!Number.isFinite(serverId))return effects;const client=new HetznerClient({apiToken});effects.providerExists=async()=>{try{return Boolean(await client.getServer(serverId))}catch{return!1}};effects.deleteProvider=async()=>{await client.deleteServer(serverId)};return effects}export function sitesSharingHostnames(sites,siteName,hostnames,hostsOf){return Object.entries(sites??{}).filter(([name])=>name!==siteName).filter(([name,site])=>hostsOf(name,site).some((host)=>hostnames.includes(host))).map(([name,site])=>`${name} (${String(site?.path??"/")})`).sort()}async function moveEffects(context){const{slug,siteName,rawSite,source,target,tsCloudConfig}=context,{buildCertificatePackScript,buildCertificateStateScript,buildCertificateUnpackScript,buildRpxConfig,buildRpxFragmentRefreshScript,buildSshArgs,certificatesMatch,DEFAULT_RPX_CERTS_DIR,parseCertificateState,probeHostRoutes,sshExec,sshExecOrThrow}=await import("@stacksjs/ts-cloud"),{reconcileHetznerDns}=await import("./deploy"),ssh={user:"root",connectTimeoutSec:10},runOnSource=(script)=>sshExecOrThrow(source.ipv4,script,ssh),runOnTarget=(script)=>sshExecOrThrow(target.ipv4,script,ssh);async function carry(path){const args=buildSshArgs(ssh,"ssh"),reader=Bun.spawn(["ssh",...args,`root@${source.ipv4}`,`cat ${path}`],{stdout:"pipe",stderr:"pipe"}),writer=Bun.spawn(["ssh",...args,`root@${target.ipv4}`,`cat > ${path}`],{stdin:reader.stdout,stdout:"pipe",stderr:"pipe"}),[readCode,writeCode]=await Promise.all([reader.exited,writer.exited]);if(readCode!==0||writeCode!==0){const why=(await new Response(readCode===0?writer.stderr:reader.stderr).text()).trim();throw Error(why||`Carrying ${path} from ${source.name} to ${target.name} failed.`)}}const staged=async(path)=>(await sshExec(target.ipv4,`test -s ${path} && echo staged`,ssh)).stdout.includes("staged"),{siteMoveArchivePath,siteMoveCertArchivePath}=await import("@stacksjs/ts-cloud"),archive=siteMoveArchivePath(slug,siteName),effects={runOnSource,runOnTarget,archiveStaged:()=>staged(archive),transferArchive:()=>carry(archive),publishedAddress:async()=>{const host=context.hostnames[0];if(!host)return;try{const{resolve4}=await import("node:dns/promises");return(await resolve4(host))[0]}catch{return}},cutoverDns:async()=>{const warnings=[],collect=new Proxy(log,{get:(target_,key)=>key==="warn"?(message)=>{warnings.push(String(message))}:target_[key]});await reconcileHetznerDns({[siteName]:rawSite},target.ipv4,collect,target.ipv6,tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww);return warnings},targetRoutesSite:async()=>{const probe=await probeHostRoutes(target,(host,command)=>sshExec(host,command,ssh));if(probe.unavailable)return!1;return probe.routes.some((route)=>context.hostnames.includes(String(route.host)))},refreshTargetGateway:async()=>{const rpx=buildRpxConfig(tsCloudConfig?.sites??{},{proxy:tsCloudConfig?.infrastructure?.compute?.proxy??{},slug});await runOnTarget(buildRpxFragmentRefreshScript({config:rpx,slug}).join(`
4
- `))}},certArchive=siteMoveCertArchivePath(slug,siteName);effects.certificates={inPlace:async()=>{const read=async(run)=>parseCertificateState(await run(buildCertificateStateScript(DEFAULT_RPX_CERTS_DIR,context.hostnames)));return certificatesMatch(await read(runOnSource),await read(runOnTarget))},carry:async()=>{await runOnSource(buildCertificatePackScript(DEFAULT_RPX_CERTS_DIR,context.hostnames,certArchive));await carry(certArchive);await runOnTarget(buildCertificateUnpackScript(DEFAULT_RPX_CERTS_DIR,certArchive))}};return effects}export async function serverServing(servers,hosts,probe){for(const candidate of servers){if(!candidate?.ipv4)continue;const result=await probe(candidate);if(!result.unavailable&&(result.routes??[]).some((route)=>hosts.includes(String(route.host))))return candidate}return}export async function onBoxDatabase(tsCloudConfig){const{isLocalDatabase,resolveAppDatabase}=await import("@stacksjs/ts-cloud"),database=resolveAppDatabase(tsCloudConfig);if(!database||!isLocalDatabase(database))return;const engine=String(database.engine||database.driver||"");if(engine==="sqlite"||engine==="better-sqlite3")return;const name=String(database.name||"");return name?{name}:void 0}async function assertFleetProvider(tsCloudConfig,command){const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(isSshPipelineProvider(provider))return;await log.info("The on-box half (the rpx gateway registry) is provider-independent; the server listing is not yet.");await log.exit(`\`buddy ${command}\` can list Hetzner and ssh servers, and this project's provider is '${provider}'.`,ExitCode.FatalError)}function readSshStatePins(cwd=process.cwd()){const dir=join(cwd,"storage","cloud","state");if(!existsSync(dir))return[];const pins=[];for(const file of readdirSync(dir)){if(!file.endsWith(".json"))continue;try{pins.push(JSON.parse(readFileSync(join(dir,file),"utf8")))}catch{}}return pins}async function listFleet(tsCloudConfig){if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER)==="ssh"){const servers=sshFleetFromConfigAndState(tsCloudConfig,readSshStatePins());return{servers,problem:servers.length===0?"No ssh hosts are configured. Add one under `ssh.hosts` in config/cloud.ts, or set TS_CLOUD_SSH_HOST.":void 0}}const{HetznerClient,toInventoryServer}=await import("@stacksjs/ts-cloud"),{resolveHetznerApiToken}=await import("./deploy"),apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken)return{servers:[],problem:"No Hetzner API token, so no servers were looked up. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts)."};try{return{servers:(await new HetznerClient({apiToken}).listServers()).map((server)=>toInventoryServer(server)).sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const status=Number(error?.status),where=Number.isFinite(status)&&status>0?`returned HTTP ${status}`:"could not be reached";return{servers:[],problem:`The Hetzner API ${where}, so the server list is incomplete. ${error?.message??String(error)}`+(status===401||status===403?" That is an auth failure, not an empty project: check the token is valid for this Hetzner project.":"")}}}async function declaredSitesFor(tsCloudConfig,slug){const{resolveSiteKind,siteInstallBase}=await import("@stacksjs/ts-cloud");return Object.entries(tsCloudConfig?.sites??{}).map(([name,site])=>{const domain=typeof site?.domain==="string"&&site.domain.trim()?site.domain.trim():void 0,port=Number(site?.port);return{name,kind:resolveSiteKind(site),domain,path:typeof site?.path==="string"&&site.path.trim()?site.path.trim():"/",port:Number.isFinite(port)&&port>0?port:void 0,installBase:siteInstallBase(slug,name),loopbackOnly:!domain}})}function describeAttachEdits(slug,owner,edit,dryRun){const lines=[" Two edits make the attach real, in two different repositories:",""];if(edit.state==="refused"){lines.push(` 1. config/cloud.ts here: could not edit it (${edit.reason})`);lines.push(` Add \`attachTo: '${owner}'\` to the \`cloud\` block by hand.`)}else if(edit.state==="already-set")lines.push(` 1. config/cloud.ts here: already sets attachTo: '${owner}'. Nothing to do.`);else lines.push(` 1. config/cloud.ts here: ${dryRun?`would set attachTo: '${owner}' (--dry-run, not written)`:`set attachTo: '${owner}'`}`);lines.push("");lines.push(` 2. In the '${owner}' project's own repository, which this command cannot edit:`);lines.push(` add '${slug}' to the \`tenants\` array in its config/cloud.ts.`);lines.push(` Without it, that project's deploy ships ${slug.toUpperCase()}_* keys from its`);lines.push(" env files into this project's .env instead of dropping them.");lines.push("");lines.push(" Then `buddy deploy` from here puts these sites on that box.");return lines}async function runCloudDiff(){try{const{InfrastructureGenerator}=await import("@stacksjs/ts-cloud"),{tsCloud:cloudConfig}=await import("~/config/cloud"),environment=cloudEnvironment(),template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().toJSON(),result=await diffStackTemplate(template,{config:cloudConfig});if(result.isErr)return result.error.message;const diff=result.value;if(!diff.deployed)log.info(`${diff.stack} is not deployed in ${diff.region}. The whole template (${diff.localBytes} bytes) is new.`);else if(!diff.changed)log.info(`No changes detected against ${diff.stack} (${diff.region}).`);else{log.info(`Changes detected between ${diff.stack} (${diff.region}) and the local template:`);log.info(`Deployed template: ${diff.deployedBytes} bytes`);log.info(`Local template: ${diff.localBytes} bytes`)}return}catch(error){return error instanceof Error?error.message:String(error)}}export function cloud(buddy){const descriptions={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",dashboard:"Run the local Stacks Cloud management cockpit (servers, sites, deploys)",sites:"List every server and what each one is hosting, across projects",attach:"Attach this project to a server another project owns, after checking it is safe",rename:"Rename a server in place, keeping the provider, state pin, hostname and inventory in step",renameTo:"The new server name",renameEnv:"Environment whose fleet and state pin to rename in",renameJson:"Emit the rename plan as JSON",destroy:"Destroy a drained server, once nothing on it is anyone's rollback",destroyEnv:"Environment whose fleet and state pin the server belongs to",destroyJson:"Emit the teardown plan as JSON",destroyConfirm:"The exact server name, which an irreversible step requires before it runs",destroyDiscardDrained:"Destroy it even though it still holds site trees that are somebody's rollback",move:"Move a deployed site to another server, cutting DNS over once the target serves it",moveTo:"Server to move the site to, by provider name or by owning project slug",moveFrom:"Server the site is on now, when more than one could be serving it",moveEnv:"Environment whose fleet and sites to move within",moveJson:"Emit the move plan as JSON",moveConfirm:"The exact site name, which the irreversible steps require before they run",attachServer:"Server to attach to, by provider name or by owning project slug",dryRun:"Print the plan and change nothing",sitesEnv:"Environment to take the inventory for",remote:"Skip the SSH read of each box's gateway registry (co-tenants are then not listed)",json:"Emit the inventory as JSON",host:"Host to bind the dashboard to",port:"Port to bind the dashboard to",env:"Environment to manage",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("cloud",descriptions.cloud).option("--ssh",descriptions.ssh,{default:!1}).option("--connect",descriptions.ssh,{default:!1}).option("--invalidate-cache",descriptions.invalidateCache,{default:!1}).option("--paths [paths]",descriptions.paths).option("--diff",descriptions.diff,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud` ...",options);const startTime=performance.now();if(options.ssh||options.connect){const jumpBox=await addJumpBox();if(isResultError(jumpBox)){await outro("Could not find the jump box",{startTime,useSeconds:!0},getResultError(jumpBox));process.exit(ExitCode.FatalError)}const{message,state}=getResultValue(jumpBox);if(!state.instanceId){log.info(message);await outro("There is no jump box to connect to",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}const result=await runCommand(["aws","ssm","start-session","--target",state.instanceId,"--region",state.region],{...options,cwd:p.projectPath(),stdin:"inherit",stdout:"inherit"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(options.invalidateCache){if(!await prompts.confirm("Would you like to invalidate the CDN (CloudFront) cache?")){await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const{AWSCloudFrontClient}=await import("@stacksjs/ts-cloud"),cloudfront=new AWSCloudFrontClient,distributionId=await getCloudFrontDistributionId();try{const invalidationId=await cloudfront.invalidateAll(distributionId);log.success(`Invalidation created: ${invalidationId}`);log.info("Status: pending")}catch(err){log.error(`Failed to invalidate CloudFront cache: ${err.message}`)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(options.diff){const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:!0},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:add",descriptions.add).option("--jump-box","Check for the jump box, and say how to declare one if the stack has none",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:add` ...",options);const startTime=await intro("buddy cloud:add");if(options.jumpBox){const result=await addJumpBox();if(isResultError(result)){await outro("While running the cloud:add command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No jump box was added.",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has a jump box.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("This functionality is not yet implemented.");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:remove",descriptions.remove).alias("cloud:rm").alias("undeploy").option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:!1}).option("--yes","Skip confirmation prompts",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:remove` ...",options);const startTime=await intro("buddy cloud:remove"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production";if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While removing your jump-box, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("The jump box was not removed.",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has no jump box.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes&&(isCI||!hasTTY||!process.stdin.isTTY)){log.syncError(`Refusing to remove the "${environment}" cloud infrastructure from a non-interactive shell without confirmation.`);log.syncError(" \u27A1\uFE0F Re-run with `--yes` to confirm (e.g. in CI): `buddy cloud:remove --yes`");await outro("cloud:remove cancelled.",{startTime,useSeconds:!0,type:"warning"});await log.flush();process.exit(ExitCode.FatalError)}if(!options.yes){log.warning(`This will permanently delete the "${environment}" cloud infrastructure (compute, storage, CDN, and DNS managed by Stacks). This cannot be undone.`);if((await text({message:`Type the environment name "${environment}" to confirm (blank to cancel):`})).trim()!==environment){await outro("cloud:remove cancelled - confirmation did not match.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}}console.log("");console.log("Removing cloud infrastructure...");console.log(` ${italic("This typically takes 2-5 minutes.")}`);console.log("");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs"),{projectPath}=await import("@stacksjs/path"),envFiles=[projectPath(`.env.${environment}`),projectPath(".env")];for(const envPath of envFiles)if(existsSync(envPath)){const lines=readFileSync(envPath,"utf-8").split(`
5
- `);for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("="),value=valueParts.join("=").replace(/^["']|["']$/g,"");if(key==="AWS_ACCESS_KEY_ID"||key==="AWS_SECRET_ACCESS_KEY"||key==="AWS_REGION"||key==="AWS_ACCOUNT_ID")process.env[key]=value}break}}delete process.env.AWS_PROFILE;try{const{undeployStack}=await import("../../../actions/deploy"),region=await stacksCloudRegion(void 0,environment);await undeployStack({environment,region,verbose:options.verbose});await outro("Cloud infrastructure removed",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}catch(error){console.log("");console.error("\u2717 Failed to remove cloud infrastructure");const errorStr=String(error.message||error);if(errorStr.includes("security token")||errorStr.includes("credentials")){console.log("");console.error(" AWS credentials are invalid or expired");console.log(" Check your AWS credentials in .env.production:");console.log(" - AWS_ACCESS_KEY_ID");console.log(" - AWS_SECRET_ACCESS_KEY")}else if(errorStr.includes("region")||errorStr.includes("AWS_REGION")){console.log("");console.error(" AWS Region not configured");console.log(" Add AWS_REGION to your .env.production file")}else if(errorStr.includes("AccessDenied")){console.log("");console.error(" Access denied");console.log(" Your AWS credentials may not have permission to delete stacks")}else console.error(` ${errorStr}`);console.log("");console.log("Troubleshooting:");console.log(" ./buddy cloud:cleanup - Clean up resources manually");console.log(" --verbose - Show detailed error information");console.log("");if(options.verbose)console.error("Error details:",error);await outro("Failed to remove infrastructure",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}});buddy.command("cloud:optimize-cost",descriptions.optimizeCost).option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:!0}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:optimize-cost` ...",options);const startTime=await intro("buddy cloud:optimize-cost");if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While checking your jump-box, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No cost optimization was applied",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}}await outro("No cost optimization was applied",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:cleanup",descriptions.cleanUp).alias("cloud:clean-up").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:cleanup` ...",options);const startTime=await intro("buddy cloud:cleanup");delete process.env.AWS_PROFILE;log.info("Cleaning up your cloud resources will take a while to complete. Please be patient.");await new Promise((resolve)=>setTimeout(resolve,2000));const cleanupSteps=[{label:"retained S3 buckets",fn:deleteStacksBuckets},{label:"retained Lambda functions",fn:deleteStacksFunctions,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:deleteLogGroups},{label:"stored parameters",fn:deleteParameterStore},{label:"VPCs",fn:deleteVpcs},{label:"Subnets",fn:deleteSubnets},{label:"CDK remnants",fn:deleteCdkRemnants},{label:"IAM users",fn:deleteIamUsers}],errors=[];for(const step of cleanupSteps){log.info(`Removing any ${step.label}...`);try{const result=await step.fn();if(isResultError(result)){const errMsg=getResultError(result);if(!step.ignoreErrors?.includes(errMsg)){log.warn(`${step.label} cleanup issue: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}else{const value=getResultValue(result);if(value)log.info(String(value))}}catch(e){const errMsg=e.message||"AWS SDK error";log.warn(`${step.label} cleanup skipped: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}if(errors.length>0){log.warn(`Cleanup completed with ${errors.length} issue(s):`);for(const{label,error}of errors)log.warn(` - ${label}: ${error}`)}await outro("AWS resources have been removed",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:invalidate-cache",descriptions.invalidateCache).option("--paths [paths]",descriptions.paths,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:invalidate-cache` ...",options);const startTime=await intro("buddy cloud:invalidate-cache");if(!await prompts.confirm("Would you like to invalidate the CloudFront cache?")){await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const distributionId=await getCloudFrontDistributionId();if(!distributionId){await outro("Could not resolve CloudFront distribution ID",{startTime,useSeconds:!0},"Ensure your cloud stack is deployed before invalidating cache.");process.exit(ExitCode.FatalError)}const paths=options.paths?String(options.paths):"/*",result=await runCommand(`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths ${paths}`,{...options,cwd:p.projectPath(),stdin:"pipe",stdout:"pipe"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:diff",descriptions.diff).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:diff` ...",options);const startTime=await intro("buddy cloud:diff"),failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:!0},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:dashboard",descriptions.dashboard).alias("cloud:cockpit").option("--host [host]",descriptions.host,{default:"127.0.0.1"}).option("--port [port]",descriptions.port,{default:"7676"}).option("--env [env]",descriptions.env).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:dashboard` ...",options);const startTime=await intro("buddy cloud:dashboard"),tsCloud=await import("@stacksjs/ts-cloud");if(typeof tsCloud.startLocalDashboardServer!=="function"){await outro("The installed @stacksjs/ts-cloud does not provide the local cockpit yet",{startTime,useSeconds:!0},"Update your dependencies (requires @stacksjs/ts-cloud >= 0.5.27).");process.exit(ExitCode.FatalError)}try{const server=await tsCloud.startLocalDashboardServer({host:options.host?String(options.host):void 0,port:options.port?Number(options.port):void 0,environment:options.env,verbose:!!options.verbose});log.success(`Stacks Cloud cockpit running at ${underline(server.url)}`);log.info(italic("Manage servers, sites, SSH keys and deploys. Press Ctrl+C to stop."));await new Promise(()=>{})}catch(error){await outro("While starting the cloud dashboard, there was an issue",{startTime,useSeconds:!0},error?.message??String(error));process.exit(ExitCode.FatalError)}});buddy.command("cloud:sites",descriptions.sites).option("--env [env]",descriptions.sitesEnv).option("--no-remote",descriptions.remote).option("-J, --json",descriptions.json,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:sites` ...",options);const{formatInventory,probeHostRoutes}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy"),environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:sites");const listing=await listFleet(tsCloudConfig);if(listing.problem)await log.error(listing.problem);const declared=await declaredSitesFor(tsCloudConfig,slug),probes=options.remote===!1?[]:await probeFleet(listing.servers),inventory={slug,servers:listing.servers,probes,declared};if(options.json)console.log(JSON.stringify({environment,...inventory},null,2));else for(const line of formatInventory(inventory))console.log(line);process.exit(listing.problem&&listing.servers.length===0?ExitCode.FatalError:ExitCode.Success);async function probeFleet(servers){const{sshExec}=await import("@stacksjs/ts-cloud"),probes=[];for(let index=0;index<servers.length;index+=6)probes.push(...await Promise.all(servers.slice(index,index+6).map((server)=>probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})))));return probes}});buddy.command("cloud:attach",descriptions.attach).option("--server <server>",descriptions.attachServer).option("--env [env]",descriptions.sitesEnv).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.json,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:attach` ...",options);const{attachConflicts,attachIsViable,attachPreconditions,formatAttachPlan,probeHostRoutes,resolveAttachTarget,setAttachToInCloudConfig,sshExec}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy");if(!options.server)return await refuse("Which server? Pass --server <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:attach");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const target=resolveAttachTarget(listing.servers,String(options.server),environment);if("problem"in target)return await refuse(`${target.problem} \`buddy cloud:sites\` lists what is there.`);const server=target.server,preconditions=attachPreconditions(slug,server);if(preconditions.length>0)return await refuse(...preconditions);const declared=await declaredSitesFor(tsCloudConfig,slug),probe=await probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})),plan={slug,owner:server.project,server,declared,conflicts:probe.unavailable?[]:attachConflicts(slug,declared,probe.routes),registryRead:!probe.unavailable,registryProblem:probe.unavailable},viable=attachIsViable(plan),edit=viable?await applyAttachToConfig(plan.owner,Boolean(options.dryRun)):void 0;if(options.json)console.log(JSON.stringify({environment,...plan,edit},null,2));else{for(const line of formatAttachPlan(plan))console.log(line);if(edit)console.log(["",...describeAttachEdits(plan.slug,plan.owner,edit,Boolean(options.dryRun))].join(`
4
+ `))}},certArchive=siteMoveCertArchivePath(slug,siteName);effects.certificates={inPlace:async()=>{const read=async(run)=>parseCertificateState(await run(buildCertificateStateScript(DEFAULT_RPX_CERTS_DIR,context.hostnames)));return certificatesMatch(await read(runOnSource),await read(runOnTarget))},carry:async()=>{await runOnSource(buildCertificatePackScript(DEFAULT_RPX_CERTS_DIR,context.hostnames,certArchive));await carry(certArchive);await runOnTarget(buildCertificateUnpackScript(DEFAULT_RPX_CERTS_DIR,certArchive))}};return effects}export async function serverServing(servers,hosts,probe){for(const candidate of servers){if(!candidate?.ipv4)continue;const result=await probe(candidate);if(!result.unavailable&&(result.routes??[]).some((route)=>hosts.includes(String(route.host))))return candidate}return}export async function onBoxDatabase(tsCloudConfig){const{isLocalDatabase,resolveAppDatabase}=await import("@stacksjs/ts-cloud"),database=resolveAppDatabase(tsCloudConfig);if(!database||!isLocalDatabase(database))return;const engine=String(database.engine||database.driver||"");if(engine==="sqlite"||engine==="better-sqlite3")return;const name=String(database.name||"");return name?{name}:void 0}async function assertFleetProvider(tsCloudConfig,command){const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(isSshPipelineProvider(provider))return;await log.info("The on-box half (the rpx gateway registry) is provider-independent; the server listing is not yet.");await log.exit(`\`buddy ${command}\` can list Hetzner and ssh servers, and this project's provider is '${provider}'.`,ExitCode.FatalError)}function readSshStatePins(cwd=process.cwd()){const dir=join(cwd,"storage","cloud","state");if(!existsSync(dir))return[];const pins=[];for(const file of readdirSync(dir)){if(!file.endsWith(".json"))continue;try{pins.push(JSON.parse(readFileSync(join(dir,file),"utf8")))}catch{}}return pins}async function listFleet(tsCloudConfig){if((tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER)==="ssh"){const servers=sshFleetFromConfigAndState(tsCloudConfig,readSshStatePins());return{servers,problem:servers.length===0?"No ssh hosts are configured. Add one under `ssh.hosts` in config/cloud.ts, or set TS_CLOUD_SSH_HOST.":void 0}}const{HetznerClient,toInventoryServer}=await import("@stacksjs/ts-cloud"),{resolveHetznerApiToken}=await import("./deploy"),apiToken=resolveHetznerApiToken(tsCloudConfig);if(!apiToken)return{servers:[],problem:"No Hetzner API token, so no servers were looked up. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts)."};try{return{servers:(await new HetznerClient({apiToken}).listServers()).map((server)=>toInventoryServer(server)).sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const status=Number(error?.status),where=Number.isFinite(status)&&status>0?`returned HTTP ${status}`:"could not be reached";return{servers:[],problem:`The Hetzner API ${where}, so the server list is incomplete. ${error?.message??String(error)}`+(status===401||status===403?" That is an auth failure, not an empty project: check the token is valid for this Hetzner project.":"")}}}async function declaredSitesFor(tsCloudConfig,slug){const{resolveSiteKind,siteInstallBase}=await import("@stacksjs/ts-cloud");return Object.entries(tsCloudConfig?.sites??{}).map(([name,site])=>{const domain=typeof site?.domain==="string"&&site.domain.trim()?site.domain.trim():void 0,port=Number(site?.port);return{name,kind:resolveSiteKind(site),domain,path:typeof site?.path==="string"&&site.path.trim()?site.path.trim():"/",port:Number.isFinite(port)&&port>0?port:void 0,installBase:siteInstallBase(slug,name),loopbackOnly:!domain}})}function describeAttachEdits(slug,owner,edit,dryRun){const lines=[" Two edits make the attach real, in two different repositories:",""];if(edit.state==="refused"){lines.push(` 1. config/cloud.ts here: could not edit it (${edit.reason})`);lines.push(` Add \`attachTo: '${owner}'\` to the \`cloud\` block by hand.`)}else if(edit.state==="already-set")lines.push(` 1. config/cloud.ts here: already sets attachTo: '${owner}'. Nothing to do.`);else lines.push(` 1. config/cloud.ts here: ${dryRun?`would set attachTo: '${owner}' (--dry-run, not written)`:`set attachTo: '${owner}'`}`);lines.push("");lines.push(` 2. In the '${owner}' project's own repository, which this command cannot edit:`);lines.push(` add '${slug}' to the \`tenants\` array in its config/cloud.ts.`);lines.push(` Without it, that project's deploy ships ${slug.toUpperCase()}_* keys from its`);lines.push(" env files into this project's .env instead of dropping them.");lines.push("");lines.push(" Then `buddy deploy` from here puts these sites on that box.");return lines}async function runCloudDiff(){try{const{InfrastructureGenerator}=await import("@stacksjs/ts-cloud"),{tsCloud:cloudConfig}=await import("~/config/cloud"),environment=cloudEnvironment(),template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().toJSON(),result=await diffStackTemplate(template,{config:cloudConfig});if(result.isErr)return result.error.message;const diff=result.value;if(!diff.deployed)log.info(`${diff.stack} is not deployed in ${diff.region}. The whole template (${diff.localBytes} bytes) is new.`);else if(!diff.changed)log.info(`No changes detected against ${diff.stack} (${diff.region}).`);else{log.info(`Changes detected between ${diff.stack} (${diff.region}) and the local template:`);log.info(`Deployed template: ${diff.deployedBytes} bytes`);log.info(`Local template: ${diff.localBytes} bytes`)}return}catch(error){return error instanceof Error?error.message:String(error)}}export function cloud(buddy){const descriptions={cloud:"Interact with the Stacks Cloud",ssh:"SSH into the Stacks Cloud",add:"Add a resource to the Stacks Cloud",remove:"Remove the Stacks Cloud. In case it fails, try again",optimizeCost:"Remove certain resources that may be re-applied at a later time",cleanUp:"Remove all resources that were retained during the cloud deletion",invalidateCache:"Invalidate the CloudFront cache",diff:"Show the diff of the current, undeployed cloud changes ",dashboard:"Run the local Stacks Cloud management cockpit (servers, sites, deploys)",sites:"List every server and what each one is hosting, across projects",attach:"Attach this project to a server another project owns, after checking it is safe",rename:"Rename a server in place, keeping the provider, state pin, hostname and inventory in step",renameTo:"The new server name",renameEnv:"Environment whose fleet and state pin to rename in",renameJson:"Emit the rename plan as JSON",destroy:"Destroy a drained server, once nothing on it is anyone's rollback",destroyEnv:"Environment whose fleet and state pin the server belongs to",destroyJson:"Emit the teardown plan as JSON",destroyConfirm:"The exact server name, which an irreversible step requires before it runs",destroyDiscardDrained:"Destroy it even though it still holds site trees that are somebody's rollback",move:"Move a deployed site to another server, cutting DNS over once the target serves it",moveTo:"Server to move the site to, by provider name or by owning project slug",moveFrom:"Server the site is on now, when more than one could be serving it",moveEnv:"Environment whose fleet and sites to move within",moveJson:"Emit the move plan as JSON",moveConfirm:"The exact site name, which the irreversible steps require before they run",attachServer:"Server to attach to, by provider name or by owning project slug",dryRun:"Print the plan and change nothing",sitesEnv:"Environment to take the inventory for",remote:"Skip the SSH read of each box's gateway registry (co-tenants are then not listed)",json:"Emit the inventory as JSON",host:"Host to bind the dashboard to",port:"Port to bind the dashboard to",env:"Environment to manage",paths:"The paths to invalidate",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("cloud",descriptions.cloud).option("--ssh",descriptions.ssh,{default:!1}).option("--connect",descriptions.ssh,{default:!1}).option("--invalidate-cache",descriptions.invalidateCache,{default:!1}).option("--paths [paths]",descriptions.paths).option("-y, --yes","Invalidate the CDN cache without asking first",{default:!1}).option("--diff",descriptions.diff,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud` ...",options);const startTime=performance.now();if(options.ssh||options.connect){const jumpBox=await addJumpBox();if(isResultError(jumpBox)){await outro("Could not find the jump box",{startTime,useSeconds:!0},getResultError(jumpBox));process.exit(ExitCode.FatalError)}const{message,state}=getResultValue(jumpBox);if(!state.instanceId){log.info(message);await outro("There is no jump box to connect to",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}const result=await runCommand(["aws","ssm","start-session","--target",state.instanceId,"--region",state.region],{...options,cwd:p.projectPath(),stdin:"inherit",stdout:"inherit"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(options.invalidateCache){if(!await confirmInvalidation(options,"buddy cloud --invalidate-cache --yes","Would you like to invalidate the CDN (CloudFront) cache?")){await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const{AWSCloudFrontClient}=await import("@stacksjs/ts-cloud"),cloudfront=new AWSCloudFrontClient,distributionId=await getCloudFrontDistributionId();try{const invalidationId=await cloudfront.invalidateAll(distributionId);log.success(`Invalidation created: ${invalidationId}`);log.info("Status: pending")}catch(err){log.error(`Failed to invalidate CloudFront cache: ${err.message}`)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(options.diff){const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:!0},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Not implemented yet. Read more about `buddy cloud` here: https://stacksjs.com/docs/cloud");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:add",descriptions.add).option("--jump-box","Check for the jump box, and say how to declare one if the stack has none",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:add` ...",options);const startTime=await intro("buddy cloud:add");if(options.jumpBox){const result=await addJumpBox();if(isResultError(result)){await outro("While running the cloud:add command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No jump box was added.",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has a jump box.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("This functionality is not yet implemented.");await log.flush();process.exit(ExitCode.Success)});buddy.command("cloud:remove",descriptions.remove).alias("cloud:rm").alias("undeploy").option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:!1}).option("-y, --yes","Skip the confirmation prompt",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:remove` ...",options);const startTime=await intro("buddy cloud:remove"),environment=process.env.APP_ENV||process.env.NODE_ENV||"production";if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While removing your jump-box, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("The jump box was not removed.",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has no jump box.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes&&(isCI||!hasTTY||!process.stdin.isTTY)){log.syncError(`Refusing to remove the "${environment}" cloud infrastructure from a non-interactive shell without confirmation.`);log.syncError(" \u27A1\uFE0F Re-run with `--yes` to confirm (e.g. in CI): `buddy cloud:remove --yes`");await outro("cloud:remove cancelled.",{startTime,useSeconds:!0,type:"warning"});await log.flush();process.exit(ExitCode.FatalError)}if(!options.yes){log.warning(`This will permanently delete the "${environment}" cloud infrastructure (compute, storage, CDN, and DNS managed by Stacks). This cannot be undone.`);if((await text({message:`Type the environment name "${environment}" to confirm (blank to cancel):`})).trim()!==environment){await outro("cloud:remove cancelled - confirmation did not match.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}}console.log("");console.log("Removing cloud infrastructure...");console.log(` ${italic("This typically takes 2-5 minutes.")}`);console.log("");if(!process.env.AWS_ACCESS_KEY_ID||!process.env.AWS_SECRET_ACCESS_KEY){const{existsSync,readFileSync}=await import("node:fs"),{projectPath}=await import("@stacksjs/path"),envFiles=[projectPath(`.env.${environment}`),projectPath(".env")];for(const envPath of envFiles)if(existsSync(envPath)){const lines=readFileSync(envPath,"utf-8").split(`
5
+ `);for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("="),value=valueParts.join("=").replace(/^["']|["']$/g,"");if(key==="AWS_ACCESS_KEY_ID"||key==="AWS_SECRET_ACCESS_KEY"||key==="AWS_REGION"||key==="AWS_ACCOUNT_ID")process.env[key]=value}break}}delete process.env.AWS_PROFILE;try{const{undeployStack}=await import("../../../actions/deploy"),region=await stacksCloudRegion(void 0,environment);await undeployStack({environment,region,verbose:options.verbose});await outro("Cloud infrastructure removed",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}catch(error){console.log("");console.error("\u2717 Failed to remove cloud infrastructure");const errorStr=String(error.message||error);if(errorStr.includes("security token")||errorStr.includes("credentials")){console.log("");console.error(" AWS credentials are invalid or expired");console.log(" Check your AWS credentials in .env.production:");console.log(" - AWS_ACCESS_KEY_ID");console.log(" - AWS_SECRET_ACCESS_KEY")}else if(errorStr.includes("region")||errorStr.includes("AWS_REGION")){console.log("");console.error(" AWS Region not configured");console.log(" Add AWS_REGION to your .env.production file")}else if(errorStr.includes("AccessDenied")){console.log("");console.error(" Access denied");console.log(" Your AWS credentials may not have permission to delete stacks")}else console.error(` ${errorStr}`);console.log("");console.log("Troubleshooting:");console.log(" ./buddy cloud:cleanup - Clean up resources manually");console.log(" --verbose - Show detailed error information");console.log("");if(options.verbose)console.error("Error details:",error);await outro("Failed to remove infrastructure",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}});buddy.command("cloud:optimize-cost",descriptions.optimizeCost).option("--jump-box","Check for the jump box, and say how to remove it from the stack",{default:!0}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:optimize-cost` ...",options);const startTime=await intro("buddy cloud:optimize-cost");if(options.jumpBox){const result=await deleteJumpBox();if(isResultError(result)){await outro("While checking your jump-box, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}const change=getResultValue(result);log.info(change.message);if(!change.done){await outro("No cost optimization was applied",{startTime,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}}await outro("No cost optimization was applied",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:cleanup",descriptions.cleanUp).alias("cloud:clean-up").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:cleanup` ...",options);const startTime=await intro("buddy cloud:cleanup");delete process.env.AWS_PROFILE;log.info("Cleaning up your cloud resources will take a while to complete. Please be patient.");await new Promise((resolve)=>setTimeout(resolve,2000));const cleanupSteps=[{label:"retained S3 buckets",fn:deleteStacksBuckets},{label:"retained Lambda functions",fn:deleteStacksFunctions,ignoreErrors:["No stacks functions found"]},{label:"remaining Stacks logs",fn:deleteLogGroups},{label:"stored parameters",fn:deleteParameterStore},{label:"VPCs",fn:deleteVpcs},{label:"Subnets",fn:deleteSubnets},{label:"CDK remnants",fn:deleteCdkRemnants},{label:"IAM users",fn:deleteIamUsers}],errors=[];for(const step of cleanupSteps){log.info(`Removing any ${step.label}...`);try{const result=await step.fn();if(isResultError(result)){const errMsg=getResultError(result);if(!step.ignoreErrors?.includes(errMsg)){log.warn(`${step.label} cleanup issue: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}else{const value=getResultValue(result);if(value)log.info(String(value))}}catch(e){const errMsg=e.message||"AWS SDK error";log.warn(`${step.label} cleanup skipped: ${errMsg}`);errors.push({label:step.label,error:errMsg})}}if(errors.length>0){log.warn(`Cleanup completed with ${errors.length} issue(s):`);for(const{label,error}of errors)log.warn(` - ${label}: ${error}`)}await outro("AWS resources have been removed",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:invalidate-cache",descriptions.invalidateCache).option("--paths [paths]",descriptions.paths,{default:!1}).option("-y, --yes","Invalidate without asking first",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:invalidate-cache` ...",options);const startTime=await intro("buddy cloud:invalidate-cache");if(!await confirmInvalidation(options,"buddy cloud:invalidate-cache --yes","Would you like to invalidate the CloudFront cache?")){await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const distributionId=await getCloudFrontDistributionId();if(!distributionId){await outro("Could not resolve CloudFront distribution ID",{startTime,useSeconds:!0},"Ensure your cloud stack is deployed before invalidating cache.");process.exit(ExitCode.FatalError)}const paths=options.paths?String(options.paths):"/*",result=await runCommand(`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths ${paths}`,{...options,cwd:p.projectPath(),stdin:"pipe",stdout:"pipe"});if(isResultError(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:!0},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:diff",descriptions.diff).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:diff` ...",options);const startTime=await intro("buddy cloud:diff"),failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:!0},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("cloud:dashboard",descriptions.dashboard).alias("cloud:cockpit").option("--host [host]",descriptions.host,{default:"127.0.0.1"}).option("--port [port]",descriptions.port,{default:"7676"}).option("--env [env]",descriptions.env).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:dashboard` ...",options);const startTime=await intro("buddy cloud:dashboard"),tsCloud=await import("@stacksjs/ts-cloud");if(typeof tsCloud.startLocalDashboardServer!=="function"){await outro("The installed @stacksjs/ts-cloud does not provide the local cockpit yet",{startTime,useSeconds:!0},"Update your dependencies (requires @stacksjs/ts-cloud >= 0.5.27).");process.exit(ExitCode.FatalError)}try{const server=await tsCloud.startLocalDashboardServer({host:options.host?String(options.host):void 0,port:options.port?Number(options.port):void 0,environment:options.env,verbose:!!options.verbose});log.success(`Stacks Cloud cockpit running at ${underline(server.url)}`);log.info(italic("Manage servers, sites, SSH keys and deploys. Press Ctrl+C to stop."));await new Promise(()=>{})}catch(error){await outro("While starting the cloud dashboard, there was an issue",{startTime,useSeconds:!0},error?.message??String(error));process.exit(ExitCode.FatalError)}});buddy.command("cloud:sites",descriptions.sites).option("--env [env]",descriptions.sitesEnv).option("--no-remote",descriptions.remote).option("-J, --json",descriptions.json,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:sites` ...",options);const{formatInventory,probeHostRoutes}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy"),environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:sites");const listing=await listFleet(tsCloudConfig);if(listing.problem)await log.error(listing.problem);const declared=await declaredSitesFor(tsCloudConfig,slug),probes=options.remote===!1?[]:await probeFleet(listing.servers),inventory={slug,servers:listing.servers,probes,declared};if(options.json)console.log(JSON.stringify({environment,...inventory},null,2));else for(const line of formatInventory(inventory))console.log(line);process.exit(listing.problem&&listing.servers.length===0?ExitCode.FatalError:ExitCode.Success);async function probeFleet(servers){const{sshExec}=await import("@stacksjs/ts-cloud"),probes=[];for(let index=0;index<servers.length;index+=6)probes.push(...await Promise.all(servers.slice(index,index+6).map((server)=>probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})))));return probes}});buddy.command("cloud:attach",descriptions.attach).option("--server <server>",descriptions.attachServer).option("--env [env]",descriptions.sitesEnv).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.json,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy cloud:attach` ...",options);const{attachConflicts,attachIsViable,attachPreconditions,formatAttachPlan,probeHostRoutes,resolveAttachTarget,setAttachToInCloudConfig,sshExec}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy");if(!options.server)return await refuse("Which server? Pass --server <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=tsCloudConfig?.project?.slug||"app";await assertFleetProvider(tsCloudConfig,"cloud:attach");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const target=resolveAttachTarget(listing.servers,String(options.server),environment);if("problem"in target)return await refuse(`${target.problem} \`buddy cloud:sites\` lists what is there.`);const server=target.server,preconditions=attachPreconditions(slug,server);if(preconditions.length>0)return await refuse(...preconditions);const declared=await declaredSitesFor(tsCloudConfig,slug),probe=await probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})),plan={slug,owner:server.project,server,declared,conflicts:probe.unavailable?[]:attachConflicts(slug,declared,probe.routes),registryRead:!probe.unavailable,registryProblem:probe.unavailable},viable=attachIsViable(plan),edit=viable?await applyAttachToConfig(plan.owner,Boolean(options.dryRun)):void 0;if(options.json)console.log(JSON.stringify({environment,...plan,edit},null,2));else{for(const line of formatAttachPlan(plan))console.log(line);if(edit)console.log(["",...describeAttachEdits(plan.slug,plan.owner,edit,Boolean(options.dryRun))].join(`
6
6
  `))}process.exit(viable?ExitCode.Success:ExitCode.FatalError);async function applyAttachToConfig(owner,dryRun){const configPath=p.projectPath("config/cloud.ts"),{readFileSync,writeFileSync}=await import("node:fs"),before=readFileSync(configPath,"utf8");try{const after=setAttachToInCloudConfig({configText:before,owner});if(after===before)return{state:"already-set"};if(dryRun)return{state:"would-write"};writeFileSync(configPath,after);return{state:"written"}}catch(error){return{state:"refused",reason:error instanceof Error?error.message:String(error)}}}});buddy.command("cloud:rename <server>",descriptions.rename).option("--to <name>",descriptions.renameTo).option("--env [env]",descriptions.renameEnv).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.renameJson,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(server,options)=>{log.debug("Running `buddy cloud:rename` ...",options);const{applyPlan,formatPlan,pendingSteps,planServerRename,resolvePlan,validateServerName}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy");if(!options.to)return await refuse("Rename it to what? Pass --to <name>.");const next=String(options.to);try{validateServerName(next)}catch(error){return await refuse(error instanceof Error?error.message:String(error))}const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0);await assertFleetProvider(tsCloudConfig,"cloud:rename");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const current=listing.servers.find((s)=>s?.name===server);if(!current)return await refuse(`No server named ${server}. \`buddy cloud:sites\` lists what is there.`);if(server===next)return await refuse(`${server} is already called that.`);const plan=await planServerRename(server,next,await renameEffects(tsCloudConfig,listing.servers,current)),resolved=await resolvePlan(plan),pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,to:next,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`${server} is already named ${next} everywhere. Nothing to do.`);return}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`)});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`Re-run \`buddy cloud:rename ${server} --to ${next}\` to continue: completed steps skip themselves.`)}await log.success(`Renamed ${server} to ${next}`)});buddy.command("cloud:destroy <server>",descriptions.destroy).option("--env [env]",descriptions.destroyEnv).option("--confirm <name>",descriptions.destroyConfirm).option("--discard-drained",descriptions.destroyDiscardDrained,{default:!1}).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.destroyJson,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(server,options)=>{log.debug("Running `buddy cloud:destroy` ...",options);const{applyPlan,buildDrainedSiteScanScript,formatDrainedSiteRefusal,formatPlan,parseDrainedSites,pendingSteps,resolvePlan,sshExec}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy"),environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0);await assertFleetProvider(tsCloudConfig,"cloud:destroy");const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const current=listing.servers.find((s)=>s?.name===server);if(!current)return await refuse(`No server named ${server}. \`buddy cloud:sites\` lists what is there.`);const slug=String(tsCloudConfig?.project?.slug||"app");if(current.ipv4&&!options.discardDrained){const scan=await sshExec(current.ipv4,buildDrainedSiteScanScript(slug).join(`
7
- `),{user:"root",connectTimeoutSec:10});if(scan.code===0){const drained=parseDrainedSites(scan.stdout);if(drained.length>0)return await refuse(formatDrainedSiteRefusal(drained,slug,"--discard-drained"))}else if(!options.dryRun)return await refuse(`Could not scan ${server} for drained sites: ${scan.stderr.trim()||"the box did not answer over SSH."}`,"A box that cannot be scanned may still be holding a rollback. Re-run with --discard-drained if it is not.")}const plan=planServerDestroy(server,await destroyEffects(tsCloudConfig,current)),resolved=await resolvePlan(plan),pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`${server} is already gone, and nothing still points at it.`);return}if(options.confirm!==server)return await refuse(`Destroying ${server} cannot be undone.`,`Re-run with \`--confirm ${server}\` to go ahead.`);const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`Re-run \`buddy cloud:destroy ${server} --confirm ${server}\` to continue: completed steps skip themselves.`)}await log.success(`Destroyed ${server}`)});buddy.command("cloud:move <site>",descriptions.move).option("--to <server>",descriptions.moveTo).option("--from <server>",descriptions.moveFrom).option("--env [env]",descriptions.moveEnv).option("--confirm <site>",descriptions.moveConfirm).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.moveJson,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(site,options)=>{log.debug("Running `buddy cloud:move` ...",options);const{applyPlan,formatPlan,gatewayHostnames,pendingSteps,planSiteMove,probeHostRoutes,resolveAttachTarget,resolvePlan,siteInstallBase,sshExec}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy");if(!options.to)return await refuse("Move it where? Pass --to <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=String(tsCloudConfig?.project?.slug||"app");await assertFleetProvider(tsCloudConfig,"cloud:move");const rawSite=(tsCloudConfig?.sites??{})[site];if(!rawSite)return await refuse(`config/cloud.ts declares no site named '${site}'.`);const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const resolvedTarget=resolveAttachTarget(listing.servers,String(options.to),environment);if("problem"in resolvedTarget)return await refuse(`${resolvedTarget.problem} \`buddy cloud:sites\` lists what is there.`);const target=resolvedTarget.server,hostnames=gatewayHostnames({[site]:rawSite},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)}),shared=sitesSharingHostnames(tsCloudConfig?.sites??{},site,hostnames,(name,declared)=>gatewayHostnames({[name]:declared},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)}));if(shared.length>0)return await refuse(`'${site}' answers on ${hostnames.join(", ")}, and so do ${shared.length} other site(s): ${shared.join(", ")}.`,"A move repoints the hostname, not the path - so this would carry one tree to the target and send every request for the others to a box that does not have them.","Give the site its own hostname first, or move the whole set to the target and deploy once.");const source=options.from?listing.servers.find((s)=>s?.name===options.from):await serverServing(listing.servers,hostnames,(candidate)=>probeHostRoutes(candidate,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})));if(!source)return await refuse(options.from?`No server named ${options.from}.`:`Could not tell which server serves '${site}'. Pass --from <name> to say.`);if(source.name===target.name)return await refuse(`'${site}' is already on ${target.name}.`);if(!source.ipv4||!target.ipv4)return await refuse(`A move needs an address for both boxes, and ${(source.ipv4?target:source).name} has none.`);let plan;try{plan=await planSiteMove({slug,siteName:site,appBase:siteInstallBase(slug,site),from:source.name,to:target.name,targetAddress:target.ipv4,port:Number(rawSite?.port)||void 0,database:await onBoxDatabase(tsCloudConfig)},await moveEffects({tsCloudConfig,slug,siteName:site,rawSite,source,target,hostnames}))}catch(error){return await refuse(error instanceof Error?error.message:String(error))}const resolved=await resolvePlan(plan),pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,from:source.name,to:target.name,hostnames,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`'${site}' is already on ${target.name}, serving and cut over.`);return}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`The source still holds the site's files - that is the rollback. Re-run \`buddy cloud:move ${site} --to ${target.name}\` to continue: completed steps skip themselves.`)}await log.success(`Moved '${site}' from ${source.name} to ${target.name}`)});onUnknownSubcommand(buddy,"cloud")}
7
+ `),{user:"root",connectTimeoutSec:10});if(scan.code===0){const drained=parseDrainedSites(scan.stdout);if(drained.length>0)return await refuse(formatDrainedSiteRefusal(drained,slug,"--discard-drained"))}else if(!options.dryRun)return await refuse(`Could not scan ${server} for drained sites: ${scan.stderr.trim()||"the box did not answer over SSH."}`,"A box that cannot be scanned may still be holding a rollback. Re-run with --discard-drained if it is not.")}const plan=planServerDestroy(server,await destroyEffects(tsCloudConfig,current)),resolved=await resolvePlan(plan),pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`${server} is already gone, and nothing still points at it.`);return}if(options.confirm!==server)return await refuse(`Destroying ${server} cannot be undone.`,`Re-run with \`--confirm ${server}\` to go ahead.`);const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`Re-run \`buddy cloud:destroy ${server} --confirm ${server}\` to continue: completed steps skip themselves.`)}await log.success(`Destroyed ${server}`)});buddy.command("cloud:move <site>",descriptions.move).option("--to <server>",descriptions.moveTo).option("--from <server>",descriptions.moveFrom).option("--env [env]",descriptions.moveEnv).option("--confirm <site>",descriptions.moveConfirm).option("--dry-run",descriptions.dryRun,{default:!1}).option("-J, --json",descriptions.moveJson,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(site,options)=>{log.debug("Running `buddy cloud:move` ...",options);const{applyPlan,formatPlan,gatewayHostnames,pendingSteps,planSiteMove,probeHostRoutes,resolveAttachTarget,resolvePlan,siteInstallBase,sshExec}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy");if(!options.to)return await refuse("Move it where? Pass --to <name|owner-slug>. `buddy cloud:sites` lists them.");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production"),tsCloudConfig=await loadTsCloudConfig(options.env?environment:void 0),slug=String(tsCloudConfig?.project?.slug||"app");await assertFleetProvider(tsCloudConfig,"cloud:move");const rawSite=(tsCloudConfig?.sites??{})[site];if(!rawSite)return await refuse(`config/cloud.ts declares no site named '${site}'.`);const listing=await listFleet(tsCloudConfig);if(listing.problem)return await refuse(listing.problem);const resolvedTarget=resolveAttachTarget(listing.servers,String(options.to),environment);if("problem"in resolvedTarget)return await refuse(`${resolvedTarget.problem} \`buddy cloud:sites\` lists what is there.`);const target=resolvedTarget.server,hostnames=gatewayHostnames({[site]:rawSite},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)}),shared=sitesSharingHostnames(tsCloudConfig?.sites??{},site,hostnames,(name,declared)=>gatewayHostnames({[name]:declared},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)}));if(shared.length>0)return await refuse(`'${site}' answers on ${hostnames.join(", ")}, and so do ${shared.length} other site(s): ${shared.join(", ")}.`,"A move repoints the hostname, not the path - so this would carry one tree to the target and send every request for the others to a box that does not have them.","Give the site its own hostname first, or move the whole set to the target and deploy once.");const source=options.from?listing.servers.find((s)=>s?.name===options.from):await serverServing(listing.servers,hostnames,(candidate)=>probeHostRoutes(candidate,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10})));if(!source)return await refuse(options.from?`No server named ${options.from}.`:`Could not tell which server serves '${site}'. Pass --from <name> to say.`);if(source.name===target.name)return await refuse(`'${site}' is already on ${target.name}.`);if(!source.ipv4||!target.ipv4)return await refuse(`A move needs an address for both boxes, and ${(source.ipv4?target:source).name} has none.`);let plan;try{plan=await planSiteMove({slug,siteName:site,appBase:siteInstallBase(slug,site),from:source.name,to:target.name,targetAddress:target.ipv4,port:Number(rawSite?.port)||void 0,database:await onBoxDatabase(tsCloudConfig)},await moveEffects({tsCloudConfig,slug,siteName:site,rawSite,source,target,hostnames}))}catch(error){return await refuse(error instanceof Error?error.message:String(error))}const resolved=await resolvePlan(plan),pending=pendingSteps(resolved);if(options.json){console.log(JSON.stringify({operation:plan.operation,target:plan.target,from:source.name,to:target.name,hostnames,steps:resolved.map((entry)=>({id:entry.step.id,title:entry.step.title,state:entry.state,reason:entry.reason,destructive:entry.step.destructive,change:entry.step.change}))},null,2));return}console.log("");for(const line of formatPlan(plan,resolved))console.log(line);console.log("");if(options.dryRun){await log.info(`Dry run: ${pending.length} step(s) would run. Nothing changed.`);return}if(pending.length===0){await log.success(`'${site}' is already on ${target.name}, serving and cut over.`);return}const outcome=await applyPlan(plan,resolved,{log:(message)=>console.log(` ${message}`),confirm:options.confirm});if(!outcome.success){const failed=outcome.steps.find((step)=>step.state==="failed");return await refuse(`Stopped at: ${failed?.title??"an unnamed step"}`,failed?.error??"The step gave no reason.",`The source still holds the site's files - that is the rollback. Re-run \`buddy cloud:move ${site} --to ${target.name}\` to continue: completed steps skip themselves.`)}await log.success(`Moved '${site}' from ${source.name} to ${target.name}`)});onUnknownSubcommand(buddy,"cloud")}export async function confirmInvalidation(options,retry,question){if(options.yes)return!0;if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError("Refusing to invalidate the CDN cache from a non-interactive shell without confirmation.");log.syncError(` \u27A1\uFE0F Re-run with \`--yes\`: \`${retry}\``);await log.flush();process.exit(ExitCode.FatalError)}return await prompts.confirm(question)}
@@ -1,4 +1,4 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{bgCyan,bold,intro,italic,log,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{awaitConfig}from"@stacksjs/config";import{addDomain}from"@stacksjs/dns";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function domains(buddy){const descriptions={purchase:"Purchase a domain",add:"Add a domain to your cloud",remove:"Remove a domain from your cloud",skip:"Skip the confirmation prompt",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("domains:purchase <domain>",descriptions.purchase).option("--years <years>","Number of years to purchase the domain for").option("--privacy","Enable privacy protection; --no-privacy disables it (default: contactInfo.privacy, else on)").option("--auto-renew","Enable auto-renew; --no-auto-renew disables it (default: on)").option("--first-name <firstName>","Registrant first name").option("--last-name <lastName>","Registrant last name").option("--organization <organization>","Registrant organization name").option("--address-line1 <address>","Registrant address line 1").option("--address-line2 <address>","Registrant address line 2").option("--city <city>","Registrant city").option("--state <state>","Registrant state").option("--country <country>","Registrant country code").option("--zip <zip>","Registrant zip").option("--phone <phone>","Registrant phone").option("--email <email>","Registrant email").option("--admin-first-name <firstName>","Admin first name").option("--admin-last-name <lastName>","Admin last name").option("--admin-organization <organization>","Admin organization").option("--admin-address-line1 <address>","Admin address line 1").option("--admin-address-line2 <address>","Admin address line 2").option("--admin-city <city>","Admin city").option("--admin-state <state>","Admin state").option("--admin-country <country>","Admin country code").option("--admin-zip <zip>","Admin zip").option("--admin-phone <phone>","Admin phone number").option("--admin-email <email>","Admin email").option("--tech-first-name <firstName>","Tech first name").option("--tech-last-name <lastName>","Tech last name").option("--tech-organization <organization>","Tech organization name").option("--tech-address-line1 <address>","Tech address line 1").option("--tech-address-line2 <address>","Tech address line 2").option("--tech-city <city>","Tech city").option("--tech-state <state>","Tech state").option("--tech-country <country>","Tech country").option("--tech-zip <zip>","Tech zip").option("--tech-phone <phone>","Tech phone").option("--tech-email <email>","Tech email").option("--contact-type <type>","Contact type (default: contactInfo.contactType, else person)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:purchase <domain>` ...",options);options.domain=domain;const forwarded={...options};for(const key of["privacy","autoRenew"])if(forwarded[key]===!1)forwarded[key]="false";const startTime=await intro("buddy domains:purchase"),result=await runAction(Action.DomainsPurchase,forwarded);if(resultFailed(result)){await outro("While running the domains:purchase command, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(!await prompts.confirm(`Would you like to set ${domain} as your APP_URL?`)){await outro(`Alrighty! ${italic(domain)} was added to your account.`,{startTime,useSeconds:!0,type:"success"});const{dns}=await awaitConfig(),email=options.email||dns?.contactInfo?.email;log.info(`Please note, you may need to validate your email address. Check your ${italic(email??"registrant")} inbox.`);await log.flush();process.exit(ExitCode.Success)}const{writeEnv}=await import("@stacksjs/env");writeEnv("APP_URL",domain);let message=`Great! ${italic(domain)} was added to your account.`;message+=`
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{bgCyan,bold,intro,italic,log,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{awaitConfig}from"@stacksjs/config";import{addDomain}from"@stacksjs/dns";import{hasTTY,isCI}from"@stacksjs/env";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function domains(buddy){const descriptions={purchase:"Purchase a domain",add:"Add a domain to your cloud",remove:"Remove a domain from your cloud",skip:"Skip the confirmation prompt",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("domains:purchase <domain>",descriptions.purchase).option("--years <years>","Number of years to purchase the domain for").option("--privacy","Enable privacy protection; --no-privacy disables it (default: contactInfo.privacy, else on)").option("--auto-renew","Enable auto-renew; --no-auto-renew disables it (default: on)").option("--first-name <firstName>","Registrant first name").option("--last-name <lastName>","Registrant last name").option("--organization <organization>","Registrant organization name").option("--address-line1 <address>","Registrant address line 1").option("--address-line2 <address>","Registrant address line 2").option("--city <city>","Registrant city").option("--state <state>","Registrant state").option("--country <country>","Registrant country code").option("--zip <zip>","Registrant zip").option("--phone <phone>","Registrant phone").option("--email <email>","Registrant email").option("--admin-first-name <firstName>","Admin first name").option("--admin-last-name <lastName>","Admin last name").option("--admin-organization <organization>","Admin organization").option("--admin-address-line1 <address>","Admin address line 1").option("--admin-address-line2 <address>","Admin address line 2").option("--admin-city <city>","Admin city").option("--admin-state <state>","Admin state").option("--admin-country <country>","Admin country code").option("--admin-zip <zip>","Admin zip").option("--admin-phone <phone>","Admin phone number").option("--admin-email <email>","Admin email").option("--tech-first-name <firstName>","Tech first name").option("--tech-last-name <lastName>","Tech last name").option("--tech-organization <organization>","Tech organization name").option("--tech-address-line1 <address>","Tech address line 1").option("--tech-address-line2 <address>","Tech address line 2").option("--tech-city <city>","Tech city").option("--tech-state <state>","Tech state").option("--tech-country <country>","Tech country").option("--tech-zip <zip>","Tech zip").option("--tech-phone <phone>","Tech phone").option("--tech-email <email>","Tech email").option("--contact-type <type>","Contact type (default: contactInfo.contactType, else person)").option("-y, --yes","Register (and pay for) the domain without asking first",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:purchase <domain>` ...",options);options.domain=domain;const{yes,y,...rest}=options,forwarded={...rest};for(const key of["privacy","autoRenew"])if(forwarded[key]===!1)forwarded[key]="false";const startTime=await intro("buddy domains:purchase"),interactive=!isCI&&hasTTY&&Boolean(process.stdin.isTTY);if(!yes){if(!interactive){log.syncError(`Refusing to register ${domain} from a non-interactive shell without confirmation.`);log.syncError(` \u27A1\uFE0F Re-run with \`--yes\`: \`buddy domains:purchase ${domain} --yes\``);await log.flush();process.exit(ExitCode.FatalError)}const years=Number(options.years)||1;if(!await prompts.confirm(`Register ${domain} for ${years} year${years===1?"":"s"}? Route 53 bills your AWS account and does not refund registrations.`)){await outro("Cancelled the domains:purchase command",{startTime,useSeconds:!0,type:"info"});process.exit(ExitCode.Success)}}const result=await runAction(Action.DomainsPurchase,forwarded);if(resultFailed(result)){await outro("While running the domains:purchase command, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(!(!yes&&interactive&&await prompts.confirm(`Would you like to set ${domain} as your APP_URL?`))){await outro(`Alrighty! ${italic(domain)} was added to your account.`,{startTime,useSeconds:!0,type:"success"});const{dns}=await awaitConfig(),email=options.email||dns?.contactInfo?.email;log.info(`Please note, you may need to validate your email address. Check your ${italic(email??"registrant")} inbox.`);if(yes||!interactive)log.info(`APP_URL was left as it is. To serve the app from ${domain}, run \`buddy env:set APP_URL ${domain}\`.`);await log.flush();process.exit(ExitCode.Success)}const{writeEnv}=await import("@stacksjs/env");writeEnv("APP_URL",domain);let message=`Great! ${italic(domain)} was added to your account.`;message+=`
2
2
 
3
3
  And your APP_URL has been set to ${italic(domain)}.
4
4
 
@@ -6,4 +6,4 @@ Please note, this change has not been deployed yet.
6
6
 
7
7
  The next time you run ${bgCyan(italic(bold(" buddy deploy ")))}, your app will deploy to ${italic(domain)}.
8
8
 
9
- ${italic("You may need to deploy 2-3 times for the changes to take effect. Issue tracked here: https://github.com/stacksjs/stacks/issues/685")}`;await outro(message,{startTime,useSeconds:!0,type:"info"});process.exit(ExitCode.Success)});buddy.command("domains:add <domain>",descriptions.add).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:add <domain>` ...",options);const startTime=await intro("buddy domains:add"),result=await addDomain({...options,domain,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)});buddy.command("domains:remove <domain>",descriptions.remove).option("--yes",descriptions.skip,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:remove <domain>` ...",options);const opts={...options,domain},startTime=await intro("buddy domains:remove");if(!opts.yes){if(!await prompts.confirm(`Are you sure you want to remove ${domain}?`)){await outro("Cancelled the domains:remove command",{startTime,useSeconds:!0,type:"info"});process.exit(ExitCode.Success)}}const result=await runAction(Action.DomainsRemove,opts);if(resultFailed(result)){await outro("While running the domains:remove command, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Removed your domain DNS records.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"domains")}
9
+ ${italic("You may need to deploy 2-3 times for the changes to take effect. Issue tracked here: https://github.com/stacksjs/stacks/issues/685")}`;await outro(message,{startTime,useSeconds:!0,type:"info"});process.exit(ExitCode.Success)});buddy.command("domains:add <domain>",descriptions.add).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:add <domain>` ...",options);const startTime=await intro("buddy domains:add"),result=await addDomain({...options,domain,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)});buddy.command("domains:remove <domain>",descriptions.remove).option("-y, --yes",descriptions.skip,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(domain,options)=>{log.debug("Running `buddy domains:remove <domain>` ...",options);const opts={...options,domain},startTime=await intro("buddy domains:remove");if(!opts.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError(`Refusing to remove ${domain} from a non-interactive shell without confirmation.`);log.syncError(` \u27A1\uFE0F Re-run with \`--yes\`: \`buddy domains:remove ${domain} --yes\``);await log.flush();process.exit(ExitCode.FatalError)}if(!await prompts.confirm(`Are you sure you want to remove ${domain}?`)){await outro("Cancelled the domains:remove command",{startTime,useSeconds:!0,type:"info"});process.exit(ExitCode.Success)}}const result=await runAction(Action.DomainsRemove,opts);if(resultFailed(result)){await outro("While running the domains:remove command, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Removed your domain DNS records.",{startTime,useSeconds:!0});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"domains")}
@@ -1,6 +1,7 @@
1
1
  import { FEATURE_FILES, FEATURE_NAMES, migrationFeature } from '@stacksjs/features';
2
2
  import type { CLI } from '@stacksjs/types';
3
3
  import type { FeatureName } from '@stacksjs/features';
4
+ import type { StacksFeature } from '@stacksjs/config';
4
5
  /**
5
6
  * Feature install / uninstall commands.
6
7
  *
@@ -87,7 +88,7 @@ export declare function copyFeatureFiles(feature: FeatureName, options?: CopyFea
87
88
  * whether the feature is actually on, because it also applies the optional
88
89
  * `env: [...]` narrowing and any runtime override.
89
90
  */
90
- export declare function readFeatureFlag(feature: FeatureName, root?: string): true | false | 'absent' | 'unset';
91
+ export declare function readFeatureFlag(feature: StacksFeature, root?: string): true | false | 'absent' | 'unset';
91
92
  /**
92
93
  * Migrations the feature owns, split by whether the runner has hidden them.
93
94
  *
@@ -115,6 +116,22 @@ export declare function setFeatureEnabled(feature: FeatureName, enabled: boolean
115
116
  */
116
117
  export declare function uninstallAllFeatures(options?: { root?: string }): Promise<UninstallAllFeaturesResult[]>;
117
118
  export declare function features(buddy: CLI): void;
119
+ /**
120
+ * The names `feature()` answers for that are not installable bundles: a
121
+ * config section switches each one, and there is nothing to install.
122
+ *
123
+ * Keyed on what `StacksFeature` has beyond `FeatureName`, so a gate added to
124
+ * `@stacksjs/config` without a line here does not compile, and `buddy
125
+ * features` cannot fall behind `listFeatures()` again (stacksjs/stacks#2867).
126
+ * @defaultValue
127
+ * ```ts
128
+ * {
129
+ * auth: 'Loads the account models (Team, Referral, SocialAccount, Subscriber, Subscription, Site, ...). Auth routes are STACKS_DEFAULT_ROUTES, not this.',
130
+ * email: 'Mounts the email provider webhook routes, when STACKS_DEFAULT_ROUTES does not name the bundles.'
131
+ * }
132
+ * ```
133
+ */
134
+ export declare const CONFIG_GATES: Record<Exclude<StacksFeature, FeatureName>, string>;
118
135
  export declare interface DeleteFeatureFilesOptions {
119
136
  force?: boolean
120
137
  source?: string
@@ -1,4 +1,4 @@
1
- import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes:!0})){const rel=prefix?`${prefix}/${entry.name}`:entry.name;if(entry.isDirectory())out.push(...filesUnder(join(dir,entry.name),rel));else out.push(rel)}return out}function matchesTemplate(projectFile,templateFile){if(!existsSync(templateFile))return!1;try{return readFileSync(projectFile).equals(readFileSync(templateFile))}catch{return!1}}function pruneEmptyDirs(root,dir){let current=dir;while(current.startsWith(root)&&current!==root){try{if(readdirSync(current).length>0)return;rmdirSync(current)}catch{return}current=join(current,"..")}}export async function deleteFeatureFiles(feature,root=projectPath(),options={}){const source=options.source??frameworkPath("defaults"),force=options.force===!0,dryRun=options.dryRun===!0,remove=async(path,recursive=!1)=>{if(!dryRun)await rm(path,{recursive,force:!0})},removed=[],preserved=[];for(const rel of FEATURE_FILES[feature]){const full=join(root,rel);if(!existsSync(full))continue;if(force){await remove(full,!0);removed.push(rel);continue}const template=join(source,rel);if(!statSync(full).isDirectory()){if(matchesTemplate(full,template)){await remove(full);removed.push(rel)}else preserved.push(rel);continue}let keptAny=!1;for(const child of filesUnder(full)){const projectFile=join(full,child);if(matchesTemplate(projectFile,join(template,child))){await remove(projectFile);removed.push(`${rel}${child}`)}else{keptAny=!0;preserved.push(`${rel}${child}`)}}if(dryRun)continue;pruneEmptyDirs(root,full);if(!keptAny&&existsSync(full))await rm(full,{recursive:!0,force:!0})}return{removed,preserved}}export async function copyFeatureFiles(feature,options={}){const source=options.source??frameworkPath("defaults"),target=options.target??projectPath(),force=options.force===!0,copied=[],skipped=[];for(const rel of FEATURE_FILES[feature]){const sourceFull=join(source,rel);if(!existsSync(sourceFull)){skipped.push(rel);continue}const targetFull=join(target,rel);if(existsSync(targetFull)&&!force){skipped.push(rel);continue}if(options.dryRun!==!0)await cp(sourceFull,targetFull,{recursive:!0,force});copied.push(rel)}return{copied,skipped}}const FEATURE_DESCRIPTIONS={dashboard:"Admin SPA shell + Activity/Log/Request/Deployment/Notification dashboards.",commerce:"Order/Cart/Product/Customer/Coupon/GiftCard/Shipping + storefront API.",cms:"Post/Page/Author/Comment/Tag models + content edit dashboards.",forms:"User-defined forms: builder models, conditional fields, public submit + CSV export.",marketing:"/api/email/subscribe, /api/contact, Campaign/EmailList/SocialPost.",monitoring:"Error model + error-tracking views and actions.",realtime:"WebSocket broadcaster + Websocket model + realtime-stats actions.",queue:"Job + FailedJob models + queue dashboard pages."},STARTER_TEMPLATES={dashboard:`import type { DashboardConfig } from '@stacksjs/types'
1
+ import{existsSync,readdirSync,readFileSync,rmdirSync,statSync}from"node:fs";import{cp,rm}from"node:fs/promises";import{join}from"node:path";import process from"node:process";import{confirmOrNull,runCommand}from"@stacksjs/cli";import{frameworkPath,projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultError,resultFailed}from"../result";export{appModelClaimsTable,FEATURE_FILES,FEATURE_NAMES,FEATURE_TABLES,migrationFeature,migrationTable}from"@stacksjs/features";import{FEATURE_FILES,FEATURE_NAMES,migrationFeature}from"@stacksjs/features";export function featurePathsPresent(feature,root=projectPath()){return FEATURE_FILES[feature].filter((rel)=>existsSync(`${root}/${rel}`))}function filesUnder(dir,prefix=""){const out=[];for(const entry of readdirSync(dir,{withFileTypes:!0})){const rel=prefix?`${prefix}/${entry.name}`:entry.name;if(entry.isDirectory())out.push(...filesUnder(join(dir,entry.name),rel));else out.push(rel)}return out}function matchesTemplate(projectFile,templateFile){if(!existsSync(templateFile))return!1;try{return readFileSync(projectFile).equals(readFileSync(templateFile))}catch{return!1}}function pruneEmptyDirs(root,dir){let current=dir;while(current.startsWith(root)&&current!==root){try{if(readdirSync(current).length>0)return;rmdirSync(current)}catch{return}current=join(current,"..")}}export async function deleteFeatureFiles(feature,root=projectPath(),options={}){const source=options.source??frameworkPath("defaults"),force=options.force===!0,dryRun=options.dryRun===!0,remove=async(path,recursive=!1)=>{if(!dryRun)await rm(path,{recursive,force:!0})},removed=[],preserved=[];for(const rel of FEATURE_FILES[feature]){const full=join(root,rel);if(!existsSync(full))continue;if(force){await remove(full,!0);removed.push(rel);continue}const template=join(source,rel);if(!statSync(full).isDirectory()){if(matchesTemplate(full,template)){await remove(full);removed.push(rel)}else preserved.push(rel);continue}let keptAny=!1;for(const child of filesUnder(full)){const projectFile=join(full,child);if(matchesTemplate(projectFile,join(template,child))){await remove(projectFile);removed.push(`${rel}${child}`)}else{keptAny=!0;preserved.push(`${rel}${child}`)}}if(dryRun)continue;pruneEmptyDirs(root,full);if(!keptAny&&existsSync(full))await rm(full,{recursive:!0,force:!0})}return{removed,preserved}}export async function copyFeatureFiles(feature,options={}){const source=options.source??frameworkPath("defaults"),target=options.target??projectPath(),force=options.force===!0,copied=[],skipped=[];for(const rel of FEATURE_FILES[feature]){const sourceFull=join(source,rel);if(!existsSync(sourceFull)){skipped.push(rel);continue}const targetFull=join(target,rel);if(existsSync(targetFull)&&!force){skipped.push(rel);continue}if(options.dryRun!==!0)await cp(sourceFull,targetFull,{recursive:!0,force});copied.push(rel)}return{copied,skipped}}const FEATURE_DESCRIPTIONS={dashboard:"Admin SPA shell + Activity/Log/Request/Deployment/Notification dashboards.",commerce:"Order/Cart/Product/Customer/Coupon/GiftCard/Shipping + storefront API.",cms:"Post/Page/Author/Comment/Tag models + content edit dashboards.",forms:"User-defined forms: builder models, conditional fields, public submit + CSV export.",marketing:"/api/email/subscribe, /api/contact, Campaign/EmailList/SocialPost.",monitoring:"Error model + error-tracking views and actions.",realtime:"WebSocket broadcaster + Websocket model + realtime-stats actions.",queue:"Job + FailedJob models + queue dashboard pages."};export const CONFIG_GATES={auth:"Loads the account models (Team, Referral, SocialAccount, Subscriber, Subscription, Site, ...). Auth routes are STACKS_DEFAULT_ROUTES, not this.",email:"Mounts the email provider webhook routes, when STACKS_DEFAULT_ROUTES does not name the bundles."};const STARTER_TEMPLATES={dashboard:`import type { DashboardConfig } from '@stacksjs/types'
2
2
 
3
3
  /**
4
4
  * **Dashboard Configuration**
@@ -127,4 +127,4 @@ export default {
127
127
  },
128
128
  } satisfies QueueConfig
129
129
  `};function withoutComments(src){return src.replace(/\/\*[\s\S]*?\*\//g,(m)=>" ".repeat(m.length)).replace(/\/\/[^\n]*/g,(m)=>" ".repeat(m.length))}function findTopLevelEnabled(src){const scan=withoutComments(src),start=scan.search(/export default\s*\{/);if(start===-1)return null;const open=scan.indexOf("{",start);let depth=0;for(let i=open;i<scan.length;i++){const char=scan[i];if(char==="{"){depth++;continue}if(char==="}"){depth--;if(depth===0)return null;continue}if(depth!==1||char!=="e")continue;const match=/^enabled\s*:\s*(true|false)/.exec(scan.slice(i));if(!match)continue;if(i>0&&/[\w$]/.test(scan[i-1]))continue;return{index:i,length:match[0].length,value:match[1]==="true"}}return null}export function readFeatureFlag(feature,root=projectPath()){const path=join(root,`config/${feature}.ts`);if(!existsSync(path))return"absent";const found=findTopLevelEnabled(readFileSync(path,"utf8"));if(!found)return"unset";return found.value}export function featureMigrationCounts(feature,root=projectPath()){const counts={active:0,hidden:0},base=join(root,"database/migrations");if(!existsSync(base))return counts;const dirs=[base];for(const entry of readdirSync(base,{withFileTypes:!0}))if(entry.isDirectory())dirs.push(join(base,entry.name));for(const dir of dirs)for(const file of readdirSync(dir)){const hidden=file.endsWith(".sql.disabled");if(!hidden&&!file.endsWith(".sql"))continue;const sqlName=hidden?file.slice(0,-9):file;if(migrationFeature(sqlName)!==feature)continue;if(hidden)counts.hidden++;else counts.active++}return counts}export async function setFeatureEnabled(feature,enabled,options){const write=async(target,contents)=>{if(options.dryRun!==!0)await Bun.write(target,contents)},path=options.root?join(options.root,`config/${feature}.ts`):projectPath(`config/${feature}.ts`),file=Bun.file(path);if(!await file.exists()){if(!options.createIfMissing)return"missing";await write(path,STARTER_TEMPLATES[feature]);return"created"}const src=await file.text(),found=findTopLevelEnabled(src);if(found){if(found.value===enabled)return"unchanged";const replaced=src.slice(0,found.index)+`enabled: ${enabled}`+src.slice(found.index+found.length);await write(path,replaced);return"flipped"}const insertRegex=/(export default\s*\{)/;if(!insertRegex.test(src))throw Error(`Could not locate \`export default {\` in ${path} - please add \`enabled: ${enabled}\` manually.`);const next=src.replace(insertRegex,`$1
130
- enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath(),results=[];for(const feature of FEATURE_NAMES){const configOutcome=await setFeatureEnabled(feature,!1,{createIfMissing:!1,root}),{removed:filesRemoved}=await deleteFeatureFiles(feature,root,{force:!0});results.push({feature,configOutcome,filesRemoved})}return results}function isDryRun(options){return options.dryRun===!0||process.argv.includes("--dry-run")}async function offerMigrate(feature){const{active,hidden}=featureMigrationCounts(feature),total=active+hidden;if(total===0)return;console.log(` \u2192 ${feature} owns ${total} ${total===1?"migration":"migrations"}; its tables do not exist until they run.`);const answer=await confirmOrNull({message:"Run ./buddy migrate now?",initial:!1});if(answer!==!0){console.log(answer===null?" \u2192 Not asking (non-interactive). Run ./buddy migrate when ready.":" \u2192 Skipped. Run ./buddy migrate when ready.");return}const result=await runCommand("./buddy migrate",{cwd:projectPath()});if(resultFailed(result)){console.error(`\u2717 ./buddy migrate failed: ${resultError(result)}`);console.error(` \u2192 ${feature} is installed; re-run ./buddy migrate once that is resolved.`);return}console.log("\u2713 Migrated.")}function registerInstallPair(buddy,feature){const desc=FEATURE_DESCRIPTIONS[feature],configRel=`config/${feature}.ts`;buddy.command(`${feature}:install`,`Activate the ${feature} feature bundle. ${desc}`).option("--force",`Overwrite any existing ${feature} files in the project (default skips existing paths so the install is idempotent).`).option("--dry-run",`Say what ${feature}:install would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!0,{createIfMissing:!0,dryRun})){case"created":console.log(dryRun?`${mark} Would create ${configRel} with '${feature}' enabled.`:`${mark} Created ${configRel} with '${feature}' enabled.`);break;case"flipped":console.log(dryRun?`${mark} Would enable '${feature}' in ${configRel}.`:`${mark} Enabled '${feature}' in ${configRel}.`);break;case"unchanged":console.log(`${mark} '${feature}' is already enabled in ${configRel}.`);break}const{copied}=await copyFeatureFiles(feature,{force:options.force===!0,dryRun});if(copied.length>0){console.log(dryRun?`${mark} Would copy ${copied.length} stamped path(s) from framework defaults:`:`${mark} Copied ${copied.length} stamped path(s) from framework defaults:`);for(const path of copied)console.log(` - ${path}`)}else if(featurePathsPresent(feature).length>0)console.log(` \u2192 ${feature} scaffolding already in place - use --force to overwrite.`);if(dryRun){console.log(` \u2192 Dry run: nothing was written. Run it without --dry-run to install ${feature}.`);process.exit(ExitCode.Success)}await offerMigrate(feature);console.log(` \u2192 next ./buddy dev will boot with ${feature} loaded.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to install ${feature}:`,err);process.exit(ExitCode.FatalError)}});buddy.command(`${feature}:uninstall`,`Deactivate the ${feature} feature bundle.`).option("--keep-files",`Don't delete the ${feature} scaffolding (action/model/view files). Flip the flag only.`).option("--force",`Delete the ${feature} scaffolding even where you have edited it. Without this, changed files are kept.`).option("--dry-run",`Say what ${feature}:uninstall would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!1,{createIfMissing:!1,dryRun})){case"missing":console.log(`${mark} '${feature}' is already disabled (${configRel} is absent).`);break;case"flipped":console.log(dryRun?`${mark} Would disable '${feature}' in ${configRel}.`:`${mark} Disabled '${feature}' in ${configRel}. Custom config preserved.`);break;case"unchanged":console.log(`${mark} '${feature}' is already disabled in ${configRel}.`);break;case"created":console.log(`\u2717 Unexpected create on uninstall for ${feature}; please re-run with --force or report this bug.`);break}if(options.keepFiles){const stillPresent=featurePathsPresent(feature);if(stillPresent.length>0)console.log(` \u2192 ${stillPresent.length} stamped path(s) preserved (--keep-files).`)}else{const{removed,preserved}=await deleteFeatureFiles(feature,projectPath(),{force:options.force,dryRun});if(removed.length>0){console.log(dryRun?`${mark} Would remove ${removed.length} stamped path(s):`:`${mark} Removed ${removed.length} stamped path(s):`);for(const path of removed)console.log(` - ${path}`)}if(preserved.length>0){console.log(dryRun?` \u2192 Would keep ${preserved.length} path(s) you have edited (--force would remove them):`:` \u2192 Kept ${preserved.length} path(s) you have edited (re-run with --force to remove):`);for(const path of preserved)console.log(` - ${path}`)}}console.log(dryRun?` \u2192 Dry run: nothing was written or removed. Run it without --dry-run to uninstall ${feature}.`:` \u2192 next ./buddy dev will boot without ${feature}.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to uninstall ${feature}:`,err);process.exit(ExitCode.FatalError)}})}function registerStatus(buddy){buddy.command("features","Show which framework feature bundles are active.").action(async()=>{try{const{feature,overridesReady}=await import("@stacksjs/config");await overridesReady;const rows=FEATURE_NAMES.map((name)=>{const declared=readFeatureFlag(name),active=feature(name),migrations=featureMigrationCounts(name);return{name,declared,active,migrations,scaffolded:featurePathsPresent(name).length}}),enabled=rows.filter((r)=>r.active).length;console.log("");console.log(`Feature bundles (${enabled} of ${rows.length} active)`);console.log("");for(const row of rows){const mark=row.active?"\u2713":"\xB7",declared=row.declared==="absent"?"no config":row.declared==="unset"?"flag unset":`enabled: ${row.declared}`,parts=[`${mark} ${row.name.padEnd(11)}`,declared.padEnd(14)],total=row.migrations.active+row.migrations.hidden,plural=total===1?"migration":"migrations";if(total>0)parts.push(row.migrations.hidden>0?`${total} ${plural} (${row.migrations.hidden} hidden)`:`${total} ${plural}`);else parts.push("");console.log(` ${parts.join(" ")}`);if(row.declared===!0&&!row.active)console.log(` declared on but reading off - check \`env\` in config/${row.name}.ts against config.app.env`);if(row.declared===!1&&row.active)console.log(" declared off but reading on - a runtime override is in play");if(!row.active&&row.scaffolded>0)console.log(` ${row.scaffolded} scaffolded path(s) still present - \`./buddy ${row.name}:uninstall\` removes them`);if(row.active&&row.migrations.hidden>0)console.log(` ${row.migrations.hidden} migration(s) still hidden from a previous run - \`./buddy migrate\` restores them`)}console.log("");console.log(" ./buddy <feature>:install activates one, <feature>:uninstall turns it off.");console.log("");process.exit(ExitCode.Success)}catch(err){console.error("\u2717 Failed to read feature status:",err);process.exit(ExitCode.FatalError)}})}export function features(buddy){registerStatus(buddy);for(const feature of FEATURE_NAMES)registerInstallPair(buddy,feature)}
130
+ enabled: ${enabled},`);await write(path,next);return"flipped"}export async function uninstallAllFeatures(options={}){const root=options.root??projectPath(),results=[];for(const feature of FEATURE_NAMES){const configOutcome=await setFeatureEnabled(feature,!1,{createIfMissing:!1,root}),{removed:filesRemoved}=await deleteFeatureFiles(feature,root,{force:!0});results.push({feature,configOutcome,filesRemoved})}return results}function isDryRun(options){return options.dryRun===!0||process.argv.includes("--dry-run")}async function offerMigrate(feature){const{active,hidden}=featureMigrationCounts(feature),total=active+hidden;if(total===0)return;console.log(` \u2192 ${feature} owns ${total} ${total===1?"migration":"migrations"}; its tables do not exist until they run.`);const answer=await confirmOrNull({message:"Run ./buddy migrate now?",initial:!1});if(answer!==!0){console.log(answer===null?" \u2192 Not asking (non-interactive). Run ./buddy migrate when ready.":" \u2192 Skipped. Run ./buddy migrate when ready.");return}const result=await runCommand("./buddy migrate",{cwd:projectPath()});if(resultFailed(result)){console.error(`\u2717 ./buddy migrate failed: ${resultError(result)}`);console.error(` \u2192 ${feature} is installed; re-run ./buddy migrate once that is resolved.`);return}console.log("\u2713 Migrated.")}function registerInstallPair(buddy,feature){const desc=FEATURE_DESCRIPTIONS[feature],configRel=`config/${feature}.ts`;buddy.command(`${feature}:install`,`Activate the ${feature} feature bundle. ${desc}`).option("--force",`Overwrite any existing ${feature} files in the project (default skips existing paths so the install is idempotent).`).option("--dry-run",`Say what ${feature}:install would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!0,{createIfMissing:!0,dryRun})){case"created":console.log(dryRun?`${mark} Would create ${configRel} with '${feature}' enabled.`:`${mark} Created ${configRel} with '${feature}' enabled.`);break;case"flipped":console.log(dryRun?`${mark} Would enable '${feature}' in ${configRel}.`:`${mark} Enabled '${feature}' in ${configRel}.`);break;case"unchanged":console.log(`${mark} '${feature}' is already enabled in ${configRel}.`);break}const{copied}=await copyFeatureFiles(feature,{force:options.force===!0,dryRun});if(copied.length>0){console.log(dryRun?`${mark} Would copy ${copied.length} stamped path(s) from framework defaults:`:`${mark} Copied ${copied.length} stamped path(s) from framework defaults:`);for(const path of copied)console.log(` - ${path}`)}else if(featurePathsPresent(feature).length>0)console.log(` \u2192 ${feature} scaffolding already in place - use --force to overwrite.`);if(dryRun){console.log(` \u2192 Dry run: nothing was written. Run it without --dry-run to install ${feature}.`);process.exit(ExitCode.Success)}await offerMigrate(feature);console.log(` \u2192 next ./buddy dev will boot with ${feature} loaded.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to install ${feature}:`,err);process.exit(ExitCode.FatalError)}});buddy.command(`${feature}:uninstall`,`Deactivate the ${feature} feature bundle.`).option("--keep-files",`Don't delete the ${feature} scaffolding (action/model/view files). Flip the flag only.`).option("--force",`Delete the ${feature} scaffolding even where you have edited it. Without this, changed files are kept.`).option("--dry-run",`Say what ${feature}:uninstall would change, and change nothing.`,{default:!1}).action(async(options)=>{try{const dryRun=isDryRun(options),mark=dryRun?"\xB7":"\u2713";switch(await setFeatureEnabled(feature,!1,{createIfMissing:!1,dryRun})){case"missing":console.log(`${mark} '${feature}' is already disabled (${configRel} is absent).`);break;case"flipped":console.log(dryRun?`${mark} Would disable '${feature}' in ${configRel}.`:`${mark} Disabled '${feature}' in ${configRel}. Custom config preserved.`);break;case"unchanged":console.log(`${mark} '${feature}' is already disabled in ${configRel}.`);break;case"created":console.log(`\u2717 Unexpected create on uninstall for ${feature}; please re-run with --force or report this bug.`);break}if(options.keepFiles){const stillPresent=featurePathsPresent(feature);if(stillPresent.length>0)console.log(` \u2192 ${stillPresent.length} stamped path(s) preserved (--keep-files).`)}else{const{removed,preserved}=await deleteFeatureFiles(feature,projectPath(),{force:options.force,dryRun});if(removed.length>0){console.log(dryRun?`${mark} Would remove ${removed.length} stamped path(s):`:`${mark} Removed ${removed.length} stamped path(s):`);for(const path of removed)console.log(` - ${path}`)}if(preserved.length>0){console.log(dryRun?` \u2192 Would keep ${preserved.length} path(s) you have edited (--force would remove them):`:` \u2192 Kept ${preserved.length} path(s) you have edited (re-run with --force to remove):`);for(const path of preserved)console.log(` - ${path}`)}}console.log(dryRun?` \u2192 Dry run: nothing was written or removed. Run it without --dry-run to uninstall ${feature}.`:` \u2192 next ./buddy dev will boot without ${feature}.`);process.exit(ExitCode.Success)}catch(err){console.error(`\u2717 Failed to uninstall ${feature}:`,err);process.exit(ExitCode.FatalError)}})}function registerStatus(buddy){buddy.command("features","Show which framework feature bundles are active.").action(async()=>{try{const{feature,overridesReady}=await import("@stacksjs/config");await overridesReady;const rows=FEATURE_NAMES.map((name)=>{const declared=readFeatureFlag(name),active=feature(name),migrations=featureMigrationCounts(name);return{name,declared,active,migrations,scaffolded:featurePathsPresent(name).length}}),enabled=rows.filter((r)=>r.active).length;console.log("");console.log(`Feature bundles (${enabled} of ${rows.length} active)`);console.log("");for(const row of rows){const mark=row.active?"\u2713":"\xB7",declared=row.declared==="absent"?"no config":row.declared==="unset"?"flag unset":`enabled: ${row.declared}`,parts=[`${mark} ${row.name.padEnd(11)}`,declared.padEnd(14)],total=row.migrations.active+row.migrations.hidden,plural=total===1?"migration":"migrations";if(total>0)parts.push(row.migrations.hidden>0?`${total} ${plural} (${row.migrations.hidden} hidden)`:`${total} ${plural}`);else parts.push("");console.log(` ${parts.join(" ")}`);if(row.declared===!0&&!row.active)console.log(` declared on but reading off - check \`env\` in config/${row.name}.ts against config.app.env`);if(row.declared===!1&&row.active)console.log(" declared off but reading on - a runtime override is in play");if(!row.active&&row.scaffolded>0)console.log(` ${row.scaffolded} scaffolded path(s) still present - \`./buddy ${row.name}:uninstall\` removes them`);if(row.active&&row.migrations.hidden>0)console.log(` ${row.migrations.hidden} migration(s) still hidden from a previous run - \`./buddy migrate\` restores them`)}console.log("");console.log(" ./buddy <feature>:install activates one, <feature>:uninstall turns it off.");console.log("");console.log("Config gates (switched by `enabled` in their config file)");console.log("");for(const[name,description]of Object.entries(CONFIG_GATES)){const declared=readFeatureFlag(name),label=declared==="absent"?"no config":declared==="unset"?"flag unset":`enabled: ${declared}`;console.log(` ${feature(name)?"\u2713":"\xB7"} ${name.padEnd(11)} ${label.padEnd(14)} ${description}`)}console.log("");process.exit(ExitCode.Success)}catch(err){console.error("\u2717 Failed to read feature status:",err);process.exit(ExitCode.FatalError)}})}export function features(buddy){registerStatus(buddy);for(const feature of FEATURE_NAMES)registerInstallPair(buddy,feature)}
@@ -1,5 +1,5 @@
1
- import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";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)},OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":void 0},str=(key)=>{return new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out)?.[1]},num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):void 0};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"}),[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]),whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]),found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:!0});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"])if(Bun.spawnSync(["which",candidate]).exitCode===0)return[candidate,"-dc"];throw Error("No xz decompressor found, and the images are .img.xz.\n Install one with: brew install xz\n Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi(),missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"}),timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts,findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err),unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson)console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2));else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
2
- `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return!1}if(asJson)console.log(JSON.stringify({host:target.host,facts,findings},null,2));else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}return!(typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error"))}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:void 0}).option("--list","List the disks that could be written to, and exit",{default:!1}).option("--dry-run","Say what would happen without writing anything",{default:!1}).option("--yes","Do not ask for confirmation before writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes){if(await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:!1})!==!0){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);if(await Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:void 0}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:void 0}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:void 0}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:void 0}).option("--timezone <tz>","IANA timezone for the board",{default:void 0}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:!1}).action(async(options)=>{const perf=await intro("buddy server:first-boot"),api=await loadSshApi(),{config}=await loadSshProject(options.env),keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?void 0:options.user),os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os",bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:!0});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
1
+ import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";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)},OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":void 0},str=(key)=>{return new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out)?.[1]},num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):void 0};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"}),[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]),whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]),found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:!0});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"])if(Bun.spawnSync(["which",candidate]).exitCode===0)return[candidate,"-dc"];throw Error("No xz decompressor found, and the images are .img.xz.\n Install one with: brew install xz\n Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi(),missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"}),timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts,findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err),unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson)console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2));else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
2
+ `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return!1}if(asJson)console.log(JSON.stringify({host:target.host,facts,findings},null,2));else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}return!(typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error"))}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:void 0}).option("--list","List the disks that could be written to, and exit",{default:!1}).option("--dry-run","Say what would happen without writing anything",{default:!1}).option("-y, --yes","Do not ask for confirmation before writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.error("Refusing to erase a disk from a non-interactive shell without confirmation.");log.info(` \u27A1\uFE0F Re-run with \`--yes\`: \`buddy server:flash --device ${info.DeviceNode} --yes\``);process.exit(ExitCode.FatalError)}if(await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:!1})!==!0){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);if(await Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:void 0}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:void 0}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:void 0}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:void 0}).option("--timezone <tz>","IANA timezone for the board",{default:void 0}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:!1}).action(async(options)=>{const perf=await intro("buddy server:first-boot"),api=await loadSshApi(),{config}=await loadSshProject(options.env),keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?void 0:options.user),os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os",bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:!0});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
3
3
  ${bundle.instructions}`);log.info(`Next: eject the card, boot the board, then \`buddy server:doctor ${options.hostname}.local\``);await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:doctor [host]","Check that a host can run this application before deploying to it").option("--env <name>","Environment whose configuration to check against",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--json","Print the findings as JSON",{default:!1}).action(async(host,options)=>{const perf=options.json?void 0:await intro("buddy server:doctor"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target;log.info(`Checking ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const ok=await reportPreflight(api,checked,options.json===!0);if(perf)await outro(ok?"Ready":"Not ready",{startTime:perf,useSeconds:!0});process.exit(ok?ExitCode.Success:ExitCode.FatalError)});buddy.command("server:setup [host]","Adopt a host: check it, then install what the deploy needs").option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--dry-run","Run the checks and stop before changing the host",{default:!1}).action(async(host,options)=>{const perf=await intro("buddy server:setup"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const adopted=host_?{...target,host:host_}:target;log.info(`Adopting ${adopted.user}@${adopted.host}${adopted.port===22?"":`:${adopted.port}`}`);if(!await reportPreflight(api,adopted,!1)){log.error("The host is not ready. Nothing was changed on it.");process.exit(ExitCode.FatalError)}if(options.dryRun){log.info("Dry run: the host passed its checks and was not modified.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const driver=api.createCloudDriver({config,provider:"ssh"});if(!driver.provisionComputeInfrastructure){log.error("This ts-cloud cannot bootstrap an SSH host (update @stacksjs/ts-cloud).");process.exit(ExitCode.FatalError)}buildBootstrapOrExit(api,config,options.env,adopted.user==="root"?void 0:adopted.user);log.info("Installing the runtime, gateway and service units if they are missing...");let outputs;try{outputs=await driver.provisionComputeInfrastructure({config,environment:options.env})}catch(err){log.error("Bootstrapping the host failed.");log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const stackName=config.project?.stackName||`${config.project?.slug||"app"}-${options.env}`,dir=join(process.cwd(),"storage","cloud","state"),statePath=join(dir,`${stackName}.json`);let recorded=null;try{recorded=existsSync(statePath)?JSON.parse(await Bun.file(statePath).text()):null}catch{recorded=null}mkdirSync(dir,{recursive:!0});await Bun.write(statePath,`${JSON.stringify(mergeSshStatePin(recorded,sshStatePin({stackName,target:adopted,deployStoragePath:outputs?.deployStoragePath})),null,2)}
4
4
  `);log.success(`Host adopted. Recorded at storage/cloud/state/${stackName}.json`);log.info("Next: `buddy deploy --prod`");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:trust [host]","Trust the host's own certificate authority on this machine").option("--env <name>","Environment whose configuration names the host",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--ca-path <path>","Where the authority lives on the host",{default:DEFAULT_LAN_CA_PATH}).option("--mobileconfig <path>","Also write an Apple configuration profile for an iPhone or iPad",{default:void 0}).option("--export-only","Save the certificate without changing this machine, and say how to trust it by hand",{default:!1}).option("--json","Print the result as JSON",{default:!1}).action(async(host,options)=>{const asJson=options.json===!0,perf=asJson?void 0:await intro("buddy server:trust"),{target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0&&!asJson)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)if(!asJson)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target,caPath=resolveCaPath(options.caPath),fail=(reason,message,remediation,detail)=>{if(asJson)console.log(JSON.stringify({host:checked.host,caPath,error:reason,message,remediation,...detail?{detail}:{}},null,2));else{log.error(message);log.info(remediation);if(detail)log.info(detail)}process.exit(ExitCode.FatalError)};if(!asJson)log.info(`Reading ${caPath} from ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const read=await readRemoteCa(checked,caPath);if("failure"in read){if(read.failure==="missing")return fail("ca.absent",`There is no certificate authority at ${caPath} on ${checked.host}.`,"That host is not serving LAN HTTPS from its own authority. Set `ssh: { lan: { tls: 'local-ca' } }` in config/cloud.ts and run `buddy deploy --prod`, which is what creates it. Nothing was created on the host. If the authority lives elsewhere, name it with --ca-path.");if(read.failure==="unreadable")return fail("ca.unreadable",`${caPath} on ${checked.host} exists but could not be read as a certificate.`,`Check it by hand with \`ssh ${checked.user}@${checked.host} sudo cat ${caPath}\`. Reading it falls back to \`sudo -n\`, so a host whose sudo asks for a password cannot serve it to this command.`,read.detail||void 0);return fail("ssh.unreachable",`Could not reach ${checked.user}@${checked.host} over SSH.`,"Check the host is powered on and on this network, that SSH is enabled, and that your key is authorised. `buddy server:doctor` reports on all three.",read.detail.split(`
5
5
  `).find((line)=>line.trim())||void 0)}const pem=read.pem,{exportCA,getCertSha256Fingerprint,isCertTrusted,trustInstructions}=await import("@stacksjs/tlsx");let fingerprint;try{fingerprint=getCertSha256Fingerprint(pem)}catch(err){return fail("ca.unparseable",`The file at ${caPath} on ${checked.host} is not a certificate this can read.`,"Point --ca-path at the root certificate rpx writes, which is a PEM.",err instanceof Error?err.message:String(err))}const savedPath=caCopyPath(checked.host);mkdirSync(dirname(savedPath),{recursive:!0});await Bun.write(savedPath,pem.endsWith(`
@@ -16,6 +16,12 @@ import type { CLI } from '@stacksjs/cli';
16
16
  * with a non-zero exit everywhere it is not implemented. A flag that silently
17
17
  * does nothing is worse than one that does not exist, because it is exactly
18
18
  * what a careful operator reaches for first.
19
+ *
20
+ * `--force` is not here either, for the same reason (stacksjs/stacks#2869).
21
+ * It promised "Skip confirmation prompts" on every command, while the
22
+ * commands that confirm skip it with `--yes`: `gdpr:erase --force` was
23
+ * accepted, ignored, and then refused in a non-interactive shell. The 46
24
+ * commands that implement `--force` declare it, each with what it means there.
19
25
  */
20
26
  export declare function registerGlobalOptions(buddy: CLI, options?: GlobalOptionRegistration): void;
21
27
  declare interface GlobalOptionRegistration {
@@ -1 +1 @@
1
- import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){(options.version===!1?buddy:buddy.version(versionDescriptor,"-V, --version")).option("-v, --verbose","Enable verbose output").option("-q, --quiet","Suppress non-essential output").option("--debug","Enable debug output and stack traces").option("--no-interaction","Do not ask interactive questions").option("--env <environment>","Target an environment").option("--force","Skip confirmation prompts").option("--no-emoji","Disable emoji in output").option("--no-cache","Disable command metadata caching")}
1
+ import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){(options.version===!1?buddy:buddy.version(versionDescriptor,"-V, --version")).option("-v, --verbose","Enable verbose output").option("-q, --quiet","Suppress non-essential output").option("--debug","Enable debug output and stack traces").option("--no-interaction","Do not ask interactive questions").option("--env <environment>","Target an environment").option("--no-emoji","Disable emoji in output").option("--no-cache","Disable command metadata caching")}
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.85",
5
+ "version": "0.75.87",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,70 +95,70 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "^0.75.85",
99
- "@stacksjs/ai": "^0.75.85",
100
- "@stacksjs/alias": "^0.75.85",
101
- "@stacksjs/analytics": "^0.75.85",
102
- "@stacksjs/api": "^0.75.85",
103
- "@stacksjs/arrays": "^0.75.85",
104
- "@stacksjs/auth": "^0.75.85",
105
- "@stacksjs/browser-extension": "^0.75.85",
106
- "@stacksjs/build": "^0.75.85",
107
- "@stacksjs/cache": "^0.75.85",
108
- "@stacksjs/chat": "^0.75.85",
98
+ "@stacksjs/actions": "^0.75.87",
99
+ "@stacksjs/ai": "^0.75.87",
100
+ "@stacksjs/alias": "^0.75.87",
101
+ "@stacksjs/analytics": "^0.75.87",
102
+ "@stacksjs/api": "^0.75.87",
103
+ "@stacksjs/arrays": "^0.75.87",
104
+ "@stacksjs/auth": "^0.75.87",
105
+ "@stacksjs/browser-extension": "^0.75.87",
106
+ "@stacksjs/build": "^0.75.87",
107
+ "@stacksjs/cache": "^0.75.87",
108
+ "@stacksjs/chat": "^0.75.87",
109
109
  "@stacksjs/clapp": "^0.2.16",
110
- "@stacksjs/cli": "^0.75.85",
111
- "@stacksjs/cloud": "^0.75.85",
112
- "@stacksjs/cms": "^0.75.85",
113
- "@stacksjs/collections": "^0.75.85",
114
- "@stacksjs/commerce": "^0.75.85",
115
- "@stacksjs/config": "^0.75.85",
116
- "@stacksjs/database": "^0.75.85",
117
- "@stacksjs/desktop-build": "^0.75.85",
118
- "@stacksjs/dns": "^0.75.85",
110
+ "@stacksjs/cli": "^0.75.87",
111
+ "@stacksjs/cloud": "^0.75.87",
112
+ "@stacksjs/cms": "^0.75.87",
113
+ "@stacksjs/collections": "^0.75.87",
114
+ "@stacksjs/commerce": "^0.75.87",
115
+ "@stacksjs/config": "^0.75.87",
116
+ "@stacksjs/database": "^0.75.87",
117
+ "@stacksjs/desktop-build": "^0.75.87",
118
+ "@stacksjs/dns": "^0.75.87",
119
119
  "@stacksjs/dnsx": "^0.2.3",
120
- "@stacksjs/email": "^0.75.85",
121
- "@stacksjs/enums": "^0.75.85",
122
- "@stacksjs/env": "^0.75.85",
123
- "@stacksjs/error-handling": "^0.75.85",
124
- "@stacksjs/events": "^0.75.85",
125
- "@stacksjs/features": "^0.75.85",
126
- "@stacksjs/git": "^0.75.85",
120
+ "@stacksjs/email": "^0.75.87",
121
+ "@stacksjs/enums": "^0.75.87",
122
+ "@stacksjs/env": "^0.75.87",
123
+ "@stacksjs/error-handling": "^0.75.87",
124
+ "@stacksjs/events": "^0.75.87",
125
+ "@stacksjs/features": "^0.75.87",
126
+ "@stacksjs/git": "^0.75.87",
127
127
  "@stacksjs/gitit": "^0.2.5",
128
- "@stacksjs/health": "^0.75.85",
128
+ "@stacksjs/health": "^0.75.87",
129
129
  "@stacksjs/httx": "^0.1.10",
130
- "@stacksjs/image": "^0.75.85",
131
- "@stacksjs/lint": "^0.75.85",
132
- "@stacksjs/logging": "^0.75.85",
133
- "@stacksjs/notifications": "^0.75.85",
134
- "@stacksjs/objects": "^0.75.85",
135
- "@stacksjs/orm": "^0.75.85",
136
- "@stacksjs/path": "^0.75.85",
137
- "@stacksjs/payments": "^0.75.85",
138
- "@stacksjs/realtime": "^0.75.85",
139
- "@stacksjs/router": "^0.75.85",
130
+ "@stacksjs/image": "^0.75.87",
131
+ "@stacksjs/lint": "^0.75.87",
132
+ "@stacksjs/logging": "^0.75.87",
133
+ "@stacksjs/notifications": "^0.75.87",
134
+ "@stacksjs/objects": "^0.75.87",
135
+ "@stacksjs/orm": "^0.75.87",
136
+ "@stacksjs/path": "^0.75.87",
137
+ "@stacksjs/payments": "^0.75.87",
138
+ "@stacksjs/realtime": "^0.75.87",
139
+ "@stacksjs/router": "^0.75.87",
140
140
  "@stacksjs/rpx": "^0.11.54",
141
- "@stacksjs/scheduler": "^0.75.85",
142
- "@stacksjs/search-engine": "^0.75.85",
143
- "@stacksjs/security": "^0.75.85",
144
- "@stacksjs/server": "^0.75.85",
145
- "@stacksjs/sites": "^0.75.85",
146
- "@stacksjs/skills": "^0.75.85",
147
- "@stacksjs/storage": "^0.75.85",
148
- "@stacksjs/strings": "^0.75.85",
149
- "@stacksjs/stx": "^0.2.378",
150
- "@stacksjs/testing": "^0.75.85",
151
- "@stacksjs/tinker": "^0.75.85",
141
+ "@stacksjs/scheduler": "^0.75.87",
142
+ "@stacksjs/search-engine": "^0.75.87",
143
+ "@stacksjs/security": "^0.75.87",
144
+ "@stacksjs/server": "^0.75.87",
145
+ "@stacksjs/sites": "^0.75.87",
146
+ "@stacksjs/skills": "^0.75.87",
147
+ "@stacksjs/storage": "^0.75.87",
148
+ "@stacksjs/strings": "^0.75.87",
149
+ "@stacksjs/stx": "^0.2.384",
150
+ "@stacksjs/testing": "^0.75.87",
151
+ "@stacksjs/tinker": "^0.75.87",
152
152
  "@stacksjs/tlsx": "^0.13.19",
153
- "@stacksjs/ts-cloud": "^0.16.42",
154
- "@stacksjs/tunnel": "^0.75.85",
155
- "@stacksjs/types": "^0.75.85",
156
- "@stacksjs/ui": "^0.75.85",
157
- "@stacksjs/utils": "^0.75.85",
158
- "@stacksjs/validation": "^0.75.85",
153
+ "@stacksjs/ts-cloud": "^0.16.44",
154
+ "@stacksjs/tunnel": "^0.75.87",
155
+ "@stacksjs/types": "^0.75.87",
156
+ "@stacksjs/ui": "^0.75.87",
157
+ "@stacksjs/utils": "^0.75.87",
158
+ "@stacksjs/validation": "^0.75.87",
159
159
  "ajv": "^8.20.0",
160
160
  "ajv-formats": "^3.0.1",
161
- "bun-plugin-stx": "^0.2.378",
161
+ "bun-plugin-stx": "^0.2.384",
162
162
  "ts-pantry": "^0.11.69"
163
163
  },
164
164
  "devDependencies": {