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

schema.ts

322 lines8.5 KB

1import path from 'node:path'
2import { z } from 'zod'
3import { configSchema, getConfig } from '@tanstack/router-plugin'
4import type { CompileStartFrameworkOptions } from './types'
5​
6const tsrConfig = configSchema
7 .omit({ autoCodeSplitting: true, target: true })
8 .partial()
9​
10// --- Import Protection Schema ---
11​
12const patternSchema = z.union([z.string(), z.instanceof(RegExp)])
13​
14const importProtectionBehaviorSchema = z.enum(['error', 'mock'])
15​
16const importProtectionEnvRulesSchema = z.object({
17 specifiers: z.array(patternSchema).optional(),
18 files: z.array(patternSchema).optional(),
19 excludeFiles: z.array(patternSchema).optional(),
20})
21​
22const importProtectionOptionsSchema = z
23 .object({
24 enabled: z.boolean().optional(),
25 behavior: z
26 .union([
27 importProtectionBehaviorSchema,
28 z.object({
29 dev: importProtectionBehaviorSchema.optional(),
30 build: importProtectionBehaviorSchema.optional(),
31 }),
32 ])
33 .optional(),
34 /**
35 * In `behavior: 'mock'`, control whether mocked imports emit a runtime
36 * console diagnostic when accessed.
37 *
38 * - 'error': console.error(new Error(...)) (default)
39 * - 'warn': console.warn(new Error(...))
40 * - 'off': disable runtime diagnostics
41 */
42 mockAccess: z.enum(['error', 'warn', 'off']).optional(),
43 onViolation: z
44 .custom<
45 (violation: unknown) => boolean | void | Promise<boolean | void>
46 >((value) => typeof value === 'function')
47 .optional(),
48 include: z.array(patternSchema).optional(),
49 exclude: z.array(patternSchema).optional(),
50 client: importProtectionEnvRulesSchema.optional(),
51 server: importProtectionEnvRulesSchema.optional(),
52 ignoreImporters: z.array(patternSchema).optional(),
53 maxTraceDepth: z.number().optional(),
54 log: z.enum(['once', 'always']).optional(),
55 })
56 .optional()
57​
58export function parseStartConfig(
59 opts: z.input<typeof tanstackStartOptionsSchema>,
60 corePluginOpts: { framework: CompileStartFrameworkOptions },
61 root: string,
62) {
63 const rawOptions = opts ?? {}
64 const rawRouterOptions = rawOptions.router ?? {}
65 const options = tanstackStartOptionsSchema.parse(opts)
66​
67 const srcDirectory = options.srcDirectory
68​
69 const routesDirectory = path.resolve(
70 root,
71 srcDirectory,
72 rawRouterOptions.routesDirectory ?? 'routes',
73 )
74​
75 const generatedRouteTree = path.resolve(
76 root,
77 srcDirectory,
78 rawRouterOptions.generatedRouteTree ?? 'routeTree.gen.ts',
79 )
80​
81 return {
82 ...options,
83 router: {
84 ...options.router,
85 ...getConfig(
86 {
87 ...options.router,
88 routesDirectory,
89 generatedRouteTree,
90 },
91 root,
92 ),
93 target: corePluginOpts.framework,
94 },
95 }
97​
98const pageSitemapOptionsSchema = z.object({
99 exclude: z.boolean().optional(),
100 priority: z.number().min(0).max(1).optional(),
101 changefreq: z
102 .enum(['always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never'])
103 .optional(),
104 lastmod: z.union([z.string(), z.date()]).optional(),
105 alternateRefs: z
106 .array(
107 z.object({
108 href: z.string(),
109 hreflang: z.string(),
110 }),
111 )
112 .optional(),
113 images: z
114 .array(
115 z.object({
116 loc: z.string(),
117 caption: z.string().optional(),
118 title: z.string().optional(),
119 }),
120 )
121 .optional(),
122 news: z
123 .object({
124 publication: z.object({
125 name: z.string(),
126 language: z.string(),
127 }),
128 publicationDate: z.union([z.string(), z.date()]),
129 title: z.string(),
130 })
131 .optional(),
132})
133​
134const pageBaseSchema = z.object({
135 path: z.string(),
136 sitemap: pageSitemapOptionsSchema.optional(),
137 fromCrawl: z.boolean().optional(),
138})
139​
140const pagePrerenderOptionsSchema = z.object({
141 enabled: z.boolean().optional(),
142 outputPath: z.string().optional(),
143 autoSubfolderIndex: z.boolean().optional(),
144 crawlLinks: z.boolean().optional(),
145 retryCount: z.number().optional(),
146 retryDelay: z.number().optional(),
147 onSuccess: z
148 .custom<
149 (result: {
150 page: z.infer<typeof pageBaseSchema>
151 html: string
152 }) => unknown
153 >((value) => typeof value === 'function')
154 .optional(),
155 headers: z.record(z.string(), z.string()).optional(),
156})
157​
158const spaSchema = z.object({
159 enabled: z.boolean().optional().default(true),
160 maskPath: z.string().optional().default('/'),
161 prerender: pagePrerenderOptionsSchema
162 .optional()
163 .prefault({})
164 .transform((opts) => ({
165 outputPath: opts.outputPath ?? '/_shell',
166 crawlLinks: false,
167 retryCount: 0,
168 ...opts,
169 enabled: true,
170 })),
171})
172​
173const inlineCssSchema = z
174 .union([
175 z.boolean(),
176 z.object({
177 /**
178 * Inline route CSS into the server-rendered HTML response.
179 *
180 * @experimental This option is experimental!
181 */
182 enabled: z.boolean().optional().default(true),
183 /**
184 * Emit build-time templates that allow `transformAssets` to rewrite
185 * `url(...)` references inside inlined CSS at runtime.
186 */
187 transformAssets: z.boolean().optional().default(false),
188 }),
189 ])
190 .optional()
191 .default(false)
192 .transform((value) => {
193 if (typeof value === 'boolean') {
194 return { enabled: value, transformAssets: false }
195 }
196​
197 return value
198 })
199​
200export type InlineCssInputOptions = z.input<typeof inlineCssSchema>
201​
202const pageSchema = pageBaseSchema.extend({
203 prerender: pagePrerenderOptionsSchema.optional(),
204})
205​
206export const tanstackStartOptionsObjectSchema = z.object({
207 srcDirectory: z.string().optional().default('src'),
208 start: z
209 .object({
210 entry: z.string().optional(),
211 })
212 .optional()
213 .prefault({}),
214 router: z
215 .object({
216 entry: z.string().optional(),
217 basepath: z.string().optional(),
218 })
219 .and(tsrConfig.optional().prefault({}))
220 .optional()
221 .prefault({}),
222 client: z
223 .object({
224 entry: z.string().optional(),
225 base: z.string().optional().default('/_build'),
226 })
227 .optional()
228 .prefault({}),
229 server: z
230 .object({
231 entry: z.string().optional(),
232 build: z
233 .object({
234 staticNodeEnv: z.boolean().optional().default(true),
235 /**
236 * Inline route CSS into the server-rendered HTML response.
237 *
238 * @experimental This option is experimental!
239 */
240 inlineCss: inlineCssSchema,
241 })
242 .optional()
243 .prefault({}),
244 })
245 .optional()
246 .prefault({}),
247 serverFns: z
248 .object({
249 base: z.string().optional().default('/_serverFn'),
250 disableCsrfMiddlewareWarning: z.boolean().optional().default(false),
251 generateFunctionId: z
252 .custom<
253 (opts: {
254 filename: string
255 functionName: string
256 }) => string | undefined
257 >((value) => typeof value === 'function')
258 .optional(),
259 })
260 .optional()
261 .prefault({}),
262 pages: z.array(pageSchema).optional().default([]),
263 sitemap: z
264 .object({
265 enabled: z.boolean().optional().default(true),
266 host: z.string().optional(),
267 outputPath: z.string().optional().default('sitemap.xml'),
268 })
269 .optional(),
270 prerender: z
271 .object({
272 enabled: z.boolean().optional(),
273 concurrency: z.number().optional(),
274 filter: z
275 .custom<
276 (page: z.infer<typeof pageSchema>) => unknown
277 >((value) => typeof value === 'function')
278 .optional(),
279 failOnError: z.boolean().optional(),
280 autoStaticPathsDiscovery: z.boolean().optional(),
281 maxRedirects: z.number().min(0).optional(),
282 })
283 .and(pagePrerenderOptionsSchema.optional())
284 .optional(),
285 dev: z
286 .object({
287 ssrStyles: z
288 .object({
289 enabled: z.boolean().optional().default(true),
290 basepath: z.string().optional(),
291 })
292 .optional()
293 .prefault({}),
294 })
295 .optional()
296 .prefault({}),
297 spa: spaSchema.optional(),
298 importProtection: importProtectionOptionsSchema,
299})
300​
301export const tanstackStartOptionsSchema = tanstackStartOptionsObjectSchema
302 .optional()
303 .prefault({})
304​
305export type Page = z.infer<typeof pageSchema>
306​
307type TanStackStartOptionsInput = NonNullable<
308 z.input<typeof tanstackStartOptionsSchema>
310​
311export type TanStackStartInputConfig = TanStackStartOptionsInput
312export type TanStackStartOutputConfig = ReturnType<typeof parseStartConfig>
313​
314export type ImportProtectionBehavior = z.infer<
315 typeof importProtectionBehaviorSchema
317export type ImportProtectionEnvRules = z.infer<
318 typeof importProtectionEnvRulesSchema
320export type ImportProtectionOptions = z.input<
321 typeof importProtectionOptionsSchema