prunelle 0.1.1 → 0.5.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 (105) 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 +80 -36
  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 +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { AppRuntimeContext } from '../plugins/context'
4
4
  import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
- import type { RouteManifestEntry } from './manifest'
5
+ import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
6
6
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
7
  import { dirname, join } from 'node:path'
8
8
  import { precompressFiles } from './precompress'
@@ -66,6 +66,9 @@ export interface PluginHostOptions {
66
66
  isStatic: boolean
67
67
  isDev: boolean
68
68
  routes: RouteManifestEntry[]
69
+ statusPages?: StatusPageManifestEntry[] | undefined
70
+ routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
71
+ globalSourceFiles?: readonly string[] | undefined
69
72
  publicFiles: PublicFiles
70
73
  /** Client files already emitted, relative to the client dir. */
71
74
  assets: string[]
@@ -73,14 +76,88 @@ export interface PluginHostOptions {
73
76
  globalStyles: string[]
74
77
  }
75
78
 
76
- export function createPluginHost(options: PluginHostOptions) {
77
- const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
78
- const assetSet = new Set(assets)
79
+ function createStyleMutators(
80
+ styleUrls: string[],
81
+ globalStyles: string[],
82
+ routes: RouteManifestEntry[],
83
+ statusPages: StatusPageManifestEntry[],
84
+ ) {
79
85
  const styleSet = new Set(styleUrls)
80
86
  const globalStyleSet = new Set(globalStyles)
87
+ let prependedGlobalCount = 0
88
+
89
+ const addStyleUrl = (href: string): void => {
90
+ if (!styleSet.has(href)) {
91
+ styleSet.add(href)
92
+ styleUrls.push(href)
93
+ }
94
+ }
95
+
96
+ return {
97
+ addStyle(href: string) {
98
+ addStyleUrl(href)
99
+ if (!globalStyleSet.has(href)) {
100
+ globalStyleSet.add(href)
101
+ globalStyles.push(href)
102
+ }
103
+ for (const r of routes) {
104
+ if (r.styles !== undefined && !r.styles.includes(href))
105
+ r.styles.push(href)
106
+ }
107
+ for (const sp of statusPages) {
108
+ if (!sp.styles.includes(href))
109
+ sp.styles.push(href)
110
+ }
111
+ },
112
+ prependStyle(href: string) {
113
+ addStyleUrl(href)
114
+ const insertAt = prependedGlobalCount
115
+ if (!globalStyleSet.has(href)) {
116
+ globalStyleSet.add(href)
117
+ globalStyles.splice(insertAt, 0, href)
118
+ prependedGlobalCount++
119
+ }
120
+ for (const r of routes) {
121
+ if (r.styles !== undefined && !r.styles.includes(href))
122
+ r.styles.splice(Math.min(insertAt, r.styles.length), 0, href)
123
+ }
124
+ for (const sp of statusPages) {
125
+ if (!sp.styles.includes(href))
126
+ sp.styles.splice(Math.min(insertAt, sp.styles.length), 0, href)
127
+ }
128
+ },
129
+ addRouteStyle(routePath: string, href: string) {
130
+ addStyleUrl(href)
131
+ const route = routes.find(r => r.path === routePath)
132
+ if (route !== undefined) {
133
+ route.styles ??= [...globalStyles]
134
+ if (!route.styles.includes(href))
135
+ route.styles.push(href)
136
+ }
137
+ },
138
+ prependRouteStyle(routePath: string, href: string) {
139
+ addStyleUrl(href)
140
+ const route = routes.find(r => r.path === routePath)
141
+ if (route !== undefined) {
142
+ route.styles ??= [...globalStyles]
143
+ if (!route.styles.includes(href)) {
144
+ let idx = 0
145
+ while (idx < route.styles.length && globalStyleSet.has(route.styles[idx]!))
146
+ idx++
147
+ route.styles.splice(idx, 0, href)
148
+ }
149
+ }
150
+ },
151
+ }
152
+ }
153
+
154
+ export function createPluginHost(options: PluginHostOptions) {
155
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, statusPages = [], assets, styleUrls, globalStyles } = options
156
+ const assetSet = new Set(assets)
81
157
  const headTags: string[] = []
82
158
  const pluginData: Record<string, Record<string, unknown>> = {}
83
159
  const precompressed = new Set<string>()
160
+ const styles = createStyleMutators(styleUrls, globalStyles, routes, statusPages)
84
161
 
85
162
  function emitAsset(relPath: string, content: string | Uint8Array): string {
86
163
  const clean = cleanRel(relPath)
@@ -102,13 +179,6 @@ export function createPluginHost(options: PluginHostOptions) {
102
179
  return `/${clean}`
103
180
  }
104
181
 
105
- function addStyleUrl(href: string): void {
106
- if (!styleSet.has(href)) {
107
- styleSet.add(href)
108
- styleUrls.push(href)
109
- }
110
- }
111
-
112
182
  // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
183
  const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
184
  pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
@@ -131,26 +201,9 @@ export function createPluginHost(options: PluginHostOptions) {
131
201
 
132
202
  const buildCtx = {
133
203
  ...shared,
134
- addStyle(href: string) {
135
- addStyleUrl(href)
136
- if (!globalStyleSet.has(href)) {
137
- globalStyleSet.add(href)
138
- globalStyles.push(href)
139
- }
140
- for (const r of routes) {
141
- if (r.styles !== undefined && !r.styles.includes(href))
142
- r.styles.push(href)
143
- }
144
- },
145
- addRouteStyle(routePath: string, href: string) {
146
- addStyleUrl(href)
147
- const route = routes.find(r => r.path === routePath)
148
- if (route !== undefined) {
149
- route.styles ??= [...globalStyles]
150
- if (!route.styles.includes(href))
151
- route.styles.push(href)
152
- }
153
- },
204
+ ...(options.routeSourceFiles !== undefined ? { routeSourceFiles: options.routeSourceFiles } : {}),
205
+ ...(options.globalSourceFiles !== undefined ? { globalSourceFiles: options.globalSourceFiles } : {}),
206
+ ...styles,
154
207
  addHead(html: string) {
155
208
  if (html !== '')
156
209
  headTags.push(html)
@@ -176,12 +229,17 @@ export function createPluginHost(options: PluginHostOptions) {
176
229
  },
177
230
 
178
231
  /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
- async runAfterPrerender(): Promise<boolean> {
232
+ async runAfterPrerender(prerenderDir?: string): Promise<boolean> {
180
233
  let ran = false
181
234
  for (const plugin of plugins) {
182
235
  if (plugin.afterPrerender !== undefined) {
183
236
  ran = true
184
- const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
237
+ const ctx: FinalizeBuildContext = {
238
+ ...shared,
239
+ ...(prerenderDir !== undefined ? { prerenderDir } : {}),
240
+ publicFiles: options.publicFiles.files,
241
+ setData: setDataFor(plugin),
242
+ }
185
243
  await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
244
  }
187
245
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  import { availableParallelism } from 'node:os'
5
- import { dirname, extname, join } from 'node:path'
5
+ import { basename, dirname, extname, join } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
8
  import { getAppContext } from '../plugins/context'
@@ -46,9 +46,22 @@ function readEntry(file: string): Buffer | undefined {
46
46
  }
47
47
  }
48
48
 
49
+ /** Writes a self-ignoring `.gitignore` inside `.prunelle-cache/` so git never lists cached files as untracked (#39). */
50
+ export function ensureCacheGitignore(cacheRoot: string): void {
51
+ const file = join(cacheRoot, '.gitignore')
52
+ if (existsSync(file))
53
+ return
54
+ mkdirSync(cacheRoot, { recursive: true })
55
+ writeFileSync(file, '*\n')
56
+ }
57
+
49
58
  // Renamed into place, so a build running beside this one never reads half an entry.
50
59
  function writeEntry(file: string, packed: Uint8Array): void {
51
- mkdirSync(dirname(file), { recursive: true })
60
+ const dir = dirname(file)
61
+ mkdirSync(dir, { recursive: true })
62
+ const parent = dirname(dir)
63
+ if (basename(parent) === '.prunelle-cache')
64
+ ensureCacheGitignore(parent)
52
65
  const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
66
  writeFileSync(tmp, packed)
54
67
  renameSync(tmp, file)
@@ -5,7 +5,8 @@ import type { RouteManifestEntry } from './manifest'
5
5
  import { mkdirSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, extname, resolve } from 'node:path'
7
7
  import { prerenderOrigin } from '../server/prerendered'
8
- import { inlineStyleHashes } from '../server/security'
8
+ import { decodeRequestPath } from '../server/request-path'
9
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
9
10
  import { relPosix } from './files'
10
11
  import { runPluginHook } from './plugin-host'
11
12
  import { assertPathUrls } from './routes'
@@ -14,18 +15,60 @@ const CONCURRENCY = 8
14
15
  const SLASH_EDGES_RE = /^\/|\/$/g
15
16
  const TRAILING_SLASHES_RE = /\/+$/
16
17
 
18
+ const CONTENT_TYPE_EXT: Record<string, string> = {
19
+ 'application/json': '.json',
20
+ 'application/xml': '.xml',
21
+ 'text/xml': '.xml',
22
+ 'application/rss+xml': '.rss',
23
+ 'application/atom+xml': '.atom',
24
+ 'text/plain': '.txt',
25
+ 'image/svg+xml': '.svg',
26
+ 'text/calendar': '.ics',
27
+ 'text/csv': '.csv',
28
+ }
29
+
30
+ function extForContentType(contentType: string | null): string {
31
+ if (contentType === null)
32
+ return ''
33
+ const semi = contentType.indexOf(';')
34
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
35
+ return CONTENT_TYPE_EXT[mime] ?? ''
36
+ }
37
+
38
+ function assertSafePrerenderPath(raw: string, original: string): string {
39
+ const decoded = decodeRequestPath(raw)
40
+ if (decoded?.staticPath === undefined)
41
+ throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
42
+ if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
43
+ throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
44
+ return decoded.staticPath
45
+ }
17
46
 
18
47
  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
48
+ assertSafePrerenderPath(urlStr.split(/[?#]/, 1)[0] ?? '', urlStr)
49
+ let pathname: string
50
+ try {
51
+ pathname = new URL(urlStr, 'http://localhost').pathname
52
+ }
53
+ catch {
54
+ throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
55
+ }
56
+ const staticPath = assertSafePrerenderPath(pathname, urlStr)
57
+ return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
21
58
  }
22
59
 
23
- function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: boolean, contentType: string | null): string {
24
- const pathname = new URL(urlStr, 'http://localhost').pathname
60
+ function encodeUrlPath(pathname: string): string {
61
+ return pathname.split('/').map(encodeURIComponent).join('/')
62
+ }
63
+
64
+ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic: boolean, contentType: string | null): string {
25
65
  const trimmed = pathname.replace(SLASH_EDGES_RE, '')
66
+ if (trimmed.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
67
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
26
68
  const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
27
69
  const ext = extname(lastSeg).toLowerCase()
28
70
  const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
71
+ const inferredExt = !isStatic && !isHtml && ext === '' ? extForContentType(contentType) : ''
29
72
  const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
30
73
  const rel = pathname === '/'
31
74
  ? 'index.html'
@@ -33,11 +76,13 @@ function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: bo
33
76
  ? '404.html'
34
77
  : preserveFile
35
78
  ? trimmed
36
- : `${trimmed}/index.html`
79
+ : inferredExt !== ''
80
+ ? `${trimmed}${inferredExt}`
81
+ : `${trimmed}/index.html`
37
82
  const absRoot = resolve(prerenderDir)
38
83
  const abs = resolve(absRoot, rel)
39
84
  if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
40
- throw new Error(`prunelle build: prerender path "${urlStr}" escapes output directory.`)
85
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
41
86
  return abs
42
87
  }
43
88
 
@@ -79,72 +124,109 @@ export async function prerender(options: PrerenderOptions) {
79
124
  if (!pageErrors.has(request.url))
80
125
  pageErrors.set(request.url, error)
81
126
  }
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 })
127
+ 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 })
83
128
  const origin = prerenderOrigin(options.site)
84
129
  mkdirSync(prerenderDir, { recursive: true })
85
130
 
86
- for (const route of options.routes) {
87
- let urls: string[] = []
88
- let hasPathsFn = false
89
- if (!route.path.includes(':') && !route.path.includes('*')) {
90
- urls = [route.path]
91
- }
92
- else {
93
- const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
94
- if (typeof mod.paths === 'function') {
95
- hasPathsFn = true
96
- const returned: unknown = await mod.paths()
97
- assertPathUrls(returned, route.file)
98
- urls = returned
131
+ interface RenderTask {
132
+ url: string
133
+ relOut?: string | undefined
134
+ hashes?: string[] | undefined
135
+ }
136
+ const routePlans: { route: RouteManifestEntry, tasks: RenderTask[] }[] = []
137
+
138
+ try {
139
+ for (const route of options.routes) {
140
+ let urls: string[] = []
141
+ let hasPathsFn = false
142
+ if (!route.path.includes(':') && !route.path.includes('*')) {
143
+ urls = [route.path]
99
144
  }
100
145
  else {
101
- console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
146
+ const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
147
+ if (typeof mod.paths === 'function') {
148
+ hasPathsFn = true
149
+ const returned: unknown = await mod.paths()
150
+ assertPathUrls(returned, route.file)
151
+ urls = returned
152
+ }
153
+ else {
154
+ console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
155
+ }
102
156
  }
103
- }
104
157
 
105
- for (const plugin of options.plugins) {
106
- if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
107
- urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
108
- }
158
+ for (const plugin of options.plugins) {
159
+ if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
160
+ urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
161
+ }
109
162
 
110
- urls = [...new Set(urls.map(normalizePrerenderUrl))]
163
+ urls = [...new Set(urls.map(normalizePrerenderUrl))]
111
164
 
112
- if (urls.length === 0) {
113
- if (hasPathsFn)
114
- route.prerendered = {}
115
- continue
165
+ if (urls.length === 0) {
166
+ if (hasPathsFn)
167
+ route.prerendered = {}
168
+ continue
169
+ }
170
+
171
+ routePlans.push({ route, tasks: urls.map(url => ({ url })) })
116
172
  }
117
173
 
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}`)
174
+ const allTasks = routePlans.flatMap(plan => plan.tasks)
175
+ let nextIdx = 0
176
+ let failed = false
177
+ const runWorker = async (): Promise<void> => {
178
+ while (!failed) {
179
+ const idx = nextIdx++
180
+ if (idx >= allTasks.length)
181
+ return
182
+ const task = allTasks[idx]!
183
+ const u = task.url
184
+ const request = new Request(`${origin}${encodeUrlPath(u)}`)
123
185
  const res = await app.handle(request)
124
186
  const isExplicit404 = u === '/404' && res.status === 404
125
187
  if (res.status !== 200 && !isExplicit404) {
126
- if (isStatic || res.status >= 500)
188
+ if (isStatic || res.status >= 500) {
189
+ failed = true
127
190
  throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
128
- return
191
+ }
192
+ continue
129
193
  }
130
194
  const ct = res.headers.get('content-type')
131
195
  const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
132
196
  mkdirSync(dirname(absOut), { recursive: true })
133
197
  if ((ct ?? '').toLowerCase().includes('text/html')) {
134
198
  const html = await res.text()
135
- writeFileSync(absOut, html)
199
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
136
200
  const hashes = inlineStyleHashes(html)
137
201
  if (hashes.length > 0)
138
- styleHashes[u] = hashes
202
+ task.hashes = hashes
139
203
  }
140
204
  else {
141
205
  writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
142
206
  }
143
- map[u] = relPosix(isStatic ? prerenderDir : outDir, absOut)
144
- }))
207
+ task.relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
208
+ }
145
209
  }
146
- route.prerendered = map
147
- route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
210
+
211
+ const workers = Math.min(CONCURRENCY, allTasks.length)
212
+ await Promise.all(Array.from({ length: workers }, () => runWorker()))
213
+
214
+ for (const { route, tasks } of routePlans) {
215
+ const map: Record<string, string> = {}
216
+ const styleHashes: Record<string, string[]> = {}
217
+ for (const task of tasks) {
218
+ if (task.relOut !== undefined)
219
+ map[task.url] = task.relOut
220
+ if (task.hashes !== undefined)
221
+ styleHashes[task.url] = task.hashes
222
+ }
223
+ route.prerendered = map
224
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
225
+ }
226
+ }
227
+ catch (err) {
228
+ await app.dispose?.()
229
+ throw err
148
230
  }
149
- return { app, entry }
231
+ return { app, entry, errorFor: (url: string) => pageErrors.get(url) }
150
232
  }
@@ -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,34 @@ 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)`)
221
240
  for (const island of r.islands)
222
241
  lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
223
242
  }
224
243
  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.')
244
+ if (hasEco)
245
+ 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
246
  if (report.topModules.length > 0) {
226
247
  lines.push('', 'Top modules (minified output bytes):')
227
248
  for (const m of report.topModules.slice(0, 8))
@@ -1,4 +1,4 @@
1
- // Resolves an import the way prunelle build follows it: relative files, then packages through Bun's resolver; prunelle, node:, bun and ~ aliases stay unresolved.
1
+ // Resolves an import the way prunelle build follows it: relative files, then packages and tsconfig aliases through Bun's resolver; prunelle, node:, bun and virtual prefixes stay unresolved.
2
2
 
3
3
  import { statSync } from 'node:fs'
4
4
  import { dirname, join, resolve } from 'node:path'
@@ -23,28 +23,30 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
23
23
  || specifier.startsWith('node:')
24
24
  || specifier === 'bun'
25
25
  || specifier.startsWith('bun:')
26
- || specifier.startsWith('~')
26
+ || specifier.startsWith('~icons/')
27
+ || specifier.startsWith('virtual:')
27
28
  ) {
28
29
  return undefined
29
30
  }
30
31
  try {
31
32
  const resolved = Bun.resolveSync(specifier, dirname(fromFile))
32
- return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
33
+ return resolved.endsWith('.tsx') || resolved.endsWith('.ts') || resolved.endsWith('.css') ? resolved : undefined
33
34
  }
34
35
  catch {
35
36
  return undefined
36
37
  }
37
38
  }
38
39
 
40
+ const PRUNELLE_PKG_ROOT = resolve(PRUNELLE_SRC_ROOT, '..')
41
+
39
42
  const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
40
43
  Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
41
44
  subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
42
- target.replace(/^\.\/src\//, ''),
45
+ resolve(PRUNELLE_PKG_ROOT, target),
43
46
  ]),
44
47
  )
45
48
 
46
49
  /** Maps `prunelle` and its subpaths to their source file. */
47
50
  export function resolvePrunelleSpecifier(specifier: string): string | undefined {
48
- const file = PRUNELLE_SPECIFIER_FILES.get(specifier)
49
- return file === undefined ? undefined : join(PRUNELLE_SRC_ROOT, file)
51
+ return PRUNELLE_SPECIFIER_FILES.get(specifier)
50
52
  }