prunelle 0.1.1 → 0.2.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 (48) hide show
  1. package/llms.txt +12 -12
  2. package/package.json +1 -1
  3. package/src/build/client-entries.ts +3 -2
  4. package/src/build/compile.ts +2 -1
  5. package/src/build/index.ts +68 -29
  6. package/src/build/manifest.ts +18 -1
  7. package/src/build/output.ts +2 -2
  8. package/src/build/precompress.ts +15 -2
  9. package/src/build/prerender.ts +2 -2
  10. package/src/build/routes.ts +171 -10
  11. package/src/build/static.ts +71 -17
  12. package/src/build/status-pages.ts +127 -0
  13. package/src/cli/check-forms.ts +654 -0
  14. package/src/cli/check-links.ts +619 -0
  15. package/src/cli/check.ts +37 -4
  16. package/src/cli/commands.ts +5 -3
  17. package/src/cli/inspect.ts +21 -2
  18. package/src/cli/upgrade-names.ts +73 -13
  19. package/src/cli/upgrade.ts +137 -16
  20. package/src/compiler/compliance-rgaa.ts +502 -0
  21. package/src/compiler/compliance.ts +119 -220
  22. package/src/compiler/ssr.ts +121 -24
  23. package/src/dom/action.ts +4 -1
  24. package/src/dom/island.ts +5 -5
  25. package/src/plugins/config.ts +1 -1
  26. package/src/plugins/types.ts +13 -0
  27. package/src/server/action-protect.ts +186 -0
  28. package/src/server/action.ts +33 -10
  29. package/src/server/errors.ts +291 -62
  30. package/src/server/form-schema.ts +343 -0
  31. package/src/server/health.ts +244 -0
  32. package/src/server/http.ts +84 -17
  33. package/src/server/index.ts +162 -91
  34. package/src/server/param-matchers.ts +112 -0
  35. package/src/server/plugin-host.ts +40 -14
  36. package/src/server/public.ts +3 -3
  37. package/src/server/route-table.ts +5 -2
  38. package/src/server/router.ts +125 -40
  39. package/src/server/routing.ts +95 -57
  40. package/src/server/security.ts +171 -22
  41. package/src/server/serve-handlers.ts +21 -7
  42. package/src/ssr/context.ts +49 -0
  43. package/src/ssr/index.ts +120 -1
  44. package/src/test/browser.ts +6 -0
  45. package/src/test/index.ts +17 -3
  46. package/templates/_shared/src/routes/legal.tsx +5 -0
  47. package/templates/blog/prunelle.config.ts +1 -1
  48. package/templates/blog/src/routes/index.tsx +4 -0
@@ -7,12 +7,15 @@
7
7
 
8
8
  import type { Html, HydrateStrategy } from '../jsx-runtime'
9
9
  import type { ActionRegistry, RegisteredAction } from './action-registry'
10
+ import type { ServedFile } from './assets'
10
11
  import type { NormalizedConsentConfig } from './consent'
11
12
  import type { CookieStore } from './cookies'
12
13
  import type { NotifyError } from './errors'
13
- import type { EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
14
+ import type { DevTiming } from './health'
15
+ import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
14
16
  import type { RateLimiter, RateLimitStore } from './rate-limit'
15
17
  import type { LoadedMiddlewareModule } from './page'
18
+ import type { ServerPluginHost } from './plugin-host'
16
19
  import type { RequestPath } from './request-path'
17
20
  import type { CompiledRoute } from './route-table'
18
21
  import type { FastHandler } from './routing'
@@ -29,9 +32,11 @@ import { CompressionCache, compressedHtmlResponse, compressedHtmlStream, markCom
29
32
  import { normalizeConsentConfig } from './consent'
30
33
  import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeStyleHashes, resolveRenderedIslands, revivePreload, withPluginHtmlCsp } from './document'
31
34
  import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
32
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
35
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, endTimer, formatServerTiming, runTimedChain, startTimer, withRequestId } from './health'
36
+ import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
33
37
  import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
