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
@@ -0,0 +1,619 @@
1
+ // Broken internal link checker for `prunelle check`: validates JSX href/action/formAction, ctx.redirect(), and Markdown links.
2
+
3
+ import type { Node, Program } from 'oxc-parser'
4
+ import type { RouteManifestEntry } from '../build/manifest'
5
+ import type { ModuleAnalysis } from '../compiler/analyze'
6
+ import type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, PrunelleConfig, PrunellePlugin, ServerPluginAPI } from '../plugins/index'
7
+ import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../server/param-matchers'
8
+ import { existsSync, readFileSync, statSync } from 'node:fs'
9
+ import { basename, resolve } from 'node:path'
10
+ import { pathToFileURL } from 'node:url'
11
+ import { isInNodeModules, relPosix, walkAllFiles, walkFiles } from '../build/files'
12
+ import { isInside } from '../build/is-inside'
13
+ import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, SPECIAL_ROUTE_FILES } from '../build/routes'
14
+ import { walk } from '../compiler/ast'
15
+ import { calleeName, formatDiagnostic, formatLoc, offsetToLineCol, unwrapTsExpr } from '../compiler/shared'
16
+ import { createAppContext, I18N_CONFIG_SERVICE, pickRuntimeConfig, runWithAppContext } from '../plugins/index'
17
+ import { BUILTIN_PARAM_MATCHERS, extractMatcherFn, parsePatternSegment } from '../server/param-matchers'
18
+ import { decodeRequestPath } from '../server/request-path'
19
+ import { Router } from '../server/router'
20
+
21
+ export interface LinkCheckInput {
22
+ root: string
23
+ routesDir: string
24
+ publicDir: string
25
+ assetPrefix: string
26
+ site?: string | undefined
27
+ config: PrunelleConfig
28
+ plugins: readonly PrunellePlugin[]
29
+ routeFiles: readonly string[]
30
+ analyses: ReadonlyMap<string, ModuleAnalysis>
31
+ sources: ReadonlyMap<string, string>
32
+ }
33
+
34
+ interface RouteEntry { pattern: string, fileRel?: string | undefined, isDynamic: boolean, knownPaths?: ReadonlySet<string> | undefined, knownPathList?: readonly string[] | undefined }
35
+ interface DynamicSegment { kind: 'static' | 'param' | 'catchall', value: string, matcherName?: string | undefined, matcher?: ParamMatcher | undefined }
36
+ interface LinkTarget { kind: 'exact' | 'prefix', value: string, offset: number, parentOffset: number }
37
+ interface LinkResolver { checkExact: (raw: string) => string | undefined, checkPrefix: (raw: string) => string | undefined }
38
+ interface PluginProbeResult { pluginRoutes: string[], emittedPublic: string[], locales: string[] }
39
+
40
+ const LINK_ATTRS = new Set(['href', 'action', 'formaction', 'formAction'])
41
+ const LINK_IGNORE_TOKENS = new Set(['link', 'broken-link', 'link/broken'])
42
+ const CODE_IGNORE_RES = [/(?:^|[\s{;(,])\/\/\s*prunelle-ignore(-file)?(?:[ \t]+([^\r\n]*))?/g, /\/\*\s*prunelle-ignore(-file)?(?:\s+([\s\S]*?))?\*\//g]
43
+ const MD_IGNORE_RE = /<!--\s*prunelle-ignore(-file)?(?:\s+([\s\S]*?))?-->/g
44
+ const MD_INLINE_CODE_RE = /(`+)(?!`)(?:(?!\1)[\s\S])*?\1(?!`)/g
45
+ const MD_FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/
46
+ const MD_LINK_RE = /\[(?:[^\]\\]|\\.|\[[^\]]*\])*\]\(\s*(?:<([^>\n]+)>|([^)\s]+))(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/g
47
+ const MD_HTML_A_RE = /<a\b[^>]*?\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/gi
48
+ const PROBE_ROUTE: RouteManifestEntry = { path: '/__pru_probe__', file: '__pru_probe__.ts', layouts: [], middlewares: [], islandChunks: [] }
49
+
50
+ function normalizePathname(raw: string): string {
51
+ const cut = raw.search(/[?#]/)
52
+ const p = cut === -1 ? raw : raw.slice(0, cut)
53
+ return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
54
+ }
55
+
56
+ const isInternalLink = (raw: string): boolean => raw.startsWith('/') && !raw.startsWith('//')
57
+ const matchesLinkIgnore = (raw?: string): boolean => { const t = (raw ?? '').trim(); return t === '' || t.split(/[\s,]+/).some(tok => LINK_IGNORE_TOKENS.has(tok)) }
58
+ const spaces = (n: number): string => ' '.repeat(Math.max(0, n))
59
+
60
+ async function silently<T>(fn: () => T | Promise<T>): Promise<T | undefined> {
61
+ try { return await fn() }
62
+ catch (err) { void err; return undefined }
63
+ }
64
+
65
+ function levenshtein(a: string, b: string): number {
66
+ if (a.length === 0 || b.length === 0)
67
+ return a.length + b.length
68
+ let prev = Int32Array.from({ length: b.length + 1 }, (_, j) => j)
69
+ let curr = new Int32Array(b.length + 1)
70
+ for (let i = 1; i <= a.length; i++) {
71
+ curr[0] = i
72
+ const ca = a.charCodeAt(i - 1)
73
+ for (let j = 1; j <= b.length; j++)
74
+ curr[j] = Math.min(prev[j - 1]! + (ca === b.charCodeAt(j - 1) ? 0 : 1), curr[j - 1]! + 1, prev[j]! + 1)
75
+ ;[prev, curr] = [curr, prev]
76
+ }
77
+ return prev[b.length]!
78
+ }
79
+
80
+ function closestPath(target: string, candidates: readonly string[]): string | undefined {
81
+ let best: string | undefined
82
+ let bestDist = Infinity
83
+ for (const cand of candidates) {
84
+ const maxAllowed = Math.max(2, Math.floor(Math.max(target.length, cand.length) * 0.45))
85
+ if (Math.abs(target.length - cand.length) > maxAllowed)
86
+ continue
87
+ const dist = levenshtein(target, cand)
88
+ if (dist <= maxAllowed && (dist < bestDist || (dist === bestDist && best !== undefined && cand < best))) {
89
+ best = cand
90
+ bestDist = dist
91
+ }
92
+ }
93
+ return best
94
+ }
95
+
96
+ function parseCodeIgnores(code: string): { ignoreFile: boolean, ignoredLines: Set<number> } {
97
+ let ignoreFile = false
98
+ const ignoredLines = new Set<number>()
99
+ for (const re of CODE_IGNORE_RES) {
100
+ re.lastIndex = 0
101
+ for (let m = re.exec(code); m !== null; m = re.exec(code)) {
102
+ if (!matchesLinkIgnore(m[2]))
103
+ continue
104
+ if (m[1] === '-file') { ignoreFile = true; continue }
105
+ const s = offsetToLineCol(code, m.index).line
106
+ const e = offsetToLineCol(code, m.index + m[0].length).line
107
+ for (let line = s; line <= e + 1; line++)
108
+ ignoredLines.add(line)
109
+ }
110
+ }
111
+ return { ignoreFile, ignoredLines }
112
+ }
113
+
114
+ function staticStringExpr(node: Node | null | undefined): string | undefined {
115
+ if (node === null || node === undefined)
116
+ return undefined
117
+ const inner = unwrapTsExpr(node)
118
+ if (inner.type === 'Literal' && typeof inner.value === 'string')
119
+ return inner.value
120
+ if (inner.type === 'TemplateLiteral' && inner.expressions.length === 0 && inner.quasis.length === 1)
121
+ return inner.quasis[0]!.value.cooked ?? inner.quasis[0]!.value.raw
122
+ return undefined
123
+ }
124
+
125
+ function extractStaticPathsArray(program: Program): string[] | undefined {
126
+ let fn: Node | undefined
127
+ for (const stmt of program.body) {
128
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration === null)
129
+ continue
130
+ const d = stmt.declaration
131
+ if (d.type === 'FunctionDeclaration' && d.id?.name === 'paths')
132
+ fn = d
133
+ else if (d.type === 'VariableDeclaration')
134
+ fn = d.declarations.find(v => v.id.type === 'Identifier' && v.id.name === 'paths' && v.init !== null)?.init ?? fn
135
+ }
136
+ const target = fn !== undefined ? unwrapTsExpr(fn) : undefined
137
+ const expr = target?.type === 'ArrowFunctionExpression' && target.body.type !== 'BlockStatement'
138
+ ? target.body
139
+ : (target !== undefined && (target.type === 'FunctionDeclaration' || target.type === 'FunctionExpression' || target.type === 'ArrowFunctionExpression') && target.body?.type === 'BlockStatement' && target.body.body.length === 1 && target.body.body[0]!.type === 'ReturnStatement')
140
+ ? target.body.body[0]!.argument ?? undefined
141
+ : undefined
142
+ const arr = expr !== undefined ? unwrapTsExpr(expr) : undefined
143
+ if (arr?.type !== 'ArrayExpression')
144
+ return undefined
145
+ const urls: string[] = []
146
+ for (const el of arr.elements) {
147
+ const val = el !== null && el.type !== 'SpreadElement' ? staticStringExpr(el) : undefined
148
+ if (val === undefined || !val.startsWith('/')) return undefined
149
+ urls.push(normalizePathname(val))
150
+ }
151
+ return urls
152
+ }
153
+
154
+ async function evaluateRoutePaths(file: string, analysis: ModuleAnalysis, appCtx: AppRuntimeContext): Promise<readonly string[] | undefined> {
155
+ const staticUrls = extractStaticPathsArray(analysis.program)
156
+ if (staticUrls !== undefined) return staticUrls
157
+ const urls = await silently(() => runWithAppContext(appCtx, async () => {
158
+ const mod = await import(pathToFileURL(file).href) as { paths?: unknown }
159
+ return typeof mod.paths === 'function' ? await (mod.paths as () => unknown)() : undefined
160
+ }))
161
+ return Array.isArray(urls) && urls.every((u): u is string => typeof u === 'string' && u.startsWith('/')) ? urls.map(normalizePathname) : undefined
162
+ }
163
+
164
+ async function loadParamMatchers(root: string, routesDir: string, routeFiles: readonly string[], analyses: ReadonlyMap<string, ModuleAnalysis>): Promise<ParamMatcherMap> {
165
+ const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
166
+ const { customFiles } = discoverRouteMatchers({ root, routesDir, routeFiles, loadAnalysis: f => analyses.get(f) })
167
+ for (const [name, absFile] of customFiles) {
168
+ const mod = await silently(() => import(pathToFileURL(absFile).href) as Promise<unknown>)
169
+ if (mod === undefined) { merged[name] = () => true; continue }
170
+ const fn = extractMatcherFn(mod)
171
+ if (fn !== undefined) merged[name] = (v: string) => { try { return Boolean(fn(v)) } catch (e) { void e; return false } }
172
+ }
173
+ return merged
174
+ }
175
+
176
+ async function probeSinglePlugin(
177
+ plugin: PrunellePlugin,
178
+ config: PrunelleConfig,
179
+ paths: { root: string, outDir: string, assetPrefix: string, site: string | undefined },
180
+ state: { routes: string[], emitted: string[], services: Map<string, unknown>, shutdowns: (() => void | Promise<void>)[], provide: <T>(k: { readonly name: string }, v: T) => void },
181
+ ): Promise<void> {
182
+ const { root, outDir, assetPrefix, site } = paths
183
+ const inject = <T>(key: { readonly name: string }) => state.services.get(key.name) as T | undefined
184
+ if (plugin.server !== undefined) {
185
+ const api: ServerPluginAPI = {
186
+ root, outDir, assetPrefix, site, dev: false,
187
+ trustProxy: config.trustProxy ?? false, trustedOrigins: config.trustedOrigins ?? [],
188
+ config: pickRuntimeConfig(config) as Readonly<Record<string, unknown>>,
189
+ use: (_mw, opts) => { if (plugin.name === '@prunellejs/seo' && typeof opts?.scope === 'string' && opts.scope.startsWith('/')) state.routes.push(opts.scope) },
190
+ route: (_method, path) => { state.routes.push(path) },
191
+ rateLimiter: () => ({ hit: () => 0 }), rewrite: () => {}, provide: state.provide,
192
+ inject: key => inject(key) as never, getBuildData: () => undefined, healthCheck: () => {},
193
+ onShutdown: fn => { state.shutdowns.push(fn) },
194
+ }
195
+ await silently(() => plugin.server!(api))
196
+ }
197
+ // Skip @prunellejs/images build(): it tracks module-global build phase state and does not emit static public routes.
198
+ if (plugin.name === '@prunellejs/images')
199
+ return
200
+ const buildCtx: BuildPluginContext = {
201
+ root, outDir, assetPrefix, site, minify: false, isStatic: false, dev: true, routes: [],
202
+ emitAsset: rel => `${assetPrefix}/${rel.replace(/^\/+/, '')}`,
203
+ emitPublic: (rel) => { const c = rel.replace(/^\/+/, ''); state.emitted.push(c); return `/${c}` },
204
+ addStyle: () => {}, addRouteStyle: () => {}, addHead: () => {}, addRouteHead: () => {},
205
+ provide: state.provide, inject: key => inject(key) as never, setData: () => {},
206
+ }
207
+ if (plugin.build !== undefined)
208
+ await silently(() => plugin.build!(buildCtx))
209
+ if (plugin.afterPrerender !== undefined)
210
+ await silently(() => plugin.afterPrerender!({ ...buildCtx, publicFiles: state.emitted }))
211
+ }
212
+
213
+ async function probePlugins(
214
+ plugins: readonly PrunellePlugin[],
215
+ config: PrunelleConfig,
216
+ paths: { root: string, outDir: string, assetPrefix: string, site: string | undefined },
217
+ appCtx: AppRuntimeContext,
218
+ ): Promise<PluginProbeResult> {
219
+ const services = new Map<string, unknown>()
220
+ const shutdowns: (() => void | Promise<void>)[] = []
221
+ const routes: string[] = []
222
+ const emitted: string[] = []
223
+ const provide = <T>(key: { readonly name: string }, value: T): void => { services.set(key.name, value); appCtx.provide(key, value) }
224
+ try {
225
+ await runWithAppContext(appCtx, async () => {
226
+ for (const plugin of plugins)
227
+ await probeSinglePlugin(plugin, config, paths, { routes, emitted, services, shutdowns, provide })
228
+ })
229
+ }
230
+ finally {
231
+ for (let i = shutdowns.length - 1; i >= 0; i--)
232
+ await silently(() => shutdowns[i]!())
233
+ }
234
+ const locales = new Set<string>()
235
+ const i18n = services.get(I18N_CONFIG_SERVICE.name) as ActiveI18nConfig | undefined
236
+ if (i18n !== undefined) {
237
+ i18n.locales.forEach(loc => locales.add(loc))
238
+ }
239
+ else {
240
+ for (const plugin of plugins) {
241
+ if (plugin.prerenderPaths === undefined) continue
242
+ for (const p of (await silently(() => plugin.prerenderPaths!(['/__pru_probe__'], PROBE_ROUTE))) ?? []) {
243
+ const m = /^\/([^/]+)\/__pru_probe__$/.exec(p)
244
+ if (m !== null) locales.add(m[1]!)
245
+ }
246
+ }
247
+ }
248
+ return { pluginRoutes: routes, emittedPublic: emitted, locales: [...locales] }
249
+ }
250
+
251
+ function collectPublicPaths(publicDir: string, emittedPublic: readonly string[]): Set<string> {
252
+ const out = new Set<string>()
253
+ const add = (rel: string): void => {
254
+ const clean = rel.replace(/^\/+/, '').replaceAll('\\', '/')
255
+ if (clean === '') return
256
+ out.add(`/${clean}`)
257
+ if (!clean.endsWith('.html')) return
258
+ out.add(clean === 'index.html' ? '/' : `/${clean.slice(0, -5)}`)
259
+ if (clean.endsWith('/index.html')) out.add(`/${clean.slice(0, -'/index.html'.length)}`)
260
+ }
261
+ if (existsSync(publicDir)) walkAllFiles(publicDir).forEach(abs => add(relPosix(publicDir, abs)))
262
+ emittedPublic.forEach(add)
263
+ return out
264
+ }
265
+
266
+ function compileDynamicPatterns(pattern: string, matchers: ParamMatcherMap): DynamicSegment[][] {
267
+ const norm = normalizePathname(pattern)
268
+ const parsed: ParsedPatternSegment[] = norm === '/' ? [] : norm.slice(1).split('/').map(parsePatternSegment)
269
+ const optIdx = parsed.flatMap((s, i) => s.kind === 'optional' ? [i] : [])
270
+ if (optIdx.length > 6)
271
+ return []
272
+ const toSeg = (s: ParsedPatternSegment): DynamicSegment => ({
273
+ kind: s.kind === 'optional' ? 'param' : s.kind, value: s.value, matcherName: s.matcherName,
274
+ matcher: s.matcherName !== undefined ? matchers[s.matcherName] : undefined,
275
+ })
276
+ const variants: DynamicSegment[][] = []
277
+ const expand = (k: number, omitted: Set<number>): void => {
278
+ if (k === optIdx.length) { variants.push(parsed.filter((_, i) => !omitted.has(i)).map(toSeg)); return }
279
+ expand(k + 1, omitted)
280
+ omitted.add(optIdx[k]!)
281
+ expand(k + 1, omitted)
282
+ omitted.delete(optIdx[k]!)
283
+ }
284
+ expand(0, new Set())
285
+ return variants
286
+ }
287
+
288
+ const paramAccepts = (seg: DynamicSegment, value: string): boolean => seg.matcherName === undefined || (seg.matcher !== undefined && seg.matcher(value))
289
+
290
+ function patternMatchesPrefix(segs: readonly DynamicSegment[], complete: readonly string[], partial: string | undefined): boolean {
291
+ let catchAll: DynamicSegment | undefined
292
+ for (let i = 0; i < complete.length; i++) {
293
+ const part = complete[i]!
294
+ if (catchAll !== undefined) {
295
+ if (!paramAccepts(catchAll, part))
296
+ return false
297
+ continue
298
+ }
299
+ const seg = segs[i]
300
+ if (seg === undefined)
301
+ return false
302
+ if (seg.kind === 'catchall') {
303
+ catchAll = seg
304
+ if (!paramAccepts(seg, part))
305
+ return false
306
+ }
307
+ else if (seg.kind === 'static' ? seg.value !== part : !paramAccepts(seg, part)) {
308
+ return false
309
+ }
310
+ }
311
+ if (catchAll !== undefined)
312
+ return true
313
+ const next = segs[complete.length]
314
+ return next !== undefined && (partial === undefined || next.kind !== 'static' || next.value.startsWith(partial))
315
+ }
316
+
317
+ function staticPrefixOfPattern(pattern: string): string | undefined {
318
+ const norm = normalizePathname(pattern)
319
+ if (norm === '/')
320
+ return undefined
321
+ const kept: string[] = []
322
+ for (const seg of norm.slice(1).split('/')) {
323
+ if (parsePatternSegment(seg).kind !== 'static')
324
+ break
325
+ kept.push(seg)
326
+ }
327
+ return kept.length > 0 ? `/${kept.join('/')}` : undefined
328
+ }
329
+
330
+ function stripLocale(pathname: string, locales: readonly string[]): string | undefined {
331
+ const first = locales.length > 0 ? pathname.slice(1).split('/', 1)[0] : undefined
332
+ return first !== undefined && locales.includes(first) ? (pathname.slice(first.length + 1) || '/') : undefined
333
+ }
334
+
335
+ function createLinkResolver(opts: {
336
+ router: Router<RouteEntry>
337
+ publicPaths: ReadonlySet<string>
338
+ dynamicPatterns: readonly (readonly DynamicSegment[])[]
339
+ staticPaths: readonly string[]
340
+ suggestionPool: readonly string[]
341
+ prefixSuggestionPool: readonly string[]
342
+ assetPrefix: string
343
+ locales: readonly string[]
344
+ }): LinkResolver {
345
+ const { router, publicPaths, dynamicPatterns, staticPaths, suggestionPool, prefixSuggestionPool, locales } = opts
346
+ const assetPrefix = opts.assetPrefix.replace(/\/+$/, '')
347
+ const isAsset = (p: string): boolean => assetPrefix !== '' && (p === assetPrefix || p.startsWith(`${assetPrefix}/`))
348
+ const hasPublic = (p: string): boolean => {
349
+ if (publicPaths.has(p))
350
+ return true
351
+ const decoded = decodeRequestPath(p)?.staticPath
352
+ return decoded !== undefined && publicPaths.has(normalizePathname(decoded))
353
+ }
354
+ const matchExact = (p: string): { ok: true } | { ok: false, miss?: RouteEntry } => {
355
+ if (hasPublic(p))
356
+ return { ok: true }
357
+ const hit = router.match(p)
358
+ if (hit === undefined)
359
+ return { ok: false }
360
+ return hit.data.knownPaths !== undefined && !hit.data.knownPaths.has(p) ? { ok: false, miss: hit.data } : { ok: true }
361
+ }
362
+ const checkExact = (raw: string): string | undefined => {
363
+ const trimmed = raw.trim()
364
+ if (!isInternalLink(trimmed)) return undefined
365
+ const pathname = normalizePathname(trimmed)
366
+ if (isAsset(pathname)) return undefined
367
+ const first = matchExact(pathname)
368
+ if (first.ok) return undefined
369
+ const stripped = stripLocale(pathname, locales)
370
+ let miss = first.miss
371
+ if (stripped !== undefined) {
372
+ const second = matchExact(stripped)
373
+ if (second.ok) return undefined
374
+ miss ??= second.miss
375
+ }
376
+ if (miss !== undefined) {
377
+ const near = closestPath(stripped !== undefined && first.miss === undefined ? stripped : pathname, miss.knownPathList ?? [])
378
+ return `[link/broken] link "${pathname}" is not returned by paths() in ${miss.fileRel ?? miss.pattern}${near !== undefined ? `; did you mean "${near}"?` : '.'}`
379
+ }
380
+ const near = closestPath(stripped ?? pathname, suggestionPool)
381
+ return `[link/broken] broken link "${pathname}" matches no route or public file${near !== undefined ? `; did you mean "${near}"?` : '.'}`
382
+ }
383
+ const matchPrefix = (prefix: string): boolean => {
384
+ if (prefix === '/' || isAsset(prefix) || staticPaths.some(p => p.startsWith(prefix))) return true
385
+ const parts = prefix.slice(1).split('/')
386
+ return dynamicPatterns.some(pat => patternMatchesPrefix(pat, parts.slice(0, -1), prefix.endsWith('/') ? undefined : parts[parts.length - 1]))
387
+ }
388
+ const checkPrefix = (raw: string): string | undefined => {
389
+ if (!isInternalLink(raw)) return undefined
390
+ const cut = raw.search(/[?#]/)
391
+ if (cut !== -1) return checkExact(raw.slice(0, cut))
392
+ if (raw === '/' || isAsset(raw) || matchPrefix(raw)) return undefined
393
+ const stripped = stripLocale(raw, locales)
394
+ if (stripped !== undefined && matchPrefix(stripped)) return undefined
395
+ const near = closestPath(normalizePathname(stripped ?? raw), prefixSuggestionPool)
396
+ return `[link/broken] broken link prefix "${raw}..." matches no route or public file${near !== undefined ? `; did you mean "${near}"?` : '.'}`
397
+ }
398
+ return { checkExact, checkPrefix }
399
+ }
400
+
401
+ function extractLinkTargets(node: Node | null | undefined, parentOffset: number, out: LinkTarget[]): void {
402
+ if (node === null || node === undefined)
403
+ return
404
+ const inner = unwrapTsExpr(node)
405
+ if (inner.type === 'Literal' && typeof inner.value === 'string') {
406
+ out.push({ kind: 'exact', value: inner.value, offset: inner.start, parentOffset })
407
+ }
408
+ else if (inner.type === 'TemplateLiteral') {
409
+ const head = inner.quasis[0]?.value.cooked ?? inner.quasis[0]?.value.raw ?? ''
410
+ if (inner.expressions.length === 0)
411
+ out.push({ kind: 'exact', value: head, offset: inner.start, parentOffset })
412
+ else if (head.length > 0)
413
+ out.push({ kind: 'prefix', value: head, offset: inner.start, parentOffset })
414
+ }
415
+ else if (inner.type === 'ConditionalExpression') {
416
+ extractLinkTargets(inner.consequent, parentOffset, out)
417
+ extractLinkTargets(inner.alternate, parentOffset, out)
418
+ }
419
+ else if (inner.type === 'BinaryExpression' && inner.operator === '+') {
420
+ const left = staticStringExpr(inner.left)
421
+ if (left !== undefined) {
422
+ const right = staticStringExpr(inner.right)
423
+ out.push({ kind: right !== undefined ? 'exact' : 'prefix', value: right !== undefined ? left + right : left, offset: inner.start, parentOffset })
424
+ }
425
+ }
426
+ }
427
+
428
+ function scanModuleLinks(relFile: string, analysis: ModuleAnalysis, code: string, resolver: LinkResolver, warnings: string[]): void {
429
+ const { ignoreFile, ignoredLines } = parseCodeIgnores(code)
430
+ if (ignoreFile)
431
+ return
432
+ const targets: LinkTarget[] = []
433
+ walk(analysis.program, (node): boolean | void => {
434
+ if (node.type === 'JSXOpeningElement') {
435
+ for (const attr of node.attributes) {
436
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier' || !LINK_ATTRS.has(attr.name.name))
437
+ continue
438
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string')
439
+ targets.push({ kind: 'exact', value: attr.value.value, offset: attr.value.start, parentOffset: node.start })
440
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression')
441
+ extractLinkTargets(attr.value.expression, node.start, targets)
442
+ }
443
+ return
444
+ }
445
+ if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && !node.callee.computed && node.callee.property.type === 'Identifier' && node.callee.property.name === 'redirect' && node.arguments.length >= 1 && node.arguments[0]!.type !== 'SpreadElement')
446
+ extractLinkTargets(node.arguments[0]!, node.start, targets)
447
+ })
448
+ for (const t of targets) {
449
+ if (ignoredLines.has(offsetToLineCol(code, t.offset).line) || ignoredLines.has(offsetToLineCol(code, t.parentOffset).line))
450
+ continue
451
+ const msg = t.kind === 'exact' ? resolver.checkExact(t.value) : resolver.checkPrefix(t.value)
452
+ if (msg !== undefined)
453
+ warnings.push(formatDiagnostic(formatLoc(relFile, code, t.offset), msg, 'warning'))
454
+ }
455
+ }
456
+
457
+ function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[], analyses: ReadonlyMap<string, ModuleAnalysis>): string[] {
458
+ const dirs = new Set<string>()
459
+ const addDir = (raw: string): void => {
460
+ const abs = resolve(root, raw)
461
+ if (existsSync(abs) && isInside(root, abs, { orSame: true }) && statSync(abs).isDirectory())
462
+ dirs.add(abs)
463
+ }
464
+ for (const plugin of plugins) {
465
+ if (plugin.name !== '@prunellejs/content' || plugin.watchPaths === undefined)
466
+ continue
467
+ try { (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths).forEach(addDir) }
468
+ catch (err) { void err }
469
+ }
470
+ for (const [file, analysis] of analyses) {
471
+ if (isInNodeModules(file) || !isInside(root, file))
472
+ continue
473
+ walk(analysis.program, (node) => {
474
+ if (node.type !== 'CallExpression' || node.arguments[0]?.type !== 'ObjectExpression')
475
+ return
476
+ const name = calleeName(node.callee)
477
+ if (name !== 'defineCollection' && !name.endsWith('.defineCollection'))
478
+ return
479
+ for (const prop of node.arguments[0]!.properties) {
480
+ if (prop.type === 'Property' && !prop.computed && ((prop.key.type === 'Identifier' && prop.key.name === 'dir') || (prop.key.type === 'Literal' && prop.key.value === 'dir'))) {
481
+ const dirVal = staticStringExpr(prop.value)
482
+ if (dirVal !== undefined)
483
+ addDir(dirVal)
484
+ }
485
+ }
486
+ })
487
+ }
488
+ addDir('content')
489
+ return [...dirs].sort()
490
+ }
491
+
492
+ function blankHtmlComments(line: string, inComment: boolean): { text: string, inComment: boolean } {
493
+ let text = line
494
+ let active = inComment
495
+ if (active) {
496
+ const end = text.indexOf('-->')
497
+ if (end === -1)
498
+ return { text: spaces(text.length), inComment: true }
499
+ text = spaces(end + 3) + text.slice(end + 3)
500
+ active = false
501
+ }
502
+ text = text.replace(/<!--[\s\S]*?-->/g, m => spaces(m.length))
503
+ const open = text.indexOf('<!--')
504
+ return open === -1 ? { text, inComment: active } : { text: text.slice(0, open) + spaces(text.length - open), inComment: true }
505
+ }
506
+
507
+ function scanMarkdownFile(relFile: string, content: string, resolver: LinkResolver, warnings: string[]): void {
508
+ const lines = content.split(/\r?\n/)
509
+ const ignoredLines = new Set<number>()
510
+ for (let i = 0; i < lines.length; i++) {
511
+ MD_IGNORE_RE.lastIndex = 0
512
+ for (let m = MD_IGNORE_RE.exec(lines[i]!); m !== null; m = MD_IGNORE_RE.exec(lines[i]!)) {
513
+ if (!matchesLinkIgnore(m[2]))
514
+ continue
515
+ if (m[1] === '-file')
516
+ return
517
+ ignoredLines.add(i + 1)
518
+ ignoredLines.add(i + 2)
519
+ }
520
+ }
521
+ const endFm = lines[0]?.trim() === '---' ? lines.findIndex((l, idx) => idx > 0 && (l.trim() === '---' || l.trim() === '...')) : -1
522
+ let fence: { char: string, len: number } | undefined
523
+ let inComment = false
524
+ for (let i = endFm !== -1 ? endFm + 1 : 0; i < lines.length; i++) {
525
+ const rawLine = lines[i]!
526
+ if (fence !== undefined) {
527
+ const t = rawLine.trim()
528
+ if (t.length >= fence.len && t.split('').every(ch => ch === fence!.char))
529
+ fence = undefined
530
+ continue
531
+ }
532
+ const open = MD_FENCE_OPEN_RE.exec(rawLine)
533
+ if (open !== null && (open[1]![0] !== '`' || !(open[2] ?? '').includes('`'))) { fence = { char: open[1]![0]!, len: open[1]!.length }; continue }
534
+ const stripped = blankHtmlComments(rawLine, inComment)
535
+ inComment = stripped.inComment
536
+ if (ignoredLines.has(i + 1))
537
+ continue
538
+ const scanLine = stripped.text.replace(MD_INLINE_CODE_RE, m => spaces(m.length))
539
+ for (const [re, isMd] of [[MD_LINK_RE, true], [MD_HTML_A_RE, false]] as const) {
540
+ re.lastIndex = 0
541
+ for (let m = re.exec(scanLine); m !== null; m = re.exec(scanLine)) {
542
+ if (isMd && m.index > 0 && scanLine[m.index - 1] === '!')
543
+ continue
544
+ const url = m[1] ?? m[2] ?? ''
545
+ const msg = resolver.checkExact(url)
546
+ if (msg !== undefined)
547
+ warnings.push(formatDiagnostic(`${relFile}:${i + 1}:${m.index + Math.max(0, isMd ? m[0].indexOf(url) : m[0].lastIndexOf(url)) + 1}`, msg, 'warning'))
548
+ }
549
+ }
550
+ }
551
+ }
552
+
553
+ export async function checkAppLinks(input: LinkCheckInput): Promise<string[]> {
554
+ const { root, routesDir, publicDir, assetPrefix, site, config, plugins, routeFiles, analyses, sources } = input
555
+ const cleanAssetPrefix = assetPrefix.replace(/\/+$/, '')
556
+ const outDir = resolve(root, config.outDir ?? 'dist')
557
+ const appCtx = createAppContext({ root, outDir, publicDir, assetPrefix: cleanAssetPrefix, site, dev: false })
558
+ const specialFiles = routeFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
559
+ const pageFiles = routeFiles.filter(f => !basename(f).startsWith('_') && analyses.has(f) && hasRouteHandlerExport(analyses.get(f)!))
560
+ const [matchers, probe] = await Promise.all([
561
+ loadParamMatchers(root, routesDir, [...specialFiles, ...pageFiles], analyses),
562
+ probePlugins(plugins, config, { root, outDir, assetPrefix: cleanAssetPrefix, site }, appCtx),
563
+ ])
564
+
565
+ const router = new Router<RouteEntry>(matchers)
566
+ const dynamicPatterns: DynamicSegment[][] = []
567
+ const staticPathSet = new Set<string>()
568
+ const suggestionSet = new Set<string>()
569
+ const prefixSuggestionSet = new Set<string>()
570
+ const addStatic = (p: string): void => { staticPathSet.add(p); suggestionSet.add(p); prefixSuggestionSet.add(p) }
571
+ const register = (pattern: string, entry: RouteEntry): void => {
572
+ router.add(pattern, entry)
573
+ if (!entry.isDynamic) { addStatic(normalizePathname(pattern)); return }
574
+ dynamicPatterns.push(...compileDynamicPatterns(pattern, matchers))
575
+ const prefix = staticPrefixOfPattern(pattern)
576
+ if (prefix !== undefined)
577
+ prefixSuggestionSet.add(prefix)
578
+ if (entry.knownPathList !== undefined)
579
+ entry.knownPathList.forEach((p) => { staticPathSet.add(p); suggestionSet.add(p) })
580
+ else
581
+ suggestionSet.add(pattern)
582
+ }
583
+
584
+ for (const file of pageFiles) {
585
+ const analysis = analyses.get(file)!
586
+ const pattern = fileToRoutePath(routesDir, file)
587
+ const isDynamic = pattern.includes(':') || pattern.includes('*')
588
+ const knownPathList = isDynamic && analysis.hasPaths ? await evaluateRoutePaths(file, analysis, appCtx) : undefined
589
+ register(pattern, { pattern, fileRel: relPosix(root, file), isDynamic, knownPaths: knownPathList !== undefined ? new Set(knownPathList) : undefined, knownPathList })
590
+ }
591
+ probe.pluginRoutes.forEach(p => register(p, { pattern: p, isDynamic: p.includes(':') || p.includes('*') }))
592
+ if (config.consent !== undefined) {
593
+ const rawEp = (config.consent.endpoint ?? '/_pru/consent').trim()
594
+ const ep = rawEp.startsWith('/') ? rawEp : `/${rawEp}`
595
+ register(ep, { pattern: ep, isDynamic: false })
596
+ }
597
+ const publicPaths = collectPublicPaths(publicDir, probe.emittedPublic)
598
+ publicPaths.forEach(addStatic)
599
+
600
+ const resolver = createLinkResolver({
601
+ router, publicPaths, dynamicPatterns,
602
+ staticPaths: [...staticPathSet], suggestionPool: [...suggestionSet].sort(),
603
+ prefixSuggestionPool: [...prefixSuggestionSet].sort(), assetPrefix: cleanAssetPrefix, locales: probe.locales,
604
+ })
605
+
606
+ const warnings: string[] = []
607
+ for (const file of [...analyses.keys()].sort()) {
608
+ if (!isInNodeModules(file) && (isInside(root, file) || isInside(routesDir, file)))
609
+ scanModuleLinks(relPosix(root, file), analyses.get(file)!, sources.get(file) ?? readFileSync(file, 'utf8'), resolver, warnings)
610
+ }
611
+ const mdFiles = new Set<string>()
612
+ for (const dir of discoverCollectionDirs(root, plugins, analyses)) {
613
+ for (const f of walkFiles(dir, { skipDir: n => n === 'node_modules' || n.startsWith('.'), keep: e => e.name.endsWith('.md') || e.name.endsWith('.markdown') }))
614
+ mdFiles.add(f)
615
+ }
616
+ for (const mdFile of [...mdFiles].sort())
617
+ await silently(() => scanMarkdownFile(relPosix(root, mdFile), readFileSync(mdFile, 'utf8'), resolver, warnings))
618
+ return warnings
619
+ }