Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { fs, vol } from 'memfs'
3
4import { createMemoryEnvironment } from '../src/environment.js'
5import {
6 addToApp,
7 getCurrentConfiguration,
8 hasPendingGitChanges,
9 runNewCommands,
10 writeFiles,
11} from '../src/add-to-app.js'
12import {
13 getFrameworkById,
14 __testClearFrameworks,
15 __testRegisterFramework,
16} from '../src/frameworks.js'
17
18import type { PersistedOptions } from '../src/config-file.js'
19
20vi.mock('node:fs', () => fs)
21vi.mock('node:fs/promises', () => fs.promises)
22
23const fakeCTAJSON: PersistedOptions = {
24 projectName: 'test',
25 targetDir: '/foo',
26 framework: 'test',
27 mode: 'code-router',
28 chosenAddOns: [],
29 version: 1,
30 typescript: true,
31 tailwind: true,
32 packageManager: 'npm',
33 git: true,
34}
35
36beforeEach(() => {
37 const fakeFiles = {
38 'package.json': JSON.stringify({
39 name: 'test',
40 version: '1.0.0',
41 dependencies: {},
42 }),
43 }
44
45 vol.reset()
46 __testClearFrameworks()
47 __testRegisterFramework({
48 id: 'test',
49 name: 'Test',
50 description: 'Test',
51 version: '1.0.0',
52 baseDirectory: '/foo',
53 addOnsDirectories: [],
54 basePackageJSON: {},
55 optionalPackages: {},
56 bundlers: [
57 { id: 'vite', name: 'Vite', description: 'Build with Vite' },
58 { id: 'rsbuild', name: 'Rsbuild', description: 'Build with Rsbuild' },
59 ],
60 defaultBundler: 'vite',
61 getAddOns: () => [
62 {
63 id: 'test',
64 name: 'Test',
65 description: 'Test',
66 version: '1.0.0',
67 type: 'add-on',
68 phase: 'add-on',
69 modes: ['code-router', 'file-router'],
70 tailwind: true,
71 command: {
72 command: 'echo',
73 args: ['baz'],
74 },
75 packageAdditions: {
76 dependencies: {
77 'test-package': '1.0.0',
78 },
79 },
80 dependsOn: [],
81 getFiles: () => Promise.resolve(['jack.txt']),
82 getFileContents: () => Promise.resolve('foo'),
83 getDeletedFiles: () => Promise.resolve([]),
84 },
85 {
86 id: 'eslint',
87 name: 'ESLint',
88 description: 'ESLint',
89 version: '1.0.0',
90 type: 'toolchain',
91 phase: 'setup',
92 modes: ['file-router'],
93 exclusive: ['linter'],
94 packageAdditions: {},
95 dependsOn: [],
96 getFiles: () => Promise.resolve([]),
97 getFileContents: () => Promise.resolve(''),
98 getDeletedFiles: () => Promise.resolve([]),
99 },
100 {
101 id: 'biome',
102 name: 'Biome',
103 description: 'Biome',
104 version: '1.0.0',
105 type: 'toolchain',
106 phase: 'setup',
107 modes: ['file-router'],
108 exclusive: ['linter'],
109 packageAdditions: {},
110 dependsOn: [],
111 getFiles: () => Promise.resolve([]),
112 getFileContents: () => Promise.resolve(''),
113 getDeletedFiles: () => Promise.resolve([]),
114 },
115 ],
116 getFiles: () => Promise.resolve(Object.keys(fakeFiles)),
117 getFileContents: (path) => Promise.resolve(fakeFiles[path]),
118 getDeletedFiles: () => Promise.resolve([]),
119 })
120})
121
122const configFile: PersistedOptions = {
123 projectName: 'test',
124 targetDir: '/foo',
125 framework: 'test',
126 mode: 'code-router',
127 chosenAddOns: [],
128 version: 1,
129 typescript: true,
130 tailwind: true,
131 packageManager: 'npm',
132 git: true,
133}
134
135describe('getCurrentConfiguration', () => {
136 it('should check for the config file', async () => {
137 const { environment } = createMemoryEnvironment()
138 const out = await getCurrentConfiguration(environment, '/foo')
139 expect(out).toBeUndefined()
140 })
141
142 it('should read the config file', async () => {
143 const { environment } = createMemoryEnvironment()
144
145 environment.writeFile('/foo/.cta.json', JSON.stringify(configFile, null, 2))
146
147 const out = await getCurrentConfiguration(environment, '/foo')
148 expect(out).toEqual({ ...configFile, bundler: 'vite' })
149 })
150})
151
152describe('hasPendingGitChanges', () => {
153 it('should check for pending git changes', async () => {
154 const { environment } = createMemoryEnvironment()
155 environment.execute = () => Promise.resolve({ stdout: '' })
156 const out = await hasPendingGitChanges(environment, '/foo')
157 expect(out).toBe(false)
158 })
159
160 it('should check for pending git changes', async () => {
161 const { environment } = createMemoryEnvironment()
162 environment.execute = () => Promise.resolve({ stdout: 'M foo' })
163 const out = await hasPendingGitChanges(environment, '/foo')
164 expect(out).toBe(true)
165 })
166})
167
168describe('writeFiles', () => {
169 it('should prompt for confirmation when not forced', async () => {
170 const { environment } = createMemoryEnvironment('/foo')
171 environment.writeFile('/foo/bloop.txt', 'bloop')
172 environment.writeFile(
173 '/foo/package.json',
174 JSON.stringify(
175 {
176 name: 'test',
177 version: '1.0.0',
178 dependencies: {},
179 },
180 null,
181 2,
182 ),
183 )
184 environment.writeFile('/foo/bar.txt', 'bar')
185 environment.confirm = () => Promise.resolve(false)
186 let thrown = false
187 writeFiles(
188 environment,
189 '/foo',
190 {
191 files: {
192 'bar.txt': 'baz',
193 'blarg.txt': 'blarg',
194 },
195 deletedFiles: [],
196 },
197 false,
198 )
199 .catch((e) => {
200 thrown = true
201 })
202 .finally(() => {
203 expect(thrown).toBe(true)
204 })
205 })
206
207 it('should not prompt for confirmation when forced', async () => {
208 const { environment, output } = createMemoryEnvironment('/foo')
209 environment.startRun()
210 environment.writeFile('/foo/.cta.json', JSON.stringify(configFile, null, 2))
211 environment.writeFile('/foo/blooop.txt', 'blooop')
212 await writeFiles(
213 environment,
214 '/foo',
215 {
216 files: {
217 'bar.txt': 'baz',
218 'blarg.txt': 'blarg',
219 },
220 deletedFiles: [],
221 },
222 true,
223 )
224 environment.finishRun()
225 expect(output.files).toEqual({
226 'blooop.txt': 'blooop',
227 'bar.txt': 'baz',
228 'blarg.txt': 'blarg',
229 })
230 })
231
232 it('should handle binary files', async () => {
233 const { environment, output } = createMemoryEnvironment('/foo')
234 environment.startRun()
235 environment.writeFile('/foo/.cta.json', JSON.stringify(configFile, null, 2))
236 environment.writeFile('/foo/unchanged.jpg', 'base64::foobaz')
237 environment.writeFile('/foo/changing.jpg', 'base64::foobaz')
238 await writeFiles(
239 environment,
240 '/foo',
241 {
242 files: {
243 'unchanged.jpg': 'base64::foobaz',
244 'changing.jpg': 'base64::aGVsbG8=',
245 'new.jpg': 'base64::aGVsbG8=',
246 },
247 deletedFiles: [],
248 },
249 true,
250 )
251 environment.finishRun()
252 // It's ok for unchanged.jpg not to be written, because it matches the existing file
253 expect(output.files).toEqual({
254 'unchanged.jpg': 'base64::foobaz',
255 'changing.jpg': 'base64::aGVsbG8=',
256 'new.jpg': 'base64::aGVsbG8=',
257 })
258 })
259
260 it('should handle package.json', async () => {
261 const { environment, output } = createMemoryEnvironment('/foo')
262 environment.startRun()
263 environment.writeFile(
264 '/foo/package.json',
265 JSON.stringify(
266 {
267 name: 'test',
268 version: '1.0.0',
269 scripts: {
270 dev: 'echo "test"',
271 },
272 dependencies: {
273 'test-package-2': '1.0.0',
274 },
275 },
276 null,
277 2,
278 ),
279 )
280 await writeFiles(
281 environment,
282 '/foo',
283 {
284 files: {
285 'package.json': JSON.stringify(
286 {
287 scripts: {
288 test: 'echo "test"',
289 },
290 dependencies: {
291 'test-package': '1.0.0',
292 },
293 },
294 null,
295 2,
296 ),
297 },
298 deletedFiles: [],
299 },
300 true,
301 )
302 environment.finishRun()
303 expect(output.files).toEqual({
304 'package.json': JSON.stringify(
305 {
306 name: 'test',
307 version: '1.0.0',
308 scripts: {
309 dev: 'echo "test"',
310 test: 'echo "test"',
311 },
312 dependencies: {
313 'test-package-2': '1.0.0',
314 'test-package': '1.0.0',
315 },
316 devDependencies: {},
317 },
318 null,
319 2,
320 ),
321 })
322 })
323
324 it.each(['.env', '.env.local', '.env.example'])(
325 'should preserve existing values when updating %s',
326 async (fileName) => {
327 const { environment, output } = createMemoryEnvironment('/foo')
328 environment.startRun()
329 await environment.writeFile(
330 `/foo/${fileName}`,
331 '# Existing configuration\nAPI_SECRET=keep-me\n',
332 )
333
334 await writeFiles(
335 environment,
336 '/foo',
337 {
338 files: {
339 [fileName]:
340 '# Generated configuration\nAPI_SECRET=\nNEW_VALUE=generated\n\n# Another integration\nANOTHER_VALUE=\n',
341 },
342 deletedFiles: [],
343 },
344 true,
345 )
346
347 environment.finishRun()
348 expect(output.files[fileName]).toBe(
349 '# Existing configuration\nAPI_SECRET=keep-me\n\n# Generated configuration\nNEW_VALUE=generated\n\n# Another integration\nANOTHER_VALUE=\n',
350 )
351 },
352 )
353
354 it('should delete files', async () => {
355 const { environment, output } = createMemoryEnvironment('/foo')
356 environment.startRun()
357 environment.writeFile('/foo/bloop.txt', 'bloop')
358 await writeFiles(
359 environment,
360 '/foo',
361 { files: {}, deletedFiles: ['bloop.txt'] },
362 true,
363 )
364 environment.finishRun()
365 expect(output.deletedFiles).toEqual(['bloop.txt'])
366 })
367
368 it('should prompt before deleting existing files', async () => {
369 const { environment } = createMemoryEnvironment('/foo')
370 await environment.writeFile('/foo/nixpacks.toml', '[start]')
371 const confirm = vi.fn(() => Promise.resolve(false))
372 environment.confirm = confirm
373
374 await expect(
375 writeFiles(
376 environment,
377 '/foo',
378 { files: {}, deletedFiles: ['nixpacks.toml'] },
379 false,
380 ),
381 ).rejects.toThrow('User cancelled')
382
383 expect(confirm).toHaveBeenCalledOnce()
384 expect(environment.exists('/foo/nixpacks.toml')).toBe(true)
385 })
386
387 it('should normalize windows-style output paths before writing', async () => {
388 const writePaths: Array<string> = []
389 const environment = {
390 readdir: async () => [],
391 isDirectory: () => false,
392 readFile: async () => '',
393 exists: () => false,
394 deleteFile: async () => {},
395 writeFileBase64: async () => {},
396 writeFile: async (path: string) => {
397 writePaths.push(path)
398 },
399 startStep: () => {},
400 finishStep: () => {},
401 warn: () => {},
402 confirm: async () => true,
403 } as any
404
405 await writeFiles(
406 environment,
407 'C:\\Users\\marv\\workspace\\fenbi-tanstack',
408 {
409 files: {
410 'Users/marv/workspace/fenbi-tanstack/src/components.json': '{}',
411 },
412 deletedFiles: [],
413 },
414 true,
415 )
416
417 expect(writePaths).toHaveLength(1)
418 expect(writePaths[0]).toMatch(/components\.json$/)
419 expect(writePaths[0]).not.toMatch(
420 /Users[\\/]marv[\\/]workspace[\\/]fenbi-tanstack[\\/]Users[\\/]marv[\\/]workspace[\\/]fenbi-tanstack/,
421 )
422 })
423})
424
425describe('runNewCommands', () => {
426 it.each(['10.1.0', '10.2.0'])(
427 'does not rerun an existing approved command when planning for pnpm %s',
428 async (packageManagerVersion) => {
429 const framework = getFrameworkById('test')
430 if (!framework) throw new Error('Missing test framework')
431 const addOns = framework.getAddOns()
432 framework.getAddOns = () => addOns.map((addOn) => addOn.id === 'test'
433 ? { ...addOn, command: { command: 'npx', args: ['storybook', 'init'], allowBuilds: ['esbuild'] } }
434 : addOn)
435 const { environment, output } = createMemoryEnvironment('/foo')
436 const args = [
437 ...(packageManagerVersion === '10.2.0' ? ['--allow-build=esbuild'] : []),
438 'dlx', 'storybook', 'init',
439 ]
440 await runNewCommands(environment, {
441 ...fakeCTAJSON, packageManager: 'pnpm', chosenAddOns: ['test'],
442 }, '/foo', { commands: [{ command: 'pnpm', args }] }, packageManagerVersion)
443 expect(output.commands).toEqual([])
444 },
445 )
446
447 it('should run new commands', async () => {
448 const { environment, output } = createMemoryEnvironment('/foo')
449 environment.startRun()
450 await runNewCommands(environment, fakeCTAJSON, '/foo', {
451 commands: [{ command: 'echo', args: ['bloop'] }],
452 })
453 environment.finishRun()
454 expect(output.commands).toEqual([{ command: 'echo', args: ['bloop'] }])
455 })
456})
457
458describe('addToApp', () => {
459 it('should add an add-on', async () => {
460 const { environment, output } = createMemoryEnvironment('/foo')
461 environment.startRun()
462 environment.writeFile(
463 '/foo/.cta.json',
464 JSON.stringify(fakeCTAJSON, null, 2),
465 )
466 environment.writeFile(
467 '/foo/package.json',
468 JSON.stringify(
469 {
470 name: 'test',
471 version: '1.0.0',
472 scripts: {},
473 dependencies: {},
474 devDependencies: {},
475 },
476 null,
477 2,
478 ),
479 )
480 await addToApp(environment, ['test'], '/foo', {
481 forced: true,
482 })
483 environment.finishRun()
484 expect(output.files).toEqual({
485 'jack.txt': 'foo',
486 'package.json': JSON.stringify(
487 {
488 name: 'test',
489 version: '1.0.0',
490 scripts: {},
491 dependencies: {
492 'test-package': '1.0.0',
493 },
494 devDependencies: {},
495 },
496 null,
497 2,
498 ),
499 })
500 })
501
502 it('enables Tailwind when an add-on requires it', async () => {
503 const { environment } = createMemoryEnvironment('/foo')
504 environment.startRun()
505 environment.writeFile(
506 '/foo/.cta.json',
507 JSON.stringify({ ...fakeCTAJSON, tailwind: false }, null, 2),
508 )
509 environment.writeFile(
510 '/foo/package.json',
511 JSON.stringify(
512 {
513 name: 'test',
514 version: '1.0.0',
515 scripts: {},
516 dependencies: {},
517 devDependencies: {},
518 },
519 null,
520 2,
521 ),
522 )
523
524 await addToApp(environment, ['test'], '/foo', {
525 forced: true,
526 })
527
528 const persisted = JSON.parse(await environment.readFile('/foo/.cta.json'))
529 expect(persisted.tailwind).toBe(true)
530 })
531
532 it('rejects a second exclusive Rsbuild toolchain', async () => {
533 const { environment } = createMemoryEnvironment('/foo')
534 environment.startRun()
535 environment.writeFile(
536 '/foo/.cta.json',
537 JSON.stringify(
538 {
539 ...fakeCTAJSON,
540 mode: 'file-router',
541 bundler: 'rsbuild',
542 chosenAddOns: ['eslint'],
543 },
544 null,
545 2,
546 ),
547 )
548
549 await expect(
550 addToApp(environment, ['biome'], '/foo', { forced: true }),
551 ).rejects.toThrow(
552 'Cannot combine ESLint and Biome. Add-ons in the "linter" group are mutually exclusive.',
553 )
554
555 const persisted = JSON.parse(await environment.readFile('/foo/.cta.json'))
556 expect(persisted.chosenAddOns).toEqual(['eslint'])
557 })
558})