@nifrajs/cli 5.15.1 → 5.16.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 (166) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +11 -0
  3. package/dist/build-provenance.d.ts +14 -0
  4. package/dist/build-provenance.d.ts.map +1 -0
  5. package/dist/build-provenance.js +82 -0
  6. package/dist/build-provenance.js.map +1 -0
  7. package/dist/check-diagnostics.d.ts +1 -0
  8. package/dist/check-diagnostics.d.ts.map +1 -1
  9. package/dist/check-diagnostics.js +4 -0
  10. package/dist/check-diagnostics.js.map +1 -1
  11. package/dist/check-scan.d.ts +1 -1
  12. package/dist/check-scan.d.ts.map +1 -1
  13. package/dist/check-scan.js +6 -5
  14. package/dist/check-scan.js.map +1 -1
  15. package/dist/check-timings.d.ts +11 -0
  16. package/dist/check-timings.d.ts.map +1 -0
  17. package/dist/check-timings.js +23 -0
  18. package/dist/check-timings.js.map +1 -0
  19. package/dist/check.d.ts +3 -0
  20. package/dist/check.d.ts.map +1 -1
  21. package/dist/check.js +68 -28
  22. package/dist/check.js.map +1 -1
  23. package/dist/cli.d.ts.map +1 -1
  24. package/dist/cli.js +26 -11
  25. package/dist/cli.js.map +1 -1
  26. package/dist/command-catalog.d.ts +3 -0
  27. package/dist/command-catalog.d.ts.map +1 -1
  28. package/dist/command-catalog.js +25 -4
  29. package/dist/command-catalog.js.map +1 -1
  30. package/dist/dev-feed-tool.d.ts.map +1 -1
  31. package/dist/dev-feed-tool.js +4 -2
  32. package/dist/dev-feed-tool.js.map +1 -1
  33. package/dist/doctor.d.ts +5 -2
  34. package/dist/doctor.d.ts.map +1 -1
  35. package/dist/doctor.js +27 -9
  36. package/dist/doctor.js.map +1 -1
  37. package/dist/internal/named-imports.d.ts +4 -0
  38. package/dist/internal/named-imports.d.ts.map +1 -0
  39. package/dist/internal/named-imports.js +19 -0
  40. package/dist/internal/named-imports.js.map +1 -0
  41. package/dist/internal/rewrite-kit.d.ts +35 -0
  42. package/dist/internal/rewrite-kit.d.ts.map +1 -0
  43. package/dist/internal/rewrite-kit.js +14 -0
  44. package/dist/internal/rewrite-kit.js.map +1 -0
  45. package/dist/internal/source-facts.d.ts +37 -0
  46. package/dist/internal/source-facts.d.ts.map +1 -1
  47. package/dist/internal/source-facts.js +115 -0
  48. package/dist/internal/source-facts.js.map +1 -1
  49. package/dist/levels-tool.d.ts +3 -0
  50. package/dist/levels-tool.d.ts.map +1 -1
  51. package/dist/levels-tool.js +28 -18
  52. package/dist/levels-tool.js.map +1 -1
  53. package/dist/mcp-exec.js +1 -1
  54. package/dist/mcp-exec.js.map +1 -1
  55. package/dist/mcp-http.js +1 -1
  56. package/dist/mcp-io.d.ts +3 -1
  57. package/dist/mcp-io.d.ts.map +1 -1
  58. package/dist/mcp-io.js +9 -2
  59. package/dist/mcp-io.js.map +1 -1
  60. package/dist/mcp-isolate.d.ts.map +1 -1
  61. package/dist/mcp-isolate.js +3 -1
  62. package/dist/mcp-isolate.js.map +1 -1
  63. package/dist/mcp-project-child.d.ts +10 -0
  64. package/dist/mcp-project-child.d.ts.map +1 -1
  65. package/dist/mcp-project-child.js +12 -1
  66. package/dist/mcp-project-child.js.map +1 -1
  67. package/dist/mcp-tool-meta.d.ts.map +1 -1
  68. package/dist/mcp-tool-meta.js +4 -1
  69. package/dist/mcp-tool-meta.js.map +1 -1
  70. package/dist/recipes/5.16.0.d.ts +12 -0
  71. package/dist/recipes/5.16.0.d.ts.map +1 -0
  72. package/dist/recipes/5.16.0.js +31 -0
  73. package/dist/recipes/5.16.0.js.map +1 -0
  74. package/dist/recipes/index.d.ts.map +1 -1
  75. package/dist/recipes/index.js +2 -0
  76. package/dist/recipes/index.js.map +1 -1
  77. package/dist/review.d.ts.map +1 -1
  78. package/dist/review.js +3 -0
  79. package/dist/review.js.map +1 -1
  80. package/dist/rules/codes.d.ts +3 -0
  81. package/dist/rules/codes.d.ts.map +1 -1
  82. package/dist/rules/codes.js +3 -0
  83. package/dist/rules/codes.js.map +1 -1
  84. package/dist/rules/explanations.d.ts.map +1 -1
  85. package/dist/rules/explanations.js +15 -0
  86. package/dist/rules/explanations.js.map +1 -1
  87. package/dist/rules/route-hooks.d.ts +10 -0
  88. package/dist/rules/route-hooks.d.ts.map +1 -0
  89. package/dist/rules/route-hooks.js +88 -0
  90. package/dist/rules/route-hooks.js.map +1 -0
  91. package/dist/rules/silent-sse.d.ts +9 -0
  92. package/dist/rules/silent-sse.d.ts.map +1 -0
  93. package/dist/rules/silent-sse.js +89 -0
  94. package/dist/rules/silent-sse.js.map +1 -0
  95. package/dist/rules/source-scan.d.ts +4 -2
  96. package/dist/rules/source-scan.d.ts.map +1 -1
  97. package/dist/rules/source-scan.js +3 -1
  98. package/dist/rules/source-scan.js.map +1 -1
  99. package/dist/source-rewrites.d.ts +2 -20
  100. package/dist/source-rewrites.d.ts.map +1 -1
  101. package/dist/source-rewrites.js +3 -13
  102. package/dist/source-rewrites.js.map +1 -1
  103. package/dist/typecheck-cache.d.ts +6 -0
  104. package/dist/typecheck-cache.d.ts.map +1 -0
  105. package/dist/typecheck-cache.js +37 -0
  106. package/dist/typecheck-cache.js.map +1 -0
  107. package/dist/typecheck-coverage.js +1 -1
  108. package/dist/typecheck-coverage.js.map +1 -1
  109. package/dist/typed-api-rewrites.d.ts +3 -0
  110. package/dist/typed-api-rewrites.d.ts.map +1 -0
  111. package/dist/typed-api-rewrites.js +253 -0
  112. package/dist/typed-api-rewrites.js.map +1 -0
  113. package/dist/upgrade.d.ts.map +1 -1
  114. package/dist/upgrade.js +3 -1
  115. package/dist/upgrade.js.map +1 -1
  116. package/dist/verification-gates.d.ts +23 -0
  117. package/dist/verification-gates.d.ts.map +1 -0
  118. package/dist/verification-gates.js +8 -0
  119. package/dist/verification-gates.js.map +1 -0
  120. package/dist/verification.d.ts +2 -0
  121. package/dist/verification.d.ts.map +1 -1
  122. package/dist/verification.js +6 -0
  123. package/dist/verification.js.map +1 -1
  124. package/dist/work-graph.d.ts +17 -8
  125. package/dist/work-graph.d.ts.map +1 -1
  126. package/dist/work-graph.js +157 -104
  127. package/dist/work-graph.js.map +1 -1
  128. package/docs/examples.json +2 -2
  129. package/docs/llms-full.txt +563 -46
  130. package/docs/types.json +269 -84
  131. package/package.json +12 -12
  132. package/src/build-provenance.ts +107 -0
  133. package/src/check-diagnostics.ts +5 -0
  134. package/src/check-scan.ts +7 -4
  135. package/src/check-timings.ts +27 -0
  136. package/src/check.ts +77 -32
  137. package/src/cli.ts +33 -12
  138. package/src/command-catalog.ts +28 -4
  139. package/src/dev-feed-tool.ts +8 -3
  140. package/src/doctor.ts +37 -18
  141. package/src/internal/named-imports.ts +26 -0
  142. package/src/internal/rewrite-kit.ts +49 -0
  143. package/src/internal/source-facts.ts +158 -0
  144. package/src/levels-tool.ts +27 -18
  145. package/src/mcp-exec.ts +1 -1
  146. package/src/mcp-http.ts +1 -1
  147. package/src/mcp-io.ts +13 -1
  148. package/src/mcp-isolate.ts +4 -0
  149. package/src/mcp-project-child.ts +19 -1
  150. package/src/mcp-tool-meta.ts +5 -1
  151. package/src/recipes/5.16.0.ts +41 -0
  152. package/src/recipes/index.ts +2 -0
  153. package/src/review.ts +3 -0
  154. package/src/rules/codes.ts +3 -0
  155. package/src/rules/explanations.ts +15 -0
  156. package/src/rules/route-hooks.ts +112 -0
  157. package/src/rules/silent-sse.ts +95 -0
  158. package/src/rules/source-scan.ts +8 -3
  159. package/src/source-rewrites.ts +18 -52
  160. package/src/typecheck-cache.ts +33 -0
  161. package/src/typecheck-coverage.ts +1 -1
  162. package/src/typed-api-rewrites.ts +308 -0
  163. package/src/upgrade.ts +2 -1
  164. package/src/verification-gates.ts +9 -0
  165. package/src/verification.ts +8 -0
  166. package/src/work-graph.ts +200 -121
