Open History to see the last commit
1import { resolve, sep } from 'node:path'
2import { render } from 'ejs'
3import { format } from 'prettier'
4
5import { formatCommand } from './utils.js'
6import {
7 getPackageManagerInstallCommand,
8 getPackageManagerScriptCommand,
9} from './package-manager.js'
10import { relativePath } from './file-helpers.js'
11
12import type { Environment, Options } from './types.js'
13
14function convertDotFilesAndPaths(path: string) {
15 return path
16 .split(sep)
17 .map((segment) => segment.replace(/^_dot_/, '.'))
18 .join(sep)
19}
20
21export function createTemplateFile(environment: Environment, options: Options) {
22 function getPackageManagerAddScript(
23 packageName: string,
24 isDev: boolean = false,
25 ) {
26 return formatCommand(
27 getPackageManagerInstallCommand(
28 options.packageManager,
29 packageName,
30 isDev,
31 ),
32 )
33 }
34 function getPackageManagerRunScript(
35 scriptName: string,
36 args: Array<string> = [],
37 ) {
38 return formatCommand(
39 getPackageManagerScriptCommand(options.packageManager, [
40 scriptName,
41 ...args,
42 ]),
43 )
44 }
45
46 class IgnoreFileError extends Error {
47 constructor() {
48 super('ignoreFile')
49 this.name = 'IgnoreFileError'
50 }
51 }
52
53 // Collect all custom properties from add-ons
54 const customProperties: Record<string, Array<unknown>> = {}
55
56 // Initialize arrays for all framework custom properties
57 if (options.framework.customProperties) {
58 for (const key of Object.keys(options.framework.customProperties)) {
59 customProperties[key] = []
60 }
61 }
62
63 // Collect custom properties from each add-on
64 for (const addOn of options.chosenAddOns) {
65 if (addOn.customProperties) {
66 for (const [key, values] of Object.entries(addOn.customProperties)) {
67 // Initialize array if it doesn't exist (for properties not defined in framework)
68 if (!(key in customProperties)) {
69 customProperties[key] = []
70 }
71
72 // Add values to the array
73 if (Array.isArray(values)) {
74 customProperties[key].push(...values)
75 } else {
76 customProperties[key].push(values)
77 }
78 }
79 }
80 }
81
82 // Collect routes and integrations from add-ons (they're at root level in info.json)
83 // but they're defined in customProperties in the framework schema
84 if (options.framework.customProperties?.routes) {
85 customProperties.routes = []
86 for (const addOn of options.chosenAddOns) {
87 if (addOn.routes) {
88 customProperties.routes.push(...addOn.routes)
89 }
90 }
91 }
92
93 if (options.framework.customProperties?.integrations) {
94 customProperties.integrations = []
95 for (const addOn of options.chosenAddOns) {
96 if ('integrations' in addOn && addOn.integrations) {
97 customProperties.integrations.push(...(addOn as any).integrations)
98 }
99 }
100 }
101
102 const addOnEnabled = options.chosenAddOns.reduce<Record<string, boolean>>(
103 (acc, addOn) => {
104 acc[addOn.id] = true
105 return acc
106 },
107 {},
108 )
109
110 return async function templateFile(file: string, content: string) {
111 const templateValues = {
112 packageManager: options.packageManager,
113 projectName: options.projectName,
114 typescript: options.typescript,
115 tailwind: options.tailwind,
116 js: options.typescript ? 'ts' : 'js',
117 jsx: options.typescript ? 'tsx' : 'jsx',
118 fileRouter: options.mode === 'file-router',
119 codeRouter: options.mode === 'code-router',
120 addOnEnabled,
121 addOns: options.chosenAddOns,
122
123 // Spread custom properties to make them available at top level
124 ...customProperties,
125
126 getPackageManagerAddScript,
127 getPackageManagerRunScript,
128
129 relativePath: (path: string) => relativePath(file, path),
130
131 ignoreFile: () => {
132 throw new IgnoreFileError()
133 },
134 }
135
136 let ignoreFile = false
137
138 if (file.endsWith('.ejs')) {
139 try {
140 content = render(content, templateValues)
141 } catch (error) {
142 if (error instanceof IgnoreFileError) {
143 ignoreFile = true
144 } else {
145 console.error(file, error)
146 environment.error(`EJS error in file ${file}`, error?.toString())
147 process.exit(1)
148 }
149 }
150 }
151
152 if (ignoreFile) {
153 return
154 }
155
156 let target = convertDotFilesAndPaths(file.replace('.ejs', ''))
157
158 let append = false
159 if (target.endsWith('.append')) {
160 append = true
161 target = target.replace('.append', '')
162 }
163
164 if (target.endsWith('.ts') || target.endsWith('.tsx')) {
165 content = await format(content, {
166 semi: false,
167 singleQuote: true,
168 trailingComma: 'all',
169 parser: 'typescript',
170 })
171 }
172
173 if (!options.typescript) {
174 target = target.replace(/\.tsx$/, '.jsx').replace(/\.ts$/, '.js')
175 }
176
177 if (append) {
178 await environment.appendFile(resolve(options.targetDir, target), content)
179 } else {
180 await environment.writeFile(resolve(options.targetDir, target), content)
181 }
182 }
183}