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
@@ -1,5 +1,7 @@
1
1
  // How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits.
2
2
 
3
+ import { nodeEnv } from './env'
4
+
3
5
  export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
4
6
  /** Requests a key may make per window. */
5
7
  max: number
@@ -12,6 +14,8 @@ export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: stri
12
14
  export interface RateLimiter {
13
15
  /** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. */
14
16
  hit(key: string): number
17
+ /** The seconds `hit(key)` would answer, counting nothing: 0 while `key` is under the limit. */
18
+ peek(key: string): number
15
19
  }
16
20
 
17
21
  export interface RateLimitStore {
@@ -31,9 +35,10 @@ export interface RateLimitStoreOptions {
31
35
  maxHits?: number | undefined
32
36
  }
33
37
 
34
- interface Entry {
35
- hits: number[]
36
- windowMs: number
38
+ interface Bucket {
39
+ readonly entries: Map<string, number[]>
40
+ readonly windowMs: number
41
+ hitCount: number
37
42
  }
38
43
 
39
44
  const SWEEP_MS = 60_000
@@ -49,47 +54,55 @@ export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, wher
49
54
  export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateLimitStore {
50
55
  const maxKeys = Math.max(1, options.maxKeys ?? 10_000)
51
56
  const maxHits = Math.max(1, options.maxHits ?? 1_000_000)
52
- // Least recently used first: a key is moved to the end on each request.
53
- const entries = new Map<string, Entry>()
54
- let hitCount = 0
55
- let nextId = 0
57
+ // Each limiter owns a bounded LRU map so flooding one endpoint cannot evict keys from another.
58
+ const buckets: Bucket[] = []
59
+ let totalKeys = 0
56
60
  let timer: ReturnType<typeof setInterval> | undefined
57
61
 
58
- function trim(entry: Entry, now: number): void {
59
- const cutoff = now - entry.windowMs
62
+ function secondsUntilFree(hits: readonly number[], max: number, windowMs: number, now: number): number {
63
+ return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
64
+ }
65
+
66
+ function trim(bucket: Bucket, hits: number[], now: number): void {
67
+ const cutoff = now - bucket.windowMs
60
68
  let stale = 0
61
- while (stale < entry.hits.length && entry.hits[stale]! <= cutoff)
69
+ while (stale < hits.length && hits[stale]! <= cutoff)
62
70
  stale++
63
71
  if (stale > 0) {
64
- entry.hits.splice(0, stale)
65
- hitCount -= stale
72
+ hits.splice(0, stale)
73
+ bucket.hitCount -= stale
66
74
  }
67
75
  }
68
76
 
69
77
  function sweep(now = Date.now()): number {
70
78
  let removed = 0
71
- for (const [key, entry] of entries) {
72
- trim(entry, now)
73
- if (entry.hits.length === 0) {
74
- entries.delete(key)
75
- removed++
79
+ for (const bucket of buckets) {
80
+ for (const [key, hits] of bucket.entries) {
81
+ trim(bucket, hits, now)
82
+ if (hits.length === 0) {
83
+ bucket.entries.delete(key)
84
+ totalKeys--
85
+ removed++
86
+ }
76
87
  }
77
88
  }
78
89
  return removed
79
90
  }
80
91
 
81
- function evict(): void {
82
- while (entries.size > maxKeys || hitCount > maxHits) {
83
- const [key, entry] = entries.entries().next().value!
84
- entries.delete(key)
85
- hitCount -= entry.hits.length
92
+ function evict(bucket: Bucket): void {
93
+ while (bucket.entries.size > maxKeys || bucket.hitCount > maxHits) {
94
+ const [key, hits] = bucket.entries.entries().next().value!
95
+ bucket.entries.delete(key)
96
+ bucket.hitCount -= hits.length
97
+ totalKeys--
86
98
  }
87
99
  }
88
100
 
89
101
  return {
90
102
  limiter(limit) {
91
103
  const { max, windowMs } = limit
92
- const prefix = `${nextId++}\0`
104
+ const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
105
+ buckets.push(bucket)
93
106
  if (timer === undefined) {
94
107
  timer = setInterval(sweep, SWEEP_MS)
95
108
  timer.unref()
@@ -97,23 +110,36 @@ export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateL
97
110
  return {
98
111
  hit(key) {
99
112
  const now = Date.now()
100
- const id = prefix + key
101
- const entry = entries.get(id) ?? { hits: [], windowMs }
102
- trim(entry, now)
103
- entries.delete(id)
104
- entries.set(id, entry)
105
- if (entry.hits.length >= max)
106
- return Math.max(1, Math.ceil((entry.hits[entry.hits.length - max]! + windowMs - now) / 1000))
107
- entry.hits.push(now)
108
- hitCount++
109
- evict()
113
+ const existing = bucket.entries.get(key)
114
+ const hits = existing ?? []
115
+ if (existing !== undefined) {
116
+ trim(bucket, hits, now)
117
+ bucket.entries.delete(key)
118
+ }
119
+ else {
120
+ totalKeys++
121
+ }
122
+ bucket.entries.set(key, hits)
123
+ if (hits.length >= max)
124
+ return secondsUntilFree(hits, max, windowMs, now)
125
+ hits.push(now)
126
+ bucket.hitCount++
127
+ evict(bucket)
110
128
  return 0
111
129
  },
130
+ peek(key) {
131
+ const hits = bucket.entries.get(key)
132
+ if (hits === undefined)
133
+ return 0
134
+ const now = Date.now()
135
+ trim(bucket, hits, now)
136
+ return hits.length >= max ? secondsUntilFree(hits, max, windowMs, now) : 0
137
+ },
112
138
  }
113
139
  },
114
140
  sweep,
115
141
  get size() {
116
- return entries.size
142
+ return totalKeys
117
143
  },
118
144
  close() {
119
145
  clearInterval(timer)
@@ -127,7 +153,47 @@ export function tooManyRequests(retryAfter: number): Response {
127
153
  return Response.json({ ok: false, status: 429, error: 'Too many requests' }, { status: 429, headers: { 'retry-after': String(retryAfter) } })
128
154
  }
129
155
 
130
- /** Counts `ctx` against `limiter` by the limit's key, else the client address; returns 0 or the seconds to wait. */
156
+ // One warning per limit declaration, so a test or a second server does not inherit another's silence.
157
+ const warnedMissingIp = new WeakSet<object>()
158
+
159
+ const BRACKETED_RE = /^\[([^\]]+)\](?::\d+)?$/
160
+ const IPV4_PORT_RE = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/
161
+ const MAPPED_IPV4_RE = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i
162
+ const HEXTET_RE = /^[\da-f]{1,4}$/i
163
+
164
+ /** The address a rate limit counts: an IPv4 address without its port or its `::ffff:` mapping, or the /64 network of an IPv6 address, any of whose 2^64 addresses one host may use. */
165
+ export function rateLimitAddress(ip: string): string {
166
+ const bare = BRACKETED_RE.exec(ip)?.[1] ?? IPV4_PORT_RE.exec(ip)?.[1] ?? ip
167
+ const addr = MAPPED_IPV4_RE.exec(bare)?.[1] ?? bare
168
+ const halves = addr.split('::')
169
+ if (!addr.includes(':') || halves.length > 2)
170
+ return addr
171
+ const head = halves[0] === '' ? [] : halves[0]!.split(':')
172
+ const tail = halves[1] ? halves[1].split(':') : []
173
+ // A dotted IPv4 ending holds the last two groups.
174
+ const tailGroups = tail.length + (tail.at(-1)?.includes('.') === true ? 1 : 0)
175
+ const zeros = halves.length === 2 ? 8 - head.length - tailGroups : 0
176
+ const groups = [...head, ...Array.from({ length: Math.max(0, zeros) }, () => '0'), ...tail].slice(0, 4)
177
+ if (groups.length < 4 || !groups.every(g => HEXTET_RE.test(g)))
178
+ return addr
179
+ return `${groups.map(g => Number.parseInt(g, 16).toString(16)).join(':')}::/64`
180
+ }
181
+
182
+ /** The key `limit` counts `ctx` under: the limit's own `key`, else the client's network (`rateLimitAddress`), else one shared fallback that warns in production. */
183
+ export function rateLimitKey<Ctx extends { ip?: string | undefined }>(limit: RateLimit<Ctx>, ctx: Ctx): string {
184
+ const custom = limit.key?.(ctx)
185
+ if (custom !== undefined)
186
+ return `k:${custom}`
187
+ if (ctx.ip !== undefined && ctx.ip !== '')
188
+ return `ip:${rateLimitAddress(ctx.ip)}`
189
+ if (!warnedMissingIp.has(limit) && nodeEnv() === 'production') {
190
+ warnedMissingIp.add(limit)
191
+ console.warn('prunelle: rateLimit ran with no client IP (ctx.ip is undefined); configure trustProxy in prunelle.config.ts or pass remoteIp to app.handle() so callers do not share one fallback bucket.')
192
+ }
193
+ return 'ip:unknown'
194
+ }
195
+
196
+ /** Counts `ctx` against `limiter` under `rateLimitKey`; returns 0 or the seconds to wait. */
131
197
  export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
132
- return limiter.hit(limit.key?.(ctx) ?? ctx.ip ?? '')
198
+ return limiter.hit(rateLimitKey(limit, ctx))
133
199
  }
@@ -7,7 +7,7 @@
7
7
  */
8
8
  export async function readStringFields(request: Request): Promise<Record<string, string>> {
9
9
  const fields: Record<string, string> = Object.create(null)
10
- const contentType = request.headers.get('content-type') ?? ''
10
+ const contentType = (request.headers.get('content-type') ?? '').toLowerCase()
11
11
  if (contentType.includes('application/json')) {
12
12
  const raw: unknown = await request.json()
13
13
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
@@ -0,0 +1,445 @@
1
+ // Bounded in-memory route response cache with stale-while-revalidate (SWR) and per-encoding compression reuse.
2
+
3
+ import type { CompressionCache, CompressionEncoding } from './compress'
4
+ import { ACTION_ERROR_COOKIE } from './action'
5
+ import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
6
+ import { etagMatches } from './http'
7
+ import { hasRegionHeader } from './region'
8
+
9
+ export interface RouteCacheSpec {
10
+ /** Fresh lifetime in milliseconds. */
11
+ maxAgeMs: number
12
+ /** Stale-while-revalidate window in milliseconds (defaults to `maxAgeMs`). */
13
+ swrMs: number
14
+ /** Normalized `Cache-Control` header value (`public, s-maxage=..., stale-while-revalidate=...`). */
15
+ cacheControl: string
16
+ }
17
+
18
+ export interface RouteCacheOptions {
19
+ /** Maximum cached responses kept in memory (default: 500). */
20
+ maxEntries?: number | undefined
21
+ /** Maximum total bytes across cached responses and their compressed variants (default: 32 MiB). */
22
+ maxBytes?: number | undefined
23
+ /** Backoff cooldown in milliseconds after a failed SWR revalidation before retrying (default: 5000). */
24
+ failureCooldownMs?: number | undefined
25
+ }
26
+
27
+ export interface RouteCacheSingleflightResult {
28
+ entry: CachedRouteEntry | undefined
29
+ html: string
30
+ headers: Record<string, string>
31
+ }
32
+
33
+ export interface CachedRouteEntry {
34
+ /** The key it is stored under, so a holder can tell whether it is still the stored entry. */
35
+ key: string
36
+ html: string
37
+ bytes: number
38
+ headers: Record<string, string>
39
+ createdAt: number
40
+ freshUntil: number
41
+ staleUntil: number
42
+ spec: RouteCacheSpec
43
+ /** Weak validator of `html`, so a revisit can get a 304. */
44
+ etag: string
45
+ compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
46
+ }
47
+
48
+ export type RouteCacheLookup =
49
+ | { status: 'fresh', entry: CachedRouteEntry }
50
+ | { status: 'stale', entry: CachedRouteEntry }
51
+
52
+ const DEFAULT_MAX_ENTRIES = 500
53
+ const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
54
+ const DEFAULT_FAILURE_COOLDOWN_MS = 5_000
55
+ const MIN_COMPRESS_BYTES = 256
56
+ const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
57
+ // Campaign and click identifiers: they change who is counted, never what the page shows.
58
+ const TRACKING_PARAM_RE = /^(?:utm_.+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)$/
59
+ const TRACKING_SEARCH_RE = /[?&](?:utm_|gclid=|gbraid=|wbraid=|dclid=|fbclid=|msclkid=|mc_cid=|mc_eid=)/
60
+
61
+ const UNIT_MS: Record<string, number> = {
62
+ ms: 1,
63
+ s: 1000,
64
+ m: 60_000,
65
+ h: 3_600_000,
66
+ d: 86_400_000,
67
+ }
68
+
69
+ /** Parses a duration string (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'1d'`) or number of seconds into milliseconds. */
70
+ export function parseCacheDuration(value: unknown, allowZero = false): number | undefined {
71
+ if (typeof value === 'number') {
72
+ if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
73
+ return undefined
74
+ return Math.round(value * 1000)
75
+ }
76
+ if (typeof value !== 'string')
77
+ return undefined
78
+ const match = DURATION_RE.exec(value.trim())
79
+ if (match === null)
80
+ return undefined
81
+ const amount = Number(match[1])
82
+ const unit = UNIT_MS[match[2]!.toLowerCase()]
83
+ if (!Number.isFinite(amount) || unit === undefined)
84
+ return undefined
85
+ const ms = Math.round(amount * unit)
86
+ if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
87
+ return undefined
88
+ return ms
89
+ }
90
+
91
+ /** Formats milliseconds into the cleanest short duration token (`1h`, `30s`, `500ms`). */
92
+ export function formatCacheDuration(ms: number): string {
93
+ if (ms === 0)
94
+ return '0s'
95
+ if (ms % 86_400_000 === 0)
96
+ return `${ms / 86_400_000}d`
97
+ if (ms % 3_600_000 === 0)
98
+ return `${ms / 3_600_000}h`
99
+ if (ms % 60_000 === 0)
100
+ return `${ms / 60_000}m`
101
+ if (ms % 1000 === 0)
102
+ return `${ms / 1000}s`
103
+ return `${ms}ms`
104
+ }
105
+
106
+ /** The `Cache-Control` of a cached route under an app `_middleware.ts`: the middleware may gate it, so only the server's own cache, behind the middleware, keeps the render. */
107
+ export const GATED_ROUTE_CACHE_CONTROL = 'private, no-cache'
108
+
109
+ /** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
110
+ export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
111
+ const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
112
+ const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
113
+ return {
114
+ maxAgeMs,
115
+ swrMs,
116
+ cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
117
+ }
118
+ }
119
+
120
+ /** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
121
+ export function formatCacheSpec(spec: RouteCacheSpec): string {
122
+ const maxAge = formatCacheDuration(spec.maxAgeMs)
123
+ if (spec.swrMs === spec.maxAgeMs)
124
+ return maxAge
125
+ return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
126
+ }
127
+
128
+ /** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
129
+ export function withCacheControl(headers: Record<string, string>, cacheControl: string): Record<string, string> {
130
+ return { ...headers, 'cache-control': cacheControl }
131
+ }
132
+
133
+ /** Builds a host-scoped cache key so multi-domain deployments never poison one host from another; tracking parameters are left out, so a campaign link reuses the page. */
134
+ export function routeCacheKey(url: URL): string {
135
+ if (!TRACKING_SEARCH_RE.test(url.search))
136
+ return `${url.host}${url.pathname}${url.search}`
137
+ const kept = [...url.searchParams].filter(([name]) => !TRACKING_PARAM_RE.test(name))
138
+ return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${new URLSearchParams(kept)}`}`
139
+ }
140
+
141
+ function weakEtagOf(html: string): string {
142
+ return `W/"${Bun.hash(html).toString(36)}"`
143
+ }
144
+
145
+ /** Whether a request is eligible to read from or populate the shared route cache. */
146
+ export function isCacheableRequest(request: Request): boolean {
147
+ if (request.method !== 'GET' && request.method !== 'HEAD')
148
+ return false
149
+ if (hasRegionHeader(request))
150
+ return false
151
+ const cookie = request.headers.get('cookie')
152
+ if (cookie !== null && cookie.includes(`${ACTION_ERROR_COOKIE}=`))
153
+ return false
154
+ return true
155
+ }
156
+
157
+ function compressCachedHtml(html: string, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
158
+ const rawSize = Buffer.byteLength(html, 'utf8')
159
+ if (rawSize < MIN_COMPRESS_BYTES)
160
+ return null
161
+ const buf = (encoding === 'zstd' ? Bun.zstdCompressSync(html, { level: 3 }) : Bun.gzipSync(html, { level: 6 })) as Uint8Array<ArrayBuffer>
162
+ return buf.byteLength < rawSize ? buf : null
163
+ }
164
+
165
+ /** Bounded LRU cache for rendered HTML routes with stale-while-revalidate deduplication. */
166
+ export class RouteCache {
167
+ readonly #map = new Map<string, CachedRouteEntry>()
168
+ readonly #revalidating = new Set<string>()
169
+ readonly #inflight = new Map<string, Promise<RouteCacheSingleflightResult | undefined>>()
170
+ readonly #failedUntil = new Map<string, number>()
171
+ readonly #maxEntries: number
172
+ readonly #maxBytes: number
173
+ readonly #failureCooldownMs: number
174
+ #totalBytes = 0
175
+
176
+ constructor(options?: RouteCacheOptions) {
177
+ const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
178
+ const bytes = options?.maxBytes ?? DEFAULT_MAX_BYTES
179
+ const cooldown = options?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS
180
+ this.#maxEntries = Number.isFinite(entries) && entries > 0 ? Math.floor(entries) : 0
181
+ this.#maxBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0
182
+ this.#failureCooldownMs = Number.isFinite(cooldown) && cooldown >= 0 ? Math.floor(cooldown) : DEFAULT_FAILURE_COOLDOWN_MS
183
+ }
184
+
185
+ get size(): number {
186
+ return this.#map.size
187
+ }
188
+
189
+ get bytes(): number {
190
+ return this.#totalBytes
191
+ }
192
+
193
+ hasInflight(key: string): boolean {
194
+ return this.#revalidating.has(key) || this.#inflight.has(key)
195
+ }
196
+
197
+ getInflight(key: string): Promise<RouteCacheSingleflightResult | undefined> | undefined {
198
+ return this.#inflight.get(key)
199
+ }
200
+
201
+ trackInflight(key: string, promise: Promise<RouteCacheSingleflightResult | undefined>): void {
202
+ this.#inflight.set(key, promise)
203
+ const cleanup = (): void => {
204
+ if (this.#inflight.get(key) === promise)
205
+ this.#inflight.delete(key)
206
+ }
207
+ void promise.then(cleanup, cleanup)
208
+ }
209
+
210
+ clear(): void {
211
+ this.#map.clear()
212
+ this.#failedUntil.clear()
213
+ this.#totalBytes = 0
214
+ }
215
+
216
+ delete(key: string): void {
217
+ const prev = this.#map.get(key)
218
+ if (prev === undefined)
219
+ return
220
+ this.#map.delete(key)
221
+ this.#totalBytes -= prev.bytes
222
+ }
223
+
224
+ /** Looks up `key`, refreshing LRU recency on fresh/stale hits and deleting expired entries. */
225
+ lookup(key: string, now = Date.now()): RouteCacheLookup | undefined {
226
+ const entry = this.#map.get(key)
227
+ if (entry === undefined)
228
+ return undefined
229
+ if (now >= entry.staleUntil) {
230
+ this.#map.delete(key)
231
+ this.#totalBytes -= entry.bytes
232
+ return undefined
233
+ }
234
+ this.#map.delete(key)
235
+ this.#map.set(key, entry)
236
+ return now < entry.freshUntil
237
+ ? { status: 'fresh', entry }
238
+ : { status: 'stale', entry }
239
+ }
240
+
241
+ /** Stores rendered HTML and headers under `key`, evicting LRU entries to enforce both caps. */
242
+ set(key: string, html: string, headers: Record<string, string>, spec: RouteCacheSpec, now = Date.now()): CachedRouteEntry | undefined {
243
+ const rawBytes = Buffer.byteLength(html, 'utf8')
244
+ if (this.#maxEntries <= 0 || this.#maxBytes <= 0 || rawBytes > this.#maxBytes)
245
+ return undefined
246
+ this.#failedUntil.delete(key)
247
+ const prev = this.#map.get(key)
248
+ if (prev !== undefined) {
249
+ this.#totalBytes -= prev.bytes
250
+ this.#map.delete(key)
251
+ }
252
+ const entry: CachedRouteEntry = {
253
+ key,
254
+ html,
255
+ bytes: rawBytes,
256
+ headers,
257
+ createdAt: now,
258
+ freshUntil: now + spec.maxAgeMs,
259
+ staleUntil: now + spec.maxAgeMs + spec.swrMs,
260
+ spec,
261
+ etag: weakEtagOf(html),
262
+ compressed: {},
263
+ }
264
+ this.#map.set(key, entry)
265
+ this.#totalBytes += rawBytes
266
+ this.#evict(key)
267
+ return entry
268
+ }
269
+
270
+ /** Schedules a deduplicated background revalidation for `key`, backing off briefly on failure and reporting via `onError`. */
271
+ revalidate(key: string, task: () => Promise<void>, onError: (error: unknown) => void, now = Date.now()): boolean {
272
+ if (this.#revalidating.has(key))
273
+ return false
274
+ const cooldownUntil = this.#failedUntil.get(key)
275
+ if (cooldownUntil !== undefined) {
276
+ if (now < cooldownUntil)
277
+ return false
278
+ this.#failedUntil.delete(key)
279
+ }
280
+ this.#revalidating.add(key)
281
+ void Promise.resolve()
282
+ .then(task)
283
+ .then(() => {
284
+ this.#failedUntil.delete(key)
285
+ })
286
+ .catch((error: unknown) => {
287
+ if (this.#failureCooldownMs > 0) {
288
+ this.#failedUntil.set(key, Date.now() + this.#failureCooldownMs)
289
+ this.#pruneCooldowns()
290
+ }
291
+ onError(error)
292
+ })
293
+ .finally(() => {
294
+ this.#revalidating.delete(key)
295
+ })
296
+ return true
297
+ }
298
+
299
+ #pruneCooldowns(): void {
300
+ const cap = Math.max(this.#maxEntries * 2, 1000)
301
+ if (this.#failedUntil.size <= cap)
302
+ return
303
+ const now = Date.now()
304
+ for (const [k, until] of this.#failedUntil) {
305
+ if (now >= until)
306
+ this.#failedUntil.delete(k)
307
+ }
308
+ }
309
+
310
+ /** Builds a 200 HTML response for a cache hit (`age` included, precompressed variant reused). */
311
+ respondHit(
312
+ entry: CachedRouteEntry,
313
+ request: Request,
314
+ requestId: string,
315
+ compressCache: CompressionCache | undefined,
316
+ now = Date.now(),
317
+ ): Response {
318
+ const age = String(Math.max(0, Math.floor((now - entry.createdAt) / 1000)))
319
+ return this.#buildResponse(entry, entry.html, entry.headers, request, requestId, compressCache, age)
320
+ }
321
+
322
+ /** Builds a 200 HTML response for a freshly rendered miss (stored in cache when it fits). */
323
+ respondMiss(
324
+ entry: CachedRouteEntry | undefined,
325
+ html: string,
326
+ headers: Record<string, string>,
327
+ request: Request,
328
+ requestId: string,
329
+ compressCache: CompressionCache | undefined,
330
+ serverTiming?: string,
331
+ ): Response {
332
+ return this.#buildResponse(entry, html, headers, request, requestId, compressCache, undefined, serverTiming)
333
+ }
334
+
335
+ #buildResponse(
336
+ entry: CachedRouteEntry | undefined,
337
+ html: string,
338
+ baseHeaders: Record<string, string>,
339
+ request: Request,
340
+ requestId: string,
341
+ compressCache: CompressionCache | undefined,
342
+ age?: string,
343
+ serverTiming?: string,
344
+ ): Response {
345
+ const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId, 'etag': entry?.etag ?? weakEtagOf(html) }
346
+ if (age !== undefined)
347
+ headers.age = age
348
+ if (serverTiming !== undefined)
349
+ headers['server-timing'] = serverTiming
350
+ if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
351
+ return markCompressionHandled(new Response(null, { status: 304, headers }))
352
+
353
+ if (compressCache !== undefined) {
354
+ headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
355
+ if (request.method !== 'HEAD') {
356
+ const enc = pickEncoding(request.headers.get('accept-encoding'))
357
+ if (enc !== undefined) {
358
+ const compressed = this.#getOrCompress(entry, html, enc)
359
+ if (compressed !== null) {
360
+ headers['content-encoding'] = enc
361
+ return markCompressionHandled(new Response(compressed, { status: 200, headers }))
362
+ }
363
+ }
364
+ }
365
+ }
366
+ return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, { status: 200, headers }))
367
+ }
368
+
369
+ #getOrCompress(entry: CachedRouteEntry | undefined, html: string, enc: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
370
+ if (entry !== undefined) {
371
+ const existing = entry.compressed[enc]
372
+ if (existing !== undefined)
373
+ return existing
374
+ }
375
+ const buf = compressCachedHtml(html, enc)
376
+ if (entry !== undefined) {
377
+ if (buf === null) {
378
+ entry.compressed[enc] = null
379
+ }
380
+ else if (this.#map.get(entry.key) === entry && entry.bytes + buf.byteLength <= this.#maxBytes) {
381
+ entry.compressed[enc] = buf
382
+ entry.bytes += buf.byteLength
383
+ this.#totalBytes += buf.byteLength
384
+ this.#evictEntry(entry)
385
+ }
386
+ }
387
+ return buf
388
+ }
389
+
390
+ #evict(keepKey?: string): void {
391
+ while (this.#map.size > this.#maxEntries || this.#totalBytes > this.#maxBytes) {
392
+ const oldest = this.#map.keys().next()
393
+ if (oldest.done)
394
+ break
395
+ const key = oldest.value
396
+ if (key === keepKey && this.#map.size === 1)
397
+ break
398
+ const evicted = this.#map.get(key)!
399
+ this.#map.delete(key)
400
+ this.#totalBytes -= evicted.bytes
401
+ }
402
+ }
403
+
404
+ #evictEntry(keep: CachedRouteEntry): void {
405
+ while (this.#totalBytes > this.#maxBytes) {
406
+ let victimKey: string | undefined
407
+ for (const [k, v] of this.#map) {
408
+ if (v !== keep) {
409
+ victimKey = k
410
+ break
411
+ }
412
+ }
413
+ if (victimKey === undefined)
414
+ break
415
+ const evicted = this.#map.get(victimKey)!
416
+ this.#map.delete(victimKey)
417
+ this.#totalBytes -= evicted.bytes
418
+ }
419
+ }
420
+ }
421
+
422
+ /** Looks up a cached hit and schedules background revalidation when stale. */
423
+ export function serveCachedHit(
424
+ routeCache: RouteCache,
425
+ key: string,
426
+ request: Request,
427
+ requestId: string,
428
+ compressCache: CompressionCache | undefined,
429
+ revalidate: () => Promise<void>,
430
+ onError: (error: unknown) => void,
431
+ ): Response | undefined {
432
+ const hit = routeCache.lookup(key)
433
+ if (hit === undefined)
434
+ return undefined
435
+ if (hit.status === 'stale')
436
+ routeCache.revalidate(key, revalidate, onError)
437
+ return routeCache.respondHit(hit.entry, request, requestId, compressCache)
438
+ }
439
+
440
+ /** Creates a `RouteCache` unless disabled (`dev`, build prerendering, or `routeCache: false`). */
441
+ export function createRouteCache(option: RouteCacheOptions | false | undefined, disabled = false): RouteCache | undefined {
442
+ if (disabled || option === false)
443
+ return undefined
444
+ return new RouteCache(option)
445
+ }