@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nifrajs/cli",
3
- "version": "5.15.1",
3
+ "version": "5.16.0",
4
4
  "description": "The nifra CLI - zero-config dev/build/start for a nifra app (`nifra dev`, `nifra build`, `nifra start`).",
5
5
  "keywords": [
6
6
  "bun",
@@ -70,17 +70,17 @@
70
70
  "access": "public"
71
71
  },
72
72
  "dependencies": {
73
- "@nifrajs/agent-review": "5.15.1",
74
- "@nifrajs/client": "5.15.1",
75
- "@nifrajs/core": "5.15.1",
76
- "@nifrajs/i18n": "5.15.1",
77
- "@nifrajs/mcp": "5.15.1",
78
- "@nifrajs/mcp-db": "5.15.1",
79
- "@nifrajs/runner": "5.15.1",
80
- "@nifrajs/schema": "5.15.1",
81
- "@nifrajs/testing": "5.15.1",
82
- "@nifrajs/utils": "5.15.1",
83
- "@nifrajs/web": "5.15.1"
73
+ "@nifrajs/agent-review": "5.16.0",
74
+ "@nifrajs/client": "5.16.0",
75
+ "@nifrajs/core": "5.16.0",
76
+ "@nifrajs/i18n": "5.16.0",
77
+ "@nifrajs/mcp": "5.16.0",
78
+ "@nifrajs/mcp-db": "5.16.0",
79
+ "@nifrajs/runner": "5.16.0",
80
+ "@nifrajs/schema": "5.16.0",
81
+ "@nifrajs/testing": "5.16.0",
82
+ "@nifrajs/utils": "5.16.0",
83
+ "@nifrajs/web": "5.16.0"
84
84
  },
