@nifrajs/cli 5.9.0 → 5.11.0

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 (136) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/check-diagnostics.d.ts +1 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +4 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan.d.ts +1 -0
  7. package/dist/check-scan.d.ts.map +1 -1
  8. package/dist/check-scan.js +8 -1
  9. package/dist/check-scan.js.map +1 -1
  10. package/dist/check.d.ts.map +1 -1
  11. package/dist/check.js +7 -2
  12. package/dist/check.js.map +1 -1
  13. package/dist/cli.d.ts.map +1 -1
  14. package/dist/cli.js +21 -20
  15. package/dist/cli.js.map +1 -1
  16. package/dist/command-catalog.d.ts +1 -5
  17. package/dist/command-catalog.d.ts.map +1 -1
  18. package/dist/command-catalog.js +2 -21
  19. package/dist/command-catalog.js.map +1 -1
  20. package/dist/doctor.js +2 -2
  21. package/dist/doctor.js.map +1 -1
  22. package/dist/internal/source-facts.d.ts +30 -0
  23. package/dist/internal/source-facts.d.ts.map +1 -1
  24. package/dist/internal/source-facts.js +127 -0
  25. package/dist/internal/source-facts.js.map +1 -1
  26. package/dist/load.d.ts +4 -2
  27. package/dist/load.d.ts.map +1 -1
  28. package/dist/load.js +6 -1
  29. package/dist/load.js.map +1 -1
  30. package/dist/mcp-delegate.d.ts +17 -3
  31. package/dist/mcp-delegate.d.ts.map +1 -1
  32. package/dist/mcp-delegate.js +24 -9
  33. package/dist/mcp-delegate.js.map +1 -1
  34. package/dist/mcp-http.js +1 -1
  35. package/dist/mcp-http.js.map +1 -1
  36. package/dist/mcp-relay.d.ts +37 -0
  37. package/dist/mcp-relay.d.ts.map +1 -0
  38. package/dist/mcp-relay.js +129 -0
  39. package/dist/mcp-relay.js.map +1 -0
  40. package/dist/mcp-tool-meta.d.ts.map +1 -1
  41. package/dist/mcp-tool-meta.js +0 -1
  42. package/dist/mcp-tool-meta.js.map +1 -1
  43. package/dist/mcp.d.ts.map +1 -1
  44. package/dist/mcp.js +55 -1
  45. package/dist/mcp.js.map +1 -1
  46. package/dist/migrate-layout.d.ts.map +1 -1
  47. package/dist/migrate-layout.js +45 -33
  48. package/dist/migrate-layout.js.map +1 -1
  49. package/dist/recipes/5.10.0.d.ts +13 -0
  50. package/dist/recipes/5.10.0.d.ts.map +1 -0
  51. package/dist/recipes/5.10.0.js +45 -0
  52. package/dist/recipes/5.10.0.js.map +1 -0
  53. package/dist/recipes/5.11.0.d.ts +10 -0
  54. package/dist/recipes/5.11.0.d.ts.map +1 -0
  55. package/dist/recipes/5.11.0.js +50 -0
  56. package/dist/recipes/5.11.0.js.map +1 -0
  57. package/dist/recipes/index.d.ts.map +1 -1
  58. package/dist/recipes/index.js +4 -0
  59. package/dist/recipes/index.js.map +1 -1
  60. package/dist/review.d.ts.map +1 -1
  61. package/dist/review.js +3 -0
  62. package/dist/review.js.map +1 -1
  63. package/dist/rules/codes.d.ts +3 -0
  64. package/dist/rules/codes.d.ts.map +1 -1
  65. package/dist/rules/codes.js +3 -0
  66. package/dist/rules/codes.js.map +1 -1
  67. package/dist/rules/explanations.d.ts.map +1 -1
  68. package/dist/rules/explanations.js +15 -0
  69. package/dist/rules/explanations.js.map +1 -1
  70. package/dist/rules/internal-links.d.ts +5 -0
  71. package/dist/rules/internal-links.d.ts.map +1 -0
  72. package/dist/rules/internal-links.js +418 -0
  73. package/dist/rules/internal-links.js.map +1 -0
  74. package/dist/rules/legacy.d.ts.map +1 -1
  75. package/dist/rules/legacy.js +20 -0
  76. package/dist/rules/legacy.js.map +1 -1
  77. package/dist/rules/server-fn-namespace.d.ts +8 -0
  78. package/dist/rules/server-fn-namespace.d.ts.map +1 -0
  79. package/dist/rules/server-fn-namespace.js +43 -0
  80. package/dist/rules/server-fn-namespace.js.map +1 -0
  81. package/dist/rules/source-scan.d.ts +29 -0
  82. package/dist/rules/source-scan.d.ts.map +1 -0
  83. package/dist/rules/source-scan.js +38 -0
  84. package/dist/rules/source-scan.js.map +1 -0
  85. package/dist/rules/text-slot-boolean.d.ts.map +1 -1
  86. package/dist/rules/text-slot-boolean.js +21 -43
  87. package/dist/rules/text-slot-boolean.js.map +1 -1
  88. package/dist/source-rewrites.d.ts +0 -5
  89. package/dist/source-rewrites.d.ts.map +1 -1
  90. package/dist/source-rewrites.js +350 -10
  91. package/dist/source-rewrites.js.map +1 -1
  92. package/dist/typecheck-coverage.d.ts +9 -0
  93. package/dist/typecheck-coverage.d.ts.map +1 -1
  94. package/dist/typecheck-coverage.js +16 -0
  95. package/dist/typecheck-coverage.js.map +1 -1
  96. package/dist/upgrade.d.ts +19 -1
  97. package/dist/upgrade.d.ts.map +1 -1
  98. package/dist/upgrade.js +55 -2
  99. package/dist/upgrade.js.map +1 -1
  100. package/docs/examples.json +21 -9
  101. package/docs/llms-full.txt +800 -262
  102. package/docs/types.json +868 -128
  103. package/package.json +11 -11
  104. package/src/check-diagnostics.ts +5 -0
  105. package/src/check-scan.ts +9 -1
  106. package/src/check.ts +15 -3
  107. package/src/cli.ts +25 -20
  108. package/src/command-catalog.ts +2 -26
  109. package/src/doctor.ts +2 -2
  110. package/src/internal/source-facts.ts +155 -0
  111. package/src/load.ts +15 -3
  112. package/src/mcp-delegate.ts +37 -11
  113. package/src/mcp-http.ts +1 -1
  114. package/src/mcp-relay.ts +155 -0
  115. package/src/mcp-tool-meta.ts +0 -1
  116. package/src/mcp.ts +51 -1
  117. package/src/migrate-layout.ts +61 -29
  118. package/src/recipes/5.10.0.ts +46 -0
  119. package/src/recipes/5.11.0.ts +51 -0
  120. package/src/recipes/index.ts +4 -0
  121. package/src/review.ts +3 -0
  122. package/src/rules/codes.ts +3 -0
  123. package/src/rules/explanations.ts +15 -0
  124. package/src/rules/internal-links.ts +490 -0
  125. package/src/rules/legacy.ts +21 -0
  126. package/src/rules/server-fn-namespace.ts +47 -0
  127. package/src/rules/source-scan.ts +66 -0
  128. package/src/rules/text-slot-boolean.ts +26 -42
  129. package/src/source-rewrites.ts +383 -12
  130. package/src/typecheck-coverage.ts +23 -0
  131. package/src/upgrade.ts +71 -3
  132. package/dist/sync-routes.d.ts +0 -29
  133. package/dist/sync-routes.d.ts.map +0 -1
  134. package/dist/sync-routes.js +0 -56
  135. package/dist/sync-routes.js.map +0 -1
  136. package/src/sync-routes.ts +0 -70
