prunelle 0.1.1 → 0.5.1

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 (88) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +3 -2
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. package/ts-plugin.cjs +4277 -0
@@ -5,42 +5,45 @@
5
5
  // - <Head> collection + cancel-safe streaming <Suspense> (0-overhead fast path when unused)
6
6
  // - Hybrid prerendered HTML serving + embedded single-executable mode
7
7
 
8
- import type { Html, HydrateStrategy } from '../jsx-runtime'
9
8
  import type { ActionRegistry, RegisteredAction } from './action-registry'
9
+ import type { ServedFile } from './assets'
10
10
  import type { NormalizedConsentConfig } from './consent'
11
11
  import type { CookieStore } from './cookies'
12
12
  import type { NotifyError } from './errors'
13
- import type { EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
13
+ import type { DevTiming } from './health'
14
+ import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
14
15
  import type { RateLimiter, RateLimitStore } from './rate-limit'
15
16
  import type { LoadedMiddlewareModule } from './page'
17
+ import type { ServerPluginHost } from './plugin-host'
16
18
  import type { RequestPath } from './request-path'
17
19
  import type { CompiledRoute } from './route-table'
18
20
  import type { FastHandler } from './routing'
19
21
  import type { TrustProxy } from './security'
20
22
  import { join } from 'node:path'
21
23
  import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
22
- import { createRenderContext, runWithRenderContext } from '../ssr/context'
23
24
  import { createNavigation } from '../ssr/navigation'
24
- import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
25
- import { ACTION_ERROR_COOKIE, executeAction, finishActionRedirect, hydrateActionErrorFlash, isServerAction } from './action'
25
+ import { executeAction, finishActionRedirect, isServerAction } from './action'
26
26
  import { createActionRegistry } from './action-registry'
27
27
  import { createAssets } from './assets'
28
- import { CompressionCache, compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, maybeCompressResponse } from './compress'
28
+ import { CompressionCache, maybeCompressResponse } from './compress'
29
29
  import { normalizeConsentConfig } from './consent'
30
- import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeStyleHashes, resolveRenderedIslands, revivePreload, withPluginHtmlCsp } from './document'
30
+ import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
31
31
  import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
32
- import { applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
33
- import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
34
- import { allowedPluginMethodsHeader, createServerPluginHost } from './plugin-host'
32
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
33
+ import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
34
+ import { stripHeadBody } from './page'
35
+ import { resolveParamMatchers } from './param-matchers'
36
+ import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
35
37
 
36
- import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
38
+ import { withRegionVary } from './region'
37
39
  import { decodeRequestPath, literalPath } from './request-path'
38
40
  import { nativePrerenderedCheck } from './prerendered'
39
- import { compileRouteTable } from './route-table'
41
+ import { createRouteCache } from './route-cache'
42
+ import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
40
43
  import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
41
- import { hasActionErrorCookie, isPlainRead, isRead, serveHandlers } from './serve-handlers'
42
- import { buildSecurityHeaderEntries, resolveHstsValue, styleHashesOf, verifyOrigin } from './security'
43
- import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
44
+ import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
45
+ import { buildSecurityHeaderEntries, resolveHstsValue, verifyOrigin } from './security'
46
+ import { createStreamTracker } from './stream'
44
47
 
45
48
  /**
46
49
  * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
@@ -48,8 +51,9 @@ import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
48
51
  */
49
52
  export interface PrunelleLocals {}
50
53
 
51
- export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
52
- export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
54
+ export { CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, JOBS_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
55
+ export type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, BuildPluginTarget, CheckPluginContext, ComplianceConfig, ComplianceRule, ConsentConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, CreateAppContextOptions, DocumentHeadContext, FinalizeBuildContext, JobsEnqueueOptions, JobsQueueOptions, JobsService, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from '../plugins/index'
56
+ export { currentRequest } from './request-scope'
53
57
  export { action, getActionError } from './action'
54
58
  export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
55
59
  export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
@@ -57,9 +61,12 @@ export type { CompressionEncoding, PrecompressedEncoding } from './compress'
57
61
  export type { RequestConsent } from './consent'
58
62
  export type { CookieOptions, Cookies } from './cookies'
59
63
  export { defineEnv, nodeEnv } from './env'
64
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
60
65
  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'
66
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
62
67
  export { createServer } from './loader'
68
+ export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
69
+ export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
63
70
  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
71
  export type { SecurityHeadersOptions, TrustProxy } from './security'
65
72
  export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
@@ -70,39 +77,78 @@ const DEFAULT_STREAM_TIMEOUT = 30_000
70
77
 
71
78
 
72
79
  const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
80
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
81
+
82
+ function maybeRenderDenied(
83
+ res: Response,
84
+ request: Request,
85
+ url: URL,
86
+ ctx: RequestContext,
87
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
88
+ routeFile?: string,
89
+ isApi = false,
90
+ ): Response | Promise<Response> {
91
+ if (isApi)
92
+ return res
93
+ const denied = getDeniedInfo(res)
94
+ if (denied === undefined || !acceptsHtml(request))
95
+ return res
96
+ return renderDenied(denied, url, request, ctx, routeFile)
97
+ }
98
+
73
99
  const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
74
100
  // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
75
101
  const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
76
102
  const makeFileGone = (securityRecord: Record<string, string>) => (): Response => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...securityRecord } })