package/src/mcp-io.ts CHANGED
@@ -25,13 +25,25 @@ export const LOCAL_TOOL_MAX_RESPONSE_BYTES = 1_048_576
25
25
  */
26
26
  export const OWN_PROCESS_GROUP = process.platform !== "win32"
27
27
 
28
+ // The MCP server cancels the whole project child group. Its subprocesses must stay in that group.
29
+ let projectChildProcess = false
30
+
31
+ export function enterProjectChildProcess(): void {
32
+ projectChildProcess = true
33
+ }
34
+
35
+ export function inProjectChildProcess(): boolean {
36
+ return projectChildProcess
37
+ }
38
+
28
39
  /** Signal a child spawned with `detached: OWN_PROCESS_GROUP`: its whole group on POSIX. */
29
40
  export function signalProcessGroup(
30
41
  proc: { readonly pid: number; kill(signal?: NodeJS.Signals): void },
31
42
  signal: NodeJS.Signals,
43
+ detached = OWN_PROCESS_GROUP,
32
44
  ): void {
33
45
  try {
34
- if (OWN_PROCESS_GROUP) process.kill(-proc.pid, signal)
46
+ if (detached) process.kill(-proc.pid, signal)
35
47
  else proc.kill(signal)
36
48
  } catch {
37
49
  // The group has already exited.
@@ -16,10 +16,12 @@ import type { NifraMonorepoConfig } from "./load.ts"
16
16
  import { appFingerprint } from "./mcp-exec.ts"
17
17
  import {
18
18
  CHILD_TIMEOUT_MS,
19
+ forwardTerminalSignals,
19
20
  OWN_PROCESS_GROUP,
20
21
  readBoundedLines,
21
22
  readBoundedStream,
22
23
  signalProcessGroup,
24
+ stopGroupAndWait,
23
25
  stopGroupOnExit,
24
26
  } from "./mcp-io.ts"
25
27
  import type {
@@ -135,6 +137,7 @@ export async function askProjectChild(
135
137
  )
136
138
  }
137
139
  stopGroupOnExit(proc)
140
+ const releaseSignals = forwardTerminalSignals(() => stopGroupAndWait(proc))
138
141
  let stopped: "timeout" | "cancel" | undefined
139
142
  const stop = (reason: "timeout" | "cancel"): void => {
140
143
  if (stopped !== undefined) return
@@ -174,6 +177,7 @@ export async function askProjectChild(
174
177
  )
175
178
  } finally {
176
179
  clearTimeout(timer)
180
+ releaseSignals()
177
181
  context?.signal.removeEventListener("abort", onAbort)
178
182
  }
179
183
  }
@@ -13,7 +13,12 @@ import { isRecord } from "./internal/record.ts"
13
13
  import { detectMonorepo } from "./load.ts"
14
14
  import { projectResources } from "./mcp-context.ts"
15
15
  import { createCachedAppLoader, projectTools } from "./mcp-exec.ts"
16
- import { CHILD_INPUT_MAX_BYTES, protocolStdout, readBoundedStream } from "./mcp-io.ts"
16
+ import {
17
+ CHILD_INPUT_MAX_BYTES,
18
+ enterProjectChildProcess,
19
+ protocolStdout,
20
+ readBoundedStream,
21
+ } from "./mcp-io.ts"
17
22
  import type {
18
23
  McpPrompt,
19
24
  McpPromptMessage,
@@ -26,10 +31,12 @@ import {
26
31
  extractBackendResources,
27
32
  extractBackendTools,
28
33
  } from "./mcp-reflect.ts"
34
+ import { VERIFICATION_GATES, type VerificationGate } from "./verification-gates.ts"
29
35
 
30
36
  export type ProjectChildRequest =
31
37
  | { readonly op: "monorepo" }
32
38
  | { readonly op: "surface" }
39
+ | { readonly op: "proof-gates"; readonly level: VerificationGate["level"] }
33
40
  | { readonly op: "tool"; readonly name: string; readonly args: Record<string, unknown> }
34
41
  | { readonly op: "resource"; readonly uri: string }
35
42
  | { readonly op: "prompt"; readonly name: string; readonly args: Record<string, unknown> }
@@ -44,6 +51,7 @@ export interface AppSurface {
44
51
  export type ProjectChildAnswer =
45
52
  | { readonly ok: true; readonly apps: Readonly<Record<string, string>> | null }
46
53
  | { readonly ok: true; readonly surface: AppSurface }
54
+ | { readonly ok: true; readonly proofGates: readonly { level: number; ok: boolean }[] }
47
55
  | { readonly ok: true; readonly result: string | McpToolResult }
48
56
  | { readonly ok: true; readonly resource: { readonly text: string; readonly mimeType?: string } }
49
57
  | { readonly ok: true; readonly messages: readonly McpPromptMessage[] }
@@ -66,6 +74,11 @@ export async function answerProjectRequest(
66
74
  if (request.op === "monorepo") {
67
75
  return { ok: true, apps: (await detectMonorepo(cwd))?.apps ?? null }
68
76
  }
77
+ if (request.op === "proof-gates") {
78
+ const { collectVerificationLevels } = await import("./levels-tool.ts")
79
+ const { levels } = await collectVerificationLevels(cwd, { throughLevel: request.level })
80
+ return { ok: true, proofGates: levels.map(({ level, ok }) => ({ level, ok })) }
81
+ }
69
82
  const loadAppCached = createCachedAppLoader(cwd)
70
83
  const backend = (): Promise<unknown> =>
71
84
  loadAppCached.backend().then(
@@ -121,6 +134,10 @@ function parseRequest(text: string): { token: string; request: ProjectChildReque
121
134
  const { token, op, name, uri, args } = value
122
135
  if (typeof token !== "string" || !/^[0-9a-f-]{16,64}$/.test(token)) return undefined
123
136
  if (op === "monorepo" || op === "surface") return { token, request: { op } }
137
+ if (op === "proof-gates") {
138
+ const gate = VERIFICATION_GATES.find(({ level }) => level === value.level)
139
+ return gate === undefined ? undefined : { token, request: { op, level: gate.level } }
140
+ }
124
141
  if (op === "resource" && typeof uri === "string") return { token, request: { op, uri } }
125
142
  if ((op === "tool" || op === "prompt") && typeof name === "string" && isRecord(args)) {
126
143
  return { token, request: { op, name, args } }
@@ -161,6 +178,7 @@ export async function serveProjectChild(
161
178
  }
162
179
 
163
180
  if (import.meta.main) {
181
+ enterProjectChildProcess()
164
182
  const stdout = protocolStdout()
165
183
  const served = await serveProjectChild(
166
184
  process.argv[2] ?? process.cwd(),
@@ -43,9 +43,12 @@ interface ToolMeta {
43
43
  /** Every project tool by name. The docs tools set their own annotations and are not repeated. */
44
44
  export const PROJECT_TOOL_META: Readonly<Record<string, ToolMeta>> = {
45
45
  nifra_check: {
46
- annotations: READ,
46
+ annotations: EXECUTE,
47
47
  fields: {
48
48
  lintsOnly: "Skip tsc and run only the source lints, a near-instant pass.",
49
+ incremental:
50
+ "Reuse compiler state from .nifra/check/ on TypeScript versions that support it.",
51
+ timings: "Include total and per-phase wall time in milliseconds.",
49
52
  json: JSON_RESULT,
50
53
  sarif: "Return the diagnostics as a SARIF 2.1.0 log.",
51
54
  maxDiagnostics: "Return at most this many diagnostics.",
@@ -182,6 +185,7 @@ export const PROJECT_TOOL_META: Readonly<Record<string, ToolMeta>> = {
182
185
  fields: {
183
186
  files: "The changed files to plan proofs for, project-relative.",
184
187
  minLevel: "The verification level (0 to 4) the stop condition requires.",
188
+ run: "Execute the planned gates and return their results for the current source and build.",
185
189
  json: JSON_RESULT,
186
190
  dir: DIR,
187
191
  },
@@ -0,0 +1,41 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.16.
5
+ *
6
+ * No import or dependency moves. The route hooks, the query cache's reads and writes, `serverFn` and
7
+ * `formFor` are typed from the generated route table and the backend, which retires the old call shapes:
8
+ * the `route-hooks`, `query-keys` and `form-for` source rewrites move the sites whose new form the call
9
+ * decides, and `nifra upgrade` lists the rest by line. The runtime of every one is unchanged; what an
10
+ * app sees is `tsc` failing on the old shapes.
11
+ */
12
+ export const recipe: UpgradeRecipe = {
13
+ version: "5.16.0",
14
+ pins: [
15
+ { match: "@nifrajs/", to: "5.16.0" },
16
+ { match: "create-nifra", to: "5.16.0" },
17
+ { match: "nifra", to: "5.16.0" },
18
+ ],
19
+ importMoves: [],
20
+ sourceRewrites: ["route-hooks", "query-keys", "form-for"],
21
+ affects: [
22
+ "@nifrajs/cli",
23
+ "@nifrajs/web",
24
+ "@nifrajs/web-react",
25
+ "@nifrajs/web-preact",
26
+ "@nifrajs/web-solid",
27
+ "@nifrajs/web-svelte",
28
+ "@nifrajs/web-vue",
29
+ "create-nifra",
30
+ ],
31
+ notes: [
32
+ '`useSearch` and `useParams` take the route they read: `useSearch("/reports")` is that route\'s `searchSchema` output, `useParams("/users/:id")` its params, from `.nifra/types/routes.d.ts`. `useSearch<typeof searchSchema>()`, `useParams<{ id: string }>()` and the bare calls are removed, and `useParams` is new in `@nifrajs/web-preact`, `-solid`, `-svelte` and `-vue` (an accessor in Solid and Svelte, a ref in Vue). The argument is read only by the compiler; nothing changes at run time. The `route-hooks` rewrite writes the pattern of the page file the call is in; a call in a layout, a shared component or a `.svelte` or `.vue` file is listed by line, because only its author knows the route it renders in. A component shared by several pages takes the pattern as a prop typed as the union of their routes and passes it on. A pattern the table does not hold is a compile error, and `nifra check` warns (NF-C059) when a page names another page\'s route.',
33
+ 'A Vue page reads its search with `useSearch("/reports")`, not `defineProps<Route.ComponentProps>()`: `vue-tsc` accepts that type but `@vue/compiler-sfc` cannot resolve `./+types/<name>` or its conditional types, so the component does not compile. React, Preact, Solid and Svelte pages get `search` as a prop typed by `Route.ComponentProps`.',
34
+ '`QueryClient.getQueryData` and `setQueryData` take a typed key: `queryKey<User>(["user", id])` carries the data type, and a plain array no longer compiles. `query`, `prefetchQuery`, `useQuery` and `createQuery` still take a plain key; given a typed one, its fetcher must return that type. The `query-keys` rewrite wraps the key at each call in a file that imports from `@nifrajs/web` (a file with a TanStack import is skipped) and moves a call\'s type argument onto the key: `qc.getQueryData<User>(KEY)` becomes `qc.getQueryData(queryKey<User>(KEY))`. A key shared by several calls reads better typed once where it is defined: `const USER = queryKey<User>(["user"])`, then `qc.getQueryData(USER)`.',
35
+ "`serverFn` ties its result to its `output` schema: the caller's type is the schema's output, and the function must return what the schema accepts. A function that returns data without an `output` schema no longer compiles; it was already refused when the app started, so no app that ran is affected. Add the `output` schema, or return nothing.",
36
+ "`formFor<App>()(path, method?)` replaces `formFor<App, Path, Method>()`: the path is checked against the app's routes, the method against the ones that route declares, and the handle carries the route's own `action` and `method` for `<form action={f.action} method={f.method}>`. The `form-for` rewrite moves a literal path and method from the type arguments to the call; a path or method written as a type alias is listed by line.",
37
+ "A route with no params has `Route.Params` of `Record<never, never>`, so reading `props.params.anything` is a compile error (any key was accepted, typed `never`). `href({ to })` of a route with no params takes no `params`, and a search field the route's schema defaults may be left out of `href({ to, search })`. A `.svelte` or `.vue` route's `searchSchema` reaches the table under `svelte-check` and `vue-tsc`; plain `tsc` sees only the file's default export, and `.mdx` routes stay loosely typed.",
38
+ "`nifra check` adds NF-C059 (a page's hook names another route) and NF-C060 (a value cast to `Href`, which skips the route check `href()` and `rawHref()` make), and warns when a source imports `useSearch` or `useParams` and no program loads the route table. `create-nifra` scaffolds a `nifra.check.json` that makes dead internal links (NF-C057), NF-C059 and NF-C060 errors; add the same `rules` to an existing app to hold them.",
39
+ "After `nifra upgrade 5.16.0 --write`, run `nifra types` and then `tsc`: whatever the rewrites listed or left shows as a compile error at its line. The Linux or CI build needs `.nifra/types/routes.d.ts` generated before `tsc`, as it did for `href()`.",
40
+ ],
41
+ }
@@ -27,6 +27,7 @@ import { recipe as v5_12_0 } from "./5.12.0.ts"
27
27
  import { recipe as v5_13_0 } from "./5.13.0.ts"
28
28
  import { recipe as v5_14_0 } from "./5.14.0.ts"
29
29
  import { recipe as v5_15_0 } from "./5.15.0.ts"
30
+ import { recipe as v5_16_0 } from "./5.16.0.ts"
30
31
 
31
32
  /** A pin rule: every dependency whose name starts with `match` is set to version `to`. */
32
33
  export interface PinRule {
@@ -113,6 +114,7 @@ const RECIPES: Record<string, UpgradeRecipe> = {
113
114
  [v5_13_0.version]: v5_13_0,
114
115
  [v5_14_0.version]: v5_14_0,
115
116
  [v5_15_0.version]: v5_15_0,
117
+ [v5_16_0.version]: v5_16_0,
116
118
  }
117
119
 
118
120
  export function getRecipe(version: string): UpgradeRecipe | undefined {
package/src/review.ts CHANGED
@@ -165,6 +165,9 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
165
165
  "NF-C056": "route-boundary",
166
166
  "NF-C057": "typed-client",
167
167
  "NF-C058": "typed-client",
168
+ "NF-C059": "typed-client",
169
+ "NF-C060": "typed-client",
170
+ "NF-C061": "configuration",
168
171
  "NF-C046": "dependency",
169
172
  "NF-D001": "dependency",
170
173
  "NF-D002": "dependency",
@@ -57,6 +57,9 @@ export const RULE_CODES = Object.freeze({
57
57
  "NF-C056": "serverFunctions namespace differs from its module's filename",
58
58
  "NF-C057": "Internal link to a path no page serves",
59
59
  "NF-C058": "Internal link written as a path string",
60
+ "NF-C059": "Route hook names another route than its page's",
61
+ "NF-C060": "Value cast to Href",
62
+ "NF-C061": "SSE stream with no heartbeat under Bun's idle timeout",
60
63
  "NF-D001": "Doctor check",
61
64
  "NF-D002": "Mixed nifra versions",
62
65
  "NF-D003": "Stale file: dependencies in bun.lock",
@@ -304,6 +304,21 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
304
304
  fix: "Build the link with `href({ to, params, search, hash })`, which `nifra check` and `tsc` hold to the app's routes. A path built elsewhere, such as a CMS link, takes `rawHref(path)`; a link kept on purpose takes `// nifra-expect NF-C058: <reason>` above the attribute. Silence the code for the project with `rules` in `nifra.config`.",
305
305
  docs: "/docs/routing",
306
306
  },
307
+ "NF-C059": {
308
+ why: "`useSearch(from)` and `useParams(from)` type the page from the route they name. A page that names another route is typed with that route's search or params, and `tsc` cannot tell: both patterns exist. The values read at run time are the page's own.",
309
+ fix: 'Name the page\'s own route: `useSearch("/reports")` in `routes/reports.tsx`. A component shared by several pages names the route of the page it renders in. A pattern kept on purpose takes `// nifra-expect NF-C059: <reason>` above the call.',
310
+ docs: "/docs/routing",
311
+ },
312
+ "NF-C060": {
313
+ why: "An `Href` is what `href()` and `rawHref()` return, the two places a link is checked: `href()` against the app's routes at compile time, `rawHref()` against same-origin rules at run time. A cast to `Href` skips both, so a dead or hostile path compiles.",
314
+ fix: "Build the link with `href({ to, params, search })`. A path built elsewhere, such as a CMS link, goes through `rawHref(path)`. A cast kept on purpose takes `// nifra-expect NF-C060: <reason>` above it.",
315
+ docs: "/docs/routing",
316
+ },
317
+ "NF-C061": {
318
+ why: "Bun closes a connection that moves no bytes for the listener's `idleTimeoutSec` seconds (10 by default). An SSE stream that sends no ping inside that time is cut whenever its events are further apart, and a test through `app.fetch` never shows it because that path has no listener.",
319
+ fix: "Pass `{ keepAlive: 5_000 }` to the stream so a ping goes out well inside the timeout, or raise the timeout: `withIdleTimeout(c, seconds, work)` from `@nifrajs/core/idle-timeout` under `listen()`, or the `idleTimeout` option of `Bun.serve()`. A stream kept on purpose takes `// nifra-expect NF-C061: <reason>` above the registration.",
320
+ docs: "/docs/api",
321
+ },
307
322
  "NF-D001": {
308
323
  why: "The doctor gate of `nifra assure` found an undeclared import or a package installed more than once.",
309
324
  fix: "Run `nifra doctor` for the details and the fix of each finding.",
@@ -0,0 +1,112 @@
1
+ import { join } from "node:path"
2
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
3
+ import type { CheckRule, RuleContext } from "./index.ts"
4
+ import { scanSources } from "./source-scan.ts"
5
+
6
+ /**
7
+ * NF-C059 - a route hook that does not name the page it renders in. `useSearch("/reports")` and
8
+ * `useParams("/users/:id")` take their types from the route they name, so naming another route types a
9
+ * page with the wrong search or params and `tsc` cannot tell: both patterns exist. In a page file
10
+ * the pattern must be one of the page's own; a call without a literal pattern is left alone (a
11
+ * component shared by several pages names its own route).
12
+ */
13
+
14
+ const TEST_DIR = /(?:^|\/)(?:tests?|__tests__)\//
15
+
16
+ /** The URL patterns each page file of the app serves, by path relative to the app root. */
17
+ async function pagePatterns(ctx: RuleContext): Promise<ReadonlyMap<string, readonly string[]>> {
18
+ const routesDir = join(ctx.root, "routes")
19
+ const found = new Map<string, string[]>()
20
+ try {
21
+ const { discoverRoutes } = await import("@nifrajs/web/fs")
22
+ for (const route of discoverRoutes(routesDir).routes) {
23
+ const key = `routes/${route.file}`
24
+ found.set(key, [...(found.get(key) ?? []), route.pattern])
25
+ }
26
+ } catch {
27
+ return new Map()
28
+ }
29
+ return found
30
+ }
31
+
32
+ function wrongRoute(file: string, line: number, message: string, evidence: string): Diagnostic {
33
+ return diagnostic({
34
+ code: "NF-C059",
35
+ severity: "warn",
36
+ file,
37
+ line,
38
+ message,
39
+ evidence: [evidence],
40
+ verify: "nifra check",
41
+ })
42
+ }
43
+
44
+ export const routeHookRule: CheckRule = {
45
+ code: "NF-C059",
46
+ title: "Route hook names another route than its page's",
47
+ async scan(ctx) {
48
+ const pages = await pagePatterns(ctx)
49
+ if (pages.size === 0) return []
50
+ return scanSources(ctx, {
51
+ expectation: ["NF-C059", "route-hook"],
52
+ components: true,
53
+ mayMatch: (text) => text.includes("useSearch") || text.includes("useParams"),
54
+ find: (facts, tree) => {
55
+ const own = pages.get(tree.fileName)
56
+ if (own === undefined) return []
57
+ return facts.routeHookCalls(tree).flatMap((call) => {
58
+ if (call.pattern === undefined || own.includes(call.pattern)) return []
59
+ return [
60
+ {
61
+ position: call.position,
62
+ report: (line: number, note?: string) =>
63
+ wrongRoute(
64
+ tree.fileName,
65
+ line,
66
+ `${call.hook}("${call.pattern}") in a page that serves ${own.map((pattern) => `"${pattern}"`).join(" and ")}.${note === undefined ? "" : ` ${note}`}`,
67
+ `Name the page's own route: ${call.hook}("${own[own.length - 1]}"). A component shared by several pages keeps the pattern of the page it renders in, and a pattern kept on purpose takes \`// nifra-expect NF-C059: <reason>\` above the call.`,
68
+ ),
69
+ },
70
+ ]
71
+ })
72
+ },
73
+ })
74
+ },
75
+ }
76
+
77
+ /**
78
+ * NF-C060 - a value cast to `Href`. An `Href` is what `href()` and `rawHref()` return, the two places a
79
+ * link is checked against the app's routes; an assertion to `Href` skips both, so a dead or hostile path compiles. A
80
+ * path built elsewhere goes through `rawHref(path)`, which checks it at run time.
81
+ */
82
+ export const hrefCastRule: CheckRule = {
83
+ code: "NF-C060",
84
+ title: "Value cast to Href",
85
+ async scan(ctx) {
86
+ return scanSources(ctx, {
87
+ expectation: ["NF-C060", "href-cast"],
88
+ components: true,
89
+ mayMatch: (text) => text.includes("Href"),
90
+ find: (facts, tree) =>
91
+ TEST_DIR.test(tree.fileName)
92
+ ? []
93
+ : facts.hrefCasts(tree).map((cast) => ({
94
+ position: cast.position,
95
+ report: (line: number, note?: string) =>
96
+ diagnostic({
97
+ code: "NF-C060",
98
+ severity: "warn",
99
+ file: tree.fileName,
100
+ line,
101
+ message: `A value is cast to Href, so the link is not checked against the app's routes.${note === undefined ? "" : ` ${note}`}`,
102
+ evidence: [
103
+ "Build the link with `href({ to, params, search })`, or pass a path built elsewhere through `rawHref(path)`, which checks it at run time. A cast kept on purpose takes `// nifra-expect NF-C060: <reason>` above it.",
104
+ ],
105
+ verify: "nifra check",
106
+ }),
107
+ })),
108
+ })
109
+ },
110
+ }
111
+
112
+ export const routeHookRules = Object.freeze([routeHookRule, hrefCastRule])
@@ -0,0 +1,95 @@
1
+ import type * as TSApi from "typescript"
2
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
3
+ import { createSourceFacts } from "../internal/source-facts.ts"
4
+ import type { TypeScriptApi } from "../internal/typescript-import.ts"
5
+ import { commentBlockExpectation } from "./comment-markers.ts"
6
+ import type { CheckRule } from "./index.ts"
7
+ import { loadRuleTypeScript } from "./typescript.ts"
8
+
9
+ const SILENT_SSE_EXPECTATION = ["NF-C061", "silent-sse"]
10
+ /** Bun's `idleTimeoutSec` default: a connection that moves no bytes for this long is closed. */
11
+ const BUN_IDLE_SECONDS = 10
12
+ const BUN_LISTENER = /\.listen\s*\(|\bBun\.serve\s*\(/
13
+ /** What sets a listener's idle timeout: `withIdleTimeout`, `listen()`'s `idleTimeoutSec`, `Bun.serve()`'s `idleTimeout`. */
14
+ const IDLE_TUNING_NAMES: ReadonlySet<string> = new Set([
15
+ "withIdleTimeout",
16
+ "idleTimeoutSec",
17
+ "idleTimeout",
18
+ ])
19
+ const IDLE_TUNING_HINT = /\bwithIdleTimeout\b|\bidleTimeoutSec\b|\bidleTimeout\b/
20
+
21
+ /** Whether code in `tree` names one of {@link IDLE_TUNING_NAMES}: a comment or a string that says so tunes nothing. */
22
+ function tunesIdleTimeout(ts: TypeScriptApi, tree: TSApi.SourceFile): boolean {
23
+ const visit = (node: TSApi.Node): boolean => {
24
+ if (ts.isIdentifier(node) && IDLE_TUNING_NAMES.has(node.text)) return true
25
+ // `{ "idleTimeout": 60 }` and `{ ["idleTimeout"]: 60 }` set it too; a string anywhere else tunes nothing.
26
+ if (ts.isPropertyAssignment(node)) {
27
+ const key = ts.isComputedPropertyName(node.name) ? node.name.expression : node.name
28
+ if (ts.isStringLiteralLike(key) && IDLE_TUNING_NAMES.has(key.text)) return true
29
+ }
30
+ return ts.forEachChild(node, visit) === true
31
+ }
32
+ return visit(tree)
33
+ }
34
+
35
+ /**
36
+ * NF-C061: in a project served by a Bun `listen()` or `Bun.serve()`, an SSE stream that sends no ping
37
+ * inside the listener's idle timeout. Bun closes a connection that moves no bytes for 10 seconds, so
38
+ * a stream that stays silent that long is cut, and `app.fetch` in a test never shows it. A project
39
+ * that tunes the timeout in code anywhere (`withIdleTimeout`, `idleTimeoutSec`, `idleTimeout`) is left alone.
40
+ */
41
+ export const silentSseRule: CheckRule = {
42
+ code: "NF-C061",
43
+ title: "SSE stream with no heartbeat under Bun's idle timeout",
44
+ async scan(ctx) {
45
+ const loaded = await loadRuleTypeScript(ctx)
46
+ if (loaded.diagnostics !== undefined) return loaded.diagnostics
47
+ const ts = loaded.compiler
48
+ if (ts === undefined) return []
49
+ const facts = createSourceFacts(ts)
50
+ const candidates: { file: string; text: string; tree: TSApi.SourceFile }[] = []
51
+ let bunListener = false
52
+ for (const file of ctx.project.source.files) {
53
+ if (!/\.[cm]?[jt]sx?$/.test(file)) continue
54
+ const text = ctx.project.source.read(file)
55
+ if (text === undefined) continue
56
+ const tuned = IDLE_TUNING_HINT.test(text)
57
+ const serves = BUN_LISTENER.test(text)
58
+ const streams = /\bsse\b/.test(text)
59
+ if (!tuned && !serves && !streams) continue
60
+ const tree = facts.parse(file, text)
61
+ if (tree === undefined) continue
62
+ if (tuned && tunesIdleTimeout(ts, tree)) return []
63
+ bunListener ||= serves
64
+ if (streams) candidates.push({ file, text, tree })
65
+ }
66
+ if (!bunListener) return []
67
+ const findings: Diagnostic[] = []
68
+ for (const { file, text, tree } of candidates) {
69
+ const lines = text.split("\n")
70
+ for (const stream of facts.silentSseStreams(tree, BUN_IDLE_SECONDS)) {
71
+ const line = tree.getLineAndCharacterOfPosition(stream.position).line + 1
72
+ if (commentBlockExpectation(lines, line, SILENT_SSE_EXPECTATION) !== undefined) continue
73
+ findings.push(
74
+ diagnostic({
75
+ code: "NF-C061",
76
+ severity: "info",
77
+ file,
78
+ line,
79
+ message:
80
+ stream.keepAlive === undefined
81
+ ? `This SSE stream sends no keep-alive ping, so on a Bun server it is closed after ${BUN_IDLE_SECONDS} seconds without an event. Pass \`{ keepAlive: 5_000 }\`, or raise the timeout: \`withIdleTimeout\` from \`@nifrajs/core/idle-timeout\` under \`listen()\`, or the \`idleTimeout\` option of \`Bun.serve()\`.`
82
+ : `This SSE stream pings every ${stream.keepAlive} ms, which is not inside Bun's default ${BUN_IDLE_SECONDS}-second idle timeout, so a quiet stream is closed. Ping more often than every ${BUN_IDLE_SECONDS * 1000} ms, or raise the timeout with \`withIdleTimeout\` under \`listen()\` or the \`idleTimeout\` option of \`Bun.serve()\`.`,
83
+ evidence: [
84
+ "the project serves with a Bun listener and sets no idleTimeoutSec, idleTimeout or withIdleTimeout",
85
+ `Bun closes a connection that moves no bytes for ${BUN_IDLE_SECONDS} seconds by default`,
86
+ "a stream kept on purpose: `// nifra-expect NF-C061: <reason>` above the registration",
87
+ ],
88
+ verify: "nifra check",
89
+ }),
90
+ )
91
+ }
92
+ }
93
+ return findings
94
+ },
95
+ }
@@ -1,4 +1,5 @@
1
1
  import type * as TSApi from "typescript"
2
+ import { COMPONENT_FILE } from "../check-scan.ts"
2
3
  import type { Diagnostic } from "../diagnostics.ts"
3
4
  import { createSourceFacts, type SourceFacts } from "../internal/source-facts.ts"
4
5
  import { commentBlockExpectation, MISSING_EXPECTATION_REASON } from "./comment-markers.ts"
@@ -20,14 +21,16 @@ export interface SourceScan {
20
21
  readonly expectation: readonly string[]
21
22
  /** Whether a comment without a reason after its colon fails to accept a finding. */
22
23
  readonly requireReason?: boolean
24
+ /** Whether `.svelte` and `.vue` files are read too: the index holds each as its `<script>` blocks, in place. */
25
+ readonly components?: boolean
23
26
  /** A cheap test of a file's text; the file is parsed only when it passes. */
24
27
  readonly mayMatch: (text: string) => boolean
25
28
  readonly find: (facts: SourceFacts, tree: TSApi.SourceFile) => readonly SourceFinding[]
26
29
  }
27
30
 
28
31
  /**
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
32
+ * The shared walk of a lint over TypeScript sources: every `.ts`/`.tsx` file (and, with `components`,
33
+ * the script of each `.svelte`/`.vue` file) whose text passes `mayMatch` is parsed, `find` names its findings, and one a `// nifra-expect <code>` block above its line
31
34
  * accepts is dropped.
32
35
  */
33
36
  export async function scanSources(
@@ -40,7 +43,9 @@ export async function scanSources(
40
43
  const facts = createSourceFacts(loaded.compiler)
41
44
  const findings: Diagnostic[] = []
42
45
  for (const file of ctx.project.source.files) {
43
- if (!/\.[cm]?tsx?$/.test(file)) continue
46
+ const component = scan.components === true && COMPONENT_FILE.test(file)
47
+ if (!component && !/\.[cm]?tsx?$/.test(file)) continue
48
+ // The index holds a component as its `<script>` blocks already, every other character blanked.
44
49
  const text = ctx.project.source.read(file)
45
50
  if (text === undefined || !scan.mayMatch(text)) continue
46
51
  const tree = facts.parse(file, text)
@@ -6,44 +6,15 @@
6
6
  import { isSameOriginPath } from "@nifrajs/core/pattern"
7
7
  import type * as TS from "typescript"
8
8
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
9
- import { scriptKindOf } from "./internal/script-kind.ts"
10
-
11
- /** A site a rewrite found and left alone, with what to write instead. */
12
- export interface ManualSite {
13
- readonly line: number
14
- readonly reason: string
15
- }
16
-
17
- export interface RewriteResult {
18
- readonly text: string
19
- /** Sites rewritten. */
20
- readonly count: number
21
- readonly manual: readonly ManualSite[]
22
- }
23
-
24
- export interface SourceRewrite {
25
- readonly id: string
26
- /** What it rewrites, for the plan. */
27
- readonly description: string
28
- /** Whether `text` may hold a site: a file it refuses is never parsed. */
29
- readonly mentions: (text: string) => boolean
30
- readonly rewrite: (ts: typeof TS, file: string, text: string) => RewriteResult
31
- }
32
-
33
- interface Edit {
34
- readonly start: number
35
- readonly end: number
36
- readonly text: string
37
- }
38
-
39
- /** Apply `edits` (disjoint ranges) to `text`, from the end so earlier offsets stay valid. */
40
- function applyEdits(text: string, edits: readonly Edit[]): string {
41
- let out = text
42
- for (const edit of edits.toSorted((a, b) => b.start - a.start)) {
43
- out = `${out.slice(0, edit.start)}${edit.text}${out.slice(edit.end)}`
44
- }
45
- return out
46
- }
9
+ import {
10
+ applyEdits,
11
+ type Edit,
12
+ type ManualSite,
13
+ parseSource,
14
+ type RewriteResult,
15
+ type SourceRewrite,
16
+ } from "./internal/rewrite-kit.ts"
17
+ import { TYPED_API_REWRITES } from "./typed-api-rewrites.ts"
47
18
 
48
19
  const WEB = "@nifrajs/web"
49
20
  const NODE = "@nifrajs/node"
@@ -68,20 +39,6 @@ function propertyName(ts: typeof TS, name: TS.PropertyName): string | undefined
68
39
  return ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : undefined
69
40
  }
70
41
 
71
- /**
72
- * 5.9: `servePublicDir` (removed from `@nifrajs/web`) becomes the runtime's `serveStatic` with the
73
- * options that keep its answers; `@nifrajs/node`'s `static` mount objects are wrapped in
74
- * `serveStatic()`; and `signals` on `@nifrajs/node`'s and `@nifrajs/deno`'s `serve()` becomes
75
- * `gracefulSignals`.
76
- */
77
- /** Parse `text` as `file`, with the line lookup a rewrite lists its manual sites by. */
78
- function parseSource(ts: typeof TS, file: string, text: string) {
79
- const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, scriptKindOf(ts, file))
80
- const lineOf = (node: TS.Node): number =>
81
- tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1
82
- return { tree, lineOf }
83
- }
84
-
85
42
  /** Named-import order: by the imported name, a `type` modifier aside. */
86
43
  const specifierOrder = (a: string, b: string): number =>
87
44
  codeUnitOrder(a.replace(/^type /, ""), b.replace(/^type /, ""))
@@ -107,6 +64,12 @@ function quoteOf(ts: typeof TS, tree: TS.SourceFile, fallback: "'" | '"'): "'" |
107
64
  return single === double ? fallback : single > double ? "'" : '"'
108
65
  }
109
66
 
67
+ /**
68
+ * 5.9: `servePublicDir` (removed from `@nifrajs/web`) becomes the runtime's `serveStatic` with the
69
+ * options that keep its answers; `@nifrajs/node`'s `static` mount objects are wrapped in
70
+ * `serveStatic()`; and `signals` on `@nifrajs/node`'s and `@nifrajs/deno`'s `serve()` becomes
71
+ * `gracefulSignals`.
72
+ */
110
73
  function rewriteServeStatic(ts: typeof TS, file: string, text: string): RewriteResult {
111
74
  const { tree, lineOf } = parseSource(ts, file, text)
112
75
  const importQuote = /from\s*'/.test(text) ? "'" : '"'
@@ -827,8 +790,11 @@ const REWRITES: Readonly<Record<string, SourceRewrite>> = {
827
790
  [SERVE_STATIC.id]: SERVE_STATIC,
828
791
  [PPR_OPTION.id]: PPR_OPTION,
829
792
  [HREF_NAVIGATION.id]: HREF_NAVIGATION,
793
+ ...Object.fromEntries(TYPED_API_REWRITES.map((rewrite) => [rewrite.id, rewrite])),
830
794
  }
831
795
 
796
+ export type { ManualSite, RewriteResult, SourceRewrite }
797
+
832
798
  export function getSourceRewrite(id: string): SourceRewrite | undefined {
833
799
  return REWRITES[id]
834
800
  }
@@ -0,0 +1,33 @@
1
+ import { copyFileSync, mkdirSync, readFileSync, renameSync, rmSync } from "node:fs"
2
+ import { join, resolve } from "node:path"
3
+
4
+ /** Each invocation writes a private sibling so parallel compilers never read a partial cache. */
5
+ export function stageTypecheckCache(cwd: string, tscBin: string, tsconfig: string) {
6
+ const metadata: unknown = JSON.parse(readFileSync(resolve(tscBin, "../../package.json"), "utf8"))
7
+ const version: unknown = Reflect.get(Object(metadata), "version")
8
+ if (typeof version !== "string" || !/^[56]\./.test(version)) return undefined
9
+
10
+ const directory = join(cwd, ".nifra", "check")
11
+ const key = Bun.CryptoHasher.hash("sha256", JSON.stringify([tscBin, version, tsconfig]), "hex")
12
+ const filename = join(directory, `${key}.tsbuildinfo`)
13
+ const staged = join(directory, `${key}-${crypto.randomUUID()}.tsbuildinfo`)
14
+ mkdirSync(directory, { recursive: true })
15
+ try {
16
+ copyFileSync(filename, staged)
17
+ } catch (error) {
18
+ if (Reflect.get(Object(error), "code") !== "ENOENT") throw error
19
+ }
20
+ return {
21
+ path: staged,
22
+ finish(publish: boolean): void {
23
+ try {
24
+ if (publish) renameSync(staged, filename)
25
+ } catch (error) {
26
+ // Some compiler exits never produce build info; they still have valid diagnostics.
27
+ if (Reflect.get(Object(error), "code") !== "ENOENT") throw error
28
+ } finally {
29
+ rmSync(staged, { force: true })
30
+ }
31
+ },
32
+ }
33
+ }
@@ -143,7 +143,7 @@ const excludedBy = (patterns: readonly string[], file: string): boolean =>
143
143
 
144
144
  // A named import of a navigation API from `@nifrajs/web` or an adapter: what the route table types.
145
145
  const NAVIGATION_IMPORT =
146
- /\bimport\s+(?:type\s+)?\{[^}]*\b(?:useNavigate|Link|NavLink|Navigate|redirect|href|rawHref)\b[^}]*\}\s*from\s*["']@nifrajs\/web(?:-[a-z]+)?(?:\/(?:router|client))?["']/
146
+ /\bimport\s+(?:type\s+)?\{[^}]*\b(?:useNavigate|Link|NavLink|Navigate|redirect|href|rawHref|useSearch|useParams)\b[^}]*\}\s*from\s*["']@nifrajs\/web(?:-[a-z]+)?(?:\/(?:router|client))?["']/
147
147
 
148
148
  /**
149
149
  * `.nifra/types/routes.d.ts` (project-relative) when a source file uses a navigation API, the table