Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

package-json.ts

98 lines2.7 KB

1import { render } from 'ejs'
2import { sortObject } from './utils.js'
3​
4import type { Options } from './types.js'
5​
6export function mergePackageJSON(
7 packageJSON: Record<string, any>,
8 overlayPackageJSON?: Record<string, any>,
9) {
10 return {
11 ...packageJSON,
12 ...(overlayPackageJSON || {}),
13 dependencies: {
14 ...packageJSON.dependencies,
15 ...(overlayPackageJSON?.dependencies || {}),
16 },
17 devDependencies: {
18 ...packageJSON.devDependencies,
19 ...(overlayPackageJSON?.devDependencies || {}),
20 },
21 scripts: {
22 ...packageJSON.scripts,
23 ...(overlayPackageJSON?.scripts || {}),
24 },
25 }
27​
28export function createPackageJSON(options: Options) {
29 let packageJSON = {
30 ...JSON.parse(JSON.stringify(options.framework.basePackageJSON)),
31 name: options.projectName,
32 }
33​
34 const additions: Array<Record<string, any> | undefined> = [
35 options.framework.optionalPackages.typescript,
36 options.framework.optionalPackages.tailwindcss,
37 options.mode ? options.framework.optionalPackages[options.mode] : undefined,
38 ]
39 for (const addition of additions.filter(Boolean)) {
40 packageJSON = mergePackageJSON(packageJSON, addition)
41 }
42​
43 for (const addOn of options.chosenAddOns) {
44 let addOnPackageJSON = addOn.packageAdditions
45​
46 // Process EJS template if present
47 if (addOn.packageTemplate) {
48 const templateValues = {
49 packageManager: options.packageManager,
50 projectName: options.projectName,
51 typescript: true,
52 tailwind: true,
53 js: 'ts',
54 jsx: 'tsx',
55 fileRouter: options.mode === 'file-router',
56 codeRouter: options.mode === 'code-router',
57 addOnEnabled: options.chosenAddOns.reduce<Record<string, boolean>>(
58 (acc, addon) => {
59 acc[addon.id] = true
60 return acc
61 },
62 {},
63 ),
64 addOnOption: options.addOnOptions,
65 addOns: options.chosenAddOns,
66 }
67​
68 try {
69 const renderedTemplate = render(addOn.packageTemplate, templateValues)
70 addOnPackageJSON = JSON.parse(renderedTemplate)
71 } catch (error) {
72 console.error(
73 `Error processing package.json.ejs for add-on ${addOn.id}:`,
74 error,
75 )
76 // Fall back to packageAdditions if template processing fails
77 }
78 }
79​
80 packageJSON = mergePackageJSON(packageJSON, addOnPackageJSON)
81 }
82​
83 if (options.starter) {
84 packageJSON = mergePackageJSON(
85 packageJSON,
86 options.starter.packageAdditions,
87 )
88 }
89​
90 packageJSON.dependencies = sortObject(
91 (packageJSON.dependencies ?? {}) as Record<string, string>,
92 )
93 packageJSON.devDependencies = sortObject(
94 (packageJSON.devDependencies ?? {}) as Record<string, string>,
95 )
96​
97 return packageJSON