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

config.ts

236 lines6.9 KB

1import path from 'node:path'
2import { existsSync, readFileSync } from 'node:fs'
3import { z } from 'zod'
4import { virtualRootRouteSchema } from './filesystem/virtual/config'
5import type { GeneratorPlugin } from './plugin/types'
6​
7const tokenJsonRegexSchema = z.object({
8 regex: z.string(),
9 flags: z.string().optional(),
10})
11​
12const tokenMatcherSchema = z.union([
13 z.string(),
14 z.instanceof(RegExp),
15 tokenJsonRegexSchema,
16])
17​
18export type TokenMatcherJson = string | z.infer<typeof tokenJsonRegexSchema>
19​
20export type TokenMatcher = z.infer<typeof tokenMatcherSchema>
21​
22export const baseConfigSchema = z.object({
23 target: z.enum(['react', 'solid', 'vue']).optional().default('react'),
24 virtualRouteConfig: virtualRootRouteSchema.or(z.string()).optional(),
25 routeFilePrefix: z.string().optional(),
26 routeFileIgnorePrefix: z.string().optional().default('-'),
27 routeFileIgnorePattern: z.string().optional(),
28 routesDirectory: z.string().optional().default('./src/routes'),
29 quoteStyle: z.enum(['single', 'double']).optional().default('single'),
30 semicolons: z.boolean().optional().default(false),
31 disableLogging: z.boolean().optional().default(false),
32 routeTreeFileHeader: z
33 .array(z.string())
34 .optional()
35 .default([
36 '/* eslint-disable */',
37 '// @ts-nocheck',
38 '// noinspection JSUnusedGlobalSymbols',
39 ]),
40 indexToken: tokenMatcherSchema.optional().default('index'),
41 routeToken: tokenMatcherSchema.optional().default('route'),
42 pathParamsAllowedCharacters: z
43 .array(z.enum([';', ':', '@', '&', '=', '+', '$', ',']))
44 .optional(),
45})
46​
47export type BaseConfig = z.infer<typeof baseConfigSchema>
48​
49export const configSchema = baseConfigSchema.extend({
50 generatedRouteTree: z.string().optional().default('./src/routeTree.gen.ts'),
51 disableTypes: z.boolean().optional().default(false),
52 addExtensions: z
53 .union([z.boolean(), z.string()])
54 .optional()
55 .default(false)
56 .transform((v) =>
57 typeof v === 'string' ? (v.startsWith('.') ? v : `.${v}`) : v,
58 ),
59 enableRouteTreeFormatting: z.boolean().optional().default(true),
60 routeTreeFileFooter: z
61 .union([
62 z.array(z.string()).optional().default([]),
63 z.custom<() => Array<string>>((value) => typeof value === 'function'),
64 ])
65 .optional(),
66 autoCodeSplitting: z.boolean().optional(),
67 customScaffolding: z
68 .object({
69 routeTemplate: z.string().optional(),
70 lazyRouteTemplate: z.string().optional(),
71 })
72 .optional(),
73 experimental: z
74 .object({
75 // TODO: This has been made stable and is now "autoCodeSplitting". Remove in next major version.
76 enableCodeSplitting: z.boolean().optional(),
77 })
78 .optional(),
79 plugins: z.array(z.custom<GeneratorPlugin>()).optional(),
80 tmpDir: z.string().optional().default(''),
81 importRoutesUsingAbsolutePaths: z.boolean().optional().default(false),
82})
83​
84export type Config = z.infer<typeof configSchema>
85​
86type ResolveParams = {
87 configDirectory: string
89​
90export function resolveConfigPath({ configDirectory }: ResolveParams) {
91 return path.resolve(configDirectory, 'tsr.config.json')
93​
94export function getConfig(
95 inlineConfig: Partial<Config> = {},
96 configDirectory?: string,
97): Config {
98 if (configDirectory === undefined) {
99 configDirectory = process.cwd()
100 }
101 const configFilePathJson = resolveConfigPath({ configDirectory })
102 const exists = existsSync(configFilePathJson)
103​
104 let config: Config
105​
106 if (exists) {
107 // Parse file config (allows JSON regex-object form)
108 const fileConfigRaw = JSON.parse(readFileSync(configFilePathJson, 'utf-8'))
109​
110 // Merge raw configs (inline overrides file), then parse once to apply defaults
111 // This ensures file config values aren't overwritten by inline defaults
112 const merged = {
113 ...fileConfigRaw,
114 ...inlineConfig,
115 }
116 config = configSchema.parse(merged)
117 } else {
118 config = configSchema.parse(inlineConfig)
119 }
120​
121 // If typescript is disabled, make sure the generated route tree is a .js file
122 if (config.disableTypes) {
123 config.generatedRouteTree = config.generatedRouteTree.replace(
124 /\.(ts|tsx)$/,
125 '.js',
126 )
127 }
128​
129 // if a configDirectory is used, paths should be relative to that directory
130 if (configDirectory) {
131 // if absolute configDirectory is provided, use it as the root
132 if (path.isAbsolute(configDirectory)) {
133 config.routesDirectory = path.resolve(
134 configDirectory,
135 config.routesDirectory,
136 )
137 config.generatedRouteTree = path.resolve(
138 configDirectory,
139 config.generatedRouteTree,
140 )
141 } else {
142 config.routesDirectory = path.resolve(
143 process.cwd(),
144 configDirectory,
145 config.routesDirectory,
146 )
147 config.generatedRouteTree = path.resolve(
148 process.cwd(),
149 configDirectory,
150 config.generatedRouteTree,
151 )
152 }
153 }
154​
155 const resolveTmpDir = (dir: string | Array<string>) => {
156 if (Array.isArray(dir)) {
157 dir = path.join(...dir)
158 }
159 if (!path.isAbsolute(dir)) {
160 dir = path.resolve(process.cwd(), dir)
161 }
162 return dir
163 }
164​
165 if (config.tmpDir) {
166 config.tmpDir = resolveTmpDir(config.tmpDir)
167 } else if (process.env.TSR_TMP_DIR) {
168 config.tmpDir = resolveTmpDir(process.env.TSR_TMP_DIR)
169 } else {
170 config.tmpDir = resolveTmpDir(['.tanstack', 'tmp'])
171 }
172​
173 validateConfig(config)
174 return config
176​
177function validateConfig(config: Config) {
178 if (typeof config.experimental?.enableCodeSplitting !== 'undefined') {
179 const message = `
180------
181⚠️ ⚠️ ⚠️
182ERROR: The "experimental.enableCodeSplitting" flag has been made stable and is now "autoCodeSplitting". Please update your configuration file to use "autoCodeSplitting" instead of "experimental.enableCodeSplitting".
183------
185 console.error(message)
186 throw new Error(message)
187 }
188​
189 // Check that indexToken and routeToken are not identical
190 // Works for strings, RegExp, and JSON regex objects
191 if (areTokensEqual(config.indexToken, config.routeToken)) {
192 throw new Error(
193 `The "indexToken" and "routeToken" options must be different.`,
194 )
195 }
196​
197 if (
198 config.routeFileIgnorePrefix &&
199 config.routeFileIgnorePrefix.trim() === '_'
200 ) {
201 throw new Error(
202 `The "routeFileIgnorePrefix" cannot be an underscore ("_"). This is a reserved character used to denote a pathless route. Please use a different prefix.`,
203 )
204 }
205​
206 return config
208​
209/**
210 * Compares two token matchers for equality.
211 * Handles strings, RegExp instances, and JSON regex objects.
212 */
213function areTokensEqual(a: TokenMatcher, b: TokenMatcher): boolean {
214 // Both strings
215 if (typeof a === 'string' && typeof b === 'string') {
216 return a === b
217 }
218​
219 // Both RegExp instances
220 if (a instanceof RegExp && b instanceof RegExp) {
221 return a.source === b.source && a.flags === b.flags
222 }
223​
224 // Both JSON regex objects
225 if (
226 typeof a === 'object' &&
227 'regex' in a &&
228 typeof b === 'object' &&
229 'regex' in b
230 ) {
231 return a.regex === b.regex && (a.flags ?? '') === (b.flags ?? '')
232 }
233​
234 // Mixed types - not equal
235 return false