34
- import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
38
+ import { resolveParamMatchers } from './param-matchers'
39
+ import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
35
40
 
36
41
  import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
37
42
  import { decodeRequestPath, literalPath } from './request-path'
@@ -57,8 +62,9 @@ export type { CompressionEncoding, PrecompressedEncoding } from './compress'
57
62
  export type { RequestConsent } from './consent'
58
63
  export type { CookieOptions, Cookies } from './cookies'
59
64
  export { defineEnv, nodeEnv } from './env'
65
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
60
66
  export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
61
- export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
67
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
62
68
  export { createServer } from './loader'
63
69
  export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
64
70
  export type { SecurityHeadersOptions, TrustProxy } from './security'
@@ -70,6 +76,25 @@ const DEFAULT_STREAM_TIMEOUT = 30_000
70
76
 
71
77
 
72
78
  const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
79
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => typeof mod[method] === 'function' || (method === 'HEAD' && typeof mod.GET === 'function')
80
+
81
+ function maybeRenderDenied(
82
+ res: Response,
83
+ request: Request,
84
+ url: URL,
85
+ ctx: RequestContext,
86
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
87
+ routeFile?: string,
88
+ isApi = false,
89
+ ): Response | Promise<Response> {
90
+ if (isApi)
91
+ return res
92
+ const denied = getDeniedInfo(res)
93
+ if (denied === undefined || !acceptsHtml(request))
94
+ return res
95
+ return renderDenied(denied, url, request, ctx, routeFile)
96
+ }
97
+
73
98
  const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
74
99
  // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
75
100
  const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
@@ -82,6 +107,34 @@ function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string |
82
107
  return map.get(staticPath) ?? map.get(normPath)
83
108
  }
84
109
 
110
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
111
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
112
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
113
+ }
114
+
115
+ function matchStaticOrPublic(
116
+ request: Request,
117
+ requestPath: RequestPath,
118
+ assetMap: ReadonlyMap<string, ServedFile>,
119
+ publicMap: ReadonlyMap<string, ServedFile>,
120
+ pluginRouter: ServerPluginHost['router'],
121
+ ): ServedFile | undefined {
122
+ const { staticPath } = requestPath
123
+ if (staticPath === undefined)
124
+ return undefined
125
+ const asset = assetMap.get(staticPath)
126
+ if (asset !== undefined)
127
+ return asset
128
+ const pub = publicMap.get(staticPath)
129
+ if (pub === undefined)
130
+ return undefined
131
+ const matchedPlugin = pluginRouter.match(requestPath)
132
+ const reqMethod = request.method.toUpperCase()
133
+ const shadowedByPlugin = matchedPlugin !== undefined
134
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
135
+ return shadowedByPlugin ? undefined : pub
136
+ }
137
+
85
138
  async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
86
139
  const { entry, mod, layouts } = route
87
140
  let inner: string
@@ -103,6 +156,26 @@ async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: R
103
156
  }
104
157
 
105
158
 
159
+ function createRequestGuards(
160
+ maxRequestBodySize: number,
161
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
162
+ ) {
163
+ const refuseCrossSite = (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string): Response =>
164
+ finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore, requestId)
165
+
166
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
167
+ if (bodyLimited)
168
+ return request
169
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
170
+ if (bounded.ok)
171
+ return bounded.request
172
+ return finish(wantsJson(request)
173
+ ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
174
+ : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
175
+ }
176
+ return { refuseCrossSite, checkBodyLimit }
177
+ }
178
+
106
179
  interface ActionDispatcherDeps {
107
180
  actions: ActionRegistry
108
181
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
@@ -110,15 +183,16 @@ interface ActionDispatcherDeps {
110
183
  trustProxy: TrustProxy
111
184
  consent: NormalizedConsentConfig | undefined
112
185
  rateLimits: RateLimitStore
113
- refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore) => Response
114
- checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore) => Promise<Request | Response>
115
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
186
+ isDev: boolean
187
+ refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string) => Response
188
+ checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
189
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
116
190
  notifyError: NotifyError
