Skip to content

feat(cli): add programmatic api - #494

Merged
AmanVarshney01 merged 6 commits into
mainfrom
bts-api
Aug 12, 2025
Merged

AmanVarshney01 merged 6 commits into
mainfrom
bts-api

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Aug 11, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features
    • Programmatic CLI API: init(), sponsors(), docs(), builder() returning a typed InitResult; directory-conflict strategies (merge, overwrite, increment, error); --verbose and --yolo runtime options; --render-title toggle.
  • Documentation
    • Added Programmatic API guide and expanded CLI options/examples (directory conflict, verbose, yolo, render-title).
  • Tests
    • Smoke tests and new programmatic API test suite run the CLI in-process.
  • Chores
    • CLI startup/packaging updated and programmatic error/exit behavior improved.

@changeset-bot

changeset-bot Bot commented Aug 11, 2025 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d1d0703

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
create-better-t-stack Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds a programmatic API to the CLI (createBtsCli, init, sponsors, docs, builder), refactors init to return a structured InitResult, introduces directory-conflict strategies and yolo/verbose/renderTitle flags, changes CLI entrypoints/build outputs, adapts tests to run the CLI in-process, and updates docs and types.

Changes

Cohort / File(s) Summary
Release metadata
.changeset/eleven-walls-tease.md
Adds a minor changeset entry: “Add programmatic API”.
CLI packaging & build
apps/cli/package.json, apps/cli/tsdown.config.ts, package.json
Switch CLI bin/script to dist/cli.js; add exports mapping and dts: true; add src/cli.ts as tsdown entry.
CLI runtime entry
apps/cli/src/cli.ts
New launcher that invokes createBtsCli().run() to start the CLI.
Public API & router
apps/cli/src/index.ts
Exposes router and new programmatic APIs: createBtsCli, init, sponsors, docs, builder; init accepts yolo, verbose, directoryConflict, renderTitle and can return InitResult when verbose.
Types & schemas
apps/cli/src/types.ts
Add DirectoryConflictSchema/DirectoryConflict, extend CreateInput with yolo, verbose, directoryConflict, renderTitle, and introduce InitResult interface.
Init handler refactor
apps/cli/src/helpers/project-generation/command-handlers.ts
createProjectHandler now returns Promise<InitResult>; adds programmatic directory-conflict resolution modes (overwrite/merge/increment/error), YOLO mode, timing fields, reproducible command generation, and structured InitResult/error returns.
Directory conflict utility
apps/cli/src/utils/project-directory.ts
handleDirectoryConflict(currentPathInput, silent = false) added; in silent mode throws when dir exists and is non-empty; preserves interactive behavior when not silent.
Error handling for programmatic use
apps/cli/src/utils/errors.ts
Add isProgrammatic check; exitWithError, exitCancelled, handleError throw Error in programmatic mode instead of calling process.exit.
Validation helpers
apps/cli/src/validation.ts
Add processProvidedFlagsWithoutValidation(options, projectName?); update processAndValidateFlags signature to accept projectName; centralize name derivation/validation and array normalization.
Programmatic wiring in tests
apps/cli/test/cli.smoke.test.ts, apps/cli/test/programmatic-api.test.ts
Smoke tests and new programmatic API tests drive CLI in-process via createBtsCli/init; new helpers, environment toggles, and expectations for returned InitResult.
Docs: CLI usage & programmatic API
apps/web/content/docs/cli/index.mdx, options.mdx, programmatic-api.mdx
Document new flags/options (--verbose, --yolo, --directory-conflict, --render-title) and add Programmatic Usage/API page with examples and types.
Docs: navigation
apps/web/content/docs/cli/meta.json
Insert programmatic-api into CLI docs pages array.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant App as Node program
  participant API as createBtsCli / init
  participant Handler as createProjectHandler
  participant FS as FileSystem

  User->>App: call init(projectName?, options)
  App->>API: init(projectName, options)
  API->>Handler: combine input (yolo, verbose, directoryConflict, renderTitle)
  Handler->>FS: check target directory
  alt exists
    Handler->>Handler: resolve conflict (merge/overwrite/increment/error)
    opt overwrite
      Handler->>FS: clear directory
    end
    opt increment
      Handler->>FS: compute unique name
    end
  end
  Handler->>FS: scaffold project
  Handler-->>API: return InitResult
  API-->>App: return InitResult (if verbose) or void
