@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.
Files changed (135) hide show
  1. package/dist/app-store-connect.js +2 -2
  2. package/dist/cli.js +4 -4
  3. package/dist/cloud-tenants.js +1 -1
  4. package/dist/commands/about.js +1 -1
  5. package/dist/commands/add.js +1 -1
  6. package/dist/commands/ai-access.js +2 -2
  7. package/dist/commands/ai-context.js +2 -2
  8. package/dist/commands/auth-prune-options.js +1 -1
  9. package/dist/commands/auth.js +1 -1
  10. package/dist/commands/build.js +1 -1
  11. package/dist/commands/cd.js +3 -3
  12. package/dist/commands/changelog.js +1 -1
  13. package/dist/commands/clean.js +1 -1
  14. package/dist/commands/cloud.js +7 -7
  15. package/dist/commands/comments.js +2 -2
  16. package/dist/commands/commerce-import.js +3 -3
  17. package/dist/commands/commit.js +1 -1
  18. package/dist/commands/completion.js +7 -7
  19. package/dist/commands/config-migrate.js +5 -5
  20. package/dist/commands/configure.js +2 -2
  21. package/dist/commands/create.js +1 -1
  22. package/dist/commands/db.js +1 -1
  23. package/dist/commands/deploy-fly.js +2 -2
  24. package/dist/commands/deploy-preview.js +1 -1
  25. package/dist/commands/deploy-ssh-target.js +1 -1
  26. package/dist/commands/deploy.js +588 -19
  27. package/dist/commands/desktop-apple.js +12 -12
  28. package/dist/commands/desktop-probe.js +1 -1
  29. package/dist/commands/dev.js +4 -4
  30. package/dist/commands/dns.js +2 -2
  31. package/dist/commands/docs/agent-counts.js +2 -2
  32. package/dist/commands/docs/buddy-commands.js +11 -11
  33. package/dist/commands/docs/capabilities.js +2 -2
  34. package/dist/commands/docs/desktop-matrix.js +2 -2
  35. package/dist/commands/docs/framework-repo.js +1 -1
  36. package/dist/commands/docs/generated-artifacts.js +3 -3
  37. package/dist/commands/docs/links.js +2 -2
  38. package/dist/commands/docs/native-skills.js +2 -2
  39. package/dist/commands/docs/snippets.js +7 -7
  40. package/dist/commands/doctor.js +3 -3
  41. package/dist/commands/domains.js +2 -2
  42. package/dist/commands/email.js +26 -26
  43. package/dist/commands/env.js +1 -1
  44. package/dist/commands/extension.js +3 -3
  45. package/dist/commands/features.js +3 -3
  46. package/dist/commands/feedback.js +3 -3
  47. package/dist/commands/fresh.js +1 -1
  48. package/dist/commands/gdpr.js +6 -6
  49. package/dist/commands/generate.js +5 -5
  50. package/dist/commands/http.js +1 -1
  51. package/dist/commands/install.js +1 -1
  52. package/dist/commands/integrations-probe.js +2 -2
  53. package/dist/commands/key.js +1 -1
  54. package/dist/commands/libs.js +1 -1
  55. package/dist/commands/link.js +2 -2
  56. package/dist/commands/lint.js +2 -2
  57. package/dist/commands/list.js +2 -2
  58. package/dist/commands/mail.js +13 -13
  59. package/dist/commands/maintenance.js +1 -1
  60. package/dist/commands/make.js +1 -1
  61. package/dist/commands/migrate-project.js +1 -1
  62. package/dist/commands/migrate.js +59 -59
  63. package/dist/commands/outdated.js +1 -1
  64. package/dist/commands/package.js +1 -1
  65. package/dist/commands/phone.js +13 -13
  66. package/dist/commands/ports.js +2 -2
  67. package/dist/commands/prepublish.js +1 -1
  68. package/dist/commands/preview-deploy.js +1 -1
  69. package/dist/commands/projects.js +1 -1
  70. package/dist/commands/publish.js +8 -8
  71. package/dist/commands/queue.js +1 -1
  72. package/dist/commands/release.js +7 -7
  73. package/dist/commands/route.js +1 -1
  74. package/dist/commands/saas.js +1 -1
  75. package/dist/commands/schedule.js +1 -1
  76. package/dist/commands/search.js +1 -1
  77. package/dist/commands/security.js +2 -2
  78. package/dist/commands/seed.js +1 -1
  79. package/dist/commands/serve.js +1 -1
  80. package/dist/commands/server-image.js +2 -2
  81. package/dist/commands/server-trust.js +2 -2
  82. package/dist/commands/server.js +10 -8
  83. package/dist/commands/setup-ai.js +2 -2
  84. package/dist/commands/setup.js +5 -5
  85. package/dist/commands/share.js +1 -1
  86. package/dist/commands/simulator.js +1 -1
  87. package/dist/commands/sms.js +25 -25
  88. package/dist/commands/socials.js +3 -3
  89. package/dist/commands/stacks.js +1 -1
  90. package/dist/commands/storage-backup.js +1 -1
  91. package/dist/commands/telemetry.js +1 -1
  92. package/dist/commands/test.js +1 -1
  93. package/dist/commands/tinker.js +1 -1
  94. package/dist/commands/types.js +1 -1
  95. package/dist/commands/upgrade.js +1 -1
  96. package/dist/commands/user.js +2 -2
  97. package/dist/config.js +1 -1
  98. package/dist/custom-cli.js +1 -1
  99. package/dist/database-backup.js +2 -2
  100. package/dist/database-preflight.js +1 -1
  101. package/dist/deploy-notify.js +3 -3
  102. package/dist/deployment-inputs.d.ts +6 -0
  103. package/dist/deployment-inputs.js +1 -0
  104. package/dist/deployment-revision.js +4 -4
  105. package/dist/dns-credentials.js +1 -1
  106. package/dist/email-reprocess.js +1 -1
  107. package/dist/feedback-links.js +1 -1
  108. package/dist/global-options.js +1 -1
  109. package/dist/lazy-commands.js +1 -1
  110. package/dist/mail-dns-health.js +1 -1
  111. package/dist/mail-users.js +1 -1
  112. package/dist/migrators/index.js +1 -1
  113. package/dist/migrators/laravel/index.js +1 -1
  114. package/dist/migrators/laravel/migrations.js +4 -4
  115. package/dist/migrators/laravel/models.js +4 -4
  116. package/dist/native-project.js +7 -7
  117. package/dist/native-site.js +2 -2
  118. package/dist/pantry-service-ports.js +2 -2
  119. package/dist/production-server.js +1 -1
  120. package/dist/project-setup.js +1 -1
  121. package/dist/publish-stx.js +1 -1
  122. package/dist/registry.js +1 -1
  123. package/dist/release-ios.js +1 -1
  124. package/dist/result.js +1 -1
  125. package/dist/scaffold-app.js +4 -4
  126. package/dist/scaffold-desktop.js +1 -1
  127. package/dist/scaffold-package-app.js +7 -7
  128. package/dist/scaffold-site.js +1 -1
  129. package/dist/storage-backup.js +1 -1
  130. package/dist/system-dependencies.js +1 -1
  131. package/dist/unbacked-data.js +1 -1
  132. package/dist/unvendor-rewrite.js +2 -2
  133. package/dist/version-info.js +1 -1
  134. package/dist/workflow-prune.js +3 -3
  135. package/package.json +55 -55
