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

add-on.ts

305 lines8.0 KB

1import { readFile, watch } 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.js'
16import type {
17 AddOn,
18 AddOnCompiled,
19 AddOnInfo,
20 Environment,
21 Options,
22} from '../types.js'
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',
33​
34const INFO_FILE = '.add-on/info.json'
35const COMPILED_FILE = 'add-on.json'
36​
37const ASSETS_DIR = 'assets'
38​
39const ADD_ON_DEV_IGNORE_PREFIXES = [
40 '.add-on/',
41 '.git/',
42 'node_modules/',
43 '.turbo/',
44 'dist/',
46​
47function shouldIgnoreDevPath(path: string) {
48 const normalized = path.replace(/\\/g, '/')
49 if (normalized === COMPILED_FILE) return true
50 return ADD_ON_DEV_IGNORE_PREFIXES.some((prefix) =>
51 normalized.startsWith(prefix),
52 )
54​
55export function camelCase(str: string) {
56 return str
57 .split(/(\.|-|\/)/)
58 .filter((part) => /^[a-zA-Z]+$/.test(part))
59 .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
60 .join('')
62​
63export function templatize(routeCode: string, routeFile: string) {
64 let code = routeCode
65​
66 // Replace the import
67 code = code.replace(
68 /import { createFileRoute } from ['"]@tanstack\/react-router['"]/g,
69 `import { createFileRoute } from '@tanstack/react-router'`,
70 )
71​
72 // Extract route path and definition, then transform the route declaration
73 const routeMatch = code.match(
74 /export\s+const\s+Route\s*=\s*createFileRoute\(['"]([^'"]+)['"]\)\s*\(\{([^}]+)\}\)/,
75 )
76​
77 let path = ''
78​
79 if (routeMatch) {
80 const fullMatch = routeMatch[0]
81 path = routeMatch[1]
82 const routeDefinition = routeMatch[2]
83 code = code.replace(
84 fullMatch,
85 `export const Route = createFileRoute('${path}')({${routeDefinition}})`,
86 )
87 } else {
88 console.error(`No route found in the file: ${routeFile}`)
89 }
90​
91 const name = basename(path)
92 .replace('.tsx', '')
93 .replace(/^demo/, '')
94 .replace('.', ' ')
95 .trim()
96​
97 const jsName = camelCase(basename(path))
98​
99 return { url: path, code, name, jsName }
101​
102export async function validateAddOnSetup(environment: Environment) {
103 const options = await readCurrentProjectOptions(environment)
104​
105 if (options.mode === 'code-router') {
106 environment.error(
107 'This project is using code-router mode.',
108 'To create an add-on, the project must not use code-router mode.',
109 )
110 process.exit(1)
111 }
113​
114export async function readOrGenerateAddOnInfo(
115 options: PersistedOptions,
116): Promise<AddOnInfo> {
117 const info = existsSync(INFO_FILE)
118 ? JSON.parse((await readFile(INFO_FILE)).toString())
119 : ({
120 id: `${options.projectName}-add-on`,
121 name: `${options.projectName}-add-on`,
122 version: '0.0.1',
123 description: 'Add-on',
124 author: 'Jane Smith <jane.smith@example.com>',
125 license: 'MIT',
126 link: `https://github.com/jane-smith/${options.projectName}-add-on`,
127 shadcnComponents: [],
128 framework: options.framework,
129 modes: [options.mode],
130 routes: [],
131 warning: '',
132 phase: 'add-on',
133 type: 'add-on',
134 packageAdditions: {
135 scripts: {},
136 dependencies: {},
137 devDependencies: {},
138 },
139 dependsOn: options.chosenAddOns,
140 } as AddOnInfo)
141​
142 if (!info.version) {
143 info.version = '0.0.1'
144 }
145​
146 return info
148​
149export async function generateProject(persistedOptions: PersistedOptions) {
150 const info = await readOrGenerateAddOnInfo(persistedOptions)
151​
152 const output = await runCreateApp(
153 (await createAppOptionsFromPersisted(
154 persistedOptions,
155 )) as Required<Options>,
156 )
157​
158 return { info, output }
160​
161export async function buildAssetsDirectory(
162 output: {
163 files: Record<string, string>
164 },
165 info: AddOnInfo,
166) {
167 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
168 const ignore = createIgnore(process.cwd())
169​
170 if (!existsSync(assetsDir)) {
171 const changedFiles: Record<string, string> = {}
172 await compareFilesRecursively('.', ignore, output.files, changedFiles)
173​
174 for (const file of Object.keys(changedFiles).filter(
175 (file) => !ADD_ON_IGNORE_FILES.includes(basename(file)),
176 )) {
177 mkdirSync(dirname(resolve(assetsDir, file)), {
178 recursive: true,
179 })
180 if (file.includes('/routes/')) {
181 const { url, code, name, jsName } = templatize(changedFiles[file], file)
182 info.routes ||= []
183 if (!info.routes.find((r) => r.url === url)) {
184 info.routes.push({
185 url,
186 name,
187 jsName,
188 path: file,
189 })
190 }
191 writeFileSync(resolve(assetsDir, `${file}.ejs`), code)
192 } else {
193 writeFileSync(resolve(assetsDir, file), changedFiles[file])
194 }
195 }
196 }
198​
199export async function updateAddOnInfo(environment: Environment) {
200 const { info, output } = await generateProject(
201 await readCurrentProjectOptions(environment),
202 )
203​
204 info.packageAdditions = createPackageAdditions(
205 JSON.parse(output.files['./package.json']),
206 JSON.parse((await readFile('package.json')).toString()),
207 )
208​
209 await buildAssetsDirectory(output, info)
210​
211 mkdirSync(resolve(dirname(INFO_FILE)), { recursive: true })
212 writeFileSync(INFO_FILE, JSON.stringify(info, null, 2))
214​
215export async function compileAddOn(environment: Environment) {
216 const info = await readOrGenerateAddOnInfo(
217 await readCurrentProjectOptions(environment),
218 )
219​
220 const assetsDir = resolve(ADD_ON_DIR, ASSETS_DIR)
221​
222 const compiledInfo: AddOnCompiled = {
223 ...info,
224 files: await recursivelyGatherFiles(assetsDir),
225 deletedFiles: [],
226 }
227​
228 writeFileSync(COMPILED_FILE, JSON.stringify(compiledInfo, null, 2))
230​
231export async function initAddOn(environment: Environment) {
232 await validateAddOnSetup(environment)
233 await updateAddOnInfo(environment)
234 await compileAddOn(environment)
236​
237export async function devAddOn(environment: Environment) {
238 await initAddOn(environment)
239​
240 environment.info(
241 'Add-on dev mode is running.',
242 'Watching project files and recompiling add-on output on changes. Press Ctrl+C to stop.',
243 )
244​
245 const abortController = new AbortController()
246 let debounceTimeout: ReturnType<typeof setTimeout> | undefined
247​
248 const rerun = async () => {
249 try {
250 await updateAddOnInfo(environment)
251 await compileAddOn(environment)
252 environment.info('Add-on updated.', 'Compiled add-on.json and refreshed .add-on')
253 } catch (error) {
254 const message = error instanceof Error ? error.message : String(error)
255 environment.error('Failed to rebuild add-on.', message)
256 }
257 }
258​
259 process.once('SIGINT', () => {
260 abortController.abort()
261 })
262​
263 try {
264 for await (const event of watch(process.cwd(), {
265 recursive: true,
266 signal: abortController.signal,
267 })) {
268 const file = event.filename?.toString()
269 if (!file || shouldIgnoreDevPath(file)) continue
270​
271 if (debounceTimeout) {
272 clearTimeout(debounceTimeout)
273 }
274​
275 debounceTimeout = setTimeout(() => {
276 void rerun()
277 }, 200)
278 }
279 } catch (error) {
280 const message = error instanceof Error ? error.message : String(error)
281 if (!message.includes('aborted')) {
282 throw error
283 }
284 }
286​
287export async function loadRemoteAddOn(url: string): Promise<AddOn> {
288 const response = await fetch(url)
289 const jsonContent = await response.json()
290​
291 const checked = AddOnCompiledSchema.safeParse(jsonContent)
292 if (!checked.success) {
293 throw new Error(`Invalid add-on: ${url}`)
294 }
295​
296 const addOn = checked.data
297 addOn.id = url
298 const out = {
299 ...addOn,
300 getFiles: () => Promise.resolve(Object.keys(addOn.files)),
301 getFileContents: (path: string) => Promise.resolve(addOn.files[path]),
302 getDeletedFiles: () => Promise.resolve(addOn.deletedFiles),
303 }
304 return out