Loading
sequenceDiagram
  participant Shell
  participant Entry as dist/cli.js (apps/cli/src/cli.ts)
  participant API as createBtsCli
  participant Router as router/caller

  Shell->>Entry: node dist/cli.js
  Entry->>API: createBtsCli()
  API->>Router: create caller from router
  API-->>Entry: CLI instance
  Entry->>Entry: run()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I’m a rabbit with a tiny plan,
I call init from Node — no shell, hooray!
YOLO hops, conflicts solved by hand,
A timed result, a reproducible way.
Burrow built, I dance — programmatic day. 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca296ac and d1d0703.

📒 Files selected for processing (3)
  • apps/cli/src/index.ts (6 hunks)
  • apps/cli/src/utils/errors.ts (1 hunks)
  • apps/cli/test/programmatic-api.test.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bts-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@pkg-pr-new

pkg-pr-new Bot commented Aug 11, 2025 •

Copy link
Copy Markdown

Open in StackBlitz

npx https://pkg.pr.new/AmanVarshney01/create-better-t-stack@494

commit: d1d0703

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (1)
apps/cli/src/utils/project-directory.ts (1)

16-19: Handle non-directory paths to avoid readdirSync throwing.
If resolvedPath exists but is a file, readdirSync will throw. Guard with isDirectory.

- const dirExists = fs.pathExistsSync(resolvedPath);
- const dirIsNotEmpty = dirExists && fs.readdirSync(resolvedPath).length > 0;
+ const exists = fs.pathExistsSync(resolvedPath);
+ const stat = exists ? fs.statSync(resolvedPath) : undefined;
+ const isDir = !!stat && stat.isDirectory();
+ const dirIsNotEmpty = isDir && fs.readdirSync(resolvedPath).length > 0;
🧹 Nitpick comments (10)
apps/cli/src/utils/project-directory.ts (2)

24-28: Silent mode throws — refine guidance in the error and tie it to flags.
The message is clear. Consider mentioning the non-interactive flag to use, e.g., suggest --directory-conflict overwrite|increment|error to avoid this error in CLI mode.

- throw new Error(
-  `Directory "${currentPathInput}" already exists and is not empty. In silent mode, please provide a different project name or clear the directory manually.`,
- );
+ throw new Error(
+  `Directory "${currentPathInput}" exists and is not empty. In silent mode, provide a different path, clear it manually, or set --directory-conflict=overwrite|increment|error.`,
+ );

75-78: Propagate silent flag in recursive call (rename path).
Not strictly needed today (silent=false in interactive mode), but passing it through is safer if defaults change.

- return await handleDirectoryConflict(newPathInput);
+ return await handleDirectoryConflict(newPathInput, silent);
apps/web/content/docs/cli/options.mdx (1)

40-80: New flags are clearly documented. Minor clarifications suggested.

  • Mention the default directory-conflict behavior is “prompt”.
  • For increment strategy, note it will keep incrementing until a free name is found.
- How to handle existing, non-empty target directories:
+ How to handle existing, non-empty target directories (default: prompt):
@@
-- `increment`: Create a suffixed directory (e.g., `my-app-1`)
+- `increment`: Create a suffixed directory (e.g., `my-app-1`, `my-app-2`, …) until a free name is found
apps/web/content/docs/cli/index.mdx (1)

159-177: Improve example code for better type safety and error handling

The programmatic usage example could be improved for clarity and robustness.

 import { init } from "create-better-t-stack";
 
 // Create multiple projects programmatically
 const projects = [
   { name: "api", config: { frontend: ["none"], backend: "hono" } },
   { name: "web", config: { frontend: ["next"], backend: "none" } }
 ];
 
