Skip to content

feat(cli): improve error handling with better-result - #834

Merged
AmanVarshney01 merged 6 commits into
mainfrom
better-result
Jan 18, 2026
Merged

AmanVarshney01 merged 6 commits into
mainfrom
better-result

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Jan 18, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Documentation

    • Added migration guides and detailed docs for typed errors, agent usage, and adoption of the new result-based patterns.
  • Refactor

    • CLI and generator now return structured results and surface cancellations as typed errors for more predictable, programmatic flows and clearer error messages.
    • Validation and project-creation flows improved to provide consistent outcomes and diagnostics.
  • Chores

    • Added a runtime dependency to support the new Result-based error handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel

vercel Bot commented Jan 18, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
create-better-t-stack-web Ready Ready Preview, Comment Jan 18, 2026 2:58pm

Request Review

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. cli Changes to the CLI tool enhancement New feature or request labels Jan 18, 2026
@AmanVarshney01
AmanVarshney01 enabled auto-merge (squash) January 18, 2026 13:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR migrates the CLI's error handling from traditional try/catch patterns to type-safe Result types using the better-result library. The migration introduces TaggedError classes for domain-specific errors (UserCancelledError, CLIError, ValidationError, etc.) and updates public APIs to return Result<T, E> instead of throwing exceptions or returning success/error objects.

Changes:

  • Introduced better-result dependency (v2.3.0) for type-safe error handling
  • Refactored error handling to use TaggedError classes and Result types throughout the codebase
  • Updated public APIs (create, createVirtual, generate) to return Result types instead of status objects

Reviewed changes

