@stacksjs/buddy 0.75.640 → 0.75.647
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 +2 -2
- package/dist/commands/tray.d.ts +2 -0
- package/dist/commands/tray.js +1 -0
- package/dist/launcher.js +1 -1
- package/dist/lazy-commands.js +1 -1
- package/dist/production-server.js +1 -1
- package/dist/tray/api.d.ts +23 -0
- package/dist/tray/api.js +1 -0
- package/dist/tray/pantry.d.ts +14 -0
- package/dist/tray/pantry.js +1 -0
- package/dist/tray/run.d.ts +3 -0
- package/dist/tray/run.js +744 -0
- package/dist/tray/system.d.ts +10 -0
- package/dist/tray/system.js +1 -0
- package/dist/tray/view.d.ts +10 -0
- package/dist/workflow-template.js +1 -1
- package/package.json +57 -57
package/dist/commands/dev.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
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://localhost:${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://localhost:${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://localhost:${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(`localhost:${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.")}
|
|
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.")}
|
|
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,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,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,includeDashboard);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,includeDashboard}=input;const dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...includeDashboard?[{id:`${domain}-dashboard`,from:`
|
|
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,includeDashboard){return[domain,...includeDashboard?[`dashboard.${domain}`]:[],"rpx.localhost"]}async function ensureRpxDevelopmentHttps(domain,options,includeDashboard,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,includeDashboard);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,includeDashboard}=input;const dashboardDomain=`dashboard.${domain}`;return[{id:`${domain}-frontend`,from:`localhost:${frontendPort}`,to:domain,pathRewrites:[{from:"/api",to:`localhost:${apiPort}`,stripPrefix:false},{from:"/docs",to:`localhost:${docsPort}`,stripPrefix:true}]},...includeDashboard?[{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,includeDashboard,verbose){const{checkHosts,removeHosts,resolverFilePath,contentLooksLikeRpxResolver}=await importDevelopmentRpx();const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];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 labels=domain.split(".");const basename=labels.length>=2?labels.slice(-2).join("."):domain;const resolverPath=resolverFilePath(basename);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
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,includeDashboard,options,skipHosts=false,trustCertificate=true}=input;const verbose=options.verbose??false;const hosts=[domain,...includeDashboard?[`dashboard.${domain}`]:[]];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,includeDashboard,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,includeDashboard:process.env.STACKS_DEV_DASHBOARD==="1",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,includeDashboard,options}=input;const verbose=options.verbose??false;const proxies=buildRpxProxySpecs({domain,frontendPort,apiPort,docsPort,dashboardPort,includeDashboard});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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{reportFailure}from"../result";export function tray(buddy){buddy.command("tray","Open the Buddy menu-bar app for your Stacks projects").action(async()=>{try{const{runTray}=await import("../tray/run");await runTray()}catch(error){reportFailure({error})}})}
|
package/dist/launcher.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{accessSync,constants,realpathSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{findProject,findProjectRoot,isCompiledBinary,isVisitingCli,noteProjectUsed,projectCliEntry}from"@stacksjs/path";import{isIsolatedRuntime,withoutIsolation}from"./runtime-flags";const MACHINE_COMMANDS=["new","create","projects","cd","daemon","dashboard"];const MACHINE_COMMAND_GROUPS=["projects:","daemon:"];export function isMachineCommand(command){if(command===undefined)return false;return MACHINE_COMMANDS.includes(command)||MACHINE_COMMAND_GROUPS.some((group)=>command.startsWith(group))}export const SHORT_P_IS_NOT_PROJECT=["build","make","preview","serve","serve:api","share"];export function findProjectSelector(args,builtInCommands){const command=args[0];if(command===undefined||!(builtInCommands.has(command)||builtInCommands.has(command.split(":")[0])))return null;const flags=SHORT_P_IS_NOT_PROJECT.includes(command)?["--project"]:["--project","-p"];for(let index=0;index<args.length;index++){const arg=args[index];if(arg==="--")break;for(const flag of flags){if(arg===flag){const value=args[index+1];if(value!==undefined&&!value.startsWith("-"))return{value,index:index+1,attached:null}}else if(arg.startsWith(`${flag}=`)&&arg.length>flag.length+1){return{value:arg.slice(flag.length+1),index,attached:flag}}}}return null}export function projectAfterCommand(args){const first=args[0];if(first==="--project"||first==="-p"){const[,value,command,...rest]=args;if(value!==undefined&&!value.startsWith("-")&&command!==undefined&&!command.startsWith("-"))return[command,"--project",value,...rest];return args}const attached=first?.match(/^(?:--project|-p)=(.+)$/);if(attached&&args[1]!==undefined&&!args[1].startsWith("-"))return[args[1],"--project",attached[1],...args.slice(2)];return args}function samePath(a,b){try{return realpathSync(a)===realpathSync(b)}catch{return a===b}}function isExecutable(file){try{accessSync(file,constants.X_OK);return true}catch{return false}}function runsWithoutInstall(args){return args[0]==="install"}export function planInvocation(context){const{cwd}=context;const args=projectAfterCommand(context.args);const command=args[0];if(isMachineCommand(command))return{kind:"run",root:findProjectRoot(cwd),args};const selector=args!==context.args?{value:args[2],index:2,attached:null}:findProjectSelector(args,context.builtInCommands);let root;let forwarded=args;if(selector){const match=findProject(selector.value,cwd);if(!match.project){return{kind:"refuse",message:match.candidates.length>0?`"${selector.value}" matches more than one Stacks project: ${match.candidates.map((project)=>project.name).join(", ")}. Name one of them in full, or give its path.`:`No Stacks project matches "${selector.value}". Run \`buddy projects\` to see the ones on this machine, or give a path.`}}root=match.project.path;forwarded=selector.attached?args.toSpliced(selector.index,1):args.toSpliced(selector.index-1,2)}else{root=findProjectRoot(cwd)}if(!root)return{kind:"run",root:null,args};if(projectCliEntry(root)===null&&!runsWithoutInstall(forwarded)){const name=basename(root);return{kind:"refuse",message:`${name} has nothing installed yet, so it has no buddy of its own to run this. Install its dependencies first:
|
|
1
|
+
import{accessSync,constants,realpathSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{findProject,findProjectRoot,isCompiledBinary,isVisitingCli,noteProjectUsed,projectCliEntry}from"@stacksjs/path";import{isIsolatedRuntime,withoutIsolation}from"./runtime-flags";const MACHINE_COMMANDS=["new","create","projects","cd","daemon","dashboard","tray"];const MACHINE_COMMAND_GROUPS=["projects:","daemon:"];export function isMachineCommand(command){if(command===undefined)return false;return MACHINE_COMMANDS.includes(command)||MACHINE_COMMAND_GROUPS.some((group)=>command.startsWith(group))}export const SHORT_P_IS_NOT_PROJECT=["build","make","preview","serve","serve:api","share"];export function findProjectSelector(args,builtInCommands){const command=args[0];if(command===undefined||!(builtInCommands.has(command)||builtInCommands.has(command.split(":")[0])))return null;const flags=SHORT_P_IS_NOT_PROJECT.includes(command)?["--project"]:["--project","-p"];for(let index=0;index<args.length;index++){const arg=args[index];if(arg==="--")break;for(const flag of flags){if(arg===flag){const value=args[index+1];if(value!==undefined&&!value.startsWith("-"))return{value,index:index+1,attached:null}}else if(arg.startsWith(`${flag}=`)&&arg.length>flag.length+1){return{value:arg.slice(flag.length+1),index,attached:flag}}}}return null}export function projectAfterCommand(args){const first=args[0];if(first==="--project"||first==="-p"){const[,value,command,...rest]=args;if(value!==undefined&&!value.startsWith("-")&&command!==undefined&&!command.startsWith("-"))return[command,"--project",value,...rest];return args}const attached=first?.match(/^(?:--project|-p)=(.+)$/);if(attached&&args[1]!==undefined&&!args[1].startsWith("-"))return[args[1],"--project",attached[1],...args.slice(2)];return args}function samePath(a,b){try{return realpathSync(a)===realpathSync(b)}catch{return a===b}}function isExecutable(file){try{accessSync(file,constants.X_OK);return true}catch{return false}}function runsWithoutInstall(args){return args[0]==="install"}export function planInvocation(context){const{cwd}=context;const args=projectAfterCommand(context.args);const command=args[0];if(isMachineCommand(command))return{kind:"run",root:findProjectRoot(cwd),args};const selector=args!==context.args?{value:args[2],index:2,attached:null}:findProjectSelector(args,context.builtInCommands);let root;let forwarded=args;if(selector){const match=findProject(selector.value,cwd);if(!match.project){return{kind:"refuse",message:match.candidates.length>0?`"${selector.value}" matches more than one Stacks project: ${match.candidates.map((project)=>project.name).join(", ")}. Name one of them in full, or give its path.`:`No Stacks project matches "${selector.value}". Run \`buddy projects\` to see the ones on this machine, or give a path.`}}root=match.project.path;forwarded=selector.attached?args.toSpliced(selector.index,1):args.toSpliced(selector.index-1,2)}else{root=findProjectRoot(cwd)}if(!root)return{kind:"run",root:null,args};if(projectCliEntry(root)===null&&!runsWithoutInstall(forwarded)){const name=basename(root);return{kind:"refuse",message:`${name} has nothing installed yet, so it has no buddy of its own to run this. Install its dependencies first:
|
|
2
2
|
|
|
3
3
|
buddy install --project ${name}
|
|
4
4
|
`}}const projectHasCli=projectCliEntry(root)!==null;const needsProjectConfig=projectHasCli&&isIsolatedRuntime(context.execArgv);if(context.handedRoot&&samePath(context.handedRoot,root)&&samePath(cwd,root)&&!needsProjectConfig)return{kind:"run",root,args:forwarded};if(isVisitingCli(root,context.main)){const shim=join(root,"buddy");return{kind:"handoff",root,command:isExecutable(shim)?[shim,...forwarded]:[process.execPath,projectCliEntry(root),...forwarded]}}if(!samePath(cwd,root)||needsProjectConfig){const execArgv=projectHasCli?withoutIsolation(context.execArgv):context.execArgv;const self=isCompiledBinary(context.main)?[process.execPath]:[process.execPath,...execArgv,context.main];return{kind:"handoff",root,command:[...self,...forwarded]}}return{kind:"run",root,args:forwarded}}export const HANDED_ROOT_ENV="STACKS_BUDDY_ROOT";function handOff(root,command){const env={...process.env,[HANDED_ROOT_ENV]:root};process.chdir(root);if(typeof process.execve==="function")process.execve(command[0],command,env);const child=Bun.spawnSync(command,{cwd:root,env,stdin:"inherit",stdout:"inherit",stderr:"inherit"});process.exit(child.exitCode??1)}export function launch(context){const invocation=planInvocation(context);if(invocation.kind==="refuse"){process.stderr.write(`${invocation.message}
|
package/dist/lazy-commands.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==undefined)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},daemon:{path:"./commands/daemon.js",load:()=>import("./commands/daemon.js"),exportName:"daemon"},dashboard:{path:"./commands/dashboard.js",load:()=>import("./commands/dashboard.js"),exportName:"dashboard"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:update:keypair":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"release:desktop":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"hq:connect":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"support:install":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"support:doctor":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"hq:status":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"hq:sync":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},license:{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},"license:keygen":{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:audit":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},screenshot:{path:"./commands/screenshot.js",load:()=>import("./commands/screenshot.js"),exportName:"screenshot"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},"workflow:setup":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:step":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:release-state":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:runs":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:show":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:run":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:artifacts":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:screenshots":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:stories":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}};const commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]};const loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader){return false}let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return true;set.add(key);try{const module=await loader.load();const commandFunction=module[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return true}else{return false}}catch{return false}}export async function loadCommands(commandNames,buddy){const seen=new Set;const unique=[];for(const name of commandNames){const loader=commandRegistry[name];const key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands){await loadCommands(commands,buddy)}}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0];const isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v";const isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h";const isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list"){return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")]}if(commandRegistry[requestedCommand]){return[requestedCommand]}if(commandRegistry[baseCommand]){return[baseCommand]}return Object.keys(commandRegistry)}
|
|
1
|
+
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==undefined)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},daemon:{path:"./commands/daemon.js",load:()=>import("./commands/daemon.js"),exportName:"daemon"},dashboard:{path:"./commands/dashboard.js",load:()=>import("./commands/dashboard.js"),exportName:"dashboard"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:update:keypair":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"release:desktop":{path:"./commands/desktop-release.js",load:()=>import("./commands/desktop-release.js"),exportName:"desktopRelease"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"hq:connect":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"support:install":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"support:doctor":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"hq:status":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},"hq:sync":{path:"./commands/hq.js",load:()=>import("./commands/hq.js"),exportName:"hq"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},license:{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},"license:keygen":{path:"./commands/license.js",load:()=>import("./commands/license.js"),exportName:"license"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:audit":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},tray:{path:"./commands/tray.js",load:()=>import("./commands/tray.js"),exportName:"tray"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},screenshot:{path:"./commands/screenshot.js",load:()=>import("./commands/screenshot.js"),exportName:"screenshot"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},"workflow:setup":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:step":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:release-state":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:runs":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:show":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:run":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},"workflow:artifacts":{path:"./commands/workflow.js",load:()=>import("./commands/workflow.js"),exportName:"workflow"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:screenshots":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:stories":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:style-guide:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}};const commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]};const loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader){return false}let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return true;set.add(key);try{const module=await loader.load();const commandFunction=module[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return true}else{return false}}catch{return false}}export async function loadCommands(commandNames,buddy){const seen=new Set;const unique=[];for(const name of commandNames){const loader=commandRegistry[name];const key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands){await loadCommands(commands,buddy)}}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0];const isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v";const isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h";const isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list"){return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")]}if(commandRegistry[requestedCommand]){return[requestedCommand]}if(commandRegistry[baseCommand]){return[baseCommand]}return Object.keys(commandRegistry)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{clearShownFormFlash,enterRequestScope,feature,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const candidates=["resources/partials","resources/views/partials","partials","resources/components"];const existing=candidates.filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:true})].length>0}catch{return false}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const mod=await import(configPath);const dir=mod.default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts";const vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000;const{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server");const{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources");const{stxPageAuthMiddleware}=await import("@stacksjs/auth");const{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router");const pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:false})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing"){await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError)}if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else{({serve:stxServe}=await import("bun-plugin-stx/serve"))}log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule();const{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig();const userViewsPath="resources/views";const defaultsResources=resolveDefaultsResources();const defaultViewsPath=join(defaultsResources,"views");const userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts";const userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components";const userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir());const apiBase=resolveApiBase(config.ports?.api);const{mountedDefaultRouteBundles}=await import("@stacksjs/router");const viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,undefined,undefined,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo");const seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url};const siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache;const documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port,autoIncrementPort:false,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==true,...cacheConfig?.renders&&{renderCache:true,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:true}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server");const gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url);const redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,undefined,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog");const feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews){import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{})}if(config.sites?.enabled){const sites=await import("@stacksjs/sites");const siteHost=sites.requestHost(req.headers,sites.sitesOptions());const resolved=await sites.resolveSiteByHost(siteHost);sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved);if(siteHost)snapshot.siteHost=siteHost}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules);const secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse;const method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD"){finishRequestCapture(req,secured??response);return secured}const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled&&feature("cms")){try{const{cmsNotFoundFallback}=await import("@stacksjs/cms");const cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}const shown=clearShownFormFlash(req,finished??response,config.app?.key);if(shown!==(finished??response))finished=shown;if(!documentCacheControl){finishRequestCapture(req,finished??response);return finished}const cached=applyDocumentCacheControl(req,finished??response,documentCacheControl);finishRequestCapture(req,cached??finished??response);return cached}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0);const parts=[`public`,`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return true;const cookie=request.headers.get("cookie")||"";if(!cookie)return false;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router";const SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing"){await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError)}if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales;const defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath);const site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{clearShownFormFlash,enterRequestScope,feature,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const candidates=["resources/partials","resources/views/partials","partials","resources/components"];const existing=candidates.filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:true})].length>0}catch{return false}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const mod=await import(configPath);const dir=mod.default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts";const vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000;const hostname=process.env.HOST?.trim()||undefined;const{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server");const{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources");const{stxPageAuthMiddleware}=await import("@stacksjs/auth");const{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router");const pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:false})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing"){await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError)}if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else{({serve:stxServe}=await import("bun-plugin-stx/serve"))}log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule();const{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig();const userViewsPath="resources/views";const defaultsResources=resolveDefaultsResources();const defaultViewsPath=join(defaultsResources,"views");const userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts";const userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components";const userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir());const apiBase=resolveApiBase(config.ports?.api);const{mountedDefaultRouteBundles}=await import("@stacksjs/router");const viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,undefined,undefined,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo");const seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url};const siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache;const documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,hostname,port,autoIncrementPort:false,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==true,...cacheConfig?.renders&&{renderCache:true,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:true}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server");const gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url);const redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,undefined,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog");const feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews){import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{})}if(config.sites?.enabled){const sites=await import("@stacksjs/sites");const siteHost=sites.requestHost(req.headers,sites.sitesOptions());const resolved=await sites.resolveSiteByHost(siteHost);sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved);if(siteHost)snapshot.siteHost=siteHost}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules);const secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse;const method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD"){finishRequestCapture(req,secured??response);return secured}const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled&&feature("cms")){try{const{cmsNotFoundFallback}=await import("@stacksjs/cms");const cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}const shown=clearShownFormFlash(req,finished??response,config.app?.key);if(shown!==(finished??response))finished=shown;if(!documentCacheControl){finishRequestCapture(req,finished??response);return finished}const cached=applyDocumentCacheControl(req,finished??response,documentCacheControl);finishRequestCapture(req,cached??finished??response);return cached}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0);const parts=[`public`,`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return true;const cookie=request.headers.get("cookie")||"";if(!cookie)return false;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router";const SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing"){await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError)}if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales;const defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath);const site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { createSystemSampler } from './system';
|
|
2
|
+
import type { createTrayPantry } from './pantry';
|
|
3
|
+
import type { DaemonStatus } from '@stacksjs/actions/daemon/server';
|
|
4
|
+
import type { RegisteredProject } from '@stacksjs/path';
|
|
5
|
+
export declare function traySnapshot(status: DaemonStatus | null, projects: RegisteredProject[]): {
|
|
6
|
+
online: boolean;
|
|
7
|
+
watched: {} | number;
|
|
8
|
+
running: boolean;
|
|
9
|
+
failed: unknown;
|
|
10
|
+
projects: ReturnType<(RegisteredProject[])["map"]>
|
|
11
|
+
};
|
|
12
|
+
export declare function createTrayApi(token: string, services: TrayServices, documentOrigin: string): (request: Request, origin: string) => Promise<Response>;
|
|
13
|
+
declare interface TrayServices {
|
|
14
|
+
status: () => Promise<DaemonStatus | null>
|
|
15
|
+
projects: () => RegisteredProject[]
|
|
16
|
+
start: () => Promise<unknown>
|
|
17
|
+
dashboard: (project: RegisteredProject) => Promise<void>
|
|
18
|
+
review: (project: RegisteredProject) => Promise<void>
|
|
19
|
+
quit: () => void
|
|
20
|
+
system: ReturnType<typeof createSystemSampler>
|
|
21
|
+
pantry: ReturnType<typeof createTrayPantry>
|
|
22
|
+
}
|
|
23
|
+
export {};
|
package/dist/tray/api.js
ADDED
|
@@ -0,0 +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)}}}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function createTrayPantry(): {
|
|
2
|
+
status: () => Promise<unknown>;
|
|
3
|
+
catalog: (query: string) => unknown;
|
|
4
|
+
jobs: () => Promise<unknown>;
|
|
5
|
+
pair: (code: string) => Promise<void>;
|
|
6
|
+
change: (operation: 'install' | 'uninstall', domain: string, requestId: string) => Promise<{
|
|
7
|
+
id: unknown;
|
|
8
|
+
domain: unknown;
|
|
9
|
+
status: unknown;
|
|
10
|
+
operation: unknown;
|
|
11
|
+
error: unknown
|
|
12
|
+
}>;
|
|
13
|
+
disconnect: () => Promise<void>
|
|
14
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{secrets}from"bun";import{bundledPackageCatalog,createPackageCatalogSearch}from"ts-pantry/catalog";import{PantryDesktopClient,PantryDesktopError}from"ts-pantry/desktop";const credential={service:"com.stacksjs.buddy.tray",name:"Pantry Desktop"};export function createTrayPantry(){let connection;let search;const client=(token)=>new PantryDesktopClient({token,fetch:(url,init)=>fetch(url,{...init,redirect:"error",signal:AbortSignal.timeout(4000)})});const readToken=()=>connection??=secrets.get(credential).catch((error)=>{connection=undefined;throw error});async function connected(){const token=await readToken();if(!token)throw new PantryDesktopError("Pair Pantry with Buddy first.",401);return client(token)}async function jobs(bridge){const records=await bridge.jobs();return records.map(({id,domain,status,operation,error})=>({id,domain,status,operation,error}))}return{async status(){try{const health=await client().health();const capabilities=Array.isArray(health.capabilities)?health.capabilities:[];if(!await readToken())return{state:"pair"};const bridge=await connected();const[packages,recentJobs]=await Promise.all([bridge.installed(),jobs(bridge)]);return{state:"ready",packages,jobs:recentJobs,removal:capabilities.includes("uninstall:user")}}catch(error){if(error instanceof PantryDesktopError&&error.status===401)return{state:"pair"};return{state:"offline",issue:error instanceof Error?error.message:"Pantry is unavailable."}}},catalog(query){search??=createPackageCatalogSearch(bundledPackageCatalog());return search(query,{limit:8}).map(({domain,name})=>({domain,name}))},async jobs(){return jobs(await connected())},async pair(code){const bridge=client();const token=await bridge.pair(code,"Buddy");try{await secrets.set({...credential,value:token});connection=Promise.resolve(token)}catch(error){await client(token).disconnect().catch(()=>{});throw error}},async change(operation,domain,requestId){const bridge=await connected();const job=await(operation==="install"?bridge.install(domain,requestId):bridge.uninstall(domain,requestId));return{id:job.id,domain:job.domain,status:job.status,operation:job.operation,error:job.error}},async disconnect(){const bridge=await connected();await bridge.disconnect();connection=Promise.resolve(null);await secrets.delete(credential)}}}
|