@nifrajs/cli 5.15.1 → 5.17.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 (171) hide show
  1. package/CHANGELOG.md +64 -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/5.17.0.d.ts +10 -0
  75. package/dist/recipes/5.17.0.d.ts.map +1 -0
  76. package/dist/recipes/5.17.0.js +20 -0
  77. package/dist/recipes/5.17.0.js.map +1 -0
  78. package/dist/recipes/index.d.ts.map +1 -1
  79. package/dist/recipes/index.js +4 -0
  80. package/dist/recipes/index.js.map +1 -1
  81. package/dist/review.d.ts.map +1 -1
  82. package/dist/review.js +3 -0
  83. package/dist/review.js.map +1 -1
  84. package/dist/rules/codes.d.ts +3 -0
  85. package/dist/rules/codes.d.ts.map +1 -1
  86. package/dist/rules/codes.js +3 -0
  87. package/dist/rules/codes.js.map +1 -1
  88. package/dist/rules/explanations.d.ts.map +1 -1
  89. package/dist/rules/explanations.js +15 -0
  90. package/dist/rules/explanations.js.map +1 -1
  91. package/dist/rules/route-hooks.d.ts +10 -0
  92. package/dist/rules/route-hooks.d.ts.map +1 -0
  93. package/dist/rules/route-hooks.js +88 -0
  94. package/dist/rules/route-hooks.js.map +1 -0
  95. package/dist/rules/silent-sse.d.ts +9 -0
  96. package/dist/rules/silent-sse.d.ts.map +1 -0
  97. package/dist/rules/silent-sse.js +89 -0
  98. package/dist/rules/silent-sse.js.map +1 -0
  99. package/dist/rules/source-scan.d.ts +4 -2
  100. package/dist/rules/source-scan.d.ts.map +1 -1
  101. package/dist/rules/source-scan.js +3 -1
  102. package/dist/rules/source-scan.js.map +1 -1
  103. package/dist/source-rewrites.d.ts +2 -20
  104. package/dist/source-rewrites.d.ts.map +1 -1
  105. package/dist/source-rewrites.js +3 -13
  106. package/dist/source-rewrites.js.map +1 -1
  107. package/dist/typecheck-cache.d.ts +6 -0
  108. package/dist/typecheck-cache.d.ts.map +1 -0
  109. package/dist/typecheck-cache.js +37 -0
  110. package/dist/typecheck-cache.js.map +1 -0
  111. package/dist/typecheck-coverage.js +1 -1
  112. package/dist/typecheck-coverage.js.map +1 -1
  113. package/dist/typed-api-rewrites.d.ts +3 -0
  114. package/dist/typed-api-rewrites.d.ts.map +1 -0
  115. package/dist/typed-api-rewrites.js +253 -0
  116. package/dist/typed-api-rewrites.js.map +1 -0
  117. package/dist/upgrade.d.ts.map +1 -1
  118. package/dist/upgrade.js +3 -1
  119. package/dist/upgrade.js.map +1 -1
  120. package/dist/verification-gates.d.ts +23 -0
  121. package/dist/verification-gates.d.ts.map +1 -0
  122. package/dist/verification-gates.js +8 -0
  123. package/dist/verification-gates.js.map +1 -0
  124. package/dist/verification.d.ts +2 -0
  125. package/dist/verification.d.ts.map +1 -1
  126. package/dist/verification.js +6 -0
  127. package/dist/verification.js.map +1 -1
  128. package/dist/work-graph.d.ts +17 -8
  129. package/dist/work-graph.d.ts.map +1 -1
  130. package/dist/work-graph.js +157 -104
  131. package/dist/work-graph.js.map +1 -1
  132. package/docs/examples.json +2 -2
  133. package/docs/llms-full.txt +585 -51
  134. package/docs/types.json +293 -94
  135. package/package.json +12 -12
  136. package/src/build-provenance.ts +107 -0
  137. package/src/check-diagnostics.ts +5 -0
  138. package/src/check-scan.ts +7 -4
  139. package/src/check-timings.ts +27 -0
  140. package/src/check.ts +77 -32
  141. package/src/cli.ts +33 -12
  142. package/src/command-catalog.ts +28 -4
  143. package/src/dev-feed-tool.ts +8 -3
  144. package/src/doctor.ts +37 -18
  145. package/src/internal/named-imports.ts +26 -0
  146. package/src/internal/rewrite-kit.ts +49 -0
  147. package/src/internal/source-facts.ts +158 -0
  148. package/src/levels-tool.ts +27 -18
  149. package/src/mcp-exec.ts +1 -1
  150. package/src/mcp-http.ts +1 -1
  151. package/src/mcp-io.ts +13 -1
  152. package/src/mcp-isolate.ts +4 -0
  153. package/src/mcp-project-child.ts +19 -1
  154. package/src/mcp-tool-meta.ts +5 -1
  155. package/src/recipes/5.16.0.ts +41 -0
  156. package/src/recipes/5.17.0.ts +28 -0
  157. package/src/recipes/index.ts +4 -0
  158. package/src/review.ts +3 -0
  159. package/src/rules/codes.ts +3 -0
  160. package/src/rules/explanations.ts +15 -0
  161. package/src/rules/route-hooks.ts +112 -0
  162. package/src/rules/silent-sse.ts +95 -0
  163. package/src/rules/source-scan.ts +8 -3
  164. package/src/source-rewrites.ts +18 -52
  165. package/src/typecheck-cache.ts +33 -0
  166. package/src/typecheck-coverage.ts +1 -1
  167. package/src/typed-api-rewrites.ts +308 -0
  168. package/src/upgrade.ts +2 -1
  169. package/src/verification-gates.ts +9 -0
  170. package/src/verification.ts +8 -0
  171. package/src/work-graph.ts +200 -121
@@ -280,6 +280,8 @@ function parseBooleanFlags(
280
280
 
281
281
  interface CheckInput {
282
282
  readonly lintsOnly?: boolean | undefined
283
+ readonly incremental?: boolean | undefined
284
+ readonly timings?: boolean | undefined
283
285
  readonly json?: boolean | undefined
284
286
  readonly sarif?: boolean | undefined
285
287
  readonly maxDiagnostics?: number | undefined
@@ -474,6 +476,7 @@ interface SyncInput {
474
476
  interface ProveInput {
475
477
  readonly files?: readonly string[] | undefined
476
478
  readonly minLevel?: number | undefined
479
+ readonly run?: boolean | undefined
477
480
  readonly json?: boolean | undefined
478
481
  readonly dir?: string | undefined
479
482
  }
@@ -574,6 +577,8 @@ interface SmokeCommandOutput extends SmokeReport {}
574
577
  const CHECK_SCHEMA = input<CheckInput>(
575
578
  objectSchema({
576
579
  lintsOnly: { type: "boolean" },
580
+ incremental: { type: "boolean" },
581
+ timings: { type: "boolean" },
577
582
  json: { type: "boolean" },
578
583
  sarif: { type: "boolean" },
579
584
  maxDiagnostics: { type: "integer", minimum: 1 },
@@ -585,7 +590,7 @@ const CHECK_SCHEMA = input<CheckInput>(
585
590
  if (maxDiagnostics !== undefined && (!Number.isInteger(maxDiagnostics) || maxDiagnostics < 1))
586
591
  throw new TypeError("maxDiagnostics must be a positive integer")
587
592
  return {
588
- ...parseBooleanFlags(raw, ["lintsOnly", "json", "sarif"]),
593
+ ...parseBooleanFlags(raw, ["lintsOnly", "incremental", "timings", "json", "sarif"]),
589
594
  ...(maxDiagnostics === undefined ? {} : { maxDiagnostics }),
590
595
  ...(raw.dir === undefined ? {} : { dir: raw.dir }),
591
596
  } as CheckInput
@@ -1008,6 +1013,7 @@ const PROVE_SCHEMA = input<ProveInput>(
1008
1013
  objectSchema({
1009
1014
  files: { type: "array", items: { type: "string" } },
1010
1015
  minLevel: { type: "integer", minimum: 0, maximum: 4 },
1016
+ run: { type: "boolean" },
1011
1017
  json: { type: "boolean" },
1012
1018
  dir: { type: "string" },
1013
1019
  }),
@@ -1025,7 +1031,7 @@ const PROVE_SCHEMA = input<ProveInput>(
1025
1031
  return {
1026
1032
  ...(files === undefined ? {} : { files }),
1027
1033
  ...(minLevel === undefined ? {} : { minLevel }),
1028
- ...parseBooleanFlags(raw, ["json"]),
1034
+ ...parseBooleanFlags(raw, ["json", "run"]),
1029
1035
  ...(raw.dir === undefined ? {} : { dir: raw.dir }),
1030
1036
  }
1031
1037
  },
@@ -1122,7 +1128,18 @@ const checkSpec: CommandSpec<CheckInput, CheckCommandOutput> = {
1122
1128
  input: CHECK_SCHEMA,
1123
1129
  output: output<CheckCommandOutput>({
1124
1130
  type: "object",
1125
- properties: { ok: { type: "boolean" }, diagnostics: { type: "array" } },
1131
+ properties: {
1132
+ ok: { type: "boolean" },
1133
+ diagnostics: { type: "array" },
1134
+ timings: {
1135
+ type: "object",
1136
+ properties: {
1137
+ totalMs: { type: "number" },
1138
+ phasesMs: { type: "object", additionalProperties: { type: "number" } },
1139
+ },
1140
+ required: ["totalMs", "phasesMs"],
1141
+ },
1142
+ },
1126
1143
  required: ["ok", "diagnostics"],
1127
1144
  }),
1128
1145
  transports: ["cli", "mcp"],
@@ -1130,6 +1147,8 @@ const checkSpec: CommandSpec<CheckInput, CheckCommandOutput> = {
1130
1147
  argv: {
1131
1148
  flags: [
1132
1149
  { name: "lints-only", field: "lintsOnly", type: "boolean" },
1150
+ { name: "incremental", field: "incremental", type: "boolean" },
1151
+ { name: "timings", field: "timings", type: "boolean" },
1133
1152
  { name: "json", field: "json", type: "boolean" },
1134
1153
  { name: "sarif", field: "sarif", type: "boolean" },
1135
1154
  ],
@@ -1139,6 +1158,8 @@ const checkSpec: CommandSpec<CheckInput, CheckCommandOutput> = {
1139
1158
  return (
1140
1159
  await collectProjectVerification(ctx.cwd, {
1141
1160
  lintsOnly: value.lintsOnly === true,
1161
+ incremental: value.incremental === true,
1162
+ timings: value.timings === true,
1142
1163
  ...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
1143
1164
  ...(value.maxDiagnostics === undefined ? {} : { maxDiagnostics: value.maxDiagnostics }),
1144
1165
  })
@@ -2166,7 +2187,7 @@ const syncManifestSpec: CommandSpec<SyncInput, SyncManifestCommandOutput> = {
2166
2187
  const proveSpec: CommandSpec<ProveInput, ProjectWorkGraphResult> = {
2167
2188
  name: "prove",
2168
2189
  summary:
2169
- "Build the static verification work graph, plan the cheapest proofs for the changed files, and report a machine-checkable stop condition.",
2190
+ "Plan cumulative verification gates and optionally run them against the current source and build.",
2170
2191
  input: PROVE_SCHEMA,
2171
2192
  output: output({ type: "object" }),
2172
2193
  transports: ["cli", "mcp"],
@@ -2175,6 +2196,7 @@ const proveSpec: CommandSpec<ProveInput, ProjectWorkGraphResult> = {
2175
2196
  flags: [
2176
2197
  { name: "file", field: "files", type: "string[]" },
2177
2198
  { name: "min", field: "minLevel", type: "number" },
2199
+ { name: "run", field: "run", type: "boolean" },
2178
2200
  { name: "json", field: "json", type: "boolean" },
2179
2201
  ],
2180
2202
  },
@@ -2182,6 +2204,8 @@ const proveSpec: CommandSpec<ProveInput, ProjectWorkGraphResult> = {
2182
2204
  return collectProjectWorkGraph(ctx.cwd, {
2183
2205
  ...(value.files === undefined ? {} : { changedFiles: value.files }),
2184
2206
  ...(value.minLevel === undefined ? {} : { minLevel: value.minLevel }),
2207
+ ...(value.run === true ? { execute: true } : {}),
2208
+ ...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
2185
2209
  })
2186
2210
  },
2187
2211
  render: (out) => [renderWorkGraphText(out)],
@@ -646,7 +646,7 @@ export function renderErrors(out: ErrorsOutput): string[] {
646
646
  entry.resolvedAt === undefined ? undefined : "resolved",
647
647
  ].filter((tag) => tag !== undefined)
648
648
  lines.push(
649
- ` ✖ [${entry.category}] ${headline(diagnostic)}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`,
649
+ ` ${diagnostic.severity === "warning" ? "⚠" : "✖"} [${entry.category}] ${headline(diagnostic)}${tags.length > 0 ? ` (${tags.join(", ")})` : ""}`,
650
650
  )
651
651
  const at = topFrame(diagnostic)
652
652
  if (at !== undefined) lines.push(` at ${at}`)
@@ -677,10 +677,15 @@ export function renderLogs(out: LogsOutput): string[] {
677
677
  return lines
678
678
  }
679
679
 
680
- /** 0: nothing open; 1: errors the current code produced; 2: no live server to ask. */
680
+ /** 0: nothing open; 1: errors the current code produced (a warning does not count); 2: no live server to ask. */
681
681
  function errorsExitCode(out: ErrorsOutput): number {
682
682
  if (out.from !== "live") return 2
683
- return out.errors.some((entry) => !entry.stale && entry.resolvedAt === undefined) ? 1 : 0
683
+ return out.errors.some(
684
+ (entry) =>
685
+ !entry.stale && entry.resolvedAt === undefined && entry.diagnostic.severity !== "warning",
686
+ )
687
+ ? 1
688
+ : 0
684
689
  }
685
690
 
686
691
  function isFeedOutput<T extends FeedOutput>(value: unknown, list: "errors" | "logs"): value is T {
package/src/doctor.ts CHANGED
@@ -29,7 +29,13 @@ import {
29
29
  identityParityBasis,
30
30
  resolvedInstalledCopy,
31
31
  } from "@nifrajs/web/internal/parity"
32
- import { codePositionMask, type SourceFinding, stripComments, walkSource } from "./check.ts"
32
+ import {
33
+ codePositionMask,
34
+ IGNORED,
35
+ type SourceFinding,
36
+ stripComments,
37
+ walkSource,
38
+ } from "./check-scan.ts"
33
39
  import {
34
40
  type HandBuiltManifest,
35
41
  handBuiltManifestMessage,
@@ -726,12 +732,19 @@ async function linkedReadinessSources(
726
732
  async function collectDoctorReadiness(
727
733
  cwd: string,
728
734
  opts: { readonly target?: string; readonly strict?: boolean },
735
+ sources?: readonly { file: string; content: string }[],
729
736
  ): Promise<DoctorReadiness> {
730
737
  const resolved = await resolveTarget(cwd, opts.target)
731
738
  const own: ReadinessSource[] = []
732
- await walkSource(cwd, (file, source) => {
733
- own.push(readinessSource(file, source))
734
- })
739
+ if (sources === undefined) {
740
+ await walkSource(cwd, (file, source) => {
741
+ own.push(readinessSource(file, source))
742
+ })
743
+ } else {
744
+ for (const { file, content } of sources) {
745
+ if (!IGNORED.test(file)) own.push(readinessSource(file, content))
746
+ }
747
+ }
735
748
  // The app's own files first, so a setting it makes itself is the evidence shown.
736
749
  const files = [...own, ...(await linkedReadinessSources(cwd, own))]
737
750
  const edgeTarget = /^(?:cloudflare|vercel|workers|edge|static)$/.test(resolved?.target ?? "")
@@ -994,6 +1007,7 @@ function keepAliveRoutes(cwd: string): readonly string[] {
994
1007
  export async function collectDoctorResult(
995
1008
  cwd: string,
996
1009
  opts: { readonly target?: string; readonly strict?: boolean; readonly cliVersion?: string } = {},
1010
+ sources?: Promise<readonly { file: string; content: string }[]>,
997
1011
  ): Promise<DoctorResult> {
998
1012
  const pkg = await readJson(join(cwd, "package.json"))
999
1013
  if (pkg === undefined)
@@ -1028,26 +1042,31 @@ export async function collectDoctorResult(
1028
1042
  rel === "bench" ||
1029
1043
  rel.startsWith("bench/") ||
1030
1044
  rel.startsWith("packages/create-nifra/template"))
1031
- await walkSource(
1032
- cwd,
1033
- (rel, content) => {
1034
- const scope = scopeForFile(scopes, rel)
1035
- for (const f of scanUndeclaredImports(rel, content, scope.declared, scope.isAlias)) {
1036
- findings.push({ file: f.file, line: f.line, package: f.snippet })
1037
- }
1038
- manifestLists.push(...manifestListsIn(rel, content))
1039
- if (!identitySignal && IDENTITY_SIGNAL.test(content)) identitySignal = true
1040
- if (renamedIn === undefined && RENAMED_SESSION.test(content)) renamedIn = rel
1041
- },
1042
- { includeTests: scanScope.includeTests, ignore: workspaceSurface },
1043
- )
1045
+ const visit = (rel: string, content: string): void => {
1046
+ const scope = scopeForFile(scopes, rel)
1047
+ for (const f of scanUndeclaredImports(rel, content, scope.declared, scope.isAlias)) {
1048
+ findings.push({ file: f.file, line: f.line, package: f.snippet })
1049
+ }
1050
+ manifestLists.push(...manifestListsIn(rel, content))
1051
+ if (!identitySignal && IDENTITY_SIGNAL.test(content)) identitySignal = true
1052
+ if (renamedIn === undefined && RENAMED_SESSION.test(content)) renamedIn = rel
1053
+ }
1054
+ const typedSources = (await sources)?.filter(({ file }) => /\.[cm]?tsx?$/.test(file))
1055
+ if (typedSources === undefined) {
1056
+ await walkSource(cwd, visit, { includeTests: scanScope.includeTests, ignore: workspaceSurface })
1057
+ } else {
1058
+ for (const { file, content } of typedSources) {
1059
+ if (!workspaceSurface(file) && (scanScope.includeTests || !IGNORED.test(file)))
1060
+ visit(file, content)
1061
+ }
1062
+ }
1044
1063
  findings.sort((a, b) => codeUnitOrder(a.file, b.file) || a.line - b.line)
1045
1064
  const identity = await collectAllDuplicateInstalls(cwd, pkg)
1046
1065
  const duplicateInstalls = identity.duplicates
1047
1066
  const staleDists = await collectStaleWorkspaceDists(cwd, pkg)
1048
1067
  const pipeline = await collectPipelineReport(cwd)
1049
1068
  const pipelineErrors = pipeline.findings.filter((f) => f.severity === "error")
1050
- const readiness = await collectDoctorReadiness(cwd, opts)
1069
+ const readiness = await collectDoctorReadiness(cwd, opts, typedSources)
1051
1070
  // A stale binary answering about a project it does not match is an environment condition, so like
1052
1071
  // `staleDists` it is reported but never folded into `ok`. Skipped entirely when the caller did not
1053
1072
  // pass its own version (e.g. the MCP server, which already annotates every result with the drift).
@@ -0,0 +1,26 @@
1
+ import type * as TS from "typescript"
2
+
3
+ /** The local names `source` imports from a specifier matching `from`, by the imported name in `wanted`. */
4
+ export function importedNames(
5
+ ts: typeof TS,
6
+ source: TS.SourceFile,
7
+ from: RegExp,
8
+ wanted: readonly string[],
9
+ ): ReadonlyMap<string, string> {
10
+ const names = new Map<string, string>()
11
+ for (const statement of source.statements) {
12
+ if (
13
+ !ts.isImportDeclaration(statement) ||
14
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
15
+ !from.test(statement.moduleSpecifier.text)
16
+ )
17
+ continue
18
+ const bindings = statement.importClause?.namedBindings
19
+ if (bindings === undefined || !ts.isNamedImports(bindings)) continue
20
+ for (const element of bindings.elements) {
21
+ const original = (element.propertyName ?? element.name).text
22
+ if (wanted.includes(original)) names.set(element.name.text, original)
23
+ }
24
+ }
25
+ return names
26
+ }
@@ -0,0 +1,49 @@
1
+ import type * as TS from "typescript"
2
+ import { scriptKindOf } from "./script-kind.ts"
3
+
4
+ /** A site a rewrite found and left alone, with what to write instead. */
5
+ export interface ManualSite {
6
+ readonly line: number
7
+ readonly reason: string
8
+ }
9
+
10
+ export interface RewriteResult {
11
+ readonly text: string
12
+ /** Sites rewritten. */
13
+ readonly count: number
14
+ readonly manual: readonly ManualSite[]
15
+ }
16
+
17
+ export interface SourceRewrite {
18
+ readonly id: string
19
+ /** What it rewrites, for the plan. */
20
+ readonly description: string
21
+ /** Whether `text` may hold a site: a file it refuses is never parsed. */
22
+ readonly mentions: (text: string) => boolean
23
+ /** Whether `.svelte` and `.vue` files are read too. Left out, they are skipped: a rewrite parses a TypeScript source. */
24
+ readonly components?: boolean
25
+ readonly rewrite: (ts: typeof TS, file: string, text: string) => RewriteResult
26
+ }
27
+
28
+ export interface Edit {
29
+ readonly start: number
30
+ readonly end: number
31
+ readonly text: string
32
+ }
33
+
34
+ /** Apply `edits` (disjoint ranges) to `text`, from the end so earlier offsets stay valid. */
35
+ export function applyEdits(text: string, edits: readonly Edit[]): string {
36
+ let out = text
37
+ for (const edit of edits.toSorted((a, b) => b.start - a.start)) {
38
+ out = `${out.slice(0, edit.start)}${edit.text}${out.slice(edit.end)}`
39
+ }
40
+ return out
41
+ }
42
+
43
+ /** Parse `text` as `file`, with the line lookup a rewrite lists its manual sites by. */
44
+ export function parseSource(ts: typeof TS, file: string, text: string) {
45
+ const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, scriptKindOf(ts, file))
46
+ const lineOf = (node: TS.Node): number =>
47
+ tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1
48
+ return { tree, lineOf }
49
+ }
@@ -1,4 +1,5 @@
1
1
  import type * as TSApi from "typescript"
2
+ import { importedNames } from "./named-imports.ts"
2
3
  import { scriptKindOf } from "./script-kind.ts"
3
4
  import type { TypeScriptApi } from "./typescript-import.ts"
4
5
 
@@ -27,6 +28,14 @@ export interface UndeclaredResponseRoute {
27
28
  readonly path: string
28
29
  }
29
30
 
31
+ /** An SSE stream of one file with no heartbeat under Bun's idle cut, from {@link SourceFacts.silentSseStreams}. */
32
+ export interface SilentSseStream {
33
+ /** The start of the `sse` name (`.sse(` route registration or the `sse(c, run)` helper call). */
34
+ readonly position: number
35
+ /** The `keepAlive` milliseconds written as a literal; undefined when the stream sets none. */
36
+ readonly keepAlive: number | undefined
37
+ }
38
+
30
39
  /** A zod `coerce.boolean()` that a route's text slot reaches, from {@link SourceFacts.textSlotBooleanCoercions}. */
31
40
  export interface TextSlotBooleanCoercion {
32
41
  /** The start of the `coerce.boolean()` call. */
@@ -47,6 +56,23 @@ export interface InternalAnchor {
47
56
  /** Stands for one `${...}` in {@link InternalAnchor.path}. */
48
57
  export const ANCHOR_HOLE = "\u0000"
49
58
 
59
+ /** A `useSearch(from)` or `useParams(from)` call, from {@link SourceFacts.routeHookCalls}. */
60
+ export interface RouteHookCall {
61
+ /** The start of the call. */
62
+ readonly position: number
63
+ readonly hook: "useSearch" | "useParams"
64
+ /** The route pattern written as the argument; undefined when there is none or it is not a literal. */
65
+ readonly pattern: string | undefined
66
+ /** Whether the call has an argument at all. */
67
+ readonly hasArgument: boolean
68
+ }
69
+
70
+ /** A type assertion to `Href` (the `as` form or `<Href>x`), from {@link SourceFacts.hrefCasts}. */
71
+ export interface HrefCast {
72
+ /** The start of the cast expression. */
73
+ readonly position: number
74
+ }
75
+
50
76
  /** A `serverFunctions("namespace", module)` mount of a `*.fn.ts` module, from {@link SourceFacts.serverFunctionMounts}. */
51
77
  export interface ServerFunctionMount {
52
78
  /** The start of the namespace literal. */
@@ -107,6 +133,14 @@ export interface SourceFacts {
107
133
  * left out too, since the file does not show whether it declares one.
108
134
  */
109
135
  undeclaredResponseRoutes(source: TSApi.SourceFile): readonly UndeclaredResponseRoute[]
136
+ /**
137
+ * The SSE streams of `source` that send no ping within `idleSeconds`: an `app.sse(path, schema, run)`
138
+ * route or an `sse(c, run)` helper call (imported from a `@nifrajs/` package) whose init object
139
+ * has no `keepAlive`, or a literal one of `idleSeconds` seconds or more. An init that is not an
140
+ * object literal, spreads another object, or sets `keepAlive` to something that is not a literal
141
+ * is left out, since the file does not show its interval.
142
+ */
143
+ silentSseStreams(source: TSApi.SourceFile, idleSeconds: number): readonly SilentSseStream[]
110
144
  /**
111
145
  * The zod `coerce.boolean()` calls a route's `query`, `headers` or `cookies` schema reaches in
112
146
  * `source`: written in the route's options, or in a variable of the file the options name, at any
@@ -125,6 +159,13 @@ export interface SourceFacts {
125
159
  * `#hash` and a `//host` are left out.
126
160
  */
127
161
  internalAnchors(source: TSApi.SourceFile): readonly InternalAnchor[]
162
+ /**
163
+ * The calls of `useSearch` and `useParams` imported from a `@nifrajs/web-<framework>` package
164
+ * (`/router` or the root), under the name they were imported as.
165
+ */
166
+ routeHookCalls(source: TSApi.SourceFile): readonly RouteHookCall[]
167
+ /** The casts of a value to `Href`, imported from `@nifrajs/web` or a `@nifrajs/web-<framework>` package. */
168
+ hrefCasts(source: TSApi.SourceFile): readonly HrefCast[]
128
169
  /** Whether the function `source` exports as `name` returns a raw `Response` on some path. */
129
170
  exportReturnsResponse(source: TSApi.SourceFile, name: string): boolean
130
171
  /** Whether the `import` keyword at `position` starts a runtime `import(specifier)` call (true) or a
@@ -834,6 +875,120 @@ export function createSourceFacts(
834
875
  return found
835
876
  }
836
877
 
878
+ const WEB_ADAPTER = /^@nifrajs\/web-(?:react|preact|solid|svelte|vue)(?:\/router)?$/
879
+ const WEB_ANY = /^@nifrajs\/web(?:-(?:react|preact|solid|svelte|vue))?(?:\/(?:router|client))?$/
880
+ const localNames = (
881
+ source: TSApi.SourceFile,
882
+ from: RegExp,
883
+ imported: readonly string[],
884
+ ): ReadonlyMap<string, string> => importedNames(ts, source, from, imported)
885
+
886
+ const routeHookCalls = (source: TSApi.SourceFile): readonly RouteHookCall[] => {
887
+ const names = localNames(source, WEB_ADAPTER, ["useSearch", "useParams"])
888
+ if (names.size === 0) return []
889
+ const found: RouteHookCall[] = []
890
+ const visit = (node: TSApi.Node): void => {
891
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
892
+ const hook = names.get(node.expression.text)
893
+ if (hook === "useSearch" || hook === "useParams") {
894
+ const [first] = node.arguments
895
+ found.push({
896
+ position: node.getStart(source),
897
+ hook,
898
+ pattern:
899
+ first !== undefined &&
900
+ (ts.isStringLiteral(first) || ts.isNoSubstitutionTemplateLiteral(first))
901
+ ? first.text
902
+ : undefined,
903
+ hasArgument: first !== undefined,
904
+ })
905
+ }
906
+ }
907
+ ts.forEachChild(node, visit)
908
+ }
909
+ visit(source)
910
+ return found
911
+ }
912
+
913
+ const hrefCasts = (source: TSApi.SourceFile): readonly HrefCast[] => {
914
+ const names = new Set(localNames(source, WEB_ANY, ["Href"]).keys())
915
+ if (names.size === 0) return []
916
+ const found: HrefCast[] = []
917
+ const visit = (node: TSApi.Node): void => {
918
+ if (
919
+ (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) &&
920
+ ts.isTypeReferenceNode(node.type) &&
921
+ ts.isIdentifier(node.type.typeName) &&
922
+ names.has(node.type.typeName.text)
923
+ )
924
+ found.push({ position: node.getStart(source) })
925
+ ts.forEachChild(node, visit)
926
+ }
927
+ visit(source)
928
+ return found
929
+ }
930
+
931
+ const silentSseStreams = (
932
+ source: TSApi.SourceFile,
933
+ idleSeconds: number,
934
+ ): readonly SilentSseStream[] => {
935
+ const helpers = new Set<string>()
936
+ for (const [local, { specifier, name }] of valueImports(ts, source))
937
+ if (name === "sse" && specifier.startsWith("@nifrajs/")) helpers.add(local)
938
+ const found: SilentSseStream[] = []
939
+ const visit = (node: TSApi.Node): void => {
940
+ ts.forEachChild(node, visit)
941
+ if (!ts.isCallExpression(node)) return
942
+ const callee = node.expression
943
+ let name: TSApi.MemberName | undefined
944
+ let initIndex = 0
945
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === "sse") {
946
+ const path = node.arguments[0]
947
+ if (path === undefined || !ts.isStringLiteralLike(path) || node.arguments.length < 3) return
948
+ name = callee.name
949
+ initIndex = 3
950
+ } else if (
951
+ ts.isIdentifier(callee) &&
952
+ helpers.has(callee.text) &&
953
+ node.arguments.length >= 2
954
+ ) {
955
+ name = callee
956
+ initIndex = 2
957
+ }
958
+ if (name === undefined) return
959
+ const init = node.arguments[initIndex]
960
+ let keepAlive: number | undefined
961
+ if (init !== undefined) {
962
+ const value = unwrapExpression(ts, init)
963
+ if (!ts.isObjectLiteralExpression(value)) return
964
+ for (const property of value.properties) {
965
+ if (ts.isSpreadAssignment(property)) return
966
+ const key = property.name
967
+ if (key === undefined) continue
968
+ // A computed key the file does not spell out may be `keepAlive`: the interval is unknown.
969
+ if (ts.isComputedPropertyName(key)) {
970
+ const spelled = unwrapExpression(ts, key.expression)
971
+ if (!ts.isStringLiteralLike(spelled)) return
972
+ if (spelled.text !== "keepAlive") continue
973
+ } else if (
974
+ !(ts.isIdentifier(key) || ts.isStringLiteralLike(key)) ||
975
+ key.text !== "keepAlive"
976
+ ) {
977
+ continue
978
+ }
979
+ if (!ts.isPropertyAssignment(property)) return
980
+ const written = unwrapExpression(ts, property.initializer)
981
+ if (!ts.isNumericLiteral(written)) return
982
+ keepAlive = Number(written.text)
983
+ }
984
+ }
985
+ if (keepAlive !== undefined && keepAlive > 0 && keepAlive < idleSeconds * 1000) return
986
+ found.push({ position: name.getStart(source), keepAlive })
987
+ }
988
+ visit(source)
989
+ return found.sort((a, b) => a.position - b.position)
990
+ }
991
+
837
992
  const textSlotBooleanCoercions = (
838
993
  source: TSApi.SourceFile,
839
994
  ): readonly TextSlotBooleanCoercion[] => {
@@ -1015,8 +1170,11 @@ export function createSourceFacts(
1015
1170
  isResponseSyntaxAt,
1016
1171
  untypedResponseRoutes,
1017
1172
  undeclaredResponseRoutes,
1173
+ silentSseStreams,
1018
1174
  textSlotBooleanCoercions,
1019
1175
  internalAnchors,
1176
+ routeHookCalls,
1177
+ hrefCasts,
1020
1178
  serverFunctionMounts,
1021
1179
  exportReturnsResponse,
1022
1180
  isDynamicImportAt,
@@ -34,6 +34,7 @@ import {
34
34
  parseCapabilityLockfile,
35
35
  } from "./capabilities-tool.ts"
36
36
  import { DEFAULT_MANIFEST_FILE } from "./manifest-tool.ts"
37
+ import { VERIFICATION_GATES, type VerificationGate } from "./verification-gates.ts"
37
38
 
38
39
  export interface VerificationLevelStatus {
39
40
  readonly level: number
@@ -66,6 +67,8 @@ export interface CollectLevelsOptions {
66
67
  readonly config?: string
67
68
  /** Deterministic seed for the L4 invariant run. Default 1. */
68
69
  readonly seed?: number
70
+ /** Run the requested prefix when collecting evidence for a proof plan. */
71
+ readonly throughLevel?: VerificationGate["level"]
69
72
  }
70
73
 
71
74
  /** Compute the ladder. Each level is evaluated independently, then gated on the levels below. */
@@ -81,16 +84,24 @@ export async function collectVerificationLevels(
81
84
  ...(options.config !== undefined ? { config: options.config } : {}),
82
85
  maxDiagnostics: 5,
83
86
  })
87
+ const [typed, route, capabilities, manifest, invariants] = VERIFICATION_GATES
88
+ const through = options.throughLevel ?? invariants.level
84
89
  const statuses: LevelStatusDraft[] = []
85
90
 
86
91
  // L0 - typed contract (`nifra check`).
87
92
  const check = await verification.check()
88
93
  statuses.push({
89
- level: 0,
90
- name: "typed contract",
91
- ok: check.ok,
92
- reasons: check.ok ? [] : check.diagnostics.map((d) => `${d.rule}: ${d.message}`).slice(0, 5),
94
+ level: typed.level,
95
+ name: typed.name,
96
+ ok: check.ok && check.typecheck === "pass",
97
+ reasons:
98
+ check.typecheck === "skipped"
99
+ ? [`typecheck skipped: ${check.typecheckNote ?? "no compiler result"}`]
100
+ : check.ok && check.typecheck === "pass"
101
+ ? []
102
+ : check.diagnostics.map((d) => `${d.rule}: ${d.message}`).slice(0, 5),
93
103
  })
104
+ if (through === typed.level) return finalize(statuses, verification.routeAssurance?.routes ?? [])
94
105
 
95
106
  // L1-L4 all hang off the assurance config; without it the ladder stops at L0 by definition.
96
107
  if (verification.config === undefined) {
@@ -98,12 +109,7 @@ export async function collectVerificationLevels(
98
109
  verification.configError instanceof Error
99
110
  ? verification.configError.message
100
111
  : String(verification.configError)
101
- for (const [level, name] of [
102
- [1, "route assurance"],
103
- [2, "capability lockfile"],
104
- [3, "route manifest"],
105
- [4, "invariant-tested"],
106
- ] as const) {
112
+ for (const { level, name } of VERIFICATION_GATES.slice(1, through + 1)) {
107
113
  statuses.push({ level, name, ok: false, reasons: [reason] })
108
114
  }
109
115
  return finalize(statuses, [])
@@ -113,11 +119,12 @@ export async function collectVerificationLevels(
113
119
  // L1 - route assurance.
114
120
  const assurance = verification.routeAssurance as AssuranceReport
115
121
  statuses.push({
116
- level: 1,
117
- name: "route assurance",
122
+ level: route.level,
123
+ name: route.name,
118
124
  ok: assurance.ok,
119
125
  reasons: assurance.findings.map((f) => f.message).slice(0, 5),
120
126
  })
127
+ if (through === route.level) return finalize(statuses, assurance.routes)
121
128
 
122
129
  // L2 - capability assurance + lockfile in sync.
123
130
  const l2Reasons: string[] = []
@@ -139,11 +146,12 @@ export async function collectVerificationLevels(
139
146
  }
140
147
  }
141
148
  statuses.push({
142
- level: 2,
143
- name: "capability lockfile",
149
+ level: capabilities.level,
150
+ name: capabilities.name,
144
151
  ok: l2Reasons.length === 0,
145
152
  reasons: l2Reasons,
146
153
  })
154
+ if (through === capabilities.level) return finalize(statuses, assurance.routes)
147
155
 
148
156
  // L3 - emitted manifest hash-verifies AND matches the current app.
149
157
  const l3Reasons: string[] = []
@@ -176,11 +184,12 @@ export async function collectVerificationLevels(
176
184
  }
177
185
  }
178
186
  statuses.push({
179
- level: 3,
180
- name: "route manifest",
187
+ level: manifest.level,
188
+ name: manifest.name,
181
189
  ok: l3Reasons.length === 0,
182
190
  reasons: l3Reasons,
183
191
  })
192
+ if (through === manifest.level) return finalize(statuses, assurance.routes)
184
193
 
185
194
  // L4 - contract-generated invariants against an explicitly isolated executor.
186
195
  const l4 =
@@ -193,8 +202,8 @@ export async function collectVerificationLevels(
193
202
  }
194
203
  : await runInvariants(config.source, config.invariants, options.seed ?? 1)
195
204
  const l4Status: LevelStatusDraft = {
196
- level: 4,
197
- name: "invariant-tested",
205
+ level: invariants.level,
206
+ name: invariants.name,
198
207
  ok: l4.reasons.length === 0,
199
208
  reasons: l4.reasons,
200
209
  }
package/src/mcp-exec.ts CHANGED
@@ -376,7 +376,7 @@ export function projectTools(
376
376
  {
377
377
  name: "nifra_inspect",
378
378
  description:
379
- "Observe what your requests ACTUALLY did on the running dev server: one trace per request, `{ requestId, method, path, status, durationMs, bytes, isr, errorIds, logCount }`. After nifra_run or a real browser request, call this to SEE the outcome (the status, how long, ISR hit/miss, whether it logged or failed) instead of guessing; pass a trace's `requestId` to nifra_errors/nifra_logs for what that request failed with or printed. Every `nifra dev` server keeps these traces and is found automatically; `port`/`dir` pick one when several run. Narrow with `path` (a path prefix), `requestId`, `since` (a cursor from an earlier call) or `limit` (most recent N). An explicit `port` this project did not start falls back to the `@nifrajs/devtools` plugin's traces.",
379
+ "Inspect recent requests on the running dev server after nifra_run or a browser request. Traces include status, durationMs, bytes when known, ISR status, errorIds and logCount. Page traces can include routeTiming with the matched pattern and phase totals in milliseconds: pageLoader, layoutLoaders, validation, serialization, and render. Parallel loader times can overlap. Pass requestId to nifra_errors or nifra_logs to follow a trace. Narrow with path, requestId, since or limit. Pass port or dir to pick a server. A port this project did not start can fall back to the @nifrajs/devtools plugin.",
380
380
  inputSchema: {
381
381
  type: "object",
382
382
  properties: {
package/src/mcp-http.ts CHANGED
@@ -30,7 +30,7 @@ export { docsTools } from "./mcp-docs-tools.ts"
30
30
  export type { TypeEntry } from "./types-search.ts"
31
31
 
32
32
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
33
- const VERSION = "5.15.1"
33
+ const VERSION = "5.17.0"
34
34
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
35
35
  // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
36
36
  const docsHealth = (tools: McpTool[]): string =>