77
103
 
78
- function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string | undefined): T | undefined {
104
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
105
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
106
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
107
+ }
108
+
109
+ function matchStaticOrPublic(
110
+ request: Request,
111
+ requestPath: RequestPath,
112
+ assetMap: ReadonlyMap<string, ServedFile>,
113
+ publicMap: ReadonlyMap<string, ServedFile>,
114
+ pluginRouter: ServerPluginHost['router'],
115
+ ): ServedFile | undefined {
116
+ const { staticPath } = requestPath
79
117
  if (staticPath === undefined)
80
118
  return undefined
81
- const normPath = staticPath.length > 1 && staticPath.endsWith('/') ? staticPath.slice(0, -1) : staticPath
82
- return map.get(staticPath) ?? map.get(normPath)
119
+ const asset = assetMap.get(staticPath)
120
+ if (asset !== undefined)
121
+ return asset
122
+ const pub = publicMap.get(staticPath)
123
+ if (pub === undefined)
124
+ return undefined
125
+ const matchedPlugin = pluginRouter.match(requestPath)
126
+ const reqMethod = request.method.toUpperCase()
127
+ const shadowedByPlugin = matchedPlugin !== undefined
128
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
129
+ return shadowedByPlugin ? undefined : pub
83
130
  }
84
131
 
85
- async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
86
- const { entry, mod, layouts } = route
87
- let inner: string
88
- if (entry.isIsland && entry.islandChunk !== undefined) {
89
- inner = ssrIsland(
90
- entry.islandChunk,
91
- () => ssrChild(mod.default!(pageProps) as Html),
92
- pickPageIslandProps(data, entry, mod),
93
- entry.islandHydrate as HydrateStrategy | undefined,
94
- true, mod.default!.name,
95
- )
96
- }
97
- else {
98
- inner = ssrChild(await mod.default!(pageProps) as Html)
132
+ function createRequestGuards(
133
+ maxRequestBodySize: number,
134
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
135
+ ) {
136
+ const refuseCrossSite = (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string): Response =>
137
+ finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore, requestId)
138
+
139
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
140
+ if (bodyLimited)
141
+ return request
142
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
143
+ if (bounded.ok)
144
+ return bounded.request
145
+ return finish(wantsJson(request)
146
+ ? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
147
+ : new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
99
148
  }
100
- for (let i = layouts.length - 1; i >= 0; i--)
101
- inner = ssrChild(await layouts[i]!.default({ children: raw(inner), url: ctx.url, params: ctx.params, locals: ctx.locals }) as Html)
102
- return inner
149
+ return { refuseCrossSite, checkBodyLimit }
103
150
  }
104
151
 
