prunelle 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,687 @@
|
|
|
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 { Html, HydrateStrategy } from '../jsx-runtime'
|
|
9
|
+
import type { ActionRegistry, RegisteredAction } from './action-registry'
|
|
10
|
+
import type { ServedFile } from './assets'
|
|
11
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
12
|
+
import type { CookieStore } from './cookies'
|
|
13
|
+
import type { NotifyError } from './errors'
|
|
14
|
+
import type { DevTiming } from './health'
|
|
15
|
+
import type { DeniedInfo, EmbeddedServerConfig, PrunelleApp, PrunelleServer, Middleware, RequestContext } from './http'
|
|
16
|
+
import type { RateLimiter, RateLimitStore } from './rate-limit'
|
|
17
|
+
import type { LoadedMiddlewareModule } from './page'
|
|
18
|
+
import type { ServerPluginHost } from './plugin-host'
|
|
19
|
+
import type { RequestPath } from './request-path'
|
|
20
|
+
import type { CompiledRoute } from './route-table'
|
|
21
|
+
import type { FastHandler } from './routing'
|
|
22
|
+
import type { TrustProxy } from './security'
|
|
23
|
+
import { join } from 'node:path'
|
|
24
|
+
import { createAppContext, getAppContext, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
25
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
26
|
+
import { createNavigation } from '../ssr/navigation'
|
|
27
|
+
import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
|
|
28
|
+
import { ACTION_ERROR_COOKIE, executeAction, finishActionRedirect, hydrateActionErrorFlash, isServerAction } from './action'
|
|
29
|
+
import { createActionRegistry } from './action-registry'
|
|
30
|
+
import { createAssets } from './assets'
|
|
31
|
+
import { CompressionCache, compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, maybeCompressResponse } from './compress'
|
|
32
|
+
import { normalizeConsentConfig } from './consent'
|
|
33
|
+
import { addedInlineStyleHashes, createDocumentHooks, createHtmlHeaders, mergeStyleHashes, resolveRenderedIslands, revivePreload, withPluginHtmlCsp } from './document'
|
|
34
|
+
import { createErrorNotifier, createFallbackPages, devErrorResponse } from './errors'
|
|
35
|
+
import { collectHealthChecks, createHealthHandler, createRequestIdResolver, createTiming, endTimer, formatServerTiming, runTimedChain, startTimer, withRequestId } from './health'
|
|
36
|
+
import { acceptsHtml, applyHstsHeader, DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit, finalizeResponse, getDeniedInfo, isNotFound, makeRequestContext, runChain, wantsJson } from './http'
|
|
37
|
+
import { allowedMethodsHeader, pickPageIslandProps, stripHeadBody } from './page'
|
|
38
|
+
import { resolveParamMatchers } from './param-matchers'
|
|
39
|
+
import { allowedPluginMethodsHeader, createServerPluginHost, takesEncoded } from './plugin-host'
|
|
40
|
+
|
|
41
|
+
import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
|
|
42
|
+
import { decodeRequestPath, literalPath } from './request-path'
|
|
43
|
+
import { nativePrerenderedCheck } from './prerendered'
|
|
44
|
+
import { compileRouteTable } from './route-table'
|
|
45
|
+
import { actionRoutePrefix, createAncestorMiddlewareLookup, inferRoutesServerPrefix, methodNotAllowed } from './routing'
|
|
46
|
+
import { hasActionErrorCookie, isPlainRead, isRead, serveHandlers } from './serve-handlers'
|
|
47
|
+
import { buildSecurityHeaderEntries, resolveHstsValue, styleHashesOf, verifyOrigin } from './security'
|
|
48
|
+
import { createStreamTracker, STREAM_TAIL_MARK, streamDocument } from './stream'
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Request-scoped locals bag shared across middlewares, plugins, actions, layouts, and pages.
|
|
52
|
+
* Augment via `declare module 'prunelle/server' { interface PrunelleLocals { ... } }`.
|
|
53
|
+
*/
|
|
54
|
+
export interface PrunelleLocals {}
|
|
55
|
+
|
|
56
|
+
export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, defineConfig, definePlugin, getAppContext, I18N_CONFIG_SERVICE, loadConfig, pickRuntimeConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
|
|
57
|
+
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'
|
|
58
|
+
export { action, getActionError } from './action'
|
|
59
|
+
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionResult, ServerAction } from './action'
|
|
60
|
+
export { CompressionCache, isCompressibleType, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
|
|
61
|
+
export type { CompressionEncoding, PrecompressedEncoding } from './compress'
|
|
62
|
+
export type { RequestConsent } from './consent'
|
|
63
|
+
export type { CookieOptions, Cookies } from './cookies'
|
|
64
|
+
export { defineEnv, nodeEnv } from './env'
|
|
65
|
+
export type { HealthCheckConfig, HealthCheckFn, HealthCheckResult } from './health'
|
|
66
|
+
export { DEFAULT_MAX_REQUEST_BODY_SIZE, notFound } from './http'
|
|
67
|
+
export type { EmbeddedServerConfig, ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, ParamMatcherTypes, RequestContext, RouteContext, ServerOptions, StatusPageProps } from './http'
|
|
68
|
+
export { createServer } from './loader'
|
|
69
|
+
export { DEFAULT_CSP, DEFAULT_HSTS, DEFAULT_PERMISSIONS_POLICY, getClientIp, isHttpsRequest, isTrustedOrigin, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, verifyOrigin, withCspHashes } from './security'
|
|
70
|
+
export type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
71
|
+
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
72
|
+
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
73
|
+
|
|
74
|
+
// Matches Bun.serve's 30 s idle timeout, which a streamed page turns off.
|
|
75
|
+
const DEFAULT_STREAM_TIMEOUT = 30_000
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
|
|
79
|
+
const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => typeof mod[method] === 'function' || (method === 'HEAD' && typeof mod.GET === 'function')
|
|
80
|
+
|
|
81
|
+
function maybeRenderDenied(
|
|
82
|
+
res: Response,
|
|
83
|
+
request: Request,
|
|
84
|
+
url: URL,
|
|
85
|
+
ctx: RequestContext,
|
|
86
|
+
renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
|
|
87
|
+
routeFile?: string,
|
|
88
|
+
isApi = false,
|
|
89
|
+
): Response | Promise<Response> {
|
|
90
|
+
if (isApi)
|
|
91
|
+
return res
|
|
92
|
+
const denied = getDeniedInfo(res)
|
|
93
|
+
if (denied === undefined || !acceptsHtml(request))
|
|
94
|
+
return res
|
|
95
|
+
return renderDenied(denied, url, request, ctx, routeFile)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const makeServerError = (securityRecord: Record<string, string>) => (): Response => new Response('Internal Server Error', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord } })
|
|
99
|
+
// A file body Bun could not open: a build swapped in since this app loaded, or a file deleted by hand. Never cached.
|
|
100
|
+
const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
101
|
+
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 } })
|
|
102
|
+
|
|
103
|
+
function lookupPrerendered<T>(map: ReadonlyMap<string, T>, staticPath: string | undefined): T | undefined {
|
|
104
|
+
if (staticPath === undefined)
|
|
105
|
+
return undefined
|
|
106
|
+
const normPath = staticPath.length > 1 && staticPath.endsWith('/') ? staticPath.slice(0, -1) : staticPath
|
|
107
|
+
return map.get(staticPath) ?? map.get(normPath)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
|
|
111
|
+
const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
|
|
112
|
+
return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function matchStaticOrPublic(
|
|
116
|
+
request: Request,
|
|
117
|
+
requestPath: RequestPath,
|
|
118
|
+
assetMap: ReadonlyMap<string, ServedFile>,
|
|
119
|
+
publicMap: ReadonlyMap<string, ServedFile>,
|
|
120
|
+
pluginRouter: ServerPluginHost['router'],
|
|
121
|
+
): ServedFile | undefined {
|
|
122
|
+
const { staticPath } = requestPath
|
|
123
|
+
if (staticPath === undefined)
|
|
124
|
+
return undefined
|
|
125
|
+
const asset = assetMap.get(staticPath)
|
|
126
|
+
if (asset !== undefined)
|
|
127
|
+
return asset
|
|
128
|
+
const pub = publicMap.get(staticPath)
|
|
129
|
+
if (pub === undefined)
|
|
130
|
+
return undefined
|
|
131
|
+
const matchedPlugin = pluginRouter.match(requestPath)
|
|
132
|
+
const reqMethod = request.method.toUpperCase()
|
|
133
|
+
const shadowedByPlugin = matchedPlugin !== undefined
|
|
134
|
+
&& (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
|
|
135
|
+
return shadowedByPlugin ? undefined : pub
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function renderRouteBody(route: CompiledRoute, data: unknown, pageProps: Record<string, unknown>, ctx: RequestContext): Promise<string> {
|
|
139
|
+
const { entry, mod, layouts } = route
|
|
140
|
+
let inner: string
|
|
141
|
+
if (entry.isIsland && entry.islandChunk !== undefined) {
|
|
142
|
+
inner = ssrIsland(
|
|
143
|
+
entry.islandChunk,
|
|
144
|
+
() => ssrChild(mod.default!(pageProps) as Html),
|
|
145
|
+
pickPageIslandProps(data, entry, mod),
|
|
146
|
+
entry.islandHydrate as HydrateStrategy | undefined,
|
|
147
|
+
true, mod.default!.name,
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
inner = ssrChild(await mod.default!(pageProps) as Html)
|
|
152
|
+
}
|
|
153
|
+
for (let i = layouts.length - 1; i >= 0; i--)
|
|
154
|
+
inner = ssrChild(await layouts[i]!.default({ children: raw(inner), url: ctx.url, params: ctx.params, locals: ctx.locals }) as Html)
|
|
155
|
+
return inner
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
function createRequestGuards(
|
|
160
|
+
maxRequestBodySize: number,
|
|
161
|
+
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response,
|
|
162
|
+
) {
|
|
163
|
+
const refuseCrossSite = (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string): Response =>
|
|
164
|
+
finish(Response.json({ ok: false, status: 403, error: reason }, { status: 403 }), request, cookieStore, requestId)
|
|
165
|
+
|
|
166
|
+
const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
|
|
167
|
+
if (bodyLimited)
|
|
168
|
+
return request
|
|
169
|
+
const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
|
|
170
|
+
if (bounded.ok)
|
|
171
|
+
return bounded.request
|
|
172
|
+
return finish(wantsJson(request)
|
|
173
|
+
? Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
|
|
174
|
+
: new Response('Payload Too Large', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
|
|
175
|
+
}
|
|
176
|
+
return { refuseCrossSite, checkBodyLimit }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
interface ActionDispatcherDeps {
|
|
180
|
+
actions: ActionRegistry
|
|
181
|
+
rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
|
|
182
|
+
trustedOrigins: Set<string> | undefined
|
|
183
|
+
trustProxy: TrustProxy
|
|
184
|
+
consent: NormalizedConsentConfig | undefined
|
|
185
|
+
rateLimits: RateLimitStore
|
|
186
|
+
isDev: boolean
|
|
187
|
+
refuseCrossSite: (request: Request, reason: string, cookieStore?: CookieStore, requestId?: string) => Response
|
|
188
|
+
checkBodyLimit: (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string) => Promise<Request | Response>
|
|
189
|
+
finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
|
|
190
|
+
notifyError: NotifyError
|
|
191
|
+
renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function createActionDispatcher(deps: ActionDispatcherDeps) {
|
|
195
|
+
const { actions, rewrites, trustedOrigins, trustProxy, consent, rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError } = deps
|
|
196
|
+
const limiters = new WeakMap<RegisteredAction['act'], RateLimiter>()
|
|
197
|
+
const limiterFor = (act: RegisteredAction['act']): RateLimiter | undefined => {
|
|
198
|
+
if (act.rateLimit === undefined)
|
|
199
|
+
return undefined
|
|
200
|
+
let limiter = limiters.get(act)
|
|
201
|
+
if (limiter === undefined) {
|
|
202
|
+
limiter = rateLimits.limiter(act.rateLimit)
|
|
203
|
+
limiters.set(act, limiter)
|
|
204
|
+
}
|
|
205
|
+
return limiter
|
|
206
|
+
}
|
|
207
|
+
return async (
|
|
208
|
+
registeredAction: RegisteredAction,
|
|
209
|
+
request: Request,
|
|
210
|
+
url: URL,
|
|
211
|
+
rawPathname: string,
|
|
212
|
+
remoteIp: string | undefined,
|
|
213
|
+
bodyLimited: boolean,
|
|
214
|
+
requestId: string,
|
|
215
|
+
existing?: { ctx: RequestContext, cookieStore: CookieStore },
|
|
216
|
+
): Promise<Response> => {
|
|
217
|
+
const actionHandler = request.method === 'POST' ? registeredAction : undefined
|
|
218
|
+
let req = request
|
|
219
|
+
if (actionHandler !== undefined) {
|
|
220
|
+
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
221
|
+
if (!originCheck.ok)
|
|
222
|
+
return refuseCrossSite(request, originCheck.reason, existing?.cookieStore, requestId)
|
|
223
|
+
const checked = await checkBodyLimit(request, bodyLimited, existing?.cookieStore, requestId)
|
|
224
|
+
if (checked instanceof Response)
|
|
225
|
+
return checked
|
|
226
|
+
req = checked
|
|
227
|
+
}
|
|
228
|
+
const { act, middlewares } = registeredAction
|
|
229
|
+
const { ctx, cookieStore } = existing ?? makeRequestContext(req, {}, { trustProxy, remoteIp, url, consent, requestId })
|
|
230
|
+
ctx.request = req
|
|
231
|
+
if (existing === undefined && rewrites.length > 0) {
|
|
232
|
+
for (const rewrite of rewrites)
|
|
233
|
+
rewrite(rawPathname, ctx)
|
|
234
|
+
}
|
|
235
|
+
const timing = createTiming(isDev)
|
|
236
|
+
try {
|
|
237
|
+
const res = await actions.run(ctx, () => runTimedChain(ctx, middlewares, () =>
|
|
238
|
+
actionHandler !== undefined
|
|
239
|
+
? executeAction(act, req, ctx, trustedOrigins, trustProxy, limiterFor(act))
|
|
240
|
+
: methodNotAllowed('POST'),
|
|
241
|
+
timing, runChain))
|
|
242
|
+
return finish(actionHandler !== undefined ? finishActionRedirect(res, req) : res, req, cookieStore, ctx.requestId, formatServerTiming(timing))
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
notifyError(error, req, 'action', ctx.requestId)
|
|
246
|
+
return renderError(error, cookieStore, ctx.url, req, ctx)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
interface ManifestActions {
|
|
252
|
+
manifest: EmbeddedServerConfig['manifest']
|
|
253
|
+
modules: EmbeddedServerConfig['modules']
|
|
254
|
+
actions: ReturnType<typeof createActionRegistry>
|
|
255
|
+
routesPrefix: ReturnType<typeof inferRoutesServerPrefix>
|
|
256
|
+
routePathByFile: Map<string, string>
|
|
257
|
+
middlewaresFor: (path: string) => readonly Middleware[]
|
|
258
|
+
middlewaresForPaths: (paths: string[]) => readonly Middleware[]
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Server actions and their live URLs.
|
|
262
|
+
function registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths }: ManifestActions): void {
|
|
263
|
+
for (const entry of manifest.actions) {
|
|
264
|
+
const mod = modules[entry.file] as Record<string, unknown> | undefined
|
|
265
|
+
const act = mod?.[entry.exportName]
|
|
266
|
+
if (isServerAction(act)) {
|
|
267
|
+
const routePrefix = actionRoutePrefix(entry, routesPrefix, routePathByFile)
|
|
268
|
+
const pluginMws = routePrefix !== undefined ? middlewaresForPaths([entry.url, routePrefix]) : middlewaresFor(entry.url)
|
|
269
|
+
actions.register(act, entry.exportName, entry.url, entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default), pluginMws)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export async function createServerFromEmbedded(config: EmbeddedServerConfig): Promise<PrunelleApp> {
|
|
275
|
+
const { manifest, modules, assets, publicAssets = {}, publicEtags = {}, prerendered = {}, prerenderedFiles = {}, prerenderedEtags = {}, lang = 'en', security } = config
|
|
276
|
+
const plugins = resolvePlugins(config.plugins)
|
|
277
|
+
const assetPrefix = (config.assetPrefix ?? '/_pru').replace(/\/$/, '')
|
|
278
|
+
const site = config.site?.replace(/\/$/, '') || undefined
|
|
279
|
+
const trustedOriginsList = config.trustedOrigins ?? []
|
|
280
|
+
const trustedOrigins = trustedOriginsList.length > 0 ? new Set(trustedOriginsList) : undefined
|
|
281
|
+
const trustProxy = config.trustProxy ?? false
|
|
282
|
+
const consent = normalizeConsentConfig(config.consent)
|
|
283
|
+
const maxRequestBodySize = config.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
|
|
284
|
+
const streamTimeout = config.streamTimeout ?? DEFAULT_STREAM_TIMEOUT
|
|
285
|
+
const isDev = config.dev ?? (process.env.PRUNELLE_DEV === '1')
|
|
286
|
+
const serverRoot = config.root ?? process.cwd()
|
|
287
|
+
const serverOutDir = config.outDir ?? join(serverRoot, 'dist')
|
|
288
|
+
const serverPublicDir = config.publicDir ?? join(serverOutDir, 'public')
|
|
289
|
+
const parentAppCtx = getAppContext()
|
|
290
|
+
|
|
291
|
+
const alwaysLoadRuntime = plugins.some(p => Boolean(p.clientEntry))
|
|
292
|
+
const notifyError = createErrorNotifier(config.onError, plugins, { dev: isDev, sink: config.errorSink })
|
|
293
|
+
const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
|
|
294
|
+
const { hasHeadHooks, hasHtmlTransformers, resolveDocumentHead, applyHtmlTransforms } = document
|
|
295
|
+
|
|
296
|
+
const securityEntries = buildSecurityHeaderEntries(security)
|
|
297
|
+
const securityRecord: Record<string, string> = Object.fromEntries(securityEntries)
|
|
298
|
+
const nosniffHeader: Record<string, string> = security !== false && (security?.contentTypeOptions ?? true) ? { 'x-content-type-options': 'nosniff' } : {}
|
|
299
|
+
const hstsValue = resolveHstsValue(security)
|
|
300
|
+
const withHsts = (res: Response, request: Request): Response => applyHstsHeader(res, request, hstsValue, trustProxy, isDev)
|
|
301
|
+
// The one way out of every response not built with the security headers already in place.
|
|
302
|
+
const finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string): Response =>
|
|
303
|
+
withHsts(finalizeResponse(res, cookieStore, securityEntries, requestId, serverTiming), request)
|
|
304
|
+
const resolveRequestId = createRequestIdResolver(trustProxy)
|
|
305
|
+
const serverError = makeServerError(securityRecord)
|
|
306
|
+
const fileGone = makeFileGone(securityRecord)
|
|
307
|
+
const navigation = createNavigation(config.navigation)
|
|
308
|
+
const htmlHeaders = createHtmlHeaders(security, securityRecord, navigation, plugins)
|
|
309
|
+
const streams = createStreamTracker()
|
|
310
|
+
|
|
311
|
+
const compressEnabled = config.compress ?? !isDev
|
|
312
|
+
const compressCache = compressEnabled ? new CompressionCache() : undefined
|
|
313
|
+
|
|
314
|
+
const files = createAssets({ assets, assetPrefix, isDev, compressEnabled, compressCache, nosniffHeader, securityRecord, withHsts })
|
|
315
|
+
const { assetMap, publicMap, serveFile } = files
|
|
316
|
+
files.registerPublicFiles(publicAssets, publicEtags)
|
|
317
|
+
|
|
318
|
+
const serverAppCtx = createAppContext({
|
|
319
|
+
root: serverRoot,
|
|
320
|
+
outDir: serverOutDir,
|
|
321
|
+
publicDir: serverPublicDir,
|
|
322
|
+
assetPrefix,
|
|
323
|
+
site,
|
|
324
|
+
dev: isDev, nodeEnv: config.nodeEnv ?? parentAppCtx?.nodeEnv,
|
|
325
|
+
onRegisterPublicFile: (rel) => {
|
|
326
|
+
parentAppCtx?.registerPublicFile(rel)
|
|
327
|
+
files.registerPublicFromDisk(serverPublicDir, rel)
|
|
328
|
+
},
|
|
329
|
+
})
|
|
330
|
+
|
|
331
|
+
const actions = createActionRegistry()
|
|
332
|
+
const pluginHost = await createServerPluginHost({
|
|
333
|
+
plugins,
|
|
334
|
+
config,
|
|
335
|
+
manifest,
|
|
336
|
+
appCtx: serverAppCtx,
|
|
337
|
+
root: serverRoot,
|
|
338
|
+
outDir: serverOutDir,
|
|
339
|
+
assetPrefix,
|
|
340
|
+
site,
|
|
341
|
+
dev: isDev,
|
|
342
|
+
trustProxy,
|
|
343
|
+
trustedOriginsList,
|
|
344
|
+
trustedOrigins,
|
|
345
|
+
})
|
|
346
|
+
const { router: pluginRouter, middlewaresFor, middlewaresForPaths } = pluginHost
|
|
347
|
+
const healthPath = `${assetPrefix}/health`
|
|
348
|
+
const healthHandler = createHealthHandler({ checks: collectHealthChecks(config.healthCheck, pluginHost.healthChecks), securityRecord, withHsts, resolveRequestId })
|
|
349
|
+
const hasPluginRewrites = pluginHost.rewrites.length > 0
|
|
350
|
+
const routesPrefix = inferRoutesServerPrefix(manifest)
|
|
351
|
+
const paramMatchers = resolveParamMatchers(manifest.paramMatchers, modules)
|
|
352
|
+
const routePathByFile = new Map(manifest.routes.map(r => [r.file, r.path]))
|
|
353
|
+
const ancestorMiddlewaresFor = createAncestorMiddlewareLookup(manifest, modules, routesPrefix, paramMatchers)
|
|
354
|
+
const pluginMiddlewaresFor = (effectiveScopedPath: string, rawScopedPath: string): readonly Middleware[] =>
|
|
355
|
+
effectiveScopedPath === rawScopedPath ? middlewaresFor(effectiveScopedPath) : middlewaresForPaths([effectiveScopedPath, rawScopedPath])
|
|
356
|
+
|
|
357
|
+
registerManifestActions({ manifest, modules, actions, routesPrefix, routePathByFile, middlewaresFor, middlewaresForPaths })
|
|
358
|
+
const { buildNotFoundResponse, renderError, renderDenied } = createFallbackPages({ manifest, modules, routesPrefix, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, dev: isDev, document, htmlHeaders, notifyError, finish })
|
|
359
|
+
|
|
360
|
+
async function renderNotFound(
|
|
361
|
+
cookieStore: CookieStore,
|
|
362
|
+
url: URL,
|
|
363
|
+
request: Request,
|
|
364
|
+
ctx: RequestContext,
|
|
365
|
+
effective: RequestPath,
|
|
366
|
+
rawScopedPath: string,
|
|
367
|
+
timing?: DevTiming,
|
|
368
|
+
): Promise<Response> {
|
|
369
|
+
const pluginMws = pluginMiddlewaresFor(effective.scopedPath, rawScopedPath)
|
|
370
|
+
const ancestor = ancestorMiddlewaresFor(effective)
|
|
371
|
+
if (ancestor !== undefined)
|
|
372
|
+
ctx.params = ancestor.params
|
|
373
|
+
const chain = ancestor === undefined ? pluginMws : [...pluginMws, ...ancestor.middlewares]
|
|
374
|
+
try {
|
|
375
|
+
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, chain, () => buildNotFoundResponse(url, request, ctx), timing, runChain))
|
|
376
|
+
return finish(await maybeRenderDenied(rawRes, request, url, ctx, renderDenied), request, cookieStore, ctx.requestId, formatServerTiming(timing))
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
notifyError(error, request, 'route', ctx.requestId)
|
|
380
|
+
return renderError(error, cookieStore, url, request, ctx)
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const { refuseCrossSite, checkBodyLimit } = createRequestGuards(maxRequestBodySize, finish)
|
|
385
|
+
|
|
386
|
+
const { router, fastStaticPages } = compileRouteTable({
|
|
387
|
+
manifest, modules, paramMatchers, lang, alwaysLoadRuntime, navigation: navigation.html, middlewaresFor,
|
|
388
|
+
pluginIntercepts: path => hasPluginRewrites || hasHeadHooks || hasHtmlTransformers || pluginRouter.match(literalPath(path)) !== undefined,
|
|
389
|
+
fast: { trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts, dev: isDev, resolveRequestId },
|
|
390
|
+
})
|
|
391
|
+
const { all: prerenderedMap, fast: fastPrerenderedMap } = files.collectPrerendered(manifest.routes, {
|
|
392
|
+
prerendered,
|
|
393
|
+
prerenderedFiles,
|
|
394
|
+
prerenderedEtags,
|
|
395
|
+
// The route's region script is what sends `x-pru-region`, so a page without one never varies on it.
|
|
396
|
+
htmlHeaders: (route, urlPath) => withRegionVary(htmlHeaders(route.islandChunks.length > 0, false, false, route.prerenderedStyleHashes?.[urlPath]), route.usesRegion === true),
|
|
397
|
+
isFast: nativePrerenderedCheck({ site, rewrites: pluginHost.rewrites, pluginRouter, router, actions, middlewaresForPaths, trustProxy, consent }),
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
async function renderCompiledRoute(
|
|
401
|
+
route: CompiledRoute,
|
|
402
|
+
ctx: RequestContext,
|
|
403
|
+
disableTimeout?: () => void,
|
|
404
|
+
staticPath?: string,
|
|
405
|
+
timing?: DevTiming,
|
|
406
|
+
): Promise<Response> {
|
|
407
|
+
const { entry, mod, doc } = route
|
|
408
|
+
|
|
409
|
+
const isRegion = hasRegionHeader(ctx.request)
|
|
410
|
+
// Serve prerendered HTML after middlewares have passed (skip on full-page GETs with a flash cookie so it hydrates & clears, and on region requests)
|
|
411
|
+
if (isRead(ctx.request)) {
|
|
412
|
+
const pre = lookupPrerendered(prerenderedMap, staticPath)
|
|
413
|
+
if (pre !== undefined && !isRegion && (ctx.request.method === 'HEAD' || !hasActionErrorCookie(ctx.request)))
|
|
414
|
+
return serveFile(ctx.request, pre)
|
|
415
|
+
// Prerendered dynamic route: unlisted param returns 404 (never falls back to SSR)
|
|
416
|
+
if (pre === undefined && entry.prerender === true && entry.prerendered !== undefined && route.dynamic)
|
|
417
|
+
return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// API route (.ts exporting GET/POST/etc.) — HEAD falls back to GET without a body
|
|
421
|
+
const method = ctx.request.method.toUpperCase()
|
|
422
|
+
const methodHandler = mod[method]
|
|
423
|
+
if (typeof methodHandler === 'function')
|
|
424
|
+
return await (methodHandler as (c: RequestContext) => Response | Promise<Response>)(ctx)
|
|
425
|
+
if (method === 'HEAD' && typeof mod.GET === 'function')
|
|
426
|
+
return stripHeadBody(await mod.GET(ctx))
|
|
427
|
+
|
|
428
|
+
// Page routes only handle GET/HEAD; unsafe methods (POST/PUT/PATCH/DELETE) without a method export get 405.
|
|
429
|
+
if (typeof mod.default !== 'function' || !isRead(ctx.request))
|
|
430
|
+
return methodNotAllowed(allowedMethodsHeader(mod))
|
|
431
|
+
if (isRegion && requestedRegion(ctx.request) === undefined)
|
|
432
|
+
return invalidRegionResponse(ctx.request)
|
|
433
|
+
|
|
434
|
+
// Hydrate one-shot flash cookie on full page GETs only; defer deletion until a full page renders (not load() redirects or <Region> requests)
|
|
435
|
+
const hasFlash = ctx.request.method === 'GET' && !isRegion && hasActionErrorCookie(ctx.request) && hydrateActionErrorFlash(ctx)
|
|
436
|
+
|
|
437
|
+
let data: unknown
|
|
438
|
+
if (entry.hasLoad && typeof mod.load === 'function') {
|
|
439
|
+
const loadStart = startTimer(timing)
|
|
440
|
+
try {
|
|
441
|
+
data = await mod.load(ctx)
|
|
442
|
+
}
|
|
443
|
+
catch (error) {
|
|
444
|
+
if (isNotFound(error))
|
|
445
|
+
return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
|
|
446
|
+
throw error
|
|
447
|
+
}
|
|
448
|
+
endTimer(timing, 'load', loadStart)
|
|
449
|
+
}
|
|
450
|
+
if (isNotFound(data))
|
|
451
|
+
return buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file)
|
|
452
|
+
if (data instanceof Response)
|
|
453
|
+
return data
|
|
454
|
+
const pageProps: Record<string, unknown> = {
|
|
455
|
+
params: ctx.params,
|
|
456
|
+
locals: ctx.locals,
|
|
457
|
+
url: ctx.url,
|
|
458
|
+
...(data !== undefined ? { data } : {}),
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (isRegion) {
|
|
462
|
+
return respondRegion(
|
|
463
|
+
ctx.request, mod, pageProps, entry.path, htmlHeaders,
|
|
464
|
+
rctx => resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
|
|
465
|
+
streamTimeout, error => notifyError(error, ctx.request, 'route', ctx.requestId),
|
|
466
|
+
hasHtmlTransformers ? html => applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const renderStart = startTimer(timing)
|
|
471
|
+
const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, ctx.request, 'route', ctx.requestId))
|
|
472
|
+
const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, ctx))
|
|
473
|
+
if (hasFlash)
|
|
474
|
+
ctx.cookies.delete(ACTION_ERROR_COOKIE)
|
|
475
|
+
const docHead = await resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
|
|
476
|
+
const renderedIslands = resolveRenderedIslands(rctx, body)
|
|
477
|
+
const isStreamed = rctx.pending.length > 0
|
|
478
|
+
const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
|
|
479
|
+
// A streamed page preloads before its boundaries render, so it takes the route's eager islands: a lazy one loads when its strategy fires.
|
|
480
|
+
const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, manifest.reviveScript)]
|
|
481
|
+
const hasRegions = rctx.regionNames.size > 0
|
|
482
|
+
|
|
483
|
+
const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
|
|
484
|
+
|
|
485
|
+
// Streaming SSR when <Suspense> boundaries are pending, compressed per flush, never buffered
|
|
486
|
+
if (isStreamed) {
|
|
487
|
+
endTimer(timing, 'render', renderStart)
|
|
488
|
+
const streamStart = startTimer(timing)
|
|
489
|
+
if (ctx.request.method === 'HEAD') {
|
|
490
|
+
endTimer(timing, 'stream', streamStart)
|
|
491
|
+
return markCompressionHandled(new Response(null, { status: 200, headers: withRegionVary(htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions) }))
|
|
492
|
+
}
|
|
493
|
+
disableTimeout?.()
|
|
494
|
+
const docShell = renderDocument({ ...doc, body: body + STREAM_TAIL_MARK, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands, hasSuspense: true })
|
|
495
|
+
// Transforms see the document with its initial body; boundaries resolved later stream as they render.
|
|
496
|
+
const shell = hasHtmlTransformers ? await applyHtmlTransforms(docShell, ctx.url, ctx.request, ctx) : docShell
|
|
497
|
+
const streamStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docShell, shell))
|
|
498
|
+
endTimer(timing, 'stream', streamStart)
|
|
499
|
+
return compressedHtmlStream(streamDocument(shell, rctx, streamTimeout, error => notifyError(error, ctx.request, 'route', ctx.requestId)), 200, withRegionVary(htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, compressCache)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const docHtml = renderDocument({ ...doc, body, head: docHead.head, lang: docHead.lang, htmlAttrs: docHead.htmlAttrs, preloadChunks, hasIslands })
|
|
503
|
+
const html = hasHtmlTransformers ? await applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
|
|
504
|
+
const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
|
|
505
|
+
endTimer(timing, 'render', renderStart)
|
|
506
|
+
|
|
507
|
+
return compressedHtmlResponse(html, 200, withRegionVary(htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions), ctx.request, compressCache)
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const dispatchAction = createActionDispatcher({
|
|
511
|
+
actions, rewrites: pluginHost.rewrites, trustedOrigins, trustProxy, consent, rateLimits: pluginHost.rateLimits, isDev, refuseCrossSite, checkBodyLimit, finish, notifyError, renderError,
|
|
512
|
+
})
|
|
513
|
+
|
|
514
|
+
// `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
|
|
515
|
+
async function handleInternal(request: Request, remoteIp?: string, disableTimeout?: () => void, bodyLimited = false): Promise<Response> {
|
|
516
|
+
const requestId = resolveRequestId(request)
|
|
517
|
+
try {
|
|
518
|
+
const url = new URL(request.url)
|
|
519
|
+
const rawPathname = url.pathname
|
|
520
|
+
const requestPath = decodeRequestPath(rawPathname)
|
|
521
|
+
if (requestPath === undefined)
|
|
522
|
+
return finish(badRequest(), request, undefined, requestId)
|
|
523
|
+
const { staticPath, scopedPath } = requestPath
|
|
524
|
+
if (staticPath === healthPath)
|
|
525
|
+
return healthHandler(request, requestId)
|
|
526
|
+
const read = isRead(request)
|
|
527
|
+
|
|
528
|
+
// 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
|
|
529
|
+
if (read) {
|
|
530
|
+
const staticFile = matchStaticOrPublic(request, requestPath, assetMap, publicMap, pluginRouter)
|
|
531
|
+
if (staticFile !== undefined)
|
|
532
|
+
return withRequestId(await serveFile(request, staticFile), requestId)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
|
|
536
|
+
const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
|
|
537
|
+
if (registeredAction !== undefined)
|
|
538
|
+
return dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
|
|
539
|
+
|
|
540
|
+
// 3. Prerendered static HTML, then 4. the zero-overhead static route path
|
|
541
|
+
const plainRead = isPlainRead(request)
|
|
542
|
+
if (plainRead && staticPath !== undefined) {
|
|
543
|
+
const pre = fastPrerenderedMap.get(staticPath)
|
|
544
|
+
if (pre !== undefined)
|
|
545
|
+
return withRequestId(await serveFile(request, pre), requestId)
|
|
546
|
+
const fast = fastStaticPages.get(staticPath)
|
|
547
|
+
if (fast !== undefined)
|
|
548
|
+
return fast(request, remoteIp, url, requestId)
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
552
|
+
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent, requestId })
|
|
553
|
+
const timing = createTiming(isDev)
|
|
554
|
+
|
|
555
|
+
// Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
556
|
+
let effectivePath = rawPathname
|
|
557
|
+
for (const rewrite of pluginHost.rewrites) {
|
|
558
|
+
const nextPath = rewrite(effectivePath, ctx)
|
|
559
|
+
if (nextPath !== undefined)
|
|
560
|
+
effectivePath = nextPath
|
|
561
|
+
}
|
|
562
|
+
let effective = requestPath
|
|
563
|
+
if (effectivePath !== rawPathname) {
|
|
564
|
+
const rewritten = decodeRequestPath(effectivePath)
|
|
565
|
+
if (rewritten === undefined)
|
|
566
|
+
return finish(badRequest(), request, cookieStore, requestId)
|
|
567
|
+
effective = rewritten
|
|
568
|
+
const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
|
|
569
|
+
if (rewrittenAction !== undefined)
|
|
570
|
+
return dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
|
|
571
|
+
}
|
|
572
|
+
const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
|
|
573
|
+
|
|
574
|
+
// Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
|
|
575
|
+
const method = request.method.toUpperCase()
|
|
576
|
+
const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
|
|
577
|
+
const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
|
|
578
|
+
const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
|
|
579
|
+
const routeDef = directPluginDef ?? headFallbackPluginDef
|
|
580
|
+
if (pluginMatch !== undefined && routeDef !== undefined) {
|
|
581
|
+
if (routeDef.csrf) {
|
|
582
|
+
const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
|
|
583
|
+
if (!originCheck.ok)
|
|
584
|
+
return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
|
|
585
|
+
}
|
|
586
|
+
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
587
|
+
if (checked instanceof Response)
|
|
588
|
+
return checked
|
|
589
|
+
ctx.request = checked
|
|
590
|
+
ctx.params = pluginMatch.params
|
|
591
|
+
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
592
|
+
try {
|
|
593
|
+
let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
|
|
594
|
+
if (headFallbackPluginDef !== undefined)
|
|
595
|
+
res = stripHeadBody(res)
|
|
596
|
+
else if (isEventStream(res))
|
|
597
|
+
res = streams.track(res, disableTimeout)
|
|
598
|
+
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
notifyError(error, ctx.request, 'plugin', requestId)
|
|
602
|
+
return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
|
|
607
|
+
if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
|
|
608
|
+
const pub = publicMap.get(effectiveStaticPath)
|
|
609
|
+
if (pub !== undefined)
|
|
610
|
+
return withRequestId(await serveFile(request, pub), requestId)
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const matched = router.match(effective)
|
|
614
|
+
if (matched === undefined) {
|
|
615
|
+
if (pluginMatch !== undefined) {
|
|
616
|
+
ctx.params = pluginMatch.params
|
|
617
|
+
const allow = allowedPluginMethodsHeader(pluginMatch.data)
|
|
618
|
+
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
619
|
+
try {
|
|
620
|
+
const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
|
|
621
|
+
return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
notifyError(error, request, 'plugin', requestId)
|
|
625
|
+
return renderError(error, cookieStore, ctx.url, request, ctx)
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
ctx.params = matched.params
|
|
632
|
+
const route = matched.data
|
|
633
|
+
|
|
634
|
+
// CSRF verification & body limit for file-based API routes (opt out of CSRF via `export const csrf = false`)
|
|
635
|
+
if (typeof route.mod[method] === 'function') {
|
|
636
|
+
if (route.mod.csrf !== false) {
|
|
637
|
+
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
638
|
+
if (!originCheck.ok)
|
|
639
|
+
return refuseCrossSite(request, originCheck.reason, cookieStore, requestId)
|
|
640
|
+
}
|
|
641
|
+
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
642
|
+
if (checked instanceof Response)
|
|
643
|
+
return checked
|
|
644
|
+
ctx.request = checked
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
|
|
648
|
+
? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
|
|
649
|
+
: route.middlewares
|
|
650
|
+
|
|
651
|
+
try {
|
|
652
|
+
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, disableTimeout, staticPath, timing), timing, runChain))
|
|
653
|
+
const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
|
|
654
|
+
const res = isEventStream(handledRes) ? streams.track(handledRes, disableTimeout) : handledRes
|
|
655
|
+
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
656
|
+
const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
|
|
657
|
+
return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
658
|
+
}
|
|
659
|
+
catch (error) {
|
|
660
|
+
notifyError(error, ctx.request, 'route', requestId)
|
|
661
|
+
return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
notifyError(error, request, 'route', requestId)
|
|
666
|
+
return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function handle(request: Request, remoteIp?: string): Promise<Response> {
|
|
671
|
+
return runWithAppContext(serverAppCtx, () => handleInternal(request, remoteIp))
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
const runRequest = (req: Request, remoteIp: string | undefined, disableTimeout: () => void): Promise<Response> => runWithAppContext(serverAppCtx, () => handleInternal(req, remoteIp, disableTimeout, true))
|
|
675
|
+
const runFast = (handler: FastHandler, req: Request, remoteIp: string | undefined): Response | Promise<Response> => runWithAppContext(serverAppCtx, () => handler(req, remoteIp))
|
|
676
|
+
const handlers = (server: () => PrunelleServer | undefined) => serveHandlers(server, { files, fastPrerenderedMap, fastStaticPages, pluginRouter, healthPath, healthHandler, resolveRequestId, runRequest, runFast, notifyError, serverError, fileGone })
|
|
677
|
+
|
|
678
|
+
function serve(port = 3000, hostname = '127.0.0.1') {
|
|
679
|
+
const server: PrunelleServer = Bun.serve({ port, hostname, idleTimeout: 30, maxRequestBodySize, development: false, ...handlers(() => server) })
|
|
680
|
+
return server
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
const reloadInto = (server: PrunelleServer): void => {
|
|
684
|
+
server.reload(handlers(() => server))
|
|
685
|
+
}
|
|
686
|
+
return { handle, serve, reloadInto, closeStreams: streams.closeAll, dispose: async () => { await streams.closeAll(); await pluginHost.dispose() } }
|
|
687
|
+
}
|