Open History to see the last commit
1import { readFile } from 'node:fs/promises'
2import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
3import { basename, dirname, resolve } from 'node:path'
4
5import { AddOnCompiledSchema } from '../types.js'
6import { createIgnore, recursivelyGatherFiles } from '../file-helpers.js'
7import {
8 compareFilesRecursively,
9 createAppOptionsFromPersisted,
10 createPackageAdditions,
11 readCurrentProjectOptions,
12 runCreateApp,
13} from './shared.js'
14
15import type { PersistedOptions } from '../config-file'
16import type {
17 AddOn,
18 AddOnCompiled,
19 AddOnInfo,
20 Environment,
21 Options,
22} from '../types'
23
24const ADD_ON_DIR = '.add-on'
25
26export const ADD_ON_IGNORE_FILES: Array<string> = [
27 'main.jsx',
28 'App.jsx',
29 'main.tsx',
30 'App.tsx',
31 'routeTree.gen.ts',
32]
33
34const INFO_FILE = '.add-on/info.json'
35const COMPILED_FILE = 'add-on.json'
36
37const ASSETS_DIR = 'assets'
38
39export function camelCase(str: string) {
40 return str
41 .split(/(\.|-|\/)/)
42 .filter((part) => /^[a-zA-Z]+$/.test(part))
43 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
44 .join('')
45}
46
47export function templatize(routeCode: string, routeFile: string) {
48 let code = routeCode
49
50 // Replace the import
51 code = code.replace(
52 /import { createFileRoute } from ['"]@tanstack\/react-router['"]/g,
53 `import { <% if (fileRouter) { %>createFileRoute<% } else { %>createRoute<% } %> } from '@tanstack/react-router'`,
54 )
55
56 // Extract route path and definition, then transform the route declaration
57 const routeMatch = code.match(
58 /export\s+const\s+Route\s*=\s*createFileRoute\(['"]([^'"]+)['"]\)\s*\(\{([^}]+)\}\)/,
59 )
60
61 let path = ''
62
63 if (routeMatch) {
64 const fullMatch = routeMatch[0]
65 path = routeMatch[1]
66 const routeDefinition = routeMatch[2]
67 code = code.replace(
68 fullMatch,
69 `<% if (codeRouter) { %>
70import type { RootRoute } from '@tanstack/react-router'
71<% } else { %>
72export const Route = createFileRoute('${path}')({${routeDefinition}})
73<% } %>`,
74 )
75
76 code += `
77<% if (codeRouter) { %>
78export default (parentRoute: RootRoute) => createRoute({
79 path: '${path}',
80 ${routeDefinition}
81 getParentRoute: () => parentRoute,
82})
83<% } %>
84`
85 } else {
86 console.error(`No route found in the file: ${routeFile}`)
87 }
88
89 const name = basename(path)
90 .replace('.tsx', '')
91 .replace(/^demo/, '')
92 .replace('.', ' ')
93 .trim()
94
95 const jsName = camelCase(basename(path))
96
97 return { url: path, code, name, jsName }
98}
99
100export async function validateAddOnSetup(environment: Environment) {
101 const options = await readCurrentProjectOptions(environment)
102
103 if (options.mode === 'code-router') {
104 environment.error(
105 'This project is using code-router mode.',
106 'To create an add-on, the project must not use code-router mode.',
107 )
108 process.exit(1)
109 }
110 if (!options.tailwind) {
111 environment.error(
112 'This project is not using Tailwind CSS.',
113 'To create an add-on, the project must be created with Tailwind CSS.',
114 )
115 process.exit(1)
116 }
117 if (!options.typescript) {
118 environment.error(
119 'This project is not using TypeScript.',
120 'To create an add-on, the project must be created with TypeScript.',
121 )
122 process.exit(1)
123 }
124}
125
126export async function readOrGenerateAddOnInfo(
127 options: PersistedOptions,
128): Promise<AddOnInfo> {
129 return existsSync(INFO_FILE)
130 ? JSON.parse((await readFile(INFO_FILE)).toString())
131 : ({
132 id: `${options.projectName}-add-on`,
133 name: `${options.projectName}-add-on`,
134 version: '0.0.1',
135 description: 'Add-on',
136 author: 'Jane Smith <jane.smith@example.com>',
137 license: 'MIT',
138 link: `https://github.com/jane-smith/${options.projectName}-add-on`,
139 shadcnComponents: [],
140 framework: options.framework,
141 modes: [options.mode],
142 routes: [],
143 warning: '',
144 phase: 'add-on',
145 type: 'add-on',
146 packageAdditions: {
147 scripts: {},
148 dependencies: {},
149 devDependencies: {},
150 },
151 dependsOn: options.chosenAddOns,
152 } as AddOnInfo)
153}
154
155export async function generateProject(persistedOptions: PersistedOptions) {
156 const info = await readOrGenerateAddOnInfo(persistedOptions)
157
158 const output = await runCreateApp(
159 (await createAppOptionsFromPersisted(
160 persistedOptions,
161 )) as Required<Options>,
162 )
163
164 return { info, output }
165}
166
167export async function buildAssetsDirectory(
168 output: {
169 files: Record<string, string>
170 },
171 info: AddOnInfo,
172) {
173 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
174 const ignore = createIgnore(process.cwd())
175
176 if (!existsSync(assetsDir)) {
177 const changedFiles: Record<string, string> = {}
178 await compareFilesRecursively('.', ignore, output.files, changedFiles)
179
180 for (const file of Object.keys(changedFiles).filter(
181 (file) => !ADD_ON_IGNORE_FILES.includes(basename(file)),
182 )) {
183 mkdirSync(dirname(resolve(assetsDir, file)), {
184 recursive: true,
185 })
186 if (file.includes('/routes/')) {
187 const { url, code, name, jsName } = templatize(changedFiles[file], file)
188 info.routes ||= []
189 if (!info.routes.find((r) => r.url === url)) {
190 info.routes.push({
191 url,
192 name,
193 jsName,
194 path: file,
195 })
196 }
197 writeFileSync(resolve(assetsDir, `${file}.ejs`), code)
198 } else {
199 writeFileSync(resolve(assetsDir, file), changedFiles[file])
200 }
201 }
202 }
203}
204
205export async function updateAddOnInfo(environment: Environment) {
206 const { info, output } = await generateProject(
207 await readCurrentProjectOptions(environment),
208 )
209
210 info.packageAdditions = createPackageAdditions(
211 JSON.parse(output.files['./package.json']),
212 JSON.parse((await readFile('package.json')).toString()),
213 )
214
215 await buildAssetsDirectory(output, info)
216
217 mkdirSync(resolve(dirname(INFO_FILE)), { recursive: true })
218 writeFileSync(INFO_FILE, JSON.stringify(info, null, 2))
219}
220
221export async function compileAddOn(environment: Environment) {
222 const info = await readOrGenerateAddOnInfo(
223 await readCurrentProjectOptions(environment),
224 )
225
226 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
227
228 const compiledInfo: AddOnCompiled = {
229 ...info,
230 files: await recursivelyGatherFiles(assetsDir),
231 deletedFiles: [],
232 }
233
234 writeFileSync(COMPILED_FILE, JSON.stringify(compiledInfo, null, 2))
235}
236
237export async function initAddOn(environment: Environment) {
238 await validateAddOnSetup(environment)
239 await updateAddOnInfo(environment)
240 await compileAddOn(environment)
241}
242
243export async function loadRemoteAddOn(url: string): Promise<AddOn> {
244 const response = await fetch(url)
245 const jsonContent = await response.json()
246
247 const checked = AddOnCompiledSchema.safeParse(jsonContent)
248 if (!checked.success) {
249 throw new Error(`Invalid add-on: ${url}`)
250 }
251
252 const addOn = checked.data
253 addOn.id = url
254 const out = {
255 ...addOn,
256 getFiles: () => Promise.resolve(Object.keys(addOn.files)),
257 getFileContents: (path: string) => Promise.resolve(addOn.files[path]),
258 getDeletedFiles: () => Promise.resolve(addOn.deletedFiles),
259 }
260 return out
261}