prunelle 0.1.1 → 0.5.1

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 (88) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +3 -2
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. package/ts-plugin.cjs +4277 -0
@@ -47,7 +47,6 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
47
47
  const runtimeLines: string[] = []
48
48
  if (env.islands.targets.size > 0) {
49
49
  runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
50
- runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';`)
51
50
  runtimeLines.push(`defineIslandElement();`)
52
51
  }
53
52
  for (const pe of pluginClientEntries)
@@ -64,12 +63,14 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
64
63
 
65
64
  out.entryPoints.push(...options.standaloneCss)
66
65
 
66
+ // Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
67
+ const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
67
68
  for (const [key, target] of env.islands.targets) {
68
69
  const entryPath = join(entriesDir, `${target.id}.ts`)
69
70
  const exportStmt = target.exportName === 'default'
70
71
  ? `export { default } from ${JSON.stringify(target.file)};\n`
71
72
  : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
72
- writeEntry(entryPath, exportStmt)
73
+ writeEntry(entryPath, exportStmt + domExports)
73
74
  out.entryPoints.push(entryPath)
74
75
  out.islandEntryToKey.set(entryPath, key)
75
76
  }
@@ -24,6 +24,7 @@ export interface ClientTransforms {
24
24
 
25
25
  export interface ClientPluginEnv {
26
26
  root: string
27
+ isDev: boolean
27
28
  graph: ModuleGraph
28
29
  cache: BuildCache | undefined
29
30
  actionsByFile: ActionsByFile
@@ -114,7 +115,7 @@ export function directPrunelleImports(code: string, graph: ModuleGraph, filename
114
115
  }
115
116
 
116
117
  export function clientPlugin(env: ClientPluginEnv): BunPlugin {
117
- const { root, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
118
+ const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
118
119
  return {
119
120
  name: 'prunelle-client',
120
121
  setup(b) {
@@ -151,14 +152,17 @@ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
151
152
  const stamp = graph.stamp(args.path)
152
153
  const extraExports = localExports.get(args.path) ?? ''
153
154
  const keep = clientKeep.get(args.path)
154
- const key = `${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
155
+ const key = `${isDev ? 'd:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
155
156
  const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
156
157
  if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
157
158
  return { contents: cachedDom.code, loader: 'tsx' }
158
159
  const analysis = graph.analyses.get(args.path)
159
160
  const source = graph.source(args.path)
160
- const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep)
161
- const dom = compileDom(args.path, clientSource, clientSource === source ? { analysis } : {})
161
+ const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep, { preserveLines: isDev })
162
+ const dom = compileDom(args.path, clientSource, {
163
+ ...(clientSource === source ? { analysis } : {}),
164
+ devSourceRoot: isDev ? root : undefined,
165
+ })
162
166
  const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
163
167
  if (cache !== undefined && stamp !== undefined)
164
168
  cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })
@@ -38,13 +38,22 @@ export function clientView(analysis: ModuleAnalysis, code: string, keep: Readonl
38
38
  }
39
39
  }
40
40
 
41
+ function padPreservingLines(original: string, replacement: string): string {
42
+ if (replacement === '')
43
+ return original.replace(/[^\r\n]/g, ' ')
44
+ const origNewlines = original.split('\n').length - 1
45
+ const nextNewlines = replacement.split('\n').length - 1
46
+ return origNewlines > nextNewlines ? `${replacement}${'\n'.repeat(origNewlines - nextNewlines)}` : replacement
47
+ }
48
+
41
49
  /** `code` with each top-level declaration, import and re-export outside `keep` removed. Everything else (module-level statements, types) stays. */
42
- export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>): string {
50
+ export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>, options?: { preserveLines?: boolean | undefined }): string {
43
51
  const editor = new SourceEditor(code)
52
+ const preserveLines = options?.preserveLines === true
44
53
  for (const stmt of program.body) {
45
54
  const text = keptText(stmt, code, keep)
46
55
  if (text !== undefined)
47
- editor.replace(stmt.start, stmt.end, text)
56
+ editor.replace(stmt.start, stmt.end, preserveLines ? padPreservingLines(code.slice(stmt.start, stmt.end), text) : text)
48
57
  }
49
58
  return editor.toString()
50
59
  }
@@ -72,6 +72,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
72
72
  }
73
73
 
74
74
  const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
75
+ const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
75
76
  const code = [
76
77
  ...imports,
77
78
  `const manifest = ${JSON.stringify(manifest)};`,
@@ -83,7 +84,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
83
84
  `const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
84
85
  `const hostname = process.env.HOST || undefined;`,
85
86
  `const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
86
- `if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
87
+ `if (Bun.argv.includes('--health')) { const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${port}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
87
88
  `const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
88
89
  `const server = app.serve(port, hostname);`,
89
90
  `handleSignals(app, server);`,
@@ -0,0 +1,229 @@
1
+ // GreenIT EcoIndex score, grade (A–G), GHG emissions and water footprint for prerendered pages.
2
+
3
+ import type { Locate } from './first-load'
4
+ import type { RouteManifestEntry } from './manifest'
5
+ import { existsSync, readFileSync, statSync } from 'node:fs'
6
+ import { extname, join } from 'node:path'
7
+ import { firstLoadUrls, measureFirstLoad } from './first-load'
8
+ import { appBrotliCacheDir, brotliSync } from './precompress'
9
+
10
+ export type EcoIndexGrade = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G'
11
+
12
+ export interface EcoIndexInputs {
13
+ dom: number
14
+ requests: number
15
+ weightBytes: number
16
+ }
17
+
18
+ export interface RouteEcoIndex {
19
+ grade: EcoIndexGrade
20
+ score: number
21
+ dom: number
22
+ requests: number
23
+ weightBytes: number
24
+ ghgGrams: number
25
+ waterCl: number
26
+ url?: string | undefined
27
+ }
28
+
29
+ // Official GreenIT EcoIndex 20-quantile reference tables (DOM elements, HTTP requests, transfer size in KB).
30
+ const QUANTILES_DOM = [
31
+ 0, 47, 75, 159, 233, 298, 358, 417, 476, 537, 603,
32
+ 674, 753, 843, 949, 1076, 1237, 1459, 1801, 2479, 594601,
33
+ ] as const
34
+
35
+ const QUANTILES_REQ = [
36
+ 0, 2, 15, 25, 34, 42, 49, 56, 63, 70, 78,
37
+ 86, 95, 105, 117, 130, 147, 170, 205, 281, 3920,
38
+ ] as const
39
+
40
+ const QUANTILES_SIZE = [
41
+ 0, 1.37, 144.7, 319.53, 479.46, 631.97, 783.38, 937.91, 1098.62, 1265.47, 1448.32,
42
+ 1648.27, 1876.08, 2142.06, 2465.37, 2866.31, 3401.59, 4155.73, 5400.08, 8037.54, 223212.26,
43
+ ] as const
44
+
45
+ const RAW_CLOSE_RE: Record<string, RegExp> = {
46
+ script: /<\/script(?:\s[^>]*)?>/gi,
47
+ style: /<\/style(?:\s[^>]*)?>/gi,
48
+ textarea: /<\/textarea(?:\s[^>]*)?>/gi,
49
+ title: /<\/title(?:\s[^>]*)?>/gi,
50
+ }
51
+
52
+ const isAsciiAlpha = (c: number): boolean => (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
53
+
54
+ const isTagNameChar = (c: number): boolean =>
55
+ isAsciiAlpha(c) || (c >= 48 && c <= 57) || c === 45 || c === 95 || c === 58 || c === 46
56
+
57
+ const isTagDelimiter = (c: number): boolean =>
58
+ c === 62 || c === 47 || c === 32 || c === 9 || c === 10 || c === 13 || c === 12
59
+
60
+ function findTagEnd(html: string, start: number): number {
61
+ let quote = 0
62
+ for (let i = start; i < html.length; i++) {
63
+ const c = html.charCodeAt(i)
64
+ if (quote !== 0) {
65
+ if (c === quote)
66
+ quote = 0
67
+ }
68
+ else if (c === 34 || c === 39) {
69
+ quote = c
70
+ }
71
+ else if (c === 62) {
72
+ return i
73
+ }
74
+ }
75
+ return -1
76
+ }
77
+
78
+ function skipBangConstruct(html: string, lt: number): number {
79
+ if (html.startsWith('<!--', lt)) {
80
+ const end = html.indexOf('-->', lt + 4)
81
+ return end === -1 ? html.length : end + 3
82
+ }
83
+ if (html.startsWith('<![CDATA[', lt)) {
84
+ const end = html.indexOf(']]>', lt + 9)
85
+ return end === -1 ? html.length : end + 3
86
+ }
87
+ const end = html.indexOf('>', lt + 2)
88
+ return end === -1 ? html.length : end + 1
89
+ }
90
+
91
+ /** Counts HTML element nodes by scanning opening tags, ignoring DOCTYPE, comments, closing tags and raw text inside script/style/textarea/title. */
92
+ export function countDomElements(html: string): number {
93
+ let count = 0
94
+ let i = 0
95
+ const len = html.length
96
+ while (i < len) {
97
+ const lt = html.indexOf('<', i)
98
+ if (lt === -1)
99
+ break
100
+ const next = html.charCodeAt(lt + 1)
101
+ if (next === 33) {
102
+ i = skipBangConstruct(html, lt)
103
+ continue
104
+ }
105
+ if (next === 47 || next === 63) {
106
+ const end = html.indexOf('>', lt + 2)
107
+ i = end === -1 ? len : end + 1
108
+ continue
109
+ }
110
+ if (!isAsciiAlpha(next)) {
111
+ i = lt + 1
112
+ continue
113
+ }
114
+ let nameEnd = lt + 2
115
+ while (nameEnd < len && isTagNameChar(html.charCodeAt(nameEnd)))
116
+ nameEnd++
117
+ if (nameEnd >= len || !isTagDelimiter(html.charCodeAt(nameEnd))) {
118
+ i = lt + 1
119
+ continue
120
+ }
121
+ const tagEnd = findTagEnd(html, nameEnd)
122
+ if (tagEnd === -1)
123
+ break
124
+ count++
125
+ i = tagEnd + 1
126
+ const closeRe = RAW_CLOSE_RE[html.slice(lt + 1, nameEnd).toLowerCase()]
127
+ if (closeRe !== undefined) {
128
+ closeRe.lastIndex = i
129
+ const match = closeRe.exec(html)
130
+ i = match === null ? len : closeRe.lastIndex
131
+ }
132
+ }
133
+ return count
134
+ }
135
+
136
+ function computeQuantile(quantiles: readonly number[], value: number): number {
137
+ if (value <= quantiles[0]!)
138
+ return 0
139
+ for (let i = 1; i < quantiles.length; i++) {
140
+ const hi = quantiles[i]!
141
+ if (value < hi) {
142
+ const lo = quantiles[i - 1]!
143
+ return (i - 1) + (value - lo) / (hi - lo)
144
+ }
145
+ }
146
+ return quantiles.length - 1
147
+ }
148
+
149
+ function gradeForScore(score: number): EcoIndexGrade {
150
+ if (score > 75)
151
+ return 'A'
152
+ if (score > 65)
153
+ return 'B'
154
+ if (score > 50)
155
+ return 'C'
156
+ if (score > 35)
157
+ return 'D'
158
+ if (score > 20)
159
+ return 'E'
160
+ if (score > 5)
161
+ return 'F'
162
+ return 'G'
163
+ }
164
+
165
+ /** Computes the GreenIT EcoIndex score (0–100), grade (A–G), GHG emissions (gCO2e) and water consumption (cl) per view. */
166
+ export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'url'> {
167
+ const dom = Math.max(0, inputs.dom)
168
+ const requests = Math.max(0, inputs.requests)
169
+ const weightBytes = Math.max(0, inputs.weightBytes)
170
+ const qDom = computeQuantile(QUANTILES_DOM, dom)
171
+ const qReq = computeQuantile(QUANTILES_REQ, requests)
172
+ const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1024)
173
+ const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
174
+ const score = Math.round(Math.min(100, Math.max(0, raw)) * 10) / 10
175
+ const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
176
+ const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
177
+ return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
178
+ }
179
+
180
+ function htmlServedSize(abs: string, raw: Uint8Array): number {
181
+ const sidecar = `${abs}.br`
182
+ if (existsSync(sidecar))
183
+ return statSync(sidecar).size
184
+ const packed = brotliSync(raw, appBrotliCacheDir()).byteLength
185
+ return Math.min(packed, raw.byteLength)
186
+ }
187
+
188
+ function isWorse(candidate: Omit<RouteEcoIndex, 'url'>, current: Omit<RouteEcoIndex, 'url'>): boolean {
189
+ if (candidate.score !== current.score)
190
+ return candidate.score < current.score
191
+ if (candidate.weightBytes !== current.weightBytes)
192
+ return candidate.weightBytes > current.weightBytes
193
+ return candidate.dom > current.dom
194
+ }
195
+
196
+ /** Measures EcoIndex across a route's prerendered HTML files, returning the worst (lowest) score for multi-URL routes. */
197
+ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prerenderBaseDir: string, locate: Locate }): RouteEcoIndex | undefined {
198
+ if (route.prerendered === undefined)
199
+ return undefined
200
+ const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
201
+ let worst: Omit<RouteEcoIndex, 'url'> | undefined
202
+ let worstUrl: string | undefined
203
+ let measured = 0
204
+
205
+ for (const [url, relFile] of entries) {
206
+ const abs = join(options.prerenderBaseDir, relFile)
207
+ const ext = extname(abs).toLowerCase()
208
+ if ((ext !== '.html' && ext !== '.htm') || !existsSync(abs))
209
+ continue
210
+ const raw = readFileSync(abs)
211
+ const html = raw.toString('utf8')
212
+ const htmlBytes = htmlServedSize(abs, raw)
213
+ const load = measureFirstLoad(firstLoadUrls(html), options.locate, htmlBytes)
214
+ const eco = computeEcoIndex({
215
+ dom: countDomElements(html),
216
+ requests: 1 + load.files,
217
+ weightBytes: load.total,
218
+ })
219
+ measured++
220
+ if (worst === undefined || isWorse(eco, worst)) {
221
+ worst = eco
222
+ worstUrl = url
223
+ }
224
+ }
225
+
226
+ if (worst === undefined || worstUrl === undefined)
227
+ return undefined
228
+ return measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : worst
229
+ }
@@ -12,6 +12,8 @@ import type { BuildManifest } from './manifest'
12
12
  import type { PublicFiles } from './plugin-host'
13
13
  import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
14
  import { basename, dirname, join, relative, resolve } from 'node:path'
15
+ import { checkAppForms } from '../cli/check-forms'
16
+ import { findCachedRoutePrivateReads } from '../compiler/cacheability'
15
17
  import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
16
18
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
17
19
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
@@ -31,14 +33,16 @@ import { prerender } from './prerender'
31
33
  import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
32
34
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
33
35
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
34
- import { assertNoRouteConflicts, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
36
+ import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
35
37
  import { exportStatic } from './static'
38
+ import { findUnknownStatusPages } from './status-pages'
39
+ import { consolidateStylesheets } from './style-bundles'
36
40
 
37
41
  export type { BuildCache } from './graph'
38
42
  export { createBuildCache } from './graph'
39
- export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
40
- export { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson } from './report'
41
- export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
43
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry, StatusPageKind, StatusPageManifestEntry } from './manifest'
44
+ export { analyzeBundleWeights, checkJsBudget, computeEcoIndex, countDomElements, formatBundleReport, formatBundleReportJson } from './report'
45
+ export type { BundleReport, EcoIndexGrade, RouteBundleMetrics, RouteEcoIndex, RouteIsland } from './report'
42
46
  export { resolvePrunelleSpecifier } from './resolve'
43
47
 
44
48
  export interface BuildOptions {
@@ -56,12 +60,16 @@ export interface BuildOptions {
56
60
  analyze?: boolean | undefined
57
61
  /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
58
62
  analyzeJson?: boolean | undefined
63
+ /** Receives the computed `BundleReport` in-process without printing to stdout (used by `prunelle mcp`). */
64
+ onAnalyze?: ((report: import('./report').BundleReport) => void) | undefined
59
65
  /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
60
66
  maxJs?: number | undefined
61
67
  /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
62
68
  static?: boolean | undefined
63
69
  /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
64
70
  prerender?: boolean | undefined
71
+ /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
72
+ autoPrerender?: boolean | undefined
65
73
  /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
66
74
  copyPublic?: boolean | undefined
67
75
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
@@ -122,6 +130,7 @@ interface BuildRun {
122
130
  assetPrefix: string
123
131
  site: string | undefined
124
132
  compliance: ComplianceConfig | undefined
133
+ autoPrerender: boolean
125
134
  minify: boolean
126
135
  isDev: boolean
127
136
  nodeEnv: string | undefined
@@ -180,6 +189,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
180
189
  assetPrefix,
181
190
  site,
182
191
  compliance: fileConfig.compliance,
192
+ autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
183
193
  minify: options.minify ?? true,
184
194
  isDev,
185
195
  nodeEnv: effectiveNodeEnv,
@@ -246,6 +256,15 @@ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph,
246
256
  if (missing !== undefined)
247
257
  place(file, missing.offset, `prunelle build: ${missing.message}`)
248
258
  }
259
+ const cacheProblems = findCachedRoutePrivateReads({
260
+ graph,
261
+ pageFiles,
262
+ layoutsFor: file => ancestorFiles(routesDir, file, ['_layout.tsx']),
263
+ toRel: file => relPosix(root, file),
264
+ tool: 'prunelle build',
265
+ })
266
+ for (const problem of cacheProblems)
267
+ place(problem.file, problem.offset, problem.message)
249
268
  if (placed.length > 0)
250
269
  throw new Error(placed.join('\n\n'))
251
270
  return islands
@@ -281,6 +300,55 @@ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles:
281
300
  }
282
301
  }
283
302
 
303
+ function validateRoutesAndMatchers(root: string, routesDir: string, allRouteFiles: readonly string[], specialFiles: readonly string[], candidateFiles: readonly string[], graph: ModuleGraph): { pageFiles: string[], customMatchers: Map<string, string> } {
304
+ const unknownStatus = findUnknownStatusPages(root, allRouteFiles)
305
+ if (unknownStatus.length > 0)
306
+ throw new Error(`prunelle build: ${unknownStatus[0]!.message}`)
307
+ const routesRel = relPosix(root, routesDir)
308
+ for (const f of [...specialFiles, ...candidateFiles]) {
309
+ const analysis = graph.analyses.get(f)!
310
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
311
+ if (problem !== undefined)
312
+ throw new Error(`prunelle build: ${problem}`)
313
+ }
314
+ // A file exporting only actions stays in routes/ for its folder's middleware.
315
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
316
+ assertNoRouteConflicts(root, routesDir, pageFiles)
317
+ const { customFiles, problems } = discoverRouteMatchers({
318
+ root,
319
+ routesDir,
320
+ routeFiles: [...specialFiles, ...pageFiles],
321
+ loadAnalysis: file => graph.load(file),
322
+ })
323
+ if (problems.length > 0)
324
+ throw new Error(`prunelle build: ${problems[0]!.message}`)
325
+ return { pageFiles, customMatchers: customFiles }
326
+ }
327
+
328
+ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: string): ActionsByFile {
329
+ const actionsByFile: ActionsByFile = new Map()
330
+ for (const [file, analysis] of graph.analyses) {
331
+ if (analysis.exportedActions.length > 0) {
332
+ const rel = relPosix(root, file)
333
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
334
+ exportName,
335
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
336
+ })))
337
+ }
338
+ }
339
+ return actionsByFile
340
+ }
341
+
342
+ async function validateAppForms(root: string, routesDir: string, routeFiles: readonly string[], graph: ModuleGraph, isDev: boolean): Promise<void> {
343
+ const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph })
344
+ if (formCheck.errors.length > 0)
345
+ throw new Error(formCheck.errors.join('\n'))
346
+ if (!isDev) {
347
+ for (const warning of formCheck.warnings)
348
+ console.warn(warning)
349
+ }
350
+ }
351
+
284
352
  async function runBuild(run: BuildRun): Promise<BuildManifest> {
285
353
  const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
286
354
  const clientDir = join(outDir, 'client')
@@ -306,30 +374,12 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
306
374
  graph.load(f)
307
375
  emitBuildWarnings(run, graph, allRouteFiles)
308
376
 
309
- const routesRel = relPosix(root, routesDir)
310
- for (const f of [...specialFiles, ...candidateFiles]) {
311
- const analysis = graph.analyses.get(f)!
312
- const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
313
- if (problem !== undefined)
314
- throw new Error(`prunelle build: ${problem}`)
315
- }
316
- // A file exporting only actions stays in routes/ for its folder's middleware.
317
- const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
318
- assertNoRouteConflicts(root, routesDir, pageFiles)
319
-
320
- // Server actions, keyed by source file
321
- const actionsByFile: ActionsByFile = new Map()
322
- for (const [file, analysis] of graph.analyses) {
323
- if (analysis.exportedActions.length > 0) {
324
- const rel = relPosix(root, file)
325
- actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
326
- exportName,
327
- url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
328
- })))
329
- }
330
- }
377
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
378
+ const customMatcherFiles = [...new Set(customMatchers.values())]
331
379
 
380
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
332
381
  const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
382
+ await validateAppForms(root, routesDir, allRouteFiles, graph, isDev)
333
383
 
334
384
  mkdirSync(clientDir, { recursive: true })
335
385
  mkdirSync(serverDir, { recursive: true })
@@ -337,19 +387,21 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
337
387
  .flatMap(p => p.css ?? [])
338
388
  .map(c => resolve(root, c))
339
389
  .filter(c => existsSync(c))
340
- const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined, graph, cache: options.cache, plugins, actionsByFile, islands }
390
+ const wantsAnalyze = wantsBundleAnalysis(options)
391
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: wantsAnalyze, graph, cache: options.cache, plugins, actionsByFile, islands }
341
392
 
342
393
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
343
394
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
344
395
  // `_entry.js` imports all of these; each stays an entrypoint so its code lands in a content-named chunk that `prunelle dev` keeps loaded while it is unchanged.
345
- const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
346
- const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
396
+ const bundledModules = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...customMatcherFiles]
397
+ const serverEntries = [...bundledModules, ...(hasConfigFile ? [configSrc] : [])]
398
+ const serverRoot = standaloneActionFiles.length > 0 || customMatcherFiles.length > 0 || hasConfigFile ? root : routesDir
347
399
  const toOutRel = (srcFile: string): string =>
348
400
  relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
349
401
  const serverEntry = {
350
402
  file: join(serverRoot, SERVER_ENTRY_FILE),
351
403
  source: serverEntrySource({
352
- modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
404
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
353
405
  config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
354
406
  assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
355
407
  }),
@@ -387,7 +439,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
387
439
  }
388
440
  const builtClientAssets = new Set(assets)
389
441
 
390
- const { routes, globalStyles } = buildRouteEntries({
442
+ const { routes, statusPages, globalStyles, routeSourceFiles, globalSourceFiles } = buildRouteEntries({
391
443
  graph,
392
444
  islands,
393
445
  islandChunks: client.islandChunks,
@@ -395,10 +447,14 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
395
447
  islandCssUrl: client.islandCssUrl,
396
448
  routesDir,
397
449
  pageFiles,
450
+ specialFiles,
398
451
  pluginCssFiles,
399
- isStatic,
452
+ isStatic, autoPrerender: run.autoPrerender,
400
453
  toOutRel,
401
454
  })
455
+ const paramMatchers = customMatchers.size > 0
456
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
457
+ : undefined
402
458
 
403
459
  // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
404
460
  const outPublicDir = join(outDir, 'public')
@@ -423,6 +479,9 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
423
479
  isStatic,
424
480
  isDev,
425
481
  routes,
482
+ statusPages,
483
+ routeSourceFiles,
484
+ globalSourceFiles,
426
485
  publicFiles,
427
486
  assets,
428
487
  styleUrls: client.styleUrls,
@@ -430,6 +489,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
430
489
  })
431
490
  await host.runBuild()
432
491
  restoreCachedPluginAssets(options.cache, clientDir, assets, anyPassSkipped)
492
+ consolidateStylesheets({ clientDir, assetPrefix, minify: run.minify, routes, statusPages, globalStyles, assets, styleUrls: client.styleUrls })
433
493
  await host.precompressOutput()
434
494
 
435
495
  const manifest: BuildManifest = {
@@ -438,10 +498,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
438
498
  globalStyles,
439
499
  ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
440
500
  routes,
441
-
442
501
  ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
443
502
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
444
503
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
504
+ ...(statusPages.length > 0 ? { statusPages } : {}),
505
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
445
506
  actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
446
507
  islands: Object.fromEntries(client.islandChunks),
447
508
  assets,
@@ -450,17 +511,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
450
511
  }
451
512
  const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
452
513
  writeManifest()
453
- if (options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined) {
454
- const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, client.metafile, islandOrigins(islands, client.islandChunks, graph, root), [outPublicDir, run.publicDir])
455
- if (options.analyzeJson === true)
456
- console.log(formatBundleReportJson(report))
457
- else if (options.analyze === true)
458
- console.log(formatBundleReport(report))
459
- if (options.maxJs !== undefined)
460
- checkJsBudget(report, options.maxJs)
461
- }
514
+ const analyzeOrigins = wantsAnalyze
515
+ ? islandOrigins(islands, client.islandChunks, graph, root)
516
+ : undefined
462
517
 
463
- await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile })
518
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile, metafile: client.metafile, analyzeOrigins, outPublicDir })
464
519
  return manifest
465
520
  }
466
521
 
@@ -472,6 +527,27 @@ interface BuiltOutput {
472
527
  assets: string[]
473
528
  builtClientAssets: ReadonlySet<string>
474
529
  hasNotFoundFile: boolean
530
+ metafile: Bun.BuildOutput['metafile']
531
+ analyzeOrigins: ReturnType<typeof islandOrigins> | undefined
532
+ outPublicDir: string
533
+ }
534
+
535
+ function wantsBundleAnalysis(options: BuildOptions): boolean {
536
+ return options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined || options.onAnalyze !== undefined
537
+ }
538
+
539
+ function emitBundleAnalysis(run: BuildRun, built: BuiltOutput, clientDir: string, prerenderBaseDir: string | undefined): void {
540
+ const { options, assetPrefix } = run
541
+ if (!wantsBundleAnalysis(options))
542
+ return
543
+ const report = analyzeBundleWeights(built.manifest, clientDir, assetPrefix, built.metafile, built.analyzeOrigins, [built.outPublicDir, run.publicDir], prerenderBaseDir)
544
+ options.onAnalyze?.(report)
545
+ if (options.analyzeJson === true)
546
+ console.log(formatBundleReportJson(report))
547
+ else if (options.analyze === true)
548
+ console.log(formatBundleReport(report))
549
+ if (options.maxJs !== undefined)
550
+ checkJsBudget(report, options.maxJs)
475
551
  }
476
552
 
477
553
  /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
@@ -489,11 +565,12 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
489
565
  : undefined
490
566
 
491
567
  try {
492
- const ranAfterPrerender = await host.runAfterPrerender()
568
+ const ranAfterPrerender = await host.runAfterPrerender(isStatic ? prerenderDir : outDir)
493
569
  recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets)
494
570
  await host.precompressOutput()
495
571
  if (Object.keys(host.pluginData).length > 0)
496
572
  manifest.pluginData = host.pluginData
573
+ emitBundleAnalysis(run, built, clientDir, prerendered !== undefined ? (isStatic ? prerenderDir : outDir) : undefined)
497
574
 
498
575
  if (isStatic) {
499
576
  await exportStatic({