@stacksjs/buddy 0.75.661 → 0.75.663
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.
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `buddy dev` runs the scheduler beside its servers (stacksjs/stacks#3366).
|
|
3
|
+
*
|
|
4
|
+
* It used to start the frontend, API and docs and never the scheduler, so
|
|
5
|
+
* scheduled work did not happen during local use at all: a post scheduled a
|
|
6
|
+
* minute ahead never went out, with nothing to say a second command was
|
|
7
|
+
* needed. It is on by default; `--no-schedule` or `STACKS_DEV_SCHEDULE=0`
|
|
8
|
+
* turns it off, for an app whose tasks send or post for real.
|
|
9
|
+
*
|
|
10
|
+
* An app with nothing to schedule starts nothing.
|
|
11
|
+
*/
|
|
12
|
+
export declare function devSchedulerEnabled(input: { flag?: boolean, env?: string, hasScheduledWork: boolean }): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Whether the app declares anything the scheduler would run: an
|
|
15
|
+
* `app/Scheduler.ts`, or a job in `app/Jobs/` (a job's `rate` schedules it).
|
|
16
|
+
*/
|
|
17
|
+
export declare function hasScheduledWork(root: string): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync,readdirSync}from"node:fs";import{join}from"node:path";export function devSchedulerEnabled(input){if(input.flag===false)return false;if(input.env!==undefined&&["0","false","off","no"].includes(input.env.trim().toLowerCase()))return false;return input.hasScheduledWork}export function hasScheduledWork(root){if(existsSync(join(root,"app","Scheduler.ts")))return true;try{return readdirSync(join(root,"app","Jobs")).some((file)=>file.endsWith(".ts"))}catch{return false}}
|
package/dist/commands/dev.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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.")}
|
|
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";import{devSchedulerEnabled,hasScheduledWork}from"./dev-scheduler";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 &`)",noSchedule:"Do not run scheduled tasks (app/Scheduler.ts, job rates) beside the dev servers; also STACKS_DEV_SCHEDULE=0"};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}).option("--no-schedule",descriptions.noSchedule).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 includeSchedule=devSchedulerEnabled({flag:options.schedule,env:process.env.STACKS_DEV_SCHEDULE,hasScheduledWork:hasScheduledWork(projectPath())});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,includeSchedule,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(),includeSchedule?a.runScheduleDevServer({verbose:options.verbose}).catch((error)=>{log.error(`Scheduler: ${error instanceof Error?error.message: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,includeSchedule,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(includeSchedule)console.log(` ${green("➜")} ${bold("Scheduler")}: ${cyan("running")} ${dim("(--no-schedule to turn off)")}`);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")}
|
package/dist/scaffold-site.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{cpSync,existsSync,readdirSync,rmSync}from"node:fs";import{join}from"node:path";export const SITE_ONLY_PATHS=["resources/views/index.stx","resources/views/coming-soon.stx","resources/views/compare","resources/views/features","resources/views/use-cases","resources/views/components/FeatureCard.stx","resources/views/layouts/marketing.stx","resources/views/partials/theme.stx","resources/data/assets.ts","resources/data/comparisons.ts","resources/data/features.ts","resources/data/highlight.ts","resources/data/nav.ts","resources/data/stats.ts","resources/data/use-cases.ts","resources/partials/marketing-footer.stx","resources/partials/marketing-head.stx","resources/partials/marketing-nav.stx","resources/partials/marketing-theme-toggle.stx","resources/emails/subscription-confirmation.stx","resources/assets/scripts/site-mode.js","public/assets/styles/home.css","public/assets/styles/marketing.css","public/assets/styles/theme.css","resources/assets/fonts/nps","public/assets/fonts/nps","public/assets/images","resources/assets/images/bg-img.png","resources/assets/images/marketing-park-camp.svg","resources/assets/images/marketing-park-geyser.svg","resources/assets/images/marketing-park-lighthouse.svg","resources/assets/images/marketing-park-trail.svg","resources/assets/images/marketing-park-wing.svg","resources/assets/images/park-ridge.svg","resources/assets/images/river.svg","resources/assets/images/topography.svg","resources/assets/images/wood-sign.svg","docs","content/blog","content/BLOG_STRATEGY.md","public/images/atomic-fx-diagram.png","public/images/atomic-ui-diagram.png","public/images/diagram.png","public/images/og-image.png","public/images/social.png","public/images/background-auth.jpg","public/images/background-features.jpg","public/images/screenshots/expenses.webp","public/images/screenshots/reporting.webp","public/images/screenshots/vat-returns.webp","public/images/logos/amex.jpg","public/images/logos/jcb.svg","public/images/logos/laravel.svg","public/images/logos/logo-dark.svg","public/images/logos/logo-mini.svg","public/images/logos/logo-transparent.svg","public/images/logos/logo-white.png","public/images/logos/logo.png","public/images/logos/logo.svg","public/images/logos/mastercard.svg","public/images/logos/meilisearch.svg","public/images/logos/mirage.svg","public/images/logos/statamic.svg","public/images/logos/statickit.svg","public/images/logos/transistor.svg","public/images/logos/tuple.svg","public/images/logos/visa.png","public/images/logos/visa.svgz","cloud/production",".reviewos","resources/assets/scripts/main.ts","resources/assets/styles/main.css","resources/layouts/Desktop.stx","resources/partials/welcome-pdf-content.stx","resources/partials/welcome-pdf-toolbar.stx","resources/components/ContextMenu.stx","resources/components/ContextMenuItem.stx","resources/components/DesktopIcon.stx","resources/components/FeatureButton.stx","resources/components/InputGroup.stx","resources/components/LoginForm.stx","resources/components/LoginScreen.stx","resources/components/NotificationPopup.stx","resources/components/PackageItem.stx","resources/components/StartMenu.stx","resources/components/StartMenuItem.stx","resources/components/Taskbar.stx","resources/components/Window.stx"];export const APP_SITE_TEMPLATE="storage/framework/defaults/scaffold/resources";export function applyAppSiteTemplate(root){const template=join(root,APP_SITE_TEMPLATE);if(!existsSync(template))throw new Error(`No app site template at ${APP_SITE_TEMPLATE}`);const removed=[];for(const relative of[...SITE_ONLY_PATHS,"ops"]){const target=join(root,relative);if(!existsSync(target))continue;rmSync(target,{recursive:true,force:true});removed.push(relative)}for(const relative of removed){let dir=parentOf(relative);while(dir&&!KEPT_ROOTS.has(dir)&&isEmptyDir(join(root,dir))){rmSync(join(root,dir),{recursive:true,force:true});dir=parentOf(dir)}}cpSync(template,join(root,"resources"),{recursive:true});return removed}const KEPT_ROOTS=new Set(["resources","public"]);export const APP_TOP_LEVEL=[".devcontainer",".dockerignore",".editorconfig",".env.example",".gitattributes",".github",".gitignore",".security-ignore.json","AGENTS.md","CHANGELOG.md","README.md","app","bootstrap","buddy","bun.lock","bunfig.toml","cloud","config","database","locales","package.json","pantry.lock","public","resources","routes","storage","tests","tsconfig.json"];export const REMOVED_BY_OTHER_STEPS={".env.development":"install",".env.production":"install",".env.staging":"install","LICENSE.md":"removeFrameworkLicense","deps.yml":"generatePantryDeps"};function parentOf(relative){return relative.includes("/")?relative.slice(0,relative.lastIndexOf("/")):""}function isEmptyDir(dir){return existsSync(dir)&&readdirSync(dir).length===0}
|
|
1
|
+
import{cpSync,existsSync,readdirSync,rmSync}from"node:fs";import{join}from"node:path";export const SITE_ONLY_PATHS=["resources/views/index.stx","resources/views/coming-soon.stx","resources/views/compare","resources/views/features","resources/views/use-cases","resources/views/blog.stx","resources/views/blog","resources/views/components/FeatureCard.stx","resources/components/SignupForm.stx","resources/views/layouts/marketing.stx","resources/views/partials/theme.stx","resources/data/assets.ts","resources/data/blog.ts","resources/data/comparisons.ts","resources/data/features.ts","resources/data/highlight.ts","resources/data/home.ts","resources/data/llms.ts","resources/data/nav.ts","resources/data/schema.ts","resources/data/signup-messages.ts","resources/data/stats.ts","resources/data/theme.ts","resources/data/use-cases.ts","resources/partials/blog-post.stx","resources/partials/blog-subscribe.stx","resources/partials/marketing-footer.stx","resources/partials/marketing-head.stx","resources/partials/marketing-nav.stx","resources/partials/marketing-theme-toggle.stx","resources/emails/subscription-confirmation.stx","resources/assets/scripts/site-mode.js","public/assets/styles/blog.css","public/assets/styles/home.css","public/assets/styles/marketing.css","public/assets/styles/theme.css","public/llms.txt","resources/assets/fonts/nps","public/assets/fonts/nps","public/assets/fonts/geist","public/assets/images","resources/assets/images/bg-img.png","resources/assets/images/marketing-park-camp.svg","resources/assets/images/marketing-park-geyser.svg","resources/assets/images/marketing-park-lighthouse.svg","resources/assets/images/marketing-park-trail.svg","resources/assets/images/marketing-park-wing.svg","resources/assets/images/park-ridge.svg","resources/assets/images/river.svg","resources/assets/images/topography.svg","resources/assets/images/wood-sign.svg","docs","content/blog","content/BLOG_STRATEGY.md","public/images/atomic-fx-diagram.png","public/images/atomic-ui-diagram.png","public/images/diagram.png","public/images/og-image.png","public/images/social.png","public/images/background-auth.jpg","public/images/background-features.jpg","public/images/screenshots/expenses.webp","public/images/screenshots/reporting.webp","public/images/screenshots/vat-returns.webp","public/images/logos/amex.jpg","public/images/logos/jcb.svg","public/images/logos/laravel.svg","public/images/logos/logo-dark.svg","public/images/logos/logo-mini.svg","public/images/logos/logo-transparent.svg","public/images/logos/logo-white.png","public/images/logos/logo.png","public/images/logos/logo.svg","public/images/logos/mastercard.svg","public/images/logos/meilisearch.svg","public/images/logos/mirage.svg","public/images/logos/statamic.svg","public/images/logos/statickit.svg","public/images/logos/transistor.svg","public/images/logos/tuple.svg","public/images/logos/visa.png","public/images/logos/visa.svgz","cloud/production",".reviewos","resources/assets/scripts/main.ts","resources/assets/styles/main.css","resources/layouts/Desktop.stx","resources/partials/welcome-pdf-content.stx","resources/partials/welcome-pdf-toolbar.stx","resources/components/ContextMenu.stx","resources/components/ContextMenuItem.stx","resources/components/DesktopIcon.stx","resources/components/FeatureButton.stx","resources/components/InputGroup.stx","resources/components/LoginForm.stx","resources/components/LoginScreen.stx","resources/components/NotificationPopup.stx","resources/components/PackageItem.stx","resources/components/StartMenu.stx","resources/components/StartMenuItem.stx","resources/components/Taskbar.stx","resources/components/Window.stx"];export const APP_SITE_TEMPLATE="storage/framework/defaults/scaffold/resources";export function applyAppSiteTemplate(root){const template=join(root,APP_SITE_TEMPLATE);if(!existsSync(template))throw new Error(`No app site template at ${APP_SITE_TEMPLATE}`);const removed=[];for(const relative of[...SITE_ONLY_PATHS,"ops"]){const target=join(root,relative);if(!existsSync(target))continue;rmSync(target,{recursive:true,force:true});removed.push(relative)}for(const relative of removed){let dir=parentOf(relative);while(dir&&!KEPT_ROOTS.has(dir)&&isEmptyDir(join(root,dir))){rmSync(join(root,dir),{recursive:true,force:true});dir=parentOf(dir)}}cpSync(template,join(root,"resources"),{recursive:true});return removed}const KEPT_ROOTS=new Set(["resources","public"]);export const APP_TOP_LEVEL=[".devcontainer",".dockerignore",".editorconfig",".env.example",".gitattributes",".github",".gitignore",".security-ignore.json","AGENTS.md","CHANGELOG.md","README.md","app","bootstrap","buddy","bun.lock","bunfig.toml","cloud","config","database","locales","package.json","pantry.lock","public","resources","routes","storage","tests","tsconfig.json"];export const REMOVED_BY_OTHER_STEPS={".env.development":"install",".env.production":"install",".env.staging":"install","LICENSE.md":"removeFrameworkLicense","deps.yml":"generatePantryDeps"};function parentOf(relative){return relative.includes("/")?relative.slice(0,relative.lastIndexOf("/")):""}function isEmptyDir(dir){return existsSync(dir)&&readdirSync(dir).length===0}
|
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.663",
|
|
6
6
|
"description": "Meet Buddy. The Stacks runtime.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -95,74 +95,74 @@
|
|
|
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.663",
|
|
99
|
+
"@stacksjs/docs": "0.75.663",
|
|
100
|
+
"@stacksjs/ai": "0.75.663",
|
|
101
|
+
"@stacksjs/alias": "0.75.663",
|
|
102
|
+
"@stacksjs/analytics": "0.75.663",
|
|
103
|
+
"@stacksjs/api": "0.75.663",
|
|
104
|
+
"@stacksjs/arrays": "0.75.663",
|
|
105
|
+
"@stacksjs/auth": "0.75.663",
|
|
106
|
+
"@stacksjs/browser-extension": "0.75.663",
|
|
107
|
+
"@stacksjs/build": "0.75.663",
|
|
108
108
|
"@stacksjs/bumpx": "^0.2.32",
|
|
109
|
-
"@stacksjs/cache": "0.75.
|
|
110
|
-
"@stacksjs/chat": "0.75.
|
|
109
|
+
"@stacksjs/cache": "0.75.663",
|
|
110
|
+
"@stacksjs/chat": "0.75.663",
|
|
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.663",
|
|
113
|
+
"@stacksjs/cloud": "0.75.663",
|
|
114
|
+
"@stacksjs/cms": "0.75.663",
|
|
115
|
+
"@stacksjs/collections": "0.75.663",
|
|
116
|
+
"@stacksjs/commerce": "0.75.663",
|
|
117
|
+
"@stacksjs/config": "0.75.663",
|
|
118
|
+
"@stacksjs/database": "0.75.663",
|
|
119
|
+
"@stacksjs/desktop-build": "0.75.663",
|
|
120
|
+
"@stacksjs/dns": "0.75.663",
|
|
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.663",
|
|
123
|
+
"@stacksjs/enums": "0.75.663",
|
|
124
|
+
"@stacksjs/env": "0.75.663",
|
|
125
|
+
"@stacksjs/error-handling": "0.75.663",
|
|
126
|
+
"@stacksjs/events": "0.75.663",
|
|
127
|
+
"@stacksjs/features": "0.75.663",
|
|
128
|
+
"@stacksjs/git": "0.75.663",
|
|
129
129
|
"@stacksjs/gitit": "^0.2.5",
|
|
130
|
-
"@stacksjs/health": "0.75.
|
|
131
|
-
"@stacksjs/hq": "0.75.
|
|
130
|
+
"@stacksjs/health": "0.75.663",
|
|
131
|
+
"@stacksjs/hq": "0.75.663",
|
|
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.663",
|
|
134
|
+
"@stacksjs/lint": "0.75.663",
|
|
135
|
+
"@stacksjs/logging": "0.75.663",
|
|
136
|
+
"@stacksjs/notifications": "0.75.663",
|
|
137
|
+
"@stacksjs/objects": "0.75.663",
|
|
138
|
+
"@stacksjs/orm": "0.75.663",
|
|
139
|
+
"@stacksjs/path": "0.75.663",
|
|
140
|
+
"@stacksjs/payments": "0.75.663",
|
|
141
|
+
"@stacksjs/realtime": "0.75.663",
|
|
142
|
+
"@stacksjs/router": "0.75.663",
|
|
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.
|
|
153
|
-
"@stacksjs/stx": "^0.2.
|
|
154
|
-
"@stacksjs/testing": "0.75.
|
|
155
|
-
"@stacksjs/tinker": "0.75.
|
|
144
|
+
"@stacksjs/scheduler": "0.75.663",
|
|
145
|
+
"@stacksjs/search-engine": "0.75.663",
|
|
146
|
+
"@stacksjs/security": "0.75.663",
|
|
147
|
+
"@stacksjs/server": "0.75.663",
|
|
148
|
+
"@stacksjs/sites": "0.75.663",
|
|
149
|
+
"@stacksjs/skills": "0.75.663",
|
|
150
|
+
"@stacksjs/socials": "0.75.663",
|
|
151
|
+
"@stacksjs/storage": "0.75.663",
|
|
152
|
+
"@stacksjs/strings": "0.75.663",
|
|
153
|
+
"@stacksjs/stx": "^0.2.927",
|
|
154
|
+
"@stacksjs/testing": "0.75.663",
|
|
155
|
+
"@stacksjs/tinker": "0.75.663",
|
|
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.663",
|
|
159
|
+
"@stacksjs/types": "0.75.663",
|
|
160
|
+
"@stacksjs/ui": "0.75.663",
|
|
161
|
+
"@stacksjs/utils": "0.75.663",
|
|
162
|
+
"@stacksjs/validation": "0.75.663",
|
|
163
163
|
"ajv": "^8.20.0",
|
|
164
164
|
"ajv-formats": "^3.0.1",
|
|
165
|
-
"bun-plugin-stx": "^0.2.
|
|
165
|
+
"bun-plugin-stx": "^0.2.927",
|
|
166
166
|
"ts-pantry": "^0.11.205"
|
|
167
167
|
},
|
|
168
168
|
"devDependencies": {
|