@@ -0,0 +1,490 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { join } from "node:path"
3
+ import { Glob } from "bun"
4
+ import { CONFIG_FILE, FRAMEWORK_FILE } from "../app-files.ts"
5
+ import { IGNORED, stripComments } from "../check-scan.ts"
6
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
7
+ import { codeUnitOrder } from "../internal/code-unit-order.ts"
8
+ import { toPosix } from "../internal/posix-path.ts"
9
+ import { ANCHOR_HOLE } from "../internal/source-facts.ts"
10
+ import { buildRouteTable } from "../introspect.ts"
11
+ import { commentBlockExpectation } from "./comment-markers.ts"
12
+ import type { CheckRule, RuleContext } from "./index.ts"
13
+ import { readStaticApiPrefix } from "./pages.ts"
14
+ import { scanSources } from "./source-scan.ts"
15
+
16
+ /**
17
+ * NF-C057 and NF-C058 - an `<a href="/path">` written as a string. `href()` checks a link against the
18
+ * app's routes, so a renamed or removed page is a compile error; a path string is invisible to the types.
19
+ * The two codes split what the route table can tell apart, so each takes its own severity:
20
+ *
21
+ * - NF-C057 (warn): the path matches no page, no backend route and no file: the link is a 404.
22
+ * - NF-C058 (info): the path is a page of the app, so it works today but nothing keeps it working.
23
+ *
24
+ * A template literal (`/users/${id}`) is judged by its shape only, and never reported as dead: the
25
+ * route it builds may live outside the file routes.
26
+ */
27
+
28
+ const TEST_DIR = /(?:^|\/)(?:tests?|__tests__)\//
29
+ const FILE_EXTENSION = /\.[A-Za-z0-9]{1,8}$/
30
+ // One attribute of a tag, matched where the previous one ended (sticky), so a tag is read in one pass:
31
+ // `href="/x"`, `href='/x'`, `href={"/x"}` or `` href={`/x`} `` (Svelte), and Vue's `:href="'/x'"`. Any
32
+ // other `{...}` value is an expression and names no path.
33
+ const ATTRIBUTE =
34
+ /\s+([^\s=>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(?:"([^"]*)"|'([^']*)'|`([^`]*)`)\s*\}|\{[^}]*\}))?/y
35
+ const BOUND_LITERAL = /^\s*(?:'([^']*)'|"([^"]*)"|`([^`$]*)`)\s*$/
36
+
37
+ interface Judged {
38
+ readonly pattern: string
39
+ readonly params: ReadonlyMap<string, string>
40
+ }
41
+
42
+ interface PageRoutes {
43
+ /** The page route an anchor path resolves to, most specific first. */
44
+ match(path: string): Judged | undefined
45
+ /** Whether something other than a page serves `path`: a backend route or a file in `public/`. */
46
+ servedElsewhere(path: string): boolean
47
+ /** The static page pattern closest to `path`, when it is a typo away. */
48
+ nearest(path: string): string | undefined
49
+ /** Whether a backend route path the scan could not read leaves the dead-link verdict open. */
50
+ readonly backendUnknown: boolean
51
+ }
52
+
53
+ const cache = new WeakMap<RuleContext, Promise<PageRoutes | undefined>>()
54
+
55
+ function distance(a: string, b: string): number {
56
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i)
57
+ for (let i = 1; i <= a.length; i++) {
58
+ const next = [i]
59
+ for (let j = 1; j <= b.length; j++) {
60
+ next[j] = Math.min(
61
+ (row[j] ?? 0) + 1,
62
+ (next[j - 1] ?? 0) + 1,
63
+ (row[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1),
64
+ )
65
+ }
66
+ row = next
67
+ }
68
+ return row[b.length] ?? 0
69
+ }
70
+
71
+ /** Read only literal mount exports, never import/evaluate the app's config. An unreadable field
72
+ * leaves the dead-link verdict open, just like an unreadable backend registration. */
73
+ function backendMount(
74
+ ctx: RuleContext,
75
+ ): { readonly prefix: string | undefined; readonly strip: boolean } | undefined {
76
+ let prefix: string | undefined
77
+ let strip = false
78
+ let prefixUnknown = false
79
+ let stripUnknown = false
80
+ // nifra.config.ts overrides individual fields inherited from backend/framework.ts.
81
+ for (const file of [FRAMEWORK_FILE, CONFIG_FILE]) {
82
+ const path = join(ctx.root, file)
83
+ if (!existsSync(path)) continue
84
+ const source = stripComments(readFileSync(path, "utf8"))
85
+ const read = readStaticApiPrefix(source)
86
+ if (read.kind !== "default") {
87
+ prefixUnknown = read.kind === "unreadable"
88
+ if (read.kind === "literal") prefix = read.value
89
+ }
90
+ if (/\bapiStrip\b/.test(source)) {
91
+ const literal =
92
+ /\bexport\s+const\s+apiStrip\s*(?::\s*boolean\s*)?=\s*(true|false)\s*(?:as\s+const\s*)?(?:;|\r?\n|$)/.exec(
93
+ source,
94
+ )
95
+ stripUnknown = literal === null
96
+ if (literal !== null) strip = literal[1] === "true"
97
+ }
98
+ // A star re-export may supply either field; it cannot prove an absent/default mount.
99
+ if (/\bexport\s*\*/.test(source)) {
100
+ prefixUnknown = true
101
+ stripUnknown = true
102
+ }
103
+ }
104
+ return prefixUnknown || stripUnknown ? undefined : { prefix, strip }
105
+ }
106
+
107
+ function pageRoutes(ctx: RuleContext): Promise<PageRoutes | undefined> {
108
+ let loaded = cache.get(ctx)
109
+ if (loaded === undefined) {
110
+ loaded = loadPageRoutes(ctx)
111
+ cache.set(ctx, loaded)
112
+ }
113
+ return loaded
114
+ }
115
+
116
+ async function loadPageRoutes(ctx: RuleContext): Promise<PageRoutes | undefined> {
117
+ // The pages come from the file system, not the scanned sources: a `.vue`, `.svelte` or `.mdx` page is
118
+ // not in the source index, and a missed page would turn its links into false 404s.
119
+ const routesDir = join(ctx.root, "routes")
120
+ if (!existsSync(routesDir)) return undefined
121
+ const { discoverRoutes } = await import("@nifrajs/web/fs")
122
+ const { compileRoutePattern, matchRoutePattern, sortRoutesBySpecificity } = await import(
123
+ "@nifrajs/core/pattern"
124
+ )
125
+ let patterns: string[]
126
+ try {
127
+ patterns = discoverRoutes(routesDir).routes.map((route) => route.pattern)
128
+ } catch {
129
+ return undefined
130
+ }
131
+ if (patterns.length === 0) return undefined
132
+ // `sortRoutesBySpecificity` reads the compiled pattern from `pattern`, and carries the rest along.
133
+ const compile = (route: string) => {
134
+ try {
135
+ return [{ route, pattern: compileRoutePattern(route) }]
136
+ } catch {
137
+ return []
138
+ }
139
+ }
140
+ const pageEntries = sortRoutesBySpecificity(patterns.flatMap(compile))
141
+ const mount = backendMount(ctx)
142
+ const backendEntries = buildRouteTable({
143
+ pages: [],
144
+ api: ctx.project.routes,
145
+ apiPrefix: mount?.prefix ?? "",
146
+ apiStrip: mount?.strip ?? false,
147
+ })
148
+ // Without a configured mount, preserve the scan's allowance for independently served backends.
149
+ .filter((route) => mount?.prefix === undefined || route.autoMounted)
150
+ .flatMap((route) => compile(route.path))
151
+ // Code-unit order, so which of two equally close pages a diagnostic names does not depend on the
152
+ // directory order of the machine that ran the check.
153
+ const staticPatterns = patterns.filter((pattern) => !/[:*]/.test(pattern)).sort(codeUnitOrder)
154
+ return {
155
+ backendUnknown: mount === undefined || ctx.project.sourceFindings.routePaths.length > 0,
156
+ match(path) {
157
+ for (const entry of pageEntries) {
158
+ const found = matchRoutePattern(entry.pattern, path)
159
+ if (found.matched)
160
+ return {
161
+ pattern: entry.route,
162
+ params: new Map(Object.entries(found.params).map(([k, v]) => [k, String(v)])),
163
+ }
164
+ }
165
+ return undefined
166
+ },
167
+ servedElsewhere(path) {
168
+ if (backendEntries.some((entry) => matchRoutePattern(entry.pattern, path).matched))
169
+ return true
170
+ if (FILE_EXTENSION.test(path) || path.startsWith("/_")) return true
171
+ try {
172
+ return existsSync(join(ctx.root, "public", decodeURI(path)))
173
+ } catch {
174
+ return false
175
+ }
176
+ },
177
+ nearest(path) {
178
+ let best: { pattern: string; at: number } | undefined
179
+ for (const pattern of staticPatterns) {
180
+ const at = distance(path, pattern)
181
+ if (at <= 2 && (best === undefined || at < best.at)) best = { pattern, at }
182
+ }
183
+ return best?.pattern
184
+ },
185
+ }
186
+ }
187
+
188
+ interface Verdict {
189
+ readonly kind: "dead" | "unchecked"
190
+ readonly shown: string
191
+ readonly message: string
192
+ readonly evidence: readonly string[]
193
+ }
194
+
195
+ const spell = (path: string): string => path.replaceAll(ANCHOR_HOLE, `\${…}`)
196
+
197
+ /** Judge one anchor path (a hole stands for a `${...}`), or undefined when it is not this rule's business. */
198
+ function judge(routes: PageRoutes, written: string): Verdict | undefined {
199
+ const cut = written.search(/[?#]/)
200
+ const path = cut < 0 ? written : written.slice(0, cut)
201
+ const rest = cut < 0 ? "" : written.slice(cut)
202
+ const dynamic = path.includes(ANCHOR_HOLE)
203
+ const found = routes.match(path)
204
+ const shown = spell(written)
205
+ if (found !== undefined) {
206
+ const hash = rest.includes("#") ? rest.slice(rest.indexOf("#") + 1) : undefined
207
+ const query = rest.startsWith("?")
208
+ const entries = [...found.params]
209
+ const params =
210
+ entries.length === 0
211
+ ? ""
212
+ : `, params: { ${entries.map(([name, value]) => `${name}: ${dynamic ? "…" : JSON.stringify(value)}`).join(", ")} }`
213
+ const call = `href({ to: ${JSON.stringify(found.pattern)}${params}${query ? ", search: { … }" : ""}${hash !== undefined && hash !== "" && !hash.includes(ANCHOR_HOLE) ? `, hash: ${JSON.stringify(hash)}` : ""} })`
214
+ return {
215
+ kind: "unchecked",
216
+ shown,
217
+ message: `\`<a href="${shown}">\` writes a page's path by hand, so renaming or removing ${found.pattern} leaves it dead and nothing fails. Build it with \`${call}\` (\`href\` is exported by \`@nifrajs/web-<framework>/router\`), which checks the route and its params against the app.`,
218
+ evidence: [
219
+ `${shown} resolves to the page route ${found.pattern}`,
220
+ "a path built elsewhere, such as a CMS link, takes `rawHref(path)`",
221
+ ],
222
+ }
223
+ }
224
+ if (dynamic || routes.backendUnknown || routes.servedElsewhere(path)) return undefined
225
+ const near = routes.nearest(path)
226
+ return {
227
+ kind: "dead",
228
+ shown,
229
+ message: `\`<a href="${shown}">\` links to a path no page of this app serves, so following it is a 404.${near === undefined ? "" : ` Did you mean ${near}?`} Use \`href({ to })\` with a route of the app, which fails to compile for one that does not exist.`,
230
+ evidence: [
231
+ `${path} matches no page route, no backend route and no file in public/`,
232
+ "a path another server answers takes `rawHref(path)`",
233
+ ],
234
+ }
235
+ }
236
+
237
+ const adviceFor = (code: string, template: boolean): string =>
238
+ template
239
+ ? `a link kept as written, on purpose: \`<!-- nifra-expect ${code}: <reason> -->\` above the anchor`
240
+ : `a link kept as written, on purpose: \`// nifra-expect ${code}: <reason>\` above the attribute`
241
+
242
+ function report(
243
+ code: string,
244
+ severity: "warn" | "info",
245
+ file: string,
246
+ line: number,
247
+ verdict: Verdict,
248
+ note: string | undefined,
249
+ template = false,
250
+ ): Diagnostic {
251
+ return diagnostic({
252
+ code,
253
+ severity,
254
+ file,
255
+ line,
256
+ message: note === undefined ? verdict.message : `${verdict.message} ${note}`,
257
+ evidence: [...verdict.evidence, adviceFor(code, template)],
258
+ verify: "nifra check",
259
+ })
260
+ }
261
+
262
+ interface HtmlComment {
263
+ readonly start: number
264
+ /** Where the text after `<!--` stops: before the closing delimiter. */
265
+ readonly bodyEnd: number
266
+ readonly end: number
267
+ }
268
+
269
+ // A comment ends at `-->` or `--!>`.
270
+ const COMMENT_END = /--!?>/g
271
+
272
+ /** The comment opened at `start`, which HTML ends at `-->` or `--!>`; `<!-->` and `<!--->` are empty. */
273
+ function commentAt(text: string, start: number): HtmlComment {
274
+ const body = start + 4
275
+ if (text.startsWith(">", body)) return { start, bodyEnd: body, end: body + 1 }
276
+ if (text.startsWith("->", body)) return { start, bodyEnd: body, end: body + 2 }
277
+ COMMENT_END.lastIndex = body
278
+ const close = COMMENT_END.exec(text)
279
+ return close === null
280
+ ? { start, bodyEnd: text.length, end: text.length }
281
+ : { start, bodyEnd: close.index, end: close.index + close[0].length }
282
+ }
283
+
284
+ /** The end of a markup tag or `{expression}`, ignoring `>`/braces inside quoted values. */
285
+ function markupEnd(text: string, start: number, expression = false): number {
286
+ let quote: string | undefined
287
+ let braces = expression ? 1 : 0
288
+ for (let at = start; at < text.length; at++) {
289
+ const char = text[at]
290
+ if (quote !== undefined) {
291
+ if (braces > 0 && char === "\\") at++
292
+ else if (char === quote) quote = undefined
293
+ } else if (char === '"' || char === "'" || (braces > 0 && char === "`")) quote = char
294
+ else if (char === "{") braces++
295
+ else if (char === "}") {
296
+ braces--
297
+ if (expression && braces === 0) return at + 1
298
+ } else if (!expression && braces === 0 && char === ">") return at + 1
299
+ }
300
+ return text.length
301
+ }
302
+
303
+ /** Scan markup, not script strings, HTML comments or other tags' quoted attributes. The existing
304
+ * componentScripts scanner only extracts scripts and cannot distinguish these template regions. */
305
+ function templateHrefs(
306
+ text: string,
307
+ vue: boolean,
308
+ ): {
309
+ readonly hrefs: Array<{ readonly at: number; readonly tagAt: number; readonly value: string }>
310
+ readonly expectationLines: readonly string[]
311
+ } {
312
+ const hrefs: Array<{ at: number; tagAt: number; value: string }> = []
313
+ const comments: HtmlComment[] = []
314
+ let templateDepth = 0
315
+ for (let at = 0; at < text.length; ) {
316
+ if (text.startsWith("<!--", at)) {
317
+ const comment = commentAt(text, at)
318
+ comments.push(comment)
319
+ at = comment.end
320
+ continue
321
+ }
322
+ if (text[at] === "{" && (!vue || text.startsWith("{{", at))) {
323
+ at = markupEnd(text, at + 1, true)
324
+ continue
325
+ }
326
+ if (text[at] !== "<") {
327
+ at++
328
+ continue
329
+ }
330
+ const tag = /^<(\/?)([\w-]+)(?=[\s/>])/.exec(text.slice(at))
331
+ if (tag === null) {
332
+ at++
333
+ continue
334
+ }
335
+ const tagAt = at
336
+ const end = markupEnd(text, at + tag[0].length)
337
+ const name = tag[2]?.toLowerCase()
338
+ const closing = tag[1] === "/"
339
+ at = end
340
+ if (!closing && (name === "script" || name === "style")) {
341
+ const close = name === "script" ? /<\/script\s*>/gi : /<\/style\s*>/gi
342
+ close.lastIndex = end
343
+ const match = close.exec(text)
344
+ at = match === null ? text.length : close.lastIndex
345
+ continue
346
+ }
347
+ if (name === "template") templateDepth += closing ? -1 : 1
348
+ if (closing || name !== "a" || (vue && templateDepth <= 0)) continue
349
+ ATTRIBUTE.lastIndex = tagAt + tag[0].length
350
+ for (let match = ATTRIBUTE.exec(text); match !== null; match = ATTRIBUTE.exec(text)) {
351
+ const [whole, attribute, doubled, single, braceDouble, braceSingle, braceTemplate] = match
352
+ if (attribute !== "href" && attribute !== ":href" && attribute !== "v-bind:href") continue
353
+ const raw = doubled ?? single
354
+ const value =
355
+ attribute === "href"
356
+ ? (raw ?? braceDouble ?? braceSingle ?? braceTemplate)
357
+ : raw
358
+ ?.match(BOUND_LITERAL)
359
+ ?.slice(1)
360
+ .find((part) => part !== undefined)
361
+ if (value !== undefined)
362
+ hrefs.push({
363
+ at: ATTRIBUTE.lastIndex - whole.length + whole.indexOf(attribute),
364
+ tagAt,
365
+ value,
366
+ })
367
+ }
368
+ }
369
+ // Adapt only real HTML comments to the shared directive parser. Non-comment code stays a block
370
+ // boundary; quoted marker text cannot suppress anything. Line counts are unchanged.
371
+ const code = (part: string): string => part.replace(/[^\s]/g, "x")
372
+ let expectations = ""
373
+ let previous = 0
374
+ for (const comment of comments) {
375
+ expectations += code(text.slice(previous, comment.start))
376
+ expectations += text
377
+ .slice(comment.start + 4, comment.bodyEnd)
378
+ .split("\n")
379
+ .map((line) => `// ${line}`)
380
+ .join("\n")
381
+ previous = comment.end
382
+ }
383
+ expectations += code(text.slice(previous))
384
+ return { hrefs, expectationLines: expectations.split("\n") }
385
+ }
386
+
387
+ /** The 1-based line of an offset in `text`: a search over the line starts, so a file with thousands of links is not re-split for each. */
388
+ function lineLookup(text: string): (offset: number) => number {
389
+ const starts = [0]
390
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) starts.push(at + 1)
391
+ return (offset) => {
392
+ let low = 0
393
+ let high = starts.length - 1
394
+ while (low < high) {
395
+ const mid = (low + high + 1) >> 1
396
+ if ((starts[mid] ?? 0) <= offset) low = mid
397
+ else high = mid - 1
398
+ }
399
+ return low + 1
400
+ }
401
+ }
402
+
403
+ async function templateFindings(
404
+ ctx: RuleContext,
405
+ routes: PageRoutes,
406
+ kind: Verdict["kind"],
407
+ code: string,
408
+ severity: "warn" | "info",
409
+ ): Promise<Diagnostic[]> {
410
+ const findings: Diagnostic[] = []
411
+ const files: string[] = []
412
+ for await (const entry of new Glob("**/*.{vue,svelte}").scan({ cwd: ctx.root, dot: false })) {
413
+ // Bun yields `\` paths on Windows, which IGNORED and TEST_DIR (and the reported location) expect as `/`.
414
+ const file = toPosix(entry)
415
+ if (!IGNORED.test(file) && !TEST_DIR.test(file)) files.push(file)
416
+ }
417
+ for (const file of files.sort()) {
418
+ // The source index holds only a component's script blocks; the links are in its template.
419
+ const text = readFileSync(join(ctx.root, file), "utf8")
420
+ if (!text.includes("href")) continue
421
+ const { hrefs, expectationLines } = templateHrefs(text, file.endsWith(".vue"))
422
+ const lineOf = lineLookup(text)
423
+ for (const { at, tagAt, value } of hrefs) {
424
+ if (!value.startsWith("/") || value.startsWith("//")) continue
425
+ // A Svelte `{expression}` inside the value is a hole.
426
+ const verdict = judge(routes, value.replace(/\$?\{[^}]*\}/g, ANCHOR_HOLE))
427
+ if (verdict?.kind !== kind) continue
428
+ const line = lineOf(at)
429
+ const tagLine = lineOf(tagAt)
430
+ if (
431
+ commentBlockExpectation(expectationLines, tagLine, [code, "internal-link"]) !== undefined ||
432
+ commentBlockExpectation(expectationLines, line, [code, "internal-link"]) !== undefined
433
+ )
434
+ continue
435
+ findings.push(report(code, severity, file, line, verdict, undefined, true))
436
+ }
437
+ }
438
+ return findings
439
+ }
440
+
441
+ function internalLinkRule(
442
+ code: string,
443
+ title: string,
444
+ kind: Verdict["kind"],
445
+ severity: "warn" | "info",
446
+ ): CheckRule {
447
+ return {
448
+ code,
449
+ title,
450
+ async scan(ctx) {
451
+ const routes = await pageRoutes(ctx)
452
+ if (routes === undefined) return []
453
+ const scripts = await scanSources(ctx, {
454
+ expectation: [code, "internal-link"],
455
+ mayMatch: (text) => text.includes("<a") && text.includes("href"),
456
+ find: (facts, tree) =>
457
+ TEST_DIR.test(tree.fileName)
458
+ ? []
459
+ : facts.internalAnchors(tree).flatMap((anchor) => {
460
+ const verdict = judge(routes, anchor.path)
461
+ if (verdict?.kind !== kind) return []
462
+ return [
463
+ {
464
+ position: anchor.position,
465
+ report: (line: number, note?: string) =>
466
+ report(code, severity, tree.fileName, line, verdict, note),
467
+ },
468
+ ]
469
+ }),
470
+ })
471
+ return [...scripts, ...(await templateFindings(ctx, routes, kind, code, severity))]
472
+ },
473
+ }
474
+ }
475
+
476
+ export const deadInternalLinkRule = internalLinkRule(
477
+ "NF-C057",
478
+ "Internal link to a path no page serves",
479
+ "dead",
480
+ "warn",
481
+ )
482
+
483
+ export const uncheckedInternalLinkRule = internalLinkRule(
484
+ "NF-C058",
485
+ "Internal link written as a path string",
486
+ "unchecked",
487
+ "info",
488
+ )
489
+
490
+ export const internalLinkRules = Object.freeze([deadInternalLinkRule, uncheckedInternalLinkRule])
@@ -409,10 +409,31 @@ const typecheckRule: CheckRule = {
409
409
  }