105
-
106
152
  interface ActionDispatcherDeps {
107
153
  actions: ActionRegistry
108
154
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
@@ -110,15 +156,16 @@ interface ActionDispatcherDeps {
110
156
  trustProxy: TrustProxy
111
157
  consent: NormalizedConsentConfig | undefined
112
158
  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
159
+ isDev: boolean
160
+ refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string) => Response
161
+ checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
162
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
116
163
  notifyError: NotifyError
117
164
  renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
118
165
  }
119
166
 
120
167
  function createActionDispatcher(deps: ActionDispatcherDeps) {
121
- const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
168
+ const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
122
169
  const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
123
170
  const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
124
171
  if (act.rateLimit === undefined)
@@ -137,6 +184,7 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
137
184
  rawPathname: string,
138
185
  remoteIp: string | undefined,
139
186
  bodyLimited: boolean,
187
+ requestId: string,
140
188
  existing?: { ctx: RequestContext, cookieStore: CookieStore },
141
189
  ): Promise<Response> => {
142
190
  const actionHandler = request.method === 'POST' ? registeredAction : undefined
@@ -144,29 +192,30 @@ function createActionDispatcher(deps: ActionDispatcherDeps) {
144
192
  if (actionHandler !== undefined) {
145
193
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
146
194
  if (!originCheck.ok)
147
- return refuseCrossSite(request, originCheck.reason, existing?.cookieStore)
148
- const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore)
195
+ return refuseCrossSite(request, originCheck.reason, existing?.cookieStore, requestId)
196
+ const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
149
197
  if (checked instanceof Response)
150
198
  return checked
151
199
  req = checked
152
200
  }
153
201
  const { act, middlewares } = registeredAction
154
- const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent })
202
+ const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent, requestId })
155
203
  ctx.request = req
156
204
  if (existing === undefined && rewrites.length > 0) {
157
205
  for (const rewrite of rewrites)
158
206
  rewrite(rawPathname, ctx)
159
207
  }
208
+ const timing = createTiming(isDev)
160
209
  try {
161
- const res = await actions.run(ctx, () => runChain(ctx, middlewares, () =>
210
+ const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
162
211
  actionHandler !== undefined
163
212
  ? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
164
213
  : methodNotAllowed('POST'),
165
- ))
166
- return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore)
214
+ timing, runChain))
215
+ return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
167
216
  }
168
217
  catch (error) {
169
- notifyError(error, req, 'action')
218
+ notifyError(error, req, 'action', ctx.requestId)
170
219
  return renderError(error, cookieStore, ctx.url, req, ctx)
171
220
  }
172
221
  }
@@ -223,7 +272,9 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
223
272
  const hstsValue = resolveHstsValue(security)
224
273
  const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
225
274
  // 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)
275
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
276
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
277
+ const resolveRequestId = createRequestIdResolver(trustProxy)
227
278
  const serverError = makeServerError(securityRecord)
228
279
  const fileGone = makeFileGone(securityRecord)
229
280
  const navigation = createNavigation(config.navigation)
@@ -232,6 +283,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
232
283
 
233
284
  const compressEnabled = config.compress ?? !isDev
234
285
  const compressCache = compressEnabled ? new CompressionCache() : undefined
286
+ const routeCache = createRouteCache(config.routeCache, isDev || config.prerender === true)
235
287
 
236
288
  const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
237
289
  const { assetMap, publicMap, serveFile } = files
@@ -266,19 +318,18 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
266
318
  trustedOrigins,
267
319
  })
268
320
  const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
321
+ const healthPath = `${assetPrefix}/health`
322
+ const healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId })
269
323
  const hasPluginRewrites = pluginHost.rewrites.length > 0
270
324
  const routesPrefix = inferRoutesServerPrefix(manifest)
325
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
271
326
  const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
272
- const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix)
327
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
273
328
  const pluginMiddlewaresFor = (effectiveScopedPath: string, rawScopedPath: string): readonly Middleware[] =>
274
- effectiveScopedPath === rawScopedPath
275
- ? middlewaresFor(effectiveScopedPath)
276
- : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
329
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
277
330
 
278
331
  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 })
332
+ const { buildNotFoundResponse, renderError, renderDenied } = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
282
333
 
283
334
  async function renderNotFound(
284
335
  cookieStore: CookieStore,
@@ -287,6 +338,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
287
338
  ctx: RequestContext,
288
339
  effective: RequestPath,
289
340
  rawScopedPath: string,
341
+ timing?: DevTiming,
290
342
  ): Promise<Response> {
291
343
  const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
292
344
  const ancestor = ancestorMiddlewaresFor(effective)
@@ -294,34 +346,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
294
346
  ctx.params = ancestor.params
295
347
  const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
296
348
  try {
297
- const res = await actions.run(ctx, () => runChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx)))
298
- return finish(res, request, cookieStore)
349
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
350
+ return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
299
351
  }
300
352
  catch (error) {
301
- notifyError(error, request, 'route')
353
+ notifyError(error, request, 'route', ctx.requestId)
302
354
  return renderError(error, cookieStore, url, request, ctx)
303
355
  }
304
356
  }
305
357
 
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
- }
358
+ const { refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish)
320
359
 
321
360
  const { router, fastStaticPages } = compileRouteTable({
322
- manifest, modules, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
361
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
323
362
  pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
324
- fast: { trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, notifyError, finish, withHsts },
363
+ fast: { trustProxy, consent, htmlHeaders, compressCache, routeCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
325
364
  })
326
365
  const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
327
366
  prerendered,
@@ -332,155 +371,54 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
332
371
  isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
333
372
  })
334
373
 
335
- async function renderCompiledRoute(
336
- route: CompiledRoute,
337
- ctx: RequestContext,
338
- disableTimeout?: () => void,
339
- staticPath?: string,
340
- ): Promise<Response> {
341
- const { entry, mod, doc } = route
342
-
343
- const isRegion = hasRegionHeader(ctx.request)
344
- // Serve prerendered HTML after middlewares have passed (skip on full-page GETs with a flash cookie so it hydrates & clears, and on region requests)
345
- if (isRead(ctx.request)) {
346
- const pre = lookupPrerendered(prerenderedMap, staticPath)
347
- if (pre !== undefined && !isRegion && (ctx.request.method === 'HEAD' || !hasActionErrorCookie(ctx.request)))
348
- return serveFile(ctx.request, pre)
349
- // Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
350
- if (pre === undefined && entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
351
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
352
- }
353
-
354
- // API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
355
- const method = ctx.request.method.toUpperCase()
356
- const methodHandler = mod[method]
357
- if (typeof methodHandler === 'function')
358
- return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
359
- if (method === 'HEAD' && typeof mod.GET === 'function')
360
- return stripHeadBody(await mod.GET(ctx))
361
-
362
- // Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
363
- if (typeof mod.default !== 'function' || !isRead(ctx.request))
364
- return methodNotAllowed(allowedMethodsHeader(mod))
365
- if (isRegion && requestedRegion(ctx.request) === undefined)
366
- return invalidRegionResponse(ctx.request)
367
-
368
- // Hydrate one-shot flash cookie on full page GETs only; defer deletion until a full page renders (not load() redirects or <Region> requests)
369
- const hasFlash = ctx.request.method === 'GET' && !isRegion && hasActionErrorCookie(ctx.request) && hydrateActionErrorFlash(ctx)
370
-
371
- let data: unknown
372
- if (entry.hasLoad && typeof mod.load === 'function') {
373
- try {
374
- data = await mod.load(ctx)
375
- }
376
- catch (error) {
377
- if (isNotFound(error))
378
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
379
- throw error
380
- }
381
- }
382
- if (isNotFound(data))
383
- return buildNotFoundResponse(ctx.url, ctx.request, ctx)
384
- if (data instanceof Response)
385
- return data
386
- const pageProps: Record<string, unknown> = {
387
- params: ctx.params,
388
- locals: ctx.locals,
389
- url: ctx.url,
390
- ...(data !== undefined ? { data } : {}),
391
- }
392
-
393
- if (isRegion) {
394
- return respondRegion(
395
- ctx.request, mod, pageProps, entry.path, htmlHeaders,
396
- rctx => resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
397
- streamTimeout, error => notifyError(error, ctx.request, 'route'),
398
- hasHtmlTransformers ? html => applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
399
- )
400
- }
401
-
402
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, ctx.request, 'route'))
403
- const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
404
- if (hasFlash)
405
- ctx.cookies.delete(ACTION_ERROR_COOKIE)
406
- const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
407
- const renderedIslands = resolveRenderedIslands(rctx, body)
408
- const isStreamed = rctx.pending.length > 0
409
- const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
410
- // A streamed page preloads before its boundaries render, so it takes the route's eager islands: a lazy one loads when its strategy fires.
411
- const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, manifest.reviveScript)]
412
- const hasRegions = rctx.regionNames.size > 0
413
-
414
- const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
415
-
416
- // Streaming SSR when <Suspense> boundaries are pending, compressed per flush, never buffered
417
- if (isStreamed) {
418
- if (ctx.request.method === 'HEAD')
419
- return markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) }))
420
- disableTimeout?.()
421
- const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
422
- // Transforms see the document with its initial body; boundaries resolved later stream as they render.
423
- const shell = hasHtmlTransformers ? await applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
424
- 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)
426
- }
427
-
428
- const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
429
- const html = hasHtmlTransformers ? await applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
430
- const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
431
-
432
- return compressedHtmlResponse(html, 200, withRegionVary(htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions), ctx.request, compressCache)
433
- }
374
+ const renderCompiledRoute = createCompiledRouteRenderer({
375
+ manifest, prerenderedMap, serveFile, buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
376
+ })
434
377
 
