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
@@ -4,7 +4,7 @@ import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { RouteManifestEntry } from './manifest'
5
5
  import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, extname, join, resolve } from 'node:path'
7
- import { FORM_TIMESTAMP_FIELD } from '../server/action-protect'
7
+ import { FORM_TIMESTAMP_FIELD, MAX_FORM_AGE_MS } from '../server/action-protect'
8
8
  import { prerenderOrigin } from '../server/prerendered'
9
9
  import { decodeRequestPath } from '../server/request-path'
10
10
  import { inlineStyleHashes, injectMetaCsp } from '../server/security'
@@ -71,7 +71,7 @@ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic:
71
71
  const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
72
72
  const ext = extname(lastSeg).toLowerCase()
73
73
  const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
74
- const inferredExt = !isStatic && !isHtml && ext === '' ? extForContentType(contentType) : ''
74
+ const inferredExt = !isHtml && ext === '' ? extForContentType(contentType) : ''
75
75
  const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
76
76
  const rel = pathname === '/'
77
77
  ? 'index.html'
@@ -226,6 +226,11 @@ export async function prerender(options: PrerenderOptions) {
226
226
  const res = await app.handle(request)
227
227
  const isExplicit404 = u === '/404' && res.status === 404
228
228
  if (res.status !== 200 && !isExplicit404) {
229
+ // An API route (a module with no default export) answering 204 or 405 to GET has nothing to export; only a page answering non-200 fails the export.
230
+ if (isStatic && res.status < 500 && typeof (entry?.modules?.[task.route.file] as { default?: unknown } | undefined)?.default !== 'function') {
231
+ console.warn(`prunelle build --static: skipping API route "${u}" (${routeSource(options, task.route)}) because its GET answered HTTP ${res.status}, so a static host answers 404 for it: give it a GET that answers 200, or ignore this if it is meant for other methods.`)
232
+ continue
233
+ }
229
234
  if (isStatic || res.status >= 500) {
230
235
  failed = true
231
236
  throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
@@ -256,7 +261,7 @@ export async function prerender(options: PrerenderOptions) {
256
261
  continue
257
262
  }
258
263
  failed = true
259
- throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused 24 h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
264
+ throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused ${MAX_FORM_AGE_MS / 3_600_000} h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
260
265
  }
261
266
  writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
262
267
  const hashes = inlineStyleHashes(html)
@@ -7,6 +7,19 @@ import { islandKey } from './islands'
7
7
 
8
8
  const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
9
9
 
10
+ function analysisImportsRegion(analysis: ModuleAnalysis): boolean {
11
+ return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
12
+ }
13
+
14
+ /** True when any analyzed module in the build graph imports `<Region>`. */
15
+ export function graphUsesRegion(graph: ModuleGraph): boolean {
16
+ for (const analysis of graph.analyses.values()) {
17
+ if (analysisImportsRegion(analysis))
18
+ return true
19
+ }
20
+ return false
21
+ }
22
+
10
23
  interface ModuleEdge {
11
24
  source: string
12
25
  specifiers?: readonly { local: string, imported: string }[] | undefined
@@ -92,9 +105,10 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
92
105
  if (chunk === undefined)
93
106
  continue
94
107
  reach.chunks.add(chunk)
95
- const isDeferred = analysis.deferredIslandTags.has(localName)
96
- || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
97
- if (!isDeferred)
108
+ // Each use counts on its own: `$hydrate="load"` is eager whatever the island file says, and a use with no `$hydrate` takes the file's mode.
109
+ const fileLoads = target.defaultHydrate === undefined || target.defaultHydrate === 'load'
110
+ const uses = analysis.hydrateUses.get(localName)
111
+ if (uses === undefined ? fileLoads : [...uses].some(mode => mode === 'load' || (mode === '' && fileLoads)))
98
112
  reach.eager.add(chunk)
99
113
  }
100
114
  return false
@@ -127,7 +141,7 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
127
141
  pruned = addIslandChunks(file, file === root, analysis, reach)
128
142
  if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
129
143
  reach.usesRenderContext = true
130
- if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
144
+ if (atImports && !reach.usesRegion && analysisImportsRegion(analysis))
131
145
  reach.usesRegion = true
132
146
 
133
147
  // The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
@@ -244,7 +244,7 @@ export function formatBundleReport(report: BundleReport): string {
244
244
  }
245
245
  lines.push('', 'First load is what a first visit downloads besides the page\'s HTML: CSS, eager JS and its imports, fonts, images and icons, brotli.')
246
246
  if (hasEco)
247
- lines.push('EcoIndex (A–G, 0–100) scores prerendered pages from DOM elements, first-visit requests and brotli transfer weight, with estimated gCO2e and water per view.')
247
+ lines.push('EcoIndex is a static estimate (A–G, 0–100): it scores prerendered pages from the build\'s HTML and files (DOM elements, first-visit requests, brotli transfer weight), not from a browser visit, with estimated gCO2e and water per view.')
248
248
  if (report.topModules.length > 0) {
249
249
  lines.push('', 'Top modules (minified output bytes):')
250
250
  for (const m of report.topModules.slice(0, 8))
@@ -7,10 +7,14 @@ import pkg from '../../package.json' with { type: 'json' }
7
7
  export const PRUNELLE_SRC_ROOT = resolve(import.meta.dir, '..')
8
8
 
9
9
 
10
+ const JS_SUFFIX_RE = /\.(?:js|jsx|mjs)$/
11
+
10
12
  export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
11
13
  if (specifier.startsWith('.')) {
12
14
  const base = resolve(dirname(fromFile), specifier)
13
- const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
15
+ // NodeNext projects write `./Counter.js` for `Counter.tsx`: the source file stands behind the suffix, as for TypeScript.
16
+ const bare = base.replace(JS_SUFFIX_RE, '')
17
+ const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts'), ...bare === base ? [] : [`${bare}.tsx`, `${bare}.ts`]]
14
18
  for (const c of candidates) {
15
19
  if (statSync(c, { throwIfNoEntry: false })?.isFile())
16
20
  return c
@@ -0,0 +1,16 @@
1
+ // The app's route patterns as types, so `href()`, `RouteContext` and `PageProps` refuse a pattern no route file serves.
2
+
3
+ import { writeKeyTypes } from './key-types'
4
+ import { fileToRoutePattern } from './routes'
5
+
6
+ export const ROUTE_TYPES_FILE = 'prunelle-routes.d.ts'
7
+
8
+ export function writeRouteTypes(root: string, routesDir: string, pageFiles: readonly string[]): void {
9
+ writeKeyTypes(root, routesDir, {
10
+ file: ROUTE_TYPES_FILE,
11
+ header: 'Written by prunelle dev, build and check from the route files: the patterns href(), RouteContext and PageProps accept.',
12
+ module: 'prunelle/server',
13
+ interface: 'PrunelleRoutes',
14
+ keys: pageFiles.map(page => fileToRoutePattern(routesDir, page)),
15
+ })
16
+ }
@@ -5,6 +5,7 @@ import type { ModuleAnalysis } from '../compiler/index'
5
5
  import { existsSync } from 'node:fs'
6
6
  import { basename, dirname, join, relative } from 'node:path'
7
7
  import { parseCacheExport } from '../compiler/cacheability'
8
+ import { ASTRO_GUIDE, NEXT_GUIDE, withGuide } from '../compiler/mistakes'
8
9
  import { parseCacheDuration } from '../server/route-cache'
9
10
  import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
10
11
  import { relPosix } from './files'
@@ -97,8 +98,26 @@ const SPECIAL_FILE_DEFAULTS = new Map([
97
98
  ['_503', '503 status page component'],
98
99
  ])
99
100
 
101
+ // A file or folder name the router cannot match: a parameter beside text (`pre-[id]`), or an optional catch-all (`[[...rest]]`).
102
+ function routeSegmentProblem(file: string, routesRel: string): string | undefined {
103
+ const inside = file.startsWith(`${routesRel}/`) ? file.slice(routesRel.length + 1) : file
104
+ for (const part of inside.replace(TS_EXT_RE, '').split('/')) {
105
+ if (!part.includes('[') || isRouteGroupSegment(part))
106
+ continue
107
+ const optional = OPTIONAL_PARAM_SEG_RE.exec(part)
108
+ if (optional?.[1]?.startsWith('...') === true)
109
+ return `${file} names a route "${part}", an optional catch-all prunelle does not route: name it [${optional[1]}] for the sub-paths and add an index route for the bare path.`
110
+ if (!OPTIONAL_PARAM_SEG_RE.test(part) && !CATCH_ALL_SEG_RE.test(part) && !PARAM_SEG_RE.test(part))
111
+ return `${file} names a route "${part}" that mixes text and a parameter, which the router never matches: make the whole name the parameter (such as [id]), or put the text in a folder (such as pre/[id]).`
112
+ }
113
+ return undefined
114
+ }
115
+
100
116
  /** For a route file or a special route file (`_layout`, `_middleware`, `_error`, `_404`, `_401`, `_403`, `_429`, `_503`), reports missing default export or non-route files. */
101
117
  export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
118
+ const segmentProblem = routeSegmentProblem(file, routesRel)
119
+ if (segmentProblem !== undefined)
120
+ return segmentProblem
102
121
  const name = basename(file)
103
122
  if (SPECIAL_ROUTE_FILES.has(name))
104
123
  return analysis.exportedNames.includes('default') ? undefined : `${file} has no default export: export default its ${SPECIAL_FILE_DEFAULTS.get(name.replace(TS_EXT_RE, ''))}.`
@@ -108,19 +127,20 @@ export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesR
108
127
  const LOAD_FIX = 'prunelle never calls it; export async function load() and read its data with the page\'s load prop'
109
128
  const PATHS_FIX = 'prunelle never calls it; export function paths() returning URL strings such as "/posts/a"'
110
129
  const HEAD_FIX = 'prunelle never reads it; render <Head> in the page'
111
- // Exports other frameworks read from a route file, and what prunelle wants instead.
130
+ // Exports other frameworks read from a route file, and what prunelle wants instead, with the guide for the framework that taught it.
112
131
  const FOREIGN_ROUTE_EXPORTS = new Map([
113
- ['getStaticProps', LOAD_FIX],
114
- ['getServerSideProps', LOAD_FIX],
115
- ['getInitialProps', LOAD_FIX],
132
+ ['getStaticProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
133
+ ['getServerSideProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
134
+ ['getInitialProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
116
135
  ['loader', LOAD_FIX],
117
136
  ['clientLoader', LOAD_FIX],
118
- ['getStaticPaths', PATHS_FIX],
119
- ['generateStaticParams', PATHS_FIX],
120
- ['metadata', HEAD_FIX],
121
- ['generateMetadata', HEAD_FIX],
137
+ ['getStaticPaths', withGuide(PATHS_FIX, ASTRO_GUIDE)],
138
+ ['generateStaticParams', withGuide(PATHS_FIX, NEXT_GUIDE)],
139
+ ['metadata', withGuide(HEAD_FIX, NEXT_GUIDE)],
140
+ ['generateMetadata', withGuide(HEAD_FIX, NEXT_GUIDE)],
122
141
  ['meta', HEAD_FIX],
123
- ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, `prunelle never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`] as const),
142
+ ['revalidate', withGuide('prunelle never reads it; export const cache = \'60s\' (any duration), and call invalidateCache() where the data changes', NEXT_GUIDE)],
143
+ ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, withGuide(`prunelle never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`, ASTRO_GUIDE)] as const),
124
144
  ])
125
145
 
126
146
  function findExportOffset(analysis: ModuleAnalysis, exportName: string): number {
@@ -225,16 +245,23 @@ export function assertPathUrls(urls: unknown, file: string): asserts urls is str
225
245
  }
226
246
  }
227
247
 
228
- export function fileToRoutePath(routesDir: string, file: string): string {
229
- const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
230
- const rawParts = rel.split('/')
248
+ // The URL segments of a route file, in its folder names' bracket form: `(group)` folders and a final `index` dropped.
249
+ function routeSegments(routesDir: string, file: string): string[] {
250
+ const rawParts = relPosix(routesDir, file).replace(TS_EXT_RE, '').split('/')
231
251
  const filePart = rawParts.pop()!
232
252
  const urlParts = rawParts.filter(part => !isRouteGroupSegment(part))
233
253
  if (filePart !== 'index')
234
254
  urlParts.push(filePart)
235
- if (urlParts.length === 0)
236
- return '/'
237
- return `/${urlParts.map(convertRouteSegment).join('/')}`
255
+ return urlParts
256
+ }
257
+
258
+ export function fileToRoutePath(routesDir: string, file: string): string {
259
+ return `/${routeSegments(routesDir, file).map(convertRouteSegment).join('/')}`
260
+ }
261
+
262
+ /** The pattern of a route file as `RouteContext`, `PageProps` and `href()` take it: `/posts/[slug]`. */
263
+ export function fileToRoutePattern(routesDir: string, file: string): string {
264
+ return `/${routeSegments(routesDir, file).join('/')}`
238
265
  }
239
266
 
240
267
  /** The shape two route paths conflict on: parameter names do not matter, but optionality and matcher names do. */
@@ -0,0 +1,65 @@
1
+ // Names each module-level `signal()` and `store()` for the page to seed: the server renders a value an island wrote, and the browser starts from it.
2
+
3
+ import { parseSync } from 'oxc-parser'
4
+
5
+ const CALL_RE = /\b(?:signal|store)\s*\(/
6
+ const TS_LANG_RE = /\.[cm]?ts$/i
7
+ const IMPORT = "import { seedSignal as __pruSeedSignal, seedStore as __pruSeedStore } from 'prunelle/internal/seed';"
8
+
9
+ interface Node { type: string, start: number, end: number, [key: string]: unknown }
10
+
11
+ /** The id a module's signal or store has on the server and in the browser, which agree on the file and the name. */
12
+ export function seedId(file: string, name: string): string {
13
+ return Bun.hash(`${file}#${name}`).toString(36).slice(0, 8)
14
+ }
15
+
16
+ /** Wraps each top-level `const x = signal(…)` or `store(…)` (the two imported from `prunelle`) in the seed call carrying its id. `file` is the project-relative path. */
17
+ export function nameModuleState(code: string, filename: string, file: string, target: 'server' | 'client'): string {
18
+ if (!CALL_RE.test(code))
19
+ return code
20
+ const parsed = parseSync(filename, code, { lang: TS_LANG_RE.test(filename) ? 'ts' : 'tsx', sourceType: 'module' })
21
+ if (parsed.errors.length > 0)
22
+ return code
23
+ const callees = new Map<string, 'signal' | 'store'>()
24
+ for (const stmt of parsed.program.body) {
25
+ if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type' || stmt.source.value !== 'prunelle')
26
+ continue
27
+ for (const spec of stmt.specifiers) {
28
+ if (spec.type !== 'ImportSpecifier' || spec.importKind === 'type' || spec.imported.type !== 'Identifier')
29
+ continue
30
+ if (spec.imported.name === 'signal' || spec.imported.name === 'store')
31
+ callees.set(spec.local.name, spec.imported.name)
32
+ }
33
+ }
34
+ if (callees.size === 0)
35
+ return code
36
+
37
+ const edits: { at: number, text: string }[] = []
38
+ for (const stmt of parsed.program.body) {
39
+ const decl = (stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt) as Node | null | undefined
40
+ if (decl?.type !== 'VariableDeclaration' || decl.kind !== 'const')
41
+ continue
42
+ for (const d of decl.declarations as { id: Node & { name?: string }, init: (Node & { callee?: Node & { name?: string } }) | null }[]) {
43
+ const init = d.init
44
+ if (d.id.type !== 'Identifier' || init?.type !== 'CallExpression' || init.callee?.type !== 'Identifier')
45
+ continue
46
+ const kind = callees.get(init.callee.name!)
47
+ if (kind === undefined)
48
+ continue
49
+ const fn = kind === 'signal' ? '__pruSeedSignal' : '__pruSeedStore'
50
+ // The server names the signal in the errors a write it cannot carry throws; the browser has no use for the name.
51
+ const label = target === 'server' ? `, ${JSON.stringify(`${file}#${d.id.name}`)}` : ''
52
+ edits.push({ at: init.start, text: `${fn}(` }, { at: init.end, text: `, ${JSON.stringify(seedId(file, d.id.name!))}${label})` })
53
+ }
54
+ }
55
+ if (edits.length === 0)
56
+ return code
57
+ edits.sort((a, b) => a.at - b.at)
58
+ let out = ''
59
+ let cursor = 0
60
+ for (const e of edits) {
61
+ out += code.slice(cursor, e.at) + e.text
62
+ cursor = e.at
63
+ }
64
+ return `${out}${code.slice(cursor)}\n${IMPORT}\n`
65
+ }
@@ -0,0 +1,111 @@
1
+ // Tells whether the page could need seeds at all: only an app where some module writes state another module made, outside an event handler, ships the helper that carries it to the browser.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/analyze'
4
+ import type { ModuleGraph } from './graph'
5
+ import { walk } from '../compiler/ast'
6
+ import { isInNodeModules } from './files'
7
+
8
+ const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'add', 'delete', 'clear', 'assign'])
9
+ // What runs after the render: a handler, or the callback of one of these.
10
+ const LATER_CALLS = new Set(['onMount', 'effect', 'onCleanup'])
11
+
12
+ type Loose = Record<string, any>
13
+
14
+ // `cart.lines[0].qty` is rooted at `cart`.
15
+ function rootName(node: Loose | null | undefined): string | undefined {
16
+ let cur = node
17
+ while (cur != null) {
18
+ if (cur.type === 'Identifier')
19
+ return cur.name
20
+ if (cur.type === 'MemberExpression')
21
+ cur = cur.object
22
+ else if (cur.type === 'ChainExpression' || cur.type === 'ParenthesizedExpression')
23
+ cur = cur.expression
24
+ else if (cur.type === 'TSNonNullExpression' || cur.type === 'TSAsExpression')
25
+ cur = cur.expression
26
+ else
27
+ return undefined
28
+ }
29
+ return undefined
30
+ }
31
+
32
+ /** True when the module writes, outside a handler, `onMount` or `effect`, state it imports or made at its top level; aliases and bare hand-overs count too, so a doubt answers true. */
33
+ function writesState(analysis: ModuleAnalysis, graph: Pick<ModuleGraph, 'analyses' | 'resolve'>): boolean {
34
+ const roots = new Set<string>()
35
+ for (const imp of analysis.imports) {
36
+ const target = graph.analyses.get(graph.resolve(analysis.filename, imp.source) ?? '')
37
+ if (target === undefined)
38
+ continue
39
+ // A barrel re-exports state under names its own file does not hold.
40
+ for (const spec of imp.specifiers) {
41
+ if (spec.imported === '*' || target.reexports.length > 0 || target.stateExports.includes(spec.imported))
42
+ roots.add(spec.local)
43
+ }
44
+ }
45
+ for (const stmt of analysis.program.body as Loose[]) {
46
+ const decl = (stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt) as Loose | null
47
+ for (const d of decl?.type === 'VariableDeclaration' ? decl.declarations as Loose[] : []) {
48
+ if (d.id.type === 'Identifier' && d.init?.type === 'CallExpression' && (d.init.callee.name === 'signal' || d.init.callee.name === 'store'))
49
+ roots.add(d.id.name)
50
+ }
51
+ }
52
+ if (roots.size === 0)
53
+ return false
54
+ let found = false
55
+ walk(analysis.program, (n) => {
56
+ if (found)
57
+ return false
58
+ const node = n as unknown as Loose
59
+ switch (node.type) {
60
+ case 'JSXAttribute': {
61
+ const name = node.name.type === 'JSXIdentifier' ? node.name.name as string : ''
62
+ const value = node.value?.expression as Loose | undefined
63
+ if (/^on[A-Z]/.test(name) && (value?.type === 'ArrowFunctionExpression' || value?.type === 'FunctionExpression'))
64
+ return false
65
+ return undefined
66
+ }
67
+ case 'CallExpression': {
68
+ const callee = node.callee as Loose
69
+ if (callee.type === 'Identifier' && LATER_CALLS.has(callee.name))
70
+ return false
71
+ const base = rootName(callee.type === 'MemberExpression' ? callee.object : undefined)
72
+ if (callee.type === 'MemberExpression' && base !== undefined && roots.has(base) && MUTATORS.has(callee.property?.name))
73
+ found = true
74
+ if ((node.arguments as Loose[]).some(a => a.type === 'Identifier' && roots.has(a.name)))
75
+ found = true
76
+ return undefined
77
+ }
78
+ case 'AssignmentExpression':
79
+ found = rootName(node.left) !== undefined && roots.has(rootName(node.left)!)
80
+ return undefined
81
+ case 'UpdateExpression':
82
+ found = rootName(node.argument) !== undefined && roots.has(rootName(node.argument)!)
83
+ return undefined
84
+ case 'UnaryExpression':
85
+ if (node.operator === 'delete')
86
+ found = rootName(node.argument) !== undefined && roots.has(rootName(node.argument)!)
87
+ return undefined
88
+ case 'JSXExpressionContainer':
89
+ if (node.expression.type === 'Identifier' && roots.has(node.expression.name))
90
+ found = true
91
+ return undefined
92
+ case 'VariableDeclarator': {
93
+ const root = rootName(node.init)
94
+ if (node.id.type === 'Identifier' && root !== undefined && roots.has(root))
95
+ roots.add(node.id.name)
96
+ return undefined
97
+ }
98
+ default:
99
+ return undefined
100
+ }
101
+ })
102
+ return found
103
+ }
104
+
105
+ /** Whether a module of the app could write module-level state while an island renders on the server. */
106
+ export function writesModuleState(graph: Pick<ModuleGraph, 'analyses' | 'resolve'>): boolean {
107
+ const files = [...graph.analyses].filter(([file]) => !isInNodeModules(file))
108
+ if (!files.some(([, a]) => a.stateExports.length > 0))
109
+ return false
110
+ return files.some(([, a]) => writesState(a, graph))
111
+ }
@@ -3,7 +3,7 @@
3
3
  import type { SecurityHeadersOptions } from '../server/security'
4
4
  import { existsSync, readFileSync, writeFileSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
- import { buildSecurityHeaderEntries, resolveHstsValue } from '../server/security'
6
+ import { buildSecurityHeaderEntries, resolveHstsValue, withoutCspReports } from '../server/security'
7
7
 
8
8
  export const CADDY_SNIPPET = 'prunelle.caddy'
9
9
  export const NGINX_SNIPPET = 'prunelle.nginx.conf'
@@ -51,7 +51,7 @@ export function parseRedirects(text: string): StaticRedirect[] {
51
51
 
52
52
  function headerEntries(security: SecurityHeadersOptions | false | undefined): [string, string][] {
53
53
  const entries: [string, string][] = []
54
- for (const [name, value] of buildSecurityHeaderEntries(security)) {
54
+ for (const [name, value] of buildSecurityHeaderEntries(withoutCspReports(security))) {
55
55
  if (name !== 'content-security-policy') {
56
56
  entries.push([name, value])
57
57
  continue
@@ -177,7 +177,7 @@ export async function emitStaticNotFoundPages(options: StaticNotFoundOptions): P
177
177
  renderError ??= err
178
178
  }
179
179
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
180
- const navigation = createNavigation(options.entry.prunelleConfig.navigation)
180
+ const navigation = createNavigation(options.entry.prunelleConfig.navigation, options.entry.prunelleConfig.assetPrefix)
181
181
  const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
182
182
  const routesPrefix = inferRoutesServerPrefix(options.manifest)
183
183
  const paramMatchers = resolveParamMatchers(options.manifest.paramMatchers, options.entry.modules)
@@ -0,0 +1,51 @@
1
+ // `prunelle check` rules on the route cache: a tag `invalidateCache()` drops that no route declares.
2
+
3
+ import { parseSync } from 'oxc-parser'
4
+ import { walk } from '../compiler/ast'
5
+ import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
6
+
7
+ /** One warning per `invalidateCache({ tag })` naming a tag outside `declared`, the tags of every route's `export const cache`. */
8
+ export function unknownCacheTagWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, declared: ReadonlySet<string>): string[] {
9
+ const warnings: string[] = []
10
+ for (const file of files) {
11
+ const code = read(file)
12
+ if (!code.includes('invalidateCache'))
13
+ continue
14
+ const parsed = parseSync(file, code, { lang: file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts', sourceType: 'module' })
15
+ const names = new Set<string>()
16
+ for (const stmt of parsed.program.body) {
17
+ if (stmt.type !== 'ImportDeclaration' || stmt.source.value !== 'prunelle/server')
18
+ continue
19
+ for (const spec of stmt.specifiers) {
20
+ if (spec.type === 'ImportSpecifier' && (spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value) === 'invalidateCache')
21
+ names.add(spec.local.name)
22
+ }
23
+ }
24
+ if (names.size === 0)
25
+ continue
26
+ walk(parsed.program, (node) => {
27
+ if (node.type !== 'CallExpression')
28
+ return
29
+ const callee = unwrapTsExpr(node.callee)
30
+ if (callee.type !== 'Identifier' || !names.has(callee.name))
31
+ return
32
+ for (const arg of node.arguments) {
33
+ const tag = arg.type === 'ObjectExpression' ? staticTag(arg) : undefined
34
+ if (tag !== undefined && !declared.has(tag))
35
+ warnings.push(formatDiagnostic(locate(file, arg.start), `[cache/unknown-tag] invalidateCache() drops the tag "${tag}", which no route declares, so it drops nothing: add it to the \`tags\` of a route's \`export const cache\`, or fix its name.`, 'warning'))
36
+ }
37
+ })
38
+ }
39
+ return warnings
40
+ }
41
+
42
+ function staticTag(object: Extract<ReturnType<typeof unwrapTsExpr>, { type: 'ObjectExpression' }>): string | undefined {
43
+ for (const prop of object.properties) {
44
+ if (prop.type !== 'Property' || prop.computed || prop.key.type !== 'Identifier' || prop.key.name !== 'tag')
45
+ continue
46
+ const value = unwrapTsExpr(prop.value)
47
+ if (value.type === 'Literal' && typeof value.value === 'string')
48
+ return value.value
49
+ }
50
+ return undefined
51
+ }
@@ -0,0 +1,95 @@
1
+ // `prunelle check` warnings about the cookies an app sets: a banner nobody can reopen, a cookie set before the visitor chose, and one `<CookieTable>` cannot describe.
2
+
3
+ import type { Argument, ObjectExpression } from 'oxc-parser'
4
+ import type { ComplianceConfig } from '../compiler/compliance'
5
+ import { parseSync } from 'oxc-parser'
6
+ import { walk } from '../compiler/ast'
7
+ import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
8
+ import { isCookieSet, mergeCookies, scanCookieSets, unreadableFields } from '../compiler/cookie-inventory'
9
+ import { formatDiagnostic } from '../compiler/shared'
10
+
11
+ type Read = (file: string) => string
12
+ type Locate = (file: string, offset: number) => string
13
+
14
+ const BANNER_RE = /<ConsentBanner\b/g
15
+ const PREFERENCES_RE = /<ConsentPreferences\b/
16
+
17
+
18
+ /** The warnings about the app's cookies: those about its `consent` config only when it has one. */
19
+ export function cookieWarnings(consentConfigured: boolean, files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
20
+ const consent = consentConfigured ? [...consentPreferencesWarnings(files, read, locate, compliance), ...cookieCategoryWarnings(files, read, locate, compliance)] : []
21
+ return [...consent, ...cookiePurposeWarnings(files, read, locate, compliance)]
22
+ }
23
+
24
+ /** One warning at the first `<ConsentBanner>` when no file renders `<ConsentPreferences>`: the banner is gone once the visitor chose, so nothing lets them change it. */
25
+ export function consentPreferencesWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
26
+ if (isRuleIgnored('rgpd/consent-preferences', compliance))
27
+ return []
28
+ const sources = files.map(file => ({ file, code: read(file) }))
29
+ if (sources.some(({ code }) => PREFERENCES_RE.test(code)))
30
+ return []
31
+ for (const { file, code } of sources) {
32
+ const ignores = parsePrunelleIgnores(code)
33
+ for (const match of code.matchAll(BANNER_RE)) {
34
+ if (!isIgnoredAt(ignores, 'rgpd/consent-preferences', match.index))
35
+ return [formatDiagnostic(locate(file, match.index), '[rgpd/consent-preferences] <ConsentBanner> asks for consent but no page renders <ConsentPreferences>, so a visitor cannot change or withdraw their choice afterwards, and the CNIL asks withdrawing to be as easy as consenting: add <ConsentPreferences /> to the cookie policy page and link it from the footer.', 'warning')]
36
+ }
37
+ }
38
+ return []
39
+ }
40
+
41
+
42
+ function hasCategory(options: ObjectExpression): boolean {
43
+ return options.properties.some((prop) => {
44
+ if (prop.type !== 'Property' || prop.computed)
45
+ return false
46
+ return (prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? prop.key.value : undefined) === 'category'
47
+ })
48
+ }
49
+
50
+ // Options held in a variable or spread into the object cannot be read, so they may hold the category.
51
+ function lacksCategory(options: Argument | undefined): boolean {
52
+ if (options === undefined)
53
+ return true
54
+ return options.type === 'ObjectExpression' && options.properties.every(prop => prop.type === 'Property') && !hasCategory(options)
55
+ }
56
+
57
+ /** A warning at each cookie set with no `category` while `consent` is configured: it counts as essential, so it is set before the visitor chose. */
58
+ export function cookieCategoryWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
59
+ if (isRuleIgnored('rgpd/cookie-category', compliance))
60
+ return []
61
+ const warnings: string[] = []
62
+ for (const file of files) {
63
+ const code = read(file)
64
+ if (!code.includes('cookies'))
65
+ continue
66
+ const ignores = parsePrunelleIgnores(code)
67
+ if (ignores.fileRules.has('rgpd/cookie-category'))
68
+ continue
69
+ walk(parseSync(file, code, { lang: file.endsWith('x') ? 'tsx' : 'ts' }).program, (node): undefined => {
70
+ if (node.type !== 'CallExpression' || !isCookieSet(node.callee) || !lacksCategory(node.arguments[2]) || isIgnoredAt(ignores, 'rgpd/cookie-category', node.start))
71
+ return undefined
72
+ const name = node.arguments[0]
73
+ const literal = name?.type === 'Literal' && typeof name.value === 'string' ? name.value : undefined
74
+ warnings.push(formatDiagnostic(locate(file, node.start), `[rgpd/cookie-category] ${literal === undefined ? 'a cookie' : `cookie "${literal}"`} is set without a category while consent is configured, so it is set before the visitor chose anything: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`, 'warning'))
75
+ return undefined
76
+ })
77
+ }
78
+ return warnings
79
+ }
80
+
81
+ /** A warning at each cookie whose name, purpose, category or lifetime cannot be read from the source, so `<CookieTable>` cannot list it whole. */
82
+ export function cookiePurposeWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
83
+ if (isRuleIgnored('rgpd/cookie-purpose', compliance))
84
+ return []
85
+ const sources = files.map(file => ({ file, code: read(file) }))
86
+ const ignoresOf = new Map(sources.map(({ file, code }) => [file, parsePrunelleIgnores(code)]))
87
+ const warnings: string[] = []
88
+ for (const cookie of mergeCookies(sources.flatMap(({ file, code }) => scanCookieSets(file, code)))) {
89
+ const missing = unreadableFields(cookie)
90
+ if (missing.length === 0 || isIgnoredAt(ignoresOf.get(cookie.file)!, 'rgpd/cookie-purpose', cookie.start))
91
+ continue
92
+ warnings.push(formatDiagnostic(locate(cookie.file, cookie.start), `[rgpd/cookie-purpose] prunelle cannot read the ${missing.join(' and ')} of ${cookie.name === undefined ? 'a cookie' : `cookie "${cookie.name}"`}, which a cookie policy must give, so <CookieTable> shows [to fill in] in its place: write it as a literal in the options of cookies.set, such as { purpose: 'Keeps the chosen theme.', maxAge: 31536000 }.`, 'warning'))
93
+ }
94
+ return warnings
95
+ }
@@ -15,12 +15,13 @@ import { resolveExportTarget } from '../build/island-promote'
15
15
  import { isInside } from '../build/is-inside'
16
16
  import { resolvePrunelleSpecifier } from '../build/resolve'
17
17
  import { walk } from '../compiler/ast'
18
+ import { hasOpaqueChild } from './form-opaque-children'
18
19
  import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
19
20
  import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
20
21
  import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
21
22
  import { closestName } from '../plugins/config'
22
23
  import { isServerAction } from '../server/action'
23
- import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
24
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName, MAX_FORM_AGE_MS } from '../server/action-protect'
24
25
  import { extractFormSchema, isRecord, lookupFieldConstraint } from '../server/form-schema'
25
26
 
26
27
  export interface FormCheckInput {
@@ -382,11 +383,18 @@ function collectFormFields(formNode: JSXElement, enclosingRoot: Node, rootFile:
382
383
  const analysis = graph.analyses.get(file)
383
384
  if (analysis === undefined) return
384
385
 
386
+ if (!externalOnly && Array.isArray(target) && hasOpaqueChild(target, analysis.program)) hasOpaqueFields = true
387
+
385
388
  walk(target, (node) => {
389
+ if (node.type === 'JSXFragment') {
390
+ if (!externalOnly && hasOpaqueChild(node.children, analysis.program)) hasOpaqueFields = true
391
+ return undefined
392
+ }
386
393
  if (node.type !== 'JSXElement') return undefined
387
394
  if (node === formNode) return false
388
395
  const tag = jsxTagName(node.openingElement.name)
389
396
  if (!externalOnly && tag === 'form') return false
397
+ if (!externalOnly && tag !== 'select' && hasOpaqueChild(node.children, analysis.program)) hasOpaqueFields = true
390
398
 
391
399
  if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
392
400
  const match = controlFormMatch(node.openingElement.attributes, propsScope, formId, hasDynamicId, externalOnly)
@@ -589,7 +597,7 @@ function frozenTimestampErrors(form: CollectedForm, pages: readonly string[], gr
589
597
  const analysis = graph.analyses.get(page)
590
598
  const frozenBy = analysis?.hasPrerender === true ? 'prerender = true' : analysis?.cache !== undefined ? 'cache' : undefined
591
599
  if (frozenBy === undefined) continue
592
- errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused 24 h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
600
+ errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused ${MAX_FORM_AGE_MS / 3_600_000} h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
593
601
  }
594
602
  return errors
595
603
  }