@stacksjs/buddy 0.75.515 → 0.75.519

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/dist/app-store-connect.js +2 -2
  2. package/dist/cli.js +4 -4
  3. package/dist/cloud-tenants.js +1 -1
  4. package/dist/commands/about.js +1 -1
  5. package/dist/commands/add.js +1 -1
  6. package/dist/commands/ai-access.js +2 -2
  7. package/dist/commands/ai-context.js +2 -2
  8. package/dist/commands/auth-prune-options.js +1 -1
  9. package/dist/commands/auth.js +1 -1
  10. package/dist/commands/build.js +1 -1
  11. package/dist/commands/cd.js +3 -3
  12. package/dist/commands/changelog.js +1 -1
  13. package/dist/commands/clean.js +1 -1
  14. package/dist/commands/cloud.js +7 -7
  15. package/dist/commands/comments.js +2 -2
  16. package/dist/commands/commerce-import.js +3 -3
  17. package/dist/commands/commit.js +1 -1
  18. package/dist/commands/completion.js +7 -7
  19. package/dist/commands/config-migrate.js +5 -5
  20. package/dist/commands/configure.js +2 -2
  21. package/dist/commands/create.js +1 -1
  22. package/dist/commands/db.js +1 -1
  23. package/dist/commands/deploy-fly.js +2 -2
  24. package/dist/commands/deploy-preview.js +1 -1
  25. package/dist/commands/deploy-ssh-target.js +1 -1
  26. package/dist/commands/deploy.js +588 -19
  27. package/dist/commands/desktop-apple.js +12 -12
  28. package/dist/commands/desktop-probe.js +1 -1
  29. package/dist/commands/dev.js +4 -4
  30. package/dist/commands/dns.js +2 -2
  31. package/dist/commands/docs/agent-counts.js +2 -2
  32. package/dist/commands/docs/buddy-commands.js +10 -10
  33. package/dist/commands/docs/capabilities.js +2 -2
  34. package/dist/commands/docs/desktop-matrix.js +2 -2
  35. package/dist/commands/docs/framework-repo.js +1 -1
  36. package/dist/commands/docs/generated-artifacts.js +2 -2
  37. package/dist/commands/docs/links.js +2 -2
  38. package/dist/commands/docs/native-skills.js +2 -2
  39. package/dist/commands/docs/snippets.js +6 -6
  40. package/dist/commands/doctor.js +3 -3
  41. package/dist/commands/domains.js +2 -2
  42. package/dist/commands/email.js +26 -26
  43. package/dist/commands/env.js +1 -1
  44. package/dist/commands/extension.js +3 -3
  45. package/dist/commands/features.js +3 -3
  46. package/dist/commands/feedback.js +3 -3
  47. package/dist/commands/fresh.js +1 -1
  48. package/dist/commands/gdpr.js +6 -6
  49. package/dist/commands/generate.js +5 -5
  50. package/dist/commands/http.js +1 -1
  51. package/dist/commands/install.js +1 -1
  52. package/dist/commands/integrations-probe.js +2 -2
  53. package/dist/commands/key.js +1 -1
  54. package/dist/commands/libs.js +1 -1
  55. package/dist/commands/link.js +2 -2
  56. package/dist/commands/lint.js +2 -2
  57. package/dist/commands/list.js +2 -2
  58. package/dist/commands/mail.js +13 -13
  59. package/dist/commands/maintenance.js +1 -1
  60. package/dist/commands/make.js +1 -1
  61. package/dist/commands/migrate-project.js +1 -1
  62. package/dist/commands/migrate.js +59 -59
  63. package/dist/commands/outdated.js +1 -1
  64. package/dist/commands/package.js +1 -1
  65. package/dist/commands/phone.js +13 -13
  66. package/dist/commands/ports.js +2 -2
  67. package/dist/commands/prepublish.js +1 -1
  68. package/dist/commands/preview-deploy.js +1 -1
  69. package/dist/commands/projects.js +1 -1
  70. package/dist/commands/publish.js +8 -8
  71. package/dist/commands/queue.js +1 -1
  72. package/dist/commands/release.js +7 -7
  73. package/dist/commands/route.js +1 -1
  74. package/dist/commands/saas.js +1 -1
  75. package/dist/commands/schedule.js +1 -1
  76. package/dist/commands/search.js +1 -1
  77. package/dist/commands/security.js +2 -2
  78. package/dist/commands/seed.js +1 -1
  79. package/dist/commands/serve.js +1 -1
  80. package/dist/commands/server-image.js +2 -2
  81. package/dist/commands/server-trust.js +2 -2
  82. package/dist/commands/server.js +10 -8
  83. package/dist/commands/setup-ai.js +2 -2
  84. package/dist/commands/setup.js +5 -5
  85. package/dist/commands/share.js +1 -1
  86. package/dist/commands/simulator.js +1 -1
  87. package/dist/commands/sms.js +25 -25
  88. package/dist/commands/socials.js +3 -3
  89. package/dist/commands/stacks.js +1 -1
  90. package/dist/commands/storage-backup.js +1 -1
  91. package/dist/commands/telemetry.js +1 -1
  92. package/dist/commands/test.js +1 -1
  93. package/dist/commands/tinker.js +1 -1
  94. package/dist/commands/types.js +1 -1
  95. package/dist/commands/upgrade.js +1 -1
  96. package/dist/commands/user.js +2 -2
  97. package/dist/config.js +1 -1
  98. package/dist/custom-cli.js +1 -1
  99. package/dist/database-backup.js +2 -2
  100. package/dist/database-preflight.js +1 -1
  101. package/dist/deploy-notify.js +3 -3
  102. package/dist/deployment-inputs.js +1 -1
  103. package/dist/deployment-revision.js +4 -4
  104. package/dist/dns-credentials.js +1 -1
  105. package/dist/email-reprocess.js +1 -1
  106. package/dist/feedback-links.js +1 -1
  107. package/dist/global-options.js +1 -1
  108. package/dist/lazy-commands.js +1 -1
  109. package/dist/mail-dns-health.js +1 -1
  110. package/dist/mail-users.js +1 -1
  111. package/dist/migrators/index.js +1 -1
  112. package/dist/migrators/laravel/index.js +1 -1
  113. package/dist/migrators/laravel/migrations.js +4 -4
  114. package/dist/migrators/laravel/models.js +4 -4
  115. package/dist/native-project.js +7 -7
  116. package/dist/native-site.js +2 -2
  117. package/dist/pantry-service-ports.js +2 -2
  118. package/dist/production-server.js +1 -1
  119. package/dist/project-setup.js +1 -1
  120. package/dist/publish-stx.js +1 -1
  121. package/dist/registry.js +1 -1
  122. package/dist/release-ios.js +1 -1
  123. package/dist/result.js +1 -1
  124. package/dist/scaffold-app.js +4 -4
  125. package/dist/scaffold-desktop.js +1 -1
  126. package/dist/scaffold-package-app.js +7 -7
  127. package/dist/scaffold-site.js +1 -1
  128. package/dist/storage-backup.js +1 -1
  129. package/dist/system-dependencies.js +1 -1
  130. package/dist/unbacked-data.js +1 -1
  131. package/dist/unvendor-rewrite.js +2 -2
  132. package/dist/version-info.js +1 -1
  133. package/dist/workflow-prune.js +3 -3
  134. package/package.json +55 -55
@@ -1,7 +1,7 @@
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
- `)}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
- `)}}}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(p.projectPath("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){buddy.command("cloud:apply","Apply configured server size, persistent volumes and deployment storage").option("--env [env]","Environment to reconcile",{default:"production"}).option("--dry-run","Show the compute plan without changing anything",{default:!1}).option("--yes","Apply the displayed plan without prompting",{default:!1}).option("-J, --json","Print the plan as JSON",{default:!1}).action(async(options)=>{try{const{createCloudDriver}=await import("@stacksjs/ts-cloud"),{loadTsCloudConfig}=await import("./deploy"),config=await loadTsCloudConfig(options.env);if(!config?.project?.slug)throw Error("config/cloud.ts must declare tsCloud.project.slug");const environment=options.env||"production",nativeConfig=config,driver=createCloudDriver({config:nativeConfig});if(!driver.applyComputeChanges)throw Error("This cloud provider does not support configured compute changes");const plan=await driver.applyComputeChanges({config:nativeConfig,environment,dryRun:!0});if(options.json)console.log(JSON.stringify(plan,null,2));else{for(const change of plan.changes)await log.info(`${change.resource}: ${change.action} (${change.detail})`);if(plan.waitingForCapacity)await log.warn(plan.waitingForCapacity)}if(options.dryRun)return;if(!await confirmCloudChange(options,"buddy cloud:apply --yes","Apply these compute changes?","apply compute changes"))return;const applied=await driver.applyComputeChanges({config:nativeConfig,environment});if(applied.waitingForCapacity)await log.warn(applied.waitingForCapacity);await log.success("Configured compute changes applied")}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exitCode=ExitCode.FatalError}});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("--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("--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("@stacksjs/actions/deploy/stack"),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("--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("--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("--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
- `))}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")}export async function confirmInvalidation(options,retry,question){return confirmCloudChange(options,retry,question,"invalidate the CDN cache")}export async function confirmCloudChange(options,retry,question,action){if(options.yes)return!0;if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError(`Refusing to ${action} 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
+ 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");const client=new AWSClient;const 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");const 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");const 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
+ `)}export async function renameEffects(tsCloudConfig,servers,current){const taken=servers.map((s)=>String(s?.name)).filter(Boolean);const effects={takenNames:async()=>taken,inventoryName:()=>String(current?.name??""),renameInventory:(next)=>{current.name=next}};const 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):undefined};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");const ssh={user:"root",connectTimeoutSec:10};effects.remoteHostname=async()=>{const result=await sshExec(host,"hostname",ssh);if(result.code!==0)throw new 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 new Error(result.stderr.trim()||`Setting the hostname on ${host} failed.`)}}const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(provider!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);const 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:true,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);const effects={providerExists:async()=>true,deleteProvider:async()=>{throw new 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):undefined};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
+ `)}}}const provider=tsCloudConfig?.cloud?.provider||process.env.CLOUD_PROVIDER||"aws";if(provider!=="hetzner")return effects;const{HetznerClient}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const apiToken=resolveHetznerApiToken(tsCloudConfig);const 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 false}};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;const{buildCertificatePackScript,buildCertificateStateScript,buildCertificateUnpackScript,buildRpxConfig,buildRpxFragmentRefreshScript,buildSshArgs,certificatesMatch,DEFAULT_RPX_CERTS_DIR,parseCertificateState,probeHostRoutes,sshExec,sshExecOrThrow}=await import("@stacksjs/ts-cloud");const{reconcileHetznerDns}=await import("./deploy");const ssh={user:"root",connectTimeoutSec:10};const runOnSource=(script)=>sshExecOrThrow(source.ipv4,script,ssh);const runOnTarget=(script)=>sshExecOrThrow(target.ipv4,script,ssh);async function carry(path){const args=buildSshArgs(ssh,"ssh");const reader=Bun.spawn(["ssh",...args,`root@${source.ipv4}`,`cat ${path}`],{stdout:"pipe",stderr:"pipe"});const writer=Bun.spawn(["ssh",...args,`root@${target.ipv4}`,`cat > ${path}`],{stdin:reader.stdout,stdout:"pipe",stderr:"pipe"});const[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 new 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");const{siteMoveArchivePath,siteMoveCertArchivePath}=await import("@stacksjs/ts-cloud");const archive=siteMoveArchivePath(slug,siteName);const 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=[];const 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 false;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
+ `))}};const 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");const 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}:undefined}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.":undefined}}const{HetznerClient,toInventoryServer}=await import("@stacksjs/ts-cloud");const{resolveHetznerApiToken}=await import("./deploy");const 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{const servers=await new HetznerClient({apiToken}).listServers();return{servers:servers.map((server)=>toInventoryServer(server)).sort((a,b)=>a.name.localeCompare(b.name))}}catch(error){const status=Number(error?.status);const 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():undefined;const 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:undefined,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");const{tsCloud:cloudConfig}=await import(p.projectPath("config/cloud"));const environment=cloudEnvironment();const template=new InfrastructureGenerator({config:cloudConfig,environment}).generate().toJSON();const 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){buddy.command("cloud:apply","Apply configured server size, persistent volumes and deployment storage").option("--env [env]","Environment to reconcile",{default:"production"}).option("--dry-run","Show the compute plan without changing anything",{default:false}).option("--yes","Apply the displayed plan without prompting",{default:false}).option("-J, --json","Print the plan as JSON",{default:false}).action(async(options)=>{try{const{createCloudDriver}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const config=await loadTsCloudConfig(options.env);if(!config?.project?.slug)throw new Error("config/cloud.ts must declare tsCloud.project.slug");const environment=options.env||"production";const nativeConfig=config;const driver=createCloudDriver({config:nativeConfig});if(!driver.applyComputeChanges)throw new Error("This cloud provider does not support configured compute changes");const plan=await driver.applyComputeChanges({config:nativeConfig,environment,dryRun:true});if(options.json)console.log(JSON.stringify(plan,null,2));else{for(const change of plan.changes)await log.info(`${change.resource}: ${change.action} (${change.detail})`);if(plan.waitingForCapacity)await log.warn(plan.waitingForCapacity)}if(options.dryRun)return;if(!await confirmCloudChange(options,"buddy cloud:apply --yes","Apply these compute changes?","apply compute changes"))return;const applied=await driver.applyComputeChanges({config:nativeConfig,environment});if(applied.waitingForCapacity)await log.warn(applied.waitingForCapacity);await log.success("Configured compute changes applied")}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exitCode=ExitCode.FatalError}});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:false}).option("--connect",descriptions.ssh,{default:false}).option("--invalidate-cache",descriptions.invalidateCache,{default:false}).option("--paths [paths]",descriptions.paths).option("-y, --yes","Invalidate the CDN cache without asking first",{default:false}).option("--diff",descriptions.diff,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).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:true},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:true,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:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}if(options.invalidateCache){const confirm=await confirmInvalidation(options,"buddy cloud --invalidate-cache --yes","Would you like to invalidate the CDN (CloudFront) cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)}log.info("Invalidating the CloudFront cache...");const{AWSCloudFrontClient}=await import("@stacksjs/ts-cloud");const cloudfront=new AWSCloudFrontClient;const 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:true});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:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});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:false}).option("--verbose",descriptions.verbose,{default:false}).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:true},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:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has a jump box.",{startTime,useSeconds:true});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:false}).option("-y, --yes","Skip the confirmation prompt",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:remove` ...",options);const startTime=await intro("buddy cloud:remove");const 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:true},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:true,type:"warning"});process.exit(ExitCode.FatalError)}await outro("Your cloud has no jump box.",{startTime,useSeconds:true});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(` ➡️ Re-run with \`--yes\` to confirm (e.g. in CI): \`buddy cloud:remove --yes\``);await outro("cloud:remove cancelled.",{startTime,useSeconds:true,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.`);const typed=await text({message:`Type the environment name "${environment}" to confirm (blank to cancel):`});if(typed.trim()!==environment){await outro("cloud:remove cancelled - confirmation did not match.",{startTime,useSeconds:true});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");const{projectPath}=await import("@stacksjs/path");const envFiles=[projectPath(`.env.${environment}`),projectPath(".env")];for(const envPath of envFiles){if(existsSync(envPath)){const envContent=readFileSync(envPath,"utf-8");const lines=envContent.split(`
5
+ `);for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("="))continue;const[key,...valueParts]=trimmed.split("=");const 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("@stacksjs/actions/deploy/stack");const region=await stacksCloudRegion(undefined,environment);await undeployStack({environment,region,verbose:options.verbose});await outro("Cloud infrastructure removed",{startTime,useSeconds:true});process.exit(ExitCode.Success)}catch(error){console.log("");console.error("✗ 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:true,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:true}).option("--verbose",descriptions.verbose,{default:false}).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:true},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:true,type:"warning"});process.exit(ExitCode.FatalError)}}await outro("No cost optimization was applied",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:cleanup",descriptions.cleanUp).alias("cloud:clean-up").option("--verbose",descriptions.verbose,{default:false}).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}];const 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:true});process.exit(ExitCode.Success)});buddy.command("cloud:invalidate-cache",descriptions.invalidateCache).option("--paths [paths]",descriptions.paths,{default:false}).option("-y, --yes","Invalidate without asking first",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:invalidate-cache` ...",options);const startTime=await intro("buddy cloud:invalidate-cache");const confirm=await confirmInvalidation(options,"buddy cloud:invalidate-cache --yes","Would you like to invalidate the CloudFront cache?");if(!confirm){await outro("Exited",{startTime,useSeconds:true});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:true},"Ensure your cloud stack is deployed before invalidating cache.");process.exit(ExitCode.FatalError)}const paths=options.paths?String(options.paths):"/*";const 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:true},getResultError(result));process.exit(ExitCode.FatalError)}await outro("Exited",{startTime,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("cloud:diff",descriptions.diff).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:diff` ...",options);const startTime=await intro("buddy cloud:diff");const failure=await runCloudDiff();if(failure){await outro("While running the cloud diff command, there was an issue",{startTime,useSeconds:true},failure);process.exit(ExitCode.FatalError)}await outro("Cloud diff complete",{startTime,useSeconds:true});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:false}).action(async(options)=>{log.debug("Running `buddy cloud:dashboard` ...",options);const startTime=await intro("buddy cloud:dashboard");const 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:true},"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):undefined,port:options.port?Number(options.port):undefined,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:true},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:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:sites` ...",options);const{formatInventory,probeHostRoutes}=await import("@stacksjs/ts-cloud");const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const 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);const probes=options.remote===false?[]:await probeFleet(listing.servers);const 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");const 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:false}).option("-J, --json",descriptions.json,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy cloud:attach` ...",options);const{attachConflicts,attachIsViable,attachPreconditions,formatAttachPlan,probeHostRoutes,resolveAttachTarget,setAttachToInCloudConfig,sshExec}=await import("@stacksjs/ts-cloud");const{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");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const 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;const preconditions=attachPreconditions(slug,server);if(preconditions.length>0)return await refuse(...preconditions);const declared=await declaredSitesFor(tsCloudConfig,slug);const probe=await probeHostRoutes(server,(host,command)=>sshExec(host,command,{user:"root",connectTimeoutSec:10}));const plan={slug,owner:server.project,server,declared,conflicts:probe.unavailable?[]:attachConflicts(slug,declared,probe.routes),registryRead:!probe.unavailable,registryProblem:probe.unavailable};const viable=attachIsViable(plan);const edit=viable?await applyAttachToConfig(plan.owner,Boolean(options.dryRun)):undefined;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
+ `))}process.exit(viable?ExitCode.Success:ExitCode.FatalError);async function applyAttachToConfig(owner,dryRun){const configPath=p.projectPath("config/cloud.ts");const{readFileSync,writeFileSync}=await import("node:fs");const 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:false}).option("-J, --json",descriptions.renameJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(server,options)=>{log.debug("Running `buddy cloud:rename` ...",options);const{applyPlan,formatPlan,pendingSteps,planServerRename,resolvePlan,validateServerName}=await import("@stacksjs/ts-cloud");const{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");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);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));const resolved=await resolvePlan(plan);const 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:false}).option("--dry-run",descriptions.dryRun,{default:false}).option("-J, --json",descriptions.destroyJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).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");const{loadTsCloudConfig}=await import("./deploy");const environment=String(options.env||process.env.APP_ENV||process.env.NODE_ENV||"production");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);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));const resolved=await resolvePlan(plan);const 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:false}).option("-J, --json",descriptions.moveJson,{default:false}).option("--verbose",descriptions.verbose,{default:false}).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");const{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");const tsCloudConfig=await loadTsCloudConfig(options.env?environment:undefined);const 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;const hostnames=gatewayHostnames({[site]:rawSite},{autoWww:Boolean(tsCloudConfig?.infrastructure?.compute?.proxy?.autoWww)});const 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)||undefined,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);const 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){return confirmCloudChange(options,retry,question,"invalidate the CDN cache")}export async function confirmCloudChange(options,retry,question,action){if(options.yes)return true;if(isCI||!hasTTY||!process.stdin.isTTY){log.syncError(`Refusing to ${action} from a non-interactive shell without confirmation.`);log.syncError(` ➡️ Re-run with \`--yes\`: \`${retry}\``);await log.flush();process.exit(ExitCode.FatalError)}return await prompts.confirm(question)}
@@ -1,2 +1,2 @@
1
- import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const STATUSES=["pending","approved","rejected"];export function excerpt(body,width=60){const flat=String(body??"").replace(/\s+/g," ").trim();return flat.length>width?`${flat.slice(0,width-1)}\u2026`:flat}export function commenter(row){if(row.author_name)return row.author_name;if(row.user_id)return`user #${row.user_id}`;return"anonymous"}export function formatCommentRow(row){const owner=`${row.commentables_type}#${row.commentables_id}`;return` ${String(row.id).padStart(5)} ${String(row.status??"").padEnd(8)} ${owner.padEnd(12)} ${commenter(row).padEnd(18).slice(0,18)} ${excerpt(row.body)}`}async function commentId(raw){const id=Number(raw);if(!Number.isInteger(id)||id<=0){await log.error(`\`${raw}\` is not a comment id. Find one with \`buddy comments:list\`.`);await log.flush();process.exit(ExitCode.FatalError)}return id}async function requireComment(id){const{comments}=await import("@stacksjs/cms"),row=await comments.fetchCommentById(id);if(!row){await log.error(`No comment with id ${id}.`);await log.flush();process.exit(ExitCode.FatalError)}return row}export function commentsCommands(buddy){buddy.command("comments:list","List reader comments, newest first").option("--status <status>",`Only this status: ${STATUSES.join(", ")}`).option("--type <type>","Only comments on this table, e.g. posts").option("--limit <limit>","How many to show",{default:"25"}).example("buddy comments:list").example("buddy comments:list --status pending --type posts").action(async(options)=>{if(options.status&&!STATUSES.includes(options.status)){await log.error(`--status must be one of ${STATUSES.join(", ")}.`);await log.flush();process.exit(ExitCode.FatalError)}const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom("commentables");if(options.status)query=query.where("status","=",options.status);if(options.type)query=query.where("commentables_type","=",options.type);const rows=await query.selectAll().orderBy("id","desc").limit(Number(options.limit)||25).execute();if(rows.length===0){log.info("No comments match.");await log.flush();process.exit(ExitCode.Success)}for(const row of rows)process.stdout.write(`${formatCommentRow(row)}
2
- `);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:approve <id>","Publish a comment").example("buddy comments:approve 12").action(async(raw)=>{const id=await commentId(raw);await requireComment(id);const{comments}=await import("@stacksjs/cms");await comments.approveComment(id);log.success(`Approved comment ${id}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:reject <id>","Hide a comment without deleting it").example("buddy comments:reject 12").action(async(raw)=>{const id=await commentId(raw);await requireComment(id);const{comments}=await import("@stacksjs/cms");await comments.rejectComment(id);log.success(`Rejected comment ${id}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:delete <id>","Delete a comment for good").example("buddy comments:delete 12").action(async(raw)=>{const id=await commentId(raw),row=await requireComment(id),{comments}=await import("@stacksjs/cms");await comments.deleteComment(id);log.success(`Deleted comment ${id} by ${commenter(row)}: "${excerpt(row.body,40)}"`);await log.flush();process.exit(ExitCode.Success)})}
1
+ import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const STATUSES=["pending","approved","rejected"];export function excerpt(body,width=60){const flat=String(body??"").replace(/\s+/g," ").trim();return flat.length>width?`${flat.slice(0,width-1)}…`:flat}export function commenter(row){if(row.author_name)return row.author_name;if(row.user_id)return`user #${row.user_id}`;return"anonymous"}export function formatCommentRow(row){const owner=`${row.commentables_type}#${row.commentables_id}`;return` ${String(row.id).padStart(5)} ${String(row.status??"").padEnd(8)} ${owner.padEnd(12)} ${commenter(row).padEnd(18).slice(0,18)} ${excerpt(row.body)}`}async function commentId(raw){const id=Number(raw);if(!Number.isInteger(id)||id<=0){await log.error(`\`${raw}\` is not a comment id. Find one with \`buddy comments:list\`.`);await log.flush();process.exit(ExitCode.FatalError)}return id}async function requireComment(id){const{comments}=await import("@stacksjs/cms");const row=await comments.fetchCommentById(id);if(!row){await log.error(`No comment with id ${id}.`);await log.flush();process.exit(ExitCode.FatalError)}return row}export function commentsCommands(buddy){buddy.command("comments:list","List reader comments, newest first").option("--status <status>",`Only this status: ${STATUSES.join(", ")}`).option("--type <type>","Only comments on this table, e.g. posts").option("--limit <limit>","How many to show",{default:"25"}).example("buddy comments:list").example("buddy comments:list --status pending --type posts").action(async(options)=>{if(options.status&&!STATUSES.includes(options.status)){await log.error(`--status must be one of ${STATUSES.join(", ")}.`);await log.flush();process.exit(ExitCode.FatalError)}const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom("commentables");if(options.status)query=query.where("status","=",options.status);if(options.type)query=query.where("commentables_type","=",options.type);const rows=await query.selectAll().orderBy("id","desc").limit(Number(options.limit)||25).execute();if(rows.length===0){log.info("No comments match.");await log.flush();process.exit(ExitCode.Success)}for(const row of rows)process.stdout.write(`${formatCommentRow(row)}
2
+ `);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:approve <id>","Publish a comment").example("buddy comments:approve 12").action(async(raw)=>{const id=await commentId(raw);await requireComment(id);const{comments}=await import("@stacksjs/cms");await comments.approveComment(id);log.success(`Approved comment ${id}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:reject <id>","Hide a comment without deleting it").example("buddy comments:reject 12").action(async(raw)=>{const id=await commentId(raw);await requireComment(id);const{comments}=await import("@stacksjs/cms");await comments.rejectComment(id);log.success(`Rejected comment ${id}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("comments:delete <id>","Delete a comment for good").example("buddy comments:delete 12").action(async(raw)=>{const id=await commentId(raw);const row=await requireComment(id);const{comments}=await import("@stacksjs/cms");await comments.deleteComment(id);log.success(`Deleted comment ${id} by ${commenter(row)}: "${excerpt(row.body,40)}"`);await log.flush();process.exit(ExitCode.Success)})}
@@ -1,4 +1,4 @@
1
- import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export const SUPPORTED_SOURCES=["shopify","woocommerce","shopware"],CREDENTIAL_ENV={shopify:"SHOPIFY_ADMIN_TOKEN",woocommerce:"WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET",shopware:"SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET"},SHOPWARE_ACCESS_KEY_HELP='It is public by design, not a secret. Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card.';export function parseImportFlags(flags,env=process.env){const source=String(flags.from??"").trim().toLowerCase();if(!source)throw Error(`Say where the catalog comes from: --from ${SUPPORTED_SOURCES.join(" or --from ")}.`);if(!SUPPORTED_SOURCES.includes(source))throw Error(`--from must be one of ${SUPPORTED_SOURCES.join(", ")}; got "${flags.from}".`);const customers=flags.customers===!0,orders=flags.orders===!0,include={catalog:flags.catalog===!0||!customers&&!orders,customers,orders};let limit;if(flags.limit!==void 0&&flags.limit!==""){limit=Number(flags.limit);if(!Number.isInteger(limit)||limit<=0)throw Error(`--limit must be a whole number above 0; got "${flags.limit}".`)}let currency;if(flags.currency!==void 0&&flags.currency!==""){currency=String(flags.currency).trim().toUpperCase();if(!/^[A-Z]{3}$/.test(currency))throw Error(`--currency must be a three-letter ISO 4217 code such as USD; got "${flags.currency}".`)}let adminUrl;if(flags.adminUrl!==void 0&&String(flags.adminUrl).trim()!==""){if(!customers&&!orders)throw Error("--admin-url only applies to --customers and --orders; the catalog is read from the storefront.");adminUrl=String(flags.adminUrl).trim()}const flagKey=flags.accessKey===void 0?"":String(flags.accessKey).trim();let accessKey;if(source==="shopware"&&include.catalog){accessKey=flagKey||env.SHOPWARE_ACCESS_KEY?.trim()||void 0;if(!accessKey)throw Error(`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`);if(/\s/.test(accessKey))throw Error("--access-key must be a single key with no spaces.");if(/^SW(?:IA|UA)/i.test(accessKey))throw Error(`That looks like an Admin API key (it starts with ${accessKey.slice(0,4).toUpperCase()}), not a sales channel access key (SWSC...). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env instead. ${SHOPWARE_ACCESS_KEY_HELP}`)}else if(flagKey&&source==="shopware")throw Error("--access-key is for the catalog (the Store API). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env.");else if(flagKey)throw Error(`--access-key only applies to --from shopware; ${source} needs no key.`);return{source,limit,currency,...accessKey?{accessKey}:{},...adminUrl?{adminUrl}:{},include,dryRun:flags.dryRun===!0}}function money(minor,currency,format){return minor===null?"unpriced":format(minor,currency)}function verbOf(action,dryRun){if(action==="create")return dryRun?"would create":"created";return dryRun?"would update":"updated"}export function formatImportedProduct(product,format,dryRun=!1){const variantCount=product.variants.create+product.variants.update,details=[money(product.priceMinor,product.currency,format),variantCount>0?`${variantCount} variant${variantCount===1?"":"s"}`:null,product.category?`in ${product.category}`:null,product.vendor?`by ${product.vendor}`:null,product.imageCount===0?"no image":null].filter(Boolean).join(", ");return` ${verbOf(product.action,dryRun).padEnd(12)} ${product.name} (${product.handle}) ${details}`}export function formatImportedCustomer(customer,dryRun=!1){const matched=customer.matchedBy==="email"?" (matched an existing customer by email)":"";return` ${verbOf(customer.action,dryRun).padEnd(12)} ${customer.name} <${customer.email}>${matched}`}export function formatImportedOrder(order,format,dryRun=!1){const details=[format(order.totalMinor,order.currency),`${order.status} (${order.sourceStatus})`,`${order.lines} line${order.lines===1?"":"s"}`,order.unlinkedLines>0?`${order.unlinkedLines} without a product`:null,order.refundedMinor>0&&order.status!=="REFUNDED"?`${format(order.refundedMinor,order.currency)} refunded`:null,order.customerEmail?`for ${order.customerEmail}`:"no customer"].filter(Boolean).join(", ");return` ${verbOf(order.action,dryRun).padEnd(12)} ${order.number??order.externalId} ${details}`}export function formatImportSummary(result){const{counts}=result,would=result.dryRun?"would be ":"";return[`Products: ${counts.products.created} ${would}created, ${counts.products.updated} ${would}updated`,`Variants: ${counts.variants.created} ${would}created, ${counts.variants.updated} ${would}updated`,`Categories: ${counts.categories.created} ${would}created. Manufacturers: ${counts.manufacturers.created} ${would}created`,...counts.duplicates>0?[`Duplicates skipped: ${counts.duplicates}`]:[],`Currency: ${result.currencies.length>0?result.currencies.join(", "):"not reported by the store"}`]}export function formatCustomerSummary(result){const would=result.dryRun?"would be ":"",{customers,merged}=result.counts;return[`Customers: ${customers.created} ${would}created, ${customers.updated} ${would}updated${merged>0?`, ${merged} merged by email`:""}`]}export function formatOrderSummary(result){const would=result.dryRun?"would be ":"",{orders,customers,lines,duplicates}=result.counts;return[`Orders: ${orders.created} ${would}created, ${orders.updated} ${would}updated${duplicates>0?`, ${duplicates} duplicates skipped`:""}`,`Order lines: ${lines.linked} linked to a product, ${lines.unlinked} without one${lines.productless>0?`, ${lines.productless} with no product at the source (fees, custom or deleted items)`:""}`,...customers.created>0?[`Customers created from orders: ${customers.created}`]:[],`Order currencies: ${result.currencies.length>0?result.currencies.join(", "):"none"}`]}export function currencyMismatch(result,configured){if(!configured||result.currencies.length===0)return null;const other=result.currencies.filter((code)=>code!==configured.toUpperCase());if(other.length===0)return null;return`Prices were imported in ${other.join(", ")} minor units, but config/commerce.ts sets currency to ${configured}. products.price has no currency column, so set commerce.currency to match.`}export function commerceDisabledReason(enabled,dryRun){if(enabled||dryRun)return null;return"Commerce is disabled, so its tables (products, customers, orders) are not migrated. Set enabled: true in config/commerce.ts (or run buddy commerce:install), run buddy migrate, then import again. --dry-run works without it."}export const OUT_OF_SCOPE_NOTE="Customers and orders were not imported. Add --customers and/or --orders, with the admin API credentials in env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, or SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET.";async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function reportWarnings(warnings){for(const warning of warnings)log.warn(warning.externalId?`${warning.externalId}: ${warning.message}`:warning.message)}export function commerceImport(buddy){buddy.command("commerce:import <url>","Import a Shopify, WooCommerce or Shopware 6 catalog, and optionally its customers and orders").option("--from <platform>",`Where the store lives: ${SUPPORTED_SOURCES.join(", ")}`).option("--customers","Also import customers from the admin API (credentials from env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY/_SECRET or SHOPWARE_CLIENT_ID/_SECRET)",{default:!1}).option("--orders","Also import orders and their lines from the admin API (same credentials as --customers)",{default:!1}).option("--catalog","Import the catalog too when --customers or --orders is given (it is the default otherwise)",{default:!1}).option("--access-key <key>","Shopware catalog only: the sales channel access key (public, from Sales Channels > API access), or set SHOPWARE_ACCESS_KEY").option("--admin-url <url>","Customers and orders only: the admin API address when it differs from <url>, e.g. https://<store>.myshopify.com for a Shopify custom domain").option("--limit <count>","Import at most this many products, customers and orders (each)").option("--currency <code>","ISO 4217 currency, for a store or order that does not report one").option("--dry-run","Show what would be created or updated without writing anything",{default:!1}).example("buddy commerce:import https://shop.example.com --from shopify --dry-run").example("buddy commerce:import example.com/shop --from woocommerce --limit 50").example("buddy commerce:import https://shop.example.de --from shopware --access-key SWSC... --dry-run").example("SHOPIFY_ADMIN_TOKEN=shpat_... buddy commerce:import https://shop.example.com --from shopify --customers --orders --admin-url northwind.myshopify.com").action(async(url,options)=>{let settings;try{settings=parseImportFlags(options)}catch(error){return fail(error.message)}try{const{feature}=await import("@stacksjs/config"),disabled=commerceDisabledReason(feature("commerce"),settings.dryRun);if(disabled)return fail(disabled)}catch{}const{catalogImport}=await import("@stacksjs/commerce"),formatMinor=catalogImport.formatMinor,{include,dryRun}=settings,accounts=include.customers||include.orders;let storeUrl,credentials;try{storeUrl=catalogImport.normalizeStoreUrl(url);if(accounts)credentials=catalogImport.readAccountCredentials(settings.source,process.env)}catch(error){return fail(error.message)}if(include.catalog){let repository=catalogImport.createDatabaseRepository();if(dryRun)try{await repository.findProducts(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every product is reported as new.`);repository=catalogImport.createMemoryRepository()}log.info(`${dryRun?"Dry run: reading":"Importing"} the ${settings.source} catalog at ${storeUrl}`);let result;try{result=await catalogImport.importCatalog({adapter:catalogImport.catalogAdapter(settings.source),storeUrl,repository,dryRun,limit:settings.limit,currency:settings.currency,accessKey:settings.accessKey,onProduct:(product)=>process.stdout.write(`${formatImportedProduct(product,formatMinor,dryRun)}
2
- `)})}catch(error){return fail(`Import stopped: ${error.message}${dryRun?"":" Products written before this point are kept; re-running resumes safely."}`)}if(result.products.length===0)log.info(`${storeUrl} has no products to import.`);reportWarnings(result.warnings);for(const line of formatImportSummary(result))log.info(line);try{const{config}=await import("@stacksjs/config"),mismatch=currencyMismatch(result,config.commerce?.currency);if(mismatch)log.warn(mismatch)}catch{}}if(accounts){let repository=catalogImport.createDatabaseAccountRepository();if(dryRun){try{await repository.findOrders(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyAccountRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every customer and order is reported as new.`);repository=catalogImport.createReadOnlyAccountRepository(catalogImport.createMemoryAccountRepository())}if(include.catalog&&include.orders)log.info("A dry run writes no products, so order lines are matched only against products already in Stacks.")}const shared={adapter:catalogImport.accountAdapter(settings.source),storeUrl,repository,credentials,dryRun,limit:settings.limit,currency:settings.currency,adminUrl:settings.adminUrl};if(include.customers){log.info(`${dryRun?"Dry run: reading":"Importing"} ${settings.source} customers from ${settings.adminUrl??storeUrl}`);try{const result=await catalogImport.importCustomers({...shared,onCustomer:(customer)=>process.stdout.write(`${formatImportedCustomer(customer,dryRun)}
1
+ import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export const SUPPORTED_SOURCES=["shopify","woocommerce","shopware"];export const CREDENTIAL_ENV={shopify:"SHOPIFY_ADMIN_TOKEN",woocommerce:"WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET",shopware:"SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET"};export const SHOPWARE_ACCESS_KEY_HELP='It is public by design, not a secret. Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card.';export function parseImportFlags(flags,env=process.env){const source=String(flags.from??"").trim().toLowerCase();if(!source)throw new Error(`Say where the catalog comes from: --from ${SUPPORTED_SOURCES.join(" or --from ")}.`);if(!SUPPORTED_SOURCES.includes(source))throw new Error(`--from must be one of ${SUPPORTED_SOURCES.join(", ")}; got "${flags.from}".`);const customers=flags.customers===true;const orders=flags.orders===true;const include={catalog:flags.catalog===true||!customers&&!orders,customers,orders};let limit;if(flags.limit!==undefined&&flags.limit!==""){limit=Number(flags.limit);if(!Number.isInteger(limit)||limit<=0)throw new Error(`--limit must be a whole number above 0; got "${flags.limit}".`)}let currency;if(flags.currency!==undefined&&flags.currency!==""){currency=String(flags.currency).trim().toUpperCase();if(!/^[A-Z]{3}$/.test(currency))throw new Error(`--currency must be a three-letter ISO 4217 code such as USD; got "${flags.currency}".`)}let adminUrl;if(flags.adminUrl!==undefined&&String(flags.adminUrl).trim()!==""){if(!customers&&!orders)throw new Error("--admin-url only applies to --customers and --orders; the catalog is read from the storefront.");adminUrl=String(flags.adminUrl).trim()}const flagKey=flags.accessKey===undefined?"":String(flags.accessKey).trim();let accessKey;if(source==="shopware"&&include.catalog){accessKey=flagKey||env.SHOPWARE_ACCESS_KEY?.trim()||undefined;if(!accessKey)throw new Error(`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`);if(/\s/.test(accessKey))throw new Error("--access-key must be a single key with no spaces.");if(/^SW(?:IA|UA)/i.test(accessKey))throw new Error(`That looks like an Admin API key (it starts with ${accessKey.slice(0,4).toUpperCase()}), not a sales channel access key (SWSC...). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env instead. ${SHOPWARE_ACCESS_KEY_HELP}`)}else if(flagKey&&source==="shopware"){throw new Error("--access-key is for the catalog (the Store API). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env.")}else if(flagKey){throw new Error(`--access-key only applies to --from shopware; ${source} needs no key.`)}return{source,limit,currency,...accessKey?{accessKey}:{},...adminUrl?{adminUrl}:{},include,dryRun:flags.dryRun===true}}function money(minor,currency,format){return minor===null?"unpriced":format(minor,currency)}function verbOf(action,dryRun){if(action==="create")return dryRun?"would create":"created";return dryRun?"would update":"updated"}export function formatImportedProduct(product,format,dryRun=false){const variantCount=product.variants.create+product.variants.update;const details=[money(product.priceMinor,product.currency,format),variantCount>0?`${variantCount} variant${variantCount===1?"":"s"}`:null,product.category?`in ${product.category}`:null,product.vendor?`by ${product.vendor}`:null,product.imageCount===0?"no image":null].filter(Boolean).join(", ");return` ${verbOf(product.action,dryRun).padEnd(12)} ${product.name} (${product.handle}) ${details}`}export function formatImportedCustomer(customer,dryRun=false){const matched=customer.matchedBy==="email"?" (matched an existing customer by email)":"";return` ${verbOf(customer.action,dryRun).padEnd(12)} ${customer.name} <${customer.email}>${matched}`}export function formatImportedOrder(order,format,dryRun=false){const details=[format(order.totalMinor,order.currency),`${order.status} (${order.sourceStatus})`,`${order.lines} line${order.lines===1?"":"s"}`,order.unlinkedLines>0?`${order.unlinkedLines} without a product`:null,order.refundedMinor>0&&order.status!=="REFUNDED"?`${format(order.refundedMinor,order.currency)} refunded`:null,order.customerEmail?`for ${order.customerEmail}`:"no customer"].filter(Boolean).join(", ");return` ${verbOf(order.action,dryRun).padEnd(12)} ${order.number??order.externalId} ${details}`}export function formatImportSummary(result){const{counts}=result;const would=result.dryRun?"would be ":"";return[`Products: ${counts.products.created} ${would}created, ${counts.products.updated} ${would}updated`,`Variants: ${counts.variants.created} ${would}created, ${counts.variants.updated} ${would}updated`,`Categories: ${counts.categories.created} ${would}created. Manufacturers: ${counts.manufacturers.created} ${would}created`,...counts.duplicates>0?[`Duplicates skipped: ${counts.duplicates}`]:[],`Currency: ${result.currencies.length>0?result.currencies.join(", "):"not reported by the store"}`]}export function formatCustomerSummary(result){const would=result.dryRun?"would be ":"";const{customers,merged}=result.counts;return[`Customers: ${customers.created} ${would}created, ${customers.updated} ${would}updated${merged>0?`, ${merged} merged by email`:""}`]}export function formatOrderSummary(result){const would=result.dryRun?"would be ":"";const{orders,customers,lines,duplicates}=result.counts;return[`Orders: ${orders.created} ${would}created, ${orders.updated} ${would}updated${duplicates>0?`, ${duplicates} duplicates skipped`:""}`,`Order lines: ${lines.linked} linked to a product, ${lines.unlinked} without one${lines.productless>0?`, ${lines.productless} with no product at the source (fees, custom or deleted items)`:""}`,...customers.created>0?[`Customers created from orders: ${customers.created}`]:[],`Order currencies: ${result.currencies.length>0?result.currencies.join(", "):"none"}`]}export function currencyMismatch(result,configured){if(!configured||result.currencies.length===0)return null;const other=result.currencies.filter((code)=>code!==configured.toUpperCase());if(other.length===0)return null;return`Prices were imported in ${other.join(", ")} minor units, but config/commerce.ts sets currency to ${configured}. products.price has no currency column, so set commerce.currency to match.`}export function commerceDisabledReason(enabled,dryRun){if(enabled||dryRun)return null;return"Commerce is disabled, so its tables (products, customers, orders) are not migrated. Set enabled: true in config/commerce.ts (or run buddy commerce:install), run buddy migrate, then import again. --dry-run works without it."}export const OUT_OF_SCOPE_NOTE="Customers and orders were not imported. Add --customers and/or --orders, with the admin API credentials in env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, or SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET.";async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function reportWarnings(warnings){for(const warning of warnings)log.warn(warning.externalId?`${warning.externalId}: ${warning.message}`:warning.message)}export function commerceImport(buddy){buddy.command("commerce:import <url>","Import a Shopify, WooCommerce or Shopware 6 catalog, and optionally its customers and orders").option("--from <platform>",`Where the store lives: ${SUPPORTED_SOURCES.join(", ")}`).option("--customers","Also import customers from the admin API (credentials from env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY/_SECRET or SHOPWARE_CLIENT_ID/_SECRET)",{default:false}).option("--orders","Also import orders and their lines from the admin API (same credentials as --customers)",{default:false}).option("--catalog","Import the catalog too when --customers or --orders is given (it is the default otherwise)",{default:false}).option("--access-key <key>","Shopware catalog only: the sales channel access key (public, from Sales Channels > API access), or set SHOPWARE_ACCESS_KEY").option("--admin-url <url>","Customers and orders only: the admin API address when it differs from <url>, e.g. https://<store>.myshopify.com for a Shopify custom domain").option("--limit <count>","Import at most this many products, customers and orders (each)").option("--currency <code>","ISO 4217 currency, for a store or order that does not report one").option("--dry-run","Show what would be created or updated without writing anything",{default:false}).example("buddy commerce:import https://shop.example.com --from shopify --dry-run").example("buddy commerce:import example.com/shop --from woocommerce --limit 50").example("buddy commerce:import https://shop.example.de --from shopware --access-key SWSC... --dry-run").example("SHOPIFY_ADMIN_TOKEN=shpat_... buddy commerce:import https://shop.example.com --from shopify --customers --orders --admin-url northwind.myshopify.com").action(async(url,options)=>{let settings;try{settings=parseImportFlags(options)}catch(error){return fail(error.message)}try{const{feature}=await import("@stacksjs/config");const disabled=commerceDisabledReason(feature("commerce"),settings.dryRun);if(disabled)return fail(disabled)}catch{}const{catalogImport}=await import("@stacksjs/commerce");const formatMinor=catalogImport.formatMinor;const{include,dryRun}=settings;const accounts=include.customers||include.orders;let storeUrl;let credentials;try{storeUrl=catalogImport.normalizeStoreUrl(url);if(accounts)credentials=catalogImport.readAccountCredentials(settings.source,process.env)}catch(error){return fail(error.message)}if(include.catalog){let repository=catalogImport.createDatabaseRepository();if(dryRun){try{await repository.findProducts(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every product is reported as new.`);repository=catalogImport.createMemoryRepository()}}log.info(`${dryRun?"Dry run: reading":"Importing"} the ${settings.source} catalog at ${storeUrl}`);let result;try{result=await catalogImport.importCatalog({adapter:catalogImport.catalogAdapter(settings.source),storeUrl,repository,dryRun,limit:settings.limit,currency:settings.currency,accessKey:settings.accessKey,onProduct:(product)=>process.stdout.write(`${formatImportedProduct(product,formatMinor,dryRun)}
2
+ `)})}catch(error){return fail(`Import stopped: ${error.message}${dryRun?"":" Products written before this point are kept; re-running resumes safely."}`)}if(result.products.length===0)log.info(`${storeUrl} has no products to import.`);reportWarnings(result.warnings);for(const line of formatImportSummary(result))log.info(line);try{const{config}=await import("@stacksjs/config");const mismatch=currencyMismatch(result,config.commerce?.currency);if(mismatch)log.warn(mismatch)}catch{}}if(accounts){let repository=catalogImport.createDatabaseAccountRepository();if(dryRun){try{await repository.findOrders(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyAccountRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every customer and order is reported as new.`);repository=catalogImport.createReadOnlyAccountRepository(catalogImport.createMemoryAccountRepository())}if(include.catalog&&include.orders)log.info("A dry run writes no products, so order lines are matched only against products already in Stacks.")}const adapter=catalogImport.accountAdapter(settings.source);const shared={adapter,storeUrl,repository,credentials,dryRun,limit:settings.limit,currency:settings.currency,adminUrl:settings.adminUrl};if(include.customers){log.info(`${dryRun?"Dry run: reading":"Importing"} ${settings.source} customers from ${settings.adminUrl??storeUrl}`);try{const result=await catalogImport.importCustomers({...shared,onCustomer:(customer)=>process.stdout.write(`${formatImportedCustomer(customer,dryRun)}
3
3
  `)});reportWarnings(result.warnings);for(const line of formatCustomerSummary(result))log.info(line)}catch(error){return fail(`Customer import stopped: ${error.message}${dryRun?"":" Customers written before this point are kept; re-running resumes safely."}`)}}if(include.orders){log.info(`${dryRun?"Dry run: reading":"Importing"} ${settings.source} orders from ${settings.adminUrl??storeUrl}`);try{const result=await catalogImport.importOrders({...shared,onOrder:(order)=>process.stdout.write(`${formatImportedOrder(order,formatMinor,dryRun)}
4
- `)});reportWarnings(result.warnings);for(const line of formatOrderSummary(result))log.info(line)}catch(error){return fail(`Order import stopped: ${error.message}${dryRun?"":" Orders written before this point are kept; re-running resumes safely."}`)}}}else log.info(OUT_OF_SCOPE_NOTE);if(dryRun)log.info("Dry run complete. Nothing was written.");else log.success(`Import from ${storeUrl} complete.`);await log.flush();process.exit(ExitCode.Success)})}
4
+ `)});reportWarnings(result.warnings);for(const line of formatOrderSummary(result))log.info(line)}catch(error){return fail(`Order import stopped: ${error.message}${dryRun?"":" Orders written before this point are kept; re-running resumes safely."}`)}}}else{log.info(OUT_OF_SCOPE_NOTE)}if(dryRun)log.info("Dry run complete. Nothing was written.");else log.success(`Import from ${storeUrl} complete.`);await log.flush();process.exit(ExitCode.Success)})}
@@ -1 +1 @@
1
- import{runCommit}from"@stacksjs/actions";import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";export function commit(buddy){const descriptions={commit:"Commit your staged changes",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("commit",descriptions.commit).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy commit` ...",options);await runCommit(options)});onUnknownSubcommand(buddy,"commit")}
1
+ import{runCommit}from"@stacksjs/actions";import{log}from"@stacksjs/logging";import{onUnknownSubcommand}from"@stacksjs/cli";export function commit(buddy){const descriptions={commit:"Commit your staged changes",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("commit",descriptions.commit).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy commit` ...",options);await runCommit(options)});onUnknownSubcommand(buddy,"commit")}
@@ -1,4 +1,4 @@
1
- import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";export function completion(buddy){const descriptions={completion:"Generate shell completion scripts",shell:"Shell type (bash, zsh, fish)"};buddy.command("completion [shell]",descriptions.completion).option("-s, --shell [shell]",descriptions.shell).example("buddy completion bash").example("buddy completion zsh").example("buddy completion fish").example("buddy completion bash > /usr/local/etc/bash_completion.d/buddy").action(async(shell,options)=>{log.debug("Running `buddy completion` ...",options);const targetShell=shell||options.shell||"bash",commandNames=(buddy.commands||[]).map((cmd)=>cmd.name).filter((name)=>Boolean(name));switch(targetShell){case"bash":console.log(generateBashCompletion(commandNames));break;case"zsh":console.log(generateZshCompletion(commandNames));break;case"fish":console.log(generateFishCompletion(commandNames));break;default:console.error(`Unknown shell: ${targetShell}`);console.error("Supported shells: bash, zsh, fish");process.exit(1)}});onUnknownSubcommand(buddy,"completion")}function generateBashCompletion(commands){return`# buddy completion for bash
1
+ import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";export function completion(buddy){const descriptions={completion:"Generate shell completion scripts",shell:"Shell type (bash, zsh, fish)"};buddy.command("completion [shell]",descriptions.completion).option("-s, --shell [shell]",descriptions.shell).example("buddy completion bash").example("buddy completion zsh").example("buddy completion fish").example("buddy completion bash > /usr/local/etc/bash_completion.d/buddy").action(async(shell,options)=>{log.debug("Running `buddy completion` ...",options);const targetShell=shell||options.shell||"bash";const commands=buddy.commands||[];const commandNames=commands.map((cmd)=>cmd.name).filter((name)=>Boolean(name));switch(targetShell){case"bash":console.log(generateBashCompletion(commandNames));break;case"zsh":console.log(generateZshCompletion(commandNames));break;case"fish":console.log(generateFishCompletion(commandNames));break;default:console.error(`Unknown shell: ${targetShell}`);console.error("Supported shells: bash, zsh, fish");process.exit(1)}});onUnknownSubcommand(buddy,"completion")}function generateBashCompletion(commands){return`# buddy completion for bash
2
2
 
3
3
  _buddy_completion() {
4
4
  local cur prev commands
@@ -31,15 +31,15 @@ complete -F _buddy_completion buddy
31
31
  # - macOS: /usr/local/etc/bash_completion.d/buddy
32
32
  #
33
33
  # Then reload your shell or run: source ~/.bashrc
34
- `}function generateZshCompletion(commands){return`#compdef buddy
34
+ `}function generateZshCompletion(commands){const commandList=commands.map((cmd)=>` '${cmd}:${cmd} command'`).join(`
35
+ `);return`#compdef buddy
35
36
 
36
37
  # buddy completion for zsh
37
38
 
38
39
  _buddy() {
39
40
  local -a commands
40
41
  commands=(
41
- ${commands.map((cmd)=>` '${cmd}:${cmd} command'`).join(`
42
- `)}
42
+ ${commandList}
43
43
  )
44
44
 
45
45
  local -a global_flags
@@ -77,14 +77,14 @@ _buddy "$@"
77
77
  # Then add to your ~/.zshrc:
78
78
  # fpath=(~/.zsh/completions $fpath)
79
79
  # autoload -Uz compinit && compinit
80
- `}function generateFishCompletion(commands){return`# buddy completion for fish
80
+ `}function generateFishCompletion(commands){const commandCompletions=commands.map((cmd)=>`complete -c buddy -n "__fish_use_subcommand" -a "${cmd}" -d "${cmd} command"`).join(`
81
+ `);return`# buddy completion for fish
81
82
 
82
83
  # Remove old completions
83
84
  complete -c buddy -e
84
85
 
85
86
  # Command completions
86
- ${commands.map((cmd)=>`complete -c buddy -n "__fish_use_subcommand" -a "${cmd}" -d "${cmd} command"`).join(`
87
- `)}
87
+ ${commandCompletions}
88
88
 
89
89
  # Global flag completions
90
90
  complete -c buddy -l help -d "Display help message"
@@ -1,6 +1,6 @@
1
- import{existsSync,readFileSync,writeFileSync}from"node:fs";import process from"node:process";import{italic,log}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";const CODEMODS=[{id:"0.65-cache-driver-rename",description:"Rename `cache.driver` to `cache.default` (introduced in 0.65).",files:["cache.ts"],shouldApply:(c)=>/\bdriver\s*:/.test(c)&&!c.includes("default:"),apply:(c)=>c.replace(/(\bcache\b[\s\S]*?)\bdriver(\s*:)/m,"$1default$2")},{id:"0.68-search-engine-name",description:"Rename `searchEngine.driver` to `searchEngine.default` (matches other configs).",files:["search-engine.ts"],shouldApply:(c)=>/\bdriver\s*:/.test(c),apply:(c)=>c.replace(/\bdriver(\s*:)/g,"default$1")},{id:"0.70-ports-string-to-number",description:'Convert string port values like `"3000"` to numbers (TypeScript types now require number).',files:["ports.ts"],shouldApply:(c)=>/:\s*['"]\d+['"]/.test(c),apply:(c)=>c.replace(/:\s*['"](\d+)['"]/g,": $1")}];export async function runConfigMigrations(opts){const changed=[],skipped=[],codemods=opts.only?CODEMODS.filter((m)=>m.id===opts.only):CODEMODS;if(codemods.length===0){log.warn(`No matching codemods. Available: ${CODEMODS.map((m)=>m.id).join(", ")}`);return{changed,skipped}}for(const cm of codemods){log.info(`Codemod ${italic(cm.id)} - ${cm.description}`);for(const rel of cm.files){const full=projectPath(`config/${rel}`);if(!existsSync(full)){skipped.push(`${full} (missing)`);continue}const before=readFileSync(full,"utf-8");if(!cm.shouldApply(before)){skipped.push(`${full} (no changes)`);continue}const after=cm.apply(before);if(after===before){skipped.push(`${full} (no changes)`);continue}if(opts.dryRun){log.info(`[dry-run] would update ${full}`);printDiff(before,after)}else{writeFileSync(full,after);log.success(`updated ${full}`)}changed.push(full)}}return{changed,skipped}}function printDiff(before,after){const beforeLines=before.split(`
2
- `),afterLines=after.split(`
3
- `),max=Math.max(beforeLines.length,afterLines.length);for(let i=0;i<max;i++){const b=beforeLines[i],a=afterLines[i];if(b===a)continue;if(b!==void 0)process.stdout.write(` - ${b}
4
- `);if(a!==void 0)process.stdout.write(` + ${a}
1
+ import{existsSync,readFileSync,writeFileSync}from"node:fs";import process from"node:process";import{italic,log}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";const CODEMODS=[{id:"0.65-cache-driver-rename",description:"Rename `cache.driver` to `cache.default` (introduced in 0.65).",files:["cache.ts"],shouldApply:(c)=>/\bdriver\s*:/.test(c)&&!c.includes("default:"),apply:(c)=>c.replace(/(\bcache\b[\s\S]*?)\bdriver(\s*:)/m,"$1default$2")},{id:"0.68-search-engine-name",description:"Rename `searchEngine.driver` to `searchEngine.default` (matches other configs).",files:["search-engine.ts"],shouldApply:(c)=>/\bdriver\s*:/.test(c),apply:(c)=>c.replace(/\bdriver(\s*:)/g,"default$1")},{id:"0.70-ports-string-to-number",description:'Convert string port values like `"3000"` to numbers (TypeScript types now require number).',files:["ports.ts"],shouldApply:(c)=>/:\s*['"]\d+['"]/.test(c),apply:(c)=>c.replace(/:\s*['"](\d+)['"]/g,": $1")}];export async function runConfigMigrations(opts){const changed=[];const skipped=[];const codemods=opts.only?CODEMODS.filter((m)=>m.id===opts.only):CODEMODS;if(codemods.length===0){log.warn(`No matching codemods. Available: ${CODEMODS.map((m)=>m.id).join(", ")}`);return{changed,skipped}}for(const cm of codemods){log.info(`Codemod ${italic(cm.id)} - ${cm.description}`);for(const rel of cm.files){const full=projectPath(`config/${rel}`);if(!existsSync(full)){skipped.push(`${full} (missing)`);continue}const before=readFileSync(full,"utf-8");if(!cm.shouldApply(before)){skipped.push(`${full} (no changes)`);continue}const after=cm.apply(before);if(after===before){skipped.push(`${full} (no changes)`);continue}if(opts.dryRun){log.info(`[dry-run] would update ${full}`);printDiff(before,after)}else{writeFileSync(full,after);log.success(`updated ${full}`)}changed.push(full)}}return{changed,skipped}}function printDiff(before,after){const beforeLines=before.split(`
2
+ `);const afterLines=after.split(`
3
+ `);const max=Math.max(beforeLines.length,afterLines.length);for(let i=0;i<max;i++){const b=beforeLines[i];const a=afterLines[i];if(b===a)continue;if(b!==undefined)process.stdout.write(` - ${b}
4
+ `);if(a!==undefined)process.stdout.write(` + ${a}
5
5
  `)}process.stdout.write(`
6
- `)}export function configMigrate(buddy){buddy.command("config:migrate","Apply config-shape codemods for the latest Stacks version").option("--dry-run","Preview changes without writing",{default:!1}).option("--only [id]","Run a single codemod by id",{default:""}).action(async(options)=>{log.info("Running `buddy config:migrate` ...");const{changed,skipped}=await runConfigMigrations({dryRun:Boolean(options.dryRun),only:options.only?.length?options.only:void 0});log.info(`Changed: ${changed.length}, Skipped: ${skipped.length}`);if(skipped.length>0)for(const s of skipped)log.debug(` skipped: ${s}`)})}
6
+ `)}export function configMigrate(buddy){buddy.command("config:migrate","Apply config-shape codemods for the latest Stacks version").option("--dry-run","Preview changes without writing",{default:false}).option("--only [id]","Run a single codemod by id",{default:""}).action(async(options)=>{log.info("Running `buddy config:migrate` ...");const{changed,skipped}=await runConfigMigrations({dryRun:Boolean(options.dryRun),only:options.only?.length?options.only:undefined});log.info(`Changed: ${changed.length}, Skipped: ${skipped.length}`);if(skipped.length>0){for(const s of skipped)log.debug(` skipped: ${s}`)}})}
@@ -1,5 +1,5 @@
1
- import process from"node:process";import{log,onUnknownSubcommand,outro,runCommand}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function configure(buddy){const descriptions={configure:"Configure options",aws:"Configure the AWS connection",project:"Target a specific project",profile:"The AWS profile to use",verbose:"Enable verbose output"};buddy.command("configure",descriptions.configure).option("--aws",descriptions.aws,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy configure` ...",options);if(options?.aws){await configureAws(options);process.exit(ExitCode.Success)}log.info("Not implemented yet. Please use the --aws flag to configure AWS.");await log.flush();process.exit(ExitCode.Success)});buddy.command("configure:aws",descriptions.aws).option("-p, --project [project]",descriptions.project,{default:!1}).option("--profile",descriptions.profile).option("--verbose",descriptions.verbose,{default:!1}).option("--access-key-id","The AWS access key").option("--secret-access-key","The AWS secret access key").option("--region","The AWS region").option("--output","The AWS output format").option("--quiet","Suppress output").action(async(options)=>{log.debug("Running `buddy configure:aws` ...",options);await configureAws(options);process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"configure")}async function configureAws(options){const startTime=performance.now(),awsAccessKeyId=options?.accessKeyId??process.env.AWS_ACCESS_KEY_ID,awsSecretAccessKey=options?.secretAccessKey??process.env.AWS_SECRET_ACCESS_KEY,defaultRegion="us-east-1",defaultOutputFormat=options?.output??"json",profile=process.env.AWS_PROFILE??options?.profile,command=profile?`aws configure --profile ${profile}`:"aws configure",input=`${awsAccessKeyId}
1
+ import process from"node:process";import{log,onUnknownSubcommand,outro,runCommand}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function configure(buddy){const descriptions={configure:"Configure options",aws:"Configure the AWS connection",project:"Target a specific project",profile:"The AWS profile to use",verbose:"Enable verbose output"};buddy.command("configure",descriptions.configure).option("--aws",descriptions.aws,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy configure` ...",options);if(options?.aws){await configureAws(options);process.exit(ExitCode.Success)}log.info("Not implemented yet. Please use the --aws flag to configure AWS.");await log.flush();process.exit(ExitCode.Success)});buddy.command("configure:aws",descriptions.aws).option("-p, --project [project]",descriptions.project,{default:false}).option("--profile",descriptions.profile).option("--verbose",descriptions.verbose,{default:false}).option("--access-key-id","The AWS access key").option("--secret-access-key","The AWS secret access key").option("--region","The AWS region").option("--output","The AWS output format").option("--quiet","Suppress output").action(async(options)=>{log.debug("Running `buddy configure:aws` ...",options);await configureAws(options);process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"configure")}async function configureAws(options){const startTime=performance.now();const awsAccessKeyId=options?.accessKeyId??process.env.AWS_ACCESS_KEY_ID;const awsSecretAccessKey=options?.secretAccessKey??process.env.AWS_SECRET_ACCESS_KEY;const defaultRegion="us-east-1";const defaultOutputFormat=options?.output??"json";const profile=process.env.AWS_PROFILE??options?.profile;const command=profile?`aws configure --profile ${profile}`:`aws configure`;const input=`${awsAccessKeyId}
2
2
  ${awsSecretAccessKey}
3
3
  ${defaultRegion}
4
4
  ${defaultOutputFormat}
5
- `,result=await runCommand(command,{cwd:p.projectPath(),stdin:"pipe",input,stdout:"pipe"});if(resultFailed(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(options?.quiet)return;await outro("Exited",{startTime,useSeconds:!0})}
5
+ `;const result=await runCommand(command,{cwd:p.projectPath(),stdin:"pipe",input,stdout:"pipe"});if(resultFailed(result)){await outro("While running the cloud command, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}if(options?.quiet)return;await outro("Exited",{startTime,useSeconds:true})}
@@ -1 +1 @@
1
- import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{isCompiledBinary,relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{attemptPantryDependencies,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{bunExecutable,failureReason,installScaffoldDependencies}from"../scaffold-dependencies";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:!1}).option("-u, --ui",descriptions.ui,{default:!0}).option("-c, --components",descriptions.components,{default:!0}).option("-w, --web-components",descriptions.webComponents,{default:!0}).option("-p, --views",descriptions.views,{default:!0}).option("-f, --functions",descriptions.functions,{default:!0}).option("-a, --api",descriptions.api,{default:!0}).option("-d, --database",descriptions.database,{default:!0}).option("-ca, --cache",descriptions.cache,{default:!1}).option("-e, --email",descriptions.email,{default:!1}).option("-P, --project [project]",descriptions.project,{default:!1}).option("-m, --minimal",descriptions.minimal,{default:!1}).option("--native","Create a minimal offline Craft desktop app",{default:!1}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:!1}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:!1}).option("--with-core",descriptions.withCore,{default:!1}).option("--vendor-defaults",descriptions.vendorDefaults,{default:!1}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw Error("--adopt requires --native");if(options.desktop&&options.native)throw Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project"),{version}=await import("../../package.json"),{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);const missingSystemDependencies=await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options,missingSystemDependencies!==null);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(missingSystemDependencies!==null){log.warn(`The app is scaffolded at ${path}, but Pantry could not install its system dependencies: ${missingSystemDependencies}`);log.warn(`Finish with: ${cyan(`cd ${name??"."} && pantry install`)}`);log.warn(`Its JavaScript packages were installed with ${cyan("bun install")} instead, so everything else is ready.`);await log.flush();process.exit(ExitCode.FatalError)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! \u269B\uFE0F"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:!0})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:!0})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:!1}}catch(error){return{isErr:!0,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github"),destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:!0,force:!0});cpSync(source,destination,{recursive:!0});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config"),destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path),changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:!0,force:!0})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"])try{chmodSync(resolve(path,script),493)}catch{}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===!1){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return null}const outcome=await installScaffoldDependencies({pantry:async()=>{const failure=await attemptPantryDependencies(path);return failure===null?null:failureReason(failure.error)},hasNodeModules:()=>existsSync(resolve(path,"node_modules")),bunInstall:async()=>{const bun=bunExecutable(Bun.which("bun"),process.execPath,isCompiledBinary());if(bun===null)return"Bun is not on PATH, and this buddy is a compiled binary, so it cannot run Bun itself.";log.info("Installing the JavaScript packages with Bun...");const result=await runCommand([bun,"install"],{cwd:path});return resultFailed(result)?failureReason(result.error):null}});if(outcome.status==="complete"){log.success("Environment is ready");return null}if(outcome.status==="system-dependencies-missing"){log.warn(`Pantry could not install the system dependencies (${outcome.pantryFailure}). Continuing with the JavaScript packages Bun installed.`);return outcome.pantryFailure}if(outcome.pantryFailure!==null)await log.error(`Pantry could not install the dependencies: ${outcome.pantryFailure}`);await log.error(`Bun could not install the JavaScript packages either: ${outcome.bunFailure}`);await log.error(`${path} is only partly scaffolded. Delete it and run \`buddy new\` again once the installers can reach their registries.`);process.exit(ExitCode.FatalError)}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example \u2192 .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:!0});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git")))log.info("Existing git repository detected, skipping git init");else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options,withBun){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const result=await runCommand(withBun?"./buddy unpublish:core --all --force --installer bun":"./buddy unpublish:core --all --force",{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:!0})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path),scripts=applyAppPackageScripts(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path}),authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=!1;for(const{feature,configOutcome,filesRemoved}of results)if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=!0;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}if(!strippedAny)log.info(" \u2192 no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
1
+ import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{isCompiledBinary,relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{attemptPantryDependencies,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{bunExecutable,failureReason,installScaffoldDependencies}from"../scaffold-dependencies";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",ui:"Are you building a UI?",components:"Are you building UI components?",webComponents:"Automagically built optimized custom elements/web components?",views:"How about views?",functions:"Are you developing functions/composables?",api:"Are you building an API?",database:"Do you need a database?",notifications:"Do you need notifications? e.g. email, SMS, push or chat notifications",cache:"Do you need caching?",email:"Do you need email?",project:"Target a specific project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:false}).option("-u, --ui",descriptions.ui,{default:true}).option("-c, --components",descriptions.components,{default:true}).option("-w, --web-components",descriptions.webComponents,{default:true}).option("-p, --views",descriptions.views,{default:true}).option("-f, --functions",descriptions.functions,{default:true}).option("-a, --api",descriptions.api,{default:true}).option("-d, --database",descriptions.database,{default:true}).option("-ca, --cache",descriptions.cache,{default:false}).option("-e, --email",descriptions.email,{default:false}).option("-P, --project [project]",descriptions.project,{default:false}).option("-m, --minimal",descriptions.minimal,{default:false}).option("--native","Create a minimal offline Craft desktop app",{default:false}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:false}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:false}).option("--with-core",descriptions.withCore,{default:false}).option("--vendor-defaults",descriptions.vendorDefaults,{default:false}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw new Error("--adopt requires --native");if(options.desktop&&options.native)throw new Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project");const{version}=await import("../../package.json");const{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw new Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);const missingSystemDependencies=await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options,missingSystemDependencies!==null);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(missingSystemDependencies!==null){log.warn(`The app is scaffolded at ${path}, but Pantry could not install its system dependencies: ${missingSystemDependencies}`);log.warn(`Finish with: ${cyan(`cd ${name??"."} && pantry install`)}`);log.warn(`Its JavaScript packages were installed with ${cyan("bun install")} instead, so everything else is ready.`);await log.flush();process.exit(ExitCode.FatalError)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! ⚛️"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:true})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:true})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:false}}catch(error){return{isErr:true,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github");const destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:true,force:true});cpSync(source,destination,{recursive:true});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config");const destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path);const changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:true,force:true})}log.success("App starts with a clean test suite")}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"]){try{chmodSync(resolve(path,script),493)}catch{}}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===false){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return null}const outcome=await installScaffoldDependencies({pantry:async()=>{const failure=await attemptPantryDependencies(path);return failure===null?null:failureReason(failure.error)},hasNodeModules:()=>existsSync(resolve(path,"node_modules")),bunInstall:async()=>{const bun=bunExecutable(Bun.which("bun"),process.execPath,isCompiledBinary());if(bun===null)return"Bun is not on PATH, and this buddy is a compiled binary, so it cannot run Bun itself.";log.info("Installing the JavaScript packages with Bun...");const result=await runCommand([bun,"install"],{cwd:path});return resultFailed(result)?failureReason(result.error):null}});if(outcome.status==="complete"){log.success("Environment is ready");return null}if(outcome.status==="system-dependencies-missing"){log.warn(`Pantry could not install the system dependencies (${outcome.pantryFailure}). Continuing with the JavaScript packages Bun installed.`);return outcome.pantryFailure}if(outcome.pantryFailure!==null)await log.error(`Pantry could not install the dependencies: ${outcome.pantryFailure}`);await log.error(`Bun could not install the JavaScript packages either: ${outcome.bunFailure}`);await log.error(`${path} is only partly scaffolded. Delete it and run \`buddy new\` again once the installers can reach their registries.`);process.exit(ExitCode.FatalError)}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example → .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:true});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}if(existsSync(resolve(path,".git"))){log.info("Existing git repository detected, skipping git init")}else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80")}async function unvendorCore(path,options,withBun){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const command=withBun?"./buddy unpublish:core --all --force --installer bun":"./buddy unpublish:core --all --force";const result=await runCommand(command,{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:true})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path);const scripts=applyAppPackageScripts(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path});const authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=false;for(const{feature,configOutcome,filesRemoved}of results){if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=true;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}}if(!strippedAny)log.info(" → no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}