prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,238 @@
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
+ /** Heaviest prerendered URL when a sibling page weighs more than the lowest-EcoIndex page. */
30
+ heaviest?: { bytes: number, url: string } | undefined
31
+ }
32
+
33
+ // 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.
34
+ const QUANTILES_DOM = [
35
+ 0, 47, 75, 159, 233, 298, 358, 417, 476, 537, 603,
36
+ 674, 753, 843, 949, 1076, 1237, 1459, 1801, 2479, 594601,
37
+ ] as const
38
+
39
+ const QUANTILES_REQ = [
40
+ 0, 2, 15, 25, 34, 42, 49, 56, 63, 70, 78,
41
+ 86, 95, 105, 117, 130, 147, 170, 205, 281, 3920,
42
+ ] as const
43
+
44
+ const QUANTILES_SIZE = [
45
+ 0, 1.37, 144.7, 319.53, 479.46, 631.97, 783.38, 937.91, 1098.62, 1265.47, 1448.32,
46
+ 1648.27, 1876.08, 2142.06, 2465.37, 2866.31, 3401.59, 4155.73, 5400.08, 8037.54, 223212.26,
47
+ ] as const
48
+
49
+ const RAW_CLOSE_RE: Record<string, RegExp> = {
50
+ script: /<\/script(?:\s[^>]*)?>/gi,
51
+ style: /<\/style(?:\s[^>]*)?>/gi,
52
+ textarea: /<\/textarea(?:\s[^>]*)?>/gi,
53
+ title: /<\/title(?:\s[^>]*)?>/gi,
54
+ }
55
+
56
+ const isAsciiAlpha = (c: number): boolean => (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
57
+
58
+ const isTagNameChar = (c: number): boolean =>
59
+ isAsciiAlpha(c) || (c >= 48 && c <= 57) || c === 45 || c === 95 || c === 58 || c === 46
60
+
61
+ const isTagDelimiter = (c: number): boolean =>
62
+ c === 62 || c === 47 || c === 32 || c === 9 || c === 10 || c === 13 || c === 12
63
+
64
+ function findTagEnd(html: string, start: number): number {
65
+ let quote = 0
66
+ for (let i = start; i < html.length; i++) {
67
+ const c = html.charCodeAt(i)
68
+ if (quote !== 0) {
69
+ if (c === quote)
70
+ quote = 0
71
+ }
72
+ else if (c === 34 || c === 39) {
73
+ quote = c
74
+ }
75
+ else if (c === 62) {
76
+ return i
77
+ }
78
+ }
79
+ return -1
80
+ }
81
+
82
+ function skipBangConstruct(html: string, lt: number): number {
83
+ if (html.startsWith('<!--', lt)) {
84
+ const end = html.indexOf('-->', lt + 4)
85
+ return end === -1 ? html.length : end + 3
86
+ }
87
+ if (html.startsWith('<![CDATA[', lt)) {
88
+ const end = html.indexOf(']]>', lt + 9)
89
+ return end === -1 ? html.length : end + 3
90
+ }
91
+ const end = html.indexOf('>', lt + 2)
92
+ return end === -1 ? html.length : end + 1
93
+ }
94
+
95
+ /** Counts HTML element nodes by scanning opening tags, ignoring DOCTYPE, comments, closing tags and raw text inside script/style/textarea/title. */
96
+ export function countDomElements(html: string): number {
97
+ let count = 0
98
+ let i = 0
99
+ const len = html.length
100
+ while (i < len) {
101
+ const lt = html.indexOf('<', i)
102
+ if (lt === -1)
103
+ break
104
+ const next = html.charCodeAt(lt + 1)
105
+ if (next === 33) {
106
+ i = skipBangConstruct(html, lt)
107
+ continue
108
+ }
109
+ if (next === 47 || next === 63) {
110
+ const end = html.indexOf('>', lt + 2)
111
+ i = end === -1 ? len : end + 1
112
+ continue
113
+ }
114
+ if (!isAsciiAlpha(next)) {
115
+ i = lt + 1
116
+ continue
117
+ }
118
+ let nameEnd = lt + 2
119
+ while (nameEnd < len && isTagNameChar(html.charCodeAt(nameEnd)))
120
+ nameEnd++
121
+ if (nameEnd >= len || !isTagDelimiter(html.charCodeAt(nameEnd))) {
122
+ i = lt + 1
123
+ continue
124
+ }
125
+ const tagEnd = findTagEnd(html, nameEnd)
126
+ if (tagEnd === -1)
127
+ break
128
+ count++
129
+ i = tagEnd + 1
130
+ const closeRe = RAW_CLOSE_RE[html.slice(lt + 1, nameEnd).toLowerCase()]
131
+ if (closeRe !== undefined) {
132
+ closeRe.lastIndex = i
133
+ const match = closeRe.exec(html)
134
+ i = match === null ? len : closeRe.lastIndex
135
+ }
136
+ }
137
+ return count
138
+ }
139
+
140
+ function computeQuantile(quantiles: readonly number[], value: number): number {
141
+ if (value <= quantiles[0]!)
142
+ return 0
143
+ for (let i = 1; i < quantiles.length; i++) {
144
+ const hi = quantiles[i]!
145
+ if (value < hi) {
146
+ const lo = quantiles[i - 1]!
147
+ return (i - 1) + (value - lo) / (hi - lo)
148
+ }
149
+ }
150
+ return quantiles.length - 1
151
+ }
152
+
153
+ function gradeForScore(score: number): EcoIndexGrade {
154
+ if (score > 80)
155
+ return 'A'
156
+ if (score > 70)
157
+ return 'B'
158
+ if (score > 55)
159
+ return 'C'
160
+ if (score > 40)
161
+ return 'D'
162
+ if (score > 25)
163
+ return 'E'
164
+ if (score > 10)
165
+ return 'F'
166
+ return 'G'
167
+ }
168
+
169
+ /** Computes the GreenIT EcoIndex score (0–100), grade (A–G), GHG emissions (gCO2e) and water consumption (cl) per view. */
170
+ export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'url'> {
171
+ const dom = Math.max(0, inputs.dom)
172
+ const requests = Math.max(0, inputs.requests)
173
+ const weightBytes = Math.max(0, inputs.weightBytes)
174
+ const qDom = computeQuantile(QUANTILES_DOM, dom)
175
+ const qReq = computeQuantile(QUANTILES_REQ, requests)
176
+ const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1000)
177
+ const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
178
+ const score = Math.round(Math.min(100, Math.max(0, raw)))
179
+ const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
180
+ const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
181
+ return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
182
+ }
183
+
184
+ function htmlServedSize(abs: string, raw: Uint8Array): number {
185
+ const sidecar = `${abs}.br`
186
+ if (existsSync(sidecar))
187
+ return statSync(sidecar).size
188
+ const packed = brotliSync(raw, appBrotliCacheDir()).byteLength
189
+ return Math.min(packed, raw.byteLength)
190
+ }
191
+
192
+ function isWorse(candidate: Omit<RouteEcoIndex, 'url'>, current: Omit<RouteEcoIndex, 'url'>): boolean {
193
+ if (candidate.score !== current.score)
194
+ return candidate.score < current.score
195
+ if (candidate.weightBytes !== current.weightBytes)
196
+ return candidate.weightBytes > current.weightBytes
197
+ return candidate.dom > current.dom
198
+ }
199
+
200
+ /** Measures EcoIndex across a route's prerendered HTML files, returning the worst (lowest) score for multi-URL routes. */
201
+ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prerenderBaseDir: string, locate: Locate }): RouteEcoIndex | undefined {
202
+ if (route.prerendered === undefined)
203
+ return undefined
204
+ const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
205
+ let worst: Omit<RouteEcoIndex, 'url' | 'heaviest'> | undefined
206
+ let worstUrl: string | undefined
207
+ let heaviest: { bytes: number, url: string } | undefined
208
+ let measured = 0
209
+
210
+ for (const [url, relFile] of entries) {
211
+ const abs = join(options.prerenderBaseDir, relFile)
212
+ const ext = extname(abs).toLowerCase()
213
+ if ((ext !== '.html' && ext !== '.htm') || !existsSync(abs))
214
+ continue
215
+ const raw = readFileSync(abs)
216
+ const html = raw.toString('utf8')
217
+ const htmlBytes = htmlServedSize(abs, raw)
218
+ const load = measureFirstLoad(firstLoadUrls(html), options.locate, htmlBytes)
219
+ const eco = {
220
+ ...computeEcoIndex({ dom: countDomElements(html), requests: 1 + load.files + load.external, weightBytes: load.total }),
221
+ ...(load.external > 0 ? { external: load.external } : {}),
222
+ }
223
+ measured++
224
+ if (worst === undefined || isWorse(eco, worst)) {
225
+ worst = eco
226
+ worstUrl = url
227
+ }
228
+ if (heaviest === undefined || load.total > heaviest.bytes)
229
+ heaviest = { bytes: load.total, url }
230
+ }
231
+
232
+ if (worst === undefined || worstUrl === undefined)
233
+ return undefined
234
+ const result: RouteEcoIndex = measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : { ...worst }
235
+ if (heaviest !== undefined && heaviest.bytes > worst.weightBytes)
236
+ result.heaviest = heaviest
237
+ return result
238
+ }
@@ -0,0 +1,171 @@
1
+ // File-system helpers of the build: directory walks and the outDir safety check.
2
+
3
+ import type { Dirent } from 'node:fs'
4
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
7
+ import { isInside } from './is-inside'
8
+
9
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
10
+ const BACKSLASH_RE = /\\/g
11
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
12
+
13
+ /** `relative(from, to)` with forward slashes, the form manifests and messages use. */
14
+ export function relPosix(from: string, to: string): string {
15
+ return relative(from, to).replace(BACKSLASH_RE, '/')
16
+ }
17
+
18
+ /** Whether `file` sits under a `node_modules` folder, with either path separator. */
19
+ export function isInNodeModules(file: string): boolean {
20
+ return NODE_MODULES_RE.test(file)
21
+ }
22
+
23
+ export function isTsFile(file: string): boolean {
24
+ return file.endsWith('.tsx') || file.endsWith('.ts')
25
+ }
26
+
27
+ /** The size of a file in bytes, or undefined when it does not exist. */
28
+ export function fileSize(file: string): number | undefined {
29
+ try {
30
+ return statSync(file).size
31
+ }
32
+ catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ interface WalkOptions {
38
+ skipDir?: (name: string) => boolean
39
+ keep?: (entry: Dirent) => boolean
40
+ }
41
+
42
+ /** Every kept file under `dir`, depth first; a missing `dir` is empty. */
43
+ export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
44
+ if (!existsSync(dir))
45
+ return out
46
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
47
+ const full = join(dir, entry.name)
48
+ if (entry.isDirectory()) {
49
+ if (options.skipDir?.(entry.name) !== true)
50
+ walkFiles(full, options, out)
51
+ }
52
+ else if (options.keep === undefined || options.keep(entry)) {
53
+ out.push(full)
54
+ }
55
+ }
56
+ return out
57
+ }
58
+
59
+ /** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
60
+ export function walkRoutes(dir: string): string[] {
61
+ return walkFiles(dir, {
62
+ skipDir: name => name.startsWith('_'),
63
+ keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
64
+ })
65
+ }
66
+
67
+ /** Folders that never hold an app's own source: its dependencies, its build, and dot folders such as `.git` and `.prunelle-cache`. */
68
+ export function isNotSourceDir(name: string): boolean {
69
+ return name === 'node_modules' || name === 'dist' || name.startsWith('.')
70
+ }
71
+
72
+ export function walkAllFiles(dir: string): string[] {
73
+ return walkFiles(dir, { keep: entry => entry.isFile() })
74
+ }
75
+
76
+
77
+ export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
78
+ // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
79
+ if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
80
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
81
+ }
82
+ if (isInside(outDir, root, { orSame: true })) {
83
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
84
+ }
85
+ if (existsSync(outDir)) {
86
+ try {
87
+ const realRoot = realpathSync(root)
88
+ const realOut = realpathSync(outDir)
89
+ if (dirname(realOut) === realOut || isInside(realOut, realRoot, { orSame: true })) {
90
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
91
+ }
92
+ if (existsSync(publicDir)) {
93
+ const realPublic = realpathSync(publicDir)
94
+ if (isInside(realPublic, realOut, { orSame: true })) {
95
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is inside publicDir ("${realPublic}"), which would publish the server bundle: set outDir outside public/ (e.g. "dist").`)
96
+ }
97
+ }
98
+ }
99
+ catch (err) {
100
+ if (err instanceof Error && err.message.startsWith('prunelle build: refusing unsafe outDir'))
101
+ throw err
102
+ }
103
+ }
104
+ const protectedTargets: [string, string][] = [
105
+ ['src', resolve(root, 'src')],
106
+ ['routesDir', routesDir],
107
+ ['publicDir', publicDir],
108
+ ['prunelle.config.ts', resolve(root, 'prunelle.config.ts')],
109
+ ['package.json', resolve(root, 'package.json')],
110
+ ]
111
+ for (const [label, target] of protectedTargets) {
112
+ if (isInside(outDir, target, { orSame: true })) {
113
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
114
+ }
115
+ }
116
+ if (isInside(publicDir, outDir)) {
117
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it sits inside publicDir ("${publicDir}"), which would publish the server bundle as public files: set outDir outside public/ (e.g. "dist").`)
118
+ }
119
+ // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
120
+ if (!isInside(root, outDir) && existsSync(outDir)) {
121
+ for (const marker of ['package.json', 'prunelle.config.ts', 'src']) {
122
+ if (existsSync(join(outDir, marker))) {
123
+ throw new Error(`prunelle build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ export interface BunBuildLogLike {
130
+ message?: string | undefined
131
+ level?: string | undefined
132
+ position?: {
133
+ file?: string | undefined
134
+ line?: number | undefined
135
+ column?: number | undefined
136
+ length?: number | undefined
137
+ lineText?: string | undefined
138
+ } | null | undefined
139
+ }
140
+
141
+ /** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
142
+ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
143
+ return logs.map((raw) => {
144
+ if (raw === null || typeof raw !== 'object')
145
+ return String(raw)
146
+ const log = raw as BunBuildLogLike
147
+ const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
148
+ const pos = log.position
149
+ if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
150
+ const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
151
+ const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
152
+ const severity = log.level === 'warning' ? 'warning' : 'error'
153
+ const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
154
+ if (typeof pos.lineText === 'string') {
155
+ const lineStr = String(pos.line)
156
+ const pad = ' '.repeat(lineStr.length)
157
+ const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
158
+ const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
159
+ return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
160
+ }
161
+ return header
162
+ }
163
+ return msg
164
+ }).join('\n')
165
+ }
166
+
167
+ /** Whether a `public/` path holds a dotfile or dot folder (`.env`, `.DS_Store`, `.git/`) other than under `.well-known`: the build leaves those out. */
168
+ export function isHiddenPublicPath(rel: string): boolean {
169
+ const segments = rel.split(/[\\/]/).filter(s => s !== '')
170
+ return segments.some((s, i) => s.startsWith('.') && !(i === 0 && s === '.well-known'))
171
+ }
@@ -0,0 +1,235 @@
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
+
3
+ import { existsSync, readFileSync, statSync } from 'node:fs'
4
+ import { extname, join, posix } from 'node:path'
5
+ import { appBrotliCacheDir, brotliSync, COMPRESSIBLE_EXTS } from './precompress'
6
+
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
+ export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
9
+
10
+ const TAG_RE = /<(\/?)(img|script|link|source|picture|video|audio|iframe)\b[^>]*>/g
11
+ const SRC_RE = /\bsrc="([^"]+)"/
12
+ const SRCSET_RE = /\bsrcset="([^"]+)"/
13
+ const POSTER_RE = /\bposter="([^"]+)"/
14
+ const HREF_RE = /\bhref="([^"]+)"/
15
+ const REL_RE = /\brel="([^"]+)"/
16
+ const TYPE_RE = /\btype="([^"]+)"/
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
21
+ const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
22
+ const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
23
+ const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
24
+ const FETCHED_RELS = new Set(['stylesheet', 'modulepreload', 'preload'])
25
+ const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf'])
26
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico'])
27
+ const SKIPPED_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i
28
+
29
+ export interface FirstLoad {
30
+ /** The page's own HTML, brotli, as given by the caller. */
31
+ html: number
32
+ css: number
33
+ js: number
34
+ fonts: number
35
+ images: number
36
+ other: number
37
+ total: number
38
+ /** The part of `total` a browser keeps in its cache for the next page: the files `cacheable` accepts. */
39
+ cached: number
40
+ /** Files counted besides the page. */
41
+ files: number
42
+ /** Third-party URLs the page fetches: requests whose size the build cannot know. */
43
+ external: number
44
+ }
45
+
46
+ /** Turns a URL the page links into the file that serves it, or `undefined` when no file does. */
47
+ export type Locate = (url: string) => string | undefined
48
+
49
+ /** The widest candidate of a `srcset`: the EcoIndex measures at 1920x1080, where a browser takes the large one. */
50
+ function widestCandidate(srcset: string): string | undefined {
51
+ let best: string | undefined
52
+ let bestSize = -1
53
+ for (const candidate of srcset.split(',')) {
54
+ const text = candidate.trim()
55
+ const size = Number(SRCSET_WIDTH_RE.exec(text)?.[1] ?? 1)
56
+ if (text !== '' && size > bestSize) {
57
+ best = text.split(/\s/)[0]
58
+ bestSize = size
59
+ }
60
+ }
61
+ return best
62
+ }
63
+
64
+ const imageUrl = (element: string): string | undefined => {
65
+ const srcset = SRCSET_RE.exec(element)?.[1]
66
+ return (srcset === undefined ? undefined : widestCandidate(srcset)) ?? SRC_RE.exec(element)?.[1]
67
+ }
68
+
69
+ /** 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. */
70
+ export function firstLoadUrls(html: string): string[] {
71
+ const urls = new Set<string>()
72
+ const icons: string[] = []
73
+ let svgIcon: string | undefined
74
+ // Inside a <picture>, or a <video>/<audio> that fetches its media: whether the source a browser takes was found.
75
+ let picture: { taken: boolean } | undefined
76
+ let media: { fetches: boolean, taken: boolean } | undefined
77
+ const add = (url: string | undefined): void => {
78
+ if (url !== undefined)
79
+ urls.add(url)
80
+ }
81
+ for (const [element, closing, name] of html.matchAll(TAG_RE)) {
82
+ if (closing === '/') {
83
+ if (name === 'picture')
84
+ picture = undefined
85
+ else if (name === 'video' || name === 'audio')
86
+ media = undefined
87
+ continue
88
+ }
89
+ if (name === 'picture') {
90
+ picture = { taken: false }
91
+ continue
92
+ }
93
+ if (name === 'video' || name === 'audio') {
94
+ const fetches = AUTOPLAY_RE.test(element) || PRELOAD_AUTO_RE.test(element)
95
+ add(POSTER_RE.exec(element)?.[1])
96
+ const src = SRC_RE.exec(element)?.[1]
97
+ media = { fetches, taken: src !== undefined }
98
+ if (fetches)
99
+ add(src)
100
+ continue
101
+ }
102
+ if (name === 'source') {
103
+ const slot = media ?? picture
104
+ if (slot === undefined || slot.taken)
105
+ continue
106
+ slot.taken = true
107
+ if (media === undefined || media.fetches)
108
+ add(media === undefined ? imageUrl(element) : SRC_RE.exec(element)?.[1])
109
+ continue
110
+ }
111
+ if (name === 'img') {
112
+ if (picture?.taken !== true)
113
+ add(imageUrl(element))
114
+ continue
115
+ }
116
+ if (name === 'link') {
117
+ const url = HREF_RE.exec(element)?.[1]
118
+ const relation = REL_RE.exec(element)?.[1] ?? ''
119
+ if (url === undefined)
120
+ continue
121
+ if (relation === 'icon') {
122
+ icons.push(url)
123
+ svgIcon ??= TYPE_RE.exec(element)?.[1] === 'image/svg+xml' ? url : undefined
124
+ }
125
+ else if (FETCHED_RELS.has(relation)) {
126
+ urls.add(url)
127
+ }
128
+ continue
129
+ }
130
+ add(SRC_RE.exec(element)?.[1])
131
+ }
132
+ // A browser that draws SVG icons fetches that one alone; the others are for browsers that do not.
133
+ for (const icon of svgIcon === undefined ? icons : [svgIcon])
134
+ urls.add(icon)
135
+ return [...urls]
136
+ }
137
+
138
+ /** The locator for a build's output: `/_pru/x` is `clientDir/x`, anything else is looked up in each public dir. */
139
+ export function distLocator(options: { clientDir: string, assetPrefix: string, publicDirs: readonly string[] }): Locate {
140
+ const prefix = `${options.assetPrefix.replace(/\/$/, '')}/`
141
+ return (url) => {
142
+ const path = url.split(/[?#]/)[0]!
143
+ if (path.startsWith(prefix)) {
144
+ const file = join(options.clientDir, path.slice(prefix.length))
145
+ return existsSync(file) ? file : undefined
146
+ }
147
+ if (!path.startsWith('/'))
148
+ return undefined
149
+ return options.publicDirs.map(dir => join(dir, path.slice(1))).find(file => existsSync(file))
150
+ }
151
+ }
152
+
153
+ const brotliCache = new Map<string, number>()
154
+
155
+ /** Bytes on the wire: the `.br` sidecar prunelle wrote, else brotli of a compressible file, else the file as it is. */
156
+ function servedSize(file: string): number {
157
+ const sidecar = `${file}.br`
158
+ if (existsSync(sidecar))
159
+ return statSync(sidecar).size
160
+ const raw = readFileSync(file)
161
+ if (!COMPRESSIBLE_EXTS.has(extname(file).toLowerCase()))
162
+ return raw.byteLength
163
+ const key = `${file}:${raw.byteLength}`
164
+ let packed = brotliCache.get(key)
165
+ if (packed === undefined) {
166
+ packed = brotliSync(raw, appBrotliCacheDir()).byteLength
167
+ brotliCache.set(key, packed)
168
+ }
169
+ return Math.min(packed, raw.byteLength)
170
+ }
171
+
172
+ // A browser takes the first source of an @font-face it can use, so only that one is fetched; every other url() is.
173
+ function cssUrls(css: string): string[] {
174
+ const urls: string[] = []
175
+ const rest = css.replace(FONT_FACE_RE, (face) => {
176
+ const first = new RegExp(CSS_URL_RE.source).exec(face)?.[2]
177
+ if (first !== undefined)
178
+ urls.push(first)
179
+ return ''
180
+ })
181
+ for (const match of rest.matchAll(CSS_URL_RE))
182
+ urls.push(match[2]!)
183
+ for (const match of rest.matchAll(CSS_IMPORT_RE))
184
+ urls.push(match[1]!)
185
+ return urls.filter(url => THIRD_PARTY_RE.test(url) || !SKIPPED_URL_RE.test(url))
186
+ }
187
+
188
+ /** What a file pulls in beside itself: a script's static imports and a stylesheet's `url()`s, as URLs. */
189
+ function dependenciesOf(url: string, file: string): string[] {
190
+ const ext = extname(file).toLowerCase()
191
+ if (ext !== '.js' && ext !== '.css')
192
+ return []
193
+ const text = readFileSync(file, 'utf8')
194
+ const base = posix.dirname(url.split(/[?#]/)[0]!)
195
+ const raw = ext === '.js' ? [...text.matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => m[1]!) : cssUrls(text)
196
+ return raw.map(dep => (dep.startsWith('/') || THIRD_PARTY_RE.test(dep) ? dep : posix.join(base, dep)))
197
+ }
198
+
199
+ /** 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). */
200
+ export function measureFirstLoad(roots: Iterable<string>, locate: Locate, htmlBytes = 0, cacheable: (url: string) => boolean = () => false): FirstLoad {
201
+ const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0, external: 0 }
202
+ const seen = new Set<string>()
203
+ const stack = [...roots]
204
+ while (stack.length > 0) {
205
+ const url = stack.pop()!
206
+ if (THIRD_PARTY_RE.test(url)) {
207
+ if (!seen.has(url))
208
+ result.external++
209
+ seen.add(url)
210
+ continue
211
+ }
212
+ const file = locate(url)
213
+ if (file === undefined || seen.has(file))
214
+ continue
215
+ seen.add(file)
216
+ const ext = extname(file).toLowerCase()
217
+ const size = servedSize(file)
218
+ if (ext === '.css')
219
+ result.css += size
220
+ else if (ext === '.js' || ext === '.mjs')
221
+ result.js += size
222
+ else if (FONT_EXTS.has(ext))
223
+ result.fonts += size
224
+ else if (IMAGE_EXTS.has(ext))
225
+ result.images += size
226
+ else
227
+ result.other += size
228
+ result.total += size
229
+ if (cacheable(url))
230
+ result.cached += size
231
+ result.files++
232
+ stack.push(...dependenciesOf(url, file))
233
+ }
234
+ return result
235
+ }