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.
Files changed (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  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 +94 -136
  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 +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -0,0 +1,101 @@
1
+ // The route patterns `prunelle check` matches internal links against: optional segments expanded, param matchers applied, and templated links (`/posts/${id}`) matched segment by segment.
2
+
3
+ import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../server/param-matchers'
4
+ import { parsePatternSegment } from '../server/param-matchers'
5
+
6
+ export interface DynamicSegment { kind: 'static' | 'param' | 'catchall', value: string, matcherName?: string | undefined, matcher?: ParamMatcher | undefined }
7
+
8
+ export function normalizePathname(raw: string): string {
9
+ const cut = raw.search(/[?#]/)
10
+ const p = cut === -1 ? raw : raw.slice(0, cut)
11
+ return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
12
+ }
13
+
14
+ export function compileDynamicPatterns(pattern: string, matchers: ParamMatcherMap): DynamicSegment[][] {
15
+ const norm = normalizePathname(pattern)
16
+ const parsed: ParsedPatternSegment[] = norm === '/' ? [] : norm.slice(1).split('/').map(parsePatternSegment)
17
+ const optIdx = parsed.flatMap((s, i) => s.kind === 'optional' ? [i] : [])
18
+ if (optIdx.length > 6) return []
19
+ const toSeg = (s: ParsedPatternSegment): DynamicSegment => ({
20
+ kind: s.kind === 'optional' ? 'param' : s.kind, value: s.value, matcherName: s.matcherName,
21
+ matcher: s.matcherName !== undefined ? matchers[s.matcherName] : undefined,
22
+ })
23
+ const variants: DynamicSegment[][] = []
24
+ const expand = (k: number, omitted: Set<number>): void => {
25
+ if (k === optIdx.length) { variants.push(parsed.filter((_, i) => !omitted.has(i)).map(toSeg)); return }
26
+ expand(k + 1, omitted)
27
+ omitted.add(optIdx[k]!)
28
+ expand(k + 1, omitted)
29
+ omitted.delete(optIdx[k]!)
30
+ }
31
+ expand(0, new Set())
32
+ return variants
33
+ }
34
+
35
+ const paramAccepts = (seg: DynamicSegment, value: string): boolean => seg.matcherName === undefined || (seg.matcher !== undefined && seg.matcher(value))
36
+
37
+ export function patternMatchesPrefix(segs: readonly DynamicSegment[], complete: readonly string[], partial: string | undefined): boolean {
38
+ let catchAll: DynamicSegment | undefined
39
+ for (let i = 0; i < complete.length; i++) {
40
+ const part = complete[i]!
41
+ if (catchAll !== undefined) { if (!paramAccepts(catchAll, part)) return false; continue }
42
+ const seg = segs[i]
43
+ if (seg === undefined) return false
44
+ if (seg.kind === 'catchall') { catchAll = seg; if (!paramAccepts(seg, part)) return false }
45
+ else if (seg.kind === 'static' ? seg.value !== part : !paramAccepts(seg, part)) return false
46
+ }
47
+ if (catchAll !== undefined) return true
48
+ const next = segs[complete.length]
49
+ return next !== undefined && (partial === undefined || next.kind !== 'static' || next.value.startsWith(partial))
50
+ }
51
+
52
+ export function staticPrefixOfPattern(pattern: string): string | undefined {
53
+ const norm = normalizePathname(pattern)
54
+ if (norm === '/') return undefined
55
+ const kept: string[] = []
56
+ for (const seg of norm.slice(1).split('/')) {
57
+ if (parsePatternSegment(seg).kind !== 'static') break
58
+ kept.push(seg)
59
+ }
60
+ return kept.length > 0 ? `/${kept.join('/')}` : undefined
61
+ }
62
+
63
+ function segMatchesPattern(tSeg: string, pSeg: DynamicSegment): boolean {
64
+ if (!tSeg.includes('\0')) return pSeg.kind === 'static' ? pSeg.value === tSeg : paramAccepts(pSeg, tSeg)
65
+ if (pSeg.kind !== 'static') return true
66
+ const pieces = tSeg.split('\0')
67
+ let pos = 0
68
+ for (let i = 0; i < pieces.length; i++) {
69
+ const piece = pieces[i]!
70
+ if (piece === '') continue
71
+ if (i === 0 && !pSeg.value.startsWith(piece)) return false
72
+ if (i === pieces.length - 1 && !pSeg.value.endsWith(piece)) return false
73
+ const idx = pSeg.value.indexOf(piece, pos)
74
+ if (idx === -1) return false
75
+ pos = idx + piece.length
76
+ }
77
+ return true
78
+ }
79
+
80
+ export function patternMatchesTemplate(pat: readonly DynamicSegment[], tSegs: readonly string[]): boolean {
81
+ const matchAt = (ti: number, pi: number): boolean => {
82
+ if (ti === tSegs.length && pi === pat.length) return true
83
+ if (pi === pat.length) return false
84
+ const pSeg = pat[pi]!
85
+ if (pSeg.kind === 'catchall') {
86
+ for (let k = ti; k < tSegs.length; k++)
87
+ if (!tSegs[k]!.includes('\0') && !paramAccepts(pSeg, tSegs[k]!)) return false
88
+ return ti < tSegs.length
89
+ }
90
+ if (ti === tSegs.length) return false
91
+ const tSeg = tSegs[ti]!
92
+ if (!tSeg.includes('\0')) return segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)
93
+ if (segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)) return true
94
+ if (tSeg === '\0') {
95
+ for (let nextPi = pi + 2; nextPi <= pat.length; nextPi++)
96
+ if (matchAt(ti + 1, nextPi)) return true
97
+ }
98
+ return false
99
+ }
100
+ return matchAt(0, 0)
101
+ }
@@ -4,7 +4,7 @@ import type { Node, Program } from 'oxc-parser'
4
4
  import type { RouteManifestEntry } from '../build/manifest'
5
5
  import type { ModuleAnalysis } from '../compiler/analyze'
6
6
  import type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, PrunelleConfig, PrunellePlugin, ServerPluginAPI } from '../plugins/index'
