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.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,492 @@
|
|
|
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 { loadConfig, runWithFreshConfig } from '../plugins/load'
|
|
12
|
+
import { checkProject, diagnosticData } from './check'
|
|
13
|
+
import { discoverLlmsDocs, searchLlmsDocs } from './docs'
|
|
14
|
+
import { inspectProject } from './inspect'
|
|
15
|
+
import { isReadOnlyRenderMethod, renderMethod, renderUrl } from './render'
|
|
16
|
+
|
|
17
|
+
export interface McpToolAnnotations {
|
|
18
|
+
title?: string | undefined
|
|
19
|
+
readOnlyHint?: boolean | undefined
|
|
20
|
+
destructiveHint?: boolean | undefined
|
|
21
|
+
idempotentHint?: boolean | undefined
|
|
22
|
+
openWorldHint?: boolean | undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface McpToolDefinition {
|
|
26
|
+
name: string
|
|
27
|
+
description: string
|
|
28
|
+
inputSchema: {
|
|
29
|
+
type: 'object'
|
|
30
|
+
properties: Record<string, unknown>
|
|
31
|
+
required?: string[] | undefined
|
|
32
|
+
additionalProperties?: boolean | undefined
|
|
33
|
+
}
|
|
34
|
+
annotations: McpToolAnnotations
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface McpToolCallResult {
|
|
38
|
+
content: { type: 'text', text: string }[]
|
|
39
|
+
isError?: boolean | undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface McpResource {
|
|
43
|
+
uri: string
|
|
44
|
+
name: string
|
|
45
|
+
description: string
|
|
46
|
+
mimeType: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface McpResourceContent {
|
|
50
|
+
uri: string
|
|
51
|
+
mimeType: string
|
|
52
|
+
text: string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface PrunelleMcpContext {
|
|
56
|
+
root: string
|
|
57
|
+
allowWrite: boolean
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const WRITE_GATE_MESSAGE = 'Writing build output requires starting `prunelle mcp --allow-write`.'
|
|
61
|
+
const LLMS_URI_PREFIX = 'prunelle://llms/'
|
|
62
|
+
|
|
63
|
+
function safeRealpath(target: string): string | undefined {
|
|
64
|
+
try {
|
|
65
|
+
return realpathSync(target)
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return undefined
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function nearestExistingRealpath(target: string): string | undefined {
|
|
73
|
+
let cursor = target
|
|
74
|
+
while (true) {
|
|
75
|
+
if (existsSync(cursor))
|
|
76
|
+
return safeRealpath(cursor)
|
|
77
|
+
const parent = dirname(cursor)
|
|
78
|
+
if (parent === cursor)
|
|
79
|
+
return undefined
|
|
80
|
+
cursor = parent
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Resolves a user-supplied relative path against `baseDir` (default `root`) and refuses any path or symlink escaping `root`. */
|
|
85
|
+
export function resolveProjectPath(root: string, maybeRel: unknown, label: string, baseDir?: string): string {
|
|
86
|
+
const absRoot = resolve(root)
|
|
87
|
+
const absBase = baseDir !== undefined ? resolve(baseDir) : absRoot
|
|
88
|
+
if (maybeRel === undefined || maybeRel === '')
|
|
89
|
+
return absBase
|
|
90
|
+
if (typeof maybeRel !== 'string')
|
|
91
|
+
throw new Error(`prunelle mcp: ${label} must be a string`)
|
|
92
|
+
|
|
93
|
+
const resolved = resolve(absBase, maybeRel)
|
|
94
|
+
if (!isInside(absRoot, resolved, { orSame: true }))
|
|
95
|
+
throw new Error(`prunelle mcp: ${label} "${maybeRel}" escapes the project root`)
|
|
96
|
+
|
|
97
|
+
const realRoot = safeRealpath(absRoot)
|
|
98
|
+
const realTarget = nearestExistingRealpath(resolved)
|
|
99
|
+
if (realRoot !== undefined && realTarget !== undefined && !isInside(realRoot, realTarget, { orSame: true }))
|
|
100
|
+
throw new Error(`prunelle mcp: ${label} "${maybeRel}" escapes the project root via symlink`)
|
|
101
|
+
|
|
102
|
+
return resolved
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function asArgsRecord(args: unknown): Record<string, unknown> {
|
|
106
|
+
if (args === undefined || args === null)
|
|
107
|
+
return {}
|
|
108
|
+
if (typeof args !== 'object' || Array.isArray(args))
|
|
109
|
+
throw new Error('prunelle mcp: tool arguments must be a JSON object')
|
|
110
|
+
return args as Record<string, unknown>
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function optionalBoolean(args: Record<string, unknown>, key: string): boolean | undefined {
|
|
114
|
+
const value = args[key]
|
|
115
|
+
if (value === undefined)
|
|
116
|
+
return undefined
|
|
117
|
+
if (typeof value !== 'boolean')
|
|
118
|
+
throw new Error(`prunelle mcp: "${key}" must be a boolean`)
|
|
119
|
+
return value
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function optionalString(args: Record<string, unknown>, key: string): string | undefined {
|
|
123
|
+
const value = args[key]
|
|
124
|
+
if (value === undefined)
|
|
125
|
+
return undefined
|
|
126
|
+
if (typeof value !== 'string')
|
|
127
|
+
throw new Error(`prunelle mcp: "${key}" must be a string`)
|
|
128
|
+
return value
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function normalizeRenderHeaders(raw: unknown): string[] | undefined {
|
|
132
|
+
if (raw === undefined)
|
|
133
|
+
return undefined
|
|
134
|
+
if (Array.isArray(raw)) {
|
|
135
|
+
if (!raw.every(item => typeof item === 'string'))
|
|
136
|
+
throw new Error('prunelle mcp: "headers" array entries must be strings')
|
|
137
|
+
return raw
|
|
138
|
+
}
|
|
139
|
+
if (typeof raw === 'object' && raw !== null) {
|
|
140
|
+
return Object.entries(raw as Record<string, unknown>).map(([k, v]) => `${k}: ${String(v)}`)
|
|
141
|
+
}
|
|
142
|
+
throw new Error('prunelle mcp: "headers" must be an object or string array')
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function normalizeStringArray(raw: unknown, key: string): string[] | undefined {
|
|
146
|
+
if (raw === undefined)
|
|
147
|
+
return undefined
|
|
148
|
+
if (!Array.isArray(raw) || !raw.every(item => typeof item === 'string'))
|
|
149
|
+
throw new Error(`prunelle mcp: "${key}" must be an array of strings`)
|
|
150
|
+
return raw
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function jsonResult(data: unknown): McpToolCallResult {
|
|
154
|
+
return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function errorResult(message: string): McpToolCallResult {
|
|
158
|
+
return { content: [{ type: 'text', text: message }], isError: true }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Returns the list of MCP tools exposed by `prunelle mcp`. */
|
|
162
|
+
export function listPrunelleTools(): McpToolDefinition[] {
|
|
163
|
+
return [
|
|
164
|
+
{
|
|
165
|
+
name: 'check',
|
|
166
|
+
description: 'Run `prunelle check` and return structured JSON diagnostics (errors, warnings, checkedFiles, typecheck).',
|
|
167
|
+
inputSchema: {
|
|
168
|
+
type: 'object',
|
|
169
|
+
properties: {
|
|
170
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
171
|
+
skipTypecheck: { type: 'boolean', description: 'Skip the TypeScript typecheck step.' },
|
|
172
|
+
strict: { type: 'boolean', description: 'Fail (ok: false) when warnings are present.' },
|
|
173
|
+
},
|
|
174
|
+
additionalProperties: false,
|
|
175
|
+
},
|
|
176
|
+
annotations: { title: 'Check Prunelle project', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
name: 'inspect',
|
|
180
|
+
description: 'Statically inspect routes, islands, server actions, and active plugins without bundling.',
|
|
181
|
+
inputSchema: {
|
|
182
|
+
type: 'object',
|
|
183
|
+
properties: {
|
|
184
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
185
|
+
},
|
|
186
|
+
additionalProperties: false,
|
|
187
|
+
},
|
|
188
|
+
annotations: { title: 'Inspect Prunelle project', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
name: 'build_analyze',
|
|
192
|
+
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`.',
|
|
193
|
+
inputSchema: {
|
|
194
|
+
type: 'object',
|
|
195
|
+
properties: {
|
|
196
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
197
|
+
static: { type: 'boolean', description: 'Analyze as a static export.' },
|
|
198
|
+
autoPrerender: { type: 'boolean', description: 'Enable auto-prerender for static pages.' },
|
|
199
|
+
write: { type: 'boolean', description: 'Keep the built output on disk (requires `--allow-write`).' },
|
|
200
|
+
outDir: { type: 'string', description: 'Custom output directory inside the project root (requires `--allow-write`).' },
|
|
201
|
+
},
|
|
202
|
+
additionalProperties: false,
|
|
203
|
+
},
|
|
204
|
+
annotations: { title: 'Analyze bundle weights', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
name: 'build',
|
|
208
|
+
description: 'Build the Prunelle app to disk (`dist/` or `outDir`). Requires starting `prunelle mcp --allow-write`.',
|
|
209
|
+
inputSchema: {
|
|
210
|
+
type: 'object',
|
|
211
|
+
properties: {
|
|
212
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
213
|
+
static: { type: 'boolean', description: 'Export a static site instead of a server build.' },
|
|
214
|
+
autoPrerender: { type: 'boolean', description: 'Enable auto-prerender for static pages.' },
|
|
215
|
+
outDir: { type: 'string', description: 'Output directory inside the project root.' },
|
|
216
|
+
analyze: { type: 'boolean', description: 'Also include the bundle weight report in the response.' },
|
|
217
|
+
},
|
|
218
|
+
additionalProperties: false,
|
|
219
|
+
},
|
|
220
|
+
annotations: { title: 'Build Prunelle project', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
name: 'render',
|
|
224
|
+
description: 'Render a route or API endpoint in-process without binding a port or touching `dist/`. A method other than GET, HEAD or OPTIONS runs real actions and requires `--allow-write`.',
|
|
225
|
+
inputSchema: {
|
|
226
|
+
type: 'object',
|
|
227
|
+
properties: {
|
|
228
|
+
url: { type: 'string', description: 'URL path (e.g. "/" or "/api/items?page=2") or full URL to render.' },
|
|
229
|
+
method: { type: 'string', description: 'HTTP method (defaults to GET, or POST when body is set; anything but GET, HEAD and OPTIONS requires `--allow-write`).' },
|
|
230
|
+
body: { type: 'string', description: 'Request body string.' },
|
|
231
|
+
headers: { description: 'Request headers as an object ({ name: value }) or array of "Name: Value" strings.' },
|
|
232
|
+
cookies: { type: 'array', items: { type: 'string' }, description: 'Cookie entries ("name=value").' },
|
|
233
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
234
|
+
fresh: { type: 'boolean', description: 'Force a fresh build instead of reusing `.prunelle-cache/render-build`.' },
|
|
235
|
+
},
|
|
236
|
+
required: ['url'],
|
|
237
|
+
additionalProperties: false,
|
|
238
|
+
},
|
|
239
|
+
annotations: { title: 'Render a URL', readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
name: 'docs',
|
|
243
|
+
description: 'Search `llms.txt` documentation across `prunelle` and every installed `@prunellejs/*` package.',
|
|
244
|
+
inputSchema: {
|
|
245
|
+
type: 'object',
|
|
246
|
+
properties: {
|
|
247
|
+
query: { type: 'string', description: 'Whitespace-separated search keywords (case-insensitive AND).' },
|
|
248
|
+
limit: { type: 'number', description: 'Maximum number of matching sections to return (default 20).' },
|
|
249
|
+
},
|
|
250
|
+
required: ['query'],
|
|
251
|
+
additionalProperties: false,
|
|
252
|
+
},
|
|
253
|
+
annotations: { title: 'Search Prunelle docs', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
name: 'dev_errors',
|
|
257
|
+
description: 'Read the last build error, child crash, and recent runtime errors recorded by `prunelle dev`.',
|
|
258
|
+
inputSchema: {
|
|
259
|
+
type: 'object',
|
|
260
|
+
properties: {
|
|
261
|
+
dir: { type: 'string', description: 'Optional sub-directory inside the project root.' },
|
|
262
|
+
},
|
|
263
|
+
additionalProperties: false,
|
|
264
|
+
},
|
|
265
|
+
annotations: { title: 'Read last dev errors', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
266
|
+
},
|
|
267
|
+
]
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function runCheckTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
271
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
272
|
+
const skipTypecheck = optionalBoolean(args, 'skipTypecheck') === true
|
|
273
|
+
const strict = optionalBoolean(args, 'strict') === true
|
|
274
|
+
const res = await checkProject(targetDir, { skipTypecheck })
|
|
275
|
+
const errors = res.errors.map(e => diagnosticData(e, 'error'))
|
|
276
|
+
const warnings = res.warnings.map(w => diagnosticData(w, 'warning'))
|
|
277
|
+
const ok = res.ok && (!strict || warnings.length === 0)
|
|
278
|
+
return jsonResult({ ok, checkedFiles: res.checkedFiles, typecheck: res.typecheck, errors, warnings })
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function runInspectTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
282
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
283
|
+
const report = await inspectProject(targetDir)
|
|
284
|
+
return jsonResult({
|
|
285
|
+
routes: report.routes,
|
|
286
|
+
statusPages: report.statusPages,
|
|
287
|
+
paramMatchers: report.paramMatchers,
|
|
288
|
+
islands: report.islands,
|
|
289
|
+
actions: report.actions,
|
|
290
|
+
plugins: report.plugins,
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function runBuildAnalyzeTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
295
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
296
|
+
const isStatic = optionalBoolean(args, 'static') === true
|
|
297
|
+
const autoPrerender = optionalBoolean(args, 'autoPrerender') === true ? true : undefined
|
|
298
|
+
const wantsWrite = optionalBoolean(args, 'write') === true || args.outDir !== undefined
|
|
299
|
+
const explicitOutDir = args.outDir !== undefined ? resolveProjectPath(ctx.root, args.outDir, 'outDir', targetDir) : undefined
|
|
300
|
+
|
|
301
|
+
if (wantsWrite && !ctx.allowWrite)
|
|
302
|
+
return errorResult(WRITE_GATE_MESSAGE)
|
|
303
|
+
|
|
304
|
+
let report: BundleReport | undefined
|
|
305
|
+
if (wantsWrite) {
|
|
306
|
+
await build({
|
|
307
|
+
root: targetDir,
|
|
308
|
+
outDir: explicitOutDir,
|
|
309
|
+
static: isStatic,
|
|
310
|
+
autoPrerender,
|
|
311
|
+
onAnalyze: (r) => {
|
|
312
|
+
report = r
|
|
313
|
+
},
|
|
314
|
+
})
|
|
315
|
+
return jsonResult(report ?? { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] })
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const cacheDir = join(targetDir, '.prunelle-cache')
|
|
319
|
+
const cacheExisted = existsSync(cacheDir)
|
|
320
|
+
const tempOutDir = join(cacheDir, `mcp-analyze-${processSuffix()}`)
|
|
321
|
+
try {
|
|
322
|
+
await build({
|
|
323
|
+
root: targetDir,
|
|
324
|
+
outDir: tempOutDir,
|
|
325
|
+
static: isStatic,
|
|
326
|
+
autoPrerender,
|
|
327
|
+
onAnalyze: (r) => {
|
|
328
|
+
report = r
|
|
329
|
+
},
|
|
330
|
+
})
|
|
331
|
+
return jsonResult(report ?? { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] })
|
|
332
|
+
}
|
|
333
|
+
finally {
|
|
334
|
+
rmSync(tempOutDir, { recursive: true, force: true })
|
|
335
|
+
if (!cacheExisted && existsSync(cacheDir)) {
|
|
336
|
+
const remaining = readdirSync(cacheDir)
|
|
337
|
+
if (remaining.every(name => name === '.gitignore' || name === 'entries' || name.startsWith('brotli-')))
|
|
338
|
+
rmSync(cacheDir, { recursive: true, force: true })
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function runBuildTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
344
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
345
|
+
const explicitOutDir = args.outDir !== undefined ? resolveProjectPath(ctx.root, args.outDir, 'outDir', targetDir) : undefined
|
|
346
|
+
if (!ctx.allowWrite)
|
|
347
|
+
return errorResult(WRITE_GATE_MESSAGE)
|
|
348
|
+
|
|
349
|
+
const isStatic = optionalBoolean(args, 'static') === true
|
|
350
|
+
const autoPrerender = optionalBoolean(args, 'autoPrerender') === true ? true : undefined
|
|
351
|
+
const wantReport = optionalBoolean(args, 'analyze') === true
|
|
352
|
+
let report: BundleReport | undefined
|
|
353
|
+
const manifest = await build({
|
|
354
|
+
root: targetDir,
|
|
355
|
+
outDir: explicitOutDir,
|
|
356
|
+
static: isStatic,
|
|
357
|
+
autoPrerender,
|
|
358
|
+
...(wantReport ? { onAnalyze: (r: BundleReport) => { report = r } } : {}),
|
|
359
|
+
})
|
|
360
|
+
const resolvedOutDir = explicitOutDir !== undefined
|
|
361
|
+
? explicitOutDir
|
|
362
|
+
: resolve(targetDir, (await loadConfig(targetDir, { fresh: true })).outDir ?? 'dist')
|
|
363
|
+
return jsonResult({
|
|
364
|
+
ok: true,
|
|
365
|
+
outDir: relPosix(targetDir, resolvedOutDir),
|
|
366
|
+
routes: manifest.routes.map(r => r.path),
|
|
367
|
+
routeCount: manifest.routes.length,
|
|
368
|
+
assetCount: manifest.assets.length,
|
|
369
|
+
actionCount: manifest.actions.length,
|
|
370
|
+
islandCount: Object.keys(manifest.islands).length,
|
|
371
|
+
...(report !== undefined ? { report } : {}),
|
|
372
|
+
})
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function runRenderTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): Promise<McpToolCallResult> {
|
|
376
|
+
const url = optionalString(args, 'url')
|
|
377
|
+
if (url === undefined || url.trim().length === 0)
|
|
378
|
+
throw new Error('prunelle mcp: "url" is required and must be a non-empty string')
|
|
379
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
380
|
+
const body = optionalString(args, 'body')
|
|
381
|
+
const method = renderMethod(optionalString(args, 'method'), body)
|
|
382
|
+
if (!ctx.allowWrite && !isReadOnlyRenderMethod(method))
|
|
383
|
+
return errorResult(`Rendering a ${method} runs the app's actions and handlers, which may write: start \`prunelle mcp --allow-write\`, or render with GET.`)
|
|
384
|
+
const headers = normalizeRenderHeaders(args.headers)
|
|
385
|
+
const cookies = normalizeStringArray(args.cookies, 'cookies')
|
|
386
|
+
const fresh = optionalBoolean(args, 'fresh') === true
|
|
387
|
+
const result = await renderUrl({ root: targetDir, url, method, body, headers, cookies, fresh })
|
|
388
|
+
return jsonResult({
|
|
389
|
+
status: result.status,
|
|
390
|
+
statusText: result.statusText,
|
|
391
|
+
ok: result.ok,
|
|
392
|
+
headers: result.headers,
|
|
393
|
+
setCookies: result.setCookies,
|
|
394
|
+
body: result.body,
|
|
395
|
+
...(result.isBinary === true ? { isBinary: true, encoding: 'base64' } : {}),
|
|
396
|
+
reusedBuild: result.reusedBuild,
|
|
397
|
+
errors: result.errors,
|
|
398
|
+
})
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function runDocsTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): McpToolCallResult {
|
|
402
|
+
const query = optionalString(args, 'query')
|
|
403
|
+
if (query === undefined)
|
|
404
|
+
throw new Error('prunelle mcp: "query" is required and must be a string')
|
|
405
|
+
let limit: number | undefined
|
|
406
|
+
if (args.limit !== undefined) {
|
|
407
|
+
if (typeof args.limit !== 'number' || !Number.isFinite(args.limit))
|
|
408
|
+
throw new Error('prunelle mcp: "limit" must be a finite number')
|
|
409
|
+
limit = args.limit
|
|
410
|
+
}
|
|
411
|
+
const result = searchLlmsDocs(ctx.root, query, { limit })
|
|
412
|
+
return jsonResult({
|
|
413
|
+
query: result.query,
|
|
414
|
+
words: result.words,
|
|
415
|
+
packages: result.packages,
|
|
416
|
+
matches: result.matches,
|
|
417
|
+
})
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function runDevErrorsTool(ctx: PrunelleMcpContext, args: Record<string, unknown>): McpToolCallResult {
|
|
421
|
+
const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
|
|
422
|
+
const log = readDevErrorLog(targetDir)
|
|
423
|
+
if (log === undefined) {
|
|
424
|
+
return jsonResult({
|
|
425
|
+
hasErrors: false,
|
|
426
|
+
runtimeErrors: [],
|
|
427
|
+
note: 'No dev errors recorded (start `prunelle dev` or no errors have occurred).',
|
|
428
|
+
})
|
|
429
|
+
}
|
|
430
|
+
const hasErrors = log.buildError !== undefined || log.crashError !== undefined || log.runtimeErrors.length > 0
|
|
431
|
+
return jsonResult({
|
|
432
|
+
hasErrors,
|
|
433
|
+
updatedAt: log.updatedAt,
|
|
434
|
+
...(log.buildError !== undefined ? { buildError: log.buildError } : {}),
|
|
435
|
+
...(log.crashError !== undefined ? { crashError: log.crashError } : {}),
|
|
436
|
+
runtimeErrors: log.runtimeErrors,
|
|
437
|
+
})
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export type ToolHandler = (ctx: PrunelleMcpContext, args: Record<string, unknown>) => McpToolCallResult | Promise<McpToolCallResult>
|
|
441
|
+
|
|
442
|
+
const TOOL_HANDLERS: Record<string, ToolHandler> = {
|
|
443
|
+
check: runCheckTool,
|
|
444
|
+
inspect: runInspectTool,
|
|
445
|
+
build_analyze: runBuildAnalyzeTool,
|
|
446
|
+
build: runBuildTool,
|
|
447
|
+
render: runRenderTool,
|
|
448
|
+
docs: runDocsTool,
|
|
449
|
+
dev_errors: runDevErrorsTool,
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
export function hasPrunelleTool(name: string): boolean {
|
|
453
|
+
return Object.prototype.hasOwnProperty.call(TOOL_HANDLERS, name)
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export async function callPrunelleTool(ctx: PrunelleMcpContext, name: string, rawArgs: unknown): Promise<McpToolCallResult> {
|
|
457
|
+
const handler = TOOL_HANDLERS[name]
|
|
458
|
+
if (handler === undefined)
|
|
459
|
+
throw new Error(`Unknown tool: ${name}`)
|
|
460
|
+
try {
|
|
461
|
+
const args = asArgsRecord(rawArgs)
|
|
462
|
+
return await runWithFreshConfig(() => handler(ctx, args))
|
|
463
|
+
}
|
|
464
|
+
catch (err) {
|
|
465
|
+
return errorResult(err instanceof Error ? err.message : String(err))
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Lists every discovered `llms.txt` (`prunelle` and installed `@prunellejs/*` packages) as an MCP resource. */
|
|
470
|
+
export function listPrunelleResources(root: string): McpResource[] {
|
|
471
|
+
return discoverLlmsDocs(root).map(doc => ({
|
|
472
|
+
uri: `${LLMS_URI_PREFIX}${doc.packageName}`,
|
|
473
|
+
name: `${doc.packageName} llms.txt`,
|
|
474
|
+
description: `${doc.packageName}${doc.version !== undefined ? `@${doc.version}` : ''} reference (${doc.relFile})`,
|
|
475
|
+
mimeType: 'text/markdown',
|
|
476
|
+
}))
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Reads a `prunelle://llms/<package>` MCP resource fresh from disk, returning `undefined` when unknown. */
|
|
480
|
+
export function readPrunelleResource(root: string, uri: string): McpResourceContent | undefined {
|
|
481
|
+
if (!uri.startsWith(LLMS_URI_PREFIX))
|
|
482
|
+
return undefined
|
|
483
|
+
const targetPkg = uri.slice(LLMS_URI_PREFIX.length)
|
|
484
|
+
const doc = discoverLlmsDocs(root).find(d => d.packageName === targetPkg)
|
|
485
|
+
if (doc === undefined)
|
|
486
|
+
return undefined
|
|
487
|
+
return {
|
|
488
|
+
uri,
|
|
489
|
+
mimeType: 'text/markdown',
|
|
490
|
+
text: doc.content,
|
|
491
|
+
}
|
|
492
|
+
}
|
package/src/cli/mcp.ts
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Built-in `prunelle mcp` stdio JSON-RPC 2.0 server (MCP 2025-03-26, zero external dependencies).
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { join, resolve } from 'node:path'
|
|
5
|
+
import {
|
|
6
|
+
callPrunelleTool,
|
|
7
|
+
hasPrunelleTool,
|
|
8
|
+
listPrunelleResources,
|
|
9
|
+
listPrunelleTools,
|
|
10
|
+
readPrunelleResource,
|
|
11
|
+
} from './mcp-tools'
|
|
12
|
+
|
|
13
|
+
export const PRUNELLE_MCP_PROTOCOL_VERSION = '2025-03-26'
|
|
14
|
+
|
|
15
|
+
export interface PrunelleMcpOptions {
|
|
16
|
+
root: string
|
|
17
|
+
allowWrite?: boolean | undefined
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface JsonRpcRequest {
|
|
21
|
+
jsonrpc: '2.0'
|
|
22
|
+
id?: string | number | null | undefined
|
|
23
|
+
method: string
|
|
24
|
+
params?: Record<string, unknown> | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface JsonRpcResponse {
|
|
28
|
+
jsonrpc: '2.0'
|
|
29
|
+
id: string | number | null
|
|
30
|
+
result?: unknown
|
|
31
|
+
error?: { code: number, message: string, data?: unknown }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readPrunelleVersion(): string {
|
|
35
|
+
try {
|
|
36
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, '../../package.json'), 'utf8')) as { version?: unknown }
|
|
37
|
+
return typeof pkg.version === 'string' && pkg.version.length > 0 ? pkg.version : '0.0.0'
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return '0.0.0'
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const PRUNELLE_VERSION = readPrunelleVersion()
|
|
45
|
+
|
|
46
|
+
const SERVER_INSTRUCTIONS = [
|
|
47
|
+
'Prunelle development MCP server.',
|
|
48
|
+
'Read `prunelle://llms/*` resources or call `docs` for framework and plugin APIs.',
|
|
49
|
+
'Use `check`, `inspect`, `build_analyze`, `render`, and `dev_errors` to verify and debug the app.',
|
|
50
|
+
'Tools that write build output (`build`, or `build_analyze` with `write: true` / `outDir`) and `render` with a method other than GET, HEAD or OPTIONS require `--allow-write`.',
|
|
51
|
+
].join(' ')
|
|
52
|
+
|
|
53
|
+
function rpcError(id: string | number | null, code: number, message: string): JsonRpcResponse {
|
|
54
|
+
return { jsonrpc: '2.0', id, error: { code, message } }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function rpcResult(id: string | number | null, result: unknown): JsonRpcResponse {
|
|
58
|
+
return { jsonrpc: '2.0', id, result }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function asParamsRecord(params: unknown): Record<string, unknown> | undefined {
|
|
62
|
+
if (params === undefined || params === null)
|
|
63
|
+
return undefined
|
|
64
|
+
if (typeof params === 'object' && !Array.isArray(params))
|
|
65
|
+
return params as Record<string, unknown>
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Creates an in-process JSON-RPC 2.0 dispatcher for `prunelle mcp` (used by both stdio transport and unit tests). */
|
|
70
|
+
export function createPrunelleMcpDispatcher(options: PrunelleMcpOptions): {
|
|
71
|
+
handleMessage: (msg: unknown) => Promise<unknown | undefined>
|
|
72
|
+
handleLine: (line: string) => Promise<string | undefined>
|
|
73
|
+
} {
|
|
74
|
+
const ctx = {
|
|
75
|
+
root: resolve(options.root),
|
|
76
|
+
allowWrite: options.allowWrite === true,
|
|
77
|
+
}
|
|
78
|
+
const tools = listPrunelleTools()
|
|
79
|
+
const toolNamesHint = tools.map(t => t.name).join(', ')
|
|
80
|
+
|
|
81
|
+
async function handleMessage(msg: unknown): Promise<JsonRpcResponse | undefined> {
|
|
82
|
+
if (typeof msg !== 'object' || msg === null || Array.isArray(msg))
|
|
83
|
+
return rpcError(null, -32600, 'Invalid Request')
|
|
84
|
+
|
|
85
|
+
const req = msg as Partial<JsonRpcRequest>
|
|
86
|
+
const hasId = 'id' in req && req.id !== undefined
|
|
87
|
+
const id = hasId ? (req.id ?? null) : null
|
|
88
|
+
|
|
89
|
+
if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
|
|
90
|
+
return rpcError(id, -32600, 'Invalid Request')
|
|
91
|
+
|
|
92
|
+
// JSON-RPC notifications (no `id`) produce no response.
|
|
93
|
+
if (!hasId)
|
|
94
|
+
return undefined
|
|
95
|
+
|
|
96
|
+
switch (req.method) {
|
|
97
|
+
case 'initialize':
|
|
98
|
+
return rpcResult(id, {
|
|
99
|
+
protocolVersion: PRUNELLE_MCP_PROTOCOL_VERSION,
|
|
100
|
+
capabilities: {
|
|
101
|
+
tools: { listChanged: false },
|
|
102
|
+
resources: { subscribe: false, listChanged: false },
|
|
103
|
+
},
|
|
104
|
+
serverInfo: { name: 'prunelle', version: PRUNELLE_VERSION },
|
|
105
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
case 'ping':
|
|
109
|
+
return rpcResult(id, {})
|
|
110
|
+
|
|
111
|
+
case 'tools/list':
|
|
112
|
+
return rpcResult(id, { tools })
|
|
113
|
+
|
|
114
|
+
case 'tools/call': {
|
|
115
|
+
const params = asParamsRecord(req.params)
|
|
116
|
+
const toolName = typeof params?.name === 'string' ? params.name : undefined
|
|
117
|
+
if (toolName === undefined)
|
|
118
|
+
return rpcError(id, -32602, 'Missing tool name')
|
|
119
|
+
if (!hasPrunelleTool(toolName))
|
|
120
|
+
return rpcError(id, -32602, `Unknown tool: ${toolName} (available: ${toolNamesHint})`)
|
|
121
|
+
const toolResult = await callPrunelleTool(ctx, toolName, params?.arguments)
|
|
122
|
+
return rpcResult(id, toolResult)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
case 'resources/list':
|
|
126
|
+
return rpcResult(id, { resources: listPrunelleResources(ctx.root) })
|
|
127
|
+
|
|
128
|
+
case 'resources/read': {
|
|
129
|
+
const params = asParamsRecord(req.params)
|
|
130
|
+
const uri = typeof params?.uri === 'string' ? params.uri : undefined
|
|
131
|
+
if (uri === undefined)
|
|
132
|
+
return rpcError(id, -32602, 'Missing resource uri')
|
|
133
|
+
const content = readPrunelleResource(ctx.root, uri)
|
|
134
|
+
if (content === undefined)
|
|
135
|
+
return rpcError(id, -32002, `Unknown resource: ${uri}`)
|
|
136
|
+
return rpcResult(id, { contents: [content] })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
default:
|
|
140
|
+
return rpcError(id, -32601, `Method not found: ${req.method}`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function handleLine(line: string): Promise<string | undefined> {
|
|
145
|
+
const trimmed = line.trim()
|
|
146
|
+
if (trimmed.length === 0)
|
|
147
|
+
return undefined
|
|
148
|
+
let parsed: unknown
|
|
149
|
+
try {
|
|
150
|
+
parsed = JSON.parse(trimmed)
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return JSON.stringify(rpcError(null, -32700, 'Parse error'))
|
|
154
|
+
}
|
|
155
|
+
const response = await handleMessage(parsed)
|
|
156
|
+
return response !== undefined ? JSON.stringify(response) : undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return { handleMessage, handleLine }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Runs the `prunelle mcp` stdio JSON-RPC 2.0 loop, redirecting console/stdout logs to stderr so framing stays clean. */
|
|
163
|
+
export async function runPrunelleMcpStdio(options: PrunelleMcpOptions): Promise<number> {
|
|
164
|
+
const dispatcher = createPrunelleMcpDispatcher(options)
|
|
165
|
+
const writeFrame = process.stdout.write.bind(process.stdout)
|
|
166
|
+
const origStdoutWrite = process.stdout.write
|
|
167
|
+
const origConsoleLog = console.log
|
|
168
|
+
const origConsoleInfo = console.info
|
|
169
|
+
const origConsoleDebug = console.debug
|
|
170
|
+
|
|
171
|
+
process.stdout.write = process.stderr.write.bind(process.stderr)
|
|
172
|
+
console.log = console.error
|
|
173
|
+
console.info = console.error
|
|
174
|
+
console.debug = console.error
|
|
175
|
+
|
|
176
|
+
const emit = (line: string | undefined): void => {
|
|
177
|
+
if (line !== undefined)
|
|
178
|
+
writeFrame(`${line}\n`)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const decoder = new TextDecoder()
|
|
183
|
+
let buffer = ''
|
|
184
|
+
for await (const chunk of process.stdin) {
|
|
185
|
+
buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })
|
|
186
|
+
let newlineIdx = buffer.indexOf('\n')
|
|
187
|
+
while (newlineIdx !== -1) {
|
|
188
|
+
const line = buffer.slice(0, newlineIdx)
|
|
189
|
+
buffer = buffer.slice(newlineIdx + 1)
|
|
190
|
+
emit(await dispatcher.handleLine(line))
|
|
191
|
+
newlineIdx = buffer.indexOf('\n')
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const trailing = buffer + decoder.decode()
|
|
195
|
+
if (trailing.trim().length > 0)
|
|
196
|
+
emit(await dispatcher.handleLine(trailing))
|
|
197
|
+
return 0
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
process.stdout.write = origStdoutWrite
|
|
201
|
+
console.log = origConsoleLog
|
|
202
|
+
console.info = origConsoleInfo
|
|
203
|
+
console.debug = origConsoleDebug
|
|
204
|
+
}
|
|
205
|
+
}
|