117
191
  renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
118
192
  }
119
193
 
120
194
  function createActionDispatcher(deps: ActionDispatcherDeps) {
121
- const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
195
+ const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
122
196
  const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
123
197
  const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
124
198
  if (act.rateLimit === undefined)
@@ -137,6 +211,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
137
211
  rawPathname: string,
138
212
  remoteIp: string | undefined,
139
213
  bodyLimited: boolean,
214
+ requestId: string,
140
215
  existing?: { ctx: RequestContext, cookieStore: CookieStore },
141
216
  ): Promise<Response> => {
142
217
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
@@ -144,29 +219,30 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
144
219
  if (actionHandler !== undefined) {
145
220
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
146
221
  if (!originCheck.ok)
147
- return refuseCrossSite(request, originCheck.reason, existing?.cookieStore)
148
- const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore)
222
+ return refuseCrossSite(request, originCheck.reason, existing?.cookieStore, requestId)
223
+ const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
149
224
  if (checked instanceof Response)
150
225
  return checked
151
226
  req = checked
152
227
  }
153
228
  const { act, middlewares } = registeredAction
154
- const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent })
229
+ const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent, requestId })
155
230
  ctx.request = req
156
231
  if (existing === undefined && rewrites.length > 0) {
157
232
  for (const rewrite of rewrites)
158
233
  rewrite(rawPathname, ctx)
159
234
  }
235
+ const timing = createTiming(isDev)
160
236
  try {
161
- const res = await actions.run(ctx, () => runChain(ctx, middlewares, () =>
237
+ const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
162
238
  actionHandler !== undefined
163
239
  ? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
164
240
  : methodNotAllowed('POST'),
165
- ))
166
- return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore)
241
+ timing, runChain))
242
+ return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
167
243
  }
168
244
  catch (error) {
169
- notifyError(error, req, 'action')
245
+ notifyError(error, req, 'action', ctx.requestId)
170
246
  return renderError(error, cookieStore, ctx.url, req, ctx)
171
247
  }
172
248
  }
@@ -223,7 +299,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
223
299
  const hstsValue = resolveHstsValue(security)
224
300
  const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
225
301
  // The one way out of every response not built with the security headers already in place.
226
- const finish = (res: Response, request: Request, cookieStore?: CookieStore): Response => withHsts(finalizeResponse(res, cookieStore, securityEntries), request)
302
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
303
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
304
+ const resolveRequestId = createRequestIdResolver(trustProxy)
227
305
  const serverError = makeServerError(securityRecord)
228
306
  const fileGone = makeFileGone(securityRecord)
229
307
  const navigation = createNavigation(config.navigation)
@@ -266,19 +344,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
266
344
  trustedOrigins,
267
345
  })
268
346
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
347
+ const healthPath = `${assetPrefix}/health`
348
+ const healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId })
269
349
  const hasPluginRewrites = pluginHost.rewrites.length > 0
270
350
  const routesPrefix = inferRoutesServerPrefix(manifest)
351
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
271
352
  const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
272
- const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix)
353
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
273
354
  const pluginMiddlewaresFor = (effectiveScopedPath: string, rawScopedPath: string): readonly Middleware[] =>
274
- effectiveScopedPath === rawScopedPath
275
- ? middlewaresFor(effectiveScopedPath)
276
- : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
355
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
277
356
 
278
357
  registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