410
410
  }
411
411
  findings.push(...outsideProgramFindings(tc.outsideProgram ?? []))
412
+ if (tc.routeTableOutsideProgram !== undefined)
413
+ findings.push(routeTableFinding(tc.routeTableOutsideProgram))
412
414
  return findings
413
415
  },
414
416
  }
415
417
 
418
+ /** The route table exists but no program loads it: every `to` and `search` stays loose, silently. */
419
+ function routeTableFinding(file: string): Diagnostic {
420
+ return legacyDiagnostic("typecheck", {
421
+ severity: "warning",
422
+ file,
423
+ message: `${file} is outside tsc's program, so navigate, redirect and Link accept any target and search: no route imports its ./+types module, and no tsconfig names the table`,
424
+ fix: `Add "${file}" to tsconfig.json "files" (a "files" entry is not filtered by "exclude"), or import a route's ./+types module from a file the program holds`,
425
+ suggestion: {
426
+ kind: "manual",
427
+ title: "Load the generated route table",
428
+ steps: [
429
+ `Add "${file}" to the "files" array in tsconfig.json, or in another tsconfig the typecheck runs.`,
430
+ 'List it under "files", not "include": an "exclude" that names ".nifra" would drop it from "include".',
431
+ "Run `nifra check` again; links and redirects are now checked against the app's routes.",
432
+ ],
433
+ },
434
+ })
435
+ }
436
+
416
437
  /** One finding per zone folder: the fix (tsconfig `include`) is per folder, not per file. */
