prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) 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 +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  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 +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -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 +610 -0
  36. package/src/cli/check-imports.ts +25 -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 +107 -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 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -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);`,
@@ -105,7 +108,8 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
105
108
  try {
106
109
  res = await Bun.build({
107
110
  entrypoints: [entryPath],
108
- compile: { outfile },
111
+ // The host passes the environment: a .env or bunfig.toml (with its preload) in whatever cwd the binary starts in is not the app's.
112
+ compile: { outfile, autoloadDotenv: false, autoloadBunfig: false },
109
113
  minify: true,
110
114
  plugins: [prunelleResolvePlugin, ...bunPlugins],
111
115
  })
@@ -122,6 +126,5 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
122
126
  }
123
127
  finally {
124
128
  rmSync(entryPath, { force: true })
125
- rmSync(prodEnvPath, { force: true })
126
129
  }
127
130
  }
@@ -0,0 +1,230 @@
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
+ /** Third-party requests, counted in `requests` but not in `weightBytes`. */
27
+ external?: number | undefined
28
+ url?: string | undefined
29
+ }
30
+
31
+ // The EcoIndex as computed by its reference implementation, cnumr/ecoindex_python at 8833bb3 (components/ecoindex/compute/ecoindex.py, data/quantiles.py, data/grades.py): 20-quantile tables of DOM elements, HTTP requests and transfer size in KB of 1000.
32
+ const QUANTILES_DOM = [
33
+ 0, 47, 75, 159, 233, 298, 358, 417, 476, 537, 603,
34
+ 674, 753, 843, 949, 1076, 1237, 1459, 1801, 2479, 594601,
35
+ ] as const
36
+
37
+ const QUANTILES_REQ = [
38
+ 0, 2, 15, 25, 34, 42, 49, 56, 63, 70, 78,
39
+ 86, 95, 105, 117, 130, 147, 170, 205, 281, 3920,
40
+ ] as const
41
+
42
+ const QUANTILES_SIZE = [
43
+ 0, 1.37, 144.7, 319.53, 479.46, 631.97, 783.38, 937.91, 1098.62, 1265.47, 1448.32,
44
+ 1648.27, 1876.08, 2142.06, 2465.37, 2866.31, 3401.59, 4155.73, 5400.08, 8037.54, 223212.26,
45
+ ] as const
46
+
47
+ const RAW_CLOSE_RE: Record<string, RegExp> = {
48
+ script: /<\/script(?:\s[^>]*)?>/gi,
49
+ style: /<\/style(?:\s[^>]*)?>/gi,
50
+ textarea: /<\/textarea(?:\s[^>]*)?>/gi,
51
+ title: /<\/title(?:\s[^>]*)?>/gi,
52
+ }
53
+
54
+ const isAsciiAlpha = (c: number): boolean => (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
55
+
56
+ const isTagNameChar = (c: number): boolean =>
57
+ isAsciiAlpha(c) || (c >= 48 && c <= 57) || c === 45 || c === 95 || c === 58 || c === 46
58
+
59
+ const isTagDelimiter = (c: number): boolean =>
60
+ c === 62 || c === 47 || c === 32 || c === 9 || c === 10 || c === 13 || c === 12
61
+
62
+ function findTagEnd(html: string, start: number): number {
63
+ let quote = 0
64
+ for (let i = start; i < html.length; i++) {
65
+ const c = html.charCodeAt(i)
66
+ if (quote !== 0) {
67
+ if (c === quote)
68
+ quote = 0
69
+ }
70
+ else if (c === 34 || c === 39) {
71
+ quote = c
72
+ }
73
+ else if (c === 62) {
74
+ return i
75
+ }
76
+ }
77
+ return -1
78
+ }
79
+
80
+ function skipBangConstruct(html: string, lt: number): number {
81
+ if (html.startsWith('<!--', lt)) {
82
+ const end = html.indexOf('-->', lt + 4)
83
+ return end === -1 ? html.length : end + 3
84
+ }
85
+ if (html.startsWith('<![CDATA[', lt)) {
86
+ const end = html.indexOf(']]>', lt + 9)
87
+ return end === -1 ? html.length : end + 3
88
+ }
89
+ const end = html.indexOf('>', lt + 2)
90
+ return end === -1 ? html.length : end + 1
91
+ }
92
+
93
+ /** Counts HTML element nodes by scanning opening tags, ignoring DOCTYPE, comments, closing tags and raw text inside script/style/textarea/title. */
94
+ export function countDomElements(html: string): number {
95
+ let count = 0
96
+ let i = 0
97
+ const len = html.length
98
+ while (i < len) {
99
+ const lt = html.indexOf('<', i)
100
+ if (lt === -1)
101
+ break
102
+ const next = html.charCodeAt(lt + 1)
103
+ if (next === 33) {
104
+ i = skipBangConstruct(html, lt)
105
+ continue
106
+ }
107
+ if (next === 47 || next === 63) {
108
+ const end = html.indexOf('>', lt + 2)
109
+ i = end === -1 ? len : end + 1
110
+ continue
111
+ }
112
+ if (!isAsciiAlpha(next)) {
113
+ i = lt + 1
114
+ continue
115
+ }
116
+ let nameEnd = lt + 2
117
+ while (nameEnd < len && isTagNameChar(html.charCodeAt(nameEnd)))
118
+ nameEnd++
119
+ if (nameEnd >= len || !isTagDelimiter(html.charCodeAt(nameEnd))) {
120
+ i = lt + 1
121
+ continue
122
+ }
123
+ const tagEnd = findTagEnd(html, nameEnd)
124
+ if (tagEnd === -1)
125
+ break
126
+ count++
127
+ i = tagEnd + 1
128
+ const closeRe = RAW_CLOSE_RE[html.slice(lt + 1, nameEnd).toLowerCase()]
129
+ if (closeRe !== undefined) {
130
+ closeRe.lastIndex = i
131
+ const match = closeRe.exec(html)
132
+ i = match === null ? len : closeRe.lastIndex
133
+ }
134
+ }
135
+ return count
136
+ }
137
+
138
+ function computeQuantile(quantiles: readonly number[], value: number): number {
139
+ if (value <= quantiles[0]!)
140
+ return 0
141
+ for (let i = 1; i < quantiles.length; i++) {
142
+ const hi = quantiles[i]!
143
+ if (value < hi) {
144
+ const lo = quantiles[i - 1]!
145
+ return (i - 1) + (value - lo) / (hi - lo)
146
+ }
147
+ }
148
+ return quantiles.length - 1
149
+ }
150
+
151
+ function gradeForScore(score: number): EcoIndexGrade {
152
+ if (score > 80)
153
+ return 'A'
154
+ if (score > 70)
155
+ return 'B'
156
+ if (score > 55)
157
+ return 'C'
158
+ if (score > 40)
159
+ return 'D'
160
+ if (score > 25)
161
+ return 'E'
162
+ if (score > 10)
163
+ return 'F'
164
+ return 'G'
165
+ }
166
+
167
+ /** Computes the GreenIT EcoIndex score (0–100), grade (A–G), GHG emissions (gCO2e) and water consumption (cl) per view. */
168
+ export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'url'> {
169
+ const dom = Math.max(0, inputs.dom)
170
+ const requests = Math.max(0, inputs.requests)
171
+ const weightBytes = Math.max(0, inputs.weightBytes)
172
+ const qDom = computeQuantile(QUANTILES_DOM, dom)
173
+ const qReq = computeQuantile(QUANTILES_REQ, requests)
174
+ const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1000)
175
+ const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
176
+ const score = Math.round(Math.min(100, Math.max(0, raw)))
177
+ const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
178
+ const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
179
+ return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
180
+ }
181
+
182
+ function htmlServedSize(abs: string, raw: Uint8Array): number {
183
+ const sidecar = `${abs}.br`
184
+ if (existsSync(sidecar))
185
+ return statSync(sidecar).size
186
+ const packed = brotliSync(raw, appBrotliCacheDir()).byteLength
187
+ return Math.min(packed, raw.byteLength)
188
+ }
189
+
190
+ function isWorse(candidate: Omit<RouteEcoIndex, 'url'>, current: Omit<RouteEcoIndex, 'url'>): boolean {
191
+ if (candidate.score !== current.score)
192
+ return candidate.score < current.score
193
+ if (candidate.weightBytes !== current.weightBytes)
194
+ return candidate.weightBytes > current.weightBytes
195
+ return candidate.dom > current.dom
196
+ }
197
+
198
+ /** Measures EcoIndex across a route's prerendered HTML files, returning the worst (lowest) score for multi-URL routes. */
199
+ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prerenderBaseDir: string, locate: Locate }): RouteEcoIndex | undefined {
200
+ if (route.prerendered === undefined)
201
+ return undefined
202
+ const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
203
+ let worst: Omit<RouteEcoIndex, 'url'> | undefined
204
+ let worstUrl: string | undefined
205
+ let measured = 0
206
+
207
+ for (const [url, relFile] of entries) {
208
+ const abs = join(options.prerenderBaseDir, relFile)
209
+ const ext = extname(abs).toLowerCase()
210
+ if ((ext !== '.html' && ext !== '.htm') || !existsSync(abs))
211
+ continue
212
+ const raw = readFileSync(abs)
213
+ const html = raw.toString('utf8')
214
+ const htmlBytes = htmlServedSize(abs, raw)
215
+ const load = measureFirstLoad(firstLoadUrls(html), options.locate, htmlBytes)
216
+ const eco = {
217
+ ...computeEcoIndex({ dom: countDomElements(html), requests: 1 + load.files + load.external, weightBytes: load.total }),
218
+ ...(load.external > 0 ? { external: load.external } : {}),
219
+ }
220
+ measured++
221
+ if (worst === undefined || isWorse(eco, worst)) {
222
+ worst = eco
223
+ worstUrl = url
224
+ }
225
+ }
226
+
227
+ if (worst === undefined || worstUrl === undefined)
228
+ return undefined
229
+ return measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : worst
230
+ }
@@ -154,3 +154,9 @@ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): str
154
154
  return msg
155
155
  }).join('\n')
156
156
  }
157
+
158
+ /** Whether a `public/` path holds a dotfile or dot folder (`.env`, `.DS_Store`, `.git/`) other than under `.well-known`: the build leaves those out. */
159
+ export function isHiddenPublicPath(rel: string): boolean {
160
+ const segments = rel.split(/[\\/]/).filter(s => s !== '')
161
+ return segments.some((s, i) => s.startsWith('.') && !(i === 0 && s === '.well-known'))
162
+ }
@@ -1,4 +1,4 @@
1
- // What a first visit downloads, as served: the page, the files it links, and the files those pull in (a script's static imports, a stylesheet's `url()`s), each counted once. The docs footer and `prunelle build --analyze` both measure with this.
1
+ // What a visit scrolled to the bottom downloads, as served (the EcoIndex measures so): the page, the files it links, and the files those pull in (a script's static imports, a stylesheet's `url()`s), each counted once. The docs footer and `prunelle build --analyze` both measure with this.
2
2
 
3
3
  import { existsSync, readFileSync, statSync } from 'node:fs'
4
4
  import { extname, join, posix } from 'node:path'
@@ -7,12 +7,17 @@ import { appBrotliCacheDir, brotliSync } from './precompress'
7
7
  // A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
8
8
  export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
9
9
 
10
- const TAG_RE = /<(img|script|link)\b[^>]*>/g
10
+ const TAG_RE = /<(\/?)(img|script|link|source|picture|video|audio|iframe)\b[^>]*>/g
11
11
  const SRC_RE = /\bsrc="([^"]+)"/
12
+ const SRCSET_RE = /\bsrcset="([^"]+)"/
13
+ const POSTER_RE = /\bposter="([^"]+)"/
12
14
  const HREF_RE = /\bhref="([^"]+)"/
13
15
  const REL_RE = /\brel="([^"]+)"/
14
16
  const TYPE_RE = /\btype="([^"]+)"/
15
- const LAZY_RE = /\bloading="lazy"/
17
+ const AUTOPLAY_RE = /\bautoplay\b/
18
+ const PRELOAD_AUTO_RE = /\bpreload(?:="auto"|="")?(?=[\s/>])/
19
+ const SRCSET_WIDTH_RE = /\s(\d+(?:\.\d+)?)[wx]$/
20
+ const THIRD_PARTY_RE = /^(?:https?:)?\/\//i
16
21
  const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
17
22
  const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
18
23
  const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
@@ -35,17 +40,80 @@ export interface FirstLoad {
35
40
  cached: number
36
41
  /** Files counted besides the page. */
37
42
  files: number
43
+ /** Third-party URLs the page fetches: requests whose size the build cannot know. */
44
+ external: number
38
45
  }
39
46
 
40
47
  /** Turns a URL the page links into the file that serves it, or `undefined` when no file does. */
41
48
  export type Locate = (url: string) => string | undefined
42
49
 
43
- /** The URLs a browser fetches from this markup: stylesheets, preloads, scripts, one icon, and images that are not lazy. */
50
+ /** The widest candidate of a `srcset`: the EcoIndex measures at 1920x1080, where a browser takes the large one. */
51
+ function widestCandidate(srcset: string): string | undefined {
52
+ let best: string | undefined
53
+ let bestSize = -1
54
+ for (const candidate of srcset.split(',')) {
55
+ const text = candidate.trim()
56
+ const size = Number(SRCSET_WIDTH_RE.exec(text)?.[1] ?? 1)
57
+ if (text !== '' && size > bestSize) {
58
+ best = text.split(/\s/)[0]
59
+ bestSize = size
60
+ }
61
+ }
62
+ return best
63
+ }
64
+
65
+ const imageUrl = (element: string): string | undefined => {
66
+ const srcset = SRCSET_RE.exec(element)?.[1]
67
+ return (srcset === undefined ? undefined : widestCandidate(srcset)) ?? SRC_RE.exec(element)?.[1]
68
+ }
69
+
70
+ /** The URLs a browser fetches from this markup once scrolled to the bottom, as the EcoIndex measures: stylesheets, preloads, scripts, one icon, every image (a `<picture>`'s first source, a `srcset`'s widest candidate), frames, posters, and the media that autoplays or preloads. */
44
71
  export function firstLoadUrls(html: string): string[] {
45
72
  const urls = new Set<string>()
46
73
  const icons: string[] = []
47
74
  let svgIcon: string | undefined
48
- for (const [element, name] of html.matchAll(TAG_RE)) {
75
+ // Inside a <picture>, or a <video>/<audio> that fetches its media: whether the source a browser takes was found.
76
+ let picture: { taken: boolean } | undefined
77
+ let media: { fetches: boolean, taken: boolean } | undefined
78
+ const add = (url: string | undefined): void => {
79
+ if (url !== undefined)
80
+ urls.add(url)
81
+ }
82
+ for (const [element, closing, name] of html.matchAll(TAG_RE)) {
83
+ if (closing === '/') {
84
+ if (name === 'picture')
85
+ picture = undefined
86
+ else if (name === 'video' || name === 'audio')
87
+ media = undefined
88
+ continue
89
+ }
90
+ if (name === 'picture') {
91
+ picture = { taken: false }
92
+ continue
93
+ }
94
+ if (name === 'video' || name === 'audio') {
95
+ const fetches = AUTOPLAY_RE.test(element) || PRELOAD_AUTO_RE.test(element)
96
+ add(POSTER_RE.exec(element)?.[1])
97
+ const src = SRC_RE.exec(element)?.[1]
98
+ media = { fetches, taken: src !== undefined }
99
+ if (fetches)
100
+ add(src)
101
+ continue
102
+ }
103
+ if (name === 'source') {
104
+ const slot = media ?? picture
105
+ if (slot === undefined || slot.taken)
106
+ continue
107
+ slot.taken = true
108
+ if (media === undefined || media.fetches)
109
+ add(media === undefined ? imageUrl(element) : SRC_RE.exec(element)?.[1])
110
+ continue
111
+ }
112
+ if (name === 'img') {
113
+ if (picture?.taken !== true)
114
+ add(imageUrl(element))
115
+ continue
116
+ }
49
117
  if (name === 'link') {
50
118
  const url = HREF_RE.exec(element)?.[1]
51
119
  const relation = REL_RE.exec(element)?.[1] ?? ''
@@ -60,9 +128,7 @@ export function firstLoadUrls(html: string): string[] {
60
128
  }
61
129
  continue
62
130
  }
63
- const url = SRC_RE.exec(element)?.[1]
64
- if (url !== undefined && !LAZY_RE.test(element))
65
- urls.add(url)
131
+ add(SRC_RE.exec(element)?.[1])
66
132
  }
67
133
  // A browser that draws SVG icons fetches that one alone; the others are for browsers that do not.
68
134
  for (const icon of svgIcon === undefined ? icons : [svgIcon])
@@ -117,7 +183,7 @@ function cssUrls(css: string): string[] {
117
183
  urls.push(match[2]!)
118
184
  for (const match of rest.matchAll(CSS_IMPORT_RE))
119
185
  urls.push(match[1]!)
120
- return urls.filter(url => !SKIPPED_URL_RE.test(url))
186
+ return urls.filter(url => THIRD_PARTY_RE.test(url) || !SKIPPED_URL_RE.test(url))
121
187
  }
122
188
 
123
189
  /** What a file pulls in beside itself: a script's static imports and a stylesheet's `url()`s, as URLs. */
@@ -128,16 +194,22 @@ function dependenciesOf(url: string, file: string): string[] {
128
194
  const text = readFileSync(file, 'utf8')
129
195
  const base = posix.dirname(url.split(/[?#]/)[0]!)
130
196
  const raw = ext === '.js' ? [...text.matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => m[1]!) : cssUrls(text)
131
- return raw.map(dep => (dep.startsWith('/') ? dep : posix.join(base, dep)))
197
+ return raw.map(dep => (dep.startsWith('/') || THIRD_PARTY_RE.test(dep) ? dep : posix.join(base, dep)))
132
198
  }
133
199
 
134
200
  /** Adds up what a first visit fetches from these root URLs and what they pull in; `htmlBytes` is the page itself, brotli; `cacheable` names the URLs served for long caching (prunelle's hashed assets). */
135
201
  export function measureFirstLoad(roots: Iterable<string>, locate: Locate, htmlBytes = 0, cacheable: (url: string) => boolean = () => false): FirstLoad {
136
- const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0 }
202
+ const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0, external: 0 }
137
203
  const seen = new Set<string>()
138
204
  const stack = [...roots]
139
205
  while (stack.length > 0) {
140
206
  const url = stack.pop()!
207
+ if (THIRD_PARTY_RE.test(url)) {
208
+ if (!seen.has(url))
209
+ result.external++
210
+ seen.add(url)
211
+ continue
212
+ }
141
213
  const file = locate(url)
142
214
  if (file === undefined || seen.has(file))
143
215
  continue
@@ -2,10 +2,13 @@
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
4
  import { existsSync, readFileSync, statSync } from 'node:fs'
5
+ import { parseTsx } from '../compiler/analyze'
6
+ import { computeJsxNodes } from '../compiler/ast'
5
7
  import { analyzeModule } from '../compiler/index'
6
8
  import { PrunelleMistake } from '../compiler/mistakes'
7
9
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
8
10
  import { isTsFile, relPosix } from './files'
11
+ import { resolveExportTarget } from './island-promote'
9
12
  import { resolveImportPath } from './resolve'
10
13
 
11
14
  export interface FileStamp {
@@ -41,8 +44,28 @@ export interface BuildCacheStats {
41
44
  serverSkips: number
42
45
  }
43
46
 
47
+ /** An analysis without the AST and what is keyed by its nodes: the cache outlives a build, the AST (many times the size of the source) does not need to. */
48
+ export type SlimAnalysis = Omit<ModuleAnalysis, 'program' | 'jsxNodes' | 'exprContext'>
49
+
50
+ export function slimAnalysis(analysis: ModuleAnalysis): SlimAnalysis {
51
+ const { program: _program, jsxNodes: _jsxNodes, exprContext: _exprContext, ...slim } = analysis
52
+ return slim
53
+ }
54
+
55
+ /** The analysis again, its program and JSX node set parsed together on first use: the node set only matches the program it was computed from. */
56
+ export function reviveAnalysis(slim: SlimAnalysis, code: string): ModuleAnalysis {
57
+ let program: ModuleAnalysis['program'] | undefined
58
+ let jsxNodes: ModuleAnalysis['jsxNodes'] | undefined
59
+ const parsed = (): ModuleAnalysis['program'] => program ??= parseTsx(slim.filename, code)
60
+ return Object.defineProperties({ ...slim } as ModuleAnalysis, {
61
+ program: { get: parsed, enumerable: true, configurable: true },
62
+ jsxNodes: { get: () => jsxNodes ??= slim.hasJsx ? computeJsxNodes(parsed()) : new WeakSet(), enumerable: true, configurable: true },
63
+ exprContext: { value: undefined, writable: true, enumerable: true, configurable: true },
64
+ })
65
+ }
66
+
44
67
  export interface BuildCache {
45
- analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
68
+ analyses: Map<string, FileStamp & { code: string, analysis: SlimAnalysis }>
46
69
  domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
47
70
  ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
48
71
  lastClient?: CachedClientBuild | undefined
@@ -101,7 +124,6 @@ export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolea
101
124
  return true
102
125
  }
103
126
 
104
- const MAX_REEXPORT_DEPTH = 8
105
127
 
106
128
  export class ModuleGraph {
107
129
  readonly analyses = new Map<string, ModuleAnalysis>()
@@ -175,14 +197,14 @@ export class ModuleGraph {
175
197
  const cached = stamp === undefined ? undefined : this.cache?.analyses.get(file)
176
198
  let analysis: ModuleAnalysis
177
199
  if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
178
- analysis = cached.analysis
200
+ analysis = reviveAnalysis(cached.analysis, cached.code)
179
201
  this.sources.set(file, cached.code)
180
202
  }
181
203
  else {
182
204
  const code = this.source(file)
183
205
  analysis = this.analyze(file, code)
184
206
  if (this.cache !== undefined && stamp !== undefined)
185
- this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
207
+ this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis: slimAnalysis(analysis) })
186
208
  }
187
209
  this.analyses.set(file, analysis)
188
210
  for (const dep of this.localDeps(file))
@@ -208,40 +230,8 @@ export class ModuleGraph {
208
230
  }
209
231
  }
210
232
 
211
- /** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
212
- exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
213
- if (depth > MAX_REEXPORT_DEPTH)
214
- return { file, exportName }
215
- const key = `${file}\0${exportName}`
216
- if (seen.has(key))
217
- return { file, exportName }
218
- seen.add(key)
219
-
220
- const analysis = this.load(file)
221
- const direct = analysis.reexports.find(r => r.exported === exportName)
222
- if (direct !== undefined) {
223
- const next = this.resolve(file, direct.source)
224
- if (next !== undefined && isTsFile(next))
225
- return this.exportTarget(next, direct.local, depth + 1, seen)
226
- }
227
-
228
- if (analysis.exportedNames.includes(exportName))
229
- return { file, exportName }
230
-
231
- // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
232
- if (exportName !== 'default') {
233
- for (const re of analysis.reexports) {
234
- if (re.exported !== '*')
235
- continue
236
- const next = this.resolve(file, re.source)
237
- if (next === undefined || !isTsFile(next))
238
- continue
239
- const candidate = this.exportTarget(next, exportName, depth + 1, seen)
240
- if (this.load(candidate.file).exportedNames.includes(candidate.exportName))
241
- return candidate
242
- }
243
- }
244
-
245
- return { file, exportName }
233
+ /** The module that declares `exportName`, following re-export chains and loading each file (parse errors are never swallowed). */
234
+ exportTarget(file: string, exportName: string): { file: string, exportName: string } {
235
+ return resolveExportTarget(this, f => this.load(f), file, exportName) ?? { file, exportName }
246
236
  }
247
237
  }