prunelle 0.7.7 → 0.9.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.
Files changed (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -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) })
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
 
@@ -0,0 +1,54 @@
1
+ // An API route that exports a Standard Schema as `schema` has its input checked before the handler runs, with the same 400 envelope actions answer.
2
+
3
+ import type { RequestContext } from './http'
4
+ import type { StandardSchemaV1 } from './standard-schema'
5
+ import { validateSchema } from './standard-schema'
6
+
7
+ const QUERY_METHODS = new Set(['GET', 'HEAD'])
8
+
9
+ export function isStandardSchema(value: unknown): value is StandardSchemaV1 {
10
+ return typeof value === 'object' && value !== null && typeof (value as { '~standard'?: { validate?: unknown } })['~standard']?.validate === 'function'
11
+ }
12
+
13
+ // A key repeated in the query becomes an array, the way a form's repeated field does.
14
+ function queryObject(url: URL): Record<string, string | string[]> {
15
+ const out: Record<string, string | string[]> = {}
16
+ for (const key of new Set(url.searchParams.keys())) {
17
+ const values = url.searchParams.getAll(key)
18
+ Object.defineProperty(out, key, { value: values.length === 1 ? values[0]! : values, enumerable: true, writable: true, configurable: true })
19
+ }
20
+ return out
21
+ }
22
+
23
+ const invalid = (error: string): Response => Response.json({ ok: false, status: 400, error }, { status: 400 })
24
+
25
+ /** Checks `ctx` against the module's `schema` and sets `ctx.input` to the parsed value; answers the 400 when the input is invalid, and nothing when the module declares no schema. The handler's body stays readable: the check reads a clone. */
26
+ export async function validateRouteInput(schema: unknown, ctx: RequestContext): Promise<Response | undefined> {
27
+ if (!isStandardSchema(schema))
28
+ return undefined
29
+ const { request } = ctx
30
+ let raw: unknown
31
+ if (QUERY_METHODS.has(request.method.toUpperCase())) {
32
+ raw = queryObject(ctx.url)
33
+ }
34
+ else {
35
+ const text = await request.clone().text().catch(() => undefined)
36
+ if (text === undefined)
37
+ return invalid('Invalid request body')
38
+ if (text.trim() !== '') {
39
+ if (!(request.headers.get('content-type') ?? '').toLowerCase().includes('application/json'))
40
+ return invalid('Expected a JSON body')
41
+ try {
42
+ raw = JSON.parse(text)
43
+ }
44
+ catch {
45
+ return invalid('Invalid request body')
46
+ }
47
+ }
48
+ }
49
+ const checked = await validateSchema(schema, raw)
50
+ if (!checked.ok)
51
+ return Response.json({ ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues }, { status: 400 })
52
+ ctx.input = checked.value
53
+ return undefined
54
+ }
@@ -11,7 +11,7 @@ import type { NormalizedConsentConfig } from './consent'
11
11
  import type { CookieStore } from './cookies'
12
12
  import type { DocumentHooks, HtmlHeaders } from './document'
13
13
  import type { NotifyError } from './errors'
14
- import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { PhaseTiming, RequestIdResolver } from './health'
15
15
  import type { Middleware, RequestContext } from './http'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
@@ -23,8 +23,10 @@ import type { StreamTracker } from './stream'
23
23
  import { runWithAppContext } from '../plugins/index'
