prunelle 0.1.1 → 0.7.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -10,9 +10,11 @@ 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 { Middleware, RequestContext } from './http'
13
+ import type { DevTiming, RequestIdResolver } from './health'
14
+ import type { DeniedInfo, Middleware, RequestContext } from './http'
14
15
  import type { PrunelleLocals } from './index'
15
16
  import type { LoadedLayoutModule, LoadedMiddlewareModule, LoadedPageModule } from './page'
17
+ import type { ParamMatcherMap } from './param-matchers'
16
18
  import type { RequestPath } from './request-path'
17
19
  import type { TrustProxy } from './security'
18
20
  import { createRenderContext, runWithRenderContext } from '../ssr/context'
@@ -20,18 +22,24 @@ import { raw, renderDocument, ssrChild, ssrIsland } from '../ssr/index'
20
22
  import { keepScrollTag } from '../ssr/navigation'
21
23
  import { compressedHtmlResponse, maybeCompressResponse } from './compress'
22
24
  import { headTagStyleHashes, mergeStyleHashes } from './document'
23
- import { isNotFound, makeRequestContext } from './http'
25
+ import { createTiming, endTimer, finishRenderTiming, formatServerTiming, resolveFallbackRequestId, startTimer } from './health'
26
+ import { acceptsHtml, getDeniedInfo, isNotFound, makeRequestContext } from './http'
24
27
  import { pickPageIslandProps } from './page'
28
+ import { BUILTIN_PARAM_MATCHERS } from './param-matchers'
25
29
  import { withRegionVary } from './region'
26
- import { pathPrefix } from './request-path'
30
+ import { decodeRequestPath, pathPrefix } from './request-path'
27
31
  import { Router } from './router'
28
32
  import { styleHashesOf } from './security'
29
33
 
30
34
  const MIDDLEWARE_BASENAME_RE = /(?:^|\/)_middleware\.js$/
35
+ const ROUTE_GROUP_RE = /^\([^/()]+\)$/
36
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
37
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
38
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
31
39
  const CATCH_ALL_BRACKET_RE = /\[\.\.\.([^\]]+)\]/g
32
40
  const PARAM_BRACKET_RE = /\[([^\]]+)\]/g
33
41
 
34
- export type FastHandler = (req: Request, remoteIp?: string, url?: URL) => Response | Promise<Response>
42
+ export type FastHandler = (req: Request, remoteIp?: string, url?: URL, requestId?: string) => Response | Promise<Response>
35
43
 
36
44
 
