Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/all-doodles-hear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-better-t-stack": minor
---

Add 'add' command for adding addons to existing projects
7 changes: 4 additions & 3 deletions apps/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,16 @@
"globby": "^14.1.0",
"gradient-string": "^3.0.0",
"handlebars": "^4.7.8",
"jsonc-parser": "^3.3.1",
"picocolors": "^1.1.1",
"posthog-node": "^4.18.0",
"trpc-cli": "^0.8.0",
"zod": "^3.25.57"
"zod": "^3.25.67"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^24.0.0",
"tsdown": "^0.12.7",
"@types/node": "^24.0.3",
"tsdown": "^0.12.8",
"typescript": "^5.8.3"
}
}
10 changes: 10 additions & 0 deletions apps/cli/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,13 @@ export const dependencyVersionMap = {
} as const;

export type AvailableDependencies = keyof typeof dependencyVersionMap;

export const ADDON_COMPATIBILITY = {
pwa: ["tanstack-router", "react-router", "solid"],
tauri: ["tanstack-router", "react-router", "nuxt", "svelte", "solid"],
biome: [],
husky: [],
turborepo: [],
starlight: [],
none: [],
} as const;
104 changes: 104 additions & 0 deletions apps/cli/src/helpers/project-generation/add-addons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import path from "node:path";
import { cancel, log } from "@clack/prompts";
import pc from "picocolors";
import type { AddInput, Addons, ProjectConfig } from "../../types";
import { validateAddonCompatibility } from "../../utils/addon-compatibility";
import { updateBtsConfig } from "../../utils/bts-config";
import { setupAddons } from "../setup/addons-setup";
import {
detectProjectConfig,
isBetterTStackProject,
} from "./detect-project-config";
import { installDependencies } from "./install-dependencies";
import { setupAddonsTemplate } from "./template-manager";

function exitWithError(message: string): never {
cancel(pc.red(message));
process.exit(1);
}

export async function addAddonsToProject(
input: AddInput & { addons: Addons[] },
): Promise<void> {
try {
const projectDir = input.projectDir || process.cwd();

const isBetterTStack = await isBetterTStackProject(projectDir);
if (!isBetterTStack) {
exitWithError(
"This doesn't appear to be a Better-T Stack project. Please run this command from the root of a Better-T Stack project.",
);
}

const detectedConfig = await detectProjectConfig(projectDir);
if (!detectedConfig) {
exitWithError(
"Could not detect the project configuration. Please ensure this is a valid Better-T Stack project.",
);
}

const config: ProjectConfig = {
projectName: detectedConfig.projectName || path.basename(projectDir),
projectDir,
relativePath: ".",
database: detectedConfig.database || "none",
orm: detectedConfig.orm || "none",
backend: detectedConfig.backend || "none",
runtime: detectedConfig.runtime || "none",
frontend: detectedConfig.frontend || [],
addons: input.addons,
examples: detectedConfig.examples || [],
auth: detectedConfig.auth || false,
git: false,
packageManager:
input.packageManager || detectedConfig.packageManager || "npm",
install: input.install || false,
dbSetup: detectedConfig.dbSetup || "none",
api: detectedConfig.api || "none",
};

for (const addon of input.addons) {
const { isCompatible, reason } = validateAddonCompatibility(
addon,
config.frontend,
);
if (!isCompatible) {
exitWithError(
reason ||
`${addon} addon is not compatible with current frontend configuration`,
);
}
}

log.info(
pc.green(
`Adding ${input.addons.join(", ")} to ${config.frontend.join("/")}`,
),
);

await setupAddonsTemplate(projectDir, config);
await setupAddons(config, true);

const currentAddons = detectedConfig.addons || [];
const mergedAddons = [...new Set([...currentAddons, ...input.addons])];
await updateBtsConfig(projectDir, { addons: mergedAddons });

if (config.install) {
await installDependencies({
projectDir,
packageManager: config.packageManager,
});
} else {
log.info(
pc.yellow(
`Run ${pc.bold(
`${config.packageManager} install`,
)} to install dependencies`,
),
);
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
exitWithError(`Error adding addons: ${message}`);
}
}
4 changes: 4 additions & 0 deletions apps/cli/src/helpers/project-generation/create-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { cancel, log } from "@clack/prompts";
import fs from "fs-extra";
import pc from "picocolors";
import type { ProjectConfig } from "../../types";
import { writeBtsConfig } from "../../utils/bts-config";
import { setupAddons } from "../setup/addons-setup";
import { setupApi } from "../setup/api-setup";
import { setupAuth } from "../setup/auth-setup";
Expand Down Expand Up @@ -71,6 +72,9 @@ export async function createProject(options: ProjectConfig) {
await setupEnvironmentVariables(options);
await updatePackageConfigurations(projectDir, options);
await createReadme(projectDir, options);

await writeBtsConfig(options);

await initializeGit(projectDir, options.git);

log.success("Project template successfully scaffolded!");
Expand Down
43 changes: 43 additions & 0 deletions apps/cli/src/helpers/project-generation/detect-project-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import path from "node:path";
import fs from "fs-extra";
import type { ProjectConfig } from "../../types";
import { readBtsConfig } from "../../utils/bts-config";

export async function detectProjectConfig(
projectDir: string,
): Promise<Partial<ProjectConfig> | null> {
try {
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,
packageManager: btsConfig.packageManager,
dbSetup: btsConfig.dbSetup,
api: btsConfig.api,
};
}

return null;
} catch (_error) {
return null;
}
}