-for (const { name, config } of projects) {
-  const result = await init(name, {
-    yes: true,
-    ...config,
-    directoryConflict: "increment"
-  });
-  
-  console.log(result.success ? `✅ ${name}` : `❌ ${name}: ${result.error}`);
-}
+async function createProjects() {
+  for (const { name, config } of projects) {
+    try {
+      const result = await init(name, {
+        yes: true,
+        directoryConflict: "increment",
+        ...config, // Spread config last to allow overrides
+      });
+      
+      if (result.success) {
+        console.log(`✅ Created ${name} at ${result.projectDirectory}`);
+      } else {
+        console.error(`❌ Failed to create ${name}: ${result.error}`);
+      }
+    } catch (error) {
+      console.error(`❌ Unexpected error creating ${name}:`, error);
+    }
+  }
+}
+
+createProjects();
apps/cli/src/types.ts (1)

188-197: Add JSDoc comments for better IDE support

The InitResult interface would benefit from JSDoc comments to improve developer experience.

+/**
+ * Result of a project initialization operation
+ */
 export interface InitResult {
+  /** Whether the operation completed successfully */
   success: boolean;
+  /** Final project configuration used */
   projectConfig: ProjectConfig;
+  /** CLI command that can recreate this project */
   reproducibleCommand: string;
+  /** ISO 8601 timestamp when scaffolding started */
   timeScaffolded: string;
+  /** Total time taken in milliseconds */
   elapsedTimeMs: number;
+  /** Absolute path to the created project directory */
   projectDirectory: string;
+  /** Relative path from cwd to project directory */
   relativePath: string;
+  /** Error message if operation failed (only present when success is false) */
   error?: string;
 }
apps/cli/test/cli.smoke.test.ts (1)

16-38: Simplify error handling logic

The nested while loop for unwrapping FailedToExitError could be simplified and made more readable.

 async function runCli(argv: string[], cwd: string) {
   const previous = process.cwd();
   process.chdir(cwd);
   try {
     const cli = createBtsCli();
     await cli
       .run({
         argv,
-        logger: { info: () => {}, error: () => {} },
+        logger: { 
+          info: process.env.DEBUG_TESTS ? console.info : () => {},
+          error: console.error // Always log errors for debugging
+        },
         process: { exit: () => void 0 as never },
       })
       .catch((err) => {
-        let e: unknown = err;
-        while (e instanceof FailedToExitError) {
-          if (e.exitCode === 0) return e.cause;
-          e = e.cause;
-        }
-        throw e;
+        // Unwrap FailedToExitError to get the actual cause
+        const unwrapError = (error: unknown): unknown => {
+          if (error instanceof FailedToExitError) {
+            return error.exitCode === 0 ? error.cause : unwrapError(error.cause);
+          }
+          return error;
+        };
+        const unwrapped = unwrapError(err);
+        if (err instanceof FailedToExitError && err.exitCode === 0) {
+          return unwrapped;
+        }
+        throw unwrapped;
       });
   } finally {
     process.chdir(previous);
   }
 }
apps/web/content/docs/cli/programmatic-api.mdx (2)

186-192: Strengthen warning about YOLO mode

The YOLO mode warning should be more prominent given its potential to break projects.

 ### YOLO Mode
 
-Bypass validation checks (not recommended):
+⚠️ **WARNING: Bypass validation checks at your own risk!**
+
+YOLO mode skips all compatibility validations and can result in broken or non-functional projects. Only use this if you fully understand the implications.
 
 ```typescript
 // Skip compatibility validations
 yolo: true

---

`203-210`: **Improve error handling example completeness**

The error handling example should demonstrate accessing all fields of the failed result.


```diff
 const result = await init("existing-dir", {
   directoryConflict: "error"
 });
 
 if (!result.success) {
   console.log(result.error); // "Directory exists and is not empty..."
+  // All fields are still populated even on failure:
+  console.log(`Failed after ${result.elapsedTimeMs}ms`);
+  console.log(`Attempted path: ${result.relativePath || 'not set'}`);
   // Handle gracefully instead of process exit
 }
apps/cli/src/helpers/project-generation/command-handlers.ts (2)

45-47: Reconsider using consola.fatal for non-fatal warning