85
85
  "repository": {
86
86
  "type": "git",
@@ -0,0 +1,107 @@
1
+ import { createReadStream } from "node:fs"
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
3
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path"
4
+ import { Glob } from "bun"
5
+ import { codeUnitOrder } from "./internal/code-unit-order.ts"
6
+ import { isRecord } from "./internal/record.ts"
7
+
8
+ const PROJECT_SOURCE = new Glob(
9
+ "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json,jsonc,svelte,vue,md,mdx,css,lock,lockb,toml,yaml,yml}",
10
+ )
11
+ const PUBLIC_ASSET = new Glob("public/**/*")
12
+ const FILES = new Glob("**/*")
13
+ const IGNORED = /(^|\/)(node_modules|dist|build|\.nifra|\.git|\.wrangler|coverage)\//
14
+ const SHA256 = /^[a-f0-9]{64}$/
15
+
16
+ const posix = (path: string): string => (sep === "\\" ? path.replaceAll("\\", "/") : path)
17
+
18
+ function projectInputs(root: string, outDir: string, glob: Glob): string[] {
19
+ const output = posix(relative(root, outDir))
20
+ const inside =
21
+ output !== "" && output !== ".." && !output.startsWith("../") && !isAbsolute(output)
22
+ return [...glob.scanSync({ cwd: root })]
23
+ .map(posix)
24
+ .filter((path) => !IGNORED.test(path) && (!inside || !path.startsWith(`${output}/`)))
25
+ }
26
+
27
+ export function projectSourceFiles(root: string, outDir: string): string[] {
28
+ return projectInputs(root, outDir, PROJECT_SOURCE).sort(codeUnitOrder)
29
+ }
30
+
31
+ export function buildOutputFiles(outDir: string): string[] {
32
+ return [...FILES.scanSync({ cwd: outDir, dot: true })].map(posix).sort(codeUnitOrder)
33
+ }
34
+
35
+ export async function fingerprintFiles(root: string, paths: readonly string[]): Promise<string> {
36
+ const manifest = new Bun.CryptoHasher("sha256")
37
+ for (const path of paths) {
38
+ const file = new Bun.CryptoHasher("sha256")
39
+ for await (const chunk of createReadStream(resolve(root, path))) file.update(chunk)
40
+ manifest.update(JSON.stringify([path, file.digest("hex")]))
41
+ }
42
+ return manifest.digest("hex")
43
+ }
44
+
45
+ export async function fingerprintBuildInputs(root: string, outDir: string): Promise<string> {
46
+ const paths = new Set([
47
+ ...projectSourceFiles(root, outDir),
48
+ ...projectInputs(root, outDir, PUBLIC_ASSET),
49
+ ])
50
+ return fingerprintFiles(root, [...paths].sort(codeUnitOrder))
51
+ }
52
+
53
+ interface BuildProvenance {
54
+ readonly version: 1
55
+ readonly sourceDigest: string
56
+ readonly buildDigest: string
57
+ }
58
+
59
+ function receiptPath(root: string, outDir: string): string {
60
+ const key = Bun.CryptoHasher.hash("sha256", posix(relative(root, outDir)), "hex")
61
+ return resolve(root, ".nifra", "build-provenance", `${key}.json`)
62
+ }
63
+
64
+ /** Record the completed build only if it read the same project inputs on both sides of the build. */
65
+ export async function recordBuildProvenance(
66
+ root: string,
67
+ outDir: string,
68
+ before: string,
69
+ ): Promise<boolean> {
70
+ const buildDigest = await fingerprintFiles(outDir, buildOutputFiles(outDir))
71
+ const sourceDigest = await fingerprintBuildInputs(root, outDir)
72
+ if (sourceDigest !== before) return false
73
+ const receipt: BuildProvenance = { version: 1, sourceDigest, buildDigest }
74
+ const path = receiptPath(root, outDir)
75
+ const staged = `${path}.${crypto.randomUUID()}.tmp`
76
+ await mkdir(dirname(path), { recursive: true })
77
+ try {
78
+ await writeFile(staged, `${JSON.stringify(receipt)}\n`, { flag: "wx" })
79
+ await rename(staged, path)
80
+ } finally {
81
+ await rm(staged, { force: true })
82
+ }
83
+ return true
84
+ }
85
+
86
+ export async function readBuildProvenance(
87
+ root: string,
88
+ outDir: string,
89
+ ): Promise<BuildProvenance | undefined> {
90
+ try {
91
+ const parsed: unknown = JSON.parse(await readFile(receiptPath(root, outDir), "utf8"))
92
+ if (
93
+ isRecord(parsed) &&
94
+ parsed.version === 1 &&
95
+ typeof parsed.sourceDigest === "string" &&
96
+ SHA256.test(parsed.sourceDigest) &&
97
+ typeof parsed.buildDigest === "string" &&
98
+ SHA256.test(parsed.buildDigest)
99
+ )
100
+ return { version: 1, sourceDigest: parsed.sourceDigest, buildDigest: parsed.buildDigest }
101
+ } catch (error) {
102
+ // A missing or malformed receipt cannot certify any build.
103
+ if (!(error instanceof SyntaxError) && Reflect.get(Object(error), "code") !== "ENOENT")
104
+ throw error
105
+ }
106
+ return undefined
107
+ }
@@ -32,11 +32,13 @@ import { LEGACY_RULE_CODES, LEGACY_RULE_ORDER, legacyRules } from "./rules/legac
32
32
  import { mergeAuthGapRule } from "./rules/merge-auth.ts"
33
33
  import { pageRules } from "./rules/pages.ts"
34
34
  import { pprRules } from "./rules/ppr.ts"
35
+ import { routeHookRules } from "./rules/route-hooks.ts"
35
36
  import { routeStatementRule } from "./rules/route-statement.ts"
36
37
  import { routeRules } from "./rules/routes.ts"
37
38
  import { secretRules } from "./rules/secrets.ts"
38
39
  import { securityRules } from "./rules/security.ts"
39
40
  import { serverFnNamespaceRule } from "./rules/server-fn-namespace.ts"
41
+ import { silentSseRule } from "./rules/silent-sse.ts"
40
42
  import { swapRules } from "./rules/swap.ts"
41
43
  import { textSlotBooleanRule } from "./rules/text-slot-boolean.ts"
42
44
  import { undeclaredResponseRule } from "./rules/undeclared-response.ts"
@@ -82,6 +84,7 @@ export type CheckSuggestion = DiagnosticSuggestion
82
84
  /** The structured result of a full check - what `--json` prints and the `nifra_check` MCP tool returns. */
83
85
  export interface CheckResult {
84
86
  readonly ok: boolean
87
+ readonly timings?: import("./check-timings.ts").CheckTimings
85
88
  readonly typecheck: "pass" | "fail" | "skipped"
86
89
  /** Why `typecheck` is `"skipped"` (no tsconfig.json, typescript not installed, lints-only mode), or
87
90
  * why it failed when the compiler itself passed (zoned files outside its program). Echoed in the
@@ -509,8 +512,10 @@ export async function collectCheckDiagnostics(
509
512
  mergeAuthGapRule,
510
513
  routeStatementRule,
511
514
  undeclaredResponseRule,
515
+ silentSseRule,
512
516
  textSlotBooleanRule,
513
517
  ...internalLinkRules,
518
+ ...routeHookRules,
514
519
  serverFnNamespaceRule,
515
520
  ...zoneRules,
516
521
  ...dataGuardRules,
package/src/check-scan.ts CHANGED
@@ -877,7 +877,10 @@ function scanRouteArguments(
877
877
  const routes: StaticRouteFinding[] = []
878
878
  const unresolved: UnresolvedRoutePathFinding[] = []
879
879
  const code = stripComments(content)
880
- if (!isPotentialBackendSource(code, file, project)) return { routes, unresolved }
880
+ ROUTE_ARGUMENT.lastIndex = 0
881
+ const first = ROUTE_ARGUMENT.exec(code)
882
+ if (first === null || !isPotentialBackendSource(code, file, project))
883
+ return { routes, unresolved }
881
884
  const lines = content.split("\n")
882
885
  const constants = moduleConstants(code, content)
883
886
  const imports = namedImports(code)
@@ -894,8 +897,7 @@ function scanRouteArguments(
894
897
  const constant = found.get(name)
895
898
  return constant?.exported === true ? constant : undefined
896
899
  }
897
- ROUTE_ARGUMENT.lastIndex = 0
898
- for (let m = ROUTE_ARGUMENT.exec(code); m !== null; m = ROUTE_ARGUMENT.exec(code)) {
900
+ for (let m: RegExpExecArray | null = first; m !== null; m = ROUTE_ARGUMENT.exec(code)) {
899
901
  const method = (m[1] ?? "").toUpperCase()
900
902
  if (!verbs.has(method)) continue
901
903
  const at = m.index + m[0].lastIndexOf(m[2] ?? "")
@@ -2619,12 +2621,13 @@ export function scanSqlSites(
2619
2621
  content: string,
2620
2622
  ts: TypeScriptApi,
2621
2623
  imports?: SqlImports,
2624
+ parse = (path: string, text: string) => parseSqlSource(ts, path, text),
2622
2625
  ): SqlFinding[] {
2623
2626
  const out: SqlFinding[] = []
2624
2627
  const lines = content.split("\n")
2625
2628
  // Malformed source is already a typecheck failure. Do not turn parser recovery nodes into a second,
2626
2629
  // misleading SQL diagnostic (notably an unterminated template recovered as an interpolation).
2627
- const source = parseSqlSource(ts, file, content)
2630
+ const source = parse(file, content)
2628
2631
  if (source === undefined) return out
2629
2632
  // Module-scope bindings, read once per file: an interpolated `const` that resolves to compile-time
2630
2633
  // text cannot carry request data, so the shared-projection idiom (`const COLS = "id, name"` …
@@ -0,0 +1,27 @@
1
+ export interface CheckTimings {
2
+ readonly totalMs: number
3
+ /** Wall time per phase. Concurrent phases may overlap. */
4
+ readonly phasesMs: Readonly<Record<string, number>>
5
+ }
6
+
7
+ export function createCheckTimer() {
8
+ const began = performance.now()
9
+ const phasesMs: Record<string, number> = {}
10
+ const elapsed = (started: number): number => Math.round((performance.now() - started) * 100) / 100
11
+ return {
12
+ record(phase: string, started: number): void {
13
+ phasesMs[phase] = elapsed(started)
14
+ },
15
+ async measure<T>(phase: string, run: () => T | Promise<T>): Promise<T> {
16
+ const started = performance.now()
17
+ try {
18
+ return await run()
19
+ } finally {
20
+ phasesMs[phase] = elapsed(started)
21
+ }
22
+ },
23
+ snapshot(): CheckTimings {
24
+ return { totalMs: elapsed(began), phasesMs }
25
+ },
26
+ }
27
+ }
package/src/check.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  type RuleOverride,
31
31
  safeIgnoreGlobMatch,
32
32
  } from "./check-diagnostics.ts"
