prunelle 0.1.1 → 0.6.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 (120) hide show
  1. package/llms.txt +130 -38
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +92 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +81 -0
  75. package/src/plugins/types.ts +34 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +131 -32
  90. package/src/server/index.ts +231 -261
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,561 @@
1
+ // Static form validation for `prunelle check` and `prunelle build`:
2
+ // - Checks `<form action={fn}>` fields against the action's Standard Schema JSON Schema (unknown fields, missing required fields, `<select>` enum options)
3
+ // - Warns once per schema vendor lacking JSON Schema output
4
+ // - Warns on unguarded public form actions without `protect` / `rateLimit` / `_middleware.ts`
5
+
6
+ import type { JSXAttribute, JSXElement, Node, Program } from 'oxc-parser'
7
+ import type { ModuleGraph } from '../build/graph'
8
+ import type { ModuleAnalysis } from '../compiler/analyze'
9
+ import type { ServerAction } from '../server/action'
10
+ import { readFileSync } from 'node:fs'
11
+ import { basename, dirname } from 'node:path'
12
+ import { isInNodeModules, isTsFile, relPosix } from '../build/files'
13
+ import { isInside } from '../build/is-inside'
14
+ import { resolvePrunelleSpecifier } from '../build/resolve'
15
+ import { walk } from '../compiler/ast'
16
+ import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
17
+ import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
18
+ import { closestName } from '../plugins/config'
19
+ import { isServerAction } from '../server/action'
20
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
21
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
22
+
23
+ export interface FormCheckInput {
24
+ root: string
25
+ routesDir: string
26
+ routeFiles: readonly string[]
27
+ graph: ModuleGraph
28
+ /** Optional pre-read source map (falls back to `graph.source(file)`). */
29
+ sources?: ReadonlyMap<string, string> | undefined
30
+ }
31
+
32
+ export interface FormCheckResult {
33
+ errors: string[]
34
+ warnings: string[]
35
+ }
36
+
37
+ interface ActionRef { file: string, exportName: string }
38
+ interface SelectOptionInfo { value: string, file: string, offset: number }
39
+ interface CollectedField { name: string, tag: string, file: string, offset: number, options?: SelectOptionInfo[] | undefined }
40
+ interface CollectedForm { action: ActionRef, file: string, offset: number, fields: CollectedField[], hasOpaqueFields: boolean }
41
+ interface PropsScope { bindings: ReadonlyMap<string, string>, propsParam?: string | undefined, destructured: ReadonlyMap<string, string> }
42
+ interface ModuleActionResolver { resolveExpr(node: Node): ActionRef | undefined }
43
+
44
+ const PRUNELLE_SPECIFIER_RE = /^prunelle(?:\/|$)/
45
+ const EMPTY_MAP: ReadonlyMap<string, string> = new Map()
46
+ const EMPTY_PROPS_SCOPE: PropsScope = { bindings: EMPTY_MAP, destructured: EMPTY_MAP }
47
+ const UI_FORM_CONTROL_TAGS = new Set(['Checkbox', 'RadioGroup', 'Switch', 'Select'])
48
+ const NON_INPUT_UI_TAGS = new Set([
49
+ 'Button', 'Icon', 'Stack', 'Cluster', 'Notice', 'Badge', 'Card', 'CardHeader', 'CardBody', 'CardFooter',
50
+ 'Divider', 'Spinner', 'Field', 'Grid', 'Sidebar', 'Split', 'Accordion', 'AccordionItem', 'Popover', 'Progress',
51
+ 'Tabs', 'Dialog', 'ControlledDialog', 'Drawer', 'ControlledDrawer', 'Menu', 'DataTable', 'CommandPalette',
52
+ 'Toaster', 'Alert', 'Tooltip', 'Separator', 'Spacer', 'Box', 'Flex', 'Container', 'Heading', 'Text', 'Avatar',
53
+ 'Skeleton', 'Image', 'Picture', 'Link',
54
+ ])
55
+
56
+ async function tryDirectImport(file: string, hash: string): Promise<Record<string, unknown> | undefined> {
57
+ try { return await import(`${file}?pru-form=${hash}`) as Record<string, unknown> }
58
+ catch { return undefined }
59
+ }
60
+
61
+ async function loadActionModule(file: string, cache: Map<string, Record<string, unknown> | null>): Promise<Record<string, unknown> | undefined> {
62
+ if (cache.has(file)) return cache.get(file) ?? undefined
63
+
64
+ let hash = '0'
65
+ try { hash = Bun.hash(readFileSync(file)).toString(36) }
66
+ catch { cache.set(file, null); return undefined }
67
+
68
+ const direct = await tryDirectImport(file, hash)
69
+ if (direct !== undefined) { cache.set(file, direct); return direct }
70
+
71
+ try {
72
+ const built = await Bun.build({
73
+ entrypoints: [file],
74
+ target: 'bun',
75
+ plugins: [{
76
+ name: 'prunelle-form-check-resolve',
77
+ setup(b) {
78
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_RE }, (args) => {
79
+ const resolved = resolvePrunelleSpecifier(args.path)
80
+ return resolved !== undefined ? { path: resolved, external: true } : undefined
81
+ })
82
+ },
83
+ }],
84
+ })
85
+ const output = built.outputs[0]
86
+ if (!built.success || output === undefined) { cache.set(file, null); return undefined }
87
+ const js = await output.text()
88
+ const mod = await import(`data:text/javascript;base64,${Buffer.from(js, 'utf8').toString('base64')}`) as Record<string, unknown>
89
+ cache.set(file, mod)
90
+ return mod
91
+ }
92
+ catch { cache.set(file, null); return undefined }
93
+ }
94
+
95
+ function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
96
+ const analysis = graph.analyses.get(target.file)
97
+ return analysis !== undefined && analysis.exportedActions.includes(target.exportName)
98
+ }
99
+
100
+ function safeExportTarget(graph: ModuleGraph, file: string, exportName: string, depth = 0): ActionRef {
101
+ const analysis = depth > 16 ? undefined : graph.analyses.get(file)
102
+ if (analysis === undefined) return { file, exportName }
103
+ const direct = analysis.reexports.find(r => r.exported === exportName)
104
+ if (direct !== undefined) {
105
+ const next = graph.resolve(file, direct.source)
106
+ if (next !== undefined && isTsFile(next)) return safeExportTarget(graph, next, direct.local, depth + 1)
107
+ }
108
+ if (analysis.exportedNames.includes(exportName) || exportName === 'default') return { file, exportName }
109
+ for (const re of analysis.reexports) {
110
+ if (re.exported !== '*') continue
111
+ const next = graph.resolve(file, re.source)
112
+ if (next !== undefined && isTsFile(next) && graph.analyses.has(next)) {
113
+ const resolved = safeExportTarget(graph, next, exportName, depth + 1)
114
+ if (graph.analyses.get(resolved.file)?.exportedNames.includes(resolved.exportName)) return resolved
115
+ }
116
+ }
117
+ return { file, exportName }
118
+ }
119
+
120
+ function createActionResolver(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): ModuleActionResolver {
121
+ const directActions = new Map<string, ActionRef>()
122
+ const namespaceImports = new Map<string, string>()
123
+ const useActionVars = new Map<string, ActionRef>()
124
+ const useActionCallees = new Set<string>()
125
+ const prunelleNamespaces = new Set<string>()
126
+
127
+ for (const name of analysis.exportedActions)
128
+ directActions.set(name, { file, exportName: name })
129
+
130
+ for (const imp of analysis.imports) {
131
+ if (imp.source === 'prunelle') {
132
+ for (const spec of imp.specifiers) {
133
+ if (spec.imported === 'useAction') useActionCallees.add(spec.local)
134
+ else if (spec.imported === '*') prunelleNamespaces.add(spec.local)
135
+ }
136
+ continue
137
+ }
138
+ const target = graph.resolve(file, imp.source)
139
+ if (target === undefined || !isTsFile(target) || !graph.analyses.has(target)) continue
140
+ for (const spec of imp.specifiers) {
141
+ if (spec.imported === '*') { namespaceImports.set(spec.local, target); continue }
142
+ const resolved = safeExportTarget(graph, target, spec.imported)
143
+ if (isExportedAction(graph, resolved)) directActions.set(spec.local, resolved)
144
+ }
145
+ }
146
+
147
+ const resolveBase = (node: Node): ActionRef | undefined => {
148
+ const inner = unwrapTsExpr(node)
149
+ if (inner.type === 'Identifier') return directActions.get(inner.name)
150
+ if (inner.type === 'MemberExpression' && !inner.computed && inner.object.type === 'Identifier' && inner.property.type === 'Identifier') {
151
+ if (inner.property.name === 'action' && useActionVars.has(inner.object.name))
152
+ return useActionVars.get(inner.object.name)
153
+ const nsFile = namespaceImports.get(inner.object.name)
154
+ if (nsFile !== undefined) {
155
+ const resolved = safeExportTarget(graph, nsFile, inner.property.name)
156
+ if (isExportedAction(graph, resolved)) return resolved
157
+ }
158
+ }
159
+ return undefined
160
+ }
161
+
162
+ const isUseActionCall = (node: Node): boolean => {
163
+ if (node.type !== 'CallExpression') return false
164
+ const name = calleeName(node.callee)
165
+ return useActionCallees.has(name) || (name.endsWith('.useAction') && prunelleNamespaces.has(name.slice(0, -'.useAction'.length)))
166
+ }
167
+
168
+ walk(analysis.program, (node) => {
169
+ if (node.type !== 'VariableDeclarator' || node.init === null) return
170
+ const init = unwrapTsExpr(node.init)
171
+ if (isUseActionCall(init) && init.type === 'CallExpression' && init.arguments.length >= 1) {
172
+ const arg = init.arguments[0]
173
+ const target = arg !== undefined && arg.type !== 'SpreadElement' ? resolveBase(arg) : undefined
174
+ if (target === undefined) return
175
+ if (node.id.type === 'Identifier') { useActionVars.set(node.id.name, target); return }
176
+ if (node.id.type === 'ObjectPattern') {
177
+ for (const prop of node.id.properties) {
178
+ if (prop.type === 'Property' && !prop.computed && prop.key.type === 'Identifier' && prop.key.name === 'action' && prop.value.type === 'Identifier')
179
+ directActions.set(prop.value.name, target)
180
+ }
181
+ }
182
+ return
183
+ }
184
+ if (node.id.type === 'Identifier') {
185
+ const ref = resolveBase(init)
186
+ if (ref !== undefined) directActions.set(node.id.name, ref)
187
+ }
188
+ })
189
+
190
+ return { resolveExpr: resolveBase }
191
+ }
192
+
193
+ function findAttr(attrs: readonly JSXElement['openingElement']['attributes'][number][], name: string): JSXAttribute | undefined {
194
+ for (const attr of attrs)
195
+ if (attr.type === 'JSXAttribute' && jsxTagName(attr.name).toLowerCase() === name) return attr
196
+ return undefined
197
+ }
198
+
199
+ function extractPropsScope(fnNode: Node, bindings: ReadonlyMap<string, string>): PropsScope {
200
+ if (bindings.size === 0) return EMPTY_PROPS_SCOPE
201
+ const inner = unwrapTsExpr(fnNode)
202
+ if (inner.type !== 'FunctionDeclaration' && inner.type !== 'FunctionExpression' && inner.type !== 'ArrowFunctionExpression')
203
+ return EMPTY_PROPS_SCOPE
204
+ const rawFirst = inner.params[0]
205
+ if (rawFirst === undefined) return EMPTY_PROPS_SCOPE
206
+ const first = rawFirst.type === 'AssignmentPattern' ? rawFirst.left : rawFirst
207
+ if (first.type === 'Identifier') return { bindings, propsParam: first.name, destructured: EMPTY_MAP }
208
+ if (first.type !== 'ObjectPattern') return EMPTY_PROPS_SCOPE
209
+ const destructured = new Map<string, string>()
210
+ for (const prop of first.properties) {
211
+ if (prop.type !== 'Property' || prop.computed) continue
212
+ const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' && typeof prop.key.value === 'string' ? prop.key.value : undefined
213
+ const val = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
214
+ if (key !== undefined && val.type === 'Identifier') destructured.set(val.name, key)
215
+ }
216
+ return { bindings, destructured }
217
+ }
218
+
219
+ function resolveStaticStringAttr(attr: JSXAttribute | undefined, props: PropsScope): { known: true, value: string } | { known: false } {
220
+ if (attr === undefined || attr.value === null) return { known: false }
221
+ if (attr.value.type === 'Literal' && typeof attr.value.value === 'string') return { known: true, value: attr.value.value }
222
+ if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
223
+ const expr = unwrapTsExpr(attr.value.expression)
224
+ const lit = staticLiteralOrTemplate(expr)
225
+ if (lit.ok && typeof lit.value === 'string') return { known: true, value: lit.value }
226
+ if (expr.type === 'Identifier') {
227
+ const propKey = props.destructured.get(expr.name)
228
+ if (propKey !== undefined && props.bindings.has(propKey)) return { known: true, value: props.bindings.get(propKey)! }
229
+ }
230
+ if (expr.type === 'MemberExpression' && !expr.computed && expr.object.type === 'Identifier' && props.propsParam !== undefined && expr.object.name === props.propsParam && expr.property.type === 'Identifier' && props.bindings.has(expr.property.name))
231
+ return { known: true, value: props.bindings.get(expr.property.name)! }
232
+ }
233
+ return { known: false }
234
+ }
235
+
236
+ function isKnownNonInputExternal(tag: string, attrs: readonly JSXElement['openingElement']['attributes'][number][], analysis: ModuleAnalysis): boolean {
237
+ const hasNameAttr = findAttr(attrs, 'name') !== undefined
238
+ const dotIdx = tag.indexOf('.')
239
+ for (const imp of analysis.imports) {
240
+ if (imp.source.startsWith('.') || imp.source.startsWith('/')) continue
241
+ for (const spec of imp.specifiers) {
242
+ let importedName: string | undefined
243
+ if (dotIdx === -1 && spec.local === tag && spec.imported !== '*')
244
+ importedName = spec.imported === 'default' ? tag : spec.imported
245
+ else if (dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx))
246
+ importedName = tag.slice(dotIdx + 1)
247
+ if (importedName === undefined) continue
248
+ if (imp.source === '@prunellejs/icons' || imp.source.startsWith('@prunellejs/icons/') || imp.source === '@prunellejs/images' || imp.source.startsWith('@prunellejs/images/'))
249
+ return true
250
+ if (imp.source === '@prunellejs/ui' || imp.source.startsWith('@prunellejs/ui/'))
251
+ return !UI_FORM_CONTROL_TAGS.has(importedName) && (importedName !== 'Button' || !hasNameAttr)
252
+ return (NON_INPUT_UI_TAGS.has(importedName) || NON_INPUT_UI_TAGS.has(tag)) && (importedName !== 'Button' || !hasNameAttr)
253
+ }
254
+ }
255
+ return false
256
+ }
257
+
258
+ function findLocalComponentNode(program: Program, localName: string): Node | undefined {
259
+ for (const stmt of program.body) {
260
+ if (stmt.type === 'ExportDefaultDeclaration' && localName === 'default')
261
+ return unwrapTsExpr(stmt.declaration)
262
+ const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
263
+ if (decl?.type === 'FunctionDeclaration' && decl.id?.name === localName) return decl
264
+ if (decl?.type === 'VariableDeclaration') {
265
+ for (const d of decl.declarations)
266
+ if (d.id.type === 'Identifier' && d.id.name === localName && d.init !== null) return unwrapTsExpr(d.init)
267
+ }
268
+ }
269
+ return undefined
270
+ }
271
+
272
+ function resolveComponentTarget(
273
+ tag: string,
274
+ file: string,
275
+ analysis: ModuleAnalysis,
276
+ graph: ModuleGraph,
277
+ ): { file: string, node: Node, key: string } | undefined {
278
+ const local = findLocalComponentNode(analysis.program, tag)
279
+ if (local !== undefined) return { file, node: local, key: `${file}\0${tag}` }
280
+
281
+ const dotIdx = tag.indexOf('.')
282
+ for (const imp of analysis.imports) {
283
+ const targetFile = graph.resolve(file, imp.source)
284
+ if (targetFile === undefined || !isTsFile(targetFile) || !graph.analyses.has(targetFile)) continue
285
+ for (const spec of imp.specifiers) {
286
+ const exported = dotIdx === -1 && spec.local === tag && spec.imported !== '*'
287
+ ? spec.imported
288
+ : dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx)
289
+ ? tag.slice(dotIdx + 1)
290
+ : undefined
291
+ if (exported === undefined) continue
292
+ const resolved = graph.exportTarget(targetFile, exported)
293
+ const targetAnalysis = graph.analyses.get(resolved.file)
294
+ if (targetAnalysis === undefined) continue
295
+ const localName = targetAnalysis.exportLocals.get(resolved.exportName) ?? resolved.exportName
296
+ const fnNode = findLocalComponentNode(targetAnalysis.program, localName)
297
+ if (fnNode !== undefined) return { file: resolved.file, node: fnNode, key: `${resolved.file}\0${localName}` }
298
+ }
299
+ }
300
+ return undefined
301
+ }
302
+
303
+ function collectSelectOptions(selectEl: JSXElement, file: string): SelectOptionInfo[] {
304
+ const options: SelectOptionInfo[] = []
305
+ walk(selectEl.children, (node) => {
306
+ if (node.type !== 'JSXElement') return undefined
307
+ const tag = jsxTagName(node.openingElement.name)
308
+ if (tag === 'select') return false
309
+ if (tag !== 'option') return undefined
310
+ const valueAttr = findAttr(node.openingElement.attributes, 'value')
311
+ if (valueAttr !== undefined) {
312
+ if (valueAttr.value?.type === 'Literal' && typeof valueAttr.value.value === 'string') {
313
+ options.push({ value: valueAttr.value.value, file, offset: valueAttr.start })
314
+ }
315
+ else if (valueAttr.value?.type === 'JSXExpressionContainer' && valueAttr.value.expression.type !== 'JSXEmptyExpression') {
316
+ const lit = staticLiteralOrTemplate(valueAttr.value.expression)
317
+ if (lit.ok && (typeof lit.value === 'string' || typeof lit.value === 'number'))
318
+ options.push({ value: String(lit.value), file, offset: valueAttr.start })
319
+ }
320
+ return false
321
+ }
322
+ const text = staticOptionText(node.children)
323
+ if (text !== undefined) options.push({ value: text, file, offset: node.start })
324
+ return false
325
+ })
326
+ return options
327
+ }
328
+
329
+ function collectFormFields(formNode: JSXElement, rootFile: string, graph: ModuleGraph): { fields: CollectedField[], hasOpaqueFields: boolean } {
330
+ const fields: CollectedField[] = []
331
+ let hasOpaqueFields = false
332
+
333
+ const visitTree = (target: Node | readonly Node[], file: string, propsScope: PropsScope, visited: ReadonlySet<string>): void => {
334
+ const analysis = graph.analyses.get(file)
335
+ if (analysis === undefined) return
336
+
337
+ walk(target, (node) => {
338
+ if (node.type !== 'JSXElement') return undefined
339
+ const tag = jsxTagName(node.openingElement.name)
340
+ if (tag === 'form') return false
341
+
342
+ if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
343
+ const attrs = node.openingElement.attributes
344
+ const nameAttr = findAttr(attrs, 'name')
345
+ const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
346
+ if (tag === 'button') {
347
+ if (nameAttr === undefined) return undefined
348
+ const typeVal = resolveStaticStringAttr(findAttr(attrs, 'type'), propsScope)
349
+ if (typeVal.known && (typeVal.value.toLowerCase() === 'button' || typeVal.value.toLowerCase() === 'reset')) return undefined
350
+ }
351
+ if (nameAttr === undefined) {
352
+ if (hasSpread && tag !== 'button') hasOpaqueFields = true
353
+ return undefined
354
+ }
355
+ const resolvedName = resolveStaticStringAttr(nameAttr, propsScope)
356
+ if (!resolvedName.known) { hasOpaqueFields = true; return undefined }
357
+ if (resolvedName.value !== '') {
358
+ fields.push({
359
+ name: resolvedName.value,
360
+ tag,
361
+ file,
362
+ offset: nameAttr.start,
363
+ ...(tag === 'select' ? { options: collectSelectOptions(node, file) } : {}),
364
+ })
365
+ }
366
+ return tag === 'select' ? false : undefined
367
+ }
368
+
369
+ if (isComponentTag(tag)) {
370
+ if (node.children.length > 0) visitTree(node.children, file, propsScope, visited)
371
+ if (resolvePrunelleTag(tag, analysis.imports) !== undefined) return false
372
+ const resolved = resolveComponentTarget(tag, file, analysis, graph)
373
+ if (resolved === undefined) {
374
+ if (!isKnownNonInputExternal(tag, node.openingElement.attributes, analysis)) hasOpaqueFields = true
375
+ return false
376
+ }
377
+ if (visited.has(resolved.key)) return false
378
+ const nextBindings = new Map<string, string>()
379
+ for (const attr of node.openingElement.attributes) {
380
+ if (attr.type !== 'JSXAttribute') continue
381
+ const val = resolveStaticStringAttr(attr, propsScope)
382
+ if (val.known) nextBindings.set(jsxTagName(attr.name), val.value)
383
+ }
384
+ const nextVisited = new Set(visited)
385
+ nextVisited.add(resolved.key)
386
+ visitTree(resolved.node, resolved.file, extractPropsScope(resolved.node, nextBindings), nextVisited)
387
+ return false
388
+ }
389
+
390
+ return undefined
391
+ })
392
+ }
393
+
394
+ visitTree(formNode.children, rootFile, EMPTY_PROPS_SCOPE, new Set())
395
+ return { fields, hasOpaqueFields }
396
+ }
397
+
398
+ function collectModuleForms(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): CollectedForm[] {
399
+ const resolver = createActionResolver(file, analysis, graph)
400
+ const forms: CollectedForm[] = []
401
+
402
+ walk(analysis.program, (node) => {
403
+ if (node.type !== 'JSXElement' || jsxTagName(node.openingElement.name) !== 'form') return undefined
404
+ const actionAttr = findAttr(node.openingElement.attributes, 'action')
405
+ if (actionAttr?.value?.type !== 'JSXExpressionContainer' || actionAttr.value.expression.type === 'JSXEmptyExpression') return undefined
406
+ const actionRef = resolver.resolveExpr(actionAttr.value.expression)
407
+ if (actionRef === undefined) return undefined
408
+ const { fields, hasOpaqueFields } = collectFormFields(node, file, graph)
409
+ forms.push({ action: actionRef, file, offset: node.start, fields, hasOpaqueFields })
410
+ return undefined
411
+ })
412
+
413
+ return forms
414
+ }
415
+
416
+ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[], graph: ModuleGraph) {
417
+ const middlewareDirs = new Set<string>()
418
+ const layoutByDir = new Map<string, string>()
419
+ const pageRouteSet = new Set<string>()
420
+ for (const file of routeFiles) {
421
+ const base = basename(file)
422
+ if (base === '_middleware.ts' || base === '_middleware.tsx') middlewareDirs.add(dirname(file))
423
+ else if (base === '_layout.tsx') layoutByDir.set(dirname(file), file)
424
+ else if (!base.startsWith('_') && graph.analyses.get(file)?.exportedNames.includes('default')) pageRouteSet.add(file)
425
+ }
426
+
427
+ const walkAncestorDirs = (file: string, onDir: (dir: string) => boolean | void): boolean => {
428
+ if (!isInside(routesDir, file)) return false
429
+ let dir = dirname(file)
430
+ while (true) {
431
+ if (onDir(dir) === true) return true
432
+ if (dir === routesDir) return false
433
+ const parent = dirname(dir)
434
+ if (parent === dir || !isInside(routesDir, parent, { orSame: true })) return false
435
+ dir = parent
436
+ }
437
+ }
438
+
439
+ const hasAncestorMiddleware = (file: string): boolean => walkAncestorDirs(file, dir => middlewareDirs.has(dir))
440
+
441
+ const importers = new Map<string, Set<string>>()
442
+ const addImporter = (dep: string, owner: string): void => {
443
+ let set = importers.get(dep)
444
+ if (set === undefined) { set = new Set(); importers.set(dep, set) }
445
+ set.add(owner)
446
+ }
447
+ for (const file of graph.analyses.keys())
448
+ for (const dep of graph.localDeps(file)) addImporter(dep, file)
449
+ for (const page of pageRouteSet) {
450
+ walkAncestorDirs(page, (dir) => {
451
+ const layout = layoutByDir.get(dir)
452
+ if (layout !== undefined) addImporter(layout, page)
453
+ })
454
+ }
455
+
456
+ const isOnPublicPage = (file: string): boolean => {
457
+ const seen = new Set<string>([file])
458
+ const queue = [file]
459
+ for (let i = 0; i < queue.length; i++) {
460
+ const cur = queue[i]!
461
+ if (pageRouteSet.has(cur) && !hasAncestorMiddleware(cur)) return true
462
+ for (const parent of importers.get(cur) ?? [])
463
+ if (!seen.has(parent)) { seen.add(parent); queue.push(parent) }
464
+ }
465
+ return false
466
+ }
467
+
468
+ return { hasAncestorMiddleware, isOnPublicPage }
469
+ }
470
+
471
+ function checkFormAgainstAction(
472
+ form: CollectedForm,
473
+ act: ServerAction<unknown, unknown>,
474
+ locAt: (file: string, offset: number) => string,
475
+ warnedVendors: Set<string>,
476
+ errors: string[],
477
+ warnings: string[],
478
+ ): void {
479
+ const { exportName } = form.action
480
+ if (act.schema === undefined) return
481
+
482
+ const extracted = extractFormSchema(act.schema)
483
+ if (!extracted.ok) {
484
+ if (!warnedVendors.has(extracted.vendor)) {
485
+ warnedVendors.add(extracted.vendor)
486
+ warnings.push(formatDiagnostic(locAt(form.file, form.offset), `[form/schema-unsupported] Action "${exportName}" uses a "${extracted.vendor}" schema that has no JSON Schema output; form field checks skipped.`, 'warning'))
487
+ }
488
+ return
489
+ }
490
+
491
+ const hpField = honeypotFieldName(act.protect)
492
+ const knownFields = [...extracted.fields.keys()]
493
+ const checkUnknown = extracted.fields.size > 0 || extracted.jsonSchema.additionalProperties === false
494
+ const sentFields = new Set<string>()
495
+
496
+ for (const field of form.fields) {
497
+ if (field.name === FORM_TIMESTAMP_FIELD || (hpField !== undefined && field.name === hpField)) continue
498
+ const normalized = field.name.endsWith('[]') ? field.name.slice(0, -2) : field.name
499
+ sentFields.add(field.name)
500
+ sentFields.add(normalized)
501
+
502
+ const constraint = lookupFieldConstraint(extracted.fields, field.name)
503
+ if (constraint === undefined && checkUnknown) {
504
+ const near = closestName(normalized, knownFields)
505
+ const hint = near !== undefined ? `did you mean "${near}"?` : knownFields.length > 0 ? `known fields: ${knownFields.join(', ')}.` : 'the schema accepts no fields.'
506
+ errors.push(formatDiagnostic(locAt(field.file, field.offset), `[form/unknown-field] Form field "${field.name}" does not exist on action "${exportName}"'s schema: ${hint}`, 'error'))
507
+ continue
508
+ }
509
+
510
+ if (field.options !== undefined && constraint?.enumValues !== undefined && constraint.enumValues.length > 0) {
511
+ const allowed = new Set(constraint.enumValues)
512
+ for (const opt of field.options) {
513
+ if (opt.value === '' || allowed.has(opt.value)) continue
514
+ warnings.push(formatDiagnostic(locAt(opt.file, opt.offset), `[form/invalid-option] <option value="${opt.value}"> on <select name="${field.name}"> is not allowed by action "${exportName}"'s schema (allowed: ${constraint.enumValues.join(', ')}).`, 'warning'))
515
+ }
516
+ }
517
+ }
518
+
519
+ if (!form.hasOpaqueFields) {
520
+ const sentList = [...sentFields]
521
+ for (const reqField of extracted.required) {
522
+ if (sentFields.has(reqField)) continue
523
+ const near = closestName(reqField, sentList)
524
+ const hint = near !== undefined ? ` (found "${near}")` : ''
525
+ errors.push(formatDiagnostic(locAt(form.file, form.offset), `[form/missing-field] Form bound to action "${exportName}" never sends required schema field "${reqField}"${hint}.`, 'error'))
526
+ }
527
+ }
528
+ }
529
+
530
+ /** Checks every `<form action={fn}>` across the app against its action's schema and public protection config. */
531
+ export async function checkAppForms(input: FormCheckInput): Promise<FormCheckResult> {
532
+ const { root, routesDir, routeFiles, graph, sources } = input
533
+ const errors: string[] = []
534
+ const warnings: string[] = []
535
+ const moduleCache = new Map<string, Record<string, unknown> | null>()
536
+ const warnedVendors = new Set<string>()
537
+ const { hasAncestorMiddleware, isOnPublicPage } = buildMiddlewareLookup(routesDir, routeFiles, graph)
538
+
539
+ const sourceOf = (file: string): string => sources?.get(file) ?? graph.source(file)
540
+ const locAt = (targetFile: string, offset: number): string => formatLoc(relPosix(root, targetFile), sourceOf(targetFile), offset)
541
+
542
+ for (const [file, analysis] of graph.analyses) {
543
+ if (isInNodeModules(file) || !file.endsWith('.tsx') || !analysis.hasJsx) continue
544
+ const forms = collectModuleForms(file, analysis, graph)
545
+ if (forms.length === 0) continue
546
+
547
+ const publicPage = isOnPublicPage(file)
548
+ for (const form of forms) {
549
+ const mod = await loadActionModule(form.action.file, moduleCache)
550
+ const act = mod?.[form.action.exportName]
551
+ if (!isServerAction(act)) continue
552
+
553
+ checkFormAgainstAction(form, act, locAt, warnedVendors, errors, warnings)
554
+
555
+ if (publicPage && !hasAncestorMiddleware(form.action.file) && act.protect === undefined && act.rateLimit === undefined)
556
+ warnings.push(formatDiagnostic(locAt(form.file, form.offset), `[action/unguarded-public-form] Public form action "${form.action.exportName}" has no protection: add { protect: { rateLimit, honeypot, minTime } } to action() or guard it with _middleware.ts.`, 'warning'))
557
+ }
558
+ }
559
+
560
+ return { errors, warnings }
561
+ }