prunelle 0.0.0-stage → 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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  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/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,615 @@
1
+ // Prunelle native Bun.serve server:
2
+ // - Static + dynamic ([param], [...catchall]) Router
3
+ // - Composable directory-scoped _middleware.ts chains + ctx.cookies + ctx.locals
4
+ // - Unified Standard-Schema action() endpoint handling with CSRF verification
5
+ // - <Head> collection + cancel-safe streaming <Suspense> (0-overhead fast path when unused)
6
+ // - Hybrid prerendered HTML serving + embedded single-executable mode
7
+
8
+ import type { ActionRegistry, RegisteredAction } from './action-registry'
9
+ import type { ServedFile } from './assets'
10
+ import type { NormalizedConsentConfig } from './consent'
11
+ import type { CookieStore } from './cookies'
12
+ import type { NotifyError } from './errors'
13
+ import type { DevTiming } from './health'
14
+ import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
15
+ import type { RateLimiter, RateLimitStore } from './rate-limit'
16
+ export { rateLimitKey } from './rate-limit'
17
+ export { sanitizeMarkdownHtml } from './sanitize-html'
18
+ import type { LoadedMiddlewareModule } from './page'
19
+ import type { ServerPluginHost } from './plugin-host'
20
+ import type { RequestPath } from './request-path'
21
+ import type { CompiledRoute } from './route-table'
22
+ import type { FastHandler } from './routing'
23
+ import type { OriginRefusal, TrustProxy } from './security'
24
+ import { join } from 'node:path'
25
+ import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
26
+ import { createNavigation } from '../ssr/navigation'
27
+ import { executeAction, finishActionRedirect, isServerAction } from './action'
28
+ import { createActionRegistry } from './action-registry'
29
+ import { createAssets } from './assets'
30
+ import { CompressionCache, maybeCompressResponse } from './compress'
31
+ import { normalizeConsentConfig } from './consent'
32
+ import { devFromEnv, nodeEnv } from './env'
33
+ import { createDocumentHooks, createHtmlHeaders, withPluginHtmlCsp } from './document'
34
+ import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
35
+ import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, formatServerTiming, runTimedChain, withRequestId } from './health'
36
+ import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
37
+ import { hasPublicFavicon, stripHeadBody } from './page'
38
+ import { resolveParamMatchers } from './param-matchers'
39
+ import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
40
+
41
+ import { withRegionVary } from './region'
42
+ import { decodeRequestPath, literalPath } from './request-path'
43
+ import { nativePrerenderedCheck } from './prerendered'
44
+ import { createRouteCache } from './route-cache'
45
+ import { compileRouteTable, createCompiledRouteRenderer, routeMethodHandler } from './route-table'
46
+ import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
47
+ import { isPlainRead, isRead, serveHandlers } from './serve-handlers'
48
+ import { buildSecurityHeaderEntries, isLoopbackHost, logOriginHint, resolveHstsValue, verifyOrigin } from './security'
49
+ import { createStreamTracker } from './stream'
50
+
51
+ /**
52
+ * Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
53
+ * Augment via `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`.
54
+ */
55
+ export interface PrunelleLocals {}
56
+
57
+ 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'
58
+ 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'
59
+ export { currentRequest } from './request-scope'
60
+ export { action, getActionError } from './action'
61
+ export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
62
+ export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
63
+ export type { CompressionEncoding, PrecompressedEncoding } from './compress'
64
+ export type { RequestConsent } from './consent'
65
+ export type { CookieOptions, Cookies } from './cookies'
66
+ export { defineEnv, devFromEnv, nodeEnv } from './env'
67
+ export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
68
+ export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
69
+ export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
70
+ export { createServer } from './loader'
71
+ export { buildRouteCacheSpec, createRouteCache, formatCacheSpec, parseCacheDuration, RouteCache } from './route-cache'
72
+ export type { CachedRouteEntry, RouteCacheOptions, RouteCacheSpec } from './route-cache'
73
+ export { DEFAULT_COOP, DEFAULT_CORP, DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isLoopbackHost, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
74
+ export type { SecurityHeadersOptions, TrustProxy } from './security'
75
+ export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
76
+ export type { InferInput, InferOutput, StandardJSONSchemaConverter, StandardJSONSchemaOptions, StandardJSONSchemaTarget, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
77
+
78
+ // Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
79
+ const DEFAULT_STREAM_TIMEOUT = 30_000
80
+
81
+
82
+ const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
83
+ const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
84
+
85
+ function maybeRenderDenied(
86
+ res: Response,
87
+ request: Request,
88
+ url: URL,
89
+ ctx: RequestContext,
90
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
91
+ routeFile?: string,
92
+ isApi = false,
93
+ ): Response | Promise<Response> {
94
+ if (isApi)
95
+ return res
96
+ const denied = getDeniedInfo(res)
97
+ if (denied === undefined || !acceptsHtml(request))
98
+ return res
99
+ return renderDenied(denied, url, request, ctx, routeFile)
100
+ }
101
+
102
+ const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
103
+ // A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
104
+ const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
105
+ 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 } })
106
+
107
+ function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
108
+ const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
109
+ return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
110
+ }
111
+
112
+ function matchStaticOrPublic(
113
+ request: Request,
114
+ requestPath: RequestPath,
115
+ assetMap: ReadonlyMap<string, ServedFile>,
116
+ publicMap: ReadonlyMap<string, ServedFile>,
117
+ pluginRouter: ServerPluginHost['router'],
118
+ ): ServedFile | undefined {
119
+ const { staticPath } = requestPath
120
+ if (staticPath === undefined)
121
+ return undefined
122
+ const asset = assetMap.get(staticPath)
123
+ if (asset !== undefined)
124
+ return asset
125
+ const pub = publicMap.get(staticPath)
126
+ if (pub === undefined)
127
+ return undefined
128
+ const matchedPlugin = pluginRouter.match(requestPath)
129
+ const reqMethod = request.method.toUpperCase()
130
+ const shadowedByPlugin = matchedPlugin !== undefined
131
+ && (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
132
+ return shadowedByPlugin ? undefined : pub
133
+ }
134
+
135
+ function createRequestGuards(
136
+ maxRequestBodySize: number,
137
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
138
+ ) {
139
+ const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
140
+ logOriginHint(check.hint)
141
+ return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
142
+ }
143
+
144
+ const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
145
+ if (bodyLimited)
146
+ return request
147
+ const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
148
+ if (bounded.ok)
149
+ return bounded.request
150
+ const status = bounded.aborted ? 400 : 413
151
+ const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
152
+ return finish(wantsJson(request)
153
+ ? Response.json({ ok: false, status, error: message }, { status })
154
+ : new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
155
+ }
156
+ return { refuseCrossSite, checkBodyLimit }
157
+ }
158
+
159
+ interface ActionDispatcherDeps {
160
+ actions: ActionRegistry
161
+ rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
162
+ trustedOrigins: Set<string> | undefined
163
+ trustProxy: TrustProxy
164
+ httpsSite: boolean
165
+ consent: NormalizedConsentConfig | undefined
166
+ rateLimits: RateLimitStore
167
+ isDev: boolean
168
+ refuseCrossSite: (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string) => Response
169
+ checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
170
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
171
+ notifyError: NotifyError
172
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
173
+ }
174
+
175
+ function createActionDispatcher(deps: ActionDispatcherDeps) {
176
+ const { actions, rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
177
+ const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
178
+ const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
179
+ if (act.rateLimit === undefined)
180
+ return undefined
181
+ let limiter = limiters.get(act)
182
+ if (limiter === undefined) {
183
+ limiter = rateLimits.limiter(act.rateLimit)
184
+ limiters.set(act, limiter)
185
+ }
186
+ return limiter
187
+ }
188
+ return async (
189
+ registeredAction: RegisteredAction,
190
+ request: Request,
191
+ url: URL,
192
+ rawPathname: string,
193
+ remoteIp: string | undefined,
194
+ bodyLimited: boolean,
195
+ requestId: string,
196
+ existing?: { ctx: RequestContext, cookieStore: CookieStore },
197
+ ): Promise<Response> => {
198
+ const actionHandler = request.method === 'POST' ? registeredAction : undefined
199
+ let req = request
200
+ if (actionHandler !== undefined) {
201
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
202
+ if (!originCheck.ok)
203
+ return refuseCrossSite(request, originCheck, existing?.cookieStore, requestId)
204
+ const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
205
+ if (checked instanceof Response)
206
+ return checked
207
+ req = checked
208
+ }
209
+ const { act, middlewares } = registeredAction
210
+ const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
211
+ ctx.request = req
212
+ if (existing === undefined && rewrites.length > 0) {
213
+ for (const rewrite of rewrites)
214
+ rewrite(rawPathname, ctx)
215
+ }
216
+ const timing = createTiming(isDev)
217
+ try {
218
+ const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
219
+ actionHandler !== undefined
220
+ ? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
221
+ : methodNotAllowed('POST'),
222
+ timing, runChain))
223
+ return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
224
+ }
225
+ catch (error) {
226
+ notifyError(error, req, 'action', ctx.requestId)
227
+ return renderError(error, cookieStore, ctx.url, req, ctx)
228
+ }
229
+ }
230
+ }
231
+
232
+ interface ManifestActions {
233
+ manifest: EmbeddedServerConfig['manifest']
234
+ modules: EmbeddedServerConfig['modules']
235
+ actions: ReturnType<typeof createActionRegistry>
236
+ routesPrefix: ReturnType<typeof inferRoutesServerPrefix>
237
+ routePathByFile: Map<string, string>
238
+ middlewaresFor: (path: string) => readonly Middleware[]
239
+ middlewaresForPaths: (paths: string[]) => readonly Middleware[]
240
+ }
241
+
242
+ // Server actions and their live URLs.
243
+ function registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths }: ManifestActions): void {
244
+ for (const entry of manifest.actions) {
245
+ const mod = modules[entry.file] as Record<string, unknown> | undefined
246
+ const act = mod?.[entry.exportName]
247
+ if (isServerAction(act)) {
248
+ const routePrefix = actionRoutePrefix(entry, routesPrefix, routePathByFile)
249
+ const pluginMws = routePrefix !== undefined ? middlewaresForPaths([entry.url, routePrefix]) : middlewaresFor(entry.url)
250
+ actions.register(act, entry.exportName, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), pluginMws)
251
+ }
252
+ }
253
+ }
254
+
255
+ interface NotFoundRendererDeps {
256
+ actions: ActionRegistry
257
+ pluginMiddlewaresFor: (effectiveScopedPath: string, rawScopedPath: string) => readonly Middleware[]
258
+ ancestorMiddlewaresFor: ReturnType<typeof createAncestorMiddlewareLookup>
259
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
260
+ renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
261
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
262
+ notifyError: NotifyError
263
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
264
+ }
265
+
266
+ function createNotFoundRenderer(deps: NotFoundRendererDeps) {
267
+ const { actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse, renderDenied, renderError, notifyError, finish } = deps
268
+ return async (
269
+ cookieStore: CookieStore,
270
+ url: URL,
271
+ request: Request,
272
+ ctx: RequestContext,
273
+ effective: RequestPath,
274
+ rawScopedPath: string,
275
+ timing?: DevTiming,
276
+ ): Promise<Response> => {
277
+ const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
278
+ const ancestor = ancestorMiddlewaresFor(effective)
279
+ if (ancestor !== undefined)
280
+ ctx.params = ancestor.params
281
+ const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
282
+ try {
283
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
284
+ return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
285
+ }
286
+ catch (error) {
287
+ notifyError(error, request, 'route', ctx.requestId)
288
+ return renderError(error, cookieStore, url, request, ctx)
289
+ }
290
+ }
291
+ }
292
+
293
+ /** The security headers every response carries, and the helpers that put them on a response built without them. */
294
+ function createSecurityResponders(
295
+ security: EmbeddedServerConfig['security'],
296
+ trustProxy: TrustProxy,
297
+ isDev: boolean,
298
+ site: string | undefined,
299
+ explicitNodeEnv: string | undefined,
300
+ ) {
301
+ const resolvedNodeEnv = explicitNodeEnv ?? nodeEnv()
302
+ // An https `site` says the app is served over https, whatever a proxy the server does not trust leaves in the request.
303
+ const httpsSite = !isDev && resolvedNodeEnv !== 'development' && resolvedNodeEnv !== 'test' && site?.startsWith('https://') === true
304
+ const securityEntries = buildSecurityHeaderEntries(security)
305
+ const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
306
+ const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
307
+ const hstsValue = resolveHstsValue(security)
308
+ // Every response passes here, so it is where a production server first sees it runs behind a proxy it does not trust.
309
+ let proxyChecked = trustProxy !== false || isDev || resolvedNodeEnv !== 'production'
310
+ const withHsts = (res: Response, request: Request): Response => {
311
+ if (!proxyChecked && request.headers.has('x-forwarded-proto')) {
312
+ proxyChecked = true
313
+ console.warn('prunelle: a request came through a proxy (it carries x-forwarded-proto) but trustProxy is off, so ctx.ip and rate limits see the proxy\'s address and https is known from site alone: set trustProxy in prunelle.config.ts to the proxy the server runs behind.')
314
+ }
315
+ return applyHstsHeader(res, request, hstsValue, trustProxy, isDev, explicitNodeEnv, httpsSite)
316
+ }
317
+ // The one way out of every response not built with the security headers already in place.
318
+ const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
319
+ withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
320
+ return { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError: makeServerError(securityRecord), fileGone: makeFileGone(securityRecord) }
321
+ }
322
+
323
+ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
324
+ const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
325
+ const plugins = resolvePlugins(config.plugins)
326
+ const assetPrefix = (config.assetPrefix ?? '/_pru').replace(/\/$/, '')
327
+ const site = config.site?.replace(/\/$/, '') || undefined
328
+ const trustedOriginsList = config.trustedOrigins ?? []
329
+ const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
330
+ const trustProxy = config.trustProxy ?? false
331
+ const consent = normalizeConsentConfig(config.consent)
332
+ const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
333
+ const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
334
+ const isDev = config.dev ?? devFromEnv()
335
+ const serverRoot = config.root ?? process.cwd()
336
+ const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
337
+ const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
338
+ const parentAppCtx = getAppContext()
339
+
340
+ const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
341
+ const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink })
342
+ const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
343
+ const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
344
+
345
+ const { httpsSite, securityRecord, nosniffHeader, withHsts, finish, serverError, fileGone } = createSecurityResponders(security, trustProxy, isDev, site, config.nodeEnv ?? parentAppCtx?.nodeEnv)
346
+ const resolveRequestId = createRequestIdResolver(trustProxy)
347
+ const navigation = createNavigation(config.navigation)
348
+ const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
349
+ const streams = createStreamTracker()
350
+
351
+ const compressEnabled = config.compress ?? !isDev
352
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
353
+ const routeCache = createRouteCache(config.routeCache, isDev || config.prerender === true)
354
+
355
+ const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
356
+ const { assetMap, publicMap, serveFile } = files
357
+ files.registerPublicFiles(publicAssets, publicEtags)
358
+
359
+ const serverAppCtx = createAppContext({
360
+ root: serverRoot,
361
+ outDir: serverOutDir,
362
+ publicDir: serverPublicDir,
363
+ assetPrefix,
364
+ site,
365
+ dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
366
+ onRegisterPublicFile: (rel) => {
367
+ parentAppCtx?.registerPublicFile(rel)
368
+ files.registerPublicFromDisk(serverPublicDir, rel)
369
+ },
370
+ })
371
+
372
+ const actions = createActionRegistry()
373
+ const pluginHost = await createServerPluginHost({
374
+ plugins,
375
+ config,
376
+ manifest,
377
+ appCtx: serverAppCtx,
378
+ root: serverRoot,
379
+ outDir: serverOutDir,
380
+ assetPrefix,
381
+ site,
382
+ dev: isDev,
383
+ devExposed: config.devHost !== undefined && !isLoopbackHost(config.devHost),
384
+ trustProxy,
385
+ trustedOriginsList,
386
+ trustedOrigins,
387
+ })
388
+ const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
389
+ const healthPath = `${assetPrefix}/health`
390
+ const hasPluginRewrites = pluginHost.rewrites.length > 0
391
+ const pluginMiddlewaresFor = (effectiveScopedPath: string, rawScopedPath: string): readonly Middleware[] =>
392
+ effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
393
+
394
+ let healthHandler: ReturnType<typeof createHealthHandler>
395
+ let renderError: ReturnType<typeof createFallbackPages>['renderError']
396
+ let renderDenied: ReturnType<typeof createFallbackPages>['renderDenied']
397
+ let renderNotFound: ReturnType<typeof createNotFoundRenderer>
398
+ let refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
399
+ let checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
400
+ let router: ReturnType<typeof compileRouteTable>['router']
401
+ let fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
402
+ let fastPrerenderedMap: ReadonlyMap<string, ServedFile>
403
+ let renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
404
+ let dispatchAction: ReturnType<typeof createActionDispatcher>
405
+ try {
406
+ healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId, exposeErrors: isDev })
407
+ const routesPrefix = inferRoutesServerPrefix(manifest)
408
+ const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
409
+ const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
410
+ const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
411
+ registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
412
+ const hasFavicon = hasPublicFavicon(manifest, publicMap, serverPublicDir)
413
+ const fallbacks = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, dev: isDev, document, htmlHeaders, notifyError, finish })
414
+ ;({ renderError, renderDenied } = fallbacks)
415
+ renderNotFound = createNotFoundRenderer({ actions, pluginMiddlewaresFor, ancestorMiddlewaresFor, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderDenied, renderError, notifyError, finish })
416
+ ;({ refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish))
417
+ ;({ router, fastStaticPages } = compileRouteTable({
418
+ manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, hasFavicon, middlewaresFor,
419
+ pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
420
+ fast: { trustProxy, httpsSite, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse: fallbacks.buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
421
+ }))
422
+ const collected = files.collectPrerendered(manifest.routes, {
423
+ prerendered, prerenderedFiles, prerenderedEtags,
424
+ // The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
425
+ // no-cache, not public: an app middleware may gate the page, and its ETag still spares a revisit the download.
426
+ htmlHeaders: (route, urlPath) => ({ 'cache-control': 'no-cache', ...withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true) }),
427
+ isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
428
+ })
429
+ fastPrerenderedMap = collected.fast
430
+ renderCompiledRoute = createCompiledRouteRenderer({
431
+ manifest, prerenderedMap: collected.all, serveFile, buildNotFoundResponse: fallbacks.buildNotFoundResponse, htmlHeaders, resolveDocumentHead, applyHtmlTransforms, hasHtmlTransformers, streamTimeout, streams, compressCache, routeCache, notifyError, actions, rewrites: pluginHost.rewrites, trustProxy, consent, resolveRequestId, serverAppCtx,
432
+ })
433
+ dispatchAction = createActionDispatcher({
434
+ actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, httpsSite, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
435
+ })
436
+ }
437
+ catch (error) {
438
+ await pluginHost.dispose()
439
+ throw error
440
+ }
441
+
442
+ // `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
443
+ async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
444
+ const requestId = resolveRequestId(request)
445
+ try {
446
+ const url = new URL(request.url)
447
+ const rawPathname = url.pathname
448
+ const requestPath = decodeRequestPath(rawPathname)
449
+ if (requestPath === undefined)
450
+ return finish(badRequest(), request, undefined, requestId)
451
+ const { staticPath, scopedPath } = requestPath
452
+ if (staticPath === healthPath)
453
+ return healthHandler(request, requestId)
454
+ const read = isRead(request)
455
+
456
+ // 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
457
+ if (read) {
458
+ const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
459
+ if (staticFile !== undefined)
460
+ return withRequestId(await serveFile(request, staticFile), requestId)
461
+ }
462
+
463
+ // 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
464
+ const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
465
+ if (registeredAction !== undefined)
466
+ return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
467
+
468
+ // 3. Prerendered static HTML, then 4. the zero-overhead static route path
469
+ const plainRead = isPlainRead(request)
470
+ if (plainRead && staticPath !== undefined) {
471
+ const pre = fastPrerenderedMap.get(staticPath)
472
+ if (pre !== undefined)
473
+ return withRequestId(await serveFile(request, pre), requestId)
474
+ const fast = fastStaticPages.get(staticPath)
475
+ if (fast !== undefined)
476
+ return fast(request, remoteIp, url, requestId)
477
+ }
478
+
479
+ // 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
480
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
481
+ const timing = createTiming(isDev)
482
+
483
+ // Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
484
+ let effectivePath = rawPathname
485
+ for (const rewrite of pluginHost.rewrites) {
486
+ const nextPath = rewrite(effectivePath, ctx)
487
+ if (nextPath !== undefined)
488
+ effectivePath = nextPath
489
+ }
490
+ let effective = requestPath
491
+ if (effectivePath !== rawPathname) {
492
+ const rewritten = decodeRequestPath(effectivePath)
493
+ if (rewritten === undefined)
494
+ return finish(badRequest(), request, cookieStore, requestId)
495
+ effective = rewritten
496
+ const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
497
+ if (rewrittenAction !== undefined)
498
+ return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
499
+ }
500
+ const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
501
+
502
+ // Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
503
+ const method = request.method.toUpperCase()
504
+ const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
505
+ const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
506
+ const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
507
+ const routeDef = directPluginDef ?? headFallbackPluginDef
508
+ if (pluginMatch !== undefined && routeDef !== undefined) {
509
+ if (routeDef.csrf) {
510
+ const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
511
+ if (!originCheck.ok)
512
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
513
+ }
514
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
515
+ if (checked instanceof Response)
516
+ return checked
517
+ ctx.request = checked
518
+ ctx.params = pluginMatch.params
519
+ const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
520
+ try {
521
+ let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
522
+ if (headFallbackPluginDef !== undefined)
523
+ res = stripHeadBody(res)
524
+ else if (isEventStream(res))
525
+ res = streams.track(res, disableTimeout)
526
+ return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
527
+ }
528
+ catch (error) {
529
+ notifyError(error, ctx.request, 'plugin', requestId)
530
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
531
+ }
532
+ }
533
+
534
+ // Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
535
+ if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
536
+ const pub = publicMap.get(effectiveStaticPath)
537
+ if (pub !== undefined)
538
+ return withRequestId(await serveFile(request, pub), requestId)
539
+ }
540
+
541
+ const matched = router.match(effective)
542
+ if (matched === undefined) {
543
+ if (pluginMatch !== undefined) {
544
+ ctx.params = pluginMatch.params
545
+ const allow = allowedPluginMethodsHeader(pluginMatch.data)
546
+ const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
547
+ try {
548
+ const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
549
+ return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
550
+ }
551
+ catch (error) {
552
+ notifyError(error, request, 'plugin', requestId)
553
+ return renderError(error, cookieStore, ctx.url, request, ctx)
554
+ }
555
+ }
556
+ return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
557
+ }
558
+
559
+ ctx.params = matched.params
560
+ const route = matched.data
561
+
562
+ // CSRF verification & body limit for file-based API routes (opt out of CSRF via `export const csrf = false`)
563
+ if (routeMethodHandler(route.mod, method) !== undefined) {
564
+ if (route.mod.csrf !== false) {
565
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
566
+ if (!originCheck.ok)
567
+ return refuseCrossSite(request, originCheck, cookieStore, requestId)
568
+ }
569
+ const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
570
+ if (checked instanceof Response)
571
+ return checked
572
+ ctx.request = checked
573
+ }
574
+
575
+ const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
576
+ ? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
577
+ : route.middlewares
578
+
579
+ try {
580
+ const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, disableTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
581
+ const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
582
+ const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
583
+ // Compress uncompressed API/middleware responses after the middleware chain unwinds.
584
+ const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
585
+ return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
586
+ }
587
+ catch (error) {
588
+ notifyError(error, ctx.request, 'route', requestId)
589
+ return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
590
+ }
591
+ }
592
+ catch (error) {
593
+ notifyError(error, request, 'route', requestId)
594
+ return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
595
+ }
596
+ }
597
+
598
+ function handle(request: Request, remoteIp?: string, disableTimeout?: () => void): Promise<Response> {
599
+ return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp, disableTimeout))
600
+ }
601
+
602
+ const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
603
+ const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
604
+ const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
605
+
606
+ function serve(port = 3000, hostname = '127.0.0.1') {
607
+ const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })
608
+ return server
609
+ }
610
+
611
+ const reloadInto = (server: PrunelleServer): void => {
612
+ server.reload(handlers(() => server))
613
+ }
614
+ return { handle, serve, reloadInto, inject: serverAppCtx.inject, closeStreams: streams.closeAll, securityHeaders: securityRecord, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
615
+ }