Using consola.fatal for YOLO mode is misleading since execution continues. The "fatal" level typically indicates unrecoverable errors.

  if (input.yolo) {
-   consola.fatal("YOLO mode enabled - skipping checks. Things may break!");
+   consola.warn("⚠️  YOLO mode enabled - skipping validation checks. Proceed with caution!");
  }

49-65: Extract complex path determination logic

The nested conditions for determining currentPathInput are complex and would benefit from extraction into a helper function.

+async function determineProjectPath(input: CreateInput & { projectName?: string }): Promise<string> {
+  if (input.yes && input.projectName) {
+    return input.projectName;
+  }
+  
+  if (input.yes) {
+    let defaultName = DEFAULT_CONFIG.relativePath;
+    let counter = 1;
+    while (
+      fs.pathExistsSync(path.resolve(process.cwd(), defaultName)) &&
+      fs.readdirSync(path.resolve(process.cwd(), defaultName)).length > 0
+    ) {
+      defaultName = `${DEFAULT_CONFIG.projectName}-${counter}`;
+      counter++;
+    }
+    return defaultName;
+  }
+  
+  return getProjectName(input.projectName);
+}

- let currentPathInput: string;
- if (input.yes && input.projectName) {
-   currentPathInput = input.projectName;
- } else if (input.yes) {
-   let defaultName = DEFAULT_CONFIG.relativePath;
-   let counter = 1;
-   while (
-     fs.pathExistsSync(path.resolve(process.cwd(), defaultName)) &&
-     fs.readdirSync(path.resolve(process.cwd(), defaultName)).length > 0
-   ) {
-     defaultName = `${DEFAULT_CONFIG.projectName}-${counter}`;
-     counter++;
-   }
-   currentPathInput = defaultName;
- } else {
-   currentPathInput = await getProjectName(input.projectName);
- }
+ const currentPathInput = await determineProjectPath(input);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b2827e and b0aa87b.

📒 Files selected for processing (15)
  • .changeset/eleven-walls-tease.md (1 hunks)
  • apps/cli/package.json (2 hunks)
  • apps/cli/src/cli.ts (1 hunks)
  • apps/cli/src/helpers/project-generation/command-handlers.ts (2 hunks)
  • apps/cli/src/index.ts (6 hunks)
  • apps/cli/src/types.ts (3 hunks)
  • apps/cli/src/utils/project-directory.ts (2 hunks)
  • apps/cli/src/validation.ts (1 hunks)
  • apps/cli/test/cli.smoke.test.ts (3 hunks)
  • apps/cli/tsdown.config.ts (1 hunks)
  • apps/web/content/docs/cli/index.mdx (3 hunks)
  • apps/web/content/docs/cli/meta.json (1 hunks)
  • apps/web/content/docs/cli/options.mdx (1 hunks)
  • apps/web/content/docs/cli/programmatic-api.mdx (1 hunks)
  • package.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
apps/cli/src/cli.ts (1)
apps/cli/src/index.ts (1)
  • createBtsCli (170-176)
apps/cli/src/validation.ts (1)
apps/cli/src/types.ts (13)
  • CLIInput (147-149)
  • ProjectConfig (151-169)
  • API (81-81)
  • Backend (16-16)
  • Database (6-6)
  • ORM (11-11)
  • Runtime (21-21)
  • DatabaseSetup (78-78)
  • PackageManager (64-64)
  • WebDeploy (109-109)
  • Frontend (37-37)
  • Addons (54-54)
  • Examples (59-59)
apps/cli/test/cli.smoke.test.ts (1)
apps/cli/src/index.ts (1)
  • createBtsCli (170-176)
apps/cli/src/helpers/project-generation/command-handlers.ts (1)
apps/cli/src/types.ts (3)
  • InitResult (188-197)
  • ProjectConfig (151-169)
  • DirectoryConflict (114-114)
apps/cli/src/index.ts (1)
apps/cli/src/types.ts (3)
  • DirectoryConflictSchema (111-113)
  • CreateInput (116-137)
  • InitResult (188-197)
apps/cli/src/types.ts (1)
apps/cli/src/index.ts (4)
  • DirectoryConflict (244-244)
  • CreateInput (245-245)
  • InitResult (249-249)
  • ProjectConfig (247-247)
🔇 Additional comments (18)
.changeset/eleven-walls-tease.md (1)

1-6: Changeset looks correct for publishing the programmatic API.
Package name matches, bump type is minor, and the message is concise. Good to go.

package.json (1)

8-8: Root CLI script now points to dist/cli.js — aligns with new entrypoint.
This matches the bin move. Ensure the CLI is built before invoking this script locally.

Can you confirm your local workflow (or a pre-step) builds apps/cli before running this script? Otherwise, consider a small wrapper script that builds if dist is missing.

apps/cli/package.json (2)

9-10: Bin moved to dist/cli.js — consistent with new bootstrap.
This aligns with src/cli.ts and the root script change.


56-61: Exports map exposes programmatic API at package root (ESM-only).
Looks good for ESM consumers. If you intend to support CommonJS require(), you’d need a CJS build and a "require" condition. If ESM-only is intentional, this is fine.

Do you plan to support require()? If not, consider documenting ESM-only usage in the README to prevent confusion for consumers.

apps/cli/src/utils/project-directory.ts (1)

10-10: New silent parameter is a good addition for non-interactive flows.
This enables programmatic/CI usage without prompts.

apps/web/content/docs/cli/meta.json (1)

4-4: Nav updated — programmatic-api page added.
Order looks good.

apps/cli/tsdown.config.ts (3)

4-4: Including src/cli.ts in entries is correct.
Ensures the CLI bootstrap is built and published.


9-9: dts: true — good for publishing types.
This will emit .d.ts for both index and cli entries.


4-12: Global shebang banner may affect dist/index.js consumers.
With a global banner, both dist/cli.js and dist/index.js will get the shebang. Node tolerates this, but some bundlers/runtimes can be picky when importing a library module with a shebang.

Can you verify that dist/index.js also gets the shebang and that programmatic imports in your target environments (Node, Bun) behave correctly? If needed, consider scoping the shebang to only the CLI output.

apps/cli/src/index.ts (9)

10-40: LGTM! Clean type management for public API.

The type imports are comprehensive and well-organized, providing all necessary types for the programmatic API surface.


49-49: LGTM! Router export enables programmatic access.

Exporting the router is essential for the programmatic API functionality.


65-76: LGTM! Well-designed input schema extensions.

The new input fields are properly typed, optional with sensible defaults, and have clear descriptions. The warning on the yolo flag is appropriate.

Also applies to: 91-92


96-107: LGTM! Smart conditional return for programmatic vs CLI usage.

The modification to capture and conditionally return the result enables programmatic access while maintaining backward compatibility for CLI usage.


168-168: LGTM! Standard tRPC caller pattern.

The caller creation follows tRPC best practices and enables the programmatic API functions.


170-176: LGTM! Clean CLI factory function.

The createBtsCli function provides a clean way to instantiate the CLI programmatically.


178-218: Excellent documentation and implementation!

The comprehensive documentation with both CLI and programmatic examples is very helpful. The implementation correctly forces verbose mode to ensure structured data is always returned.


220-230: LGTM! Simple and clean wrapper functions.

These wrapper functions provide a consistent programmatic API for all CLI commands.


232-250: LGTM! Comprehensive type exports for public API.

The type exports provide a complete public API surface, enabling proper TypeScript integration for library consumers.

Comment thread apps/cli/src/cli.ts Outdated
Comment on lines +1 to +3
import { createBtsCli } from "./index";

void createBtsCli().run();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Prefer top-level await to propagate exit codes.
Using void discards rejections. Awaiting ensures thrown errors set a non-zero exit code.

-import { createBtsCli } from "./index";
-
-void createBtsCli().run();
+import { createBtsCli } from "./index";
+
+await createBtsCli().run();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { createBtsCli } from "./index";
void createBtsCli().run();
import { createBtsCli } from "./index";
await createBtsCli().run();
🤖 Prompt for AI Agents
In apps/cli/src/cli.ts around lines 1-3, the code uses "void
createBtsCli().run();" which discards rejections and prevents non-zero exit
codes; replace it with a top-level await: "await createBtsCli().run();", and if
your project uses TypeScript ensure tsconfig.json uses a module target that
supports top-level await (e.g., "module": "ES2022" or "ESNext") so the await is
allowed and unhandled rejections propagate to a non-zero exit code.