279
-
280
-
281
- const { buildNotFoundResponse, renderError } = createFallbackPages({ manifest, modules, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
358
+ const { buildNotFoundResponse, renderError, renderDenied } = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
282
359
 
283
360
  async function renderNotFound(
284
361
  cookieStore: CookieStore,
@@ -287,6 +364,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
287
364
  ctx: RequestContext,
288
365
  effective: RequestPath,
289
366
  rawScopedPath: string,
367
+ timing?: DevTiming,
290
368
  ): Promise<Response> {
291
369
  const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
292
370
  const ancestor = ancestorMiddlewaresFor(effective)
@@ -294,34 +372,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
294
372
  ctx.params = ancestor.params
295
373
  const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
296
374
  try {
297
- const res = await actions.run(ctx, () => runChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx)))
298
- return finish(res, request, cookieStore)
375
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
376
+ return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
299
377
  }
300
378
  catch (error) {
301
- notifyError(error, request, 'route')
379
+ notifyError(error, request, 'route', ctx.requestId)
302
380
  return renderError(error, cookieStore, url, request, ctx)
303
381
  }
304
382
  }
305
383
 
306
- function refuseCrossSite(request: Request, reason: string, cookieStore?: CookieStore): Response {
307
- return finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore)
308
- }
309
-
310
- async function checkBodyLimit(request: Request, bodyLimited: boolean, cookieStore?: CookieStore): Promise<Request | Response> {
311
- if (bodyLimited)
312
- return request
313
- const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
314
- if (bounded.ok)
315
- return bounded.request
316
- return finish(wantsJson(request)
317
- ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
318
- : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore)
319
- }
384
+ const { refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish)
320
385
 
321
386
  const { router, fastStaticPages } = compileRouteTable({
322
- manifest, modules, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
387
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
323
388
  pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
324
- fast: { trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, notifyError, finish, withHsts },
389
+ fast: { trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
325
390
  })
326
391
  const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
327
392
  prerendered,
@@ -337,6 +402,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
337
402
  ctx: RequestContext,
338
403
  disableTimeout?: () => void,
339
404
  staticPath?: string,
405
+ timing?: DevTiming,
340
406
  ): Promise<Response> {
341
407
  const { entry, mod, doc } = route
342
408
 
@@ -348,7 +414,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
348
414
  return serveFile(ctx.request, pre)
349
415
  // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
350
416
  if (pre === undefined && entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
351
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
417
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
352
418
  }
353
419
 
354
420
  // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
@@ -370,17 +436,19 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
370
436
 
371
437
  let data: unknown
372
438
  if (entry.hasLoad && typeof mod.load === 'function') {
439
+ const loadStart = startTimer(timing)
373
440
  try {
374
441
  data = await mod.load(ctx)
375
442
  }
376
443
  catch (error) {
377
444
  if (isNotFound(error))
378
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
445
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
379
446
  throw error
380
447
  }
448
+ endTimer(timing, 'load', loadStart)
381
449
  }
382
450
  if (isNotFound(data))
383
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
451
+ return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
384
452
  if (data instanceof Response)
385
453
  return data
386
454
  const pageProps: Record<string, unknown> = {
@@ -394,12 +462,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
394
462
  return respondRegion(
395
463
  ctx.request, mod, pageProps, entry.path, htmlHeaders,
396
464
  rctx => resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
397
- streamTimeout, error => notifyError(error, ctx.request, 'route'),
465
+ streamTimeout, error => notifyError(error, ctx.request, 'route', ctx.requestId),
398
466
  hasHtmlTransformers ? html => applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
399
467
  )
400
468
  }
401
469
 
402
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, ctx.request, 'route'))
470
+ const renderStart = startTimer(timing)
471
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, ctx.request, 'route', ctx.requestId))
403
472
  const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
404
473
  if (hasFlash)
405
474
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
@@ -415,72 +484,73 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
415
484
 
416
485
  // Streaming SSR when <Suspense> boundaries are pending, compressed per flush, never buffered
417
486
  if (isStreamed) {
418
- if (ctx.request.method === 'HEAD')
487
+ endTimer(timing, 'render', renderStart)
488
+ const streamStart = startTimer(timing)
489
+ if (ctx.request.method === 'HEAD') {
490
+ endTimer(timing, 'stream', streamStart)
419
491
  return markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) }))