24
24
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
25
25
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
26
- import { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action'
26
+ import { ACTION_ERROR_COOKIE, getActionError, hydrateActionErrorFlash } from './action'
27
+ import { markFlashedFields } from './field-errors'
27
28
  import { compressedHtmlResponse, compressedHtmlStream, markCompressionHandled, mergeVaryValue } from './compress'
29
+ import { cancelQuietly, markHandled } from './discard'
28
30
  import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
29
31
  import { endTimer, startTimer } from './health'
30
32
  import { isNotFound, makeRequestContext, runChain } from './http'
@@ -32,6 +34,7 @@ import { allowedMethodsHeader, hasPublicFavicon, mergedHeadTags, pickPageIslandP
32
34
  import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
33
35
  import { hasRegionHeader, invalidRegionResponse, requestedRegion, respondRegion, withRegionVary } from './region'
34
36
  import { GATED_ROUTE_CACHE_CONTROL, isCacheableRequest, parseCacheDuration, routeCacheKey, serveCachedHit, trackPrivateReads, withCacheControl } from './route-cache'
37
+ import { validateRouteInput } from './route-input'
35
38
  import { Router } from './router'
36
39
  import { createFastStaticPageHandler, methodNotAllowed } from './routing'
37
40
  import { styleHashesOf } from './security'
@@ -80,6 +83,7 @@ function routeDocument(manifest: BuildManifest, entry: RouteManifestEntry, mod:
80
83
  navigation,
81
84
  hasFavicon,
82
85
  regionScript: entry.usesRegion === true ? manifest.regionScript : undefined,
86
+ buildId: manifest.buildId,
83
87
  styles: entry.styles ?? manifest.styles,
84
88
  }
85
89
  }
@@ -174,6 +178,7 @@ export interface CompiledRouteRendererDeps {
174
178
  actions: ActionRegistry
175
179
  rewrites: readonly ((pathname: string, ctx: RequestContext) => string | undefined)[]
176
180
  trustProxy: TrustProxy
181
+ httpsSite?: boolean | undefined
177
182
  consent: NormalizedConsentConfig | undefined
178
183
  resolveRequestId: RequestIdResolver
179
184
  serverAppCtx: AppRuntimeContext
@@ -191,15 +196,17 @@ async function renderPageDocument(
191
196
  ctx: RequestContext,
192
197
  hasFlash: boolean,
193
198
  setIdleTimeout?: (seconds: number) => void,
194
- timing?: DevTiming,
199
+ timing?: PhaseTiming,
195
200
  privateTracker?: PrivateReadTracker,
196
201
  ): Promise<RenderedPageOutput> {
197
202
  const { entry, doc } = route
198
203
  const renderStart = startTimer(timing)
199
204
  const rctx = createRenderContext(undefined, undefined, privateTracker !== undefined ? privateTracker.consent : ctx.consent, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId))
200
- const body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
201
- if (hasFlash)
205
+ let body = await runWithRenderContext(rctx, () => renderRouteBody(route, data, pageProps, privateTracker?.ctx ?? ctx))
206
+ if (hasFlash) {
202
207
  ctx.cookies.delete(ACTION_ERROR_COOKIE)
208
+ body = await markFlashedFields(body, getActionError(ctx.locals))
209
+ }
203
210
  // A route's `export const lang` names the language it is written in, so a plugin head hook such as i18n's cannot replace it.
204
211
  const pageLang = typeof route.mod.lang === 'string' ? route.mod.lang : undefined
205
212
  const resolvedHead = await deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx)
@@ -210,6 +217,7 @@ async function renderPageDocument(
210
217
  const hasIslands = renderedIslands.hasIslands || (isStreamed && entry.islandChunks.length > 0)
211
218
  const preloadChunks = [...isStreamed ? entry.eagerIslandChunks ?? entry.islandChunks : renderedIslands.eagerChunks, ...revivePreload(rctx, deps.manifest.reviveScript)]
212
219
  const hasRegions = rctx.regionNames.size > 0
220
+ const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
213
221
  const trustedStyleHashes = mergeStyleHashes(route.headStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles))
214
222
 
215
223
  if (isStreamed) {
@@ -218,7 +226,7 @@ async function renderPageDocument(
218
226
  if (ctx.request.method === 'HEAD') {
219
227
  rctx.aborted = true
220
228
  endTimer(timing, 'stream', streamStart)
221
- const headers = withRegionVary(deps.htmlHeaders(hasIslands, true, true, trustedStyleHashes), hasRegions)
229
+ const headers = withRegionVary(deps.htmlHeaders(needsIslandStyle, true, true, trustedStyleHashes), hasRegions)
222
230
  if (deps.compressCache !== undefined)
223
231
  headers.vary = mergeVaryValue(headers.vary, 'Accept-Encoding')
224
232
  return { kind: 'stream', response: markCompressionHandled(new Response(null, { status: 200, headers })) }
@@ -230,7 +238,7 @@ async function renderPageDocument(
230
238
  rctx.headersFlushed = true
231
239
  endTimer(timing, 'stream', streamStart)
232
240
  const transformChunk = deps.hasHtmlTransformers ? (html: string) => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined
233
- const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk, deps.streams), 200, withRegionVary(deps.htmlHeaders(hasIslands, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
241
+ const response = await compressedHtmlStream(streamDocument(shell, rctx, deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId), transformChunk, deps.streams), 200, withRegionVary(deps.htmlHeaders(needsIslandStyle, true, true, streamStyleHashes), hasRegions), ctx.request, deps.compressCache)
234
242
  return { kind: 'stream', response }
235
243
  }
236
244
 
@@ -238,7 +246,7 @@ async function renderPageDocument(
238
246
  const html = deps.hasHtmlTransformers ? await deps.applyHtmlTransforms(docHtml, ctx.url, ctx.request, ctx) : docHtml
239
247
  const finalStyleHashes = mergeStyleHashes(trustedStyleHashes, addedInlineStyleHashes(docHtml, html))
240
248
  endTimer(timing, 'render', renderStart)
241
- return { kind: 'html', html, headers: withRegionVary(deps.htmlHeaders(hasIslands, false, true, finalStyleHashes), hasRegions) }
249
+ return { kind: 'html', html, headers: withRegionVary(deps.htmlHeaders(needsIslandStyle, false, true, finalStyleHashes), hasRegions) }
242
250
  }
243
251
 
244
252
  async function revalidateCompiledRoute(
@@ -253,10 +261,11 @@ async function revalidateCompiledRoute(
253
261
  const routeCache = deps.routeCache
254
262
  if (routeCache === undefined)
255
263
  return
264
+ const generation = routeCache.generation
256
265
  await runWithAppContext(deps.serverAppCtx, async () => {
257
266
  const bgReq = new Request(url.href, { method: 'GET' })
258
267
  const bgReqId = deps.resolveRequestId(bgReq)
259
- const { ctx, cookieStore } = makeRequestContext(bgReq, { ...params }, { trustProxy: deps.trustProxy, url, consent: deps.consent, requestId: bgReqId })
268
+ const { ctx, cookieStore } = makeRequestContext(bgReq, { ...params }, { trustProxy: deps.trustProxy, httpsSite: deps.httpsSite, url, consent: deps.consent, requestId: bgReqId })
260
269
  for (const rewrite of deps.rewrites)
261
270
  rewrite(url.pathname, ctx)
262
271
  await deps.actions.run(ctx, async () => {
@@ -275,7 +284,7 @@ async function revalidateCompiledRoute(
275
284
  return new Response(null, { status: 404 })
276
285
  }
277
286
  if (error instanceof Response) {
278
- void error.body?.cancel().catch(() => undefined)
287
+ void cancelQuietly(error.body)
279
288
  throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
280
289
  }
281
290
  throw error
@@ -293,9 +302,11 @@ async function revalidateCompiledRoute(
293
302
  ? new Response(null, { status: 200, headers: rendered.headers })
294
303
  : rendered.response
295
304
  })
305
+ if (routeCache.generation !== generation)
306
+ return
296
307
  if (!nonCacheable && rendered?.kind === 'html' && res.status === 200 && !cookieStore.hasChanges)
297
308
  routeCache.set(cacheKey, rendered.html, withCacheControl(rendered.headers, cacheSpec.cacheControl), cacheSpec)
298
- else
309
+ else if (rendered !== undefined || (res.status !== 401 && res.status !== 403 && (res.status < 300 || res.status >= 400)))
299
310
  routeCache.delete(cacheKey)
300
311
  })
301
312
  })
@@ -305,7 +316,7 @@ async function runCompiledRouteLoad(
305
316
  deps: CompiledRouteRendererDeps,
306
317
  route: CompiledRoute,
307
318
  ctx: RequestContext,
308
- timing?: DevTiming,
319
+ timing?: PhaseTiming,
309
320
  ): Promise<{ kind: 'response', response: Response } | { kind: 'data', data: unknown }> {
310
321
  const { entry, mod } = route
311
322
  let data: unknown
@@ -318,7 +329,7 @@ async function runCompiledRouteLoad(
318
329
  if (isNotFound(error))
319
330
  return { kind: 'response', response: await deps.buildNotFoundResponse(ctx.url, ctx.request, ctx, entry.file) }
320
331
  if (error instanceof Response) {
321
- void error.body?.cancel().catch(() => undefined)
332
+ void cancelQuietly(error.body)
322
333
  throw new Error(`prunelle: load() threw a Response (HTTP ${error.status}) instead of returning it; return the Response from load() instead.`)
323
334
  }
324
335
  throw error
@@ -350,9 +361,9 @@ async function resolvePrerenderedOrApi(
350
361
  const method = ctx.request.method.toUpperCase()
351
362
  const methodHandler = routeMethodHandler(mod, method)
352
363
  if (methodHandler !== undefined)
353
- return await methodHandler(ctx)
364
+ return await validateRouteInput(mod.schema, ctx) ?? await methodHandler(ctx)
354
365
  if (method === 'HEAD' && typeof mod.GET === 'function')
355
- return stripHeadBody(await mod.GET(ctx))
366
+ return await validateRouteInput(mod.schema, ctx) ?? stripHeadBody(await mod.GET(ctx))
356
367
  return undefined
357
368
  }
358
369
 
@@ -363,7 +374,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
363
374
  cookieStore: CookieStore,
364
375
  setIdleTimeout?: (seconds: number) => void,
365
376
  staticPath?: string,
366
- timing?: DevTiming,
377
+ timing?: PhaseTiming,
367
378
  middlewares: readonly Middleware[] = route.middlewares,
368
379
  ): Promise<Response> {
369
380
  const { entry, mod, doc } = route
@@ -384,14 +395,17 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
384
395
  const cacheSpec = deps.routeCache !== undefined && !isRegion && !hasFlash && isCacheableRequest(ctx.request) ? entry.cache : undefined
385
396
  const cacheKey = cacheSpec !== undefined ? routeCacheKey(ctx.url) : undefined
386
397
  let inflight: PromiseWithResolvers<RouteCacheSingleflightResult | undefined> | undefined
398
+ const generation = deps.routeCache?.generation
387
399
  if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined) {
400
+ // A route guarded by directory middleware with auth credentials may reject an unauthenticated background SWR; revalidate synchronously on the authorized request instead.
401
+ const hasCredentials = ctx.request.headers.has('cookie') || ctx.request.headers.has('authorization')
388
402
  const cached = serveCachedHit(
389
403
  deps.routeCache,
390
404
  cacheKey,
391
405
  ctx.request,
392
406
  ctx.requestId,
393
407
  deps.compressCache,
394
- () => revalidateCompiledRoute(deps, route, ctx.url, ctx.params, cacheKey, cacheSpec, middlewares),
408
+ route.dirMiddlewares.length > 0 && hasCredentials ? undefined : () => revalidateCompiledRoute(deps, route, ctx.url, ctx.params, cacheKey, cacheSpec, middlewares),
395
409
  error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
396
410
  )
397
411
  if (cached !== undefined)
@@ -404,7 +418,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
404
418
  }
405
419
  else {
406
420
  inflight = Promise.withResolvers<RouteCacheSingleflightResult | undefined>()
407
- void inflight.promise.catch(() => undefined)
421
+ markHandled(inflight.promise)
408
422
  deps.routeCache.trackInflight(cacheKey, inflight.promise)
409
423
  }
410
424
  }
@@ -422,6 +436,7 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
422
436
  rctx => deps.resolveDocumentHead(rctx, doc.headTags as readonly string[] | undefined, ctx.url, ctx.request, ctx),
423
437
  deps.streamTimeout, error => deps.notifyError(error, ctx.request, 'route', ctx.requestId),
424
438
  deps.hasHtmlTransformers ? html => deps.applyHtmlTransforms(html, ctx.url, ctx.request, ctx) : undefined,
439
+ doc.buildId,
425
440
  )
426
441
  }
427
442
 
@@ -432,7 +447,8 @@ export function createCompiledRouteRenderer(deps: CompiledRouteRendererDeps) {
432
447
  return compressedHtmlResponse(rendered.html, 200, withCacheControl(rendered.headers, 'private, no-store'), ctx.request, deps.compressCache)
433
448
  if (cacheSpec !== undefined && cacheKey !== undefined && deps.routeCache !== undefined && !cookieStore.hasChanges) {
434
449
  const cachedHeaders = withCacheControl(rendered.headers, cacheSpec.cacheControl)
435
- const stored = deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec)
450
+ // A drop while this rendered may have changed what it read: answer with it, but keep it out of the cache.
451
+ const stored = deps.routeCache.generation === generation ? deps.routeCache.set(cacheKey, rendered.html, cachedHeaders, cacheSpec) : undefined
436
452
  inflight?.resolve({ entry: stored, html: rendered.html, headers: cachedHeaders })
437
453
  return deps.routeCache.respondMiss(stored, rendered.html, cachedHeaders, ctx.request, ctx.requestId, deps.compressCache)
438
454
  }
@@ -10,16 +10,16 @@ import type { NormalizedConsentConfig } from './consent'
10
10
  import type { CookieStore } from './cookies'
11
11
  import type { HtmlHeaders } from './document'
12
12
  import type { NotifyError } from './errors'
13
- import type { DevTiming, RequestIdResolver } from './health'
13
+ import type { PhaseTiming, RequestIdResolver } from './health'
14
14
  import type { DeniedInfo, Middleware, RequestContext } from './http'
15
- import type { PrunelleLocals } from './index'
15
+ import type { PrunelleLocals } from './public'
16
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
17
  import type { ParamMatcherMap } from './param-matchers'
18
18
  import type { RequestPath } from './request-path'
19
19
  import type { TrustProxy } from './security'
20
20
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
21
21
  import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
22
- import { keepScrollTag } from '../ssr/navigation'
22
+ import { withKeepScroll } from '../ssr/navigation'
23
23
  import { compressedHtmlResponse, maybeCompressResponse } from './compress'
24
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
25
25
  import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
@@ -260,10 +260,11 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
260
260
  notifyError(error, request, 'route', ctx?.requestId)
261
261
  return renderError(error, cookieStore, url, request, ctx, entry.file)
262
262
  }
263
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
264
- const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
263
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response => {
264
+ const html = withKeepScroll(rctx.revives ? revivingPrefix : docPrefix, body, docSuffix)
265
265
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
266
- const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
266
+ const needsIslandStyle = hasIslands || (doc.regionScript !== undefined && doc.runtimeScript !== undefined)
267
+ const headers = withRegionVary(htmlHeaders(needsIslandStyle, false, true, styleHashes), rctx.regionNames.size > 0)
267
268
  const st = timing !== undefined ? finishRenderTiming(timing) : undefined
268
269
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
269
270
  res.headers.set('x-request-id', ctx.requestId)
@@ -273,7 +274,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
273
274
  }
274
275
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
275
276
 
276
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
277
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Promise<Response> => {
277
278
  try {
278
279
  return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
279
280
  }
@@ -282,7 +283,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
282
283
  }
283
284
  }
284
285
 
285
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
286
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
286
287
  if (layouts.length === 0)
287
288
  return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
288
289
  if (singleLayout !== undefined) {
@@ -304,7 +305,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
304
305
  })()
305
306
  }
306
307
 
307
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
308
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Promise<Response> => {
308
309
  try {
309
310
  return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
310
311
  }
@@ -313,7 +314,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
313
314
  }
314
315
  }
315
316
 
316
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
317
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: PhaseTiming): Response | Promise<Response> => {
317
318
  if (timing !== undefined)
318
319
  timing.render = performance.now()
319
320
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
@@ -335,7 +336,7 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
335
336
 
336
337
  return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
337
338
  const reqId = requestId ?? getRequestId(request)
338
- const timing = createTiming(isDev)
339
+ const timing = createTiming(isDev, request)
339
340
  const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
340
341
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
341
342
  return actions.run(ctx, async () => {
@@ -1,4 +1,4 @@
1
- // HTML allow-list sanitizer for rendered Markdown, shared by @prunellejs/content and the @prunellejs/cms preview: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
1
+ // HTML allow-list sanitizer for rendered Markdown, used by @prunellejs/content: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
2
 
3
3
  const DROP_CONTENT_TAGS = new Set([
4
4
  'script',