7
- import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../server/param-matchers'
7
+ import type { ParamMatcher, ParamMatcherMap } from '../server/param-matchers'
8
8
  import { existsSync, readFileSync, statSync } from 'node:fs'
9
9
  import { basename, resolve } from 'node:path'
10
10
  import { pathToFileURL } from 'node:url'
@@ -14,21 +14,24 @@ import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, SPECIAL_
14
14
  import { walk } from '../compiler/ast'
15
15
  import { calleeName, formatDiagnostic, formatLoc, offsetToLineCol, unwrapTsExpr } from '../compiler/shared'
16
16
  import { createAppContext, I18N_CONFIG_SERVICE, pickRuntimeConfig, runWithAppContext } from '../plugins/index'
17
- import { BUILTIN_PARAM_MATCHERS, extractMatcherFn, parsePatternSegment } from '../server/param-matchers'
17
+ import { BUILTIN_PARAM_MATCHERS, extractMatcherFn } from '../server/param-matchers'
18
+ import { compileDynamicPatterns, type DynamicSegment, normalizePathname, patternMatchesPrefix, patternMatchesTemplate, staticPrefixOfPattern } from './check-links-patterns'
18
19
  import { decodeRequestPath } from '../server/request-path'
20
+ import { type PluginRouteClaim, shadowedPages, shadowMessage } from '../server/plugin-route-shadow'
19
21
  import { Router } from '../server/router'
20
22
 
21
23
  export interface LinkCheckInput {
22
24
  root: string; routesDir: string; publicDir: string; assetPrefix: string; site?: string | undefined
23
25
  config: PrunelleConfig; plugins: readonly PrunellePlugin[]; routeFiles: readonly string[]
24
26
  analyses: ReadonlyMap<string, ModuleAnalysis>; sources: ReadonlyMap<string, string>
27
+ /** Receives the errors found beside the link warnings: a plugin route that hides a page. */
28
+ errors?: string[] | undefined
25
29
  }
26
30
 
27
31
  interface RouteEntry { pattern: string, fileRel?: string | undefined, isDynamic: boolean, knownPaths?: ReadonlySet<string> | undefined, knownPathList?: readonly string[] | undefined }
28
- interface DynamicSegment { kind: 'static' | 'param' | 'catchall', value: string, matcherName?: string | undefined, matcher?: ParamMatcher | undefined }
29
32
  interface LinkTarget { kind: 'exact' | 'prefix' | 'template', value: string, parts?: readonly string[] | undefined, offset: number, parentOffset: number }
30
33
  interface LinkResolver { checkExact: (raw: string) => string | undefined, checkPrefix: (raw: string) => string | undefined, checkTemplate: (parts: readonly string[]) => string | undefined }