492
+ }
420
493
  disableTimeout?.()
421
494
  const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
422
495
  // Transforms see the document with its initial body; boundaries resolved later stream as they render.
423
496
  const shell = hasHtmlTransformers ? await applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
424
497
  const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
425
- return compressedHtmlStream(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route')), 200, withRegionVary(htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, compressCache)
498
+ endTimer(timing, 'stream', streamStart)
499
+ return compressedHtmlStream(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route', ctx.requestId)), 200, withRegionVary(htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, compressCache)
426
500
  }
427
501
 
428
502
  const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
429
503
  const html = hasHtmlTransformers ? await applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
430
504
  const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
505
+ endTimer(timing, 'render', renderStart)
431
506
 
432
507
  return compressedHtmlResponse(html, 200, withRegionVary(htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions), ctx.request, compressCache)
433
508
  }
434
509
 
435
510
  const dispatchAction = createActionDispatcher({
436
- actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
511
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
437
512
  })
438
513
 
439
514
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
440
515
  async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
516
+ const requestId = resolveRequestId(request)
441
517
  try {
442
518
  const url = new URL(request.url)
443
519
  const rawPathname = url.pathname
444
520
  const requestPath = decodeRequestPath(rawPathname)
445
521
  if (requestPath === undefined)
446
- return finish(badRequest(), request)
522
+ return finish(badRequest(), request, undefined, requestId)
447
523
  const { staticPath, scopedPath } = requestPath
524
+ if (staticPath === healthPath)
525
+ return healthHandler(request, requestId)
448
526
  const read = isRead(request)
449
527
 
450
528
  // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
451
- if (read && staticPath !== undefined) {
452
- const asset = assetMap.get(staticPath)
453
- if (asset !== undefined)
454
- return serveFile(request, asset)
455
- const pub = publicMap.get(staticPath)
456
- if (pub !== undefined) {
457
- const matchedPlugin = pluginRouter.match(requestPath)
458
- const reqMethod = request.method.toUpperCase()
459
- const shadowedByPlugin = matchedPlugin !== undefined
460
- && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
461
- if (!shadowedByPlugin)
462
- return serveFile(request, pub)
463
- }
529
+ if (read) {
530
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
531
+ if (staticFile !== undefined)
532
+ return withRequestId(await serveFile(request, staticFile), requestId)
464
533
  }
465
534
 
466
535
  // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
467
536
  const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
468
537
  if (registeredAction !== undefined)
469
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited)
538
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
470
539
 
471
540
  // 3. Prerendered static HTML, then 4. the zero-overhead static route path
472
541
  const plainRead = isPlainRead(request)
473
542
  if (plainRead && staticPath !== undefined) {
474
543
  const pre = fastPrerenderedMap.get(staticPath)
475
544
  if (pre !== undefined)
476
- return serveFile(request, pre)
545
+ return withRequestId(await serveFile(request, pre), requestId)
477
546
  const fast = fastStaticPages.get(staticPath)
478
547
  if (fast !== undefined)
479
- return fast(request, remoteIp, url)
548
+ return fast(request, remoteIp, url, requestId)
480
549
  }
481
550
 
482
551
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
483
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
552
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId })
553
+ const timing = createTiming(isDev)
484
554
 
485
555
  // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
486
556
  let effectivePath = rawPathname
@@ -493,17 +563,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
493
563
  if (effectivePath !== rawPathname) {
494
564
  const rewritten = decodeRequestPath(effectivePath)
495
565
  if (rewritten === undefined)
496
- return finish(badRequest(), request, cookieStore)
566
+ return finish(badRequest(), request, cookieStore, requestId)
497
567
  effective = rewritten
498
568
  const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
499
569
  if (rewrittenAction !== undefined)
500
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, { ctx, cookieStore })
570
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
501
571
  }
