Repository navigation
feat(cli): add programmatic api - #494
Conversation
🦋 Changeset detectedLatest commit: d1d0703 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
|
Caution Review failedThe pull request is closed. WalkthroughAdds 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
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
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()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (3)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
commit: |
There was a problem hiding this comment.
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|errorto 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 foundapps/web/content/docs/cli/index.mdx (1)
159-177: Improve example code for better type safety and error handlingThe 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 supportThe
InitResultinterface 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 logicThe nested while loop for unwrapping
FailedToExitErrorcould 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 modeThe 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 usingconsola.fatalfor non-fatal warningUsing
consola.fatalfor 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 logicThe nested conditions for determining
currentPathInputare 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
📒 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
yoloflag 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
createBtsClifunction 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.
| import { createBtsCli } from "./index"; | ||
|
|
||
| void createBtsCli().run(); |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| process.env.BTS_TELEMETRY_DISABLED = "1"; | ||
| consola.info("Programmatic CLI mode"); |
There was a problem hiding this comment.
🛠️ 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.
| 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.
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (1)
apps/cli/src/validation.ts (1)
167-179: Unreachable branch in examples processingInside 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 processArrayOptionTighten 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 helpersvalidateProjectName 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 APIHere, 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
⛔ Files ignored due to path filters (1)
bun.lockis 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 goodUsing 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.
| function deriveProjectName( | ||
| projectName?: string, | ||
| projectDirectory?: string, | ||
| ): string { | ||
| if (projectName) { | ||
| return projectName; | ||
| } | ||
| if (projectDirectory) { | ||
| return path.basename(path.resolve(process.cwd(), projectDirectory)); | ||
| } | ||
| return ""; | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ 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.
| 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.
| const derivedName = deriveProjectName(projectName, options.projectDirectory); | ||
| if (derivedName) { | ||
| const nameToValidate = projectName | ||
| ? path.basename(projectName) | ||
| : derivedName; | ||
| validateProjectName(nameToValidate); | ||
| config.projectName = projectName || derivedName; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| 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; | ||
| } |
There was a problem hiding this comment.
🛠️ 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.
Summary by CodeRabbit