417
438
  function outsideProgramFindings(files: readonly string[]): Diagnostic[] {
418
439
  const byFolder = new Map<string, { readonly first: string; readonly group: string[] }>()
@@ -0,0 +1,47 @@
1
+ import { diagnostic } from "../diagnostics.ts"
2
+ import type { CheckRule } from "./index.ts"
3
+ import { scanSources } from "./source-scan.ts"
4
+
5
+ const SERVER_FN_SUFFIX = /\.fn(?:\.[cm]?[jt]sx?)?$/
6
+
7
+ /**
8
+ * NF-C056: `serverFunctions("todos", mod)` where `mod` is `todos-list.fn.ts`. The client build calls
9
+ * the namespace named by the file, so a mount under another word serves routes the stubs never reach
10
+ * and every call 404s.
11
+ */
12
+ export const serverFnNamespaceRule: CheckRule = {
13
+ code: "NF-C056",
14
+ title: "serverFunctions namespace differs from its module's filename",
15
+ scan: (ctx) =>
16
+ scanSources(ctx, {
17
+ expectation: ["NF-C056", "server-fn-namespace"],
18
+ requireReason: true,
19
+ mayMatch: (text) => text.includes("serverFunctions") && text.includes(".fn"),
20
+ find: (facts, tree) =>
21
+ facts.serverFunctionMounts(tree).flatMap((mount) => {
22
+ const base = mount.specifier.split("/").pop() ?? ""
23
+ const expected = base.replace(SERVER_FN_SUFFIX, "")
24
+ if (mount.namespace === expected) return []
25
+ return [
26
+ {
27
+ position: mount.position,
28
+ expectAt: mount.callPosition,
29
+ report: (line, note) =>
30
+ diagnostic({
31
+ code: "NF-C056",
32
+ severity: "error",
33
+ file: tree.fileName,
34
+ line,
35
+ message: `serverFunctions(${JSON.stringify(mount.namespace)}, ...) mounts ${base}, whose client stubs call the namespace ${JSON.stringify(expected)}: every call 404s. Mount it as serverFunctions(${JSON.stringify(expected)}, ...), or rename the file.${note === undefined ? "" : ` ${note}.`}`,
36
+ evidence: [
37
+ "the client build names a *.fn.ts module's namespace after its filename without .fn",
38
+ `the server mounts it under /_nifra/fn/${mount.namespace}/, the stubs POST to /_nifra/fn/${expected}/`,
39
+ "a mount kept on purpose: `// nifra-expect NF-C056: <reason>` above the call",
40
+ ],
41
+ verify: "nifra check",
42
+ }),
43
+ },
44
+ ]
45
+ }),
46
+ }),
47
+ }
@@ -0,0 +1,66 @@
1
+ import type * as TSApi from "typescript"
2
+ import type { Diagnostic } from "../diagnostics.ts"
3
+ import { createSourceFacts, type SourceFacts } from "../internal/source-facts.ts"
4
+ import { commentBlockExpectation, MISSING_EXPECTATION_REASON } from "./comment-markers.ts"
5
+ import type { RuleContext } from "./index.ts"
6
+ import { loadRuleTypeScript } from "./typescript.ts"
7
+
8
+ /** One place in a file a source rule reports, once the line it sits on is known. */
9
+ export interface SourceFinding {
10
+ /** The offset in the file the finding is reported at. */
11
+ readonly position: number
12
+ /** Where a `nifra-expect` comment is read: the line of this offset, else the finding's own. */
13
+ readonly expectAt?: number
14
+ /** `note` is set when a `nifra-expect` comment names the finding but gives no reason. */
15
+ readonly report: (line: number, note?: string) => Diagnostic
16
+ }
17
+
18
+ export interface SourceScan {
19
+ /** The `nifra-expect` names that accept a finding. */
20
+ readonly expectation: readonly string[]
21
+ /** Whether a comment without a reason after its colon fails to accept a finding. */
22
+ readonly requireReason?: boolean
23
+ /** A cheap test of a file's text; the file is parsed only when it passes. */
24
+ readonly mayMatch: (text: string) => boolean
25
+ readonly find: (facts: SourceFacts, tree: TSApi.SourceFile) => readonly SourceFinding[]
26
+ }
27
+
28
+ /**
29
+ * The shared walk of a lint over TypeScript sources: every `.ts`/`.tsx` file whose text passes `mayMatch`
30
+ * is parsed, `find` names its findings, and one a `// nifra-expect <code>` block above its line
31
+ * accepts is dropped.
32
+ */
33
+ export async function scanSources(
34
+ ctx: RuleContext,
35
+ scan: SourceScan,
36
+ ): Promise<readonly Diagnostic[]> {
37
+ const loaded = await loadRuleTypeScript(ctx)
38
+ if (loaded.diagnostics !== undefined) return loaded.diagnostics
39
+ if (loaded.compiler === undefined) return []
40
+ const facts = createSourceFacts(loaded.compiler)
41
+ const findings: Diagnostic[] = []
42
+ for (const file of ctx.project.source.files) {
43
+ if (!/\.[cm]?tsx?$/.test(file)) continue
44
+ const text = ctx.project.source.read(file)
45
+ if (text === undefined || !scan.mayMatch(text)) continue
46
+ const tree = facts.parse(file, text)
47
+ if (tree === undefined) continue
48
+ const lines = text.split("\n")
49
+ const lineOf = (position: number): number =>
50
+ tree.getLineAndCharacterOfPosition(position).line + 1
51
+ for (const found of scan.find(facts, tree)) {
52
+ const line = lineOf(found.position)
53
+ const expected = commentBlockExpectation(
54
+ lines,
55
+ found.expectAt === undefined ? line : lineOf(found.expectAt),
56
+ scan.expectation,
57
+ )
58
+ if (expected !== undefined && (scan.requireReason !== true || expected.reason !== undefined))
59
+ continue
60
+ findings.push(
61
+ found.report(line, expected === undefined ? undefined : MISSING_EXPECTATION_REASON),
62
+ )
63
+ }
64
+ }
65
+ return findings
66
+ }