@stacksjs/buddy 0.75.262 → 0.75.263

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.
@@ -1,3 +1,3 @@
1
- import{lstatSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,installedDefaultsVersion,path,usesVendoredDefaults}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now(),ac=new AbortController,timer=setTimeout(()=>ac.abort(),timeoutMs);try{const message=await Promise.race([fn(),new Promise((_,rej)=>ac.signal.addEventListener("abort",()=>rej(Error(`timed out (>${Math.round(timeoutMs/1000)}s)`))))]);checks.push({name,status:"pass",message:`${message} (${Date.now()-start}ms)`})}catch(err){checks.push({name,status:err instanceof ProbeWarning?"warn":"fail",message:err instanceof Error?err.message:String(err)})}finally{clearTimeout(timer)}}async function mailDnsChecks(){const{hasExplicitEmailConfig,declaredDnsProvider,loadTsCloudConfig}=await import("./deploy");if(!hasExplicitEmailConfig())return[{name:"Mail DNS",status:"pass",message:"No config/email.ts (skipped)"}];const{email}=await import("@stacksjs/config"),cfg=email??{};if(cfg.server?.enabled!==!0)return[{name:"Mail DNS",status:"pass",message:"email.server.enabled is off (skipped)"}];const{describeMailDnsProvider,describeMailDnsRecords,describePostmaster,gatherMailDnsFacts,mailDomainFromConfig}=await import("../mail-dns-health"),{envFileForEnvironment,envFileKeys}=await import("../dns-credentials"),domain=mailDomainFromConfig(cfg);if(!domain)return[{name:"Mail DNS",status:"warn",message:"email.server.enabled is on but config/email.ts names no domain (set `domain` or a from-address)"}];const fs=await import("node:fs"),envFile=envFileForEnvironment("production"),envPath=resolve(process.cwd(),envFile),fileKeys=fs.existsSync(envPath)?envFileKeys(fs.readFileSync(envPath,"utf8")):new Set,dkimSelector="mail",[declared,facts]=await Promise.all([loadTsCloudConfig("production").then(declaredDnsProvider).catch(()=>{return}),gatherMailDnsFacts(domain,dkimSelector)]);return[{name:"Mail DNS provider",...describeMailDnsProvider({domain,zone:facts.zone,nameservers:facts.nameservers,declared,fileKeys,envFile})},{name:"Mail DNS records",...describeMailDnsRecords({domain,records:facts.records,dkimSelector,dmarcPolicy:cfg.server?.dmarc?.policy,mxAddresses:facts.mxAddresses})},{name:"Postmaster Tools",...describePostmaster(domain,cfg.server?.postmaster,facts.records.filter((record)=>record.type==="TXT"&&record.name===domain).map((record)=>record.content))}]}export function doctor(buddy){buddy.command("doctor","Run health checks on your Stacks installation").option("--no-fail","Print results but always exit 0 (CI ramp-up)").action(async(options)=>{log.debug("Running `buddy doctor` ...");await intro("buddy doctor");const checks=[],modulesPath=resolve(process.cwd(),"node_modules");try{if(lstatSync(modulesPath).isSymbolicLink()){const target=resolve(process.cwd(),readlinkSync(modulesPath)),insideProject=target.startsWith(`${resolve(process.cwd())}/`);checks.push({name:"Dependency tree",status:insideProject?"warn":"fail",message:insideProject?`node_modules is a symlink to ${target}`:`node_modules is a symlink to ${target}, which belongs to another project - installs here mutate it, and what runs locally is not what the lockfile resolves. Remove the link and run \`bun install\`.`})}else checks.push({name:"Dependency tree",status:"pass",message:"node_modules is this project's own"})}catch{checks.push({name:"Dependency tree",status:"warn",message:"node_modules is missing - run `bun install`"})}await probe(checks,"Framework defaults",async()=>{const{measureDefaultsDrift,summarizeStructureChanges}=await import("@stacksjs/actions"),root=resolve(process.cwd()),skew=inspectDefaultsProvenance(root);if(skew.status==="not-applicable"){if(!usesVendoredDefaults(root)&&installedDefaultsVersion(root))return`Runs @stacksjs/defaults ${installedDefaultsVersion(root)} from node_modules (not vendored)`;return"Not a package-managed project (nothing to compare)"}const drift=measureDefaultsDrift(root)??[],synced=skew.syncedAt?`, synced ${skew.syncedAt.slice(0,10)}`:"";if(drift.length===0)return`Vendored tree matches @stacksjs/defaults ${skew.installed}${synced}. \`buddy unpublish:defaults\` drops the copy from the repository and runs the package instead`;const counts=summarizeStructureChanges(drift);if(skew.status==="stale")throw new ProbeWarning(`storage/framework/defaults is from ${skew.vendored} while @stacksjs/defaults ${skew.installed} is installed (${counts}). Boot resolves the package, so the tree on disk is not what runs. Run \`buddy upgrade\` to sync it.`);throw new ProbeWarning(`storage/framework/defaults differs from the installed @stacksjs/defaults ${skew.installed} (${counts}), and carries no record of what it was synced from. The app runs the vendored copy. Run \`buddy upgrade\` to sync it.`)},8000);await probe(checks,"Route actions",async()=>{const{describeDanglingRouteActions,findDanglingRouteActions}=await import("@stacksjs/actions"),dangling=findDanglingRouteActions(resolve(process.cwd()));if(dangling.length===0)return"Every action a route names exists";throw new ProbeWarning(`${describeDanglingRouteActions(dangling).split(`
1
+ import{existsSync,lstatSync,readFileSync,readlinkSync}from"node:fs";import{resolve}from"node:path";import process from"node:process";import{bold,dim,green,intro,log,onUnknownSubcommand,red,yellow}from"@stacksjs/cli";import{feature}from"@stacksjs/config";import{inspectDefaultsProvenance,installedDefaultsVersion,path,usesVendoredDefaults}from"@stacksjs/path";import{storage}from"@stacksjs/storage";import{isSupportedBunVersion,isVersionGreaterThanOrEqual,minimumBunVersion}from"@stacksjs/utils";import{FEATURE_NAMES,featurePathsPresent}from"./features";const minimumSqliteVersion="3.47.2";class ProbeWarning extends Error{}async function probe(checks,name,fn,timeoutMs=2000){const start=Date.now(),ac=new AbortController,timer=setTimeout(()=>ac.abort(),timeoutMs);try{const message=await Promise.race([fn(),new Promise((_,rej)=>ac.signal.addEventListener("abort",()=>rej(Error(`timed out (>${Math.round(timeoutMs/1000)}s)`))))]);checks.push({name,status:"pass",message:`${message} (${Date.now()-start}ms)`})}catch(err){checks.push({name,status:err instanceof ProbeWarning?"warn":"fail",message:err instanceof Error?err.message:String(err)})}finally{clearTimeout(timer)}}async function mailDnsChecks(){const{hasExplicitEmailConfig,declaredDnsProvider,loadTsCloudConfig}=await import("./deploy");if(!hasExplicitEmailConfig())return[{name:"Mail DNS",status:"pass",message:"No config/email.ts (skipped)"}];const{email}=await import("@stacksjs/config"),cfg=email??{};if(cfg.server?.enabled!==!0)return[{name:"Mail DNS",status:"pass",message:"email.server.enabled is off (skipped)"}];const{describeMailDnsProvider,describeMailDnsRecords,describePostmaster,gatherMailDnsFacts,mailDomainFromConfig}=await import("../mail-dns-health"),{envFileForEnvironment,envFileKeys}=await import("../dns-credentials"),domain=mailDomainFromConfig(cfg);if(!domain)return[{name:"Mail DNS",status:"warn",message:"email.server.enabled is on but config/email.ts names no domain (set `domain` or a from-address)"}];const fs=await import("node:fs"),envFile=envFileForEnvironment("production"),envPath=resolve(process.cwd(),envFile),fileKeys=fs.existsSync(envPath)?envFileKeys(fs.readFileSync(envPath,"utf8")):new Set,dkimSelector="mail",[declared,facts]=await Promise.all([loadTsCloudConfig("production").then(declaredDnsProvider).catch(()=>{return}),gatherMailDnsFacts(domain,dkimSelector)]);return[{name:"Mail DNS provider",...describeMailDnsProvider({domain,zone:facts.zone,nameservers:facts.nameservers,declared,fileKeys,envFile})},{name:"Mail DNS records",...describeMailDnsRecords({domain,records:facts.records,dkimSelector,dmarcPolicy:cfg.server?.dmarc?.policy,mxAddresses:facts.mxAddresses})},{name:"Postmaster Tools",...describePostmaster(domain,cfg.server?.postmaster,facts.records.filter((record)=>record.type==="TXT"&&record.name===domain).map((record)=>record.content))}]}export function doctor(buddy){buddy.command("doctor","Run health checks on your Stacks installation").option("--no-fail","Print results but always exit 0 (CI ramp-up)").action(async(options)=>{log.debug("Running `buddy doctor` ...");await intro("buddy doctor");const checks=[],modulesPath=resolve(process.cwd(),"node_modules");try{if(lstatSync(modulesPath).isSymbolicLink()){const target=resolve(process.cwd(),readlinkSync(modulesPath)),insideProject=target.startsWith(`${resolve(process.cwd())}/`);checks.push({name:"Dependency tree",status:insideProject?"warn":"fail",message:insideProject?`node_modules is a symlink to ${target}`:`node_modules is a symlink to ${target}, which belongs to another project - installs here mutate it, and what runs locally is not what the lockfile resolves. Remove the link and run \`bun install\`.`})}else checks.push({name:"Dependency tree",status:"pass",message:"node_modules is this project's own"})}catch{checks.push({name:"Dependency tree",status:"warn",message:"node_modules is missing - run `bun install`"})}const depsPath=resolve(process.cwd(),"config/deps.ts");if(existsSync(depsPath)){const{describeSystemDependencies}=await import("../system-dependencies");checks.push({name:"System dependencies",...describeSystemDependencies(readFileSync(depsPath,"utf8"))})}await probe(checks,"Framework defaults",async()=>{const{measureDefaultsDrift,summarizeStructureChanges}=await import("@stacksjs/actions"),root=resolve(process.cwd()),skew=inspectDefaultsProvenance(root);if(skew.status==="not-applicable"){if(!usesVendoredDefaults(root)&&installedDefaultsVersion(root))return`Runs @stacksjs/defaults ${installedDefaultsVersion(root)} from node_modules (not vendored)`;return"Not a package-managed project (nothing to compare)"}const drift=measureDefaultsDrift(root)??[],synced=skew.syncedAt?`, synced ${skew.syncedAt.slice(0,10)}`:"";if(drift.length===0)return`Vendored tree matches @stacksjs/defaults ${skew.installed}${synced}. \`buddy unpublish:defaults\` drops the copy from the repository and runs the package instead`;const counts=summarizeStructureChanges(drift);if(skew.status==="stale")throw new ProbeWarning(`storage/framework/defaults is from ${skew.vendored} while @stacksjs/defaults ${skew.installed} is installed (${counts}). Boot resolves the package, so the tree on disk is not what runs. Run \`buddy upgrade\` to sync it.`);throw new ProbeWarning(`storage/framework/defaults differs from the installed @stacksjs/defaults ${skew.installed} (${counts}), and carries no record of what it was synced from. The app runs the vendored copy. Run \`buddy upgrade\` to sync it.`)},8000);await probe(checks,"Route actions",async()=>{const{describeDanglingRouteActions,findDanglingRouteActions}=await import("@stacksjs/actions"),dangling=findDanglingRouteActions(resolve(process.cwd()));if(dangling.length===0)return"Every action a route names exists";throw new ProbeWarning(`${describeDanglingRouteActions(dangling).split(`
2
2
  `).join("; ")}. Point each route at an action that exists, or delete it. \`buddy upgrade\` removes the ones the scaffold wrote.`)});await probe(checks,"Security overrides",async()=>{const{findShadowedSecurityDefaults,frameworkDefaultsDir,SHADOWED_DEFAULT_REVIEW_MARKER}=await import("@stacksjs/server"),defaultsDir=frameworkDefaultsDir("app");if(!defaultsDir)return"No framework defaults to compare against";const shadowed=findShadowedSecurityDefaults(path.appPath(),defaultsDir);if(shadowed.length===0)return"No app/ file shadows a framework security default";const identical=shadowed.filter((entry)=>entry.kind==="identical").map((entry)=>`app/${entry.path}`),modified=shadowed.filter((entry)=>entry.kind==="modified").map((entry)=>`app/${entry.path} (${SHADOWED_DEFAULT_REVIEW_MARKER} ${entry.fingerprint})`);throw new ProbeWarning([identical.length?`Unchanged copies, delete to receive security fixes: ${identical.join(", ")}.`:"",modified.length?`Differ from the current default, review and mark reviewed: ${modified.join(", ")}.`:""].filter(Boolean).join(" "))});const bunVersion=process.versions.bun;if(bunVersion&&isSupportedBunVersion(bunVersion))checks.push({name:"Bun Runtime",status:"pass",message:`v${bunVersion}`});else if(bunVersion)checks.push({name:"Bun Runtime",status:"fail",message:`v${bunVersion} (requires v${minimumBunVersion} or later, run: bun upgrade)`});else checks.push({name:"Bun Runtime",status:"fail",message:"Not found"});try{const pinnedBun=(await storage.readPackageJson("./package.json")).engines?.bun;if(pinnedBun&&bunVersion&&bunVersion!==pinnedBun)checks.push({name:"Pinned Bun",status:"warn",message:`v${bunVersion} is not the pinned v${pinnedBun} (engines.bun). Installing rewrites bun.lock - use \`./pantry/.bin/bun install\`, the pinned toolchain this checkout already carries, and \`git checkout -- bun.lock\` if it already changed.`});else if(pinnedBun&&bunVersion)checks.push({name:"Pinned Bun",status:"pass",message:`v${bunVersion} matches engines.bun`})}catch{}const nodeVersion=process.versions.node;if(nodeVersion)if(Number.parseInt(nodeVersion.split(".")[0]||"0",10)>=18)checks.push({name:"Node.js",status:"pass",message:`v${nodeVersion}`});else checks.push({name:"Node.js",status:"warn",message:`v${nodeVersion} (v18+ recommended)`});try{const pkg=await storage.readPackageJson("./package.json");if(pkg.name)checks.push({name:"package.json",status:"pass",message:`Found: ${pkg.name}`})}catch{checks.push({name:"package.json",status:"fail",message:"Not found in current directory"})}try{await storage.readTextFile(".env");checks.push({name:".env file",status:"pass",message:"Found"})}catch{checks.push({name:".env file",status:"warn",message:"Not found (optional)"})}const appKey=process.env.APP_KEY;if(appKey&&appKey.length>0)checks.push({name:"APP_KEY",status:appKey.length>=32?"pass":"warn",message:appKey.length>=32?"Set (\u226532 chars)":`Set but short (${appKey.length} chars; \u226532 recommended)`});else checks.push({name:"APP_KEY",status:"fail",message:"Not set - features that depend on it (encrypted columns, signed URLs, env decryption) will refuse to run. Run `buddy key:generate`."});await probe(checks,"SQLite Engine",async()=>{const{Database}=await import("bun:sqlite"),memory=new Database(":memory:");let version;try{const row=memory.query("SELECT sqlite_version() AS version").get();if(typeof row?.version==="string")version=row.version}finally{memory.close()}if(!version)throw new ProbeWarning("could not read sqlite_version() (skipped)");if(!isVersionGreaterThanOrEqual(version,minimumSqliteVersion))throw Error(`v${version} is below the required v${minimumSqliteVersion} (system.sqlite in package.json); upgrade Bun for a newer bundled SQLite`);return`v${version}`});await probe(checks,"Database",async()=>{const{db}=await import("@stacksjs/database"),unsafe=db.unsafe;if(typeof unsafe!=="function")throw new ProbeWarning("driver exposes no raw query method (skipped)");const statement=unsafe("SELECT 1");if(!statement||typeof statement.then!=="function"&&typeof statement.execute!=="function")throw new ProbeWarning("driver returned a non-executable statement (skipped)");const result=typeof statement.execute==="function"?await statement.execute():await statement;if(result===void 0||result===null)throw Error("probe query returned no result");if(Array.isArray(result)&&result.length===0)throw Error("probe query returned no rows");return"Reachable"});await probe(checks,"Database FKs",async()=>{const{auditForeignKeys}=await import("@stacksjs/database"),result=await auditForeignKeys();if(result.declared.length===0)return"No belongsTo declarations";const skipped=result.absentTable.length>0?`, ${result.absentTable.length} on tables not migrated`:"";if(result.missing.length===0)return`${result.declared.length} declared FKs all present${skipped}`;const sample=result.missing.slice(0,5).map((fk)=>`${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"";throw Error(`${result.missing.length}/${result.declared.length} declared FKs missing from live schema: ${sample}${more}${skipped}. Run \`buddy migrate:fresh\` (will reset data) or \`buddy migrate\` against a clean DB.`)});await probe(checks,"Unique indexes",async()=>{const{auditUniqueIndexes}=await import("@stacksjs/database"),result=await auditUniqueIndexes();if(!result.supported)return"Dialect not audited (skipped)";const skipped=result.skippedTables.length>0?`, ${result.skippedTables.length} tables skipped (not migrated)`:"";if(result.missing.length===0)return`${result.declared.length} declared unique constraints all indexed${skipped}`;const sample=result.missing.slice(0,5).map((u)=>`${u.table}.${u.columns.join("+")}`).join(", "),more=result.missing.length>5?` (+${result.missing.length-5} more)`:"",first=result.missing[0];if(!first)throw Error("Unique-index audit reported missing entries without details");const example=`CREATE UNIQUE INDEX IF NOT EXISTS "${first.table}_${first.columns.join("_")}_unique" ON "${first.table}" ("${first.columns.join('", "')}")`;throw Error(`${result.missing.length}/${result.declared.length} declared unique constraints have no UNIQUE index: ${sample}${more}. Run \`buddy migrate\` (re-queues missing unique-index migrations, #1952) - dedupe duplicate rows first or migrate hard-fails; if no migration file exists run \`buddy generate:migrations\`, or create manually: ${example}`)},1e4);await probe(checks,"Migration ledger",async()=>{const{auditMigrationLedger}=await import("@stacksjs/database"),result=await auditMigrationLedger();if(!result.supported)return"Dialect not audited (skipped)";if(result.entries.length===0)return"No migration files";const{counts,orphans}=result;if(!result.drift)return`${result.entries.length} migrations, ledger consistent with the schema`;const parts=[];if(counts.stranded>0)parts.push(`${counts.stranded} applied but unrecorded (would re-run)`);if(counts.partial>0)parts.push(`${counts.partial} half-applied`);if(counts.reverted>0)parts.push(`${counts.reverted} recorded but missing from the schema`);if(orphans.length>0)parts.push(`${orphans.length} ledger row(s) with no file on disk`);const needsReapply=counts.reverted+counts.partial,repair=needsReapply>0?`\`buddy migrate:status --reconcile\` cannot repair ${needsReapply} of these - it never runs migration SQL, so it skips anything the schema is missing. Those need re-applying: \`buddy migrate:fresh\` (rebuilds from the corpus, RESETS DATA), or restore the database and re-run the missing files by hand.`:"Repair with `buddy migrate:status --reconcile`.";throw Error(`Migration ledger has drifted: ${parts.join(", ")}. Inspect with \`buddy migrate:status\`. ${repair}`)},1e4);await probe(checks,"FK orphans",async()=>{const{findFkOrphans}=await import("@stacksjs/database"),result=await findFkOrphans();if(!result.supported)return"Dialect not audited (skipped)";if(result.total===0)return"No orphan rows (PRAGMA foreign_key_check clean)";const sample=result.orphans.slice(0,5).map((o)=>`${o.table}.${o.column} \u2192 ${o.parent} (${o.count})`).join(", "),more=result.orphans.length>5?` (+${result.orphans.length-5} more)`:"",first=result.orphans[0];if(!first)throw Error("Foreign-key audit reported orphan rows without details");throw Error(`${result.total} orphan rows violate FKs: ${sample}${more}. Legacy rows written under foreign_keys=OFF (#1951). Review and clean manually, e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}) - doctor never deletes data.`)},1e4);await probe(checks,"Cache",async()=>{const{cache}=await import("@stacksjs/cache"),k=`__doctor_${Date.now()}`;await cache.set(k,1,5);const v=await cache.get(k);await cache.del(k);if(v!==1)throw Error("round-trip failed");return"Round-trip ok"});await probe(checks,"Queue driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.queue?.default??"sync"}`});await probe(checks,"Mail driver",async()=>{const{config}=await import("@stacksjs/config");return`Driver: ${config.email?.default??"log"}`});{const budget=new Promise((resolve)=>setTimeout(()=>resolve([{name:"Mail DNS",status:"warn",message:"DNS lookups timed out (>6s) (skipped)"}]),6000).unref?.());checks.push(...await Promise.race([mailDnsChecks(),budget]).catch((err)=>[{name:"Mail DNS",status:"warn",message:`Could not audit mail DNS: ${err instanceof Error?err.message:String(err)}`}]))}{const{ensureRuntimeDirectories,projectPath}=await import("@stacksjs/path"),leftover=ensureRuntimeDirectories().filter((entry)=>!entry.cleared);checks.push(leftover.length===0?{name:"Runtime directories",status:"pass",message:"All under storage/"}:{name:"Runtime directories",status:"warn",message:`Still in the project root: ${leftover.map((entry)=>entry.legacy.slice(projectPath().length+1)).join(", ")} - remove them so state stays under storage/`})}const hasAwsCreds=Boolean(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY),hasAwsRole=Boolean(process.env.AWS_PROFILE)||Boolean(process.env.AWS_ROLE_ARN);if(hasAwsCreds||hasAwsRole)checks.push({name:"AWS credentials",status:"pass",message:hasAwsCreds?"Static keys in env":"IAM role configured"});else checks.push({name:"AWS credentials",status:"warn",message:"Not configured (cloud / SES / S3 commands will fail)"});await probe(checks,"Database backups",async()=>{const fs=await import("node:fs"),cloudConfig=resolve(process.cwd(),"config/cloud.ts");if(!fs.existsSync(cloudConfig))return"No config/cloud.ts (skipped)";const{findUnbackedManagedServices,hasOffsiteBackupDestination,unbackedDataMessage}=await import("../unbacked-data");let tsCloud;try{tsCloud=(await import(cloudConfig)).tsCloud}catch{throw new ProbeWarning("could not read config/cloud.ts (skipped)")}const unbacked=findUnbackedManagedServices(tsCloud,await hasOffsiteBackupDestination());if(unbacked.length===0)return"No unbacked managed data services";throw new ProbeWarning(unbackedDataMessage(unbacked))});await probe(checks,".env decryption",async()=>{const fs=await import("node:fs");if(!fs.existsSync(".env"))return"No .env (skipped)";const content=fs.readFileSync(".env","utf8");if(!/(?:^|=)(?:enc|encrypted):/m.test(content))return"No encrypted values";const privateKey=process.env.DOTENV_PRIVATE_KEY;if(!privateKey)throw Error("Encrypted values present but DOTENV_PRIVATE_KEY is unset");const{parse}=await import("@stacksjs/env"),{errors}=parse(content,{privateKey});if(errors.length>0)throw Error(errors.join("; "));return"All encrypted values decrypt cleanly"});try{const{filesystems}=await import("@stacksjs/config"),driver=filesystems.driver??"local";if(driver==="s3"){const bucket=process.env.S3_BUCKET??filesystems.s3?.bucket,accessKeyId=process.env.AWS_ACCESS_KEY_ID,secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY,missing=[];if(!bucket)missing.push("S3_BUCKET");if(!accessKeyId)missing.push("AWS_ACCESS_KEY_ID");if(!secretAccessKey)missing.push("AWS_SECRET_ACCESS_KEY");if(missing.length>0)checks.push({name:"Storage credentials",status:"warn",message:`Default disk is 's3' but missing: ${missing.join(", ")}. Uploads will throw on first use.`});else checks.push({name:"Storage credentials",status:"pass",message:"s3 default disk has bucket + AWS credentials"})}else checks.push({name:"Storage credentials",status:"pass",message:`Default disk is '${driver}' (no remote credentials required)`})}catch(err){checks.push({name:"Storage credentials",status:"warn",message:`Could not audit storage config: ${err instanceof Error?err.message:String(err)}`})}try{if(process.platform!=="darwin")checks.push({name:"Dev domains (rpx)",status:"pass",message:"Not macOS (skipped)"});else{const fs=await import("node:fs"),os=await import("node:os"),path=await import("node:path"),isAlive=(pid)=>{try{process.kill(pid,0);return!0}catch(err){return err.code==="EPERM"}},registryDir=path.join(os.homedir(),".stacks","rpx","registry.d"),registered=new Set,deadRegistryFiles=[];if(fs.existsSync(registryDir))for(const file of fs.readdirSync(registryDir)){if(!file.endsWith(".json"))continue;try{const entry=JSON.parse(fs.readFileSync(path.join(registryDir,file),"utf8"));if(entry.to&&(entry.pid===void 0||isAlive(entry.pid)))registered.add(entry.to.toLowerCase());if(typeof entry.pid==="number"&&!isAlive(entry.pid))deadRegistryFiles.push(file)}catch{}}const staleHosts=new Set,staleResolvers=[],hostsPath="/etc/hosts",hostsLines=fs.existsSync(hostsPath)?fs.readFileSync(hostsPath,"utf8").split(`
3
3
  `):[];for(let i=0;i<hostsLines.length;i++){const line=hostsLines[i];if(line.trim()==="# Added by rpx"){for(let j=i+1;j<hostsLines.length;j++){const blockLine=hostsLines[j].trim();if(blockLine===""||blockLine.startsWith("#"))break;const names=blockLine.split("#")[0]?.trim().split(/\s+/).slice(1)??[];for(const name of names)if(!registered.has(name.toLowerCase()))staleHosts.add(name)}continue}const hash=line.indexOf("#");if(hash===-1)continue;const marker=/^rpx(?::pid=(\d+))?$/.exec(line.slice(hash+1).trim());if(!marker)continue;const names=line.slice(0,hash).trim().split(/\s+/).slice(1),pid=marker[1]?Number.parseInt(marker[1],10):null;if(pid!==null?!isAlive(pid):names.every((n)=>!registered.has(n.toLowerCase())))for(const name of names)staleHosts.add(name)}const resolverDir="/etc/resolver";if(fs.existsSync(resolverDir))for(const file of fs.readdirSync(resolverDir))try{const content=fs.readFileSync(path.join(resolverDir,file),"utf8");if(!content.includes("127.0.0.1")||!content.includes("15353"))continue;const domain=file.toLowerCase();if(![...registered].some((host)=>host===domain||host.endsWith(`.${domain}`)))staleResolvers.push(file)}catch{}if(staleHosts.size>0||staleResolvers.length>0||deadRegistryFiles.length>0){const parts=[];if(staleHosts.size>0)parts.push(`hosts(${[...staleHosts].join(", ")})`);if(staleResolvers.length>0)parts.push(`resolver(${staleResolvers.join(", ")})`);if(deadRegistryFiles.length>0)parts.push(`registry(${deadRegistryFiles.join(", ")})`);checks.push({name:"Dev domains (rpx)",status:"warn",message:`Stale loopback overrides from dead dev sessions: ${parts.join(" ")}. These keep pointing the domain at 127.0.0.1. Remove with: sudo nano /etc/hosts; sudo rm /etc/resolver/<name>; rm ~/.stacks/rpx/registry.d/<file>. Updating @stacksjs/rpx lets the daemon sweep pid-stamped entries automatically.`})}else checks.push({name:"Dev domains (rpx)",status:"pass",message:"No stale dev-domain overrides"})}}catch(err){checks.push({name:"Dev domains (rpx)",status:"warn",message:`Could not audit dev-domain overrides: ${err instanceof Error?err.message:String(err)}`})}await probe(checks,"Dev ports",async()=>{const net=await import("node:net"),{config}=await import("@stacksjs/config"),configured=config.ports??{},targets=[{name:"frontend",key:"frontend",envVar:"PORT",fallback:3000},{name:"api",key:"api",envVar:"PORT_API",fallback:3008},{name:"docs",key:"docs",envVar:"PORT_DOCS",fallback:3006},{name:"dashboard",key:"admin",envVar:"PORT_ADMIN",fallback:3002}].map((t)=>({...t,port:Number(configured[t.key])||t.fallback})),canConnect=(port,host)=>new Promise((resolve)=>{const socket=net.createConnection({port,host});socket.setTimeout(400);const done=(occupied)=>{socket.destroy();resolve(occupied)};socket.once("connect",()=>done(!0));socket.once("timeout",()=>done(!1));socket.once("error",()=>done(!1))}),occupied=new Set;await Promise.all([...new Set(targets.map((t)=>t.port))].map(async(port)=>{if(await canConnect(port,"127.0.0.1")||await canConnect(port,"::1"))occupied.add(port)}));const busy=targets.filter((t)=>occupied.has(t.port));if(busy.length>0){const list=busy.map((t)=>`${t.name} :${t.port} (${t.envVar})`).join(", ");throw new ProbeWarning(`in use: ${list}. buddy dev will fail to bind; stop the process holding the port or set the override env var`)}return`All free: ${targets.map((t)=>`${t.name} :${t.port}`).join(", ")}`});try{const orphans=[];for(const name of FEATURE_NAMES){if(feature(name))continue;const present=featurePathsPresent(name);if(present.length>0)orphans.push({feature:name,count:present.length})}if(orphans.length>0){const summary=orphans.map((o)=>`${o.feature} (${o.count} path${o.count===1?"":"s"})`).join(", ");checks.push({name:"Feature scaffolding",status:"warn",message:`Stamped files remain for disabled features: ${summary}. Run \`./buddy <feature>:uninstall\` to remove or \`<feature>:install\` to re-enable.`})}else checks.push({name:"Feature scaffolding",status:"pass",message:"No orphan files for disabled features"})}catch(err){checks.push({name:"Feature scaffolding",status:"warn",message:`Could not audit feature scaffolding: ${err instanceof Error?err.message:String(err)}`})}log.info("");log.info(bold("Health Check Results:"));log.info(dim("\u2500".repeat(60)));log.info("");let hasFailures=!1,hasWarnings=!1;for(const check of checks){let statusIcon="",statusColor=(text)=>text;if(check.status==="pass"){statusIcon="\u2713";statusColor=green}else if(check.status==="warn"){statusIcon="\u26A0";statusColor=yellow;hasWarnings=!0}else{statusIcon="\u2717";statusColor=red;hasFailures=!0}log.info(`${statusColor(statusIcon)} ${bold(check.name.padEnd(20))} ${dim(check.message)}`)}log.info("");log.info(dim("\u2500".repeat(60)));log.info("");if(hasFailures){log.error("Some critical checks failed. Please address the issues above.");if(options?.fail!==!1){await log.flush();process.exit(1)}}else if(hasWarnings)log.info(yellow("Some checks have warnings. Your system should work but may have issues."));else log.success(green("All checks passed! Your Stacks installation looks healthy."));log.info("")});onUnknownSubcommand(buddy,"doctor")}
@@ -2,4 +2,4 @@ import process from"node:process";import{generateComponentMeta,generateCoreSymli
2
2
  \u274C ${result.error}
3
3
  `);process.exit(ExitCode.FatalError)}console.log(result.report);if(options.dryRun)console.log(JSON.stringify(result.vschema,null,2));else log.success(`Wrote ${result.path} (${result.tableCount} tables)`)});buddy.command("generate:erd-diagram","Derive an entity-relationship diagram from your models (writes docs/erd.md)").alias("generate:erd").option("--dry-run","Print the diagram without writing it",{default:!1}).option("--out [path]","Where to write the diagram; a .md target gets a fenced mermaid block",{default:"docs/erd.md"}).option("--no-columns","Relationships only, without the column lists",{default:!0}).option("--only [tables]","Comma-separated tables or model names to include",{default:""}).action(async(options)=>{const{generateErd}=await import("@stacksjs/actions"),only=(options.only??"").split(",").map((entry)=>entry.trim()).filter(Boolean),result=await generateErd({dryRun:options.dryRun,out:options.out,noColumns:options.columns===!1,only});if(!result.ok){console.error(`
4
4
  \u274C ${result.error}
5
- `);process.exit(ExitCode.FatalError)}if(options.dryRun){console.log(result.diagram);return}log.success(`Wrote ${result.path} (${result.modelCount} models)`);if(result.skipped.length>0)log.warn(`${result.skipped.length} model(s) could not be read and are missing from the diagram`)});buddy.command("generate:entries",descriptions.entries).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:entries` ...",options);await generateLibEntries(options)});buddy.command("generate:web-types",descriptions.webTypes).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:web-types` ...",options);await generateWebTypes()});buddy.command("generate:vscode-custom-data",descriptions.customData).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:vscode-custom-data` ...",options);await generateVsCodeCustomData()});buddy.command("generate:ide-helpers",descriptions.ideHelpers).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:ide-helpers` ...",options);await generateIdeHelpers()});buddy.command("generate:component-meta",descriptions.componentMeta).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:component-meta` ...",options);await generateComponentMeta()});buddy.command("generate:pantry-config",descriptions.pantry).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:pantry-config` ...",options);await generatePantryConfig()});buddy.command("generate:openapi-spec",descriptions.openApi).alias("generate:openapi").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:openapi-spec` ...",options);const perf=await intro("buddy generate:openapi-spec");await generateOpenApiSpec();await outro("Generated OpenAPI specification",{startTime:perf,useSeconds:!0})});buddy.command("generate:migrations","Generate Migrations").action(async(options)=>{log.debug("Running `buddy generate:migrations` ...",options);const{generateMigrations}=await import("@stacksjs/database"),result=await generateMigrations();if(resultFailed(result))reportFailure(result,"generateMigrations failed")});buddy.command("generate:core-symlink","Symlink `.framework` -> storage/framework. A shortcut for core developers.").action(async(options)=>{log.debug("Running `buddy generate:core-symlink` ...",options);await generateCoreSymlink()});buddy.command("generate:images",descriptions.images).alias("images:generate").option("--social","Only build the social cards").option("--app-store","Only build the App Store screenshots").option("--app-icons","Only build the app icons and favicons").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:images` ...",options);const perf=await intro("buddy generate:images"),only=[];if(options.social)only.push("social");if(options.appStore)only.push("app-store");if(options.appIcons)only.push("app-icons");await generateProjectImages({only,verbose:options.verbose});await outro("Generated images",{startTime:perf,useSeconds:!0})});buddy.command("generate:og",descriptions.og).alias("generate:social").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:og` ...",options);const perf=await intro("buddy generate:og");await generateProjectImages({only:["social"],verbose:options.verbose});await outro("Generated social cards",{startTime:perf,useSeconds:!0})});buddy.command("generate:app-store",descriptions.appStore).alias("generate:screenshots").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:app-store` ...",options);const perf=await intro("buddy generate:app-store");await generateProjectImages({only:["app-store"],verbose:options.verbose});await outro("Generated App Store screenshots",{startTime:perf,useSeconds:!0})});buddy.command("generate:app-icons",descriptions.appIcons).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:app-icons` ...",options);const perf=await intro("buddy generate:app-icons");await generateProjectImages({only:["app-icons"],verbose:options.verbose});await outro("Generated app icons",{startTime:perf,useSeconds:!0})});onUnknownSubcommand(buddy,"generate")}
5
+ `);process.exit(ExitCode.FatalError)}if(options.dryRun){console.log(result.diagram);return}log.success(`Wrote ${result.path} (${result.modelCount} models)`);if(result.skipped.length>0)log.warn(`${result.skipped.length} model(s) could not be read and are missing from the diagram`)});buddy.command("generate:entries",descriptions.entries).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:entries` ...",options);await generateLibEntries(options)});buddy.command("generate:web-types",descriptions.webTypes).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:web-types` ...",options);await generateWebTypes()});buddy.command("generate:vscode-custom-data",descriptions.customData).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:vscode-custom-data` ...",options);await generateVsCodeCustomData()});buddy.command("generate:ide-helpers",descriptions.ideHelpers).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:ide-helpers` ...",options);await generateIdeHelpers()});buddy.command("generate:component-meta",descriptions.componentMeta).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:component-meta` ...",options);await generateComponentMeta()});buddy.command("generate:pantry-config",descriptions.pantry).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:pantry-config` ...",options);await generatePantryConfig()});buddy.command("generate:openapi-spec",descriptions.openApi).alias("generate:openapi").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:openapi-spec` ...",options);const perf=await intro("buddy generate:openapi-spec");await generateOpenApiSpec();await outro("Generated OpenAPI specification",{startTime:perf,useSeconds:!0})});buddy.command("generate:migrations","Generate Migrations").option("--dialect <dialect>","Generate into this dialect's corpus instead of the connected one (sqlite, mysql, singlestore, vitess, postgres), or `all` for the connected dialect and every other one that keeps a corpus. No database of that dialect is needed").action(async(options)=>{log.debug("Running `buddy generate:migrations` ...",options);const{dialectsBehindModels,generateMigrations,siblingMigrationDialects}=await import("@stacksjs/database"),targets=options.dialect==="all"?[void 0,...await siblingMigrationDialects()]:[options.dialect];for(const dialect of targets){const result=await generateMigrations(dialect?{dialect}:{});if(resultFailed(result))reportFailure(result,"generateMigrations failed")}if(!options.dialect)for(const dialect of await dialectsBehindModels())log.warn(`The ${dialect} migrations are behind these models. Run \`./buddy generate:migrations --dialect ${dialect}\` (or \`--dialect all\`) and commit the result.`)});buddy.command("generate:auto-imports","Regenerate the auto-import barrels and name registries in storage/framework/auto-imports").action(async(options)=>{log.debug("Running `buddy generate:auto-imports` ...",options);const perf=await intro("buddy generate:auto-imports"),{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles();await outro("Regenerated storage/framework/auto-imports",{startTime:perf,useSeconds:!0})});buddy.command("generate:core-symlink","Symlink `.framework` -> storage/framework. A shortcut for core developers.").action(async(options)=>{log.debug("Running `buddy generate:core-symlink` ...",options);await generateCoreSymlink()});buddy.command("generate:images",descriptions.images).alias("images:generate").option("--social","Only build the social cards").option("--app-store","Only build the App Store screenshots").option("--app-icons","Only build the app icons and favicons").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:images` ...",options);const perf=await intro("buddy generate:images"),only=[];if(options.social)only.push("social");if(options.appStore)only.push("app-store");if(options.appIcons)only.push("app-icons");await generateProjectImages({only,verbose:options.verbose});await outro("Generated images",{startTime:perf,useSeconds:!0})});buddy.command("generate:og",descriptions.og).alias("generate:social").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:og` ...",options);const perf=await intro("buddy generate:og");await generateProjectImages({only:["social"],verbose:options.verbose});await outro("Generated social cards",{startTime:perf,useSeconds:!0})});buddy.command("generate:app-store",descriptions.appStore).alias("generate:screenshots").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:app-store` ...",options);const perf=await intro("buddy generate:app-store");await generateProjectImages({only:["app-store"],verbose:options.verbose});await outro("Generated App Store screenshots",{startTime:perf,useSeconds:!0})});buddy.command("generate:app-icons",descriptions.appIcons).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy generate:app-icons` ...",options);const perf=await intro("buddy generate:app-icons");await generateProjectImages({only:["app-icons"],verbose:options.verbose});await outro("Generated app icons",{startTime:perf,useSeconds:!0})});onUnknownSubcommand(buddy,"generate")}
@@ -1,2 +1,2 @@
1
1
  import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";async function runStyleAction(entry,label,options){const actions=await import("@stacksjs/actions"),{ok}=await actions[entry](options);if(!ok){await log.error(`${label} reported failure`);process.exit(ExitCode.FatalError)}}async function runStxChecks(startTime){const{runStxLint}=await import("@stacksjs/actions"),report=await runStxLint(),out=[""];for(const r of report.results)if(r.status==="fail"){out.push(` FAIL ${r.label}`);out.push(` ${r.count} found, baseline ${r.baseline}${r.why?` (${r.why})`:""}`);for(const line of r.detail.slice(0,8))out.push(` ${line}`)}else if(r.status==="loosened")out.push(` DROP ${r.label}: ${r.count} < baseline ${r.baseline} - lower it in config/lint.ts`);else out.push(` ok ${r.label}${r.baseline>0?` (${r.count}, held)`:""}`);if(report.distMissing)out.push(""," note: no build output found - the dist checks did not run. Run `./buddy build` first.");if(report.loosened>0){out.push(""," Current counts, for config/lint.ts:");for(const[id,count]of Object.entries(report.counts).sort(([a],[b])=>a.localeCompare(b)))out.push(` '${id}': ${count},`)}console.log(out.join(`
