Repository navigation
feat(cli): add add-app command for additional frontend apps - #1185
JimiPatel2023 wants to merge 2 commits into
Conversation
|
@JimiPatel2023 is attempting to deploy a commit to the Better T Stack Team on Vercel. A member of the Team first needs to authorize it. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughChangesThis PR adds support for additional frontend apps during project creation and after creation. It adds shared validation, stack-builder state, app scaffolding, CLI, programmatic, MCP, configuration, tests, and documentation. Additional frontend app workflow
Possibly related PRs
Merge Risk: 🟡 Moderate · up to The new multi-frontend scaffolding can leave projects with conflicting app records, recorded ports that do not match generated apps, or apparent success after incomplete configuration or installation; generated shell commands may also behave unsafely for unexpected values. These are bounded but concrete merge-readiness issues that should be fixed or explicitly accepted before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
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: 8
🧹 Nitpick comments (2)
plugin/skills/add-to-project/SKILL.md (1)
31-31: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winName the supported app frameworks.
Replace “React-family frameworks” with the natural-language names and
WebFrontendSchemavalues. Identify the React-family subset separately: TanStack Router (tanstack-router), React Router (react-router), TanStack Start (tanstack-start), and Next.js (next). Also document Nuxt (nuxt), Svelte (svelte), Solid (solid), and Astro (astro) as the other supported web frameworks.Source: Learnings
apps/cli/src/utils/bts-config.ts (1)
30-61: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftConsider returning a
Resultinstead of a boolean.The change correctly stops hiding write failures. The boolean still discards the reason, so
add-app-handler.tsLine 448 can only print a generic warning and cannot distinguish a missing file from a permission error or a JSONC parse failure.The CLI coding guideline states: "In CLI code, prefer
better-resultover ad-hoctry/catchfor recoverable flows; return typedResult<T, E>and useResult.ok,Result.err,Result.try, andResult.tryPromise."This is not a regression from this PR, because the previous version already used
try/catch. Treat it as a follow-up if you prefer to keep the caller changes small.♻️ Sketch of a Result-based signature
-): Promise<boolean> { - try { - const configPath = path.join(projectDir, BTS_CONFIG_FILE); - - if (!(await fs.pathExists(configPath))) { - return false; - } +): Promise<Result<void, CLIError>> { + const configPath = path.join(projectDir, BTS_CONFIG_FILE); + + if (!(await fs.pathExists(configPath))) { + return Result.err(new CLIError({ message: `${BTS_CONFIG_FILE} not found in ${projectDir}` })); + } + + return Result.tryPromise({ + try: async () => { + let content = await fs.readFile(configPath, "utf-8"); + for (const [key, value] of Object.entries(updates)) { + const edits = modify(content, [key], value, { formattingOptions: { tabSize: 2 } }); + content = applyEdits(content, edits); + } + await fs.writeFile(configPath, content, "utf-8"); + }, + catch: (e) => + new CLIError({ + message: `Failed to update ${BTS_CONFIG_FILE}: ${e instanceof Error ? e.message : String(e)}`, + cause: e, + }), + }); +}Update
add-handler.tsLine 455 andadd-app-handler.tsLine 444 accordingly.Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4215d43f-6ae4-49b9-a866-e969c10a1f5d
📒 Files selected for processing (29)
apps/cli/src/helpers/core/add-app-handler.tsapps/cli/src/helpers/core/add-handler.tsapps/cli/src/helpers/core/detect-project-config.tsapps/cli/src/index.tsapps/cli/src/mcp.tsapps/cli/src/prompts/add-app.tsapps/cli/src/utils/bts-config.tsapps/cli/src/utils/compatibility-rules.tsapps/cli/test/add-app.test.tsapps/cli/test/input-schemas.test.tsapps/cli/test/mcp.test.tsapps/cli/test/programmatic-api.test.tsapps/cli/test/schema-command.test.tsapps/web/content/docs/bts-config.mdxapps/web/content/docs/cli/agent-workflows.mdxapps/web/content/docs/cli/index.mdxapps/web/content/docs/cli/options.mdxapps/web/content/docs/cli/programmatic-api.mdxapps/web/content/docs/project-structure.mdxpackages/template-generator/src/core/virtual-fs.tspackages/template-generator/src/index.tspackages/template-generator/src/post-process/index.tspackages/template-generator/src/post-process/package-configs.tspackages/types/src/json-schema.tspackages/types/src/schemas.tspackages/types/src/types.tsplugin/agents/stack-architect.mdplugin/commands/add.mdplugin/skills/add-to-project/SKILL.md
Included review availability: Your plan provides up to 8 included reviews per hour; 7 remain after this review.
| // Examples that remain compatible with the new app's framework | ||
| const keptExamples = (existingConfig.examples ?? []).filter((example) => { | ||
| if (example === "todo") { | ||
| return isExampleTodoAllowed( | ||
| existingConfig.backend, | ||
| existingConfig.database, | ||
| existingConfig.api, | ||
| ); | ||
| } | ||
| if (example === "ai") { | ||
| return isExampleAIAllowed(existingConfig.backend, [frontend]); | ||
| } | ||
| return false; | ||
| }); | ||
| const droppedExamples = (existingConfig.examples ?? []).filter( | ||
| (example) => example !== "none" && !keptExamples.includes(example), | ||
| ); | ||
| if (!isSilent() && droppedExamples.length > 0) { | ||
| log.info( | ||
| pc.dim( | ||
| `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`, | ||
| ), | ||
| ); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Correct the dropped-example message attribution.
The message states the examples are "not supported by ${frontend}". The todo example is filtered by isExampleTodoAllowed(backend, database, api), which does not consider the frontend. If todo is dropped because of the backend or database, the message names the wrong cause.
Report the framework only for the examples that the frontend actually gates.
💡 Proposed message fix
if (!isSilent() && droppedExamples.length > 0) {
log.info(
pc.dim(
- `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`,
+ `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by this stack: ${droppedExamples.join(", ")}`,
),
);
}📝 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.
| // Examples that remain compatible with the new app's framework | |
| const keptExamples = (existingConfig.examples ?? []).filter((example) => { | |
| if (example === "todo") { | |
| return isExampleTodoAllowed( | |
| existingConfig.backend, | |
| existingConfig.database, | |
| existingConfig.api, | |
| ); | |
| } | |
| if (example === "ai") { | |
| return isExampleAIAllowed(existingConfig.backend, [frontend]); | |
| } | |
| return false; | |
| }); | |
| const droppedExamples = (existingConfig.examples ?? []).filter( | |
| (example) => example !== "none" && !keptExamples.includes(example), | |
| ); | |
| if (!isSilent() && droppedExamples.length > 0) { | |
| log.info( | |
| pc.dim( | |
| `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by ${frontend}: ${droppedExamples.join(", ")}`, | |
| ), | |
| ); | |
| } | |
| // Examples that remain compatible with the new app's framework | |
| const keptExamples = (existingConfig.examples ?? []).filter((example) => { | |
| if (example === "todo") { | |
| return isExampleTodoAllowed( | |
| existingConfig.backend, | |
| existingConfig.database, | |
| existingConfig.api, | |
| ); | |
| } | |
| if (example === "ai") { | |
| return isExampleAIAllowed(existingConfig.backend, [frontend]); | |
| } | |
| return false; | |
| }); | |
| const droppedExamples = (existingConfig.examples ?? []).filter( | |
| (example) => example !== "none" && !keptExamples.includes(example), | |
| ); | |
| if (!isSilent() && droppedExamples.length > 0) { | |
| log.info( | |
| pc.dim( | |
| `Skipping example${droppedExamples.length > 1 ? "s" : ""} not supported by this stack: ${droppedExamples.join(", ")}`, | |
| ), | |
| ); | |
| } |
| const configUpdated = await updateBtsConfig(projectDir, { | ||
| apps: [...existingApps, { name: appName, frontend, port }], | ||
| }); | ||
| if (!configUpdated && !isSilent()) { | ||
| log.warn( | ||
| pc.yellow( | ||
| "Could not update bts.jsonc. Add the new app to its 'apps' array manually so future commands see it.", | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| if (input.install) { | ||
| await installDependencies({ projectDir, packageManager }); | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Report the bts.jsonc write failure in silent mode, and wrap installDependencies.
Two problems in this block:
-
configUpdated === falseis surfaced only when!isSilent(). In silent mode, which is the MCP and programmatic path, the function still returnssuccess: trueat Line 473 whilebts.jsoncdoes not contain the new app. The nextadd-appcall then reuses the same port, andadd-handler.tsLine 344 does not preload the new app manifest. Propagate the failure in the result so an agent can react. -
installDependenciesis awaited withoutResult.tryPromise. If it rejects, the error escapesaddAppHandlerInternalandaddAppHandleras an unhandled rejection. The app files are already written at this point, so a dependency-install failure must not crash the command.
Based on the coding guideline "In CLI code, prefer better-result over ad-hoc try/catch for recoverable flows; return typed Result<T, E>".
🛠️ Proposed fix
const configUpdated = await updateBtsConfig(projectDir, {
apps: [...existingApps, { name: appName, frontend, port }],
});
- if (!configUpdated && !isSilent()) {
- log.warn(
- pc.yellow(
- "Could not update bts.jsonc. Add the new app to its 'apps' array manually so future commands see it.",
- ),
- );
- }
+ const configWarning = configUpdated
+ ? undefined
+ : `Could not update bts.jsonc. Add {"name":"${appName}","frontend":"${frontend}","port":${port}} to its 'apps' array manually so future commands see it.`;
+ if (configWarning && !isSilent()) {
+ log.warn(pc.yellow(configWarning));
+ }
if (input.install) {
- await installDependencies({ projectDir, packageManager });
+ const installResult = await Result.tryPromise({
+ try: () => installDependencies({ projectDir, packageManager }),
+ catch: (e) =>
+ new CLIError({
+ message: `Failed to install dependencies: ${e instanceof Error ? e.message : String(e)}`,
+ cause: e,
+ }),
+ });
+ if (installResult.isErr() && !isSilent()) {
+ log.warn(pc.yellow(installResult.error.message));
+ }
}Then include configWarning in the returned AddAppResult (add an optional warning?: string field to the interface at Line 41) so silent callers see it.
Source: Coding guidelines
| function getPortConfigPath(appDir: string, frontend: AddedApp["frontend"]): string | undefined { | ||
| switch (frontend) { | ||
| case "tanstack-router": | ||
| case "tanstack-start": | ||
| case "solid": | ||
| return `${appDir}/vite.config.ts`; | ||
| case "nuxt": | ||
| return `${appDir}/nuxt.config.ts`; | ||
| default: | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| function pinDevPortInConfigFiles( | ||
| vfs: VirtualFileSystem, | ||
| appDir: string, | ||
| frontend: AddedApp["frontend"], | ||
| port: number, | ||
| ): void { | ||
| const configPath = getPortConfigPath(appDir, frontend); | ||
| if (!configPath) return; | ||
|
|
||
| const content = vfs.readFile(configPath); | ||
| if (!content) return; | ||
|
|
||
| vfs.writeFile(configPath, content.replaceAll("port: 3001", `port: ${port}`)); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
The new app's port is applied by unverified string substitution. Both sites pin the dev port by matching a template-specific literal. Neither site confirms that the substitution occurred, and there is no exhaustive mapping from every AddedApp["frontend"] value to a pinning strategy. When a match fails, the app keeps the template default, collides with an existing app, and the command still reports and persists the requested port.
apps/cli/src/helpers/core/add-app-handler.ts#L571-L597: make thegetPortConfigPathswitch exhaustive over the frontend union so a new frontend is a compile error, and warn whenreplaceAll("port: 3001", ...)changes nothing.apps/cli/src/helpers/core/add-app-handler.ts#L557-L565: append--port ${port}when thenextdev script contains no--portflag, instead of relying on areplacethat can be a no-op.
📍 Affects 1 file
apps/cli/src/helpers/core/add-app-handler.ts#L571-L597(this comment)apps/cli/src/helpers/core/add-app-handler.ts#L557-L565
| const options = WEB_FRONTEND_OPTIONS.filter((option) => | ||
| validateAddAppFrontendCompatibility(option.value, config).isOk(), | ||
| ); | ||
|
|
||
| const response = await navigableSelect<AddAppFrontend>({ | ||
| message: "Choose a framework for the new app", | ||
| options, | ||
| }); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Return the compatibility error before opening an empty selector.
When config.backend === "self", validateAddAppFrontendCompatibility() rejects every frontend. Lines 90-92 then produce an empty options array. Line 94 opens navigableSelect() with no valid selection.
Return a CLIError before the prompt, or validate this project state in the handler before calling getAppFrontend(). This gives the user the required reason instead of an empty selection flow.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cdb5941e-a11d-4054-a554-159b9342ecba
📒 Files selected for processing (14)
apps/web/content/docs/cli/index.mdxapps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsxapps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsxapps/web/src/app/(home)/new/_components/stack-builder/index.tsxapps/web/src/app/(home)/new/_components/stack-builder/tech-categories.tsxapps/web/src/app/(home)/new/_components/utils.tsapps/web/src/app/(home)/stack/_components/stack-display.tsxapps/web/src/lib/constant.tsapps/web/src/lib/extra-apps.tsapps/web/src/lib/sanitize-stack-addons.tsapps/web/src/lib/stack-url-keys.tsapps/web/src/lib/stack-url-state.client.tsapps/web/src/lib/stack-url-state.tsapps/web/test/extra-apps.test.ts
Included review availability: Your plan provides up to 8 included reviews per hour; 6 remain after this review.
| export function generateAddAppCommands(stack: StackState): string[] { | ||
| const apps = stack.apps.map(parseExtraApp).filter((app): app is ExtraApp => app !== null); | ||
| if (apps.length === 0) return []; | ||
|
|
||
| const runners = { | ||
| npm: "npx", | ||
| pnpm: "pnpm dlx", | ||
| default: "bunx", | ||
| }; | ||
| const runner = runners[stack.packageManager as keyof typeof runners] || runners.default; | ||
|
|
||
| return apps.map( | ||
| (app) => | ||
| `${runner} create-better-t-stack@latest add-app ${app.name} --frontend ${app.frontend}`, | ||
| ); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
Validate every dynamic shell token before rendering copied commands.
These commands do not execute in the browser. They can execute unintended shell syntax after a user copies and runs them. generateAddAppCommands only parses apps, and AddAppCommandsBox uses projectName without validation or shell-safe encoding.
apps/web/src/lib/extra-apps.ts#L142-L156: sanitizestack.appswithsanitizeExtraApps(stack.apps, stack)before generating commands.apps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsx#L34-L35: use the same validated project-name token as the create command, or safely quote the directory argument.apps/web/test/extra-apps.test.ts#L134-L153: add cases for malformed app values and project names containing shell metacharacters.
📍 Affects 3 files
apps/web/src/lib/extra-apps.ts#L142-L156(this comment)apps/web/src/app/(home)/new/_components/stack-builder/add-app-commands-box.tsx#L34-L35apps/web/test/extra-apps.test.ts#L134-L153
6531d33 to
46a42d8
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
apps/cli/src/helpers/core/command-handlers.ts (1)
426-431: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShare the
--appssuffix construction withcreate-project.ts.This block builds the
--apps name:frontend ...suffix for the returnedreproducibleCommandand for history.apps/cli/src/helpers/core/create-project.tsLines 148-155 builds the same suffix again for the value persisted inbts.jsonc. The two strings must stay identical. Extract one helper and call it from both sites.apps/cli/test/add-app.test.ts (1)
86-94: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the directory before you create it.
writeSyntheticProjectcallsrm(..., { recursive: true, force: true })first, but this test does not. IfSMOKE_DIRsurvives between runs and a previous run left abts.jsoncinadd-app-missing-config, the assertion fails. Add the same reset for determinism.Based on the coding guideline "Keep CLI tests deterministic and reuse shared setup utilities from
apps/cli/test/setup.ts".🛠️ Proposed change
const projectDir = join(SMOKE_DIR, "add-app-missing-config"); + await rm(projectDir, { recursive: true, force: true }); await mkdir(projectDir, { recursive: true });Source: Coding guidelines
apps/web/test/extra-apps.test.ts (1)
128-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTighten the "keeps compatible apps" assertion.
result.adjustedStack?.apps ?? ["admin:next"]passes whenadjustedStackisundefinedand also whenadjustedStack.appsisundefined. The test therefore cannot detect a regression that drops theappskey from the adjusted stack. Assert the intended contract directly.🛠️ Proposed change
test("keeps compatible apps untouched", () => { const result = analyzeStackCompatibility(createStack({ apps: ["admin:next"] })); - expect(result.adjustedStack?.apps ?? ["admin:next"]).toEqual(["admin:next"]); + expect(result.changes.some((change) => change.category === "apps")).toBe(false); + if (result.adjustedStack) { + expect(result.adjustedStack.apps).toEqual(["admin:next"]); + } });packages/types/src/schemas.ts (1)
478-537: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffUse camelCase for the new schema values.
WebFrontendSchema,AppNameSchema,AddedAppSchema,AddedAppSpecSchema,AddAppInputSchema,RESERVED_APP_NAMES, andWEB_FRONTEND_VALUESare runtime values. Rename these exports to camelCase and update their imports.As per coding guidelines,
**/*.{ts,tsx}requires camelCase for functions and variables. PascalCase is for types and components.Also applies to: 589-600, 689-689
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d6e35ebc-0b0e-4235-8940-620233e7617d
📒 Files selected for processing (20)
apps/cli/src/helpers/core/add-app-handler.tsapps/cli/src/helpers/core/command-handlers.tsapps/cli/src/helpers/core/create-project.tsapps/cli/src/index.tsapps/cli/src/mcp.tsapps/cli/src/utils/bts-config.tsapps/cli/test/add-app.test.tsapps/cli/test/input-schemas.test.tsapps/cli/test/schema-command.test.tsapps/web/content/docs/cli/index.mdxapps/web/content/docs/cli/options.mdxapps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsxapps/web/src/app/(home)/new/_components/stack-builder/index.tsxapps/web/src/app/(home)/new/_components/stack-builder/selected-stack-badges.tsxapps/web/src/app/(home)/stack/_components/stack-display.tsxapps/web/src/lib/extra-apps.tsapps/web/src/lib/stack-utils.tsapps/web/test/extra-apps.test.tspackages/types/src/json-schema.tspackages/types/src/schemas.ts
Included review availability: Your plan provides up to 8 included reviews per hour; 5 remain after this review.
| function pinDevPortInConfigFiles( | ||
| vfs: VirtualFileSystem, | ||
| appDir: string, | ||
| frontend: AddedApp["frontend"], | ||
| port: number, | ||
| ): void { | ||
| const configPath = getPortConfigPath(appDir, frontend); | ||
| if (!configPath) return; | ||
|
|
||
| const content = vfs.readFile(configPath); | ||
| if (!content) return; | ||
|
|
||
| const updated = content.replaceAll("port: 3001", `port: ${port}`); | ||
| if (updated === content) { | ||
| // The template no longer matches the expected literal — don't record a | ||
| // port that was never applied without telling the user. | ||
| if (!isSilent()) { | ||
| log.warn( | ||
| pc.yellow(`Could not pin the dev port in ${configPath}. Set port ${port} manually.`), | ||
| ); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| vfs.writeFile(configPath, updated); | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Propagate the failed port pin to the result in silent mode.
pinDevPortInConfigFiles reports the failure only through log.warn when !isSilent(). The silent path is used by addApp(), the MCP tools, and create --apps. In that path the function returns without a signal, and the handler still records port in bts.jsonc and in AddAppResult. The new app then starts on the template default port and can collide with the primary web app, while the recorded state says otherwise.
The handler already collects a warnings array at Line 458. Return the failure from this helper and add it to that array so silent callers receive it in result.warning.
🛠️ Proposed change
-function pinDevPortInConfigFiles(
+function pinDevPortInConfigFiles(
vfs: VirtualFileSystem,
appDir: string,
frontend: AddedApp["frontend"],
port: number,
-): void {
+): string | undefined {
const configPath = getPortConfigPath(appDir, frontend);
- if (!configPath) return;
+ if (!configPath) return undefined;
const content = vfs.readFile(configPath);
- if (!content) return;
+ if (!content) return undefined;
const updated = content.replaceAll("port: 3001", `port: ${port}`);
if (updated === content) {
- // The template no longer matches the expected literal — don't record a
- // port that was never applied without telling the user.
- if (!isSilent()) {
- log.warn(
- pc.yellow(`Could not pin the dev port in ${configPath}. Set port ${port} manually.`),
- );
- }
- return;
+ return `Could not pin the dev port in ${configPath}. Set port ${port} manually.`;
}
vfs.writeFile(configPath, updated);
+ return undefined;
}Then capture the return value at Line 385 and push it into warnings before the result is built.
| for (const app of extraApps) { | ||
| const appResult = await addAppHandler( | ||
| { projectDir, name: app.name, frontend: app.frontend, install: false }, | ||
| { silent: true }, | ||
| ); | ||
| const appPort = appResult?.success ? appResult.port : undefined; | ||
| if (appPort === undefined) { | ||
| yield* new ProjectCreationError({ | ||
| phase: "extra-apps", | ||
| message: appResult?.error ?? `Failed to add app '${app.name}'.`, | ||
| }); | ||
| } else { | ||
| addedApps.push({ name: app.name, frontend: app.frontend, port: appPort }); | ||
| } | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Surface appResult.warning for each scaffolded app.
addAppHandler returns a warning field for non-fatal problems, for example a failed bts.jsonc update. This loop reads only success and port, so those warnings are discarded. A user who runs create --apps then receives a project whose bts.jsonc does not list an app that exists on disk, with no message.
Collect the warnings and print them with the wiring note when not silent.
🛠️ Proposed change
const addedApps: AddedApp[] = [];
+ const appWarnings: string[] = [];
for (const app of extraApps) {
const appResult = await addAppHandler(
{ projectDir, name: app.name, frontend: app.frontend, install: false },
{ silent: true },
);
const appPort = appResult?.success ? appResult.port : undefined;
if (appPort === undefined) {
yield* new ProjectCreationError({
phase: "extra-apps",
message: appResult?.error ?? `Failed to add app '${app.name}'.`,
});
} else {
+ if (appResult?.warning) appWarnings.push(appResult.warning);
addedApps.push({ name: app.name, frontend: app.frontend, port: appPort });
}
}Then log appWarnings inside the existing if (!isSilent()) block.
| export function getAddAppInputJsonSchema() { | ||
| const schema = z.toJSONSchema(AddAppInputSchema) as { | ||
| properties?: { name?: { not?: { enum: string[] } } }; | ||
| }; | ||
|
|
||
| // The reserved-name rule lives in a zod refinement, which does not | ||
| // serialize; surface it so JSON-Schema consumers see it too. | ||
| if (schema.properties?.name) { | ||
| schema.properties.name.not = { enum: [...RESERVED_APP_NAMES].sort() }; | ||
| } | ||
|
|
||
| return schema; |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- candidate files ---'
git ls-files 'packages/types/src/json-schema.ts' 'packages/types/src/*' | sed -n '1,120p'
printf '%s\n' '--- relevant declarations and uses ---'
rg -n -C 5 'get(AddAppInput|CreateInput)JsonSchema|CreateInputSchema|AddedAppSpecSchema|RESERVED_APP_NAMES|reserved|web:next' packages/types/src packages/types 2>/dev/null | sed -n '1,260p'
printf '%s\n' '--- json-schema.ts outline ---'
ast-grep outline packages/types/src/json-schema.ts 2>/dev/null || true
printf '%s\n' '--- json-schema.ts relevant lines ---'
sed -n '1,180p' packages/types/src/json-schema.tsRepository: AmanVarshney01/create-better-t-stack
Length of output: 22922
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- package and test context ---'
rg -n -C 4 '"zod"|json schema|JSON Schema|getCreateInputJsonSchema|createInput' package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | sed -n '1,260p'
printf '%s\n' '--- complete schema definitions ---'
sed -n '491,565p' packages/types/src/schemas.ts
printf '%s\n' '--- JSON Schema exports and tests ---'
rg -n -C 5 'getAllJsonSchemas|getCreateInputJsonSchema|getAddAppInputJsonSchema|toJSONSchema' --glob '*.{ts,tsx,js,jsx,json}' . | sed -n '1,320p'
printf '%s\n' '--- standalone structural verifier ---'
python3 - <<'PY'
import re
from pathlib import Path
source = Path("packages/types/src/schemas.ts").read_text()
reserved = re.search(r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)', source, re.S)
spec = re.search(r'AddedAppSpecSchema\s*=\s*z\s*\.\s*string\(\)\s*\.regex\(\s*new RegExp\(`([^`]+)`', source, re.S)
create = re.search(r'CreateInputSchema\s*=\s*z\s*\.\s*object\(\s*\{(.*?)\n\s*\}\)', source, re.S)
assert reserved and spec and create, "Could not locate the expected schema declarations"
names = re.findall(r'"([^"]+)"', reserved.group(1))
pattern = spec.group(1)
create_body = create.group(1)
assert "apps: z.array(AddedAppSpecSchema).optional()" in create_body
assert "refine" in source[source.index("AddedAppSpecSchema"):source.index("CreateInputSchema")]
assert "web" in names and "next" in pattern
# The serialized regex validates the reserved spec because the refinement is
# not part of the regex; the Zod refinement rejects it separately.
candidate = "web:next"
regex = re.compile(pattern.replace("${WebFrontendSchema.options.join('|')}", "(?:tanstack-router|next|react|vue|svelte|solid|astro)"))
assert regex.fullmatch(candidate), candidate
assert candidate.split(":")[0] in names
print("CreateInputSchema.apps -> AddedAppSpecSchema")
print("Serialized regex accepts:", candidate)
print("Zod refinement rejects reserved prefix:", candidate.split(":")[0])
print("A JSON-Schema exclusion is required to preserve this refinement.")
PYRepository: AmanVarshney01/create-better-t-stack
Length of output: 13109
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- package and test context ---'
rg -n -C 4 '"zod"|json schema|JSON Schema|getCreateInputJsonSchema|createInput' package.json packages/*/package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null | sed -n '1,260p'
printf '%s\n' '--- complete schema definitions ---'
sed -n '491,565p' packages/types/src/schemas.ts
printf '%s\n' '--- JSON Schema exports and tests ---'
rg -n -C 5 'getAllJsonSchemas|getCreateInputJsonSchema|getAddAppInputJsonSchema|toJSONSchema' --glob '*.{ts,tsx,js,jsx,json}' . | sed -n '1,320p'
printf '%s\n' '--- standalone structural verifier ---'
python3 - <<'PY'
import re
from pathlib import Path
source = Path("packages/types/src/schemas.ts").read_text()
reserved = re.search(r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)', source, re.S)
spec = re.search(r'AddedAppSpecSchema\s*=\s*z\s*\.\s*string\(\)\s*\.regex\(\s*new RegExp\(`([^`]+)`', source, re.S)
create = re.search(r'CreateInputSchema\s*=\s*z\s*\.\s*object\(\s*\{(.*?)\n\s*\}\)', source, re.S)
assert reserved and spec and create, "Could not locate the expected schema declarations"
names = re.findall(r'"([^"]+)"', reserved.group(1))
pattern = spec.group(1)
create_body = create.group(1)
assert "apps: z.array(AddedAppSpecSchema).optional()" in create_body
assert "refine" in source[source.index("AddedAppSpecSchema"):source.index("CreateInputSchema")]
assert "web" in names and "next" in pattern
candidate = "web:next"
regex = re.compile(pattern.replace("${WebFrontendSchema.options.join('|')}", "(?:tanstack-router|next|react|vue|svelte|solid|astro)"))
assert regex.fullmatch(candidate), candidate
assert candidate.split(":")[0] in names
print("CreateInputSchema.apps -> AddedAppSpecSchema")
print("Serialized regex accepts:", candidate)
print("Zod refinement rejects reserved prefix:", candidate.split(":")[0])
print("A JSON-Schema exclusion is required to preserve this refinement.")
PYRepository: AmanVarshney01/create-better-t-stack
Length of output: 13109
🌐 Web query:
Zod 4 z.toJSONSchema refinements unrepresentable refinements omitted JSON Schema
💡 Result:
In Zod 4, the z.toJSONSchema function converts Zod schemas into their closest JSON Schema equivalents [1][2]. Because Zod supports types and runtime logic that have no direct analog in the JSON Schema specification, the conversion process is inherently lossy [3][4]. Handling Unrepresentable Refinements and Types: By default, when z.toJSONSchema encounters an unrepresentable construct—such as custom .refine() logic, .transform() operations, or specialized types like z.bigint(), z.date(), z.map(), z.set(), and z.function()—it will throw an error [3][2][5]. This is intended to prevent the creation of misleading or invalid schemas [2][5]. Options for Unrepresentable Constructs: You can manage this behavior using the unrepresentable option in the z.toJSONSchema configuration [1][2]: 1. "throw" (Default): The process throws an error if any unrepresentable type or refinement is encountered [1][6]. 2. "any": Unrepresentable types are converted to {} (the JSON Schema equivalent of unknown), allowing the generation to proceed without throwing [1][7]. 3. Custom Function: You can provide a function to the unrepresentable option to return a specific JSON Schema representation for identified unrepresentable types [6]. Additionally, an override function can be provided to z.toJSONSchema to manually inject logic for modifying the generated schema for specific Zod types, which is often used to map Zod-specific types to standard JSON Schema formats (e.g., converting a z.date() to {"type": "string", "format": "date-time"}) [8][6]. Because custom refinements (like those created with .refine() or .superRefine()) cannot be converted into standard JSON Schema keywords, they are omitted from the output entirely [3][4]. Consequently, the resulting JSON Schema will represent the base data structure but will not enforce the custom business logic or constraints defined within those refinements [3][4].
Citations:
- 1: https://zod.dev/json-schema
- 2: https://github.com/colinhacks/zod/blob/v4.4.3/packages/docs/content/json-schema.mdx
- 3: https://frameworkkit.dev/guides/zod-4-tojsonschema
- 4: https://mintlify.wiki/colinhacks/zod/guides/json-schema
- 5: https://github.com/colinhacks/zod/blob/c7805073/packages/docs/content/json-schema.mdx
- 6: https://github.com/colinhacks/zod/blob/main/packages/zod/src/v4/core/to-json-schema.ts
- 7: https://github.com/colinhacks/zod/blob/main/packages/docs/content/json-schema.mdx
- 8: Refine toJSONSchema unrepresentables colinhacks/zod#4995
🏁 Script executed:
#!/bin/bash
set -eu
python3 - <<'PY'
import re
from pathlib import Path
source = Path("packages/types/src/schemas.ts").read_text()
reserved_match = re.search(
r'RESERVED_APP_NAMES\s*=\s*new Set\(\s*\[(.*?)\]\s*\)',
source,
re.S,
)
assert reserved_match, "RESERVED_APP_NAMES declaration not found"
reserved = re.findall(r'"([^"]+)"', reserved_match.group(1))
spec_start = source.index("export const AddedAppSpecSchema")
spec_end = source.index("export const CreateInputSchema")
spec_source = source[spec_start:spec_end]
create_start = source.index("export const CreateInputSchema")
create_end = source.index("export const CLIInputSchema")
create_source = source[create_start:create_end]
assert "AddedAppSpecSchema" in spec_source
assert ".refine(" in spec_source
assert "apps: z.array(AddedAppSpecSchema).optional()" in create_source
assert "web" in reserved
# The regex accepts the reserved prefix because the reserved-name check is a
# separate refinement.
assert re.fullmatch(r"[a-z][a-z0-9-]{0,29}:(?:[a-z-]+)", "web:next")
print("CreateInputSchema.apps uses AddedAppSpecSchema")
print("AddedAppSpecSchema has a separate reserved-name refinement")
print("web:next matches the serializable shape and is rejected only by the refinement")
PYRepository: AmanVarshney01/create-better-t-stack
Length of output: 359
🌐 Web query:
site:zod.dev/json-schema refinements unrepresentable z.toJSONSchema default
💡 Result:
When using z.toJSONSchema in Zod, the unrepresentable option determines how the library handles Zod schemas that lack a direct equivalent in JSON Schema, such as dates or BigInts [1]. By default, Zod throws an error when it encounters an unrepresentable schema [1]. You can modify this behavior using the unrepresentable option: 1. Setting unrepresentable to "any": This converts any unrepresentable types into an empty JSON Schema object {}, which is equivalent to unknown [1]. 2. Providing a custom handler function: You can pass a function to handle specific cases [1]. This function receives the Zod schema, its path, and an error message [1]. It should return a valid JSON Schema object, the string "any", or "throw" (the default behavior) [1]. Regarding default values, if a schema uses.default with a value that cannot be serialized into JSON, it is also treated as unrepresentable and processed through the same unrepresentable handler mechanism [1]. If the handler returns a schema, that schema is used; otherwise, the default behavior of throwing an error applies [1].
Citations:
🏁 Script executed:
#!/bin/bash
set -eu
curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/docs/content/json-schema.mdx \
| rg -n -C 5 'unrepresentable|refine|refinement|override' \
| sed -n '1,220p'
curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/zod/src/v4/core/to-json-schema.ts \
| rg -n -C 8 'refinement|unrepresentable|onattach|ZodTransform' \
| sed -n '1,260p'Repository: AmanVarshney01/create-better-t-stack
Length of output: 7301
🏁 Script executed:
#!/bin/bash
set -eu
curl -fsSL https://raw.githubusercontent.com/colinhacks/zod/v4.4.3/packages/zod/src/v4/core/to-json-schema.ts \
| sed -n '300,430p;620,760p' \
| sed -n '1,280p'Repository: AmanVarshney01/create-better-t-stack
Length of output: 4160
Preserve reserved-name validation in getCreateInputJsonSchema().
CreateInputSchema.apps uses AddedAppSpecSchema, whose refinement rejects reserved prefixes such as web in web:next. Add a constraint under apps.items that rejects reserved-name specifications, and test that both Zod and the generated JSON Schema reject web:next.
| auth: AuthSchema.optional(), | ||
| payments: PaymentsSchema.optional(), | ||
| frontend: z.array(FrontendSchema).optional(), | ||
| apps: z.array(AddedAppSpecSchema).optional(), |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Reject duplicate app identities and ports.
The schemas validate each app independently but do not validate the app collection. This permits duplicate names in create input and duplicate names or ports in persisted configuration. These values can produce conflicting apps/<name> targets and dev-server assignments.
packages/types/src/schemas.ts#L553-L553: reject duplicate app names after parsing eachname:frameworkspec.packages/types/src/schemas.ts#L649-L649: reject duplicate app names and duplicate ports in persisted app records.
📍 Affects 1 file
packages/types/src/schemas.ts#L553-L553(this comment)packages/types/src/schemas.ts#L649-L649
46a42d8 to
0d3d88e
Compare
Adds two ways to get additional web frontends (admin panel, landing page, ...) into a project, sharing its API, auth, and workspace packages: - add-app <name> --frontend <framework> scaffolds an app into apps/<name> of an existing project: unique dev port (3002+), per-app env module with rewritten imports, root dev:<name> script using the project's task-runner filter syntax, catalog resolution, pnpm allowBuilds/npm allowScripts unioning, and a bts.jsonc record under a new optional 'apps' array. Framework choice is validated against the stack (trpc/clerk imply react-family, convex excludes solid/astro, backend self is refused). The CLI never edits user server code; it prints the CORS/trustedOrigins steps instead. - create --apps name:framework runs the same flow during project creation, before install and git init, so the initial commit and single install include the apps; the reproducibleCommand records the flag. Also exposed as add-app-json, programmatic addApp(), and MCP bts_plan_app/bts_add_app. Two shared fixes: packages/env exports rebuilding now preserves unmanaged entries, and the add path preloads extra-app manifests. Closes AmanVarshney01#170, closes AmanVarshney01#201.
Adds an Extra Apps section below the web-frontend grid: plan additional frontend apps (name + framework) with the same validation and compatibility gating as the CLI. Planned apps append --apps to the generated create command, render as apps/<name> chips in the Selected stack panel (framework on hover, click jumps to the section), persist in builder URLs and saved stacks, auto-drop with a toast when a stack change makes them incompatible, and show on the shared /stack page. Hidden entirely for fullstack (self) backends.
0d3d88e to
2b4c371
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
apps/cli/src/helpers/core/add-app-handler.ts (2)
427-429: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReport pnpm workspace merge failures, and use the async read.
Two points in
mergePnpmWorkspaceEntries:
- The function returns
void, andcatch: () => nulldiscards every parse or merge error. If the merge fails, the new app'sallowBuildsandminimumReleaseAgeExcludeentries are dropped without any signal. The handler already collectswarnings; return a message and push it there. The coding guideline asks CLI code to return typedResult<T, E>for recoverable flows.- Line 814 calls
fs.readFileSyncinside anasyncfunction. Useawait fs.readFileand pass the content into the synchronous merge step.As per coding guidelines: "In CLI code, prefer
better-resultover ad-hoctry/catchfor recoverable flows; return typedResult<T, E>".♻️ Proposed shape
-): Promise<void> { +): Promise<string | undefined> { const workspaceRelPath = "pnpm-workspace.yaml"; const workspaceDiskPath = path.join(projectDir, workspaceRelPath); const scratchWorkspace = scratchFiles.get(workspaceRelPath); - if (!scratchWorkspace) return; - if (!(await fs.pathExists(workspaceDiskPath))) return; + if (!scratchWorkspace) return undefined; + if (!(await fs.pathExists(workspaceDiskPath))) return undefined; + + const realContent = await fs.readFile(workspaceDiskPath, "utf-8"); const merged = Result.try({ try: () => { const scratchParsed = YAML.parse(scratchWorkspace.content) as PnpmWorkspaceConfig; - const realContent = fs.readFileSync(workspaceDiskPath, "utf-8"); const doc = YAML.parseDocument(realContent); @@ - if (merged.isOk() && merged.value) { - vfs.writeFile(workspaceRelPath, merged.value); - } + if (merged.isErr()) { + return "Could not merge pnpm-workspace.yaml entries for the new app. Check its allowBuilds and minimumReleaseAgeExclude entries manually."; + } + if (merged.value) { + vfs.writeFile(workspaceRelPath, merged.value); + } + return undefined; }Also applies to: 800-850
Source: Coding guidelines
853-862: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueFormat files concurrently to shorten the add-app run.
formatVfsFilesawaitsformatCodeonce per file in a sequential loop. A scaffolded app contains many files, so the total latency is the sum of every format call. Collect the results withPromise.allover the file list, then write the changed contents back.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1f1ebea0-23d4-436f-9e39-7f9fcf433c18
📒 Files selected for processing (5)
apps/cli/src/helpers/core/add-app-handler.tsapps/cli/src/prompts/add-app.tsapps/web/src/app/(home)/new/_components/stack-builder/extra-apps-section.tsxapps/web/src/lib/extra-apps.tspackages/types/src/json-schema.ts
Included review availability: Your plan provides up to 8 included reviews per hour; 4 remain after this review.
Closes #170, closes #201 — the multi-frontend requests (admin panel + storefront + landing sharing one backend) open since April 2025.
What
Two ways to get additional web frontends into a project, sharing its API, auth, and workspace packages:
Each app lands in
apps/<name>with:packages/env/src/<name>.ts+exports["./<name>"]entry with rewritten imports (frameworks have different client prefixes, so a Next admin next to a TanStack web app needs its own validation module — same pattern as the existingnative.ts); the export is only written when the module is@{project}/api,@{project}/auth,@{project}/uiand a rootdev:<name>script using the project's task-runner filter syntaxbts.jsoncrecord under a new optionalappsarray ({ name, frontend, port }), so re-runs allocate the next port and later commands see the extra apps;create --appsalso records the flag inreproducibleCommandFramework choice may differ from the primary web app and is validated against the stack via the existing helpers: tRPC and Clerk imply React-family, Convex excludes Solid/Astro,
backend: selfis refused (checked before any prompt opens). App names are validated against^[a-z][a-z0-9-]*$and a reserved set (web,server,env,ui, …) — the reserved set is also surfaced in the published JSON Schema.Also exposed as
add-app-json, programmaticaddApp(), and MCPbts_plan_app/bts_add_app(mirroring the addon plan/apply pair;install: trueis rejected like project creation, to avoid MCP client timeouts).Stack Builder
A compact Extra apps section below the web-frontend grid — zero footprint until used (one dashed "Add app" button), then an inline name + framework form with live validation and framework chips disabled-with-reason using the same gating as the CLI. Planned apps:
--appsto the generated create command — the builder output stays a single commandapps/<name>chips in the Selected stack panel (framework name on hover, click jumps to the section, × removes) and as removable chips in the section itself?apps=admin:next), saved stacks, and presets/reset behave correctlyanalyzeStackCompatibilityengine when a stack change makes them incompatible; the whole section hides for fullstackselfbackends/stackpageState is encoded as
"name:frontend"strings in a newStackState.apps: string[], so URL/localStorage/share serialization work unchanged. No ports in the UI — the CLI allocates them.How
No destPrefix threading through the template handlers. The handler builds a synthetic single-frontend config from the project's bts.jsonc (deploy forced to
none, addons filtered to task runners so vite-plus/turbo conditionals render correctly) and runs the existing exportedgenerate()in memory, then cherry-picksapps/web/**intoapps/<name>/**with the identity rewrites above. Files outside the new app dir touched: rootpackage.json(script + npm allowScripts/overrides union),packages/env/package.json(exports + missing framework deps),bts.jsonc, and on pnpmpnpm-workspace.yaml(union of framework-conditionalallowBuildsmap entries andminimumReleaseAgeExclude). Catalog references ("catalog:") in cherry-picked package.jsons are resolved back to concrete versions.create --appsreuses the exact same flow insidecreateProject, after files are written and before install/git — so the single install and the initial commit include the apps.Deliberately conservative about user-owned code: the CLI never edits server source; it prints the exact CORS / better-auth
trustedOriginsorigin additions instead. Two small shared fixes:updateEnvPackageJsonpreserves export entries it doesn't manage (a lateradd <addon>would otherwise delete per-app entries — regression-tested), and the add path preloads extra-app manifests.Out of scope (v1)
Deploy wiring for extra apps (alchemy/vercel/docker assume a single
webidentity — apps scaffold without it and warn), a second native app, addons targeting extra apps, interactive prompting for--appsduringcreate(useadd-appinteractively instead), regenerating the project README, and app removal/renaming.Verification
bun run checkclean;bun run buildcleanapps/cli/test/add-app.test.ts(19 tests: refusals incl. reserved names and per-stack framework gating, dry-run, full write, port allocation,create --appsend-to-end, pnpm allowBuilds/release-age union regression, env-export survival across a lateradd), MCP contract tests for the new tool pair, schema/input/programmatic API updates — full suite run with no regressions vs a pristine-main baselineapps/web/test/extra-apps.test.ts(encoding, validation messages, compat gating, sanitize,--appscommand generation, compat-engine drops); full web suite green including the random-stack invariant tests carrying the new field--apps admin:next landing:astro) → single initial commit includes both apps,bun install+turbo run check-typespass across all 5 workspaces; tanstack+trpc project +add-app admin --frontend next→ same; trpc+astro correctly refused before any writes; dry-run writes nothingNote for maintainer
BetterTStackConfigSchemagained the optionalappsfield, soapps/web/scripts/generate-schema.tsneeds a rerun to republishschema.jsonto R2 (editors fetch it live; no runtime impact since the CLI reads bts.jsonc with a plain jsonc parse).Summary by CodeRabbit