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