Repository navigation
feat(cli): improve error handling with better-result - #834
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
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.
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughAdopts 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 Changes
Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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:UserCancelledErroris 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:UserCancelledErroris swallowed by the catch block.Similar to
ultracite-setup.ts, this catch block will swallowUserCancelledErrorthrown 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 swallowUserCancelledErrorin 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
UserCancelledErrorthrown 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-throwUserCancelledErrorto avoid treating cancellation as an error.When the user cancels,
UserCancelledErroris 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-throwUserCancelledErrorto avoid treating cancellation as a setup error.Same issue as in
supabase-setup.ts: when the user cancels at any prompt,UserCancelledErroris 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) onwriteBtsConfig.
Inference fromResult.tryPromiseis 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 toBun.write/Bun.fileto 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 refactoringvalidateArrayOptionsto return a Result for consistency.The try-catch wrapper around
validateArrayOptionsworks correctly but is inconsistent with the Result-based approach used elsewhere. IfvalidateArrayOptionswere updated to return aValidationResult, 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 foronCancel.This aligns with the project’s function-declaration guideline.
As per coding guidelines, ...♻️ Proposed refactor
- onCancel: () => { + onCancel() { throw new UserCancelledError({ message: "Operation cancelled" }); - }, + },apps/cli/src/prompts/orm.ts (1)
51-51: Consider omitting the redundant message parameter.The
UserCancelledErrorconstructor already defaults to"Operation cancelled"(seeapps/cli/src/utils/errors.tslines 14-16), so you can simplify this tothrow 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
UserCancelledErroris 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 onformatProject.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 ongenerate.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 oninstallDependencies.Rely on inference; the Result type is already implied by the implementation. As per coding guidelines, please avoid explicit return types in
.tsfiles.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 oninitializeGit.Let TypeScript infer the return type. As per coding guidelines, avoid explicit return types in
.tsfiles.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
CreateProjectOptionsto a type alias and drop explicit return types oncreateProject/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: ConfirmResult.genisn’t double-wrapping the return.If
Result.genexpects a raw value, returningResult.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, andDirectoryConflictResultto 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.copyFilewith 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, andcopyBinaryFile. 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 forcreateandcreateVirtual.Drop the explicit return annotations to align with the TypeScript style rules. As per coding guidelines, avoid explicit return types in
.tsfiles.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,
CLIErroruses the implicit TaggedError constructor. For consistency withValidationError,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
displayErroronly showserror.message. For errors likeValidationError(which hasfield,value) orDatabaseSetupError(which hasprovider,cause), the additional context is lost. Consider logging structured details in verbose/debug mode or whencauseis 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); + } } }
There was a problem hiding this comment.
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 fromformatCode(). Since the function returnsstring | 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: VerifycreateProjectHandler’s return shape before casting.This block assumes a
{ success, error }shape; ifcreateProjectHandlernow returns aResult, theresult.successcheck and cast toInitResultwill mis-handle errors. Consider returning aResultdirectly 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/coreapps/cli/src/utils/config-validation.ts (2)
468-471: Avoid mutatingconfig.addonsinside 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.genshould return a plain value, notResult.ok(...).Returning
Result.ok(undefined)from the generator risks producingOk(Ok(...))instead ofOk(undefined). Preferreturn undefined(or justreturn) 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 usingBun.$instead ofexeca.As per coding guidelines, prefer
Bun.$template literal syntax for shell command execution instead of theexecapackage.
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
catchhandler'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
tryblock implicitly returnsundefined, so on successresultis alreadyOk(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 oncreateProject.
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 onsetPackageManagerVersion.
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: UseBun.$instead ofexecafor shelling out.
The${packageManager} -vcall should useBun.$per repo conventions and to avoidexecausage 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 forsetupWithCreateDb,writeEnvFile, andsetupPrismaPostgresto match TS conventions. As per coding guidelines, please adjust.Also applies to: 106-110, 155-158
64-67: PreferBun.$overexecafor CLI calls.
Thecreate-dbinvocation should useBun.$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: UseBun.$instead ofexecafor shell execution.
Replace theexeca-based$calls (e.g.,turso auth whoami) withBun.$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 toBun.$instead ofexeca.
The Atlas CLI invocation should useBun.$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 onrunSetup.
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: () => undefinedsilently 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.
readBtsConfigalready returnsBetterTStackConfig | nulland handles all errors internally (never throws). Wrapping it inResult.tryPromiseis 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
hasNextand the default case return the same URL (http://localhost:3001), making thehasNextcheck 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 fromsetupWxt.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 theexecadependency.♻️ 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
createandcreateVirtual.♻️ 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
Summary by CodeRabbit
Documentation
Refactor
Chores
✏️ Tip: You can customize this high-level summary in your review settings.