502
572
  const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
503
573
 
504
574
  // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
505
575
  const method = request.method.toUpperCase()
506
- const pluginMatch = pluginRouter.match(effective)
576
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
507
577
  const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
508
578
  const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
509
579
  const routeDef = directPluginDef ?? headFallbackPluginDef
@@ -511,24 +581,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
511
581
  if (routeDef.csrf) {
512
582
  const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
513
583
  if (!originCheck.ok)
514
- return refuseCrossSite(request, originCheck.reason, cookieStore)
584
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
515
585
  }
516
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
586
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
517
587
  if (checked instanceof Response)
518
588
  return checked
519
589
  ctx.request = checked
520
590
  ctx.params = pluginMatch.params
521
591
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
522
592
  try {
523
- let res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => routeDef.handler(ctx)))
593
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
524
594
  if (headFallbackPluginDef !== undefined)
525
595
  res = stripHeadBody(res)
526
596
  else if (isEventStream(res))
527
597
  res = streams.track(res, disableTimeout)
528
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore)
598
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
529
599
  }
530
600
  catch (error) {
531
- notifyError(error, ctx.request, 'plugin')
601
+ notifyError(error, ctx.request, 'plugin', requestId)
532
602
  return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
533
603
  }
534
604
  }
@@ -537,7 +607,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
537
607
  if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
538
608
  const pub = publicMap.get(effectiveStaticPath)
539
609
  if (pub !== undefined)
540
- return serveFile(request, pub)
610
+ return withRequestId(await serveFile(request, pub), requestId)
541
611
  }
542
612
 
543
613
  const matched = router.match(effective)
@@ -547,15 +617,15 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
547
617
  const allow = allowedPluginMethodsHeader(pluginMatch.data)
548
618
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
549
619
  try {
550
- const res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => methodNotAllowed(allow)))
551
- return finish(res, request, cookieStore)
620
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
621
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
552
622
  }
553
623
  catch (error) {
554
- notifyError(error, request, 'plugin')
624
+ notifyError(error, request, 'plugin', requestId)
555
625
  return renderError(error, cookieStore, ctx.url, request, ctx)
556
626
  }
557
627
  }
558
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath)
628
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
559
629
  }
560
630
 
561
631
  ctx.params = matched.params
@@ -566,9 +636,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
566
636
  if (route.mod.csrf !== false) {
567
637
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
568
638
  if (!originCheck.ok)
569
- return refuseCrossSite(request, originCheck.reason, cookieStore)
639
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
570
640
  }
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
641
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
642
  if (checked instanceof Response)
573
643
  return checked
574
644
  ctx.request = checked
@@ -579,20 +649,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
579
649
  : route.middlewares
580
650
 
581
651
  try {
582
- const rawRes = await actions.run(ctx, () => runChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, disableTimeout, staticPath)))
583
- const res = isEventStream(rawRes) ? streams.track(rawRes, disableTimeout) : rawRes
652
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, disableTimeout, staticPath, timing), timing, runChain))
653
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
654
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
655
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
585
656
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
586
- return finish(finalRes, ctx.request, cookieStore)
657
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
587
658
  }
588
659
  catch (error) {
589
- notifyError(error, ctx.request, 'route')
590
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
660
+ notifyError(error, ctx.request, 'route', requestId)
661
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
591
662
  }
592
663
  }
593
664
  catch (error) {
594
- notifyError(error, request, 'route')
595
- return withHsts(isDev ? devErrorResponse(error, request) : serverError(), request)
665
+ notifyError(error, request, 'route', requestId)
666
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
596
667
  }
597
668
  }
598
669
 
@@ -602,7 +673,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
602
673
 
603
674
  const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
675
  const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
605
- const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, runRequest, runFast, notifyError, serverError, fileGone })
676
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
606
677
 
607
678
  function serve(port = 3000, hostname = '127.0.0.1') {
608
679
  const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })