@stacksjs/buddy 0.75.617 → 0.75.621

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.
@@ -56,6 +56,6 @@ export declare function offlineReason(fetcher?: typeof fetch): Promise<string |
56
56
  * scaffolding a week apart get the same app rather than whatever main happened
57
57
  * to be.
58
58
  */
59
- export declare function templateRef(fetchVersions?: typeof fetchPublishedVersions): Promise<string | null>;
59
+ export declare function templateRef(fetchVersions?: typeof fetchPublishedVersions, requested?: string): Promise<string | null>;
60
60
  /** The gitit spec for a template ref, or the default branch when there is none. */
61
61
  export declare function templateSpec(ref: string | null): string;
@@ -1 +1 @@
1
- import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{isCompiledBinary,relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{attemptPantryDependencies,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageOverrides,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{commitScaffold}from"../scaffold-git";import{bunExecutable,failureReason,installScaffoldDependencies}from"../scaffold-dependencies";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:false}).option("-m, --minimal",descriptions.minimal,{default:false}).option("--native","Create a minimal offline Craft desktop app",{default:false}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:false}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:false}).option("--with-core",descriptions.withCore,{default:false}).option("--vendor-defaults",descriptions.vendorDefaults,{default:false}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw new Error("--adopt requires --native");if(options.desktop&&options.native)throw new Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project");const{version}=await import("../../package.json");const{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw new Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);const missingSystemDependencies=await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);const createdRepository=await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options,missingSystemDependencies!==null);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(createdRepository)recordScaffold(path);if(missingSystemDependencies!==null){log.warn(`The app is scaffolded at ${path}, but Pantry could not install its system dependencies: ${missingSystemDependencies}`);log.warn(`Finish with: ${cyan(`cd ${name??"."} && pantry install`)}`);log.warn(`Its JavaScript packages were installed with ${cyan("bun install")} instead, so everything else is ready.`);await log.flush();process.exit(ExitCode.FatalError)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! ⚛️"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions){try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,_options){log.info("Setting up your stack.");const ref=await templateRef();try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:true})}catch(error){if(!ref)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:true})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:false}}catch(error){return{isErr:true,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github");const destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:true,force:true});cpSync(source,destination,{recursive:true});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config");const destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path);const changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:true,force:true})}log.success("App starts with a clean test suite")}function recordScaffold(path){const reason=commitScaffold(path,appIdentity(path).displayName);if(reason===null)log.success("Committed the generated app");else log.warn(`Left the generated app uncommitted (${reason}). Make the first commit yourself.`)}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"]){try{chmodSync(resolve(path,script),493)}catch{}}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===false){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return null}const outcome=await installScaffoldDependencies({pantry:async()=>{const failure=await attemptPantryDependencies(path);return failure===null?null:failureReason(failure.error)},hasNodeModules:()=>existsSync(resolve(path,"node_modules")),bunInstall:async()=>{const bun=bunExecutable(Bun.which("bun"),process.execPath,isCompiledBinary());if(bun===null)return"Bun is not on PATH, and this buddy is a compiled binary, so it cannot run Bun itself.";log.info("Installing the JavaScript packages with Bun...");const result=await runCommand([bun,"install"],{cwd:path});return resultFailed(result)?failureReason(result.error):null}});if(outcome.status==="complete"){log.success("Environment is ready");return null}if(outcome.status==="system-dependencies-missing"){log.warn(`Pantry could not install the system dependencies (${outcome.pantryFailure}). Continuing with the JavaScript packages Bun installed.`);return outcome.pantryFailure}if(outcome.pantryFailure!==null)await log.error(`Pantry could not install the dependencies: ${outcome.pantryFailure}`);await log.error(`Bun could not install the JavaScript packages either: ${outcome.bunFailure}`);await log.error(`${path} is only partly scaffolded. Delete it and run \`buddy new\` again once the installers can reach their registries.`);process.exit(ExitCode.FatalError)}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example → .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:true});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}const createdRepository=!existsSync(resolve(path,".git"));if(!createdRepository){log.info("Existing git repository detected, skipping git init")}else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80");return createdRepository}async function unvendorCore(path,options,withBun){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const command=withBun?"./buddy unpublish:core --all --force --installer bun":"./buddy unpublish:core --all --force";const result=await runCommand(command,{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:true})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path);const scripts=applyAppPackageScripts(path);applyAppPackageOverrides(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path});const authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=false;for(const{feature,configOutcome,filesRemoved}of results){if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=true;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}}if(!strippedAny)log.info(" → no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
1
+ import{chmodSync,cpSync,existsSync,readFileSync,readdirSync,rmSync,writeFileSync}from"node:fs";import process from"node:process";import{runAction}from"@stacksjs/actions";import{bold,cyan,dim,intro,log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{isCompiledBinary,relative,resolve}from"@stacksjs/path";import{isFolder}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{uninstallAllFeatures}from"./features";import{attemptPantryDependencies,optimizePantryDeps}from"./setup";import{resultFailed}from"../result";import{appIdentity,applyAppAgentsTemplate,applyAppChangelogTemplate,applyAppEnvTemplate,applyAppPackageTemplate,removeFrameworkLicense,renderTemplate}from"../scaffold-app";import{applyAppSiteTemplate}from"../scaffold-site";import{adoptPackagedDefaults,applyAppPackageOverrides,applyAppPackageScripts,applyPackageAppTsconfig,pruneFrameworkOnlyFiles,rewriteCoreContentPaths,stripFrameworkManifestCredits}from"../scaffold-package-app";import{fetchPublishedVersions}from"../registry";import{ensureAuthRoutesEnv}from"../minimal-routes";import{scaffoldDesktopApp}from"../scaffold-desktop";import{commitScaffold}from"../scaffold-git";import{bunExecutable,failureReason,installScaffoldDependencies}from"../scaffold-dependencies";export function create(buddy){const descriptions={name:"The name of the project",command:"Create a new Stacks project",minimal:"Skip optional feature bundles (cms, commerce, dashboard, marketing, monitoring, realtime, queue) - bare-bones API/SPA starter that can re-add them later via `./buddy <feature>:install`.",withCore:"Keep the framework vendored in `storage/framework/core` as a Bun workspace, for working ON Stacks. Apps that only work WITH Stacks want the default, which resolves every @stacksjs/* package from npm.",vendorDefaults:"Commit a copy of the framework defaults in `storage/framework/defaults` instead of linking it to node_modules/@stacksjs/defaults. Implied by --with-core.",verbose:"Enable verbose output"};buddy.command("new [name]",descriptions.command).alias("create").option("-n, --name [name]",descriptions.name,{default:false}).option("-m, --minimal",descriptions.minimal,{default:false}).option("--native","Create a minimal offline Craft desktop app",{default:false}).option("--desktop","Also make it a native Mac app: stx screens drawn by AppKit, with the API running inside the app (config/desktop.ts, macos.agent)",{default:false}).option("--adopt","Integrate an existing native app without replacing its source (requires --native)",{default:false}).option("--with-core",descriptions.withCore,{default:false}).option("--vendor-defaults",descriptions.vendorDefaults,{default:false}).option("--no-provision","Install JavaScript dependencies without provisioning system packages").option("--ref <ref>","Scaffold from an explicit Stacks tag, branch or commit").option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy new <name>` ...",options);const startTime=await intro("buddy new");name=name??options.name;const path=resolve(process.cwd(),name??".");if(options.adopt&&!options.native)throw new Error("--adopt requires --native");if(options.desktop&&options.native)throw new Error("--desktop makes a Stacks app with a native Mac app; --native makes a standalone Craft app. Choose one.");if(options.native){const{scaffoldNativeProject}=await import("../native-project");const{version}=await import("../../package.json");const{latest}=await fetchPublishedVersions("@stacksjs/stx");if(!latest)throw new Error("The registry has no published stx version.");scaffoldNativeProject(path,{adopt:options.adopt,buddyVersion:version,stxVersion:latest});const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success(`Native app ready at ${path}. Run ./buddy dev to launch.`);await log.flush();return}isFolderCheck(path);await onlineCheck();const result=await download(name,path,options);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}ensureExecutableScripts(path);applyAppVcsTemplate(path);applyAppConfigTemplate(path);applyAppEnv(path);applyAppPackage(path);applyAppReadme(path);applyAppAgents(path);replaceFrameworkSite(path);removeFrameworkTests(path);await generatePantryDeps(path);const missingSystemDependencies=await ensureEnv(path,options);if(options.minimal)await stripFeatures(path);const createdRepository=await install(path,options);if(!options.withCore){trimFrameworkOnlyFiles(path);await unvendorCore(path,options,missingSystemDependencies!==null);applyPackageAppTsconfig(path);if(!options.vendorDefaults)linkFrameworkDefaults(path)}if(options.minimal||!options.withCore&&!options.vendorDefaults)await regenerateAutoImports(path,options);if(options.desktop){const written=scaffoldDesktopApp(path,appIdentity(path));log.success(`Added the Mac app (${written.join(", ")}). Run ${cyan("bun run dev:desktop")} to open it.`)}if(createdRepository)recordScaffold(path);if(missingSystemDependencies!==null){log.warn(`The app is scaffolded at ${path}, but Pantry could not install its system dependencies: ${missingSystemDependencies}`);log.warn(`Finish with: ${cyan(`cd ${name??"."} && pantry install`)}`);log.warn(`Its JavaScript packages were installed with ${cyan("bun install")} instead, so everything else is ready.`);await log.flush();process.exit(ExitCode.FatalError)}if(startTime){const time=performance.now()-startTime;log.success(dim(`[${time.toFixed(2)}ms] Completed`))}log.info(bold("Welcome to the Stacks Framework! ⚛️"));log.info(`Get started: ${cyan(`cd ${name}`)} and then ${cyan("./buddy dev")}`);log.info(`Run ${cyan("./buddy doctor")} anytime to check your setup`);log.info("To learn more, visit https://stacksjs.com");await log.flush();process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"new")}export function scaffoldTargetOccupants(path){if(!isFolder(path))return[];return readdirSync(path).filter((entry)=>entry!==".git")}function isFolderCheck(path){if(scaffoldTargetOccupants(path).length===0)return;console.error(`Path ${path} already exists`);process.exit(ExitCode.FatalError)}async function onlineCheck(){const offline=await offlineReason();if(!offline)return;log.info(`It appears you are disconnected from the internet (github.com: ${offline}).`);log.info("Creating a new project requires a brief internet connection to download the template and install dependencies.");await log.flush();process.exit(ExitCode.FatalError)}export async function offlineReason(fetcher=fetch){try{await fetcher("https://github.com",{method:"HEAD",signal:AbortSignal.timeout(3000)});return null}catch(error){return error instanceof Error?error.message:String(error)}}export async function templateRef(fetchVersions=fetchPublishedVersions,requested){if(requested!==undefined){if(typeof requested!=="string"||!/^[a-zA-Z0-9][\w./-]{0,199}$/.test(requested)||requested.includes("..")||requested.endsWith("/"))throw new Error("Choose a valid Stacks template ref");return requested}try{const{latest}=await fetchVersions("stacks");return latest?`v${latest}`:null}catch{return null}}export function templateSpec(ref){return ref?`gh:stacksjs/stacks#${ref}`:"gh:stacksjs/stacks"}async function download(name,path,options){log.info("Setting up your stack.");const ref=await templateRef(fetchPublishedVersions,options.ref);try{const{downloadTemplate}=await import("@stacksjs/gitit");try{await downloadTemplate(templateSpec(ref),{dir:name,force:true})}catch(error){if(!ref||options.ref!==undefined)throw error;log.warn(`No ${ref} tag to scaffold from (${error instanceof Error?error.message:String(error)}).`);log.info("Falling back to the default branch. If this app does not typecheck, that gap is why.");await downloadTemplate(templateSpec(null),{dir:name,force:true})}log.success(`Successfully scaffolded your project at ${cyan(path)}`);return{isErr:false}}catch(error){return{isErr:true,error:error instanceof Error?error.message:String(error)}}}function applyAppVcsTemplate(path){const source=resolve(path,"storage/framework/defaults/vcs/github");const destination=resolve(path,".github");if(!existsSync(source)){log.warn("No app CI template found at storage/framework/defaults/vcs/github - leaving .github as downloaded.");return}log.info("Installing app-shaped GitHub workflows...");try{rmSync(destination,{recursive:true,force:true});cpSync(source,destination,{recursive:true});log.success("App CI installed")}catch(error){log.warn(`Could not install the app CI template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppConfigTemplate(path){const source=resolve(path,"storage/framework/defaults/scaffold/config");const destination=resolve(path,"config");if(!existsSync(source)){log.warn("No app config template found at storage/framework/defaults/scaffold/config - leaving config as downloaded.");return}const identity=appIdentity(path);log.info("Installing app-safe infrastructure configuration...");try{for(const file of readdirSync(source)){if(!file.endsWith(".ts"))continue;const template=readFileSync(resolve(source,file),"utf8");writeFileSync(resolve(destination,file),renderTemplate(template,identity))}log.success("App-safe infrastructure configuration installed")}catch(error){log.warn(`Could not install the app config template: ${error instanceof Error?error.message:String(error)}`)}}function applyAppEnv(path){try{const changed=applyAppEnvTemplate(path,appIdentity(path));if(changed.length>0)log.success(`Named the app in .env.example (${changed.join(", ")})`)}catch(error){log.warn(`Could not name the app in .env.example: ${error instanceof Error?error.message:String(error)}`)}}function applyAppPackage(path){try{const identity=appIdentity(path);const changed=applyAppPackageTemplate(path,identity);if(changed.length>0)log.success(`Named the app in package.json (${changed.join(", ")})`);if(applyAppChangelogTemplate(path,identity))log.success("Started the app its own CHANGELOG.md");if(removeFrameworkLicense(path))log.success("Removed the framework's LICENSE.md - choose the app's own licence")}catch(error){log.warn(`Could not name the app in package.json: ${error instanceof Error?error.message:String(error)}`)}}function applyAppAgents(path){try{if(applyAppAgentsTemplate(path))log.success("AGENTS.md no longer tells agents to publish as the framework's author")}catch(error){log.warn(`Could not update AGENTS.md: ${error instanceof Error?error.message:String(error)}`)}}function applyAppReadme(path){const source=resolve(path,"storage/framework/defaults/scaffold/README.md");if(!existsSync(source))return;try{writeFileSync(resolve(path,"README.md"),renderTemplate(readFileSync(source,"utf8"),appIdentity(path)))}catch(error){log.warn(`Could not write the app README: ${error instanceof Error?error.message:String(error)}`)}}function replaceFrameworkSite(path){log.info("Replacing the stacksjs.com site with a starter page...");try{const removed=applyAppSiteTemplate(path);log.success(`Starter page installed (${removed.length} stacksjs.com path${removed.length===1?"":"s"} removed)`)}catch(error){log.warn(`Could not install the starter page: ${error instanceof Error?error.message:String(error)}`)}}function removeFrameworkTests(path){const tests=resolve(path,"tests");if(!existsSync(tests))return;log.info("Removing the framework's own test suite...");for(const entry of readdirSync(tests)){if(entry==="setup.ts")continue;rmSync(resolve(tests,entry),{recursive:true,force:true})}log.success("App starts with a clean test suite")}function recordScaffold(path){const reason=commitScaffold(path,appIdentity(path).displayName);if(reason===null)log.success("Committed the generated app");else log.warn(`Left the generated app uncommitted (${reason}). Make the first commit yourself.`)}function ensureExecutableScripts(path){for(const script of["buddy","bootstrap"]){try{chmodSync(resolve(path,script),493)}catch{}}}async function ensureEnv(path,options){log.info("Ensuring your environment is ready...");if(options.provision===false){const installed=await runCommand(["bun","install"],{cwd:path});if(resultFailed(installed))throw installed.error;log.success("JavaScript dependencies installed; system provisioning skipped");return null}const outcome=await installScaffoldDependencies({pantry:async()=>{const failure=await attemptPantryDependencies(path);return failure===null?null:failureReason(failure.error)},hasNodeModules:()=>existsSync(resolve(path,"node_modules")),bunInstall:async()=>{const bun=bunExecutable(Bun.which("bun"),process.execPath,isCompiledBinary());if(bun===null)return"Bun is not on PATH, and this buddy is a compiled binary, so it cannot run Bun itself.";log.info("Installing the JavaScript packages with Bun...");const result=await runCommand([bun,"install"],{cwd:path});return resultFailed(result)?failureReason(result.error):null}});if(outcome.status==="complete"){log.success("Environment is ready");return null}if(outcome.status==="system-dependencies-missing"){log.warn(`Pantry could not install the system dependencies (${outcome.pantryFailure}). Continuing with the JavaScript packages Bun installed.`);return outcome.pantryFailure}if(outcome.pantryFailure!==null)await log.error(`Pantry could not install the dependencies: ${outcome.pantryFailure}`);await log.error(`Bun could not install the JavaScript packages either: ${outcome.bunFailure}`);await log.error(`${path} is only partly scaffolded. Delete it and run \`buddy new\` again once the installers can reach their registries.`);process.exit(ExitCode.FatalError)}async function install(path,options){log.info("Installing & setting up Stacks");log.info("Copying .env.example → .env");let result=await runCommand("cp .env.example .env",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}log.info("Removing template-encrypted env files...");const{rm}=await import("node:fs/promises");for(const stale of[".env.development",".env.staging",".env.production",".env.keys"])await rm(`${path}/${stale}`,{force:true});log.info("Generating application key...");const keyResult=await runAction(Action.KeyGenerate,{...options,cwd:path});if(resultFailed(keyResult)){await log.error(keyResult.error);process.exit(ExitCode.FatalError)}const createdRepository=!existsSync(resolve(path,".git"));if(!createdRepository){log.info("Existing git repository detected, skipping git init")}else{log.info("Initializing git repository...");result=await runCommand("git init",{...options,cwd:path});if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}}log.success("Installed & set-up \uD83D\uDE80");return createdRepository}async function unvendorCore(path,options,withBun){log.info("Resolving the framework from npm (pass --with-core to keep it vendored)...");const command=withBun?"./buddy unpublish:core --all --force --installer bun":"./buddy unpublish:core --all --force";const result=await runCommand(command,{...options,cwd:path});if(resultFailed(result)){const reason=result.error instanceof Error?result.error.stack??result.error.message:String(result.error??"").trim();log.error("Could not resolve the framework from npm.");log.error(reason.length>0?reason:"The step failed without reporting a reason.");log.error("");log.error(`The project at ${path} is half converted: the vendored framework has been`);log.error("removed and the published packages are not in place yet, so ./buddy cannot");log.error("boot there. Finish it by hand with:");log.error("");await log.error(` cd ${path} && rm -f node_modules/stacks && bun install`);await log.error("");await log.error("Or start over with `--with-core` to keep the framework vendored.");process.exit(ExitCode.FatalError)}log.success("Framework resolved from npm")}async function generatePantryDeps(path){try{if(await optimizePantryDeps(path))rmSync(resolve(path,"deps.yml"),{force:true})}catch(error){log.warn(`Could not generate deps.yaml from config/deps.ts, keeping the template's deps.yml: ${error instanceof Error?error.message:String(error)}`)}}function trimFrameworkOnlyFiles(path){try{const removed=pruneFrameworkOnlyFiles(path);const scripts=applyAppPackageScripts(path);applyAppPackageOverrides(path);rewriteCoreContentPaths(path);stripFrameworkManifestCredits(path);log.success(`Removed ${removed.length} framework-only path${removed.length===1?"":"s"} and ${scripts.removed.length} framework-only script${scripts.removed.length===1?"":"s"}`)}catch(error){log.warn(`Could not remove the framework-only files: ${error instanceof Error?error.message:String(error)}`)}}function linkFrameworkDefaults(path){log.info("Linking the framework defaults from node_modules (pass --vendor-defaults to commit a copy)...");try{const adopted=adoptPackagedDefaults(path);log.success(`storage/framework/defaults now links to ${relative(path,adopted.packageRoot)}`)}catch(error){log.warn(`Could not move the framework defaults to node_modules: ${error instanceof Error?error.message:String(error)}`)}}async function regenerateAutoImports(path,options){const result=await runCommand("./buddy generate --types",{...options,cwd:path});if(resultFailed(result))log.warn("Could not regenerate the auto-import barrels. Run `./buddy generate --types` in the project before `./buddy dev`.")}async function stripFeatures(path){log.info("Stripping optional feature bundles (--minimal)...");const results=await uninstallAllFeatures({root:path});const authEnv=ensureAuthRoutesEnv(path);if(authEnv.length>0)log.info(` - kept the auth routes mounted (STACKS_DEFAULT_ROUTES=auth in ${authEnv.join(", ")})`);let strippedAny=false;for(const{feature,configOutcome,filesRemoved}of results){if(configOutcome==="flipped"||filesRemoved.length>0){strippedAny=true;const fileSummary=filesRemoved.length>0?` (${filesRemoved.length} path${filesRemoved.length===1?"":"s"})`:"";log.info(` - ${feature}${fileSummary}`)}}if(!strippedAny)log.info(" → no feature scaffolding present; nothing to strip.");else log.success("Minimal skeleton ready - run `./buddy <feature>:install` to add features back.")}
@@ -4,7 +4,7 @@ ${lines.join(`
4
4
  ${remedy}`);return false}log.warn(message);log.info(remedy);return true}catch(err){log.debug(`[migrate] duplicate migration number check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}async function reportHandWrittenMigrations(options={}){try{const{handWrittenMigrations}=await import("@stacksjs/database");const{files}=await handWrittenMigrations();if(files.length===0)return true;log.warn(`${files.length} hand-written migration${files.length===1?"":"s"} - no \`-- qb:generated\` marker, so the models do not describe ${files.length===1?"it":"them"}${options.list?`:
5
5
  ${files.slice(0,20).map((file)=>` • ${file}`).join(`
6
6
  `)}${files.length>20?`
7
- • … +${files.length-20} more`:""}`:" (`./buddy migrate:status` lists them)."}`);log.info(" Move the change into app/Models and regenerate (`./buddy migrate:regenerate`), or allow the file in database.safety.allowHandWrittenMigrations.");return false}catch(err){log.debug(`[migrate] hand-written migration check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}export function generatesMigrations(flag,interactive){return flag??interactive}function strictMode(options){return options.strict===true||process.env.STACKS_MIGRATE_STRICT==="1"}async function addMissingEnumLabels(){try{const{alignSchema,ENUM_ALIGN_KINDS}=await import("@stacksjs/database");const result=await alignSchema({apply:true,only:ENUM_ALIGN_KINDS});for(const action of result.plan.actions)log.info(` ${action.detail}`);if(result.applied.length>0)log.success(`Added ${result.applied.length} enum label${result.applied.length===1?"":"s"} the models declare and the database was missing.`)}catch(err){log.warn(`Could not check enum labels against the models: ${err instanceof Error?err.message:String(err)}`)}}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database");const result=await auditForeignKeys();if(result.absentTable.length>0){log.debug(`[migrate] ${result.absentTable.length} declared foreign key(s) belong to tables that are not in this database (${[...new Set(result.absentTable.map((fk)=>fk.fromTable))].join(", ")}); not reported as missing.`)}if(result.missing.length===0)return;const sample=result.missing.slice(0,5).map((fk)=>` • ${fk.fromTable}.${fk.fromColumn} → ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
7
+ • … +${files.length-20} more`:""}`:" (`./buddy migrate:status` lists them)."}`);log.info(" Move the change into app/Models and regenerate (`./buddy migrate:regenerate`), or allow the file in database.safety.allowHandWrittenMigrations.");return false}catch(err){log.debug(`[migrate] hand-written migration check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}export function generatesMigrations(flag,interactive){return flag??interactive}function logLedgerChanges(fixed,level){const changes=[[`Retired ${fixed.retired.length} ledger row(s) for migrations a regeneration replaced:`,[...fixed.retired]],[`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file:`,fixed.remapped.map((r)=>`${r.from} -> ${r.to}`)],[`Recorded ${fixed.recorded.length} migration(s) the schema already reflects, so they will not run:`,[...fixed.recorded]],[`Pruned ${fixed.pruned.length} duplicate ledger row(s); each stays recorded under its current name:`,[...fixed.pruned]],[`Un-recorded ${fixed.requeued.length} migration(s) so the next \`./buddy migrate\` rebuilds the missing table(s):`,[...fixed.requeued]]];for(const[heading,rows]of changes){if(rows.length===0)continue;log[level](heading);for(const row of rows)log.info(` ${row}`)}}function strictMode(options){return options.strict===true||process.env.STACKS_MIGRATE_STRICT==="1"}async function addMissingEnumLabels(){try{const{alignSchema,ENUM_ALIGN_KINDS}=await import("@stacksjs/database");const result=await alignSchema({apply:true,only:ENUM_ALIGN_KINDS});for(const action of result.plan.actions)log.info(` ${action.detail}`);if(result.applied.length>0)log.success(`Added ${result.applied.length} enum label${result.applied.length===1?"":"s"} the models declare and the database was missing.`)}catch(err){log.warn(`Could not check enum labels against the models: ${err instanceof Error?err.message:String(err)}`)}}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database");const result=await auditForeignKeys();if(result.absentTable.length>0){log.debug(`[migrate] ${result.absentTable.length} declared foreign key(s) belong to tables that are not in this database (${[...new Set(result.absentTable.map((fk)=>fk.fromTable))].join(", ")}); not reported as missing.`)}if(result.missing.length===0)return;const sample=result.missing.slice(0,5).map((fk)=>` • ${fk.fromTable}.${fk.fromColumn} → ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
8
8
  `);const more=result.missing.length>5?`
9
9
  + ${result.missing.length-5} more - run \`./buddy doctor\` for the full list.`:"";log.warn(`${result.missing.length} of ${result.declared.length} declared foreign keys are missing from the live schema:
10
10
  ${sample}${more}
@@ -95,8 +95,8 @@ ${unrebuildable.map((t)=>` ${t}`).join(`
95
95
  • ${removed.length} existing file(s) will be removed${obsoleteBlock}${dataOnlyBlock}${dataBlock}${protectedHistoryBlock}${outOfScopeBlock}${unrebuildableBlock}
96
96
  • These files are tracked in git, so review with \`git diff\` afterwards
97
97
  ─────────────────────────────────────────────
98
- `);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Replace ${removed.length} migration file(s) with ${files.length} generated for ${target}?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}const result=await regenerateMigrationCorpus({dialect:target,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(result)){log.syncError(result.error.message);process.exit(ExitCode.FatalError)}log.success(`Wrote ${result.value.files.length} ${target} migration file(s) to ${relativeMigrationDirectory(result.value.dir)}.`);const recordedNow=applied>0?applied:await countAppliedMigrations().catch(()=>0);if(recordedNow>0){const{reconcileMigrationLedger}=await import("@stacksjs/database");const fixed=await reconcileMigrationLedger({regenerated:{removed:result.value.removed,written:result.value.files.map((file)=>file.name)}});if(fixed.remapped.length>0)log.info(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.recorded.length>0)log.info(`Recorded ${fixed.recorded.length} regenerated migration(s) whose every table, index and type the schema already has - they will not run.`);if(fixed.retired.length>0)log.info(`Retired ${fixed.retired.length} ledger row(s) for migrations the regenerated corpus replaced.`);if(fixed.pruned.length>0)log.info(`Pruned ${fixed.pruned.length} duplicate ledger row(s).`);if(fixed.skipped.length>0){log.warn(`${fixed.skipped.length} ledger entr(ies) need a look:`);for(const entry of fixed.skipped.slice(0,10))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>10)log.info(` … +${fixed.skipped.length-10} more - run \`./buddy migrate:status\``)}log.info("This database has history. Before `./buddy migrate`, bring its schema in line with the models:");log.info(" ./buddy migrate:align # what differs, and what can be repaired safely");log.info(" ./buddy migrate:align --apply # rename legacy indexes, add missing indexes and foreign keys");log.info(" ./buddy migrate:status --reconcile # record the regenerated files the schema now satisfies")}log.info("Review the change with `git diff`, then run `./buddy migrate`.");await outro("Regenerated.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:align","Repair a live database that drifted from the models, without writing migrations (PostgreSQL)").option("--apply","Run the safe repairs, in one transaction",{default:false}).option("--widen-integers","Also widen integer columns the models declare as bigint (rewrites those tables)",{default:false}).option("--relax-constraints","Also remove obsolete NOT NULL constraints, polymorphic foreign keys, and conflicting keys with an enforced model reference",{default:false}).option("-f, --force","With --apply, skip the confirmation",{default:false}).option("--json","Emit the plan as JSON",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:align");const{alignSchema}=await import("@stacksjs/database");let planned;try{planned=await alignSchema({widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints})}catch(error){log.syncError(`Could not compare the database with the models: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}if(options.json){console.log(JSON.stringify(planned,null,2));process.exit(ExitCode.Success)}if(!planned.supported){await log.info(`migrate:align is not supported for "${planned.dialect}" yet - only PostgreSQL. Nothing was compared.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{actions,reports,refused}=planned.plan;const report=["",` Align plan: ${planned.dialect}`," ─────────────────────────────────────────────"];if(actions.length>0){report.push(` ${actions.length} safe repair(s)${options.apply?"":" - run with --apply to make them, in one transaction"}:`);for(const action of actions)report.push(` • ${action.detail}`,` ${action.sql};`);report.push("")}if(refused.length>0){report.push(` ${refused.length} repair(s) REFUSED - the data would violate them:`);for(const action of refused)report.push(` • ${action.detail}: ${action.reason}`);report.push("")}if(reports.length>0){report.push(` ${reports.length} difference(s) left for you to decide - destructive or ambiguous, never applied:`);for(const item of reports.slice(0,40))report.push(` • [${item.kind}] ${item.detail}`);if(reports.length>40)report.push(` … +${reports.length-40} more (--json lists all)`);report.push("")}if(actions.length===0&&refused.length===0&&reports.length===0)report.push(" The database matches the models.","");console.log(report.join(`
99
- `));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(refused.length>0?ExitCode.FatalError:ExitCode.Success)}if(!options.force&&!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Apply ${actions.length} repair(s) to the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}"?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}try{const applied=await alignSchema({apply:true,widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints});await log.success(`Applied ${applied.applied.length} repair(s).`);for(const action of applied.plan.refused)await log.warn(`Refused: ${action.detail}: ${action.reason}`)}catch(error){log.syncError(`Nothing was changed - the repairs run as one transaction and it failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}await log.info("Migrations whose every table, index and type now exists can be recorded without running:");await log.info(" ./buddy migrate:status --reconcile");await outro("Aligned.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:status","Compare database/migrations, the migrations ledger, and the live schema").option("--reconcile","Repair the ledger where the schema proves what happened",{default:false}).option("--include-partial","With --reconcile, also record half-applied migrations",{default:false}).option("--requeue-reverted","With --reconcile, un-record the migrations of a table that is missing so the next migrate rebuilds it",{default:false}).option("--json","Emit the audit as JSON",{default:false}).option("--strict","Also fail when a migration was written by hand rather than generated from the models",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:status");const{auditMigrationLedger,handWrittenMigrations,reconcileMigrationLedger}=await import("@stacksjs/database");const audit=await auditMigrationLedger();const handWritten=(await handWrittenMigrations()).files;const strict=strictMode(options);const handWrittenFails=strict&&handWritten.length>0;if(options.json){console.log(JSON.stringify({...audit,handWritten},(_k,v)=>v instanceof Set?[...v]:v,2));process.exit(audit.drift||handWrittenFails?ExitCode.FatalError:ExitCode.Success)}if(!audit.supported){log.info(`Dialect "${audit.dialect}" is not audited. Nothing to compare.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{counts,entries,orphans}=audit;const list=(status)=>entries.filter((e)=>e.status===status).map((e)=>e.file);const report=[];const section=(heading,files)=>{if(files.length===0)return;if(heading)report.push(` ${heading}`);for(const file of files.slice(0,8))report.push(` ${file}`);if(files.length>8)report.push(` … +${files.length-8} more`);report.push("")};report.push("");report.push(` Migration status: ${audit.dialect}`);report.push(" ─────────────────────────────────────────────");report.push(` ${entries.length+audit.gated.length} file(s) on disk · ${audit.recordedCount} recorded in the ledger`);report.push("");if(counts.applied>0)report.push(` ${counts.applied} applied - recorded, and present in the schema.`,"");if(counts.unverifiable>0)report.push(` ${counts.unverifiable} unverifiable - data migrations with no schema trace to check.`,"");if(audit.gated.length>0)report.push(` ${audit.gated.length} skipped - owned by a disabled feature, so \`buddy migrate\` does not run them until it is enabled.`,"");section(`${counts.pending} pending - not applied yet, will run on the next \`buddy migrate\`:`,list("pending"));if(counts.stranded>0){report.push(` ${counts.stranded} STRANDED - already applied to the schema, but missing from the ledger.`);report.push(" These re-run on the next `buddy migrate`, which is unsafe for anything not idempotent.");section("",list("stranded"))}section(`${counts.partial} PARTIAL - some effects present, some missing. Needs a human:`,list("partial"));section(`${counts.reverted} REVERTED - recorded as applied, but the effects are gone from the schema:`,list("reverted"));if(orphans.length>0){section(`${orphans.length} orphaned ledger row(s) - recorded, but no such file on disk:`,orphans.map((o)=>{if(o.renamedTo)return`${o.migration} -> renumbered to ${o.renamedTo}`;if(audit.remapPlan.superseded.includes(o.migration))return`${o.migration} (duplicate; already recorded under its current name)`;return`${o.migration} (no counterpart; migration deleted?)`}))}if(handWritten.length>0){section(`${handWritten.length} hand-written - no \`-- qb:generated\` marker, so no model describes ${handWritten.length===1?"it":"them"}${strict?" (fails --strict)":""}:`,handWritten);report.push(" Move each change into app/Models and regenerate, or allow the file in");report.push(" database.safety.allowHandWrittenMigrations (reference data no model can describe).","")}console.log(report.join(`
98
+ `);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Replace ${removed.length} migration file(s) with ${files.length} generated for ${target}?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}const result=await regenerateMigrationCorpus({dialect:target,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(result)){log.syncError(result.error.message);process.exit(ExitCode.FatalError)}log.success(`Wrote ${result.value.files.length} ${target} migration file(s) to ${relativeMigrationDirectory(result.value.dir)}.`);const recordedNow=applied>0?applied:await countAppliedMigrations().catch(()=>0);if(recordedNow>0){const{reconcileMigrationLedger}=await import("@stacksjs/database");const fixed=await reconcileMigrationLedger({regenerated:{removed:result.value.removed,written:result.value.files.map((file)=>file.name)}});logLedgerChanges(fixed,"info");if(fixed.skipped.length>0){log.warn(`${fixed.skipped.length} ledger entr(ies) need a look:`);for(const entry of fixed.skipped.slice(0,10))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>10)log.info(` … +${fixed.skipped.length-10} more - run \`./buddy migrate:status\``)}log.info("This database has history. Before `./buddy migrate`, bring its schema in line with the models:");log.info(" ./buddy migrate:align # what differs, and what can be repaired safely");log.info(" ./buddy migrate:align --apply # rename legacy indexes, add missing indexes and foreign keys");log.info(" ./buddy migrate:status --reconcile # record the regenerated files the schema now satisfies")}log.info("Review the change with `git diff`, then run `./buddy migrate`.");await outro("Regenerated.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:align","Repair a live database that drifted from the models, without writing migrations (PostgreSQL)").option("--apply","Run the safe repairs, in one transaction",{default:false}).option("--widen-integers","Also widen integer columns the models declare as bigint (rewrites those tables)",{default:false}).option("--relax-constraints","Also remove obsolete NOT NULL constraints, polymorphic foreign keys, and conflicting keys with an enforced model reference",{default:false}).option("-f, --force","With --apply, skip the confirmation",{default:false}).option("--json","Emit the plan as JSON",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:align");const{alignSchema}=await import("@stacksjs/database");let planned;try{planned=await alignSchema({widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints})}catch(error){log.syncError(`Could not compare the database with the models: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}if(options.json){console.log(JSON.stringify(planned,null,2));process.exit(ExitCode.Success)}if(!planned.supported){await log.info(`migrate:align is not supported for "${planned.dialect}" yet - only PostgreSQL. Nothing was compared.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{actions,reports,refused}=planned.plan;const report=["",` Align plan: ${planned.dialect}`," ─────────────────────────────────────────────"];if(actions.length>0){report.push(` ${actions.length} safe repair(s)${options.apply?"":" - run with --apply to make them, in one transaction"}:`);for(const action of actions)report.push(` • ${action.detail}`,` ${action.sql};`);report.push("")}if(refused.length>0){report.push(` ${refused.length} repair(s) REFUSED - the data would violate them:`);for(const action of refused)report.push(` • ${action.detail}: ${action.reason}`);report.push("")}if(reports.length>0){report.push(` ${reports.length} difference(s) left for you to decide - destructive or ambiguous, never applied:`);for(const item of reports.slice(0,40))report.push(` • [${item.kind}] ${item.detail}`);if(reports.length>40)report.push(` … +${reports.length-40} more (--json lists all)`);report.push("")}if(actions.length===0&&refused.length===0&&reports.length===0)report.push(" The database matches the models.","");console.log(report.join(`
99
+ `));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(refused.length>0?ExitCode.FatalError:ExitCode.Success)}if(!options.force&&!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Apply ${actions.length} repair(s) to the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}"?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}try{const applied=await alignSchema({apply:true,widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints});await log.success(`Applied ${applied.applied.length} repair(s).`);for(const action of applied.plan.refused)await log.warn(`Refused: ${action.detail}: ${action.reason}`)}catch(error){log.syncError(`Nothing was changed - the repairs run as one transaction and it failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}await log.info("Migrations whose every table, index and type now exists can be recorded without running:");await log.info(" ./buddy migrate:status --reconcile");await outro("Aligned.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:status","Compare database/migrations, the migrations ledger, and the live schema").option("--reconcile","Repair the ledger where the schema proves what happened",{default:false}).option("--include-partial","With --reconcile, also record half-applied migrations",{default:false}).option("--requeue-reverted","With --reconcile, un-record the migrations of a table that is missing so the next migrate rebuilds it",{default:false}).option("--json","Emit the audit as JSON",{default:false}).option("--strict","Also fail when a migration was written by hand rather than generated from the models",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:status");const{auditMigrationLedger,handWrittenMigrations,reconcileMigrationLedger}=await import("@stacksjs/database");const audit=await auditMigrationLedger();const handWritten=(await handWrittenMigrations()).files;const strict=strictMode(options);const handWrittenFails=strict&&handWritten.length>0;if(options.json){console.log(JSON.stringify({...audit,handWritten},(_k,v)=>v instanceof Set?[...v]:v,2));process.exit(audit.drift||handWrittenFails?ExitCode.FatalError:ExitCode.Success)}if(!audit.supported){log.info(`Dialect "${audit.dialect}" is not audited. Nothing to compare.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{counts,entries,orphans}=audit;const list=(status)=>entries.filter((e)=>e.status===status).map((e)=>e.file);const report=[];const section=(heading,files)=>{if(files.length===0)return;if(heading)report.push(` ${heading}`);for(const file of files.slice(0,8))report.push(` ${file}`);if(files.length>8)report.push(` … +${files.length-8} more`);report.push("")};report.push("");report.push(` Migration status: ${audit.dialect}`);report.push(" ─────────────────────────────────────────────");report.push(` ${entries.length+audit.gated.length} file(s) on disk · ${audit.recordedCount} recorded in the ledger`);report.push("");if(counts.applied>0)report.push(` ${counts.applied} applied - recorded, and present in the schema.`,"");if(counts.unverifiable>0)report.push(` ${counts.unverifiable} unverifiable - data migrations with no schema trace to check.`,"");if(audit.gated.length>0)report.push(` ${audit.gated.length} skipped - owned by a disabled feature, so \`buddy migrate\` does not run them until it is enabled.`,"");section(`${counts.pending} pending - not applied yet, will run on the next \`buddy migrate\`:`,list("pending"));if(counts.stranded>0){report.push(` ${counts.stranded} STRANDED - already applied to the schema, but missing from the ledger.`);report.push(" These re-run on the next `buddy migrate`, which is unsafe for anything not idempotent.");section("",list("stranded"))}section(`${counts.partial} PARTIAL - some effects present, some missing. Needs a human:`,list("partial"));section(`${counts.reverted} REVERTED - recorded as applied, but the effects are gone from the schema:`,list("reverted"));if(orphans.length>0){section(`${orphans.length} orphaned ledger row(s) - recorded, but no such file on disk:`,orphans.map((o)=>{if(o.renamedTo)return`${o.migration} -> renumbered to ${o.renamedTo}`;if(audit.remapPlan.superseded.includes(o.migration))return`${o.migration} (duplicate; already recorded under its current name)`;if(audit.remapPlan.ambiguous.includes(o.migration))return`${o.migration} (its name matches more than one file; which one is unknowable)`;return`${o.migration} (no counterpart; migration deleted?)`}))}if(audit.foreign.length>0){const corpora=[...new Set(audit.foreign.map((row)=>relativeMigrationDirectory(row.corpus)))];report.push(` ${audit.foreign.length} ledger row(s) from ${corpora.join(", ")} - history, not drift.`);report.push(` This database ran them before it moved to ${relativeMigrationDirectory(audit.dir)}. They are kept,`);report.push(" so those files never run here twice, and nothing matches them to this corpus by name.","")}if(handWritten.length>0){section(`${handWritten.length} hand-written - no \`-- qb:generated\` marker, so no model describes ${handWritten.length===1?"it":"them"}${strict?" (fails --strict)":""}:`,handWritten);report.push(" Move each change into app/Models and regenerate, or allow the file in");report.push(" database.safety.allowHandWrittenMigrations (reference data no model can describe).","")}console.log(report.join(`
100
100
  `));if(!audit.drift){if(handWrittenFails){await outro("--strict: hand-written migrations (see above).",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("Ledger matches the corpus and the schema.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!options.reconcile){console.log(`
101
101
  Repair with: ./buddy migrate:status --reconcile
102
102
  That repoints renumbered ledger rows and records migrations the schema
@@ -106,4 +106,4 @@ ${unrebuildable.map((t)=>` ${t}`).join(`
106
106
  ./buddy migrate:status --reconcile --requeue-reverted
107
107
  That un-records the migrations that built it, only when none of them
108
108
  touches a table that is still there, so the next migrate rebuilds it.
109
- `);await outro("Drift detected.",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}const fixed=await reconcileMigrationLedger({includePartial:options.includePartial,requeueReverted:options.requeueReverted});if(fixed.retired.length>0)log.success(`Retired ${fixed.retired.length} ledger row(s) for migrations a regeneration replaced.`);if(fixed.remapped.length>0)log.success(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.requeued.length>0){log.success(`Un-recorded ${fixed.requeued.length} migration(s) so the next \`./buddy migrate\` rebuilds the missing table(s):`);for(const file of fixed.requeued.slice(0,8))log.info(` ${file}`);if(fixed.requeued.length>8)log.info(` … +${fixed.requeued.length-8} more`)}if(fixed.recorded.length>0)log.success(`Recorded ${fixed.recorded.length} migration(s) the schema already reflects.`);if(fixed.pruned.length)log.success(`Pruned ${fixed.pruned.length} duplicate ledger row(s) left by a renumbering.`);if(fixed.skipped.length>0){log.warn(`Left ${fixed.skipped.length} entr(ies) alone:`);for(const entry of fixed.skipped.slice(0,8))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>8)log.info(` … +${fixed.skipped.length-8} more`)}if(fixed.remapped.length===0&&fixed.recorded.length===0&&fixed.pruned.length===0&&fixed.requeued.length===0)log.info("Nothing could be repaired automatically.");if(fixed.skipped.some((entry)=>entry.reason.includes("no longer exists on disk"))){log.info("A recorded migration with no file is not repaired automatically: removing the row would let it run again.");log.info(" Restore the file if it went missing by accident - a bad merge, a partial checkout.");log.info(" Delete the row by hand if the migration is genuinely retired: DELETE FROM migrations WHERE migration = '<file>'.")}await outro("Reconciled.",{startTime:perf,useSeconds:true});process.exit(handWrittenFails?ExitCode.FatalError:ExitCode.Success)});onUnknownSubcommand(buddy,"migrate")}
109
+ `);await outro("Drift detected.",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}const fixed=await reconcileMigrationLedger({includePartial:options.includePartial,requeueReverted:options.requeueReverted});logLedgerChanges(fixed,"success");if(fixed.skipped.length>0){log.warn(`Left ${fixed.skipped.length} entr(ies) alone:`);for(const entry of fixed.skipped.slice(0,8))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>8)log.info(` … +${fixed.skipped.length-8} more`)}if(fixed.retired.length===0&&fixed.remapped.length===0&&fixed.recorded.length===0&&fixed.pruned.length===0&&fixed.requeued.length===0)log.info("Nothing could be repaired automatically.");if(fixed.skipped.some((entry)=>entry.reason.includes("no longer exists on disk"))){log.info("A recorded migration with no file is not repaired automatically: removing the row would let it run again.");log.info(" Restore the file if it went missing by accident - a bad merge, a partial checkout.");log.info(" Delete the row by hand if the migration is genuinely retired: DELETE FROM migrations WHERE migration = '<file>'.")}await outro("Reconciled.",{startTime:perf,useSeconds:true});process.exit(handWrittenFails?ExitCode.FatalError:ExitCode.Success)});onUnknownSubcommand(buddy,"migrate")}
@@ -1,4 +1,4 @@
1
- function relativePath(value){return typeof value==="string"&&!!value&&!/^[A-Za-z]:|^[\\/]|[\\\r\n\x00]/.test(value)&&!value.split("/").some((segment)=>segment==="."||segment==="..")}export function validateWorkflowConfig(config){const origin=new URL(config.origin);if(config.provider!=="reviewos"||origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+\/[\w.-]+$/.test(config.repository)||config.repository.split("/").some((part)=>part==="."||part===".."))throw new Error("Configure a canonical ReviewOS origin and owner/repository");for(const group of["checks",...config.deploy?["deploy"]:[],...config.native?["ios"]:[]]){const labels=config.runners[group];if(!Array.isArray(labels)||!labels.includes("self-hosted")||labels.some((label)=>!/^[\w.-]+$/.test(label)))throw new Error(`Declare the owned ${group} runner labels`)}for(const values of Object.values(config.env??{})){if(!values||typeof values!=="object"||Array.isArray(values)||Object.entries(values).some(([name,value])=>!/^[A-Z_][A-Z0-9_]*$/.test(name)||typeof value!=="string"||value.includes("\x00")))throw new Error("Workflow environment settings must be named string values")}for(const names of Object.values(config.secrets??{})){if(!Array.isArray(names)||names.some((name)=>!/^[A-Z_][A-Z0-9_]*$/.test(name)))throw new Error("Workflow secrets must be environment variable names")}for(const[step,names]of Object.entries(config.stepSecrets??{})){if(!["native-build","native-accept","native-sign","native-upload","native-verify","native-cleanup"].includes(step)||!Array.isArray(names)||names.some((name)=>!config.secrets?.ios?.includes(name)))throw new Error("Step credentials must name declared native secrets")}if(config.native&&(!config.native.artifacts.length||![...config.native.artifacts,config.native.downloadDirectory,config.native.archivePattern,...config.native.evidence??[],...config.native.releaseArtifacts??[]].every(relativePath)))throw new Error("Native artifacts must stay inside the workspace");if(config.deploy&&!config.commands?.["after-deploy"]?.length)throw new Error("Configure deployed application verification");if(config.native&&["native-build","native-accept"].some((step)=>!config.commands?.[step]?.length))throw new Error("Configure native build and downloaded acceptance commands");if(config.release&&(!config.native||["native-sign","native-upload","native-verify","native-cleanup"].some((step)=>!config.commands?.[step]?.length)))throw new Error("Configure native signing, upload, verification and cleanup before releasing");if(config.release&&(!relativePath(config.release.versionFile)||config.release.notesDirectory!==undefined&&!relativePath(config.release.notesDirectory)||config.release.locales?.some((locale)=>!/^[a-z]{2}(?:-[A-Z]{2})?$/.test(locale))))throw new Error("Release files and locales must stay inside the workspace");for(const commands of Object.values(config.commands??{})){if(!Array.isArray(commands)||commands.some((argv)=>!Array.isArray(argv)||!argv.length||argv.some((arg)=>typeof arg!=="string"||arg.includes("\x00"))))throw new Error("Workflow commands must be nonempty argv arrays")}}export function renderReviewOsWorkflow(config){validateWorkflowConfig(config);const branch=config.branch??"main";if(!/^[\w./-]+$/.test(branch)||branch.includes(".."))throw new Error("Configure a branch name");const main=`github.ref == 'refs/heads/${branch}' && github.event_name != 'pull_request'`;const upload="steps.release.outputs.upload == 'true'";const secretEnv=(group)=>Object.fromEntries((config.secrets?.[group]??[]).map((name)=>[name,"${{ secrets."+name+" }}"]));const nativeSecrets=(step)=>{const names=config.stepSecrets?.[step]??(step==="native-sign"?config.secrets?.ios??[]:[]);return names.length?{env:Object.fromEntries(names.map((name)=>[name,"${{ secrets."+name+" }}"]))}:{}};const bootstrap=()=>[{name:"Checkout the exact source",uses:"actions/checkout@11d5960a326750d5838078e36cf38b85af677262",with:{"fetch-depth":0,"persist-credentials":false}},{name:"Set up the pinned tools",uses:"pantry-pm/pantry/packages/action@624cd6674f8c5c2d4e4204c11ece62a00d7fac0a",with:{version:config.pantry??"0.11.199",install:"false",packages:`bun.sh@${config.bun??"1.4.4"}`}},{name:"Install the frozen application dependencies",run:"bun install --frozen-lockfile"},{name:"Prepare declared application inputs",run:"./buddy workflow:step prepare"}];const jobs={};for(const name of["lint","typecheck","test","build"])jobs[name]={"runs-on":config.runners.checks,"timeout-minutes":name==="test"?90:30,reviewos:{secrets:config.secrets?.checks??[]},env:{...config.env?.checks,...secretEnv("checks")},steps:[...bootstrap(),{name:`Run ${name}`,run:`./buddy workflow:step ${name}`}]};if(config.deploy)jobs.deploy={needs:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.deploy,"timeout-minutes":60,environment:"production",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.deploy??[]]},env:{...config.env?.checks,...config.env?.deploy,...secretEnv("checks"),...secretEnv("deploy")},steps:[...bootstrap(),{name:"Deploy the qualified source",run:"./buddy workflow:step deploy"},{name:"Verify the deployed application",run:"./buddy workflow:step after-deploy"}]};if(config.native)jobs.native={needs:config.deploy?["deploy"]:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.ios,"timeout-minutes":90,environment:"ios-testflight",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.ios??[]]},env:{...config.env?.checks,...config.env?.ios,...secretEnv("checks")},steps:[...bootstrap(),{name:"Read the committed release identity",id:"release",run:"./buddy workflow:release-state",env:{WORKFLOW_UPLOAD_REQUESTED:"${{ inputs.upload && 'true' || 'false' }}"}},{name:"Build the simulator application",run:"./buddy workflow:step native-build",...nativeSecrets("native-build")},{name:"Publish the simulator application",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-simulator-${{ github.run_id }}-${{ github.run_attempt }}",path:config.native.artifacts.join(`
1
+ function relativePath(value){return typeof value==="string"&&!!value&&!/^[A-Za-z]:|^[\\/]|[\\\r\n\x00]/.test(value)&&!value.split("/").some((segment)=>segment==="."||segment==="..")}export function validateWorkflowConfig(config){const origin=new URL(config.origin);if(config.provider!=="reviewos"||origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+\/[\w.-]+$/.test(config.repository)||config.repository.split("/").some((part)=>part==="."||part===".."))throw new Error("Configure a canonical ReviewOS origin and owner/repository");for(const group of["checks",...config.deploy?["deploy"]:[],...config.native?["ios"]:[]]){const labels=config.runners[group];if(!Array.isArray(labels)||!labels.includes("self-hosted")||labels.some((label)=>!/^[\w.-]+$/.test(label)))throw new Error(`Declare the owned ${group} runner labels`)}if(config.priorities!==undefined&&(!config.priorities||typeof config.priorities!=="object"||Array.isArray(config.priorities)||Object.entries(config.priorities).some(([stage,value])=>!["checks","deploy","ios"].includes(stage)||!Number.isInteger(value)||value<-1000||value>1000)))throw new Error("Workflow priorities must name checks, deploy or ios with integer values from -1000 to 1000");for(const values of Object.values(config.env??{})){if(!values||typeof values!=="object"||Array.isArray(values)||Object.entries(values).some(([name,value])=>!/^[A-Z_][A-Z0-9_]*$/.test(name)||typeof value!=="string"||value.includes("\x00")))throw new Error("Workflow environment settings must be named string values")}for(const names of Object.values(config.secrets??{})){if(!Array.isArray(names)||names.some((name)=>!/^[A-Z_][A-Z0-9_]*$/.test(name)))throw new Error("Workflow secrets must be environment variable names")}for(const[step,names]of Object.entries(config.stepSecrets??{})){if(!["native-build","native-accept","native-sign","native-upload","native-verify","native-cleanup"].includes(step)||!Array.isArray(names)||names.some((name)=>!config.secrets?.ios?.includes(name)))throw new Error("Step credentials must name declared native secrets")}if(config.native&&(!config.native.artifacts.length||![...config.native.artifacts,config.native.downloadDirectory,config.native.archivePattern,...config.native.evidence??[],...config.native.releaseArtifacts??[]].every(relativePath)))throw new Error("Native artifacts must stay inside the workspace");if(config.deploy&&!config.commands?.["after-deploy"]?.length)throw new Error("Configure deployed application verification");if(config.native&&["native-build","native-accept"].some((step)=>!config.commands?.[step]?.length))throw new Error("Configure native build and downloaded acceptance commands");if(config.release&&(!config.native||["native-sign","native-upload","native-verify","native-cleanup"].some((step)=>!config.commands?.[step]?.length)))throw new Error("Configure native signing, upload, verification and cleanup before releasing");if(config.release&&(!relativePath(config.release.versionFile)||config.release.notesDirectory!==undefined&&!relativePath(config.release.notesDirectory)||config.release.locales?.some((locale)=>!/^[a-z]{2}(?:-[A-Z]{2})?$/.test(locale))))throw new Error("Release files and locales must stay inside the workspace");for(const commands of Object.values(config.commands??{})){if(!Array.isArray(commands)||commands.some((argv)=>!Array.isArray(argv)||!argv.length||argv.some((arg)=>typeof arg!=="string"||arg.includes("\x00"))))throw new Error("Workflow commands must be nonempty argv arrays")}}export function renderReviewOsWorkflow(config){validateWorkflowConfig(config);const branch=config.branch??"main";if(!/^[\w./-]+$/.test(branch)||branch.includes(".."))throw new Error("Configure a branch name");const main=`github.ref == 'refs/heads/${branch}' && github.event_name != 'pull_request'`;const upload="steps.release.outputs.upload == 'true'";const secretEnv=(group)=>Object.fromEntries((config.secrets?.[group]??[]).map((name)=>[name,"${{ secrets."+name+" }}"]));const nativeSecrets=(step)=>{const names=config.stepSecrets?.[step]??(step==="native-sign"?config.secrets?.ios??[]:[]);return names.length?{env:Object.fromEntries(names.map((name)=>[name,"${{ secrets."+name+" }}"]))}:{}};const bootstrap=()=>[{name:"Checkout the exact source",uses:"actions/checkout@11d5960a326750d5838078e36cf38b85af677262",with:{"fetch-depth":0,"persist-credentials":false}},{name:"Set up the pinned tools",uses:"pantry-pm/pantry/packages/action@624cd6674f8c5c2d4e4204c11ece62a00d7fac0a",with:{version:config.pantry??"0.11.199",install:"false",packages:`bun.sh@${config.bun??"1.4.4"}`}},{name:"Install the frozen application dependencies",run:"bun install --frozen-lockfile"},{name:"Prepare declared application inputs",run:"./buddy workflow:step prepare"}];const jobPriority=(stage)=>{const value=config.priorities?.[stage];return value===undefined?{}:{priority:value}};const jobs={};for(const name of["lint","typecheck","test","build"])jobs[name]={"runs-on":config.runners.checks,"timeout-minutes":name==="test"?90:30,reviewos:{...jobPriority("checks"),secrets:config.secrets?.checks??[]},env:{...config.env?.checks,...secretEnv("checks")},steps:[...bootstrap(),{name:`Run ${name}`,run:`./buddy workflow:step ${name}`}]};if(config.deploy)jobs.deploy={needs:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.deploy,"timeout-minutes":60,environment:"production",reviewos:{...jobPriority("deploy"),secrets:[...config.secrets?.checks??[],...config.secrets?.deploy??[]]},env:{...config.env?.checks,...config.env?.deploy,...secretEnv("checks"),...secretEnv("deploy")},steps:[...bootstrap(),{name:"Deploy the qualified source",run:"./buddy workflow:step deploy"},{name:"Verify the deployed application",run:"./buddy workflow:step after-deploy"}]};if(config.native)jobs.native={needs:config.deploy?["deploy"]:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.ios,"timeout-minutes":90,environment:"ios-testflight",reviewos:{...jobPriority("ios"),secrets:[...config.secrets?.checks??[],...config.secrets?.ios??[]]},env:{...config.env?.checks,...config.env?.ios,...secretEnv("checks")},steps:[...bootstrap(),{name:"Read the committed release identity",id:"release",run:"./buddy workflow:release-state",env:{WORKFLOW_UPLOAD_REQUESTED:"${{ inputs.upload && 'true' || 'false' }}"}},{name:"Build the simulator application",run:"./buddy workflow:step native-build",...nativeSecrets("native-build")},{name:"Publish the simulator application",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-simulator-${{ github.run_id }}-${{ github.run_attempt }}",path:config.native.artifacts.join(`
2
2
  `),"if-no-files-found":"error","retention-days":7}},{name:"Download the published application",uses:"actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093",with:{name:"native-simulator-${{ github.run_id }}-${{ github.run_attempt }}",path:config.native.downloadDirectory}},{name:"Accept the downloaded application",run:"./buddy workflow:step native-accept",...nativeSecrets("native-accept")},{name:"Prepare temporary signing material",if:upload,run:"./buddy workflow:step native-sign",...nativeSecrets("native-sign")},{name:"Upload the accepted application",if:upload,run:"./buddy workflow:step native-upload",...nativeSecrets("native-upload")},{name:"Verify tester availability",if:upload,run:"./buddy workflow:step native-verify",...nativeSecrets("native-verify")},{name:"Remove temporary signing material",if:"always()",run:"./buddy workflow:step native-cleanup",...nativeSecrets("native-cleanup")},...[...config.native.evidence??[],...config.native.releaseArtifacts??[]].length?[{name:"Preserve acceptance and release receipts",if:"always()",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-evidence-${{ github.run_id }}-${{ github.run_attempt }}",path:[...config.native.evidence??[],...config.native.releaseArtifacts??[]].join(`
3
3
  `),"if-no-files-found":"warn","retention-days":7}}]:[]]};return`# Generated by buddy workflow:setup from config/workflows.ts.
4
4
  `+Bun.YAML.stringify({name:"CI",on:{push:{branches:[branch]},pull_request:{branches:[branch]},workflow_dispatch:{inputs:{upload:{type:"boolean",default:false,description:"Upload a committed release after native acceptance"}}}},concurrency:{group:"stacks-app-${{ github.ref }}","cancel-in-progress":`\${{ github.ref != 'refs/heads/${branch}' }}`},permissions:{contents:"read"},jobs},null,2)}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.617",
5
+ "version": "0.75.621",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,74 +95,74 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "0.75.617",
99
- "@stacksjs/docs": "0.75.617",
100
- "@stacksjs/ai": "0.75.617",
101
- "@stacksjs/alias": "0.75.617",
102
- "@stacksjs/analytics": "0.75.617",
103
- "@stacksjs/api": "0.75.617",
104
- "@stacksjs/arrays": "0.75.617",
105
- "@stacksjs/auth": "0.75.617",
106
- "@stacksjs/browser-extension": "0.75.617",
107
- "@stacksjs/build": "0.75.617",
98
+ "@stacksjs/actions": "0.75.621",
99
+ "@stacksjs/docs": "0.75.621",
100
+ "@stacksjs/ai": "0.75.621",
101
+ "@stacksjs/alias": "0.75.621",
102
+ "@stacksjs/analytics": "0.75.621",
103
+ "@stacksjs/api": "0.75.621",
104
+ "@stacksjs/arrays": "0.75.621",
105
+ "@stacksjs/auth": "0.75.621",
106
+ "@stacksjs/browser-extension": "0.75.621",
107
+ "@stacksjs/build": "0.75.621",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.617",
110
- "@stacksjs/chat": "0.75.617",
109
+ "@stacksjs/cache": "0.75.621",
110
+ "@stacksjs/chat": "0.75.621",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.617",
113
- "@stacksjs/cloud": "0.75.617",
114
- "@stacksjs/cms": "0.75.617",
115
- "@stacksjs/collections": "0.75.617",
116
- "@stacksjs/commerce": "0.75.617",
117
- "@stacksjs/config": "0.75.617",
118
- "@stacksjs/database": "0.75.617",
119
- "@stacksjs/desktop-build": "0.75.617",
120
- "@stacksjs/dns": "0.75.617",
112
+ "@stacksjs/cli": "0.75.621",
113
+ "@stacksjs/cloud": "0.75.621",
114
+ "@stacksjs/cms": "0.75.621",
115
+ "@stacksjs/collections": "0.75.621",
116
+ "@stacksjs/commerce": "0.75.621",
117
+ "@stacksjs/config": "0.75.621",
118
+ "@stacksjs/database": "0.75.621",
119
+ "@stacksjs/desktop-build": "0.75.621",
120
+ "@stacksjs/dns": "0.75.621",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.617",
123
- "@stacksjs/enums": "0.75.617",
124
- "@stacksjs/env": "0.75.617",
125
- "@stacksjs/error-handling": "0.75.617",
126
- "@stacksjs/events": "0.75.617",
127
- "@stacksjs/features": "0.75.617",
128
- "@stacksjs/git": "0.75.617",
122
+ "@stacksjs/email": "0.75.621",
123
+ "@stacksjs/enums": "0.75.621",
124
+ "@stacksjs/env": "0.75.621",
125
+ "@stacksjs/error-handling": "0.75.621",
126
+ "@stacksjs/events": "0.75.621",
127
+ "@stacksjs/features": "0.75.621",
128
+ "@stacksjs/git": "0.75.621",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.617",
131
- "@stacksjs/hq": "0.75.617",
130
+ "@stacksjs/health": "0.75.621",
131
+ "@stacksjs/hq": "0.75.621",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.617",
134
- "@stacksjs/lint": "0.75.617",
135
- "@stacksjs/logging": "0.75.617",
136
- "@stacksjs/notifications": "0.75.617",
137
- "@stacksjs/objects": "0.75.617",
138
- "@stacksjs/orm": "0.75.617",
139
- "@stacksjs/path": "0.75.617",
140
- "@stacksjs/payments": "0.75.617",
141
- "@stacksjs/realtime": "0.75.617",
142
- "@stacksjs/router": "0.75.617",
133
+ "@stacksjs/image": "0.75.621",
134
+ "@stacksjs/lint": "0.75.621",
135
+ "@stacksjs/logging": "0.75.621",
136
+ "@stacksjs/notifications": "0.75.621",
137
+ "@stacksjs/objects": "0.75.621",
138
+ "@stacksjs/orm": "0.75.621",
139
+ "@stacksjs/path": "0.75.621",
140
+ "@stacksjs/payments": "0.75.621",
141
+ "@stacksjs/realtime": "0.75.621",
142
+ "@stacksjs/router": "0.75.621",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.617",
145
- "@stacksjs/search-engine": "0.75.617",
146
- "@stacksjs/security": "0.75.617",
147
- "@stacksjs/server": "0.75.617",
148
- "@stacksjs/sites": "0.75.617",
149
- "@stacksjs/skills": "0.75.617",
150
- "@stacksjs/socials": "0.75.617",
151
- "@stacksjs/storage": "0.75.617",
152
- "@stacksjs/strings": "0.75.617",
153
- "@stacksjs/stx": "^0.2.889",
154
- "@stacksjs/testing": "0.75.617",
155
- "@stacksjs/tinker": "0.75.617",
144
+ "@stacksjs/scheduler": "0.75.621",
145
+ "@stacksjs/search-engine": "0.75.621",
146
+ "@stacksjs/security": "0.75.621",
147
+ "@stacksjs/server": "0.75.621",
148
+ "@stacksjs/sites": "0.75.621",
149
+ "@stacksjs/skills": "0.75.621",
150
+ "@stacksjs/socials": "0.75.621",
151
+ "@stacksjs/storage": "0.75.621",
152
+ "@stacksjs/strings": "0.75.621",
153
+ "@stacksjs/stx": "^0.2.907",
154
+ "@stacksjs/testing": "0.75.621",
155
+ "@stacksjs/tinker": "0.75.621",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
157
  "@stacksjs/ts-cloud": "^0.16.137",
158
- "@stacksjs/tunnel": "0.75.617",
159
- "@stacksjs/types": "0.75.617",
160
- "@stacksjs/ui": "0.75.617",
161
- "@stacksjs/utils": "0.75.617",
162
- "@stacksjs/validation": "0.75.617",
158
+ "@stacksjs/tunnel": "0.75.621",
159
+ "@stacksjs/types": "0.75.621",
160
+ "@stacksjs/ui": "0.75.621",
161
+ "@stacksjs/utils": "0.75.621",
162
+ "@stacksjs/validation": "0.75.621",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
- "bun-plugin-stx": "^0.2.889",
165
+ "bun-plugin-stx": "^0.2.907",
166
166
  "ts-pantry": "^0.11.205"
167
167
  },
168
168
  "devDependencies": {