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.
Files changed (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
4
  import type { PrunelleChild } from '../jsx-runtime'
5
- import type { ServerErrorInfo, ServerRuntimeConfig } from '../plugins/index'
5
+ import type { ServerErrorInfo, ServerRuntimeConfig, ServiceKey } from '../plugins/index'
6
6
  import type { NormalizedConsentConfig, RequestConsent } from './consent'
7
7
  import type { Cookies } from './cookies'
8
8
  import type { PrunelleLocals } from './index'
@@ -10,8 +10,10 @@ import type { TrustProxy } from './security'
10
10
  import { createRequestConsent } from './consent'
11
11
  import { CookieStore } from './cookies'
12
12
  import { nodeEnv } from './env'
13
+ import { resolveFallbackRequestId } from './health'
13
14
  import { requestedRegion } from './region'
14
- import { getClientIp, isHttpsRequest } from './security'
15
+ import { GATED_ROUTE_CACHE_CONTROL } from './route-cache'
16
+ import { expectedOrigin, getClientIp, isHttpsRequest } from './security'
15
17
 
16
18
  export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
17
19
 
@@ -31,21 +33,41 @@ export function isNotFound(value: unknown): value is NotFoundResult {
31
33
  return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
32
34
  }
33
35
 
34
- type SegmentParam<Seg extends string> =
35
- Seg extends `[...${infer Name}]`
36
- ? { [K in Name]: string }
37
- : Seg extends `[${infer Name}]`
38
- ? { [K in Name]: string }
39
- : Seg extends `*${infer Name}`
40
- ? { [K in Name extends '' ? 'rest' : Name]: string }
41
- : Seg extends `:${infer Name}`
42
- ? { [K in Name]: string }
43
- : unknown
44
-
45
- type MergeParams<A, B> = {
46
- [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
36
+ /** Maps built-in (and augmented) route param matcher names to their TypeScript param value types. */
37
+ export interface ParamMatcherTypes {
38
+ integer: `${number}`
39
+ uuid: `${string}-${string}-${string}-${string}-${string}`
40
+ slug: string
47
41
  }
48
42
 
43
+ type MatcherValue<Name extends string> = Name extends keyof ParamMatcherTypes ? ParamMatcherTypes[Name] : string
44
+
45
+ type ParseParamSpec<Spec extends string> =
46
+ Spec extends `${infer Name}=${infer Matcher}`
47
+ ? [Name, MatcherValue<Matcher>]
48
+ : [Spec, string]
49
+
50
+ type SegmentParam<Seg extends string> =
51
+ Seg extends `(${string})`
52
+ ? unknown
53
+ : Seg extends `[[${infer Spec}]]`
54
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
55
+ : Seg extends `[...${infer Spec}]`
56
+ ? { [K in ParseParamSpec<Spec>[0]]: string }
57
+ : Seg extends `[${infer Spec}]`
58
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
59
+ : Seg extends `*${infer Spec}`
60
+ ? { [K in ParseParamSpec<Spec>[0] extends '' ? 'rest' : ParseParamSpec<Spec>[0]]: string }
61
+ : Seg extends `:${infer Spec}?`
62
+ ? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
63
+ : Seg extends `:${infer Spec}`
64
+ ? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
65
+ : unknown
66
+
67
+ type MergeParams<A, B> = unknown extends B
68
+ ? A
69
+ : { [K in keyof (Omit<A, keyof B> & B)]: (Omit<A, keyof B> & B)[K] }
70
+
49
71
  type ExtractRouteParamsRec<Path extends string, Acc = {}> =
50
72
  Path extends `${infer Seg}/${infer Rest}`
51
73
  ? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
@@ -53,7 +75,7 @@ type ExtractRouteParamsRec<Path extends string, Acc = {}> =
53
75
  ? Acc
54
76
  : MergeParams<Acc, SegmentParam<Path>>
55
77
 
56
- /** Extracts typed route params from a Prunelle route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
78
+ /** Extracts typed route params from a Prunelle route path (`'/notices/[id=integer]'` -> `{ id: `${number}` }`, `'/[[lang]]/about'` -> `{ lang?: string | undefined }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
57
79
  export type ExtractRouteParams<Path extends string> =
58
80
  string extends Path
59
81
  ? Record<string, string>
@@ -91,11 +113,22 @@ export interface LayoutProps<Path extends string = string> {
91
113
  url: URL
92
114
  }
93
115
 
116
+ /** Props passed to a Prunelle status page (`_401.tsx`, `_403.tsx`, `_404.tsx`, `_429.tsx`, `_503.tsx`). */
117
+ export interface StatusPageProps<Path extends string = string> {
118
+ status: number
119
+ message: string
120
+ params: ExtractRouteParams<Path>
121
+ locals: PrunelleLocals
122
+ url: URL
123
+ }
124
+
94
125
  export interface ServerOptions extends ServerRuntimeConfig {
95
126
  root: string
96
127
  outDir?: string | undefined
97
128
  port?: number | undefined
98
129
  dev?: boolean | undefined
130
+ /** @internal The address `prunelle dev` binds, from which plugins get `api.devExposed`. */
131
+ devHost?: string | undefined
99
132
  nodeEnv?: string | undefined
100
133
  /** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
101
134
  importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
@@ -103,6 +136,8 @@ export interface ServerOptions extends ServerRuntimeConfig {
103
136
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
104
137
  /** @internal The build's prerender server, which runs before the production environment exists, so plugin `requires` are not checked. */
105
138
  prerender?: boolean | undefined
139
+ /** @internal True during a `--static` export, which ships static HTML directly and must enforce plugin `requires` in production. */
140
+ static?: boolean | undefined
106
141
  }
107
142
 
108
143
  export interface RequestContext<Params = Record<string, string>> {
@@ -113,11 +148,14 @@ export interface RequestContext<Params = Record<string, string>> {
113
148
  consent: RequestConsent
114
149
  locals: PrunelleLocals
115
150
  ip?: string | undefined
151
+ /** Unique identifier for this request, echoed in the `x-request-id` response header and passed to `onError`. */
152
+ readonly requestId: string
116
153
  /** The region a `data-pru-target` link or form asked for alone (`x-pru-region`): `load()` can skip the data the others show. */
117
154
  readonly region?: string | undefined
118
155
  json: (data: unknown, init?: ResponseInit) => Response
119
156
  text: (body: string, init?: ResponseInit) => Response
120
- redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
157
+ /** A redirect to a path or a URL of this site; one to another site throws unless `{ external: true }` says the app chose that target (never one read from the request). */
158
+ redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308, options?: RedirectOptions) => Response
121
159
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
122
160
  }
123
161
 
@@ -129,12 +167,16 @@ export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) =>
129
167
  export type PrunelleServer = ReturnType<typeof Bun.serve>
130
168
 
131
169
  export interface PrunelleApp {
132
- handle: (request: Request, remoteIp?: string) => Promise<Response>
170
+ handle: (request: Request, remoteIp?: string, disableTimeout?: () => void) => Promise<Response>
133
171
  serve: (port?: number, hostname?: string) => PrunelleServer
134
172
  /** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
135
173
  reloadInto?: (server: PrunelleServer) => void
174
+ /** Looks up a server-scoped plugin service registered during `server(api)` (e.g. `JOBS_SERVICE`). */
175
+ inject?: <T>(key: ServiceKey<T>) => T | undefined
136
176
  /** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
137
177
  closeStreams?: () => Promise<void>
178
+ /** @internal The security headers each response of this app carries, which the 503 of a build swap in `prunelle start` repeats. */
179
+ securityHeaders?: Readonly<Record<string, string>> | undefined
138
180
  /** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
139
181
  dispose?: () => Promise<void>
140
182
  }
@@ -155,9 +197,11 @@ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
155
197
  outDir?: string | undefined
156
198
  publicDir?: string | undefined
157
199
  dev?: boolean | undefined
200
+ devHost?: string | undefined
158
201
  nodeEnv?: string | undefined
159
202
  errorSink?: ((info: ServerErrorInfo) => void) | undefined
160
203
  prerender?: boolean | undefined
204
+ static?: boolean | undefined
161
205
  }
162
206
 
163
207
  export const MIME: Record<string, string> = {
@@ -210,6 +254,9 @@ export interface RequestContextOptions {
210
254
  /** The parsed `request.url`, when the caller already has it. */
211
255
  url?: URL | undefined
212
256
  consent?: NormalizedConsentConfig | undefined
257
+ requestId?: string | undefined
258
+ /** The app's `site` is https: cookies get `Secure` even when a proxy the server does not trust hides the scheme. */
259
+ httpsSite?: boolean | undefined
213
260
  }
214
261
 
215
262
  // None of these read the request, so every context shares them.
@@ -230,8 +277,62 @@ const text: RequestContext['text'] = (body, init) => {
230
277
  headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
231
278
  return new Response(body, { ...init, headers })
232
279
  }
233
- const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
234
- const deny: RequestContext['deny'] = (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status })
280
+ export interface DeniedInfo {
281
+ status: number
282
+ message: string
283
+ fieldErrors?: Record<string, string> | undefined
284
+ }
285
+
286
+ const DENIED_RESPONSES = new WeakMap<Response, DeniedInfo>()
287
+
288
+ /** Metadata attached to a `Response` produced by `ctx.deny()`. */
289
+ export function getDeniedInfo(res: Response): DeniedInfo | undefined {
290
+ return DENIED_RESPONSES.get(res)
291
+ }
292
+
293
+ export interface RedirectOptions {
294
+ /** Allows a target on another site: a payment page, an identity provider, a redirect rule the app wrote itself. */
295
+ external?: boolean | undefined
296
+ }
297
+
298
+ const EXTERNAL_REDIRECTS = new WeakSet<Response>()
299
+
300
+ /** Whether `res` came from `ctx.redirect(url, status, { external: true })`: the one kind of cross-site redirect an island's action call follows. */
301
+ export function isExternalRedirect(res: Response): boolean {
302
+ return EXTERNAL_REDIRECTS.has(res)
303
+ }
304
+
305
+ const REDIRECT_CONTROL_CHAR_RE = /[\u0000-\u001F\u007F]/
306
+ const NON_HIERARCHICAL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:(?!\/\/)/i
307
+
308
+ function sameOrigin(location: string, baseOrigin: string): boolean {
309
+ if (baseOrigin === 'null' || REDIRECT_CONTROL_CHAR_RE.test(location) || NON_HIERARCHICAL_SCHEME_RE.test(location.trimStart()))
310
+ return false
311
+ try {
312
+ return new URL(location, baseOrigin).origin === baseOrigin
313
+ }
314
+ catch {
315
+ return false
316
+ }
317
+ }
318
+
319
+ const makeRedirect = (request: Request, trustProxy: TrustProxy, url: URL): RequestContext['redirect'] => (location, status = 302, options) => {
320
+ const external = options?.external === true
321
+ if (!external) {
322
+ const baseOrigin = expectedOrigin(request, trustProxy, url)
323
+ if (!sameOrigin(location, baseOrigin))
324
+ throw new Error(`prunelle: ctx.redirect("${location}") leaves ${baseOrigin}: redirect to a path of this site, or pass { external: true } as the third argument when the app chose that address itself (never one read from the request, which makes an open redirect).`)
325
+ }
326
+ const res = new Response(null, { status, headers: { location } })
327
+ if (external)
328
+ EXTERNAL_REDIRECTS.add(res)
329
+ return res
330
+ }
331
+ const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
332
+ const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
333
+ DENIED_RESPONSES.set(res, { status, message, fieldErrors })
334
+ return res
335
+ }
235
336
 
