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.
- package/LICENSE +21 -0
- package/llms.txt +245 -0
- package/package.json +62 -4
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +661 -0
- package/src/build/byte-size.ts +11 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +175 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +130 -0
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +171 -0
- package/src/build/first-load.ts +235 -0
- package/src/build/graph.ts +237 -0
- package/src/build/index.ts +678 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +452 -0
- package/src/build/manifest.ts +204 -0
- package/src/build/output.ts +81 -0
- package/src/build/plugin-host.ts +294 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +288 -0
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +290 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +209 -0
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +409 -0
- package/src/cli/commands.ts +372 -0
- package/src/cli/docs.ts +403 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +406 -0
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +52 -0
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +367 -0
- package/src/compiler/analyze.ts +651 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +250 -0
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +653 -0
- package/src/compiler/data-keys.ts +302 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +641 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +587 -0
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +520 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +635 -0
- package/src/compiler/server-only.ts +365 -0
- package/src/compiler/shared.ts +397 -0
- package/src/compiler/signal-reads.ts +246 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +525 -0
- package/src/context.ts +199 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +268 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +24 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +212 -0
- package/src/dev/watchers.ts +276 -0
- package/src/dom/action.ts +187 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +579 -0
- package/src/dom/index.ts +329 -0
- package/src/dom/island.ts +318 -0
- package/src/dom/loop.ts +484 -0
- package/src/dom/revive.ts +36 -0
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +92 -0
- package/src/plugins/context.ts +109 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +90 -0
- package/src/plugins/order.ts +148 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +119 -0
- package/src/plugins/types.ts +278 -0
- package/src/reactivity/graph.ts +259 -0
- package/src/reactivity/index.ts +541 -0
- package/src/reactivity/selector.ts +78 -0
- package/src/reactivity/store.ts +252 -0
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +511 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +646 -0
- package/src/server/consent.ts +290 -0
- package/src/server/cookies.ts +153 -0
- package/src/server/document.ts +286 -0
- package/src/server/env.ts +47 -0
- package/src/server/errors.ts +396 -0
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +588 -0
- package/src/server/index.ts +615 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +131 -0
- package/src/server/page.ts +122 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +267 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +20 -0
- package/src/server/rate-limit.ts +199 -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-cache.ts +541 -0
- package/src/server/route-table.ts +424 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +388 -0
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +550 -0
- package/src/server/serve-handlers.ts +93 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +104 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +246 -0
- package/src/server/stream.ts +233 -0
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +399 -0
- package/src/ssr/index.ts +624 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +192 -0
- package/src/style.ts +96 -0
- package/src/test/browser.ts +201 -0
- package/src/test/index.ts +262 -0
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -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 +8 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +22 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +8 -0
- package/templates/app/package.json +22 -0
- package/templates/app/prunelle.config.ts +13 -0
- package/templates/app/src/auth.ts +12 -0
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +40 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +47 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +53 -0
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +14 -0
- package/templates/app/tests/app.test.ts +73 -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 +25 -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 +15 -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 +28 -0
- package/templates/fullstack/src/routes/_layout.tsx +18 -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 +39 -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 +18 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +32 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// What plugins see of a running server: each `server(api)` hook, and the middleware, routes, rewrites and shutdown hooks those hooks register.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { AppRuntimeContext } from '../plugins/context'
|
|
5
|
+
import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
|
|
6
|
+
import type { HealthCheckEntry } from './health'
|
|
7
|
+
import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
|
|
8
|
+
|
|
9
|
+
import type { TrustProxy } from './security'
|
|
10
|
+
import { runWithAppContext } from '../plugins/context'
|
|
11
|
+
import { enforceRequirements } from '../plugins/requires'
|
|
12
|
+
import { normalizeConsentConfig, registerConsentRoute } from './consent'
|
|
13
|
+
import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
|
|
14
|
+
import type { RequestPath } from './request-path'
|
|
15
|
+
import type { RouteMatch } from './router'
|
|
16
|
+
import { Router } from './router'
|
|
17
|
+
|
|
18
|
+
export interface PluginRouteDef {
|
|
19
|
+
plugin: string
|
|
20
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>
|
|
21
|
+
csrf: boolean
|
|
22
|
+
trustedOrigins: Set<string> | undefined
|
|
23
|
+
trustProxy: TrustProxy
|
|
24
|
+
/** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
|
|
25
|
+
encodedSlashes: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface ScopedMiddleware {
|
|
29
|
+
mw: Middleware
|
|
30
|
+
scope: 'all' | 'rendered' | 'dynamic' | string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What a request reaches, as middleware scopes see it: a page built ahead of time, a page with no `load` that renders the same for everyone, or anything else answered per request. */
|
|
34
|
+
export type RequestKind = 'prerendered' | 'static' | 'dynamic'
|
|
35
|
+
|
|
36
|
+
const isKindScope = (scope: string): boolean => scope === 'all' || scope === 'rendered' || scope === 'dynamic'
|
|
37
|
+
|
|
38
|
+
export interface ServerPluginHostOptions {
|
|
39
|
+
plugins: readonly PrunellePlugin[]
|
|
40
|
+
config: EmbeddedServerConfig
|
|
41
|
+
manifest: BuildManifest
|
|
42
|
+
appCtx: AppRuntimeContext
|
|
43
|
+
root: string
|
|
44
|
+
outDir: string
|
|
45
|
+
assetPrefix: string
|
|
46
|
+
site: string | undefined
|
|
47
|
+
dev: boolean
|
|
48
|
+
devExposed: boolean
|
|
49
|
+
trustProxy: TrustProxy
|
|
50
|
+
trustedOriginsList: readonly string[]
|
|
51
|
+
trustedOrigins: Set<string> | undefined
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, kind: RequestKind): boolean {
|
|
55
|
+
if (scope === 'all')
|
|
56
|
+
return true
|
|
57
|
+
if (scope === 'rendered')
|
|
58
|
+
return kind !== 'prerendered'
|
|
59
|
+
if (scope === 'dynamic')
|
|
60
|
+
return kind === 'dynamic'
|
|
61
|
+
const normScope = scope.length > 1 && scope.endsWith('/') ? scope.slice(0, -1) : scope
|
|
62
|
+
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
63
|
+
if (normScope === '/')
|
|
64
|
+
return normPath.startsWith('/')
|
|
65
|
+
return normPath === normScope || normPath.startsWith(`${normScope}/`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
|
|
69
|
+
export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
|
|
70
|
+
if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
|
|
71
|
+
return match
|
|
72
|
+
const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
|
|
73
|
+
return data.size === 0 ? undefined : { data, params: match.params }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
77
|
+
const allowed = new Set<string>()
|
|
78
|
+
for (const m of methods.keys()) {
|
|
79
|
+
if (m === 'ALL')
|
|
80
|
+
continue
|
|
81
|
+
allowed.add(m)
|
|
82
|
+
}
|
|
83
|
+
if (allowed.has('GET'))
|
|
84
|
+
allowed.add('HEAD')
|
|
85
|
+
return [...allowed].join(', ')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
|
|
89
|
+
const directConflict = byMethod.get(upperMethod)
|
|
90
|
+
if (directConflict !== undefined)
|
|
91
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
92
|
+
if (upperMethod === 'ALL' && byMethod.size > 0) {
|
|
93
|
+
const [existingMethod, existingDef] = byMethod.entries().next().value!
|
|
94
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
|
|
95
|
+
}
|
|
96
|
+
const allConflict = byMethod.get('ALL')
|
|
97
|
+
if (allConflict !== undefined)
|
|
98
|
+
throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function createMiddlewareLookup(scopedMiddlewares: readonly ScopedMiddleware[]) {
|
|
102
|
+
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
103
|
+
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
|
|
104
|
+
// With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
|
|
105
|
+
const byKind: Record<RequestKind, readonly Middleware[]> = {
|
|
106
|
+
prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
|
|
107
|
+
static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
|
|
108
|
+
dynamic: allMiddlewares,
|
|
109
|
+
}
|
|
110
|
+
const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
111
|
+
if (!hasPathScopedMiddlewares)
|
|
112
|
+
return byKind[kind]
|
|
113
|
+
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
|
|
114
|
+
}
|
|
115
|
+
const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
|
|
116
|
+
if (!hasPathScopedMiddlewares)
|
|
117
|
+
return byKind[kind]
|
|
118
|
+
return scopedMiddlewares
|
|
119
|
+
.filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
|
|
120
|
+
.map(m => m.mw)
|
|
121
|
+
}
|
|
122
|
+
return { allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
126
|
+
const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
|
|
127
|
+
// The counters of every limited route and action of this server, dropped with it.
|
|
128
|
+
const rateLimits = createRateLimitStore()
|
|
129
|
+
const scopedMiddlewares: ScopedMiddleware[] = []
|
|
130
|
+
const healthChecks: HealthCheckEntry[] = []
|
|
131
|
+
const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
|
|
132
|
+
const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
|
|
133
|
+
const router = new Router<Map<string, PluginRouteDef>>()
|
|
134
|
+
const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
|
|
135
|
+
|
|
136
|
+
const registerRouteFor = (pluginName: string) => (
|
|
137
|
+
method: string,
|
|
138
|
+
path: string,
|
|
139
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>,
|
|
140
|
+
routeOptions?: PluginRouteOptions,
|
|
141
|
+
): void => {
|
|
142
|
+
const upperMethod = method.toUpperCase()
|
|
143
|
+
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
144
|
+
const encodedSlashes = routeOptions?.encodedSlashes === true
|
|
145
|
+
if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
|
|
146
|
+
throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
|
|
147
|
+
let byMethod = routeEntries.get(normPath)
|
|
148
|
+
if (byMethod === undefined) {
|
|
149
|
+
byMethod = new Map()
|
|
150
|
+
routeEntries.set(normPath, byMethod)
|
|
151
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
assertRouteFree(pluginName, upperMethod, normPath, byMethod)
|
|
155
|
+
// The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
|
|
156
|
+
if (encodedSlashes)
|
|
157
|
+
router.add(normPath, byMethod, { encodedSlashes })
|
|
158
|
+
}
|
|
159
|
+
let routeTrustedOrigins = trustedOrigins
|
|
160
|
+
if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
|
|
161
|
+
routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...routeOptions.trustedOrigins])
|
|
162
|
+
}
|
|
163
|
+
const limit = routeOptions?.rateLimit
|
|
164
|
+
let limited = handler
|
|
165
|
+
if (limit !== undefined) {
|
|
166
|
+
assertRateLimit(limit, `${upperMethod} ${normPath} from "${pluginName}"`)
|
|
167
|
+
const limiter = rateLimits.limiter(limit)
|
|
168
|
+
limited = (ctx) => {
|
|
169
|
+
const retryAfter = hitFor(limiter, limit, ctx)
|
|
170
|
+
return retryAfter > 0 ? tooManyRequests(retryAfter) : handler(ctx)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
byMethod.set(upperMethod, {
|
|
174
|
+
plugin: pluginName,
|
|
175
|
+
handler: limited,
|
|
176
|
+
csrf: routeOptions?.csrf ?? true,
|
|
177
|
+
trustedOrigins: routeTrustedOrigins,
|
|
178
|
+
trustProxy: routeOptions?.trustProxy ?? trustProxy,
|
|
179
|
+
encodedSlashes,
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
let disposed = false
|
|
184
|
+
async function dispose(): Promise<void> {
|
|
185
|
+
if (disposed)
|
|
186
|
+
return
|
|
187
|
+
disposed = true
|
|
188
|
+
rateLimits.close()
|
|
189
|
+
for (const { plugin, hook } of shutdownHooks) {
|
|
190
|
+
try {
|
|
191
|
+
await hook()
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const {
|
|
200
|
+
manifest: _m,
|
|
201
|
+
modules: _mods,
|
|
202
|
+
assets: _a,
|
|
203
|
+
publicAssets: _pa,
|
|
204
|
+
publicEtags: _pe,
|
|
205
|
+
prerendered: _pr,
|
|
206
|
+
prerenderedFiles: _pf,
|
|
207
|
+
...forwardedConfig
|
|
208
|
+
} = config as EmbeddedServerConfig & Record<string, unknown>
|
|
209
|
+
const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
|
|
210
|
+
|
|
211
|
+
try {
|
|
212
|
+
const consentConfig = normalizeConsentConfig(config.consent)
|
|
213
|
+
if (consentConfig !== undefined)
|
|
214
|
+
registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
|
|
215
|
+
|
|
216
|
+
if (config.prerender !== true || config.static === true) {
|
|
217
|
+
const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
|
|
218
|
+
await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site, consentCategories: consentConfig?.categories ?? [] }, production))
|
|
219
|
+
}
|
|
220
|
+
for (const plugin of plugins) {
|
|
221
|
+
if (plugin.server !== undefined) {
|
|
222
|
+
const pluginApi: ServerPluginAPI = {
|
|
223
|
+
root: options.root,
|
|
224
|
+
outDir: options.outDir,
|
|
225
|
+
assetPrefix: options.assetPrefix,
|
|
226
|
+
site: options.site,
|
|
227
|
+
dev: options.dev,
|
|
228
|
+
devExposed: options.devExposed,
|
|
229
|
+
trustProxy,
|
|
230
|
+
trustedOrigins: options.trustedOriginsList,
|
|
231
|
+
config: readonlyRuntimeConfig,
|
|
232
|
+
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
233
|
+
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
234
|
+
},
|
|
235
|
+
route: registerRouteFor(plugin.name),
|
|
236
|
+
rateLimiter(limit) {
|
|
237
|
+
assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
|
|
238
|
+
return rateLimits.limiter(limit)
|
|
239
|
+
},
|
|
240
|
+
rewrite(fn) {
|
|
241
|
+
rewrites.push(fn)
|
|
242
|
+
},
|
|
243
|
+
provide: appCtx.provide,
|
|
244
|
+
inject: appCtx.inject,
|
|
245
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
246
|
+
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
247
|
+
},
|
|
248
|
+
healthCheck(name, fn) {
|
|
249
|
+
healthChecks.push({ name, fn })
|
|
250
|
+
},
|
|
251
|
+
onShutdown(fn) {
|
|
252
|
+
shutdownHooks.push({ plugin: plugin.name, hook: fn })
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
await dispose()
|
|
261
|
+
throw error
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return { router, rewrites, healthChecks, ...createMiddlewareLookup(scopedMiddlewares), rateLimits, dispose }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Which prerendered pages Bun's route table can answer on its own, before prunelle sees the request.
|
|
2
|
+
|
|
3
|
+
import type { RouteManifestEntry } from '../build/index'
|
|
4
|
+
import type { ActionRegistry } from './action-registry'
|
|
5
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
6
|
+
import type { Middleware, RequestContext } from './http'
|
|
7
|
+
import type { RequestKind } from './plugin-host'
|
|
8
|
+
import type { RequestPath } from './request-path'
|
|
9
|
+
import type { CompiledRoute } from './route-table'
|
|
10
|
+
import type { Router } from './router'
|
|
11
|
+
import type { TrustProxy } from './security'
|
|
12
|
+
import { makeRequestContext } from './http'
|
|
13
|
+
import { decodeRequestPath, literalPath } from './request-path'
|
|
14
|
+
|
|
15
|
+
/** The origin a page is prerendered from: the configured site's, else `http://localhost`. */
|
|
16
|
+
export function prerenderOrigin(site: string | undefined): string {
|
|
17
|
+
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
18
|
+
const parsed = new URL(site)
|
|
19
|
+
if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
|
|
20
|
+
return parsed.origin
|
|
21
|
+
}
|
|
22
|
+
return 'http://localhost'
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface NativePrerenderedDeps {
|
|
26
|
+
site: string | undefined
|
|
27
|
+
rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
|
|
28
|
+
pluginRouter: Pick<Router<unknown>, 'match'>
|
|
29
|
+
router: Pick<Router<CompiledRoute>, 'match'>
|
|
30
|
+
actions: Pick<ActionRegistry, 'byUrl'>
|
|
31
|
+
middlewaresForPaths: (paths: readonly string[], kind?: RequestKind) => readonly Middleware[]
|
|
32
|
+
trustProxy: TrustProxy
|
|
33
|
+
consent: NormalizedConsentConfig | undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Whether nothing would run before a prerendered page's file is served: no route or plugin middleware, no plugin route, and the same wherever the rewrites send it.
|
|
38
|
+
* The build rendered the page through the rewrites on an anonymous GET, so running them once on the same GET says where they send it.
|
|
39
|
+
*/
|
|
40
|
+
export function nativePrerenderedCheck(deps: NativePrerenderedDeps): (urlPath: string, route: RouteManifestEntry) => boolean {
|
|
41
|
+
const origin = prerenderOrigin(deps.site)
|
|
42
|
+
|
|
43
|
+
function rewritten(urlPath: string): RequestPath | undefined {
|
|
44
|
+
const url = new URL(urlPath, origin)
|
|
45
|
+
const { ctx } = makeRequestContext(new Request(url), {}, { trustProxy: deps.trustProxy, url, consent: deps.consent })
|
|
46
|
+
let path = url.pathname
|
|
47
|
+
try {
|
|
48
|
+
for (const rewrite of deps.rewrites)
|
|
49
|
+
path = rewrite(path, ctx) ?? path
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// A rewrite that throws here throws on the request too, which reports it; the page just stays off the table.
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
return path === url.pathname ? literalPath(urlPath) : decodeRequestPath(path)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return (urlPath, route) => {
|
|
59
|
+
if (route.middlewares.length > 0 || deps.pluginRouter.match(literalPath(urlPath)) !== undefined)
|
|
60
|
+
return false
|
|
61
|
+
const effective = deps.rewrites.length > 0 ? rewritten(urlPath) : literalPath(urlPath)
|
|
62
|
+
if (effective === undefined)
|
|
63
|
+
return false
|
|
64
|
+
if (effective.scopedPath === urlPath)
|
|
65
|
+
return deps.middlewaresForPaths([urlPath], 'prerendered').length === 0
|
|
66
|
+
return deps.router.match(effective)?.data.dirMiddlewares.length === 0
|
|
67
|
+
&& deps.pluginRouter.match(effective) === undefined
|
|
68
|
+
&& (effective.staticPath === undefined || deps.actions.byUrl(effective.staticPath) === undefined)
|
|
69
|
+
&& deps.middlewaresForPaths([effective.scopedPath, urlPath], 'prerendered').length === 0
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// `prunelle/server`: what an app's routes, actions and middleware use, and `createServer` to run a built app inside another program. Anything not listed here stays internal.
|
|
2
|
+
|
|
3
|
+
export { action, getActionError } from './action'
|
|
4
|
+
export type { ActionContext, ActionErrorFlash, ActionOptions, ActionProtectOptions, ActionResult, ServerAction } from './action'
|
|
5
|
+
export { safeEqual } from './app-secret'
|
|
6
|
+
export type { ConsentConfig, RequestConsent } from './consent'
|
|
7
|
+
export type { CookieOptions, Cookies } from './cookies'
|
|
8
|
+
export { defineEnv, nodeEnv } from './env'
|
|
9
|
+
export { notFound, wantsJson } from './http'
|
|
10
|
+
export type { ExtractRouteParams, PrunelleApp, LayoutProps, LoaderData, LoaderFn, Middleware, NotFoundResult, PageProps, RequestContext, RouteContext, ServerOptions } from './http'
|
|
11
|
+
export type { PrunelleLocals } from './index'
|
|
12
|
+
export { createServer } from './loader'
|
|
13
|
+
export { createRateLimitStore, rateLimitAddress } from './rate-limit'
|
|
14
|
+
export type { RateLimit, RateLimiter, RateLimitStore, RateLimitStoreOptions } from './rate-limit'
|
|
15
|
+
export { readStringFields } from './request-body'
|
|
16
|
+
export { DEFAULT_CSP, extendCsp, getClientIp, isHttpsRequest, isTrustedOrigin, safeRedirect, verifyOrigin } from './security'
|
|
17
|
+
export type { CspDirectives, SecurityHeadersOptions, TrustProxy } from './security'
|
|
18
|
+
export { formatIssuePath, formatSchemaIssues, validateSchema, validateSchemaSync } from './standard-schema'
|
|
19
|
+
export type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult, ValidationSuccess } from './standard-schema'
|
|
20
|
+
export { esc, escAttr, escJson, escXml, raw } from '../ssr/index'
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
// How often a client may call a plugin route or an action: a sliding window per key, in one store per server bounded in keys and hits.
|
|
2
|
+
|
|
3
|
+
import { nodeEnv } from './env'
|
|
4
|
+
|
|
5
|
+
export interface RateLimit<Ctx extends { ip?: string | undefined } = { ip?: string | undefined }> {
|
|
6
|
+
/** Requests a key may make per window. */
|
|
7
|
+
max: number
|
|
8
|
+
/** Window length in ms. */
|
|
9
|
+
windowMs: number
|
|
10
|
+
/** What a client is counted by (default: its address, `ctx.ip` as `trustProxy` reads it); `undefined` falls back to the address. */
|
|
11
|
+
key?: ((ctx: Ctx) => string | undefined) | undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface RateLimiter {
|
|
15
|
+
/** Counts a request from `key` and returns 0; past the limit, counts nothing and returns the whole seconds until the next request would pass. */
|
|
16
|
+
hit(key: string): number
|
|
17
|
+
/** The seconds `hit(key)` would answer, counting nothing: 0 while `key` is under the limit. */
|
|
18
|
+
peek(key: string): number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface RateLimitStore {
|
|
22
|
+
/** A limiter counting in this store, apart from every other limiter's keys. */
|
|
23
|
+
limiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
|
|
24
|
+
/** Drops the hits older than their window, and the keys left with none; returns how many keys went. */
|
|
25
|
+
sweep(now?: number): number
|
|
26
|
+
readonly size: number
|
|
27
|
+
/** Stops the sweep timer. */
|
|
28
|
+
close(): void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface RateLimitStoreOptions {
|
|
32
|
+
/** Keys kept before the least recently used go (default: 10 000). */
|
|
33
|
+
maxKeys?: number | undefined
|
|
34
|
+
/** Hits kept across all keys before the least recently used keys go (default: 1 000 000, about 8 MB). */
|
|
35
|
+
maxHits?: number | undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface Bucket {
|
|
39
|
+
readonly entries: Map<string, number[]>
|
|
40
|
+
readonly windowMs: number
|
|
41
|
+
hitCount: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const SWEEP_MS = 60_000
|
|
45
|
+
|
|
46
|
+
/** Throws when a `rateLimit` option cannot count anything, naming where it was set. */
|
|
47
|
+
export function assertRateLimit(limit: Pick<RateLimit, 'max' | 'windowMs'>, where: string): void {
|
|
48
|
+
if (!Number.isInteger(limit.max) || limit.max < 1)
|
|
49
|
+
throw new Error(`prunelle: rateLimit.max of ${where} is ${String(limit.max)}; give a whole number of requests, 1 or more.`)
|
|
50
|
+
if (!Number.isFinite(limit.windowMs) || limit.windowMs <= 0)
|
|
51
|
+
throw new Error(`prunelle: rateLimit.windowMs of ${where} is ${String(limit.windowMs)}; give the window in milliseconds, above 0.`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createRateLimitStore(options: RateLimitStoreOptions = {}): RateLimitStore {
|
|
55
|
+
const maxKeys = Math.max(1, options.maxKeys ?? 10_000)
|
|
56
|
+
const maxHits = Math.max(1, options.maxHits ?? 1_000_000)
|
|
57
|
+
// Each limiter owns a bounded LRU map so flooding one endpoint cannot evict keys from another.
|
|
58
|
+
const buckets: Bucket[] = []
|
|
59
|
+
let totalKeys = 0
|
|
60
|
+
let timer: ReturnType<typeof setInterval> | undefined
|
|
61
|
+
|
|
62
|
+
function secondsUntilFree(hits: readonly number[], max: number, windowMs: number, now: number): number {
|
|
63
|
+
return Math.max(1, Math.ceil((hits[hits.length - max]! + windowMs - now) / 1000))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function trim(bucket: Bucket, hits: number[], now: number): void {
|
|
67
|
+
const cutoff = now - bucket.windowMs
|
|
68
|
+
let stale = 0
|
|
69
|
+
while (stale < hits.length && hits[stale]! <= cutoff)
|
|
70
|
+
stale++
|
|
71
|
+
if (stale > 0) {
|
|
72
|
+
hits.splice(0, stale)
|
|
73
|
+
bucket.hitCount -= stale
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function sweep(now = Date.now()): number {
|
|
78
|
+
let removed = 0
|
|
79
|
+
for (const bucket of buckets) {
|
|
80
|
+
for (const [key, hits] of bucket.entries) {
|
|
81
|
+
trim(bucket, hits, now)
|
|
82
|
+
if (hits.length === 0) {
|
|
83
|
+
bucket.entries.delete(key)
|
|
84
|
+
totalKeys--
|
|
85
|
+
removed++
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return removed
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function evict(bucket: Bucket): void {
|
|
93
|
+
while (bucket.entries.size > maxKeys || bucket.hitCount > maxHits) {
|
|
94
|
+
const [key, hits] = bucket.entries.entries().next().value!
|
|
95
|
+
bucket.entries.delete(key)
|
|
96
|
+
bucket.hitCount -= hits.length
|
|
97
|
+
totalKeys--
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
limiter(limit) {
|
|
103
|
+
const { max, windowMs } = limit
|
|
104
|
+
const bucket: Bucket = { entries: new Map(), windowMs, hitCount: 0 }
|
|
105
|
+
buckets.push(bucket)
|
|
106
|
+
if (timer === undefined) {
|
|
107
|
+
timer = setInterval(sweep, SWEEP_MS)
|
|
108
|
+
timer.unref()
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
hit(key) {
|
|
112
|
+
const now = Date.now()
|
|
113
|
+
const existing = bucket.entries.get(key)
|
|
114
|
+
const hits = existing ?? []
|
|
115
|
+
if (existing !== undefined) {
|
|
116
|
+
trim(bucket, hits, now)
|
|
117
|
+
bucket.entries.delete(key)
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
totalKeys++
|
|
121
|
+
}
|
|
122
|
+
bucket.entries.set(key, hits)
|
|
123
|
+
if (hits.length >= max)
|
|
124
|
+
return secondsUntilFree(hits, max, windowMs, now)
|
|
125
|
+
hits.push(now)
|
|
126
|
+
bucket.hitCount++
|
|
127
|
+
evict(bucket)
|
|
128
|
+
return 0
|
|
129
|
+
},
|
|
130
|
+
peek(key) {
|
|
131
|
+
const hits = bucket.entries.get(key)
|
|
132
|
+
if (hits === undefined)
|
|
133
|
+
return 0
|
|
134
|
+
const now = Date.now()
|
|
135
|
+
trim(bucket, hits, now)
|
|
136
|
+
return hits.length >= max ? secondsUntilFree(hits, max, windowMs, now) : 0
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
sweep,
|
|
141
|
+
get size() {
|
|
142
|
+
return totalKeys
|
|
143
|
+
},
|
|
144
|
+
close() {
|
|
145
|
+
clearInterval(timer)
|
|
146
|
+
timer = undefined
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The 429 a limited route or action answers a client calling from script. */
|
|
152
|
+
export function tooManyRequests(retryAfter: number): Response {
|
|
153
|
+
return Response.json({ ok: false, status: 429, error: 'Too many requests' }, { status: 429, headers: { 'retry-after': String(retryAfter) } })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// One warning per limit declaration, so a test or a second server does not inherit another's silence.
|
|
157
|
+
const warnedMissingIp = new WeakSet<object>()
|
|
158
|
+
|
|
159
|
+
const BRACKETED_RE = /^\[([^\]]+)\](?::\d+)?$/
|
|
160
|
+
const IPV4_PORT_RE = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/
|
|
161
|
+
const MAPPED_IPV4_RE = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i
|
|
162
|
+
const HEXTET_RE = /^[\da-f]{1,4}$/i
|
|
163
|
+
|
|
164
|
+
/** The address a rate limit counts: an IPv4 address without its port or its `::ffff:` mapping, or the /64 network of an IPv6 address, any of whose 2^64 addresses one host may use. */
|
|
165
|
+
export function rateLimitAddress(ip: string): string {
|
|
166
|
+
const bare = BRACKETED_RE.exec(ip)?.[1] ?? IPV4_PORT_RE.exec(ip)?.[1] ?? ip
|
|
167
|
+
const addr = MAPPED_IPV4_RE.exec(bare)?.[1] ?? bare
|
|
168
|
+
const halves = addr.split('::')
|
|
169
|
+
if (!addr.includes(':') || halves.length > 2)
|
|
170
|
+
return addr
|
|
171
|
+
const head = halves[0] === '' ? [] : halves[0]!.split(':')
|
|
172
|
+
const tail = halves[1] ? halves[1].split(':') : []
|
|
173
|
+
// A dotted IPv4 ending holds the last two groups.
|
|
174
|
+
const tailGroups = tail.length + (tail.at(-1)?.includes('.') === true ? 1 : 0)
|
|
175
|
+
const zeros = halves.length === 2 ? 8 - head.length - tailGroups : 0
|
|
176
|
+
const groups = [...head, ...Array.from({ length: Math.max(0, zeros) }, () => '0'), ...tail].slice(0, 4)
|
|
177
|
+
if (groups.length < 4 || !groups.every(g => HEXTET_RE.test(g)))
|
|
178
|
+
return addr
|
|
179
|
+
return `${groups.map(g => Number.parseInt(g, 16).toString(16)).join(':')}::/64`
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The key `limit` counts `ctx` under: the limit's own `key`, else the client's network (`rateLimitAddress`), else one shared fallback that warns in production. */
|
|
183
|
+
export function rateLimitKey<Ctx extends { ip?: string | undefined }>(limit: RateLimit<Ctx>, ctx: Ctx): string {
|
|
184
|
+
const custom = limit.key?.(ctx)
|
|
185
|
+
if (custom !== undefined)
|
|
186
|
+
return `k:${custom}`
|
|
187
|
+
if (ctx.ip !== undefined && ctx.ip !== '')
|
|
188
|
+
return `ip:${rateLimitAddress(ctx.ip)}`
|
|
189
|
+
if (!warnedMissingIp.has(limit) && nodeEnv() === 'production') {
|
|
190
|
+
warnedMissingIp.add(limit)
|
|
191
|
+
console.warn('prunelle: rateLimit ran with no client IP (ctx.ip is undefined); configure trustProxy in prunelle.config.ts or pass remoteIp to app.handle() so callers do not share one fallback bucket.')
|
|
192
|
+
}
|
|
193
|
+
return 'ip:unknown'
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Counts `ctx` against `limiter` under `rateLimitKey`; returns 0 or the seconds to wait. */
|
|
197
|
+
export function hitFor<Ctx extends { ip?: string | undefined }>(limiter: RateLimiter, limit: RateLimit<Ctx>, ctx: Ctx): number {
|
|
198
|
+
return limiter.hit(rateLimitKey(limit, ctx))
|
|
199
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// A request with `x-pru-region` gets that region's HTML alone: no layouts, no document, and the page's other regions never build their children.
|
|
2
|
+
|
|
3
|
+
import type { Html } from '../jsx-runtime'
|
|
4
|
+
import type { RenderContext } from '../ssr/context'
|
|
5
|
+
|
|
6
|
+
import type { HtmlHeaders } from './document'
|
|
7
|
+
import type { LoadedPageModule } from './page'
|
|
8
|
+
|
|
9
|
+
import { getAppContext, runWithAppContext } from '../plugins/index'
|
|
10
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
11
|
+
import { ssrChild } from '../ssr/index'
|
|
12
|
+
import { finishRegion } from '../ssr/region'
|
|
13
|
+
import { mergeVaryValue } from './compress'
|
|
14
|
+
import { currentRequest, runInRequest } from './request-scope'
|
|
15
|
+
|
|
16
|
+
export const REGION_HEADER = 'x-pru-region'
|
|
17
|
+
|
|
18
|
+
export function hasRegionHeader(request: Request): boolean {
|
|
19
|
+
return request.headers.has(REGION_HEADER)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The header is the region's path, outermost first: `results/sets` is `sets` inside `results`.
|
|
23
|
+
function parseRegionPath(header: string | null): string[] | undefined {
|
|
24
|
+
if (header === null)
|
|
25
|
+
return undefined
|
|
26
|
+
const trimmed = header.trim()
|
|
27
|
+
if (trimmed === '')
|
|
28
|
+
return []
|
|
29
|
+
const parts = trimmed.split('/')
|
|
30
|
+
if (parts.some(name => name.trim() === ''))
|
|
31
|
+
return []
|
|
32
|
+
return parts.map(name => name.trim())
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function requestedRegion(request: Request): string | undefined {
|
|
36
|
+
const path = parseRegionPath(request.headers.get(REGION_HEADER))
|
|
37
|
+
return path !== undefined && path.length > 0 ? path.at(-1) : undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function invalidRegionResponse(request: Request): Response {
|
|
41
|
+
return new Response(request.method === 'HEAD' ? null : 'prunelle: invalid x-pru-region header: pass a non-empty region name or slash-separated path.', {
|
|
42
|
+
status: 400,
|
|
43
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'vary': REGION_HEADER },
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function withRegionVary(headers: Record<string, string>, hasRegions: boolean): Record<string, string> {
|
|
48
|
+
if (!hasRegions)
|
|
49
|
+
return headers
|
|
50
|
+
return { ...headers, vary: mergeVaryValue(headers.vary ?? headers.Vary, REGION_HEADER) }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
const TITLE_INNER_RE = /<title\b[^>]*>([\s\S]*?)<\/title>/i
|
|
55
|
+
|
|
56
|
+
/** Answers with the region's HTML and the page's title as it renders at this URL, in `x-pru-title` (percent-encoded), so the browser can retitle the tab without the head. */
|
|
57
|
+
export async function respondRegion(
|
|
58
|
+
request: Request,
|
|
59
|
+
mod: LoadedPageModule,
|
|
60
|
+
pageProps: Record<string, unknown>,
|
|
61
|
+
routePath: string,
|
|
62
|
+
htmlHeaders: HtmlHeaders,
|
|
63
|
+
resolveHead: (rctx: RenderContext) => Promise<{ head: string }>,
|
|
64
|
+
streamTimeout?: number,
|
|
65
|
+
onError?: (error: unknown) => void,
|
|
66
|
+
transformHtml?: (html: string) => Promise<string>,
|
|
67
|
+
): Promise<Response> {
|
|
68
|
+
const path = parseRegionPath(request.headers.get(REGION_HEADER))
|
|
69
|
+
if (path === undefined || path.length === 0)
|
|
70
|
+
return invalidRegionResponse(request)
|
|
71
|
+
const name = path.at(-1)!
|
|
72
|
+
const appCtx = getAppContext()
|
|
73
|
+
const reqScope = currentRequest()
|
|
74
|
+
const runInScope = <T>(fn: () => T): T => {
|
|
75
|
+
const inner = reqScope !== undefined ? () => runInRequest(reqScope, fn) : fn
|
|
76
|
+
return appCtx !== undefined ? runWithAppContext(appCtx, inner) : inner()
|
|
77
|
+
}
|
|
78
|
+
const rctx = createRenderContext(name, new Set(path.slice(0, -1)), reqScope?.ctx.consent, onError)
|
|
79
|
+
const html = await runWithRenderContext(rctx, async () => {
|
|
80
|
+
ssrChild(await mod.default!(pageProps) as Html)
|
|
81
|
+
return await finishRegion(rctx, { streamTimeout, onError, runInScope })
|
|
82
|
+
})
|
|
83
|
+
if (html === undefined) {
|
|
84
|
+
const message = `prunelle: the route ${routePath} does not render <Region name="${name}">: add it to the page, or point the link's data-pru-target at a region it has.`
|
|
85
|
+
return new Response(request.method === 'HEAD' ? null : message, {
|
|
86
|
+
status: 404,
|
|
87
|
+
headers: { 'content-type': 'text/plain; charset=utf-8', 'vary': REGION_HEADER },
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
const outHtml = request.method === 'HEAD' ? null : (transformHtml !== undefined ? await transformHtml(html) : html)
|
|
91
|
+
const title = TITLE_INNER_RE.exec((await resolveHead(rctx)).head)?.[1]
|
|
92
|
+
const headers: Record<string, string> = { ...htmlHeaders(rctx.hasIslands, false, true), 'vary': REGION_HEADER, [REGION_HEADER]: path.join('/') }
|
|
93
|
+
if (title !== undefined)
|
|
94
|
+
headers['x-pru-title'] = encodeURIComponent(title)
|
|
95
|
+
return new Response(outHtml, { status: 200, headers })
|
|
96
|
+
}
|