prunelle 0.1.1 → 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.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,541 @@
|
|
|
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 type { RequestContext } from './http'
|
|
5
|
+
import { ACTION_ERROR_COOKIE } from './action'
|
|
6
|
+
import { markCompressionHandled, mergeVaryValue, pickEncoding } from './compress'
|
|
7
|
+
import { etagMatches } from './http'
|
|
8
|
+
import { hasRegionHeader } from './region'
|
|
9
|
+
|
|
10
|
+
export interface RouteCacheSpec {
|
|
11
|
+
/** Fresh lifetime in milliseconds. */
|
|
12
|
+
maxAgeMs: number
|
|
13
|
+
/** Stale-while-revalidate window in milliseconds (defaults to `maxAgeMs`). */
|
|
14
|
+
swrMs: number
|
|
15
|
+
/** Normalized `Cache-Control` header value (`public, s-maxage=..., stale-while-revalidate=...`). */
|
|
16
|
+
cacheControl: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface RouteCacheOptions {
|
|
20
|
+
/** Maximum cached responses kept in memory (default: 500). */
|
|
21
|
+
maxEntries?: number | undefined
|
|
22
|
+
/** Maximum total bytes across cached responses and their compressed variants (default: 32 MiB). */
|
|
23
|
+
maxBytes?: number | undefined
|
|
24
|
+
/** Backoff cooldown in milliseconds after a failed SWR revalidation before retrying (default: 5000). */
|
|
25
|
+
failureCooldownMs?: number | undefined
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RouteCacheSingleflightResult {
|
|
29
|
+
entry: CachedRouteEntry | undefined
|
|
30
|
+
html: string
|
|
31
|
+
headers: Record<string, string>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CachedRouteEntry {
|
|
35
|
+
/** The key it is stored under, so a holder can tell whether it is still the stored entry. */
|
|
36
|
+
key: string
|
|
37
|
+
html: string
|
|
38
|
+
bytes: number
|
|
39
|
+
headers: Record<string, string>
|
|
40
|
+
createdAt: number
|
|
41
|
+
freshUntil: number
|
|
42
|
+
staleUntil: number
|
|
43
|
+
spec: RouteCacheSpec
|
|
44
|
+
/** Weak validator of `html`, so a revisit can get a 304. */
|
|
45
|
+
etag: string
|
|
46
|
+
compressed: Partial<Record<CompressionEncoding, Uint8Array<ArrayBuffer> | null>>
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type RouteCacheLookup =
|
|
50
|
+
| { status: 'fresh', entry: CachedRouteEntry }
|
|
51
|
+
| { status: 'stale', entry: CachedRouteEntry }
|
|
52
|
+
|
|
53
|
+
const DEFAULT_MAX_ENTRIES = 500
|
|
54
|
+
const DEFAULT_MAX_BYTES = 32 * 1024 * 1024
|
|
55
|
+
const DEFAULT_FAILURE_COOLDOWN_MS = 5_000
|
|
56
|
+
const MIN_COMPRESS_BYTES = 256
|
|
57
|
+
const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i
|
|
58
|
+
// Campaign and click identifiers: they change who is counted, never what the page shows.
|
|
59
|
+
const TRACKING_PARAM_RE = /^(?:utm_.+|gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)$/
|
|
60
|
+
const TRACKING_SEARCH_RE = /[?&](?:utm_|(?:gclid|gbraid|wbraid|dclid|fbclid|msclkid|mc_cid|mc_eid)(?:[=&]|$))/
|
|
61
|
+
|
|
62
|
+
const UNIT_MS: Record<string, number> = {
|
|
63
|
+
ms: 1,
|
|
64
|
+
s: 1000,
|
|
65
|
+
m: 60_000,
|
|
66
|
+
h: 3_600_000,
|
|
67
|
+
d: 86_400_000,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Parses a duration string (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'1d'`) or number of seconds into milliseconds. */
|
|
71
|
+
export function parseCacheDuration(value: unknown, allowZero = false): number | undefined {
|
|
72
|
+
if (typeof value === 'number') {
|
|
73
|
+
if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0))
|
|
74
|
+
return undefined
|
|
75
|
+
return Math.round(value * 1000)
|
|
76
|
+
}
|
|
77
|
+
if (typeof value !== 'string')
|
|
78
|
+
return undefined
|
|
79
|
+
const match = DURATION_RE.exec(value.trim())
|
|
80
|
+
if (match === null)
|
|
81
|
+
return undefined
|
|
82
|
+
const amount = Number(match[1])
|
|
83
|
+
const unit = UNIT_MS[match[2]!.toLowerCase()]
|
|
84
|
+
if (!Number.isFinite(amount) || unit === undefined)
|
|
85
|
+
return undefined
|
|
86
|
+
const ms = Math.round(amount * unit)
|
|
87
|
+
if (!Number.isFinite(ms) || (allowZero ? ms < 0 : ms <= 0))
|
|
88
|
+
return undefined
|
|
89
|
+
return ms
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Formats milliseconds into the cleanest short duration token (`1h`, `30s`, `500ms`). */
|
|
93
|
+
export function formatCacheDuration(ms: number): string {
|
|
94
|
+
if (ms === 0)
|
|
95
|
+
return '0s'
|
|
96
|
+
if (ms % 86_400_000 === 0)
|
|
97
|
+
return `${ms / 86_400_000}d`
|
|
98
|
+
if (ms % 3_600_000 === 0)
|
|
99
|
+
return `${ms / 3_600_000}h`
|
|
100
|
+
if (ms % 60_000 === 0)
|
|
101
|
+
return `${ms / 60_000}m`
|
|
102
|
+
if (ms % 1000 === 0)
|
|
103
|
+
return `${ms / 1000}s`
|
|
104
|
+
return `${ms}ms`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 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. */
|
|
108
|
+
export const GATED_ROUTE_CACHE_CONTROL = 'private, no-cache'
|
|
109
|
+
|
|
110
|
+
/** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
|
|
111
|
+
export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
|
|
112
|
+
const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
|
|
113
|
+
const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
|
|
114
|
+
return {
|
|
115
|
+
maxAgeMs,
|
|
116
|
+
swrMs,
|
|
117
|
+
cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
|
|
122
|
+
export function formatCacheSpec(spec: RouteCacheSpec): string {
|
|
123
|
+
const maxAge = formatCacheDuration(spec.maxAgeMs)
|
|
124
|
+
if (spec.swrMs === spec.maxAgeMs)
|
|
125
|
+
return maxAge
|
|
126
|
+
return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
|
|
130
|
+
export function withCacheControl(headers: Record<string, string>, cacheControl: string): Record<string, string> {
|
|
131
|
+
return { ...headers, 'cache-control': cacheControl }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 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. */
|
|
135
|
+
export function routeCacheKey(url: URL): string {
|
|
136
|
+
if (!TRACKING_SEARCH_RE.test(url.search))
|
|
137
|
+
return `${url.host}${url.pathname}${url.search}`
|
|
138
|
+
const kept: string[] = []
|
|
139
|
+
for (const part of url.search.slice(1).split('&')) {
|
|
140
|
+
if (part.length === 0)
|
|
141
|
+
continue
|
|
142
|
+
const eq = part.indexOf('=')
|
|
143
|
+
const name = eq === -1 ? part : part.slice(0, eq)
|
|
144
|
+
if (!TRACKING_PARAM_RE.test(name))
|
|
145
|
+
kept.push(part)
|
|
146
|
+
}
|
|
147
|
+
return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${kept.join('&')}`}`
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function weakEtagOf(html: string): string {
|
|
151
|
+
return `W/"${Bun.hash(html).toString(36)}"`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Whether a request is eligible to read from or populate the shared route cache. */
|
|
155
|
+
export function isCacheableRequest(request: Request): boolean {
|
|
156
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
157
|
+
return false
|
|
158
|
+
if (hasRegionHeader(request))
|
|
159
|
+
return false
|
|
160
|
+
const cookie = request.headers.get('cookie')
|
|
161
|
+
if (cookie !== null && cookie.includes(`${ACTION_ERROR_COOKIE}=`))
|
|
162
|
+
return false
|
|
163
|
+
return true
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function compressCachedHtml(html: string, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
|
|
167
|
+
const rawSize = Buffer.byteLength(html, 'utf8')
|
|
168
|
+
if (rawSize < MIN_COMPRESS_BYTES)
|
|
169
|
+
return null
|
|
170
|
+
const buf = (encoding === 'zstd' ? Bun.zstdCompressSync(html, { level: 3 }) : Bun.gzipSync(html, { level: 6 })) as Uint8Array<ArrayBuffer>
|
|
171
|
+
return buf.byteLength < rawSize ? buf : null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Bounded LRU cache for rendered HTML routes with stale-while-revalidate deduplication. */
|
|
175
|
+
export class RouteCache {
|
|
176
|
+
readonly #map = new Map<string, CachedRouteEntry>()
|
|
177
|
+
readonly #revalidating = new Set<string>()
|
|
178
|
+
readonly #inflight = new Map<string, Promise<RouteCacheSingleflightResult | undefined>>()
|
|
179
|
+
readonly #failedUntil = new Map<string, number>()
|
|
180
|
+
readonly #maxEntries: number
|
|
181
|
+
readonly #maxBytes: number
|
|
182
|
+
readonly #failureCooldownMs: number
|
|
183
|
+
#totalBytes = 0
|
|
184
|
+
|
|
185
|
+
constructor(options?: RouteCacheOptions) {
|
|
186
|
+
const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
|
|
187
|
+
const bytes = options?.maxBytes ?? DEFAULT_MAX_BYTES
|
|
188
|
+
const cooldown = options?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS
|
|
189
|
+
this.#maxEntries = Number.isFinite(entries) && entries > 0 ? Math.floor(entries) : 0
|
|
190
|
+
this.#maxBytes = Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0
|
|
191
|
+
this.#failureCooldownMs = Number.isFinite(cooldown) && cooldown >= 0 ? Math.floor(cooldown) : DEFAULT_FAILURE_COOLDOWN_MS
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
get size(): number {
|
|
195
|
+
return this.#map.size
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
get bytes(): number {
|
|
199
|
+
return this.#totalBytes
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
hasInflight(key: string): boolean {
|
|
203
|
+
return this.#revalidating.has(key) || this.#inflight.has(key)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
getInflight(key: string): Promise<RouteCacheSingleflightResult | undefined> | undefined {
|
|
207
|
+
return this.#inflight.get(key)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
trackInflight(key: string, promise: Promise<RouteCacheSingleflightResult | undefined>): void {
|
|
211
|
+
this.#inflight.set(key, promise)
|
|
212
|
+
const cleanup = (): void => {
|
|
213
|
+
if (this.#inflight.get(key) === promise)
|
|
214
|
+
this.#inflight.delete(key)
|
|
215
|
+
}
|
|
216
|
+
void promise.then(cleanup, cleanup)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
clear(): void {
|
|
220
|
+
this.#map.clear()
|
|
221
|
+
this.#failedUntil.clear()
|
|
222
|
+
this.#totalBytes = 0
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
delete(key: string): void {
|
|
226
|
+
const prev = this.#map.get(key)
|
|
227
|
+
if (prev === undefined)
|
|
228
|
+
return
|
|
229
|
+
this.#map.delete(key)
|
|
230
|
+
this.#totalBytes -= prev.bytes
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Looks up `key`, refreshing LRU recency on fresh/stale hits and deleting expired entries. */
|
|
234
|
+
lookup(key: string, now = Date.now()): RouteCacheLookup | undefined {
|
|
235
|
+
const entry = this.#map.get(key)
|
|
236
|
+
if (entry === undefined)
|
|
237
|
+
return undefined
|
|
238
|
+
if (now >= entry.staleUntil) {
|
|
239
|
+
this.#map.delete(key)
|
|
240
|
+
this.#totalBytes -= entry.bytes
|
|
241
|
+
return undefined
|
|
242
|
+
}
|
|
243
|
+
this.#map.delete(key)
|
|
244
|
+
this.#map.set(key, entry)
|
|
245
|
+
return now < entry.freshUntil
|
|
246
|
+
? { status: 'fresh', entry }
|
|
247
|
+
: { status: 'stale', entry }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Stores rendered HTML and headers under `key`, evicting LRU entries to enforce both caps. */
|
|
251
|
+
set(key: string, html: string, headers: Record<string, string>, spec: RouteCacheSpec, now = Date.now()): CachedRouteEntry | undefined {
|
|
252
|
+
const rawBytes = Buffer.byteLength(html, 'utf8')
|
|
253
|
+
if (this.#maxEntries <= 0 || this.#maxBytes <= 0 || rawBytes > this.#maxBytes)
|
|
254
|
+
return undefined
|
|
255
|
+
this.#failedUntil.delete(key)
|
|
256
|
+
const prev = this.#map.get(key)
|
|
257
|
+
if (prev !== undefined) {
|
|
258
|
+
this.#totalBytes -= prev.bytes
|
|
259
|
+
this.#map.delete(key)
|
|
260
|
+
}
|
|
261
|
+
const entry: CachedRouteEntry = {
|
|
262
|
+
key,
|
|
263
|
+
html,
|
|
264
|
+
bytes: rawBytes,
|
|
265
|
+
headers,
|
|
266
|
+
createdAt: now,
|
|
267
|
+
freshUntil: now + spec.maxAgeMs,
|
|
268
|
+
staleUntil: now + spec.maxAgeMs + spec.swrMs,
|
|
269
|
+
spec,
|
|
270
|
+
etag: weakEtagOf(html),
|
|
271
|
+
compressed: {},
|
|
272
|
+
}
|
|
273
|
+
this.#map.set(key, entry)
|
|
274
|
+
this.#totalBytes += rawBytes
|
|
275
|
+
this.#evict(key)
|
|
276
|
+
return entry
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Schedules a deduplicated background revalidation for `key`, backing off briefly on failure and reporting via `onError`. */
|
|
280
|
+
revalidate(key: string, task: () => Promise<void>, onError: (error: unknown) => void, now = Date.now()): boolean {
|
|
281
|
+
if (this.#revalidating.has(key))
|
|
282
|
+
return false
|
|
283
|
+
const cooldownUntil = this.#failedUntil.get(key)
|
|
284
|
+
if (cooldownUntil !== undefined) {
|
|
285
|
+
if (now < cooldownUntil)
|
|
286
|
+
return false
|
|
287
|
+
this.#failedUntil.delete(key)
|
|
288
|
+
}
|
|
289
|
+
this.#revalidating.add(key)
|
|
290
|
+
void Promise.resolve()
|
|
291
|
+
.then(task)
|
|
292
|
+
.then(() => {
|
|
293
|
+
this.#failedUntil.delete(key)
|
|
294
|
+
})
|
|
295
|
+
.catch((error: unknown) => {
|
|
296
|
+
if (this.#failureCooldownMs > 0) {
|
|
297
|
+
this.#failedUntil.set(key, Date.now() + this.#failureCooldownMs)
|
|
298
|
+
this.#pruneCooldowns()
|
|
299
|
+
}
|
|
300
|
+
onError(error)
|
|
301
|
+
})
|
|
302
|
+
.finally(() => {
|
|
303
|
+
this.#revalidating.delete(key)
|
|
304
|
+
})
|
|
305
|
+
return true
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
#pruneCooldowns(): void {
|
|
309
|
+
const cap = Math.max(this.#maxEntries * 2, 1000)
|
|
310
|
+
if (this.#failedUntil.size <= cap)
|
|
311
|
+
return
|
|
312
|
+
const now = Date.now()
|
|
313
|
+
for (const [k, until] of this.#failedUntil) {
|
|
314
|
+
if (now >= until)
|
|
315
|
+
this.#failedUntil.delete(k)
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Builds a 200 HTML response for a cache hit (`age` included, precompressed variant reused). */
|
|
320
|
+
respondHit(
|
|
321
|
+
entry: CachedRouteEntry,
|
|
322
|
+
request: Request,
|
|
323
|
+
requestId: string,
|
|
324
|
+
compressCache: CompressionCache | undefined,
|
|
325
|
+
now = Date.now(),
|
|
326
|
+
): Response {
|
|
327
|
+
const age = String(Math.max(0, Math.floor((now - entry.createdAt) / 1000)))
|
|
328
|
+
return this.#buildResponse(entry, entry.html, entry.headers, request, requestId, compressCache, age)
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Builds a 200 HTML response for a freshly rendered miss (stored in cache when it fits). */
|
|
332
|
+
respondMiss(
|
|
333
|
+
entry: CachedRouteEntry | undefined,
|
|
334
|
+
html: string,
|
|
335
|
+
headers: Record<string, string>,
|
|
336
|
+
request: Request,
|
|
337
|
+
requestId: string,
|
|
338
|
+
compressCache: CompressionCache | undefined,
|
|
339
|
+
serverTiming?: string,
|
|
340
|
+
): Response {
|
|
341
|
+
return this.#buildResponse(entry, html, headers, request, requestId, compressCache, undefined, serverTiming)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
#buildResponse(
|
|
345
|
+
entry: CachedRouteEntry | undefined,
|
|
346
|
+
html: string,
|
|
347
|
+
baseHeaders: Record<string, string>,
|
|
348
|
+
request: Request,
|
|
349
|
+
requestId: string,
|
|
350
|
+
compressCache: CompressionCache | undefined,
|
|
351
|
+
age?: string,
|
|
352
|
+
serverTiming?: string,
|
|
353
|
+
): Response {
|
|
354
|
+
const headers: Record<string, string> = { ...baseHeaders, 'x-request-id': requestId, 'etag': entry?.etag ?? weakEtagOf(html) }
|
|
355
|
+
if (age !== undefined)
|
|
356
|
+
headers.age = age
|
|
357
|
+
if (serverTiming !== undefined)
|
|
358
|
+
headers['server-timing'] = serverTiming
|
|
359
|
+
if (etagMatches(request.headers.get('if-none-match'), headers.etag!))
|
|
360
|
+
return markCompressionHandled(new Response(null, { status: 304, headers }))
|
|
361
|
+
|
|
362
|
+
if (compressCache !== undefined) {
|
|
363
|
+
headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
|
|
364
|
+
if (request.method !== 'HEAD') {
|
|
365
|
+
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
366
|
+
if (enc !== undefined) {
|
|
367
|
+
const compressed = this.#getOrCompress(entry, html, enc)
|
|
368
|
+
if (compressed !== null) {
|
|
369
|
+
headers['content-encoding'] = enc
|
|
370
|
+
return markCompressionHandled(new Response(compressed, { status: 200, headers }))
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return markCompressionHandled(new Response(request.method === 'HEAD' ? null : html, { status: 200, headers }))
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
#getOrCompress(entry: CachedRouteEntry | undefined, html: string, enc: CompressionEncoding): Uint8Array<ArrayBuffer> | null {
|
|
379
|
+
if (entry !== undefined) {
|
|
380
|
+
const existing = entry.compressed[enc]
|
|
381
|
+
if (existing !== undefined)
|
|
382
|
+
return existing
|
|
383
|
+
}
|
|
384
|
+
const buf = compressCachedHtml(html, enc)
|
|
385
|
+
if (entry !== undefined) {
|
|
386
|
+
if (buf === null) {
|
|
387
|
+
entry.compressed[enc] = null
|
|
388
|
+
}
|
|
389
|
+
else if (this.#map.get(entry.key) === entry && entry.bytes + buf.byteLength <= this.#maxBytes) {
|
|
390
|
+
entry.compressed[enc] = buf
|
|
391
|
+
entry.bytes += buf.byteLength
|
|
392
|
+
this.#totalBytes += buf.byteLength
|
|
393
|
+
this.#evictEntry(entry)
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return buf
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
#evict(keepKey?: string): void {
|
|
400
|
+
while (this.#map.size > this.#maxEntries || this.#totalBytes > this.#maxBytes) {
|
|
401
|
+
const oldest = this.#map.keys().next()
|
|
402
|
+
if (oldest.done)
|
|
403
|
+
break
|
|
404
|
+
const key = oldest.value
|
|
405
|
+
if (key === keepKey && this.#map.size === 1)
|
|
406
|
+
break
|
|
407
|
+
const evicted = this.#map.get(key)!
|
|
408
|
+
this.#map.delete(key)
|
|
409
|
+
this.#totalBytes -= evicted.bytes
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
#evictEntry(keep: CachedRouteEntry): void {
|
|
414
|
+
while (this.#totalBytes > this.#maxBytes) {
|
|
415
|
+
let victimKey: string | undefined
|
|
416
|
+
for (const [k, v] of this.#map) {
|
|
417
|
+
if (v !== keep) {
|
|
418
|
+
victimKey = k
|
|
419
|
+
break
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (victimKey === undefined)
|
|
423
|
+
break
|
|
424
|
+
const evicted = this.#map.get(victimKey)!
|
|
425
|
+
this.#map.delete(victimKey)
|
|
426
|
+
this.#totalBytes -= evicted.bytes
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Looks up a cached hit and schedules background revalidation when stale. */
|
|
432
|
+
export function serveCachedHit(
|
|
433
|
+
routeCache: RouteCache,
|
|
434
|
+
key: string,
|
|
435
|
+
request: Request,
|
|
436
|
+
requestId: string,
|
|
437
|
+
compressCache: CompressionCache | undefined,
|
|
438
|
+
revalidate: () => Promise<void>,
|
|
439
|
+
onError: (error: unknown) => void,
|
|
440
|
+
): Response | undefined {
|
|
441
|
+
const hit = routeCache.lookup(key)
|
|
442
|
+
if (hit === undefined)
|
|
443
|
+
return undefined
|
|
444
|
+
if (hit.status === 'stale')
|
|
445
|
+
routeCache.revalidate(key, revalidate, onError)
|
|
446
|
+
return routeCache.respondHit(hit.entry, request, requestId, compressCache)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Creates a `RouteCache` unless disabled (`dev`, build prerendering, or `routeCache: false`). */
|
|
450
|
+
export function createRouteCache(option: RouteCacheOptions | false | undefined, disabled = false): RouteCache | undefined {
|
|
451
|
+
if (disabled || option === false)
|
|
452
|
+
return undefined
|
|
453
|
+
return new RouteCache(option)
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const PRIVATE_HEADER_NAMES = new Set(['cookie', 'authorization'])
|
|
457
|
+
const BULK_HEADER_KEYS = new Set<PropertyKey>(['entries', 'values', 'keys', 'forEach', 'toJSON', 'getSetCookie', Symbol.iterator])
|
|
458
|
+
|
|
459
|
+
export interface PrivateReadTracker {
|
|
460
|
+
readonly ctx: RequestContext
|
|
461
|
+
readonly locals: RequestContext['locals']
|
|
462
|
+
readonly consent: RequestContext['consent']
|
|
463
|
+
readonly didReadPrivate: () => boolean
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function wrapTrackedHeaders(headers: Headers, mark: () => void): Headers {
|
|
467
|
+
return new Proxy(headers, {
|
|
468
|
+
get(target, prop) {
|
|
469
|
+
if (prop === 'get' || prop === 'has') {
|
|
470
|
+
const fn = target[prop].bind(target) as (name: string) => unknown
|
|
471
|
+
return (name: string) => {
|
|
472
|
+
if (PRIVATE_HEADER_NAMES.has(String(name).toLowerCase()))
|
|
473
|
+
mark()
|
|
474
|
+
return fn(name)
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (BULK_HEADER_KEYS.has(prop) || (typeof prop === 'string' && PRIVATE_HEADER_NAMES.has(prop.toLowerCase())))
|
|
478
|
+
mark()
|
|
479
|
+
const value = Reflect.get(target, prop, target)
|
|
480
|
+
return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
|
|
481
|
+
},
|
|
482
|
+
ownKeys(target) {
|
|
483
|
+
mark()
|
|
484
|
+
return Reflect.ownKeys(target)
|
|
485
|
+
},
|
|
486
|
+
})
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Tracks runtime reads of per-visitor request data on a cached route so private HTML is never stored or shared. */
|
|
490
|
+
export function trackPrivateReads(ctx: RequestContext): PrivateReadTracker {
|
|
491
|
+
let readPrivate = false
|
|
492
|
+
const mark = (): void => { readPrivate = true }
|
|
493
|
+
const locals = new Proxy(ctx.locals, {
|
|
494
|
+
get(target, prop, receiver) {
|
|
495
|
+
mark()
|
|
496
|
+
return Reflect.get(target, prop, receiver)
|
|
497
|
+
},
|
|
498
|
+
has(target, prop) {
|
|
499
|
+
mark()
|
|
500
|
+
return Reflect.has(target, prop)
|
|
501
|
+
},
|
|
502
|
+
ownKeys(target) {
|
|
503
|
+
mark()
|
|
504
|
+
return Reflect.ownKeys(target)
|
|
505
|
+
},
|
|
506
|
+
})
|
|
507
|
+
const consent: RequestContext['consent'] = ctx.consent !== undefined
|
|
508
|
+
? new Proxy(ctx.consent, {
|
|
509
|
+
get(target, prop) {
|
|
510
|
+
mark()
|
|
511
|
+
const value = Reflect.get(target, prop, target)
|
|
512
|
+
return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
|
|
513
|
+
},
|
|
514
|
+
})
|
|
515
|
+
: ctx.consent
|
|
516
|
+
let headersProxy: Headers | undefined
|
|
517
|
+
const request = new Proxy(ctx.request, {
|
|
518
|
+
get(target, prop) {
|
|
519
|
+
if (prop === 'headers')
|
|
520
|
+
return headersProxy ??= wrapTrackedHeaders(target.headers, mark)
|
|
521
|
+
const value = Reflect.get(target, prop, target)
|
|
522
|
+
return typeof value === 'function' ? (value as (...args: unknown[]) => unknown).bind(target) : value
|
|
523
|
+
},
|
|
524
|
+
})
|
|
525
|
+
const trackedCtx: RequestContext = {
|
|
526
|
+
url: ctx.url,
|
|
527
|
+
params: ctx.params,
|
|
528
|
+
requestId: ctx.requestId,
|
|
529
|
+
region: ctx.region,
|
|
530
|
+
json: ctx.json,
|
|
531
|
+
text: ctx.text,
|
|
532
|
+
redirect: ctx.redirect,
|
|
533
|
+
deny: ctx.deny,
|
|
534
|
+
get request() { return request },
|
|
535
|
+
get cookies() { mark(); return ctx.cookies },
|
|
536
|
+
get locals() { return locals },
|
|
537
|
+
get consent() { mark(); return consent },
|
|
538
|
+
get ip() { mark(); return ctx.ip },
|
|
539
|
+
}
|
|
540
|
+
return { ctx: trackedCtx, locals, consent, didReadPrivate: () => readPrivate }
|
|
541
|
+
}
|