31
- interface PluginProbeResult { pluginRoutes: string[], emittedPublic: string[], locales: string[] }
34
+ interface PluginProbeResult { pluginRoutes: string[], claims: PluginRouteClaim[], emittedPublic: string[], locales: string[] }
32
35
 
33
36
  const LINK_ATTRS = new Set(['href', 'action', 'formaction', 'formAction'])
34
37
  const LINK_IGNORE_TOKENS = new Set(['link', 'broken-link', 'link/broken'])
@@ -40,12 +43,6 @@ const MD_LINK_RE = /\[(?:[^\]\\]|\\.|\[[^\]]*\])*\]\(\s*(?:<([^>\n]+)>|([^)\s]+)
40
43
  const MD_HTML_A_RE = /<a\b[^>]*?\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/gi
41
44
  const PROBE_ROUTE: RouteManifestEntry = { path: '/__pru_probe__', file: '__pru_probe__.ts', layouts: [], middlewares: [], islandChunks: [] }
42
45
 
43
- function normalizePathname(raw: string): string {
44
- const cut = raw.search(/[?#]/)
45
- const p = cut === -1 ? raw : raw.slice(0, cut)
46
- return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
47
- }
48
-
49
46
  function decodePathname(raw: string): string {
50
47
  const norm = normalizePathname(raw)
51
48
  const decoded = decodeRequestPath(norm)?.staticPath
@@ -166,7 +163,7 @@ async function probeSinglePlugin(
166
163
  plugin: PrunellePlugin,
167
164
  config: PrunelleConfig,
168
165
  paths: { root: string, outDir: string, assetPrefix: string, site: string | undefined },
169
- state: { routes: string[], emitted: string[], services: Map<string, unknown>, shutdowns: (() => void | Promise<void>)[], provide: <T>(k: { readonly name: string }, v: T) => void },
166
+ state: { routes: string[], claims: PluginRouteClaim[], emitted: string[], services: Map<string, unknown>, shutdowns: (() => void | Promise<void>)[], provide: <T>(k: { readonly name: string }, v: T) => void },
170
167
  ): Promise<void> {
171
168
  const { root, outDir, assetPrefix, site } = paths
172
169
  const inject = <T>(key: { readonly name: string }) => state.services.get(key.name) as T | undefined
@@ -176,10 +173,12 @@ async function probeSinglePlugin(
176
173
  trustProxy: config.trustProxy ?? false, trustedOrigins: config.trustedOrigins ?? [],
177
174
  config: pickRuntimeConfig(config) as Readonly<Record<string, unknown>>,
178
175
  use: (_mw, opts) => { if (plugin.name === '@prunellejs/seo' && typeof opts?.scope === 'string' && opts.scope.startsWith('/')) state.routes.push(opts.scope) },
179
- route: (_method, path) => { state.routes.push(path) },
176
+ route: (method, path) => { state.routes.push(path); state.claims.push({ plugin: plugin.name, method, path }) },
180
177
  rateLimiter: () => ({ hit: () => 0, peek: () => 0 }), rewrite: () => {}, provide: state.provide,
181
178
  inject: key => inject(key) as never, getBuildData: () => undefined, healthCheck: () => {},
182
179
  onShutdown: fn => { state.shutdowns.push(fn) },
180
+ onRequestEnd: () => {},
181
+ surface: () => ({ actions: [], routes: [] }),
183
182
  }
184
183
  await silently(() => plugin.server!(api))
185
184
  }
@@ -205,11 +204,12 @@ async function probePlugins(
205
204
  const services = new Map<string, unknown>()
206
205
  const shutdowns: (() => void | Promise<void>)[] = []
207
206
  const routes: string[] = []
207
+ const claims: PluginRouteClaim[] = []
208
208
  const emitted: string[] = []
209
209
  const provide = <T>(key: { readonly name: string }, value: T): void => { services.set(key.name, value); appCtx.provide(key, value) }
210
210
  try {
211
211
  await runWithAppContext(appCtx, async () => {
212
- for (const plugin of plugins) await probeSinglePlugin(plugin, config, paths, { routes, emitted, services, shutdowns, provide })
212
+ for (const plugin of plugins) await probeSinglePlugin(plugin, config, paths, { routes, claims, emitted, services, shutdowns, provide })
213
213
  })
214
214
  }
215
215
  finally {
@@ -229,7 +229,7 @@ async function probePlugins(
229
229
  }
230
230
  }
231
231
  }
232
- return { pluginRoutes: routes, emittedPublic: emitted, locales: [...locales] }
232
+ return { pluginRoutes: routes, claims, emittedPublic: emitted, locales: [...locales] }
233
233
  }
234
234
 
235
235
  function collectPublicPaths(publicDir: string, emittedPublic: readonly string[]): Set<string> {
@@ -247,95 +247,6 @@ function collectPublicPaths(publicDir: string, emittedPublic: readonly string[])
247
247
  return out
248
248
  }
249
249
 
250
- function compileDynamicPatterns(pattern: string, matchers: ParamMatcherMap): DynamicSegment[][] {
251
- const norm = normalizePathname(pattern)
252
- const parsed: ParsedPatternSegment[] = norm === '/' ? [] : norm.slice(1).split('/').map(parsePatternSegment)
253
- const optIdx = parsed.flatMap((s, i) => s.kind === 'optional' ? [i] : [])
254
- if (optIdx.length > 6) return []
255
- const toSeg = (s: ParsedPatternSegment): DynamicSegment => ({
256
- kind: s.kind === 'optional' ? 'param' : s.kind, value: s.value, matcherName: s.matcherName,
257
- matcher: s.matcherName !== undefined ? matchers[s.matcherName] : undefined,
258
- })
259
- const variants: DynamicSegment[][] = []
260
- const expand = (k: number, omitted: Set<number>): void => {
261
- if (k === optIdx.length) { variants.push(parsed.filter((_, i) => !omitted.has(i)).map(toSeg)); return }
262
- expand(k + 1, omitted)
263
- omitted.add(optIdx[k]!)
264
- expand(k + 1, omitted)
265
- omitted.delete(optIdx[k]!)
266
- }
267
- expand(0, new Set())
268
- return variants
269
- }
270
-
271
- const paramAccepts = (seg: DynamicSegment, value: string): boolean => seg.matcherName === undefined || (seg.matcher !== undefined && seg.matcher(value))
272
-
273
- function patternMatchesPrefix(segs: readonly DynamicSegment[], complete: readonly string[], partial: string | undefined): boolean {
274
- let catchAll: DynamicSegment | undefined
275
- for (let i = 0; i < complete.length; i++) {
276
- const part = complete[i]!
277
- if (catchAll !== undefined) { if (!paramAccepts(catchAll, part)) return false; continue }
278
- const seg = segs[i]
279
- if (seg === undefined) return false
280
- if (seg.kind === 'catchall') { catchAll = seg; if (!paramAccepts(seg, part)) return false }
281
- else if (seg.kind === 'static' ? seg.value !== part : !paramAccepts(seg, part)) return false
282
- }
283
- if (catchAll !== undefined) return true
284
- const next = segs[complete.length]
285
- return next !== undefined && (partial === undefined || next.kind !== 'static' || next.value.startsWith(partial))
286
- }
287
-
288
- function staticPrefixOfPattern(pattern: string): string | undefined {
289
- const norm = normalizePathname(pattern)
290
- if (norm === '/') return undefined
291
- const kept: string[] = []
292
- for (const seg of norm.slice(1).split('/')) {
293
- if (parsePatternSegment(seg).kind !== 'static') break
294
- kept.push(seg)
295
- }
296
- return kept.length > 0 ? `/${kept.join('/')}` : undefined
297
- }
298
-
299
- function segMatchesPattern(tSeg: string, pSeg: DynamicSegment): boolean {
300
- if (!tSeg.includes('\0')) return pSeg.kind === 'static' ? pSeg.value === tSeg : paramAccepts(pSeg, tSeg)
301
- if (pSeg.kind !== 'static') return true
302
- const pieces = tSeg.split('\0')
303
- let pos = 0
304
- for (let i = 0; i < pieces.length; i++) {
305
- const piece = pieces[i]!
306
- if (piece === '') continue
307
- if (i === 0 && !pSeg.value.startsWith(piece)) return false
308
- if (i === pieces.length - 1 && !pSeg.value.endsWith(piece)) return false
309
- const idx = pSeg.value.indexOf(piece, pos)
310
- if (idx === -1) return false
311
- pos = idx + piece.length
312
- }
313
- return true
314
- }
315
-
316
- function patternMatchesTemplate(pat: readonly DynamicSegment[], tSegs: readonly string[]): boolean {
317
- const matchAt = (ti: number, pi: number): boolean => {
318
- if (ti === tSegs.length && pi === pat.length) return true
319
- if (pi === pat.length) return false
320
- const pSeg = pat[pi]!
321
- if (pSeg.kind === 'catchall') {
322
- for (let k = ti; k < tSegs.length; k++)
323
- if (!tSegs[k]!.includes('\0') && !paramAccepts(pSeg, tSegs[k]!)) return false
324
- return ti < tSegs.length
325
- }
326
- if (ti === tSegs.length) return false
327
- const tSeg = tSegs[ti]!
328
- if (!tSeg.includes('\0')) return segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)
329
- if (segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)) return true
330
- if (tSeg === '\0') {
331
- for (let nextPi = pi + 2; nextPi <= pat.length; nextPi++)
332
- if (matchAt(ti + 1, nextPi)) return true
333
- }
334
- return false
335
- }
336
- return matchAt(0, 0)
337
- }
338
-
339
250
  function stripLocale(pathname: string, locales: readonly string[]): string | undefined {
340
251
  const first = locales.length > 0 ? pathname.slice(1).split('/', 1)[0] : undefined
341
252
  return first !== undefined && locales.includes(first) ? (pathname.slice(first.length + 1) || '/') : undefined
@@ -485,6 +396,16 @@ function scanModuleLinks(relFile: string, analysis: ModuleAnalysis, code: string
485
396
  }
486
397
  }
487
398
 
399
+ /** A plugin whose `watchPaths` throws has none to offer: the content check goes on without it. */
400
+ function pluginWatchPaths(plugin: PrunellePlugin, root: string): readonly string[] {
401
+ try {
402
+ return (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths) ?? []
403
+ }
404
+ catch {
405
+ return []
406
+ }
407
+ }
408
+
488
409
  function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[], analyses: ReadonlyMap<string, ModuleAnalysis>): string[] {
489
410
  const dirs = new Set<string>()
490
411
  const addDir = (raw: string): void => {
@@ -493,8 +414,7 @@ function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[]
493
414
  }
494
415
  for (const plugin of plugins) {
495
416
  if (plugin.name !== '@prunellejs/content' || plugin.watchPaths === undefined) continue
496
- try { (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths).forEach(addDir) }
497
- catch {}
417
+ pluginWatchPaths(plugin, root).forEach(addDir)
498
418
  }
499
419
  for (const [file, analysis] of analyses) {
500
420
  if (isInNodeModules(file) || !isInside(root, file)) continue
@@ -605,6 +525,11 @@ export async function checkAppLinks(input: LinkCheckInput): Promise<string[]> {
605
525
  register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList.map(decodePathname)) : undefined, knownPathList })