435
378
  const dispatchAction = createActionDispatcher({
436
- actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
379
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
437
380
  })
438
381
 
439
382
  // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
440
383
  async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
384
+ const requestId = resolveRequestId(request)
441
385
  try {
442
386
  const url = new URL(request.url)
443
387
  const rawPathname = url.pathname
444
388
  const requestPath = decodeRequestPath(rawPathname)
445
389
  if (requestPath === undefined)
446
- return finish(badRequest(), request)
390
+ return finish(badRequest(), request, undefined, requestId)
447
391
  const { staticPath, scopedPath } = requestPath
392
+ if (staticPath === healthPath)
393
+ return healthHandler(request, requestId)
448
394
  const read = isRead(request)
449
395
 
450
396
  // 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
- }
397
+ if (read) {
398
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
399
+ if (staticFile !== undefined)
400
+ return withRequestId(await serveFile(request, staticFile), requestId)
464
401
  }
465
402
 
466
403
  // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
467
404
  const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
468
405
  if (registeredAction !== undefined)
469
- return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited)
406
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
470
407
 
471
408
  // 3. Prerendered static HTML, then 4. the zero-overhead static route path
472
409
  const plainRead = isPlainRead(request)
473
410
  if (plainRead && staticPath !== undefined) {
474
411
  const pre = fastPrerenderedMap.get(staticPath)
475
412
  if (pre !== undefined)
476
- return serveFile(request, pre)
413
+ return withRequestId(await serveFile(request, pre), requestId)
477
414
  const fast = fastStaticPages.get(staticPath)
478
415
  if (fast !== undefined)
479
- return fast(request, remoteIp, url)
416
+ return fast(request, remoteIp, url, requestId)
480
417
  }
481
418
 
482
419
  // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
483
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
420
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId })
421
+ const timing = createTiming(isDev)
484
422
 
485
423
  // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
486
424
  let effectivePath = rawPathname
@@ -493,17 +431,17 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
493
431
  if (effectivePath !== rawPathname) {
494
432
  const rewritten = decodeRequestPath(effectivePath)
495
433
  if (rewritten === undefined)
496
- return finish(badRequest(), request, cookieStore)
434
+ return finish(badRequest(), request, cookieStore, requestId)
497
435
  effective = rewritten
498
436
  const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
499
437
  if (rewrittenAction !== undefined)
500
- return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, { ctx, cookieStore })
438
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
501
439
  }
502
440
  const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
503
441
 
