prunelle 0.1.1 → 0.5.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 (105) hide show
  1. package/llms.txt +23 -19
  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 +91 -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 +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -2,15 +2,18 @@
2
2
 
3
3
  import type { ActionsByFile } from '../build/islands'
4
4
  import type { PrunelleConfig, PrunellePlugin, ServerPluginAPI } from '../plugins/index'
5
+ import type { RouteCacheSpec } from '../server/route-cache'
5
6
  import { existsSync } from 'node:fs'
6
7
  import { basename, join, resolve } from 'node:path'
7
8
  import { relPosix, walkRoutes } from '../build/files'
8
9
  import { ModuleGraph } from '../build/graph'
9
10
  import { analyzeIslands } from '../build/islands'
10
11
  import { buildActionEntries, buildRouteEntries } from '../build/manifest'
11
- import { hasRouteHandlerExport, SPECIAL_ROUTE_FILES } from '../build/routes'
12
+ import { hasRouteHandlerExport, routeGroupsOf, SPECIAL_ROUTE_FILES } from '../build/routes'
12
13
  import { createAppContext, loadConfig, pickRuntimeConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
13
14
  import { actionHash } from '../server/action'
15
+ import { extractOptionalParams, extractPatternMatchers } from '../server/param-matchers'
16
+ import { formatCacheSpec } from '../server/route-cache'
14
17
 
15
18
  const HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
16
19
 
@@ -19,10 +22,15 @@ export interface InspectRoute {
19
22
  file?: string | undefined
20
23
  plugin?: string | undefined
21
24
  methods?: string[] | undefined
25
+ groups?: string[] | undefined
26
+ matchers?: Record<string, string> | undefined
27
+ optionalParams?: string[] | undefined
22
28
  layouts: string[]
23
29
  middlewares: string[]
24
30
  load: boolean
25
31
  prerender: boolean
32
+ cache?: RouteCacheSpec | undefined
33
+ cacheable?: boolean | undefined
26
34
  }
27
35
 
28
36
  export interface InspectIsland {
@@ -106,6 +114,7 @@ async function discoverPluginRoutes(
106
114
  },
107
115
  inject: key => services.get(key.name) as never,
108
116
  getBuildData: () => undefined,
117
+ healthCheck: () => {},
109
118
  onShutdown: (fn) => {
110
119
  shutdowns.push(fn)
111
120
  },
@@ -198,17 +207,27 @@ export async function inspectProject(rootDir: string): Promise<InspectReport> {
198
207
  })
199
208
 
200
209
  const fileRoutes: InspectRoute[] = routeEntries.map((entry, idx) => {
201
- const analysis = graph.analyses.get(pageFiles[idx]!)
210
+ const pageFile = pageFiles[idx]!
211
+ const analysis = graph.analyses.get(pageFile)
202
212
  const hasDefault = analysis?.exportedNames.includes('default') === true
203
213
  const methods = analysis?.exportedNames.filter(name => HTTP_METHODS.has(name)) ?? []
214
+ const groups = routeGroupsOf(routesDir, pageFile)
215
+ const matcherRefs = extractPatternMatchers(entry.path)
216
+ const matchers = matcherRefs.length > 0 ? Object.fromEntries(matcherRefs.map(m => [m.param, m.matcher])) : undefined
217
+ const optionalParams = extractOptionalParams(entry.path)
204
218
  return {
205
219
  path: entry.path,
206
220
  file: entry.file,
207
221
  ...(methods.length > 0 ? { methods } : {}),
222
+ ...(groups.length > 0 ? { groups } : {}),
223
+ ...(matchers !== undefined ? { matchers } : {}),
224
+ ...(optionalParams.length > 0 ? { optionalParams } : {}),
208
225
  layouts: hasDefault ? entry.layouts : [],
209
226
  middlewares: entry.middlewares,
210
227
  load: entry.hasLoad === true,
211
228
  prerender: entry.prerender === true,
229
+ ...(entry.cache !== undefined ? { cache: entry.cache } : {}),
230
+ ...(entry.cacheable === true ? { cacheable: true } : {}),
212
231
  }
213
232
  })
214
233
 
@@ -261,10 +280,20 @@ export function formatInspectReport(report: InspectReport): string {
261
280
  if (r.methods !== undefined && r.methods.length > 0)
262
281
  parts.push(r.methods.join(','))
263
282
  parts.push(r.file ?? `(plugin: ${r.plugin})`)
283
+ if (r.groups !== undefined && r.groups.length > 0)
284
+ parts.push(`groups=[${r.groups.join(', ')}]`)
285
+ if (r.matchers !== undefined)
286
+ parts.push(`matchers=[${Object.entries(r.matchers).map(([k, v]) => `${k}=${v}`).join(', ')}]`)
287
+ if (r.optionalParams !== undefined && r.optionalParams.length > 0)
288
+ parts.push(`optional=[${r.optionalParams.join(', ')}]`)
264
289
  if (r.load)
265
290
  parts.push('load')
266
291
  if (r.prerender)
267
292
  parts.push('prerender')
293
+ if (r.cache !== undefined)
294
+ parts.push(`cache=${formatCacheSpec(r.cache)}`)
295
+ if (r.cacheable === true)
296
+ parts.push('cacheable')
268
297
  if (r.layouts.length > 0)
269
298
  parts.push(`layouts=[${r.layouts.join(', ')}]`)
270
299
  if (r.middlewares.length > 0)
@@ -0,0 +1,480 @@
1
+ // Tool and resource definitions & handlers for the built-in `prunelle mcp` server.
2
+
3
+ import type { BundleReport } from '../build/report'
4
+ import { existsSync, readdirSync, realpathSync, rmSync } from 'node:fs'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { relPosix } from '../build/files'
7
+ import { build } from '../build/index'
8
+ import { isInside } from '../build/is-inside'
9
+ import { processSuffix } from '../build/output'
10
+ import { readDevErrorLog } from '../dev/error-log'
11
+ import { checkProject, diagnosticData } from './check'
12
+ import { discoverLlmsDocs, searchLlmsDocs } from './docs'
13
+ import { inspectProject } from './inspect'
14
+ import { renderUrl } from './render'
15
+
16
+ export interface McpToolAnnotations {
17
+ title?: string | undefined
18
+ readOnlyHint?: boolean | undefined
19
+ destructiveHint?: boolean | undefined
20
+ idempotentHint?: boolean | undefined
21
+ openWorldHint?: boolean | undefined
22
+ }
23
+
24
+ export interface McpToolDefinition {
25
+ name: string
26
+ description: string
27
+ inputSchema: {
28
+ type: 'object'
29
+ properties: Record<string, unknown>
30
+ required?: string[] | undefined
31
+ additionalProperties?: boolean | undefined
32
+ }
33
+ annotations: McpToolAnnotations
34
+ }
35
+
36
+ export interface McpToolCallResult {
37
+ content: { type: 'text', text: string }[]
38
+ isError?: boolean | undefined
39
+ }
40
+
41
+ export interface McpResource {
42
+ uri: string
43
+ name: string
44
+ description: string
45
+ mimeType: string
46
+ }
47
+
48
+ export interface McpResourceContent {
49
+ uri: string
50
+ mimeType: string
51
+ text: string
52
+ }
53
+
54
+ export interface PrunelleMcpContext {
55
+ root: string
56
+ allowWrite: boolean
57
+ }
58
+
59
+ const WRITE_GATE_MESSAGE = 'Writing build output requires starting `prunelle mcp --allow-write`.'
60
+ const LLMS_URI_PREFIX = 'prunelle://llms/'
61
+
62
+ function safeRealpath(target: string): string | undefined {
63
+ try {
64
+ return realpathSync(target)
65
+ }
66
+ catch {
67
+ return undefined
68
+ }
69
+ }
70
+
71
+ function nearestExistingRealpath(target: string): string | undefined {
72
+ let cursor = target
73
+ while (true) {
74
+ if (existsSync(cursor))
75
+ return safeRealpath(cursor)
76
+ const parent = dirname(cursor)
77
+ if (parent === cursor)
78
+ return undefined
79
+ cursor = parent
80
+ }
81
+ }
82
+
83
+ /** Resolves a user-supplied relative path against `baseDir` (default `root`) and refuses any path or symlink escaping `root`. */
84
+ export function resolveProjectPath(root: string, maybeRel: unknown, label: string, baseDir?: string): string {
85
+ const absRoot = resolve(root)
86
+ const absBase = baseDir !== undefined ? resolve(baseDir) : absRoot
87
+ if (maybeRel === undefined || maybeRel === '')
88
+ return absBase
89
+ if (typeof maybeRel !== 'string')
90
+ throw new Error(`prunelle mcp: ${label} must be a string`)
91
+
92
+ const resolved = resolve(absBase, maybeRel)
93
+ if (!isInside(absRoot, resolved, { orSame: true }))
94
+ throw new Error(`prunelle mcp: ${label} "${maybeRel}" escapes the project root`)
95
+
96
+ const realRoot = safeRealpath(absRoot)
97
+ const realTarget = nearestExistingRealpath(resolved)
98
+ if (realRoot !== undefined && realTarget !== undefined && !isInside(realRoot, realTarget, { orSame: true }))
99
+ throw new Error(`prunelle mcp: ${label} "${maybeRel}" escapes the project root via symlink`)
100
+
101
+ return resolved
102
+ }
103
+
104
+ function asArgsRecord(args: unknown): Record<string, unknown> {
105
+ if (args === undefined || args === null)
106
+ return {}
107
+ if (typeof args !== 'object' || Array.isArray(args))
108
+ throw new Error('prunelle mcp: tool arguments must be a JSON object')
109
+ return args as Record<string, unknown>
110
+ }
111
+
112
+ function optionalBoolean(args: Record<string, unknown>, key: string): boolean | undefined {
113
+ const value = args[key]
114
+ if (value === undefined)
115
+ return undefined
116
+ if (typeof value !== 'boolean')
117
+ throw new Error(`prunelle mcp: "${key}" must be a boolean`)
118
+ return value
119
+ }
120
+
121
+ function optionalString(args: Record<string, unknown>, key: string): string | undefined {
122
+ const value = args[key]
123
+ if (value === undefined)
124
+ return undefined
125
+ if (typeof value !== 'string')
126
+ throw new Error(`prunelle mcp: "${key}" must be a string`)
127
+ return value
128
+ }
129
+
130
+ function normalizeRenderHeaders(raw: unknown): string[] | undefined {
131
+ if (raw === undefined)
132
+ return undefined
133
+ if (Array.isArray(raw)) {
134
+ if (!raw.every(item => typeof item === 'string'))
135
+ throw new Error('prunelle mcp: "headers" array entries must be strings')
136
+ return raw
137
+ }
138
+ if (typeof raw === 'object' && raw !== null) {
139
+ return Object.entries(raw as Record<string, unknown>).map(([k, v]) => `${k}: ${String(v)}`)
140
+ }
141
+ throw new Error('prunelle mcp: "headers" must be an object or string array')
142
+ }
143
+
144
+ function normalizeStringArray(raw: unknown, key: string): string[] | undefined {
145
+ if (raw === undefined)
146
+ return undefined
147
+ if (!Array.isArray(raw) || !raw.every(item => typeof item === 'string'))
148
+ throw new Error(`prunelle mcp: "${key}" must be an array of strings`)
149
+ return raw
150
+ }
151
+
152
+ function jsonResult(data: unknown): McpToolCallResult {
153
+ return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }
154
+ }
155
+
156
+ function errorResult(message: string): McpToolCallResult {
157
+ return { content: [{ type: 'text', text: message }], isError: true }
158
+ }
159
+
160
+ /** Returns the list of MCP tools exposed by `prunelle mcp`. */
161
+ export function listPrunelleTools(): McpToolDefinition[] {
162
+ return [
163
+ {
164
+ name: 'check',
165
+ description: 'Run `prunelle check` and return structured JSON diagnostics (errors, warnings, checkedFiles, typecheck).',
166
+ inputSchema: {
167
+ type: 'object',
168
+ properties: {
169
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
170
+ skipTypecheck: { type: 'boolean', description: 'Skip the TypeScript typecheck step.' },
171
+ strict: { type: 'boolean', description: 'Fail (ok: false) when warnings are present.' },
172
+ },
173
+ additionalProperties: false,
174
+ },
175
+ annotations: { title: 'Check Prunelle project', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
176
+ },
177
+ {
178
+ name: 'inspect',
179
+ description: 'Statically inspect routes, islands, server actions, and active plugins without bundling.',
180
+ inputSchema: {
181
+ type: 'object',
182
+ properties: {
183
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
184
+ },
185
+ additionalProperties: false,
186
+ },
187
+ annotations: { title: 'Inspect Prunelle project', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
188
+ },
189
+ {
190
+ name: 'build_analyze',
191
+ description: 'Analyze per-route JS/CSS bundle weights and islands. Read-only by default (uses a temporary cache folder and cleans up); passing write=true or outDir requires `--allow-write`.',
192
+ inputSchema: {
193
+ type: 'object',
194
+ properties: {
195
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
196
+ static: { type: 'boolean', description: 'Analyze as a static export.' },
197
+ autoPrerender: { type: 'boolean', description: 'Enable auto-prerender for static pages.' },
198
+ write: { type: 'boolean', description: 'Keep the built output on disk (requires `--allow-write`).' },
199
+ outDir: { type: 'string', description: 'Custom output directory inside the project root (requires `--allow-write`).' },
200
+ },
201
+ additionalProperties: false,
202
+ },
203
+ annotations: { title: 'Analyze bundle weights', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
204
+ },
205
+ {
206
+ name: 'build',
207
+ description: 'Build the Prunelle app to disk (`dist/` or `outDir`). Requires starting `prunelle mcp --allow-write`.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
212
+ static: { type: 'boolean', description: 'Export a static site instead of a server build.' },
213
+ autoPrerender: { type: 'boolean', description: 'Enable auto-prerender for static pages.' },
214
+ outDir: { type: 'string', description: 'Output directory inside the project root.' },
215
+ analyze: { type: 'boolean', description: 'Also include the bundle weight report in the response.' },
216
+ },
217
+ additionalProperties: false,
218
+ },
219
+ annotations: { title: 'Build Prunelle project', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
220
+ },
221
+ {
222
+ name: 'render',
223
+ description: 'Render a route or API endpoint in-process without binding a port or touching `dist/`.',
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: {
227
+ url: { type: 'string', description: 'URL path (e.g. "/" or "/api/items?page=2") or full URL to render.' },
228
+ method: { type: 'string', description: 'HTTP method (defaults to GET, or POST when body is set).' },
229
+ body: { type: 'string', description: 'Request body string.' },
230
+ headers: { description: 'Request headers as an object ({ name: value }) or array of "Name: Value" strings.' },
231
+ cookies: { type: 'array', items: { type: 'string' }, description: 'Cookie entries ("name=value").' },
232
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
233
+ fresh: { type: 'boolean', description: 'Force a fresh build instead of reusing `.prunelle-cache/render-build`.' },
234
+ },
235
+ required: ['url'],
236
+ additionalProperties: false,
237
+ },
238
+ annotations: { title: 'Render a URL', readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
239
+ },
240
+ {
241
+ name: 'docs',
242
+ description: 'Search `llms.txt` documentation across `prunelle` and every installed `@prunellejs/*` package.',
243
+ inputSchema: {
244
+ type: 'object',
245
+ properties: {
246
+ query: { type: 'string', description: 'Whitespace-separated search keywords (case-insensitive AND).' },
247
+ limit: { type: 'number', description: 'Maximum number of matching sections to return (default 20).' },
248
+ },
249
+ required: ['query'],
250
+ additionalProperties: false,
251
+ },
252
+ annotations: { title: 'Search Prunelle docs', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
253
+ },
254
+ {
255
+ name: 'dev_errors',
256
+ description: 'Read the last build error, child crash, and recent runtime errors recorded by `prunelle dev`.',
257
+ inputSchema: {
258
+ type: 'object',
259
+ properties: {
260
+ dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
261
+ },
262
+ additionalProperties: false,
263
+ },
264
+ annotations: { title: 'Read last dev errors', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
265
+ },
266
+ ]
267
+ }
268
+
269
+ async function runCheckTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
270
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
271
+ const skipTypecheck = optionalBoolean(args, 'skipTypecheck') === true
272
+ const strict = optionalBoolean(args, 'strict') === true
273
+ const res = await checkProject(targetDir, { skipTypecheck })
274
+ const errors = res.errors.map(e => diagnosticData(e, 'error'))
275
+ const warnings = res.warnings.map(w => diagnosticData(w, 'warning'))
276
+ const ok = res.ok && (!strict || warnings.length === 0)
277
+ return jsonResult({ ok, checkedFiles: res.checkedFiles, typecheck: res.typecheck, errors, warnings })
278
+ }
279
+
280
+ async function runInspectTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
281
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
282
+ const report = await inspectProject(targetDir)
283
+ return jsonResult({
284
+ routes: report.routes,
285
+ islands: report.islands,
286
+ actions: report.actions,
287
+ plugins: report.plugins,
288
+ })
289
+ }
290
+
291
+ async function runBuildAnalyzeTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
292
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
293
+ const isStatic = optionalBoolean(args, 'static') === true
294
+ const autoPrerender = optionalBoolean(args, 'autoPrerender') === true ? true : undefined
295
+ const wantsWrite = optionalBoolean(args, 'write') === true || args.outDir !== undefined
296
+ const explicitOutDir = args.outDir !== undefined ? resolveProjectPath(ctx.root, args.outDir, 'outDir', targetDir) : undefined
297
+
298
+ if (wantsWrite && !ctx.allowWrite)
299
+ return errorResult(WRITE_GATE_MESSAGE)
300
+
301
+ let report: BundleReport | undefined
302
+ if (wantsWrite) {
303
+ await build({
304
+ root: targetDir,
305
+ outDir: explicitOutDir,
306
+ static: isStatic,
307
+ autoPrerender,
308
+ onAnalyze: (r) => {
309
+ report = r
310
+ },
311
+ })
312
+ return jsonResult(report ?? { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] })
313
+ }
314
+
315
+ const cacheDir = join(targetDir, '.prunelle-cache')
316
+ const cacheExisted = existsSync(cacheDir)
317
+ const tempOutDir = join(cacheDir, `mcp-analyze-${processSuffix()}`)
318
+ try {
319
+ await build({
320
+ root: targetDir,
321
+ outDir: tempOutDir,
322
+ static: isStatic,
323
+ autoPrerender,
324
+ onAnalyze: (r) => {
325
+ report = r
326
+ },
327
+ })
328
+ return jsonResult(report ?? { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] })
329
+ }
330
+ finally {
331
+ rmSync(tempOutDir, { recursive: true, force: true })
332
+ if (!cacheExisted && existsSync(cacheDir) && readdirSync(cacheDir).length === 0)
333
+ rmSync(cacheDir, { recursive: true, force: true })
334
+ }
335
+ }
336
+
337
+ async function runBuildTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
338
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
339
+ const explicitOutDir = args.outDir !== undefined ? resolveProjectPath(ctx.root, args.outDir, 'outDir', targetDir) : undefined
340
+ if (!ctx.allowWrite)
341
+ return errorResult(WRITE_GATE_MESSAGE)
342
+
343
+ const isStatic = optionalBoolean(args, 'static') === true
344
+ const autoPrerender = optionalBoolean(args, 'autoPrerender') === true ? true : undefined
345
+ const wantReport = optionalBoolean(args, 'analyze') === true
346
+ let report: BundleReport | undefined
347
+ const manifest = await build({
348
+ root: targetDir,
349
+ outDir: explicitOutDir,
350
+ static: isStatic,
351
+ autoPrerender,
352
+ ...(wantReport ? { onAnalyze: (r: BundleReport) => { report = r } } : {}),
353
+ })
354
+ return jsonResult({
355
+ ok: true,
356
+ outDir: explicitOutDir !== undefined ? relPosix(targetDir, explicitOutDir) : 'dist',
357
+ routes: manifest.routes.map(r => r.path),
358
+ routeCount: manifest.routes.length,
359
+ assetCount: manifest.assets.length,
360
+ actionCount: manifest.actions.length,
361
+ islandCount: Object.keys(manifest.islands).length,
362
+ ...(report !== undefined ? { report } : {}),
363
+ })
364
+ }
365
+
366
+ async function runRenderTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
367
+ const url = optionalString(args, 'url')
368
+ if (url === undefined || url.trim().length === 0)
369
+ throw new Error('prunelle mcp: "url" is required and must be a non-empty string')
370
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
371
+ const method = optionalString(args, 'method')
372
+ const body = optionalString(args, 'body')
373
+ const headers = normalizeRenderHeaders(args.headers)
374
+ const cookies = normalizeStringArray(args.cookies, 'cookies')
375
+ const fresh = optionalBoolean(args, 'fresh') === true
376
+ const result = await renderUrl({ root: targetDir, url, method, body, headers, cookies, fresh })
377
+ return jsonResult({
378
+ status: result.status,
379
+ statusText: result.statusText,
380
+ ok: result.ok,
381
+ headers: result.headers,
382
+ setCookies: result.setCookies,
383
+ body: result.body,
384
+ reusedBuild: result.reusedBuild,
385
+ errors: result.errors,
386
+ })
387
+ }
388
+
389
+ function runDocsTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): McpToolCallResult {
390
+ const query = optionalString(args, 'query')
391
+ if (query === undefined)
392
+ throw new Error('prunelle mcp: "query" is required and must be a string')
393
+ let limit: number | undefined
394
+ if (args.limit !== undefined) {
395
+ if (typeof args.limit !== 'number' || !Number.isFinite(args.limit))
396
+ throw new Error('prunelle mcp: "limit" must be a finite number')
397
+ limit = args.limit
398
+ }
399
+ const result = searchLlmsDocs(ctx.root, query, { limit })
400
+ return jsonResult({
401
+ query: result.query,
402
+ words: result.words,
403
+ packages: result.packages,
404
+ matches: result.matches,
405
+ })
406
+ }
407
+
408
+ function runDevErrorsTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): McpToolCallResult {
409
+ const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
410
+ const log = readDevErrorLog(targetDir)
411
+ if (log === undefined) {
412
+ return jsonResult({
413
+ hasErrors: false,
414
+ runtimeErrors: [],
415
+ note: 'No dev errors recorded (start `prunelle dev` or no errors have occurred).',
416
+ })
417
+ }
418
+ const hasErrors = log.buildError !== undefined || log.crashError !== undefined || log.runtimeErrors.length > 0
419
+ return jsonResult({
420
+ hasErrors,
421
+ updatedAt: log.updatedAt,
422
+ ...(log.buildError !== undefined ? { buildError: log.buildError } : {}),
423
+ ...(log.crashError !== undefined ? { crashError: log.crashError } : {}),
424
+ runtimeErrors: log.runtimeErrors,
425
+ })
426
+ }
427
+
428
+ export type ToolHandler = (ctx: PrunelleMcpContext, args: Record<string, unknown>) => McpToolCallResult | Promise<McpToolCallResult>
429
+
430
+ const TOOL_HANDLERS: Record<string, ToolHandler> = {
431
+ check: runCheckTool,
432
+ inspect: runInspectTool,
433
+ build_analyze: runBuildAnalyzeTool,
434
+ build: runBuildTool,
435
+ render: runRenderTool,
436
+ docs: runDocsTool,
437
+ dev_errors: runDevErrorsTool,
438
+ }
439
+
440
+ export function hasPrunelleTool(name: string): boolean {
441
+ return Object.prototype.hasOwnProperty.call(TOOL_HANDLERS, name)
442
+ }
443
+
444
+ export async function callPrunelleTool(ctx: PrunelleMcpContext, name: string, rawArgs: unknown): Promise<McpToolCallResult> {
445
+ const handler = TOOL_HANDLERS[name]
446
+ if (handler === undefined)
447
+ throw new Error(`Unknown tool: ${name}`)
448
+ try {
449
+ const args = asArgsRecord(rawArgs)
450
+ return await handler(ctx, args)
451
+ }
452
+ catch (err) {
453
+ return errorResult(err instanceof Error ? err.message : String(err))
454
+ }
455
+ }
456
+
457
+ /** Lists every discovered `llms.txt` (`prunelle` and installed `@prunellejs/*` packages) as an MCP resource. */
458
+ export function listPrunelleResources(root: string): McpResource[] {
459
+ return discoverLlmsDocs(root).map(doc => ({
460
+ uri: `${LLMS_URI_PREFIX}${doc.packageName}`,
461
+ name: `${doc.packageName} llms.txt`,
462
+ description: `${doc.packageName}${doc.version !== undefined ? `@${doc.version}` : ''} reference (${doc.relFile})`,
463
+ mimeType: 'text/markdown',
464
+ }))
465
+ }
466
+
467
+ /** Reads a `prunelle://llms/<package>` MCP resource fresh from disk, returning `undefined` when unknown. */
468
+ export function readPrunelleResource(root: string, uri: string): McpResourceContent | undefined {
469
+ if (!uri.startsWith(LLMS_URI_PREFIX))
470
+ return undefined
471
+ const targetPkg = uri.slice(LLMS_URI_PREFIX.length)
472
+ const doc = discoverLlmsDocs(root).find(d => d.packageName === targetPkg)
473
+ if (doc === undefined)
474
+ return undefined
475
+ return {
476
+ uri,
477
+ mimeType: 'text/markdown',
478
+ text: doc.content,
479
+ }
480
+ }