prunelle 0.1.1 → 0.5.1
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/llms.txt +23 -19
- package/package.json +8 -2
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +3 -2
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +8 -4
- package/src/build/client-prune.ts +11 -2
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +229 -0
- package/src/build/index.ts +121 -44
- package/src/build/manifest.ts +66 -5
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +91 -33
- package/src/build/precompress.ts +15 -2
- package/src/build/prerender.ts +2 -2
- package/src/build/report.ts +23 -2
- package/src/build/resolve.ts +4 -3
- package/src/build/routes.ts +175 -10
- package/src/build/static.ts +71 -17
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +338 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +52 -5
- package/src/cli/commands.ts +86 -4
- package/src/cli/docs.ts +402 -0
- package/src/cli/inspect.ts +31 -2
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +2 -2
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +137 -16
- package/src/compiler/analyze.ts +17 -3
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +120 -221
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom.ts +7 -7
- package/src/compiler/ssr.ts +135 -37
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +60 -29
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +3 -0
- package/src/dom/action.ts +4 -1
- package/src/dom/island.ts +11 -10
- package/src/plugins/config.ts +4 -4
- package/src/plugins/index.ts +2 -2
- package/src/plugins/public.ts +5 -2
- package/src/plugins/services.ts +62 -0
- package/src/plugins/types.ts +32 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +82 -27
- package/src/server/errors.ts +291 -62
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +86 -19
- package/src/server/index.ts +158 -219
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +40 -14
- package/src/server/public.ts +3 -3
- package/src/server/rate-limit.ts +58 -35
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +365 -0
- package/src/server/route-table.ts +302 -6
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +187 -61
- package/src/server/security.ts +208 -32
- package/src/server/serve-handlers.ts +21 -7
- package/src/ssr/context.ts +49 -0
- package/src/ssr/index.ts +120 -1
- package/src/test/browser.ts +6 -0
- package/src/test/index.ts +17 -3
- package/src/ts-plugin/diagnostics.ts +378 -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/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +5 -0
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/index.tsx +4 -0
- package/ts-plugin.cjs +4277 -0
package/src/cli/check.ts
CHANGED
|
@@ -3,20 +3,24 @@
|
|
|
3
3
|
import type { IslandIssue } from '../build/islands'
|
|
4
4
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
5
|
import type { ComplianceConfig } from '../compiler/compliance'
|
|
6
|
-
import type { CheckPluginContext, PrunellePlugin } from '../plugins/index'
|
|
6
|
+
import type { CheckPluginContext, PrunelleConfig, PrunellePlugin } from '../plugins/index'
|
|
7
7
|
import { existsSync, readFileSync } from 'node:fs'
|
|
8
8
|
import { basename, join, relative, resolve } from 'node:path'
|
|
9
9
|
import { isInNodeModules, isNotSourceDir, isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
|
|
10
10
|
import { ModuleGraph } from '../build/graph'
|
|
11
11
|
import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from '../build/render-rules'
|
|
12
12
|
import { analyzeIslands } from '../build/islands'
|
|
13
|
-
import { fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
13
|
+
import { ancestorFiles, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblemLocation, routeFileProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
|
|
14
|
+
import { findUnknownStatusPages } from '../build/status-pages'
|
|
14
15
|
import { analyzeModule } from '../compiler/analyze'
|
|
16
|
+
import { findCachedRoutePrivateReads } from '../compiler/cacheability'
|
|
15
17
|
import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
|
|
16
18
|
import { collectMistakes, PrunelleMistake, serverOnlyTagError } from '../compiler/mistakes'
|
|
17
19
|
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc } from '../compiler/shared'
|
|
18
20
|
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
19
21
|
import { collectRequirements } from '../plugins/requires'
|
|
22
|
+
import { checkAppForms } from './check-forms'
|
|
23
|
+
import { checkAppLinks } from './check-links'
|
|
20
24
|
|
|
21
25
|
/** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
|
|
22
26
|
export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
|
|
@@ -176,7 +180,7 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
|
|
|
176
180
|
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
|
|
177
181
|
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, outDir: string, assetPrefix: string, site: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
|
|
178
182
|
const { root, routesDir, outDir, assetPrefix, site } = paths
|
|
179
|
-
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, dev: false })
|
|
183
|
+
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
|
|
180
184
|
const placed = (message: string, severity: 'error' | 'warning'): string =>
|
|
181
185
|
DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
|
|
182
186
|
const pluginCtx: CheckPluginContext = {
|
|
@@ -184,6 +188,8 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
|
|
|
184
188
|
routesDir,
|
|
185
189
|
error: message => errors.push(placed(message, 'error')),
|
|
186
190
|
warn: message => warnings.push(placed(message, 'warning')),
|
|
191
|
+
provide: appCtx.provide,
|
|
192
|
+
inject: appCtx.inject,
|
|
187
193
|
}
|
|
188
194
|
for (const plugin of plugins) {
|
|
189
195
|
if (plugin.check === undefined)
|
|
@@ -210,12 +216,15 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
210
216
|
// 1. Validate prunelle.config.ts
|
|
211
217
|
let routesDir = resolve(root, 'src/routes')
|
|
212
218
|
let outDir = resolve(root, 'dist')
|
|
219
|
+
let publicDir = resolve(root, 'public')
|
|
213
220
|
let assetPrefix = '/_pru'
|
|
214
221
|
let site: string | undefined
|
|
215
222
|
let compliance: ComplianceConfig | undefined
|
|
223
|
+
let loadedConfig: PrunelleConfig = {}
|
|
216
224
|
let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
|
|
217
225
|
try {
|
|
218
226
|
const cfg = await loadConfig(root)
|
|
227
|
+
loadedConfig = cfg
|
|
219
228
|
plugins = resolvePlugins(cfg.plugins)
|
|
220
229
|
site = cfg.site
|
|
221
230
|
compliance = cfg.compliance
|
|
@@ -223,6 +232,8 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
223
232
|
routesDir = resolve(root, cfg.routesDir)
|
|
224
233
|
if (cfg.outDir !== undefined)
|
|
225
234
|
outDir = resolve(root, cfg.outDir)
|
|
235
|
+
if (cfg.publicDir !== undefined)
|
|
236
|
+
publicDir = resolve(root, cfg.publicDir)
|
|
226
237
|
if (cfg.assetPrefix !== undefined)
|
|
227
238
|
assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
|
|
228
239
|
}
|
|
@@ -265,9 +276,19 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
265
276
|
|
|
266
277
|
// Exact route discovery matching `prunelle build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
|
|
267
278
|
const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
|
|
279
|
+
for (const unknown of findUnknownStatusPages(root, routeFiles))
|
|
280
|
+
errors.push(formatDiagnostic(`${relPosix(root, unknown.file)}:1:1`, `prunelle check: ${unknown.message}`))
|
|
268
281
|
const routeFileSet = new Set(routeFiles)
|
|
269
282
|
const specialFiles = routeFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
|
|
270
283
|
const pageFiles = routeFiles.filter(f => !basename(f).startsWith('_') && analyses.has(f) && hasRouteHandlerExport(analyses.get(f)!))
|
|
284
|
+
const matcherDiscovery = discoverRouteMatchers({
|
|
285
|
+
root,
|
|
286
|
+
routesDir,
|
|
287
|
+
routeFiles: [...specialFiles, ...pageFiles],
|
|
288
|
+
loadAnalysis: load,
|
|
289
|
+
})
|
|
290
|
+
for (const problem of matcherDiscovery.problems)
|
|
291
|
+
errors.push(formatDiagnostic(`${relPosix(root, problem.file)}:1:1`, `prunelle check: ${problem.message}`))
|
|
271
292
|
|
|
272
293
|
// 3a. Unified island planning, state-read promotion, special-file checks & reachability checks (shared with `prunelle build`)
|
|
273
294
|
const islands = analyzeIslands({
|
|
@@ -288,6 +309,13 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
288
309
|
if (isInNodeModules(file))
|
|
289
310
|
continue
|
|
290
311
|
const rel = relPosix(root, file)
|
|
312
|
+
for (const imp of analysis.imports) {
|
|
313
|
+
if (imp.source === '@prunellejs/auth') {
|
|
314
|
+
const removed = imp.specifiers.find(s => s.imported === 'createRateLimiter' || s.imported === 'RateLimiter')
|
|
315
|
+
if (removed !== undefined)
|
|
316
|
+
warnings.push(formatDiagnostic(locOf(root, file, sources, imp.start), `prunelle check: ${removed.imported} was removed from @prunellejs/auth in 0.2.0: use \`rateLimit\` on \`api.route()\`/\`action()\`, \`api.rateLimiter()\` in a plugin, or \`createRateLimitStore()\` from \`prunelle/server\`.`, 'warning'))
|
|
317
|
+
}
|
|
318
|
+
}
|
|
291
319
|
for (const offset of serverNodeEnvReads(analysis, islands, file))
|
|
292
320
|
warnings.push(formatDiagnostic(locOf(root, file, sources, offset), nodeEnvWarning(rel), 'warning'))
|
|
293
321
|
|
|
@@ -322,10 +350,29 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
322
350
|
}
|
|
323
351
|
}
|
|
324
352
|
|
|
325
|
-
// 3c.
|
|
353
|
+
// 3c. Cached route private-read guardrails (#6)
|
|
354
|
+
for (const problem of findCachedRoutePrivateReads({
|
|
355
|
+
graph,
|
|
356
|
+
pageFiles,
|
|
357
|
+
layoutsFor: file => ancestorFiles(routesDir, file, ['_layout.tsx']),
|
|
358
|
+
toRel: file => relPosix(root, file),
|
|
359
|
+
tool: 'prunelle check',
|
|
360
|
+
})) {
|
|
361
|
+
errors.push(formatDiagnostic(locOf(root, problem.file, sources, problem.offset), problem.message))
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// 3d. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
|
|
326
365
|
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, site }))
|
|
327
366
|
|
|
328
|
-
// 3d.
|
|
367
|
+
// 3d. Form field / schema checks & public action protection warnings (#4, #5)
|
|
368
|
+
const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources })
|
|
369
|
+
errors.push(...formCheck.errors)
|
|
370
|
+
warnings.push(...formCheck.warnings)
|
|
371
|
+
|
|
372
|
+
// 3e. Broken internal link checks (#3)
|
|
373
|
+
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
|
|
374
|
+
|
|
375
|
+
// 3f. Plugin check(ctx) hooks
|
|
329
376
|
await runPluginChecks(plugins, { root, routesDir, outDir, assetPrefix, site }, errors, warnings)
|
|
330
377
|
|
|
331
378
|
const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
|
package/src/cli/commands.ts
CHANGED
|
@@ -123,13 +123,15 @@ function upgradeCommand(cwd: string): Commands[string] {
|
|
|
123
123
|
const res = upgradeProject(root)
|
|
124
124
|
for (const file of res.changed)
|
|
125
125
|
console.log(` ${file}`)
|
|
126
|
-
console.log(`prunelle upgrade rewrote ${res.changed.length}
|
|
127
|
-
|
|
126
|
+
console.log(`prunelle upgrade rewrote ${res.changed.length} file${res.changed.length === 1 ? '' : 's'}`)
|
|
127
|
+
// The dependencies moved: the first run for this app, which renames its cookies; a later run only fixes what an older prunelle left.
|
|
128
|
+
const moved = res.changed.some(file => file === 'package.json' || file.endsWith('/package.json'))
|
|
129
|
+
if (moved && values['no-install'] !== true) {
|
|
128
130
|
const install = Bun.spawnSync(['bun', 'install'], { cwd: root, stdout: 'inherit', stderr: 'inherit' })
|
|
129
131
|
if (install.exitCode !== 0)
|
|
130
132
|
return 1
|
|
131
133
|
}
|
|
132
|
-
if (
|
|
134
|
+
if (moved)
|
|
133
135
|
console.log('Signed-in users sign in again and visitors answer the cookie banner again: prunelle names its cookies pru_session and pru_consent.')
|
|
134
136
|
for (const line of res.manual)
|
|
135
137
|
console.error(line)
|
|
@@ -163,6 +165,7 @@ function buildCommand(cwd: string): Commands[string] {
|
|
|
163
165
|
run: async (args) => {
|
|
164
166
|
const { values, positionals: [dir] } = parse(args, 'prunelle build [options] [dir]: builds the app into dist/', {
|
|
165
167
|
'static': { type: 'boolean', description: 'export plain HTML files instead of a server' },
|
|
168
|
+
'auto-prerender': { type: 'boolean', description: 'prerender static pages that read nothing from the request or clock' },
|
|
166
169
|
'compile': { type: 'string', optional: { bare: '' }, description: 'also produce one binary, at [out] when given' },
|
|
167
170
|
'analyze': { type: 'boolean', description: 'list each island with why it is one' },
|
|
168
171
|
'json': { type: 'boolean', description: 'with --analyze, print the bundle report as JSON' },
|
|
@@ -176,7 +179,8 @@ function buildCommand(cwd: string): Commands[string] {
|
|
|
176
179
|
const analyzeJson = values.analyze === true && values.json === true
|
|
177
180
|
const { build } = await import('../build/index')
|
|
178
181
|
const t0 = performance.now()
|
|
179
|
-
const
|
|
182
|
+
const autoPrerender = values['auto-prerender'] === true ? true : undefined
|
|
183
|
+
const manifest = await failing('build', async () => build({ root: rootOf(cwd, values.root, dir), static: values.static === true, autoPrerender, compile, analyze: values.analyze === true, analyzeJson, maxJs }))
|
|
180
184
|
const ms = (performance.now() - t0).toFixed(1)
|
|
181
185
|
if (!analyzeJson)
|
|
182
186
|
console.log(`prunelle build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
|
|
@@ -227,11 +231,89 @@ function devCommand(cwd: string): Commands[string] {
|
|
|
227
231
|
}
|
|
228
232
|
}
|
|
229
233
|
|
|
234
|
+
function docsCommand(cwd: string): Commands[string] {
|
|
235
|
+
return {
|
|
236
|
+
summary: 'search llms.txt across prunelle and installed plugins',
|
|
237
|
+
run: async (args) => {
|
|
238
|
+
const { values, positionals } = parse(args, 'prunelle docs [options] <words...>: searches llms.txt of prunelle and every installed @prunellejs/* package', {
|
|
239
|
+
json: { type: 'boolean', description: 'print { query, words, packages, matches } as JSON' },
|
|
240
|
+
limit: { type: 'string', description: 'maximum matching sections to print (default: 20)' },
|
|
241
|
+
root: ROOT,
|
|
242
|
+
}, { positionals: ['<words...>'], exits: [OK, [1, 'no matching section found'], USAGE_EXIT] })
|
|
243
|
+
const limit = values.limit === undefined ? undefined : Number(values.limit)
|
|
244
|
+
if (limit !== undefined && (!Number.isInteger(limit) || limit <= 0))
|
|
245
|
+
return badUsage(`invalid --limit "${values.limit}": give a positive integer`)
|
|
246
|
+
const query = positionals.join(' ').trim()
|
|
247
|
+
if (query === '')
|
|
248
|
+
return badUsage('give at least one search word, e.g. prunelle docs action')
|
|
249
|
+
const { formatDocsSearchResult, searchLlmsDocs } = await import('./docs')
|
|
250
|
+
const result = searchLlmsDocs(rootOf(cwd, values.root, undefined), query, { limit })
|
|
251
|
+
if (values.json === true) {
|
|
252
|
+
console.log(JSON.stringify(result, null, 2))
|
|
253
|
+
return result.matches.length > 0 ? 0 : 1
|
|
254
|
+
}
|
|
255
|
+
console.log(formatDocsSearchResult(result))
|
|
256
|
+
return result.matches.length > 0 ? 0 : 1
|
|
257
|
+
},
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function renderCommand(cwd: string): Commands[string] {
|
|
262
|
+
return {
|
|
263
|
+
summary: 'render a URL in-process without binding a port',
|
|
264
|
+
run: async (args) => {
|
|
265
|
+
const { values, positionals: [url] } = parse(args, 'prunelle render [options] <url>: builds or reuses a test build and prints the response with no port bound', {
|
|
266
|
+
method: { type: 'string', short: 'X', description: 'HTTP method (default: GET, or POST when --body is passed)' },
|
|
267
|
+
body: { type: 'string', short: 'd', description: 'request body string' },
|
|
268
|
+
header: { type: 'string', short: 'H', multiple: true, description: 'request header as "Name: Value" (repeatable)' },
|
|
269
|
+
cookie: { type: 'string', short: 'b', multiple: true, description: 'request cookie as "name=value" (repeatable)' },
|
|
270
|
+
include: { type: 'boolean', short: 'i', description: 'include HTTP status line and response headers before the body' },
|
|
271
|
+
fresh: { type: 'boolean', description: 'force a fresh build instead of reusing the cached render build' },
|
|
272
|
+
root: ROOT,
|
|
273
|
+
}, { positionals: ['<url>'], exits: [[0, 'response status is 2xx or 3xx'], [1, 'response status is 4xx/5xx or the render failed'], USAGE_EXIT] })
|
|
274
|
+
const { formatRenderResult, renderUrl } = await import('./render')
|
|
275
|
+
const result = await failing('render', () => renderUrl({
|
|
276
|
+
root: rootOf(cwd, values.root, undefined),
|
|
277
|
+
url: url!,
|
|
278
|
+
method: values.method,
|
|
279
|
+
body: values.body,
|
|
280
|
+
headers: values.header,
|
|
281
|
+
cookies: values.cookie,
|
|
282
|
+
includeHeaders: values.include === true,
|
|
283
|
+
fresh: values.fresh === true,
|
|
284
|
+
}))
|
|
285
|
+
const out = formatRenderResult(result, values.include === true)
|
|
286
|
+
process.stdout.write(out.endsWith('\n') || out.length === 0 ? out : `${out}\n`)
|
|
287
|
+
return result.ok ? 0 : 1
|
|
288
|
+
},
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function mcpCommand(cwd: string): Commands[string] {
|
|
293
|
+
return {
|
|
294
|
+
summary: 'run the Prunelle stdio MCP server for coding agents',
|
|
295
|
+
run: async (args) => {
|
|
296
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle mcp [options] [dir]: runs a stdio MCP server exposing check, inspect, build analysis, render, docs, dev errors, and llms.txt resources', {
|
|
297
|
+
'allow-write': { type: 'boolean', description: 'allow MCP tools that write build output to disk' },
|
|
298
|
+
'root': ROOT,
|
|
299
|
+
}, { positionals: ['[dir]'], exits: [OK, [1, 'the MCP server exited with an error'], USAGE_EXIT] })
|
|
300
|
+
const { runPrunelleMcpStdio } = await import('./mcp')
|
|
301
|
+
return await failing('mcp', () => runPrunelleMcpStdio({
|
|
302
|
+
root: rootOf(cwd, values.root, dir),
|
|
303
|
+
allowWrite: values['allow-write'] === true,
|
|
304
|
+
}))
|
|
305
|
+
},
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
230
309
|
export function builtinCommands(cwd: string): Commands {
|
|
231
310
|
return {
|
|
232
311
|
new: newCommand(cwd),
|
|
233
312
|
check: checkCommand(cwd),
|
|
234
313
|
inspect: inspectCommand(cwd),
|
|
314
|
+
docs: docsCommand(cwd),
|
|
315
|
+
render: renderCommand(cwd),
|
|
316
|
+
mcp: mcpCommand(cwd),
|
|
235
317
|
dev: devCommand(cwd),
|
|
236
318
|
build: buildCommand(cwd),
|
|
237
319
|
start: startCommand(cwd),
|
package/src/cli/docs.ts
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
// `prunelle docs <words>`: discover and search installed `llms.txt` files for `prunelle` and `@prunellejs/*` packages.
|
|
2
|
+
|
|
3
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import { relPosix } from '../build/files'
|
|
6
|
+
|
|
7
|
+
const HEADING_RE = /^(#{1,3})\s+(.+?)\s*$/
|
|
8
|
+
const BOLD_BULLET_RE = /^- \*\*(.+?)\*\*/
|
|
9
|
+
const FENCE_RE = /^\s*```/
|
|
10
|
+
const WORD_SPLIT_RE = /\s+/
|
|
11
|
+
const SCOPED_PACKAGE_DIRS = ['@prunellejs', '@prunelle'] as const
|
|
12
|
+
const DEFAULT_LIMIT = 20
|
|
13
|
+
|
|
14
|
+
export interface LlmsPackageDoc {
|
|
15
|
+
packageName: string
|
|
16
|
+
version: string | undefined
|
|
17
|
+
file: string
|
|
18
|
+
relFile: string
|
|
19
|
+
content: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DocsMatch {
|
|
23
|
+
packageName: string
|
|
24
|
+
version: string | undefined
|
|
25
|
+
file: string
|
|
26
|
+
relFile: string
|
|
27
|
+
heading: string
|
|
28
|
+
line: number
|
|
29
|
+
score: number
|
|
30
|
+
content: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DocsSearchResult {
|
|
34
|
+
query: string
|
|
35
|
+
words: string[]
|
|
36
|
+
packages: { name: string, version: string | undefined, file: string }[]
|
|
37
|
+
matches: DocsMatch[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface ParsedSection {
|
|
41
|
+
heading: string
|
|
42
|
+
line: number
|
|
43
|
+
content: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface HeadingBlock {
|
|
47
|
+
heading: string
|
|
48
|
+
line: number
|
|
49
|
+
lines: { num: number, text: string }[]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isFile(path: string): boolean {
|
|
53
|
+
const st = statSync(path, { throwIfNoEntry: false })
|
|
54
|
+
return st !== undefined && st.isFile()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function isDirectory(path: string): boolean {
|
|
58
|
+
const st = statSync(path, { throwIfNoEntry: false })
|
|
59
|
+
return st !== undefined && st.isDirectory()
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readPackageMeta(pkgDir: string, fallbackName: string): { name: string, version: string | undefined } {
|
|
63
|
+
const pkgJsonPath = join(pkgDir, 'package.json')
|
|
64
|
+
if (!isFile(pkgJsonPath))
|
|
65
|
+
return { name: fallbackName, version: undefined }
|
|
66
|
+
try {
|
|
67
|
+
const parsed = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as { name?: unknown, version?: unknown }
|
|
68
|
+
const name = typeof parsed.name === 'string' && parsed.name.length > 0 ? parsed.name : fallbackName
|
|
69
|
+
const version = typeof parsed.version === 'string' && parsed.version.length > 0 ? parsed.version : undefined
|
|
70
|
+
return { name, version }
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return { name: fallbackName, version: undefined }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function addPackageDoc(
|
|
78
|
+
docs: LlmsPackageDoc[],
|
|
79
|
+
seen: Set<string>,
|
|
80
|
+
root: string,
|
|
81
|
+
pkgDir: string,
|
|
82
|
+
fallbackName: string,
|
|
83
|
+
): void {
|
|
84
|
+
const llmsPath = join(pkgDir, 'llms.txt')
|
|
85
|
+
if (!isFile(llmsPath))
|
|
86
|
+
return
|
|
87
|
+
const meta = readPackageMeta(pkgDir, fallbackName)
|
|
88
|
+
if (seen.has(meta.name))
|
|
89
|
+
return
|
|
90
|
+
seen.add(meta.name)
|
|
91
|
+
docs.push({
|
|
92
|
+
packageName: meta.name,
|
|
93
|
+
version: meta.version,
|
|
94
|
+
file: llmsPath,
|
|
95
|
+
relFile: relPosix(root, llmsPath),
|
|
96
|
+
content: readFileSync(llmsPath, 'utf8'),
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function scanScopedPackages(
|
|
101
|
+
docs: LlmsPackageDoc[],
|
|
102
|
+
seen: Set<string>,
|
|
103
|
+
root: string,
|
|
104
|
+
nodeModulesDir: string,
|
|
105
|
+
): void {
|
|
106
|
+
for (const scope of SCOPED_PACKAGE_DIRS) {
|
|
107
|
+
const scopeDir = join(nodeModulesDir, scope)
|
|
108
|
+
if (!isDirectory(scopeDir))
|
|
109
|
+
continue
|
|
110
|
+
let entries: string[]
|
|
111
|
+
try {
|
|
112
|
+
entries = readdirSync(scopeDir)
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
continue
|
|
116
|
+
}
|
|
117
|
+
for (const entry of entries)
|
|
118
|
+
addPackageDoc(docs, seen, root, join(scopeDir, entry), `${scope}/${entry}`)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Discovers `llms.txt` files for `prunelle` and installed `@prunellejs/*` (and `@prunelle/*`) packages from `rootDir` up through ancestor `node_modules`. */
|
|
123
|
+
export function discoverLlmsDocs(rootDir: string): LlmsPackageDoc[] {
|
|
124
|
+
const root = resolve(rootDir)
|
|
125
|
+
const docs: LlmsPackageDoc[] = []
|
|
126
|
+
const seen = new Set<string>()
|
|
127
|
+
|
|
128
|
+
let dir = root
|
|
129
|
+
while (true) {
|
|
130
|
+
const nodeModulesDir = join(dir, 'node_modules')
|
|
131
|
+
if (isDirectory(nodeModulesDir)) {
|
|
132
|
+
if (!seen.has('prunelle'))
|
|
133
|
+
addPackageDoc(docs, seen, root, join(nodeModulesDir, 'prunelle'), 'prunelle')
|
|
134
|
+
scanScopedPackages(docs, seen, root, nodeModulesDir)
|
|
135
|
+
}
|
|
136
|
+
const parent = dirname(dir)
|
|
137
|
+
if (parent === dir)
|
|
138
|
+
break
|
|
139
|
+
dir = parent
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (!seen.has('prunelle'))
|
|
143
|
+
addPackageDoc(docs, seen, root, resolve(import.meta.dir, '../..'), 'prunelle')
|
|
144
|
+
|
|
145
|
+
docs.sort((a, b) => {
|
|
146
|
+
if (a.packageName === 'prunelle' && b.packageName !== 'prunelle')
|
|
147
|
+
return -1
|
|
148
|
+
if (b.packageName === 'prunelle' && a.packageName !== 'prunelle')
|
|
149
|
+
return 1
|
|
150
|
+
return a.packageName.localeCompare(b.packageName)
|
|
151
|
+
})
|
|
152
|
+
return docs
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function splitHeadingBlocks(content: string): HeadingBlock[] {
|
|
156
|
+
const rawLines = content.split(/\r?\n/)
|
|
157
|
+
const blocks: HeadingBlock[] = []
|
|
158
|
+
let current: HeadingBlock | undefined
|
|
159
|
+
let inFence = false
|
|
160
|
+
|
|
161
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
162
|
+
const text = rawLines[i]!
|
|
163
|
+
const num = i + 1
|
|
164
|
+
if (FENCE_RE.test(text))
|
|
165
|
+
inFence = !inFence
|
|
166
|
+
|
|
167
|
+
if (!inFence) {
|
|
168
|
+
const headingMatch = HEADING_RE.exec(text)
|
|
169
|
+
if (headingMatch !== null) {
|
|
170
|
+
current = { heading: headingMatch[2]!.trim(), line: num, lines: [] }
|
|
171
|
+
blocks.push(current)
|
|
172
|
+
continue
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (current === undefined) {
|
|
177
|
+
current = { heading: 'Overview', line: num, lines: [] }
|
|
178
|
+
blocks.push(current)
|
|
179
|
+
}
|
|
180
|
+
current.lines.push({ num, text })
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return blocks
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function flushLines(heading: string, line: number, lines: readonly { num: number, text: string }[], out: ParsedSection[]): void {
|
|
187
|
+
const text = lines.map(l => l.text).join('\n').trim()
|
|
188
|
+
if (text.length > 0)
|
|
189
|
+
out.push({ heading, line, content: text })
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function splitBlockSections(block: HeadingBlock): ParsedSection[] {
|
|
193
|
+
const hasBoldBullet = (() => {
|
|
194
|
+
let inFence = false
|
|
195
|
+
for (const l of block.lines) {
|
|
196
|
+
if (FENCE_RE.test(l.text))
|
|
197
|
+
inFence = !inFence
|
|
198
|
+
else if (!inFence && BOLD_BULLET_RE.test(l.text))
|
|
199
|
+
return true
|
|
200
|
+
}
|
|
201
|
+
return false
|
|
202
|
+
})()
|
|
203
|
+
|
|
204
|
+
if (!hasBoldBullet) {
|
|
205
|
+
const out: ParsedSection[] = []
|
|
206
|
+
flushLines(block.heading, block.line, block.lines, out)
|
|
207
|
+
return out
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const sections: ParsedSection[] = []
|
|
211
|
+
let activeBullet: { heading: string, line: number, lines: { num: number, text: string }[] } | undefined
|
|
212
|
+
let generalLines: { num: number, text: string }[] = []
|
|
213
|
+
let generalLine = block.line
|
|
214
|
+
let inFence = false
|
|
215
|
+
|
|
216
|
+
const flushActiveBullet = (): void => {
|
|
217
|
+
if (activeBullet !== undefined) {
|
|
218
|
+
flushLines(activeBullet.heading, activeBullet.line, activeBullet.lines, sections)
|
|
219
|
+
activeBullet = undefined
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const flushGeneral = (): void => {
|
|
224
|
+
if (generalLines.length > 0) {
|
|
225
|
+
flushLines(block.heading, generalLine, generalLines, sections)
|
|
226
|
+
generalLines = []
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for (const entry of block.lines) {
|
|
231
|
+
if (FENCE_RE.test(entry.text))
|
|
232
|
+
inFence = !inFence
|
|
233
|
+
|
|
234
|
+
if (!inFence) {
|
|
235
|
+
const bulletMatch = BOLD_BULLET_RE.exec(entry.text)
|
|
236
|
+
if (bulletMatch !== null) {
|
|
237
|
+
flushGeneral()
|
|
238
|
+
flushActiveBullet()
|
|
239
|
+
activeBullet = {
|
|
240
|
+
heading: `${block.heading} > ${bulletMatch[1]!.trim()}`,
|
|
241
|
+
line: entry.num,
|
|
242
|
+
lines: [entry],
|
|
243
|
+
}
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (activeBullet !== undefined) {
|
|
248
|
+
if (entry.text.trim() === '' || entry.text.startsWith(' ') || entry.text.startsWith('\t')) {
|
|
249
|
+
activeBullet.lines.push(entry)
|
|
250
|
+
continue
|
|
251
|
+
}
|
|
252
|
+
flushActiveBullet()
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
else if (activeBullet !== undefined) {
|
|
256
|
+
activeBullet.lines.push(entry)
|
|
257
|
+
continue
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (generalLines.length === 0)
|
|
261
|
+
generalLine = entry.num
|
|
262
|
+
generalLines.push(entry)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
flushActiveBullet()
|
|
266
|
+
flushGeneral()
|
|
267
|
+
return sections
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function parseSections(content: string): ParsedSection[] {
|
|
271
|
+
const blocks = splitHeadingBlocks(content)
|
|
272
|
+
const sections: ParsedSection[] = []
|
|
273
|
+
for (const block of blocks) {
|
|
274
|
+
for (const section of splitBlockSections(block))
|
|
275
|
+
sections.push(section)
|
|
276
|
+
}
|
|
277
|
+
return sections
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function countOccurrences(haystack: string, needle: string, maxCount: number): number {
|
|
281
|
+
let count = 0
|
|
282
|
+
let pos = 0
|
|
283
|
+
while (count < maxCount) {
|
|
284
|
+
const idx = haystack.indexOf(needle, pos)
|
|
285
|
+
if (idx === -1)
|
|
286
|
+
break
|
|
287
|
+
count++
|
|
288
|
+
pos = idx + needle.length
|
|
289
|
+
}
|
|
290
|
+
return count
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function escapeRegExp(text: string): string {
|
|
294
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function scoreSection(
|
|
298
|
+
pkgLower: string,
|
|
299
|
+
headingLower: string,
|
|
300
|
+
contentLower: string,
|
|
301
|
+
words: readonly string[],
|
|
302
|
+
phrase: string,
|
|
303
|
+
): number {
|
|
304
|
+
let score = 0
|
|
305
|
+
if (headingLower.includes(phrase))
|
|
306
|
+
score += 30
|
|
307
|
+
if (pkgLower.includes(phrase))
|
|
308
|
+
score += 25
|
|
309
|
+
if (contentLower.includes(phrase))
|
|
310
|
+
score += 10
|
|
311
|
+
|
|
312
|
+
for (const word of words) {
|
|
313
|
+
const wordBoundary = new RegExp(`(?:^|[^a-z0-9])${escapeRegExp(word)}(?:$|[^a-z0-9])`)
|
|
314
|
+
if (pkgLower.includes(word))
|
|
315
|
+
score += wordBoundary.test(pkgLower) ? 25 : 15
|
|
316
|
+
if (headingLower.includes(word))
|
|
317
|
+
score += wordBoundary.test(headingLower) ? 25 : 20
|
|
318
|
+
const bodyHits = countOccurrences(contentLower, word, 10)
|
|
319
|
+
score += bodyHits * 2
|
|
320
|
+
if (bodyHits > 0 && wordBoundary.test(contentLower))
|
|
321
|
+
score += 3
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
return score
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Searches installed `llms.txt` docs for every whitespace-separated word in `query` (case-insensitive AND). */
|
|
328
|
+
export function searchLlmsDocs(
|
|
329
|
+
rootDir: string,
|
|
330
|
+
query: string,
|
|
331
|
+
options?: { limit?: number | undefined },
|
|
332
|
+
): DocsSearchResult {
|
|
333
|
+
const docs = discoverLlmsDocs(rootDir)
|
|
334
|
+
const packages = docs.map(doc => ({ name: doc.packageName, version: doc.version, file: doc.relFile }))
|
|
335
|
+
const words = query.trim().toLowerCase().split(WORD_SPLIT_RE).filter(Boolean)
|
|
336
|
+
if (words.length === 0)
|
|
337
|
+
return { query, words: [], packages, matches: [] }
|
|
338
|
+
|
|
339
|
+
const phrase = words.join(' ')
|
|
340
|
+
const matches: DocsMatch[] = []
|
|
341
|
+
|
|
342
|
+
for (const doc of docs) {
|
|
343
|
+
const pkgLower = doc.packageName.toLowerCase()
|
|
344
|
+
for (const section of parseSections(doc.content)) {
|
|
345
|
+
const headingLower = section.heading.toLowerCase()
|
|
346
|
+
const contentLower = section.content.toLowerCase()
|
|
347
|
+
const combined = `${pkgLower} ${headingLower} ${contentLower}`
|
|
348
|
+
if (!words.every(word => combined.includes(word)))
|
|
349
|
+
continue
|
|
350
|
+
|
|
351
|
+
const score = scoreSection(pkgLower, headingLower, contentLower, words, phrase)
|
|
352
|
+
matches.push({
|
|
353
|
+
packageName: doc.packageName,
|
|
354
|
+
version: doc.version,
|
|
355
|
+
file: doc.file,
|
|
356
|
+
relFile: doc.relFile,
|
|
357
|
+
heading: section.heading,
|
|
358
|
+
line: section.line,
|
|
359
|
+
score,
|
|
360
|
+
content: section.content,
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
matches.sort((a, b) => {
|
|
366
|
+
if (b.score !== a.score)
|
|
367
|
+
return b.score - a.score
|
|
368
|
+
const aCore = a.packageName === 'prunelle' ? 0 : 1
|
|
369
|
+
const bCore = b.packageName === 'prunelle' ? 0 : 1
|
|
370
|
+
if (aCore !== bCore)
|
|
371
|
+
return aCore - bCore
|
|
372
|
+
const byPkg = a.packageName.localeCompare(b.packageName)
|
|
373
|
+
if (byPkg !== 0)
|
|
374
|
+
return byPkg
|
|
375
|
+
return a.line - b.line
|
|
376
|
+
})
|
|
377
|
+
|
|
378
|
+
const limit = options?.limit ?? DEFAULT_LIMIT
|
|
379
|
+
const limited = limit >= 0 ? matches.slice(0, limit) : matches
|
|
380
|
+
return { query, words, packages, matches: limited }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function formatPackageLabel(name: string, version: string | undefined): string {
|
|
384
|
+
return version !== undefined ? `${name}@${version}` : name
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Formats a `DocsSearchResult` for terminal output. */
|
|
388
|
+
export function formatDocsSearchResult(result: DocsSearchResult): string {
|
|
389
|
+
if (result.matches.length === 0) {
|
|
390
|
+
const pkgList = result.packages.length > 0
|
|
391
|
+
? result.packages.map(pkg => `${formatPackageLabel(pkg.name, pkg.version)} (${pkg.file})`).join(', ')
|
|
392
|
+
: '(none)'
|
|
393
|
+
if (result.words.length === 0)
|
|
394
|
+
return `No search words provided.\nAvailable packages (${result.packages.length}): ${pkgList}`
|
|
395
|
+
return `No docs matched "${result.query}".\nSearched packages (${result.packages.length}): ${pkgList}`
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
return result.matches.map((match) => {
|
|
399
|
+
const pkgLabel = formatPackageLabel(match.packageName, match.version)
|
|
400
|
+
return `=== ${pkgLabel} — ${match.heading} (${match.relFile}:${match.line}) ===\n${match.content}`
|
|
401
|
+
}).join('\n\n')
|
|
402
|
+
}
|