37
45
  export function methodNotAllowed(allow: string): Response {
@@ -42,7 +50,14 @@ export function methodNotAllowed(allow: string): Response {
42
50
  export function toBunRouteKey(path: string): string | undefined {
43
51
  if (path.includes('*'))
44
52
  return undefined
45
- return path.split('/').map(encodeURIComponent).join('/')
53
+ return path.split('/').map((seg) => {
54
+ if (seg.includes('%')) {
55
+ const decoded = decodeRequestPath(`/${seg}`)
56
+ if (decoded?.staticPath !== undefined)
57
+ return encodeURIComponent(decoded.staticPath.slice(1))
58
+ }
59
+ return encodeURIComponent(seg)
60
+ }).join('/')
46
61
  }
47
62
 
48
63
  function dirnamePrefix(file: string): string {
@@ -50,10 +65,26 @@ function dirnamePrefix(file: string): string {
50
65
  return slash === -1 ? '' : file.slice(0, slash + 1)
51
66
  }
52
67
 
68
+ function convertDirSegment(seg: string): string {
69
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(seg)
70
+ if (opt !== null)
71
+ return `:${opt[1]}?`
72
+ const catchAll = CATCH_ALL_SEG_RE.exec(seg)
73
+ if (catchAll !== null)
74
+ return `*${catchAll[1]}`
75
+ const param = PARAM_SEG_RE.exec(seg)
76
+ if (param !== null)
77
+ return `:${param[1]}`
78
+ return seg.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')
79
+ }
80
+
53
81
  function dirToRoutePattern(relDir: string): string {
54
82
  if (relDir === '')
55
83
  return '/'
56
- return `/${relDir.replace(CATCH_ALL_BRACKET_RE, '*$1').replace(PARAM_BRACKET_RE, ':$1')}`
84
+ const parts = relDir.split('/').filter(p => p !== '' && !ROUTE_GROUP_RE.test(p))
85
+ if (parts.length === 0)
86
+ return '/'
87
+ return `/${parts.map(convertDirSegment).join('/')}`
57
88
  }
58
89
 
59
90
  /** Infers the compiled module prefix for files under `routesDir` (e.g. `'server/'` or `'server/src/routes/'`). */
@@ -66,9 +97,17 @@ export function inferRoutesServerPrefix(manifest: BuildManifest): string {
66
97
  const fileParts = route.file.split('/')
67
98
  const pathSegs = route.path === '/' ? [] : route.path.replace(/^\/|\/$/g, '').split('/')
68
99
  const isIndex = fileParts[fileParts.length - 1] === 'index.js'
69
- const routePartCount = pathSegs.length + (isIndex ? 1 : 0)
70
- if (routePartCount <= fileParts.length) {
71
- const prefixParts = fileParts.slice(0, fileParts.length - routePartCount)
100
+ let remaining = pathSegs.length + (isIndex ? 1 : 0)
101
+ let idx = fileParts.length
102
+ while (idx > 0 && remaining > 0) {
103
+ idx--
104
+ if (!ROUTE_GROUP_RE.test(fileParts[idx]!))
105
+ remaining--
106
+ }
107
+ while (idx > 0 && ROUTE_GROUP_RE.test(fileParts[idx - 1]!))
108
+ idx--
109
+ if (remaining === 0) {
110
+ const prefixParts = fileParts.slice(0, idx)
72
111
  return prefixParts.length === 0 ? '' : `${prefixParts.join('/')}/`
73
112
  }
74
113
  }
@@ -107,6 +146,7 @@ export function createAncestorMiddlewareLookup(
107
146
  manifest: BuildManifest,
108
147
  modules: Record<string, unknown>,
109
148
  routesPrefix: string,
149
+ paramMatchers: ParamMatcherMap = BUILTIN_PARAM_MATCHERS,
110
150
  ): (path: RequestPath) => AncestorMiddlewareMatch | undefined {
111
151
  const byPattern = new Map<string, Middleware[]>()
112
152
  const seenModules = new Set<string>()
@@ -122,6 +162,9 @@ export function createAncestorMiddlewareLookup(
122
162
  return
123
163
  const rel = modKey.slice(routesPrefix.length)
124
164
  const relDir = rel.replace(MIDDLEWARE_BASENAME_RE, '')
165
+ // A `(group)` middleware only applies to routes/actions inside that group, never to unrelated unmatched URLs.
166
+ if (relDir !== '' && relDir.split('/').some(p => ROUTE_GROUP_RE.test(p)))
167
+ return
125
168
  const pattern = dirToRoutePattern(relDir)
126
169
  let list = byPattern.get(pattern)
127
170
  if (list === undefined) {
@@ -147,7 +190,7 @@ export function createAncestorMiddlewareLookup(
147
190
  if (byPattern.size === 0)
148
191
  return () => undefined
149
192
 
150
- const dirRouter = new Router<Middleware[]>()
193
+ const dirRouter = new Router<Middleware[]>(paramMatchers)
151
194
  for (const [pattern, list] of byPattern)
152
195
  dirRouter.add(pattern, list)
153
196
 
@@ -182,36 +225,18 @@ export interface FastStaticPageOptions {
182
225
  htmlHeaders: HtmlHeaders
183
226
  compressCache: CompressionCache | undefined
184
227
  actions: ActionRegistry
185
- buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext) => Promise<Response>
186
- renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext) => Promise<Response>
228
+ buildNotFoundResponse: (url?: URL, req?: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
229
+ renderError: (error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>
230
+ renderDenied?: ((denied: DeniedInfo, url: URL, req: Request, ctx?: RequestContext, routeFile?: string) => Promise<Response>) | undefined
187
231
  notifyError: NotifyError
188
- finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
232
+ finish: (res: Response, request: Request, cookieStore?: CookieStore, requestId?: string, serverTiming?: string) => Response
189
233
  withHsts: (res: Response, request: Request) => Response
234
+ dev?: boolean | undefined
235
+ resolveRequestId?: RequestIdResolver | undefined
236
+ httpsSite?: boolean | undefined
190
237
  }
191
238
 
192
- /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
193
- export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
194
- const {
195
- entry,
196
- mod,
197
- layouts,
198
- doc,
199
- reviveScript,
200
- hasIslands,
201
- hasLoad,
202
- trustProxy,
203
- consent,
204
- htmlHeaders,
205
- compressCache,
206
- actions,
207
- buildNotFoundResponse,
208
- renderError,
209
- notifyError,
210
- finish,
211
- withHsts,
212
- } = options
213
-
214
- const eagerChunks = entry.eagerIslandChunks ?? entry.islandChunks
239
+ function buildFastDocShell(doc: DocumentOptions, eagerChunks: string[], reviveScript: string | undefined, hasIslands: boolean): { docPrefix: string, revivingPrefix: string, docSuffix: string } {
215
240
  const shellAround = (preloadChunks: string[]): [string, string] => {
216
241
  const shell = renderDocument({ ...doc, body: '\0', preloadChunks, hasIslands })
217
242
  const splitAt = shell.indexOf('\0')
@@ -219,46 +244,59 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
219
244
  }
220
245
  const [docPrefix, docSuffix] = shellAround(eagerChunks)
221
246
  const revivingPrefix = reviveScript === undefined ? docPrefix : shellAround([...eagerChunks, reviveScript])[0]
247
+ return { docPrefix, revivingPrefix, docSuffix }
248
+ }
249
+
250
+ /** Builds the zero-overhead static-path page handler, keeping `actions.run()` active through load, render, and 404 fallback. */
251
+ export function createFastStaticPageHandler(options: FastStaticPageOptions): FastHandler {
252
+ const { entry, mod, layouts, doc, reviveScript, hasIslands, hasLoad, trustProxy, consent, htmlHeaders, compressCache, actions, buildNotFoundResponse, renderError, renderDenied, notifyError, finish, withHsts } = options
253
+ const isDev = options.dev === true
254
+ const getRequestId: RequestIdResolver = options.resolveRequestId ?? (req => resolveFallbackRequestId(req, trustProxy))
255
+ const { docPrefix, revivingPrefix, docSuffix } = buildFastDocShell(doc, entry.eagerIslandChunks ?? entry.islandChunks, reviveScript, hasIslands)
222
256
  const headStyleHashes = headTagStyleHashes(doc.headTags)
223
257
  const singleLayout = layouts.length === 1 ? layouts[0]! : undefined
224
258
 
225
259
  const fail = (error: unknown, request: Request, url: URL, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
226
- notifyError(error, request, 'route')
227
- return renderError(error, cookieStore, url, request, ctx)
260
+ notifyError(error, request, 'route', ctx?.requestId)
261
+ return renderError(error, cookieStore, url, request, ctx, entry.file)
228
262
  }
229
- const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore?: CookieStore): Response => {
263
+ const respondHtml = (body: string, request: Request, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response => {
230
264
  const html = (rctx.revives ? revivingPrefix : docPrefix) + body + keepScrollTag(body) + docSuffix
231
265
  const styleHashes = mergeStyleHashes(headStyleHashes, styleHashesOf(rctx.inlineStyles))
232
266
  const headers = withRegionVary(htmlHeaders(hasIslands, false, true, styleHashes), rctx.regionNames.size > 0)
267
+ const st = timing !== undefined ? finishRenderTiming(timing) : undefined
233
268
  const res = compressedHtmlResponse(html, 200, headers, request, compressCache, !hasLoad)
234
- return cookieStore?.hasChanges ? finish(res, request, cookieStore) : withHsts(res, request)
269
+ res.headers.set('x-request-id', ctx.requestId)
270
+ if (st !== undefined)
271
+ res.headers.set('server-timing', st)
272
+ return cookieStore.hasChanges ? finish(res, request, cookieStore, ctx.requestId, st) : withHsts(res, request)
235
273
  }
236
274
  const layoutProps = (inner: string, url: URL, locals: PrunelleLocals) => ({ children: raw(inner), url, params: {}, locals })
237
275
 
238
- const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
276
+ const finishSingleLayout = async (wrapped: Promise<Html | string>, request: Request, url: URL, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
239
277
  try {
240
- return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore)
278
+ return respondHtml(ssrChild(await wrapped as Html), request, rctx, cookieStore, ctx, timing)
241
279
  }
242
280
  catch (error) {
243
281
  return fail(error, request, url, cookieStore, ctx)
244
282
  }
245
283
  }
246
284
 
247
- const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
285
+ const wrapLayouts = (inner: string, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
248
286
  if (layouts.length === 0)
249
- return respondHtml(inner, request, rctx, cookieStore)
287
+ return respondHtml(inner, request, rctx, cookieStore, ctx, timing)
250
288
  if (singleLayout !== undefined) {
251
289
  const wrapped = singleLayout.default(layoutProps(inner, url, locals))
252
290
  if (wrapped instanceof Promise)
253
- return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx)
254
- return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore)
291
+ return finishSingleLayout(wrapped, request, url, rctx, cookieStore, ctx, timing)
292
+ return respondHtml(ssrChild(wrapped as Html), request, rctx, cookieStore, ctx, timing)
255
293
  }
256
294
  return (async () => {
257
295
  try {
258
296
  let cur = inner
259
297
  for (let i = layouts.length - 1; i >= 0; i--)
260
298
  cur = ssrChild(await layouts[i]!.default(layoutProps(cur, url, locals)) as Html)
261
- return respondHtml(cur, request, rctx, cookieStore)
299
+ return respondHtml(cur, request, rctx, cookieStore, ctx, timing)
262
300
  }
263
301
  catch (error) {
264
302
  return fail(error, request, url, cookieStore, ctx)
@@ -266,16 +304,18 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
266
304
  })()
267
305
  }
268
306
 
269
- const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Promise<Response> => {
307
+ const finishAsyncPage = async (rendered: Promise<Html | string>, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Promise<Response> => {
270
308
  try {
271
- return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx)
309
+ return await wrapLayouts(ssrChild(await rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
272
310
  }
273
311
  catch (error) {
274
312
  return fail(error, request, url, cookieStore, ctx)
275
313
  }
276
314
  }
277
315
 
278
- const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore?: CookieStore, ctx?: RequestContext): Response | Promise<Response> => {
316
+ const renderPage = (data: unknown, request: Request, url: URL, locals: PrunelleLocals, rctx: RenderContext, cookieStore: CookieStore, ctx: RequestContext, timing?: DevTiming): Response | Promise<Response> => {
317
+ if (timing !== undefined)
318
+ timing.render = performance.now()
279
319
  const pageProps: Record<string, unknown> = { params: {}, locals, url, ...(data !== undefined ? { data } : {}) }
280
320
  if (entry.isIsland && entry.islandChunk !== undefined) {
281
321
  return wrapLayouts(ssrIsland(
@@ -285,47 +325,56 @@ export function createFastStaticPageHandler(options: FastStaticPageOptions): Fas
285
325
  entry.islandHydrate as HydrateStrategy | undefined,
286
326
  true,
287
327
  mod.default!.name,
288
- ), request, url, locals, rctx, cookieStore, ctx)
328
+ ), request, url, locals, rctx, cookieStore, ctx, timing)
289
329
  }
290
330
  const rendered = mod.default!(pageProps)
291
331
  if (rendered instanceof Promise)
292
- return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx)
293
- return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx)
332
+ return finishAsyncPage(rendered, request, url, locals, rctx, cookieStore, ctx, timing)
333
+ return wrapLayouts(ssrChild(rendered as Html), request, url, locals, rctx, cookieStore, ctx, timing)
294
334
  }
295
335
 
296
- return (request, remoteIp, url = new URL(request.url)) => {
297
- const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, remoteIp, url, consent })
336
+ return (request, remoteIp, url = new URL(request.url), requestId?: string) => {
337
+ const reqId = requestId ?? getRequestId(request)
338
+ const timing = createTiming(isDev)
339
+ const { ctx, cookieStore } = makeRequestContext(request, {}, { trustProxy, httpsSite: options.httpsSite, remoteIp, url, consent, requestId: reqId })
298
340
  if (request.method === 'HEAD' && typeof mod.HEAD === 'function') {
299
341
  return actions.run(ctx, async () => {
300
342
  try {
301
- return finish(await mod.HEAD!(ctx), request, cookieStore)
343
+ return finish(await mod.HEAD!(ctx), request, cookieStore, reqId, formatServerTiming(timing))
302
344
  }
303
345
  catch (error) {
304
346
  return fail(error, request, url, cookieStore, ctx)
305
347
  }
306
348
  })
307
349
  }
308
- const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route'))
350
+ const rctx = createRenderContext(undefined, undefined, ctx.consent, error => notifyError(error, request, 'route', reqId))
309
351
  try {
310
352
  if (!hasLoad)
311
- return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx)))
353
+ return actions.run(ctx, () => runWithRenderContext(rctx, () => renderPage(undefined, request, url, ctx.locals, rctx, cookieStore, ctx, timing)))
312
354
 
313
355
  return actions.run(ctx, async () => {
314
356
  let loaded: unknown
357
+ const loadStart = startTimer(timing)
315
358
  try {
316
359
  loaded = await mod.load!(ctx)
317
360
  }
318
361
  catch (error) {
319
362
  if (isNotFound(error))
320
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
363
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
321
364
  return fail(error, request, url, cookieStore, ctx)
322
365
  }
366
+ endTimer(timing, 'load', loadStart)
323
367
  if (isNotFound(loaded))
324
- return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx), request, compressCache), request, cookieStore)
325
- if (loaded instanceof Response)
326
- return finish(await maybeCompressResponse(loaded, request, compressCache), request, cookieStore)
368
+ return finish(await maybeCompressResponse(await buildNotFoundResponse(url, request, ctx, entry.file), request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
369
+ if (loaded instanceof Response) {
370
+ const denied = getDeniedInfo(loaded)
371
+ const out = denied !== undefined && renderDenied !== undefined && acceptsHtml(request)
372
+ ? await renderDenied(denied, url, request, ctx, entry.file)
373
+ : loaded
374
+ return finish(await maybeCompressResponse(out, request, compressCache), request, cookieStore, reqId, formatServerTiming(timing))
375
+ }
327
376
  try {
328
- return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx))
377
+ return await runWithRenderContext(rctx, () => renderPage(loaded, request, url, ctx.locals, rctx, cookieStore, ctx, timing))
329
378
  }
330
379
  catch (error) {
331
380
  return fail(error, request, url, cookieStore, ctx)
@@ -0,0 +1,309 @@
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.
2
+
3
+ const DROP_CONTENT_TAGS = new Set([
4
+ 'script',
5
+ 'style',
6
+ 'iframe',
7
+ 'object',
8
+ 'applet',
9
+ 'noscript',
10
+ 'template',
11
+ ])
12
+
13
+ const ALLOWED_MD_TAGS = new Set([
14
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
+ 'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
16
+ 'a', 'img', 'picture', 'source',
17
+ 'pre', 'code', 'kbd', 'samp', 'var',
18
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
19
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
20
+ 'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
21
+ 'details', 'summary', 'figure', 'figcaption',
22
+ 'input',
23
+ ])
24
+
25
+ // Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
26
+ const GLOBAL_ALLOWED_ATTRS = new Set([
27
+ 'class',
28
+ 'title',
29
+ 'lang',
30
+ 'dir',
31
+ 'role',
32
+ 'aria-label',
33
+ 'aria-hidden',
34
+ 'aria-current',
35
+ 'aria-expanded',
36
+ 'aria-level',
37
+ 'aria-description',
38
+ 'aria-roledescription',
39
+ ])
40
+
41
+ const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
42
+ a: new Set(['href', 'rel', 'target', 'hreflang']),
43
+ img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
44
+ source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
45
+ blockquote: new Set(['cite']),
46
+ q: new Set(['cite']),
47
+ del: new Set(['cite', 'datetime']),
48
+ ins: new Set(['cite', 'datetime']),
49
+ time: new Set(['datetime']),
50
+ ol: new Set(['start', 'reversed', 'type']),
51
+ li: new Set(['value']),
52
+ th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
53
+ td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
54
+ col: new Set(['span', 'align']),
55
+ colgroup: new Set(['span', 'align']),
56
+ details: new Set(['open']),
57
+ }
58
+
59
+ const URL_ATTRS = new Set(['href', 'src', 'cite'])
60
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
61
+ const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
62
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
63
+
64
+ function decodeHtmlEntities(rawVal: string): string {
65
+ return rawVal
66
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
67
+ const cp = Number.parseInt(hex, 16)
68
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
69
+ })
70
+ .replace(/&#([0-9]+);?/g, (_, dec: string) => {
71
+ const cp = Number.parseInt(dec, 10)
72
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
73
+ })
74
+ .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
75
+ const lower = name.toLowerCase()
76
+ if (lower === 'colon') return ':'
77
+ if (lower === 'tab') return '\t'
78
+ if (lower === 'newline') return '\n'
79
+ return '&'
80
+ })
81
+ }
82
+
83
+ function isSafeUrl(val: string): boolean {
84
+ const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
85
+ if (cleaned === '')
86
+ return true
87
+ if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
88
+ return true
89
+ if (HAS_SCHEME_RE.test(cleaned))
90
+ return false
91
+ return true
92
+ }
93
+
94
+ function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
95
+ const attrs: Array<{ name: string, value: string | null }> = []
96
+ let i = 0
97
+ const len = attrSrc.length
98
+ while (i < len) {
99
+ while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
100
+ if (i >= len) break
101
+ const nameStart = i
102
+ while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
103
+ const name = attrSrc.slice(nameStart, i).toLowerCase()
104
+ if (!name) {
105
+ i++
106
+ continue
107
+ }
108
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
109
+ if (attrSrc[i] !== '=') {
110
+ attrs.push({ name, value: null })
111
+ continue
112
+ }
113
+ i++ // skip '='
114
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
115
+ if (i >= len) {
116
+ attrs.push({ name, value: '' })
117
+ break
118
+ }
119
+ const quote = attrSrc[i]!
120
+ if (quote === '"' || quote === '\'') {
121
+ i++
122
+ const valStart = i
123
+ while (i < len && attrSrc[i] !== quote) i++
124
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
125
+ if (i < len) i++
126
+ }
127
+ else {
128
+ const valStart = i
129
+ while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
130
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
131
+ }
132
+ }
133
+ return attrs
134
+ }
135
+
136
+ function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
137
+ const typeAttr = rawAttrs.find(a => a.name === 'type')
138
+ if (typeAttr?.value?.toLowerCase() !== 'checkbox')
139
+ return ''
140
+ const safeParts = ['type="checkbox"']
141
+ for (const a of rawAttrs) {
142
+ if (a.name === 'class' && a.value !== null)
143
+ safeParts.push(`class="${a.value.replaceAll('"', '&quot;')}"`)
144
+ else if (a.name === 'disabled')
145
+ safeParts.push('disabled')
146
+ else if (a.name === 'checked')
147
+ safeParts.push('checked')
148
+ }
149
+ return `<input ${safeParts.join(' ')}>`
150
+ }
151
+
152
+ type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
153
+
154
+ function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
155
+ if (value === null || allowed === undefined)
156
+ return false
157
+ if (typeof allowed === 'string')
158
+ return value.startsWith(allowed)
159
+ for (const prefix of allowed) {
160
+ if (value.startsWith(prefix))
161
+ return true
162
+ }
163
+ return false
164
+ }
165
+
166
+ function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
167
+ if (tagName === 'div' && name === 'data-pru-md-slot')
168
+ return matchesSlotPrefix(value, slotPrefixes)
169
+ return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
170
+ }
171
+
172
+ function sanitizeAttributes(
173
+ tagName: string,
174
+ rawAttrs: Array<{ name: string, value: string | null }>,
175
+ slotPrefixes: AllowedSlotPrefixes,
176
+ ): string[] {
177
+ const safeParts: string[] = []
178
+ for (const a of rawAttrs) {
179
+ if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
180
+ continue
181
+ if (URL_ATTRS.has(a.name)) {
182
+ if (a.value === null || !isSafeUrl(a.value))
183
+ continue
184
+ }
185
+ else if (a.name === 'srcset' && a.value !== null) {
186
+ const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
187
+ if (!candidates.every(isSafeUrl))
188
+ continue
189
+ }
190
+ if (a.value === null)
191
+ safeParts.push(a.name)
192
+ else
193
+ safeParts.push(`${a.name}="${a.value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}"`)
194
+ }
195
+ return safeParts
196
+ }
197
+
198
+ function findTagEndOffset(html: string, start: number): number {
199
+ let tagEnd = start
200
+ const len = html.length
201
+ let inQuote: string | null = null
202
+ while (tagEnd < len) {
203
+ const c = html[tagEnd]!
204
+ if (inQuote !== null) {
205
+ if (c === inQuote)
206
+ inQuote = null
207
+ }
208
+ else if (c === '"' || c === '\'') {
209
+ inQuote = c
210
+ }
211
+ else if (c === '>') {
212
+ return tagEnd
213
+ }
214
+ tagEnd++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
+ let out = ''
221
+ let i = 0
222
+ const len = html.length
223
+
224
+ while (i < len) {
225
+ const lt = html.indexOf('<', i)
226
+ if (lt === -1) {
227
+ out += html.slice(i)
228
+ break
229
+ }
230
+ out += html.slice(i, lt)
231
+
232
+ // Strip HTML comments (including HTML5 `--!>` closer)
233
+ if (html.startsWith('<!--', lt)) {
234
+ const endStd = html.indexOf('-->', lt + 4)
235
+ const endBang = html.indexOf('--!>', lt + 4)
236
+ if (endStd === -1 && endBang === -1)
237
+ i = len
238
+ else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
239
+ i = endBang + 4
240
+ else
241
+ i = endStd + 3
242
+ continue
243
+ }
244
+
245
+ let pos = lt + 1
246
+ const isClosing = html[pos] === '/'
247
+ if (isClosing)
248
+ pos++
249
+
250
+ const nameStart = pos
251
+ while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
+ const tagName = html.slice(nameStart, pos).toLowerCase()
253
+ if (!tagName) {
254
+ out += '&lt;'
255
+ i = lt + 1
256
+ continue
257
+ }
258
+
259
+ const tagEnd = findTagEndOffset(html, pos)
260
+ if (tagEnd === -1)
261
+ break
262
+
263
+ const attrSrc = html.slice(pos, tagEnd)
264
+ const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
+ i = tagEnd + 1
266
+
267
+ if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
268
+ if (!selfClosing) {
269
+ const closeRe = new RegExp(`</${tagName}\\b[^<>]*>`, 'gi')
270
+ closeRe.lastIndex = i
271
+ const m = closeRe.exec(html)
272
+ i = m ? m.index + m[0].length : len
273
+ }
274
+ continue
275
+ }
276
+
277
+ if (!ALLOWED_MD_TAGS.has(tagName))
278
+ continue
279
+
280
+ if (isClosing) {
281
+ if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
+ out += `</${tagName}>`
283
+ continue
284
+ }
285
+
286
+ const rawAttrs = parseTagAttributes(attrSrc)
287
+ if (tagName === 'input') {
288
+ out += sanitizeInputTag(rawAttrs)
289
+ continue
290
+ }
291
+
292
+ const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
+ const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
294
+ out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
+ }
296
+
297
+ return out
298
+ }
299
+
300
+ export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
301
+ let current = html
302
+ for (let pass = 0; pass < 3; pass++) {
303
+ const next = sanitizePass(current, slotPrefixes)
304
+ if (next === current)
305
+ return next
306
+ current = next
307
+ }
308
+ return current
309
+ }