prunelle 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -1,26 +1,100 @@
1
- // Route files: their URL patterns, conflicts, and the `_layout`/`_middleware` chain that wraps them.
1
+ // Route files: their URL patterns, groups, param matchers, conflicts, and the `_layout`/`_middleware` chain that wraps them.
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, dirname, join, relative } from 'node:path'
6
+ import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
6
7
  import { relPosix } from './files'
7
8
 
8
- export const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
9
+ export const SPECIAL_ROUTE_FILES = new Set([
10
+ '_layout.tsx',
11
+ '_middleware.ts',
12
+ '_middleware.tsx',
13
+ '_error.tsx',
14
+ '_404.tsx',
15
+ '_401.tsx',
16
+ '_403.tsx',
17
+ '_429.tsx',
18
+ '_503.tsx',
19
+ ])
9
20
  export const MIDDLEWARE_NAMES = ['_middleware.ts', '_middleware.tsx']
10
21
  const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
11
22
  const TS_EXT_RE = /\.(?:tsx|ts)$/
23
+ const ROUTE_GROUP_RE = /^\(([^/()]+)\)$/
24
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
25
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
26
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
12
27
  const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
13
28
  const PARAM_RE = /\[([^\]]+)\]/g
14
29
  const PATH_SEPARATOR_RE = /[/\\]/
15
30
 
31
+ /** True when a route folder segment is a route group such as `(marketing)` or `(admin)`. */
32
+ export function isRouteGroupSegment(segment: string): boolean {
33
+ return ROUTE_GROUP_RE.test(segment)
34
+ }
35
+
36
+ /** True when a relative POSIX directory path contains any `(group)` segment. */
37
+ export function hasRouteGroupInRel(relDir: string): boolean {
38
+ if (relDir === '' || relDir === '.')
39
+ return false
40
+ return relDir.split('/').some(isRouteGroupSegment)
41
+ }
42
+
43
+ /** Returns the `(group)` folder names wrapping `file` under `routesDir`, outermost first. */
44
+ export function routeGroupsOf(routesDir: string, file: string): string[] {
45
+ const relDir = relPosix(routesDir, dirname(file))
46
+ if (relDir === '' || relDir === '.')
47
+ return []
48
+ const groups: string[] = []
49
+ for (const part of relDir.split('/')) {
50
+ const match = ROUTE_GROUP_RE.exec(part)
51
+ if (match !== null)
52
+ groups.push(match[1]!)
53
+ }
54
+ return groups
55
+ }
56
+
57
+ /** Converts one file-system route segment (`about`, `[id=integer]`, `[[lang]]`, `[...path=slug]`) into a router pattern segment. */
58
+ export function convertRouteSegment(segment: string): string {
59
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(segment)
60
+ if (opt !== null)
61
+ return `:${opt[1]}?`
62
+ const catchAll = CATCH_ALL_SEG_RE.exec(segment)
63
+ if (catchAll !== null)
64
+ return `*${catchAll[1]}`
65
+ const param = PARAM_SEG_RE.exec(segment)
66
+ if (param !== null)
67
+ return `:${param[1]}`
68
+ return segment.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')
69
+ }
70
+
71
+ /** Converts a relative POSIX directory path under `routesDir` into a URL folder pattern, stripping `(group)` folders. */
72
+ export function dirToRoutePatternFromRel(relDir: string): string {
73
+ if (relDir === '' || relDir === '.')
74
+ return '/'
75
+ const parts = relDir.split('/').filter(p => p !== '' && !isRouteGroupSegment(p))
76
+ if (parts.length === 0)
77
+ return '/'
78
+ return `/${parts.map(convertRouteSegment).join('/')}`
79
+ }
80
+
16
81
  /** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
17
82
  export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
18
83
  return analysis.exportedNames.some(name => ROUTE_EXPORTS.has(name))
19
84
  }
20
85
 
21
- const SPECIAL_FILE_DEFAULTS = new Map([['_layout', 'layout component'], ['_middleware', 'middleware function'], ['_error', 'error page component'], ['_404', 'not-found page component']])
86
+ const SPECIAL_FILE_DEFAULTS = new Map([
87
+ ['_layout', 'layout component'],
88
+ ['_middleware', 'middleware function'],
89
+ ['_error', 'error page component'],
90
+ ['_404', 'not-found page component'],
91
+ ['_401', '401 status page component'],
92
+ ['_403', '403 status page component'],
93
+ ['_429', '429 status page component'],
94
+ ['_503', '503 status page component'],
95
+ ])
22
96
 
23
- /** For a route file or a `_layout`, `_middleware`, `_error` or `_404`, what prunelle would otherwise drop or fail on per request: neither a route nor an action, which its folder's middleware guards, or no default export. `routesRel` is the routes folder as the app writes it. */
97
+ /** For a route file or a special route file (`_layout`, `_middleware`, `_error`, `_404`, `_401`, `_403`, `_429`, `_503`), reports missing default export or non-route files. */
24
98
  export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