export async function isBetterTStackProject(
projectDir: string,
): Promise<boolean> {
try {
return await fs.pathExists(path.join(projectDir, "bts.jsonc"));
} catch (_error) {
return false;
}
}
18 changes: 17 additions & 1 deletion apps/cli/src/helpers/setup/addons-setup.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import path from "node:path";
import { log } from "@clack/prompts";
import fs from "fs-extra";
import pc from "picocolors";
import type { Frontend, ProjectConfig } from "../../types";
import { addPackageDependency } from "../../utils/add-package-deps";
import { setupStarlight } from "./starlight-setup";
import { setupTauri } from "./tauri-setup";

export async function setupAddons(config: ProjectConfig) {
export async function setupAddons(config: ProjectConfig, isAddCommand = false) {
const { addons, frontend, projectDir } = config;
const hasReactWebFrontend =
frontend.includes("react-router") ||
Expand All @@ -21,6 +23,20 @@ export async function setupAddons(config: ProjectConfig) {
devDependencies: ["turbo"],
projectDir,
});

if (isAddCommand) {
log.info(`${pc.yellow("Update your package.json scripts:")}

${pc.dim("Replace:")} ${pc.yellow('"pnpm -r dev"')} ${pc.dim("→")} ${pc.green(
'"turbo dev"',
)}
${pc.dim("Replace:")} ${pc.yellow('"pnpm --filter web dev"')} ${pc.dim(
"→",
)} ${pc.green('"turbo -F web dev"')}

${pc.cyan("Docs:")} ${pc.underline("https://turborepo.com/docs")}
`);
}
}

if (addons.includes("pwa") && (hasReactWebFrontend || hasSolidFrontend)) {
Expand Down
77 changes: 76 additions & 1 deletion apps/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ import fs from "fs-extra";
import pc from "picocolors";
import { createCli, trpcServer, zod as z } from "trpc-cli";
import { DEFAULT_CONFIG } from "./constants";
import { addAddonsToProject } from "./helpers/project-generation/add-addons";
import { createProject } from "./helpers/project-generation/create-project";
import { detectProjectConfig } from "./helpers/project-generation/detect-project-config";
import { getAddonsToAdd } from "./prompts/addons";
import { gatherConfig } from "./prompts/config-prompts";
import { getProjectName } from "./prompts/project-name";
import type { CreateInput, ProjectConfig } from "./types";
import type { AddInput, CreateInput, ProjectConfig } from "./types";
import {
AddonsSchema,
APISchema,
Expand Down Expand Up @@ -259,6 +262,53 @@ async function createProjectHandler(
}
}

async function addAddonsHandler(input: AddInput): Promise<void> {
try {
if (!input.addons || input.addons.length === 0) {
const projectDir = input.projectDir || process.cwd();
const detectedConfig = await detectProjectConfig(projectDir);

if (!detectedConfig) {
cancel(
pc.red(
"Could not detect project configuration. Please ensure this is a valid Better-T Stack project.",
),
);
process.exit(1);
}

const addonsPrompt = await getAddonsToAdd(
detectedConfig.frontend || [],
detectedConfig.addons || [],
);

if (addonsPrompt.length === 0) {
outro(
pc.yellow(
"No addons to add or all compatible addons are already present.",
),
);
return;
}

input.addons = addonsPrompt;
}

if (!input.addons || input.addons.length === 0) {
outro(pc.yellow("No addons specified to add."));
return;
}

await addAddonsToProject({
...input,
addons: input.addons,
});
} catch (error) {
console.error(error);
process.exit(1);
}
}
Comment thread
AmanVarshney01 marked this conversation as resolved.
Resolved

const router = t.router({
init: t.procedure
.meta({
Expand Down Expand Up @@ -301,6 +351,31 @@ const router = t.router({
};
await createProjectHandler(combinedInput);
}),
add: t.procedure
.meta({
description: "Add addons to an existing Better-T Stack project",
})
.input(
z.tuple([
z
.object({
addons: z.array(AddonsSchema).optional().default([]),
projectDir: z.string().optional(),
install: z
.boolean()
.optional()
.default(false)
.describe("Install dependencies after adding addons"),
packageManager: PackageManagerSchema.optional(),
})
.optional()
.default({}),
]),
)
.mutation(async ({ input }) => {
const [options] = input;
await addAddonsHandler(options);
}),
sponsors: t.procedure
.meta({ description: "Show Better-T Stack sponsors" })
.mutation(async () => {
Expand Down
Loading