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,646 @@
1
+ // Zero-dependency native HTTP compression (Bun.zstdCompressSync / Bun.gzipSync) with bounded byte-budget LRU.
2
+ // `node:zlib` (3 MB of RSS) loads only with the first page streamed to a client taking gzip and not zstd, as Bun has no streaming gzip of its own that flushes.
3
+
4
+ export type CompressionEncoding = 'zstd' | 'gzip'
5
+ export type PrecompressedEncoding = 'br' | 'gzip'
6
+
7
+ const MIN_COMPRESS_BYTES = 256
8
+ const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
9
+
10
+ const COMPRESSIBLE_EXACT = new Set([
11
+ 'application/javascript',
12
+ 'application/json',
13
+ 'application/xml',
14
+ 'application/xhtml+xml',
15
+ 'application/manifest+json',
16
+ 'application/rss+xml',
17
+ 'application/atom+xml',
18
+ 'application/wasm',
19
+ 'image/svg+xml',
20
+ 'image/x-icon',
21
+ 'font/ttf',
22
+ 'font/otf',
23
+ ])
24
+
25
+ export function isCompressibleType(contentType: string | null | undefined): boolean {
26
+ if (!contentType)
27
+ return false
28
+ const semi = contentType.indexOf(';')
29
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
30
+ if (mime.startsWith('text/'))
31
+ return mime !== 'text/event-stream'
32
+ if (COMPRESSIBLE_EXACT.has(mime))
33
+ return true
34
+ return mime.endsWith('+json') || mime.endsWith('+xml')
35
+ }
36
+
37
+ const Q_VALUE_RE = /;\s*q\s*=\s*([0-9.]+)/i
38
+
39
+ // The `first` token wins ties; a token the header omits or gives q=0 never wins. Headers without q-values (the usual browser ones) take the allocation-free path.
40
+ function pickToken<A extends string, B extends string>(acceptEncoding: string, first: A | undefined, second: B | undefined): A | B | undefined {
41
+ if (!acceptEncoding.includes(';')) {
42
+ const lower = acceptEncoding.toLowerCase()
43
+ if (first !== undefined && hasToken(lower, first))
44
+ return first
45
+ return second !== undefined && hasToken(lower, second) ? second : undefined
46
+ }
47
+
48
+ let firstQ = -1
49
+ let secondQ = -1
50
+ for (const rawPart of acceptEncoding.split(',')) {
51
+ const part = rawPart.trim()
52
+ const semi = part.indexOf(';')
53
+ const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
54
+ if (name !== first && name !== second)
55
+ continue
56
+ let q = 1
57
+ if (semi !== -1) {
58
+ const parsed = Number(Q_VALUE_RE.exec(part.slice(semi))?.[1])
59
+ if (!Number.isNaN(parsed))
60
+ q = parsed
61
+ }
62
+ if (name === first)
63
+ firstQ = q
64
+ else
65
+ secondQ = q
66
+ }
67
+ if (firstQ <= 0 && secondQ <= 0)
68
+ return undefined
69
+ return firstQ >= secondQ ? first : second
70
+ }
71
+
72
+ export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
73
+ return acceptEncoding ? pickToken(acceptEncoding, 'zstd', 'gzip') : undefined
74
+ }
75
+
76
+ export function pickPrecompressedEncoding(
77
+ acceptEncoding: string | null,
78
+ available: { br?: boolean, gz?: boolean },
79
+ ): PrecompressedEncoding | undefined {
80
+ if (!acceptEncoding)
81
+ return undefined
82
+ return pickToken(acceptEncoding, available.br ? 'br' : undefined, available.gz ? 'gzip' : undefined)
83
+ }
84
+
85
+ export function toWeakEtag(etag: string): string {
86
+ return etag.startsWith('W/') || etag.startsWith('w/') ? etag : `W/${etag}`
87
+ }
88
+
89
+ function hasNoTransform(cacheControl: string | null | undefined): boolean {
90
+ return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
91
+ }
92
+
93
+ const PENDING: unique symbol = Symbol('pending')
94
+ const MAX_BUFFERED_PROBE_CHUNKS = 32
95
+ const MAX_BUFFERED_PROBE_BYTES = 4 * 1024 * 1024
96
+ const compressionHandled = new WeakSet<Response>()
97
+
98
+ /** Marks a `Response` as already processed for compression (compressed, too small, unshrinkable, or intentionally streamed). */
99
+ export function markCompressionHandled(res: Response): Response {
100
+ compressionHandled.add(res)
101
+ return res
102
+ }
103
+
104
+ function concatChunks(chunks: readonly Uint8Array[], totalBytes: number): Uint8Array<ArrayBuffer> {
105
+ if (chunks.length === 1) {
106
+ const only = chunks[0]!
107
+ if (only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength)
108
+ return only as Uint8Array<ArrayBuffer>
109
+ }
110
+ const out = new Uint8Array(totalBytes)
111
+ let offset = 0
112
+ for (const chunk of chunks) {
113
+ out.set(chunk, offset)
114
+ offset += chunk.byteLength
115
+ }
116
+ return out
117
+ }
118
+
119
+ // Microtask-only probe: buffered bodies (string, TypedArray, JSON, closed streams) settle all chunks
120
+ // within microtasks and can be compressed; open streams stay pending and pass straight through unbuffered.
121
+ export async function readBufferedOrPassThrough(
122
+ res: Response,
123
+ ): Promise<{ buffered: Uint8Array<ArrayBuffer> } | { passthrough: Response }> {
124
+ const te = res.headers.get('transfer-encoding')
125
+ if (te !== null && te.toLowerCase().includes('chunked'))
126
+ return { passthrough: res }
127
+ if (res.body === null)
128
+ return { buffered: new Uint8Array(0) }
129
+
130
+ const reader = res.body.getReader()
131
+ const chunks: Uint8Array[] = []
132
+ let totalBytes = 0
133
+ let pendingRead: ReturnType<typeof reader.read> | undefined
134
+
135
+ while (true) {
136
+ const readPromise = reader.read()
137
+ void readPromise.catch(() => undefined)
138
+ const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
139
+ const outcome = await Promise.race([readPromise, tick])
140
+ if (outcome === PENDING) {
141
+ pendingRead = readPromise
142
+ break
143
+ }
144
+ if (outcome.done) {
145
+ reader.releaseLock()
146
+ return { buffered: concatChunks(chunks, totalBytes) }
147
+ }
148
+ chunks.push(outcome.value)
149
+ totalBytes += outcome.value.byteLength
150
+ if (chunks.length >= MAX_BUFFERED_PROBE_CHUNKS || totalBytes > MAX_BUFFERED_PROBE_BYTES)
151
+ break
152
+ }
153
+
154
+ let chunkIdx = 0
155
+ const stream = new ReadableStream<Uint8Array>({
156
+ async pull(controller) {
157
+ if (chunkIdx < chunks.length) {
158
+ controller.enqueue(chunks[chunkIdx++]!)
159
+ return
160
+ }
161
+ const next = pendingRead !== undefined ? pendingRead : reader.read()
162
+ pendingRead = undefined
163
+ const { done, value } = await next
164
+ if (done)
165
+ controller.close()
166
+ else
167
+ controller.enqueue(value)
168
+ },
169
+ cancel(reason) {
170
+ pendingRead = undefined
171
+ return reader.cancel(reason)
172
+ },
173
+ })
174
+ return {
175
+ passthrough: new Response(stream, {
176
+ status: res.status,
177
+ statusText: res.statusText,
178
+ headers: res.headers,
179
+ }),
180
+ }
181
+ }
182
+
183
+ function hasToken(haystack: string, token: string): boolean {
184
+ let idx = haystack.indexOf(token)
185
+ while (idx !== -1) {
186
+ const before = idx === 0 ? ',' : haystack[idx - 1]!
187
+ const after = idx + token.length === haystack.length ? ',' : haystack[idx + token.length]!
188
+ if ((before === ',' || before === ' ' || before === '\t') && (after === ',' || after === ' ' || after === '\t'))
189
+ return true
190
+ idx = haystack.indexOf(token, idx + token.length)
191
+ }
192
+ return false
193
+ }
194
+
195
+ // A variant compressed once and served many times takes gzip 6; one compressed for a single response takes gzip 3, about a quarter of the CPU for some 9% more bytes.
196
+ const GZIP_KEPT = 6
197
+ const GZIP_PER_RESPONSE = 3
198
+ type GzipLevel = typeof GZIP_KEPT | typeof GZIP_PER_RESPONSE
199
+
200
+ // `undefined` when the input is too small to be worth compressing or does not shrink. A string goes to the compressor as is: encoding it first costs more than compressing it.
201
+ function shrink(input: Uint8Array<ArrayBuffer> | string, encoding: CompressionEncoding, gzipLevel: GzipLevel): Uint8Array<ArrayBuffer> | undefined {
202
+ const size = typeof input === 'string' ? Buffer.byteLength(input) : input.byteLength
203
+ if (size < MIN_COMPRESS_BYTES)
204
+ return undefined
205
+ const compressed = (encoding === 'zstd' ? Bun.zstdCompressSync(input, { level: 3 }) : Bun.gzipSync(input, { level: gzipLevel })) as Uint8Array<ArrayBuffer>
206
+ return compressed.byteLength < size ? compressed : undefined
207
+ }
208
+
209
+ const DEFAULT_MAX_FILE_CACHE_BYTES = 8 * 1024 * 1024
210
+
211
+ export class CompressionCache {
212
+ // Path-keyed build files (assets, public, prerendered pages): bounded byte-budget LRU + in-flight dedup. `null` marks a file that does not shrink.
213
+ readonly #files = new Map<string, Uint8Array<ArrayBuffer> | null>()
214
+ readonly #fileInflight = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
215
+ readonly #maxFileBytes: number
216
+ readonly #maxFileEntryBytes: number
217
+ #fileBytes = 0
218
+ // Content-hashed HTML of routes rendered per request: a byte-budget LRU.
219
+ readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
220
+ readonly #maxBytes: number
221
+ readonly #maxEntryBytes: number
222
+ #totalBytes = 0
223
+
224
+ constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES, maxFileBytes = DEFAULT_MAX_FILE_CACHE_BYTES) {
225
+ this.#maxBytes = maxBytes
226
+ this.#maxEntryBytes = Math.floor(maxBytes / 4)
227
+ this.#maxFileBytes = maxFileBytes
228
+ this.#maxFileEntryBytes = Math.floor(maxFileBytes / 4)
229
+ }
230
+
231
+ get(key: string): Uint8Array<ArrayBuffer> | undefined {
232
+ const hit = this.#map.get(key)
233
+ if (hit === undefined)
234
+ return undefined
235
+ // Refresh recency
236
+ this.#map.delete(key)
237
+ this.#map.set(key, hit)
238
+ return hit
239
+ }
240
+
241
+ set(key: string, value: Uint8Array<ArrayBuffer>): void {
242
+ const size = value.byteLength
243
+ if (size > this.#maxEntryBytes)
244
+ return
245
+ const prev = this.#map.get(key)
246
+ if (prev !== undefined) {
247
+ this.#totalBytes -= prev.byteLength
248
+ this.#map.delete(key)
249
+ }
250
+ this.#map.set(key, value)
251
+ this.#totalBytes += size
252
+ while (this.#totalBytes > this.#maxBytes) {
253
+ const oldest = this.#map.keys().next()
254
+ if (oldest.done)
255
+ break
256
+ const evicted = this.#map.get(oldest.value)!
257
+ this.#map.delete(oldest.value)
258
+ this.#totalBytes -= evicted.byteLength
259
+ }
260
+ }
261
+
262
+ /** Compresses `input`, kept in the LRU under `staticKey` when given; without one nothing is stored. */
263
+ compress(input: Uint8Array<ArrayBuffer> | string, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
264
+ const cacheKey = staticKey !== undefined ? `${encoding}:${staticKey}` : undefined
265
+ const cached = cacheKey !== undefined ? this.get(cacheKey) : undefined
266
+ if (cached !== undefined)
267
+ return cached
268
+ const compressed = shrink(input, encoding, cacheKey !== undefined ? GZIP_KEPT : GZIP_PER_RESPONSE)
269
+ if (compressed !== undefined && cacheKey !== undefined)
270
+ this.set(cacheKey, compressed)
271
+ return compressed
272
+ }
273
+
274
+ /** The compressed variant of a build file, read and compressed on its first request only (deduped + bounded LRU); `undefined` when it does not shrink. */
275
+ file(key: string, encoding: CompressionEncoding, read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
276
+ return this.#kept(`${encoding}:${key}`, async () => shrink(await read(), encoding, GZIP_KEPT))
277
+ }
278
+
279
+ /** Whether a file of `bytes` fits in the build-file LRU, so a request for it is answered from memory once read. */
280
+ keeps(bytes: number): boolean {
281
+ return bytes <= this.#maxFileEntryBytes
282
+ }
283
+
284
+ /** A `.br` or `.gz` file the build wrote, read on its first request only and kept in the same LRU, so a hot one is not opened per request. */
285
+ sidecar(key: string, read: () => Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
286
+ return this.#kept(`sidecar:${key}`, read)
287
+ }
288
+
289
+ async #kept(variantKey: string, produce: () => Promise<Uint8Array<ArrayBuffer> | undefined>): Promise<Uint8Array<ArrayBuffer> | undefined> {
290
+ if (this.#files.has(variantKey)) {
291
+ const hit = this.#files.get(variantKey)!
292
+ // Refresh LRU recency
293
+ this.#files.delete(variantKey)
294
+ this.#files.set(variantKey, hit)
295
+ return hit ?? undefined
296
+ }
297
+ const inflight = this.#fileInflight.get(variantKey)
298
+ if (inflight !== undefined)
299
+ return inflight
300
+
301
+ const task = (async () => {
302
+ const variant = (await produce()) ?? null
303
+ if (variant === null) {
304
+ this.#files.set(variantKey, null)
305
+ return undefined
306
+ }
307
+ if (variant.byteLength <= this.#maxFileEntryBytes) {
308
+ this.#files.set(variantKey, variant)
309
+ this.#fileBytes += variant.byteLength
310
+ while (this.#fileBytes > this.#maxFileBytes) {
311
+ const oldest = this.#files.keys().next()
312
+ if (oldest.done)
313
+ break
314
+ const evicted = this.#files.get(oldest.value)
315
+ this.#files.delete(oldest.value)
316
+ if (evicted !== null && evicted !== undefined)
317
+ this.#fileBytes -= evicted.byteLength
318
+ }
319
+ }
320
+ return variant
321
+ })()
322
+
323
+ this.#fileInflight.set(variantKey, task)
324
+ try {
325
+ return await task
326
+ }
327
+ finally {
328
+ this.#fileInflight.delete(variantKey)
329
+ }
330
+ }
331
+ }
332
+
333
+ export function mergeVaryValue(existing: string | null | undefined, token: string): string {
334
+ if (!existing)
335
+ return token
336
+ const lowerToken = token.toLowerCase()
337
+ const parts = existing.split(',').map(p => p.trim()).filter(Boolean)
338
+ if (parts.some(p => p.toLowerCase() === lowerToken))
339
+ return parts.join(', ')
340
+ return `${parts.join(', ')}, ${token}`
341
+ }
342
+
343
+ function appendVaryAcceptEncoding(headers: Headers): void {
344
+ headers.set('vary', mergeVaryValue(headers.get('vary'), 'Accept-Encoding'))
345
+ }
346
+
347
+ function tryAppendVaryAcceptEncoding(res: Response): Response {
348
+ try {
349
+ appendVaryAcceptEncoding(res.headers)
350
+ return res
351
+ }
352
+ catch {
353
+ const headers = new Headers(res.headers)
354
+ appendVaryAcceptEncoding(headers)
355
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
356
+ }
357
+ }
358
+
359
+ function withVaryAcceptEncoding(baseHeaders: Record<string, string>): Record<string, string> {
360
+ const headers: Record<string, string> = { ...baseHeaders }
361
+ let existing: string | undefined
362
+ for (const key of Object.keys(headers)) {
363
+ if (key.toLowerCase() === 'vary') {
364
+ existing = existing !== undefined ? `${existing}, ${headers[key]}` : headers[key]
365
+ if (key !== 'vary')
366
+ delete headers[key]
367
+ }
368
+ }
369
+ headers.vary = mergeVaryValue(existing, 'Accept-Encoding')
370
+ return headers
371
+ }
372
+
373
+ /** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
374
+ export function compressedHtmlResponse(
375
+ html: string,
376
+ status: number,
377
+ baseHeaders: Record<string, string>,
378
+ request: Request,
379
+ cache: CompressionCache | undefined,
380
+ reuse = false,
381
+ ): Response {
382
+ const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
383
+ if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
384
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
385
+ if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
386
+ // SHA-256 of the page, so two pages never share a kept body: a 64-bit hash could be made to collide by a page that renders the query string.
387
+ const staticKey = reuse ? `s:${new Bun.CryptoHasher('sha256').update(html).digest('base64url')}` : undefined
388
+ let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
389
+ if (compressed === undefined)
390
+ compressed = cache.compress(html, enc, staticKey)
391
+ if (compressed !== undefined) {
392
+ const headers = withVaryAcceptEncoding(baseHeaders)
393
+ headers['content-encoding'] = enc
394
+ const etag = headers.etag ?? headers.ETag
395
+ if (etag !== undefined) {
396
+ delete headers.ETag
397
+ headers.etag = toWeakEtag(etag)
398
+ }
399
+ return markCompressionHandled(new Response(compressed, { status, headers }))
400
+ }
401
+ }
402
+ }
403
+ return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, {
404
+ status,
405
+ headers: cache !== undefined && !noTransform ? withVaryAcceptEncoding(baseHeaders) : baseHeaders,
406
+ }))
407
+ }
408
+
409
+ function compressedHeaders(res: Response, enc: CompressionEncoding): Headers {
410
+ const headers = new Headers(res.headers)
411
+ appendVaryAcceptEncoding(headers)
412
+ headers.set('content-encoding', enc)
413
+ headers.delete('content-length')
414
+ const etag = headers.get('etag')
415
+ if (etag !== null)
416
+ headers.set('etag', toWeakEtag(etag))
417
+ return headers
418
+ }
419
+
420
+ function compressedResponseFrom(res: Response, compressed: Uint8Array<ArrayBuffer>, enc: CompressionEncoding): Response {
421
+ return markCompressionHandled(new Response(compressed, { status: res.status, statusText: res.statusText, headers: compressedHeaders(res, enc) }))
422
+ }
423
+
424
+ let zlib: Promise<typeof import('node:zlib')> | undefined
425
+
426
+ /**
427
+ * Each chunk as a zstd frame of its own. A zstd body is one or more frames (RFC 8878, section 3), so the browser decodes each one as it arrives,
428
+ * and a frame costs a few microseconds where a zstd stream from `node:zlib` costs over 100 to set up per response.
429
+ */
430
+ function zstdFrames(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
431
+ // Pulled by hand: Bun's pipeThrough does not pass a client's cancel back to the renderer.
432
+ const reader = body.getReader()
433
+ return new ReadableStream<Uint8Array>({
434
+ async pull(controller) {
435
+ const next = await reader.read()
436
+ if (next.done)
437
+ controller.close()
438
+ else
439
+ controller.enqueue(Bun.zstdCompressSync(next.value, { level: 3 }))
440
+ },
441
+ cancel: reason => reader.cancel(reason),
442
+ }, { highWaterMark: 0 })
443
+ }
444
+
445
+ function tryCloseController(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
446
+ try {
447
+ controller.close()
448
+ return true
449
+ }
450
+ catch {
451
+ return false
452
+ }
453
+ }
454
+
455
+ function tryErrorController(controller: ReadableStreamDefaultController<Uint8Array>, error: unknown): boolean {
456
+ try {
457
+ controller.error(error)
458
+ return true
459
+ }
460
+ catch {
461
+ return false
462
+ }
463
+ }
464
+
465
+ /** One gzip stream flushed after each chunk: concatenated gzip members would stop a browser after the first. */
466
+ async function gzipFlushed(body: ReadableStream<Uint8Array>): Promise<ReadableStream<Uint8Array>> {
467
+ const { constants, createGzip } = await (zlib ??= import('node:zlib'))
468
+ const compressor = createGzip({ level: GZIP_PER_RESPONSE, flush: constants.Z_SYNC_FLUSH })
469
+ const reader = body.getReader()
470
+ let closed = false
471
+ let ended: Promise<void> | undefined
472
+ let resolveEnded: (() => void) | undefined
473
+ const markEnded = (): void => {
474
+ resolveEnded?.()
475
+ resolveEnded = undefined
476
+ }
477
+ return new ReadableStream<Uint8Array>({
478
+ start(controller) {
479
+ compressor.on('data', (chunk: Uint8Array) => {
480
+ if (closed)
481
+ return
482
+ try {
483
+ controller.enqueue(chunk)
484
+ }
485
+ catch {
486
+ closed = true
487
+ markEnded()
488
+ compressor.destroy()
489
+ }
490
+ })
491
+ compressor.once('end', () => {
492
+ if (!closed) {
493
+ closed = true
494
+ tryCloseController(controller)
495
+ }
496
+ markEnded()
497
+ })
498
+ compressor.on('error', (error: unknown) => {
499
+ if (!closed) {
500
+ closed = true
501
+ tryErrorController(controller, error)
502
+ }
503
+ markEnded()
504
+ })
505
+ compressor.once('close', () => {
506
+ closed = true
507
+ markEnded()
508
+ })
509
+ },
510
+ async pull() {
511
+ if (closed)
512
+ return
513
+ if (ended !== undefined)
514
+ return ended
515
+ let next: Awaited<ReturnType<typeof reader.read>>
516
+ try {
517
+ next = await reader.read()
518
+ }
519
+ catch (error: unknown) {
520
+ closed = true
521
+ markEnded()
522
+ compressor.destroy()
523
+ throw error
524
+ }
525
+ if (closed)
526
+ return
527
+ if (next.done) {
528
+ if (compressor.readableEnded || compressor.destroyed) {
529
+ closed = true
530
+ return
531
+ }
532
+ ended = new Promise<void>((resolve) => {
533
+ resolveEnded = resolve
534
+ })
535
+ compressor.end()
536
+ return ended
537
+ }
538
+ // The compressor emits the flushed bytes before it calls back, so each chunk leaves before the next one is read.
539
+ await new Promise<void>((resolve, reject) => {
540
+ if (closed || compressor.destroyed) {
541
+ resolve()
542
+ return
543
+ }
544
+ compressor.write(next.value, error => (error && !closed ? reject(error) : resolve()))
545
+ })
546
+ },
547
+ cancel(reason) {
548
+ closed = true
549
+ markEnded()
550
+ compressor.destroy()
551
+ return reader.cancel(reason)
552
+ },
553
+ })
554
+ }
555
+
556
+ /** An open HTML stream compressed as it goes, flushed after each chunk the renderer sends, so the shell still reaches the browser before the suspended parts. */
557
+ async function compressedStream(res: Response, body: ReadableStream<Uint8Array>, enc: CompressionEncoding): Promise<Response> {
558
+ const compressed = enc === 'zstd' ? zstdFrames(body) : await gzipFlushed(body)
559
+ return markCompressionHandled(new Response(compressed, { status: res.status, statusText: res.statusText, headers: compressedHeaders(res, enc) }))
560
+ }
561
+
562
+ /** A page streamed past its `<Suspense>` boundaries, compressed per flush for a client taking zstd or gzip. */
563
+ export async function compressedHtmlStream(
564
+ stream: ReadableStream<Uint8Array>,
565
+ status: number,
566
+ baseHeaders: Record<string, string>,
567
+ request: Request,
568
+ cache: CompressionCache | undefined,
569
+ ): Promise<Response> {
570
+ const enc = cache !== undefined ? pickEncoding(request.headers.get('accept-encoding')) : undefined
571
+ if (enc !== undefined)
572
+ return compressedStream(new Response(null, { status, headers: baseHeaders }), stream, enc)
573
+ return markCompressionHandled(new Response(stream, { status, headers: cache !== undefined ? withVaryAcceptEncoding(baseHeaders) : baseHeaders }))
574
+ }
575
+
576
+ const isHtml = (res: Response): boolean => (res.headers.get('content-type') ?? '').trimStart().toLowerCase().startsWith('text/html')
577
+
578
+ export async function maybeCompressResponse(
579
+ res: Response,
580
+ request: Request,
581
+ cache: CompressionCache | undefined,
582
+ staticKey?: string,
583
+ ): Promise<Response> {
584
+ if (cache === undefined || compressionHandled.has(res))
585
+ return res
586
+ if (res.status === 204 || res.status === 206 || res.status === 304 || (res.status >= 300 && res.status < 400))
587
+ return res
588
+ if (res.headers.has('content-encoding'))
589
+ return res
590
+ if (hasNoTransform(res.headers.get('cache-control')))
591
+ return res
592
+ if (!isCompressibleType(res.headers.get('content-type')))
593
+ return res
594
+
595
+ const cl = res.headers.get('content-length')
596
+ const clBytes = cl !== null && cl.trim() !== '' ? Number(cl) : Number.NaN
597
+ const hasValidCl = Number.isFinite(clBytes) && clBytes >= 0
598
+ const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
599
+ if (enc === undefined)
600
+ return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
601
+
602
+ if (hasValidCl && clBytes < MIN_COMPRESS_BYTES)
603
+ return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
604
+
605
+ if (res.body === null)
606
+ return res
607
+
608
+ if (staticKey !== undefined) {
609
+ let readRaw: Uint8Array<ArrayBuffer> | undefined
610
+ const compressed = await cache.file(staticKey, enc, async () => {
611
+ readRaw = new Uint8Array(await res.arrayBuffer())
612
+ return readRaw
613
+ })
614
+ if (compressed !== undefined)
615
+ return compressedResponseFrom(res, compressed, enc)
616
+ if (readRaw !== undefined) {
617
+ const headers = new Headers(res.headers)
618
+ appendVaryAcceptEncoding(headers)
619
+ return markCompressionHandled(new Response(readRaw, { status: res.status, statusText: res.statusText, headers }))
620
+ }
621
+ return markCompressionHandled(tryAppendVaryAcceptEncoding(res))
622
+ }
623
+
624
+ if (hasValidCl && clBytes > MAX_BUFFERED_PROBE_BYTES)
625
+ return isHtml(res) ? compressedStream(res, res.body, enc) : markCompressionHandled(tryAppendVaryAcceptEncoding(res))
626
+
627
+ let raw: Uint8Array<ArrayBuffer>
628
+ if (hasValidCl) {
629
+ raw = new Uint8Array(await res.arrayBuffer())
630
+ }
631
+ else {
632
+ const probe = await readBufferedOrPassThrough(res)
633
+ if ('passthrough' in probe) {
634
+ const { body } = probe.passthrough
635
+ return isHtml(res) && body !== null ? compressedStream(res, body, enc) : markCompressionHandled(probe.passthrough)
636
+ }
637
+ raw = probe.buffered
638
+ }
639
+ const compressed = cache.compress(raw, enc)
640
+ if (compressed === undefined) {
641
+ const headers = new Headers(res.headers)
642
+ appendVaryAcceptEncoding(headers)
643
+ return markCompressionHandled(new Response(raw, { status: res.status, statusText: res.statusText, headers }))
644
+ }
645
+ return compressedResponseFrom(res, compressed, enc)
646
+ }