Copilot reviewed 55 out of 58 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
packages/template-generator/src/types.ts Replaced GeneratorResult interface with GeneratorError TaggedError class
packages/template-generator/src/generator.ts Refactored generate() to return Result<VirtualFileTree, GeneratorError>
packages/template-generator/src/fs-writer.ts Updated writeTree() and writeSelected() to return Result types
apps/cli/src/utils/errors.ts Defined TaggedError classes and error handling utilities
apps/cli/src/validation.ts Converted validation functions to return Result types
apps/cli/src/utils/project-name-validation.ts Updated validation to return Result instead of throwing
apps/cli/src/utils/config-validation.ts Refactored validation using Result.gen for composition
apps/cli/src/utils/compatibility-rules.ts Updated compatibility checks to return Result types
apps/cli/src/prompts/*.ts Changed prompts to throw UserCancelledError instead of calling exitCancelled
apps/cli/src/helpers/core/create-project.ts Refactored createProject using Result.gen for sequential operations
apps/cli/src/helpers/core/command-handlers.ts Updated handler to return Result and handle errors appropriately
apps/cli/src/index.ts Updated create() and createVirtual() APIs to return Result types
apps/cli/test/test-utils.ts Updated tests to handle Result types from create()
apps/web/src/app/api/preview/route.ts Updated to use Result-based generate() API

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/cli/src/prompts/navigable-group.ts Resolved
Comment thread apps/cli/src/index.ts Resolved
Comment thread apps/cli/src/utils/errors.ts Resolved
Comment thread apps/cli/src/validation.ts Resolved
@coderabbitai

coderabbitai Bot commented Jan 18, 2026 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adopts a Result/TaggedError model (better-result) across CLI and template-generator: replaces cancellation return paths with UserCancelledError, converts many functions to return Result-wrapped types, updates public exports to include Result and new error classes, bumps dependencies, adds docs, and adds opensrc/ to .gitignore.

Changes

Cohort / File(s) Summary
Ignore / Docs & Guides
\.gitignore, AGENTS.md, .opencode/command/adopt-better-result.md, .opencode/skill/better-result-adopt/SKILL.md, .opencode/skill/better-result-adopt/references/tagged-errors.md
Adds opensrc/ to .gitignore and adds documentation/skill guides for adopting better-result.
Workspace Dependencies
package.json, apps/cli/package.json, packages/template-generator/package.json
Adds better-result@^2.3.0 and bumps several CLI deps.
Core Error Framework
apps/cli/src/utils/errors.ts
Introduces TaggedError classes (UserCancelledError, CLIError, ValidationError, CompatibilityError, DirectoryConflictError, ProjectCreationError, DatabaseSetupError, AddonSetupError), AppError union, and Result-returning helper constructors and display/exit helpers.
Prompt handlers
apps/cli/src/prompts/*.ts, apps/cli/src/prompts/navigable-group.ts
Replaces exitCancelled(...) return paths with throw new UserCancelledError(...) across prompt modules; broadens NavigablePromptGroup return type to include symbol; minor signature/type refinements (e.g., explicit Promise<string>).
Addons setup helpers
apps/cli/src/helpers/addons/*-setup.ts, apps/cli/src/helpers/addons/addons-setup.ts
Converts addon setup flows to return Result-wrapped outcomes, introduces AddonSetupError/userCancelled, centralizes runSetup to handle cancellations vs. non-fatal addon failures.
Database providers
apps/cli/src/helpers/database-providers/*-setup.ts, apps/cli/src/helpers/core/db-setup.ts
Migrates provider flows (neon, prisma, supabase, turso, docker-compose, mongodb-atlas, prisma-postgres, etc.) to Result-based return types, standardizes DatabaseSetupError/UserCancelledError handling, and uses centralized runSetup patterns.
Create / Command handlers
apps/cli/src/helpers/core/command-handlers.ts, apps/cli/src/helpers/core/create-project.ts
Major refactor to Result/gen orchestration: new internal flows, CreateProjectResult export, createProject returns Result<string, ProjectCreationError>, handlers return structured success/failure or undefined per CLI mode.
Project primitives
apps/cli/src/helpers/core/git.ts, apps/cli/src/helpers/core/install-dependencies.ts, apps/cli/src/utils/bts-config.ts, apps/cli/src/utils/file-formatter.ts, apps/cli/src/utils/project-directory.ts
Wraps git, dependency install, BTS config, formatting, and directory setup in Result.tryPromise, updates signatures to return `Result<..., ProjectCreationError
Validation & config
apps/cli/src/utils/config-validation.ts, apps/cli/src/utils/compatibility-rules.ts, apps/cli/src/utils/project-name-validation.ts, apps/cli/src/validation.ts, apps/cli/src/utils/config-processing.ts
Introduces ValidationResult/ValidationError, converts validators to return Result-typed results, replaces throw/exit paths with Result.err, and uses Result.gen sequencing.
Template generator & FS writer
packages/template-generator/src/generator.ts, packages/template-generator/src/types.ts, packages/template-generator/src/fs-writer.ts, packages/template-generator/src/index.ts, packages/template-generator/src/processors/env-vars.ts, templates/...
Replaces generateVirtualProject with generate returning Result<VirtualFileTree, GeneratorError>; removes GeneratorResult, adds GeneratorError/FileWriteError TaggedErrors; writeTree/writeSelected return Result; tweaks env var logic (Astro port adjustment) and template path logic.
Public API & integration
apps/cli/src/index.ts, apps/cli/src/virtual.ts, apps/web/src/app/api/preview/route.ts, apps/cli/test/test-utils.ts
Public API functions now return Result-wrapped types (e.g., create → Promise<Result<InitResult, CreateError>>), re-exports Result and error classes; integration points updated to handle Result shape.
Misc utilities
apps/cli/src/utils/analytics.ts, apps/cli/src/utils/command-exists.ts, apps/cli/src/utils/docker-utils.ts, apps/cli/src/utils/open-url.ts, apps/web/src/app/api/preview/route.ts
Converts utilities to explicit Promise returns and/or wraps operations in Result.tryPromise, returning safe booleans or void and mapping failures to safe results or logs.

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.99% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adopting better-result library for improved error handling throughout the CLI codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/cli/src/helpers/addons/ultracite-setup.ts (1)

221-226: UserCancelledError is swallowed by the catch block.

The catch block catches all errors including UserCancelledError, logs them, and returns without re-throwing. This means user cancellation won't propagate to the caller, potentially causing the CLI to continue rather than exit gracefully.

🔧 Proposed fix to re-throw UserCancelledError
   } catch (error) {
+    if (error instanceof UserCancelledError) {
+      throw error;
+    }
     log.error(pc.red("Failed to set up Ultracite"));
     if (error instanceof Error) {
       console.error(pc.red(error.message));
     }
   }
apps/cli/src/helpers/database-providers/mongodb-atlas-setup.ts (1)

170-183: UserCancelledError is swallowed by the catch block.

Similar to ultracite-setup.ts, this catch block will swallow UserCancelledError thrown at line 151, preventing proper cancellation propagation. The user's cancellation intent will be lost, and the CLI may continue with fallback behavior instead of exiting.

🔧 Proposed fix to re-throw UserCancelledError
   } catch (error) {
+    if (error instanceof UserCancelledError) {
+      throw error;
+    }
     consola.error(
       pc.red(
         `Error during MongoDB Atlas setup: ${
           error instanceof Error ? error.message : String(error)
         }`,
       ),
     );

     try {
       await writeEnvFile(projectDir, backend);
       displayManualSetupInstructions();
     } catch {}
   }
apps/cli/src/helpers/addons/ruler-setup.ts (1)

70-112: Don’t swallow UserCancelledError in the local catch.

The new cancellation throw is now caught and logged as a failure, which masks user cancellation and blocks upstream/global cancellation handling. Re-throw cancellation errors before logging.

🐛 Proposed fix
 } catch (error) {
+  if (error instanceof UserCancelledError) {
+    throw error;
+  }
   log.error(pc.red("Failed to set up Ruler"));
   if (error instanceof Error) {
     console.error(pc.red(error.message));
   }
 }
apps/cli/src/helpers/addons/fumadocs-setup.ts (1)

94-99: UserCancelledError is swallowed by the catch block.

The UserCancelledError thrown at line 64 will be caught here, logged as a failure message ("Failed to set up Fumadocs"), and then suppressed. This prevents cancellation from propagating up the call stack, which likely breaks the expected CLI flow where user cancellation should abort the entire operation.

Suggested fix: rethrow UserCancelledError
   } catch (error) {
+    if (error instanceof UserCancelledError) {
+      throw error;
+    }
     log.error(pc.red("Failed to set up Fumadocs"));
     if (error instanceof Error) {
       consola.error(pc.red(error.message));
     }
   }
apps/cli/src/helpers/database-providers/supabase-setup.ts (1)

207-214: Re-throw UserCancelledError to avoid treating cancellation as an error.

When the user cancels, UserCancelledError is caught here and logged as a red error message with manual setup instructions displayed. User cancellation should propagate to the caller for proper handling rather than being treated as a setup failure.

Proposed fix
   } catch (error) {
+    if (error instanceof UserCancelledError) {
+      throw error;
+    }
     if (error instanceof Error) {
       consola.error(pc.red(`Error during Supabase setup: ${error.message}`));
     } else {
       consola.error(pc.red(`An unknown error occurred during Supabase setup: ${String(error)}`));
     }
     displayManualSupabaseInstructions();
   }
apps/cli/src/helpers/database-providers/turso-setup.ts (1)

303-311: Re-throw UserCancelledError to avoid treating cancellation as a setup error.

Same issue as in supabase-setup.ts: when the user cancels at any prompt, UserCancelledError is caught here and logged as a red error, followed by manual setup instructions. User cancellation should propagate to the caller.

Proposed fix
   } catch (error) {
+    if (error instanceof UserCancelledError) {
+      throw error;
+    }
     if (setupSpinner) setupSpinner.stop(pc.red("Turso CLI availability check failed"));
     consola.error(
       pc.red(`Error during Turso setup: ${error instanceof Error ? error.message : String(error)}`),
     );
     await writeEnvFile(projectDir, backend);
     displayManualSetupInstructions();
     log.success("Setup completed with manual configuration required.");
   }
🧹 Nitpick comments (31)
.opencode/command/adopt-better-result.md (1)

9-11: Add a language specifier to the fenced code block.

The code block lacks a language specifier. Consider adding one for better syntax highlighting and markdown linting compliance.

Suggested fix
-```
+```js
 skill({ name: 'better-result-adopt' })
</details>

</blockquote></details>
<details>
<summary>apps/cli/src/prompts/web-deploy.ts (2)</summary><blockquote>

`62-62`: **LGTM! Consider using the default message.**

The migration to `UserCancelledError` aligns with the PR's Result-based error handling approach.

Note: `UserCancelledError` already defaults to "Operation cancelled", so you could simplify to `throw new UserCancelledError()`.



<details>
<summary>Optional simplification</summary>

```diff
-  if (isCancel(response)) throw new UserCancelledError({ message: "Operation cancelled" });
+  if (isCancel(response)) throw new UserCancelledError();

105-105: Same optional simplification applies here.

Optional simplification
-  if (isCancel(response)) throw new UserCancelledError({ message: "Operation cancelled" });
+  if (isCancel(response)) throw new UserCancelledError();
.opencode/skill/better-result-adopt/SKILL.md (1)

159-162: Tighten wording in the references note.
Consider replacing “deeper context” with “additional context” (or similar) for crisper phrasing.

apps/cli/src/utils/bts-config.ts (2)

13-16: Drop the explicit return type (and async) on writeBtsConfig.
Inference from Result.tryPromise is sufficient and keeps the signature concise. As per coding guidelines, avoid explicit return types.

♻️ Proposed change
-export async function writeBtsConfig(
-  projectConfig: ProjectConfig,
-): Promise<Result<void, ProjectCreationError>> {
-  return Result.tryPromise({
+export function writeBtsConfig(projectConfig: ProjectConfig) {
+  return Result.tryPromise({

67-72: Prefer Bun file APIs for the write.
Consider switching the write to Bun.write/Bun.file to align with the Bun-first IO guideline. As per coding guidelines, prefer Bun.file over node:fs read/write.

♻️ Proposed change
-      await fs.writeFile(configPath, finalContent, "utf-8");
+      await Bun.write(configPath, finalContent);
apps/cli/src/utils/project-name-validation.ts (1)

9-44: Remove explicit return types on the exported validators.
Type inference should keep the signatures clean and still preserve the Result types. As per coding guidelines, avoid explicit return types.

♻️ Proposed change
-export function validateProjectName(name: string): ValidationResult<void> {
+export function validateProjectName(name: string) {
@@
-export function extractAndValidateProjectName(
+export function extractAndValidateProjectName(
   projectName?: string,
   projectDirectory?: string,
   _throwOnError = false,
-): ValidationResult<string> {
+) {
apps/cli/src/utils/project-directory.ts (1)

10-13: Omit explicit return types on directory helpers.
Inference is sufficient and keeps signatures aligned with the style guide. As per coding guidelines, avoid explicit return types.

♻️ Proposed change
-export async function handleDirectoryConflict(currentPathInput: string): Promise<{
-  finalPathInput: string;
-  shouldClearDirectory: boolean;
-}> {
+export async function handleDirectoryConflict(currentPathInput: string) {
@@
-export async function setupProjectDirectory(
+export async function setupProjectDirectory(
   finalPathInput: string,
   shouldClearDirectory: boolean,
-): Promise<{ finalResolvedPath: string; finalBaseName: string }> {
+) {

Also applies to: 82-85

apps/cli/src/validation.ts (1)

78-86: Consider refactoring validateArrayOptions to return a Result for consistency.

The try-catch wrapper around validateArrayOptions works correctly but is inconsistent with the Result-based approach used elsewhere. If validateArrayOptions were updated to return a ValidationResult, this wrapper could be eliminated.

This is acceptable for now as a transitional pattern, but consider aligning it in a follow-up.

apps/cli/src/prompts/config-prompts.ts (1)

114-116: Use method syntax instead of an arrow function for onCancel.

This aligns with the project’s function-declaration guideline.

♻️ Proposed refactor
-    onCancel: () => {
+    onCancel() {
       throw new UserCancelledError({ message: "Operation cancelled" });
-    },
+    },
As per coding guidelines, ...
apps/cli/src/prompts/orm.ts (1)

51-51: Consider omitting the redundant message parameter.

The UserCancelledError constructor already defaults to "Operation cancelled" (see apps/cli/src/utils/errors.ts lines 14-16), so you can simplify this to throw new UserCancelledError().

Suggested simplification
-  if (isCancel(response)) throw new UserCancelledError({ message: "Operation cancelled" });
+  if (isCancel(response)) throw new UserCancelledError();
apps/cli/src/prompts/package-manager.ts (1)

30-30: Same simplification opportunity as other prompts.

The explicit message is redundant since the constructor defaults to "Operation cancelled".

Suggested simplification
-  if (isCancel(response)) throw new UserCancelledError({ message: "Operation cancelled" });
+  if (isCancel(response)) throw new UserCancelledError();
apps/cli/src/prompts/backend.ts (1)

82-82: LGTM with optional simplification.

The migration to UserCancelledError is correct. As noted in other files, the explicit message can be omitted since it matches the default.

apps/cli/src/prompts/auth.ts (1)

69-69: Both cancellation paths correctly migrated.

The exception-based cancellation handling is properly applied to both the Convex and non-Convex branches. The explicit message parameters can be omitted for brevity.

Also applies to: 86-86

apps/cli/src/prompts/project-name.ts (1)

27-27: Remove the explicit return type.

As per the coding guidelines for TypeScript files, explicit return types should not be used. TypeScript can infer the return type.

Proposed fix
-export async function getProjectName(initialName?: string): Promise<string> {
+export async function getProjectName(initialName?: string) {
apps/cli/src/utils/file-formatter.ts (1)

29-31: Remove the explicit return type on formatProject.

Let TypeScript infer the return type here.

♻️ Proposed change
 export async function formatProject(
   projectDir: string,
-): Promise<Result<void, ProjectCreationError>> {
+) {

As per coding guidelines, please omit explicit return type annotations.

packages/template-generator/src/generator.ts (1)

48-50: Remove explicit return type on generate.

Let TypeScript infer the return type.

♻️ Proposed change
 export async function generate(
   options: GeneratorOptions,
-): Promise<Result<VirtualFileTree, GeneratorError>> {
+) {

As per coding guidelines, please omit explicit return type annotations.

apps/cli/src/helpers/core/install-dependencies.ts (2)

10-17: Drop the explicit return type on installDependencies.

Rely on inference; the Result type is already implied by the implementation. As per coding guidelines, please avoid explicit return types in .ts files.

Proposed change
-export async function installDependencies({
+export async function installDependencies({
   projectDir,
   packageManager,
 }: {
   projectDir: string;
   packageManager: PackageManager;
   addons?: Addons[];
-}): Promise<Result<void, ProjectCreationError>> {
+}) {

22-28: Use Bun.$ for dependency installs instead of execa.

This repo standardizes on Bun’s subprocess API; please map cwd/stdio behavior to Bun.$ equivalents. As per coding guidelines, prefer Bun.$ over execa.

Proposed change (adapt options to Bun.$ as needed)
-import { $ } from "execa";
+import { $ } from "bun";
...
-      await $({
-        cwd: projectDir,
-        stderr: "inherit",
-      })`${packageManager} install`;
+      await $`${packageManager} install`.cwd(projectDir);
apps/cli/src/helpers/core/git.ts (2)

8-11: Remove the explicit return type on initializeGit.

Let TypeScript infer the return type. As per coding guidelines, avoid explicit return types in .ts files.

Proposed change
 export async function initializeGit(
   projectDir: string,
   useGit: boolean,
-): Promise<Result<void, ProjectCreationError>> {
+) {

14-44: Use Bun.$ for git commands instead of execa.

Align with the Bun-first CLI standard and ensure exit-code handling matches Bun.$ semantics. As per coding guidelines, prefer Bun.$ over execa.

apps/cli/src/helpers/core/create-project.ts (3)

21-33: Use a type alias and rely on inferred return types.

Convert CreateProjectOptions to a type alias and drop explicit return types on createProject/setPackageManagerVersion. As per coding guidelines, prefer type aliases and omit explicit return types.

Proposed change
-export interface CreateProjectOptions {
-  manualDb?: boolean;
-}
+export type CreateProjectOptions = {
+  manualDb?: boolean;
+};

 export async function createProject(
   options: ProjectConfig,
   cliInput: CreateProjectOptions = {},
-): Promise<Result<string, ProjectCreationError>> {
+) {

Also applies to: 147-150


5-6: Switch package-manager version lookup to Bun.$.

The repo standard is Bun.$ for subprocesses; please update the execa usage and adapt stdout handling to Bun.$’s API. As per coding guidelines, prefer Bun.$ over execa.

Also applies to: 160-165


143-144: Confirm Result.gen isn’t double-wrapping the return.

If Result.gen expects a raw value, returning Result.ok(projectDir) may create a nested Result. Please verify against better-result docs and adjust if needed.

Possible fix (if `Result.gen` expects a raw value)
-    return Result.ok(projectDir);
+    return projectDir;
apps/cli/src/helpers/core/command-handlers.ts (2)

36-52: Use type aliases instead of interfaces for public types.

Convert CreateHandlerOptions, CreateProjectResult, and DirectoryConflictResult to type aliases. As per coding guidelines, prefer type aliases.

Proposed change
-export interface CreateHandlerOptions {
-  silent?: boolean;
-}
+export type CreateHandlerOptions = {
+  silent?: boolean;
+};

-export interface CreateProjectResult {
+export type CreateProjectResult = {
   success: boolean;
   projectConfig: ProjectConfig;
   reproducibleCommand: string;
   timeScaffolded: string;
   elapsedTimeMs: number;
   projectDirectory: string;
   relativePath: string;
   error?: string;
-}
+};

-interface DirectoryConflictResult {
+type DirectoryConflictResult = {
   finalPathInput: string;
   shouldClearDirectory: boolean;
-}
+};

Also applies to: 350-353


57-61: Remove explicit return types from helper functions.

Let TS infer return types for createEmptyResult, createProjectHandler, createProjectHandlerInternal, and the directory-conflict helpers. As per coding guidelines, avoid explicit return types.

Example change (apply similarly to the other functions)
-function createEmptyResult(
+function createEmptyResult(
   timeScaffolded: string,
   elapsedTimeMs: number,
   error?: string,
-): CreateProjectResult {
+) {

-export async function createProjectHandler(
+export async function createProjectHandler(
   input: CreateInput & { projectName?: string },
   options: CreateHandlerOptions = {},
-): Promise<CreateProjectResult | undefined> {
+) {

Also applies to: 101-105, 142-146, 355-360, 379-383

packages/template-generator/src/fs-writer.ts (2)

44-60: Prefer Bun file APIs over node:fs writes/copies.

Replace fs.writeFile/fs.copyFile with Bun’s file APIs (e.g., Bun.write, Bun.file) while keeping directory creation as-is. As per coding guidelines, prefer Bun file APIs for read/write paths.

Possible adjustments (verify Bun API details)
-      await fs.writeFile(fullPath, fileNode.content, "utf-8");
+      await Bun.write(fullPath, fileNode.content);
...
-      await fs.writeFile(join(baseDir, nodePath), fileNode.content, "utf-8");
+      await Bun.write(join(baseDir, nodePath), fileNode.content);
...
-  await fs.copyFile(sourcePath, destPath);
+  await Bun.write(destPath, Bun.file(sourcePath));

Also applies to: 103-112, 122-126


24-28: Remove explicit return types on internal helpers.

Let TS infer return types for writeTree, writeNodeInternal, writeSelected, writeSelectedNodeInternal, and copyBinaryFile. As per coding guidelines, avoid explicit return types.

Example change (apply similarly to other functions)
 export async function writeTree(
   tree: VirtualFileTree,
   destDir: string,
-): Promise<Result<void, FileWriteError>> {
+) {

-async function writeNodeInternal(
+async function writeNodeInternal(
   node: VirtualNode,
   baseDir: string,
   relativePath: string,
-): Promise<void> {
+) {

Also applies to: 44-48, 73-77, 94-100, 122-122

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

198-201: Rely on inferred return types for create and createVirtual.

Drop the explicit return annotations to align with the TypeScript style rules. As per coding guidelines, avoid explicit return types in .ts files.

Proposed change
 export async function create(
   projectName?: string,
   options?: Partial<CreateInput>,
-): Promise<Result<InitResult, CreateError>> {
+) {

 export async function createVirtual(
   options: Partial<Omit<ProjectConfig, "projectDir" | "relativePath">>,
-): Promise<Result<VirtualFileTree, GeneratorError>> {
+) {

Also applies to: 294-296

apps/cli/src/utils/errors.ts (2)

24-27: Consider adding a constructor for consistent initialization.

Unlike other error classes, CLIError uses the implicit TaggedError constructor. For consistency with ValidationError, CompatibilityError, etc., consider adding an explicit constructor.

♻️ Optional consistency improvement
 export class CLIError extends TaggedError("CLIError")<{
   message: string;
   cause?: unknown;
-}>() {}
+}>() {
+  constructor(args: { message: string; cause?: unknown }) {
+    super(args);
+  }
+}

186-192: Consider displaying structured error details for richer debugging.

Currently displayError only shows error.message. For errors like ValidationError (which has field, value) or DatabaseSetupError (which has provider, cause), the additional context is lost. Consider logging structured details in verbose/debug mode or when cause is present.

♻️ Example enhancement for richer error display
 export function displayError(error: AppError): void {
   if (UserCancelledError.is(error)) {
     cancel(pc.red(error.message));
   } else {
     consola.error(pc.red(error.message));
+    if ("cause" in error && error.cause) {
+      consola.debug("Caused by:", error.cause);
+    }
   }
 }

Comment thread apps/cli/src/utils/config-validation.ts Resolved
Comment thread apps/cli/src/utils/config-validation.ts Resolved
Comment thread apps/cli/src/utils/config-validation.ts Resolved
Comment thread apps/cli/src/utils/file-formatter.ts Resolved

@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

♻️ Duplicate comments (4)
apps/cli/src/utils/file-formatter.ts (1)

51-51: Allow empty formatted output to be written.

The truthy check formatted && skips valid empty-string output from formatCode(). Since the function returns string | null, empty strings represent valid formatting results and should be persisted.

Suggested fix
-                  if (formatted && formatted !== content) {
+                  if (formatted !== null && formatted !== content) {
apps/cli/src/index.ts (1)

217-229: Verify createProjectHandler’s return shape before casting.

This block assumes a { success, error } shape; if createProjectHandler now returns a Result, the result.success check and cast to InitResult will mis-handle errors. Consider returning a Result directly or mapping explicitly once you confirm the handler signature.

#!/bin/bash
# Inspect createProjectHandler signature and return shape
fd 'command-handlers' -t f apps/cli/src/helpers/core
rg -nP --type=ts -C3 'createProjectHandler' apps/cli/src/helpers/core
apps/cli/src/utils/config-validation.ts (2)

468-471: Avoid mutating config.addons inside validation.

Validation should be side‑effect free; dedupe locally or upstream instead of mutating config.

♻️ Possible adjustment
-    if (config.addons && config.addons.length > 0) {
-      yield* validateAddonsAgainstFrontends(config.addons, config.frontend, config.auth);
-      config.addons = [...new Set(config.addons)];
-    }
+    if (config.addons && config.addons.length > 0) {
+      const dedupedAddons = [...new Set(config.addons)];
+      yield* validateAddonsAgainstFrontends(dedupedAddons, config.frontend, config.auth);
+      // If callers need deduped addons, do it before validation and pass it in.
+    }

434-488: Result.gen should return a plain value, not Result.ok(...).

Returning Result.ok(undefined) from the generator risks producing Ok(Ok(...)) instead of Ok(undefined). Prefer return undefined (or just return) in the generator body.

🐛 Proposed fix
-    return Result.ok(undefined);
+    return undefined;
@@
-    return Result.ok(undefined);
+    return undefined;
better-result v2.3.0 Result.gen return value — should a generator return a plain value or Result.ok?

Also applies to: 492-522

🧹 Nitpick comments (31)
apps/cli/src/utils/analytics.ts (2)

10-10: Remove explicit return type to comply with coding guidelines.

As per coding guidelines for TypeScript files, explicit return types should not be used. The return type can be inferred.

Suggested fix
-async function sendConvexEvent(payload: Record<string, unknown>): Promise<void> {
+async function sendConvexEvent(payload: Record<string, unknown>) {

26-29: Remove explicit return type to comply with coding guidelines.

As per coding guidelines for TypeScript files, explicit return types should not be used.

Suggested fix
 export async function trackProjectCreation(
   config: ProjectConfig,
   disableAnalytics = false,
-): Promise<void> {
+) {
apps/cli/src/utils/open-url.ts (2)

3-3: Consider using Bun.$ instead of execa.

As per coding guidelines, prefer Bun.$ template literal syntax for shell command execution instead of the execa package.


5-5: Remove explicit return type.

As per coding guidelines, do not use explicit return types. The return type can be inferred.

Suggested fix
-export async function openUrl(url: string): Promise<void> {
+export async function openUrl(url: string) {
apps/cli/src/utils/docker-utils.ts (2)

14-14: Remove explicit return type.

As per coding guidelines, do not use explicit return types.

Suggested fix
-export async function isDockerRunning(): Promise<boolean> {
+export async function isDockerRunning() {

15-23: Consider simplifying the Result logic.

The current implementation is correct but unnecessarily verbose. The catch handler's return value becomes the error, not a fallback value. A cleaner approach:

Simplified alternative
-  const result = await Result.tryPromise({
-    try: async () => {
-      await $`docker info`;
-      return true;
-    },
-    catch: () => false,
-  });
-
-  return result.isOk() ? result.value : false;
+  const result = await Result.tryPromise({
+    try: async () => {
+      await $`docker info`;
+    },
+    catch: () => new Error("Docker not running"),
+  });
+
+  return result.isOk();
apps/cli/src/utils/command-exists.ts (1)

4-4: Remove explicit return type.

As per coding guidelines, do not use explicit return types.

Suggested fix
-export async function commandExists(command: string): Promise<boolean> {
+export async function commandExists(command: string) {
apps/cli/src/helpers/database-providers/docker-compose-setup.ts (2)

9-11: Remove explicit return type.

As per coding guidelines, do not use explicit return types. The return type can be inferred from the function body.

Suggested fix
-export async function setupDockerCompose(
-  config: ProjectConfig,
-): Promise<Result<void, DatabaseSetupError>> {
+export async function setupDockerCompose(config: ProjectConfig) {

30-30: Simplify the return statement.

The try block implicitly returns undefined, so on success result is already Ok(undefined). The ternary is redundant.

Suggested fix
-  return result.isErr() ? result : Result.ok(undefined);
+  return result;
apps/cli/src/utils/file-formatter.ts (1)

32-34: Remove explicit return type.

As per coding guidelines, do not use explicit return types.

Suggested fix
-export async function formatProject(
-  projectDir: string,
-): Promise<Result<void, ProjectCreationError>> {
+export async function formatProject(projectDir: string) {
apps/cli/src/utils/project-directory.ts (2)

11-14: Remove explicit return type.

As per coding guidelines, do not use explicit return types.

Suggested fix
-export async function handleDirectoryConflict(currentPathInput: string): Promise<{
-  finalPathInput: string;
-  shouldClearDirectory: boolean;
-}> {
+export async function handleDirectoryConflict(currentPathInput: string) {

83-86: Remove explicit return type.

As per coding guidelines, do not use explicit return types.

Suggested fix
-export async function setupProjectDirectory(
-  finalPathInput: string,
-  shouldClearDirectory: boolean,
-): Promise<{ finalResolvedPath: string; finalBaseName: string }> {
+export async function setupProjectDirectory(
+  finalPathInput: string,
+  shouldClearDirectory: boolean,
+) {
apps/cli/src/helpers/core/create-project.ts (3)

29-32: Remove the explicit return type on createProject.
Let TypeScript infer this return type to match the repo convention.

💡 Suggested change
 export async function createProject(
   options: ProjectConfig,
   cliInput: CreateProjectOptions = {},
-): Promise<Result<string, ProjectCreationError>> {
+) {

As per coding guidelines, please adjust.


147-150: Remove the explicit return type on setPackageManagerVersion.
Let inference handle it to align with TS conventions.

💡 Suggested change
 async function setPackageManagerVersion(
   projectDir: string,
   packageManager: ProjectConfig["packageManager"],
-): Promise<Result<void, ProjectCreationError>> {
+) {

As per coding guidelines, please adjust.


158-161: Use Bun.$ instead of execa for shelling out.
The ${packageManager} -v call should use Bun.$ per repo conventions and to avoid execa usage in this module. As per coding guidelines, please adjust.

apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (2)

40-43: Drop explicit return types on setup functions.
Please rely on inference for setupWithCreateDb, writeEnvFile, and setupPrismaPostgres to match TS conventions. As per coding guidelines, please adjust.

Also applies to: 106-110, 155-158


64-67: Prefer Bun.$ over execa for CLI calls.
The create-db invocation should use Bun.$ per repo conventions. As per coding guidelines, please adjust.

apps/cli/src/helpers/database-providers/turso-setup.ts (2)

21-22: Remove explicit return types on TS function signatures.
These signatures should rely on inference to align with repo conventions. As per coding guidelines, please adjust.

Also applies to: 25-26, 36-37, 56-57, 95-96, 126-127, 155-158, 220-224, 264-267


28-29: Use Bun.$ instead of execa for shell execution.
Replace the execa-based $ calls (e.g., turso auth whoami) with Bun.$ per repo conventions. As per coding guidelines, please adjust.

apps/cli/src/utils/errors.ts (1)

132-134: Drop explicit return types on helper/display functions.
Please let inference handle these return types to follow repo TS conventions. As per coding guidelines, please adjust.

Also applies to: 139-145, 150-155, 160-162, 167-169, 174-179, 185-191, 196-202, 211-223

apps/cli/src/helpers/database-providers/mongodb-atlas-setup.ts (2)

25-33: Remove explicit return types on TS functions.
Let inference handle these return types per repo convention. As per coding guidelines, please adjust.

Also applies to: 35-38, 89-93, 134-137


51-54: Switch shell calls to Bun.$ instead of execa.
The Atlas CLI invocation should use Bun.$ per repo conventions. As per coding guidelines, please adjust.

apps/cli/src/helpers/core/db-setup.ts (1)

45-47: Remove the explicit return type on runSetup.
Let TS infer this to match repo conventions.

💡 Suggested change
   async function runSetup<T>(
     setupFn: () => Promise<Result<T, UserCancelledError | { message: string }>>,
-  ): Promise<void> {
+  ) {

As per coding guidelines, please adjust.

apps/cli/src/utils/bts-config.ts (1)

117-143: Silent failure may hide config update issues.

The catch: () => undefined silently swallows all errors without logging. While this preserves prior behavior, consider adding a warning log to aid debugging when config updates fail unexpectedly.

💡 Optional: Add warning log for debugging
     catch: (e) => {
+      console.warn(`Warning: Failed to update bts.jsonc: ${e instanceof Error ? e.message : String(e)}`);
       return undefined;
-    }, // Silent failure
+    },
   });
apps/cli/src/helpers/core/detect-project-config.ts (1)

7-38: Redundant Result wrapping around readBtsConfig.

readBtsConfig already returns BetterTStackConfig | null and handles all errors internally (never throws). Wrapping it in Result.tryPromise is unnecessary since it won't throw. The code works but adds complexity without benefit.

♻️ Simplify by removing redundant Result wrapper
 export async function detectProjectConfig(projectDir: string) {
-  const result = await Result.tryPromise({
-    try: async () => {
-      const btsConfig = await readBtsConfig(projectDir);
-      if (btsConfig) {
-        return {
-          projectDir,
-          projectName: path.basename(projectDir),
-          database: btsConfig.database,
-          orm: btsConfig.orm,
-          backend: btsConfig.backend,
-          runtime: btsConfig.runtime,
-          frontend: btsConfig.frontend,
-          addons: btsConfig.addons,
-          examples: btsConfig.examples,
-          auth: btsConfig.auth,
-          payments: btsConfig.payments,
-          packageManager: btsConfig.packageManager,
-          dbSetup: btsConfig.dbSetup,
-          api: btsConfig.api,
-          webDeploy: btsConfig.webDeploy,
-          serverDeploy: btsConfig.serverDeploy,
-        };
-      }
-
-      return null;
-    },
-    catch: () => null,
-  });
-
-  return result.isOk() ? result.value : null;
+  const btsConfig = await readBtsConfig(projectDir);
+  if (btsConfig) {
+    return {
+      projectDir,
+      projectName: path.basename(projectDir),
+      database: btsConfig.database,
+      orm: btsConfig.orm,
+      backend: btsConfig.backend,
+      runtime: btsConfig.runtime,
+      frontend: btsConfig.frontend,
+      addons: btsConfig.addons,
+      examples: btsConfig.examples,
+      auth: btsConfig.auth,
+      payments: btsConfig.payments,
+      packageManager: btsConfig.packageManager,
+      dbSetup: btsConfig.dbSetup,
+      api: btsConfig.api,
+      webDeploy: btsConfig.webDeploy,
+      serverDeploy: btsConfig.serverDeploy,
+    };
+  }
+  return null;
 }
apps/cli/src/helpers/addons/tauri-setup.ts (1)

28-33: Redundant ternary branch.

Both hasNext and the default case return the same URL (http://localhost:3001), making the hasNext check unnecessary in this ternary.

Simplified version
   const devUrl =
     hasReactRouter || hasSvelte
       ? "http://localhost:5173"
-      : hasNext
-        ? "http://localhost:3001"
-        : "http://localhost:3001";
+      : "http://localhost:3001";
apps/cli/src/helpers/addons/wxt-setup.ts (2)

40-41: Remove explicit return type from setupWxt.

Type inference already yields the correct Promise<Result<...>> here.

♻️ Proposed change
-export async function setupWxt(config: ProjectConfig): Promise<WxtSetupResult> {
+export async function setupWxt(config: ProjectConfig) {

As per coding guidelines, avoid explicit return types in TS.


81-84: Prefer Bun.$ for shell execution instead of execa.

This repo standardizes shell execution on Bun; consider swapping the call to use Bun.$ and remove the execa dependency.

♻️ Proposed change
-import { $ } from "execa";
+// Bun provides the $ helper globally; no import needed.

@@
-      await $({ cwd: appsDir, env: { CI: "true" } })`${args}`;
+      await Bun.$({ cwd: appsDir, env: { CI: "true" } })`${args}`;

As per coding guidelines, prefer Bun.$ for shell commands.

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

204-207: Drop explicit return types on programmatic APIs.

Let TS infer the return type for create and createVirtual.

♻️ Proposed change
-export async function create(
+export async function create(
   projectName?: string,
   options?: Partial<CreateInput>,
-): Promise<Result<InitResult, CreateError>> {
+) {
@@
-export async function createVirtual(
+export async function createVirtual(
   options: Partial<Omit<ProjectConfig, "projectDir" | "relativePath">>,
-): Promise<Result<VirtualFileTree, GeneratorError>> {
+) {

As per coding guidelines, avoid explicit return types in TS.

Also applies to: 300-303

apps/cli/src/validation.ts (1)

28-32: Remove explicit return types on validation helpers.

Let TS infer return types for these functions to align with repo style.

♻️ Example change
-function validateYesFlagCombination(
+function validateYesFlagCombination(
   options: CLIInput,
   providedFlags: Set<string>,
-): ValidationResult<void> {
+) {

As per coding guidelines, avoid explicit return types in TS.

Also applies to: 55-59, 103-107, 131-135

apps/cli/src/utils/config-validation.ts (1)

25-28: Omit explicit return types on validation functions.

Let TypeScript infer return types for these helpers.

♻️ Example change
-export function validateDatabaseOrmAuth(
+export function validateDatabaseOrmAuth(
   cfg: Partial<ProjectConfig>,
   flags?: Set<string>,
-): ValidationResult {
+) {

As per coding guidelines, avoid explicit return types in TS.

Also applies to: 74-77, 171-174

@AmanVarshney01
AmanVarshney01 merged commit 032cfd9 into main Jan 18, 2026
3 checks passed
@AmanVarshney01
AmanVarshney01 deleted the better-result branch January 18, 2026 15:12

This branch was successfully deployed

1 active deployment
Preview — 9aca2c9d Deployed Jan 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli Changes to the CLI tool enhancement New feature or request size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants