prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,505 @@
1
+ // Runs Prunelle's single-file compiler & compliance checks and maps them to TypeScript diagnostics.
2
+
3
+ import type { Node, Program } from 'oxc-parser'
4
+ import type ts from 'typescript'
5
+ import type { ModuleAnalysis } from '../compiler/analyze'
6
+ import type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
7
+ import type { PrunelleFixDescriptor } from './fixes'
8
+ import { existsSync, readFileSync, statSync } from 'node:fs'
9
+ import { basename, dirname, join, resolve } from 'node:path'
10
+ import { parseSync } from 'oxc-parser'
11
+ import { isInNodeModules, relPosix } from '../build/files'
12
+ import { nodeEnvWarning } from '../build/render-rules'
13
+ import { analyzeModule, parseTsx } from '../compiler/analyze'
14
+ import { walk } from '../compiler/ast'
15
+ import { parseCacheExport } from '../compiler/cacheability'
16
+ import { shouldEmitWarning } from '../compiler/compliance'
17
+ import { clientReach } from '../compiler/interactivity'
18
+ import { collectMistakes, PrunelleMistake } from '../compiler/mistakes'
19
+ import { findPrivateEnv, isServerOnlyModule } from '../compiler/server-only'
20
+ import { unwrapTsExpr } from '../compiler/shared'
21
+ import { checkBareSignals } from '../compiler/signal-reads'
22
+ import { classifyMistakeFix, classifyWarningFix, PRUNELLE_CODE } from './fixes'
23
+
24
+ export const PRUNELLE_DIAG_SOURCE = 'prunelle'
25
+
26
+ const TS_EXT_RE = /\.[cm]?tsx?$/i
27
+ const DTS_EXT_RE = /\.d\.[cm]?ts$/i
28
+ const SIGNAL_HINT_RE = /\b(?:signal|computed)\b/
29
+ const EMPTY_SET: ReadonlySet<string> = new Set()
30
+ const REL_EXTS = ['', '.ts', '.tsx', '/index.ts', '/index.tsx']
31
+ const TOKEN_RE = /^[A-Za-z_$][\w$-]*(?::[A-Za-z_$][\w$-]*)?|^'[^'\r\n]*'|^"[^"\r\n]*"|^<[A-Za-z_$][\w$.-]*/
32
+
33
+ export interface PrunellePluginOptions {
34
+ projectRoot?: string | undefined
35
+ compliance?: ComplianceConfig | undefined
36
+ site?: string | undefined
37
+ /** Optional file reader (e.g. from ts.LanguageServiceHost) used to resolve imported signal exports. */
38
+ readFile?: ((path: string) => string | undefined) | undefined
39
+ }
40
+
41
+ export interface PrunelleDiagnosticItem {
42
+ code: number
43
+ category: 'error' | 'warning'
44
+ start: number
45
+ length: number
46
+ message: string
47
+ fix?: PrunelleFixDescriptor | undefined
48
+ }
49
+
50
+ interface StaticConfigCache {
51
+ mtimeMs: number
52
+ site?: string | undefined
53
+ compliance?: ComplianceConfig | undefined
54
+ }
55
+
56
+ const configCache = new Map<string, StaticConfigCache>()
57
+
58
+ /** True when `fileName` is a project `.ts`/`.tsx` source file eligible for Prunelle analysis. */
59
+ export function isCheckableFile(fileName: string): boolean {
60
+ return TS_EXT_RE.test(fileName) && !DTS_EXT_RE.test(fileName) && !isInNodeModules(fileName)
61
+ }
62
+
63
+ function propKeyName(node: Node): string | undefined {
64
+ if (node.type === 'Identifier')
65
+ return node.name
66
+ if (node.type === 'Literal' && typeof node.value === 'string')
67
+ return node.value
68
+ return undefined
69
+ }
70
+
71
+ function staticString(node: Node): string | undefined {
72
+ const inner = unwrapTsExpr(node)
73
+ if (inner.type === 'Literal' && typeof inner.value === 'string')
74
+ return inner.value
75
+ return undefined
76
+ }
77
+
78
+ function extractConfigObject(program: Program): Extract<Node, { type: 'ObjectExpression' }> | undefined {
79
+ for (const stmt of program.body) {
80
+ if (stmt.type !== 'ExportDefaultDeclaration')
81
+ continue
82
+ const decl = unwrapTsExpr(stmt.declaration)
83
+ if (decl.type === 'ObjectExpression')
84
+ return decl
85
+ if (decl.type === 'CallExpression' && decl.arguments[0] !== undefined) {
86
+ const arg = unwrapTsExpr(decl.arguments[0])
87
+ if (arg.type === 'ObjectExpression')
88
+ return arg
89
+ }
90
+ }
91
+ return undefined
92
+ }
93
+
94
+ function parseStaticCompliance(node: Node): ComplianceConfig | undefined {
95
+ const obj = unwrapTsExpr(node)
96
+ if (obj.type !== 'ObjectExpression')
97
+ return undefined
98
+ const out: ComplianceConfig = {}
99
+ for (const prop of obj.properties) {
100
+ if (prop.type !== 'Property')
101
+ continue
102
+ const key = propKeyName(prop.key)
103
+ const val = unwrapTsExpr(prop.value)
104
+ if (key === 'publicBody' && val.type === 'Literal' && typeof val.value === 'boolean') {
105
+ out.publicBody = val.value
106
+ }
107
+ else if (key === 'legalNotice' && val.type === 'Literal' && (val.value === false || typeof val.value === 'string')) {
108
+ out.legalNotice = val.value
109
+ }
110
+ else if (key === 'ignore' && val.type === 'ArrayExpression') {
111
+ const rules: ComplianceRule[] = []
112
+ for (const el of val.elements) {
113
+ if (el !== null && el.type !== 'SpreadElement') {
114
+ const s = staticString(el)
115
+ if (s !== undefined)
116
+ rules.push(s as ComplianceRule)
117
+ }
118
+ }
119
+ out.ignore = rules
120
+ }
121
+ }
122
+ return out
123
+ }
124
+
125
+ /** Statically parses `site` and `compliance` literals from `prunelle.config.ts` without executing user code. */
126
+ export function readStaticProjectConfig(projectRoot: string | undefined): { site?: string | undefined, compliance?: ComplianceConfig | undefined } {
127
+ if (projectRoot === undefined || projectRoot === '')
128
+ return {}
129
+ const cfgPath = join(projectRoot, 'prunelle.config.ts')
130
+ if (!existsSync(cfgPath))
131
+ return {}
132
+ let mtimeMs: number
133
+ try {
134
+ mtimeMs = statSync(cfgPath).mtimeMs
135
+ }
136
+ catch {
137
+ return {}
138
+ }
139
+ const cached = configCache.get(cfgPath)
140
+ if (cached !== undefined && cached.mtimeMs === mtimeMs)
141
+ return { site: cached.site, compliance: cached.compliance }
142
+
143
+ let site: string | undefined
144
+ let compliance: ComplianceConfig | undefined
145
+ try {
146
+ const code = readFileSync(cfgPath, 'utf8')
147
+ const parsed = parseSync(cfgPath, code, { lang: 'ts', sourceType: 'module' })
148
+ const obj = parsed.errors.length === 0 ? extractConfigObject(parsed.program) : undefined
149
+ if (obj !== undefined) {
150
+ for (const prop of obj.properties) {
151
+ if (prop.type !== 'Property')
152
+ continue
153
+ const key = propKeyName(prop.key)
154
+ if (key === 'site')
155
+ site = staticString(prop.value)
156
+ else if (key === 'compliance')
157
+ compliance = parseStaticCompliance(prop.value)
158
+ }
159
+ }
160
+ }
161
+ catch {
162
+ return {}
163
+ }
164
+ configCache.set(cfgPath, { mtimeMs, site, compliance })
165
+ return { site, compliance }
166
+ }
167
+
168
+ function indexNodesAtOffsets(program: Program, offsets: ReadonlySet<number>): Map<number, Node[]> {
169
+ const byOffset = new Map<number, Node[]>()
170
+ if (offsets.size === 0)
171
+ return byOffset
172
+ walk(program, (node) => {
173
+ if (!offsets.has(node.start))
174
+ return
175
+ let list = byOffset.get(node.start)
176
+ if (list === undefined) {
177
+ list = []
178
+ byOffset.set(node.start, list)
179
+ }
180
+ list.push(node)
181
+ })
182
+ return byOffset
183
+ }
184
+
185
+ function clampSingleLine(code: string, start: number, end: number): { start: number, length: number } {
186
+ const safeStart = Math.max(0, Math.min(start, code.length))
187
+ const safeEnd = Math.max(safeStart, Math.min(end, code.length))
188
+ const nl = code.indexOf('\n', safeStart)
189
+ const effectiveEnd = nl !== -1 && nl < safeEnd ? nl : safeEnd
190
+ return { start: safeStart, length: Math.max(1, effectiveEnd - safeStart) }
191
+ }
192
+
193
+ function spanFromNodes(nodes: readonly Node[], code: string, start: number): { start: number, length: number } {
194
+ for (const node of nodes) {
195
+ if (node.type === 'JSXAttribute')
196
+ return clampSingleLine(code, node.start, node.end)
197
+ if (node.type === 'JSXElement') {
198
+ const opening = node.openingElement
199
+ const hasNewline = code.slice(opening.start, opening.end).includes('\n')
200
+ return clampSingleLine(code, opening.start, hasNewline ? opening.name.end : opening.end)
201
+ }
202
+ if (node.type === 'JSXOpeningElement') {
203
+ const hasNewline = code.slice(node.start, node.end).includes('\n')
204
+ return clampSingleLine(code, node.start, hasNewline ? node.name.end : node.end)
205
+ }
206
+ if (node.type === 'ImportDeclaration' || node.type === 'ImportSpecifier' || node.type === 'ExpressionStatement' || node.type === 'Literal' || node.type === 'MemberExpression' || node.type === 'Identifier' || node.type === 'CallExpression' || node.type === 'VariableDeclarator')
207
+ return clampSingleLine(code, node.start, node.end)
208
+ if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression')
209
+ return clampSingleLine(code, node.start, node.end)
210
+ }
211
+ const safeStart = Math.max(0, Math.min(start, Math.max(0, code.length - 1)))
212
+ const match = TOKEN_RE.exec(code.slice(safeStart))
213
+ const length = match !== null ? match[0].length : Math.min(1, Math.max(0, code.length - safeStart))
214
+ return { start: safeStart, length: Math.max(1, length) }
215
+ }
216
+
217
+ function normalizeDisplayPath(fileName: string, projectRoot: string | undefined): string {
218
+ if (projectRoot === undefined || projectRoot === '')
219
+ return fileName
220
+ const rel = relPosix(projectRoot, fileName)
221
+ return rel !== '' ? rel : fileName
222
+ }
223
+
224
+ function mergeCompliance(base: ComplianceConfig | undefined, override: ComplianceConfig | undefined): ComplianceConfig | undefined {
225
+ if (base === undefined)
226
+ return override
227
+ if (override === undefined)
228
+ return base
229
+ return {
230
+ ignore: override.ignore ?? base.ignore,
231
+ publicBody: override.publicBody ?? base.publicBody,
232
+ legalNotice: override.legalNotice ?? base.legalNotice,
233
+ }
234
+ }
235
+
236
+ function resolveRelativeSource(fromFile: string, specifier: string, readFile: (path: string) => string | undefined): { path: string, code: string } | undefined {
237
+ const base = resolve(dirname(fromFile), specifier)
238
+ const stripped = base.replace(/\.[cm]?js$/i, '')
239
+ for (const ext of REL_EXTS) {
240
+ const candidate = `${stripped}${ext}`
241
+ if (!TS_EXT_RE.test(candidate))
242
+ continue
243
+ const code = readFile(candidate)
244
+ if (code !== undefined)
245
+ return { path: candidate, code }
246
+ }
247
+ return undefined
248
+ }
249
+
250
+ function collectImportedSignalMistakes(
251
+ fileName: string,
252
+ program: Program,
253
+ imports: readonly { source: string, specifiers: readonly { local: string, imported: string }[] }[],
254
+ readFile: ((path: string) => string | undefined) | undefined,
255
+ ): PrunelleMistake[] {
256
+ if (readFile === undefined)
257
+ return []
258
+ const importedSignals = new Set<string>()
259
+ const importedSignalMembers = new Map<string, Set<string>>()
260
+ for (const imp of imports) {
261
+ if (!imp.source.startsWith('./') && !imp.source.startsWith('../'))
262
+ continue
263
+ const resolved = resolveRelativeSource(fileName, imp.source, readFile)
264
+ if (resolved === undefined || !SIGNAL_HINT_RE.test(resolved.code))
265
+ continue
266
+ let depProgram: Program
267
+ try {
268
+ depProgram = parseTsx(resolved.path, resolved.code)
269
+ }
270
+ catch {
271
+ continue
272
+ }
273
+ const { value: dep } = collectMistakes(() => analyzeModule(resolved.path, resolved.code, depProgram))
274
+ if (dep === undefined || dep.signalExports.length === 0)
275
+ continue
276
+ const exported = new Set(dep.signalExports)
277
+ for (const spec of imp.specifiers) {
278
+ if (spec.imported === '*') {
279
+ importedSignalMembers.set(spec.local, exported)
280
+ }
281
+ else if (exported.has(spec.imported)) {
282
+ importedSignals.add(spec.local)
283
+ }
284
+ }
285
+ }
286
+ if (importedSignals.size === 0 && importedSignalMembers.size === 0)
287
+ return []
288
+ return collectMistakes(() => checkBareSignals(program, EMPTY_SET, fileName, importedSignals, importedSignalMembers)).mistakes
289
+ }
290
+
291
+ const SPECIAL_SERVER_FILES = new Set(['_layout.tsx', '_error.tsx', '_404.tsx', '_401.tsx', '_403.tsx', '_429.tsx', '_503.tsx'])
292
+ const ROUTE_PATH_RE = /(?:^|\/)routes\//
293
+
294
+ interface ParityEntry {
295
+ category: 'error' | 'warning'
296
+ start: number
297
+ message: string
298
+ }
299
+
300
+ function collectClientLeakParity(displayFile: string, program: Program, value: ModuleAnalysis, out: ParityEntry[]): void {
301
+ const exported = [...value.exports].filter(([, e]) => e.interactive).map(([name]) => value.exportLocals.get(name) ?? name)
302
+ const reached = clientReach(value.bindings, [...exported, ...value.localIslands.keys()])
303
+ const keep = new Set<string>()
304
+ for (const b of reached) {
305
+ keep.add(b.name)
306
+ for (const ref of b.refs.keys())
307
+ keep.add(ref)
308
+ }
309
+ const reportedSources = new Set<string>()
310
+ for (const imp of value.imports) {
311
+ const kept = imp.specifiers.length === 0 || imp.specifiers.some(s => keep.has(s.local))
312
+ if (kept && isServerOnlyModule(imp.source) && !reportedSources.has(imp.source)) {
313
+ reportedSources.add(imp.source)
314
+ out.push({
315
+ category: 'error',
316
+ start: imp.start,
317
+ message: `prunelle check: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`,
318
+ })
319
+ }
320
+ }
321
+ for (const dyn of value.dynamicImports) {
322
+ const inClient = reached.some(b => dyn.start >= b.start && dyn.start < b.end)
323
+ if (inClient && isServerOnlyModule(dyn.source) && !reportedSources.has(dyn.source)) {
324
+ reportedSources.add(dyn.source)
325
+ out.push({
326
+ category: 'error',
327
+ start: dyn.start,
328
+ message: `prunelle check: interactive island imports server-only module "${dyn.source}". Move server logic to a server action or async server component.`,
329
+ })
330
+ }
331
+ }
332
+ const envMatch = findPrivateEnv(program, undefined, offset => reached.some(b => offset >= b.start && offset < b.end))
333
+ if (envMatch !== undefined) {
334
+ const src = envMatch.source ?? envMatch.kind
335
+ const envName = src === 'bun' ? 'Bun.env' : src === 'import.meta' ? 'import.meta.env' : 'process.env'
336
+ const hint = src === 'bun'
337
+ ? 'Bun.env is server-only and is not inlined in browser bundles; use process.env.PUBLIC_* for build-time client values.'
338
+ : src === 'import.meta'
339
+ ? 'Only import.meta.env.PUBLIC_* and MODE/DEV/PROD reach the browser.'
340
+ : 'Only process.env.PUBLIC_* reaches the browser.'
341
+ out.push({
342
+ category: 'error',
343
+ start: envMatch.offset,
344
+ message: `prunelle check: reads ${envName} and is reachable from the island in ${displayFile}. ${hint}`,
345
+ })
346
+ }
347
+ }
348
+
349
+ function collectSingleFileParity(fileName: string, displayFile: string, program: Program, value: ModuleAnalysis): ParityEntry[] {
350
+ const out: ParityEntry[] = []
351
+ const base = basename(fileName)
352
+
353
+ if (ROUTE_PATH_RE.test(displayFile) || (fileName.endsWith('.tsx') && value.exportedNames.includes('default'))) {
354
+ const cacheExport = parseCacheExport(program)
355
+ if (cacheExport.problem !== undefined) {
356
+ out.push({
357
+ category: 'error',
358
+ start: cacheExport.offset,
359
+ message: `prunelle check: ${cacheExport.problem.replace(':', ` in ${displayFile}:`)}.`,
360
+ })
361
+ }
362
+ }
363
+
364
+ if (value.nodeEnvReads.length > 0 && base !== 'prunelle.config.ts') {
365
+ for (const offset of value.nodeEnvReads) {
366
+ if (!value.browserSpans.some(([s, e]) => offset >= s && offset < e))
367
+ out.push({ category: 'warning', start: offset, message: nodeEnvWarning(displayFile) })
368
+ }
369
+ }
370
+
371
+ const defaultExport = value.exports.get('default')
372
+ if (SPECIAL_SERVER_FILES.has(base) && defaultExport?.interactive === true) {
373
+ out.push({
374
+ category: 'error',
375
+ start: defaultExport.offset ?? 0,
376
+ message: `prunelle check: ${displayFile} uses browser interactivity (${defaultExport.reason}), but it renders on the server only. Move the interactive part into a component and render that component from ${displayFile}.`,
377
+ })
378
+ }
379
+
380
+ if (value.isInteractive && value.exportedActions.length > 0) {
381
+ const name = value.exportedActions[0]!
382
+ const offset = value.bindings.find(b => b.name === name)?.start ?? 0
383
+ const reason = [...value.exports.values()].find(e => e.interactive)?.reason
384
+ ?? value.bindings.find(b => b.fact !== undefined)?.fact?.reason
385
+ out.push({
386
+ category: 'error',
387
+ start: offset,
388
+ message: `prunelle check: ${displayFile} exports server action "${name}" and also uses browser interactivity${reason ? ` (${reason})` : ''}: server action code would leak into the browser bundle. Move "${name}" into a separate non-interactive file (e.g. a .ts actions module).`,
389
+ })
390
+ }
391
+ else if (value.isInteractive) {
392
+ collectClientLeakParity(displayFile, program, value, out)
393
+ }
394
+
395
+ return out
396
+ }
397
+
398
+ /** Runs Prunelle compiler & compliance checks on one TS/TSX file and returns positioned diagnostics + mechanical fixes. */
399
+ export function collectPrunelleDiagnostics(
400
+ fileName: string,
401
+ code: string,
402
+ options: PrunellePluginOptions = {},
403
+ ): PrunelleDiagnosticItem[] {
404
+ if (!isCheckableFile(fileName))
405
+ return []
406
+
407
+ let program: Program
408
+ try {
409
+ program = parseTsx(fileName, code)
410
+ }
411
+ catch {
412
+ // While the user is typing incomplete syntax, TypeScript's syntactic diagnostics report it already.
413
+ return []
414
+ }
415
+
416
+ const { value, mistakes, error } = collectMistakes(() => analyzeModule(fileName, code, program))
417
+ const allMistakes = [...mistakes]
418
+ if (error instanceof PrunelleMistake)
419
+ allMistakes.push(error)
420
+ if (value !== undefined)
421
+ allMistakes.push(...collectImportedSignalMistakes(fileName, program, value.imports, options.readFile))
422
+
423
+ const staticCfg = options.compliance !== undefined && options.site !== undefined
424
+ ? {}
425
+ : readStaticProjectConfig(options.projectRoot)
426
+ const compliance = mergeCompliance(staticCfg.compliance, options.compliance)
427
+ const site = options.site ?? staticCfg.site
428
+
429
+ const displayFile = normalizeDisplayPath(fileName, options.projectRoot)
430
+ const activeWarnings = (value?.warnings ?? []).filter(w => shouldEmitWarning(w, compliance, site))
431
+ const parity = value !== undefined ? collectSingleFileParity(fileName, displayFile, program, value) : []
432
+ if (allMistakes.length === 0 && activeWarnings.length === 0 && parity.length === 0)
433
+ return []
434
+
435
+ const offsets = new Set<number>()
436
+ for (const m of allMistakes)
437
+ offsets.add(m.start ?? 0)
438
+ for (const w of activeWarnings)
439
+ offsets.add(w.start)
440
+ for (const p of parity)
441
+ offsets.add(p.start)
442
+ const nodesByOffset = indexNodesAtOffsets(program, offsets)
443
+
444
+ const items: PrunelleDiagnosticItem[] = []
445
+
446
+ for (const m of allMistakes) {
447
+ const start = m.start ?? 0
448
+ const nodes = nodesByOffset.get(start) ?? []
449
+ const classified = classifyMistakeFix(m.message, fileName, nodes, code)
450
+ const span = classified?.diagSpan ?? spanFromNodes(nodes, code, start)
451
+ items.push({
452
+ code: classified?.code ?? PRUNELLE_CODE.ERROR,
453
+ category: 'error',
454
+ start: span.start,
455
+ length: span.length,
456
+ message: m.message.replaceAll(fileName, displayFile),
457
+ ...(classified !== undefined ? { fix: classified.fix } : {}),
458
+ })
459
+ }
460
+
461
+ for (const w of activeWarnings) {
462
+ const nodes = nodesByOffset.get(w.start) ?? []
463
+ const classified = classifyWarningFix(w.message, nodes)
464
+ const span = classified?.diagSpan ?? spanFromNodes(nodes, code, w.start)
465
+ items.push({
466
+ code: classified?.code ?? PRUNELLE_CODE.WARNING,
467
+ category: 'warning',
468
+ start: span.start,
469
+ length: span.length,
470
+ message: w.message.replaceAll(fileName, displayFile),
471
+ ...(classified !== undefined ? { fix: classified.fix } : {}),
472
+ })
473
+ }
474
+
475
+ for (const p of parity) {
476
+ const nodes = nodesByOffset.get(p.start) ?? []
477
+ const span = spanFromNodes(nodes, code, p.start)
478
+ items.push({
479
+ code: p.category === 'warning' ? PRUNELLE_CODE.WARNING : PRUNELLE_CODE.ERROR,
480
+ category: p.category,
481
+ start: span.start,
482
+ length: span.length,
483
+ message: p.message,
484
+ })
485
+ }
486
+
487
+ return items
488
+ }
489
+
490
+ /** Converts a `PrunelleDiagnosticItem` into a TypeScript `ts.Diagnostic`. */
491
+ export function toTsDiagnostic(
492
+ tsLib: typeof ts,
493
+ item: PrunelleDiagnosticItem,
494
+ sourceFile: ts.SourceFile | undefined,
495
+ ): ts.Diagnostic {
496
+ return {
497
+ file: sourceFile,
498
+ start: item.start,
499
+ length: item.length,
500
+ messageText: item.message,
501
+ category: item.category === 'warning' ? tsLib.DiagnosticCategory.Warning : tsLib.DiagnosticCategory.Error,
502
+ code: item.code,
503
+ source: PRUNELLE_DIAG_SOURCE,
504
+ }
505
+ }