Open History to see the last commit
1import { resolve } from 'node:path'
2import { Command, InvalidArgumentError } from 'commander'
3import { intro, log } from '@clack/prompts'
4import chalk from 'chalk'
5
6import {
7 SUPPORTED_PACKAGE_MANAGERS,
8 addToApp,
9 compileAddOn,
10 compileStarter,
11 createApp,
12 createSerializedOptions,
13 getAllAddOns,
14 getFrameworkById,
15 getFrameworkByName,
16 getFrameworks,
17 initAddOn,
18 initStarter,
19} from '@tanstack/cta-engine'
20
21import { launchUI } from '@tanstack/cta-ui'
22
23import { runMCPServer } from './mcp.js'
24
25import { promptForAddOns, promptForCreateOptions } from './options.js'
26import { normalizeOptions } from './command-line.js'
27
28import { createUIEnvironment } from './ui-environment.js'
29import { convertTemplateToMode } from './utils.js'
30
31import type { CliOptions, TemplateOptions } from './types.js'
32import type { Options, PackageManager } from '@tanstack/cta-engine'
33
34// This CLI assumes that all of the registered frameworks have the same set of toolchains, modes, etc.
35
36export function cli({
37 name,
38 appName,
39 forcedMode,
40 forcedAddOns = [],
41 defaultTemplate = 'javascript',
42 defaultFramework,
43 craCompatible = false,
44 webBase,
45}: {
46 name: string
47 appName: string
48 forcedMode?: string
49 forcedAddOns?: Array<string>
50 defaultTemplate?: TemplateOptions
51 defaultFramework?: string
52 craCompatible?: boolean
53 webBase?: string
54}) {
55 const environment = createUIEnvironment(appName, false)
56
57 const program = new Command()
58
59 const availableFrameworks = getFrameworks().map((f) => f.name)
60
61 const toolchains = new Set<string>()
62 for (const framework of getFrameworks()) {
63 for (const addOn of framework.getAddOns()) {
64 if (addOn.type === 'toolchain') {
65 toolchains.add(addOn.id)
66 }
67 }
68 }
69
70 let defaultMode: string | undefined = forcedMode
71 const supportedModes = new Set<string>()
72 for (const framework of getFrameworks()) {
73 for (const mode of Object.keys(framework.supportedModes)) {
74 supportedModes.add(mode)
75 }
76 }
77 if (defaultMode && !supportedModes.has(defaultMode)) {
78 throw new InvalidArgumentError(
79 `Invalid mode: ${defaultMode}. The following are allowed: ${Array.from(
80 supportedModes,
81 ).join(', ')}`,
82 )
83 }
84 if (supportedModes.size < 2) {
85 defaultMode = Array.from(supportedModes)[0]
86 }
87
88 program.name(name).description(`CLI to create a new ${appName} application`)
89
90 program
91 .command('add')
92 .argument(
93 '[add-on...]',
94 'Name of the add-ons (or add-ons separated by spaces or commas)',
95 )
96 .option('--forced', 'Force the add-on to be added', false)
97 .option('--ui', 'Add with the UI')
98 .action(async (addOns: Array<string>) => {
99 const parsedAddOns: Array<string> = []
100 for (const addOn of addOns) {
101 if (addOn.includes(',') || addOn.includes(' ')) {
102 parsedAddOns.push(
103 ...addOn.split(/[\s,]+/).map((addon) => addon.trim()),
104 )
105 } else {
106 parsedAddOns.push(addOn.trim())
107 }
108 }
109 if (program.opts().ui) {
110 launchUI({
111 mode: 'add',
112 addOns: parsedAddOns,
113 projectPath: resolve(process.cwd()),
114 forcedRouterMode: defaultMode,
115 forcedAddOns,
116 environmentFactory: () => createUIEnvironment(appName, false),
117 webBase,
118 })
119 } else if (parsedAddOns.length < 1) {
120 const addOns = await promptForAddOns()
121 if (addOns.length) {
122 await addToApp(environment, addOns, resolve(process.cwd()), {
123 forced: program.opts().forced,
124 })
125 }
126 } else {
127 await addToApp(environment, parsedAddOns, resolve(process.cwd()), {
128 forced: program.opts().forced,
129 })
130 }
131 })
132
133 const addOnCommand = program.command('add-on')
134 addOnCommand
135 .command('init')
136 .description('Initialize an add-on from the current project')
137 .action(async () => {
138 await initAddOn(environment)
139 })
140 addOnCommand
141 .command('compile')
142 .description('Update add-on from the current project')
143 .action(async () => {
144 await compileAddOn(environment)
145 })
146
147 const starterCommand = program.command('starter')
148 starterCommand
149 .command('init')
150 .description('Initialize a project starter from the current project')
151 .action(async () => {
152 await initStarter(environment)
153 })
154 starterCommand
155 .command('compile')
156 .description('Compile the starter JSON file for the current project')
157 .action(async () => {
158 await compileStarter(environment)
159 })
160
161 program.argument('[project-name]', 'name of the project')
162
163 if (!defaultMode && craCompatible) {
164 program.option<'typescript' | 'javascript' | 'file-router'>(
165 '--template <type>',
166 'project template (typescript, javascript, file-router)',
167 (value) => {
168 if (
169 value !== 'typescript' &&
170 value !== 'javascript' &&
171 value !== 'file-router'
172 ) {
173 throw new InvalidArgumentError(
174 `Invalid template: ${value}. Only the following are allowed: typescript, javascript, file-router`,
175 )
176 }
177 return value
178 },
179 )
180 }
181
182 if (!defaultFramework) {
183 program.option<string>(
184 '--framework <type>',
185 `project framework (${availableFrameworks.join(', ')})`,
186 (value) => {
187 if (!availableFrameworks.includes(value)) {
188 throw new InvalidArgumentError(
189 `Invalid framework: ${value}. Only the following are allowed: ${availableFrameworks.join(', ')}`,
190 )
191 }
192 return value
193 },
194 defaultFramework || 'react',
195 )
196 }
197
198 program
199 .option(
200 '--starter [url]',
201 'initialize this project from a starter URL',
202 false,
203 )
204 .option<PackageManager>(
205 `--package-manager <${SUPPORTED_PACKAGE_MANAGERS.join('|')}>`,
206 `Explicitly tell the CLI to use this package manager`,
207 (value) => {
208 if (!SUPPORTED_PACKAGE_MANAGERS.includes(value as PackageManager)) {
209 throw new InvalidArgumentError(
210 `Invalid package manager: ${value}. The following are allowed: ${SUPPORTED_PACKAGE_MANAGERS.join(
211 ', ',
212 )}`,
213 )
214 }
215 return value as PackageManager
216 },
217 )
218
219 if (toolchains.size > 0) {
220 program.option<string>(
221 `--toolchain <${Array.from(toolchains).join('|')}>`,
222 `Explicitly tell the CLI to use this toolchain`,
223 (value) => {
224 if (!toolchains.has(value)) {
225 throw new InvalidArgumentError(
226 `Invalid toolchain: ${value}. The following are allowed: ${Array.from(
227 toolchains,
228 ).join(', ')}`,
229 )
230 }
231 return value
232 },
233 )
234 }
235
236 program
237 .option('--interactive', 'interactive mode', false)
238 .option('--tailwind', 'add Tailwind CSS', false)
239 .option<Array<string> | boolean>(
240 '--add-ons [...add-ons]',
241 'pick from a list of available add-ons (comma separated list)',
242 (value: string) => {
243 let addOns: Array<string> | boolean = !!value
244 if (typeof value === 'string') {
245 addOns = value.split(',').map((addon) => addon.trim())
246 }
247 return addOns
248 },
249 )
250 .option('--list-add-ons', 'list all available add-ons', false)
251 .option('--no-git', 'do not create a git repository')
252 .option(
253 '--target-dir <path>',
254 'the target directory for the application root',
255 )
256 .option('--mcp', 'run the MCP server', false)
257 .option('--mcp-sse', 'run the MCP server in SSE mode', false)
258 .option('--ui', 'Add with the UI')
259
260 program.action(async (projectName: string, options: CliOptions) => {
261 if (options.listAddOns) {
262 const addOns = await getAllAddOns(
263 getFrameworkById(options.framework || defaultFramework || 'react-cra')!,
264 defaultMode ||
265 convertTemplateToMode(options.template || defaultTemplate),
266 )
267 for (const addOn of addOns.filter((a) => !forcedAddOns.includes(a.id))) {
268 console.log(`${chalk.bold(addOn.id)}: ${addOn.description}`)
269 }
270 } else if (options.mcp || options.mcpSse) {
271 await runMCPServer(!!options.mcpSse, {
272 forcedMode: defaultMode,
273 forcedAddOns,
274 appName,
275 })
276 } else {
277 try {
278 const cliOptions = {
279 projectName,
280 ...options,
281 } as CliOptions
282
283 cliOptions.framework = getFrameworkByName(
284 options.framework || defaultFramework || 'react',
285 )!.id
286
287 if (defaultMode) {
288 cliOptions.template = defaultMode as TemplateOptions
289 }
290
291 let finalOptions: Options | undefined
292 if (cliOptions.interactive) {
293 cliOptions.addOns = true
294 } else {
295 finalOptions = await normalizeOptions(
296 cliOptions,
297 defaultMode,
298 forcedAddOns,
299 )
300 }
301
302 if (options.ui) {
303 const optionsFromCLI = await normalizeOptions(
304 cliOptions,
305 defaultMode,
306 forcedAddOns,
307 { disableNameCheck: true },
308 )
309 launchUI({
310 mode: 'setup',
311 options: {
312 ...createSerializedOptions(optionsFromCLI!),
313 projectName: 'my-app',
314 targetDir: resolve(process.cwd(), 'my-app'),
315 },
316 forcedRouterMode: defaultMode,
317 forcedAddOns,
318 environmentFactory: () => createUIEnvironment(appName, false),
319 webBase,
320 })
321 return
322 }
323
324 if (finalOptions) {
325 intro(`Creating a new ${appName} app in ${projectName}...`)
326 } else {
327 intro(`Let's configure your ${appName} application`)
328 finalOptions = await promptForCreateOptions(cliOptions, {
329 forcedMode: defaultMode,
330 forcedAddOns,
331 })
332 }
333
334 if (!finalOptions) {
335 throw new Error('No options were provided')
336 }
337
338 finalOptions.targetDir =
339 options.targetDir || resolve(process.cwd(), finalOptions.projectName)
340
341 await createApp(environment, finalOptions)
342 } catch (error) {
343 log.error(
344 error instanceof Error ? error.message : 'An unknown error occurred',
345 )
346 process.exit(1)
347 }
348 }
349 })
350
351 program.parse()
352}