33
+ import { createCheckTimer } from "./check-timings.ts"
33
34
  import { appDirs, clientModuleRoot } from "./client-module.ts"
34
35
  import { checkContractsLock, DEFAULT_CONTRACTS_LOCK } from "./contracts.ts"
35
36
  import { type Diagnostic, diagnostic, normalizeSeverity, toSarifLog } from "./diagnostics.ts"
@@ -41,6 +42,7 @@ import { createSourceFacts } from "./internal/source-facts.ts"
41
42
  import { loadProjectTypeScript, type TypeScriptApi } from "./internal/typescript-import.ts"
42
43
  import {
43
44
  forwardTerminalSignals,
45
+ inProjectChildProcess,
44
46
  OWN_PROCESS_GROUP,
45
47
  signalProcessGroup,
46
48
  stopGroupAndWait,
@@ -50,6 +52,7 @@ import {
50
52
  import type { ContractCheckFacts, ProjectFactsSeed } from "./project-facts.ts"
51
53
  import { RULE_CODES } from "./rules/codes.ts"
52
54
  import { sourceIndex } from "./rules/index.ts"
55
+ import { stageTypecheckCache } from "./typecheck-cache.ts"
53
56
  import {
54
57
  filesOutsideProgram,
55
58
  routeTableOutsideProgram,
@@ -74,6 +77,7 @@ import {
74
77
  componentScripts,
75
78
  createProjectSqlImports,
76
79
  createServerOnlyChains,
80
+ IGNORED,
77
81
  isBrowserSource,
78
82
  type ModuleReader,
79
83
  type ModuleResolver,
@@ -145,6 +149,7 @@ async function typecheck(
145
149
  cwd: string,
146
150
  signal?: AbortSignal,
147
151
  configured?: readonly string[],
152
+ incremental = false,
148
153
  ): Promise<TypecheckResult> {
149
154
  const projects = typecheckProjects(cwd, configured)
150
155
  if (projects.missing.length > 0) {
@@ -170,10 +175,10 @@ async function typecheck(
170
175
  }
171
176
  const runs: TypecheckResult[] = []
172
177
  for (const tsconfig of projects.paths) {
173
- let run = await runTsc(cwd, tscBin, tsconfig, true, signal)
178
+ let run = await runTsc(cwd, tscBin, tsconfig, true, signal, incremental)
174
179
  // A compiler that rejects `--listFiles` still gets its typecheck; only the coverage check is lost.
175
180
  if (!run.ok && !run.cancelled && /TS50(?:23|25)\b[^\n]*listFiles/.test(run.output ?? ""))
176
- run = await runTsc(cwd, tscBin, tsconfig, false, signal)
181
+ run = await runTsc(cwd, tscBin, tsconfig, false, signal, incremental)
177
182
  if (run.cancelled === true) return run
178
183
  runs.push(run)
179
184
  }
@@ -198,6 +203,7 @@ async function runTsc(
198
203
  tsconfig: string,
199
204
  listFiles: boolean,
200
205
  signal?: AbortSignal,
206
+ incremental = false,
201
207
  ): Promise<TypecheckResult> {
202
208
  if (signal?.aborted) return { ran: true, ok: false, cancelled: true, output: "cancelled" }
203
209
  const args = [process.execPath, tscBin, "--noEmit", "-p", tsconfig]
@@ -207,22 +213,31 @@ async function runTsc(
207
213
  const outputDirectory = mkdtempSync(join(tmpdir(), "nifra-tsc-"))
208
214
  const stdout = Bun.file(join(outputDirectory, "stdout"))
209
215
  const stderr = Bun.file(join(outputDirectory, "stderr"))
216
+ let cache: ReturnType<typeof stageTypecheckCache>
217
+ let publishCache = false
210
218
  try {
219
+ if (incremental) {
220
+ cache = stageTypecheckCache(cwd, tscBin, tsconfig)
221
+ if (cache !== undefined) args.push("--incremental", "--tsBuildInfoFile", cache.path)
222
+ }
223
+ const detached = OWN_PROCESS_GROUP && !inProjectChildProcess()
211
224
  const proc = Bun.spawn(args, {
212
225
  cwd,
213
226
  stdout,
214
227
  stderr,
215
- // Its own group lets cancellation also stop a compiler process the tsc entry started.
216
- detached: OWN_PROCESS_GROUP,
228
+ // Reuse the project child's cancellation group when one already exists.
229
+ detached,
217
230
  })
218
231
  let cancelled = false
219
- const stop = (): void => signalProcessGroup(proc, "SIGTERM")
232
+ const stop = (): void => signalProcessGroup(proc, "SIGTERM", detached)
220
233
  const abort = (): void => {
221
234
  cancelled = true
222
235
  stop()
223
236
  }
224
237
  signal?.addEventListener("abort", abort, { once: true })
225
- const releaseSignals = forwardTerminalSignals(() => stopGroupAndWait(proc))
238
+ const releaseSignals = detached
239
+ ? forwardTerminalSignals(() => stopGroupAndWait(proc))
240
+ : undefined
226
241
  let out = ""
227
242
  let err = ""
228
243
  let code: number | null = null
@@ -233,9 +248,10 @@ async function runTsc(
233
248
  err = result[1]
234
249
  } finally {
235
250
  signal?.removeEventListener("abort", abort)
236
- releaseSignals()
251
+ releaseSignals?.()
237
252
  }
238
253
  if (cancelled) return { ran: true, ok: false, output: "cancelled", cancelled: true }
254
+ publishCache = code === 0
239
255
  const listed = listFiles ? splitListedFiles(out) : undefined
240
256
  return {
241
257
  ran: true,
@@ -249,6 +265,7 @@ async function runTsc(
249
265
  rmSync(join(outputDirectory, "stdout"), { force: true })
250
266
  rmSync(join(outputDirectory, "stderr"), { force: true })
251
267
  rmdirSync(outputDirectory)
268
+ cache?.finish(publishCache)
252
269
  }
253
270
  }
254
271
 
@@ -347,6 +364,8 @@ async function loadCheckConfig(
347
364
  }
348
365
 
349
366
  interface CheckCollectionOptions {
367
+ readonly incremental?: boolean
368
+ readonly timer?: ReturnType<typeof createCheckTimer>
350
369
  readonly lintsOnly?: boolean
351
370
  readonly signal?: AbortSignal
352
371
  readonly maxDiagnostics?: number
@@ -411,10 +430,7 @@ function withProgramCoverage(
411
430
  }
412
431
 
413
432
  /** Build the rule input from one source walk and the other check-wide scans. */
414
- async function buildProjectScan(
415
- cwd: string,
416
- opts: Pick<CheckCollectionOptions, "lintsOnly" | "signal" | "loadTypeScript">,
417
- ): Promise<ProjectScan> {
433
+ async function buildProjectScan(cwd: string, opts: CheckCollectionOptions): Promise<ProjectScan> {
418
434
  const fetches: TypedClientFinding[] = []
419
435
  const streams: TypedClientFinding[] = []
420
436
  const staticRoutes: StaticRouteFinding[] = []
@@ -429,33 +445,48 @@ async function buildProjectScan(
429
445
  const inNifraProject = createNifraProjectProbe(cwd)
430
446
  // An API-only project has no browser bundle for server code to reach.
431
447
  const apiOnly = createApiOnlyProbe(cwd)
448
+ const timer = opts.timer ?? createCheckTimer()
432
449
  const {
433
450
  config: checkConfig,
434
451
  error: checkConfigError,
435
452
  warnings: checkConfigWarnings,
436
- } = await loadCheckConfig(cwd)
437
- const [typecheckRun, _, doctor, manifestDrift, contracts] = await Promise.all([
453
+ } = await timer.measure("config", () => loadCheckConfig(cwd))
454
+ const allSources = timer.measure("read-sources", async () => {
455
+ const files: typeof sourceFiles = []
456
+ await walkSource(cwd, (file, content) => files.push({ file, content }), {
457
+ scripts: true,
458
+ includeTests: true,
459
+ })
460
+ return files
461
+ })
462
+ const [typecheckRun, , doctor, manifestDrift, contracts] = await Promise.all([
438
463
  opts.lintsOnly
439
464
  ? Promise.resolve<TypecheckResult>({ ran: false, ok: true, note: "lints-only mode" })
440
- : typecheck(cwd, opts.signal, checkConfig.tsconfigs),
441
- walkSource(
442
- cwd,
443
- (rel, content) => {
444
- sourceFiles.push({ file: rel, content })
445
- fetches.push(...scanFetchText(rel, content, checkConfig.externalMounts))
446
- streams.push(...scanStreamText(rel, content, checkConfig.externalMounts))
447
- untypedClients.push(...scanUntypedClient(rel, content))
448
- removedImports.push(...scanRemovedImports(rel, content))
449
- const dir = dirname(rel).replace(/^\.$/, "")
450
- if (isBrowserSource(rel) && inNifraProject(dir) && !apiOnly(dir))
451
- browserModules.push({ rel, content })
452
- },
453
- { scripts: true },
465
+ : timer.measure("typecheck", () =>
466
+ typecheck(cwd, opts.signal, checkConfig.tsconfigs, opts.incremental),
467
+ ),
468
+ allSources.then((files) =>
469
+ timer.measure("source-lints", () => {
470
+ for (const { file, content } of files) {
471
+ if (IGNORED.test(file)) continue
472
+ sourceFiles.push({ file, content })
473
+ fetches.push(...scanFetchText(file, content, checkConfig.externalMounts))
474
+ streams.push(...scanStreamText(file, content, checkConfig.externalMounts))
475
+ untypedClients.push(...scanUntypedClient(file, content))
476
+ removedImports.push(...scanRemovedImports(file, content))
477
+ const dir = dirname(file).replace(/^\.$/, "")
478
+ if (isBrowserSource(file) && inNifraProject(dir) && !apiOnly(dir))
479
+ browserModules.push({ rel: file, content })
480
+ }
481
+ }),
482
+ ),
483
+ timer.measure("doctor", async () =>
484
+ (await import("./doctor.ts")).collectDoctorResult(cwd, {}, allSources),
454
485
  ),
455
- import("./doctor.ts").then((m) => m.collectDoctorResult(cwd)),
456
- scanServerManifestDrift(cwd),
457
- collectContractFacts(cwd),
486
+ timer.measure("route-manifest", () => scanServerManifestDrift(cwd)),
487
+ timer.measure("contracts", () => collectContractFacts(cwd)),
458
488
  ])
489
+ const analysisStarted = performance.now()
459
490
 
460
491
  // tsc compiles TypeScript sources only; the JavaScript and component files the scan reads are no
461
492
  // program's to cover.
@@ -493,7 +524,9 @@ async function buildProjectScan(
493
524
  routePaths.push(...scanUnresolvedRoutePaths(file, content, project, sourceFacts))
494
525
  responseRoutes.push(...scanResponseRoutes(file, content, sourceFacts, project))
495
526
  if (sqlCompiler !== undefined)
496
- interpolatedSql.push(...scanSqlSites(file, content, sqlCompiler, sqlImports))
527
+ interpolatedSql.push(
528
+ ...scanSqlSites(file, content, sqlCompiler, sqlImports, sourceFacts?.parse),
529
+ )
497
530
  }
498
531
 
499
532
  const projectPath = (path: string): string => {
@@ -508,6 +541,8 @@ async function buildProjectScan(
508
541
  return resolved === undefined ? undefined : projectPath(resolved)
509
542
  }
510
543
  const readModule: ModuleReader = (path) => {
544
+ const current = project.get(path)
545
+ if (current !== undefined) return current
511
546
  let text: string
512
547
  try {
513
548
  text = readFileSync(isAbsolute(path) ? path : join(cwd, path), "utf8")
@@ -594,6 +629,7 @@ async function buildProjectScan(
594
629
  routePaths,
595
630
  },
596
631
  }
632
+ timer.record("source-analysis", analysisStarted)
597
633
  return { facts }
598
634
  } catch (error) {
599
635
  await loadedTypeScript.session?.close()
@@ -612,7 +648,11 @@ export async function collectCheckResult(
612
648
  const cwd = resolve(root)
613
649
  const scan = await buildProjectScan(cwd, opts)
614
650
  try {
615
- return await collectCheckDiagnostics(cwd, scan, opts)
651
+ if (opts.timer === undefined) return await collectCheckDiagnostics(cwd, scan, opts)
652
+ const result = await opts.timer.measure("diagnostics", () =>
653
+ collectCheckDiagnostics(cwd, scan, opts),
654
+ )
655
+ return Object.assign(result, { timings: opts.timer.snapshot() })
616
656
  } finally {
617
657
  await scan.facts.check.typescriptSession?.close()
618
658
  }
@@ -777,6 +817,11 @@ export function renderCheckReport(result: CheckResult): string[] {
777
817
  `• showing ${result.truncated.shown} of ${result.truncated.total} diagnostics (truncated)`,
778
818
  )
779
819
  }
820
+ if (result.timings !== undefined) {
821
+ lines.push("", `check took ${result.timings.totalMs} ms (phases may overlap)`)
822
+ for (const [phase, elapsed] of Object.entries(result.timings.phasesMs))
823
+ lines.push(` ${phase} ${elapsed} ms`)
824
+ }
780
825
  const errors = result.diagnostics.filter((d) => d.severity === "error").length
781
826
  const warnings = result.diagnostics.filter((d) => d.severity === "warning").length
782
827
  const rest = belowError(warnings, result.diagnostics.length - errors - warnings)
package/src/cli.ts CHANGED
@@ -169,7 +169,7 @@ Usage:
169
169
  no longer hand-writes build-<target>.ts + _worker.ts +
170
170
  _routes.json. The server entry is generated from your
171
171
  backend/framework.ts (adapter) + backend/app.ts + routes/.
172
- --report prints a per-chunk size + gzip table (biggest first).
172
+ --report prints chunk sizes and initial client assets by route.
173
173
  Vercel defaults to Edge; export vercelRuntime = "node" from
174
174
  nifra.config.ts for ordinary Node.js 22 serverless SSR.
175
175
  [--vite | --bun] Force the bundler. Without a flag it follows your config: Bun
@@ -237,11 +237,12 @@ Usage:
237
237
  nifra runtime [<runtime>] [<symptom>] [--json]
238
238
  Print where Bun, Node, Deno and Workers differ (the human view of
239
239
  nifra_runtime): cause, fix and how to verify, with measured versions.
240
- nifra check [--json] [--sarif] [--lints-only]
240
+ nifra check [--json] [--sarif] [--lints-only] [--incremental] [--timings]
241
241
  Gate: typecheck + lints (hand-rolled fetch(), untyped client("…"),
242
242
  backend code in browser code). Run as "done"; --json for agents;
243
243
  --sarif emits the same stable diagnostics as SARIF 2.1.0 for external
244
244
  review tools; --lints-only skips tsc for a near-instant inner-loop pass.
245
+ --incremental reuses local compiler state; --timings reports phase times.
245
246
  With a contracts.lock.json, both modes import backend/app.ts
246
247
  (running its top-level code) to compare the routes it serves.
247
248
  nifra verify [--release] [--json] Run the shared repository verification gate. --release runs the
@@ -288,10 +289,9 @@ Usage:
288
289
  Compute the verification ladder (L0 typed contract → L1 route
289
290
  assurance → L2 capability lockfile → L3 route manifest → L4
290
291
  invariant-tested); --min <n> fails the exit code below level n.
291
- nifra prove [--json] [--file <path>] [--min <n>]
292
- Build the static verification work graph, plan the cheapest
293
- proofs for changed files, and report a machine-checkable stop
294
- condition. Requires a fresh build; never probes a running app.
292
+ nifra prove [--json] [--file <path>] [--min <n>] [--run]
293
+ Plan cumulative verification gates. With --run, execute them
294
+ and bind the results to the source and build digests.
295
295
  nifra doctor [--json] [--auto-fix] Flag undeclared imports and multiple physical copies of
296
296
  [--strict] [--target] @nifrajs/core/React identity-sensitive dependencies;
297
297
  print production readiness, with --strict making absent
@@ -368,7 +368,7 @@ set in the process environment is never overwritten by a file.
368
368
  ${renderCommandCatalogHelp()}`
369
369
 
370
370
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
371
- const CLI_VERSION = "5.15.1"
371
+ const CLI_VERSION = "5.16.0"
372
372
 
373
373
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
374
374
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
@@ -646,6 +646,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
646
646
  clientEntry,
647
647
  ...frameworkWebAppOptions(fw, backend),
648
648
  onLoaderError: dev.onLoaderError,
649
+ routeTiming: dev.routeTiming,
649
650
  }),
650
651
  })
651
652
  console.log(`nifra dev (bun) → http://localhost:${server.port}`)
@@ -710,6 +711,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
710
711
  clientEntry,
711
712
  ...frameworkWebAppOptions(fw, backend),
712
713
  onLoaderError: dev.onLoaderError,
714
+ routeTiming: dev.routeTiming,
713
715
  }),
714
716
  })
715
717
  console.log(`nifra dev (vite) → http://localhost:${server.port}`)
@@ -848,7 +850,7 @@ async function buildForTarget(
848
850
  app: LoadedApp,
849
851
  flag: string | undefined,
850
852
  flags: Flags,
851
- ): Promise<void> {
853
+ ): Promise<string> {
852
854
  const {
853
855
  buildWithDeploymentAdapter,
854
856
  isBuildTarget,
@@ -967,7 +969,7 @@ async function buildForTarget(
967
969
  ? `[nifra/components] Built ${fw.componentPipeline.adapter} for ${target} (${result.build}) in ${outDir}`
968
970
  : `[nifra/components] Built ${componentPipeline.adapter} for ${adapter!.id} (base ${target}, ${result.build}) in ${outDir}\n from output directory: ${adapterRun}`,
969
971
  )
970
- return
972
+ return outDir
971
973
  }
972
974
  const cssCodeSplitRequested = fw.cssCodeSplit === false
973
975
  const hasBunTransforms =
@@ -1052,6 +1054,7 @@ async function buildForTarget(
1052
1054
  ...(fw.clientIp !== undefined ? { clientIp: fw.clientIp } : {}),
1053
1055
  ...(fw.vercelRuntime !== undefined ? { vercelRuntime: fw.vercelRuntime } : {}),
1054
1056
  ...(fw.selfHost !== undefined ? { selfHost: fw.selfHost } : {}),
1057
+ reportRouteAssets: flags.report,
1055
1058
  live: fw.live?.clientEntry,
1056
1059
  ...transportOption(flags, fw, cwd),
1057
1060
  prerenderPaths: prerenderPaths(flags, target),
@@ -1103,6 +1106,7 @@ async function buildForTarget(
1103
1106
  // must never look like the default, and a default Bun build must not leave the question open either.
1104
1107
  console.log(` ${describePipeline(decision)}`)
1105
1108
  if (flags.report) console.log(`\n${renderSizeReport(result.size)}`)
1109
+ return outDir
1106
1110
  }
1107
1111
 
1108
1112
  /** Build the app FACTORY for the prerender pass of the `static`, `bun` and `node` targets. Registers the
@@ -1635,7 +1639,16 @@ async function main(): Promise<void> {
1635
1639
  }
1636
1640
  const flags = parseFlags(argv.slice(1))
1637
1641
  try {
1638
- const app = await loadApp(process.cwd(), flags.out)
1642
+ const cwd = process.cwd()
1643
+ const provenance =
1644
+ command === "build" && existsSync(resolve(cwd, BACKEND_APP_FILE))
1645
+ ? await import("./build-provenance.ts")
1646
+ : undefined
1647
+ const buildInputs = await provenance?.fingerprintBuildInputs(
1648
+ cwd,
1649
+ resolve(cwd, flags.out ?? "dist"),
1650
+ )
1651
+ const app = await loadApp(cwd, flags.out)
1639
1652
  if (command !== "start" && process.env.NIFRA_BUN_DEV_TOKEN === undefined) {
1640
1653
  const { unservedRoutesWarning } = await import("./introspect.ts")
1641
1654
  const unserved = unservedRoutesWarning(app)
@@ -1649,8 +1662,16 @@ async function main(): Promise<void> {
1649
1662
  watchRouteTypes(app.cwd)
1650
1663
  }
1651
1664
  if (command === "dev") await dev(app, flags)
1652
- else if (command === "build") await buildForTarget(app, flags.target, flags)
1653
- else await start(app, flags)
1665
+ else if (command === "build") {
1666
+ const outDir = await buildForTarget(app, flags.target, flags)
1667
+ if (
1668
+ provenance !== undefined &&
1669
+ buildInputs !== undefined &&
1670
+ !(await provenance.recordBuildProvenance(cwd, outDir, buildInputs))
1671
+ ) {
1672
+ console.warn("[nifra] source changed during the build. Rebuild before running nifra prove.")
1673
+ }
1674
+ } else await start(app, flags)
1654
1675
  } finally {
1655
1676
  // `dev` and `start` keep serving after they return; a build is over.
1656
1677
  if (command === "build") exitIfHeldOpen(command)