25
99
  const name = basename(file)
26
100
  if (SPECIAL_ROUTE_FILES.has(name))
@@ -131,21 +205,37 @@ export function assertPathUrls(urls: unknown, file: string): asserts urls is str
131
205
 
132
206
  export function fileToRoutePath(routesDir: string, file: string): string {
133
207
  const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
134
- if (rel === 'index')
208
+ const rawParts = rel.split('/')
209
+ const filePart = rawParts.pop()!
210
+ const urlParts = rawParts.filter(part => !isRouteGroupSegment(part))
211
+ if (filePart !== 'index')
212
+ urlParts.push(filePart)
213
+ if (urlParts.length === 0)
135
214
  return '/'
136
- const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
137
- return `/${clean.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')}`
215
+ return `/${urlParts.map(convertRouteSegment).join('/')}`
138
216
  }
139
217
 
140
- /** The shape two route paths conflict on: parameter names do not matter. */
218
+ /** The shape two route paths conflict on: parameter names do not matter, but optionality and matcher names do. */
141
219
  export function normalizeRoutePattern(routePath: string): string {
142
220
  return routePath
143
221
  .split('/')
144
- .map(seg => (seg.startsWith(':') ? ':' : seg.startsWith('*') ? '*' : seg))
222
+ .map((seg) => {
223
+ if (seg === '')
224
+ return ''
225
+ const parsed = parsePatternSegment(seg)
226
+ const matcher = parsed.matcherName !== undefined ? `=${parsed.matcherName}` : ''
227
+ if (parsed.kind === 'catchall')
228
+ return `*${matcher}`
229
+ if (parsed.kind === 'optional')
230
+ return `:${matcher}?`
231
+ if (parsed.kind === 'param')
232
+ return `:${matcher}`
233
+ return parsed.value
234
+ })
145
235
  .join('/')
146
236
  }
147
237
 