504
442
  // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
505
443
  const method = request.method.toUpperCase()
506
- const pluginMatch = pluginRouter.match(effective)
444
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
507
445
  const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
508
446
  const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
509
447
  const routeDef = directPluginDef ?? headFallbackPluginDef
@@ -511,24 +449,24 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
511
449
  if (routeDef.csrf) {
512
450
  const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
513
451
  if (!originCheck.ok)
514
- return refuseCrossSite(request, originCheck.reason, cookieStore)
452
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
515
453
  }
516
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
454
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
517
455
  if (checked instanceof Response)
518
456
  return checked
519
457
  ctx.request = checked
520
458
  ctx.params = pluginMatch.params
521
459
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
522
460
  try {
523
- let res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => routeDef.handler(ctx)))
461
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
524
462
  if (headFallbackPluginDef !== undefined)
525
463
  res = stripHeadBody(res)
526
464
  else if (isEventStream(res))
527
465
  res = streams.track(res, disableTimeout)
528
- return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore)
466
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
529
467
  }
530
468
  catch (error) {
531
- notifyError(error, ctx.request, 'plugin')
469
+ notifyError(error, ctx.request, 'plugin', requestId)
532
470
  return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
533
471
  }
534
472
  }
@@ -537,7 +475,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
537
475
  if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
538
476
  const pub = publicMap.get(effectiveStaticPath)
539
477
  if (pub !== undefined)
540
- return serveFile(request, pub)
478
+ return withRequestId(await serveFile(request, pub), requestId)
541
479
  }
542
480
 
543
481
  const matched = router.match(effective)
@@ -547,28 +485,28 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
547
485
  const allow = allowedPluginMethodsHeader(pluginMatch.data)
548
486
  const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
549
487
  try {
550
- const res = await actions.run(ctx, () => runChain(ctx, pluginMws, () => methodNotAllowed(allow)))
551
- return finish(res, request, cookieStore)
488
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
489
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
552
490
  }
553
491
  catch (error) {
554
- notifyError(error, request, 'plugin')
492
+ notifyError(error, request, 'plugin', requestId)
555
493
  return renderError(error, cookieStore, ctx.url, request, ctx)
556
494
  }
557
495
  }
558
- return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath)
496
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
559
497
  }
560
498
 
561
499
  ctx.params = matched.params
562
500
  const route = matched.data
563
501
 
564
502
  // CSRF verification & body limit for file-based API routes (opt out of CSRF via `export const csrf = false`)
565
- if (typeof route.mod[method] === 'function') {
503
+ if (routeMethodHandler(route.mod, method) !== undefined) {
566
504
  if (route.mod.csrf !== false) {
567
505
  const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
568
506
  if (!originCheck.ok)
569
- return refuseCrossSite(request, originCheck.reason, cookieStore)
507
+ return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
570
508
  }
571
- const checked = await checkBodyLimit(request, bodyLimited, cookieStore)
509
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
572
510
  if (checked instanceof Response)
573
511
  return checked
574
512
  ctx.request = checked
@@ -579,20 +517,21 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
579
517
  : route.middlewares
580
518
 
581
519
  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
520
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing), timing, runChain))
521
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
522
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
584
523
  // Compress uncompressed API/middleware responses after the middleware chain unwinds.
585
524
  const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
586
- return finish(finalRes, ctx.request, cookieStore)
525
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
587
526
  }
588
527
  catch (error) {
589
- notifyError(error, ctx.request, 'route')
590
- return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
528
+ notifyError(error, ctx.request, 'route', requestId)
529
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
591
530
  }
592
531
  }
593
532
  catch (error) {
594
- notifyError(error, request, 'route')
595
- return withHsts(isDev ? devErrorResponse(error, request) : serverError(), request)
533
+ notifyError(error, request, 'route', requestId)
534
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
596
535
  }
597
536
  }
598
537
 
@@ -602,7 +541,7 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
602
541
 
603
542
  const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
604
543
  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 })
544
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
606
545
 
607
546
  function serve(port = 3000, hostname = '127.0.0.1') {
608
547
  const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })