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
@@ -6,7 +6,7 @@ import type { BuildPluginTarget, PrunellePlugin } from '../plugins/index'
6
6
  import type { ClientTransforms } from './client-plugin'
7
7
  import type { BuildCache, ModuleGraph } from './graph'
8
8
  import type { ActionsByFile, IslandPlan } from './islands'
9
- import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync } from 'node:fs'
9
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from 'node:fs'
10
10
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
11
  import { compileSsr } from '../compiler/index'
12
12
  import { readsPrivateEnv } from '../compiler/server-only'
@@ -46,15 +46,34 @@ export function linkOrCopyFile(src: string, dst: string): void {
46
46
  }
47
47
  }
48
48
 
49
- function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[]): boolean {
49
+ const prunedClientCss = new WeakMap<BuildCache, Map<string, Uint8Array>>()
50
+
51
+ /** Keeps intermediate CSS bytes pruned by stylesheet consolidation so the next `buildClient` cache hit can restore them before consolidating again. */
52
+ export function setPrunedClientCss(cache: BuildCache | undefined, files: Map<string, Uint8Array>): void {
53
+ if (cache === undefined)
54
+ return
55
+ if (files.size > 0)
56
+ prunedClientCss.set(cache, files)
57
+ else
58
+ prunedClientCss.delete(cache)
59
+ }
60
+
61
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[], fallbackFiles?: ReadonlyMap<string, Uint8Array>): boolean {
50
62
  if (!existsSync(srcDir))
51
63
  return false
52
64
  if (relFiles !== undefined) {
53
65
  for (const rel of relFiles) {
54
66
  const from = join(srcDir, rel)
55
- if (!existsSync(from))
67
+ const to = join(dstDir, rel)
68
+ if (existsSync(from)) {
69
+ linkOrCopyFile(from, to)
70
+ continue
71
+ }
72
+ const bytes = fallbackFiles?.get(rel)
73
+ if (bytes === undefined)
56
74
  return false
57
- linkOrCopyFile(from, join(dstDir, rel))
75
+ mkdirSync(dirname(to), { recursive: true })
76
+ writeFileSync(to, bytes)
58
77
  }
59
78
  return true
60
79
  }
@@ -182,6 +201,40 @@ function publicEnvDefines(): Record<string, string> {
182
201
  }
183
202
 
184
203
 
204
+ function buildClientSignature(
205
+ env: BundleEnv,
206
+ standaloneCss: readonly string[],
207
+ pluginClientEntries: readonly string[],
208
+ regionClientEntries: readonly string[],
209
+ transformsKey: string,
210
+ strategies: ReturnType<typeof hydrateStrategies>['strategies'],
211
+ hasClientOnlyHydrate: boolean,
212
+ envDefines: Readonly<Record<string, string>>,
213
+ ): string {
214
+ if (env.cache === undefined)
215
+ return ''
216
+ return JSON.stringify({
217
+ minify: env.minify,
218
+ assetPrefix: env.assetPrefix,
219
+ isDev: env.isDev,
220
+ nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
221
+ transforms: transformsKey,
222
+ strategies,
223
+ hasClientOnlyHydrate,
224
+ pluginClientEntries,
225
+ regionClientEntries,
226
+ standaloneCss: [...standaloneCss].sort(),
227
+ islands: [...env.islands.targets.entries()]
228
+ .sort(([a], [b]) => a.localeCompare(b))
229
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
230
+ actions: [...env.actionsByFile.entries()]
231
+ .sort(([a], [b]) => a.localeCompare(b))
232
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
233
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
234
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
235
+ })
236
+ }
237
+
185
238
  export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
186
239
  const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
187
240
  const result: ClientBuild = {
@@ -199,8 +252,10 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
199
252
  const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
200
253
  const regionClientEntries = env.plugins.map(p => p.regionClientEntry).filter((e): e is string => Boolean(e))
201
254
  if (islands.targets.size === 0 && pluginClientEntries.length === 0 && regionClientEntries.length === 0 && standaloneCss.length === 0) {
202
- if (cache !== undefined)
255
+ if (cache !== undefined) {
203
256
  cache.lastClient = undefined
257
+ prunedClientCss.delete(cache)
258
+ }
204
259
  return result
205
260
  }
206
261
 
@@ -208,27 +263,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
208
263
  const { strategies, hasClientOnlyHydrate } = hydrateStrategies(graph.analyses.values())
209
264
 
210
265
  const envDefines = publicEnvDefines()
211
- const clientSignature = cache !== undefined
212
- ? JSON.stringify({
213
- minify: env.minify,
214
- assetPrefix,
215
- isDev: env.isDev,
216
- transforms: transforms.key,
217
- strategies,
218
- hasClientOnlyHydrate,
219
- pluginClientEntries,
220
- regionClientEntries,
221
- standaloneCss: [...standaloneCss].sort(),
222
- islands: [...islands.targets.entries()]
223
- .sort(([a], [b]) => a.localeCompare(b))
224
- .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
225
- actions: [...actionsByFile.entries()]
226
- .sort(([a], [b]) => a.localeCompare(b))
227
- .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
228
- envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
229
- bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
230
- })
231
- : ''
266
+ const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, regionClientEntries, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
232
267
 
233
268
  if (
234
269
  cache !== undefined
@@ -236,7 +271,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
236
271
  && cache.lastClient !== undefined
237
272
  && cache.lastClient.signature === clientSignature
238
273
  && stampsMatch(cache.lastClient.inputStamps)
239
- && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles)
274
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
240
275
  ) {
241
276
  cache.stats.clientSkips++
242
277
  cache.lastClient.clientDir = clientDir
@@ -261,7 +296,7 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
261
296
 
262
297
  const clientLeaks = new Set<string>()
263
298
  const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
264
- const plugin = clientPlugin({ root, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
299
+ const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
265
300
  const reviver = islands.targets.size > 0 ? await buildReviver(env) : undefined
266
301
 
267
302
  const clientResult = await runBunBuild('client', env.root, () => {
@@ -383,6 +418,7 @@ function rememberClientBuild(
383
418
  ): void {
384
419
  const { signature, clientDir, entriesDir, actionsByFile, graph, resolveMetaPath } = options
385
420
  cache.stats.clientBuilds++
421
+ prunedClientCss.delete(cache)
386
422
  const inputFiles = new Set<string>(options.inputFiles)
387
423
  for (const inKey of Object.keys(result.metafile?.inputs ?? {})) {
388
424
  const abs = resolveMetaPath(inKey)
@@ -428,8 +464,9 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
428
464
  return undefined
429
465
  }
430
466
  })
467
+ b.onLoad({ filter: /.*/, namespace: 'prunelle-server-css' }, () => ({ contents: '', loader: 'js' }))
431
468
  b.onResolve({ filter: /^[^./]/ }, (args) => {
432
- if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
469
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~icons/') || args.path.startsWith('virtual:') || isAbsolute(args.path))
433
470
  return undefined
434
471
  let resolved: string | undefined
435
472
  try {
@@ -443,15 +480,21 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
443
480
  return undefined
444
481
  }
445
482
  }
483
+ if (resolved.endsWith('.css'))
484
+ return resolved.endsWith('.module.css') ? { path: resolved } : { path: resolved, namespace: 'prunelle-server-css' }
446
485
  if (resolved.endsWith('.tsx') || reachesTsx(resolved))
447
486
  return { path: resolved }
448
- if (isDev && isTsFile(resolved)) {
449
- try {
450
- const real = realpathSync(resolved)
451
- if (!isInNodeModules(real))
452
- return { path: resolved }
487
+ if (isTsFile(resolved)) {
488
+ if (!isInNodeModules(resolved))
489
+ return { path: resolved }
490
+ if (isDev) {
491
+ try {
492
+ const real = realpathSync(resolved)
493
+ if (!isInNodeModules(real))
494
+ return { path: resolved }
495
+ }
496
+ catch {}
453
497
  }
454
- catch {}
455
498
  }
456
499
  if (externalOutDir)
457
500
  return { path: resolved, external: true }
@@ -540,7 +583,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
540
583
  // Island code of another module may render any component of a module it imports; in its own module, only the code an island reaches.
541
584
  const emitMarkers = islands.reach.has(args.path) || (isInteractive && analysis.browserSpans)
542
585
  let islandMap: Map<string, IslandBinding> | undefined
543
- let key = `${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
586
+ let key = `${env.isDev ? 'd:' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
544
587
  if (rawBindings !== undefined) {
545
588
  islandMap = new Map()
546
589
  for (const [localName, target] of rawBindings) {
@@ -560,6 +603,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
560
603
  islands: islandMap,
561
604
  isIsland: isInteractive,
562
605
  emitMarkers,
606
+ devSourceRoot: env.isDev ? root : undefined,
563
607
  } as Parameters<typeof compileSsr>[2])
564
608
  const code = transforms.apply(compiled.code, args.path, 'server')
565
609
  if (cache !== undefined && stamp !== undefined)
@@ -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 })
@@ -5,6 +5,7 @@ import type { ModuleAnalysis } from '../compiler/analyze'
5
5
  import { parseTsx } from '../compiler/analyze'
6
6
  import { clientReach } from '../compiler/interactivity'
7
7
  import { SourceEditor } from '../compiler/patch'
8
+ import { referencesAny } from '../compiler/scope'
8
9
  import { collectPatternNames } from '../compiler/shared'
9
10
 
10
11
  /** The top-level names the browser needs to run the islands `localNames` of a module: the bindings they reach and the imports those name. */
@@ -38,17 +39,62 @@ export function clientView(analysis: ModuleAnalysis, code: string, keep: Readonl
38
39
  }
39
40
  }
40
41
 
41
- /** `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 {
42
+ function padPreservingLines(original: string, replacement: string): string {
43
+ if (replacement === '')
44
+ return original.replace(/[^\r\n]/g, ' ')
45
+ const origNewlines = original.split('\n').length - 1
46
+ const nextNewlines = replacement.split('\n').length - 1
47
+ return origNewlines > nextNewlines ? `${replacement}${'\n'.repeat(origNewlines - nextNewlines)}` : replacement
48
+ }
49
+
50
+ /** `code` with each top-level declaration, import, re-export, and pruned-binding statement outside `keep` removed. Everything else stays. */
51
+ export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>, options?: { preserveLines?: boolean | undefined }): string {
43
52
  const editor = new SourceEditor(code)
53
+ const preserveLines = options?.preserveLines === true
54
+ const prunedNames = new Set<string>()
55
+ const planned: { stmt: Node, text: string | undefined }[] = []
44
56
  for (const stmt of program.body) {
45
57
  const text = keptText(stmt, code, keep)
46
- if (text !== undefined)
47
- editor.replace(stmt.start, stmt.end, text)
58
+ planned.push({ stmt, text })
59
+ collectPrunedNames(stmt, text, keep, prunedNames)
60
+ }
61
+ for (const { stmt, text } of planned) {
62
+ let next = text
63
+ if (next === undefined && prunedNames.size > 0 && (stmt.type === 'ExpressionStatement' || stmt.type === 'IfStatement') && referencesAny(stmt, prunedNames))
64
+ next = ''
65
+ if (next !== undefined)
66
+ editor.replace(stmt.start, stmt.end, preserveLines ? padPreservingLines(code.slice(stmt.start, stmt.end), next) : next)
48
67
  }
49
68
  return editor.toString()
50
69
  }
51
70
 
71
+ function collectPrunedNames(stmt: Node, text: string | undefined, keep: ReadonlySet<string>, out: Set<string>): void {
72
+ if (stmt.type === 'ImportDeclaration') {
73
+ if (text === undefined || stmt.importKind === 'type')
74
+ return
75
+ for (const s of stmt.specifiers) {
76
+ if (!keep.has(s.local.name) && !(s.type === 'ImportSpecifier' && s.importKind === 'type'))
77
+ out.add(s.local.name)
78
+ }
79
+ return
80
+ }
81
+ if (text !== '')
82
+ return
83
+ if (stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' || stmt.type === 'VariableDeclaration') {
84
+ for (const n of declaredNames(stmt) ?? [])
85
+ out.add(n)
86
+ }
87
+ else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null && stmt.declaration !== undefined) {
88
+ for (const n of declaredNames(stmt.declaration) ?? [])
89
+ out.add(n)
90
+ }
91
+ else if (stmt.type === 'ExportDefaultDeclaration') {
92
+ const decl = stmt.declaration
93
+ if ((decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null)
94
+ out.add(decl.id.name)
95
+ }
96
+ }
97
+
52
98
  const nameOf = (name: ModuleExportName): string => name.type === 'Identifier' ? name.name : String(name.value)
53
99
 
54
100
  function declaredNames(decl: Declaration): string[] | undefined {
@@ -100,13 +146,17 @@ function keptText(stmt: Node, code: string, keep: ReadonlySet<string>): string |
100
146
  }
101
147
 
102
148
  function keptImport(stmt: ImportDeclaration, code: string, keep: ReadonlySet<string>): string | undefined {
103
- // A type import or one with attributes stays as written; a side-effect import keeps all of its zero specifiers.
104
- if (stmt.importKind === 'type' || (stmt.attributes?.length ?? 0) > 0)
149
+ // A type import stays as written; a side-effect import keeps all of its zero specifiers.
150
+ if (stmt.importKind === 'type')
105
151
  return undefined
106
152
  // A type specifier is erased with the types, so it stays whatever uses it.
107
153
  const specs = stmt.specifiers.filter(s => keep.has(s.local.name) || (s.type === 'ImportSpecifier' && s.importKind === 'type'))
108
154
  if (specs.length === stmt.specifiers.length)
109
155
  return undefined
156
+ if (specs.length === 0)
157
+ return ''
158
+ if ((stmt.attributes?.length ?? 0) > 0)
159
+ return undefined
110
160
  const source = code.slice(stmt.source.start, stmt.source.end)
111
161
  return specs.map((s) => {
112
162
  if (s.type === 'ImportDefaultSpecifier')
@@ -15,20 +15,18 @@ export interface CompileExecutableOptions {
15
15
  manifest: BuildManifest
16
16
  assetPrefix: string
17
17
  site?: string | undefined
18
+ defaultPort?: number | undefined
18
19
  outfile: string
19
20
  resolvePrunelleSpecifier: (specifier: string) => string | undefined
20
21
  bunPlugins?: BunPlugin[] | undefined
21
22
  }
22
23
 
23
24
  export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
24
- const { root, outDir, clientDir, manifest, assetPrefix, site, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
25
+ const { root, outDir, clientDir, manifest, assetPrefix, site, defaultPort, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
25
26
  const entryPath = join(outDir, '__compile_entry.ts')
26
- const prodEnvPath = join(outDir, '__compile_prod_env.ts')
27
- // Evaluated first via ESM static import order so `prunelle.config.ts` and route modules see NODE_ENV=production!
28
- writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
29
27
  const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
30
28
  const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
31
- const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`, `import { createApp, prunelleConfig } from ${JSON.stringify(entryJs)};`, `import { handleSignals } from ${JSON.stringify(lifecycle)};`]
29
+ const imports: string[] = []
32
30
 
33
31
  // Embed client assets, public files and prerendered pages natively via `with { type: "file" }` (0 base64, 0 startup decode!), each with the sidecars the build compressed it into.
34
32
  let fileIdx = 0
@@ -72,8 +70,16 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
72
70
  }
73
71
 
74
72
  const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
73
+ const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
75
74
  const code = [
76
75
  ...imports,
76
+ `const hostname = process.env.HOST || undefined;`,
77
+ `const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
78
+ `if (Bun.argv.includes('--health')) { const healthPort = Number(process.env.PORT || ${JSON.stringify(defaultPort ?? 3000)}); const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${healthPort}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
79
+ `const _envKey = 'NODE_ENV';`,
80
+ `process.env[_envKey] ??= 'production';`,
81
+ `const { createApp, prunelleConfig } = await import(${JSON.stringify(entryJs)});`,
82
+ `const { handleSignals } = await import(${JSON.stringify(lifecycle)});`,
77
83
  `const manifest = ${JSON.stringify(manifest)};`,
78
84
  `const assets = { ${embeddedAssets.join(', ')} };`,
79
85
  `const publicAssets = { ${embeddedPublic.join(', ')} };`,
@@ -81,9 +87,6 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
81
87
  `const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
82
88
  `const prerenderedEtags = { ${embeddedPrerenderedEtags.join(', ')} };`,
83
89
  `const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
84
- `const hostname = process.env.HOST || undefined;`,
85
- `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
90
  `const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
88
91
  `const server = app.serve(port, hostname);`,
89
92
  `handleSignals(app, server);`,
@@ -122,6 +125,5 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
122
125
  }
123
126
  finally {
124
127
  rmSync(entryPath, { force: true })
125
- rmSync(prodEnvPath, { force: true })
126
128
  }
127
129
  }
@@ -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
+ }