@@ -1 +1 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function schedule(buddy){const descriptions={project:"Target a specific project",schedule:"Run the scheduler",verbose:"Enable verbose output",list:"List all registered scheduled tasks with their next run time",status:"Show currently-held overlap locks (this-process only)",runOne:"Run one registered scheduled task immediately",inProcess:"Run a background task in this process instead of spawning it (how the scheduler starts one)",enable:"Resume a paused scheduled task",disable:"Pause a scheduled task without editing source"};buddy.command("schedule:run",descriptions.schedule).option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy schedule:run` ...",options);const perf=await intro("buddy schedule:run"),result=await runAction(Action.ScheduleRun,options);if(resultFailed(result)){await outro("While running the schedule:run command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("schedule:list",descriptions.list).option("--json","Print a machine-readable schedule registry",{default:!1}).action(async(options)=>{try{const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();const jobs=Schedule.listJobs();if(options.json){console.log(`STACKS_SCHEDULE_JSON=${JSON.stringify({jobs,locks:Schedule.listLocks()})}`);await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}if(jobs.length===0){log.info("No scheduled tasks registered.");await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}const nameWidth=Math.max(4,...jobs.map((j)=>j.name.length)),patternWidth=Math.max(7,...jobs.map((j)=>(j.pattern??"").length));log.info(`${"NAME".padEnd(nameWidth)} ${"PATTERN".padEnd(patternWidth)} STATUS TIMEZONE NEXT RUN (UTC)`);for(const j of jobs){const next=j.nextRun?j.nextRun.toISOString():"-";log.info(`${j.name.padEnd(nameWidth)} ${(j.pattern??"").padEnd(patternWidth)} ${(j.enabled?"active":"paused").padEnd(6)} ${(j.timezone??"UTC").padEnd(25)} ${next}`)}await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:list] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});buddy.command("schedule:status",descriptions.status).option("--json","Print machine-readable scheduler status",{default:!1}).action(async(options)=>{try{const{Schedule}=await import("@stacksjs/scheduler"),held=Schedule.listLocks();if(options.json){console.log(`STACKS_SCHEDULE_STATUS_JSON=${JSON.stringify({locks:held})}`);process.exit(ExitCode.Success)}if(held.length===0)log.info("No in-process scheduler locks held.");else{log.info(`Held locks (${held.length}):`);for(const name of held)log.info(` \u2022 ${name}`)}await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:status] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});buddy.command("schedule:run-one <name>",descriptions.runOne).option("--in-process",descriptions.inProcess).action(async(name,options={})=>{try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports();const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();await Schedule.runNow(name,{inProcess:options.inProcess===!0});await Schedule.gracefulShutdown();log.success(`Scheduled task ${name} completed.`);await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:run-one] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});for(const[command,enabled,description]of[["schedule:enable",!0,descriptions.enable],["schedule:disable",!1,descriptions.disable]])buddy.command(`${command} <name>`,description).action(async(name)=>{try{const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();const exists=Schedule.listJobs().some((job)=>job.name===name);await Schedule.gracefulShutdown();if(!exists)throw Error(`Scheduled task "${name}" was not found.`);Schedule.setEnabled(name,enabled);log.success(`Scheduled task ${name} ${enabled?"resumed":"paused"}.`);await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[${command}] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}})}
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function schedule(buddy){const descriptions={project:"Target a specific project",schedule:"Run the scheduler",verbose:"Enable verbose output",list:"List all registered scheduled tasks with their next run time",status:"Show currently-held overlap locks (this-process only)",runOne:"Run one registered scheduled task immediately",inProcess:"Run a background task in this process instead of spawning it (how the scheduler starts one)",enable:"Resume a paused scheduled task",disable:"Pause a scheduled task without editing source"};buddy.command("schedule:run",descriptions.schedule).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy schedule:run` ...",options);const perf=await intro("buddy schedule:run");const result=await runAction(Action.ScheduleRun,options);if(resultFailed(result)){await outro("While running the schedule:run command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}process.exit(ExitCode.Success)});buddy.command("schedule:list",descriptions.list).option("--json","Print a machine-readable schedule registry",{default:false}).action(async(options)=>{try{const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();const jobs=Schedule.listJobs();if(options.json){console.log(`STACKS_SCHEDULE_JSON=${JSON.stringify({jobs,locks:Schedule.listLocks()})}`);await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}if(jobs.length===0){log.info("No scheduled tasks registered.");await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}const nameWidth=Math.max(4,...jobs.map((j)=>j.name.length));const patternWidth=Math.max(7,...jobs.map((j)=>(j.pattern??"").length));log.info(`${"NAME".padEnd(nameWidth)} ${"PATTERN".padEnd(patternWidth)} STATUS TIMEZONE NEXT RUN (UTC)`);for(const j of jobs){const next=j.nextRun?j.nextRun.toISOString():"-";log.info(`${j.name.padEnd(nameWidth)} ${(j.pattern??"").padEnd(patternWidth)} ${(j.enabled?"active":"paused").padEnd(6)} ${(j.timezone??"UTC").padEnd(25)} ${next}`)}await Schedule.gracefulShutdown();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:list] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});buddy.command("schedule:status",descriptions.status).option("--json","Print machine-readable scheduler status",{default:false}).action(async(options)=>{try{const{Schedule}=await import("@stacksjs/scheduler");const held=Schedule.listLocks();if(options.json){console.log(`STACKS_SCHEDULE_STATUS_JSON=${JSON.stringify({locks:held})}`);process.exit(ExitCode.Success)}if(held.length===0){log.info("No in-process scheduler locks held.")}else{log.info(`Held locks (${held.length}):`);for(const name of held)log.info(` • ${name}`)}await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:status] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});buddy.command("schedule:run-one <name>",descriptions.runOne).option("--in-process",descriptions.inProcess).action(async(name,options={})=>{try{const{injectGlobalAutoImports}=await import("@stacksjs/server");await injectGlobalAutoImports();const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();await Schedule.runNow(name,{inProcess:options.inProcess===true});await Schedule.gracefulShutdown();log.success(`Scheduled task ${name} completed.`);await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[schedule:run-one] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}});for(const[command,enabled,description]of[["schedule:enable",true,descriptions.enable],["schedule:disable",false,descriptions.disable]]){buddy.command(`${command} <name>`,description).action(async(name)=>{try{const{runScheduler,Schedule}=await import("@stacksjs/scheduler");await runScheduler();await Promise.resolve();const exists=Schedule.listJobs().some((job)=>job.name===name);await Schedule.gracefulShutdown();if(!exists)throw new Error(`Scheduled task "${name}" was not found.`);Schedule.setEnabled(name,enabled);log.success(`Scheduled task ${name} ${enabled?"resumed":"paused"}.`);await log.flush();process.exit(ExitCode.Success)}catch(err){await log.error(`[${command}] failed: ${err instanceof Error?err.message:String(err)}`);process.exit(ExitCode.FatalError)}})}}
@@ -1 +1 @@
1
- import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function search(buddy){const descriptions={import:"Indexes database data to search engine",flush:"Flushes all data from search engine",settings:"Update index settings",list:"List index settings",model:"Target a specific model",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("search-engine:update",descriptions.import).option("-m, --model <model>",descriptions.model).option("-f, --flush [flush]",descriptions.flush,{default:!1}).option("-s, --settings [settings]",descriptions.settings,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).action(async(options)=>{log.debug("Running `search-engine:update` ...",options);let actionString=Action.SearchEngineImport,introString="search-engine:update";if(options.model){actionString=Action.SearchEngineImport;introString=`search-engine:update --model ${options.model}`}if(options.settings){actionString=Action.SearchEnginePushSettings;introString="search-engine:update --settings"}if(options.flush){actionString=Action.SearchEngineFlush;introString="search-engine:update --flush"}const perf=await intro(introString),result=await runAction(actionString,options);if(resultFailed(result)){await outro("While running the search-engine:update command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully imported model data to search engine.",{startTime:perf,useSeconds:!0})});buddy.command("search-engine:settings",descriptions.list).option("-m, --model <model>",descriptions.model).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `search-engine:settings` ...",options);const perf=await intro("search-engine:settings"),result=await runAction(Action.SearchEngineListSettings,options);if(resultFailed(result)){await outro("While running the search-engine:settings command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro("Successfully listed search engine index settings.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:reindex [model]","Re-index a model (Scout-style alias for search-engine:update)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??""};log.debug("Running `search:reindex` ...",opts);const perf=await intro(`search:reindex${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineImport,opts);if(resultFailed(result)){await outro("While running the search:reindex command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Reindexed ${model}.`:"Reindexed all searchable models.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("search:flush [model]","Delete all documents from a model index (Scout-style alias)").option("-p, --project [project]",descriptions.project,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(model,options)=>{const opts={...options,model:model??"",flush:!0};log.debug("Running `search:flush` ...",opts);const perf=await intro(`search:flush${model?` ${model}`:""}`),result=await runAction(Action.SearchEngineFlush,opts);if(resultFailed(result)){await outro("While running the search:flush command, there was an issue",{startTime:perf,useSeconds:!0},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Flushed ${model} from search.`:"Flushed all model indices.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)})}
1
+ import process from"node:process";import{runAction}from"@stacksjs/actions";import{intro,log,outro}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{resultFailed}from"../result";export function search(buddy){const descriptions={import:"Indexes database data to search engine",flush:"Flushes all data from search engine",settings:"Update index settings",list:"List index settings",model:"Target a specific model",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("search-engine:update",descriptions.import).option("-m, --model <model>",descriptions.model).option("-f, --flush [flush]",descriptions.flush,{default:false}).option("-s, --settings [settings]",descriptions.settings,{default:false}).option("--verbose",descriptions.verbose,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).action(async(options)=>{log.debug("Running `search-engine:update` ...",options);let actionString=Action.SearchEngineImport;let introString="search-engine:update";if(options.model){actionString=Action.SearchEngineImport;introString=`search-engine:update --model ${options.model}`}if(options.settings){actionString=Action.SearchEnginePushSettings;introString=`search-engine:update --settings`}if(options.flush){actionString=Action.SearchEngineFlush;introString=`search-engine:update --flush`}const perf=await intro(introString);const result=await runAction(actionString,options);if(resultFailed(result)){await outro("While running the search-engine:update command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(`Successfully imported model data to search engine.`,{startTime:perf,useSeconds:true})});buddy.command("search-engine:settings",descriptions.list).option("-m, --model <model>",descriptions.model).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `search-engine:settings` ...",options);const perf=await intro("search-engine:settings");const result=await runAction(Action.SearchEngineListSettings,options);if(resultFailed(result)){await outro("While running the search-engine:settings command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(`Successfully listed search engine index settings.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("search:reindex [model]","Re-index a model (Scout-style alias for search-engine:update)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(model,options)=>{const opts={...options,model:model??""};log.debug("Running `search:reindex` ...",opts);const perf=await intro(`search:reindex${model?` ${model}`:""}`);const result=await runAction(Action.SearchEngineImport,opts);if(resultFailed(result)){await outro("While running the search:reindex command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Reindexed ${model}.`:"Reindexed all searchable models.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("search:flush [model]","Delete all documents from a model index (Scout-style alias)").option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(model,options)=>{const opts={...options,model:model??"",flush:true};log.debug("Running `search:flush` ...",opts);const perf=await intro(`search:flush${model?` ${model}`:""}`);const result=await runAction(Action.SearchEngineFlush,opts);if(resultFailed(result)){await outro("While running the search:flush command, there was an issue",{startTime:perf,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro(model?`Flushed ${model} from search.`:"Flushed all model indices.",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)})}
@@ -1,2 +1,2 @@
1
- import{resolve}from"node:path";import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";const SEVERITY_NAMES=["critical","high","medium","low","none"];function parseChecks(value,flag,known){if(!value)return;const names=value.split(",").map((name)=>name.trim().toLowerCase()).filter(Boolean),unknown=names.filter((name)=>!known.includes(name));if(unknown.length)throw Error(`${flag}: unknown check ${unknown.map((name)=>`"${name}"`).join(", ")}. Choose from ${known.join(", ")}.`);return names}export function security(buddy){const descriptions={scan:"Scan the project for security vulnerabilities: vulnerable dependencies, committed secrets, dangerous code, risky GitHub workflows and repository hygiene",only:"Run only these checks, comma-separated: dependencies, secrets, code, workflows, hygiene",skip:"Skip these checks, comma-separated",json:"Print the report as JSON",failOn:"Exit non-zero for findings at or above this severity: critical, high, medium, low or none",offline:"Do not use the network (skips the dependency advisory check)",showIgnored:"List the findings that .security-ignore.json or a security-ignore comment set aside",path:"Scan this directory instead of the project"};buddy.command("security:scan",descriptions.scan).alias("audit").option("--only <checks>",descriptions.only).option("--skip <checks>",descriptions.skip).option("--json",descriptions.json,{default:!1}).option("--fail-on <severity>",descriptions.failOn,{default:"high"}).option("--offline",descriptions.offline,{default:!1}).option("--show-ignored",descriptions.showIgnored,{default:!1}).option("--path <dir>",descriptions.path).example("buddy security:scan").example("buddy security:scan --only dependencies,secrets").example("buddy security:scan --fail-on medium --json").action(async(options)=>{log.debug("Running `buddy security:scan` ...",options);const{failsScan,formatScan,runSecurityScan,SCAN_CHECKS}=await import("@stacksjs/security/scan"),failOn=String(options.failOn??"high").toLowerCase();if(!SEVERITY_NAMES.includes(failOn)){await log.error(`--fail-on: unknown severity "${failOn}". Choose from ${SEVERITY_NAMES.join(", ")}.`);process.exit(ExitCode.InvalidArgument)}let only,skip;try{only=parseChecks(options.only,"--only",SCAN_CHECKS);skip=parseChecks(options.skip,"--skip",SCAN_CHECKS)}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.InvalidArgument)}const startTime=options.json?0:await intro("buddy security:scan"),report=await runSecurityScan({cwd:options.path?resolve(options.path):projectPath(),only,skip,offline:Boolean(options.offline)}),failed=failsScan(report,failOn);if(options.json){process.stdout.write(`${JSON.stringify({...report,failOn,passed:!failed},null,2)}
2
- `);process.exit(failed?ExitCode.FatalError:ExitCode.Success)}console.log(formatScan(report,{color:process.stdout.isTTY,showIgnored:Boolean(options.showIgnored)}));if(failed){await outro(`Security scan failed (${failOn} or worse)`,{startTime,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}await outro("Security scan passed",{startTime,useSeconds:!0})});onUnknownSubcommand(buddy,"security")}
1
+ import{resolve}from"node:path";import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";const SEVERITY_NAMES=["critical","high","medium","low","none"];function parseChecks(value,flag,known){if(!value)return;const names=value.split(",").map((name)=>name.trim().toLowerCase()).filter(Boolean);const unknown=names.filter((name)=>!known.includes(name));if(unknown.length)throw new Error(`${flag}: unknown check ${unknown.map((name)=>`"${name}"`).join(", ")}. Choose from ${known.join(", ")}.`);return names}export function security(buddy){const descriptions={scan:"Scan the project for security vulnerabilities: vulnerable dependencies, committed secrets, dangerous code, risky GitHub workflows and repository hygiene",only:"Run only these checks, comma-separated: dependencies, secrets, code, workflows, hygiene",skip:"Skip these checks, comma-separated",json:"Print the report as JSON",failOn:"Exit non-zero for findings at or above this severity: critical, high, medium, low or none",offline:"Do not use the network (skips the dependency advisory check)",showIgnored:"List the findings that .security-ignore.json or a security-ignore comment set aside",path:"Scan this directory instead of the project"};buddy.command("security:scan",descriptions.scan).alias("audit").option("--only <checks>",descriptions.only).option("--skip <checks>",descriptions.skip).option("--json",descriptions.json,{default:false}).option("--fail-on <severity>",descriptions.failOn,{default:"high"}).option("--offline",descriptions.offline,{default:false}).option("--show-ignored",descriptions.showIgnored,{default:false}).option("--path <dir>",descriptions.path).example("buddy security:scan").example("buddy security:scan --only dependencies,secrets").example("buddy security:scan --fail-on medium --json").action(async(options)=>{log.debug("Running `buddy security:scan` ...",options);const{failsScan,formatScan,runSecurityScan,SCAN_CHECKS}=await import("@stacksjs/security/scan");const failOn=String(options.failOn??"high").toLowerCase();if(!SEVERITY_NAMES.includes(failOn)){await log.error(`--fail-on: unknown severity "${failOn}". Choose from ${SEVERITY_NAMES.join(", ")}.`);process.exit(ExitCode.InvalidArgument)}let only;let skip;try{only=parseChecks(options.only,"--only",SCAN_CHECKS);skip=parseChecks(options.skip,"--skip",SCAN_CHECKS)}catch(error){await log.error(error instanceof Error?error.message:String(error));process.exit(ExitCode.InvalidArgument)}const startTime=options.json?0:await intro("buddy security:scan");const report=await runSecurityScan({cwd:options.path?resolve(options.path):projectPath(),only,skip,offline:Boolean(options.offline)});const failed=failsScan(report,failOn);if(options.json){process.stdout.write(`${JSON.stringify({...report,failOn,passed:!failed},null,2)}
2
+ `);process.exit(failed?ExitCode.FatalError:ExitCode.Success)}console.log(formatScan(report,{color:process.stdout.isTTY,showIgnored:Boolean(options.showIgnored)}));if(failed){await outro(`Security scan failed (${failOn} or worse)`,{startTime,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}await outro("Security scan passed",{startTime,useSeconds:true})});onUnknownSubcommand(buddy,"security")}
@@ -1 +1 @@
1
- import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{loadSeeders}from"../seeding";export function seed(buddy){const descriptions={seed:"Seed your database",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("seed",descriptions.seed).alias("db:seed").option("--only [models]","Comma-separated list of models to seed",{default:""}).option("--except [models]","Comma-separated list of models to skip",{default:""}).option("--only-seeders [seeders]","Comma-separated list of application seeder classes to run",{default:""}).option("--tag [tags]","Comma-separated list of seeder tags to run (e.g. deploy)",{default:""}).option("--except-seeders [seeders]","Comma-separated list of application seeder classes to skip",{default:""}).option("--skip-models","Skip model-factory seeding",{default:!1}).option("--skip-application-seeders","Skip application seeders",{default:!1}).option("--include-defaults","Also seed the framework's built-in models",{default:!1}).option("--allow-protected","Seed auth/oauth models even on a non-fresh DB (will invalidate live tokens)",{default:!1}).option("--attach-accounts","Point seeded rows at existing User/Team/Customer rows, not only ones this run seeded (scratch databases only)",{default:!1}).option("--fresh","Truncate tables before seeding",{default:!1}).option("--append","Add rows to tables that already have some, instead of skipping them",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy seed` ...",options);const perf=await intro("buddy seed"),{runApplicationSeeders,seed:seedDatabase}=await loadSeeders(),list=(value)=>value?value.split(",").map((entry)=>entry.trim()).filter(Boolean):void 0,summary=options.skipModels?{total:0,successful:0,failed:0,results:[],duration:0}:await seedDatabase({verbose:options.verbose,fresh:options.fresh,append:options.append,only:list(options.only),except:list(options.except),includeDefaults:options.includeDefaults,allowProtected:options.allowProtected,attachAccounts:options.attachAccounts}),applicationSummary=options.skipApplicationSeeders?{total:0,successful:0,failed:0,results:[],duration:0}:await runApplicationSeeders({verbose:options.verbose,only:list(options.onlySeeders),except:list(options.exceptSeeders),tags:list(options.tag)}),APP_ENV=process.env.APP_ENV||"local";if(summary.total===0&&applicationSummary.total===0){await outro("No matching model or application seeders were found.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const failures=summary.failed+applicationSummary.failed;await outro(`Seeded your ${APP_ENV} database. ${summary.successful}/${summary.total} model(s) and ${applicationSummary.successful}/${applicationSummary.total} application seeder(s) completed${failures>0?`, ${failures} failed`:""}.`,{startTime:perf,useSeconds:!0,type:failures>0?"error":"success"});process.exit(failures>0?ExitCode.FatalError:ExitCode.Success)});buddy.command("seed:roles","Seed default RBAC role packs (admin, dev, client)").alias("roles:seed").action(async()=>{const perf=await intro("buddy seed:roles");try{const{seedDefaultRoles}=await import("@stacksjs/auth"),result=await seedDefaultRoles();if(result.created.length===0&&result.skipped.length>0)await outro(`All ${result.skipped.length} default role packs already exist - nothing to do.`,{startTime:perf,useSeconds:!0});else{const createdNames=result.created.map((r)=>r.name).join(", ");await outro(`Created ${result.created.length} role pack(s): ${createdNames}. Skipped ${result.skipped.length} existing.`,{startTime:perf,useSeconds:!0})}process.exit(ExitCode.Success)}catch(err){await outro("Failed to seed default roles. Most often: migrations haven't run yet (try `./buddy migrate` first).",{startTime:perf,useSeconds:!0},err);process.exit(ExitCode.FatalError)}});buddy.command("seed:admins","Make every address in config.auth.admins an administrator").alias("admins:seed").action(async()=>{const perf=await intro("buddy seed:admins");try{const{provisionAdmins}=await import("@stacksjs/auth"),result=await provisionAdmins();for(const admin of result)log.info(`${admin.outcome.padEnd(9)} ${admin.email} (user #${admin.userId})`);await outro(result.length===0?"config.auth.admins is empty - nothing to do.":`${result.filter((admin)=>admin.outcome!=="unchanged").length} of ${result.length} administrator(s) changed.`,{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}catch(err){await outro("Failed to provision administrators.",{startTime:perf,useSeconds:!0},err);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"seed")}
1
+ import process from"node:process";import{intro,log,onUnknownSubcommand,outro}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{loadSeeders}from"../seeding";export function seed(buddy){const descriptions={seed:"Seed your database",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("seed",descriptions.seed).alias("db:seed").option("--only [models]","Comma-separated list of models to seed",{default:""}).option("--except [models]","Comma-separated list of models to skip",{default:""}).option("--only-seeders [seeders]","Comma-separated list of application seeder classes to run",{default:""}).option("--tag [tags]","Comma-separated list of seeder tags to run (e.g. deploy)",{default:""}).option("--except-seeders [seeders]","Comma-separated list of application seeder classes to skip",{default:""}).option("--skip-models","Skip model-factory seeding",{default:false}).option("--skip-application-seeders","Skip application seeders",{default:false}).option("--include-defaults","Also seed the framework's built-in models",{default:false}).option("--allow-protected","Seed auth/oauth models even on a non-fresh DB (will invalidate live tokens)",{default:false}).option("--attach-accounts","Point seeded rows at existing User/Team/Customer rows, not only ones this run seeded (scratch databases only)",{default:false}).option("--fresh","Truncate tables before seeding",{default:false}).option("--append","Add rows to tables that already have some, instead of skipping them",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy seed` ...",options);const perf=await intro("buddy seed");const{runApplicationSeeders,seed:seedDatabase}=await loadSeeders();const list=(value)=>value?value.split(",").map((entry)=>entry.trim()).filter(Boolean):undefined;const summary=options.skipModels?{total:0,successful:0,failed:0,results:[],duration:0}:await seedDatabase({verbose:options.verbose,fresh:options.fresh,append:options.append,only:list(options.only),except:list(options.except),includeDefaults:options.includeDefaults,allowProtected:options.allowProtected,attachAccounts:options.attachAccounts});const applicationSummary=options.skipApplicationSeeders?{total:0,successful:0,failed:0,results:[],duration:0}:await runApplicationSeeders({verbose:options.verbose,only:list(options.onlySeeders),except:list(options.exceptSeeders),tags:list(options.tag)});const APP_ENV=process.env.APP_ENV||"local";if(summary.total===0&&applicationSummary.total===0){await outro(`No matching model or application seeders were found.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const failures=summary.failed+applicationSummary.failed;await outro(`Seeded your ${APP_ENV} database. ${summary.successful}/${summary.total} model(s) and ${applicationSummary.successful}/${applicationSummary.total} application seeder(s) completed${failures>0?`, ${failures} failed`:""}.`,{startTime:perf,useSeconds:true,type:failures>0?"error":"success"});process.exit(failures>0?ExitCode.FatalError:ExitCode.Success)});buddy.command("seed:roles","Seed default RBAC role packs (admin, dev, client)").alias("roles:seed").action(async()=>{const perf=await intro("buddy seed:roles");try{const{seedDefaultRoles}=await import("@stacksjs/auth");const result=await seedDefaultRoles();if(result.created.length===0&&result.skipped.length>0){await outro(`All ${result.skipped.length} default role packs already exist - nothing to do.`,{startTime:perf,useSeconds:true})}else{const createdNames=result.created.map((r)=>r.name).join(", ");await outro(`Created ${result.created.length} role pack(s): ${createdNames}. Skipped ${result.skipped.length} existing.`,{startTime:perf,useSeconds:true})}process.exit(ExitCode.Success)}catch(err){await outro("Failed to seed default roles. Most often: migrations haven't run yet (try `./buddy migrate` first).",{startTime:perf,useSeconds:true},err);process.exit(ExitCode.FatalError)}});buddy.command("seed:admins","Make every address in config.auth.admins an administrator").alias("admins:seed").action(async()=>{const perf=await intro("buddy seed:admins");try{const{provisionAdmins}=await import("@stacksjs/auth");const result=await provisionAdmins();for(const admin of result)log.info(`${admin.outcome.padEnd(9)} ${admin.email} (user #${admin.userId})`);await outro(result.length===0?"config.auth.admins is empty - nothing to do.":`${result.filter((admin)=>admin.outcome!=="unchanged").length} of ${result.length} administrator(s) changed.`,{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}catch(err){await outro("Failed to provision administrators.",{startTime:perf,useSeconds:true},err);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"seed")}
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";import{startProductionServer}from"../production-server";export{loadStxPartialsDir,resolveUserPartialsPath,startProductionServer}from"../production-server";export function serve(buddy){buddy.command("serve","Start the production HTTP server (STX views + /api proxy + coming-soon/maintenance gate)").option("-p, --port <port>","Port to listen on (defaults to PORT env or 3000)").option("--verbose","Enable verbose output",{default:!1}).action(startProductionServer)}export function serveApi(buddy){buddy.command("serve:api","Start the production API server (bun-router routes the frontend proxies /api to)").option("-p, --port <port>","Port to listen on (defaults to PORT env or 3008)").action(async(options)=>{if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";await import(resolveApiEntry())})}function resolveApiEntry(){const vendored=join(process.cwd(),"storage/framework/core/actions/src/serve/api.ts");if(existsSync(vendored))return vendored;return"@stacksjs/actions/serve/api"}export function preview(buddy){buddy.command("preview [dir]","Serve a static build locally, the way a static host would").option("-p, --port <port>","Port to listen on",{default:"3001"}).example("buddy preview").example("buddy preview dist --port 4000").action(async(dir,options)=>{const root=dir||"dist",port=Number(options?.port)||3001;if(!existsSync(root)){await log.error(`No \`${root}\` directory to preview. Run \`buddy build\` first, or pass the directory to serve.`);process.exit(ExitCode.FatalError)}Bun.serve({port,async fetch(req){let pathname=new URL(req.url).pathname;if(pathname==="/"||pathname==="")pathname="/index.html";else if(!pathname.includes("."))pathname=`${pathname.replace(/\/$/,"")}.html`;const file=Bun.file(join(root,pathname));if(await file.exists())return new Response(file);const notFound=Bun.file(join(root,"404.html"));if(await notFound.exists())return new Response(notFound,{status:404});return new Response("Not Found",{status:404})}});log.success(`Previewing ./${root} at http://localhost:${port}`)})}
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging";import{ExitCode}from"@stacksjs/types";import{startProductionServer}from"../production-server";export{loadStxPartialsDir,resolveUserPartialsPath,startProductionServer}from"../production-server";export function serve(buddy){buddy.command("serve","Start the production HTTP server (STX views + /api proxy + coming-soon/maintenance gate)").option("-p, --port <port>","Port to listen on (defaults to PORT env or 3000)").option("--verbose","Enable verbose output",{default:false}).action(startProductionServer)}export function serveApi(buddy){buddy.command("serve:api","Start the production API server (bun-router routes the frontend proxies /api to)").option("-p, --port <port>","Port to listen on (defaults to PORT env or 3008)").action(async(options)=>{if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";await import(resolveApiEntry())})}function resolveApiEntry(){const vendored=join(process.cwd(),"storage/framework/core/actions/src/serve/api.ts");if(existsSync(vendored))return vendored;return"@stacksjs/actions/serve/api"}export function preview(buddy){buddy.command("preview [dir]","Serve a static build locally, the way a static host would").option("-p, --port <port>","Port to listen on",{default:"3001"}).example("buddy preview").example("buddy preview dist --port 4000").action(async(dir,options)=>{const root=dir||"dist";const port=Number(options?.port)||3001;if(!existsSync(root)){await log.error(`No \`${root}\` directory to preview. Run \`buddy build\` first, or pass the directory to serve.`);process.exit(ExitCode.FatalError)}Bun.serve({port,async fetch(req){const url=new URL(req.url);let pathname=url.pathname;if(pathname==="/"||pathname==="")pathname="/index.html";else if(!pathname.includes("."))pathname=`${pathname.replace(/\/$/,"")}.html`;const file=Bun.file(join(root,pathname));if(await file.exists())return new Response(file);const notFound=Bun.file(join(root,"404.html"));if(await notFound.exists())return new Response(notFound,{status:404});return new Response("Not Found",{status:404})}});log.success(`Previewing ./${root} at http://localhost:${port}`)})}
@@ -1,2 +1,2 @@
1
- const CATALOGUE_NAMES={"raspberry-pi-os-lite":{match:/^Raspberry Pi OS Lite \(64-bit\)$/,bootVolume:"bootfs"},"raspberry-pi-os":{match:/^Raspberry Pi OS \(64-bit\)$/,bootVolume:"bootfs"},"ubuntu-24.04":{match:/^Ubuntu Server 24\.04.*\(64-bit\)$/,bootVolume:"system-boot"},"ubuntu-26.04":{match:/^Ubuntu Server 26\.04.*\(64-bit\)$/,bootVolume:"system-boot"}};export function parseOsCatalogue(raw){const found=[],seen=new Set,visit=(node)=>{if(Array.isArray(node)){for(const item of node)visit(item);return}if(!node||typeof node!=="object")return;const entry=node,name=typeof entry.name==="string"?entry.name:"",url=typeof entry.url==="string"?entry.url:"";if(name&&url)for(const[id,spec]of Object.entries(CATALOGUE_NAMES)){if(seen.has(id)||!spec.match.test(name))continue;const devices=Array.isArray(entry.devices)?entry.devices.map(String):[],init=typeof entry.init_format==="string"?entry.init_format:"";seen.add(id);found.push({id,name,url,extractSha256:typeof entry.extract_sha256==="string"?entry.extract_sha256:void 0,downloadSha256:typeof entry.image_download_sha256==="string"?entry.image_download_sha256:void 0,downloadSize:typeof entry.image_download_size==="number"?entry.image_download_size:void 0,extractSize:typeof entry.extract_size==="number"?entry.extract_size:void 0,releaseDate:typeof entry.release_date==="string"?entry.release_date:void 0,bootVolume:spec.bootVolume,firstBoot:init.startsWith("cloudinit")?"cloudinit":"unsupported",supportsPi5:devices.includes("pi5-64bit")})}for(const value of Object.values(entry))visit(value)};visit(raw);return found}export function selectImage(images,id){const image=images.find((candidate)=>candidate.id===id);if(!image)throw Error(`No image named '${id}' in the catalogue. Found: ${images.map((i)=>i.id).join(", ")||"nothing"}.`);if(image.firstBoot!=="cloudinit")throw Error(`'${image.name}' does not boot with cloud-init, so buddy cannot write its first-boot configuration. Pick a current image, or flash it with Raspberry Pi Imager and run \`buddy server:setup\` afterwards.`);return image}export function flashRefusalReason(info){const id=info.DeviceIdentifier||info.DeviceNode||"that disk";if(info.WholeDisk!==!0)return`${id} is a partition, not a whole disk. Pass the whole device, for example /dev/disk4 rather than /dev/disk4s1.`;if(info.SystemImage===!0)return`${id} holds the running macOS system.`;if(info.Internal===!0)return`${id} is an internal disk (${info.MediaName||"unknown model"}).`;if(!(info.Removable===!0||info.Ejectable===!0||info.RemovableMediaOrExternalDevice===!0))return`${id} is neither removable nor external, so buddy will not write to it.`;return null}export function describeDisk(info){const gb=typeof info.Size==="number"?`${(info.Size/1e9).toFixed(1)} GB`:"unknown size";return`${info.DeviceNode||info.DeviceIdentifier} - ${info.MediaName||"unknown model"}, ${gb}${info.BusProtocol?`, ${info.BusProtocol}`:""}`}export function resolveBootVolume(image,exists){const primary=`/Volumes/${image.bootVolume}`;if(exists(primary))return primary;for(let n=1;n<=5;n++){const candidate=`${primary} ${n}`;if(exists(candidate))return candidate}return null}export function parseDnsSdBrowse(output){const live=new Map;for(const line of output.split(`
2
- `)){const match=/\b(Add|Rmv)\b.*?\b_ssh\._tcp\.?\s+(.+?)\s*$/.exec(line);if(!match)continue;const[,action,rawName]=match,name=(rawName??"").replace(/\\032/g," ").trim();if(!name)continue;if(action==="Rmv")live.delete(name);else live.set(name,{name,hostname:`${name.replace(/\s+/g,"-")}.local`})}return[...live.values()].sort((a,b)=>a.name.localeCompare(b.name))}
1
+ const CATALOGUE_NAMES={"raspberry-pi-os-lite":{match:/^Raspberry Pi OS Lite \(64-bit\)$/,bootVolume:"bootfs"},"raspberry-pi-os":{match:/^Raspberry Pi OS \(64-bit\)$/,bootVolume:"bootfs"},"ubuntu-24.04":{match:/^Ubuntu Server 24\.04.*\(64-bit\)$/,bootVolume:"system-boot"},"ubuntu-26.04":{match:/^Ubuntu Server 26\.04.*\(64-bit\)$/,bootVolume:"system-boot"}};export function parseOsCatalogue(raw){const found=[];const seen=new Set;const visit=(node)=>{if(Array.isArray(node)){for(const item of node)visit(item);return}if(!node||typeof node!=="object")return;const entry=node;const name=typeof entry.name==="string"?entry.name:"";const url=typeof entry.url==="string"?entry.url:"";if(name&&url){for(const[id,spec]of Object.entries(CATALOGUE_NAMES)){if(seen.has(id)||!spec.match.test(name))continue;const devices=Array.isArray(entry.devices)?entry.devices.map(String):[];const init=typeof entry.init_format==="string"?entry.init_format:"";seen.add(id);found.push({id,name,url,extractSha256:typeof entry.extract_sha256==="string"?entry.extract_sha256:undefined,downloadSha256:typeof entry.image_download_sha256==="string"?entry.image_download_sha256:undefined,downloadSize:typeof entry.image_download_size==="number"?entry.image_download_size:undefined,extractSize:typeof entry.extract_size==="number"?entry.extract_size:undefined,releaseDate:typeof entry.release_date==="string"?entry.release_date:undefined,bootVolume:spec.bootVolume,firstBoot:init.startsWith("cloudinit")?"cloudinit":"unsupported",supportsPi5:devices.includes("pi5-64bit")})}}for(const value of Object.values(entry))visit(value)};visit(raw);return found}export function selectImage(images,id){const image=images.find((candidate)=>candidate.id===id);if(!image)throw new Error(`No image named '${id}' in the catalogue. Found: ${images.map((i)=>i.id).join(", ")||"nothing"}.`);if(image.firstBoot!=="cloudinit"){throw new Error(`'${image.name}' does not boot with cloud-init, so buddy cannot write its first-boot configuration. `+`Pick a current image, or flash it with Raspberry Pi Imager and run \`buddy server:setup\` afterwards.`)}return image}export function flashRefusalReason(info){const id=info.DeviceIdentifier||info.DeviceNode||"that disk";if(info.WholeDisk!==true)return`${id} is a partition, not a whole disk. Pass the whole device, for example /dev/disk4 rather than /dev/disk4s1.`;if(info.SystemImage===true)return`${id} holds the running macOS system.`;if(info.Internal===true)return`${id} is an internal disk (${info.MediaName||"unknown model"}).`;const removable=info.Removable===true||info.Ejectable===true||info.RemovableMediaOrExternalDevice===true;if(!removable)return`${id} is neither removable nor external, so buddy will not write to it.`;return null}export function describeDisk(info){const gb=typeof info.Size==="number"?`${(info.Size/1e9).toFixed(1)} GB`:"unknown size";return`${info.DeviceNode||info.DeviceIdentifier} - ${info.MediaName||"unknown model"}, ${gb}${info.BusProtocol?`, ${info.BusProtocol}`:""}`}export function resolveBootVolume(image,exists){const primary=`/Volumes/${image.bootVolume}`;if(exists(primary))return primary;for(let n=1;n<=5;n++){const candidate=`${primary} ${n}`;if(exists(candidate))return candidate}return null}export function parseDnsSdBrowse(output){const live=new Map;for(const line of output.split(`
2
+ `)){const match=/\b(Add|Rmv)\b.*?\b_ssh\._tcp\.?\s+(.+?)\s*$/.exec(line);if(!match)continue;const[,action,rawName]=match;const name=(rawName??"").replace(/\\032/g," ").trim();if(!name)continue;if(action==="Rmv")live.delete(name);else live.set(name,{name,hostname:`${name.replace(/\s+/g,"-")}.local`})}return[...live.values()].sort((a,b)=>a.name.localeCompare(b.name))}
@@ -1,2 +1,2 @@
1
- import{join}from"node:path";import process from"node:process";export const DEFAULT_LAN_CA_PATH="/etc/rpx/local-ca/rpx-root-ca.crt",CA_MISSING_EXIT=44;export function resolveCaPath(flag){return(typeof flag==="string"?flag.trim():"")||DEFAULT_LAN_CA_PATH}export function caFileSlug(host){return String(host??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"")||"host"}export function caCopyPath(host,projectRoot=process.cwd()){return join(projectRoot,"storage","cloud","ssh",`${caFileSlug(host)}.ca.crt`)}export function shellQuote(value){return`'${String(value).replace(/'/g,"'\\''")}'`}export function caReadScript(caPath){const path=shellQuote(caPath);return[`if [ -r ${path} ]; then cat ${path}; exit 0; fi`,`if [ -e ${path} ]; then sudo -n cat ${path}; exit $?; fi`,`exit ${CA_MISSING_EXIT}`].join(`
2
- `)}export function trustSummary(input){return{host:input.host,caPath:input.caPath,savedPath:input.savedPath,fingerprint:input.fingerprint,trusted:input.trusted===!0,...input.mobileconfigPath?{mobileconfigPath:input.mobileconfigPath}:{}}}export function mobileconfigInstructions(profilePath){return[`Send ${profilePath} to the device by AirDrop, mail or a link, then open it.`,"Install it under Settings > General > VPN & Device Management.","Turn on full trust under Settings > General > About > Certificate Trust Settings.","The last step is not optional. A profile that is installed but not fully trusted still fails, and the symptom looks like a bad certificate."]}
1
+ import{join}from"node:path";import process from"node:process";export const DEFAULT_LAN_CA_PATH="/etc/rpx/local-ca/rpx-root-ca.crt";export const CA_MISSING_EXIT=44;export function resolveCaPath(flag){const value=typeof flag==="string"?flag.trim():"";return value||DEFAULT_LAN_CA_PATH}export function caFileSlug(host){const slug=String(host??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"");return slug||"host"}export function caCopyPath(host,projectRoot=process.cwd()){return join(projectRoot,"storage","cloud","ssh",`${caFileSlug(host)}.ca.crt`)}export function shellQuote(value){return`'${String(value).replace(/'/g,`'\\''`)}'`}export function caReadScript(caPath){const path=shellQuote(caPath);return[`if [ -r ${path} ]; then cat ${path}; exit 0; fi`,`if [ -e ${path} ]; then sudo -n cat ${path}; exit $?; fi`,`exit ${CA_MISSING_EXIT}`].join(`
2
+ `)}export function trustSummary(input){return{host:input.host,caPath:input.caPath,savedPath:input.savedPath,fingerprint:input.fingerprint,trusted:input.trusted===true,...input.mobileconfigPath?{mobileconfigPath:input.mobileconfigPath}:{}}}export function mobileconfigInstructions(profilePath){return[`Send ${profilePath} to the device by AirDrop, mail or a link, then open it.`,"Install it under Settings > General > VPN & Device Management.","Turn on full trust under Settings > General > About > Certificate Trust Settings.","The last step is not optional. A profile that is installed but not fully trusted still fails, and the symptom looks like a bad certificate."]}
@@ -1,10 +1,12 @@
1
- import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";const log={info:(...args)=>console.log("\u2139",...args),success:(...args)=>console.log("\u2713",...args),warn:(...args)=>console.log("\u26A0",...args),error:(...args)=>console.error("\u2717",...args)},OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"}),[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":void 0},str=(key)=>{return new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out)?.[1]},num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):void 0};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"}),[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]),whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]),found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:!0});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"])if(Bun.spawnSync(["which",candidate]).exitCode===0)return[candidate,"-dc"];throw Error("No xz decompressor found, and the images are .img.xz.\n Install one with: brew install xz\n Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi(),missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"}),timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts,findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err),unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson)console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2));else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
2
- `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return!1}if(asJson)console.log(JSON.stringify({host:target.host,facts,findings},null,2));else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}return!(typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error"))}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:void 0}).option("--list","List the disks that could be written to, and exit",{default:!1}).option("--dry-run","Say what would happen without writing anything",{default:!1}).option("-y, --yes","Do not ask for confirmation before writing",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.error("Refusing to erase a disk from a non-interactive shell without confirmation.");log.info(` \u27A1\uFE0F Re-run with \`--yes\`: \`buddy server:flash --device ${info.DeviceNode} --yes\``);process.exit(ExitCode.FatalError)}if(await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:!1})!==!0){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);if(await Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:void 0}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:void 0}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:void 0}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:void 0}).option("--timezone <tz>","IANA timezone for the board",{default:void 0}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:!1}).action(async(options)=>{const perf=await intro("buddy server:first-boot"),api=await loadSshApi(),{config}=await loadSshProject(options.env),keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?void 0:options.user),os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os",bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:!0});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
3
- ${bundle.instructions}`);log.info(`Next: eject the card, boot the board, then \`buddy server:doctor ${options.hostname}.local\``);await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:doctor [host]","Check that a host can run this application before deploying to it").option("--env <name>","Environment whose configuration to check against",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--json","Print the findings as JSON",{default:!1}).action(async(host,options)=>{const perf=options.json?void 0:await intro("buddy server:doctor"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target;log.info(`Checking ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const ok=await reportPreflight(api,checked,options.json===!0);if(perf)await outro(ok?"Ready":"Not ready",{startTime:perf,useSeconds:!0});process.exit(ok?ExitCode.Success:ExitCode.FatalError)});buddy.command("server:setup [host]","Adopt a host: check it, then install what the deploy needs").option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--dry-run","Run the checks and stop before changing the host",{default:!1}).action(async(host,options)=>{const perf=await intro("buddy server:setup"),api=await loadSshApi(),{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const adopted=host_?{...target,host:host_}:target;log.info(`Adopting ${adopted.user}@${adopted.host}${adopted.port===22?"":`:${adopted.port}`}`);if(!await reportPreflight(api,adopted,!1)){log.error("The host is not ready. Nothing was changed on it.");process.exit(ExitCode.FatalError)}if(options.dryRun){log.info("Dry run: the host passed its checks and was not modified.");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const driver=api.createCloudDriver({config,provider:"ssh"});if(!driver.provisionComputeInfrastructure){log.error("This ts-cloud cannot bootstrap an SSH host (update @stacksjs/ts-cloud).");process.exit(ExitCode.FatalError)}buildBootstrapOrExit(api,config,options.env,adopted.user==="root"?void 0:adopted.user);log.info("Installing the runtime, gateway and service units if they are missing...");let outputs;try{outputs=await driver.provisionComputeInfrastructure({config,environment:options.env})}catch(err){log.error("Bootstrapping the host failed.");log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const stackName=config.project?.stackName||`${config.project?.slug||"app"}-${options.env}`,dir=join(process.cwd(),"storage","cloud","state"),statePath=join(dir,`${stackName}.json`);let recorded=null;try{recorded=existsSync(statePath)?JSON.parse(await Bun.file(statePath).text()):null}catch{recorded=null}mkdirSync(dir,{recursive:!0});await Bun.write(statePath,`${JSON.stringify(mergeSshStatePin(recorded,sshStatePin({stackName,target:adopted,deployStoragePath:outputs?.deployStoragePath})),null,2)}
4
- `);log.success(`Host adopted. Recorded at storage/cloud/state/${stackName}.json`);log.info("Next: `buddy deploy --prod`");await outro("Done",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)});buddy.command("server:trust [host]","Trust the host's own certificate authority on this machine").option("--env <name>","Environment whose configuration names the host",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:!1}).option("--ca-path <path>","Where the authority lives on the host",{default:DEFAULT_LAN_CA_PATH}).option("--mobileconfig <path>","Also write an Apple configuration profile for an iPhone or iPad",{default:void 0}).option("--export-only","Save the certificate without changing this machine, and say how to trust it by hand",{default:!1}).option("--json","Print the result as JSON",{default:!1}).action(async(host,options)=>{const asJson=options.json===!0,perf=asJson?void 0:await intro("buddy server:trust"),{target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0&&!asJson)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)if(!asJson)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target,caPath=resolveCaPath(options.caPath),fail=(reason,message,remediation,detail)=>{if(asJson)console.log(JSON.stringify({host:checked.host,caPath,error:reason,message,remediation,...detail?{detail}:{}},null,2));else{log.error(message);log.info(remediation);if(detail)log.info(detail)}process.exit(ExitCode.FatalError)};if(!asJson)log.info(`Reading ${caPath} from ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const read=await readRemoteCa(checked,caPath);if("failure"in read){if(read.failure==="missing")return fail("ca.absent",`There is no certificate authority at ${caPath} on ${checked.host}.`,"That host is not serving LAN HTTPS from its own authority. Set `ssh: { lan: { tls: 'local-ca' } }` in config/cloud.ts and run `buddy deploy --prod`, which is what creates it. Nothing was created on the host. If the authority lives elsewhere, name it with --ca-path.");if(read.failure==="unreadable")return fail("ca.unreadable",`${caPath} on ${checked.host} exists but could not be read as a certificate.`,`Check it by hand with \`ssh ${checked.user}@${checked.host} sudo cat ${caPath}\`. Reading it falls back to \`sudo -n\`, so a host whose sudo asks for a password cannot serve it to this command.`,read.detail||void 0);return fail("ssh.unreachable",`Could not reach ${checked.user}@${checked.host} over SSH.`,"Check the host is powered on and on this network, that SSH is enabled, and that your key is authorised. `buddy server:doctor` reports on all three.",read.detail.split(`
5
- `).find((line)=>line.trim())||void 0)}const pem=read.pem,{exportCA,getCertSha256Fingerprint,isCertTrusted,trustInstructions}=await import("@stacksjs/tlsx");let fingerprint;try{fingerprint=getCertSha256Fingerprint(pem)}catch(err){return fail("ca.unparseable",`The file at ${caPath} on ${checked.host} is not a certificate this can read.`,"Point --ca-path at the root certificate rpx writes, which is a PEM.",err instanceof Error?err.message:String(err))}const savedPath=caCopyPath(checked.host);mkdirSync(dirname(savedPath),{recursive:!0});await Bun.write(savedPath,pem.endsWith(`
1
+ import{createWriteStream,existsSync,mkdirSync,statSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{intro,onUnknownSubcommand,outro,prompts}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{loadTsCloudConfig,loadTsCloudDeployApi,resolveProvider}from"./deploy";import{mergeSshStatePin,resolveSshTarget,sshCliArgs,sshStatePin}from"./deploy-ssh-target";import{describeDisk,flashRefusalReason,parseDnsSdBrowse,parseOsCatalogue,resolveBootVolume,selectImage}from"./server-image";import{CA_MISSING_EXIT,caCopyPath,caReadScript,DEFAULT_LAN_CA_PATH,mobileconfigInstructions,resolveCaPath,trustSummary}from"./server-trust";const log={info:(...args)=>console.log("ℹ",...args),success:(...args)=>console.log("✓",...args),warn:(...args)=>console.log("⚠",...args),error:(...args)=>console.error("✗",...args)};const OS_CATALOGUE_URL="https://downloads.raspberrypi.com/os_list_imagingutility_v4.json";function imageCacheDir(){return join(homedir(),".cache","stacks","images")}async function readDiskInfo(device){const proc=Bun.spawn(["diskutil","info","-plist",device],{stdout:"pipe",stderr:"pipe"});const[out,code]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);if(code!==0||!out.trim())return null;const bool=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<(true|false)/>`).exec(out);return match?match[1]==="true":undefined};const str=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<string>([^<]*)</string>`).exec(out);return match?.[1]};const num=(key)=>{const match=new RegExp(`<key>${key}</key>\\s*<integer>(\\d+)</integer>`).exec(out);return match?Number(match[1]):undefined};return{DeviceIdentifier:str("DeviceIdentifier"),DeviceNode:str("DeviceNode"),MediaName:str("MediaName"),Size:num("Size"),WholeDisk:bool("WholeDisk"),Internal:bool("Internal"),Ejectable:bool("Ejectable"),Removable:bool("Removable"),RemovableMediaOrExternalDevice:bool("RemovableMediaOrExternalDevice"),SystemImage:bool("SystemImage"),BusProtocol:str("BusProtocol")}}async function listFlashableDisks(){const proc=Bun.spawn(["diskutil","list","-plist"],{stdout:"pipe",stderr:"pipe"});const[out]=await Promise.all([new Response(proc.stdout).text(),proc.exited]);const whole=[...out.matchAll(/<string>(disk\d+)<\/string>/g)].map((match)=>match[1]);const found=[];for(const id of[...new Set(whole)]){const info=await readDiskInfo(`/dev/${id}`);if(info&&flashRefusalReason(info)===null)found.push(info)}return found}async function resolveImage(os){const response=await fetch(OS_CATALOGUE_URL);if(!response.ok)throw new Error(`Could not read the image catalogue (HTTP ${response.status}). Check the network and try again.`);return selectImage(parseOsCatalogue(await response.json()),os)}async function downloadImage(image){const dir=imageCacheDir();mkdirSync(dir,{recursive:true});const target=join(dir,image.url.split("/").pop()||`${image.id}.img.xz`);if(existsSync(target)&&image.downloadSize&&statSync(target).size===image.downloadSize){log.info(`Using the cached download at ${target}`);return target}const size=image.downloadSize?` (${(image.downloadSize/1e9).toFixed(2)} GB)`:"";log.info(`Downloading ${image.name}${size}...`);const response=await fetch(image.url);if(!response.ok||!response.body)throw new Error(`Download failed (HTTP ${response.status}) for ${image.url}`);const file=createWriteStream(`${target}.part`);await Bun.write(Bun.file(`${target}.part`),response);file.close();await Bun.$`mv ${`${target}.part`} ${target}`.quiet();return target}async function resolveDecompressor(){for(const candidate of["xz","unxz"]){const which=Bun.spawnSync(["which",candidate]);if(which.exitCode===0)return[candidate,"-dc"]}throw new Error(`No xz decompressor found, and the images are .img.xz.
2
+ `+` Install one with: brew install xz
3
+ `+" Or flash the card with Raspberry Pi Imager, then run `buddy server:first-boot` against the mounted card.")}async function loadSshApi(){const api=await loadTsCloudDeployApi();const missing=["SshDriver","buildCloudInitFirstBoot","buildSshBootstrapScript","evaluatePreflight","formatPreflightFindings"].filter((name)=>typeof api[name]!=="function");if(missing.length>0){log.error("This @stacksjs/ts-cloud does not support deploying to a host over SSH.");log.error(`Missing: ${missing.join(", ")}.`);log.info("Upgrade with `bun update @stacksjs/ts-cloud`, or point TS_CLOUD_MODULE at a build that has it.");process.exit(ExitCode.FatalError)}return api}async function loadSshProject(environment){const config=await loadTsCloudConfig(environment);if(!config){log.error("No ts-cloud configuration found. Expected a `tsCloud` export from config/cloud.ts.");process.exit(ExitCode.FatalError)}const target=resolveSshTarget(config);if(!target){log.error("No SSH host configured.");log.info("Add one to config/cloud.ts: ssh: { hosts: [{ host: 'pi-stacks.local', user: 'pi' }] }");log.info("Or set TS_CLOUD_SSH_HOST (with TS_CLOUD_SSH_USER / TS_CLOUD_SSH_PORT / TS_CLOUD_SSH_KEY).");process.exit(ExitCode.FatalError)}if(resolveProvider(config)!=="ssh")log.warn(`config/cloud.ts sets provider '${resolveProvider(config)}'. Set it to 'ssh' before \`buddy deploy\` will use this host.`);return{config,target}}async function discoverHosts(seconds=4){if(process.platform!=="darwin")return[];const proc=Bun.spawn(["dns-sd","-B","_ssh._tcp","local."],{stdout:"pipe",stderr:"ignore"});const timer=setTimeout(()=>proc.kill(),seconds*1000);try{return parseDnsSdBrowse(await new Response(proc.stdout).text())}catch{return[]}finally{clearTimeout(timer)}}async function reportPreflight(api,target,asJson){const driver=new api.SshDriver({hosts:[{host:target.host,user:target.user,port:target.port,privateKeyPath:target.identityFile}],hostKey:target.hostKey,profile:target.profile});let facts;let findings;try{({facts,findings}=await driver.preflight(target.host))}catch(err){const detail=err instanceof Error?err.message:String(err);const unreachable={code:"ssh.unreachable",severity:"error",message:`Could not reach ${target.user}@${target.host} over SSH.`,remediation:"Check the board is powered on and on this network, that SSH is enabled, and that your key is authorised. A board that has just booted can take a minute to answer.",detail};if(asJson){console.log(JSON.stringify({host:target.host,facts:null,findings:[unreachable]},null,2))}else{log.error(unreachable.message);log.info(unreachable.remediation);log.info(detail.split(`
4
+ `).find((line)=>line.trim()&&!line.startsWith("Remote SSH"))||detail)}return false}if(asJson){console.log(JSON.stringify({host:target.host,facts,findings},null,2))}else{const text=api.formatPreflightFindings(findings);if(text.trim())console.log(text);else log.success("No problems found.")}const failed=typeof api.preflightFailed==="function"?api.preflightFailed(findings):findings.some((finding)=>finding.severity==="error");return!failed}function buildBootstrapOrExit(api,config,environment,sudoUser){const profile=config.ssh?.profile==="generic"?"generic":"raspberry-pi";try{return api.buildSshBootstrapScript({config,environment,profile,sudoUser,lan:config.ssh?.lan})}catch(err){console.error(err instanceof Error?err.message:String(err));log.info("Edit config/cloud.ts and run this again.");process.exit(ExitCode.FatalError)}}async function readRemoteCa(target,caPath){const proc=Bun.spawn(["ssh",...sshCliArgs(target,{connectTimeoutSec:20}),"sh","-s"],{stdin:new TextEncoder().encode(caReadScript(caPath)),stdout:"pipe",stderr:"pipe"});const[out,err,code]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);if(code===CA_MISSING_EXIT)return{failure:"missing",detail:""};if(code!==0)return{failure:err.toLowerCase().includes("sudo")?"unreadable":"unreachable",detail:err.trim()};if(!out.includes("-----BEGIN CERTIFICATE-----"))return{failure:"unreadable",detail:""};return{pem:out}}function trustPlatform(){if(process.platform==="darwin")return"macos";return process.platform==="win32"?"windows":"debian"}export function server(buddy){const descriptions={flash:"Write a Linux OS image to an SD card or USB disk",os:"Which image to write: raspberry-pi-os-lite, raspberry-pi-os, ubuntu-24.04, ubuntu-26.04",device:"The whole disk to write to, for example /dev/disk4",verbose:"Enable verbose output"};buddy.command("server:flash",descriptions.flash).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--device <path>",descriptions.device,{default:undefined}).option("--list","List the disks that could be written to, and exit",{default:false}).option("--dry-run","Say what would happen without writing anything",{default:false}).option("-y, --yes","Do not ask for confirmation before writing",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{const perf=await intro("buddy server:flash");if(process.platform!=="darwin"){log.error("`buddy server:flash` currently supports macOS only.");log.info("On Linux, write the image with `dd`, then run `buddy server:first-boot` against the mounted boot partition.");process.exit(ExitCode.FatalError)}const disks=await listFlashableDisks();if(options.list){if(disks.length===0)log.info("No removable disks are attached.");for(const disk of disks)log.info(` ${describeDisk(disk)}`);await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}let image;try{image=await resolveImage(options.os)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Image: ${image.name} (${image.releaseDate??"unknown date"})`);if(!image.supportsPi5)log.warn("This image is not listed as supporting the Raspberry Pi 5.");let device=options.device;if(!device){if(disks.length===0){log.error("No removable disk is attached. Insert the card and try again, or pass --device.");process.exit(ExitCode.FatalError)}if(disks.length>1){log.error("Several removable disks are attached, so buddy will not pick one:");for(const disk of disks)log.error(` ${describeDisk(disk)}`);log.info("Re-run with --device /dev/diskN naming the one you mean.");process.exit(ExitCode.FatalError)}device=disks[0]?.DeviceNode}const info=device?await readDiskInfo(device):null;if(!info){log.error(`Could not read ${device}. Check the device path with \`diskutil list\`.`);process.exit(ExitCode.FatalError)}const refusal=flashRefusalReason(info);if(refusal){log.error(refusal);process.exit(ExitCode.FatalError)}let decompressor;try{decompressor=await resolveDecompressor()}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}log.info(`Target: ${describeDisk(info)}`);if(options.dryRun){log.info("Dry run: nothing was downloaded and nothing was written.");await outro("Exited",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY||!process.stdin.isTTY){log.error("Refusing to erase a disk from a non-interactive shell without confirmation.");log.info(` ➡️ Re-run with \`--yes\`: \`buddy server:flash --device ${info.DeviceNode} --yes\``);process.exit(ExitCode.FatalError)}const answer=await prompts.confirm({message:`Erase ${describeDisk(info)} and write ${image.name}?`,initial:false});if(answer!==true){log.info("Nothing was written.");process.exit(ExitCode.Success)}}let download;try{download=await downloadImage(image)}catch(err){log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const raw=info.DeviceNode.replace("/dev/disk","/dev/rdisk");log.info(`Unmounting ${info.DeviceNode}...`);await Bun.$`diskutil unmountDisk ${info.DeviceNode}`.nothrow();log.info("Writing the image. This needs your password, and takes a few minutes.");log.info(` ${decompressor.join(" ")} ${download} | sudo dd of=${raw} bs=4m status=progress`);const write=Bun.spawn(["sh","-c",`${decompressor[0]} -dc ${JSON.stringify(download)} | sudo dd of=${JSON.stringify(raw)} bs=4m status=progress`],{stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(await write.exited!==0){log.error("Writing the image failed. The card is probably unusable until it is written again.");process.exit(ExitCode.FatalError)}await Bun.$`sync`.nothrow();log.success("Image written.");const boot=resolveBootVolume(image,existsSync);if(boot)log.info(`Boot partition mounted at ${boot}`);else log.info(`Re-insert the card if it does not mount, then look for /Volumes/${image.bootVolume}`);log.info("Next: `buddy server:first-boot --hostname <name> --user <name>` to configure the first boot.");await outro("Done",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("server:first-boot","Write the first-boot configuration onto a freshly flashed card").option("--hostname <name>","The name the board answers to on the network",{default:"pi-stacks"}).option("--user <name>","The login to create, which the deploy then uses",{default:"pi"}).option("--ssh-key <path>","Public key to authorise",{default:undefined}).option("--os <name>",descriptions.os,{default:"raspberry-pi-os-lite"}).option("--out <dir>","Write the files here instead of the mounted boot partition",{default:undefined}).option("--wifi-ssid <ssid>","Join this wireless network on first boot",{default:undefined}).option("--wifi-country <code>","Two-letter regulatory domain, required with wifi",{default:undefined}).option("--timezone <tz>","IANA timezone for the board",{default:undefined}).option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--force","Overwrite first-boot files already on the card",{default:false}).action(async(options)=>{const perf=await intro("buddy server:first-boot");const api=await loadSshApi();const{config}=await loadSshProject(options.env);const keyPath=options.sshKey||join(homedir(),".ssh","id_ed25519.pub");if(!existsSync(keyPath)){log.error(`No public key at ${keyPath}.`);log.info("Generate one with: ssh-keygen -t ed25519");log.info("Or point at an existing key with --ssh-key.");process.exit(ExitCode.FatalError)}let wifi;if(options.wifiSsid){if(!options.wifiCountry){log.error("--wifi-country is required with --wifi-ssid. It sets the radio regulatory domain.");process.exit(ExitCode.FatalError)}const passphrase=process.env.WIFI_PASSWORD||await prompts.password({message:`Passphrase for ${options.wifiSsid}`});if(typeof passphrase!=="string"||!passphrase){log.error("No wireless passphrase given.");process.exit(ExitCode.FatalError)}wifi={ssid:options.wifiSsid,passphrase,country:String(options.wifiCountry).toUpperCase()}}const bootstrap=buildBootstrapOrExit(api,config,options.env,options.user==="root"?undefined:options.user);const os=String(options.os).startsWith("ubuntu")?"ubuntu":"raspberry-pi-os";const bundle=api.buildCloudInitFirstBoot({hostname:options.hostname,user:options.user,publicKey:(await Bun.file(keyPath).text()).trim(),timezone:options.timezone,wifi},bootstrap,{os});let destination=options.out;if(!destination){const image=await resolveImage(options.os).catch(()=>null);destination=image?resolveBootVolume(image,existsSync):null;if(!destination){log.error("The card does not appear to be mounted.");log.info("Insert the freshly written card and try again, or pass --out <dir> to write the files elsewhere.");process.exit(ExitCode.FatalError)}}mkdirSync(destination,{recursive:true});for(const name of Object.keys(bundle.files)){const path=join(destination,name);if(existsSync(path)&&!options.force){log.error(`${path} already exists. Re-run with --force to replace it.`);process.exit(ExitCode.FatalError)}}for(const[name,contents]of Object.entries(bundle.files)){await Bun.write(join(destination,name),contents);log.success(`Wrote ${join(destination,name)}`)}if(bundle.instructions)console.log(`
5
+ ${bundle.instructions}`);log.info(`Next: eject the card, boot the board, then \`buddy server:doctor ${options.hostname}.local\``);await outro("Done",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("server:doctor [host]","Check that a host can run this application before deploying to it").option("--env <name>","Environment whose configuration to check against",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:false}).option("--json","Print the findings as JSON",{default:false}).action(async(host,options)=>{const perf=options.json?undefined:await intro("buddy server:doctor");const api=await loadSshApi();const{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0)log.info("No hosts advertising SSH were found on this network.");for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target;log.info(`Checking ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const ok=await reportPreflight(api,checked,options.json===true);if(perf)await outro(ok?"Ready":"Not ready",{startTime:perf,useSeconds:true});process.exit(ok?ExitCode.Success:ExitCode.FatalError)});buddy.command("server:setup [host]","Adopt a host: check it, then install what the deploy needs").option("--env <name>","Environment whose configuration to bootstrap",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:false}).option("--dry-run","Run the checks and stop before changing the host",{default:false}).action(async(host,options)=>{const perf=await intro("buddy server:setup");const api=await loadSshApi();const{config,target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();for(const entry of found)log.info(` ${entry.hostname}`);host_=found[0]?.hostname}const adopted=host_?{...target,host:host_}:target;log.info(`Adopting ${adopted.user}@${adopted.host}${adopted.port===22?"":`:${adopted.port}`}`);if(!await reportPreflight(api,adopted,false)){log.error("The host is not ready. Nothing was changed on it.");process.exit(ExitCode.FatalError)}if(options.dryRun){log.info("Dry run: the host passed its checks and was not modified.");await outro("Done",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)}const driver=api.createCloudDriver({config,provider:"ssh"});if(!driver.provisionComputeInfrastructure){log.error("This ts-cloud cannot bootstrap an SSH host (update @stacksjs/ts-cloud).");process.exit(ExitCode.FatalError)}buildBootstrapOrExit(api,config,options.env,adopted.user==="root"?undefined:adopted.user);log.info("Installing the runtime, gateway and service units if they are missing...");let outputs;try{outputs=await driver.provisionComputeInfrastructure({config,environment:options.env})}catch(err){log.error("Bootstrapping the host failed.");log.error(err instanceof Error?err.message:String(err));process.exit(ExitCode.FatalError)}const stackName=config.project?.stackName||`${config.project?.slug||"app"}-${options.env}`;const dir=join(process.cwd(),"storage","cloud","state");const statePath=join(dir,`${stackName}.json`);let recorded=null;try{recorded=existsSync(statePath)?JSON.parse(await Bun.file(statePath).text()):null}catch{recorded=null}mkdirSync(dir,{recursive:true});await Bun.write(statePath,`${JSON.stringify(mergeSshStatePin(recorded,sshStatePin({stackName,target:adopted,deployStoragePath:outputs?.deployStoragePath})),null,2)}
6
+ `);log.success(`Host adopted. Recorded at storage/cloud/state/${stackName}.json`);log.info("Next: `buddy deploy --prod`");await outro("Done",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)});buddy.command("server:trust [host]","Trust the host's own certificate authority on this machine").option("--env <name>","Environment whose configuration names the host",{default:"production"}).option("--discover","Browse the local network for hosts advertising SSH",{default:false}).option("--ca-path <path>","Where the authority lives on the host",{default:DEFAULT_LAN_CA_PATH}).option("--mobileconfig <path>","Also write an Apple configuration profile for an iPhone or iPad",{default:undefined}).option("--export-only","Save the certificate without changing this machine, and say how to trust it by hand",{default:false}).option("--json","Print the result as JSON",{default:false}).action(async(host,options)=>{const asJson=options.json===true;const perf=asJson?undefined:await intro("buddy server:trust");const{target}=await loadSshProject(options.env);let host_=host;if(!host_&&options.discover){const found=await discoverHosts();if(found.length===0&&!asJson)log.info("No hosts advertising SSH were found on this network.");for(const entry of found){if(!asJson)log.info(` ${entry.hostname}`)}host_=found[0]?.hostname}const checked=host_?{...target,host:host_}:target;const caPath=resolveCaPath(options.caPath);const fail=(reason,message,remediation,detail)=>{if(asJson){console.log(JSON.stringify({host:checked.host,caPath,error:reason,message,remediation,...detail?{detail}:{}},null,2))}else{log.error(message);log.info(remediation);if(detail)log.info(detail)}process.exit(ExitCode.FatalError)};if(!asJson)log.info(`Reading ${caPath} from ${checked.user}@${checked.host}${checked.port===22?"":`:${checked.port}`}...`);const read=await readRemoteCa(checked,caPath);if("failure"in read){if(read.failure==="missing"){return fail("ca.absent",`There is no certificate authority at ${caPath} on ${checked.host}.`,"That host is not serving LAN HTTPS from its own authority. Set `ssh: { lan: { tls: 'local-ca' } }` in config/cloud.ts and run `buddy deploy --prod`, which is what creates it. Nothing was created on the host. If the authority lives elsewhere, name it with --ca-path.")}if(read.failure==="unreadable"){return fail("ca.unreadable",`${caPath} on ${checked.host} exists but could not be read as a certificate.`,`Check it by hand with \`ssh ${checked.user}@${checked.host} sudo cat ${caPath}\`. Reading it falls back to \`sudo -n\`, so a host whose sudo asks for a password cannot serve it to this command.`,read.detail||undefined)}return fail("ssh.unreachable",`Could not reach ${checked.user}@${checked.host} over SSH.`,"Check the host is powered on and on this network, that SSH is enabled, and that your key is authorised. `buddy server:doctor` reports on all three.",read.detail.split(`
7
+ `).find((line)=>line.trim())||undefined)}const pem=read.pem;const{exportCA,getCertSha256Fingerprint,isCertTrusted,trustInstructions}=await import("@stacksjs/tlsx");let fingerprint;try{fingerprint=getCertSha256Fingerprint(pem)}catch(err){return fail("ca.unparseable",`The file at ${caPath} on ${checked.host} is not a certificate this can read.`,"Point --ca-path at the root certificate rpx writes, which is a PEM.",err instanceof Error?err.message:String(err))}const savedPath=caCopyPath(checked.host);mkdirSync(dirname(savedPath),{recursive:true});await Bun.write(savedPath,pem.endsWith(`
6
8
  `)?pem:`${pem}
7
- `);if(!asJson)log.success(`Saved the certificate to ${savedPath}`);let mobileconfigPath;if(options.mobileconfig){try{const profile=await exportCA({caCertPath:savedPath,format:"mobileconfig"}),requested=String(options.mobileconfig);mobileconfigPath=requested.endsWith("/")||existsSync(requested)&&statSync(requested).isDirectory()?join(requested,profile.filename):requested;mkdirSync(dirname(mobileconfigPath),{recursive:!0});await Bun.write(mobileconfigPath,profile.data)}catch(err){return fail("profile.failed","Could not write the configuration profile.",`Check that ${options.mobileconfig} is somewhere you can write to.`,err instanceof Error?err.message:String(err))}if(!asJson){log.success(`Wrote the configuration profile to ${mobileconfigPath}`);for(const step of mobileconfigInstructions(mobileconfigPath))log.info(` ${step}`)}}let trusted=!1;try{trusted=await isCertTrusted(pem)}catch{trusted=!1}if(options.exportOnly){if(!asJson){log.info(trusted?"This machine already trusts it. --export-only, so nothing was changed.":"This machine does not trust it yet. --export-only, so nothing was changed.");console.log(trustInstructions(trustPlatform(),savedPath))}}else if(trusted){if(!asJson)log.success("This machine already trusts it. Nothing changed.")}else{if(!asJson){log.info("Installing it into this machine's trust store.");log.info("This needs sudo, so you will be asked for your password. You type it, not buddy.")}try{const{addCertToSystemTrustStore}=await import("@stacksjs/tlsx"),report=await addCertToSystemTrustStore(savedPath);trusted=report.trusted===!0;if(!asJson)for(const store of report.stores??[])log.info(` ${store.store}: ${store.status}${store.detail?` (${store.detail})`:""}`)}catch(err){const detail=err instanceof Error?err.message:String(err);return fail("trust.failed","Installing the certificate into the trust store failed.",/\s/.test(savedPath)?`The path ${savedPath} contains a space, which the underlying \`security\` invocation cannot pass through. Trust it by hand:
9
+ `);if(!asJson)log.success(`Saved the certificate to ${savedPath}`);let mobileconfigPath;if(options.mobileconfig){try{const profile=await exportCA({caCertPath:savedPath,format:"mobileconfig"});const requested=String(options.mobileconfig);const isDir=requested.endsWith("/")||existsSync(requested)&&statSync(requested).isDirectory();mobileconfigPath=isDir?join(requested,profile.filename):requested;mkdirSync(dirname(mobileconfigPath),{recursive:true});await Bun.write(mobileconfigPath,profile.data)}catch(err){return fail("profile.failed","Could not write the configuration profile.",`Check that ${options.mobileconfig} is somewhere you can write to.`,err instanceof Error?err.message:String(err))}if(!asJson){log.success(`Wrote the configuration profile to ${mobileconfigPath}`);for(const step of mobileconfigInstructions(mobileconfigPath))log.info(` ${step}`)}}let trusted=false;try{trusted=await isCertTrusted(pem)}catch{trusted=false}if(options.exportOnly){if(!asJson){log.info(trusted?"This machine already trusts it. --export-only, so nothing was changed.":"This machine does not trust it yet. --export-only, so nothing was changed.");console.log(trustInstructions(trustPlatform(),savedPath))}}else if(trusted){if(!asJson)log.success("This machine already trusts it. Nothing changed.")}else{if(!asJson){log.info("Installing it into this machine's trust store.");log.info("This needs sudo, so you will be asked for your password. You type it, not buddy.")}try{const{addCertToSystemTrustStore}=await import("@stacksjs/tlsx");const report=await addCertToSystemTrustStore(savedPath);trusted=report.trusted===true;if(!asJson){for(const store of report.stores??[])log.info(` ${store.store}: ${store.status}${store.detail?` (${store.detail})`:""}`)}}catch(err){const detail=err instanceof Error?err.message:String(err);return fail("trust.failed","Installing the certificate into the trust store failed.",/\s/.test(savedPath)?`The path ${savedPath} contains a space, which the underlying \`security\` invocation cannot pass through. Trust it by hand:
8
10
  ${trustInstructions(trustPlatform(),savedPath)}`:`Trust it by hand:
9
- ${trustInstructions(trustPlatform(),savedPath)}`,detail)}if(!trusted)return fail("trust.refused","The certificate was not added to any trust store.",`Trust it by hand:
10
- ${trustInstructions(trustPlatform(),savedPath)}`);if(!asJson)log.success("Installed. Restart any open browser before trying the LAN address again.")}const summary=trustSummary({host:checked.host,caPath,savedPath,fingerprint,trusted,mobileconfigPath});if(asJson)console.log(JSON.stringify(summary,null,2));else{log.info(`Fingerprint (SHA-256): ${fingerprint}`);if(perf)await outro("Done",{startTime:perf,useSeconds:!0})}process.exit(ExitCode.Success)});buddy.on("server:*",()=>{onUnknownSubcommand(buddy,"server")})}
11
+ ${trustInstructions(trustPlatform(),savedPath)}`,detail)}if(!trusted){return fail("trust.refused","The certificate was not added to any trust store.",`Trust it by hand:
12
+ ${trustInstructions(trustPlatform(),savedPath)}`)}if(!asJson){log.success("Installed. Restart any open browser before trying the LAN address again.")}}const summary=trustSummary({host:checked.host,caPath,savedPath,fingerprint,trusted,mobileconfigPath});if(asJson){console.log(JSON.stringify(summary,null,2))}else{log.info(`Fingerprint (SHA-256): ${fingerprint}`);if(perf)await outro("Done",{startTime:perf,useSeconds:true})}process.exit(ExitCode.Success)});buddy.on("server:*",()=>{onUnknownSubcommand(buddy,"server")})}
@@ -1,2 +1,2 @@
1
- import{cpSync,existsSync,lstatSync,mkdirSync,readdirSync,rmSync,symlinkSync,writeFileSync}from"node:fs";import process from"node:process";import{dim,green,log,yellow}from"@stacksjs/cli";import{frameworkPath,join,projectPath,relative}from"@stacksjs/path";import{listSkills,resolveSkillPath}from"@stacksjs/skills";export const AI_PROVIDERS=[{id:"claude",label:"Claude Code",reads:["AGENTS.md","CLAUDE.md",".claude/skills",".claude/launch.json"]},{id:"codex",label:"OpenAI Codex CLI",reads:["AGENTS.md"]},{id:"cursor",label:"Cursor",reads:["AGENTS.md",".cursor/rules"]},{id:"copilot",label:"GitHub Copilot",reads:["AGENTS.md",".github/copilot-instructions.md"]},{id:"gemini",label:"Gemini CLI",reads:["AGENTS.md","GEMINI.md"]}];export function isAiProvider(value){return AI_PROVIDERS.some((provider)=>provider.id===value)}export function materialize(target,path,options){const existing=lstatSync(path,{throwIfNoEntry:!1});if(existing){if(!existing.isSymbolicLink()&&!options.force)return!1;rmSync(path,{recursive:!0,force:!0})}mkdirSync(join(path,".."),{recursive:!0});if(options.copy)cpSync(target,path,{recursive:!0});else symlinkSync(relative(join(path,".."),target),path,process.platform==="win32"?"junction":"dir");return!0}function materializeFile(source,path,options){if(existsSync(path)&&!options.force)return!1;mkdirSync(join(path,".."),{recursive:!0});cpSync(source,path,{recursive:!0,force:!0});return!0}function installSkills(destination,options){const names=listSkills();let installed=0,skipped=0;mkdirSync(destination,{recursive:!0});for(const entry of readdirSync(destination)){const path=join(destination,entry);if(lstatSync(path,{throwIfNoEntry:!1})?.isSymbolicLink()&&!existsSync(path))rmSync(path,{force:!0})}for(const name of names){const source=resolveSkillPath(name);if(!source)continue;if(materialize(source,join(destination,name),options))installed++;else skipped++}return{installed,skipped}}export function setupAiProvider(provider,options={}){const created=[],skipped=[],defaults=frameworkPath("defaults/ai"),rel=(path)=>relative(projectPath(),path),record=(path,didCreate)=>{(didCreate?created:skipped).push(rel(path))},agents=projectPath("AGENTS.md");record(agents,materializeFile(join(defaults,"AGENTS.md"),agents,{...options,force:!1}));switch(provider){case"claude":{const claudeMd=projectPath("CLAUDE.md"),linked=materialize(agents,claudeMd,{...options,copy:!1,force:!1});record(claudeMd,linked);if(!linked&&existsSync(claudeMd)&&!lstatSync(claudeMd,{throwIfNoEntry:!1})?.isSymbolicLink())log.info(` \xB7 ${rel(claudeMd)} is a real file, so it is left as-is. Move its content into AGENTS.md and delete it to have both agents read one file.`);const launch=projectPath(".claude/launch.json");record(launch,materializeFile(join(defaults,"claude/launch.json"),launch,{...options,force:!1}));const skillsDir=projectPath(".claude/skills"),{installed,skipped:untouched}=installSkills(skillsDir,options);if(installed>0)created.push(`${rel(skillsDir)} (${installed} skills)`);if(untouched>0)skipped.push(`${rel(skillsDir)} (${untouched} skills)`);break}case"codex":break;case"cursor":{const rules=projectPath(".cursor/rules");record(rules,materialize(frameworkPath("defaults/ide/cursor/rules"),rules,options));break}case"copilot":{const instructions=projectPath(".github/copilot-instructions.md");if(existsSync(instructions)&&!options.force)skipped.push(rel(instructions));else{mkdirSync(projectPath(".github"),{recursive:!0});writeFileSync(instructions,pointerFile("AGENTS.md"),"utf8");created.push(rel(instructions))}break}case"gemini":{const geminiMd=projectPath("GEMINI.md");record(geminiMd,materialize(agents,geminiMd,{...options,copy:!1}));break}}return{created,skipped}}function pointerFile(target){return["# Project instructions","",`This project keeps its agent guidance in [\`${target}\`](../${target}), so every`,"agent works from the same rules. Read that file.","","Regenerate this pointer with `buddy setup:ai copilot --force`.",""].join(`
2
- `)}export function reportAiSetup(provider,result){for(const path of result.created)log.info(` ${green("+")} ${path}`);for(const path of result.skipped)log.info(` ${yellow("\xB7")} ${path} ${dim("(already present, left alone)")}`);if(result.created.length===0)log.info(dim(" Nothing to do - re-run with --force to overwrite."));log.success(`${provider.label} is set up. It reads: ${provider.reads.join(", ")}`)}
1
+ import{cpSync,existsSync,lstatSync,mkdirSync,readdirSync,rmSync,symlinkSync,writeFileSync}from"node:fs";import process from"node:process";import{dim,green,log,yellow}from"@stacksjs/cli";import{frameworkPath,join,projectPath,relative}from"@stacksjs/path";import{listSkills,resolveSkillPath}from"@stacksjs/skills";export const AI_PROVIDERS=[{id:"claude",label:"Claude Code",reads:["AGENTS.md","CLAUDE.md",".claude/skills",".claude/launch.json"]},{id:"codex",label:"OpenAI Codex CLI",reads:["AGENTS.md"]},{id:"cursor",label:"Cursor",reads:["AGENTS.md",".cursor/rules"]},{id:"copilot",label:"GitHub Copilot",reads:["AGENTS.md",".github/copilot-instructions.md"]},{id:"gemini",label:"Gemini CLI",reads:["AGENTS.md","GEMINI.md"]}];export function isAiProvider(value){return AI_PROVIDERS.some((provider)=>provider.id===value)}export function materialize(target,path,options){const existing=lstatSync(path,{throwIfNoEntry:false});if(existing){if(!existing.isSymbolicLink()&&!options.force)return false;rmSync(path,{recursive:true,force:true})}mkdirSync(join(path,".."),{recursive:true});if(options.copy){cpSync(target,path,{recursive:true})}else{symlinkSync(relative(join(path,".."),target),path,process.platform==="win32"?"junction":"dir")}return true}function materializeFile(source,path,options){if(existsSync(path)&&!options.force)return false;mkdirSync(join(path,".."),{recursive:true});cpSync(source,path,{recursive:true,force:true});return true}function installSkills(destination,options){const names=listSkills();let installed=0;let skipped=0;mkdirSync(destination,{recursive:true});for(const entry of readdirSync(destination)){const path=join(destination,entry);const stats=lstatSync(path,{throwIfNoEntry:false});if(stats?.isSymbolicLink()&&!existsSync(path))rmSync(path,{force:true})}for(const name of names){const source=resolveSkillPath(name);if(!source)continue;if(materialize(source,join(destination,name),options))installed++;else skipped++}return{installed,skipped}}export function setupAiProvider(provider,options={}){const created=[];const skipped=[];const defaults=frameworkPath("defaults/ai");const rel=(path)=>relative(projectPath(),path);const record=(path,didCreate)=>{(didCreate?created:skipped).push(rel(path))};const agents=projectPath("AGENTS.md");record(agents,materializeFile(join(defaults,"AGENTS.md"),agents,{...options,force:false}));switch(provider){case"claude":{const claudeMd=projectPath("CLAUDE.md");const linked=materialize(agents,claudeMd,{...options,copy:false,force:false});record(claudeMd,linked);if(!linked&&existsSync(claudeMd)&&!lstatSync(claudeMd,{throwIfNoEntry:false})?.isSymbolicLink())log.info(` · ${rel(claudeMd)} is a real file, so it is left as-is. Move its content into AGENTS.md and delete it to have both agents read one file.`);const launch=projectPath(".claude/launch.json");record(launch,materializeFile(join(defaults,"claude/launch.json"),launch,{...options,force:false}));const skillsDir=projectPath(".claude/skills");const{installed,skipped:untouched}=installSkills(skillsDir,options);if(installed>0)created.push(`${rel(skillsDir)} (${installed} skills)`);if(untouched>0)skipped.push(`${rel(skillsDir)} (${untouched} skills)`);break}case"codex":break;case"cursor":{const rules=projectPath(".cursor/rules");record(rules,materialize(frameworkPath("defaults/ide/cursor/rules"),rules,options));break}case"copilot":{const instructions=projectPath(".github/copilot-instructions.md");if(existsSync(instructions)&&!options.force){skipped.push(rel(instructions))}else{mkdirSync(projectPath(".github"),{recursive:true});writeFileSync(instructions,pointerFile("AGENTS.md"),"utf8");created.push(rel(instructions))}break}case"gemini":{const geminiMd=projectPath("GEMINI.md");record(geminiMd,materialize(agents,geminiMd,{...options,copy:false}));break}}return{created,skipped}}function pointerFile(target){return["# Project instructions","",`This project keeps its agent guidance in [\`${target}\`](../${target}), so every`,"agent works from the same rules. Read that file.","",`Regenerate this pointer with \`buddy setup:ai copilot --force\`.`,""].join(`
2
+ `)}export function reportAiSetup(provider,result){for(const path of result.created)log.info(` ${green("+")} ${path}`);for(const path of result.skipped)log.info(` ${yellow("·")} ${path} ${dim("(already present, left alone)")}`);if(result.created.length===0)log.info(dim(" Nothing to do - re-run with --force to overwrite."));log.success(`${provider.label} is set up. It reads: ${provider.reads.join(", ")}`)}
@@ -1,8 +1,8 @@
1
- import{cpSync,existsSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import process from"node:process";import{IosToolchainError,loadIosDependencies,pantryExecutable,pantryInstallArgs,resolveXcodegen,runAction,XCODE_NOTE,xcodeDeveloperDir}from"@stacksjs/actions";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{copyFile,storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{setupPrettyDevEnvironment}from"./dev";import{runInitialMigration}from"../initial-migration";import{syncDatabasePortToEnv}from"../pantry-service-ports";import{resolveCreatePolicy}from"../database-preflight";import{resultFailed}from"../result";function getTimeoutMs(envVar,fallbackMs){const value=Number(process.env[envVar]);if(Number.isFinite(value)&&value>0)return value;return fallbackMs}const PANTRY_CHECK_TIMEOUT_MS=getTimeoutMs("PANTRY_CHECK_TIMEOUT_MS",15000),PANTRY_INSTALL_TIMEOUT_MS=getTimeoutMs("PANTRY_INSTALL_TIMEOUT_MS",600000),PANTRY_DEPENDENCIES_TIMEOUT_MS=getTimeoutMs("PANTRY_DEPENDENCIES_TIMEOUT_MS",1200000),KEYGEN_TIMEOUT_MS=getTimeoutMs("KEYGEN_TIMEOUT_MS",120000),AWS_CONFIG_TIMEOUT_MS=getTimeoutMs("AWS_CONFIG_TIMEOUT_MS",900000);export function setup(buddy){const descriptions={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ai:"Set the project up for an AI coding agent (Claude Code, Codex, Cursor, Copilot, Gemini)",copy:"Copy the agent files instead of symlinking them, so they can be edited per project",force:"Overwrite files that already exist",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup",ios:"Install the iOS build tools (`iosDependencies` in config/deps.ts) through Pantry and check for Xcode"};buddy.command("setup",descriptions.setup).alias("ensure").option("-p, --project [project]",descriptions.project,{default:!1}).option("--skip-aws",descriptions.skipAws,{default:!1}).option("--skip-keygen",descriptions.skipKeygen,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup` ...",options);await ensurePantryInstalled();await optimizePantryDeps();await initializeProject(options)});buddy.command("setup:ios",descriptions.ios).option("--verbose",descriptions.verbose,{default:!1}).action(async()=>{if(process.platform!=="darwin"){await log.error("The iOS toolchain installs on macOS only: Xcode and xcodegen do not run anywhere else.");process.exit(ExitCode.FatalError)}const root=p.projectPath(),dependencies=await loadIosDependencies(root),pantry=pantryExecutable(root);log.info(`Installing ${Object.entries(dependencies).map(([pkg,version])=>`${pkg}@${version}`).join(", ")} through Pantry`);const install=Bun.spawnSync([pantry,...pantryInstallArgs(dependencies)],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(install.exitCode!==0){await log.error(`\`${pantry} install\` failed with exit code ${install.exitCode}. PANTRY_BIN can point at another Pantry.`);process.exit(ExitCode.FatalError)}try{const xcodegen=await resolveXcodegen(root);log.success(`xcodegen ${xcodegen.version}: ${xcodegen.path}`)}catch(error){await log.error(error instanceof IosToolchainError?error.message:String(error));process.exit(ExitCode.FatalError)}const xcode=xcodeDeveloperDir();if(xcode)log.success(`Xcode: ${xcode}`);else log.warn(`No Xcode is selected, so the project can be generated but not built or archived. ${XCODE_NOTE}`)});buddy.command("setup:ssl",descriptions.ssl).alias("ssl:setup").option("-d, --domain [domain]",descriptions.domain).option("--skip-hosts",descriptions.skipHosts,{default:!1}).option("--skip-trust",descriptions.skipTrust,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy setup:ssl` ...",options);if(!await setupPrettyDevEnvironment({domain:options.domain,skipHosts:options.skipHosts,skipTrust:options.skipTrust,verbose:options.verbose})){log.warn("SSL setup completed with warnings");log.info("You may need to manually trust certificates or update hosts file")}});buddy.command("setup:ai [provider]",descriptions.ai).alias("ai:setup").option("--copy",descriptions.copy,{default:!1}).option("--force",descriptions.force,{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(provider,options)=>{log.debug("Running `buddy setup:ai` ...",options);const{AI_PROVIDERS,isAiProvider,reportAiSetup,setupAiProvider}=await import("./setup-ai");let id=provider;if(!id){if(!process.stdin.isTTY){await log.error(`\`setup:ai\` needs a provider when stdin is not a terminal. Pass one: ${AI_PROVIDERS.map((entry)=>`buddy setup:ai ${entry.id}`).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const{select}=await import("@stacksjs/cli");id=await select({message:"Which AI coding agent do you use?",choices:AI_PROVIDERS.map((entry)=>({value:entry.id,label:entry.label})),initial:0})}if(!id||!isAiProvider(id)){await log.error(`Unknown AI provider: ${id}. Expected one of: ${AI_PROVIDERS.map((entry)=>entry.id).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const definition=AI_PROVIDERS.find((entry)=>entry.id===id),{generateAutoImportFiles}=await import("@stacksjs/server/imports");await generateAutoImportFiles();reportAiSetup(definition,setupAiProvider(id,{copy:options.copy,force:options.force}))});buddy.command("setup:oh-my-zsh",descriptions.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",descriptions.verbose,{default:!1}).action(async(_options)=>{log.debug("Running `buddy setup:oh-my-zsh` ...",_options);const result=await runAction(Action.UpgradeShell);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"setup")}async function isPantryInstalled(){try{return(await runCommand("pantry --version",{silent:!0,timeoutMs:PANTRY_CHECK_TIMEOUT_MS})).isOk}catch{return!1}}const PANTRY_NOT_ON_PATH="Pantry installed but is not available on PATH. Open a new shell and run `buddy setup` again.";async function attemptPantryInstall(){const bundledInstaller=p.frameworkPath("scripts/pantry-install"),command=existsSync(bundledInstaller)?[bundledInstaller]:["sh","-c","curl -fsSL https://pantry.dev | bash"],result=await runCommand(command,{timeoutMs:PANTRY_INSTALL_TIMEOUT_MS}),localBin=join(homedir(),".local","bin");if(!process.env.PATH?.split(":").includes(localBin))process.env.PATH=`${localBin}:${process.env.PATH||""}`;if(result.isOk&&await isPantryInstalled())return null;return{error:resultFailed(result)?result.error:Error(PANTRY_NOT_ON_PATH)}}async function reportPantryFailure(error){if(error instanceof Error&&error.message===PANTRY_NOT_ON_PATH)await log.error(PANTRY_NOT_ON_PATH);else handleError(error)}async function installPantry(){const failure=await attemptPantryInstall();if(failure===null)return;await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}export async function ensurePantryInstalled(){if(await isPantryInstalled())return;log.info("Pantry is required. Installing it from https://pantry.dev...");await installPantry()}export async function attemptPantryDependencies(cwd){if(!await isPantryInstalled()){log.info("Pantry is required. Installing it from https://pantry.dev...");const installFailure=await attemptPantryInstall();if(installFailure!==null)return installFailure}log.info("Installing project dependencies with Pantry...");const result=await runCommand("pantry install",{cwd,timeoutMs:PANTRY_DEPENDENCIES_TIMEOUT_MS});return resultFailed(result)?{error:result.error}:null}export async function ensurePantryDependencies(cwd){const failure=await attemptPantryDependencies(cwd);if(failure!==null){await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}if(existsSync(join(cwd,"package.json"))&&!existsSync(join(cwd,"node_modules"))){await log.error("Pantry completed without installing the project JavaScript dependencies.");process.exit(ExitCode.FatalError)}log.success("Installed project dependencies with Pantry")}function hasAppKey(cwd){const envPath=join(cwd,".env");if(!existsSync(envPath))return!1;return/^APP_KEY=.+$/m.test(readFileSync(envPath,"utf-8"))}export async function ensureAppKey(cwd){if(hasAppKey(cwd)||process.env.APP_KEY&&process.env.APP_KEY.length>0){log.success("APP_KEY existed");return}const keyResult=await runCommand("./buddy key:generate",{cwd,timeoutMs:KEYGEN_TIMEOUT_MS});if(resultFailed(keyResult)){handleError(keyResult.error);process.exit(ExitCode.FatalError)}log.success("Generated application key")}async function databaseIsReachable(){try{const{describeTarget,probeTargetDatabase,resolveConnectionTarget}=await import("@stacksjs/database"),target=resolveConnectionTarget();if(!target)return{ok:!0};const probe=await probeTargetDatabase(target);if(probe.ok)return{ok:!0};if(probe.kind==="missing-database"&&resolveCreatePolicy()!=="never"){process.env.STACKS_CREATE_DATABASE="1";return{ok:!0}}return{ok:!1,reason:`${describeTarget(target)} is not reachable yet (${probe.kind})`}}catch{return{ok:!0}}}async function initializeProject(options){const cwd=options.cwd||p.projectPath();await ensurePantryDependencies(cwd);await ensureEnvIsSet(options);const portSync=syncDatabasePortToEnv(cwd);if(portSync.port!==void 0)process.env.DB_PORT=String(portSync.port);if(portSync.changed)log.info(`Pointed DB_PORT at ${portSync.port}, the port Pantry assigned this project's ${portSync.service} service`);if(!options.skipKeygen)await ensureAppKey(cwd);const migration=await runInitialMigration({appEnv:process.env.APP_ENV||process.env.NODE_ENV||"local",isReachable:databaseIsReachable,migrate:()=>runAction(Action.Migrate,{cwd}),failed:resultFailed,log});ensureIdeSettings(cwd);if(!options.skipAws){log.info("Ensuring AWS is connected...");try{const awsResult=await runCommand("./buddy configure:aws",{cwd,timeoutMs:AWS_CONFIG_TIMEOUT_MS});if(resultFailed(awsResult)){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(awsResult.error)}else log.success("Configured AWS")}catch(error){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(error)}}if(migration==="failed"){process.stderr.write(`
1
+ import{cpSync,existsSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import process from"node:process";import{IosToolchainError,loadIosDependencies,pantryExecutable,pantryInstallArgs,resolveXcodegen,runAction,XCODE_NOTE,xcodeDeveloperDir}from"@stacksjs/actions";import{log,onUnknownSubcommand,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{handleError}from"@stacksjs/error-handling";import{path as p}from"@stacksjs/path";import{copyFile,storage}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{setupPrettyDevEnvironment}from"./dev";import{runInitialMigration}from"../initial-migration";import{syncDatabasePortToEnv}from"../pantry-service-ports";import{resolveCreatePolicy}from"../database-preflight";import{resultFailed}from"../result";function getTimeoutMs(envVar,fallbackMs){const value=Number(process.env[envVar]);if(Number.isFinite(value)&&value>0)return value;return fallbackMs}const PANTRY_CHECK_TIMEOUT_MS=getTimeoutMs("PANTRY_CHECK_TIMEOUT_MS",15000);const PANTRY_INSTALL_TIMEOUT_MS=getTimeoutMs("PANTRY_INSTALL_TIMEOUT_MS",10*60000);const PANTRY_DEPENDENCIES_TIMEOUT_MS=getTimeoutMs("PANTRY_DEPENDENCIES_TIMEOUT_MS",20*60000);const KEYGEN_TIMEOUT_MS=getTimeoutMs("KEYGEN_TIMEOUT_MS",2*60000);const AWS_CONFIG_TIMEOUT_MS=getTimeoutMs("AWS_CONFIG_TIMEOUT_MS",15*60000);export function setup(buddy){const descriptions={setup:"This command ensures your project is setup correctly",ssl:"Setup SSL certificates and hosts file for HTTPS development",ai:"Set the project up for an AI coding agent (Claude Code, Codex, Cursor, Copilot, Gemini)",copy:"Copy the agent files instead of symlinking them, so they can be edited per project",force:"Overwrite files that already exist",ohMyZsh:"Enable Oh My Zsh",aws:"Ensures AWS is connected to the project",project:"Target a specific project",verbose:"Enable verbose output",domain:"Custom domain to setup (defaults to APP_URL)",skipHosts:"Skip adding domain to hosts file",skipTrust:"Skip trusting the certificate",skipAws:"Skip AWS configuration during setup",skipKeygen:"Skip generating an application key during setup",ios:"Install the iOS build tools (`iosDependencies` in config/deps.ts) through Pantry and check for Xcode"};buddy.command("setup",descriptions.setup).alias("ensure").option("-p, --project [project]",descriptions.project,{default:false}).option("--skip-aws",descriptions.skipAws,{default:false}).option("--skip-keygen",descriptions.skipKeygen,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy setup` ...",options);await ensurePantryInstalled();await optimizePantryDeps();await initializeProject(options)});buddy.command("setup:ios",descriptions.ios).option("--verbose",descriptions.verbose,{default:false}).action(async()=>{if(process.platform!=="darwin"){await log.error("The iOS toolchain installs on macOS only: Xcode and xcodegen do not run anywhere else.");process.exit(ExitCode.FatalError)}const root=p.projectPath();const dependencies=await loadIosDependencies(root);const pantry=pantryExecutable(root);log.info(`Installing ${Object.entries(dependencies).map(([pkg,version])=>`${pkg}@${version}`).join(", ")} through Pantry`);const install=Bun.spawnSync([pantry,...pantryInstallArgs(dependencies)],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(install.exitCode!==0){await log.error(`\`${pantry} install\` failed with exit code ${install.exitCode}. PANTRY_BIN can point at another Pantry.`);process.exit(ExitCode.FatalError)}try{const xcodegen=await resolveXcodegen(root);log.success(`xcodegen ${xcodegen.version}: ${xcodegen.path}`)}catch(error){await log.error(error instanceof IosToolchainError?error.message:String(error));process.exit(ExitCode.FatalError)}const xcode=xcodeDeveloperDir();if(xcode)log.success(`Xcode: ${xcode}`);else log.warn(`No Xcode is selected, so the project can be generated but not built or archived. ${XCODE_NOTE}`)});buddy.command("setup:ssl",descriptions.ssl).alias("ssl:setup").option("-d, --domain [domain]",descriptions.domain).option("--skip-hosts",descriptions.skipHosts,{default:false}).option("--skip-trust",descriptions.skipTrust,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(options)=>{log.debug("Running `buddy setup:ssl` ...",options);const success=await setupPrettyDevEnvironment({domain:options.domain,skipHosts:options.skipHosts,skipTrust:options.skipTrust,verbose:options.verbose});if(!success){log.warn("SSL setup completed with warnings");log.info("You may need to manually trust certificates or update hosts file")}});buddy.command("setup:ai [provider]",descriptions.ai).alias("ai:setup").option("--copy",descriptions.copy,{default:false}).option("--force",descriptions.force,{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(async(provider,options)=>{log.debug("Running `buddy setup:ai` ...",options);const{AI_PROVIDERS,isAiProvider,reportAiSetup,setupAiProvider}=await import("./setup-ai");let id=provider;if(!id){if(!process.stdin.isTTY){await log.error(`\`setup:ai\` needs a provider when stdin is not a terminal. Pass one: ${AI_PROVIDERS.map((entry)=>`buddy setup:ai ${entry.id}`).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const{select}=await import("@stacksjs/cli");id=await select({message:"Which AI coding agent do you use?",choices:AI_PROVIDERS.map((entry)=>({value:entry.id,label:entry.label})),initial:0})}if(!id||!isAiProvider(id)){await log.error(`Unknown AI provider: ${id}. Expected one of: ${AI_PROVIDERS.map((entry)=>entry.id).join(", ")}`);process.exit(ExitCode.InvalidArgument)}const definition=AI_PROVIDERS.find((entry)=>entry.id===id);const{generateAutoImportFiles}=await import("@stacksjs/server/imports");await generateAutoImportFiles();reportAiSetup(definition,setupAiProvider(id,{copy:options.copy,force:options.force}))});buddy.command("setup:oh-my-zsh",descriptions.ohMyZsh).alias("upgrade:oh-my-zsh").option("--verbose",descriptions.verbose,{default:false}).action(async(_options)=>{log.debug("Running `buddy setup:oh-my-zsh` ...",_options);const result=await runAction(Action.UpgradeShell);if(resultFailed(result)){await log.error(result.error);process.exit(ExitCode.FatalError)}});onUnknownSubcommand(buddy,"setup")}async function isPantryInstalled(){try{const result=await runCommand("pantry --version",{silent:true,timeoutMs:PANTRY_CHECK_TIMEOUT_MS});return result.isOk}catch{return false}}const PANTRY_NOT_ON_PATH="Pantry installed but is not available on PATH. Open a new shell and run `buddy setup` again.";async function attemptPantryInstall(){const bundledInstaller=p.frameworkPath("scripts/pantry-install");const command=existsSync(bundledInstaller)?[bundledInstaller]:["sh","-c","curl -fsSL https://pantry.dev | bash"];const result=await runCommand(command,{timeoutMs:PANTRY_INSTALL_TIMEOUT_MS});const localBin=join(homedir(),".local","bin");if(!process.env.PATH?.split(":").includes(localBin))process.env.PATH=`${localBin}:${process.env.PATH||""}`;if(result.isOk&&await isPantryInstalled())return null;return{error:resultFailed(result)?result.error:new Error(PANTRY_NOT_ON_PATH)}}async function reportPantryFailure(error){if(error instanceof Error&&error.message===PANTRY_NOT_ON_PATH)await log.error(PANTRY_NOT_ON_PATH);else handleError(error)}async function installPantry(){const failure=await attemptPantryInstall();if(failure===null)return;await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}export async function ensurePantryInstalled(){if(await isPantryInstalled())return;log.info("Pantry is required. Installing it from https://pantry.dev...");await installPantry()}export async function attemptPantryDependencies(cwd){if(!await isPantryInstalled()){log.info("Pantry is required. Installing it from https://pantry.dev...");const installFailure=await attemptPantryInstall();if(installFailure!==null)return installFailure}log.info("Installing project dependencies with Pantry...");const result=await runCommand("pantry install",{cwd,timeoutMs:PANTRY_DEPENDENCIES_TIMEOUT_MS});return resultFailed(result)?{error:result.error}:null}export async function ensurePantryDependencies(cwd){const failure=await attemptPantryDependencies(cwd);if(failure!==null){await reportPantryFailure(failure.error);process.exit(ExitCode.FatalError)}if(existsSync(join(cwd,"package.json"))&&!existsSync(join(cwd,"node_modules"))){await log.error("Pantry completed without installing the project JavaScript dependencies.");process.exit(ExitCode.FatalError)}log.success("Installed project dependencies with Pantry")}function hasAppKey(cwd){const envPath=join(cwd,".env");if(!existsSync(envPath))return false;return/^APP_KEY=.+$/m.test(readFileSync(envPath,"utf-8"))}export async function ensureAppKey(cwd){if(hasAppKey(cwd)||process.env.APP_KEY&&process.env.APP_KEY.length>0){log.success("APP_KEY existed");return}const keyResult=await runCommand("./buddy key:generate",{cwd,timeoutMs:KEYGEN_TIMEOUT_MS});if(resultFailed(keyResult)){handleError(keyResult.error);process.exit(ExitCode.FatalError)}log.success("Generated application key")}async function databaseIsReachable(){try{const{describeTarget,probeTargetDatabase,resolveConnectionTarget}=await import("@stacksjs/database");const target=resolveConnectionTarget();if(!target)return{ok:true};const probe=await probeTargetDatabase(target);if(probe.ok)return{ok:true};if(probe.kind==="missing-database"&&resolveCreatePolicy()!=="never"){process.env.STACKS_CREATE_DATABASE="1";return{ok:true}}return{ok:false,reason:`${describeTarget(target)} is not reachable yet (${probe.kind})`}}catch{return{ok:true}}}async function initializeProject(options){const cwd=options.cwd||p.projectPath();await ensurePantryDependencies(cwd);await ensureEnvIsSet(options);const portSync=syncDatabasePortToEnv(cwd);if(portSync.port!==undefined)process.env.DB_PORT=String(portSync.port);if(portSync.changed)log.info(`Pointed DB_PORT at ${portSync.port}, the port Pantry assigned this project's ${portSync.service} service`);if(!options.skipKeygen){await ensureAppKey(cwd)}const migration=await runInitialMigration({appEnv:process.env.APP_ENV||process.env.NODE_ENV||"local",isReachable:databaseIsReachable,migrate:()=>runAction(Action.Migrate,{cwd}),failed:resultFailed,log});ensureIdeSettings(cwd);if(!options.skipAws){log.info("Ensuring AWS is connected...");try{const awsResult=await runCommand("./buddy configure:aws",{cwd,timeoutMs:AWS_CONFIG_TIMEOUT_MS});if(resultFailed(awsResult)){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(awsResult.error)}else{log.success("Configured AWS")}}catch(error){log.warn("AWS not configured - you can do this later via ./buddy configure:aws");log.debug(error)}}if(migration==="failed"){process.stderr.write(`
2
2
  Initial database migration FAILED, so this project is not set up.
3
3
  `);process.stderr.write(`Its database did not receive the schema; the error is above.
4
- `);process.stderr.write("Fix the migration, then run `./buddy migrate`.\n");await log.flush();process.exit(ExitCode.FatalError)}log.success("Project is setup");log.info("Run `./buddy doctor` anytime to check your setup. Happy coding! \uD83D\uDC99")}export function ensureIdeSettings(cwd){const source=p.frameworkPath("defaults/ide/vscode/.vscode"),destination=join(cwd,".vscode");if(existsSync(destination)){log.debug(".vscode already exists; keeping the project settings");return}if(!existsSync(source)){log.debug("No bundled VS Code settings found; skipping IDE setup");return}cpSync(source,destination,{recursive:!0});log.success("Installed project VS Code settings")}const DB_CONNECTION_PACKAGES={postgres:{name:"postgresql.org",version:"^17.10",service:"postgres"},mysql:{name:"mysql.com",version:"^9.2",service:"mysql"},sqlite:{name:"sqlite.org",version:"^3.47.2"}};function databaseAliases(connection,pkg){return[connection,pkg.name]}export function pantryDatabasePackage(connection){return DB_CONNECTION_PACKAGES[connection]}function detectDbPackage(cwd){const envPath=join(cwd,".env"),envExamplePath=join(cwd,".env.example"),filePath=existsSync(envPath)?envPath:existsSync(envExamplePath)?envExamplePath:void 0;if(!filePath)return;const match=readFileSync(filePath,"utf-8").match(/^DB_CONNECTION=(.+)$/m);if(!match)return;const value=match[1].trim().replace(/['"]/g,"");return pantryDatabasePackage(value)}export async function optimizePantryDeps(cwd=p.projectPath()){const depsConfigPath=join(cwd,"config","deps.ts");if(!existsSync(depsConfigPath)){log.debug("No config/deps.ts found, skipping dependency optimization");return!1}let configDeps={},configServices=[],configDefined={};try{const mod=await import(depsConfigPath),config=mod.config||mod.default;if(config?.dependencies)configDeps={...config.dependencies};if(Array.isArray(config?.services?.autoStart))configServices=config.services.autoStart.filter((name)=>typeof name==="string");if(config?.services?.define&&typeof config.services.define==="object")configDefined=config.services.define}catch(err){log.debug("Could not load config/deps.ts, skipping dependency optimization");return!1}const dbPackage=detectDbPackage(cwd),autoStart=[...configServices];if(dbPackage){const selected=new Set(Object.entries(DB_CONNECTION_PACKAGES).filter(([,pkg])=>pkg.name===dbPackage.name).flatMap(([connection,pkg])=>databaseAliases(connection,pkg))),unused=new Set(Object.entries(DB_CONNECTION_PACKAGES).flatMap(([connection,pkg])=>databaseAliases(connection,pkg)).filter((alias)=>!selected.has(alias)));for(const pkg of Object.keys(configDeps)){const domain=pkg.split("/")[0];if(unused.has(domain)){log.info(`DB_CONNECTION selects ${dbPackage.name}, dropping unused ${pkg}`);delete configDeps[pkg]}}if(!Object.keys(configDeps).some((key)=>{const domain=key.split("/")[0];return selected.has(domain)})){log.info(`Detected DB_CONNECTION requires ${dbPackage.name}, adding to dependencies`);configDeps[dbPackage.name]=dbPackage.version}if(dbPackage.service&&!autoStart.includes(dbPackage.service))autoStart.push(dbPackage.service)}const lines=["# Auto-generated from config/deps.ts and .env sniffing.","# This file is regenerated on each `buddy setup` run.","#","# To learn more, please visit:","# https://stacksjs.com/docs/dependency-management","","dependencies:"];for(const[pkg,version]of Object.entries(configDeps))lines.push(` ${pkg}: ${version}`);const defined=Object.entries(configDefined);if(autoStart.length>0||defined.length>0){lines.push("","services:"," enabled: true");if(autoStart.length>0){lines.push(" autoStart:");for(const service of autoStart)lines.push(` - ${service}`)}if(defined.length>0){lines.push(" define:");for(const[name,definition]of defined){if(!definition||typeof definition!=="object")continue;lines.push(` ${name}:`);for(const[key,value]of Object.entries(definition)){if(value===void 0||value===null)continue;lines.push(` ${key}: ${String(value)}`)}}}}const depsYamlPath=join(cwd,"deps.yaml");writeFileSync(depsYamlPath,`${lines.join(`
4
+ `);process.stderr.write("Fix the migration, then run `./buddy migrate`.\n");await log.flush();process.exit(ExitCode.FatalError)}log.success("Project is setup");log.info("Run `./buddy doctor` anytime to check your setup. Happy coding! \uD83D\uDC99")}export function ensureIdeSettings(cwd){const source=p.frameworkPath("defaults/ide/vscode/.vscode");const destination=join(cwd,".vscode");if(existsSync(destination)){log.debug(".vscode already exists; keeping the project settings");return}if(!existsSync(source)){log.debug("No bundled VS Code settings found; skipping IDE setup");return}cpSync(source,destination,{recursive:true});log.success("Installed project VS Code settings")}const DB_CONNECTION_PACKAGES={postgres:{name:"postgresql.org",version:"^17.10",service:"postgres"},mysql:{name:"mysql.com",version:"^9.2",service:"mysql"},sqlite:{name:"sqlite.org",version:"^3.47.2"}};function databaseAliases(connection,pkg){return[connection,pkg.name]}export function pantryDatabasePackage(connection){return DB_CONNECTION_PACKAGES[connection]}function detectDbPackage(cwd){const envPath=join(cwd,".env");const envExamplePath=join(cwd,".env.example");const filePath=existsSync(envPath)?envPath:existsSync(envExamplePath)?envExamplePath:undefined;if(!filePath)return;const content=readFileSync(filePath,"utf-8");const match=content.match(/^DB_CONNECTION=(.+)$/m);if(!match)return;const value=match[1].trim().replace(/['"]/g,"");return pantryDatabasePackage(value)}export async function optimizePantryDeps(cwd=p.projectPath()){const depsConfigPath=join(cwd,"config","deps.ts");if(!existsSync(depsConfigPath)){log.debug("No config/deps.ts found, skipping dependency optimization");return false}let configDeps={};let configServices=[];let configDefined={};try{const mod=await import(depsConfigPath);const config=mod.config||mod.default;if(config?.dependencies){configDeps={...config.dependencies}}if(Array.isArray(config?.services?.autoStart)){configServices=config.services.autoStart.filter((name)=>typeof name==="string")}if(config?.services?.define&&typeof config.services.define==="object")configDefined=config.services.define}catch(err){log.debug("Could not load config/deps.ts, skipping dependency optimization");return false}const dbPackage=detectDbPackage(cwd);const autoStart=[...configServices];if(dbPackage){const selected=new Set(Object.entries(DB_CONNECTION_PACKAGES).filter(([,pkg])=>pkg.name===dbPackage.name).flatMap(([connection,pkg])=>databaseAliases(connection,pkg)));const unused=new Set(Object.entries(DB_CONNECTION_PACKAGES).flatMap(([connection,pkg])=>databaseAliases(connection,pkg)).filter((alias)=>!selected.has(alias)));for(const pkg of Object.keys(configDeps)){const domain=pkg.split("/")[0];if(unused.has(domain)){log.info(`DB_CONNECTION selects ${dbPackage.name}, dropping unused ${pkg}`);delete configDeps[pkg]}}const alreadyHasDb=Object.keys(configDeps).some((key)=>{const domain=key.split("/")[0];return selected.has(domain)});if(!alreadyHasDb){log.info(`Detected DB_CONNECTION requires ${dbPackage.name}, adding to dependencies`);configDeps[dbPackage.name]=dbPackage.version}if(dbPackage.service&&!autoStart.includes(dbPackage.service))autoStart.push(dbPackage.service)}const lines=["# Auto-generated from config/deps.ts and .env sniffing.","# This file is regenerated on each `buddy setup` run.","#","# To learn more, please visit:","# https://stacksjs.com/docs/dependency-management","","dependencies:"];for(const[pkg,version]of Object.entries(configDeps)){lines.push(` ${pkg}: ${version}`)}const defined=Object.entries(configDefined);if(autoStart.length>0||defined.length>0){lines.push("","services:"," enabled: true");if(autoStart.length>0){lines.push(" autoStart:");for(const service of autoStart)lines.push(` - ${service}`)}if(defined.length>0){lines.push(" define:");for(const[name,definition]of defined){if(!definition||typeof definition!=="object")continue;lines.push(` ${name}:`);for(const[key,value]of Object.entries(definition)){if(value===undefined||value===null)continue;lines.push(` ${key}: ${String(value)}`)}}}}const depsYamlPath=join(cwd,"deps.yaml");writeFileSync(depsYamlPath,`${lines.join(`
5
5
  `)}
6
- `);log.success("Generated deps.yaml from config/deps.ts");return!0}export async function ensureEnvIsSet(options){log.info("Ensuring .env exists...");const cwd=options.cwd||p.projectPath(),envPath=`${cwd}/.env`,envExamplePath=`${cwd}/.env.example`;if(storage.doesNotExist(envPath)){try{copyFile(envExamplePath,envPath)}catch(error){handleError(error);await log.flush();process.exit(ExitCode.FatalError)}log.success(".env created")}else log.success(".env existed")}function envValues(contents){return contents.split(`
7
- `).map((line)=>line.trim()).filter((line)=>line.length>0&&!line.startsWith("#")&&!line.startsWith("DOTENV_PUBLIC_KEY")).map((line)=>line.slice(line.indexOf("=")+1).trim()).map((value)=>value.replace(/^['"]/,""))}function isCiphertext(value){return value.startsWith("encrypted:")||value.startsWith("enc:")}export function isEnvFileEncrypted(contents){return envValues(contents).every(isCiphertext)}function deployEnvTemplate(environment){return[`# Secrets for the ${environment} environment.`,"#","# Values here are encrypted with the public key below and decrypted at","# deploy time with the matching private key in .env.keys, which is NOT","# committed. This file is - that is the point: the ciphertext is reviewable","# and diffable, and losing a laptop does not leak production.","#","# Add one with:",`# buddy env:set STRIPE_SECRET_KEY sk_live_\u2026 --env ${environment}`,"#","# Left empty on purpose. Nothing was copied out of your .env: that file","# describes a laptop, and a server is not one.",""].join(`
8
- `)}export async function ensureDeployEnvIsSet(cwd,environment){if(["development","dev","local","test"].includes(environment))return;const fileName=`.env.${environment}`,filePath=join(cwd,fileName),created=!existsSync(filePath);if(created)writeFileSync(filePath,deployEnvTemplate(environment));const contents=readFileSync(filePath,"utf-8");if(!created&&isEnvFileEncrypted(contents)){log.success(`${fileName} existed`);return}const{encryptEnv}=await import("@stacksjs/env"),result=encryptEnv({file:fileName,cwd});if(!result.success){await log.error(`Could not encrypt ${fileName}: ${result.error??"unknown error"}`);process.exit(ExitCode.FatalError)}if(created){log.success(`${fileName} created (empty, encrypted - add secrets with \`buddy env:set KEY value --env ${environment}\`)`);return}const encrypted=envValues(contents).filter((value)=>!isCiphertext(value)).length;log.success(`${fileName} encrypted (${encrypted} value${encrypted===1?"":"s"})`)}
6
+ `);log.success("Generated deps.yaml from config/deps.ts");return true}export async function ensureEnvIsSet(options){log.info("Ensuring .env exists...");const cwd=options.cwd||p.projectPath();const envPath=`${cwd}/.env`;const envExamplePath=`${cwd}/.env.example`;if(storage.doesNotExist(envPath)){try{copyFile(envExamplePath,envPath)}catch(error){handleError(error);await log.flush();process.exit(ExitCode.FatalError)}log.success(".env created")}else{log.success(".env existed")}}function envValues(contents){return contents.split(`
7
+ `).map((line)=>line.trim()).filter((line)=>line.length>0&&!line.startsWith("#")&&!line.startsWith("DOTENV_PUBLIC_KEY")).map((line)=>line.slice(line.indexOf("=")+1).trim()).map((value)=>value.replace(/^['"]/,""))}function isCiphertext(value){return value.startsWith("encrypted:")||value.startsWith("enc:")}export function isEnvFileEncrypted(contents){return envValues(contents).every(isCiphertext)}function deployEnvTemplate(environment){return[`# Secrets for the ${environment} environment.`,"#","# Values here are encrypted with the public key below and decrypted at","# deploy time with the matching private key in .env.keys, which is NOT","# committed. This file is - that is the point: the ciphertext is reviewable","# and diffable, and losing a laptop does not leak production.","#","# Add one with:",`# buddy env:set STRIPE_SECRET_KEY sk_live_… --env ${environment}`,"#","# Left empty on purpose. Nothing was copied out of your .env: that file","# describes a laptop, and a server is not one.",""].join(`
8
+ `)}export async function ensureDeployEnvIsSet(cwd,environment){if(["development","dev","local","test"].includes(environment))return;const fileName=`.env.${environment}`;const filePath=join(cwd,fileName);const created=!existsSync(filePath);if(created)writeFileSync(filePath,deployEnvTemplate(environment));const contents=readFileSync(filePath,"utf-8");if(!created&&isEnvFileEncrypted(contents)){log.success(`${fileName} existed`);return}const{encryptEnv}=await import("@stacksjs/env");const result=encryptEnv({file:fileName,cwd});if(!result.success){await log.error(`Could not encrypt ${fileName}: ${result.error??"unknown error"}`);process.exit(ExitCode.FatalError)}if(created){log.success(`${fileName} created (empty, encrypted - add secrets with \`buddy env:set KEY value --env ${environment}\`)`);return}const encrypted=envValues(contents).filter((value)=>!isCiphertext(value)).length;log.success(`${fileName} encrypted (${encrypted} value${encrypted===1?"":"s"})`)}
@@ -1 +1 @@
1
- import{getErrorMessage}from"@stacksjs/utils";import process from"node:process";import{runApiDevServer,runDashboardDevServer,runDesktopDevServer,runDocsDevServer,runFrontendDevServer}from"@stacksjs/actions";import{bold,cyan,dim,green,intro,log,outro,spinner}from"@stacksjs/cli";import{ports as configPorts}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";const originalStdoutWrite=process.stdout.write.bind(process.stdout),originalStderrWrite=process.stderr.write.bind(process.stderr),{log:originalConsoleLog,error:originalConsoleError,warn:originalConsoleWarn,info:originalConsoleInfo}=console;let _muted=!1,_verboseBuffer=[];function muteOutput(){_muted=!0;_verboseBuffer=[];const filter=(fn)=>{return function(chunk,...args){if(_muted){_verboseBuffer.push(String(chunk));return!0}return fn(chunk,...args)}};process.stdout.write=filter(originalStdoutWrite);process.stderr.write=filter(originalStderrWrite);console.log=(...args)=>{if(!_muted)originalConsoleLog(...args)};console.error=(...args)=>{if(!_muted)originalConsoleError(...args)};console.warn=(...args)=>{if(!_muted)originalConsoleWarn(...args)};console.info=(...args)=>{if(!_muted)originalConsoleInfo(...args)}}function unmuteOutput(){_muted=!1;process.stdout.write=originalStdoutWrite;process.stderr.write=originalStderrWrite;console.log=originalConsoleLog;console.error=originalConsoleError;console.warn=originalConsoleWarn;console.info=originalConsoleInfo}async function waitForPort(port,host="localhost",timeoutMs=30000){const start=Date.now();while(Date.now()-start<timeoutMs)try{await(await fetch(`http://${host}:${port}`,{signal:AbortSignal.timeout(1000)})).arrayBuffer();return}catch{await Bun.sleep(300)}throw Error(`Timed out waiting for server on port ${port}`)}const devServerRunners={frontend:runFrontendDevServer,api:runApiDevServer,backend:runApiDevServer,admin:runDashboardDevServer,dashboard:runDashboardDevServer,desktop:runDesktopDevServer,docs:runDocsDevServer},companionServices={frontend:[{port:configPorts?.api||3008,suffix:"api",label:"API",runner:runApiDevServer},{port:configPorts?.docs||3006,suffix:"docs",label:"Docs",runner:runDocsDevServer}]};function capitalize(s){return s.charAt(0).toUpperCase()+s.slice(1)}export function share(buddy){buddy.command("share [type]","Share your local development server via a public tunnel").option("-p, --port <port>","Local port to share").option("--server <url>","Tunnel server URL",{default:"api.localtunnel.dev"}).option("--subdomain <name>","Request a specific subdomain").option("--verbose","Enable verbose output",{default:!1}).action(async(type,options)=>{const perf=await intro("buddy share"),serviceType=type||"frontend",defaultPorts={frontend:configPorts?.frontend||3000,api:configPorts?.api||3008,backend:configPorts?.backend||3001,admin:configPorts?.admin||3002,dashboard:configPorts?.admin||3002,library:configPorts?.library||3003,desktop:configPorts?.desktop||3004,email:configPorts?.email||3005,docs:configPorts?.docs||3006,inspect:configPorts?.inspect||3007},port=options.port?Number.parseInt(options.port,10):defaultPorts[serviceType]||3000;if(Number.isNaN(port)||port<1||port>65535){await log.error(`Invalid port: ${options.port}`);process.exit(ExitCode.InvalidArgument)}const server=options.server||"api.localtunnel.dev",tunnels=[],companions=companionServices[serviceType]||[],s=spinner();try{const{localTunnel}=await import("@stacksjs/tunnel");console.log();const runner=devServerRunners[serviceType];if(runner){s.start(`Starting ${serviceType} dev server...`);muteOutput();runner({verbose:options.verbose??!1}).catch(()=>{});await waitForPort(port);unmuteOutput();s.succeed(`${bold(capitalize(serviceType))} ready ${dim(`on :${port}`)}`)}const startedCompanions=[];if(companions.length>0){s.start("Starting companion services...");muteOutput();for(const companion of companions)companion.runner({verbose:options.verbose??!1}).catch(()=>{});const results=await Promise.allSettled(companions.map((c)=>waitForPort(c.port,"localhost",60000)));unmuteOutput();for(let i=0;i<companions.length;i++){const result=results[i],companion=companions[i];if(!result||!companion)continue;if(result.status==="fulfilled"){startedCompanions.push(companion);s.succeed(`${bold(companion.label)} ready ${dim(`on :${companion.port}`)}`)}else s.fail(`${companion.label} failed to start ${dim(`on :${companion.port}`)}`)}}console.log();s.start("Creating tunnel...");const primaryTunnel=await localTunnel({port,server,subdomain:options.subdomain,verbose:options.verbose,onRequest:(req)=>{if(options.verbose)console.log(` ${dim(`${req.method} ${req.url}`)}`)},onReconnecting:(info)=>{s.start(`Reconnecting... (attempt ${info.attempt})`)}});tunnels.push(primaryTunnel);const baseSubdomain=primaryTunnel.subdomain;for(const companion of startedCompanions)try{const companionTunnel=await localTunnel({port:companion.port,server,subdomain:`${baseSubdomain}-${companion.suffix}`,verbose:options.verbose,onReconnecting:(info)=>{s.start(`${companion.label}: reconnecting... (attempt ${info.attempt})`)}});tunnels.push(companionTunnel)}catch{}s.succeed(`Connected ${dim(`to ${server}`)}`);const entries=[{label:capitalize(serviceType),url:primaryTunnel.url,local:`localhost:${port}`}];for(const companion of startedCompanions){const tunnel=tunnels.find((t)=>t.subdomain===`${baseSubdomain}-${companion.suffix}`);if(tunnel)entries.push({label:companion.label,url:tunnel.url,local:`localhost:${companion.port}`})}const maxLabel=Math.max(...entries.map((e)=>e.label.length));console.log();for(const entry of entries){const padding=" ".repeat(maxLabel-entry.label.length+1);console.log(` ${green("\u279C")} ${bold(entry.label)}${padding} ${cyan(entry.url)}`)}console.log();for(const entry of entries){const padding=" ".repeat(maxLabel-entry.label.length+1);console.log(` ${dim(entry.label)}${dim(padding)}${dim(entry.url)} ${dim("\u2192")} ${dim(entry.local)}`)}console.log();console.log(` ${dim("press Ctrl+C to stop")}`);console.log();const cleanup=async()=>{console.log();s.start("Closing tunnels...");await Promise.all(tunnels.map((t)=>t.close()));s.succeed("Tunnels closed");outro("Stopped sharing",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)};process.on("SIGINT",()=>cleanup());process.on("SIGTERM",()=>cleanup());await new Promise(()=>{})}catch(error){unmuteOutput();s.fail(getErrorMessage(error));const caught=error instanceof Error?error:Error(String(error));if(caught.message.includes("timeout")||caught.message.includes("ECONNREFUSED")){log.error(`Could not reach tunnel server at ${server}`);log.info(`Verify with: curl -sk https://${server}/status`)}else log.error(`Failed to create tunnel: ${caught.message}`);if(options.verbose)log.error(caught.stack);for(const t of tunnels)t.close();await outro("Share failed",{startTime:perf,useSeconds:!0,type:"error"});process.exit(ExitCode.FatalError)}})}
1
+ import{getErrorMessage}from"@stacksjs/utils";import process from"node:process";import{runApiDevServer,runDashboardDevServer,runDesktopDevServer,runDocsDevServer,runFrontendDevServer}from"@stacksjs/actions";import{bold,cyan,dim,green,intro,log,outro,spinner}from"@stacksjs/cli";import{ports as configPorts}from"@stacksjs/config";import{ExitCode}from"@stacksjs/types";const originalStdoutWrite=process.stdout.write.bind(process.stdout);const originalStderrWrite=process.stderr.write.bind(process.stderr);const originalConsoleLog=console.log;const originalConsoleError=console.error;const originalConsoleWarn=console.warn;const originalConsoleInfo=console.info;let _muted=false;let _verboseBuffer=[];function muteOutput(){_muted=true;_verboseBuffer=[];const filter=(fn)=>{return function(chunk,...args){if(_muted){_verboseBuffer.push(String(chunk));return true}return fn(chunk,...args)}};process.stdout.write=filter(originalStdoutWrite);process.stderr.write=filter(originalStderrWrite);console.log=(...args)=>{if(!_muted)originalConsoleLog(...args)};console.error=(...args)=>{if(!_muted)originalConsoleError(...args)};console.warn=(...args)=>{if(!_muted)originalConsoleWarn(...args)};console.info=(...args)=>{if(!_muted)originalConsoleInfo(...args)}}function unmuteOutput(){_muted=false;process.stdout.write=originalStdoutWrite;process.stderr.write=originalStderrWrite;console.log=originalConsoleLog;console.error=originalConsoleError;console.warn=originalConsoleWarn;console.info=originalConsoleInfo}async function waitForPort(port,host="localhost",timeoutMs=30000){const start=Date.now();while(Date.now()-start<timeoutMs){try{const res=await fetch(`http://${host}:${port}`,{signal:AbortSignal.timeout(1000)});await res.arrayBuffer();return}catch{await Bun.sleep(300)}}throw new Error(`Timed out waiting for server on port ${port}`)}const devServerRunners={frontend:runFrontendDevServer,api:runApiDevServer,backend:runApiDevServer,admin:runDashboardDevServer,dashboard:runDashboardDevServer,desktop:runDesktopDevServer,docs:runDocsDevServer};const companionServices={frontend:[{port:configPorts?.api||3008,suffix:"api",label:"API",runner:runApiDevServer},{port:configPorts?.docs||3006,suffix:"docs",label:"Docs",runner:runDocsDevServer}]};function capitalize(s){return s.charAt(0).toUpperCase()+s.slice(1)}export function share(buddy){buddy.command("share [type]","Share your local development server via a public tunnel").option("-p, --port <port>","Local port to share").option("--server <url>","Tunnel server URL",{default:"api.localtunnel.dev"}).option("--subdomain <name>","Request a specific subdomain").option("--verbose","Enable verbose output",{default:false}).action(async(type,options)=>{const perf=await intro("buddy share");const serviceType=type||"frontend";const defaultPorts={frontend:configPorts?.frontend||3000,api:configPorts?.api||3008,backend:configPorts?.backend||3001,admin:configPorts?.admin||3002,dashboard:configPorts?.admin||3002,library:configPorts?.library||3003,desktop:configPorts?.desktop||3004,email:configPorts?.email||3005,docs:configPorts?.docs||3006,inspect:configPorts?.inspect||3007};const port=options.port?Number.parseInt(options.port,10):defaultPorts[serviceType]||3000;if(Number.isNaN(port)||port<1||port>65535){await log.error(`Invalid port: ${options.port}`);process.exit(ExitCode.InvalidArgument)}const server=options.server||"api.localtunnel.dev";const tunnels=[];const companions=companionServices[serviceType]||[];const s=spinner();try{const{localTunnel}=await import("@stacksjs/tunnel");console.log();const runner=devServerRunners[serviceType];if(runner){s.start(`Starting ${serviceType} dev server...`);muteOutput();runner({verbose:options.verbose??false}).catch(()=>{});await waitForPort(port);unmuteOutput();s.succeed(`${bold(capitalize(serviceType))} ready ${dim(`on :${port}`)}`)}const startedCompanions=[];if(companions.length>0){s.start(`Starting companion services...`);muteOutput();for(const companion of companions){companion.runner({verbose:options.verbose??false}).catch(()=>{})}const results=await Promise.allSettled(companions.map((c)=>waitForPort(c.port,"localhost",60000)));unmuteOutput();for(let i=0;i<companions.length;i++){const result=results[i];const companion=companions[i];if(!result||!companion)continue;if(result.status==="fulfilled"){startedCompanions.push(companion);s.succeed(`${bold(companion.label)} ready ${dim(`on :${companion.port}`)}`)}else{s.fail(`${companion.label} failed to start ${dim(`on :${companion.port}`)}`)}}}console.log();s.start("Creating tunnel...");const primaryTunnel=await localTunnel({port,server,subdomain:options.subdomain,verbose:options.verbose,onRequest:(req)=>{if(options.verbose)console.log(` ${dim(`${req.method} ${req.url}`)}`)},onReconnecting:(info)=>{s.start(`Reconnecting... (attempt ${info.attempt})`)}});tunnels.push(primaryTunnel);const baseSubdomain=primaryTunnel.subdomain;for(const companion of startedCompanions){try{const companionTunnel=await localTunnel({port:companion.port,server,subdomain:`${baseSubdomain}-${companion.suffix}`,verbose:options.verbose,onReconnecting:(info)=>{s.start(`${companion.label}: reconnecting... (attempt ${info.attempt})`)}});tunnels.push(companionTunnel)}catch{}}s.succeed(`Connected ${dim(`to ${server}`)}`);const entries=[{label:capitalize(serviceType),url:primaryTunnel.url,local:`localhost:${port}`}];for(const companion of startedCompanions){const tunnel=tunnels.find((t)=>t.subdomain===`${baseSubdomain}-${companion.suffix}`);if(tunnel)entries.push({label:companion.label,url:tunnel.url,local:`localhost:${companion.port}`})}const maxLabel=Math.max(...entries.map((e)=>e.label.length));console.log();for(const entry of entries){const padding=" ".repeat(maxLabel-entry.label.length+1);console.log(` ${green("➜")} ${bold(entry.label)}${padding} ${cyan(entry.url)}`)}console.log();for(const entry of entries){const padding=" ".repeat(maxLabel-entry.label.length+1);console.log(` ${dim(entry.label)}${dim(padding)}${dim(entry.url)} ${dim("→")} ${dim(entry.local)}`)}console.log();console.log(` ${dim("press Ctrl+C to stop")}`);console.log();const cleanup=async()=>{console.log();s.start("Closing tunnels...");await Promise.all(tunnels.map((t)=>t.close()));s.succeed("Tunnels closed");outro("Stopped sharing",{startTime:perf,useSeconds:true});process.exit(ExitCode.Success)};process.on("SIGINT",()=>cleanup());process.on("SIGTERM",()=>cleanup());await new Promise(()=>{})}catch(error){unmuteOutput();s.fail(getErrorMessage(error));const caught=error instanceof Error?error:new Error(String(error));if(caught.message.includes("timeout")||caught.message.includes("ECONNREFUSED")){log.error(`Could not reach tunnel server at ${server}`);log.info(`Verify with: curl -sk https://${server}/status`)}else{log.error(`Failed to create tunnel: ${caught.message}`)}if(options.verbose)log.error(caught.stack);for(const t of tunnels)t.close();await outro("Share failed",{startTime:perf,useSeconds:true,type:"error"});process.exit(ExitCode.FatalError)}})}
@@ -1 +1 @@
1
- import process from"node:process";const XCODE_PATHS=["/Applications/Xcode.app/Contents/Developer","/Applications/Xcode-beta.app/Contents/Developer"];async function run(command,timeoutMs=120000){const child=Bun.spawn(command,{stdout:"pipe",stderr:"pipe"});let timer;const timeout=new Promise((settle)=>{timer=setTimeout(()=>settle("timeout"),timeoutMs)});try{const finished=await Promise.race([child.exited,timeout]);if(finished==="timeout"){child.kill("SIGKILL");return{ok:!1,stdout:"",stderr:`${command[0]} did not finish within ${Math.round(timeoutMs/1000)}s`}}return{ok:finished===0,stdout:await new Response(child.stdout).text(),stderr:await new Response(child.stderr).text()}}finally{if(timer!==void 0)clearTimeout(timer)}}function onMac(){if(process.platform==="darwin")return!0;console.error(" The iOS Simulator is macOS only. Nothing to check here.");return!1}async function selectedDeveloperDir(){const result=await run(["xcode-select","-p"],1e4);return result.ok?result.stdout.trim():null}function isFullXcode(path){return path!=null&&path.includes(".app/Contents/Developer")}async function installedXcode(){for(const path of XCODE_PATHS)if(await Bun.file(`${path}/usr/bin/simctl`).exists())return path;return null}function isWebUrl(value){try{const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"}catch{return!1}}async function devices(){const result=await run(["xcrun","simctl","list","devices","available","--json"],30000);if(!result.ok)return[];let parsed;try{parsed=JSON.parse(result.stdout)}catch{return[]}const found=[];for(const[runtime,list]of Object.entries(parsed.devices??{}))for(const device of list)found.push({...device,runtime:runtime.split(".").pop()??runtime});return found.sort((left,right)=>{const phone=Number(right.name.startsWith("iPhone"))-Number(left.name.startsWith("iPhone"));return phone!==0?phone:right.runtime.localeCompare(left.runtime)})}async function runtimes(){const result=await run(["xcrun","simctl","list","runtimes","--json"],30000);if(!result.ok)return[];try{return(JSON.parse(result.stdout).runtimes??[]).filter((runtime)=>runtime.isAvailable!==!1).map((runtime)=>runtime.name)}catch{return[]}}export function simulator(buddy){buddy.command("simulator:doctor","Whether an iOS simulator can run here, and what to do when it cannot").action(async()=>{if(!onMac()){process.exit(1);return}const selected=await selectedDeveloperDir(),full=isFullXcode(selected),xcode=await installedXcode();console.error(` developer directory ${selected??"could not be read"}`);if(!full){console.error("");console.error(" The command line tools are selected, not Xcode, so there is no simulator.");if(xcode){console.error(" Xcode is installed. Point at it - this needs your password, so run it yourself:");console.error("");console.error(` sudo xcode-select -s ${xcode}`)}else{console.error(" No Xcode found in /Applications. Install it, then:");console.error("");console.error(" sudo xcode-select -s /Applications/Xcode.app/Contents/Developer")}console.error("");process.exit(1)}const available=await runtimes();console.error(` runtimes ${available.length>0?available.join(", "):"none"}`);if(available.length===0){console.error("");console.error(" No iOS runtime is installed, so nothing can boot. Xcode ships without one:");console.error("");console.error(" xcodebuild -downloadPlatform iOS");console.error("");console.error(" It is several gigabytes. Check there is room for it first.");console.error("");process.exit(1)}const list=await devices(),booted=list.filter((device)=>device.state==="Booted");console.error(` devices ${list.length} available, ${booted.length} booted`);if(booted.length>0)for(const device of booted)console.error(` ${device.name} (${device.runtime})`);console.error("");console.error(" Ready. `buddy simulator:open <url>` boots a phone and opens it in Mobile Safari.");console.error("")});buddy.command("simulator:open <url>","Open a URL in Mobile Safari on a simulator, booting one if needed").option("--device <name>","Which device, by name. Defaults to the newest iPhone.",{default:""}).option("--screenshot <path>","Save a picture of the result here",{default:""}).option("--settle <seconds>","How long to let the page load before the screenshot",{default:8}).option("--fresh","Quit Mobile Safari first, so this is not the last page again",{default:!1}).action(async(url,options)=>{if(!onMac()){process.exit(1);return}if(!isWebUrl(url)){console.error(" Only http and https URLs. Anything else is a scheme, not a page.");process.exit(1);return}if(!isFullXcode(await selectedDeveloperDir())){console.error(" No full Xcode selected. Run `buddy simulator:doctor` for the fix.");process.exit(1);return}const wanted=String(options.device??""),list=await devices(),chosen=wanted?list.find((device)=>device.name===wanted):list.find((device)=>device.state==="Booted")??list[0];if(!chosen){console.error(wanted?` No device called ${wanted}. \`xcrun simctl list devices available\` says what there is.`:" No devices available. Run `buddy simulator:doctor`.");process.exit(1);return}if(chosen.state!=="Booted"){console.error(` booting ${chosen.name}\u2026`);const booted=await run(["xcrun","simctl","boot",chosen.udid],180000);if(!booted.ok&&!booted.stderr.includes("current state: Booted")){console.error(` could not boot ${chosen.name}: ${booted.stderr.trim()}`);process.exit(1);return}await run(["xcrun","simctl","bootstatus",chosen.udid],180000)}if(options.fresh){await run(["xcrun","simctl","terminate",chosen.udid,"com.apple.mobilesafari"],30000);await Bun.sleep(1200)}const opened=await run(["xcrun","simctl","openurl",chosen.udid,url],60000);if(!opened.ok){console.error(` could not open the URL: ${opened.stderr.trim()}`);process.exit(1);return}console.error(` opened on ${chosen.name} (${chosen.runtime})`);const shot=String(options.screenshot??"");if(shot){const settle=Math.max(0,Number(options.settle??8));console.error(` waiting ${settle}s for the page\u2026`);await Bun.sleep(settle*1000);const captured=await run(["xcrun","simctl","io",chosen.udid,"screenshot",shot],60000);if(!captured.ok){console.error(` could not take a screenshot: ${captured.stderr.trim()}`);process.exit(1);return}console.error(` screenshot ${shot}`)}})}
1
+ import process from"node:process";const XCODE_PATHS=["/Applications/Xcode.app/Contents/Developer","/Applications/Xcode-beta.app/Contents/Developer"];async function run(command,timeoutMs=120000){const child=Bun.spawn(command,{stdout:"pipe",stderr:"pipe"});let timer;const timeout=new Promise((settle)=>{timer=setTimeout(()=>settle("timeout"),timeoutMs)});try{const finished=await Promise.race([child.exited,timeout]);if(finished==="timeout"){child.kill("SIGKILL");return{ok:false,stdout:"",stderr:`${command[0]} did not finish within ${Math.round(timeoutMs/1000)}s`}}return{ok:finished===0,stdout:await new Response(child.stdout).text(),stderr:await new Response(child.stderr).text()}}finally{if(timer!==undefined)clearTimeout(timer)}}function onMac(){if(process.platform==="darwin")return true;console.error(" The iOS Simulator is macOS only. Nothing to check here.");return false}async function selectedDeveloperDir(){const result=await run(["xcode-select","-p"],1e4);return result.ok?result.stdout.trim():null}function isFullXcode(path){return path!=null&&path.includes(".app/Contents/Developer")}async function installedXcode(){for(const path of XCODE_PATHS){if(await Bun.file(`${path}/usr/bin/simctl`).exists())return path}return null}function isWebUrl(value){try{const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"}catch{return false}}async function devices(){const result=await run(["xcrun","simctl","list","devices","available","--json"],30000);if(!result.ok)return[];let parsed;try{parsed=JSON.parse(result.stdout)}catch{return[]}const found=[];for(const[runtime,list]of Object.entries(parsed.devices??{})){for(const device of list)found.push({...device,runtime:runtime.split(".").pop()??runtime})}return found.sort((left,right)=>{const phone=Number(right.name.startsWith("iPhone"))-Number(left.name.startsWith("iPhone"));return phone!==0?phone:right.runtime.localeCompare(left.runtime)})}async function runtimes(){const result=await run(["xcrun","simctl","list","runtimes","--json"],30000);if(!result.ok)return[];try{const parsed=JSON.parse(result.stdout);return(parsed.runtimes??[]).filter((runtime)=>runtime.isAvailable!==false).map((runtime)=>runtime.name)}catch{return[]}}export function simulator(buddy){buddy.command("simulator:doctor","Whether an iOS simulator can run here, and what to do when it cannot").action(async()=>{if(!onMac()){process.exit(1);return}const selected=await selectedDeveloperDir();const full=isFullXcode(selected);const xcode=await installedXcode();console.error(` developer directory ${selected??"could not be read"}`);if(!full){console.error("");console.error(" The command line tools are selected, not Xcode, so there is no simulator.");if(xcode){console.error(" Xcode is installed. Point at it - this needs your password, so run it yourself:");console.error("");console.error(` sudo xcode-select -s ${xcode}`)}else{console.error(" No Xcode found in /Applications. Install it, then:");console.error("");console.error(" sudo xcode-select -s /Applications/Xcode.app/Contents/Developer")}console.error("");process.exit(1)}const available=await runtimes();console.error(` runtimes ${available.length>0?available.join(", "):"none"}`);if(available.length===0){console.error("");console.error(" No iOS runtime is installed, so nothing can boot. Xcode ships without one:");console.error("");console.error(" xcodebuild -downloadPlatform iOS");console.error("");console.error(" It is several gigabytes. Check there is room for it first.");console.error("");process.exit(1)}const list=await devices();const booted=list.filter((device)=>device.state==="Booted");console.error(` devices ${list.length} available, ${booted.length} booted`);if(booted.length>0){for(const device of booted)console.error(` ${device.name} (${device.runtime})`)}console.error("");console.error(" Ready. `buddy simulator:open <url>` boots a phone and opens it in Mobile Safari.");console.error("")});buddy.command("simulator:open <url>","Open a URL in Mobile Safari on a simulator, booting one if needed").option("--device <name>","Which device, by name. Defaults to the newest iPhone.",{default:""}).option("--screenshot <path>","Save a picture of the result here",{default:""}).option("--settle <seconds>","How long to let the page load before the screenshot",{default:8}).option("--fresh","Quit Mobile Safari first, so this is not the last page again",{default:false}).action(async(url,options)=>{if(!onMac()){process.exit(1);return}if(!isWebUrl(url)){console.error(" Only http and https URLs. Anything else is a scheme, not a page.");process.exit(1);return}if(!isFullXcode(await selectedDeveloperDir())){console.error(" No full Xcode selected. Run `buddy simulator:doctor` for the fix.");process.exit(1);return}const wanted=String(options.device??"");const list=await devices();const chosen=wanted?list.find((device)=>device.name===wanted):list.find((device)=>device.state==="Booted")??list[0];if(!chosen){console.error(wanted?` No device called ${wanted}. \`xcrun simctl list devices available\` says what there is.`:" No devices available. Run `buddy simulator:doctor`.");process.exit(1);return}if(chosen.state!=="Booted"){console.error(` booting ${chosen.name}…`);const booted=await run(["xcrun","simctl","boot",chosen.udid],180000);if(!booted.ok&&!booted.stderr.includes("current state: Booted")){console.error(` could not boot ${chosen.name}: ${booted.stderr.trim()}`);process.exit(1);return}await run(["xcrun","simctl","bootstatus",chosen.udid],180000)}if(options.fresh){await run(["xcrun","simctl","terminate",chosen.udid,"com.apple.mobilesafari"],30000);await Bun.sleep(1200)}const opened=await run(["xcrun","simctl","openurl",chosen.udid,url],60000);if(!opened.ok){console.error(` could not open the URL: ${opened.stderr.trim()}`);process.exit(1);return}console.error(` opened on ${chosen.name} (${chosen.runtime})`);const shot=String(options.screenshot??"");if(shot){const settle=Math.max(0,Number(options.settle??8));console.error(` waiting ${settle}s for the page…`);await Bun.sleep(settle*1000);const captured=await run(["xcrun","simctl","io",chosen.udid,"screenshot",shot],60000);if(!captured.ok){console.error(` could not take a screenshot: ${captured.stderr.trim()}`);process.exit(1);return}console.error(` screenshot ${shot}`)}})}