148
- /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, [id].tsx vs [slug].tsx). */
238
+ /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, (a)/about.tsx vs (b)/about.tsx, [id].tsx vs [slug].tsx). */
149
239
  export function assertNoRouteConflicts(root: string, routesDir: string, pageFiles: string[]): void {
150
240
  const seen = new Map<string, { file: string, path: string }>()
151
241
  for (const file of pageFiles) {
@@ -158,6 +248,77 @@ export function assertNoRouteConflicts(root: string, routesDir: string, pageFile
158
248
  }
159
249
  }
160
250
 
251
+ /** Resolves an app-defined param matcher file (`src/params/<name>.ts` or `.tsx`, or `<routesDir>/../params/<name>.ts`). */
252
+ export function findCustomMatcherFile(root: string, routesDir: string, matcherName: string): string | undefined {
253
+ const candidates = [
254
+ join(root, 'src/params', `${matcherName}.ts`),
255
+ join(root, 'src/params', `${matcherName}.tsx`),
256
+ join(dirname(routesDir), 'params', `${matcherName}.ts`),
257
+ join(dirname(routesDir), 'params', `${matcherName}.tsx`),
258
+ ]
259
+ for (const candidate of candidates) {
260
+ if (existsSync(candidate))
261
+ return candidate
262
+ }
263
+ return undefined
264
+ }
265
+
266
+ export interface MatcherDiscoveryResult {
267
+ /** Custom (non-built-in) matcher name -> absolute source file path. */
268
+ customFiles: Map<string, string>
269
+ /** Missing or invalid matcher diagnostics. */
270
+ problems: { file: string, message: string }[]
271
+ }
272
+
273
+ /** Discovers and validates every param matcher referenced by route patterns (and directory patterns of middleware/status pages). */
274
+ export function discoverRouteMatchers(options: {
275
+ root: string
276
+ routesDir: string
277
+ routeFiles: readonly string[]
278
+ loadAnalysis: (file: string) => ModuleAnalysis | undefined
279
+ }): MatcherDiscoveryResult {
280
+ const { root, routesDir, routeFiles, loadAnalysis } = options
281
+ const customFiles = new Map<string, string>()
282
+ const problems: { file: string, message: string }[] = []
283
+ const validatedCustom = new Set<string>()
284
+ const builtinList = BUILTIN_PARAM_MATCHER_NAMES.join(', ')
285
+
286
+ for (const file of routeFiles) {
287
+ const pattern = basename(file).startsWith('_')
288
+ ? dirToRoutePatternFromRel(relPosix(routesDir, dirname(file)))
289
+ : fileToRoutePath(routesDir, file)
290
+ const refs = extractPatternMatchers(pattern)
291
+ if (refs.length === 0)
292
+ continue
293
+ const rel = relPosix(root, file)
294
+ for (const { matcher } of refs) {
295
+ if (isBuiltinMatcher(matcher))
296
+ continue
297
+ const found = findCustomMatcherFile(root, routesDir, matcher)
298
+ if (found === undefined) {
299
+ problems.push({
300
+ file,
301
+ message: `unknown param matcher "${matcher}" in ${rel}: use a built-in matcher (${builtinList}) or create src/params/${matcher}.ts exporting match(value: string): boolean (or a default function).`,
302
+ })
303
+ continue
304
+ }
305
+ customFiles.set(matcher, found)
306
+ if (!validatedCustom.has(found)) {
307
+ validatedCustom.add(found)
308
+ const analysis = loadAnalysis(found)
309
+ if (analysis !== undefined && !analysis.exportedNames.includes('match') && !analysis.exportedNames.includes('default')) {
310
+ problems.push({
311
+ file: found,
312
+ message: `${relPosix(root, found)} exports no param matcher: export function match(value: string): boolean (or export default).`,
313
+ })
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ return { customFiles, problems }
320
+ }
321
+
161
322
  /** Finds all ancestor files named one of `names` from routesDir down to dirname(routeFile), outermost first. */
162
323
  export function ancestorFiles(routesDir: string, routeFile: string, names: string[]): string[] {
163
324
  const result: string[] = []
@@ -3,18 +3,21 @@
3
3
  import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { ServerEntry } from '../server/app-entry'
5
5
  import type { PrunelleApp } from '../server/index'
6
- import type { BuildManifest } from './manifest'
6
+ import type { BuildManifest, StatusPageManifestEntry } from './manifest'
7
7
  import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs'
8
8
  import { dirname, join, relative } from 'node:path'
9
9
  import { resolvePlugins } from '../plugins/index'
10
10
  import { createDocumentHooks, createHtmlHeaders } from '../server/document'
11
- import { createNavigation } from '../ssr/navigation'
12
11
  import { createFallbackPages } from '../server/errors'
13
- import { walkAllFiles } from './files'
14
- import { precompressFiles } from './precompress'
12
+ import { resolveParamMatchers } from '../server/param-matchers'
13
+ import { prerenderOrigin } from '../server/prerendered'
14
+ import { inferRoutesServerPrefix } from '../server/routing'
15
+ import { injectMetaCsp } from '../server/security'
16
+ import { createNavigation } from '../ssr/navigation'
15
17
  import { carryPreviousAssets } from './carry'
18
+ import { walkAllFiles } from './files'
16
19
  import { swapStage } from './output'
17
- import { prerenderOrigin } from '../server/prerendered'
20
+ import { precompressFiles } from './precompress'
18
21
  import { pageFailure } from './prerender'
19
22
 
20
23
  const LEADING_SLASH_RE = /^\//
@@ -48,8 +51,43 @@ function copyInto(dstRoot: string, rel: string, src: string): void {
48
51
  copyFileSync(src, dst)
49
52
  }
50
53
 
51
- async function renderStaticNotFound(options: StaticExportOptions): Promise<string> {
54
+ interface StaticNotFoundTarget {
55
+ outRel: string
56
+ urlPath: string
57
+ routeFile?: string | undefined
58
+ }
59
+
60
+ function staticNotFoundTargets(manifest: BuildManifest, hasNotFoundFile: boolean): StaticNotFoundTarget[] {
61
+ const targets: StaticNotFoundTarget[] = []
62
+ const seen = new Set<string>()
63
+ const statusPages: StatusPageManifestEntry[] = manifest.statusPages ?? []
64
+ for (const entry of statusPages) {
65
+ if (entry.kind !== '404' || entry.inGroup === true)
66
+ continue
67
+ if (entry.dirPattern.includes(':') || entry.dirPattern.includes('*'))
68
+ continue
69
+ const cleanDir = entry.dirPattern === '/' ? '' : entry.dirPattern.replace(LEADING_SLASH_RE, '')
70
+ const outRel = cleanDir === '' ? '404.html' : `${cleanDir}/404.html`
71
+ if (seen.has(outRel))
72
+ continue
73
+ seen.add(outRel)
74
+ targets.push({
75
+ outRel,
76
+ urlPath: cleanDir === '' ? '/404' : `/${cleanDir}/404`,
77
+ routeFile: entry.file,
78
+ })
79
+ }
80
+ if (hasNotFoundFile && !seen.has('404.html'))
81
+ targets.push({ outRel: '404.html', urlPath: '/404' })
82
+ return targets
83
+ }
84
+
85
+ async function emitStaticNotFoundPages(options: StaticExportOptions): Promise<void> {
86
+ const targets = staticNotFoundTargets(options.manifest, options.hasNotFoundFile)
87
+ if (targets.length === 0 || (options.entry === undefined && options.app === undefined))
88
+ return
52
89
  const origin = prerenderOrigin(options.site)
90
+
53
91
  if (options.entry !== undefined) {
54
92
  const plugins = resolvePlugins(options.pluginOverride ?? options.entry.prunelleConfig.plugins)
55
93
  const lang = options.entry.prunelleConfig.lang ?? 'en'
@@ -61,9 +99,13 @@ async function renderStaticNotFound(options: StaticExportOptions): Promise<strin
61
99
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
62
100
  const navigation = createNavigation(options.entry.prunelleConfig.navigation)
63
101
  const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
102
+ const routesPrefix = inferRoutesServerPrefix(options.manifest)
103
+ const paramMatchers = resolveParamMatchers(options.manifest.paramMatchers, options.entry.modules)
64
104
  const { buildNotFoundResponse } = createFallbackPages({
65
105
  manifest: options.manifest,
66
106
  modules: options.entry.modules,
107
+ routesPrefix,
108
+ paramMatchers,
67
109
  lang,
68
110
  alwaysLoadRuntime: plugins.some(p => Boolean(p.clientEntry)),
69
111
  navigation: navigation.html,
@@ -73,22 +115,34 @@ async function renderStaticNotFound(options: StaticExportOptions): Promise<strin
73
115
  notifyError,
74
116
  finish: res => res,
75
117
  })
76
- const url = new URL('/404', origin)
77
- const res = await buildNotFoundResponse(url, new Request(url))
78
- if (renderError !== undefined || res.status >= 500)
79
- throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, renderError)
80
- return await res.text()
118
+
119
+ for (const target of targets) {
120
+ renderError = undefined
121
+ const url = new URL(target.urlPath, origin)
122
+ const res = await buildNotFoundResponse(url, new Request(url), undefined, target.routeFile)
123
+ if (renderError !== undefined || res.status >= 500)
124
+ throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, renderError)
125
+ const outAbs = join(options.stageDir, target.outRel)
126
+ mkdirSync(dirname(outAbs), { recursive: true })
127
+ writeFileSync(outAbs, injectMetaCsp(await res.text(), res.headers.get('content-security-policy')))
128
+ }
129
+ return
130
+ }
131
+
132
+ for (const target of targets) {
133
+ const probePath = target.urlPath.replace(/\/404$/, '/__pru_404__')
134
+ const res = await options.app!.handle(new Request(`${origin}${probePath}`))
135
+ if (res.status >= 500)
136
+ throw pageFailure(`prunelle build: the _404 page "${target.outRel}" of the static export answered HTTP ${res.status}`, undefined)
137
+ const outAbs = join(options.stageDir, target.outRel)
138
+ mkdirSync(dirname(outAbs), { recursive: true })
139
+ writeFileSync(outAbs, injectMetaCsp(await res.text(), res.headers.get('content-security-policy')))
81
140
  }
82
- const res = await options.app!.handle(new Request(`${origin}/__pru_404__`))
83
- if (res.status >= 500)
84
- throw pageFailure(`prunelle build: the _404 page of the static export answered HTTP ${res.status}`, undefined)
85
- return await res.text()
86
141
  }
87
142
 
88
143
  export async function exportStatic(options: StaticExportOptions): Promise<void> {
89
144
  const { stageDir, finalOutDir, outDir, clientDir, publicFiles } = options
90
- if (options.hasNotFoundFile && (options.entry !== undefined || options.app !== undefined))
91
- writeFileSync(join(stageDir, '404.html'), await renderStaticNotFound(options))
145
+ await emitStaticNotFoundPages(options)
92
146
 
93
147
  // Client assets go to <stage>/_pru/..., public files to <stage>/...
94
148
  const assetDir = join(stageDir, options.assetPrefix.replace(LEADING_SLASH_RE, ''))
@@ -0,0 +1,127 @@
1
+ // Status and error page discovery, validation, and manifest entry construction (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`).
2
+
3
+ import { basename, dirname, relative } from 'node:path'
4
+ import { relPosix } from './files'
5
+ import { ancestorFiles, dirToRoutePatternFromRel, hasRouteGroupInRel } from './routes'
6
+
7
+ export type StatusPageKind = '401' | '403' | '404' | '429' | '503' | 'error'
8
+
9
+ export const SUPPORTED_STATUS_CODES = new Set(['401', '403', '404', '429', '503'])
10
+
11
+ export const STATUS_PAGE_FILES = new Set([
12
+ '_401.tsx',
13
+ '_403.tsx',
14
+ '_404.tsx',
15
+ '_429.tsx',
16
+ '_503.tsx',
17
+ '_error.tsx',
18
+ ])
19
+
20
+ const NUMERIC_STATUS_FILE_RE = /^_(\d{3})\.tsx$/
21
+
22
+ /** Maps a supported status/error page filename to its kind, or undefined for other files. */
23
+ export function statusPageKindOf(file: string): StatusPageKind | undefined {
24
+ const name = basename(file)
25
+ if (name === '_error.tsx')
26
+ return 'error'
27
+ const match = NUMERIC_STATUS_FILE_RE.exec(name)
28
+ if (match !== null && SUPPORTED_STATUS_CODES.has(match[1]!))
29
+ return match[1] as StatusPageKind
30
+ return undefined
31
+ }
32
+
33
+ /** Reports an unsupported `_NNN.tsx` file (e.g. `_418.tsx`, `_500.tsx`) in `routesDir`. */
34
+ export function unknownStatusPageProblem(fileRel: string): string | undefined {
35
+ const match = NUMERIC_STATUS_FILE_RE.exec(basename(fileRel))
36
+ if (match === null || SUPPORTED_STATUS_CODES.has(match[1]!))
37
+ return undefined
38
+ return `unsupported status page ${fileRel}: supported status pages are _401.tsx, _403.tsx, _404.tsx, _429.tsx, _503.tsx, and _error.tsx.`
39
+ }
40
+
41
+ export interface StatusPageManifestEntry {
42
+ kind: StatusPageKind
43
+ /** Route pattern of the folder holding this status page (`'/'`, `'/admin'`, `'/blog/:slug'`). */
44
+ dirPattern: string
45
+ /** Compiled server directory prefix holding this status page (`'server/'`, `'server/admin/'`, `'server/(admin)/'`). */
46
+ dirPrefix: string
47
+ /** True when the status page lives inside a `(group)/` folder. */
48
+ inGroup?: boolean | undefined
49
+ file: string
50
+ layouts: string[]
51
+ styles: string[]
52
+ islandChunks: string[]
53
+ eagerIslandChunks?: string[] | undefined
54
+ }
55
+
56
+ export interface FileReachLike {
57
+ chunks: ReadonlySet<string>
58
+ eager: ReadonlySet<string>
59
+ styles: ReadonlySet<string>
60
+ }
61
+
62
+ function compiledDirPrefix(outRel: string): string {
63
+ const slash = outRel.lastIndexOf('/')
64
+ return slash === -1 ? '' : outRel.slice(0, slash + 1)
65
+ }
66
+
67
+ /** Builds manifest entries for every status/error page (`_404`, `_error`, `_401`, `_403`, `_429`, `_503`) across `routesDir`. */
68
+ export function buildStatusPageEntries(options: {
69
+ routesDir: string
70
+ specialFiles: readonly string[]
71
+ globalPluginStyles: readonly string[]
72
+ reachOf: (file: string) => FileReachLike
73
+ toOutRel: (srcFile: string) => string
74
+ }): StatusPageManifestEntry[] {
75
+ const { routesDir, specialFiles, globalPluginStyles, reachOf, toOutRel } = options
76
+ const entries: StatusPageManifestEntry[] = []
77
+
78
+ for (const file of specialFiles) {
79
+ const kind = statusPageKindOf(file)
80
+ if (kind === undefined)
81
+ continue
82
+ const relDir = relative(routesDir, dirname(file)).replace(/\\/g, '/')
83
+ const dirPattern = dirToRoutePatternFromRel(relDir)
84
+ const inGroup = hasRouteGroupInRel(relDir)
85
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
86
+ const chunks = new Set<string>()
87
+ const eagerChunks = new Set<string>()
88
+ const styles = new Set<string>(globalPluginStyles)
89
+
90
+ for (const src of [...layoutSrcs, file]) {
91
+ const reach = reachOf(src)
92
+ for (const chunk of reach.chunks)
93
+ chunks.add(chunk)
94
+ for (const chunk of reach.eager)
95
+ eagerChunks.add(chunk)
96
+ for (const style of reach.styles)
97
+ styles.add(style)
98
+ }
99
+
100
+ const outRel = toOutRel(file)
101
+ entries.push({
102
+ kind,
103
+ dirPattern,
104
+ dirPrefix: compiledDirPrefix(outRel),
105
+ ...(inGroup ? { inGroup: true } : {}),
106
+ file: outRel,
107
+ layouts: layoutSrcs.map(toOutRel),
108
+ styles: [...styles],
109
+ islandChunks: [...chunks],
110
+ eagerIslandChunks: [...eagerChunks],
111
+ })
112
+ }
113
+
114
+ return entries
115
+ }
116
+
117
+ /** Finds every unsupported `_NNN.tsx` file under `routesDir` and returns its error messages. */
118
+ export function findUnknownStatusPages(root: string, routeFiles: readonly string[]): { file: string, message: string }[] {
119
+ const problems: { file: string, message: string }[] = []
120
+ for (const file of routeFiles) {
121
+ const rel = relPosix(root, file)
122
+ const message = unknownStatusPageProblem(rel)
123
+ if (message !== undefined)
124
+ problems.push({ file, message })
125
+ }
126
+ return problems
127
+ }