@stacksjs/buddy 0.75.514 → 0.75.518
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-store-connect.js +2 -2
- package/dist/cli.js +4 -4
- package/dist/cloud-tenants.js +1 -1
- package/dist/commands/about.js +1 -1
- package/dist/commands/add.js +1 -1
- package/dist/commands/ai-access.js +2 -2
- package/dist/commands/ai-context.js +2 -2
- package/dist/commands/auth-prune-options.js +1 -1
- package/dist/commands/auth.js +1 -1
- package/dist/commands/build.js +1 -1
- package/dist/commands/cd.js +3 -3
- package/dist/commands/changelog.js +1 -1
- package/dist/commands/clean.js +1 -1
- package/dist/commands/cloud.js +7 -7
- package/dist/commands/comments.js +2 -2
- package/dist/commands/commerce-import.js +3 -3
- package/dist/commands/commit.js +1 -1
- package/dist/commands/completion.js +7 -7
- package/dist/commands/config-migrate.js +5 -5
- package/dist/commands/configure.js +2 -2
- package/dist/commands/create.js +1 -1
- package/dist/commands/db.js +1 -1
- package/dist/commands/deploy-fly.js +2 -2
- package/dist/commands/deploy-preview.js +1 -1
- package/dist/commands/deploy-ssh-target.js +1 -1
- package/dist/commands/deploy.js +588 -19
- package/dist/commands/desktop-apple.js +12 -12
- package/dist/commands/desktop-probe.js +1 -1
- package/dist/commands/dev.js +4 -4
- package/dist/commands/dns.js +2 -2
- package/dist/commands/docs/agent-counts.js +2 -2
- package/dist/commands/docs/buddy-commands.js +11 -11
- package/dist/commands/docs/capabilities.js +2 -2
- package/dist/commands/docs/desktop-matrix.js +2 -2
- package/dist/commands/docs/framework-repo.js +1 -1
- package/dist/commands/docs/generated-artifacts.js +3 -3
- package/dist/commands/docs/links.js +2 -2
- package/dist/commands/docs/native-skills.js +2 -2
- package/dist/commands/docs/snippets.js +7 -7
- package/dist/commands/doctor.js +3 -3
- package/dist/commands/domains.js +2 -2
- package/dist/commands/email.js +26 -26
- package/dist/commands/env.js +1 -1
- package/dist/commands/extension.js +3 -3
- package/dist/commands/features.js +3 -3
- package/dist/commands/feedback.js +3 -3
- package/dist/commands/fresh.js +1 -1
- package/dist/commands/gdpr.js +6 -6
- package/dist/commands/generate.js +5 -5
- package/dist/commands/http.js +1 -1
- package/dist/commands/install.js +1 -1
- package/dist/commands/integrations-probe.js +2 -2
- package/dist/commands/key.js +1 -1
- package/dist/commands/libs.js +1 -1
- package/dist/commands/link.js +2 -2
- package/dist/commands/lint.js +2 -2
- package/dist/commands/list.js +2 -2
- package/dist/commands/mail.js +13 -13
- package/dist/commands/maintenance.js +1 -1
- package/dist/commands/make.js +1 -1
- package/dist/commands/migrate-project.js +1 -1
- package/dist/commands/migrate.js +59 -59
- package/dist/commands/outdated.js +1 -1
- package/dist/commands/package.js +1 -1
- package/dist/commands/phone.js +13 -13
- package/dist/commands/ports.js +2 -2
- package/dist/commands/prepublish.js +1 -1
- package/dist/commands/preview-deploy.js +1 -1
- package/dist/commands/projects.js +1 -1
- package/dist/commands/publish.js +8 -8
- package/dist/commands/queue.js +1 -1
- package/dist/commands/release.js +7 -7
- package/dist/commands/route.js +1 -1
- package/dist/commands/saas.js +1 -1
- package/dist/commands/schedule.js +1 -1
- package/dist/commands/search.js +1 -1
- package/dist/commands/security.js +2 -2
- package/dist/commands/seed.js +1 -1
- package/dist/commands/serve.js +1 -1
- package/dist/commands/server-image.js +2 -2
- package/dist/commands/server-trust.js +2 -2
- package/dist/commands/server.js +10 -8
- package/dist/commands/setup-ai.js +2 -2
- package/dist/commands/setup.js +5 -5
- package/dist/commands/share.js +1 -1
- package/dist/commands/simulator.js +1 -1
- package/dist/commands/sms.js +25 -25
- package/dist/commands/socials.js +3 -3
- package/dist/commands/stacks.js +1 -1
- package/dist/commands/storage-backup.js +1 -1
- package/dist/commands/telemetry.js +1 -1
- package/dist/commands/test.js +1 -1
- package/dist/commands/tinker.js +1 -1
- package/dist/commands/types.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/commands/user.js +2 -2
- package/dist/config.js +1 -1
- package/dist/custom-cli.js +1 -1
- package/dist/database-backup.js +2 -2
- package/dist/database-preflight.js +1 -1
- package/dist/deploy-notify.js +3 -3
- package/dist/deployment-inputs.d.ts +6 -0
- package/dist/deployment-inputs.js +1 -0
- package/dist/deployment-revision.js +4 -4
- package/dist/dns-credentials.js +1 -1
- package/dist/email-reprocess.js +1 -1
- package/dist/feedback-links.js +1 -1
- package/dist/global-options.js +1 -1
- package/dist/lazy-commands.js +1 -1
- package/dist/mail-dns-health.js +1 -1
- package/dist/mail-users.js +1 -1
- package/dist/migrators/index.js +1 -1
- package/dist/migrators/laravel/index.js +1 -1
- package/dist/migrators/laravel/migrations.js +4 -4
- package/dist/migrators/laravel/models.js +4 -4
- package/dist/native-project.js +7 -7
- package/dist/native-site.js +2 -2
- package/dist/pantry-service-ports.js +2 -2
- package/dist/production-server.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/publish-stx.js +1 -1
- package/dist/registry.js +1 -1
- package/dist/release-ios.js +1 -1
- package/dist/result.js +1 -1
- package/dist/scaffold-app.js +4 -4
- package/dist/scaffold-desktop.js +1 -1
- package/dist/scaffold-package-app.js +7 -7
- package/dist/scaffold-site.js +1 -1
- package/dist/storage-backup.js +1 -1
- package/dist/system-dependencies.js +1 -1
- package/dist/unbacked-data.js +1 -1
- package/dist/unvendor-rewrite.js +2 -2
- package/dist/version-info.js +1 -1
- package/dist/workflow-prune.js +3 -3
- package/package.json +55 -55
package/dist/commands/make.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{createFactory,createMiddleware,createMigration,createModel,createNotification,createPage,invoke,makeAction,makeCertificate,makeCommand,makeComponent,makeDatabase,makeFunction,makeJob,makeLanguage,makeMail,makePage,makePolicy,makeQueueTable,makeResource,makeStack,setDryRun}from"@stacksjs/actions";import{intro,italic,onUnknownSubcommand,outro}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function make(buddy){const descriptions={action:"Create a new action",command:"Create a new CLI command",model:"Create a new model",middleware:"Create a new middleware",component:"Create a new component",page:"Create a new page",function:"Create a new function",job:"Create a new job",language:"Create a new language",database:"Create a new database",migration:"Create a new migration",factory:"Create a new factory",notification:"Create a new notification",mail:"Create a new Mailable + companion stx template",policy:"Create a new authorization policy",resource:"Create a new API resource",name:"The name of the action",queue:"Make queue migration",queueTable:"Create the queue jobs table migration",stack:"Create a new stack",certificate:"Create a new SSL Certificate",select:"What are you trying to make?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("make [make]","The make command").option("-a, --action [action]",descriptions.action,{default:!1}).option("-c, --component [component]",descriptions.component,{default:!1}).option("-d, --database [database]",descriptions.database,{default:!1}).option("-f, --factory [factory]",descriptions.factory,{default:!1}).option("-fn, --function [function]",descriptions.function,{default:!1}).option("-l, --language [language]",descriptions.language,{default:!1}).option("-m, --model [model]",descriptions.model,{default:!1}).option("-mw, --middleware [middleware]",descriptions.middleware,{default:!1}).option("-p, --page [page]",descriptions.page,{default:!1}).option("-mg, --migration [migration]",descriptions.migration,{default:!1}).option("-n, --notification [notification]",descriptions.notification,{default:!1}).option("-qt, --queue-table",descriptions.queue,{default:!1}).option("-s, --stack [stack]",descriptions.stack,{default:!1}).option("--dry-run","Preview the files that would be generated without writing",{default:!1}).option("--with-validation","Include a validation rules block in the generated stub",{default:!1}).option("--with-auth","Include auth-aware boilerplate in the generated stub",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(make,options)=>{log.debug("Running `buddy make` ...",options);if(!buddy.args[0]){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}setDryRun(Boolean(options.dryRun||options["dry-run"]));if(make){options.name=buddy.args[1]??make;switch(make){case"action":await makeAction(options);break;case"certificate":await makeCertificate();break;case"command":await makeCommand(options);break;case"component":await makeComponent(options);break;case"database":makeDatabase(options);break;case"function":await makeFunction(options);break;case"job":await makeJob(options);break;case"language":await makeLanguage(options);break;case"mail":await makeMail(options);break;case"migration":await createMigration(options);break;case"middleware":await createMiddleware(options);break;case"model":await createModel(options);break;case"page":await createPage(options);break;case"notification":await createNotification(options);break;case"policy":await makePolicy({name:options.name,model:typeof options.model==="string"?options.model:void 0,register:options.register});break;case"resource":await makeResource({name:options.name,model:typeof options.model==="string"?options.model:void 0});break;case"queue-table":await makeQueueTable();break;case"stack":await makeStack(options);break;case"factory":await createFactory(options);break;default:{console.error(`Unknown make subcommand: ${make}`);console.error("Valid subcommands: action, certificate, command, component, database, factory, function, job, language, mail, middleware, migration, model, notification, page, policy, queue-table, resource, stack");process.exit(ExitCode.InvalidArgument)}}}await invoke(options);process.exit(ExitCode.Success)});buddy.command("make:action [name]",descriptions.action).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--dry-run","Preview the file without writing",{default:!1}).option("--with-validation","Generate a stub that calls validate()",{default:!1}).option("--with-auth","Generate a stub that requires an authenticated user",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.info("Running `buddy make:action` ...");log.debug("Running `buddy make:action` ...",name,options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");await log.flush();process.exit(ExitCode.FatalError)}setDryRun(Boolean(options.dryRun||options["dry-run"]));await makeAction(options)});buddy.command("make:certificate",descriptions.certificate).alias("make:cert").example("buddy make:certificate").action(async(options)=>{log.debug("Running `buddy make:certificate` ...",options);await makeCertificate()});buddy.command("scaffold:crud [name]","Generate model, migration, and CRUD actions").alias("make:crud").alias("make:scaffold").option("-n, --name [name]","Resource name (PascalCase)",{default:!1}).option("-f, --fields [fields]","Comma-separated field list, e.g. title:string,body:text,published:boolean",{default:""}).option("--dry-run","Preview the generated files without writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy scaffold:crud Post --fields=title:string,body:text,published:boolean").action(async(name,options)=>{name=name??options.name;if(!name){console.error("scaffold:crud requires a resource name. Example: buddy scaffold:crud Post --fields=title:string,body:text");process.exit(ExitCode.FatalError)}const{scaffoldCrud}=await import("@stacksjs/actions");setDryRun(Boolean(options.dryRun||options["dry-run"]));try{await scaffoldCrud(name,options)}catch(err){console.error("scaffold:crud failed:",err);process.exit(ExitCode.FatalError)}});buddy.command("make:command [name]",descriptions.command).option("-n, --name [name]",descriptions.name,{default:!1}).option("-s, --signature [signature]","The command signature (CLI name)",{default:!1}).option("-d, --description [description]","The command description",{default:!1}).option("--register","Also add an entry to app/Commands.ts (optional - commands are auto-discovered)",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy make:command SendEmails").example("buddy make:command SendEmails --signature=send-emails").action(async(name,options)=>{log.debug("Running `buddy make:command` ...",options);const perf=await intro("buddy make:command");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a command name.");console.error("Example: buddy make:command SendEmails");process.exit(ExitCode.FatalError)}if(!await makeCommand(options)){await outro("While running the make:command command, there was an issue",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} command.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:component [name]",descriptions.component).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:component` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeComponent(options)});buddy.command("make:database [name]",descriptions.database).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action((name,options)=>{log.debug("Running `buddy make:database` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a database name via the `--name` option, or as the command\u2019s argument.");console.error("Example: `buddy make:database my-cool-database`");console.error("Or: `buddy make:database --name=my-cool-database`");console.error("Read more about the documentation here: https://stacksjs.com/docs/make/database");process.exit(ExitCode.FatalError)}makeDatabase(options)});buddy.command("make:factory [name]",descriptions.factory).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:factory` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await createFactory(options)});buddy.command("make:function [name]",descriptions.function).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:function` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeFunction(options)});buddy.command("make:lang [name]",descriptions.language).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:lang` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeLanguage(options)});buddy.command("make:migration [name]",descriptions.migration).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:migration` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a migration name");process.exit(ExitCode.FatalError)}await createMigration(options)});buddy.command("make:model [name]",descriptions.model).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:model` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a model name");process.exit(ExitCode.FatalError)}await createModel(options)});buddy.command("make:mail [name]",descriptions.mail).option("-n, --name [name]",descriptions.name,{default:!1}).option("-f, --force","Overwrite existing files",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy make:mail OrderShipped").example("buddy make:mail welcome-back // PascalCases to WelcomeBack, kebab-cases to welcome-back").example("buddy make:mail Welcome --force // overwrite existing files").action(async(name,options)=>{log.debug("Running `buddy make:mail` ...",options);const perf=await intro("buddy make:mail");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name (e.g. `buddy make:mail OrderShipped`).");process.exit(ExitCode.FatalError)}await makeMail(options);await outro(`Created your ${italic(name)} mailable.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:notification [name]",descriptions.notification).option("-n, --name [name]",descriptions.name,{default:!1}).option("-e, --email","Is it an email notification?",{default:!0}).option("-c, --chat","Is it a chat notification?",{default:!1}).option("-s, --sms","Is it a SMS notification?",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:notification` ...",options);const perf=await intro("buddy make:notification");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}if(!await createNotification(options)){await outro("While running the make:notification command, there was an issue",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} notification.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:policy [name]",descriptions.policy).option("-n, --name [name]",descriptions.name,{default:!1}).option("-m, --model [model]","The model this policy is for",{default:!1}).option("--no-register","Do not register in Gates.ts").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy make:policy PostPolicy").example("buddy make:policy CommentPolicy --model=Comment").action(async(name,options)=>{log.debug("Running `buddy make:policy` ...",options);const perf=await intro("buddy make:policy");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a policy name.");console.error("Example: buddy make:policy PostPolicy");process.exit(ExitCode.FatalError)}if(!await makePolicy(options)){await outro("While running the make:policy command, there was an issue",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} policy.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:resource [name]",descriptions.resource).option("-n, --name [name]",descriptions.name,{default:!1}).option("-m, --model [model]","The model this resource is for",{default:!1}).option("-c, --collection","Create a collection resource",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).example("buddy make:resource UserResource").example("buddy make:resource PostResource --model=Post").example("buddy make:resource PostCollection --collection").action(async(name,options)=>{log.debug("Running `buddy make:resource` ...",options);const perf=await intro("buddy make:resource");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a resource name.");console.error("Example: buddy make:resource UserResource");process.exit(ExitCode.FatalError)}if(!await makeResource(options)){await outro("While running the make:resource command, there was an issue",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} resource.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:queue-table",descriptions.queueTable).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy make queue:table` ...",options);await makeQueueTable()});buddy.command("make:stack [name]",descriptions.stack).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:stack` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeStack(options)});buddy.command("make:view [name]",descriptions.page).alias("make:page [name]").option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:view` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makePage(options)});buddy.command("make:middleware [name]",descriptions.middleware).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:middleware` ...",options);const perf=await intro("buddy make:middleware");name=name??options.name;options.name=name;if(!name){await outro("A middleware name is required (e.g. `buddy make:middleware EnsureSubscribed`).",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await createMiddleware(options);await outro(`Created your ${italic(name)} middleware.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:page [name]",descriptions.page).option("-n, --name [name]",descriptions.name,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:page` ...",options);const perf=await intro("buddy make:page");name=name??options.name;options.name=name;if(!name){await outro("A page name is required (e.g. `buddy make:page Pricing`).",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await createPage(options);await outro(`Created your ${italic(name)} page.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("make:job [name]",descriptions.job).option("-n, --name [name]",descriptions.name,{default:!1}).option("-q, --queue [queue]","The queue to dispatch to",{default:"default"}).option("-c, --class","Create a class-based job",{default:!1}).option("-t, --tries [tries]","Number of retry attempts",{default:3}).option("-b, --backoff [backoff]","Backoff delay in seconds",{default:3}).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(name,options)=>{log.debug("Running `buddy make:job` ...",options);const perf=await intro("buddy make:job");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a job name.");console.error("Example: buddy make:job SendWelcomeEmail");process.exit(ExitCode.FatalError)}if(!await makeJob(options)){await outro("While running the make:job command, there was an issue",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} job.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"make")}
|
|
1
|
+
import process from"node:process";import{createFactory,createMiddleware,createMigration,createModel,createNotification,createPage,invoke,makeAction,makeCertificate,makeCommand,makeComponent,makeDatabase,makeFunction,makeJob,makeLanguage,makeMail,makePage,makePolicy,makeQueueTable,makeResource,makeStack,setDryRun}from"@stacksjs/actions";import{intro,italic,onUnknownSubcommand,outro}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";export function make(buddy){const descriptions={action:"Create a new action",command:"Create a new CLI command",model:"Create a new model",middleware:"Create a new middleware",component:"Create a new component",page:"Create a new page",function:"Create a new function",job:"Create a new job",language:"Create a new language",database:"Create a new database",migration:"Create a new migration",factory:"Create a new factory",notification:"Create a new notification",mail:"Create a new Mailable + companion stx template",policy:"Create a new authorization policy",resource:"Create a new API resource",name:"The name of the action",queue:"Make queue migration",queueTable:"Create the queue jobs table migration",stack:"Create a new stack",certificate:"Create a new SSL Certificate",select:"What are you trying to make?",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("make [make]","The make command").option("-a, --action [action]",descriptions.action,{default:false}).option("-c, --component [component]",descriptions.component,{default:false}).option("-d, --database [database]",descriptions.database,{default:false}).option("-f, --factory [factory]",descriptions.factory,{default:false}).option("-fn, --function [function]",descriptions.function,{default:false}).option("-l, --language [language]",descriptions.language,{default:false}).option("-m, --model [model]",descriptions.model,{default:false}).option("-mw, --middleware [middleware]",descriptions.middleware,{default:false}).option("-p, --page [page]",descriptions.page,{default:false}).option("-mg, --migration [migration]",descriptions.migration,{default:false}).option("-n, --notification [notification]",descriptions.notification,{default:false}).option("-qt, --queue-table",descriptions.queue,{default:false}).option("-s, --stack [stack]",descriptions.stack,{default:false}).option("--dry-run","Preview the files that would be generated without writing",{default:false}).option("--with-validation","Include a validation rules block in the generated stub",{default:false}).option("--with-auth","Include auth-aware boilerplate in the generated stub",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(make,options)=>{log.debug("Running `buddy make` ...",options);const name=buddy.args[0];if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}setDryRun(Boolean(options.dryRun||options["dry-run"]));if(make){options.name=buddy.args[1]??make;switch(make){case"action":await makeAction(options);break;case"certificate":await makeCertificate();break;case"command":await makeCommand(options);break;case"component":await makeComponent(options);break;case"database":makeDatabase(options);break;case"function":await makeFunction(options);break;case"job":await makeJob(options);break;case"language":await makeLanguage(options);break;case"mail":await makeMail(options);break;case"migration":await createMigration(options);break;case"middleware":await createMiddleware(options);break;case"model":await createModel(options);break;case"page":await createPage(options);break;case"notification":await createNotification(options);break;case"policy":await makePolicy({name:options.name,model:typeof options.model==="string"?options.model:undefined,register:options.register});break;case"resource":await makeResource({name:options.name,model:typeof options.model==="string"?options.model:undefined});break;case"queue-table":await makeQueueTable();break;case"stack":await makeStack(options);break;case"factory":await createFactory(options);break;default:{console.error(`Unknown make subcommand: ${make}`);console.error("Valid subcommands: action, certificate, command, component, database, factory, function, job, language, mail, middleware, migration, model, notification, page, policy, queue-table, resource, stack");process.exit(ExitCode.InvalidArgument)}}}await invoke(options);process.exit(ExitCode.Success)});buddy.command("make:action [name]",descriptions.action).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--dry-run","Preview the file without writing",{default:false}).option("--with-validation","Generate a stub that calls validate()",{default:false}).option("--with-auth","Generate a stub that requires an authenticated user",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.info("Running `buddy make:action` ...");log.debug("Running `buddy make:action` ...",name,options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");await log.flush();process.exit(ExitCode.FatalError)}setDryRun(Boolean(options.dryRun||options["dry-run"]));await makeAction(options)});buddy.command("make:certificate",descriptions.certificate).alias("make:cert").example("buddy make:certificate").action(async(options)=>{log.debug("Running `buddy make:certificate` ...",options);await makeCertificate()});buddy.command("scaffold:crud [name]","Generate model, migration, and CRUD actions").alias("make:crud").alias("make:scaffold").option("-n, --name [name]","Resource name (PascalCase)",{default:false}).option("-f, --fields [fields]","Comma-separated field list, e.g. title:string,body:text,published:boolean",{default:""}).option("--dry-run","Preview the generated files without writing",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy scaffold:crud Post --fields=title:string,body:text,published:boolean").action(async(name,options)=>{name=name??options.name;if(!name){console.error("scaffold:crud requires a resource name. Example: buddy scaffold:crud Post --fields=title:string,body:text");process.exit(ExitCode.FatalError)}const{scaffoldCrud}=await import("@stacksjs/actions");setDryRun(Boolean(options.dryRun||options["dry-run"]));try{await scaffoldCrud(name,options)}catch(err){console.error("scaffold:crud failed:",err);process.exit(ExitCode.FatalError)}});buddy.command("make:command [name]",descriptions.command).option("-n, --name [name]",descriptions.name,{default:false}).option("-s, --signature [signature]","The command signature (CLI name)",{default:false}).option("-d, --description [description]","The command description",{default:false}).option("--register","Also add an entry to app/Commands.ts (optional - commands are auto-discovered)",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy make:command SendEmails").example("buddy make:command SendEmails --signature=send-emails").action(async(name,options)=>{log.debug("Running `buddy make:command` ...",options);const perf=await intro("buddy make:command");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a command name.");console.error("Example: buddy make:command SendEmails");process.exit(ExitCode.FatalError)}const result=await makeCommand(options);if(!result){await outro("While running the make:command command, there was an issue",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} command.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:component [name]",descriptions.component).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:component` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeComponent(options)});buddy.command("make:database [name]",descriptions.database).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action((name,options)=>{log.debug("Running `buddy make:database` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a database name via the `--name` option, or as the command’s argument.");console.error("Example: `buddy make:database my-cool-database`");console.error("Or: `buddy make:database --name=my-cool-database`");console.error("Read more about the documentation here: https://stacksjs.com/docs/make/database");process.exit(ExitCode.FatalError)}makeDatabase(options)});buddy.command("make:factory [name]",descriptions.factory).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:factory` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await createFactory(options)});buddy.command("make:function [name]",descriptions.function).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:function` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeFunction(options)});buddy.command("make:lang [name]",descriptions.language).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:lang` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeLanguage(options)});buddy.command("make:migration [name]",descriptions.migration).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:migration` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a migration name");process.exit(ExitCode.FatalError)}await createMigration(options)});buddy.command("make:model [name]",descriptions.model).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:model` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a model name");process.exit(ExitCode.FatalError)}await createModel(options)});buddy.command("make:mail [name]",descriptions.mail).option("-n, --name [name]",descriptions.name,{default:false}).option("-f, --force","Overwrite existing files",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy make:mail OrderShipped").example("buddy make:mail welcome-back // PascalCases to WelcomeBack, kebab-cases to welcome-back").example("buddy make:mail Welcome --force // overwrite existing files").action(async(name,options)=>{log.debug("Running `buddy make:mail` ...",options);const perf=await intro("buddy make:mail");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name (e.g. `buddy make:mail OrderShipped`).");process.exit(ExitCode.FatalError)}await makeMail(options);await outro(`Created your ${italic(name)} mailable.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:notification [name]",descriptions.notification).option("-n, --name [name]",descriptions.name,{default:false}).option("-e, --email","Is it an email notification?",{default:true}).option("-c, --chat","Is it a chat notification?",{default:false}).option("-s, --sms","Is it a SMS notification?",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:notification` ...",options);const perf=await intro("buddy make:notification");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}const result=await createNotification(options);if(!result){await outro("While running the make:notification command, there was an issue",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} notification.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:policy [name]",descriptions.policy).option("-n, --name [name]",descriptions.name,{default:false}).option("-m, --model [model]","The model this policy is for",{default:false}).option("--no-register","Do not register in Gates.ts").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy make:policy PostPolicy").example("buddy make:policy CommentPolicy --model=Comment").action(async(name,options)=>{log.debug("Running `buddy make:policy` ...",options);const perf=await intro("buddy make:policy");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a policy name.");console.error("Example: buddy make:policy PostPolicy");process.exit(ExitCode.FatalError)}const result=await makePolicy(options);if(!result){await outro("While running the make:policy command, there was an issue",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} policy.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:resource [name]",descriptions.resource).option("-n, --name [name]",descriptions.name,{default:false}).option("-m, --model [model]","The model this resource is for",{default:false}).option("-c, --collection","Create a collection resource",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy make:resource UserResource").example("buddy make:resource PostResource --model=Post").example("buddy make:resource PostCollection --collection").action(async(name,options)=>{log.debug("Running `buddy make:resource` ...",options);const perf=await intro("buddy make:resource");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a resource name.");console.error("Example: buddy make:resource UserResource");process.exit(ExitCode.FatalError)}const result=await makeResource(options);if(!result){await outro("While running the make:resource command, there was an issue",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} resource.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:queue-table",descriptions.queueTable).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy make queue:table` ...",options);await makeQueueTable()});buddy.command("make:stack [name]",descriptions.stack).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:stack` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makeStack(options)});buddy.command("make:view [name]",descriptions.page).alias("make:page [name]").option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:view` ...",options);name=name??options.name;options.name=name;if(!name){console.error("You need to specify a name. Read more about the documentation here.");process.exit(ExitCode.FatalError)}await makePage(options)});buddy.command("make:middleware [name]",descriptions.middleware).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:middleware` ...",options);const perf=await intro("buddy make:middleware");name=name??options.name;options.name=name;if(!name){await outro("A middleware name is required (e.g. `buddy make:middleware EnsureSubscribed`).",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await createMiddleware(options);await outro(`Created your ${italic(name)} middleware.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:page [name]",descriptions.page).option("-n, --name [name]",descriptions.name,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:page` ...",options);const perf=await intro("buddy make:page");name=name??options.name;options.name=name;if(!name){await outro("A page name is required (e.g. `buddy make:page Pricing`).",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await createPage(options);await outro(`Created your ${italic(name)} page.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("make:job [name]",descriptions.job).option("-n, --name [name]",descriptions.name,{default:false}).option("-q, --queue [queue]","The queue to dispatch to",{default:"default"}).option("-c, --class","Create a class-based job",{default:false}).option("-t, --tries [tries]","Number of retry attempts",{default:3}).option("-b, --backoff [backoff]","Backoff delay in seconds",{default:3}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{log.debug("Running `buddy make:job` ...",options);const perf=await intro("buddy make:job");name=name??options.name;options.name=name;if(!name){console.error("You need to specify a job name.");console.error("Example: buddy make:job SendWelcomeEmail");process.exit(ExitCode.FatalError)}const result=await makeJob(options);if(!result){await outro("While running the make:job command, there was an issue",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro(`Created your ${italic(name)} job.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"make")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{DRIVERS,renderReport,runMigrator}from"../migrators";export function migrateProject(buddy){buddy.command("migrate:project [target]","Port an existing project (Laravel, Rails) into a Stacks project.").option("--from <framework>",`Source framework - one of: ${Object.keys(DRIVERS).join(", ")}`,{default:"laravel"}).option("--source <path>","Path to the existing source project. Defaults to the current working directory.",{default
|
|
1
|
+
import{existsSync}from"node:fs";import{writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{DRIVERS,renderReport,runMigrator}from"../migrators";export function migrateProject(buddy){buddy.command("migrate:project [target]","Port an existing project (Laravel, Rails) into a Stacks project.").option("--from <framework>",`Source framework - one of: ${Object.keys(DRIVERS).join(", ")}`,{default:"laravel"}).option("--source <path>","Path to the existing source project. Defaults to the current working directory.",{default:false}).option("--dry-run","Show what would be translated without writing files.",{default:false}).option("--verbose","Print the per-entry table after the summary.",{default:false}).action(async(target,options)=>{const from=options.from??"laravel";if(!(from in DRIVERS)){await log.error(`Unknown source framework: '${from}'. Supported: ${Object.keys(DRIVERS).join(", ")}.`);process.exit(ExitCode.FatalError)}const sourcePath=options.source?resolve(process.cwd(),String(options.source)):process.cwd();if(!existsSync(sourcePath)){await log.error(`Source project not found: ${sourcePath}`);process.exit(ExitCode.FatalError)}const targetPath=target?resolve(process.cwd(),target):process.cwd();log.info(`Migrating ${from} project: ${sourcePath} → ${targetPath}`);if(options.dryRun)log.info("(dry run - no files will be written)");try{const report=await runMigrator({source:sourcePath,target:targetPath,from,dryRun:options.dryRun===true});const translated=report.entries.filter((e)=>e.status==="translated").length;const copied=report.entries.filter((e)=>e.status==="copied").length;const skipped=report.entries.filter((e)=>e.status==="skipped").length;const failed=report.entries.filter((e)=>e.status==="failed").length;log.info(`Translated: ${translated} | Copied: ${copied} | Skipped: ${skipped} | Failed: ${failed}`);if(options.verbose){for(const e of report.entries){const arrow=e.target?` → ${e.target}`:"";const note=e.note?` - ${e.note}`:"";log.info(` [${e.status}] ${e.source}${arrow}${note}`)}}if(!options.dryRun){const reportPath=join(targetPath,"MIGRATION_REPORT.md");await writeFile(reportPath,renderReport(report));log.success(`Report written to ${reportPath}`)}await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`Migration failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"migrate:project")}
|
package/dist/commands/migrate.js
CHANGED
|
@@ -1,76 +1,76 @@
|
|
|
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()
|
|
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();const lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:true});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:true,release:()=>{try{rmSync(lockFile,{force:true})}catch{}}}}catch{return{acquired:false,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");const parsed=JSON.parse(raw);const 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:true})}catch{}}}function countModelFiles(dir){if(!existsSync(dir)){return 0}let count=0;const entries=readdirSync(dir,{withFileTypes:true});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");const defaultModelsPath=frameworkPath("defaults/app/Models");const userModelCount=countModelFiles(userModelsPath);const defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0){return{valid:false,error:"No models found. Please create models in app/Models or ensure framework defaults exist."}}return{valid:true}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase();const dir=resolveMigrationDirectory(driver,{cwd});const relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver);const 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:false,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:false,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:true}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database");const drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return true;log.warn(await formatSchemaDrift(drift));return false}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}async function reportMissingRecordedTables(){try{const{missingRecordedTables}=await import("@stacksjs/database");const missing=await missingRecordedTables();if(missing.length===0)return true;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 false}catch(err){log.debug(`[migrate] recorded-table check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}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");const ignored=findIgnoredMigrations();if(!ignored.length)return true;log.warn(formatIgnoredMigrations(ignored));return false}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}async function reportDuplicateMigrationNumbers(options){try{const{activeMigrationDirectory,duplicateMigrationOrdinalsIn}=await import("@stacksjs/database");const groups=duplicateMigrationOrdinalsIn(await activeMigrationDirectory());const reported=options.strict?groups:groups.filter((group)=>group.generated);if(reported.length===0)return true;const lines=reported.slice(0,10).map((group)=>` • ${group.ordinal}: ${group.files.join(", ")}`);if(reported.length>10)lines.push(` • … +${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
|
-
`)}
|
|
4
|
-
${remedy}`);return
|
|
5
|
-
${files.slice(0,20).map((file)=>`
|
|
3
|
+
`)}`;const 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
|
+
${remedy}`);return false}log.warn(message);log.info(remedy);return true}catch(err){log.debug(`[migrate] duplicate migration number check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}async function reportHandWrittenMigrations(options={}){try{const{handWrittenMigrations}=await import("@stacksjs/database");const{files}=await handWrittenMigrations();if(files.length===0)return true;log.warn(`${files.length} hand-written migration${files.length===1?"":"s"} - no \`-- qb:generated\` marker, so the models do not describe ${files.length===1?"it":"them"}${options.list?`:
|
|
5
|
+
${files.slice(0,20).map((file)=>` • ${file}`).join(`
|
|
6
6
|
`)}${files.length>20?`
|
|
7
|
-
|
|
8
|
-
`)
|
|
7
|
+
• … +${files.length-20} more`:""}`:" (`./buddy migrate:status` lists them)."}`);log.info(" Move the change into app/Models and regenerate (`./buddy migrate:regenerate`), or allow the file in database.safety.allowHandWrittenMigrations.");return false}catch(err){log.debug(`[migrate] hand-written migration check skipped: ${err instanceof Error?err.message:String(err)}`);return true}}export function generatesMigrations(flag,interactive){return flag??interactive}function strictMode(options){return options.strict===true||process.env.STACKS_MIGRATE_STRICT==="1"}async function addMissingEnumLabels(){try{const{alignSchema,ENUM_ALIGN_KINDS}=await import("@stacksjs/database");const result=await alignSchema({apply:true,only:ENUM_ALIGN_KINDS});for(const action of result.plan.actions)log.info(` ${action.detail}`);if(result.applied.length>0)log.success(`Added ${result.applied.length} enum label${result.applied.length===1?"":"s"} the models declare and the database was missing.`)}catch(err){log.warn(`Could not check enum labels against the models: ${err instanceof Error?err.message:String(err)}`)}}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database");const result=await auditForeignKeys();if(result.absentTable.length>0){log.debug(`[migrate] ${result.absentTable.length} declared foreign key(s) belong to tables that are not in this database (${[...new Set(result.absentTable.map((fk)=>fk.fromTable))].join(", ")}); not reported as missing.`)}if(result.missing.length===0)return;const sample=result.missing.slice(0,5).map((fk)=>` • ${fk.fromTable}.${fk.fromColumn} → ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
|
|
8
|
+
`);const more=result.missing.length>5?`
|
|
9
9
|
+ ${result.missing.length-5} more - run \`./buddy doctor\` for the full list.`:"";log.warn(`${result.missing.length} of ${result.declared.length} declared foreign keys are missing from the live schema:
|
|
10
10
|
${sample}${more}
|
|
11
|
-
The model-backed create migrations may be stale for this database - run \`./buddy migrate:fresh\` to regenerate and replay them from the model attributes (this resets data).`)}catch(err){log.debug(`[migrate] FK integrity check skipped: ${err instanceof Error?err.message:String(err)}`)}}async function reportFkOrphans(){try{const{findFkOrphans}=await import("@stacksjs/database")
|
|
12
|
-
`)
|
|
13
|
-
+ ${result.orphans.length-5} more - run \`./buddy doctor\` for the full list.`:""
|
|
11
|
+
The model-backed create migrations may be stale for this database - run \`./buddy migrate:fresh\` to regenerate and replay them from the model attributes (this resets data).`)}catch(err){log.debug(`[migrate] FK integrity check skipped: ${err instanceof Error?err.message:String(err)}`)}}async function reportFkOrphans(){try{const{findFkOrphans}=await import("@stacksjs/database");const result=await findFkOrphans();if(!result.supported||result.total===0)return;const sample=result.orphans.slice(0,5).map((o)=>` • ${o.table}.${o.column} → ${o.parent} (${o.count} row${o.count===1?"":"s"})`).join(`
|
|
12
|
+
`);const more=result.orphans.length>5?`
|
|
13
|
+
+ ${result.orphans.length-5} more - run \`./buddy doctor\` for the full list.`:"";const 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}"
|
|
16
|
-
|
|
17
|
-
`);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=
|
|
18
|
-
|
|
19
|
-
`);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename
|
|
20
|
-
|
|
21
|
-
`);process.exit(ExitCode.FatalError)}await reportFkOrphans();const APP_ENV=process.env.APP_ENV||"local"
|
|
22
|
-
|
|
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}" → "${op.to}"`;case"rename_table":return`rename table "${op.from}" → "${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");const 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 true}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 true;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` • ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return true;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return false}return confirm({message:"Apply these destructive changes?",initial:false})}export function isMigratePreview(options,argv=process.argv){return options.diff===true||options.dryRun===true||options.pretend===true||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 true;if(v==="0"||v==="false"||v==="no"||v==="off")return false;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:undefined}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");const resolved=await awaitConfig();cfg=resolved.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??true;const 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:false}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:false}).option("--dry-run","Same as --diff: preview, change nothing",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("-a, --auth",descriptions.auth,{default:true}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:false}).option("--create-database","Create the database if it does not exist, without asking",{default:false}).option("--from-db",descriptions.fromDb,{default:false}).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:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate");const validation=validateModelsExist();if(!validation.valid){console.error(`
|
|
16
|
+
❌ Error: ${validation.error}
|
|
17
|
+
`);process.exit(ExitCode.FatalError)}const{pendingMigrationFiles:pendingForDialect}=await import("@stacksjs/database");let willRun;try{willRun=await pendingForDialect()}catch{willRun=undefined}const dialectCheck=validateMigrationDialect(process.cwd(),{only:willRun});if(!dialectCheck.valid){console.error(`
|
|
18
|
+
❌ Error: ${dialectCheck.error}
|
|
19
|
+
`);process.exit(ExitCode.FatalError)}if(!await reportDuplicateMigrationNumbers({strict:strictMode(options)}))process.exit(ExitCode.FatalError);const applyRenames=options.rename===false?false:undefined;if(options.fromDb)process.env.STACKS_MIGRATE_FROM_DB="1";if(applyRenames===false)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===undefined&&!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=false;let files=[];try{files=await pendingMigrationFiles()}catch(error){failed=true;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(` • ${file}`);if(files.length>10)log.info(` • … +${files.length-10} more`)}let ops=[];try{ops=await pendingMigrationOperations({fromDb:options.fromDb,applyRenames})}catch(error){failed=true;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(` • ${describeOp(op)}${op.destructive?" [destructive]":""}`);if(op.warning)log.warn(` ${op.warning}`)}}const drift=await auditSchemaDrift();const 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:true,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:true});process.exit(ExitCode.Success)}if(drifted&&files.length===0&&ops.length===0)logDriftRemedy();await outro("Diff complete - no changes applied.",{startTime:perf,useSeconds:true,type:drifted?"warning":"success"});process.exit(drifted&&strictMode(options)?ExitCode.FatalError:ExitCode.Success)}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate"});const guards=await resolveMigrationGuards();if(guards.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();const proceed=await confirm({message:`Run migrations against the ${APP_ENV} database "${currentDatabaseLabel()}"?`,initial:true});if(!proceed){await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:true});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){const proceed=await confirmDestructiveMigrations({force:options.force,fromDb:options.fromDb,applyRenames});if(!proceed){lock.release();await outro("Migration cancelled - no changes applied.",{startTime:perf,useSeconds:true});process.exit(isCI||!hasTTY?ExitCode.FatalError:ExitCode.Success)}}if(options.auth!==false){log.debug("Migrating auth tables...");try{const{migrateAuthTables}=await import("@stacksjs/database");const 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.")}let traitMigrationError;if(options.auth!==false){try{const{ensureUtcDatetimeColumns,ensureUtcTimestampDefaults,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database");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{migrateEnabledImpersonationTables}=await import("@stacksjs/auth/impersonation-store");await migrateEnabledImpersonationTables();const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}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){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate notification/RBAC/trait tables:",error)}}if(resultFailed(result)||traitMigrationError){await outro("While running the migrate command, there was an issue",{startTime:perf,useSeconds:true},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}if(options.auth!==false){try{const{ensureUsersAuthColumns,sqlHelpers}=await import("@stacksjs/database");const 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");const 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 addMissingEnumLabels();await reportMissingForeignKeys();const modelsMatch=await reportSchemaDrift();const tablesPresent=await reportMissingRecordedTables();const schemaMatches=modelsMatch&&tablesPresent;const allCommittable=await reportIgnoredMigrations();const allGenerated=await reportHandWrittenMigrations({list:strictMode(options)});if(strictMode(options)&&(!schemaMatches||!allCommittable||!allGenerated)){const why=!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";console.error(`
|
|
20
|
+
❌ --strict: ${why} (see above).
|
|
21
|
+
`);process.exit(ExitCode.FatalError)}await reportFkOrphans();const APP_ENV=process.env.APP_ENV||"local";const marker=readMigrateMarker();const authSuffix=options.auth!==false?" (including auth tables)":"";const 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}`;const 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:true,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:false}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:false}).option("--dry-run","Same as --diff: preview, change nothing",{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("-s, --seed","Run database seeders after migration",{default:false}).option("-a, --auth",descriptions.auth,{default:true}).option("--no-auth","Skip auth/oauth table migrations").option("--create-database","Create the database if it does not exist, without asking",{default:false}).option("-f, --force",'Skip the drop-database confirmation (only honored when the migrateFresh guard is "allow")',{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy migrate:fresh` ...",options);const perf=await intro("buddy migrate:fresh");const validation=validateModelsExist();if(!validation.valid){console.error(`
|
|
22
|
+
❌ Error: ${validation.error}
|
|
23
23
|
`);process.exit(ExitCode.FatalError)}const dialectCheck=validateMigrationDialect();if(!dialectCheck.valid){console.error(`
|
|
24
|
-
|
|
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
|
|
24
|
+
❌ Error: ${dialectCheck.error}
|
|
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:true});process.exit(ExitCode.Success)}const guards=await resolveMigrationGuards();const dbLabel=currentDatabaseLabel();const 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
|
|
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:true,type:"error"});process.exit(ExitCode.FatalError)}const canBypass=guards.migrateFresh==="allow"&&options.force===true;if(!canBypass){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:true,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();const typed=await text({message:`Type the database name "${dbLabel}" to confirm (blank to cancel):`});if(typed.trim()!==dbLabel){await outro("migrate:fresh cancelled - confirmation did not match.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}await preflightDatabase({createDatabase:options.createDatabase,command:"migrate:fresh"});await ensureDatabaseOrExit();const result=await runAction(Action.MigrateFresh,{...options,env:{...options.env,STACKS_MIGRATE_NO_AUTH:options.auth===false?"1":"0"}});if(resultFailed(result)){log.error("Model migrations failed - applying auth/notification/RBAC table guarantees before exiting.")}let traitMigrationError;if(options.auth!==false){log.debug("Migrating auth tables...");try{const{migrateAuthTables,migrateNotificationTables,migrateRbacTables,migrateTraitTables}=await import("@stacksjs/database");const 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{migrateEnabledImpersonationTables}=await import("@stacksjs/auth/impersonation-store");await migrateEnabledImpersonationTables();const traitResult=await migrateTraitTables({verbose:options.verbose});if(!traitResult.success){traitMigrationError=traitResult.error||"Polymorphic trait table migration failed";log.error(`Failed to migrate polymorphic trait tables: ${traitMigrationError}`)}}catch(error){traitMigrationError=error instanceof Error?error.message:String(error);log.error("Failed to migrate auth/notification/RBAC/trait tables:",error)}}try{const{ensureUuidColumns,sqlHelpers}=await import("@stacksjs/database");const 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)||traitMigrationError){await outro("While running the migrate:fresh command, there was an issue",{startTime:perf,useSeconds:true},resultFailed(result)?result.error:traitMigrationError);await log.flush();process.exit(ExitCode.FatalError)}await reportMissingForeignKeys();await reportSchemaDrift();if(options.seed){log.info("Running database seeders...");try{const{runApplicationSeeders,seed}=await loadSeeders();const seedResult=await seed({verbose:options.verbose,fresh:true});const applicationSeedResult=await runApplicationSeeders({verbose:options.verbose});const 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!==false)parts.push("auth tables");if(options.seed)parts.push("seeded");const suffix=parts.length>0?` & ${parts.join(" & ")}`:"";const marker=readMigrateMarker();const 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:true});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");const target=driver.toLowerCase();const allowed=new Set(["sqlite","mysql","vitess","postgres"]);if(!allowed.has(target)){console.log(`
|
|
29
29
|
Unknown target driver "${driver}". Allowed: sqlite, mysql, vitess, postgres.
|
|
30
|
-
`);await outro(
|
|
30
|
+
`);await outro(`Aborted.`,{startTime:perf,useSeconds:true,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.
|
|
32
|
-
`);await outro(
|
|
33
|
-
|
|
34
|
-
Regenerate them against ${target} before migrating, or this switch will fail on the first file.`:""
|
|
35
|
-
(These were skipped on SQLite per stacksjs/stacks#1916 and survive on disk for replay.)`:""
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
Switch plan: ${current}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
32
|
+
`);await outro(`No-op.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const requiredEnv={sqlite:["DB_DATABASE"],mysql:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],vitess:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],postgres:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],turso:["TURSO_DATABASE_URL"]};const missingEnv=(requiredEnv[target]??[]).filter((k)=>!process.env[k]);let alterCount=0;let uniqueIdxCount=0;try{const migrationsDir=resolveMigrationDirectory(target);if(existsSync(migrationsDir)){const files=readdirSync(migrationsDir).filter((f)=>f.endsWith(".sql"));for(const f of files){const content=stripSqlNoise(readFileSync(`${migrationsDir}/${f}`,"utf-8")).toLowerCase();if(/alter\s+table[\s\S]*add\s+constraint/.test(content))alterCount++;if(/^\s*create\s+unique\s+index/m.test(content))uniqueIdxCount++}}}catch{}const auditTarget=target==="vitess"?"mysql":target;const switchAudit=auditMigrationCorpus({dir:resolveMigrationDirectory(target),target:auditTarget});const switchBlocked=switchAudit.incompatible.length>0;const blockedFiles=new Set(switchAudit.incompatible.map((m)=>m.file)).size;const dialectNote=switchBlocked?`
|
|
33
|
+
⛔ ${blockedFiles} of ${switchAudit.total} migration files are ${switchAudit.inferred??"another dialect"}-flavoured and will NOT run on ${target}.
|
|
34
|
+
Regenerate them against ${target} before migrating, or this switch will fail on the first file.`:"";const sqliteFkNote=current==="sqlite"&&alterCount>0?`
|
|
35
|
+
(These were skipped on SQLite per stacksjs/stacks#1916 and survive on disk for replay.)`:"";const boolNote=current==="sqlite"&&(target==="postgres"||target==="mysql"||target==="vitess")?`
|
|
36
|
+
• Booleans land as 0/1 on SQLite; ${target} stores them as ${target==="postgres"?"true/false":"0/1 (compatible)"}.`:"";const tzNote=target==="postgres"?`
|
|
37
|
+
• PostgreSQL uses timestamptz (with TZ) where SQLite/MySQL store plain TIMESTAMP. Existing rows do NOT auto-upgrade - they ride the column's stored type.`:"";const envExtras=target!=="sqlite"?`, plus DB_HOST / DB_PORT / DB_USERNAME / DB_PASSWORD / DB_DATABASE`:``;const missingNote=missingEnv.length>0?`
|
|
38
|
+
⚠ Missing env vars for ${target}: ${missingEnv.join(", ")}`:"";console.log(`
|
|
39
|
+
Switch plan: ${current} → ${target}
|
|
40
|
+
─────────────────────────────────────────────
|
|
41
|
+
• ${alterCount} ALTER TABLE ADD CONSTRAINT migration(s) will be applied against ${target}.${sqliteFkNote}
|
|
42
|
+
• ${uniqueIdxCount} CREATE UNIQUE INDEX migration(s) will be applied against ${target}.
|
|
43
|
+
• Auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets) will be CREATE TABLE IF NOT EXISTS — they re-create cleanly under the new dialect.${boolNote}${tzNote}
|
|
44
|
+
• Existing row data does NOT auto-migrate. Use \`mysqldump\` / \`pg_dump\` (or your own export) to move it.${missingNote}${dialectNote}
|
|
45
|
+
─────────────────────────────────────────────
|
|
46
46
|
|
|
47
47
|
Next steps:
|
|
48
48
|
1. Update .env: DB_CONNECTION=${target}${envExtras}
|
|
49
49
|
2. (Optional) Export data from the current ${current} database.
|
|
50
|
-
3. ${switchBlocked?`Regenerate the migration files for ${target} FIRST - \`./buddy migrate\` will refuse until then
|
|
50
|
+
3. ${switchBlocked?`Regenerate the migration files for ${target} FIRST - \`./buddy migrate\` will refuse until then.`:`Run \`./buddy migrate\` (or \`migrate:fresh\` to start clean).`}
|
|
51
51
|
4. The post-migrate FK audit will report any constraints that didn't replay.
|
|
52
|
-
`);await outro(
|
|
53
|
-
|
|
52
|
+
`);await outro(`Plan rendered. Re-run after updating .env to actually switch.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:regenerate [dialect]","Rebuild database/migrations from your models for a given dialect").option("--dry-run","Show what would change without writing anything",{default:false}).option("-f, --force","Regenerate even though the database already has migrations recorded",{default:false}).option("--replace-unmarked","Also delete migrations carrying no @generated marker (pre-marker corpora only)",{default:false}).option("--only-existing-tables","Rebuild exactly the tables already in the corpus, for changing dialect without adopting the framework schema",{default:false}).action(async(dialect,options)=>{const perf=await intro("buddy migrate:regenerate");const target=(dialect||process.env.DB_CONNECTION||"sqlite").toLowerCase();const allowed=new Set(["sqlite","mysql","vitess","postgres","singlestore"]);if(!allowed.has(target)){log.syncError(`Unknown dialect "${target}". Allowed: sqlite, mysql, vitess, postgres, singlestore.`);process.exit(ExitCode.FatalError)}const{countAppliedMigrations,regenerateMigrationCorpus}=await import("@stacksjs/database");let applied=0;try{applied=await countAppliedMigrations()}catch{applied=0}if(applied>0&&!options.force&&!options.dryRun){log.syncError(`This database already has ${applied} migration(s) recorded.`);log.syncError("Regenerating renumbers every file, and the migrations table keys on the filename,");log.syncError("so already-applied migrations would look pending and run a second time.");log.syncError(" Point at an empty database, or re-run with --force if you know it is safe.");process.exit(ExitCode.FatalError)}const plan=await regenerateMigrationCorpus({dialect:target,dryRun:true,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(plan)){log.syncError(plan.error.message);process.exit(ExitCode.FatalError)}const{files,removed,removedObsolete,removedDataOnly,preserved,preservedOutOfScope,preservedData,relocated,models,modelRoots,unrebuildable}=plan.value;const corpusDir=relativeMigrationDirectory(plan.value.dir);const dataKept=new Set(preservedData);const outOfScope=new Set(preservedOutOfScope);const protectedHistory=preserved.filter((f)=>!outOfScope.has(f)&&!dataKept.has(f));const outOfScopeKept=preservedOutOfScope.filter((f)=>!dataKept.has(f));const movedTo=new Map(relocated.map((r)=>[r.from,r.to]));const protectedHistoryBlock=protectedHistory.length===0?"":`
|
|
53
|
+
• ${protectedHistory.length} protected history file(s) will be KEPT:
|
|
54
54
|
${protectedHistory.map((f)=>` ${f}`).join(`
|
|
55
55
|
`)}
|
|
56
56
|
These files either cannot be regenerated safely or follow a preserved
|
|
57
57
|
CREATE migration whose chronology must remain stable. --replace-unmarked
|
|
58
|
-
only replaces files that genuinely lack the @generated marker
|
|
59
|
-
|
|
58
|
+
only replaces files that genuinely lack the @generated marker.`;const obsoleteBlock=removedObsolete.length===0?"":`
|
|
59
|
+
• ${removedObsolete.length} of those describe nothing the regenerated corpus lacks (enum types it declares, drops of indexes it never builds):
|
|
60
60
|
${removedObsolete.map((f)=>` ${f}`).join(`
|
|
61
|
-
`)}
|
|
62
|
-
|
|
61
|
+
`)}`;const dataOnlyBlock=removedDataOnly.length===0?"":`
|
|
62
|
+
• ${removedDataOnly.length} of those are data-only migrations, no-ops on a fresh database:
|
|
63
63
|
${removedDataOnly.map((f)=>` ${f}`).join(`
|
|
64
64
|
`)}
|
|
65
65
|
They only DELETE or UPDATE rows, and every table the corpus builds starts
|
|
66
|
-
empty. A database that already ran them keeps their effect
|
|
67
|
-
|
|
66
|
+
empty. A database that already ran them keeps their effect.`;const dataBlock=preservedData.length===0?"":`
|
|
67
|
+
• ${preservedData.length} data migration(s) insert rows (INSERT ... VALUES / COPY) and will be KEPT:
|
|
68
68
|
${preservedData.map((f)=>` ${f}${movedTo.has(f)?` -> renumbered to ${movedTo.get(f)}`:""}`).join(`
|
|
69
69
|
`)}
|
|
70
70
|
That can be reference data no model describes, so no flag removes it.${relocated.length>0?`
|
|
71
71
|
Renumbered ones fill a table the corpus now creates, so they move after it;
|
|
72
|
-
their logical name is unchanged, so a database that ran them will not again.`:""}
|
|
73
|
-
|
|
72
|
+
their logical name is unchanged, so a database that ran them will not again.`:""}`;const OUT_OF_SCOPE_SHOWN=20;const outOfScopeMore=outOfScopeKept.length-OUT_OF_SCOPE_SHOWN;const outOfScopeBlock=outOfScopeKept.length===0?"":`
|
|
73
|
+
• ${outOfScopeKept.length} file(s) describe tables this corpus does not rebuild, and will be KEPT:
|
|
74
74
|
${outOfScopeKept.slice(0,OUT_OF_SCOPE_SHOWN).map((f)=>` ${f}`).join(`
|
|
75
75
|
`)}${outOfScopeMore>0?`
|
|
76
76
|
... and ${outOfScopeMore} more`:""}
|
|
@@ -82,22 +82,22 @@ ${outOfScopeKept.slice(0,OUT_OF_SCOPE_SHOWN).map((f)=>` ${f}`).join(`
|
|
|
82
82
|
target dialect. database.models.includeFrameworkDefaults also works, but it
|
|
83
83
|
adopts the framework's ENTIRE schema: every framework model becomes a
|
|
84
84
|
migration in your app, which for an app declaring a handful of models is
|
|
85
|
-
dozens of files it never asked for
|
|
86
|
-
|
|
85
|
+
dozens of files it never asked for.`;const unrebuildableBlock=unrebuildable.length===0?"":`
|
|
86
|
+
• ${unrebuildable.length} table(s) in this corpus have no model behind them and will KEEP their current files:
|
|
87
87
|
${unrebuildable.map((t)=>` ${t}`).join(`
|
|
88
88
|
`)}
|
|
89
89
|
Nothing can regenerate them, so those files stay in their existing dialect.
|
|
90
|
-
Publish the models with \`buddy publish model <Name>\` to convert them too
|
|
90
|
+
Publish the models with \`buddy publish model <Name>\` to convert them too.`;const rootList=modelRoots.length===0?"no model directory":modelRoots.map((root)=>relative(process.cwd(),root)||root).join(" and ");console.log(`
|
|
91
91
|
Regenerate plan: ${target}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
`);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds
|
|
99
|
-
`));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds
|
|
100
|
-
`));if(!audit.drift){if(handWrittenFails){await outro("--strict: hand-written migrations (see above).",{startTime:perf,useSeconds
|
|
92
|
+
─────────────────────────────────────────────
|
|
93
|
+
• ${models} model(s) read from ${rootList}
|
|
94
|
+
• ${files.length} migration file(s) will be written to ${corpusDir}
|
|
95
|
+
• ${removed.length} existing file(s) will be removed${obsoleteBlock}${dataOnlyBlock}${dataBlock}${protectedHistoryBlock}${outOfScopeBlock}${unrebuildableBlock}
|
|
96
|
+
• These files are tracked in git, so review with \`git diff\` afterwards
|
|
97
|
+
─────────────────────────────────────────────
|
|
98
|
+
`);if(options.dryRun){await outro("Dry run. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Replace ${removed.length} migration file(s) with ${files.length} generated for ${target}?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was written.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}const result=await regenerateMigrationCorpus({dialect:target,replaceUnmarked:options.replaceUnmarked,onlyExistingTables:options.onlyExistingTables});if(resultFailed(result)){log.syncError(result.error.message);process.exit(ExitCode.FatalError)}log.success(`Wrote ${result.value.files.length} ${target} migration file(s) to ${relativeMigrationDirectory(result.value.dir)}.`);const recordedNow=applied>0?applied:await countAppliedMigrations().catch(()=>0);if(recordedNow>0){const{reconcileMigrationLedger}=await import("@stacksjs/database");const fixed=await reconcileMigrationLedger({regenerated:{removed:result.value.removed,written:result.value.files.map((file)=>file.name)}});if(fixed.remapped.length>0)log.info(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.recorded.length>0)log.info(`Recorded ${fixed.recorded.length} regenerated migration(s) whose every table, index and type the schema already has - they will not run.`);if(fixed.retired.length>0)log.info(`Retired ${fixed.retired.length} ledger row(s) for migrations the regenerated corpus replaced.`);if(fixed.pruned.length>0)log.info(`Pruned ${fixed.pruned.length} duplicate ledger row(s).`);if(fixed.skipped.length>0){log.warn(`${fixed.skipped.length} ledger entr(ies) need a look:`);for(const entry of fixed.skipped.slice(0,10))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>10)log.info(` … +${fixed.skipped.length-10} more - run \`./buddy migrate:status\``)}log.info("This database has history. Before `./buddy migrate`, bring its schema in line with the models:");log.info(" ./buddy migrate:align # what differs, and what can be repaired safely");log.info(" ./buddy migrate:align --apply # rename legacy indexes, add missing indexes and foreign keys");log.info(" ./buddy migrate:status --reconcile # record the regenerated files the schema now satisfies")}log.info("Review the change with `git diff`, then run `./buddy migrate`.");await outro("Regenerated.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:align","Repair a live database that drifted from the models, without writing migrations (PostgreSQL)").option("--apply","Run the safe repairs, in one transaction",{default:false}).option("--widen-integers","Also widen integer columns the models declare as bigint (rewrites those tables)",{default:false}).option("--relax-constraints","Also remove obsolete NOT NULL constraints, polymorphic foreign keys, and conflicting keys with an enforced model reference",{default:false}).option("-f, --force","With --apply, skip the confirmation",{default:false}).option("--json","Emit the plan as JSON",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:align");const{alignSchema}=await import("@stacksjs/database");let planned;try{planned=await alignSchema({widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints})}catch(error){log.syncError(`Could not compare the database with the models: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}if(options.json){console.log(JSON.stringify(planned,null,2));process.exit(ExitCode.Success)}if(!planned.supported){await log.info(`migrate:align is not supported for "${planned.dialect}" yet - only PostgreSQL. Nothing was compared.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{actions,reports,refused}=planned.plan;const report=["",` Align plan: ${planned.dialect}`," ─────────────────────────────────────────────"];if(actions.length>0){report.push(` ${actions.length} safe repair(s)${options.apply?"":" - run with --apply to make them, in one transaction"}:`);for(const action of actions)report.push(` • ${action.detail}`,` ${action.sql};`);report.push("")}if(refused.length>0){report.push(` ${refused.length} repair(s) REFUSED - the data would violate them:`);for(const action of refused)report.push(` • ${action.detail}: ${action.reason}`);report.push("")}if(reports.length>0){report.push(` ${reports.length} difference(s) left for you to decide - destructive or ambiguous, never applied:`);for(const item of reports.slice(0,40))report.push(` • [${item.kind}] ${item.detail}`);if(reports.length>40)report.push(` … +${reports.length-40} more (--json lists all)`);report.push("")}if(actions.length===0&&refused.length===0&&reports.length===0)report.push(" The database matches the models.","");console.log(report.join(`
|
|
99
|
+
`));if(!options.apply||actions.length===0){await outro(options.apply?"Nothing to repair.":"Plan only. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(refused.length>0?ExitCode.FatalError:ExitCode.Success)}if(!options.force&&!isCI&&hasTTY&&process.stdin.isTTY){await log.flush();const proceed=await confirm({message:`Apply ${actions.length} repair(s) to the ${process.env.APP_ENV||"local"} database "${currentDatabaseLabel()}"?`,initial:false});if(!proceed){await outro("Cancelled. Nothing was changed.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}}try{const applied=await alignSchema({apply:true,widenIntegers:options.widenIntegers,relaxConstraints:options.relaxConstraints});await log.success(`Applied ${applied.applied.length} repair(s).`);for(const action of applied.plan.refused)await log.warn(`Refused: ${action.detail}: ${action.reason}`)}catch(error){log.syncError(`Nothing was changed - the repairs run as one transaction and it failed: ${error instanceof Error?error.message:String(error)}`);process.exit(ExitCode.FatalError)}await log.info("Migrations whose every table, index and type now exists can be recorded without running:");await log.info(" ./buddy migrate:status --reconcile");await outro("Aligned.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("migrate:status","Compare database/migrations, the migrations ledger, and the live schema").option("--reconcile","Repair the ledger where the schema proves what happened",{default:false}).option("--include-partial","With --reconcile, also record half-applied migrations",{default:false}).option("--requeue-reverted","With --reconcile, un-record the migrations of a table that is missing so the next migrate rebuilds it",{default:false}).option("--json","Emit the audit as JSON",{default:false}).option("--strict","Also fail when a migration was written by hand rather than generated from the models",{default:false}).action(async(options)=>{const perf=options.json?undefined:await intro("buddy migrate:status");const{auditMigrationLedger,handWrittenMigrations,reconcileMigrationLedger}=await import("@stacksjs/database");const audit=await auditMigrationLedger();const handWritten=(await handWrittenMigrations()).files;const strict=strictMode(options);const handWrittenFails=strict&&handWritten.length>0;if(options.json){console.log(JSON.stringify({...audit,handWritten},(_k,v)=>v instanceof Set?[...v]:v,2));process.exit(audit.drift||handWrittenFails?ExitCode.FatalError:ExitCode.Success)}if(!audit.supported){log.info(`Dialect "${audit.dialect}" is not audited. Nothing to compare.`);await outro("Skipped.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const{counts,entries,orphans}=audit;const list=(status)=>entries.filter((e)=>e.status===status).map((e)=>e.file);const report=[];const section=(heading,files)=>{if(files.length===0)return;if(heading)report.push(` ${heading}`);for(const file of files.slice(0,8))report.push(` ${file}`);if(files.length>8)report.push(` … +${files.length-8} more`);report.push("")};report.push("");report.push(` Migration status: ${audit.dialect}`);report.push(" ─────────────────────────────────────────────");report.push(` ${entries.length+audit.gated.length} file(s) on disk · ${audit.recordedCount} recorded in the ledger`);report.push("");if(counts.applied>0)report.push(` ${counts.applied} applied - recorded, and present in the schema.`,"");if(counts.unverifiable>0)report.push(` ${counts.unverifiable} unverifiable - data migrations with no schema trace to check.`,"");if(audit.gated.length>0)report.push(` ${audit.gated.length} skipped - owned by a disabled feature, so \`buddy migrate\` does not run them until it is enabled.`,"");section(`${counts.pending} pending - not applied yet, will run on the next \`buddy migrate\`:`,list("pending"));if(counts.stranded>0){report.push(` ${counts.stranded} STRANDED - already applied to the schema, but missing from the ledger.`);report.push(" These re-run on the next `buddy migrate`, which is unsafe for anything not idempotent.");section("",list("stranded"))}section(`${counts.partial} PARTIAL - some effects present, some missing. Needs a human:`,list("partial"));section(`${counts.reverted} REVERTED - recorded as applied, but the effects are gone from the schema:`,list("reverted"));if(orphans.length>0){section(`${orphans.length} orphaned ledger row(s) - recorded, but no such file on disk:`,orphans.map((o)=>{if(o.renamedTo)return`${o.migration} -> renumbered to ${o.renamedTo}`;if(audit.remapPlan.superseded.includes(o.migration))return`${o.migration} (duplicate; already recorded under its current name)`;return`${o.migration} (no counterpart; migration deleted?)`}))}if(handWritten.length>0){section(`${handWritten.length} hand-written - no \`-- qb:generated\` marker, so no model describes ${handWritten.length===1?"it":"them"}${strict?" (fails --strict)":""}:`,handWritten);report.push(" Move each change into app/Models and regenerate, or allow the file in");report.push(" database.safety.allowHandWrittenMigrations (reference data no model can describe).","")}console.log(report.join(`
|
|
100
|
+
`));if(!audit.drift){if(handWrittenFails){await outro("--strict: hand-written migrations (see above).",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("Ledger matches the corpus and the schema.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!options.reconcile){console.log(`
|
|
101
101
|
Repair with: ./buddy migrate:status --reconcile
|
|
102
102
|
That repoints renumbered ledger rows and records migrations the schema
|
|
103
103
|
already proves. It never runs SQL from a migration file.
|
|
@@ -106,4 +106,4 @@ ${unrebuildable.map((t)=>` ${t}`).join(`
|
|
|
106
106
|
./buddy migrate:status --reconcile --requeue-reverted
|
|
107
107
|
That un-records the migrations that built it, only when none of them
|
|
108
108
|
touches a table that is still there, so the next migrate rebuilds it.
|
|
109
|
-
`);await outro("Drift detected.",{startTime:perf,useSeconds
|
|
109
|
+
`);await outro("Drift detected.",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}const fixed=await reconcileMigrationLedger({includePartial:options.includePartial,requeueReverted:options.requeueReverted});if(fixed.retired.length>0)log.success(`Retired ${fixed.retired.length} ledger row(s) for migrations a regeneration replaced.`);if(fixed.remapped.length>0)log.success(`Repointed ${fixed.remapped.length} ledger row(s) at their renumbered file.`);if(fixed.requeued.length>0){log.success(`Un-recorded ${fixed.requeued.length} migration(s) so the next \`./buddy migrate\` rebuilds the missing table(s):`);for(const file of fixed.requeued.slice(0,8))log.info(` ${file}`);if(fixed.requeued.length>8)log.info(` … +${fixed.requeued.length-8} more`)}if(fixed.recorded.length>0)log.success(`Recorded ${fixed.recorded.length} migration(s) the schema already reflects.`);if(fixed.pruned.length)log.success(`Pruned ${fixed.pruned.length} duplicate ledger row(s) left by a renumbering.`);if(fixed.skipped.length>0){log.warn(`Left ${fixed.skipped.length} entr(ies) alone:`);for(const entry of fixed.skipped.slice(0,8))log.info(` ${entry.file} - ${entry.reason}`);if(fixed.skipped.length>8)log.info(` … +${fixed.skipped.length-8} more`)}if(fixed.remapped.length===0&&fixed.recorded.length===0&&fixed.pruned.length===0&&fixed.requeued.length===0)log.info("Nothing could be repaired automatically.");if(fixed.skipped.some((entry)=>entry.reason.includes("no longer exists on disk"))){log.info("A recorded migration with no file is not repaired automatically: removing the row would let it run again.");log.info(" Restore the file if it went missing by accident - a bad merge, a partial checkout.");log.info(" Delete the row by hand if the migration is genuinely retired: DELETE FROM migrations WHERE migration = '<file>'.")}await outro("Reconciled.",{startTime:perf,useSeconds:true});process.exit(handWrittenFails?ExitCode.FatalError:ExitCode.Success)});onUnknownSubcommand(buddy,"migrate")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$}from"bun";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{onUnknownSubcommand}from"@stacksjs/cli";export function outdated(buddy){const descriptions={outdated:"List all the outdated project dependencies",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("outdated",descriptions.outdated).option("--verbose",descriptions.verbose,{default
|
|
1
|
+
import{$}from"bun";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{onUnknownSubcommand}from"@stacksjs/cli";export function outdated(buddy){const descriptions={outdated:"List all the outdated project dependencies",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("outdated",descriptions.outdated).option("--verbose",descriptions.verbose,{default:false}).action(async()=>{log.debug("Running `buddy outdated` ...");$.cwd(projectPath());const response=await $`bun outdated`.text();console.log(response)});onUnknownSubcommand(buddy,"outdated")}
|
package/dist/commands/package.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function packageCommands(buddy){buddy.command("package:discover","Discover Stacks-compatible packages from pantry").option("--verbose","Enable verbose output",{default
|
|
1
|
+
import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export function packageCommands(buddy){buddy.command("package:discover","Discover Stacks-compatible packages from pantry").option("--verbose","Enable verbose output",{default:false}).action(async()=>{const perf=await intro("buddy package:discover");const{discoverPackages}=await import("@stacksjs/actions");const manifest=await discoverPackages();const count=Object.keys(manifest.packages).length;if(count>0){log.success(`Discovered ${count} Stacks package${count===1?"":"s"}:`);for(const name of Object.keys(manifest.packages)){log.info(` - ${name}`)}}else{log.info("No Stacks-compatible packages found in pantry")}await outro("Package discovery complete",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});onUnknownSubcommand(buddy,"package")}
|