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 { createFileRoute } 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 `export const Route = createFileRoute('${path}')({${routeDefinition}})`,
70 )
71 } else {
72 console.error(`No route found in the file: ${routeFile}`)
73 }
74
75 const name = basename(path)
76 .replace('.tsx', '')
77 .replace(/^demo/, '')
78 .replace('.', ' ')
79 .trim()
80
81 const jsName = camelCase(basename(path))
82
83 return { url: path, code, name, jsName }
84}
85
86export async function validateAddOnSetup(environment: Environment) {
87 const options = await readCurrentProjectOptions(environment)
88
89 if (options.mode === 'code-router') {
90 environment.error(
91 'This project is using code-router mode.',
92 'To create an add-on, the project must not use code-router mode.',
93 )
94 process.exit(1)
95 }
96}
97
98export async function readOrGenerateAddOnInfo(
99 options: PersistedOptions,
100): Promise<AddOnInfo> {
101 const info = existsSync(INFO_FILE)
102 ? JSON.parse((await readFile(INFO_FILE)).toString())
103 : ({
104 id: `${options.projectName}-add-on`,
105 name: `${options.projectName}-add-on`,
106 version: '0.0.1',
107 description: 'Add-on',
108 author: 'Jane Smith <jane.smith@example.com>',
109 license: 'MIT',
110 link: `https://github.com/jane-smith/${options.projectName}-add-on`,
111 shadcnComponents: [],
112 framework: options.framework,
113 modes: [options.mode],
114 routes: [],
115 warning: '',
116 phase: 'add-on',
117 type: 'add-on',
118 packageAdditions: {
119 scripts: {},
120 dependencies: {},
121 devDependencies: {},
122 },
123 dependsOn: options.chosenAddOns,
124 } as AddOnInfo)
125 return info
126}
127
128export async function generateProject(persistedOptions: PersistedOptions) {
129 const info = await readOrGenerateAddOnInfo(persistedOptions)
130
131 const output = await runCreateApp(
132 (await createAppOptionsFromPersisted(
133 persistedOptions,
134 )) as Required<Options>,
135 )
136
137 return { info, output }
138}
139
140export async function buildAssetsDirectory(
141 output: {
142 files: Record<string, string>
143 },
144 info: AddOnInfo,
145) {
146 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
147 const ignore = createIgnore(process.cwd())
148
149 if (!existsSync(assetsDir)) {
150 const changedFiles: Record<string, string> = {}
151 await compareFilesRecursively('.', ignore, output.files, changedFiles)
152
153 for (const file of Object.keys(changedFiles).filter(
154 (file) => !ADD_ON_IGNORE_FILES.includes(basename(file)),
155 )) {
156 mkdirSync(dirname(resolve(assetsDir, file)), {
157 recursive: true,
158 })
159 if (file.includes('/routes/')) {
160 const { url, code, name, jsName } = templatize(changedFiles[file], file)
161 info.routes ||= []
162 if (!info.routes.find((r) => r.url === url)) {
163 info.routes.push({
164 url,
165 name,
166 jsName,
167 path: file,
168 })
169 }
170 writeFileSync(resolve(assetsDir, `${file}.ejs`), code)
171 } else {
172 writeFileSync(resolve(assetsDir, file), changedFiles[file])
173 }
174 }
175 }
176}
177
178export async function updateAddOnInfo(environment: Environment) {
179 const { info, output } = await generateProject(
180 await readCurrentProjectOptions(environment),
181 )
182
183 info.packageAdditions = createPackageAdditions(
184 JSON.parse(output.files['./package.json']),
185 JSON.parse((await readFile('package.json')).toString()),
186 )
187
188 await buildAssetsDirectory(output, info)
189
190 mkdirSync(resolve(dirname(INFO_FILE)), { recursive: true })
191 writeFileSync(INFO_FILE, JSON.stringify(info, null, 2))
192}
193
194export async function compileAddOn(environment: Environment) {
195 const info = await readOrGenerateAddOnInfo(
196 await readCurrentProjectOptions(environment),
197 )
198
199 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
200
201 const compiledInfo: AddOnCompiled = {
202 ...info,
203 files: await recursivelyGatherFiles(assetsDir),
204 deletedFiles: [],
205 }
206
207 writeFileSync(COMPILED_FILE, JSON.stringify(compiledInfo, null, 2))
208}
209
210export async function initAddOn(environment: Environment) {
211 await validateAddOnSetup(environment)
212 await updateAddOnInfo(environment)
213 await compileAddOn(environment)
214}
215
216export async function loadRemoteAddOn(url: string): Promise<AddOn> {
217 const response = await fetch(url)
218 const jsonContent = await response.json()
219
220 const checked = AddOnCompiledSchema.safeParse(jsonContent)
221 if (!checked.success) {
222 throw new Error(`Invalid add-on: ${url}`)
223 }
224
225 const addOn = checked.data
226 addOn.id = url
227 const out = {
228 ...addOn,
229 getFiles: () => Promise.resolve(Object.keys(addOn.files)),
230 getFileContents: (path: string) => Promise.resolve(addOn.files[path]),
231 getDeletedFiles: () => Promise.resolve(addOn.deletedFiles),
232 }
233 return out
234}