606
526
  }
607
527
  probe.pluginRoutes.forEach(p => register(p, { pattern: p, isDynamic: p.includes(':') || p.includes('*') }))
528
+ if (input.errors !== undefined) {
529
+ const pages = pageFiles.map(file => ({ path: fileToRoutePath(routesDir, file), file: relPosix(root, file) }))
530
+ for (const shadow of shadowedPages(pages, probe.claims))
531
+ input.errors.push(formatDiagnostic(`${shadow.file}:1:1`, `prunelle check: ${shadowMessage(shadow)}`))
532
+ }
608
533
  if (config.consent !== undefined) {
609
534
  const rawEp = (config.consent.endpoint ?? '/_pru/consent').trim()
610
535
  const ep = rawEp.startsWith('/') ? rawEp : `/${rawEp}`
@@ -0,0 +1,185 @@
1
+ // `prunelle check` rule for `<Region>`: reports static `data-pru-target="<name>"` attributes that name no `<Region name="<name>">` in the project, using parsed JSX AST and scoping dynamic `<Region name={expr}>` to the routes reaching them.
2
+
3
+ import type { JSXAttribute, Node } from 'oxc-parser'
4
+ import type { ModuleGraph } from '../build/graph'
5
+ import type { ModuleAnalysis } from '../compiler/analyze'
6
+ import { isInNodeModules } from '../build/files'
7
+ import { ancestorFiles } from '../build/routes'
8
+ import { walk } from '../compiler/ast'
9
+ import { formatDiagnostic, jsxTagName, resolvePrunelleTag, staticLiteral, unwrapTsExpr } from '../compiler/shared'
10
+
11
+ interface TargetRef {
12
+ file: string
13
+ name: string
14
+ offset: number
15
+ }
16
+
17
+ /** A dynamic `<Region name={expr}>`: `pattern` narrows template literals (e.g. `` `tab-${id}` ``), or `undefined` for arbitrary expressions. */
18
+ interface DynamicRegion {
19
+ pattern: RegExp | undefined
20
+ }
21
+
22
+ function jsxAttrName(attr: JSXAttribute): string {
23
+ return attr.name.type === 'JSXIdentifier' ? attr.name.name : `${attr.name.namespace.name}:${attr.name.name.name}`
24
+ }
25
+
26
+ function jsxStaticString(attr: JSXAttribute): string | undefined {
27
+ if (attr.value === null)
28
+ return undefined
29
+ if (attr.value.type === 'Literal')
30
+ return typeof attr.value.value === 'string' ? attr.value.value : undefined
31
+ if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
32
+ const lit = staticLiteral(attr.value.expression as Node)
33
+ return lit.ok && typeof lit.value === 'string' ? lit.value : undefined
34
+ }
35
+ return undefined
36
+ }
37
+
38
+ function templatePattern(expr: Node): RegExp | undefined {
39
+ const inner = unwrapTsExpr(expr)
40
+ if (inner.type !== 'TemplateLiteral' || inner.expressions.length === 0)
41
+ return undefined
42
+ const parts = inner.quasis.map(q => RegExp.escape(q.value.cooked ?? q.value.raw))
43
+ return new RegExp(`^${parts.join('.*')}$`)
44
+ }
45
+
46
+ function collectFileRegions(
47
+ file: string,
48
+ analysis: ModuleAnalysis,
49
+ staticRegions: Set<string>,
50
+ dynamicByFile: Map<string, DynamicRegion[]>,
51
+ targets: TargetRef[],
52
+ ): void {
53
+ walk(analysis.program, (node) => {
54
+ if (node.type !== 'JSXOpeningElement')
55
+ return
56
+ const tag = jsxTagName(node.name)
57
+ if (resolvePrunelleTag(tag, analysis.imports) === 'Region') {
58
+ let nameAttr: JSXAttribute | undefined
59
+ let hasSpread = false
60
+ for (const attr of node.attributes) {
61
+ if (attr.type === 'JSXSpreadAttribute')
62
+ hasSpread = true
63
+ else if (jsxAttrName(attr) === 'name')
64
+ nameAttr = attr
65
+ }
66
+ if (nameAttr !== undefined) {
67
+ const staticName = jsxStaticString(nameAttr)
68
+ if (staticName !== undefined) {
69
+ staticRegions.add(staticName)
70
+ }
71
+ else {
72
+ const expr = nameAttr.value?.type === 'JSXExpressionContainer' && nameAttr.value.expression.type !== 'JSXEmptyExpression'
73
+ ? nameAttr.value.expression as Node
74
+ : undefined
75
+ const list = dynamicByFile.get(file) ?? []
76
+ list.push({ pattern: expr === undefined ? undefined : templatePattern(expr) })
77
+ dynamicByFile.set(file, list)
78
+ }
79
+ }
80
+ else if (hasSpread) {
81
+ const list = dynamicByFile.get(file) ?? []
82
+ list.push({ pattern: undefined })
83
+ dynamicByFile.set(file, list)
84
+ }
85
+ return
86
+ }
87
+ if (tag !== 'a' && tag !== 'form')
88
+ return
89
+ for (const attr of node.attributes) {
90
+ if (attr.type !== 'JSXAttribute' || jsxAttrName(attr) !== 'data-pru-target')
91
+ continue
92
+ const target = jsxStaticString(attr)
93
+ if (target !== undefined && target !== '')
94
+ targets.push({ file, name: target, offset: attr.start })
95
+ }
96
+ })
97
+ }
98
+
99
+ function reachableFiles(roots: readonly string[], graph: ModuleGraph): Set<string> {
100
+ const seen = new Set<string>(roots)
101
+ const stack = [...roots]
102
+ while (stack.length > 0) {
103
+ const cur = stack.pop()!
104
+ for (const dep of graph.localDeps(cur)) {
105
+ if (!seen.has(dep)) {
106
+ seen.add(dep)
107
+ stack.push(dep)
108
+ }
109
+ }
110
+ }
111
+ return seen
112
+ }
113
+
114
+ function matchesDynamic(name: string, dynamics: readonly DynamicRegion[] | undefined): boolean {
115
+ if (dynamics === undefined)
116
+ return false
117
+ for (const dyn of dynamics) {
118
+ if (dyn.pattern === undefined || dyn.pattern.test(name))
119
+ return true
120
+ }
121
+ return false
122
+ }
123
+
124
+ export function checkRegionTargets(options: {
125
+ graph: ModuleGraph
126
+ routesDir: string
127
+ pageFiles: readonly string[]
128
+ locate: (file: string, offset: number) => string
129
+ }): string[] {
130
+ const { graph, routesDir, pageFiles, locate } = options
131
+ const staticRegions = new Set<string>()
132
+ const dynamicByFile = new Map<string, DynamicRegion[]>()
133
+ const targets: TargetRef[] = []
134
+
135
+ for (const [file, analysis] of graph.analyses) {
136
+ if (isInNodeModules(file) || !file.endsWith('.tsx'))
137
+ continue
138
+ collectFileRegions(file, analysis, staticRegions, dynamicByFile, targets)
139
+ }
140
+
141
+ if (targets.length === 0)
142
+ return []
143
+
144
+ const dynamicsForFile = new Map<string, DynamicRegion[]>()
145
+ const addDynamics = (file: string, list: readonly DynamicRegion[]): void => {
146
+ const existing = dynamicsForFile.get(file) ?? []
147
+ existing.push(...list)
148
+ dynamicsForFile.set(file, existing)
149
+ }
150
+ for (const [file, list] of dynamicByFile)
151
+ addDynamics(file, list)
152
+
153
+ if (dynamicByFile.size > 0) {
154
+ for (const pageFile of pageFiles) {
155
+ const layouts = ancestorFiles(routesDir, pageFile, ['_layout.tsx'])
156
+ const files = reachableFiles([...layouts, pageFile], graph)
157
+ const routeDynamics: { file: string, entry: DynamicRegion }[] = []
158
+ for (const f of files) {
159
+ const list = dynamicByFile.get(f)
160
+ if (list !== undefined) {
161
+ for (const entry of list)
162
+ routeDynamics.push({ file: f, entry })
163
+ }
164
+ }
165
+ if (routeDynamics.length === 0)
166
+ continue
167
+ for (const f of files) {
168
+ const extra = routeDynamics.filter(d => d.file !== f).map(d => d.entry)
169
+ if (extra.length > 0)
170
+ addDynamics(f, extra)
171
+ }
172
+ }
173
+ }
174
+
175
+ const errors: string[] = []
176
+ for (const target of targets) {
177
+ if (staticRegions.has(target.name) || matchesDynamic(target.name, dynamicsForFile.get(target.file)))
178
+ continue
179
+ errors.push(formatDiagnostic(
180
+ locate(target.file, target.offset),
181
+ `[regions] data-pru-target="${target.name}" names no <Region name="${target.name}"> in src/: add the region, or fix the name`,
182
+ ))
183
+ }
184
+ return errors
185
+ }
@@ -103,7 +103,7 @@ export function externalRedirectWarnings(files: readonly string[], read: (file:
103
103
  // Fetch directives whose `'unsafe-inline'` lets an injected script or stylesheet run; `style-src-attr` is left out, as the default policy allows `style=""` attributes.
104
104
  const INLINE_CODE_DIRECTIVES = new Set(['default-src', 'script-src', 'script-src-elem', 'style-src', 'style-src-elem'])
105
105
 
106
- /** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP, or `'unsafe-inline'` in it. */
106
+ /** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP, `'unsafe-inline'` in it, or its Trusted Types. */
107
107
  export function securityConfigWarnings(security: SecurityHeadersOptions | false | undefined): string[] {
108
108
  const at = 'prunelle.config.ts:1:1'
109
109
  if (security === false)
@@ -115,24 +115,68 @@ export function securityConfigWarnings(security: SecurityHeadersOptions | false
115
115
  .map(part => part.trim().split(/\s+/))
116
116
  .filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.some(token => token.toLowerCase() === '\'unsafe-inline\''))
117
117
  .map(([name]) => name!.toLowerCase())
118
- return loose.length === 0
119
- ? []
120
- : [formatDiagnostic(at, `[security/unsafe-inline] the CSP allows 'unsafe-inline' in ${loose.join(', ')}, which lets an injected script or style run: remove it, since prunelle hashes its own inline scripts and styles, or add a hash of the inline one you need.`, 'warning')]
118
+ return [
119
+ ...loose.length === 0 ? [] : [formatDiagnostic(at, `[security/unsafe-inline] the CSP allows 'unsafe-inline' in ${loose.join(', ')}, which lets an injected script or style run: remove it, since prunelle hashes its own inline scripts and styles, or add a hash of the inline one you need.`, 'warning')],
120
+ ...security?.trustedTypes === false ? [formatDiagnostic(at, '[security/trusted-types-off] security.trustedTypes is false, so the browser lets any script write an HTML string into the page, an injected one included: drop it, and write HTML with innerHTML={html} on an element, or through a Trusted Types policy of the app listed with `csp: { \'trusted-types\': [\'my-policy\'] }`.', 'warning')] : [],
121
+ ]
122
+ }
123
+
124
+ // Members that write an HTML string into the page: the browser refuses each one a plain string under `require-trusted-types-for 'script'`.
125
+ const HTML_SINK_PROPERTIES = new Set(['innerHTML', 'outerHTML', 'srcdoc'])
126
+ const HTML_SINK_METHODS = new Set(['insertAdjacentHTML', 'parseFromString', 'createContextualFragment', 'setHTMLUnsafe'])
127
+ const HTML_SINK_HINT = /HTML|srcdoc|parseFromString|createContextualFragment|document\.write/
128
+
129
+ function htmlSinkAt(node: Node): number | undefined {
130
+ if (node.type === 'AssignmentExpression') {
131
+ const target = unwrapTsExpr(node.left as Node)
132
+ return target.type === 'MemberExpression' && !target.computed && target.property.type === 'Identifier' && HTML_SINK_PROPERTIES.has(target.property.name) ? target.start : undefined
133
+ }
134
+ if (node.type !== 'CallExpression')
135
+ return undefined
136
+ const callee = unwrapTsExpr(node.callee)
137
+ if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier')
138
+ return undefined
139
+ const name = callee.property.name
140
+ const onDocument = callee.object.type === 'Identifier' && callee.object.name === 'document' && (name === 'write' || name === 'writeln')
141
+ return HTML_SINK_METHODS.has(name) || onDocument ? callee.start : undefined
142
+ }
143
+
144
+ /** One warning per line of app code writing an HTML string into the page while the CSP requires Trusted Types, which make the browser refuse it. */
145
+ export function htmlSinkWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, security: SecurityHeadersOptions | false | undefined, compliance?: ComplianceConfig | undefined): string[] {
146
+ if (isRuleIgnored('security/html-sink', compliance) || !/require-trusted-types-for/i.test(resolveCspPolicy(security) ?? ''))
147
+ return []
148
+ const warnings: string[] = []
149
+ for (const file of files) {
150
+ const code = read(file)
151
+ if (!HTML_SINK_HINT.test(code))
152
+ continue
153
+ const ignores = parsePrunelleIgnores(code)
154
+ const parsed = parseSync(file, code, { lang: file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts', sourceType: 'module' })
155
+ walk(parsed.program, (node) => {
156
+ const at = htmlSinkAt(node)
157
+ if (at !== undefined && !isIgnoredAt(ignores, 'security/html-sink', at))
158
+ warnings.push(formatDiagnostic(locate(file, at), '[security/html-sink] this writes an HTML string into the page, which the browser refuses under the CSP\'s Trusted Types (`require-trusted-types-for \'script\'`): render it with innerHTML={html} on an element, set plain text with textContent, or pass it through a Trusted Types policy of the app listed with `security: { csp: { \'trusted-types\': [\'my-policy\'] } }`.', 'warning'))
159
+ })
160
+ }
161
+ return warnings
121
162
  }
122
163
 
123
164
  const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
165
+ const VERIFY_WEBHOOK_RE = /\bverifyWebhook\s*\(/
124
166
 
125
- /** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route that does says so with `// prunelle-ignore security/csrf-off` above the export. */
167
+ /** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. A route calling `verifyWebhook()` does; another says so with `// prunelle-ignore security/csrf-off` above the export. */
126
168
  export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, compliance?: ComplianceConfig | undefined): string[] {
127
169
  if (isRuleIgnored('security/csrf-off', compliance))
128
170
  return []
129
171
  const warnings: string[] = []
130
172
  for (const file of files) {
131
173
  const code = read(file)
174
+ if (VERIFY_WEBHOOK_RE.test(code))
175
+ continue
132
176
  const ignores = parsePrunelleIgnores(code)
133
177
  for (const match of code.matchAll(CSRF_OFF_RE)) {
134
178
  if (!isIgnoredAt(ignores, 'security/csrf-off', match.index))
135
- warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
179
+ warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook, checked with `verifyWebhook()` from `prunelle/server`, or a bearer-token API that verifies its token itself, and say so with `// prunelle-ignore security/csrf-off` above the export; drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
136
180
  }
137
181
  }
138
182
  return warnings