@stacksjs/buddy 0.75.652 → 0.75.653
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/commands/dev.js +4 -4
- package/dist/commands/docs.js +1 -1
- package/dist/native-project-templates.d.ts +1 -1
- package/dist/native-project-templates.js +4 -1
- package/dist/tray/api.js +1 -1
- package/dist/tray/run.js +30 -17
- package/dist/tray/view.d.ts +1 -1
- package/package.json +57 -57
package/dist/commands/dev.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=false){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", ");const line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){const candidates=[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")];return candidates.find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale"){throw new Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`)}try{const{measureDefaultsDrift}=await actions();const drift=measureDefaultsDrift(projectPath(),{shallow:true});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return false;await runners[selection]();return true}export function resolvePrettyDevDomain(appUrl,nativeMode=false){if(!appUrl||nativeMode)return null;try{const url=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`);const hostname=url.hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"];const SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");return source.match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");const value=source.match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:undefined}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path)){try{return readFileSync(path,"utf8")}catch{return""}}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return false;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath();const configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==undefined||viewSource(root,"auth/login")!==undefined;const candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==undefined);const appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:undefined);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{const subprocess=Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});subprocess.unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return true;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:false})}catch{return false}}export async function claimDevPorts(servers,isFree,attempts=20){const preferred=new Set(servers.map((server)=>server.preferred));const taken=new Set;const ports=[];const shifts=[];for(const server of servers){let port=server.preferred;if(taken.has(port)||!await isFree(port)){for(let candidate=server.preferred+1;candidate<server.preferred+attempts;candidate++){if(taken.has(candidate)||preferred.has(candidate)||!await isFree(candidate))continue;port=candidate;break}}if(port!==server.preferred)shifts.push(`${server.label} :${server.preferred} → :${port}`);taken.add(port);ports.push(port)}return{ports,shifts}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:false}).option("-l, --with-localhost",descriptions.withLocalhost,{default:false}).option("--browser",descriptions.browser,{default:false}).option("--site",descriptions.site,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("--detach",descriptions.detach,{default:false}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":undefined)||(options.api?"api":undefined)||(options.components?"components":undefined)||(options.dashboard?"dashboard":undefined)||(options.desktop?"desktop":undefined)||(options.native?"native":undefined)||(options.systemTray||options["system-tray"]?"system-tray":undefined)||(options.docs?"docs":undefined);if(target){const serverOptions={...options};const a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))});const a=await actions();const handled=await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:true},perf),native:()=>startDevelopmentServer({...options,native:true},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)});if(!handled){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else{await startDevelopmentServer(options,perf)}outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components");const result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs");const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const{ports:[docsPort=preferredDocsPort],shifts}=process.env.STACKS_PROXY_MANAGED==="1"?{ports:[preferredDocsPort],shifts:[]}:await claimDevPorts([{label:"Docs",preferred:preferredDocsPort}],portIsFree);process.env.PORT_DOCS=String(docsPort);if(shifts.length>0)console.log(` ${yellow("⚠")} ${yellow("Port in use by another process")} ${dim(`- ${shifts.join(", ")}`)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(`http://localhost:${docsPort}`)}
|
|
2
|
-
`);const result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:desktop",descriptions.desktop).option("--native","Run the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");if(!options.native&&await hasWebviewDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopWebview,options);if(resultFailed(result)){await outro("While running the desktop app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("The desktop app was closed",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:false}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==false){a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)})}await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:false}).option("--site",descriptions.site,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});try{await(await actions()).runFrontendDevServer(options)}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).becomeDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options;const startedAt=_startTime;const appUrl=process.env.APP_URL??"stacks.localhost";const nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native";const entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1";const preferredFrontendPort=Number(process.env.PORT)||3000;const preferredApiPort=Number(process.env.PORT_API)||3008;const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1"){await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort])}const claimed=await claimDevPorts([{label:"Frontend",preferred:preferredFrontendPort},{label:"API",preferred:preferredApiPort},{label:"Docs",preferred:preferredDocsPort},{label:"Dashboard",preferred:preferredDashboardPort}],proxyManagedExternally?async()=>true:portIsFree);const portShifts=claimed.shifts;const[frontendPort,apiPort,docsPort,dashboardPort]=claimed.ports;process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1";const domain=resolvePrettyDevDomain(appUrl,nativeMode);const appLooksCustom=domain!==null;const localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1";const prettyUrlsRequested=appLooksCustom&&!localhostOnly;const systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?true:await canStartPrettyDevProxy();const usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized});const prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls;const hasCustomDomain=usePrettyUrls&&!proxyManagedExternally;const displayedDomain=usePrettyUrls?domain:null;const dashboardDomain=displayedDomain?`dashboard.${displayedDomain}`:null;const frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`;const frontendUrl=developmentUrl(frontendBaseUrl,entryPath);const apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`;const docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`;const dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://127.0.0.1:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("⚠")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("⚠")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting…")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,includeDashboard,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=false;let closeNativeApp;const SHUTDOWN_GRACE_MS=1500;const cleanup=(signal)=>{if(isExiting)return;isExiting=true;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,includeDashboard,options.verbose??false)}catch{}})();const teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:true};const a=await actions();const ports=[{name:"API",port:apiPort}];const readinessTimeoutMs=30000;let readyAnnounced=false;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath);const nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve();const waitingOn=new Set(ports);const bootStartedMs=Date.now();let progressLines=0;let nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=true;let proxyReachable=false;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("⚠")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?true:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1"){await printRegisteredRoutes(apiPort).catch(()=>{})}}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{log.error(`Frontend: ${error instanceof Error?error.message:error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return true;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return false}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return false}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input;const verbose=options.verbose??false;const useProxy=hasCustomDomain&&proxyReachable;const feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);const feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`;const apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`;const dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`;const dbUrl=useProxy?dashboardUrl:`http://127.0.0.1:${dashboardPort}`;const blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("➜")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("➜")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("➜")} ${bold("Native")}: ${cyan(`Craft → ${feUrl}`)}`);console.log(` ${green("➜")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("➜")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("➜")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`http://127.0.0.1:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("●")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} → ${domain}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api → localhost:${apiPort}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs → localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`127.0.0.1:${dashboardPort} → ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts");const routesLabel=relative(projectPath(),routesFile);const hasCssEngine=["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config)));if(hasCssEngine)console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile)){try{const source=readFileSync(routesFile,"utf8");const routeCount=(source.match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes → ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest → ${routesLabel}`)}`)}}}async function launchNativeAppWindow(url,options){let createApp;try{const craft=await importCraftSdk();createApp=craft.createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
|
|
1
|
+
import{execSync}from"node:child_process";import{existsSync,readdirSync,readFileSync}from"node:fs";import readline from"node:readline";import process from"node:process";import{bold,cyan,dim,green,intro,log,onUnknownSubcommand,outro,prompts,runCommand,yellow}from"@stacksjs/cli";import{homedir}from"node:os";import{dirname,join,relative}from"node:path";import{fileURLToPath}from"node:url";import{Action}from"@stacksjs/enums";import{inspectDefaultsProvenance,libsPath,projectPath,stxPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{version}from"../../package.json";import{resultFailed}from"../result";const DEV_BOOT_STARTING_LINE_COUNT=3;function eraseDevBootStartingLines(progressLines=0){if(!process.stdout.isTTY)return;for(let i=0;i<DEV_BOOT_STARTING_LINE_COUNT+progressLines;i++){readline.moveCursor(process.stdout,0,-1);readline.clearLine(process.stdout,0)}}export const DEV_BOOT_PROGRESS_EVERY_SECONDS=10;const DEV_BOOT_VERBOSE_HINT_SECONDS=30;export function devBootProgressLine(elapsedSeconds,waitingOn,verbose=false){if(!waitingOn.length||elapsedSeconds<DEV_BOOT_PROGRESS_EVERY_SECONDS)return null;const servers=waitingOn.map((server)=>`the ${server.name} on :${server.port}`).join(", ");const line=`still starting, ${Math.floor(elapsedSeconds)}s so far, waiting for ${servers}`;return!verbose&&elapsedSeconds>=DEV_BOOT_VERBOSE_HINT_SECONDS?`${line} (\`./buddy dev --verbose\` shows its output)`:line}let developmentRpx;function resolveRpxEntryPath(){const candidates=[projectPath("node_modules/@stacksjs/rpx/dist/index.js"),join(homedir(),"Code/Tools/rpx/packages/rpx/dist/index.js"),projectPath("pantry/@stacksjs/rpx/dist/src/index.js")];return candidates.find((entry)=>existsSync(entry))??null}async function importDevelopmentRpx(){if(developmentRpx)return developmentRpx;const entry=resolveRpxEntryPath();developmentRpx=entry?await import(entry):await import("@stacksjs/rpx");return developmentRpx}const activeRpxRegistryIds=[];let _actions;async function actions(){if(!_actions)_actions=await import("@stacksjs/actions");return _actions}async function checkFrameworkDefaults(){let skew;try{skew=inspectDefaultsProvenance(projectPath())}catch{return}if(skew.status==="not-applicable"||skew.status==="current")return;if(skew.status==="stale"){throw new Error(`Framework defaults version mismatch: storage/framework/defaults is from ${skew.vendored}, but @stacksjs/defaults ${skew.installed} is installed. Run \`buddy upgrade\` to synchronize them before starting development servers.`)}try{const{measureDefaultsDrift}=await actions();const drift=measureDefaultsDrift(projectPath(),{shallow:true});if(!drift||drift.length===0)return;log.warn(`storage/framework/defaults does not match the installed @stacksjs/defaults ${skew.installed}.`);log.warn("The app runs the vendored copy. Run `buddy upgrade` to sync it, or `buddy doctor` for the file counts.")}catch{}}export const interactiveDevChoices=[{value:"all",title:"All"},{value:"frontend",title:"Frontend"},{value:"api",title:"Backend"},{value:"dashboard",title:"Dashboard"},{value:"desktop",title:"Desktop"},{value:"native",title:"Native App"},{value:"components",title:"Components"},{value:"docs",title:"Documentation"}];export async function dispatchInteractiveDevSelection(selection,runners){if(!Object.hasOwn(runners,selection))return false;await runners[selection]();return true}export function resolvePrettyDevDomain(appUrl,nativeMode=false){if(!appUrl||nativeMode)return null;try{const url=new URL(/^https?:\/\//i.test(appUrl)?appUrl:`https://${appUrl}`);const hostname=url.hostname.toLowerCase();if(hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1"||hostname==="0.0.0.0")return null;return hostname}catch{return null}}async function developmentDashboardDomain(appDomain){const{resolveDashboardDomain}=await import("@stacksjs/actions/dev/dashboard-proxy");const configured=resolveDashboardDomain(appDomain,false,process.env.DASHBOARD_URL);return configured&&configured!==appDomain?configured:`dashboard.${appDomain}`}export function shouldUsePrettyDevUrls(input){return input.domain!==null&&!input.localhostOnly&&(input.proxyManagedExternally||input.systemAuthorized)}const APPLICATION_VIEW_CANDIDATES=["app/index","app","dashboard/index","dashboard","home/index","home","composer","workspace/index","workspace","feed","portal","admin","account/index","account","profile/index","profile"];const SITE_LAYOUT_NAMES=new Set(["default","guest","marketing","site"]);export function normalizeDevelopmentEntryPath(path){const value=path?.trim();if(!value||value==="/")return"/";try{const parsed=new URL(value,"http://stacks.localhost");return`${parsed.pathname}${parsed.search}${parsed.hash}`}catch{return"/"}}function configuredApplicationPath(root){if(process.env.APP_PATH)return process.env.APP_PATH;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");return source.match(/^[ \t]*appPath\s*:\s*(['"`])([^'"`]+)\1/m)?.[2]}catch{return}}function configuredDevelopmentLaunch(root){const environmentValue=process.env.STACKS_DEV_LAUNCH?.trim().toLowerCase();if(environmentValue==="browser"||environmentValue==="native")return environmentValue;try{const source=readFileSync(join(root,"config/app.ts"),"utf8");const value=source.match(/\bdevLaunch\s*:\s*(['"`])(browser|native)\1/)?.[2];return value==="browser"||value==="native"?value:undefined}catch{return}}export function resolveDevelopmentLaunch(input={}){if(input.browser||input.site)return"browser";if(input.native)return"native";const root=input.root??projectPath();return input.configuredLaunch??configuredDevelopmentLaunch(root)??"browser"}function viewSource(root,route){const base=join(root,"resources/views",route);for(const extension of["stx","vue","html"]){const path=`${base}.${extension}`;if(existsSync(path)){try{return readFileSync(path,"utf8")}catch{return""}}}return}function usesApplicationLayout(source){const layout=source.match(/@extends\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1]??source.match(/@layout\(\s*['"]layouts\/([^'"]+)['"]\s*\)/)?.[1];if(!layout)return false;return!SITE_LAYOUT_NAMES.has(layout.split("/").at(-1)??layout)}export function resolveDevelopmentEntryPath(input={}){if(input.site)return"/";const root=input.root??projectPath();const configuredPath=input.configuredPath??configuredApplicationPath(root);if(configuredPath)return normalizeDevelopmentEntryPath(configuredPath);const loginExists=viewSource(root,"login")!==undefined||viewSource(root,"auth/login")!==undefined;const candidates=APPLICATION_VIEW_CANDIDATES.map((route)=>({route,source:viewSource(root,route)})).filter((candidate)=>candidate.source!==undefined);const appCandidate=candidates.find((candidate)=>usesApplicationLayout(candidate.source))??(loginExists?candidates[0]:undefined);if(appCandidate)return normalizeDevelopmentEntryPath(`/${appCandidate.route.replace(/\/index$/,"")}`);return loginExists?"/login":"/"}export function developmentUrl(baseUrl,entryPath){const normalized=normalizeDevelopmentEntryPath(entryPath);if(normalized==="/")return baseUrl.replace(/\/$/,"");return new URL(normalized,`${baseUrl.replace(/\/$/,"")}/`).toString()}export function developmentBrowserCommand(url,platform=process.platform){if(platform==="darwin")return["open",url];if(platform==="win32")return["cmd","/c","start","",url];return["xdg-open",url]}function openDevelopmentBrowser(url){if(!process.stdout.isTTY||process.env.CI||process.env.STACKS_DEV_NO_OPEN==="1")return;try{const subprocess=Bun.spawn(developmentBrowserCommand(url),{stdin:"ignore",stdout:"ignore",stderr:"ignore"});subprocess.unref()}catch{}}async function canStartPrettyDevProxy(){if(await waitForHttpsProxy(443,150))return true;try{const{authorizeSystemAccess}=await importDevelopmentRpx();return authorizeSystemAccess({interactive:false})}catch{return false}}export async function claimDevPorts(servers,isFree,attempts=20){const preferred=new Set(servers.map((server)=>server.preferred));const taken=new Set;const ports=[];const shifts=[];for(const server of servers){let port=server.preferred;if(taken.has(port)||!await isFree(port)){for(let candidate=server.preferred+1;candidate<server.preferred+attempts;candidate++){if(taken.has(candidate)||preferred.has(candidate)||!await isFree(candidate))continue;port=candidate;break}}if(port!==server.preferred)shifts.push(`${server.label} :${server.preferred} → :${port}`);taken.add(port);ports.push(port)}return{ports,shifts}}export function dev(buddy){const descriptions={dev:"Start development server",frontend:"Start the frontend development server",components:"Start the Components development server",desktop:"Start the Desktop App development server",native:"Start the app in a native Craft window",dashboard:"Start the Dashboard development server",api:"Start the local API development server",docs:"Start the Documentation development server",systemTray:"Start the System Tray development server",interactive:"Get asked which development server to start",select:"Which development server are you trying to start?",withLocalhost:"Include the localhost URL in the output",browser:"Open the application in a browser instead of its configured native window",site:"Open the marketing site instead of the application",project:"Target a specific project",verbose:"Enable verbose output",detach:"Keep the dev servers running after this process or its shell exits (for `nohup ./buddy dev --detach &`)"};buddy.command("dev [server]",descriptions.dev).option("-f, --frontend",descriptions.frontend).option("-a, --api",descriptions.api).option("-c, --components",descriptions.components).option("-d, --dashboard",descriptions.dashboard).option("-k, --desktop",descriptions.desktop).option("-n, --native",descriptions.native).option("-o, --docs",descriptions.docs).option("-s, --system-tray",descriptions.systemTray).option("-i, --interactive",descriptions.interactive,{default:false}).option("-l, --with-localhost",descriptions.withLocalhost,{default:false}).option("--browser",descriptions.browser,{default:false}).option("--site",descriptions.site,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("--detach",descriptions.detach,{default:false}).action(async(server,options)=>{if(options.detach)process.env.STACKS_DEV_DETACH="1";const perf=Bun.nanoseconds();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});await checkFrameworkDefaults();const target=server||(options.frontend?"frontend":undefined)||(options.api?"api":undefined)||(options.components?"components":undefined)||(options.dashboard?"dashboard":undefined)||(options.desktop?"desktop":undefined)||(options.native?"native":undefined)||(options.systemTray||options["system-tray"]?"system-tray":undefined)||(options.docs?"docs":undefined);if(target){const serverOptions={...options};const a=await actions();switch(target){case"native":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"frontend":await a.runFrontendDevServer(serverOptions);break;case"api":await a.runApiDevServer(serverOptions);break;case"components":await a.runComponentsDevServer(serverOptions);break;case"dashboard":await a.runDashboardDevServer(serverOptions);break;case"desktop":await startDevelopmentServer({...serverOptions,native:true},perf);break;case"system-tray":await a.runSystemTrayDevServer(serverOptions);break;case"docs":await a.runDocsDevServer(serverOptions);break;default:await log.error(`Unknown server: ${target}`);process.exit(ExitCode.InvalidArgument)}}else if(wantsInteractive(options)){const selectedValue=await prompts.select({message:descriptions.select,choices:interactiveDevChoices.map((choice)=>({value:choice.value,label:choice.title}))});const a=await actions();const handled=await dispatchInteractiveDevSelection(selectedValue,{all:()=>startDevelopmentServer(options,perf),frontend:()=>a.runFrontendDevServer(options),api:()=>a.runApiDevServer(options),dashboard:()=>a.runDashboardDevServer(options),desktop:()=>startDevelopmentServer({...options,native:true},perf),native:()=>startDevelopmentServer({...options,native:true},perf),components:()=>a.runComponentsDevServer(options),docs:()=>a.runDocsDevServer(options)});if(!handled){await log.error("Invalid option during interactive mode");process.exit(ExitCode.InvalidArgument)}}else{await startDevelopmentServer(options,perf)}outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:components",descriptions.components).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:components");const result=await runCommand("bun run dev",{cwd:libsPath("components/stx")});if(options.verbose)log.info("buddy dev:components result",result);if(resultFailed(result)){await outro("While running the dev:components command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:docs",descriptions.docs).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:docs");const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const{ports:[docsPort=preferredDocsPort],shifts}=process.env.STACKS_PROXY_MANAGED==="1"?{ports:[preferredDocsPort],shifts:[]}:await claimDevPorts([{label:"Docs",preferred:preferredDocsPort}],portIsFree);process.env.PORT_DOCS=String(docsPort);if(shifts.length>0)console.log(` ${yellow("⚠")} ${yellow("Port in use by another process")} ${dim(`- ${shifts.join(", ")}`)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(`http://localhost:${docsPort}`)}
|
|
2
|
+
`);const result=await(await actions()).runAction(Action.DevDocs,options);if(resultFailed(result)){await outro("While running the dev:docs command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}console.log("");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("dev:native",descriptions.native).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:native");await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:desktop",descriptions.desktop).option("--native","Run the AppKit app (`macos`) when the config also declares a web view app",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const perf=await intro("buddy dev:desktop");const{hasMacosDesktop,hasWebviewDesktop}=await import("@stacksjs/desktop-build");if(!options.native&&await hasWebviewDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopWebview,options);if(resultFailed(result)){await outro("While running the desktop app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("The desktop app was closed",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(await hasMacosDesktop(projectPath())){process.env.STACKS_DESKTOP_LAUNCH="1";const{runAction}=await import("@stacksjs/actions");const{Action}=await import("@stacksjs/enums");const result=await runAction(Action.BuildDesktopMacos,options);if(resultFailed(result)){await outro("While building the native macOS app, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Opened the native macOS app",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}await startDevelopmentServer({...options,native:true},perf)});buddy.command("dev:api",descriptions.api).option("-p, --project [project]",descriptions.project,{default:false}).option("--no-watch-types","Skip the model/config type-regeneration watcher").option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();const a=await actions();if(options.watchTypes!==false){a.watchTypes(options).catch((err)=>{log.warn("[dev:api] type watcher exited:",err)})}await a.runApiDevServer(options)});buddy.command("dev:frontend",descriptions.frontend).alias("dev:pages").alias("dev:views").option("-p, --project [project]",descriptions.project,{default:false}).option("--site",descriptions.site,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();process.env.STACKS_DEV_ENTRY_PATH=resolveDevelopmentEntryPath({site:options.site});try{await(await actions()).runFrontendDevServer(options)}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}});buddy.command("dev:dashboard",descriptions.dashboard).alias("dev:admin").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).becomeDashboardDevServer(options)});buddy.command("dev:system-tray",descriptions.systemTray).alias("dev:tray").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{await checkFrameworkDefaults();await(await actions()).runSystemTrayDevServer(options)});onUnknownSubcommand(buddy,"dev")}export async function startDevelopmentServer(_options,_startTime){const options=_options;const startedAt=_startTime;const appUrl=process.env.APP_URL??"stacks.localhost";const nativeMode=resolveDevelopmentLaunch({browser:options.browser,native:options.native,site:options.site})==="native";const entryPath=resolveDevelopmentEntryPath({site:options.site});process.env.STACKS_DEV_ENTRY_PATH=entryPath;const proxyManagedExternally=process.env.STACKS_PROXY_MANAGED==="1";const preferredFrontendPort=Number(process.env.PORT)||3000;const preferredApiPort=Number(process.env.PORT_API)||3008;const preferredDocsPort=Number(process.env.PORT_DOCS)||3006;const preferredDashboardPort=Number(process.env.PORT_ADMIN)||3002;if(process.env.STACKS_DEV_NO_KILL!=="1"){await cleanupStaleDevProcesses([preferredFrontendPort,preferredApiPort,preferredDocsPort,preferredDashboardPort])}const claimed=await claimDevPorts([{label:"Frontend",preferred:preferredFrontendPort},{label:"API",preferred:preferredApiPort},{label:"Docs",preferred:preferredDocsPort},{label:"Dashboard",preferred:preferredDashboardPort}],proxyManagedExternally?async()=>true:portIsFree);const portShifts=claimed.shifts;const[frontendPort,apiPort,docsPort,dashboardPort]=claimed.ports;process.env.PORT=String(frontendPort);process.env.PORT_API=String(apiPort);process.env.PORT_DOCS=String(docsPort);process.env.PORT_ADMIN=String(dashboardPort);const includeDashboard=process.env.STACKS_DEV_DASHBOARD==="1";const domain=resolvePrettyDevDomain(appUrl,nativeMode);const appLooksCustom=domain!==null;const localhostOnly=process.env.STACKS_DEV_LOCALHOST==="1";const prettyUrlsRequested=appLooksCustom&&!localhostOnly;const systemAuthorized=!prettyUrlsRequested||proxyManagedExternally?true:await canStartPrettyDevProxy();const usePrettyUrls=shouldUsePrettyDevUrls({domain,localhostOnly,proxyManagedExternally,systemAuthorized});const prettySetupRequired=prettyUrlsRequested&&!usePrettyUrls;const hasCustomDomain=usePrettyUrls&&!proxyManagedExternally;const displayedDomain=usePrettyUrls?domain:null;const configuredDashboardDomain=includeDashboard&&domain?await developmentDashboardDomain(domain):null;const dashboardDomain=displayedDomain?configuredDashboardDomain:null;const frontendBaseUrl=displayedDomain?`https://${displayedDomain}`:`http://localhost:${frontendPort}`;const frontendUrl=developmentUrl(frontendBaseUrl,entryPath);const apiUrl=displayedDomain?`https://${displayedDomain}/api`:`http://localhost:${apiPort}`;const docsUrl=displayedDomain?`https://${displayedDomain}/docs`:`http://localhost:${docsPort}`;const dashboardUrl=dashboardDomain?`https://${dashboardDomain}`:`http://127.0.0.1:${dashboardPort}`;process.env.STACKS_PROXY_MANAGED="1";process.env.STACKS_MANAGED_DASHBOARD_DOMAIN=dashboardDomain??"";process.env.STACKS_DEV_QUIET="1";console.log();if(prettySetupRequired){console.log(` ${yellow("⚠")} ${yellow("Pretty URL setup required")} ${dim("- using localhost for this session")}`);console.log(` ${dim(" ")}${dim("Run `./buddy setup:ssl` once, then restart `./buddy dev`.")}`);console.log()}if(portShifts.length>0){console.log(` ${yellow("⚠")} ${yellow("Ports in use by another process")} ${dim(`- ${portShifts.join(", ")}`)}`);console.log()}console.log(` ${bold(cyan("stacks"))} ${dim(`v${version}`)} ${dim("starting…")}`);console.log();const rpxTlsPreflight=hasCustomDomain&&domain?prepareRpxTlsForDev({domain,dashboardDomain,options}):Promise.resolve();if(localhostOnly&&domain&&!proxyManagedExternally)removeStalePublicDomainOverrides(domain,configuredDashboardDomain,options.verbose??false).catch(()=>{});rpxTlsPreflight.catch(()=>{});let isExiting=false;let closeNativeApp;const SHUTDOWN_GRACE_MS=1500;const cleanup=(signal)=>{if(isExiting)return;isExiting=true;console.log();console.log(` ${bold(cyan("stacks"))} ${dim(`received ${signal} - shutting down the dev server`)}`);if(signal==="SIGHUP")console.log(` ${dim(" ")}${dim("The launching shell went away (a closed terminal, or a CI step that ended). nohup does not prevent this.")}`);closeNativeApp?.();const rpxTeardown=(async()=>{try{await unregisterRpxProxies(activeRpxRegistryIds);activeRpxRegistryIds.length=0;if(hasCustomDomain&&domain)await removeStalePublicDomainOverrides(domain,configuredDashboardDomain,options.verbose??false)}catch{}})();const teardownDeadline=new Promise((resolve)=>setTimeout(resolve,SHUTDOWN_GRACE_MS));Promise.race([rpxTeardown,teardownDeadline]).finally(()=>{try{process.kill(-process.pid,"SIGTERM")}catch{try{process.kill(0,"SIGTERM")}catch{}}setTimeout(()=>{try{process.kill(0,"SIGKILL")}catch{process.exit(1)}},SHUTDOWN_GRACE_MS).unref()})};process.on("SIGINT",cleanup);process.on("SIGTERM",cleanup);process.on("SIGHUP",cleanup);const quietOpts={...options,quiet:true};const a=await actions();const ports=[{name:"API",port:apiPort}];const readinessTimeoutMs=30000;let readyAnnounced=false;const nativeUrl=developmentUrl(`http://localhost:${frontendPort}`,entryPath);const nativeWindowReady=nativeMode?waitForPort(frontendPort,readinessTimeoutMs).then(async(ready)=>{if(!ready){log.warn(`Native window skipped because the frontend did not answer within ${readinessTimeoutMs/1000}s`);return}closeNativeApp=await launchNativeAppWindow(nativeUrl,options)}):Promise.resolve();const waitingOn=new Set(ports);const bootStartedMs=Date.now();let progressLines=0;let nextProgressAt=DEV_BOOT_PROGRESS_EVERY_SECONDS;const progress=setInterval(()=>{const elapsed=(Date.now()-bootStartedMs)/1000;if(elapsed<nextProgressAt)return;nextProgressAt+=DEV_BOOT_PROGRESS_EVERY_SECONDS;const line=devBootProgressLine(elapsed,[...waitingOn],options.verbose);if(!line)return;console.log(` ${dim(line)}`);progressLines++},1000);progress.unref?.();Promise.all(ports.map((p)=>waitForPort(p.port,Number.POSITIVE_INFINITY).then(()=>waitingOn.delete(p)))).then(async()=>{clearInterval(progress);if(readyAnnounced)return;readyAnnounced=true;let proxyReachable=false;if(hasCustomDomain&&domain){(async()=>{try{await rpxTlsPreflight;await registerRpxProxiesForDomain({domain,frontendPort,apiPort,docsPort,dashboardPort,dashboardDomain,options})}catch{}})();proxyReachable=await waitForHttpsProxy(443,16000);if(!proxyReachable){console.log(` ${yellow("⚠")} ${yellow("HTTPS proxy not reachable on :443")} - serving ${cyan(`http://localhost:${frontendPort}`)} instead`);console.log(` ${dim(" ")}${dim("rpx needs a valid SUDO_PASSWORD in .env to bind :443; trust the local CA, then restart `./buddy dev`.")}`);if(options.verbose)console.log(` ${dim(" ")}${dim(`Trust CA: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}}eraseDevBootStartingLines(progressLines);printDevReadyBanner({options,nativeMode,hasCustomDomain:!!appLooksCustom&&!localhostOnly,proxyReachable:proxyManagedExternally?true:proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain});if(!nativeMode){const browserUrl=hasCustomDomain&&(proxyManagedExternally||proxyReachable)?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);openDevelopmentBrowser(browserUrl)}if(startedAt){const elapsedMs=(Bun.nanoseconds()-startedAt)/1e6;console.log(` ${dim(`ready in ${(elapsedMs/1000).toFixed(1)}s`)}`);console.log();printDevEngineNotes();console.log()}if(process.env.STACKS_PRINT_ROUTES==="1"){await printRegisteredRoutes(apiPort).catch(()=>{})}}).catch(()=>{});await Promise.all([a.runFrontendDevServer(quietOpts).catch((error)=>{log.error(`Frontend: ${error instanceof Error?error.message:error}`)}),a.runApiDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`API: ${error}`)}),a.runDocsDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Docs: ${error}`)}),includeDashboard?a.runDashboardDevServer(quietOpts).catch((error)=>{if(options.verbose)log.error(`Dashboard: ${error}`)}):Promise.resolve(),nativeWindowReady.catch((error)=>{if(options.verbose)log.warn(`Native window: ${error}`)})])}function isComingSoonMode(){if(existsSync(projectPath("storage/framework/coming-soon")))return true;try{const idx=projectPath("resources/views/index.stx");return existsSync(idx)&&/siteMode\s*=\s*['"]coming-soon['"]/.test(readFileSync(idx,"utf8"))}catch{return false}}function blogIsConfigured(){try{const dir=projectPath("content/blog");return existsSync(dir)&&readdirSync(dir).some((f)=>f.endsWith(".md"))}catch{return false}}function printDevReadyBanner(input){const{options,nativeMode,hasCustomDomain,proxyReachable,frontendUrl,frontendBaseUrl,entryPath,apiUrl,docsUrl,dashboardUrl,frontendPort,apiPort,docsPort,includeDashboard,domain,dashboardPort,dashboardDomain}=input;const verbose=options.verbose??false;const useProxy=hasCustomDomain&&proxyReachable;const feUrl=useProxy?frontendUrl:developmentUrl(`http://localhost:${frontendPort}`,entryPath);const feBaseUrl=useProxy?frontendBaseUrl:`http://localhost:${frontendPort}`;const apUrl=useProxy?apiUrl:`http://localhost:${apiPort}`;const dcUrl=useProxy?docsUrl:`http://localhost:${docsPort}`;const dbUrl=useProxy?dashboardUrl:`http://127.0.0.1:${dashboardPort}`;const blogUrl=`${feBaseUrl}/blog`;console.log();const frontendLabel=entryPath==="/"?"Site":"App";console.log(` ${green("➜")} ${bold(frontendLabel.padEnd(8))}: ${cyan(feUrl)}`);if(entryPath!=="/")console.log(` ${dim("➜")} ${dim("Site")}: ${dim(feBaseUrl)}`);if(nativeMode)console.log(` ${green("➜")} ${bold("Native")}: ${cyan(`Craft → ${feUrl}`)}`);console.log(` ${green("➜")} ${bold("API")}: ${cyan(apUrl)}`);console.log(` ${green("➜")} ${bold("Docs")}: ${cyan(dcUrl)}`);if(blogIsConfigured())console.log(` ${green("➜")} ${bold("Blog")}: ${cyan(blogUrl)}`);if(includeDashboard)console.log(` ${green("➜")} ${bold("Dashboard")}: ${cyan(dbUrl)}`);if(useProxy){console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`${developmentUrl(`http://localhost:${frontendPort}`,entryPath)} (bypasses the proxy)`)}`);if(includeDashboard&&dashboardDomain)console.log(` ${dim("➜")} ${dim("Direct")}: ${dim(`http://127.0.0.1:${dashboardPort} (dashboard, bypasses the proxy)`)}`)}if(isComingSoonMode()){console.log();console.log(` ${yellow("●")} ${bold(yellow("Coming soon mode"))} ${dim("- visitors see the holding page; bypass with the coming-soon secret.")}`)}if(verbose&&domain){console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`localhost:${frontendPort} → ${domain}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/api → localhost:${apiPort}`)}`);console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`${frontendBaseUrl}/docs → localhost:${docsPort}`)}`);if(includeDashboard)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`127.0.0.1:${dashboardPort} → ${dashboardDomain}`)}`)}console.log()}function printDevEngineNotes(){const routesFile=stxPath("routes.ts");const routesLabel=relative(projectPath(),routesFile);const hasCssEngine=["config/css.ts","css.config.ts","config/crosswind.ts","crosswind.config.ts"].some((config)=>existsSync(join(projectPath(),config)));if(hasCssEngine)console.log(` ${green("[ts-css]")} ${dim("CSS engine loaded")}`);if(existsSync(routesFile)){try{const source=readFileSync(routesFile,"utf8");const routeCount=(source.match(/pattern:/g)??[]).length;if(routeCount>0)console.log(` ${green("[stx]")} ${dim(`Generated ${routeCount} routes → ${routesLabel}`)}`)}catch{console.log(` ${green("[stx]")} ${dim(`Routes manifest → ${routesLabel}`)}`)}}}async function launchNativeAppWindow(url,options){let createApp;try{const craft=await importCraftSdk();createApp=craft.createApp}catch(error){if(options.verbose)log.warn(`Native window unavailable: ${error}`);console.log(` ${dim("Native window unavailable. Install craft-native or set CRAFT_BIN to a Craft binary.")}
|
|
3
3
|
`);return}if(!createApp){console.log(` ${dim("Native window unavailable. The Craft SDK did not export createApp.")}
|
|
4
4
|
`);return}const craftBinaryPath=resolveCraftBinaryPath();if(!craftBinaryPath){console.log(` ${dim("Native window unavailable. Set CRAFT_BIN to a Craft binary, or install Craft in ~/Code/Tools/craft.")}
|
|
5
5
|
`);return}const appIconPath=resolveNativeAppIconPath();const app=createApp({url,quiet:!options.verbose,craftPath:craftBinaryPath,window:{title:await resolveNativeAppTitle(),width:1280,height:860,titlebarHidden:true,webSidebarMaterial:true,webSidebarWidth:286,webSidebarMaterialOpacity:0.78,...appIconPath&&{icon:appIconPath}}});app.show().catch((error)=>{if(options.verbose)log.warn(`Native window exited: ${error}`)});return()=>app.close()}async function importCraftSdk(){const localCraftSdk=process.env.HOME?`${process.env.HOME}/Code/Tools/craft/packages/typescript/src/index.ts`:undefined;if(localCraftSdk&&existsSync(localCraftSdk))return await import(localCraftSdk);const packageNames=["craft-native","@craft-native/craft","@stacksjs/ts-craft"];let primaryError;for(const packageName of packageNames){try{return await import(packageName)}catch(error){primaryError??=error}}throw primaryError}async function cleanupStaleDevProcesses(ports){const projectRoot=projectPath();const actionDevPath=projectPath("storage/framework/core/actions/src/dev/");const pids=new Set;for(const port of ports){for(const pid of await listenerPids(port)){if(pid===process.pid)continue;const command=await commandForPid(pid);if(!command.includes(projectRoot))continue;const isStacksDevProcess=command.includes("storage/framework/core/buddy/src/cli.ts dev")||command.includes("storage/framework/core/actions/src/dev/")||command.includes(actionDevPath);if(isStacksDevProcess)pids.add(pid)}}if(pids.size===0)return;for(const pid of pids){try{process.kill(pid,"SIGTERM")}catch{}}await new Promise((r)=>setTimeout(r,250));for(const pid of pids){try{process.kill(pid,"SIGKILL")}catch{}}await new Promise((r)=>setTimeout(r,150))}async function listenerPids(port){try{const proc=Bun.spawn(["lsof","-nP",`-iTCP:${port}`,"-sTCP:LISTEN","-t"],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.split(/\s+/).map((value)=>Number(value)).filter((pid)=>Number.isInteger(pid)&&pid>0)}catch{return[]}}async function commandForPid(pid){try{const proc=Bun.spawn(["ps","-p",String(pid),"-o","command="],{stdout:"pipe",stderr:"ignore"});const output=await new Response(proc.stdout).text();await proc.exited;return output.trim()}catch{return""}}function resolveCraftBinaryPath(){const home=process.env.HOME;const candidates=[process.env.CRAFT_BIN,home?`${home}/Code/Tools/craft/craft`:undefined,home?`${home}/Code/Tools/craft/bin/craft`:undefined,home?`${home}/Code/Tools/craft/packages/zig/zig-out/bin/craft`:undefined,home?`${home}/Documents/Projects/craft/packages/zig/zig-out/bin/craft`:undefined].filter((candidate)=>Boolean(candidate));return candidates.find((candidate)=>existsSync(candidate))}function resolveNativeAppIconPath(){const candidates=[projectPath("resources/assets/images/app-icon.png"),projectPath("resources/assets/images/icon.png"),projectPath("public/icon.png")];return candidates.find((candidate)=>existsSync(candidate))}async function resolveNativeAppTitle(){try{const pkg=await Bun.file(projectPath("package.json")).json();const name=typeof pkg.productName==="string"?pkg.productName:pkg.name;if(typeof name==="string"&&name.length>0){return name.split(/[-_\s]+/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join(" ")}}catch{}return"Stacks App"}const METHOD_COLORS={GET:cyan,POST:green,PUT:cyan,PATCH:cyan,DELETE:cyan,OPTIONS:dim};async function printRegisteredRoutes(apiPort){try{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),1500);const res=await fetch(`http://127.0.0.1:${apiPort}/__routes`,{signal:ac.signal}).catch(()=>null);clearTimeout(t);if(!res||!res.ok)return;const routes=await res.json();if(!Array.isArray(routes)||routes.length===0)return;const sorted=[...routes].sort((a,b)=>a.path.localeCompare(b.path)||a.method.localeCompare(b.method));const longestPath=Math.max(...sorted.map((r)=>r.path.length));console.log(` ${dim("Registered routes")}
|
|
6
|
-
`);for(const r of sorted){const color=METHOD_COLORS[r.method.toUpperCase()]??dim;const method=color(r.method.toUpperCase().padEnd(6));const path=r.path.padEnd(longestPath);const named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"]){const ok=await new Promise((resolve)=>{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(true)}).catch(()=>{clearTimeout(t);resolve(false)})});if(ok)return true}return false}async function portIsFree(port){for(const host of["127.0.0.1","::1"]){if(await someoneIsListening(port,host))return false}let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:false,fetch:()=>new Response})}catch{return false}server.stop(true);return true}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host});const finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(false));socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return true;await new Promise((r)=>setTimeout(r,50))}return false}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net");const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const ok=await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"});const finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));setTimeout(()=>finish(false),800).unref?.()});if(ok)return true;await new Promise((r)=>setTimeout(r,200))}return false}const RPX_SSL_DIR=join(homedir(),".stacks","ssl");const RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt");const RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,
|
|
7
|
-
' "$SUDO_PASSWORD" | sudo -S rm -f ${quotedPath}`:`sudo -n rm -f ${quotedPath}`;try{execSync(rm,{stdio:["pipe","ignore","ignore"]});log.info(`Removed stale rpx DNS resolver ${resolverPath} (left by a previous dev session)`);execSync("sudo -n dscacheutil -flushcache; sudo -n killall -HUP mDNSResponder; true",{stdio:["pipe","ignore","ignore"]})}catch{log.warn(`A stale rpx DNS resolver still hijacks ${domain}. Remove it with: sudo rm ${resolverPath}`)}}async function prepareRpxTlsForDev(input){const{domain,
|
|
6
|
+
`);for(const r of sorted){const color=METHOD_COLORS[r.method.toUpperCase()]??dim;const method=color(r.method.toUpperCase().padEnd(6));const path=r.path.padEnd(longestPath);const named=r.name?` ${dim(`(${r.name})`)}`:"";console.log(` ${method} ${path}${named}`)}console.log()}catch{}}async function probeDevServerHttp(port){for(const path of["/__health","/"]){const ok=await new Promise((resolve)=>{const ac=new AbortController;const t=setTimeout(()=>ac.abort(),path==="/"?8000:800);fetch(`http://127.0.0.1:${port}${path}`,{signal:ac.signal,redirect:"manual"}).then(()=>{clearTimeout(t);resolve(true)}).catch(()=>{clearTimeout(t);resolve(false)})});if(ok)return true}return false}async function portIsFree(port){for(const host of["127.0.0.1","::1"]){if(await someoneIsListening(port,host))return false}let server;try{server=Bun.serve({port,hostname:"0.0.0.0",reusePort:false,fetch:()=>new Response})}catch{return false}server.stop(true);return true}async function someoneIsListening(port,host){const{connect}=await import("node:net");return new Promise((resolve)=>{const socket=connect({port,host});const finish=(listening)=>{socket.destroy();resolve(listening)};socket.setTimeout(300,()=>finish(false));socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false))})}async function waitForPort(port,timeoutMs){const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){if(await probeDevServerHttp(port))return true;await new Promise((r)=>setTimeout(r,50))}return false}async function waitForHttpsProxy(port,timeoutMs){const{connect}=await import("node:net");const deadline=Date.now()+timeoutMs;while(Date.now()<deadline){const ok=await new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"});const finish=(v)=>{try{socket.destroy()}catch{}resolve(v)};socket.once("connect",()=>finish(true));socket.once("error",()=>finish(false));setTimeout(()=>finish(false),800).unref?.()});if(ok)return true;await new Promise((r)=>setTimeout(r,200))}return false}const RPX_SSL_DIR=join(homedir(),".stacks","ssl");const RPX_ROOT_CA_PATH=join(RPX_SSL_DIR,"rpx-root-ca.crt");const RPX_HOST_CERT_PATH=join(RPX_SSL_DIR,"rpx.localhost.crt");function buildDevelopmentTlsHostnames(domain,dashboardDomain){return[domain,...dashboardDomain?[dashboardDomain]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,dashboardDomain,trustCertificate=true){const verbose=options.verbose??false;const{buildRegistryTlsProxyOptions,certIncludesSanHostnames,checkExistingCertificates,clearSslConfigCache,forceTrustCertificate,generateCertificate,getRegistryDir,isDaemonRunning,isRootCaTrustedForSsl,readAll,readCertCommonName,stopDaemon,trustRootCaForBrowsers,verifyHttpsChain}=await importDevelopmentRpx();const hostnames=buildDevelopmentTlsHostnames(domain,dashboardDomain);const entries=await readAll(getRegistryDir(),false).catch(()=>[]);for(const entry of entries){const host=entry.to?.trim();if(host&&!hostnames.includes(host))hostnames.push(host)}const tlsOptions=buildRegistryTlsProxyOptions(hostnames,domain,verbose);const hostnameInCert=certIncludesSanHostnames(RPX_HOST_CERT_PATH,hostnames);const cnMatchesApp=readCertCommonName(RPX_HOST_CERT_PATH)===domain;let certRegenerated=false;const existing=await checkExistingCertificates(tlsOptions);if(!existing||!hostnameInCert||!cnMatchesApp){clearSslConfigCache();await generateCertificate({...tlsOptions,forceRegenerate:true});certRegenerated=true}let trusted=isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(!trusted&&trustCertificate){trusted=trustRootCaForBrowsers(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||await forceTrustCertificate(RPX_ROOT_CA_PATH,{serverName:domain,verbose})||isRootCaTrustedForSsl(RPX_ROOT_CA_PATH,domain,{verbose});if(trusted)console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local CA trusted - reload the browser if you still see a warning")}`);else console.log(` ${yellow("⚠")} ${yellow("HTTPS")}: ${yellow(`Local CA not trusted — run: sh ${join(RPX_SSL_DIR,"trust-rpx-cert.sh")}`)}`)}else if(verbose){console.log(` ${green("✓")} ${dim("HTTPS")}: ${dim("Local certificate trusted for SSL")}`)}const chainOk=existsSync(RPX_ROOT_CA_PATH)?await verifyHttpsChain(domain,RPX_ROOT_CA_PATH):false;if((certRegenerated||!hostnameInCert||!cnMatchesApp)&&await isDaemonRunning()){await stopDaemon({timeoutMs:8000}).catch(()=>{});if(verbose)log.info("Restarting rpx daemon to load TLS certificates for this app")}else if(!chainOk&&verbose){console.log(` ${dim(" ")}${dim("HTTPS chain not yet valid on :443 - daemon will (re)start after backends are ready")}`)}}function resolveRpxDaemonSpawnCwd(){const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return dirname(fromEnv);const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return dirname(bootstrap);return homedir()}async function resolveRpxDaemonSpawnCommand(){const bootstrap=join(dirname(fileURLToPath(import.meta.url)),"../../scripts/rpx-daemon-bootstrap.js");if(existsSync(bootstrap))return[process.execPath,bootstrap];const fromEnv=process.env.RPX_BIN||process.env.STACKS_RPX_BIN;if(fromEnv&&existsSync(fromEnv))return[fromEnv,"daemon:start"];const pkgUrl=import.meta.resolve("@stacksjs/rpx/package.json");const cli=join(dirname(fileURLToPath(pkgUrl)),"dist/bin/cli.js");return[process.execPath,cli,"daemon:start"]}function buildRpxProxySpecs(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,dashboardDomain}=input;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...dashboardDomain?[{id:`${domain}-dashboard`,from:`127.0.0.1:${dashboardPort}`,to:dashboardDomain}]:[]]}async function unregisterRpxProxies(ids){if(ids.length===0)return;try{const{removeEntry}=await importDevelopmentRpx();for(const id of ids)await removeEntry(id).catch(()=>{})}catch{}}async function removeStalePublicDomainOverrides(domain,dashboardDomain,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx();const hosts=[domain,...dashboardDomain?[dashboardDomain]:[]];const present=await checkHosts(hosts,verbose).catch(()=>hosts.map(()=>false));const staleHosts=hosts.filter((_,i)=>present[i]===true);if(staleHosts.length>0){await removeHosts(staleHosts,verbose).catch(()=>{});const remaining=await checkHosts(staleHosts,verbose).catch(()=>staleHosts.map(()=>true));if(remaining.some(Boolean))log.warn(`Stale /etc/hosts entries still point ${staleHosts.join(", ")} at loopback. Remove them with: sudo nano /etc/hosts`);else log.info(`Removed stale /etc/hosts entries for ${staleHosts.join(", ")} (left by a previous dev session)`)}if(process.platform!=="darwin")return;const resolverDomains=new Set(hosts.map((host)=>host.split(".").slice(-2).join(".")));for(const resolverDomain of resolverDomains)removeStaleRpxResolver(resolverFilePath(resolverDomain),resolverDomain,contentLooksLikeRpxResolver)}function removeStaleRpxResolver(resolverPath,domain,contentLooksLikeRpxResolver){let isRpxManaged=false;try{isRpxManaged=contentLooksLikeRpxResolver(readFileSync(resolverPath,"utf8"))}catch{}if(!isRpxManaged)return;const quotedPath=`'${resolverPath.replace(/'/g,`'\\''`)}'`;const rm=process.env.SUDO_PASSWORD?`printf '%s
|
|
7
|
+
' "$SUDO_PASSWORD" | sudo -S rm -f ${quotedPath}`:`sudo -n rm -f ${quotedPath}`;try{execSync(rm,{stdio:["pipe","ignore","ignore"]});log.info(`Removed stale rpx DNS resolver ${resolverPath} (left by a previous dev session)`);execSync("sudo -n dscacheutil -flushcache; sudo -n killall -HUP mDNSResponder; true",{stdio:["pipe","ignore","ignore"]})}catch{log.warn(`A stale rpx DNS resolver still hijacks ${domain}. Remove it with: sudo rm ${resolverPath}`)}}async function prepareRpxTlsForDev(input){const{domain,dashboardDomain,options,skipHosts=false,trustCertificate=true}=input;const verbose=options.verbose??false;const hosts=[domain,...dashboardDomain?[dashboardDomain]:[]];const hostsNeedingFile=hosts.filter((host)=>{const h=host.trim().toLowerCase();return h!=="localhost"&&!h.endsWith(".localhost")&&!h.endsWith(".localhost.")});const{addHosts,setupDevelopmentDns}=await importDevelopmentRpx();const dnsDomains=!skipHosts&&hostsNeedingFile.length>0?hosts:[];if(dnsDomains.length>0){const dnsReady=await setupDevelopmentDns({domains:dnsDomains,verbose}).catch(()=>false);if(!dnsReady&&verbose)log.warn(`Dev DNS not configured for ${dnsDomains.join(", ")} - falling back to /etc/hosts`)}if(!skipHosts&&hostsNeedingFile.length>0){await addHosts(hostsNeedingFile,verbose).catch((err)=>{log.warn(`Could not update /etc/hosts for ${hostsNeedingFile.join(", ")}: ${err.message}`);log.warn("Add 127.0.0.1 entries manually or set SUDO_PASSWORD in .env")})}await ensureRpxDevelopmentHttps(domain,options,dashboardDomain,trustCertificate)}export async function setupPrettyDevEnvironment(input){const domain=resolvePrettyDevDomain(input.domain??process.env.APP_URL??"stacks.localhost");if(!domain){log.info("APP_URL already uses localhost; no pretty URL setup is needed");return true}const rpx=await importDevelopmentRpx();if(!rpx.authorizeSystemAccess({interactive:process.stdin.isTTY===true&&process.stdout.isTTY===true})){log.error("Pretty URL setup needs administrator authorization to bind ports 80 and 443 and trust the local CA");return false}await prepareRpxTlsForDev({domain,dashboardDomain:await developmentDashboardDomain(domain),options:{verbose:input.verbose},skipHosts:input.skipHosts,trustCertificate:!input.skipTrust});const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(input.verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;await startRpxDaemonIfNeeded({spawnCommand:await resolveRpxDaemonSpawnCommand(),spawnEnv,verbose:input.verbose??false,stopRpx:rpx.stopDaemon});const ready=await waitForHttpsProxy(443,5000);if(ready)log.success(`Pretty URLs are ready at https://${domain}`);else log.error("rpx did not become reachable on port 443");return ready}async function startRpxDaemonIfNeeded(input){const{ensureDaemonRunning,isDaemonRunning:isRpxUp}=await importDevelopmentRpx();if(await isRpxUp()){if(await waitForHttpsProxy(443,1500))return;await input.stopRpx({timeoutMs:5000}).catch(()=>{})}const spawnOpts={spawnCommand:input.spawnCommand,spawnCwd:resolveRpxDaemonSpawnCwd(),startupTimeoutMs:45000,spawnEnv:input.spawnEnv,verbose:input.verbose};try{await ensureDaemonRunning(spawnOpts)}catch(firstError){await input.stopRpx({timeoutMs:5000}).catch(()=>{});await ensureDaemonRunning(spawnOpts).catch(()=>{throw firstError})}}async function registerRpxProxiesForDomain(input){const{domain,frontendPort,apiPort,docsPort,dashboardPort,dashboardDomain,options}=input;const verbose=options.verbose??false;const proxies=buildRpxProxySpecs({domain,frontendPort,apiPort,docsPort,dashboardPort,dashboardDomain});await unregisterRpxProxies([`${domain}-api`,`${domain}-docs`]);const{getRegistryDir,readAll,stopDaemon:stopRpx,syncDevelopmentDnsFromRegistry,writeEntry}=await importDevelopmentRpx();const spawnCommand=await resolveRpxDaemonSpawnCommand();const spawnEnv={};if(process.env.SUDO_PASSWORD)spawnEnv.SUDO_PASSWORD=process.env.SUDO_PASSWORD;if(verbose)spawnEnv.RPX_VERBOSE="1";const rpxEntry=resolveRpxEntryPath();if(rpxEntry)spawnEnv.RPX_MODULE=rpxEntry;try{await startRpxDaemonIfNeeded({spawnCommand,spawnEnv,verbose,stopRpx})}catch(error){const{isDaemonRunning}=await importDevelopmentRpx();if(!await isDaemonRunning())throw error;if(verbose){const message=error instanceof Error?error.message:String(error);console.log(` ${dim(" ")}${dim(`rpx daemon spawn skipped (${message}); reusing existing daemon`)}`)}}const createdAt=new Date().toISOString();for(const proxy of proxies){await writeEntry({id:proxy.id,from:proxy.from,to:proxy.to,cwd:process.cwd(),createdAt,pid:process.pid,pathRewrites:proxy.pathRewrites},undefined,verbose);if(!activeRpxRegistryIds.includes(proxy.id))activeRpxRegistryIds.push(proxy.id);if(verbose)console.log(` ${dim("➜")} ${dim("Proxy")}: ${dim(`https://${proxy.to} → ${proxy.from}`)}`)}const registryDir=getRegistryDir();const entries=await readAll(registryDir,verbose).catch(()=>[]);await syncDevelopmentDnsFromRegistry(entries,{verbose,ownerPid:process.pid}).catch((err)=>{if(verbose){const message=err instanceof Error?err.message:String(err);console.log(` ${dim(" ")}${dim(`Dev DNS sync: ${message}`)}`)}})}function wantsInteractive(options){return options.interactive}
|
package/dist/commands/docs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{run as runAgentCounts}from"./docs/agent-counts";import{run as runArtifacts}from"./docs/generated-artifacts";import{run as runBuddyDocs}from"./docs/buddy-commands";import{run as runCapabilities}from"./docs/capabilities";import{run as runSnippets}from"./docs/snippets";import{run as runDesktopMatrix}from"./docs/desktop-matrix";import{run as runLinks}from"./docs/links";import{run as runNativeSkills}from"./docs/native-skills";import{runTool}from"./run-tool";export function docs(buddy){buddy.command("docs:stories","Record browser and native user stories with video, scene screenshots and docs").option("--config <path>","Story configuration path",{default:"config/stories.ts"}).option("--out <directory>","Generated documentation and media directory").option("--only <ids>","Comma-separated story ids").option("--list","Validate and list stories without starting drivers",{default:false}).option("--check","Verify complete recordings, configuration and artifact hashes",{default:false}).option("--json","Print the story report as JSON",{default:false}).example("buddy docs:stories").example("buddy docs:stories --only checkout-ios,checkout-android").example("buddy docs:stories --check").action(async(options)=>{const{recordStories}=await import("@stacksjs/docs/stories");const report=await recordStories({config:options.config,outDir:options.out,only:options.only?.split(",").map((value)=>value.trim()).filter(Boolean),list:options.list,check:options.check,onProgress:(result)=>{if(!options.json)console.log(`${result.status} ${result.id} (${result.platform})`)}});if(options.json)console.log(JSON.stringify(report,null,2));else if(options.list)for(const story of report.inventory)console.log(`${story.id} (${story.platform}): ${story.scenes.map((scene)=>scene.id).join(", ")}`);else console.log(`Story documentation: ${report.outDir}/index.md`);if(!options.list&&report.results.some((result)=>result.status!=="passed"))process.exitCode=1});buddy.command("docs:screenshots","Capture and verify an explicit UI inventory with Bun WebView").option("--config <path>","Screenshot configuration path",{default:"config/screenshots.ts"}).option("--out <directory>","Override the output directory").option("--only <ids>","Comma-separated screen ids to capture").option("--viewport <names>","Comma-separated configured viewport names").option("--list","Validate screen coverage without opening a browser",{default:false}).option("--check","Verify the complete saved inventory and image hashes",{default:false}).option("--json","Print the inventory, model plan and capture report as JSON",{default:false}).example("buddy docs:screenshots --list").example("buddy docs:screenshots --only welcome,calendar --viewport mobile").action(async(options)=>{const{captureScreenshots}=await import("@stacksjs/docs/screenshots");const report=await captureScreenshots({config:options.config,outDir:options.out,only:options.only?.split(",").map((value)=>value.trim()).filter(Boolean),viewports:options.viewport?.split(",").map((value)=>value.trim()).filter(Boolean),list:options.list,check:options.check,onProgress:(result)=>{if(!options.json)console.log(`${result.status} ${result.id}/${result.profile}/${result.viewport.name}`)}});if(options.json){console.log(JSON.stringify(report,null,2));if(report.results.some((result)=>result.status==="failed"))process.exitCode=1;return}if(options.list)for(const screen of report.inventory)console.log(`${screen.id} ${screen.path}${screen.skip?` [excluded: ${screen.skip}]`:""}`);if(options.list)for(const model of report.models.models)console.log(`${model.name} (${model.table||"table inferred"}, key ${model.primaryKey}): ${model.factoryFields.length} factories, seeder count ${model.seederCount??"not declared"}, parents ${model.parents.join(", ")||"none"}, required overrides ${model.requiredWithoutFactory.join(", ")||"none"}, sensitive fields ${model.sensitiveFields.join(", ")||"none"}, states ${model.suggestedStates.join(", ")}`);if(options.list&&report.models.cycles.length)console.log(`Cyclic model dependencies: ${report.models.cycles.join(", ")}`);if(options.list&&report.models.externalParents.length)console.log(`Parent fixtures outside this model set: ${report.models.externalParents.join(", ")}`);const failed=report.results.filter((result)=>result.status==="failed");for(const result of failed)console.error(`${result.id}/${result.profile}/${result.viewport.name}: ${result.error}`);console.log(options.list?"Screenshot configuration and template coverage verified.":`${report.results.filter((result)=>result.status==="captured").length} captures, ${failed.length} failed, ${report.results.filter((result)=>result.status==="skipped").length} explained exclusions.`);if(failed.length)process.exitCode=1});for(const check of[false,true]){buddy.command(check?"docs:style-guide:check":"docs:style-guide",check?"Verify generated application style guide freshness":"Generate a branded application component style guide").option("--config <path>","Style guide configuration path",{default:"config/style-guide.ts"}).action(async(options)=>{const{runStyleGuide}=await import("@stacksjs/docs/style-guide");const result=await runStyleGuide({config:options.config,check});console.log(`${check?"Verified":"Generated"} style guide: ${result.components} components, ${result.stories} stories, ${result.variants} variants.`)})}buddy.command("docs:native-skills","Regenerate native skill package coverage and driver evidence").action(async()=>{await runTool(runNativeSkills,"--write")});buddy.command("docs:native-skills:check","Verify native skills cover current packages and driver capabilities").action(async()=>{await runTool(runNativeSkills,"--check")});buddy.command("docs:buddy","Regenerate the buddy command reference doc").action(async()=>{await runTool(runBuddyDocs,"--write")});buddy.command("docs:buddy:check","Verify the buddy command reference doc is current").action(async()=>{await runTool(runBuddyDocs,"--check")});buddy.command("docs:artifacts","Regenerate the generated API artifacts (OpenAPI + types)").action(async()=>{await runTool(runArtifacts,"--write")});buddy.command("docs:artifacts:check","Verify the generated API artifacts are current").action(async()=>{await runTool(runArtifacts,"--check")});buddy.command("docs:agent-counts","Rewrite the counts AGENTS.md and the skills state, from the tree").action(async()=>{await runTool(runAgentCounts,"--write")});buddy.command("docs:agent-counts:check","Verify the counts AGENTS.md and the skills state are current").action(async()=>{await runTool(runAgentCounts,"--check")});buddy.command("docs:capabilities","Regenerate the driver capability matrix in docs/features/capabilities.md").action(async()=>{await runTool(runCapabilities,"--write")});buddy.command("docs:capabilities:check","Verify the published capability matrix matches its registry").action(async()=>{await runTool(runCapabilities,"--check")});buddy.command("docs:desktop-matrix","Regenerate the desktop support matrix in docs/packages/desktop.md").action(async()=>{await runTool(runDesktopMatrix,"--write")});buddy.command("docs:desktop-matrix:check","Verify the published desktop support matrix matches its source").action(async()=>{await runTool(runDesktopMatrix,"--check")});buddy.command("docs:snippets","Record the documented imports that do not compile, as the baseline").action(async()=>{await runTool(runSnippets,"--write")});buddy.command("docs:snippets:check","Verify no NEW documented import fails to compile").action(async()=>{await runTool(runSnippets,"--check")});buddy.command("docs:links","Report internal documentation links").action(async()=>{await runTool(runLinks)});buddy.command("docs:links:check","Verify internal documentation links resolve").action(async()=>{await runTool(runLinks,"--check")})}
|
|
1
|
+
import{run as runAgentCounts}from"./docs/agent-counts";import{run as runArtifacts}from"./docs/generated-artifacts";import{run as runBuddyDocs}from"./docs/buddy-commands";import{run as runCapabilities}from"./docs/capabilities";import{run as runSnippets}from"./docs/snippets";import{run as runDesktopMatrix}from"./docs/desktop-matrix";import{run as runLinks}from"./docs/links";import{run as runNativeSkills}from"./docs/native-skills";import{runTool}from"./run-tool";export function docs(buddy){buddy.command("docs:stories","Record browser and native user stories with video, scene screenshots and docs").option("--config <path>","Story configuration path",{default:"config/stories.ts"}).option("--out <directory>","Generated documentation and media directory").option("--only <ids>","Comma-separated story ids").option("--list","Validate and list stories without starting drivers",{default:false}).option("--check","Verify complete recordings, configuration and artifact hashes",{default:false}).option("--json","Print the story report as JSON",{default:false}).example("buddy docs:stories").example("buddy docs:stories --only checkout-ios,checkout-android").example("buddy docs:stories --check").action(async(options)=>{const{recordStories}=await import("@stacksjs/docs/stories");const report=await recordStories({config:options.config,outDir:options.out,only:options.only?.split(",").map((value)=>value.trim()).filter(Boolean),list:options.list,check:options.check,onProgress:(result)=>{if(!options.json)console.log(`${result.status} ${result.id} (${result.platform})`)}});if(options.json)console.log(JSON.stringify(report,null,2));else if(options.list)for(const story of report.inventory)console.log(`${story.id} (${story.platform}): ${story.scenes.map((scene)=>scene.id).join(", ")}`);else console.log(`Story documentation: ${report.outDir}/index.md`);if(!options.list&&report.results.some((result)=>result.status!=="passed"))process.exitCode=1});buddy.command("docs:screenshots","Capture and verify an explicit UI inventory with Bun WebView").option("--config <path>","Screenshot configuration path",{default:"config/screenshots.ts"}).option("--out <directory>","Override the output directory").option("--only <ids>","Comma-separated screen ids to capture").option("--viewport <names>","Comma-separated configured viewport names").option("--list","Validate screen coverage without opening a browser",{default:false}).option("--check","Verify the complete saved inventory and image hashes",{default:false}).option("--publish","Rebuild the films and docs page from the saved captures, without a browser",{default:false}).option("--json","Print the inventory, model plan and capture report as JSON",{default:false}).example("buddy docs:screenshots --list").example("buddy docs:screenshots --only welcome,calendar --viewport mobile").action(async(options)=>{const{captureScreenshots,publishScreenshots}=await import("@stacksjs/docs/screenshots");if(options.publish){const published=await publishScreenshots({config:options.config,outDir:options.out});if(options.json)console.log(JSON.stringify(published,null,2));else console.log(`${published.films?.length??0} films${published.docsPage?` and ${published.docsPage.path}`:""} rebuilt from ${published.results.filter((result)=>result.status==="captured").length} captures.`);return}const report=await captureScreenshots({config:options.config,outDir:options.out,only:options.only?.split(",").map((value)=>value.trim()).filter(Boolean),viewports:options.viewport?.split(",").map((value)=>value.trim()).filter(Boolean),list:options.list,check:options.check,onProgress:(result)=>{if(!options.json)console.log(`${result.status} ${result.id}/${result.profile}/${result.viewport.name}`)}});if(options.json){console.log(JSON.stringify(report,null,2));if(report.results.some((result)=>result.status==="failed"))process.exitCode=1;return}if(options.list)for(const screen of report.inventory)console.log(`${screen.id} ${screen.path}${screen.skip?` [excluded: ${screen.skip}]`:""}`);if(options.list)for(const model of report.models.models)console.log(`${model.name} (${model.table||"table inferred"}, key ${model.primaryKey}): ${model.factoryFields.length} factories, seeder count ${model.seederCount??"not declared"}, parents ${model.parents.join(", ")||"none"}, required overrides ${model.requiredWithoutFactory.join(", ")||"none"}, sensitive fields ${model.sensitiveFields.join(", ")||"none"}, states ${model.suggestedStates.join(", ")}`);if(options.list&&report.models.cycles.length)console.log(`Cyclic model dependencies: ${report.models.cycles.join(", ")}`);if(options.list&&report.models.externalParents.length)console.log(`Parent fixtures outside this model set: ${report.models.externalParents.join(", ")}`);const failed=report.results.filter((result)=>result.status==="failed");for(const result of failed)console.error(`${result.id}/${result.profile}/${result.viewport.name}: ${result.error}`);console.log(options.list?"Screenshot configuration and template coverage verified.":`${report.results.filter((result)=>result.status==="captured").length} captures, ${failed.length} failed, ${report.results.filter((result)=>result.status==="skipped").length} explained exclusions.`);if(failed.length)process.exitCode=1});for(const check of[false,true]){buddy.command(check?"docs:style-guide:check":"docs:style-guide",check?"Verify generated application style guide freshness":"Generate a branded application component style guide").option("--config <path>","Style guide configuration path",{default:"config/style-guide.ts"}).action(async(options)=>{const{runStyleGuide}=await import("@stacksjs/docs/style-guide");const result=await runStyleGuide({config:options.config,check});console.log(`${check?"Verified":"Generated"} style guide: ${result.components} components, ${result.stories} stories, ${result.variants} variants.`)})}buddy.command("docs:native-skills","Regenerate native skill package coverage and driver evidence").action(async()=>{await runTool(runNativeSkills,"--write")});buddy.command("docs:native-skills:check","Verify native skills cover current packages and driver capabilities").action(async()=>{await runTool(runNativeSkills,"--check")});buddy.command("docs:buddy","Regenerate the buddy command reference doc").action(async()=>{await runTool(runBuddyDocs,"--write")});buddy.command("docs:buddy:check","Verify the buddy command reference doc is current").action(async()=>{await runTool(runBuddyDocs,"--check")});buddy.command("docs:artifacts","Regenerate the generated API artifacts (OpenAPI + types)").action(async()=>{await runTool(runArtifacts,"--write")});buddy.command("docs:artifacts:check","Verify the generated API artifacts are current").action(async()=>{await runTool(runArtifacts,"--check")});buddy.command("docs:agent-counts","Rewrite the counts AGENTS.md and the skills state, from the tree").action(async()=>{await runTool(runAgentCounts,"--write")});buddy.command("docs:agent-counts:check","Verify the counts AGENTS.md and the skills state are current").action(async()=>{await runTool(runAgentCounts,"--check")});buddy.command("docs:capabilities","Regenerate the driver capability matrix in docs/features/capabilities.md").action(async()=>{await runTool(runCapabilities,"--write")});buddy.command("docs:capabilities:check","Verify the published capability matrix matches its registry").action(async()=>{await runTool(runCapabilities,"--check")});buddy.command("docs:desktop-matrix","Regenerate the desktop support matrix in docs/packages/desktop.md").action(async()=>{await runTool(runDesktopMatrix,"--write")});buddy.command("docs:desktop-matrix:check","Verify the published desktop support matrix matches its source").action(async()=>{await runTool(runDesktopMatrix,"--check")});buddy.command("docs:snippets","Record the documented imports that do not compile, as the baseline").action(async()=>{await runTool(runSnippets,"--write")});buddy.command("docs:snippets:check","Verify no NEW documented import fails to compile").action(async()=>{await runTool(runSnippets,"--check")});buddy.command("docs:links","Report internal documentation links").action(async()=>{await runTool(runLinks)});buddy.command("docs:links:check","Verify internal documentation links resolve").action(async()=>{await runTool(runLinks,"--check")})}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* @defaultValue
|
|
4
4
|
* ```ts
|
|
5
5
|
* {
|
|
6
|
-
* ".github/workflows/buddy-bot.yml": "# The one dependency bot a generated app gets.\n#\n# The template used to ship a `renovate.json` instead, which opted every new app\n# into a bot the framework's own policy does not use (AGENTS.md: \"buddy-bot\n# handles dependency updates, not renovatebot\"). Running both is what\n# stacksjs/stacks#2574 is about: the same bump arrives twice, two dashboards\n# disagree, and a human picks a winner with nothing recording why.\n#\n# This is the app-shaped version of the framework's own buddy-bot workflow -\n# the three scheduled jobs and the manual trigger, without the framework's\n# release plumbing. Configure it in `config/buddy-bot.ts`.\nname: Buddy Bot\n\non:\n schedule:\n # Look for updates every two hours, then refresh the dashboard 15 minutes\n # later so it reflects the pull requests that run just opened.\n - cron: '0 *\/2 * * *'\n - cron: '15 *\/2 * * *'\n # Daily: close pull requests whose update already landed, and clean up the\n # branches left behind.\n - cron: '0 4 * * *'\n\n workflow_dispatch:\n inputs:\n job:\n description: Which job to run\n required: false\n default: all\n type: choice\n options:\n - all\n - check\n - update\n - dashboard\n strategy:\n description: Update strategy\n required: false\n default: patch\n type: choice\n options:\n - all\n - major\n - minor\n - patch\n dry_run:\n description: Dry run (preview only)\n required: false\n default: false\n type: boolean\n\nenv:\n # The built-in token is enough for commits, pull requests and issues.\n # BUDDY_BOT_TOKEN (a PAT with `repo` and `workflow` scope) is only needed if\n # you want buddy-bot to update workflow files themselves.\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n BUDDY_BOT_TOKEN: ${{ secrets.BUDDY_BOT_TOKEN }}\n\npermissions:\n contents: write\n pull-requests: write\n issues: write\n\n# Serialize runs so a scheduled tick and a manual one cannot race on the same\n# branches. `cancel-in-progress: false` lets the running job finish rather than\n# being killed part-way through a commit.\nconcurrency:\n group: buddy-bot-${{ github.ref }}\n cancel-in-progress: false\n\njobs:\n buddy-bot:\n runs-on: ubuntu-latest\n timeout-minutes: 30\n\n steps:\n - name: Checkout Code\n uses: actions/checkout@v4\n with:\n token: ${{ secrets.GITHUB_TOKEN }}\n # Rebasing an open branch needs the history it was cut from.\n fetch-depth: 0\n persist-credentials: true\n\n - name: Setup Pantry\n uses: pantry-pm/pantry/packages/action@cdb82193cb344c2b881a88ea79f88243f5522e0f # v0.11.75\n with:\n version: '0.11.75'\n install: 'false'\n\n - name: Install Dependencies\n run: bun install\n\n - name: Configure Git\n run: |\n git config --global user.name \"github-actions[bot]\"\n git config --global user.email \"github-actions[bot]@users.noreply.github.com\"\n\n - name: Open and refresh update pull requests\n if: ${{ github.event.schedule == '0 *\/2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('[\"all\", \"update\"]'), inputs.job)) }}\n run: bunx @buddysh/buddy update --strategy \"${{ inputs.strategy || 'patch' }}\" ${{ inputs.dry_run && '--dry-run' || '' }}\n\n - name: Update the dependency dashboard\n if: ${{ github.event.schedule == '15 *\/2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('[\"all\", \"dashboard\"]'), inputs.job)) }}\n run: bunx @buddysh/buddy
|
|
6
|
+
* ".github/workflows/buddy-bot.yml": "# The one dependency bot a generated app gets.\n#\n# The template used to ship a `renovate.json` instead, which opted every new app\n# into a bot the framework's own policy does not use (AGENTS.md: \"buddy-bot\n# handles dependency updates, not renovatebot\"). Running both is what\n# stacksjs/stacks#2574 is about: the same bump arrives twice, two dashboards\n# disagree, and a human picks a winner with nothing recording why.\n#\n# This is the app-shaped version of the framework's own buddy-bot workflow -\n# the three scheduled jobs and the manual trigger, without the framework's\n# release plumbing. Configure it in `config/buddy-bot.ts`.\nname: Buddy Bot\n\non:\n schedule:\n # Look for updates every two hours, then refresh the dashboard 15 minutes\n # later so it reflects the pull requests that run just opened.\n - cron: '0 *\/2 * * *'\n - cron: '15 *\/2 * * *'\n # Daily: close pull requests whose update already landed, and clean up the\n # branches left behind.\n - cron: '0 4 * * *'\n\n workflow_dispatch:\n inputs:\n job:\n description: Which job to run\n required: false\n default: all\n type: choice\n options:\n - all\n - check\n - update\n - dashboard\n strategy:\n description: Update strategy\n required: false\n default: patch\n type: choice\n options:\n - all\n - major\n - minor\n - patch\n dry_run:\n description: Dry run (preview only)\n required: false\n default: false\n type: boolean\n\nenv:\n # The built-in token is enough for commits, pull requests and issues.\n # BUDDY_BOT_TOKEN (a PAT with `repo` and `workflow` scope) is only needed if\n # you want buddy-bot to update workflow files themselves.\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n BUDDY_BOT_TOKEN: ${{ secrets.BUDDY_BOT_TOKEN }}\n\npermissions:\n contents: write\n pull-requests: write\n issues: write\n\n# Serialize runs so a scheduled tick and a manual one cannot race on the same\n# branches. `cancel-in-progress: false` lets the running job finish rather than\n# being killed part-way through a commit.\nconcurrency:\n group: buddy-bot-${{ github.ref }}\n cancel-in-progress: false\n\njobs:\n buddy-bot:\n runs-on: ubuntu-latest\n timeout-minutes: 30\n\n steps:\n - name: Checkout Code\n uses: actions/checkout@v4\n with:\n token: ${{ secrets.GITHUB_TOKEN }}\n # Rebasing an open branch needs the history it was cut from.\n fetch-depth: 0\n persist-credentials: true\n\n - name: Setup Pantry\n uses: pantry-pm/pantry/packages/action@cdb82193cb344c2b881a88ea79f88243f5522e0f # v0.11.75\n with:\n version: '0.11.75'\n install: 'false'\n\n - name: Install Dependencies\n run: bun install\n\n - name: Configure Git\n run: |\n git config --global user.name \"github-actions[bot]\"\n git config --global user.email \"github-actions[bot]@users.noreply.github.com\"\n\n - name: Open and refresh update pull requests\n if: ${{ github.event.schedule == '0 *\/2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('[\"all\", \"update\"]'), inputs.job)) }}\n run: bunx @buddysh/buddy update --strategy \"${{ inputs.strategy || 'patch' }}\" ${{ inputs.dry_run && '--dry-run' || '' }}\n\n # `dashboard` has no --dry-run (it rejects the option and fails the run),\n # so a dry run previews with `scan`, which lists what the dashboard would\n # show and writes nothing - as the framework's own workflow does.\n - name: Update the dependency dashboard\n if: ${{ github.event.schedule == '15 *\/2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('[\"all\", \"dashboard\"]'), inputs.job)) }}\n run: bunx @buddysh/buddy ${{ inputs.dry_run && 'scan' || 'dashboard' }}\n\n - name: Close landed pull requests and clean up branches\n if: ${{ github.event.schedule == '0 4 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('[\"all\", \"check\"]'), inputs.job)) }}\n run: bunx @buddysh/buddy update-check ${{ inputs.dry_run && '--dry-run' || '' }}\n",
|
|
7
7
|
* "config/buddy-bot.ts": "import type { BuddyConfig } from '@buddysh/buddy'\n\n/**\n * buddy-bot is the one dependency bot a Stacks app runs.\n *\n * `.github/workflows/buddy-bot.yml` is what drives it: updates every two\n * hours, a dashboard issue 15 minutes later, and a daily pass that closes pull\n * requests whose bump already landed. Nothing else should be opening\n * dependency pull requests here - two bots proposing the same bump is\n * stacksjs/stacks#2574, and it costs a full CI matrix per duplicate.\n *\/\nexport default {\n repository: {\n provider: 'github',\n // In Actions this is already the account or organization the repository\n // lives under, which is the only place the workflow above runs. Replace the\n // fallback if you also run buddy-bot locally.\n owner: process.env.GITHUB_REPOSITORY_OWNER || 'your-github-owner',\n name: '__APP_SLUG__',\n // token: process.env.BUDDY_BOT_TOKEN,\n },\n\n dashboard: {\n enabled: true,\n title: 'Dependency Dashboard',\n },\n\n workflows: {\n enabled: true,\n outputDir: '.github/workflows',\n templates: {\n daily: true,\n weekly: true,\n monthly: true,\n },\n custom: [],\n },\n\n packages: {\n strategy: 'all',\n ignore: [\n // Packages to hold back, e.g. '@types/node'\n ],\n ignorePaths: [\n // Glob patterns to skip, e.g. 'apps/legacy/**'\n ],\n },\n\n verbose: false,\n} satisfies BuddyConfig\n"
|
|
8
8
|
* }
|
|
9
9
|
* ```
|
|
@@ -100,9 +100,12 @@ jobs:
|
|
|
100
100
|
if: \${{ github.event.schedule == '0 */2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('["all", "update"]'), inputs.job)) }}
|
|
101
101
|
run: bunx @buddysh/buddy update --strategy "\${{ inputs.strategy || 'patch' }}" \${{ inputs.dry_run && '--dry-run' || '' }}
|
|
102
102
|
|
|
103
|
+
# \`dashboard\` has no --dry-run (it rejects the option and fails the run),
|
|
104
|
+
# so a dry run previews with \`scan\`, which lists what the dashboard would
|
|
105
|
+
# show and writes nothing - as the framework's own workflow does.
|
|
103
106
|
- name: Update the dependency dashboard
|
|
104
107
|
if: \${{ github.event.schedule == '15 */2 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('["all", "dashboard"]'), inputs.job)) }}
|
|
105
|
-
run: bunx @buddysh/buddy
|
|
108
|
+
run: bunx @buddysh/buddy \${{ inputs.dry_run && 'scan' || 'dashboard' }}
|
|
106
109
|
|
|
107
110
|
- name: Close landed pull requests and clean up branches
|
|
108
111
|
if: \${{ github.event.schedule == '0 4 * * *' || (github.event_name == 'workflow_dispatch' && contains(fromJSON('["all", "check"]'), inputs.job)) }}
|
package/dist/tray/api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{timingSafeEqual}from"node:crypto";export function traySnapshot(status,projects){const approvals=new Map(status?.generation?.approvals?.map(({path,files})=>[path,files]));const failures=new Map(status?.generation?.failures?.map(({path,error})=>[path,error]));return{online:status!==null,watched:status?.generation?.watched??0,running:status?.generation?.running!=null,failed:failures.size,projects:projects.map(({id,name,path})=>({id,name,path,pending:approvals.get(path)??0,issue:failures.get(path)??""}))}}export function createTrayApi(token,services,documentOrigin){const authorization=Buffer.from(`Bearer ${token}`);const json=(body,status=200)=>Response.json(body,{status,headers:{"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Access-Control-Allow-Origin":documentOrigin}});return async(request,origin)=>{const requestOrigin=request.headers.get("origin");const path=new URL(request.url).pathname;if(requestOrigin===documentOrigin&&request.method==="OPTIONS"&&path.startsWith("/api/")){return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":documentOrigin,"Access-Control-Allow-Methods":"GET, POST","Access-Control-Allow-Headers":"authorization, content-type","Access-Control-Max-Age":"600"}})}const supplied=Buffer.from(request.headers.get("authorization")??"");if(requestOrigin!==null&&requestOrigin!==origin&&requestOrigin!==documentOrigin||supplied.length!==authorization.length||!timingSafeEqual(supplied,authorization))return json({error:"This request did not come from the Buddy menu bar."},403);const url=new URL(request.url);try{if(request.method==="GET"){if(path==="/api/status"){const[status,system]=await Promise.all([services.status(),services.system()]);return json({...traySnapshot(status,services.projects()),system})}if(path==="/api/pantry")return json(await services.pantry.status());if(path==="/api/pantry/jobs")return json(await services.pantry.jobs());if(path==="/api/pantry/catalog"){const query=url.searchParams.get("q")?.trim()??"";return json(query.length>=2&&query.length<=100?services.pantry.catalog(query):[])}}if(path!=="/api/action"||request.method!=="POST")return json({error:"Unknown Buddy tray endpoint."},404);if(request.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return json({error:"Send a JSON request."},415);const input=await request.json().catch(()=>null);if(input?.action==="start"){await services.start()}else if(input?.action==="quit"){services.quit()}else if(input?.action==="pantry:pair"){if(typeof input.code!=="string"||!/^\d{8}$/.test(input.code))return json({error:"Enter Pantry’s eight-digit pairing code."},400);await services.pantry.pair(input.code)}else if(input?.action==="pantry:disconnect"){await services.pantry.disconnect()}else if(input?.action==="pantry:install"||input?.action==="pantry:uninstall"){if(typeof input.domain!=="string"||!/^[a-z0-9][a-z0-9._/-]{0,199}$/i.test(input.domain)||typeof input.requestId!=="string"||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(input.requestId))return json({error:"Select a Pantry package and try again."},400);const operation=input.action==="pantry:install"?"install":"uninstall";return json(await services.pantry.change(operation,input.domain,input.requestId),202)}else if(input?.action==="dashboard"||input?.action==="review"){const project=services.projects().find(({id})=>id===input.project);if(!project)return json({error:"This project is no longer registered with Buddy."},404);if(input.action==="review"){const pending=(await services.status())?.generation?.approvals;if(!pending?.some((approval)=>approval.path===project.path&&approval.files>0))return json({error:"This project has no changes awaiting review."},409);await services.review(project)}else{await services.dashboard(project)}}else{return json({error:"Unknown Buddy tray action."},400)}return json({ok:true})}catch(error){return json({error:error instanceof Error?error.message:"Buddy could not complete this action."},500)}}}
|
|
1
|
+
import{Buffer}from"node:buffer";import{timingSafeEqual}from"node:crypto";export function traySnapshot(status,projects){const approvals=new Map(status?.generation?.approvals?.map(({path,files})=>[path,files]));const failures=new Map(status?.generation?.failures?.map(({path,error})=>[path,error]));const dashboards=new Map(status?.dashboards.map(({path,state})=>[path,state]));return{online:status!==null,watched:status?.generation?.watched??0,running:status?.generation?.running!=null,failed:failures.size,projects:projects.map(({id,name,path})=>({id,name,path,pending:approvals.get(path)??0,issue:failures.get(path)??"",dashboard:dashboards.get(path)??"stopped"}))}}export function createTrayApi(token,services,documentOrigin){const authorization=Buffer.from(`Bearer ${token}`);const json=(body,status=200)=>Response.json(body,{status,headers:{"Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Access-Control-Allow-Origin":documentOrigin}});return async(request,origin)=>{const requestOrigin=request.headers.get("origin");const path=new URL(request.url).pathname;if(requestOrigin===documentOrigin&&request.method==="OPTIONS"&&path.startsWith("/api/")){return new Response(null,{status:204,headers:{"Access-Control-Allow-Origin":documentOrigin,"Access-Control-Allow-Methods":"GET, POST","Access-Control-Allow-Headers":"authorization, content-type","Access-Control-Max-Age":"600"}})}const supplied=Buffer.from(request.headers.get("authorization")??"");if(requestOrigin!==null&&requestOrigin!==origin&&requestOrigin!==documentOrigin||supplied.length!==authorization.length||!timingSafeEqual(supplied,authorization))return json({error:"This request did not come from the Buddy menu bar."},403);const url=new URL(request.url);try{if(request.method==="GET"){if(path==="/api/status"){const[status,system]=await Promise.all([services.status(),services.system()]);return json({...traySnapshot(status,services.projects()),system})}if(path==="/api/pantry")return json(await services.pantry.status());if(path==="/api/pantry/jobs")return json(await services.pantry.jobs());if(path==="/api/pantry/catalog"){const query=url.searchParams.get("q")?.trim()??"";return json(query.length>=2&&query.length<=100?services.pantry.catalog(query):[])}}if(path!=="/api/action"||request.method!=="POST")return json({error:"Unknown Buddy tray endpoint."},404);if(request.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()!=="application/json")return json({error:"Send a JSON request."},415);const input=await request.json().catch(()=>null);if(input?.action==="start"){await services.start()}else if(input?.action==="quit"){services.quit()}else if(input?.action==="pantry:pair"){if(typeof input.code!=="string"||!/^\d{8}$/.test(input.code))return json({error:"Enter Pantry’s eight-digit pairing code."},400);await services.pantry.pair(input.code)}else if(input?.action==="pantry:disconnect"){await services.pantry.disconnect()}else if(input?.action==="pantry:install"||input?.action==="pantry:uninstall"){if(typeof input.domain!=="string"||!/^[a-z0-9][a-z0-9._/-]{0,199}$/i.test(input.domain)||typeof input.requestId!=="string"||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(input.requestId))return json({error:"Select a Pantry package and try again."},400);const operation=input.action==="pantry:install"?"install":"uninstall";return json(await services.pantry.change(operation,input.domain,input.requestId),202)}else if(input?.action==="dashboard"||input?.action==="review"){const project=services.projects().find(({id})=>id===input.project);if(!project)return json({error:"This project is no longer registered with Buddy."},404);if(input.action==="review"){const pending=(await services.status())?.generation?.approvals;if(!pending?.some((approval)=>approval.path===project.path&&approval.files>0))return json({error:"This project has no changes awaiting review."},409);await services.review(project)}else{await services.dashboard(project)}}else{return json({error:"Unknown Buddy tray action."},400)}return json({ok:true})}catch(error){return json({error:error instanceof Error?error.message:"Buddy could not complete this action."},500)}}}
|
package/dist/tray/run.js
CHANGED
|
@@ -17,6 +17,7 @@ import { timingSafeEqual } from "crypto";
|
|
|
17
17
|
function traySnapshot(status, projects) {
|
|
18
18
|
const approvals = new Map(status?.generation?.approvals?.map(({ path, files }) => [path, files]));
|
|
19
19
|
const failures = new Map(status?.generation?.failures?.map(({ path, error }) => [path, error]));
|
|
20
|
+
const dashboards = new Map(status?.dashboards.map(({ path, state }) => [path, state]));
|
|
20
21
|
return {
|
|
21
22
|
online: status !== null,
|
|
22
23
|
watched: status?.generation?.watched ?? 0,
|
|
@@ -27,7 +28,8 @@ function traySnapshot(status, projects) {
|
|
|
27
28
|
name,
|
|
28
29
|
path,
|
|
29
30
|
pending: approvals.get(path) ?? 0,
|
|
30
|
-
issue: failures.get(path) ?? ""
|
|
31
|
+
issue: failures.get(path) ?? "",
|
|
32
|
+
dashboard: dashboards.get(path) ?? "stopped"
|
|
31
33
|
}))
|
|
32
34
|
};
|
|
33
35
|
}
|
|
@@ -229,7 +231,7 @@ function createSystemSampler() {
|
|
|
229
231
|
|
|
230
232
|
// src/tray/view.stx
|
|
231
233
|
var view_default = `<script client>
|
|
232
|
-
type Project = { id: string, name: string, path: string, pending: number, issue: string }
|
|
234
|
+
type Project = { id: string, name: string, path: string, pending: number, issue: string, dashboard: 'ready' | 'starting' | 'stopped' }
|
|
233
235
|
type Snapshot = { online: boolean, watched: number, running: boolean, failed: number, projects: Project[], system: { cpu: number | null, memory: { used: number, total: number, raw: boolean } } }
|
|
234
236
|
type Package = { name: string, version: string, managed?: boolean }
|
|
235
237
|
type CatalogMatch = { name: string, domain: string }
|
|
@@ -239,6 +241,7 @@ type PantryStatus = { state: 'offline' | 'pair' | 'ready', issue?: string, packa
|
|
|
239
241
|
const snapshot = state<Snapshot | null>(null)
|
|
240
242
|
const filter = state('')
|
|
241
243
|
const busy = state('')
|
|
244
|
+
const launching = state('')
|
|
242
245
|
const notice = state('')
|
|
243
246
|
const unavailable = state(false)
|
|
244
247
|
const pane = state<'overview' | 'pantry'>('overview')
|
|
@@ -373,6 +376,7 @@ async function searchCatalog() {
|
|
|
373
376
|
async function perform(action: string, project?: string) {
|
|
374
377
|
if (busy()) return
|
|
375
378
|
busy.set(project || action)
|
|
379
|
+
if (action === 'dashboard' && project) launching.set(project)
|
|
376
380
|
notice.set('')
|
|
377
381
|
try {
|
|
378
382
|
await call('/api/action', { action, project })
|
|
@@ -384,6 +388,7 @@ async function perform(action: string, project?: string) {
|
|
|
384
388
|
}
|
|
385
389
|
finally {
|
|
386
390
|
busy.set('')
|
|
391
|
+
launching.set('')
|
|
387
392
|
}
|
|
388
393
|
}
|
|
389
394
|
|
|
@@ -415,12 +420,12 @@ onDestroy(() => {
|
|
|
415
420
|
:root {
|
|
416
421
|
color-scheme: light dark;
|
|
417
422
|
font-family: -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
|
|
418
|
-
--ink: light-dark(#
|
|
419
|
-
--secondary: light-dark(#
|
|
420
|
-
--surface: light-dark(#
|
|
421
|
-
--line: light-dark(#
|
|
422
|
-
--accent: light-dark(#
|
|
423
|
-
--accent-surface: light-dark(#
|
|
423
|
+
--ink: light-dark(#191b23, #f4f4f8);
|
|
424
|
+
--secondary: light-dark(#575d6c, #b3b6c5);
|
|
425
|
+
--surface: light-dark(#ffffffc9, #202128db);
|
|
426
|
+
--line: light-dark(#1d22351c, #ffffff20);
|
|
427
|
+
--accent: light-dark(#254eb1, #b7cbff);
|
|
428
|
+
--accent-surface: light-dark(#e9efff, #293955);
|
|
424
429
|
}
|
|
425
430
|
html, body { margin: 0; min-height: 100%; background: transparent; color: var(--ink); }
|
|
426
431
|
body { font-size: 13px; }
|
|
@@ -441,6 +446,9 @@ onDestroy(() => {
|
|
|
441
446
|
.issue { color: light-dark(#875115, #f0bd83); }
|
|
442
447
|
.search { color: inherit; }
|
|
443
448
|
.tab { border: 0; }
|
|
449
|
+
.tray-project { min-height: 44px; }
|
|
450
|
+
.project-icon { width: 25px; height: 25px; display: grid; place-items: center; border-radius: .45rem; }
|
|
451
|
+
.dashboard-launch { min-width: 5rem; }
|
|
444
452
|
.meter { display: block; appearance: none; width: 100%; height: 4px; border: 0; overflow: hidden; border-radius: 8px; }
|
|
445
453
|
.meter::-webkit-progress-bar { background: var(--accent-surface); }
|
|
446
454
|
.meter::-webkit-progress-value { background: var(--accent); border-radius: 8px; }
|
|
@@ -571,7 +579,7 @@ onDestroy(() => {
|
|
|
571
579
|
@endforeach
|
|
572
580
|
</ul>
|
|
573
581
|
@else
|
|
574
|
-
<p class="
|
|
582
|
+
<p class="text-xs secondary">No approvals waiting.</p>
|
|
575
583
|
@endif
|
|
576
584
|
</section>
|
|
577
585
|
|
|
@@ -583,14 +591,19 @@ onDestroy(() => {
|
|
|
583
591
|
@if(recent().length)
|
|
584
592
|
<ul class="m-0 p-0 list-none border rounded-xl line surface">
|
|
585
593
|
@foreach(recent() as project)
|
|
586
|
-
<li class="flex gap-
|
|
587
|
-
<
|
|
594
|
+
<li class="flex gap-2 items-center px-2.5 py-1.5 border-b last:border-b-0 line tray-project">
|
|
595
|
+
<span class="shrink-0 font-semibold text-xs accent project-icon" aria-hidden="true">{{ project.name.trim().slice(0, 1).toUpperCase() }}</span>
|
|
596
|
+
<div class="flex-1 min-w-0">
|
|
588
597
|
<p class="truncate" :title="project.path">{{ project.name }}</p>
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
@endif
|
|
598
|
+
<p class="text-xs truncate issue" :if="project.issue" :title="project.issue">{{ project.issue }}</p>
|
|
599
|
+
<p class="text-xs online" :if="project.dashboard === 'ready' && !project.issue">Running</p>
|
|
592
600
|
</div>
|
|
593
|
-
<button type="button" class="shrink-0 px-2 py-1 text-xs rounded-md
|
|
601
|
+
<button type="button" class="shrink-0 px-2 py-1 text-xs accent rounded-md dashboard-launch tab"
|
|
602
|
+
:aria-label="'Open ' + project.name + ' dashboard'"
|
|
603
|
+
:aria-busy="launching() === project.id || project.dashboard === 'starting'"
|
|
604
|
+
:disabled="busy() !== ''" @click="perform('dashboard', project.id)">
|
|
605
|
+
{{ launching() === project.id || project.dashboard === 'starting' ? 'Opening\u2026' : 'Open' }}
|
|
606
|
+
</button>
|
|
594
607
|
</li>
|
|
595
608
|
@endforeach
|
|
596
609
|
</ul>
|
|
@@ -703,8 +716,8 @@ async function launchTray(craft) {
|
|
|
703
716
|
craftBin: craft,
|
|
704
717
|
htmlFile,
|
|
705
718
|
title: "Buddy",
|
|
706
|
-
width:
|
|
707
|
-
height:
|
|
719
|
+
width: 396,
|
|
720
|
+
height: 506,
|
|
708
721
|
trayPopover: true,
|
|
709
722
|
hotReload: false,
|
|
710
723
|
devTools: false
|
package/dist/tray/view.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { DefineComponent } from '@stacksjs/stx';
|
|
2
2
|
declare const __dtsx_component__: __DtsxStxComponentType;
|
|
3
3
|
declare type __DtsxStxComponentType = DefineComponent<{}>;
|
|
4
|
-
declare type Project = { id: string, name: string, path: string, pending: number, issue: string }
|
|
4
|
+
declare type Project = { id: string, name: string, path: string, pending: number, issue: string, dashboard: 'ready' | 'starting' | 'stopped' }
|
|
5
5
|
declare type Snapshot = { online: boolean, watched: number, running: boolean, failed: number, projects: Project[], system: { cpu: number | null, memory: { used: number, total: number, raw: boolean } } }
|
|
6
6
|
declare type Package = { name: string, version: string, managed?: boolean }
|
|
7
7
|
declare type CatalogMatch = { name: string, domain: string }
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/buddy",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.653",
|
|
6
6
|
"description": "Meet Buddy. The Stacks runtime.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -95,71 +95,71 @@
|
|
|
95
95
|
"prepublishOnly": "bun run build"
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@stacksjs/actions": "0.75.
|
|
99
|
-
"@stacksjs/docs": "0.75.
|
|
100
|
-
"@stacksjs/ai": "0.75.
|
|
101
|
-
"@stacksjs/alias": "0.75.
|
|
102
|
-
"@stacksjs/analytics": "0.75.
|
|
103
|
-
"@stacksjs/api": "0.75.
|
|
104
|
-
"@stacksjs/arrays": "0.75.
|
|
105
|
-
"@stacksjs/auth": "0.75.
|
|
106
|
-
"@stacksjs/browser-extension": "0.75.
|
|
107
|
-
"@stacksjs/build": "0.75.
|
|
98
|
+
"@stacksjs/actions": "0.75.653",
|
|
99
|
+
"@stacksjs/docs": "0.75.653",
|
|
100
|
+
"@stacksjs/ai": "0.75.653",
|
|
101
|
+
"@stacksjs/alias": "0.75.653",
|
|
102
|
+
"@stacksjs/analytics": "0.75.653",
|
|
103
|
+
"@stacksjs/api": "0.75.653",
|
|
104
|
+
"@stacksjs/arrays": "0.75.653",
|
|
105
|
+
"@stacksjs/auth": "0.75.653",
|
|
106
|
+
"@stacksjs/browser-extension": "0.75.653",
|
|
107
|
+
"@stacksjs/build": "0.75.653",
|
|
108
108
|
"@stacksjs/bumpx": "^0.2.32",
|
|
109
|
-
"@stacksjs/cache": "0.75.
|
|
110
|
-
"@stacksjs/chat": "0.75.
|
|
109
|
+
"@stacksjs/cache": "0.75.653",
|
|
110
|
+
"@stacksjs/chat": "0.75.653",
|
|
111
111
|
"@stacksjs/clapp": "^0.2.17",
|
|
112
|
-
"@stacksjs/cli": "0.75.
|
|
113
|
-
"@stacksjs/cloud": "0.75.
|
|
114
|
-
"@stacksjs/cms": "0.75.
|
|
115
|
-
"@stacksjs/collections": "0.75.
|
|
116
|
-
"@stacksjs/commerce": "0.75.
|
|
117
|
-
"@stacksjs/config": "0.75.
|
|
118
|
-
"@stacksjs/database": "0.75.
|
|
119
|
-
"@stacksjs/desktop-build": "0.75.
|
|
120
|
-
"@stacksjs/dns": "0.75.
|
|
112
|
+
"@stacksjs/cli": "0.75.653",
|
|
113
|
+
"@stacksjs/cloud": "0.75.653",
|
|
114
|
+
"@stacksjs/cms": "0.75.653",
|
|
115
|
+
"@stacksjs/collections": "0.75.653",
|
|
116
|
+
"@stacksjs/commerce": "0.75.653",
|
|
117
|
+
"@stacksjs/config": "0.75.653",
|
|
118
|
+
"@stacksjs/database": "0.75.653",
|
|
119
|
+
"@stacksjs/desktop-build": "0.75.653",
|
|
120
|
+
"@stacksjs/dns": "0.75.653",
|
|
121
121
|
"@stacksjs/dnsx": "^0.2.3",
|
|
122
|
-
"@stacksjs/email": "0.75.
|
|
123
|
-
"@stacksjs/enums": "0.75.
|
|
124
|
-
"@stacksjs/env": "0.75.
|
|
125
|
-
"@stacksjs/error-handling": "0.75.
|
|
126
|
-
"@stacksjs/events": "0.75.
|
|
127
|
-
"@stacksjs/features": "0.75.
|
|
128
|
-
"@stacksjs/git": "0.75.
|
|
122
|
+
"@stacksjs/email": "0.75.653",
|
|
123
|
+
"@stacksjs/enums": "0.75.653",
|
|
124
|
+
"@stacksjs/env": "0.75.653",
|
|
125
|
+
"@stacksjs/error-handling": "0.75.653",
|
|
126
|
+
"@stacksjs/events": "0.75.653",
|
|
127
|
+
"@stacksjs/features": "0.75.653",
|
|
128
|
+
"@stacksjs/git": "0.75.653",
|
|
129
129
|
"@stacksjs/gitit": "^0.2.5",
|
|
130
|
-
"@stacksjs/health": "0.75.
|
|
131
|
-
"@stacksjs/hq": "0.75.
|
|
130
|
+
"@stacksjs/health": "0.75.653",
|
|
131
|
+
"@stacksjs/hq": "0.75.653",
|
|
132
132
|
"@stacksjs/httx": "^0.1.10",
|
|
133
|
-
"@stacksjs/image": "0.75.
|
|
134
|
-
"@stacksjs/lint": "0.75.
|
|
135
|
-
"@stacksjs/logging": "0.75.
|
|
136
|
-
"@stacksjs/notifications": "0.75.
|
|
137
|
-
"@stacksjs/objects": "0.75.
|
|
138
|
-
"@stacksjs/orm": "0.75.
|
|
139
|
-
"@stacksjs/path": "0.75.
|
|
140
|
-
"@stacksjs/payments": "0.75.
|
|
141
|
-
"@stacksjs/realtime": "0.75.
|
|
142
|
-
"@stacksjs/router": "0.75.
|
|
133
|
+
"@stacksjs/image": "0.75.653",
|
|
134
|
+
"@stacksjs/lint": "0.75.653",
|
|
135
|
+
"@stacksjs/logging": "0.75.653",
|
|
136
|
+
"@stacksjs/notifications": "0.75.653",
|
|
137
|
+
"@stacksjs/objects": "0.75.653",
|
|
138
|
+
"@stacksjs/orm": "0.75.653",
|
|
139
|
+
"@stacksjs/path": "0.75.653",
|
|
140
|
+
"@stacksjs/payments": "0.75.653",
|
|
141
|
+
"@stacksjs/realtime": "0.75.653",
|
|
142
|
+
"@stacksjs/router": "0.75.653",
|
|
143
143
|
"@stacksjs/rpx": "^0.11.54",
|
|
144
|
-
"@stacksjs/scheduler": "0.75.
|
|
145
|
-
"@stacksjs/search-engine": "0.75.
|
|
146
|
-
"@stacksjs/security": "0.75.
|
|
147
|
-
"@stacksjs/server": "0.75.
|
|
148
|
-
"@stacksjs/sites": "0.75.
|
|
149
|
-
"@stacksjs/skills": "0.75.
|
|
150
|
-
"@stacksjs/socials": "0.75.
|
|
151
|
-
"@stacksjs/storage": "0.75.
|
|
152
|
-
"@stacksjs/strings": "0.75.
|
|
144
|
+
"@stacksjs/scheduler": "0.75.653",
|
|
145
|
+
"@stacksjs/search-engine": "0.75.653",
|
|
146
|
+
"@stacksjs/security": "0.75.653",
|
|
147
|
+
"@stacksjs/server": "0.75.653",
|
|
148
|
+
"@stacksjs/sites": "0.75.653",
|
|
149
|
+
"@stacksjs/skills": "0.75.653",
|
|
150
|
+
"@stacksjs/socials": "0.75.653",
|
|
151
|
+
"@stacksjs/storage": "0.75.653",
|
|
152
|
+
"@stacksjs/strings": "0.75.653",
|
|
153
153
|
"@stacksjs/stx": "^0.2.908",
|
|
154
|
-
"@stacksjs/testing": "0.75.
|
|
155
|
-
"@stacksjs/tinker": "0.75.
|
|
154
|
+
"@stacksjs/testing": "0.75.653",
|
|
155
|
+
"@stacksjs/tinker": "0.75.653",
|
|
156
156
|
"@stacksjs/tlsx": "^0.13.19",
|
|
157
157
|
"@stacksjs/ts-cloud": "^0.16.144",
|
|
158
|
-
"@stacksjs/tunnel": "0.75.
|
|
159
|
-
"@stacksjs/types": "0.75.
|
|
160
|
-
"@stacksjs/ui": "0.75.
|
|
161
|
-
"@stacksjs/utils": "0.75.
|
|
162
|
-
"@stacksjs/validation": "0.75.
|
|
158
|
+
"@stacksjs/tunnel": "0.75.653",
|
|
159
|
+
"@stacksjs/types": "0.75.653",
|
|
160
|
+
"@stacksjs/ui": "0.75.653",
|
|
161
|
+
"@stacksjs/utils": "0.75.653",
|
|
162
|
+
"@stacksjs/validation": "0.75.653",
|
|
163
163
|
"ajv": "^8.20.0",
|
|
164
164
|
"ajv-formats": "^3.0.1",
|
|
165
165
|
"bun-plugin-stx": "^0.2.908",
|