Comment thread apps/cli/src/validation.ts Resolved
Comment thread apps/cli/src/validation.ts Resolved
Comment on lines +328 to +329
process.env.BTS_TELEMETRY_DISABLED = "1";
consola.info("Programmatic CLI mode");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Ensure proper test isolation for environment variables

Setting process.env directly could affect other tests if they run in parallel or if the cleanup fails.

+  const originalTelemetryValue = process.env.BTS_TELEMETRY_DISABLED;
   process.env.BTS_TELEMETRY_DISABLED = "1";
   consola.info("Programmatic CLI mode");
+  
+  // Ensure cleanup in afterAll
+  afterAll(() => {
+    if (originalTelemetryValue === undefined) {
+      delete process.env.BTS_TELEMETRY_DISABLED;
+    } else {
+      process.env.BTS_TELEMETRY_DISABLED = originalTelemetryValue;
+    }
+  });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
process.env.BTS_TELEMETRY_DISABLED = "1";
consola.info("Programmatic CLI mode");
const originalTelemetryValue = process.env.BTS_TELEMETRY_DISABLED;
process.env.BTS_TELEMETRY_DISABLED = "1";
consola.info("Programmatic CLI mode");
// Ensure cleanup in afterAll
afterAll(() => {
if (originalTelemetryValue === undefined) {
delete process.env.BTS_TELEMETRY_DISABLED;
} else {
process.env.BTS_TELEMETRY_DISABLED = originalTelemetryValue;
}
});
🤖 Prompt for AI Agents
In apps/cli/test/cli.smoke.test.ts around lines 328-329, setting
process.env.BTS_TELEMETRY_DISABLED directly can leak state to other tests;
change the test to save the original value before modifying it and restore it in
an afterEach or finally block (or use Jest's beforeEach/afterEach hooks) so the
environment variable is reset after the test; ensure both undefined and string
cases are handled when restoring to avoid accidental mutation of process.env.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
apps/cli/src/validation.ts (1)

167-179: Unreachable branch in examples processing

Inside the else branch (which only runs when options.examples does NOT include "none"), the condition if (options.examples.includes("none") && …) can never be true. This is dead code and could hide actual logic you intended (e.g., special-casing "none" + non-convex backend).

Apply this diff to remove the unreachable branch:

-	} else {
-			config.examples = processArrayOption(options.examples);
-			if (options.examples.includes("none") && config.backend !== "convex") {
-				config.examples = [];
-			}
-		}
+	} else {
+		config.examples = processArrayOption(options.examples);
+	}

If there is an intended rule that affects examples for non-convex backends, consider enforcing it via validateExamplesCompatibility instead of ad-hoc inline conditions for consistency.

🧹 Nitpick comments (3)
apps/cli/src/validation.ts (3)

28-33: Constrain generic and support readonly inputs in processArrayOption

Tighten the typing and simplify the includes check. This avoids accidental non-string T usage and makes it friendlier to readonly arrays.

Apply this diff:

-function processArrayOption<T>(options: (T | "none")[] | undefined): T[] {
-	if (!options || options.length === 0) return [];
-	if (options.includes("none" as T | "none")) return [];
-	return options.filter((item): item is T => item !== "none");
-}
+function processArrayOption<T extends string>(
+	options: ReadonlyArray<T | "none"> | undefined,
+): T[] {
+	if (!options || options.length === 0) return [];
+	if (options.includes("none")) return [];
+	return options.filter((item): item is T => item !== "none");
+}

47-56: Keep validators pure; avoid process.exit in helpers

validateProjectName hard-exits the process. Prefer throwing from the validator and let the CLI path decide to exit, so the same helper can be safely reused in programmatic paths.

Proposed refactor:

-function validateProjectName(name: string): void {
-	const result = ProjectNameSchema.safeParse(name);
-	if (!result.success) {
-		exitWithError(
-			`Invalid project name: ${
-				result.error.issues[0]?.message || "Invalid project name"
-			}`,
-		);
-	}
-}
+function assertValidProjectName(name: string): void {
+	const result = ProjectNameSchema.safeParse(name);
+	if (!result.success) {
+		throw new Error(
+			`Invalid project name: ${result.error.issues[0]?.message || "Invalid project name"}`,
+		);
+	}
+}

Then, in the CLI path, wrap and exit:

try {
  assertValidProjectName(derivedName);
} catch (e) {
  exitWithError((e as Error).message);
}

493-505: Intent check: silent normalization vs. exclusivity errors for "none" in programmatic API

Here, processArrayOption silently returns [] when "none" is mixed with other values (no error), unlike the CLI path which errors on such combinations. If this divergence is intentional for the programmatic API, consider documenting it. If not, we can add an optional parameter to processArrayOption to enforce exclusivity and surface an error to the caller.

Would you like a small helper like assertExclusiveNone(options, flagName) that throws on mixing "none" with others, to reuse across both paths?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0aa87b and ca296ac.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • apps/cli/package.json (3 hunks)
  • apps/cli/src/cli.ts (1 hunks)
  • apps/cli/src/helpers/project-generation/command-handlers.ts (2 hunks)
  • apps/cli/src/validation.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/cli/src/cli.ts
  • apps/cli/package.json
  • apps/cli/src/helpers/project-generation/command-handlers.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/cli/src/validation.ts (2)
apps/cli/src/types.ts (11)
  • ProjectNameSchema (83-103)
  • CLIInput (147-149)
  • ProjectConfig (151-169)
  • API (81-81)
  • Backend (16-16)
  • Database (6-6)
  • ORM (11-11)
  • Runtime (21-21)
  • DatabaseSetup (78-78)
  • PackageManager (64-64)
  • WebDeploy (109-109)
apps/cli/src/utils/errors.ts (1)
  • exitWithError (5-8)
🔇 Additional comments (2)
apps/cli/src/validation.ts (2)

135-146: Frontend normalization + mutual exclusivity check looks good

Using processArrayOption followed by ensureSingleWebAndNative(validOptions) is clear and enforces the intended constraints.


429-433: Good addition: programmatic flags pathway (minimal validation, no process.exit)

Introducing processProvidedFlagsWithoutValidation with throw-on-invalid project name is appropriate for programmatic use and avoids side effects.