236
337
  /** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
237
338
  export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
@@ -258,26 +359,34 @@ export function makeRequestContext(
258
359
  const remoteIp = opts?.remoteIp
259
360
  const consentConfig = opts?.consent
260
361
  let cachedConsent: RequestConsent | undefined
362
+ let cachedConsentRaw: string | undefined
261
363
  const cookieStore = new CookieStore(
262
364
  request.headers.get('cookie'),
263
- isHttpsRequest(request, trustProxy),
365
+ opts?.httpsSite === true || isHttpsRequest(request, trustProxy),
264
366
  category => getConsent().has(category),
265
367
  )
266
368
  const getConsent = (): RequestConsent => {
267
- cachedConsent ??= createRequestConsent(consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined, consentConfig)
369
+ const raw = consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined
370
+ if (cachedConsent === undefined || raw !== cachedConsentRaw) {
371
+ cachedConsentRaw = raw
372
+ cachedConsent = createRequestConsent(raw, consentConfig)
373
+ }
268
374
  return cachedConsent
269
375
  }
376
+ const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
270
377
  let cachedIp: string | undefined
271
378
  let ipComputed = false
379
+ const url = opts?.url ?? new URL(request.url)
272
380
  const ctx: RequestContext = {
273
381
  request,
274
- url: opts?.url ?? new URL(request.url),
382
+ url,
275
383
  params,
276
384
  cookies: cookieStore,
277
385
  get consent() {
278
386
  return getConsent()
279
387
  },
280
388
  locals: {},
389
+ requestId,
281
390
  get ip() {
282
391
  if (!ipComputed) {
283
392
  ipComputed = true
@@ -294,7 +403,7 @@ export function makeRequestContext(
294
403
  },
295
404
  json,
296
405
  text,
297
- redirect,
406
+ redirect: makeRedirect(request, trustProxy, url),
298
407
  deny,
299
408
  }
300
409
  return { ctx, cookieStore }
@@ -302,15 +411,24 @@ export function makeRequestContext(
302
411
 
303
412
  /** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
304
413
  export function wantsJson(request: Request): boolean {
305
- return (request.headers.get('accept') ?? '').includes('application/json')
306
- || (request.headers.get('content-type') ?? '').includes('application/json')
414
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('application/json')
415
+ || (request.headers.get('content-type') ?? '').toLowerCase().includes('application/json')
307
416
  }
308
417
 
418
+ /** True when the client explicitly accepts HTML and does not ask for JSON (e.g. browser navigation). */
419
+ export function acceptsHtml(request: Request): boolean {
420
+ if (wantsJson(request))
421
+ return false
422
+ return (request.headers.get('accept') ?? '').toLowerCase().includes('text/html')
423
+ }
424
+
425
+ const PUBLIC_CACHE_RE = /\bpublic\b/i
426
+
309
427
  /** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
310
428
  export async function enforceRequestBodyLimit(
311
429
  request: Request,
312
430
  maxBytes: number,
313
- ): Promise<{ ok: true, request: Request } | { ok: false }> {
431
+ ): Promise<{ ok: true, request: Request } | { ok: false, aborted?: true }> {
314
432
  if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
315
433
  return { ok: true, request }
316
434
 
@@ -332,9 +450,16 @@ export async function enforceRequestBodyLimit(
332
450
  let total = 0
333
451
  try {
334
452
  while (true) {
335
- const { done, value } = await reader.read()
336
- if (done)
453
+ let read: Awaited<ReturnType<typeof reader.read>>
454
+ try {
455
+ read = await reader.read()
456
+ }
457
+ catch {
458
+ return { ok: false, aborted: true }
459
+ }
460
+ if (read.done)
337
461
  break
462
+ const { value } = read
338
463
  total += value.byteLength
339
464
  if (total > maxBytes) {
340
465
  try {
@@ -350,12 +475,21 @@ export async function enforceRequestBodyLimit(
350
475
  reader.releaseLock()
351
476
  }
352
477
 
353
- const combined = new Uint8Array(total)
354
- let offset = 0
355
- for (let i = 0; i < chunks.length; i++) {
356
- const chunk = chunks[i]!
357
- combined.set(chunk, offset)
358
- offset += chunk.byteLength
478
+ let combined: Uint8Array<ArrayBuffer>
479
+ if (chunks.length === 1) {
480
+ const only = chunks[0]!
481
+ combined = only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength
482
+ ? only as Uint8Array<ArrayBuffer>
483
+ : new Uint8Array(only)
484
+ }
485
+ else {
486
+ combined = new Uint8Array(total)
487
+ let offset = 0
488
+ for (let i = 0; i < chunks.length; i++) {
489
+ const chunk = chunks[i]!
490
+ combined.set(chunk, offset)
491
+ offset += chunk.byteLength
492
+ }
359
493
  }
360
494
 
361
495
  headers.delete('transfer-encoding')
@@ -377,8 +511,9 @@ export function applyHstsHeader(
377
511
  trustProxy: TrustProxy,
378
512
  isDev = false,
379
513
  resolvedEnv?: string,
514
+ httpsSite = false,
380
515
  ): Response {
381
- if (hstsValue === undefined || isDev || !isHttpsRequest(request, trustProxy))
516
+ if (hstsValue === undefined || isDev || !(httpsSite || isHttpsRequest(request, trustProxy)))
382
517
  return res
383
518
  const env = resolvedEnv ?? nodeEnv()
384
519
  if (env === 'development' || env === 'test')
@@ -396,23 +531,35 @@ export function applyHstsHeader(
396
531
  }
397
532
  }
398
533
 
399
- /** Adds the pending cookies (when any) and the security headers the response does not set itself. */
534
+ /** Adds the pending cookies (when any), security headers, `x-request-id`, and dev `Server-Timing`. */
400
535
  export function finalizeResponse(
401
536
  res: Response,
402
537
  cookieStore: CookieStore | undefined,
403
538
  entries: readonly [string, string][],
539
+ requestId?: string,
540
+ serverTiming?: string,
404
541
  ): Response {
405
542
  const hasCookies = cookieStore?.hasChanges === true
406
- if (!hasCookies && entries.length === 0)
543
+ const hasRequestId = requestId !== undefined
544
+ const hasTiming = serverTiming !== undefined && serverTiming !== ''
545
+ if (!hasCookies && entries.length === 0 && !hasRequestId && !hasTiming)
407
546
  return res
408
547
 
409
548
  const apply = (h: Headers): void => {
410
- if (hasCookies)
549
+ if (hasCookies) {
411
550
  cookieStore!.applyTo(h)
551
+ const cc = h.get('cache-control')
552
+ if (cc !== null && (PUBLIC_CACHE_RE.test(cc) || cc === GATED_ROUTE_CACHE_CONTROL))
553
+ h.set('cache-control', 'private, no-store')
554
+ }
412
555
  for (const [k, v] of entries) {
413
556
  if (!h.has(k))
414
557
  h.set(k, v)
415
558
  }
559
+ if (hasRequestId && !h.has('x-request-id'))
560
+ h.set('x-request-id', requestId)
561
+ if (hasTiming)
562
+ h.set('server-timing', serverTiming)
416
563
  }
417
564
  // Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
418
565
  try {