prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -2,10 +2,12 @@
2
2
 
3
3
  import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { RouteManifestEntry } from './manifest'
5
- import { mkdirSync, writeFileSync } from 'node:fs'
6
- import { dirname, extname, resolve } from 'node:path'
5
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { dirname, extname, join, resolve } from 'node:path'
7
+ import { FORM_TIMESTAMP_FIELD } from '../server/action-protect'
7
8
  import { prerenderOrigin } from '../server/prerendered'
8
- import { inlineStyleHashes } from '../server/security'
9
+ import { decodeRequestPath } from '../server/request-path'
10
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
9
11
  import { relPosix } from './files'
10
12
  import { runPluginHook } from './plugin-host'
11
13
  import { assertPathUrls } from './routes'
@@ -14,18 +16,60 @@ const CONCURRENCY = 8
14
16
  const SLASH_EDGES_RE = /^\/|\/$/g
15
17
  const TRAILING_SLASHES_RE = /\/+$/
16
18
 
19
+ const CONTENT_TYPE_EXT: Record<string, string> = {
20
+ 'application/json': '.json',
21
+ 'application/xml': '.xml',
22
+ 'text/xml': '.xml',
23
+ 'application/rss+xml': '.rss',
24
+ 'application/atom+xml': '.atom',
25
+ 'text/plain': '.txt',
26
+ 'image/svg+xml': '.svg',
27
+ 'text/calendar': '.ics',
28
+ 'text/csv': '.csv',
29
+ }
30
+
31
+ function extForContentType(contentType: string | null): string {
32
+ if (contentType === null)
33
+ return ''
34
+ const semi = contentType.indexOf(';')
35
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
36
+ return CONTENT_TYPE_EXT[mime] ?? ''
37
+ }
38
+
39
+ function assertSafePrerenderPath(raw: string, original: string): string {
40
+ const decoded = decodeRequestPath(raw)
41
+ if (decoded?.staticPath === undefined)
42
+ throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
43
+ if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
44
+ throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
45
+ return decoded.staticPath
46
+ }
17
47
 
18
48
  function normalizePrerenderUrl(urlStr: string): string {
19
- const pathname = new URL(urlStr, 'http://localhost').pathname
20
- return pathname.length > 1 && pathname.endsWith('/') ? (pathname.replace(TRAILING_SLASHES_RE, '') || '/') : pathname
49
+ assertSafePrerenderPath(urlStr.split(/[?#]/, 1)[0] ?? '', urlStr)
50
+ let pathname: string
51
+ try {
52
+ pathname = new URL(urlStr, 'http://localhost').pathname
53
+ }
54
+ catch {
55
+ throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
56
+ }
57
+ const staticPath = assertSafePrerenderPath(pathname, urlStr)
58
+ return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
21
59
  }
22
60
 
23
- function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: boolean, contentType: string | null): string {
24
- const pathname = new URL(urlStr, 'http://localhost').pathname
61
+ function encodeUrlPath(pathname: string): string {
62
+ return pathname.split('/').map(encodeURIComponent).join('/')
63
+ }
64
+
65
+ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic: boolean, contentType: string | null): string {
25
66
  const trimmed = pathname.replace(SLASH_EDGES_RE, '')
67
+ if (trimmed.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
68
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
26
69
  const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
27
70
  const ext = extname(lastSeg).toLowerCase()
28
71
  const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
72
+ const inferredExt = !isStatic && !isHtml && ext === '' ? extForContentType(contentType) : ''
29
73
  const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
30
74
  const rel = pathname === '/'
31
75
  ? 'index.html'
@@ -33,11 +77,13 @@ function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: bo
33
77
  ? '404.html'
34
78
  : preserveFile
35
79
  ? trimmed
36
- : `${trimmed}/index.html`
80
+ : inferredExt !== ''
81
+ ? `${trimmed}${inferredExt}`
82
+ : `${trimmed}/index.html`
37
83
  const absRoot = resolve(prerenderDir)
38
84
  const abs = resolve(absRoot, rel)
39
85
  if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
40
- throw new Error(`prunelle build: prerender path "${urlStr}" escapes output directory.`)
86
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
41
87
  return abs
42
88
  }
43
89
 
@@ -55,6 +101,17 @@ export interface PrerenderOptions {
55
101
  /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
56
102
  prerenderDir: string
57
103
  routes: RouteManifestEntry[]
104
+ /** The app's routes folder, to name a route's source file in messages. */
105
+ routesDir: string
106
+ }
107
+
108
+ const ROUTE_SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mdx', '.md']
109
+
110
+ // The source file of a built route module (`server/posts/[slug].js` is `src/routes/posts/[slug].tsx`), as messages name it.
111
+ function routeSource(options: PrerenderOptions, route: RouteManifestEntry): string {
112
+ const stem = join(options.routesDir, route.file.replace(/^server\//, '').replace(/\.js$/, ''))
113
+ const source = ROUTE_SOURCE_EXTENSIONS.map(ext => `${stem}${ext}`).find(file => existsSync(file))
114
+ return source === undefined ? route.file : relPosix(options.root, source)
58
115
  }
59
116
 
60
117
  // The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
@@ -69,20 +126,30 @@ export function pageFailure(head: string, error: unknown): Error {
69
126
  return new Error(`${head}: ${error.message}${frames}`, { cause: error })
70
127
  }
71
128
 
72
- /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
73
- export async function prerender(options: PrerenderOptions) {
74
- const { root, outDir, prerenderDir, isStatic } = options
75
- // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
76
- const { startBuiltApp } = await import('../server/loader')
77
- const pageErrors = new Map<string, unknown>()
78
- const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
79
- if (!pageErrors.has(request.url))
80
- pageErrors.set(request.url, error)
129
+ const TIMESTAMP_INPUT = `name="${FORM_TIMESTAMP_FIELD}"`
130
+
131
+ interface RenderTask {
132
+ route: RouteManifestEntry
133
+ url: string
134
+ relOut?: string | undefined
135
+ hashes?: string[] | undefined
136
+ /** The page holds a `protect.minTime` form, whose token must be signed per request. */
137
+ signsTimestamp?: boolean | undefined
138
+ }
139
+
140
+ // A route's paths(), whose throw names the route it came from.
141
+ async function namedPathsError(route: RouteManifestEntry, source: string, paths: () => Promise<string[]> | string[]): Promise<unknown> {
142
+ try {
143
+ return await paths()
81
144
  }
82
- const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true })
83
- const origin = prerenderOrigin(options.site)
84
- mkdirSync(prerenderDir, { recursive: true })
145
+ catch (error) {
146
+ throw new Error(`prunelle build: paths() of "${route.path}" (${source}) threw: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
147
+ }
148
+ }
85
149
 
150
+ /** The URLs to render for each route: its own path, or what its `paths()` and the plugins' `prerenderPaths` return. */
151
+ async function planRoutes(options: PrerenderOptions, modules: Record<string, unknown> | undefined): Promise<{ route: RouteManifestEntry, tasks: RenderTask[] }[]> {
152
+ const routePlans: { route: RouteManifestEntry, tasks: RenderTask[] }[] = []
86
153
  for (const route of options.routes) {
87
154
  let urls: string[] = []
88
155
  let hasPathsFn = false
@@ -90,15 +157,16 @@ export async function prerender(options: PrerenderOptions) {
90
157
  urls = [route.path]
91
158
  }
92
159
  else {
93
- const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
160
+ const mod = modules?.[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
94
161
  if (typeof mod.paths === 'function') {
95
162
  hasPathsFn = true
96
- const returned: unknown = await mod.paths()
97
- assertPathUrls(returned, route.file)
163
+ const source = routeSource(options, route)
164
+ const returned: unknown = await namedPathsError(route, source, mod.paths)
165
+ assertPathUrls(returned, source)
98
166
  urls = returned
99
167
  }
100
168
  else {
101
- console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
169
+ console.warn(`prunelle build${options.isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${routeSource(options, route)}) because it does not export a paths() function.`)
102
170
  }
103
171
  }
104
172
 
@@ -115,36 +183,106 @@ export async function prerender(options: PrerenderOptions) {
115
183
  continue
116
184
  }
117
185
 
118
- const map: Record<string, string> = {}
119
- const styleHashes: Record<string, string[]> = {}
120
- for (let i = 0; i < urls.length; i += CONCURRENCY) {
121
- await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
122
- const request = new Request(`${origin}${u}`)
186
+ routePlans.push({ route, tasks: urls.map(url => ({ route, url })) })
187
+ }
188
+ return routePlans
189
+ }
190
+
191
+ /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
192
+ export async function prerender(options: PrerenderOptions) {
193
+ const { root, outDir, prerenderDir, isStatic } = options
194
+ // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
195
+ const { startBuiltApp } = await import('../server/loader')
196
+ const pageErrors = new Map<string, unknown>()
197
+ const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
198
+ if (!pageErrors.has(request.url))
199
+ pageErrors.set(request.url, error)
200
+ }
201
+ const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true, static: isStatic })
202
+ const origin = prerenderOrigin(options.site)
203
+ mkdirSync(prerenderDir, { recursive: true })
204
+
205
+ try {
206
+ const routePlans = await planRoutes(options, entry?.modules)
207
+ const allTasks = routePlans.flatMap(plan => plan.tasks)
208
+ let nextIdx = 0
209
+ let failed = false
210
+ const runWorker = async (): Promise<void> => {
211
+ while (!failed) {
212
+ const idx = nextIdx++
213
+ if (idx >= allTasks.length)
214
+ return
215
+ const task = allTasks[idx]!
216
+ const u = task.url
217
+ const request = new Request(`${origin}${encodeUrlPath(u)}`)
123
218
  const res = await app.handle(request)
124
219
  const isExplicit404 = u === '/404' && res.status === 404
125
220
  if (res.status !== 200 && !isExplicit404) {
126
- if (isStatic || res.status >= 500)
221
+ if (isStatic || res.status >= 500) {
222
+ failed = true
127
223
  throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
128
- return
224
+ }
225
+ // A page prunelle chose to prerender by itself falls back to request time quietly; one the app asked for is told.
226
+ if (task.route.autoPrerender !== true) {
227
+ const isStaticRoute = !task.route.path.includes(':') && !task.route.path.includes('*')
228
+ console.warn(`prunelle build: prerender route "${u}" (${routeSource(options, task.route)}) answered HTTP ${res.status}, ${isStaticRoute ? 'so it renders at request time instead: drop `prerender = true`' : 'so it is not prerendered and answers 404 in production: leave it out of paths()'}, or have it answer 200.`)
229
+ }
230
+ continue
129
231
  }
130
232
  const ct = res.headers.get('content-type')
131
233
  const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
132
234
  mkdirSync(dirname(absOut), { recursive: true })
133
235
  if ((ct ?? '').toLowerCase().includes('text/html')) {
134
236
  const html = await res.text()
135
- writeFileSync(absOut, html)
237
+ if (html.includes(TIMESTAMP_INPUT)) {
238
+ if (task.route.autoPrerender === true) {
239
+ task.signsTimestamp = true
240
+ continue
241
+ }
242
+ failed = true
243
+ throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused 24 h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
244
+ }
245
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
136
246
  const hashes = inlineStyleHashes(html)
137
247
  if (hashes.length > 0)
138
- styleHashes[u] = hashes
248
+ task.hashes = hashes
139
249
  }
140
250
  else {
141
251
  writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
142
252
  }
143
- map[u] = relPosix(isStatic ? prerenderDir : outDir, absOut)
144
- }))
253
+ task.relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
254
+ }
145
255
  }
146
- route.prerendered = map
147
- route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
256
+
257
+ const workers = Math.min(CONCURRENCY, allTasks.length)
258
+ await Promise.all(Array.from({ length: workers }, () => runWorker()))
259
+
260
+ for (const { route, tasks } of routePlans) {
261
+ if (tasks.some(task => task.signsTimestamp === true)) {
262
+ // A protect.minTime form signs its timestamp on each request: the whole route renders at request time.
263
+ for (const task of tasks) {
264
+ if (task.relOut !== undefined)
265
+ rmSync(join(outDir, task.relOut), { force: true })
266
+ }
267
+ route.prerender = false
268
+ route.autoPrerender = undefined
269
+ continue
270
+ }
271
+ const map: Record<string, string> = {}
272
+ const styleHashes: Record<string, string[]> = {}
273
+ for (const task of tasks) {
274
+ if (task.relOut !== undefined)
275
+ map[task.url] = task.relOut
276
+ if (task.hashes !== undefined)
277
+ styleHashes[task.url] = task.hashes
278
+ }
279
+ route.prerendered = map
280
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
281
+ }
282
+ }
283
+ catch (err) {
284
+ await app.dispose?.()
285
+ throw err
148
286
  }
149
- return { app, entry }
287
+ return { app, entry, errorFor: (url: string) => pageErrors.get(url) }
150
288
  }
@@ -0,0 +1,200 @@
1
+ // What a page reaches through its imports and the islands it renders: island chunks, stylesheets, files, render-context and region use.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import type { ModuleGraph } from './graph'
5
+ import type { IslandPlan, IslandTarget } from './islands'
6
+ import { islandKey } from './islands'
7
+
8
+ const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
9
+
10
+ interface ModuleEdge {
11
+ source: string
12
+ specifiers?: readonly { local: string, imported: string }[] | undefined
13
+ start: number
14
+ }
15
+
16
+ function orderedEdges(analysis: ModuleAnalysis): readonly ModuleEdge[] {
17
+ const reexports = analysis.reexports
18
+ if (reexports === undefined || reexports.length === 0)
19
+ return analysis.imports
20
+ return [...analysis.imports, ...reexports].sort((a, b) => a.start - b.start)
21
+ }
22
+
23
+ function edgeBindings(edge: ModuleEdge, bindings: ReadonlyMap<string, IslandTarget> | undefined): IslandTarget[] {
24
+ if (bindings === undefined || edge.specifiers === undefined)
25
+ return []
26
+ const matched: IslandTarget[] = []
27
+ for (const spec of edge.specifiers) {
28
+ if (spec.imported === '*') {
29
+ const prefix = `${spec.local}.`
30
+ for (const [tag, target] of bindings) {
31
+ if (tag.startsWith(prefix))
32
+ matched.push(target)
33
+ }
34
+ }
35
+ else {
36
+ const target = bindings.get(spec.local)
37
+ if (target !== undefined)
38
+ matched.push(target)
39
+ }
40
+ }
41
+ return matched
42
+ }
43
+
44
+ export interface FileReach {
45
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
46
+ chunks: Set<string>
47
+ eager: Set<string>
48
+ styles: Set<string>
49
+ /** All reachable source files (`.ts`/`.tsx`) walked from this file. */
50
+ files: Set<string>
51
+ usesRenderContext: boolean
52
+ usesRegion: boolean
53
+ }
54
+
55
+ // How far a visit reaches. Level 0 follows imports, stopping at an island that renders nothing static (its imports ship inside it): island chunks.
56
+ // Level 1 follows every import: render-context and region use. Level 2 also follows the islands a module renders: files and styles.
57
+ // Each level reaches a superset of the one before, so a visit at a level also counts for the levels after it.
58
+ const ISLANDS = 0
59
+ const IMPORTS = 1
60
+ const RENDERED = 2
61
+
62
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it, in one pass per page. */
63
+ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
64
+ const { analyses } = graph
65
+ const depsMemo = new Map<string, string[]>()
66
+ const depsOf = (file: string): string[] => {
67
+ let deps = depsMemo.get(file)
68
+ if (deps === undefined) {
69
+ deps = graph.localDeps(file)
70
+ depsMemo.set(file, deps)
71
+ }
72
+ return deps
73
+ }
74
+
75
+ /** Adds the island chunks of a file reached at level 0; true when its imports ship inside the island and the level stops there. */
76
+ function addIslandChunks(file: string, isRoot: boolean, analysis: ModuleAnalysis, reach: FileReach): boolean {
77
+ if (analysis.isInteractive) {
78
+ if (isRoot) {
79
+ const chunk = islandChunks.get(`${file}#default`)
80
+ if (chunk !== undefined) {
81
+ reach.chunks.add(chunk)
82
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
83
+ reach.eager.add(chunk)
84
+ }
85
+ }
86
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
87
+ if (analysis.staticJsxTags.size === 0)
88
+ return true
89
+ }
90
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
91
+ const chunk = islandChunks.get(islandKey(target))
92
+ if (chunk === undefined)
93
+ continue
94
+ reach.chunks.add(chunk)
95
+ const isDeferred = analysis.deferredIslandTags.has(localName)
96
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
97
+ if (!isDeferred)
98
+ reach.eager.add(chunk)
99
+ }
100
+ return false
101
+ }
102
+
103
+ function walk(root: string): FileReach {
104
+ const reach: FileReach = { chunks: new Set(), eager: new Set(), styles: new Set(), files: new Set(), usesRenderContext: false, usesRegion: false }
105
+ const seen = [new Set<string>(), new Set<string>(), new Set<string>()]
106
+
107
+ function visit(file: string, level: number): void {
108
+ const atIslands = level === ISLANDS && !seen[ISLANDS]!.has(file)
109
+ const atImports = level <= IMPORTS && !seen[IMPORTS]!.has(file)
110
+ const atRendered = !seen[RENDERED]!.has(file)
111
+ if (!atIslands && !atImports && !atRendered)
112
+ return
113
+ if (atIslands)
114
+ seen[ISLANDS]!.add(file)
115
+ if (atImports)
116
+ seen[IMPORTS]!.add(file)
117
+ if (atRendered)
118
+ seen[RENDERED]!.add(file)
119
+ const analysis = analyses.get(file)
120
+ if (atRendered)
121
+ reach.files.add(file)
122
+ if (analysis === undefined)
123
+ return
124
+
125
+ let pruned = false
126
+ if (atIslands)
127
+ pruned = addIslandChunks(file, file === root, analysis, reach)
128
+ if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
129
+ reach.usesRenderContext = true
130
+ if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
131
+ reach.usesRegion = true
132
+
133
+ // The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
134
+ const next = atIslands ? (pruned ? IMPORTS : ISLANDS) : atImports ? IMPORTS : RENDERED
135
+ const deps = depsOf(file)
136
+ if (!atRendered) {
137
+ for (const dep of deps)
138
+ visit(dep, next)
139
+ return
140
+ }
141
+
142
+ const depSet = new Set(deps)
143
+ const visitedDeps = new Set<string>()
144
+ const bindings = islands.pageBindings.get(file)
145
+ const visitedBindings = new Set<IslandTarget>()
146
+ const addTargetStyle = (target: IslandTarget): void => {
147
+ if (visitedBindings.has(target))
148
+ return
149
+ visitedBindings.add(target)
150
+ visit(target.file, RENDERED)
151
+ const islCss = islandCssUrl.get(islandKey(target))
152
+ if (islCss !== undefined)
153
+ reach.styles.add(islCss)
154
+ }
155
+
156
+ // Walk imports and re-exports in source order so dependency CSS lands before the importer's CSS (#159).
157
+ for (const edge of orderedEdges(analysis)) {
158
+ const resolved = graph.resolve(file, edge.source)
159
+ if (resolved === undefined)
160
+ continue
161
+ const cssUrl = srcCssToUrl.get(resolved)
162
+ if (cssUrl !== undefined) {
163
+ reach.styles.add(cssUrl)
164
+ continue
165
+ }
166
+ if (depSet.has(resolved)) {
167
+ visitedDeps.add(resolved)
168
+ visit(resolved, next)
169
+ }
170
+ for (const target of edgeBindings(edge, bindings))
171
+ addTargetStyle(target)
172
+ }
173
+ for (const dep of deps) {
174
+ if (!visitedDeps.has(dep))
175
+ visit(dep, next)
176
+ }
177
+ for (const target of bindings?.values() ?? [])
178
+ addTargetStyle(target)
179
+ if (file === root && analysis.isInteractive) {
180
+ const islCss = islandCssUrl.get(`${file}#default`)
181
+ if (islCss !== undefined)
182
+ reach.styles.add(islCss)
183
+ }
184
+ }
185
+
186
+ visit(root, ISLANDS)
187
+ return reach
188
+ }
189
+
190
+ // Layouts are shared by many routes, so each file is walked once.
191
+ const memo = new Map<string, FileReach>()
192
+ return (file: string): FileReach => {
193
+ let reach = memo.get(file)
194
+ if (reach === undefined) {
195
+ reach = walk(file)
196
+ memo.set(file, reach)
197
+ }
198
+ return reach
199
+ }
200
+ }
@@ -6,7 +6,7 @@ import type { IslandPlan, StaticTag } from './islands'
6
6
  import { isInNodeModules } from './files'
7
7
  import { visitorKeys } from 'oxc-parser'
8
8
  import { walk } from '../compiler/ast'
9
- import { mistake } from '../compiler/mistakes'
9
+ import { hydrateMistake } from '../compiler/mistakes'
10
10
  import { collectPatternNames, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
11
11
 
12
12
  const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
@@ -126,7 +126,7 @@ function staticTagProblems(element: Extract<Node, { type: 'JSXOpeningElement' }>
126
126
  continue
127
127
  const attrName = attr.name.name
128
128
  if (attrName === '$hydrate')
129
- problems.push({ offset: attr.start, message: mistake(`$hydrate on <${tag}>`, rel, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`).message })
129
+ problems.push({ offset: attr.start, message: hydrateMistake(tag, rel, true).message })
130
130
  else if (found !== undefined && EVENT_PROP_RE.test(attrName) && isFunctionValue(attr, isLocalFn))
131
131
  problems.push({ offset: attr.start, message: `${command}: cannot pass event handler "${attrName}" to <${tag}>, which is not an island: the server renders it as HTML, so the handler never runs. Write the handler inside <${tag}>, or render <${tag}> from an island.` })
132
132
  }
@@ -1,13 +1,18 @@
1
1
  // The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
2
2
 
3
+ import type { EcoIndexGrade, RouteEcoIndex } from './ecoindex'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
5
6
  import type { BuildManifest } from './manifest'
6
7
  import { existsSync, readFileSync } from 'node:fs'
7
8
  import { join, posix } from 'node:path'
9
+ import { computeEcoIndex, countDomElements, measureRouteEcoIndex } from './ecoindex'
8
10
  import { relPosix } from './files'
9
11
  import { distLocator, firstLoadUrls, measureFirstLoad, STATIC_CHUNK_IMPORT_RE } from './first-load'
10
12
 
13
+ export type { EcoIndexGrade, RouteEcoIndex }
14
+ export { computeEcoIndex, countDomElements }
15
+
11
16
  export interface IslandOrigin {
12
17
  /** The component's export name, `default` for a page or a default export. */
13
18
  name: string
@@ -35,6 +40,8 @@ export interface RouteBundleMetrics {
35
40
  /** Everything a first visit fetches except the HTML (CSS, eager JS and its imports, fonts, images, icons), brotli. */
36
41
  firstLoad: number
37
42
  islands: RouteIsland[]
43
+ /** GreenIT EcoIndex score and footprint measured on prerendered HTML output (worst URL for dynamic routes). */
44
+ ecoIndex?: RouteEcoIndex | undefined
38
45
  }
39
46
 
40
47
  export interface BundleReport {
@@ -65,6 +72,7 @@ export function analyzeBundleWeights(
65
72
  metafile?: Bun.BuildOutput['metafile'],
66
73
  origins = new Map<string, IslandOrigin>(),
67
74
  publicDirs: readonly string[] = [],
75
+ prerenderBaseDir?: string | undefined,
68
76
  ): BundleReport {
69
77
  const locate = distLocator({ clientDir, assetPrefix, publicDirs })
70
78
  const prefix = `${assetPrefix.replace(/\/$/, '')}/`
@@ -166,6 +174,9 @@ export function analyzeBundleWeights(
166
174
 
167
175
  const headUrls = firstLoadUrls([...manifest.headTags ?? [], ...r.headTags ?? []].join(''))
168
176
  const load = measureFirstLoad([...cssList, ...eagerJsRoots, ...headUrls], locate)
177
+ const ecoIndex = prerenderBaseDir !== undefined
178
+ ? measureRouteEcoIndex(r, { prerenderBaseDir, locate })
179
+ : undefined
169
180
 
170
181
  return {
171
182
  path: r.path,
@@ -178,6 +189,7 @@ export function analyzeBundleWeights(
178
189
  jsFiles: jsSet.size,
179
190
  cssFiles: cssList.length,
180
191
  islands,
192
+ ...(ecoIndex !== undefined ? { ecoIndex } : {}),
181
193
  }
182
194
  })
183
195
 
@@ -203,25 +215,36 @@ const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
203
215
  const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
204
216
 
205
217
  export function formatBundleReport(report: BundleReport): string {
218
+ const hasEco = report.routes.some(r => r.ecoIndex !== undefined)
206
219
  const lines = [
207
220
  '\n=== PRUNELLE BUNDLE WEIGHT REPORT ===',
208
221
  `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
209
222
  '',
210
- 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10),
223
+ 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10) + (hasEco ? 'EcoIndex'.padStart(12) : ''),
211
224
  ]
212
225
  for (const r of report.routes) {
226
+ const ecoCell = hasEco
227
+ ? (r.ecoIndex !== undefined ? `${r.ecoIndex.grade} (${Math.round(r.ecoIndex.score)})` : '-').padStart(12)
228
+ : ''
213
229
  lines.push(
214
230
  r.path.padEnd(28)
215
231
  + kb(r.jsGzip).padStart(16)
216
232
  + kb(r.cssGzip).padStart(14)
217
233
  + kb(r.fonts).padStart(14)
218
234
  + kb(r.firstLoad).padStart(18)
219
- + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
235
+ + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10)
236
+ + ecoCell,
220
237
  )
238
+ if (r.ecoIndex?.url !== undefined)
239
+ lines.push(` worst page: ${r.ecoIndex.url} (${r.ecoIndex.dom} DOM, ${r.ecoIndex.requests} req, ${kb(r.ecoIndex.weightBytes)} br, ${r.ecoIndex.ghgGrams} gCO2e)`)
240
+ if (r.ecoIndex?.external !== undefined)
241
+ lines.push(` ${r.ecoIndex.external} third-party request${r.ecoIndex.external === 1 ? '' : 's'} counted in the EcoIndex but not weighed${r.ecoIndex.url === undefined ? '' : ` (on ${r.ecoIndex.url})`}`)
221
242
  for (const island of r.islands)
222
243
  lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
223
244
  }
224
245
  lines.push('', 'First load is what a first visit downloads besides the page\'s HTML: CSS, eager JS and its imports, fonts, images and icons, brotli.')
246
+ if (hasEco)
247
+ lines.push('EcoIndex (A–G, 0–100) scores prerendered pages from DOM elements, first-visit requests and brotli transfer weight, with estimated gCO2e and water per view.')
225
248
  if (report.topModules.length > 0) {
226
249
  lines.push('', 'Top modules (minified output bytes):')
227
250
  for (const m of report.topModules.slice(0, 8))
@@ -234,8 +257,10 @@ export function formatBundleReportJson(report: BundleReport): string {
234
257
  return JSON.stringify(report, null, 2)
235
258
  }
236
259
 
237
- /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
238
- export function checkJsBudget(report: BundleReport, maxBytes: number): void {
260
+ const routeCount = (n: number): string => (n === 1 ? 'one route' : `${n} routes`)
261
+
262
+ /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page; `source` is the setting that set it. */
263
+ export function checkJsBudget(report: BundleReport, maxBytes: number, source = '--max-js'): void {
239
264
  const over = report.routes.filter(r => r.jsGzip > maxBytes)
240
265
  if (over.length === 0)
241
266
  return
@@ -243,5 +268,23 @@ export function checkJsBudget(report: BundleReport, maxBytes: number): void {
243
268
  const eager = r.islands.filter(island => island.eager).map(islandLine)
244
269
  return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the prunelle runtime alone'}`
245
270
  })
246
- throw new Error(`prunelle build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
271
+ throw new Error(`prunelle build: eager JS over ${source} ${kb(maxBytes)} (gzip) on ${routeCount(over.length)}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise ${source}.`)
272
+ }
273
+
274
+ /** What a route's first visit downloads: its stylesheets, scripts and fonts, or, on a prerendered page, the heaviest page with its HTML and images. */
275
+ export const routeFirstLoad = (r: RouteBundleMetrics): number => Math.max(r.firstLoad, r.ecoIndex?.weightBytes ?? 0, r.ecoIndex?.heaviest?.bytes ?? 0)
276
+
277
+ /** Throws naming each route whose first load, brotli, is over `budget.firstLoad`. */
278
+ export function checkFirstLoadBudget(report: BundleReport, maxBytes: number): void {
279
+ const over = report.routes.filter(r => routeFirstLoad(r) > maxBytes)
280
+ if (over.length === 0)
281
+ return
282
+ const lines = over.map((r) => {
283
+ const bytes = routeFirstLoad(r)
284
+ const target = r.ecoIndex?.heaviest !== undefined && r.ecoIndex.heaviest.bytes >= r.firstLoad
285
+ ? r.ecoIndex.heaviest.url
286
+ : r.ecoIndex?.url ?? r.path
287
+ return ` ${target} downloads ${kb(bytes)} on a first visit`
288
+ })
289
+ throw new Error(`prunelle build: first load over budget.firstLoad ${kb(maxBytes)} (brotli) on ${routeCount(over.length)}:\n${lines.join('\n')}\nResize or compress the heaviest images with @prunellejs/images, subset the fonts, defer islands, or raise budget.firstLoad in prunelle.config.ts.`)
247
290
  }