prunelle 0.8.0 → 0.10.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 +68 -51
- package/package.json +7 -2
- package/src/a11y/declaration.ts +10 -17
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +94 -136
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +23 -11
- package/src/build/island-promote.ts +42 -2
- package/src/build/islands.ts +63 -9
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +117 -1
- package/src/build/plugin-host.ts +13 -1
- package/src/build/prerender.ts +8 -3
- package/src/build/reach.ts +18 -4
- package/src/build/report.ts +1 -1
- package/src/build/resolve.ts +5 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +42 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +10 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +30 -105
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +49 -21
- package/src/cli/commands.ts +138 -16
- package/src/cli/docs.ts +21 -2
- package/src/cli/form-opaque-children.ts +40 -0
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +22 -16
- package/src/compiler/cacheability-private.ts +13 -3
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +322 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-rules.ts +72 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +61 -93
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/dom-attrs.ts +178 -22
- package/src/compiler/dom.ts +31 -44
- package/src/compiler/emit.ts +17 -6
- package/src/compiler/expr-context.ts +260 -207
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-body.ts +263 -21
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +324 -343
- package/src/compiler/signal-reads.ts +142 -29
- package/src/compiler/spread-handlers.ts +25 -13
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +165 -121
- package/src/compiler/ssr.ts +28 -441
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/host-check.ts +2 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +5 -2
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/attrs.ts +93 -25
- package/src/dom/extras.ts +91 -50
- package/src/dom/field-marks.ts +32 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +44 -18
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/loop.ts +259 -188
- package/src/dom/prefetch.ts +135 -0
- package/src/dom/regions.ts +515 -0
- package/src/dom/swap.ts +246 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +44 -41
- package/src/eco/index.ts +8 -5
- package/src/href.ts +31 -0
- package/src/index.ts +12 -5
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +12 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +128 -10
- package/src/reactivity/graph.ts +244 -41
- package/src/reactivity/hmr.ts +101 -0
- package/src/reactivity/index.ts +243 -239
- package/src/reactivity/resource.ts +129 -0
- package/src/reactivity/seed.ts +141 -0
- package/src/reactivity/selector.ts +85 -47
- package/src/reactivity/server-seed.ts +202 -0
- package/src/reactivity/store.ts +331 -97
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-protect.ts +3 -0
- package/src/server/action-registry.ts +11 -9
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +97 -0
- package/src/server/compress.ts +55 -18
- package/src/server/consent.ts +21 -5
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +77 -8
- package/src/server/cors.ts +98 -0
- package/src/server/csp-report.ts +90 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +41 -11
- package/src/server/http.ts +28 -11
- package/src/server/index.ts +122 -307
- package/src/server/loader.ts +2 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +66 -16
- package/src/server/plugin-route-shadow.ts +24 -0
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +49 -10
- package/src/server/region.ts +22 -2
- package/src/server/request-handler.ts +406 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +55 -8
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +53 -27
- package/src/server/router.ts +2 -1
- package/src/server/routing.ts +104 -45
- package/src/server/sanitize-html.ts +4 -2
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +16 -6
- package/src/server/served-file.ts +19 -14
- package/src/server/shared-store.ts +323 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +34 -12
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +50 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +174 -53
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +63 -58
- package/src/ssr/navigation.ts +161 -14
- package/src/ssr/region.ts +9 -3
- package/src/style.ts +12 -5
- package/src/test/browser.ts +53 -23
- package/src/test/build-reuse.ts +85 -0
- package/src/test/index.ts +51 -8
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/src/ts-plugin/diagnostics.ts +56 -18
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +4058 -2246
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
// The request path of the native server: static files, actions, prerendered pages, then plugin routes and compiled routes behind their middleware chains.
|
|
2
|
+
|
|
3
|
+
import type { ActionRegistry, RegisteredAction } from './action-registry'
|
|
4
|
+
import type { createAssets, ServedFile } from './assets'
|
|
5
|
+
import type { CompressionCache } from './compress'
|
|
6
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
7
|
+
import type { CookieStore } from './cookies'
|
|
8
|
+
import type { createHtmlHeaders } from './document'
|
|
9
|
+
import type { createFallbackPages, NotifyError } from './errors'
|
|
10
|
+
import type { createHealthHandler, createRequestIdResolver, PhaseTiming } from './health'
|
|
11
|
+
import type { DeniedInfo, Middleware, RequestContext } from './http'
|
|
12
|
+
import type { ServerPluginHost } from './plugin-host'
|
|
13
|
+
import type { RequestPath } from './request-path'
|
|
14
|
+
import type { CompiledRoute, compileRouteTable, createCompiledRouteRenderer } from './route-table'
|
|
15
|
+
import type { OriginRefusal, TrustProxy } from './security'
|
|
16
|
+
import type { createStreamTracker } from './stream'
|
|
17
|
+
import { maybeCompressResponse } from './compress'
|
|
18
|
+
import { withPluginHtmlCsp } from './document'
|
|
19
|
+
import { devErrorResponse } from './errors'
|
|
20
|
+
import { acceptsHtml, enforceRequestBodyLimit, getDeniedInfo, makeRequestContext, runChain, wantsJson } from './http'
|
|
21
|
+
import { createTiming, formatServerTiming, noteRoute, runTimedChain, withRequestId } from './health'
|
|
22
|
+
import { stripHeadBody } from './page'
|
|
23
|
+
import { allowedPluginMethodsHeader, takesEncoded } from './plugin-host'
|
|
24
|
+
import { hasRegionHeader } from './region'
|
|
25
|
+
import { decodeRequestPath, literalPath } from './request-path'
|
|
26
|
+
import { markUrlDerivedLocals } from './route-cache'
|
|
27
|
+
import { routeMethodHandler } from './route-table'
|
|
28
|
+
import { methodNotAllowed } from './routing'
|
|
29
|
+
import { hasActionErrorCookie, isRead } from './serve-handlers'
|
|
30
|
+
import { logOriginHint, verifyOrigin } from './security'
|
|
31
|
+
|
|
32
|
+
type Finish = (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
|
|
33
|
+
type SetIdleTimeout = ((seconds: number) => void) | undefined
|
|
34
|
+
type RenderDenied = ReturnType<typeof createFallbackPages>['renderDenied']
|
|
35
|
+
type RenderError = ReturnType<typeof createFallbackPages>['renderError']
|
|
36
|
+
type PluginMatch = NonNullable<ReturnType<typeof matchPluginRoute>>
|
|
37
|
+
type PluginRouteDef = NonNullable<ReturnType<PluginMatch['data']['get']>>
|
|
38
|
+
type Timing = ReturnType<typeof createTiming>
|
|
39
|
+
|
|
40
|
+
const isEventStream = (res: Response): boolean => (res.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream')
|
|
41
|
+
const isApiHandler = (mod: CompiledRoute['mod'], method: string): boolean => routeMethodHandler(mod, method) !== undefined || (method === 'HEAD' && typeof mod.GET === 'function')
|
|
42
|
+
const badRequest = (): Response => new Response('Bad Request', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
43
|
+
|
|
44
|
+
export function maybeRenderDenied(
|
|
45
|
+
res: Response,
|
|
46
|
+
request: Request,
|
|
47
|
+
url: URL,
|
|
48
|
+
ctx: RequestContext,
|
|
49
|
+
renderDenied: (denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>,
|
|
50
|
+
routeFile?: string,
|
|
51
|
+
isApi = false,
|
|
52
|
+
): Response | Promise<Response> {
|
|
53
|
+
if (isApi)
|
|
54
|
+
return res
|
|
55
|
+
const denied = getDeniedInfo(res)
|
|
56
|
+
if (denied === undefined || !acceptsHtml(request))
|
|
57
|
+
return res
|
|
58
|
+
return renderDenied(denied, url, request, ctx, routeFile)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function matchPluginRoute(pluginRouter: ServerPluginHost['router'], requestPath: RequestPath, effective: RequestPath) {
|
|
62
|
+
const rawMatch = effective !== requestPath ? takesEncoded(pluginRouter.match(requestPath), requestPath) : undefined
|
|
63
|
+
return rawMatch ?? takesEncoded(pluginRouter.match(effective), effective)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function matchStaticOrPublic(
|
|
67
|
+
request: Request,
|
|
68
|
+
staticPath: string | undefined,
|
|
69
|
+
getRequestPath: () => RequestPath,
|
|
70
|
+
assetMap: ReadonlyMap<string, ServedFile>,
|
|
71
|
+
publicMap: ReadonlyMap<string, ServedFile>,
|
|
72
|
+
pluginRouter: ServerPluginHost['router'],
|
|
73
|
+
): ServedFile | undefined {
|
|
74
|
+
if (staticPath === undefined)
|
|
75
|
+
return undefined
|
|
76
|
+
const asset = assetMap.get(staticPath)
|
|
77
|
+
if (asset !== undefined)
|
|
78
|
+
return asset
|
|
79
|
+
if (publicMap.size === 0)
|
|
80
|
+
return undefined
|
|
81
|
+
const pub = publicMap.get(staticPath)
|
|
82
|
+
if (pub === undefined)
|
|
83
|
+
return undefined
|
|
84
|
+
const matchedPlugin = pluginRouter.match(getRequestPath())
|
|
85
|
+
const reqMethod = request.method.toUpperCase()
|
|
86
|
+
const shadowedByPlugin = matchedPlugin !== undefined
|
|
87
|
+
&& (matchedPlugin.data.has(reqMethod) || (reqMethod === 'HEAD' && matchedPlugin.data.has('GET')) || matchedPlugin.data.has('ALL'))
|
|
88
|
+
return shadowedByPlugin ? undefined : pub
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function createRequestGuards(maxRequestBodySize: number, finish: Finish) {
|
|
92
|
+
const refuseCrossSite = (request: Request, check: OriginRefusal, cookieStore?: CookieStore, requestId?: string): Response => {
|
|
93
|
+
logOriginHint(check.hint)
|
|
94
|
+
return finish(Response.json({ ok: false, status: 403, error: check.reason }, { status: 403 }), request, cookieStore, requestId)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const checkBodyLimit = async (request: Request, bodyLimited: boolean, cookieStore?: CookieStore, requestId?: string): Promise<Request | Response> => {
|
|
98
|
+
if (bodyLimited)
|
|
99
|
+
return request
|
|
100
|
+
const bounded = await enforceRequestBodyLimit(request, maxRequestBodySize)
|
|
101
|
+
if (bounded.ok)
|
|
102
|
+
return bounded.request
|
|
103
|
+
const status = bounded.aborted ? 400 : 413
|
|
104
|
+
const message = bounded.aborted ? 'Bad Request' : 'Payload Too Large'
|
|
105
|
+
return finish(wantsJson(request)
|
|
106
|
+
? Response.json({ ok: false, status, error: message }, { status })
|
|
107
|
+
: new Response(message, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }), request, cookieStore, requestId)
|
|
108
|
+
}
|
|
109
|
+
return { refuseCrossSite, checkBodyLimit }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface RequestHandlerDeps {
|
|
113
|
+
isDev: boolean
|
|
114
|
+
healthPath: string
|
|
115
|
+
healthHandler: ReturnType<typeof createHealthHandler>
|
|
116
|
+
resolveRequestId: ReturnType<typeof createRequestIdResolver>
|
|
117
|
+
finish: Finish
|
|
118
|
+
withHsts: (res: Response, request: Request) => Response
|
|
119
|
+
serverError: () => Response
|
|
120
|
+
assetMap: ReadonlyMap<string, ServedFile>
|
|
121
|
+
publicMap: ReadonlyMap<string, ServedFile>
|
|
122
|
+
serveFile: ReturnType<typeof createAssets>['serveFile']
|
|
123
|
+
pluginHost: ServerPluginHost
|
|
124
|
+
pluginMiddlewaresFor: (effectiveScopedPath: string, rawScopedPath: string) => readonly Middleware[]
|
|
125
|
+
actions: ActionRegistry
|
|
126
|
+
dispatchAction: (
|
|
127
|
+
registeredAction: RegisteredAction,
|
|
128
|
+
request: Request,
|
|
129
|
+
url: URL,
|
|
130
|
+
rawPathname: string,
|
|
131
|
+
remoteIp: string | undefined,
|
|
132
|
+
bodyLimited: boolean,
|
|
133
|
+
requestId: string,
|
|
134
|
+
existing?: { ctx: RequestContext, cookieStore: CookieStore },
|
|
135
|
+
) => Promise<Response>
|
|
136
|
+
fastPrerenderedMap: ReadonlyMap<string, ServedFile>
|
|
137
|
+
fastStaticPages: ReturnType<typeof compileRouteTable>['fastStaticPages']
|
|
138
|
+
router: ReturnType<typeof compileRouteTable>['router']
|
|
139
|
+
trustProxy: TrustProxy
|
|
140
|
+
httpsSite: boolean
|
|
141
|
+
consent: NormalizedConsentConfig | undefined
|
|
142
|
+
trustedOrigins: Set<string> | undefined
|
|
143
|
+
refuseCrossSite: ReturnType<typeof createRequestGuards>['refuseCrossSite']
|
|
144
|
+
checkBodyLimit: ReturnType<typeof createRequestGuards>['checkBodyLimit']
|
|
145
|
+
streams: ReturnType<typeof createStreamTracker>
|
|
146
|
+
htmlHeaders: ReturnType<typeof createHtmlHeaders>
|
|
147
|
+
compressCache: CompressionCache | undefined
|
|
148
|
+
notifyError: NotifyError
|
|
149
|
+
renderError: RenderError
|
|
150
|
+
renderDenied: RenderDenied
|
|
151
|
+
renderNotFound: (cookieStore: CookieStore, url: URL, request: Request, ctx: RequestContext, effective: RequestPath, rawScopedPath: string, timing?: PhaseTiming) => Promise<Response>
|
|
152
|
+
renderCompiledRoute: ReturnType<typeof createCompiledRouteRenderer>
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// The three ways a request that is neither a file nor an action ends: a plugin route, a plugin route's 405, and a compiled route.
|
|
156
|
+
function createRouteServers(deps: RequestHandlerDeps) {
|
|
157
|
+
const {
|
|
158
|
+
finish, pluginHost, pluginMiddlewaresFor, actions, refuseCrossSite, checkBodyLimit, streams, htmlHeaders, compressCache, notifyError, renderError,
|
|
159
|
+
renderDenied, renderCompiledRoute,
|
|
160
|
+
} = deps
|
|
161
|
+
|
|
162
|
+
// Custom plugin routes run behind path-matched plugin middlewares so ctx.locals is available without cross-scope leaks.
|
|
163
|
+
async function servePluginRoute(
|
|
164
|
+
request: Request,
|
|
165
|
+
url: URL,
|
|
166
|
+
ctx: RequestContext,
|
|
167
|
+
cookieStore: CookieStore,
|
|
168
|
+
pluginMatch: PluginMatch,
|
|
169
|
+
routeDef: PluginRouteDef,
|
|
170
|
+
isHeadFallback: boolean,
|
|
171
|
+
effectiveScopedPath: string,
|
|
172
|
+
scopedPath: string,
|
|
173
|
+
bodyLimited: boolean,
|
|
174
|
+
setIdleTimeout: SetIdleTimeout,
|
|
175
|
+
requestId: string,
|
|
176
|
+
timing: Timing,
|
|
177
|
+
): Promise<Response> {
|
|
178
|
+
if (routeDef.csrf) {
|
|
179
|
+
const originCheck = verifyOrigin(request, routeDef.trustedOrigins, routeDef.trustProxy, url)
|
|
180
|
+
if (!originCheck.ok)
|
|
181
|
+
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
182
|
+
}
|
|
183
|
+
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
184
|
+
if (checked instanceof Response)
|
|
185
|
+
return checked
|
|
186
|
+
ctx.request = checked
|
|
187
|
+
ctx.params = pluginMatch.params
|
|
188
|
+
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
189
|
+
try {
|
|
190
|
+
let res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => routeDef.handler(ctx), timing, runChain))
|
|
191
|
+
if (isHeadFallback)
|
|
192
|
+
res = stripHeadBody(res)
|
|
193
|
+
else if (isEventStream(res))
|
|
194
|
+
res = streams.track(res, setIdleTimeout)
|
|
195
|
+
return finish(await maybeCompressResponse(await withPluginHtmlCsp(res, htmlHeaders), ctx.request, compressCache), ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
notifyError(error, ctx.request, 'plugin', requestId)
|
|
199
|
+
return renderError(error, cookieStore, ctx.url, ctx.request, ctx)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// A plugin route matched the path but none of its methods the request's: the 405 still runs the plugin middlewares.
|
|
204
|
+
async function pluginMethodNotAllowed(
|
|
205
|
+
request: Request,
|
|
206
|
+
ctx: RequestContext,
|
|
207
|
+
cookieStore: CookieStore,
|
|
208
|
+
pluginMatch: PluginMatch,
|
|
209
|
+
effectiveScopedPath: string,
|
|
210
|
+
scopedPath: string,
|
|
211
|
+
requestId: string,
|
|
212
|
+
timing: Timing,
|
|
213
|
+
): Promise<Response> {
|
|
214
|
+
ctx.params = pluginMatch.params
|
|
215
|
+
const allow = allowedPluginMethodsHeader(pluginMatch.data)
|
|
216
|
+
const pluginMws = pluginMiddlewaresFor(effectiveScopedPath, scopedPath)
|
|
217
|
+
try {
|
|
218
|
+
const res = await actions.run(ctx, () => runTimedChain(ctx, pluginMws, () => methodNotAllowed(allow), timing, runChain))
|
|
219
|
+
return finish(res, request, cookieStore, requestId, formatServerTiming(timing))
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
notifyError(error, request, 'plugin', requestId)
|
|
223
|
+
return renderError(error, cookieStore, ctx.url, request, ctx)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function serveCompiledRoute(
|
|
228
|
+
ctx: RequestContext,
|
|
229
|
+
cookieStore: CookieStore,
|
|
230
|
+
route: CompiledRoute,
|
|
231
|
+
method: string,
|
|
232
|
+
effectiveScopedPath: string,
|
|
233
|
+
scopedPath: string,
|
|
234
|
+
staticPath: string | undefined,
|
|
235
|
+
setIdleTimeout: SetIdleTimeout,
|
|
236
|
+
requestId: string,
|
|
237
|
+
timing: Timing,
|
|
238
|
+
): Promise<Response> {
|
|
239
|
+
const routeMiddlewares = pluginHost.hasPathScopedMiddlewares && (route.dynamic || effectiveScopedPath !== scopedPath)
|
|
240
|
+
? [...pluginMiddlewaresFor(effectiveScopedPath, scopedPath), ...route.dirMiddlewares]
|
|
241
|
+
: route.middlewares
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
const rawRes = await actions.run(ctx, () => runTimedChain(ctx, routeMiddlewares, () => renderCompiledRoute(route, ctx, cookieStore, setIdleTimeout, staticPath, timing, routeMiddlewares), timing, runChain))
|
|
245
|
+
const handledRes = await maybeRenderDenied(rawRes, ctx.request, ctx.url, ctx, renderDenied, route.entry.file, isApiHandler(route.mod, method))
|
|
246
|
+
const res = isEventStream(handledRes) ? streams.track(handledRes, setIdleTimeout) : handledRes
|
|
247
|
+
// Compress uncompressed API/middleware responses after the middleware chain unwinds.
|
|
248
|
+
const finalRes = res.headers.has('content-encoding') ? res : await maybeCompressResponse(res, ctx.request, compressCache)
|
|
249
|
+
return finish(finalRes, ctx.request, cookieStore, requestId, formatServerTiming(timing))
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
notifyError(error, ctx.request, 'route', requestId)
|
|
253
|
+
return renderError(error, cookieStore, ctx.url, ctx.request, ctx, route.entry.file)
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return { servePluginRoute, pluginMethodNotAllowed, serveCompiledRoute }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The function every request goes through. Everything it needs is read once from `deps`: a request allocates only what its own work needs. */
|
|
261
|
+
export function createRequestHandler(deps: RequestHandlerDeps) {
|
|
262
|
+
const {
|
|
263
|
+
isDev, healthPath, healthHandler, resolveRequestId, finish, withHsts, serverError, assetMap, publicMap, serveFile, pluginHost, actions, dispatchAction,
|
|
264
|
+
fastPrerenderedMap, fastStaticPages, router, trustProxy, httpsSite, consent, trustedOrigins, refuseCrossSite, checkBodyLimit, notifyError, renderNotFound,
|
|
265
|
+
} = deps
|
|
266
|
+
const pluginRouter = pluginHost.router
|
|
267
|
+
const { servePluginRoute, pluginMethodNotAllowed, serveCompiledRoute } = createRouteServers(deps)
|
|
268
|
+
|
|
269
|
+
const isPlainFastRead = (request: Request): boolean => !hasActionErrorCookie(request) && !hasRegionHeader(request)
|
|
270
|
+
|
|
271
|
+
const matchFastRoute = (
|
|
272
|
+
request: Request,
|
|
273
|
+
staticPath: string,
|
|
274
|
+
url: URL,
|
|
275
|
+
remoteIp: string | undefined,
|
|
276
|
+
requestId: string,
|
|
277
|
+
): Promise<Response> | Response | undefined => {
|
|
278
|
+
const pre = fastPrerenderedMap.get(staticPath)
|
|
279
|
+
if (pre !== undefined && isPlainFastRead(request))
|
|
280
|
+
return serveFile(request, pre).then(res => withRequestId(res, requestId))
|
|
281
|
+
const fast = fastStaticPages.get(staticPath)
|
|
282
|
+
if (fast !== undefined && isPlainFastRead(request)) {
|
|
283
|
+
noteRoute(request, staticPath)
|
|
284
|
+
return fast(request, remoteIp, url, requestId)
|
|
285
|
+
}
|
|
286
|
+
return undefined
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// `bodyLimited` is set under `serve()`, where Bun.serve already enforces maxRequestBodySize on every body, chunked ones included.
|
|
290
|
+
return async function handleInternal(request: Request, remoteIp?: string, setIdleTimeout?: (seconds: number) => void, bodyLimited = false): Promise<Response> {
|
|
291
|
+
const requestId = resolveRequestId(request)
|
|
292
|
+
try {
|
|
293
|
+
const url = new URL(request.url)
|
|
294
|
+
const rawPathname = url.pathname
|
|
295
|
+
// Avoid allocating a `DecodedPath` wrapper when the pathname has no percent-escapes and resolves on a fast path.
|
|
296
|
+
let decodedPath: RequestPath | undefined
|
|
297
|
+
let staticPath: string | undefined
|
|
298
|
+
if (rawPathname.includes('%')) {
|
|
299
|
+
decodedPath = decodeRequestPath(rawPathname)
|
|
300
|
+
if (decodedPath === undefined)
|
|
301
|
+
return finish(badRequest(), request, undefined, requestId)
|
|
302
|
+
staticPath = decodedPath.staticPath
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
staticPath = rawPathname
|
|
306
|
+
}
|
|
307
|
+
if (staticPath === healthPath)
|
|
308
|
+
return healthHandler(request, requestId)
|
|
309
|
+
const getRequestPath = (): RequestPath => (decodedPath ??= literalPath(rawPathname))
|
|
310
|
+
const read = isRead(request)
|
|
311
|
+
|
|
312
|
+
// 1. Static client assets, then public/ files (explicit plugin routes take precedence over public/ files)
|
|
313
|
+
if (read) {
|
|
314
|
+
const staticFile = matchStaticOrPublic(request, staticPath, getRequestPath, assetMap, publicMap, pluginRouter)
|
|
315
|
+
if (staticFile !== undefined)
|
|
316
|
+
return withRequestId(await serveFile(request, staticFile), requestId)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// 2. Server actions (POST /_pru/action/<id>; non-POST runs applicable middlewares before 405)
|
|
320
|
+
const registeredAction = staticPath !== undefined ? actions.byUrl(staticPath) : undefined
|
|
321
|
+
if (registeredAction !== undefined)
|
|
322
|
+
return await dispatchAction(registeredAction, request, url, rawPathname, remoteIp, bodyLimited, requestId)
|
|
323
|
+
|
|
324
|
+
// 3. Prerendered static HTML, then 4. the zero-overhead static route path
|
|
325
|
+
if (read && staticPath !== undefined) {
|
|
326
|
+
const fastRes = matchFastRoute(request, staticPath, url, remoteIp, requestId)
|
|
327
|
+
if (fastRes !== undefined)
|
|
328
|
+
return fastRes
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// 5. Full Router + Plugin Rewrites + Plugin Routes + Middleware + Streaming/Head/Error pipeline
|
|
332
|
+
const requestPath = getRequestPath()
|
|
333
|
+
const { scopedPath } = requestPath
|
|
334
|
+
const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite, remoteIp, url, consent, requestId })
|
|
335
|
+
const timing = createTiming(isDev, request)
|
|
336
|
+
|
|
337
|
+
// Apply plugin URL rewrites (e.g. @prunellejs/i18n stripping /fr prefix and setting ctx.locals.locale)
|
|
338
|
+
let effectivePath = rawPathname
|
|
339
|
+
for (const rewrite of pluginHost.rewrites) {
|
|
340
|
+
const nextPath = rewrite(effectivePath, ctx)
|
|
341
|
+
if (nextPath !== undefined)
|
|
342
|
+
effectivePath = nextPath
|
|
343
|
+
}
|
|
344
|
+
if (pluginHost.rewrites.length > 0)
|
|
345
|
+
markUrlDerivedLocals(ctx.locals)
|
|
346
|
+
let effective = requestPath
|
|
347
|
+
if (effectivePath !== rawPathname) {
|
|
348
|
+
const rewritten = decodeRequestPath(effectivePath)
|
|
349
|
+
if (rewritten === undefined)
|
|
350
|
+
return finish(badRequest(), request, cookieStore, requestId)
|
|
351
|
+
effective = rewritten
|
|
352
|
+
const rewrittenAction = rewritten.staticPath !== undefined ? actions.byUrl(rewritten.staticPath) : undefined
|
|
353
|
+
if (rewrittenAction !== undefined)
|
|
354
|
+
return await dispatchAction(rewrittenAction, request, url, effectivePath, remoteIp, bodyLimited, requestId, { ctx, cookieStore })
|
|
355
|
+
}
|
|
356
|
+
const { scopedPath: effectiveScopedPath, staticPath: effectiveStaticPath } = effective
|
|
357
|
+
|
|
358
|
+
const method = request.method.toUpperCase()
|
|
359
|
+
const pluginMatch = matchPluginRoute(pluginRouter, requestPath, effective)
|
|
360
|
+
const directPluginDef = pluginMatch?.data.get(method) ?? pluginMatch?.data.get('ALL')
|
|
361
|
+
const headFallbackPluginDef = directPluginDef === undefined && method === 'HEAD' ? pluginMatch?.data.get('GET') : undefined
|
|
362
|
+
const routeDef = directPluginDef ?? headFallbackPluginDef
|
|
363
|
+
if (pluginMatch !== undefined && routeDef !== undefined) {
|
|
364
|
+
noteRoute(request, routeDef.path)
|
|
365
|
+
return await servePluginRoute(request, url, ctx, cookieStore, pluginMatch, routeDef, headFallbackPluginDef !== undefined, effectiveScopedPath, scopedPath, bodyLimited, setIdleTimeout, requestId, timing)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Localized/rewritten public/ links (e.g. /fr/logo.png -> /logo.png)
|
|
369
|
+
if (read && effectivePath !== rawPathname && effectiveStaticPath !== undefined) {
|
|
370
|
+
const pub = publicMap.get(effectiveStaticPath)
|
|
371
|
+
if (pub !== undefined)
|
|
372
|
+
return withRequestId(await serveFile(request, pub), requestId)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const matched = router.match(effective)
|
|
376
|
+
// Before any middleware: an unmatched path, a 405 and a route without a handler for the method are checked too, unless the route opts out.
|
|
377
|
+
if (matched?.data.mod.csrf !== false) {
|
|
378
|
+
const originCheck = verifyOrigin(request, trustedOrigins, trustProxy, url)
|
|
379
|
+
if (!originCheck.ok)
|
|
380
|
+
return refuseCrossSite(request, originCheck, cookieStore, requestId)
|
|
381
|
+
}
|
|
382
|
+
if (matched === undefined) {
|
|
383
|
+
if (pluginMatch !== undefined)
|
|
384
|
+
return await pluginMethodNotAllowed(request, ctx, cookieStore, pluginMatch, effectiveScopedPath, scopedPath, requestId, timing)
|
|
385
|
+
return renderNotFound(cookieStore, ctx.url, request, ctx, effective, scopedPath, timing)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
ctx.params = matched.params
|
|
389
|
+
const route = matched.data
|
|
390
|
+
|
|
391
|
+
// Body limit for file-based API routes; the origin was checked above.
|
|
392
|
+
if (routeMethodHandler(route.mod, method) !== undefined) {
|
|
393
|
+
const checked = await checkBodyLimit(request, bodyLimited, cookieStore, requestId)
|
|
394
|
+
if (checked instanceof Response)
|
|
395
|
+
return checked
|
|
396
|
+
ctx.request = checked
|
|
397
|
+
}
|
|
398
|
+
noteRoute(request, route.entry.path)
|
|
399
|
+
return await serveCompiledRoute(ctx, cookieStore, route, method, effectiveScopedPath, scopedPath, staticPath, setIdleTimeout, requestId, timing)
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
notifyError(error, request, 'route', requestId)
|
|
403
|
+
return withHsts(withRequestId(isDev ? devErrorResponse(error, request) : serverError(), requestId), request)
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// What a server tells about each request it answered: the access log `log.access` prints and the `onRequestEnd` hooks plugins register. With neither, no handler is wrapped and nothing is measured.
|
|
2
|
+
|
|
3
|
+
import type { LogConfig, RequestPhase, RequestRecord, ServerErrorInfo } from '../plugins/types'
|
|
4
|
+
import type { PhaseTiming, RequestPhaseName } from './health'
|
|
5
|
+
import { observeTiming } from './health'
|
|
6
|
+
|
|
7
|
+
export interface RequestHook {
|
|
8
|
+
owner: string
|
|
9
|
+
hook: (record: RequestRecord) => void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Wraps a handler so the hooks hear each request it answers. */
|
|
13
|
+
export type ObserveHandler = <A extends unknown[]>(handler: (request: Request, ...args: A) => Response | Promise<Response>) => (request: Request, ...args: A) => Promise<Response>
|
|
14
|
+
|
|
15
|
+
// The order they begin in.
|
|
16
|
+
const PHASES: readonly RequestPhaseName[] = ['middleware', 'load', 'render', 'stream']
|
|
17
|
+
|
|
18
|
+
function phasesOf(timing: PhaseTiming): RequestPhase[] {
|
|
19
|
+
const phases: RequestPhase[] = []
|
|
20
|
+
for (const name of PHASES) {
|
|
21
|
+
const start = timing.starts?.[name]
|
|
22
|
+
const duration = timing[name]
|
|
23
|
+
if (start !== undefined && duration !== undefined)
|
|
24
|
+
phases.push({ name, start: performance.timeOrigin + start, duration })
|
|
25
|
+
}
|
|
26
|
+
return phases
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const pathOf = (url: string): string => URL.parse(url)?.pathname ?? url
|
|
30
|
+
|
|
31
|
+
/** The access log: the query is left out, as it can carry a token or an address. */
|
|
32
|
+
export function accessLog(format: LogConfig['format']): (record: RequestRecord) => void {
|
|
33
|
+
if (format === 'json') {
|
|
34
|
+
return ({ request, requestId, status, start, duration }) => console.log(JSON.stringify({
|
|
35
|
+
time: new Date(start).toISOString(),
|
|
36
|
+
level: 'info',
|
|
37
|
+
msg: 'request',
|
|
38
|
+
method: request.method,
|
|
39
|
+
path: pathOf(request.url),
|
|
40
|
+
status,
|
|
41
|
+
duration: Math.round(duration * 100) / 100,
|
|
42
|
+
requestId,
|
|
43
|
+
}))
|
|
44
|
+
}
|
|
45
|
+
return ({ request, requestId, status, duration }) =>
|
|
46
|
+
console.log(`${request.method} ${pathOf(request.url)} ${status} ${duration.toFixed(1)}ms${requestId !== undefined ? ` [${requestId}]` : ''}`)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** An unhandled error as one JSON line, for `log.format: 'json'`. */
|
|
50
|
+
export function errorJsonLine(error: unknown, request: Request, source: ServerErrorInfo['source'], requestId: string | undefined): string {
|
|
51
|
+
return JSON.stringify({
|
|
52
|
+
time: new Date().toISOString(),
|
|
53
|
+
level: 'error',
|
|
54
|
+
msg: `unhandled error in ${source}`,
|
|
55
|
+
source,
|
|
56
|
+
method: request.method,
|
|
57
|
+
path: pathOf(request.url),
|
|
58
|
+
requestId,
|
|
59
|
+
error: error instanceof Error ? error.message : String(error),
|
|
60
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The wrapper that measures each request for the access log and the plugins' `onRequestEnd` hooks, or nothing when none listens. */
|
|
65
|
+
export function createRequestObserver(log: LogConfig | undefined, pluginHooks: readonly RequestHook[], isDev: boolean): ObserveHandler | undefined {
|
|
66
|
+
const hooks = log?.access === true ? [{ owner: 'prunelle.config.ts', hook: accessLog(log.format) }, ...pluginHooks] : pluginHooks
|
|
67
|
+
if (hooks.length === 0)
|
|
68
|
+
return undefined
|
|
69
|
+
const tell = (record: RequestRecord): void => {
|
|
70
|
+
for (const { owner, hook } of hooks) {
|
|
71
|
+
try {
|
|
72
|
+
hook(record)
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
console.error(`prunelle: the onRequestEnd hook of ${owner} threw; the other hooks still run.`, error)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return handler => async (request, ...args) => {
|
|
80
|
+
const start = performance.now()
|
|
81
|
+
const timing = observeTiming(request, isDev)
|
|
82
|
+
let status = 500
|
|
83
|
+
let requestId: string | null = null
|
|
84
|
+
try {
|
|
85
|
+
const res = await handler(request, ...args)
|
|
86
|
+
status = res.status
|
|
87
|
+
requestId = res.headers.get('x-request-id')
|
|
88
|
+
return res
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
tell({ request, requestId: requestId ?? undefined, status, start: performance.timeOrigin + start, duration: performance.now() - start, phases: phasesOf(timing), route: timing.route })
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -14,6 +14,8 @@ export interface RouteCacheSpec {
|
|
|
14
14
|
swrMs: number
|
|
15
15
|
/** Normalized `Cache-Control` header value (`public, s-maxage=..., stale-while-revalidate=...`). */
|
|
16
16
|
cacheControl: string
|
|
17
|
+
/** Names `invalidateCache({ tag })` drops the route's renders by. */
|
|
18
|
+
tags?: readonly string[] | undefined
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export interface RouteCacheOptions {
|
|
@@ -108,22 +110,24 @@ export function formatCacheDuration(ms: number): string {
|
|
|
108
110
|
export const GATED_ROUTE_CACHE_CONTROL = 'private, no-cache'
|
|
109
111
|
|
|
110
112
|
/** Builds a normalized `RouteCacheSpec` with its `Cache-Control` header value. */
|
|
111
|
-
export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs): RouteCacheSpec {
|
|
113
|
+
export function buildRouteCacheSpec(maxAgeMs: number, swrMs: number = maxAgeMs, tags: readonly string[] = []): RouteCacheSpec {
|
|
112
114
|
const maxAgeSec = Math.max(1, Math.round(maxAgeMs / 1000))
|
|
113
115
|
const swrSec = swrMs === 0 ? 0 : Math.max(1, Math.round(swrMs / 1000))
|
|
114
116
|
return {
|
|
115
117
|
maxAgeMs,
|
|
116
118
|
swrMs,
|
|
117
119
|
cacheControl: `public, s-maxage=${maxAgeSec}, stale-while-revalidate=${swrSec}`,
|
|
120
|
+
...(tags.length > 0 ? { tags } : {}),
|
|
118
121
|
}
|
|
119
122
|
}
|
|
120
123
|
|
|
121
124
|
/** Formats a `RouteCacheSpec` concisely for `prunelle inspect`. */
|
|
122
125
|
export function formatCacheSpec(spec: RouteCacheSpec): string {
|
|
126
|
+
const tags = spec.tags === undefined ? '' : `,tags=${spec.tags.join('+')}`
|
|
123
127
|
const maxAge = formatCacheDuration(spec.maxAgeMs)
|
|
124
128
|
if (spec.swrMs === spec.maxAgeMs)
|
|
125
|
-
return maxAge
|
|
126
|
-
return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}`
|
|
129
|
+
return `${maxAge}${tags}`
|
|
130
|
+
return `${maxAge},swr=${formatCacheDuration(spec.swrMs)}${tags}`
|
|
127
131
|
}
|
|
128
132
|
|
|
129
133
|
/** Returns a copy of `headers` with `cache-control` set to `cacheControl`. */
|
|
@@ -147,6 +151,13 @@ export function routeCacheKey(url: URL): string {
|
|
|
147
151
|
return `${url.host}${url.pathname}${kept.length === 0 ? '' : `?${kept.join('&')}`}`
|
|
148
152
|
}
|
|
149
153
|
|
|
154
|
+
// A key is the host, then the path from its first "/", then the query.
|
|
155
|
+
function pathnameOfKey(key: string): string {
|
|
156
|
+
const slash = key.indexOf('/')
|
|
157
|
+
const query = key.indexOf('?', slash)
|
|
158
|
+
return key.slice(slash, query === -1 ? undefined : query)
|
|
159
|
+
}
|
|
160
|
+
|
|
150
161
|
function weakEtagOf(html: string): string {
|
|
151
162
|
return `W/"${Bun.hash(html).toString(36)}"`
|
|
152
163
|
}
|
|
@@ -181,6 +192,7 @@ export class RouteCache {
|
|
|
181
192
|
readonly #maxBytes: number
|
|
182
193
|
readonly #failureCooldownMs: number
|
|
183
194
|
#totalBytes = 0
|
|
195
|
+
#generation = 0
|
|
184
196
|
|
|
185
197
|
constructor(options?: RouteCacheOptions) {
|
|
186
198
|
const entries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES
|
|
@@ -199,6 +211,26 @@ export class RouteCache {
|
|
|
199
211
|
return this.#totalBytes
|
|
200
212
|
}
|
|
201
213
|
|
|
214
|
+
/** Moves on each `invalidate`: a render begun under an older generation may have read what it dropped, so it is not stored. */
|
|
215
|
+
get generation(): number {
|
|
216
|
+
return this.#generation
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Drops the entries whose path and route tags `matches`, and lets no request wait on a render begun before; returns how many entries it dropped. */
|
|
220
|
+
invalidate(matches: (pathname: string, tags: readonly string[]) => boolean): number {
|
|
221
|
+
this.#generation++
|
|
222
|
+
let dropped = 0
|
|
223
|
+
for (const [key, entry] of this.#map) {
|
|
224
|
+
if (matches(pathnameOfKey(key), entry.spec.tags ?? [])) {
|
|
225
|
+
this.delete(key)
|
|
226
|
+
dropped++
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
this.#inflight.clear()
|
|
230
|
+
this.#failedUntil.clear()
|
|
231
|
+
return dropped
|
|
232
|
+
}
|
|
233
|
+
|
|
202
234
|
hasInflight(key: string): boolean {
|
|
203
235
|
return this.#revalidating.has(key) || this.#inflight.has(key)
|
|
204
236
|
}
|
|
@@ -427,21 +459,24 @@ export class RouteCache {
|
|
|
427
459
|
}
|
|
428
460
|
}
|
|
429
461
|
|
|
430
|
-
/** Looks up a cached hit and schedules background revalidation when stale. */
|
|
462
|
+
/** Looks up a cached hit and schedules background revalidation when stale (or returns undefined on stale when `revalidate` is omitted, forcing synchronous revalidation). */
|
|
431
463
|
export function serveCachedHit(
|
|
432
464
|
routeCache: RouteCache,
|
|
433
465
|
key: string,
|
|
434
466
|
request: Request,
|
|
435
467
|
requestId: string,
|
|
436
468
|
compressCache: CompressionCache | undefined,
|
|
437
|
-
revalidate: () => Promise<void
|
|
469
|
+
revalidate: (() => Promise<void>) | undefined,
|
|
438
470
|
onError: (error: unknown) => void,
|
|
439
471
|
): Response | undefined {
|
|
440
472
|
const hit = routeCache.lookup(key)
|
|
441
473
|
if (hit === undefined)
|
|
442
474
|
return undefined
|
|
443
|
-
if (hit.status === 'stale')
|
|
475
|
+
if (hit.status === 'stale') {
|
|
476
|
+
if (revalidate === undefined)
|
|
477
|
+
return undefined
|
|
444
478
|
routeCache.revalidate(key, revalidate, onError)
|
|
479
|
+
}
|
|
445
480
|
return routeCache.respondHit(hit.entry, request, requestId, compressCache)
|
|
446
481
|
}
|
|
447
482
|
|
|
@@ -485,17 +520,29 @@ function wrapTrackedHeaders(headers: Headers, mark: () => void): Headers {
|
|
|
485
520
|
})
|
|
486
521
|
}
|
|
487
522
|
|
|
523
|
+
const urlDerivedLocals = new WeakMap<object, ReadonlySet<PropertyKey>>()
|
|
524
|
+
|
|
525
|
+
/** Records the `ctx.locals` keys plugin rewrites set (`locale` from `/fr/...`): a rewrite reads the URL, which keys the cache, so reading them later is not private. */
|
|
526
|
+
export function markUrlDerivedLocals(locals: object): void {
|
|
527
|
+
urlDerivedLocals.set(locals, new Set(Reflect.ownKeys(locals)))
|
|
528
|
+
}
|
|
529
|
+
|
|
488
530
|
/** Tracks runtime reads of per-visitor request data on a cached route so private HTML is never stored or shared. */
|
|
489
531
|
export function trackPrivateReads(ctx: RequestContext): PrivateReadTracker {
|
|
490
532
|
let readPrivate = false
|
|
491
533
|
const mark = (): void => { readPrivate = true }
|
|
534
|
+
const fromUrl = urlDerivedLocals.get(ctx.locals)
|
|
535
|
+
const markUnlessFromUrl = (prop: PropertyKey): void => {
|
|
536
|
+
if (fromUrl?.has(prop) !== true)
|
|
537
|
+
mark()
|
|
538
|
+
}
|
|
492
539
|
const locals = new Proxy(ctx.locals, {
|
|
493
540
|
get(target, prop, receiver) {
|
|
494
|
-
|
|
541
|
+
markUnlessFromUrl(prop)
|
|
495
542
|
return Reflect.get(target, prop, receiver)
|
|
496
543
|
},
|
|
497
544
|
has(target, prop) {
|
|
498
|
-
|
|
545
|
+
markUnlessFromUrl(prop)
|
|
499
546
|
return Reflect.has(target, prop)
|
|
500
547
|
},
|
|
501
548
|
ownKeys(target) {
|