@stacksjs/buddy 0.75.618 → 0.75.622
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -3
- package/dist/commands/cd.d.ts +4 -4
- package/dist/commands/cd.js +6 -7
- package/dist/commands/create.d.ts +1 -1
- package/dist/commands/create.js +1 -1
- package/dist/commands/daemon.d.ts +2 -0
- package/dist/commands/daemon.js +5 -0
- package/dist/commands/dashboard.d.ts +2 -0
- package/dist/commands/dashboard.js +2 -0
- package/dist/commands/deploy.d.ts +11 -1
- package/dist/commands/deploy.js +46 -5
- package/dist/commands/dev.js +1 -1
- package/dist/commands/migrate.js +4 -4
- package/dist/commands/ports.js +1 -2
- package/dist/commands/projects.js +4 -1
- package/dist/launcher.d.ts +51 -0
- package/dist/launcher.js +2 -0
- package/dist/lazy-commands.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/workflow-template.js +1 -1
- package/package.json +60 -60
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import{writeSync}from"node:fs";import process from"node:process";import{registerGlobalOptions}from"./global-options";import{shouldSkipAppKeyCheck}from"./project-setup";import{resultFailed}from"./result";import{versionLine}from"./version-info";const
|
|
3
|
-
`);process.exit(0)}const{isNativeProject,runNativeProjectCommand}=await import("./native-project");if(isNativeProject(process.cwd())){try{if(await runNativeProjectCommand(process.cwd(),args))process.exit(0)}catch(error){console.error(`[buddy] ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}const[{cli,log},{path:p}]=await Promise.all([import("@stacksjs/cli"),import("@stacksjs/path")]);try{const{isSupportedBunVersion,minimumBunVersion}=await import("@stacksjs/utils");const currentBunVersion=typeof Bun!=="undefined"?Bun.version:process.versions.bun;if(currentBunVersion&&!isSupportedBunVersion(currentBunVersion)){console.error(`[buddy] Bun v${minimumBunVersion} or later is required (current: v${currentBunVersion}). Run: bun upgrade`);process.exit(1)}}catch{}const isHelpFlag=args.includes("--help")||args.includes("-h");const isHelpMode=requestedCommand==="help"||isHelpFlag&&args.length<=2;const skipAppKeyCheck=shouldSkipAppKeyCheck(requestedCommand,{isHelpFlag,isHelpMode});const needsFullSetup=!isVersionOnly;if(!process.env.LOG_LEVEL){if(args.includes("--quiet")||args.includes("-q"))process.env.LOG_LEVEL="warn";else if(args.includes("--verbose")||args.includes("-v"))process.env.LOG_LEVEL="debug"}if(needsFullSetup){const reportFatal=(label,error)=>{log.debug(`Buddy ${label}`);try{process.stderr.write(`
|
|
2
|
+
import{writeSync}from"node:fs";import process from"node:process";import{registerGlobalOptions}from"./global-options";import{shouldSkipAppKeyCheck}from"./project-setup";import{resultFailed}from"./result";import{versionLine}from"./version-info";if(import.meta.main)await runCli();async function runCli(){const typedArgs=process.argv.slice(2);const isVersionOnly=typedArgs.length===1&&["--version","-V","version"].includes(typedArgs[0]);if(isVersionOnly){writeSync(process.stdout.fd,`${versionLine} ${process.platform}-${process.arch} bun-v${Bun.version}
|
|
3
|
+
`);process.exit(0)}const[{HANDED_ROOT_ENV,launch},{getCommandNames}]=await Promise.all([import("./launcher"),import("./lazy-commands")]);launch({args:typedArgs,cwd:process.cwd(),main:Bun.main,execArgv:process.execArgv,handedRoot:process.env[HANDED_ROOT_ENV],builtInCommands:new Set(getCommandNames())});const args=process.argv.slice(2);const requestedCommand=args[0]||"help";const{isNativeProject,runNativeProjectCommand}=await import("./native-project");if(isNativeProject(process.cwd())){try{if(await runNativeProjectCommand(process.cwd(),args))process.exit(0)}catch(error){console.error(`[buddy] ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}const[{cli,log},{path:p}]=await Promise.all([import("@stacksjs/cli"),import("@stacksjs/path")]);try{const{isSupportedBunVersion,minimumBunVersion}=await import("@stacksjs/utils");const currentBunVersion=typeof Bun!=="undefined"?Bun.version:process.versions.bun;if(currentBunVersion&&!isSupportedBunVersion(currentBunVersion)){console.error(`[buddy] Bun v${minimumBunVersion} or later is required (current: v${currentBunVersion}). Run: bun upgrade`);process.exit(1)}}catch{}const isHelpFlag=args.includes("--help")||args.includes("-h");const isHelpMode=requestedCommand==="help"||isHelpFlag&&args.length<=2;const skipAppKeyCheck=shouldSkipAppKeyCheck(requestedCommand,{isHelpFlag,isHelpMode});const needsFullSetup=!isVersionOnly;if(!process.env.LOG_LEVEL){if(args.includes("--quiet")||args.includes("-q"))process.env.LOG_LEVEL="warn";else if(args.includes("--verbose")||args.includes("-v"))process.env.LOG_LEVEL="debug"}if(needsFullSetup){const reportFatal=(label,error)=>{log.debug(`Buddy ${label}`);try{process.stderr.write(`
|
|
4
4
|
[buddy] ${label}: ${error?.stack??String(error)}
|
|
5
5
|
`)}catch{}log.error(error);return process.exit(1)};process.on("uncaughtException",(error)=>reportFatal("uncaughtException",error));process.on("unhandledRejection",(error)=>reportFatal("unhandledRejection",error))}async function main(){const buddy=cli("buddy");registerGlobalOptions(buddy,{version:requestedCommand!=="upgrade"&&requestedCommand!=="update"});const configPath="./buddy.config.js";try{await Bun.file(configPath).text();const{applyBuddyConfig}=await import("./config.js");await applyBuddyConfig(buddy)}catch{}if(needsFullSetup){p.ensureRuntimeDirectories();const{loadCommands,getCommandsToLoad}=await import("./lazy-commands.js");if(!skipAppKeyCheck){const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const{ensureProjectIsInitialized}=await import("@stacksjs/utils");const isAppKeySet=await ensureProjectIsInitialized();if(!isAppKeySet){log.info("Your `APP_KEY` is not yet set");log.info("Generating application key...");const result=await runAction(Action.KeyGenerate);if(resultFailed(result)){await log.error("Failed to set random application key.",result.error);process.exit(1)}}}const commandsToLoad=getCommandsToLoad(args);await loadCommands(commandsToLoad,buddy);await dynamicImports(buddy)}else{const{loadCommand}=await import("./lazy-commands.js");await loadCommand("version",buddy)}buddy.help();if(args.length===0&&process.stdin.isTTY&&!buddy.isNoInteraction){await showInteractiveMenu(buddy)}else{await parseOrExit(buddy)}}async function showInteractiveMenu(buddy){const{bold,green,intro}=await import("@stacksjs/cli");const{select}=await import("@stacksjs/cli");await intro("buddy");console.log(bold(green("What would you like to do?")));console.log("");const choice=await select({message:"Select a command:",choices:[{value:"dev",label:"Start development server"},{value:"build",label:"Build for production"},{value:"test",label:"Run tests"},{value:"list",label:"List all commands"},{value:"doctor",label:"Run health checks"},{value:"about",label:"Show system information"},{value:"help",label:"Show help"},{value:"exit",label:"Exit"}],initial:0});console.log("");if(choice==="exit"){process.exit(0)}else if(choice==="help"){buddy.outputHelp()}else{process.argv=["bun","buddy",choice];await parseOrExit(buddy)}}async function parseOrExit(buddy){try{await buddy.parse()}catch(error){const isUsageError=error?.name==="ClappError"||error?.isUsageError===true;if(!isUsageError)throw error;process.stderr.write(`${error.message}
|
|
6
6
|
`);if(error.usage)process.stderr.write(`${error.usage}
|
|
7
|
-
`);process.exit(typeof error.exitCode==="number"?error.exitCode:2)}}await main();
|
|
7
|
+
`);process.exit(typeof error.exitCode==="number"?error.exitCode:2)}}await main();async function dynamicImports(buddy){const{loadCommands}=await import("@stacksjs/cli");const commands=()=>buddy.commands??[];const before=commands().length;await loadCommands(buddy,{commandsDir:p.appPath("Commands"),registryPath:p.appPath("Commands.ts"),onError:(message,error)=>log.error(`${message}:`,error),onDebug:(message)=>log.debug(message)});const appCommandNames=new Set(commands().slice(before).flatMap((command)=>[command.name??"",...command.aliasNames??[]]));if(appCommandNames.has(requestedCommand)){const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports()}try{const listenerImport=await import(p.listenersPath("Console.ts"));if(typeof listenerImport.default==="function")listenerImport.default(buddy)}catch{}}}export function applyAliases(cli,signature,aliases){const name=signature.trim().split(/\s+/)[0];const commands=cli?.commands;const command=commands?.find((candidate)=>candidate.name===name);if(!command||typeof command.alias!=="function")return false;for(const alias of aliases)command.alias(alias);return true}
|
package/dist/commands/cd.d.ts
CHANGED
|
@@ -10,10 +10,10 @@ import type { CLI } from '@stacksjs/types';
|
|
|
10
10
|
*
|
|
11
11
|
* Then `bcd my-project` actually changes the shell's directory.
|
|
12
12
|
*
|
|
13
|
-
* The
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
13
|
+
* The name is looked up on the machine's project list (`buddy projects`),
|
|
14
|
+
* which answers at once. This used to walk the home directory on every call;
|
|
15
|
+
* `--root` now names a directory to look in for a project that is not on the
|
|
16
|
+
* list yet.
|
|
17
17
|
*
|
|
18
18
|
* stacksjs/stacks#527.
|
|
19
19
|
*/
|
package/dist/commands/cd.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import
|
|
2
|
-
`);process.stderr.write('Tip: add `bcd() { eval "$(buddy cd "$1" --eval)"; }` to your shell rc to make this act like a real `cd`.\n');process.exit(ExitCode.FatalError)}const root=options.root??process.env.STACKS_PROJECTS_ROOT
|
|
3
|
-
`);
|
|
4
|
-
`);process.exit(ExitCode.FatalError)}if(
|
|
5
|
-
`);
|
|
6
|
-
`);
|
|
7
|
-
`);else process.stdout.write(`${dest}
|
|
1
|
+
import process from"node:process";import{findProject}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";export function cd(buddy){buddy.command("cd [name]","Print the absolute path of a Stacks project by name").option("--eval",'Emit `cd "path"` instead of just the path - pair with `eval "$(buddy cd <name> --eval)"` for real shell-cd',{default:false}).option("--root <dir>","A directory to look in for a project that is not on the list yet (overrides STACKS_PROJECTS_ROOT)").option("--verbose","Enable verbose output",{default:false}).action((name,options)=>{if(!name){process.stderr.write(`Usage: buddy cd <project-name> [--eval] [--root <dir>]
|
|
2
|
+
`);process.stderr.write('Tip: add `bcd() { eval "$(buddy cd "$1" --eval)"; }` to your shell rc to make this act like a real `cd`.\n');process.exit(ExitCode.FatalError)}const root=options.root??process.env.STACKS_PROJECTS_ROOT;const match=findProject(name,root||process.cwd());if(match.candidates.length>0){process.stderr.write(`Ambiguous project name "${name}". Matches:
|
|
3
|
+
`);for(const candidate of match.candidates)process.stderr.write(` - ${candidate.name} → ${candidate.path}
|
|
4
|
+
`);process.exit(ExitCode.FatalError)}if(!match.project){process.stderr.write(`No Stacks project matched: ${name}
|
|
5
|
+
`);process.stderr.write("(Looked on this machine's project list; see `buddy projects`. A project joins it the first time buddy runs inside it, and `buddy projects:scan` adds the ones already on disk.)\n");process.exit(ExitCode.FatalError)}if(options.eval)process.stdout.write(`cd ${JSON.stringify(match.project.path)}
|
|
6
|
+
`);else process.stdout.write(`${match.project.path}
|
|
8
7
|
`);process.exit(ExitCode.Success)})}
|
|
@@ -56,6 +56,6 @@ export declare function offlineReason(fetcher?: typeof fetch): Promise<string |
|
|
|
56
56
|
* scaffolding a week apart get the same app rather than whatever main happened
|
|
57
57
|
* to be.
|
|
58
58
|
*/
|
|
59
|
-
export declare function templateRef(fetchVersions?: typeof fetchPublishedVersions): Promise<string | null>;
|
|
59
|
+
export declare function templateRef(fetchVersions?: typeof fetchPublishedVersions, requested?: string): Promise<string | null>;
|
|
60
60
|
/** The gitit spec for a template ref, or the default branch when there is none. */
|
|
61
61
|
export declare function templateSpec(ref: string | null): string;
|
package/dist/commands/create.js
CHANGED
|
@@ -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,applyAppPackageOverrides,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{commitScaffold}from"../scaffold-git";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",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("-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);const createdRepository=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(createdRepository)recordScaffold(path);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 recordScaffold(path){const reason=commitScaffold(path,appIdentity(path).displayName);if(reason===null)log.success("Committed the generated app");else log.warn(`Left the generated app uncommitted (${reason}). Make the first commit yourself.`)}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)}const createdRepository=!existsSync(resolve(path,".git"));if(!createdRepository){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");return createdRepository}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);applyAppPackageOverrides(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.")}
|
|
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,applyAppPackageOverrides,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{commitScaffold}from"../scaffold-git";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",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("-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("--ref <ref>","Scaffold from an explicit Stacks tag, branch or commit").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);const createdRepository=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(createdRepository)recordScaffold(path);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,requested){if(requested!==undefined){if(typeof requested!=="string"||!/^[a-zA-Z0-9][\w./-]{0,199}$/.test(requested)||requested.includes("..")||requested.endsWith("/"))throw new Error("Choose a valid Stacks template ref");return requested}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(fetchPublishedVersions,options.ref);try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:true})}catch(error){if(!ref||options.ref!==undefined)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 recordScaffold(path){const reason=commitScaffold(path,appIdentity(path).displayName);if(reason===null)log.success("Committed the generated app");else log.warn(`Left the generated app uncommitted (${reason}). Make the first commit yourself.`)}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)}const createdRepository=!existsSync(resolve(path,".git"));if(!createdRepository){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");return createdRepository}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);applyAppPackageOverrides(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.")}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import process from"node:process";import{bold,dim,green,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";function uptime(since){const minutes=Math.max(0,Math.round((Date.now()-Date.parse(since))/60000));if(minutes<1)return"just now";if(minutes<60)return`${minutes}m`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function memoryMb(pid){const result=Bun.spawnSync(["ps","-o","rss=","-p",String(pid)],{stdout:"pipe",stderr:"ignore"});const kilobytes=Number(result.stdout.toString().trim());return result.exitCode===0&&kilobytes>0?Math.round(kilobytes/1024):null}export function daemon(buddy){const descriptions={status:"Show whether buddy is running in the background and what it is running",start:"Start buddy in the background",stop:"Stop the background buddy and the dashboards it started",restart:"Restart the background buddy",logs:"Print the background buddy's log",json:"Print the status as JSON"};async function status(options){const{daemonStatus}=await import("@stacksjs/actions/daemon/client");const running=await daemonStatus();if(options.json){process.stdout.write(`${JSON.stringify(running,null,2)}
|
|
2
|
+
`);return}if(!running){console.log(`buddy is not running in the background. ${dim("It starts when something needs it: buddy dashboard")}`);return}const memory=memoryMb(running.pid);console.log(`${green("●")} buddy is running in the background ${dim(`(pid ${running.pid}, up ${uptime(running.startedAt)}${memory?`, ${memory} MB`:""})`)}`);if(running.dashboards.length===0){console.log(dim(" No dashboards running. It stops by itself after a while with none."));return}const width=Math.max(...running.dashboards.map((dashboard)=>dashboard.name.length));for(const dashboard of running.dashboards){const state=dashboard.state==="ready"?dashboard.url:dim("starting");console.log(` ${bold(dashboard.name.padEnd(width))} ${state} ${dim(`up ${uptime(dashboard.startedAt)}`)}`)}}for(const name of["daemon","daemon:status"]){buddy.command(name,descriptions.status).option("--json",descriptions.json,{default:false}).action(async(options)=>{await status(options);process.exit(ExitCode.Success)})}buddy.command("daemon:start",descriptions.start).action(async()=>{const{startDaemon}=await import("@stacksjs/actions/daemon/client");const{status:running,started}=await startDaemon();console.log(started?`${green("●")} buddy is now running in the background ${dim(`(pid ${running.pid})`)}`:`buddy is already running in the background ${dim(`(pid ${running.pid})`)}`);process.exit(ExitCode.Success)});buddy.command("daemon:stop",descriptions.stop).action(async()=>{const{stopDaemon}=await import("@stacksjs/actions/daemon/client");console.log(await stopDaemon()?"Stopped the background buddy.":"buddy was not running in the background.");process.exit(ExitCode.Success)});buddy.command("daemon:restart",descriptions.restart).action(async()=>{const{startDaemon,stopDaemon}=await import("@stacksjs/actions/daemon/client");await stopDaemon();const{status:running}=await startDaemon();console.log(`${green("●")} buddy is running in the background ${dim(`(pid ${running.pid})`)}`);process.exit(ExitCode.Success)});buddy.command("daemon:logs",descriptions.logs).option("--lines <count>","How many lines from the end to print",{default:50}).action(async(options)=>{const{daemonLogFile}=await import("@stacksjs/actions/daemon/paths");const file=daemonLogFile();if(!existsSync(file)){console.log("The background buddy has not written a log yet.");process.exit(ExitCode.Success)}const lines=readFileSync(file,"utf8").trimEnd().split(`
|
|
3
|
+
`);process.stdout.write(`${lines.slice(-(Number(options.lines)||50)).join(`
|
|
4
|
+
`)}
|
|
5
|
+
`);process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"daemon")}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import process from"node:process";import{bold,cyan,dim,green}from"@stacksjs/cli";import{findProject,findProjectRoot,listProjects,registerProject}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";function open(url){const command=process.platform==="darwin"?["open",url]:process.platform==="win32"?["cmd","/c","start","",url]:["xdg-open",url];Bun.spawn(command,{stdout:"ignore",stderr:"ignore"}).unref()}function fail(message){process.stderr.write(`${message}
|
|
2
|
+
`);process.exit(ExitCode.FatalError)}function targetProject(name){if(name){const match=findProject(name);if(match.candidates.length>0)fail(`"${name}" matches more than one project: ${match.candidates.map((candidate)=>candidate.name).join(", ")}`);if(!match.project)fail(`No Stacks project matches "${name}". Run \`buddy projects\` to see the ones on this machine.`);return match.project.path}const here=findProjectRoot(process.cwd());if(here)return here;const recent=listProjects()[0];if(!recent)fail("There is no Stacks project here, and none on this machine's list yet. Run this inside a project, or create one: buddy new my-app");return recent.path}export function dashboard(buddy){buddy.command("dashboard [project]","Open a project's dashboard, starting it in the background if needed").option("-p, --project [project]","The project to open, by name or path").option("--no-open","Start it and print its address without opening a browser").option("--stop","Stop the project's background dashboard",{default:false}).action(async(name,options)=>{const root=targetProject(name??(typeof options.project==="string"?options.project:undefined));const project=registerProject(root);const label=bold(project?.name??root);const{openProjectDashboard,stopProjectDashboard}=await import("@stacksjs/actions/daemon/client");if(options.stop){console.log(await stopProjectDashboard(root)?`Stopped the dashboard for ${label}.`:`${label} has no dashboard running in the background.`);process.exit(ExitCode.Success)}try{const{url,started}=await openProjectDashboard(root);console.log(`${green("➜")} ${label} ${cyan(url)} ${dim(started?"started in the background":"already running")}`);if(options.open!==false)open(url)}catch(error){fail(error.message)}process.exit(ExitCode.Success)})}
|
|
@@ -568,13 +568,23 @@ export declare function relayAccountFromConfig(cfg: any, domain: string | undefi
|
|
|
568
568
|
* left for the mail step, which says what it could not do.
|
|
569
569
|
*/
|
|
570
570
|
export declare function ensureMailboxPasswords(logger: Pick<typeof log, 'info' | 'warn'>, file?: string, options?: { config?: any, save?: (key: string, value: string, file: string) => Promise<unknown> | unknown, hasConfig?: boolean }): Promise<string[]>;
|
|
571
|
+
/**
|
|
572
|
+
* A project slug as the mail reconcile writes it into a shell script and the
|
|
573
|
+
* server's domain-owner list: the same characters a gateway fragment's file
|
|
574
|
+
* name can hold, and nothing that could leave a single-quoted string. Empty
|
|
575
|
+
* when there is none, which skips the ownership check rather than recording a
|
|
576
|
+
* claim nobody can match later.
|
|
577
|
+
*/
|
|
578
|
+
export declare function mailProjectSlug(slug: unknown): string;
|
|
579
|
+
/** The project that owns the domain, when the server refused this reconcile for it. */
|
|
580
|
+
export declare function mailDomainOwner(out: string): string | undefined;
|
|
571
581
|
/**
|
|
572
582
|
* Everything is MERGE-based so a shared mail server keeps every other tenant's
|
|
573
583
|
* domains, keys, users, and forward rules untouched. Best-effort — a hiccup is
|
|
574
584
|
* logged, never fails the release. Returns what the DNS step needs (mail host +
|
|
575
585
|
* DKIM public key), or null when there is nothing to reconcile / it failed.
|
|
576
586
|
*/
|
|
577
|
-
export declare function provisionMailTenant(ip: string, logger: typeof log): Promise<MailTenantResult | null>;
|
|
587
|
+
export declare function provisionMailTenant(ip: string, logger: typeof log, options?: { projectSlug?: string }): Promise<MailTenantResult | null>;
|
|
578
588
|
/**
|
|
579
589
|
* The DNS provider the project declared, if any.
|
|
580
590
|
*
|