2
- `));if(report.failed>0){await log.error(`${report.failed} stx check(s) failed.`);await outro("stx checks failed",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(report.loosened>0){log.warn(`No regressions, but ${report.loosened} baseline(s) are now stale.`);await outro("stx baselines stale",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro("All stx checks pass",{startTime,useSeconds:!0})}export function lint(buddy){const descriptions={lint:"Automagically lints your project codebase",lintFix:"Automagically fixes all lint errors",format:"Format your project codebase",formatCheck:"Check formatting without making changes",project:"Target a specific project",stx:"Run the stx conformance checks instead of code style",verbose:"Enable verbose output"};buddy.command("lint",descriptions.lint).option("-f, --fix",descriptions.lintFix,{default:!1}).option("--stx",descriptions.stx,{default:!1}).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy lint` ...",options);const startTime=await intro("buddy lint");if(options.stx){await runStxChecks(startTime);return}const budget=options.maxWarnings??options["max-warnings"];await runStyleAction(options.fix?"lintFix":"lintProject","lint",{maxWarnings:budget===void 0?void 0:Number(budget)});await outro("Linted your project",{startTime,useSeconds:!0})});buddy.command("lint:fix",descriptions.lintFix).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy lint:fix` ...",options);const startTime=await intro("buddy lint:fix");log.info("Fixing lint errors...");const budget=options.maxWarnings??options["max-warnings"];await runStyleAction("lintFix","lint:fix",{maxWarnings:budget===void 0?void 0:Number(budget)});await outro("Fixed lint errors",{startTime,useSeconds:!0})});buddy.command("format",descriptions.format).option("-w, --write","Write changes to files",{default:!1}).option("-c, --check",descriptions.formatCheck,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy format` ...",options);const startTime=await intro("buddy format");await runStyleAction("formatProject","format",options.check?{check:!0}:{write:!0});await outro("Formatted your project",{startTime,useSeconds:!0})});buddy.command("format:check",descriptions.formatCheck).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy format:check` ...",options);const startTime=await intro("buddy format:check");await runStyleAction("formatProject","format:check",{check:!0});await outro("Format check complete",{startTime,useSeconds:!0})});onUnknownSubcommand(buddy,"lint")}
2
+ `));if(report.failed>0){await log.error(`${report.failed} stx check(s) failed.`);await outro("stx checks failed",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(report.loosened>0){log.warn(`No regressions, but ${report.loosened} baseline(s) are now stale.`);await outro("stx baselines stale",{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro("All stx checks pass",{startTime,useSeconds:!0})}function scopedOutro(label,paths){if(!paths?.length)return`${label} your project`;return`${label} ${paths.length===1?paths[0]:`${paths.length} paths`}`}async function refusePaths(command,paths,why,startTime){await log.error(`${command} does not take paths: ${why}.`);log.info(`Drop ${paths.join(" ")}, or run \`buddy lint ${paths.join(" ")}\` for the code-style checks on those paths.`);await outro(`${command} takes no paths`,{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}export function lint(buddy){const descriptions={lint:"Automagically lints your project codebase",lintFix:"Automagically fixes all lint errors",format:"Format your project codebase",formatCheck:"Check formatting without making changes",project:"Target a specific project",stx:"Run the stx conformance checks instead of code style",verbose:"Enable verbose output"};buddy.command("lint [...paths]",descriptions.lint).option("-f, --fix",descriptions.lintFix,{default:!1}).option("--stx",descriptions.stx,{default:!1}).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).example("buddy lint").example("buddy lint app/Jobs database/seeders").action(async(paths,options)=>{log.debug("Running `buddy lint` ...",options);const startTime=await intro("buddy lint");if(options.stx){if(paths?.length)await refusePaths("lint --stx",paths,"the stx checks grade the whole project against the baselines in config/lint.ts",startTime);await runStxChecks(startTime);return}const budget=options.maxWarnings??options["max-warnings"];await runStyleAction(options.fix?"lintFix":"lintProject","lint",{maxWarnings:budget===void 0?void 0:Number(budget),paths});await outro(scopedOutro("Linted",paths),{startTime,useSeconds:!0})});buddy.command("lint:fix [...paths]",descriptions.lintFix).option("--max-warnings <count>","Fail when warnings exceed this count").option("--verbose",descriptions.verbose,{default:!1}).example("buddy lint:fix").example("buddy lint:fix app/Jobs/Foo.ts").action(async(paths,options)=>{log.debug("Running `buddy lint:fix` ...",options);const startTime=await intro("buddy lint:fix");log.info("Fixing lint errors...");const budget=options.maxWarnings??options["max-warnings"];await runStyleAction("lintFix","lint:fix",{maxWarnings:budget===void 0?void 0:Number(budget),paths});await outro(scopedOutro("Fixed lint errors",paths),{startTime,useSeconds:!0})});buddy.command("format [...paths]",descriptions.format).option("-w, --write","Write changes to files",{default:!1}).option("-c, --check",descriptions.formatCheck,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy format").example("buddy format resources/components").action(async(paths,options)=>{log.debug("Running `buddy format` ...",options);const startTime=await intro("buddy format");await runStyleAction("formatProject","format",options.check?{check:!0,paths}:{write:!0,paths});await outro(scopedOutro("Formatted",paths),{startTime,useSeconds:!0})});buddy.command("format:check [...paths]",descriptions.formatCheck).option("--verbose",descriptions.verbose,{default:!1}).example("buddy format:check").example("buddy format:check docs").action(async(paths,options)=>{log.debug("Running `buddy format:check` ...",options);const startTime=await intro("buddy format:check");await runStyleAction("formatProject","format:check",{check:!0,paths});await outro("Format check complete",{startTime,useSeconds:!0})});onUnknownSubcommand(buddy,"lint")}
@@ -15,6 +15,22 @@ import type { CLI } from '@stacksjs/types';
15
15
  * and only then discover it has nothing to rebuild them with.
16
16
  */
17
17
  export declare function validateMigrationDialect(cwd?: unknown, options?: { driver?: string, only?: readonly string[] }): { valid: boolean, error?: string };
18
+ /**
19
+ * `--strict` (or STACKS_MIGRATE_STRICT=1): drift, ignored or hand-written
20
+ * migrations, and two files sharing a number fail the command instead of
21
+ * warning. For CI, where a missing table is a build
22
+ * to stop rather than a message to scroll past. Deploys keep the warning:
23
+ * repairing drift is the operator's to schedule.
24
+ */
25
+ /**
26
+ * Whether a `buddy migrate` run derives new migrations from the models.
27
+ *
28
+ * `--generate` and `--no-generate` decide outright. With neither, only an
29
+ * interactive run generates: there a developer sees the files appear and
30
+ * commits them, while in CI or on a deploy box a generated file is a schema
31
+ * change nobody reviewed, applied in the same breath (stacksjs/stacks#2948).
32
+ */
33
+ export declare function generatesMigrations(flag: boolean | undefined, interactive: boolean): boolean;
18
34
  /**
19
35
  * Whether this run is a preview. `--diff` is the migrate flag, but buddy also
20
36
  * registers `--dry-run` for every command ("Preview actions without making
@@ -1,10 +1,10 @@
1
- import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,isLibsqlDriver,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"||isLibsqlDriver(driver)){const audit=auditMigrationCorpus({dir,target,only:options.only});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportMissingRecordedTables(){try{const{missingRecordedTables}=await import("@stacksjs/database"),missing=await missingRecordedTables();if(missing.length===0)return!0;log.warn(`${missing.length} table${missing.length===1?"":"s"} the migrations table says ${missing.length===1?"was":"were"} created ${missing.length===1?"is":"are"} missing from the database: ${missing.slice(0,10).join(", ")}${missing.length>10?`, +${missing.length-10} more`:""}.`);return!1}catch(err){log.debug(`[migrate] recorded-table check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function logDriftRemedy(){log.info("`buddy migrate` only runs files the migrations table does not list, so it will not repair this on its own.");log.info(" A table that is missing although its migration is recorded: `./buddy migrate:status --reconcile --requeue-reverted`, then `./buddy migrate`.");log.info(" Anything else: `./buddy migrate:status` compares the corpus, the ledger and the live schema. Pass --strict to fail on drift in CI.")}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportDuplicateMigrationNumbers(options){try{const{activeMigrationDirectory,duplicateMigrationOrdinalsIn}=await import("@stacksjs/database"),groups=duplicateMigrationOrdinalsIn(await activeMigrationDirectory()),reported=options.strict?groups:groups.filter((group)=>group.generated);if(reported.length===0)return!0;const lines=reported.slice(0,10).map((group)=>` \u2022 ${group.ordinal}: ${group.files.join(", ")}`);if(reported.length>10)lines.push(` \u2022 \u2026 +${reported.length-10} more`);const message=`${reported.length} migration number${reported.length===1?" is":"s are"} used by more than one file:
1
+ import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{loadSeeders}from"../seeding";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,isLibsqlDriver,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"||isLibsqlDriver(driver)){const audit=auditMigrationCorpus({dir,target,only:options.only});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportMissingRecordedTables(){try{const{missingRecordedTables}=await import("@stacksjs/database"),missing=await missingRecordedTables();if(missing.length===0)return!0;log.warn(`${missing.length} table${missing.length===1?"":"s"} the migrations table says ${missing.length===1?"was":"were"} created ${missing.length===1?"is":"are"} missing from the database: ${missing.slice(0,10).join(", ")}${missing.length>10?`, +${missing.length-10} more`:""}.`);return!1}catch(err){log.debug(`[migrate] recorded-table check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function logDriftRemedy(){log.info("`buddy migrate` only runs files the migrations table does not list, so it will not repair this on its own.");log.info(" A table that is missing although its migration is recorded: `./buddy migrate:status --reconcile --requeue-reverted`, then `./buddy migrate`.");log.info(" Anything else: `./buddy migrate:status` compares the corpus, the ledger and the live schema. Pass --strict to fail on drift in CI.")}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportDuplicateMigrationNumbers(options){try{const{activeMigrationDirectory,duplicateMigrationOrdinalsIn}=await import("@stacksjs/database"),groups=duplicateMigrationOrdinalsIn(await activeMigrationDirectory()),reported=options.strict?groups:groups.filter((group)=>group.generated);if(reported.length===0)return!0;const lines=reported.slice(0,10).map((group)=>` \u2022 ${group.ordinal}: ${group.files.join(", ")}`);if(reported.length>10)lines.push(` \u2022 \u2026 +${reported.length-10} more`);const message=`${reported.length} migration number${reported.length===1?" is":"s are"} used by more than one file:
2
2
  ${lines.join(`
3
3
  `)}`,remedy=" The runner orders same-numbered files alphabetically, not by intent. Renumber the file(s) nothing has applied yet past the highest number, or regenerate them with `./buddy generate:migrations`.";if(options.strict){log.syncError(`--strict: ${message}
4
4
  ${remedy}`);return!1}log.warn(message);log.info(remedy);return!0}catch(err){log.debug(`[migrate] duplicate migration number check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportHandWrittenMigrations(options={}){try{const{handWrittenMigrations}=await import("@stacksjs/database"),{files}=await handWrittenMigrations();if(files.length===0)return!0;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)=>` \u2022 ${file}`).join(`
6
6
  `)}${files.length>20?`
7
- \u2022 \u2026 +${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!1}catch(err){log.debug(`[migrate] hand-written migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function strictMode(options){return options.strict===!0||process.env.STACKS_MIGRATE_STRICT==="1"}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database"),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)=>` \u2022 ${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
7
+ \u2022 \u2026 +${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!1}catch(err){log.debug(`[migrate] hand-written migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}export function generatesMigrations(flag,interactive){return flag??interactive}function strictMode(options){return options.strict===!0||process.env.STACKS_MIGRATE_STRICT==="1"}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database"),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)=>` \u2022 ${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
8
8
  `),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}
@@ -12,11 +12,11 @@ The model-backed create migrations may be stale for this database - run \`./budd
12
12
  `),more=result.orphans.length>5?`
13
13
  + ${result.orphans.length-5} more - run \`./buddy doctor\` for the full list.`:"",first=result.orphans[0];log.warn(`${result.total} row${result.total===1?"":"s"} violate foreign keys (orphaned parents), now that SQLite enforces \`foreign_keys = ON\`:
14
14
  ${sample}${more}
15
- These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" \u2192 "${op.to}"`;case"rename_table":return`rename table "${op.from}" \u2192 "${op.to}"`;case"add_enum_value":return`add value(s) to the enum type of "${op.table}"."${op.column}"`;case"create_enum":return`create the enum type for "${op.table}"${op.column?`."${op.column}"`:""}`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database"),dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return!0}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);for(const op of operations.filter((o)=>o.warning))log.warn(`${describeOp(op)}: ${op.warning}`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return!0;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` \u2022 ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return!0;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return!1}return confirm({message:"Apply these destructive changes?",initial:!1})}export function isMigratePreview(options,argv=process.argv){return options.diff===!0||options.dryRun===!0||options.pretend===!0||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return!0;if(v==="0"||v==="false"||v==="no"||v==="off")return!1;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:void 0}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");cfg=(await awaitConfig()).database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??!0,migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",noGenerate:"Apply committed migration files only; do not generate new ones from your models"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("--dry-run","Same as --diff: preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:!1}).option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("--from-db",descriptions.fromDb,{default:!1}).option("--no-rename",descriptions.noRename).option("--no-generate",descriptions.noGenerate).option("--strict","Fail when the schema has drifted from the models, a migration is git-ignored or hand-written, or two migrations share a number (for CI)",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate"),validation=validateModelsExist();if(!validation.valid){console.error(`
15
+ These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" \u2192 "${op.to}"`;case"rename_table":return`rename table "${op.from}" \u2192 "${op.to}"`;case"add_enum_value":return`add value(s) to the enum type of "${op.table}"."${op.column}"`;case"create_enum":return`create the enum type for "${op.table}"${op.column?`."${op.column}"`:""}`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database"),dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return!0}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);for(const op of operations.filter((o)=>o.warning))log.warn(`${describeOp(op)}: ${op.warning}`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return!0;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` \u2022 ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return!0;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return!1}return confirm({message:"Apply these destructive changes?",initial:!1})}export function isMigratePreview(options,argv=process.argv){return options.diff===!0||options.dryRun===!0||options.pretend===!0||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return!0;if(v==="0"||v==="false"||v==="no"||v==="off")return!1;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:void 0}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");cfg=(await awaitConfig()).database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??!0,migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",generate:"Generate migrations from your models before applying them. The default in an interactive terminal; a non-interactive run (CI, a deploy) applies committed files only unless this is passed. --no-generate never generates"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("--dry-run","Same as --diff: preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:!1}).option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("--from-db",descriptions.fromDb,{default:!1}).option("--no-rename",descriptions.noRename).option("--generate",descriptions.generate).option("--strict","Fail when the schema has drifted from the models, a migration is git-ignored or hand-written, or two migrations share a number (for CI)",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate"),validation=validateModelsExist();if(!validation.valid){console.error(`
16
16
  \u274C Error: ${validation.error}
17
17
  `);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=void 0}const dialectCheck=validateMigrationDialect(process.cwd(),{only:willRun});if(!dialectCheck.valid){console.error(`
18
18
  \u274C Error: ${dialectCheck.error}
19
- `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===!1?!1:void 0;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===!1)process.env.STACKS_MIGRATE_NO_RENAME="1";if(options.generate===!1)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=!1,files=[];try{files=await pendingMigrationFiles()}catch(error){failed=!0;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` \u2022 ${file}`);if(files.length>10)log.info(` \u2022 \u2026 +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=!0;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` \u2022 ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift(),modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});if((await resolveMigrationGuards()).confirmMigrate&&!options.force)if(isCI||!hasTTY)log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.");else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();if(!await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:!0})){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(options.generate!==!1){if(!await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames})){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`)}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result))log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.");if(options.auth!==!1)try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`);const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success)log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`);const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success)log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}catch(error){log.error("Failed to migrate notification/RBAC/trait tables:",error)}if(resultFailed(result)){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(options.auth!==!1)try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift(),tablesPresent=await reportMissingRecordedTables(),schemaMatches=modelsMatch&&tablesPresent,allCommittable=await reportIgnoredMigrations(),allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){console.error(`
19
+ `);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===!1?!1:void 0;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===!1)process.env.STACKS_MIGRATE_NO_RENAME="1";const generate=generatesMigrations(options.generate,hasTTY&&!isCI);if(!generate)process.env.STACKS_MIGRATE_NO_GENERATE="1";if(options.generate===void 0&&!generate)log.info("Applying committed migrations only: this run is not interactive, so nothing is generated from your models. Run `./buddy generate:migrations` and commit the result, or pass --generate.");if(options.strict)process.env.STACKS_MIGRATE_STRICT="1";if(isMigratePreview(options)){const{auditSchemaDrift,formatSchemaDrift,pendingMigrationFiles,pendingMigrationOperations}=await import("@stacksjs/database");let failed=!1,files=[];try{files=await pendingMigrationFiles()}catch(error){failed=!0;await log.error("Could not read the migrations table:",error)}if(files.length>0){log.info(`${files.length} committed migration file${files.length===1?"":"s"} not applied yet - \`buddy migrate\` will run ${files.length===1?"it":"them"}:`);for(const file of files.slice(0,10))log.info(` \u2022 ${file}`);if(files.length>10)log.info(` \u2022 \u2026 +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=!0;await log.error("Failed to diff the models against the migration snapshot:",error)}if(ops.length>0){log.info(`${ops.length} model change${ops.length===1?"":"s"} not in a migration file yet:`);for(const op of ops){log.info(` \u2022 ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift(),modelsDrifted=!drift.skipped&&!drift.clean;if(modelsDrifted)log.warn(await formatSchemaDrift(drift));const drifted=modelsDrifted||!await reportMissingRecordedTables();if(failed){await outro("Diff incomplete - see the errors above. No changes applied.",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(files.length===0&&ops.length===0&&!drifted){log.info("No pending schema changes - your models match the database.");await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:!0,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});if((await resolveMigrationGuards()).confirmMigrate&&!options.force)if(isCI||!hasTTY)log.debug("[migrate] confirmMigrate guard skipped - non-interactive environment.");else{const APP_ENV=process.env.APP_ENV||"local";await log.flush();if(!await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:!0})){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await ensureDatabaseOrExit();const lock=acquireMigrationLock();if(!lock.acquired){log.syncError("Another migration is already running (storage/framework/runtime/migrations.lock exists). Wait for it to finish, or remove the lockfile if it is stale.");process.exit(ExitCode.FatalError)}try{const{catchUpFrameworkRenames}=await import("@stacksjs/database");await catchUpFrameworkRenames()}catch(error){lock.release();log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}if(generate){if(!await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames})){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:!0});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`)}catch(error){log.error("Failed to migrate auth tables:",error)}}const result=await runAction(Action.Migrate,options).finally(()=>lock.release());if(resultFailed(result))log.error("Model migrations failed - applying notification/RBAC table guarantees before exiting.");if(options.auth!==!1)try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`);const datetimeResult=await ensureUtcDatetimeColumns({verbose:options.verbose});if(!datetimeResult.success)log.error(`Failed to convert TIMESTAMP columns to DATETIME: ${datetimeResult.error}`);const defaultsResult=await ensureUtcTimestampDefaults({verbose:options.verbose});if(!defaultsResult.success)log.error(`Failed to pin timestamp defaults to UTC: ${defaultsResult.error}`)}catch(error){log.error("Failed to migrate notification/RBAC/trait tables:",error)}if(resultFailed(result)){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}if(options.auth!==!1)try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUsersAuthColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure users auth columns post-migration:",error)}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift(),tablesPresent=await reportMissingRecordedTables(),schemaMatches=modelsMatch&&tablesPresent,allCommittable=await reportIgnoredMigrations(),allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){console.error(`
20
20
  \u274C --strict: ${!allCommittable?"a migration is git-ignored":!allGenerated?"a migration was written by hand rather than generated from the models":"the live schema does not match the models"} (see above).
21
21
  `);process.exit(ExitCode.FatalError)}await reportFkOrphans();const APP_ENV=process.env.APP_ENV||"local",marker=readMigrateMarker(),authSuffix=options.auth!==!1?" (including auth tables)":"",applied=marker==null?`Migrated your ${APP_ENV} database.${authSuffix}`:marker.appliedCount===0?schemaMatches?`Nothing to migrate - your ${APP_ENV} database is already up to date.${authSuffix}`:`Nothing to migrate${authSuffix}.`:`Applied ${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} to your ${APP_ENV} database.${authSuffix}`,outroMessage=schemaMatches?applied:`${applied} The database is still not in the state its migrations and models describe - see above.`;if(!schemaMatches)logDriftRemedy();await outro(outroMessage,{startTime:perf,useSeconds:!0,type:schemaMatches?"success":"warning"});process.exit(ExitCode.Success)});buddy.command("migrate:fresh",descriptions.fresh).alias("db:fresh").option("-d, --diff","Show what would be dropped and replayed, and change nothing",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("--dry-run","Same as --diff: preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-s, --seed","Run database seeders after migration",{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("-f, --force",'Skip the drop-database confirmation (only honored when the migrateFresh guard is "allow")',{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate:fresh` ...",options);const perf=await intro("buddy migrate:fresh"),validation=validateModelsExist();if(!validation.valid){console.error(`
22
22
  \u274C Error: ${validation.error}
@@ -25,7 +25,7 @@ These were written under the old \`foreign_keys = OFF\` default (#1951). Review
25
25
  `);process.exit(ExitCode.FatalError)}if(isMigratePreview(options)){let files=0;try{const dir=resolveMigrationDirectory(String(process.env.DB_CONNECTION||"sqlite").toLowerCase());files=readdirSync(dir).filter((file)=>file.endsWith(".sql")).length}catch{}log.info(`Would drop every table in the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}" and replay ${files} migration file${files===1?"":"s"}${options.seed?", then seed it":""}.`);await outro("Dry run - nothing was dropped or migrated.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const guards=await resolveMigrationGuards(),dbLabel=currentDatabaseLabel(),APP_ENV=process.env.APP_ENV||"local";if(guards.migrateFresh==="disabled"){await log.error(`\`buddy migrate:fresh\` is disabled by your migration safety guards (it DROPS every table).
26
26
  Target: ${APP_ENV} database "${dbLabel}"
27
27
  To allow it, set database.safety.migrateFresh to 'allow' in config/database.ts,
28
- or run once with: DB_MIGRATE_FRESH=allow ./buddy migrate:fresh`);await outro('migrate:fresh refused - the migrateFresh guard is set to "disabled".',{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(!(guards.migrateFresh==="allow"&&options.force===!0)){if(isCI||!hasTTY){const hint=guards.migrateFresh==="confirm"?'Guard is "confirm": migrate:fresh must be run interactively.':"Re-run with --force to drop the database non-interactively.";await log.error(`Refusing to drop the ${APP_ENV} database "${dbLabel}" in a non-interactive environment. ${hint}`);await outro("migrate:fresh cancelled.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}log.warn(`This will DROP ALL TABLES in the ${APP_ENV} database "${dbLabel}" and rebuild them from scratch. All data will be lost.`);await log.flush();if((await text({message:`Type the database name "${dbLabel}" to confirm (blank to cancel):`})).trim()!==dbLabel){await outro("migrate:fresh cancelled - confirmation did not match.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate:fresh"});await ensureDatabaseOrExit();const result=await runAction(Action.MigrateFresh,options);if(resultFailed(result))log.error("Model migrations failed - applying auth/notification/RBAC table guarantees before exiting.");if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`);const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`)}catch(error){log.error("Failed to migrate auth/notification/RBAC/trait tables:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}if(resultFailed(result)){await outro("While running the migrate:fresh command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await reportMissingForeignKeys();await reportSchemaDrift();if(options.seed){log.info("Running database seeders...");try{const{runApplicationSeeders,seed}=await import("@stacksjs/database"),seedResult=await seed({verbose:options.verbose,fresh:!0}),applicationSeedResult=await runApplicationSeeders({verbose:options.verbose}),failures=seedResult.failed+applicationSeedResult.failed;if(failures>0){log.warn(`Seeding completed with ${failures} failure(s)`);for(const r of seedResult.results)if(!r.success)log.error(` - ${r.model}: ${r.error}`);for(const r of applicationSeedResult.results)if(!r.success)log.error(` - ${r.seeder}: ${r.error}`)}else log.success(`Seeded ${seedResult.successful} model(s) and ran ${applicationSeedResult.successful} application seeder(s)`)}catch(error){log.error("Failed to run seeders:",error)}}const parts=[];if(options.auth!==!1)parts.push("auth tables");if(options.seed)parts.push("seeded");const suffix=parts.length>0?` & ${parts.join(" & ")}`:"",marker=readMigrateMarker(),countPhrase=marker==null?"":marker.appliedCount===0?" (0 applied - no migration files found?)":` (${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} applied)`;await outro(`All tables dropped successfully & migrated successfully${countPhrase}${suffix}`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:switch <driver>","Pre-flight check + plan for switching DB_CONNECTION between sqlite / mysql / vitess / postgres").action(async(driver)=>{log.debug(`Running \`buddy migrate:switch ${driver}\` ...`);const perf=await intro("buddy migrate:switch"),target=driver.toLowerCase();if(!new Set(["sqlite","mysql","vitess","postgres"]).has(target)){console.log(`
28
+ or run once with: DB_MIGRATE_FRESH=allow ./buddy migrate:fresh`);await outro('migrate:fresh refused - the migrateFresh guard is set to "disabled".',{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}if(!(guards.migrateFresh==="allow"&&options.force===!0)){if(isCI||!hasTTY){const hint=guards.migrateFresh==="confirm"?'Guard is "confirm": migrate:fresh must be run interactively.':"Re-run with --force to drop the database non-interactively.";await log.error(`Refusing to drop the ${APP_ENV} database "${dbLabel}" in a non-interactive environment. ${hint}`);await outro("migrate:fresh cancelled.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}log.warn(`This will DROP ALL TABLES in the ${APP_ENV} database "${dbLabel}" and rebuild them from scratch. All data will be lost.`);await log.flush();if((await text({message:`Type the database name "${dbLabel}" to confirm (blank to cancel):`})).trim()!==dbLabel){await outro("migrate:fresh cancelled - confirmation did not match.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate:fresh"});await ensureDatabaseOrExit();const result=await runAction(Action.MigrateFresh,options);if(resultFailed(result))log.error("Model migrations failed - applying auth/notification/RBAC table guarantees before exiting.");if(options.auth!==!1){log.debug("Migrating auth tables...");try{const{migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database"),authResult=await migrateAuthTables({verbose:options.verbose});if(!authResult.success)log.error(`Failed to migrate auth tables: ${authResult.error}`);const notifResult=await migrateNotificationTables({verbose:options.verbose});if(!notifResult.success)log.error(`Failed to migrate notification tables: ${notifResult.error}`);const rbacResult=await migrateRbacTables({verbose:options.verbose});if(!rbacResult.success)log.error(`Failed to migrate RBAC tables: ${rbacResult.error}`);const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success)log.error(`Failed to migrate polymorphic trait tables: ${traitResult.error}`)}catch(error){log.error("Failed to migrate auth/notification/RBAC/trait tables:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database"),driver=process.env.DB_CONNECTION||"sqlite";await ensureUuidColumns(sqlHelpers(driver),{verbose:options.verbose})}catch(error){log.error("Failed to ensure uuid columns post-migration:",error)}if(resultFailed(result)){await outro("While running the migrate:fresh command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await reportMissingForeignKeys();await reportSchemaDrift();if(options.seed){log.info("Running database seeders...");try{const{runApplicationSeeders,seed}=await loadSeeders(),seedResult=await seed({verbose:options.verbose,fresh:!0}),applicationSeedResult=await runApplicationSeeders({verbose:options.verbose}),failures=seedResult.failed+applicationSeedResult.failed;if(failures>0){log.warn(`Seeding completed with ${failures} failure(s)`);for(const r of applicationSeedResult.results)if(!r.success)log.error(` - ${r.seeder}: ${r.error}`)}else log.success(`Seeded ${seedResult.successful} model(s) and ran ${applicationSeedResult.successful} application seeder(s)`)}catch(error){log.error("Failed to run seeders:",error)}}const parts=[];if(options.auth!==!1)parts.push("auth tables");if(options.seed)parts.push("seeded");const suffix=parts.length>0?` & ${parts.join(" & ")}`:"",marker=readMigrateMarker(),countPhrase=marker==null?"":marker.appliedCount===0?" (0 applied - no migration files found?)":` (${marker.appliedCount} migration${marker.appliedCount===1?"":"s"} applied)`;await outro(`All tables dropped successfully & migrated successfully${countPhrase}${suffix}`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("migrate:switch <driver>","Pre-flight check + plan for switching DB_CONNECTION between sqlite / mysql / vitess / postgres").action(async(driver)=>{log.debug(`Running \`buddy migrate:switch ${driver}\` ...`);const perf=await intro("buddy migrate:switch"),target=driver.toLowerCase();if(!new Set(["sqlite","mysql","vitess","postgres"]).has(target)){console.log(`
29
29
  Unknown target driver "${driver}". Allowed: sqlite, mysql, vitess, postgres.
30
30
  `);await outro("Aborted.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}const current=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(current===target){console.log(`
31
31
  DB_CONNECTION is already "${target}". Nothing to switch.
@@ -1 +1 @@
1
- import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function seed(buddy){const descriptions={seed:"Seed your database",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("seed",descriptions.seed).alias("db:seed").option("--only [models]","Comma-separated list of models to seed",{default:""}).option("--except [models]","Comma-separated list of models to skip",{default:""}).option("--only-seeders [seeders]","Comma-separated list of application seeder classes to run",{default:""}).option("--tag [tags]","Comma-separated list of seeder tags to run (e.g. deploy)",{default:""}).option("--except-seeders [seeders]","Comma-separated list of application seeder classes to skip",{default:""}).option("--skip-models","Skip model-factory seeding",{default:!1}).option("--skip-application-seeders","Skip application seeders",{default:!1}).option("--include-defaults","Also seed the framework's built-in models",{default:!1}).option("--allow-protected","Seed auth/oauth models even on a non-fresh DB (will invalidate live tokens)",{default:!1}).option("--attach-accounts","Point seeded rows at existing User/Team/Customer rows, not only ones this run seeded (scratch databases only)",{default:!1}).option("--fresh","Truncate tables before seeding",{default:!1}).option("--append","Add rows to tables that already have some, instead of skipping them",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy seed` ...",options);const perf=await intro("buddy seed"),{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports();const{runApplicationSeeders,seed:seedDatabase}=await import("@stacksjs/database"),list=(value)=>value?value.split(",").map((entry)=>entry.trim()).filter(Boolean):void 0,summary=options.skipModels?{total:0,successful:0,failed:0,results:[],duration:0}:await seedDatabase({verbose:options.verbose,fresh:options.fresh,append:options.append,only:list(options.only),except:list(options.except),includeDefaults:options.includeDefaults,allowProtected:options.allowProtected,attachAccounts:options.attachAccounts}),applicationSummary=options.skipApplicationSeeders?{total:0,successful:0,failed:0,results:[],duration:0}:await runApplicationSeeders({verbose:options.verbose,only:list(options.onlySeeders),except:list(options.exceptSeeders),tags:list(options.tag)}),APP_ENV=process.env.APP_ENV||"local";if(summary.total===0&&applicationSummary.total===0){await outro("No matching model or application seeders were found.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const failures=summary.failed+applicationSummary.failed;await outro(`Seeded your ${APP_ENV} database. ${summary.successful}/${summary.total} model(s) and ${applicationSummary.successful}/${applicationSummary.total} application seeder(s) completed${failures>0?`, ${failures} failed`:""}.`,{startTime:perf,useSeconds:!0,type:failures>0?"error":"success"});process.exit(failures>0?ExitCode.FatalError:ExitCode.Success)});buddy.command("seed:roles","Seed default RBAC role packs (admin, dev, client)").alias("roles:seed").action(async()=>{const perf=await intro("buddy seed:roles");try{const{seedDefaultRoles}=await import("@stacksjs/auth"),result=await seedDefaultRoles();if(result.created.length===0&&result.skipped.length>0)await outro(`All ${result.skipped.length} default role packs already exist - nothing to do.`,{startTime:perf,useSeconds:!0});else{const createdNames=result.created.map((r)=>r.name).join(", ");await outro(`Created ${result.created.length} role pack(s): ${createdNames}. Skipped ${result.skipped.length} existing.`,{startTime:perf,useSeconds:!0})}process.exit(ExitCode.Success)}catch(err){await outro("Failed to seed default roles. Most often: migrations haven't run yet (try `./buddy migrate` first).",{startTime:perf,useSeconds:!0},err);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"seed")}
1
+ import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{loadSeeders}from"../seeding";export function seed(buddy){const descriptions={seed:"Seed your database",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("seed",descriptions.seed).alias("db:seed").option("--only [models]","Comma-separated list of models to seed",{default:""}).option("--except [models]","Comma-separated list of models to skip",{default:""}).option("--only-seeders [seeders]","Comma-separated list of application seeder classes to run",{default:""}).option("--tag [tags]","Comma-separated list of seeder tags to run (e.g. deploy)",{default:""}).option("--except-seeders [seeders]","Comma-separated list of application seeder classes to skip",{default:""}).option("--skip-models","Skip model-factory seeding",{default:!1}).option("--skip-application-seeders","Skip application seeders",{default:!1}).option("--include-defaults","Also seed the framework's built-in models",{default:!1}).option("--allow-protected","Seed auth/oauth models even on a non-fresh DB (will invalidate live tokens)",{default:!1}).option("--attach-accounts","Point seeded rows at existing User/Team/Customer rows, not only ones this run seeded (scratch databases only)",{default:!1}).option("--fresh","Truncate tables before seeding",{default:!1}).option("--append","Add rows to tables that already have some, instead of skipping them",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy seed` ...",options);const perf=await intro("buddy seed"),{runApplicationSeeders,seed:seedDatabase}=await loadSeeders(),list=(value)=>value?value.split(",").map((entry)=>entry.trim()).filter(Boolean):void 0,summary=options.skipModels?{total:0,successful:0,failed:0,results:[],duration:0}:await seedDatabase({verbose:options.verbose,fresh:options.fresh,append:options.append,only:list(options.only),except:list(options.except),includeDefaults:options.includeDefaults,allowProtected:options.allowProtected,attachAccounts:options.attachAccounts}),applicationSummary=options.skipApplicationSeeders?{total:0,successful:0,failed:0,results:[],duration:0}:await runApplicationSeeders({verbose:options.verbose,only:list(options.onlySeeders),except:list(options.exceptSeeders),tags:list(options.tag)}),APP_ENV=process.env.APP_ENV||"local";if(summary.total===0&&applicationSummary.total===0){await outro("No matching model or application seeders were found.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const failures=summary.failed+applicationSummary.failed;await outro(`Seeded your ${APP_ENV} database. ${summary.successful}/${summary.total} model(s) and ${applicationSummary.successful}/${applicationSummary.total} application seeder(s) completed${failures>0?`, ${failures} failed`:""}.`,{startTime:perf,useSeconds:!0,type:failures>0?"error":"success"});process.exit(failures>0?ExitCode.FatalError:ExitCode.Success)});buddy.command("seed:roles","Seed default RBAC role packs (admin, dev, client)").alias("roles:seed").action(async()=>{const perf=await intro("buddy seed:roles");try{const{seedDefaultRoles}=await import("@stacksjs/auth"),result=await seedDefaultRoles();if(result.created.length===0&&result.skipped.length>0)await outro(`All ${result.skipped.length} default role packs already exist - nothing to do.`,{startTime:perf,useSeconds:!0});else{const createdNames=result.created.map((r)=>r.name).join(", ");await outro(`Created ${result.created.length} role pack(s): ${createdNames}. Skipped ${result.skipped.length} existing.`,{startTime:perf,useSeconds:!0})}process.exit(ExitCode.Success)}catch(err){await outro("Failed to seed default roles. Most often: migrations haven't run yet (try `./buddy migrate` first).",{startTime:perf,useSeconds:!0},err);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"seed")}
@@ -1,2 +1,2 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function test(buddy){const descriptions={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("test",descriptions.command).option("-f, --feature",descriptions.feature,{default:!1}).option("-u, --unit",descriptions.unit,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!0}).action(async(options)=>{const perf=await intro("buddy test");if(options.feature&&options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(options.feature&&!options.unit){log.info("Running Feature tests...");const result=await runAction(Action.TestFeature,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&options.unit){log.info("Running Unit tests...");const result=await runAction(Action.TestUnit,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&!options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}await outro("Finished running tests",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("test:unit",descriptions.unit).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:unit"),result=await runAction(Action.TestUnit,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:unit`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running unit tests",{startTime:perf,useSeconds:!0})});buddy.command("test:feature",descriptions.feature).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:feature"),result=await runAction(Action.TestFeature,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:feature`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running feature tests",{startTime:perf,useSeconds:!0})});buddy.command("test:ui",descriptions.command).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:ui"),result=await runAction(Action.TestUi,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:ui`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running tests in the browser",{startTime:perf,useSeconds:!0})});buddy.command("test:types",descriptions.types).alias("typecheck").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:types"),result=await runAction(Action.Typecheck,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:types`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running typecheck",{startTime:perf,useSeconds:!0})});buddy.command("test:page-audit","Loads pages in headless Chrome and reports duplicate API requests, failed requests and console errors").option("--url <urls>","Page URLs to audit, comma-separated (paths resolve against --base)").option("--base [base]","Origin that paths in --url resolve against",{default:"http://localhost:3000"}).option("--quiet-ms [ms]","How long the network must stay quiet before a page counts as loaded",{default:1000}).option("--timeout [ms]","Give up waiting for a page to settle after this long",{default:15000}).option("--mobile","Audit at a 390px phone viewport instead of 1440px",{default:!1}).option("--json","Print the reports as JSON",{default:!1}).example("buddy test:page-audit --url /,/dashboard --base http://localhost:3000").example("buddy test:page-audit --url http://localhost:3000/pricing --json").action(async(options)=>{const targets=String(options.url??"").split(",").map((url)=>url.trim()).filter(Boolean);if(!targets.length){await log.error("Pass the pages to audit with --url (comma-separated URLs or paths)");process.exit(ExitCode.InvalidArgument)}const{auditPage,formatPageAudit,launch,pageAuditClean}=await import("@stacksjs/testing/browser"),viewport=options.mobile?{width:390,height:844,mobile:!0,deviceScaleFactor:2}:{width:1440,height:900},{cdp,close}=await launch({viewport}),reports=[];try{for(const target of targets){const url=new URL(target,options.base||"http://localhost:3000").href,report=await auditPage(url,{cdp,quietMs:Number(options.quietMs)||1000,timeoutMs:Number(options.timeout)||15000});reports.push(report);if(!options.json)await log.info(formatPageAudit(report))}}finally{await close()}if(options.json)process.stdout.write(`${JSON.stringify(reports,null,2)}
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";function testPathEnv(paths){return paths?.length?{STACKS_TEST_PATHS:JSON.stringify(paths)}:void 0}function scopedTests(label,paths){if(!paths?.length)return label;return`${label} for ${paths.length===1?paths[0]:`${paths.length} paths`}`}export function test(buddy){const descriptions={command:"Runs your test suite",types:"Typechecks your codebase",coverage:"Generates a test coverage report",ui:"Runs your test suite in the browser",unit:"Runs your unit tests",feature:"Runs your feature tests",showReport:"Show the test report",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("test [...paths]",descriptions.command).option("-f, --feature",descriptions.feature,{default:!1}).option("-u, --unit",descriptions.unit,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!0}).example("buddy test").example("buddy test tests/unit/auth.test.ts").example("buddy test storage/framework/core/scheduler/tests").action(async(paths,options)=>{const perf=await intro("buddy test"),env=testPathEnv(paths);if(options.feature&&options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(options.feature&&!options.unit){log.info("Running Feature tests...");const result=await runAction(Action.TestFeature,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&options.unit){log.info("Running Unit tests...");const result=await runAction(Action.TestUnit,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}if(!options.feature&&!options.unit){const result=await runAction(Action.Test,{...options,cwd:projectPath(),env});if(resultFailed(result)){await outro("While running `buddy test`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}}await outro(scopedTests("Finished running tests",paths),{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("test:unit [...paths]",descriptions.unit).option("--verbose",descriptions.verbose,{default:!1}).example("buddy test:unit").example("buddy test:unit tests/unit/auth.test.ts").action(async(paths,options)=>{const perf=await intro("buddy test:unit"),result=await runAction(Action.TestUnit,{...options,verbose:!0,cwd:projectPath(),env:testPathEnv(paths)});if(resultFailed(result)){await outro("While running `buddy test:unit`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(scopedTests("Finished running unit tests",paths),{startTime:perf,useSeconds:!0})});buddy.command("test:feature [...paths]",descriptions.feature).option("--verbose",descriptions.verbose,{default:!1}).example("buddy test:feature").example("buddy test:feature tests/feature/login.test.ts").action(async(paths,options)=>{const perf=await intro("buddy test:feature"),result=await runAction(Action.TestFeature,{...options,verbose:!0,cwd:projectPath(),env:testPathEnv(paths)});if(resultFailed(result)){await outro("While running `buddy test:feature`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(scopedTests("Finished running feature tests",paths),{startTime:perf,useSeconds:!0})});buddy.command("test:ui",descriptions.command).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:ui"),result=await runAction(Action.TestUi,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:ui`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running tests in the browser",{startTime:perf,useSeconds:!0})});buddy.command("test:types",descriptions.types).alias("typecheck").option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy test:types"),result=await runAction(Action.Typecheck,{...options,verbose:!0,cwd:projectPath()});if(resultFailed(result)){await outro("While running `buddy test:types`, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Finished running typecheck",{startTime:perf,useSeconds:!0})});buddy.command("test:page-audit","Loads pages in headless Chrome and reports duplicate API requests, failed requests and console errors").option("--url <urls>","Page URLs to audit, comma-separated (paths resolve against --base)").option("--base [base]","Origin that paths in --url resolve against",{default:"http://localhost:3000"}).option("--quiet-ms [ms]","How long the network must stay quiet before a page counts as loaded",{default:1000}).option("--timeout [ms]","Give up waiting for a page to settle after this long",{default:15000}).option("--mobile","Audit at a 390px phone viewport instead of 1440px",{default:!1}).option("--json","Print the reports as JSON",{default:!1}).example("buddy test:page-audit --url /,/dashboard --base http://localhost:3000").example("buddy test:page-audit --url http://localhost:3000/pricing --json").action(async(options)=>{const targets=String(options.url??"").split(",").map((url)=>url.trim()).filter(Boolean);if(!targets.length){await log.error("Pass the pages to audit with --url (comma-separated URLs or paths)");process.exit(ExitCode.InvalidArgument)}const{auditPage,formatPageAudit,launch,pageAuditClean}=await import("@stacksjs/testing/browser"),viewport=options.mobile?{width:390,height:844,mobile:!0,deviceScaleFactor:2}:{width:1440,height:900},{cdp,close}=await launch({viewport}),reports=[];try{for(const target of targets){const url=new URL(target,options.base||"http://localhost:3000").href,report=await auditPage(url,{cdp,quietMs:Number(options.quietMs)||1000,timeoutMs:Number(options.timeout)||15000});reports.push(report);if(!options.json)await log.info(formatPageAudit(report))}}finally{await close()}if(options.json)process.stdout.write(`${JSON.stringify(reports,null,2)}
2
2
  `);process.exit(reports.every(pageAuditClean)?ExitCode.Success:ExitCode.FatalError)});onUnknownSubcommand(buddy,"test")}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The database seeders, loaded with the runtime the code they run expects.
3
+ *
4
+ * A seeder is application code: it calls jobs, saves models and reads `db`, and
5
+ * the auto-import declarations promise all of those as server globals. `buddy
6
+ * seed` installed them before seeding and `migrate:fresh --seed` did not, so a
7
+ * job using the bare `db` global worked from one command and failed with
8
+ * `db is not defined` from the other (stacksjs/stacks#2952). Every command that
9
+ * seeds goes through here, so none of them can skip the boot.
10
+ */
11
+ export declare function loadSeeders(): Promise<Pick<typeof import('@stacksjs/database'), 'seed' | 'runApplicationSeeders'>>;
@@ -0,0 +1 @@
1
+ export async function loadSeeders(){const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports();const{seed,runApplicationSeeders}=await import("@stacksjs/database");return{seed,runApplicationSeeders}}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * System dependencies a project declares that the registry cannot install.
3
+ *
4
+ * Apps scaffolded before July 2026 carry `craft: '^0.0.1'` in their own
5
+ * `config/deps.ts`. Pantry resolves it to `craft-native.org`, which has no
6
+ * artifacts at all, so once a pantry release stopped skipping it every
7
+ * `./buddy` bootstrap failed at install, and an app stopped deploying for three
8
+ * days with no other symptom (stacksjs/stacks#2919). The framework's own copy
9
+ * dropped it long ago, but a scaffolded app keeps the file it was given.
10
+ *
11
+ * Craft is the native desktop shell. A web or mobile build never runs its
12
+ * binary, and the SDK comes from `craft-native` in package.json.
13
+ */
14
+ export declare function describeSystemDependencies(depsSource: string): { status: 'pass' | 'fail', message: string };
@@ -0,0 +1 @@
1
+ export function describeSystemDependencies(depsSource){const code=new Bun.Transpiler({loader:"ts",trimUnusedImports:!1}).transformSync(depsSource);if(/(?:^|[{,\s])["']?craft["']?\s*:/m.test(code))return{status:"fail",message:"config/deps.ts declares `craft`, which Pantry resolves to craft-native.org, a package the registry has no artifacts for, so `pantry install` fails. Remove the line: the Craft SDK comes from `craft-native` in package.json, and a desktop build installs the CLI with `pantry install craft`."};return{status:"pass",message:"config/deps.ts declares no system dependency the registry cannot install"}}
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.262",
5
+ "version": "0.75.263",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -96,68 +96,68 @@
96
96
  },
97
97
  "dependencies": {
98
98
  "@stacksjs/bumpx": "^0.2.25",
99
- "@stacksjs/actions": "0.75.262",
100
- "@stacksjs/ai": "0.75.262",
101
- "@stacksjs/alias": "0.75.262",
102
- "@stacksjs/analytics": "0.75.262",
103
- "@stacksjs/api": "0.75.262",
104
- "@stacksjs/arrays": "0.75.262",
105
- "@stacksjs/auth": "0.75.262",
106
- "@stacksjs/browser-extension": "0.75.262",
107
- "@stacksjs/build": "0.75.262",
108
- "@stacksjs/cache": "0.75.262",
109
- "@stacksjs/chat": "0.75.262",
99
+ "@stacksjs/actions": "0.75.263",
100
+ "@stacksjs/ai": "0.75.263",
101
+ "@stacksjs/alias": "0.75.263",
102
+ "@stacksjs/analytics": "0.75.263",
103
+ "@stacksjs/api": "0.75.263",
104
+ "@stacksjs/arrays": "0.75.263",
105
+ "@stacksjs/auth": "0.75.263",
106
+ "@stacksjs/browser-extension": "0.75.263",
107
+ "@stacksjs/build": "0.75.263",
108
+ "@stacksjs/cache": "0.75.263",
109
+ "@stacksjs/chat": "0.75.263",
110
110
  "@stacksjs/clapp": "^0.2.16",
111
- "@stacksjs/cli": "0.75.262",
112
- "@stacksjs/cloud": "0.75.262",
113
- "@stacksjs/cms": "0.75.262",
114
- "@stacksjs/collections": "0.75.262",
115
- "@stacksjs/commerce": "0.75.262",
116
- "@stacksjs/config": "0.75.262",
117
- "@stacksjs/database": "0.75.262",
118
- "@stacksjs/desktop-build": "0.75.262",
119
- "@stacksjs/dns": "0.75.262",
111
+ "@stacksjs/cli": "0.75.263",
112
+ "@stacksjs/cloud": "0.75.263",
113
+ "@stacksjs/cms": "0.75.263",
114
+ "@stacksjs/collections": "0.75.263",
115
+ "@stacksjs/commerce": "0.75.263",
116
+ "@stacksjs/config": "0.75.263",
117
+ "@stacksjs/database": "0.75.263",
118
+ "@stacksjs/desktop-build": "0.75.263",
119
+ "@stacksjs/dns": "0.75.263",
120
120
  "@stacksjs/dnsx": "^0.2.3",
121
- "@stacksjs/email": "0.75.262",
122
- "@stacksjs/enums": "0.75.262",
123
- "@stacksjs/env": "0.75.262",
124
- "@stacksjs/error-handling": "0.75.262",
125
- "@stacksjs/events": "0.75.262",
126
- "@stacksjs/features": "0.75.262",
127
- "@stacksjs/git": "0.75.262",
121
+ "@stacksjs/email": "0.75.263",
122
+ "@stacksjs/enums": "0.75.263",
123
+ "@stacksjs/env": "0.75.263",
124
+ "@stacksjs/error-handling": "0.75.263",
125
+ "@stacksjs/events": "0.75.263",
126
+ "@stacksjs/features": "0.75.263",
127
+ "@stacksjs/git": "0.75.263",
128
128
  "@stacksjs/gitit": "^0.2.5",
129
- "@stacksjs/health": "0.75.262",
129
+ "@stacksjs/health": "0.75.263",
130
130
  "@stacksjs/httx": "^0.1.10",
131
- "@stacksjs/image": "0.75.262",
132
- "@stacksjs/lint": "0.75.262",
133
- "@stacksjs/logging": "0.75.262",
134
- "@stacksjs/notifications": "0.75.262",
135
- "@stacksjs/objects": "0.75.262",
136
- "@stacksjs/orm": "0.75.262",
137
- "@stacksjs/path": "0.75.262",
138
- "@stacksjs/payments": "0.75.262",
139
- "@stacksjs/realtime": "0.75.262",
140
- "@stacksjs/router": "0.75.262",
131
+ "@stacksjs/image": "0.75.263",
132
+ "@stacksjs/lint": "0.75.263",
133
+ "@stacksjs/logging": "0.75.263",
134
+ "@stacksjs/notifications": "0.75.263",
135
+ "@stacksjs/objects": "0.75.263",
136
+ "@stacksjs/orm": "0.75.263",
137
+ "@stacksjs/path": "0.75.263",
138
+ "@stacksjs/payments": "0.75.263",
139
+ "@stacksjs/realtime": "0.75.263",
140
+ "@stacksjs/router": "0.75.263",
141
141
  "@stacksjs/rpx": "^0.11.54",
142
- "@stacksjs/scheduler": "0.75.262",
143
- "@stacksjs/search-engine": "0.75.262",
144
- "@stacksjs/security": "0.75.262",
145
- "@stacksjs/server": "0.75.262",
146
- "@stacksjs/sites": "0.75.262",
147
- "@stacksjs/skills": "0.75.262",
148
- "@stacksjs/socials": "0.75.262",
149
- "@stacksjs/storage": "0.75.262",
150
- "@stacksjs/strings": "0.75.262",
142
+ "@stacksjs/scheduler": "0.75.263",
143
+ "@stacksjs/search-engine": "0.75.263",
144
+ "@stacksjs/security": "0.75.263",
145
+ "@stacksjs/server": "0.75.263",
146
+ "@stacksjs/sites": "0.75.263",
147
+ "@stacksjs/skills": "0.75.263",
148
+ "@stacksjs/socials": "0.75.263",
149
+ "@stacksjs/storage": "0.75.263",
150
+ "@stacksjs/strings": "0.75.263",
151
151
  "@stacksjs/stx": "0.2.661",
152
- "@stacksjs/testing": "0.75.262",
153
- "@stacksjs/tinker": "0.75.262",
152
+ "@stacksjs/testing": "0.75.263",
153
+ "@stacksjs/tinker": "0.75.263",
154
154
  "@stacksjs/tlsx": "^0.13.19",
155
155
  "@stacksjs/ts-cloud": "^0.16.58",
156
- "@stacksjs/tunnel": "0.75.262",
157
- "@stacksjs/types": "0.75.262",
158
- "@stacksjs/ui": "0.75.262",
159
- "@stacksjs/utils": "0.75.262",
160
- "@stacksjs/validation": "0.75.262",
156
+ "@stacksjs/tunnel": "0.75.263",
157
+ "@stacksjs/types": "0.75.263",
158
+ "@stacksjs/ui": "0.75.263",
159
+ "@stacksjs/utils": "0.75.263",
160
+ "@stacksjs/validation": "0.75.263",
161
161
  "ajv": "^8.20.0",
162
162
  "ajv-formats": "^3.0.1",
163
163
  "bun-plugin-stx": "0.2.661",