Comment on lines +34 to +46
function deriveProjectName(
projectName?: string,
projectDirectory?: string,
): string {
if (projectName) {
return projectName;
}
if (projectDirectory) {
return path.basename(path.resolve(process.cwd(), projectDirectory));
}
return "";
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Normalize provided projectName to a basename to avoid leaking paths downstream

Currently, deriveProjectName returns the raw projectName when provided, which causes config.projectName to potentially contain a path (e.g., "./foo/bar"). Normalize to basename here so callers consistently get a clean name.

Apply this diff:

-function deriveProjectName(
-	projectName?: string,
-	projectDirectory?: string,
-): string {
-	if (projectName) {
-		return projectName;
-	}
-	if (projectDirectory) {
-		return path.basename(path.resolve(process.cwd(), projectDirectory));
-	}
-	return "";
-}
+function deriveProjectName(
+	projectName?: string,
+	projectDirectory?: string,
+): string {
+	if (projectName) {
+		return path.basename(projectName);
+	}
+	if (projectDirectory) {
+		return path.basename(path.resolve(process.cwd(), projectDirectory));
+	}
+	return "";
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function deriveProjectName(
projectName?: string,
projectDirectory?: string,
): string {
if (projectName) {
return projectName;
}
if (projectDirectory) {
return path.basename(path.resolve(process.cwd(), projectDirectory));
}
return "";
}
function deriveProjectName(
projectName?: string,
projectDirectory?: string,
): string {
if (projectName) {
return path.basename(projectName);
}
if (projectDirectory) {
return path.basename(path.resolve(process.cwd(), projectDirectory));
}
return "";
}
🤖 Prompt for AI Agents
In apps/cli/src/validation.ts around lines 34 to 46, deriveProjectName currently
returns the raw projectName which can be a path; change it to normalize the
provided projectName to a basename so callers never receive a path. When
projectName is present, resolve it against process.cwd() and return
path.basename(...) of that resolved path (same approach used for
projectDirectory), otherwise keep the existing fallback logic.

Comment on lines +126 to 133
const derivedName = deriveProjectName(projectName, options.projectDirectory);
if (derivedName) {
const nameToValidate = projectName
? path.basename(projectName)
: derivedName;
validateProjectName(nameToValidate);
config.projectName = projectName || derivedName;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Assign a sanitized projectName instead of the raw input

You validate a basename but then assign the unsanitized value. This can leak a path into config.projectName. Assign the sanitized/derived name.

Apply one of the following diffs:

Option A (if you accept the deriveProjectName normalization suggested earlier):

-	const derivedName = deriveProjectName(projectName, options.projectDirectory);
-	if (derivedName) {
-		const nameToValidate = projectName
-			? path.basename(projectName)
-			: derivedName;
-		validateProjectName(nameToValidate);
-		config.projectName = projectName || derivedName;
-	}
+	const derivedName = deriveProjectName(projectName, options.projectDirectory);
+	if (derivedName) {
+		validateProjectName(derivedName);
+		config.projectName = derivedName;
+	}

Option B (minimal change without touching deriveProjectName):

-		config.projectName = projectName || derivedName;
+		config.projectName = path.basename(projectName ?? derivedName);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const derivedName = deriveProjectName(projectName, options.projectDirectory);
if (derivedName) {
const nameToValidate = projectName
? path.basename(projectName)
: derivedName;
validateProjectName(nameToValidate);
config.projectName = projectName || derivedName;
}
const derivedName = deriveProjectName(projectName, options.projectDirectory);
if (derivedName) {
validateProjectName(derivedName);
config.projectName = derivedName;
}
🤖 Prompt for AI Agents
In apps/cli/src/validation.ts around lines 126 to 133, you validate a sanitized
basename but then assign the original raw projectName (which may contain a path)
to config.projectName; change the assignment to use the sanitized name variable
used for validation (nameToValidate) so config.projectName gets the
basename/derivedName rather than the unsanitized input, leaving the rest of the
logic intact.

Comment on lines +479 to +491
const derivedName = deriveProjectName(projectName, options.projectDirectory);
if (derivedName) {
const nameToValidate = projectName
? path.basename(projectName)
: derivedName;
const result = ProjectNameSchema.safeParse(nameToValidate);
if (!result.success) {
throw new Error(
`Invalid project name: ${result.error.issues[0]?.message}`,
);
}
config.projectName = projectName || derivedName;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Sanitize assigned projectName in programmatic path as well

Same as the CLI path: assign a basename to config.projectName to avoid leaking paths.

Apply this diff (pairs with the deriveProjectName normalization suggested earlier):

-	const derivedName = deriveProjectName(projectName, options.projectDirectory);
-	if (derivedName) {
-		const nameToValidate = projectName
-			? path.basename(projectName)
-			: derivedName;
-		const result = ProjectNameSchema.safeParse(nameToValidate);
-		if (!result.success) {
-			throw new Error(
-				`Invalid project name: ${result.error.issues[0]?.message}`,
-			);
-		}
-		config.projectName = projectName || derivedName;
-	}
+	const derivedName = deriveProjectName(projectName, options.projectDirectory);
+	if (derivedName) {
+		const result = ProjectNameSchema.safeParse(derivedName);
+		if (!result.success) {
+			throw new Error(
+				`Invalid project name: ${result.error.issues[0]?.message}`,
+			);
+		}
+		config.projectName = derivedName;
+	}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/cli/src/validation.ts around lines 479 to 491, when assigning
config.projectName the code currently uses the raw projectName or derivedName
and can leak path segments; change the assignment to always use path.basename on
the chosen value so config.projectName = projectName ?
path.basename(projectName) : path.basename(derivedName) (i.e., sanitize both
branches by applying path.basename) to mirror the CLI path handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant