@nifrajs/cli 5.1.0 → 5.3.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 (230) hide show
  1. package/CHANGELOG.md +3313 -0
  2. package/README.md +3 -0
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +7 -2
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts.map +1 -1
  11. package/dist/assure.js +14 -1
  12. package/dist/assure.js.map +1 -1
  13. package/dist/capabilities-tool.d.ts.map +1 -1
  14. package/dist/capabilities-tool.js +131 -45
  15. package/dist/capabilities-tool.js.map +1 -1
  16. package/dist/check-diagnostics.d.ts +5 -0
  17. package/dist/check-diagnostics.d.ts.map +1 -1
  18. package/dist/check-diagnostics.js +5 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts +9 -3
  21. package/dist/check-scan.d.ts.map +1 -1
  22. package/dist/check-scan.js +61 -21
  23. package/dist/check-scan.js.map +1 -1
  24. package/dist/check.d.ts.map +1 -1
  25. package/dist/check.js +55 -15
  26. package/dist/check.js.map +1 -1
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +37 -18
  29. package/dist/cli.js.map +1 -1
  30. package/dist/command-catalog.d.ts.map +1 -1
  31. package/dist/command-catalog.js +9 -5
  32. package/dist/command-catalog.js.map +1 -1
  33. package/dist/db-tool.d.ts.map +1 -1
  34. package/dist/db-tool.js +2 -1
  35. package/dist/db-tool.js.map +1 -1
  36. package/dist/dev-bun-config.d.ts +6 -3
  37. package/dist/dev-bun-config.d.ts.map +1 -1
  38. package/dist/dev-bun-config.js +13 -10
  39. package/dist/dev-bun-config.js.map +1 -1
  40. package/dist/dev-feed-tool.d.ts +3 -2
  41. package/dist/dev-feed-tool.d.ts.map +1 -1
  42. package/dist/dev-feed-tool.js +26 -5
  43. package/dist/dev-feed-tool.js.map +1 -1
  44. package/dist/doctor.d.ts +15 -1
  45. package/dist/doctor.d.ts.map +1 -1
  46. package/dist/doctor.js +79 -61
  47. package/dist/doctor.js.map +1 -1
  48. package/dist/env-file.d.ts.map +1 -1
  49. package/dist/env-file.js +41 -8
  50. package/dist/env-file.js.map +1 -1
  51. package/dist/i18n-check.d.ts +11 -1
  52. package/dist/i18n-check.d.ts.map +1 -1
  53. package/dist/i18n-check.js +170 -17
  54. package/dist/i18n-check.js.map +1 -1
  55. package/dist/init-agents.d.ts +46 -6
  56. package/dist/init-agents.d.ts.map +1 -1
  57. package/dist/init-agents.js +193 -31
  58. package/dist/init-agents.js.map +1 -1
  59. package/dist/internal/project-specifiers.d.ts.map +1 -1
  60. package/dist/internal/project-specifiers.js +9 -1
  61. package/dist/internal/project-specifiers.js.map +1 -1
  62. package/dist/internal/source-facts.d.ts +22 -0
  63. package/dist/internal/source-facts.d.ts.map +1 -1
  64. package/dist/internal/source-facts.js +322 -0
  65. package/dist/internal/source-facts.js.map +1 -1
  66. package/dist/internal/workspace-packages.d.ts +22 -0
  67. package/dist/internal/workspace-packages.d.ts.map +1 -0
  68. package/dist/internal/workspace-packages.js +215 -0
  69. package/dist/internal/workspace-packages.js.map +1 -0
  70. package/dist/load.d.ts +7 -2
  71. package/dist/load.d.ts.map +1 -1
  72. package/dist/load.js +11 -2
  73. package/dist/load.js.map +1 -1
  74. package/dist/lock-links.d.ts +42 -0
  75. package/dist/lock-links.d.ts.map +1 -0
  76. package/dist/lock-links.js +144 -0
  77. package/dist/lock-links.js.map +1 -0
  78. package/dist/mcp-exec.d.ts +1 -0
  79. package/dist/mcp-exec.d.ts.map +1 -1
  80. package/dist/mcp-exec.js +16 -5
  81. package/dist/mcp-exec.js.map +1 -1
  82. package/dist/mcp-http.js +1 -1
  83. package/dist/mcp-io.d.ts +23 -3
  84. package/dist/mcp-io.d.ts.map +1 -1
  85. package/dist/mcp-io.js +59 -12
  86. package/dist/mcp-io.js.map +1 -1
  87. package/dist/mcp-isolate.d.ts.map +1 -1
  88. package/dist/mcp-isolate.js +2 -1
  89. package/dist/mcp-isolate.js.map +1 -1
  90. package/dist/mcp-root.d.ts +6 -4
  91. package/dist/mcp-root.d.ts.map +1 -1
  92. package/dist/mcp-root.js +12 -8
  93. package/dist/mcp-root.js.map +1 -1
  94. package/dist/migrate-layout.d.ts +2 -1
  95. package/dist/migrate-layout.d.ts.map +1 -1
  96. package/dist/migrate-layout.js +435 -29
  97. package/dist/migrate-layout.js.map +1 -1
  98. package/dist/project-site.d.ts +7 -0
  99. package/dist/project-site.d.ts.map +1 -0
  100. package/dist/project-site.js +19 -0
  101. package/dist/project-site.js.map +1 -0
  102. package/dist/recipes/4.0.0.d.ts.map +1 -1
  103. package/dist/recipes/4.0.0.js +2 -0
  104. package/dist/recipes/4.0.0.js.map +1 -1
  105. package/dist/recipes/5.1.0.d.ts +9 -0
  106. package/dist/recipes/5.1.0.d.ts.map +1 -0
  107. package/dist/recipes/5.1.0.js +22 -0
  108. package/dist/recipes/5.1.0.js.map +1 -0
  109. package/dist/recipes/5.2.0.d.ts +10 -0
  110. package/dist/recipes/5.2.0.d.ts.map +1 -0
  111. package/dist/recipes/5.2.0.js +32 -0
  112. package/dist/recipes/5.2.0.js.map +1 -0
  113. package/dist/recipes/5.3.0.d.ts +11 -0
  114. package/dist/recipes/5.3.0.d.ts.map +1 -0
  115. package/dist/recipes/5.3.0.js +35 -0
  116. package/dist/recipes/5.3.0.js.map +1 -0
  117. package/dist/recipes/index.d.ts +3 -0
  118. package/dist/recipes/index.d.ts.map +1 -1
  119. package/dist/recipes/index.js +9 -0
  120. package/dist/recipes/index.js.map +1 -1
  121. package/dist/review.d.ts.map +1 -1
  122. package/dist/review.js +4 -0
  123. package/dist/review.js.map +1 -1
  124. package/dist/rule-explain.d.ts +26 -0
  125. package/dist/rule-explain.d.ts.map +1 -0
  126. package/dist/rule-explain.js +49 -0
  127. package/dist/rule-explain.js.map +1 -0
  128. package/dist/rules/codes.d.ts +4 -0
  129. package/dist/rules/codes.d.ts.map +1 -1
  130. package/dist/rules/codes.js +4 -0
  131. package/dist/rules/codes.js.map +1 -1
  132. package/dist/rules/contract-visibility.d.ts.map +1 -1
  133. package/dist/rules/contract-visibility.js +93 -21
  134. package/dist/rules/contract-visibility.js.map +1 -1
  135. package/dist/rules/explanations.d.ts +14 -0
  136. package/dist/rules/explanations.d.ts.map +1 -0
  137. package/dist/rules/explanations.js +326 -0
  138. package/dist/rules/explanations.js.map +1 -0
  139. package/dist/rules/legacy.d.ts.map +1 -1
  140. package/dist/rules/legacy.js +24 -1
  141. package/dist/rules/legacy.js.map +1 -1
  142. package/dist/rules/merge-auth.d.ts +12 -0
  143. package/dist/rules/merge-auth.d.ts.map +1 -0
  144. package/dist/rules/merge-auth.js +52 -0
  145. package/dist/rules/merge-auth.js.map +1 -0
  146. package/dist/rules/pages.d.ts +51 -0
  147. package/dist/rules/pages.d.ts.map +1 -1
  148. package/dist/rules/pages.js +293 -2
  149. package/dist/rules/pages.js.map +1 -1
  150. package/dist/rules/route-statement.d.ts +10 -0
  151. package/dist/rules/route-statement.d.ts.map +1 -0
  152. package/dist/rules/route-statement.js +150 -0
  153. package/dist/rules/route-statement.js.map +1 -0
  154. package/dist/rules/routes.d.ts +3 -2
  155. package/dist/rules/routes.d.ts.map +1 -1
  156. package/dist/rules/routes.js +4 -3
  157. package/dist/rules/routes.js.map +1 -1
  158. package/dist/rules/zones.d.ts.map +1 -1
  159. package/dist/rules/zones.js +3 -2
  160. package/dist/rules/zones.js.map +1 -1
  161. package/dist/typecheck-coverage.d.ts +11 -0
  162. package/dist/typecheck-coverage.d.ts.map +1 -1
  163. package/dist/typecheck-coverage.js +50 -7
  164. package/dist/typecheck-coverage.js.map +1 -1
  165. package/dist/upgrade.d.ts +80 -11
  166. package/dist/upgrade.d.ts.map +1 -1
  167. package/dist/upgrade.js +332 -65
  168. package/dist/upgrade.js.map +1 -1
  169. package/dist/verification-plan.d.ts.map +1 -1
  170. package/dist/verification-plan.js +2 -0
  171. package/dist/verification-plan.js.map +1 -1
  172. package/dist/version-drift.d.ts.map +1 -1
  173. package/dist/version-drift.js +12 -1
  174. package/dist/version-drift.js.map +1 -1
  175. package/dist/web-app-options.d.ts +1 -1
  176. package/dist/web-app-options.d.ts.map +1 -1
  177. package/dist/web-app-options.js.map +1 -1
  178. package/docs/examples.json +19 -1
  179. package/docs/llms-full.txt +716 -138
  180. package/docs/types.json +516 -74
  181. package/package.json +13 -12
  182. package/src/agent-files.ts +27 -17
  183. package/src/assure-hydration.ts +8 -1
  184. package/src/assure.ts +11 -1
  185. package/src/capabilities-tool.ts +159 -50
  186. package/src/check-diagnostics.ts +10 -0
  187. package/src/check-scan.ts +64 -19
  188. package/src/check.ts +75 -15
  189. package/src/cli.ts +38 -17
  190. package/src/command-catalog.ts +16 -8
  191. package/src/db-tool.ts +2 -0
  192. package/src/dev-bun-config.ts +13 -9
  193. package/src/dev-feed-tool.ts +40 -6
  194. package/src/doctor.ts +102 -66
  195. package/src/env-file.ts +42 -7
  196. package/src/i18n-check.ts +254 -18
  197. package/src/init-agents.ts +221 -41
  198. package/src/internal/project-specifiers.ts +9 -1
  199. package/src/internal/source-facts.ts +397 -0
  200. package/src/internal/workspace-packages.ts +218 -0
  201. package/src/load.ts +19 -3
  202. package/src/lock-links.ts +173 -0
  203. package/src/mcp-exec.ts +18 -4
  204. package/src/mcp-http.ts +1 -1
  205. package/src/mcp-io.ts +72 -12
  206. package/src/mcp-isolate.ts +2 -0
  207. package/src/mcp-root.ts +14 -8
  208. package/src/migrate-layout.ts +496 -31
  209. package/src/project-site.ts +18 -0
  210. package/src/recipes/4.0.0.ts +2 -0
  211. package/src/recipes/5.1.0.ts +23 -0
  212. package/src/recipes/5.2.0.ts +33 -0
  213. package/src/recipes/5.3.0.ts +36 -0
  214. package/src/recipes/index.ts +9 -0
  215. package/src/review.ts +4 -0
  216. package/src/rule-explain.ts +75 -0
  217. package/src/rules/codes.ts +4 -0
  218. package/src/rules/contract-visibility.ts +118 -20
  219. package/src/rules/explanations.ts +339 -0
  220. package/src/rules/legacy.ts +24 -1
  221. package/src/rules/merge-auth.ts +55 -0
  222. package/src/rules/pages.ts +381 -2
  223. package/src/rules/route-statement.ts +170 -0
  224. package/src/rules/routes.ts +4 -3
  225. package/src/rules/zones.ts +3 -2
  226. package/src/typecheck-coverage.ts +51 -6
  227. package/src/upgrade.ts +430 -70
  228. package/src/verification-plan.ts +6 -0
  229. package/src/version-drift.ts +15 -0
  230. package/src/web-app-options.ts +9 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nifrajs/cli",
3
- "version": "5.1.0",
3
+ "version": "5.3.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",
@@ -58,7 +58,8 @@
58
58
  "files": [
59
59
  "dist",
60
60
  "src",
61
- "docs"
61
+ "docs",
62
+ "CHANGELOG.md"
62
63
  ],
63
64
  "sideEffects": false,
64
65
  "scripts": {
@@ -69,16 +70,16 @@
69
70
  "access": "public"
70
71
  },
71
72
  "dependencies": {
72
- "@nifrajs/client": "5.1.0",
73
- "@nifrajs/core": "5.1.0",
74
- "@nifrajs/agent-review": "5.1.0",
75
- "@nifrajs/i18n": "5.1.0",
76
- "@nifrajs/mcp": "5.1.0",
77
- "@nifrajs/mcp-db": "5.1.0",
78
- "@nifrajs/runner": "5.1.0",
79
- "@nifrajs/schema": "5.1.0",
80
- "@nifrajs/testing": "5.1.0",
81
- "@nifrajs/web": "5.1.0"
73
+ "@nifrajs/client": "5.3.0",
74
+ "@nifrajs/core": "5.3.0",
75
+ "@nifrajs/agent-review": "5.3.0",
76
+ "@nifrajs/i18n": "5.3.0",
77
+ "@nifrajs/mcp": "5.3.0",
78
+ "@nifrajs/mcp-db": "5.3.0",
79
+ "@nifrajs/runner": "5.3.0",
80
+ "@nifrajs/schema": "5.3.0",
81
+ "@nifrajs/testing": "5.3.0",
82
+ "@nifrajs/web": "5.3.0"
82
83
  },
83
84
  "repository": {
84
85
  "type": "git",
@@ -40,14 +40,17 @@ export const MCP_SERVER_COMMAND = "bunx" as const
40
40
  * (`../package.json` → the same root, since `dist/` sits beside the manifest). npm always ships a
41
41
  * package's own `package.json`, so the read can't miss at install time.
42
42
  *
43
- * Why pin at all instead of `bunx @nifrajs/cli mcp`: `bunx` keys its cache on the exact version spec.
44
- * An UNPINNED spec resolves to the `latest` tag once, then `bunx` reuses that cached copy on every
45
- * later spawn WITHOUT re-checking the registry - so an editor that once launched an older `@nifrajs/cli`
46
- * keeps respawning the stale binary even after a newer one is published (the MCP server silently runs
47
- * old code). Pinning the exact version makes the version part of the cache key, so each release fetches
48
- * fresh and a stale cache can never shadow it. The cost: an already-scaffolded app's `.mcp.json` freezes
49
- * at its scaffold-time version until `nifra init-agents --sync-mcp` re-pins it to the nifra the project
50
- * installs - an acceptable, deterministic trade.
43
+ * Two launch forms. A project that declares `@nifrajs/cli` gets the unpinned
44
+ * `bunx @nifrajs/cli mcp` ({@link MCP_SERVER_ARGS_INSTALLED}): `bunx` runs the copy the project installs
45
+ * (its `node_modules`, or an ancestor's) whenever there is one, so an upgrade moves the server with it
46
+ * and nothing needs re-pinning. A pinned spec never does that, not even at the installed version: it
47
+ * always runs a registry copy. Every scaffold declares the CLI, so every scaffold is unpinned.
48
+ *
49
+ * A project that does not declare it keeps the pin ({@link MCP_SERVER_ARGS}): with no local install an
50
+ * unpinned spec resolves `latest` once and `bunx` reuses that cached copy on every later spawn without
51
+ * re-checking the registry, so the server would silently run old code. The exact version is part of the
52
+ * cache key, so each release fetches fresh; `nifra init-agents --sync-mcp` moves it to the installed
53
+ * nifra, or unpins it once the project declares the CLI.
51
54
  */
52
55
  export const MCP_CLI_VERSION: string = ownVersion()
53
56
 
@@ -66,6 +69,9 @@ function ownVersion(): string {
66
69
  }
67
70
  export const MCP_SERVER_ARGS = [`@nifrajs/cli@${MCP_CLI_VERSION}`, "mcp"] as const
68
71
 
72
+ /** The launch args for a project that declares `@nifrajs/cli`: unpinned, so `bunx` runs its install. */
73
+ export const MCP_SERVER_ARGS_INSTALLED = ["@nifrajs/cli", "mcp"] as const
74
+
69
75
  /** The server entry registered under the `nifra` key in both Claude Code's and Cursor's MCP config. */
70
76
  export interface McpServerConfig {
71
77
  readonly command: string
@@ -77,17 +83,20 @@ export interface McpConfig {
77
83
  readonly mcpServers: Readonly<Record<string, McpServerConfig>>
78
84
  }
79
85
 
80
- /** The one canonical MCP config object both registries serialize - the anti-drift seam. */
81
- export const MCP_CONFIG: McpConfig = {
82
- mcpServers: {
83
- nifra: { command: MCP_SERVER_COMMAND, args: [...MCP_SERVER_ARGS] },
84
- },
86
+ /** The one canonical MCP config both registries serialize - the anti-drift seam. `pin` is the
87
+ * `@nifrajs/cli` version to pin; without one the launch follows the project's install. */
88
+ export function mcpConfig(pin?: string): McpConfig {
89
+ const args = pin === undefined ? MCP_SERVER_ARGS_INSTALLED : [`@nifrajs/cli@${pin}`, "mcp"]
90
+ return { mcpServers: { nifra: { command: MCP_SERVER_COMMAND, args: [...args] } } }
85
91
  }
86
92
 
93
+ /** The config a scaffold writes: every scaffold declares the CLI, so its launch is unpinned. */
94
+ export const MCP_CONFIG: McpConfig = mcpConfig()
95
+
87
96
  /** Serialize the canonical MCP config as the JSON written to `.mcp.json` and `.cursor/mcp.json`.
88
97
  * Trailing newline so the file is POSIX-clean and diffs don't flag a missing EOL. */
89
- export function mcpJson(): string {
90
- return `${JSON.stringify(MCP_CONFIG, null, 2)}\n`
98
+ export function mcpJson(pin?: string): string {
99
+ return `${JSON.stringify(mcpConfig(pin), null, 2)}\n`
91
100
  }
92
101
 
93
102
  const POINTER_INTRO =
@@ -118,10 +127,11 @@ export function copilotInstructions(): string {
118
127
  * agents (Cursor, and anything that reads `AGENTS.md`) also learn the MCP exists and what to prefer.
119
128
  * Mirrors the CLAUDE.md preamble's guidance without the Claude-specific `@import`.
120
129
  */
121
- export function agentsMcpSection(): string {
130
+ export function agentsMcpSection(pin?: string): string {
131
+ const args = pin === undefined ? MCP_SERVER_ARGS_INSTALLED : [`@nifrajs/cli@${pin}`, "mcp"]
122
132
  return `## MCP server
123
133
 
124
- This project ships a **nifra MCP server** - launch it with \`${MCP_SERVER_COMMAND} ${MCP_SERVER_ARGS.join(" ")}\`. It's registered for
134
+ This project ships a **nifra MCP server** - launch it with \`${MCP_SERVER_COMMAND} ${args.join(" ")}\`. It's registered for
125
135
  Claude Code in \`.mcp.json\` and for Cursor in \`.cursor/mcp.json\`; other agents can point their MCP client
126
136
  at that command. **Prefer its tools** over writing nifra from memory - they're typechecked against this
127
137
  project + the installed version, so they beat training-data recall:
@@ -20,6 +20,8 @@ import {
20
20
  readBoundedStream,
21
21
  readHeadTail,
22
22
  signalProcessGroup,
23
+ stopGroupAndWait,
24
+ stopGroupOnExit,
23
25
  } from "./mcp-io.ts"
24
26
  import { frameworkWebAppOptions } from "./web-app-options.ts"
25
27
 
@@ -216,6 +218,7 @@ async function buildHydrationApp(cwd: string): Promise<BuiltHydrationApp | { ski
216
218
  manifest: discoverRoutes(loaded.routesDir),
217
219
  clientEntry: client.entry,
218
220
  ...frameworkWebAppOptions(loaded.framework, loaded.backend),
221
+ ...(client.copyChunks === undefined ? {} : { copyChunks: client.copyChunks }),
219
222
  }) as unknown as AppLike
220
223
  return {
221
224
  app: webApp,
@@ -648,6 +651,7 @@ export async function runHydrationAssurance(
648
651
  detached: OWN_PROCESS_GROUP,
649
652
  },
650
653
  )
654
+ stopGroupOnExit(proc)
651
655
  const stopper = escalatingStop((name) => signalProcessGroup(proc, name))
652
656
  let stopped: string | undefined
653
657
  const stop = (reason: string): void => {
@@ -656,7 +660,10 @@ export async function runHydrationAssurance(
656
660
  }
657
661
  const onAbort = (): void => stop("cancelled")
658
662
  control.signal?.addEventListener("abort", onAbort, { once: true })
659
- const releaseSignals = forwardTerminalSignals(() => stop("interrupted"))
663
+ const releaseSignals = forwardTerminalSignals(() => {
664
+ stopped ??= "interrupted"
665
+ return stopGroupAndWait(proc)
666
+ })
660
667
  const timeoutMs = control.timeoutMs ?? HYDRATION_RUN_TIMEOUT_MS
661
668
  const timer = setTimeout(() => stop(`timed out after ${timeoutMs} ms`), timeoutMs)
662
669
  try {
package/src/assure.ts CHANGED
@@ -84,7 +84,17 @@ export async function loadAssuranceConfig(
84
84
  }
85
85
  const specifier = pathToFileURL(path)
86
86
  specifier.searchParams.set("nifra-assurance", String(Date.now()))
87
- const loaded = (await import(specifier.href)) as { default?: unknown }
87
+ // Core records each route's registering module while this is set, for the capability walk. Scoped to
88
+ // the load: a module already imported in this process keeps what it recorded then.
89
+ const priorSites = process.env.NIFRA_ROUTE_SITES
90
+ process.env.NIFRA_ROUTE_SITES = "1"
91
+ let loaded: { default?: unknown }
92
+ try {
93
+ loaded = (await import(specifier.href)) as { default?: unknown }
94
+ } finally {
95
+ if (priorSites === undefined) delete process.env.NIFRA_ROUTE_SITES
96
+ else process.env.NIFRA_ROUTE_SITES = priorSites
97
+ }
88
98
  if (!isConfig(loaded.default)) {
89
99
  throw new Error(
90
100
  `[nifra] ${displayPath(path)} must default-export defineAssuranceConfig({ source, policy }).`,
@@ -17,7 +17,12 @@ import {
17
17
  validCapabilityId,
18
18
  } from "@nifrajs/core/capabilities"
19
19
  import { expandOptionalParams } from "@nifrajs/core/pattern"
20
- import { type ReflectedMount, type ReflectedRoute, reflectRoutes } from "@nifrajs/core/reflection"
20
+ import {
21
+ type ReflectedMount,
22
+ type ReflectedRoute,
23
+ reflectRouteSites,
24
+ reflectRoutes,
25
+ } from "@nifrajs/core/reflection"
21
26
  import {
22
27
  scanSkippedRouteText,
23
28
  scanStaticRouteText,
@@ -25,6 +30,7 @@ import {
25
30
  stripComments,
26
31
  walkSource,
27
32
  } from "./check.ts"
33
+ import { projectSite } from "./project-site.ts"
28
34
 
29
35
  // Import and re-export clauses are spelled out (a default binding, then `* as ns` or a `{ … }` list)
30
36
  // rather than scanned lazily, which is quadratic on a long semicolon-free module.
@@ -238,14 +244,113 @@ interface WalkResult {
238
244
 
239
245
  const MAX_PROVENANCE_MODULES = 500
240
246
  const MAX_PROVENANCE_CHAIN = 16
247
+ /** The budget for one installed package's closure, walked once per run whatever reaches it. */
248
+ const MAX_INSTALLED_MODULES = 5000
249
+
250
+ /** An effect import one module makes, and the policy rules it matches. */
251
+ interface EffectHit {
252
+ readonly specifier: string
253
+ readonly module: string
254
+ /** Specifiers from the walk's entry to this import, the import last. */
255
+ readonly chain: readonly string[]
256
+ readonly approved: readonly CapabilityPolicy["provenance"]["imports"][number][]
257
+ readonly forbidden: readonly CapabilityPolicy["provenance"]["forbiddenImports"][number][]
258
+ }
259
+
260
+ /** What a walk reads, shared by every route of one run: sources, and installed closures by entry. */
261
+ interface WalkContext {
262
+ readonly cwd: string
263
+ readonly policy: CapabilityPolicy
264
+ readonly sources: Map<string, string>
265
+ readonly installed: Map<string, Promise<InstalledWalk>>
266
+ }
267
+
268
+ interface InstalledWalk {
269
+ readonly hits: readonly EffectHit[]
270
+ readonly truncated: boolean
271
+ }
272
+
273
+ /** A module under a `node_modules` folder: installed code, the same for every route that reaches it. */
274
+ const isInstalled = (module: string): boolean => module.split("/").includes("node_modules")
275
+
276
+ async function moduleSource(context: WalkContext, module: string): Promise<string | undefined> {
277
+ const cached = context.sources.get(module)
278
+ if (cached !== undefined) return cached
279
+ try {
280
+ const content = await Bun.file(join(context.cwd, module)).text()
281
+ context.sources.set(module, content)
282
+ return content
283
+ } catch {
284
+ return undefined
285
+ }
286
+ }
287
+
288
+ /**
289
+ * The effect imports one module makes, each with the rules it matches, and the modules its other
290
+ * imports load. An approved import is the owned effect seam: its implementation may legitimately
291
+ * import the raw provider, so the walk does not follow it.
292
+ */
293
+ function scanModule(
294
+ context: WalkContext,
295
+ module: string,
296
+ content: string,
297
+ chain: readonly string[],
298
+ ): { readonly hits: EffectHit[]; readonly next: Array<{ module: string; specifier: string }> } {
299
+ const hits: EffectHit[] = []
300
+ const next: Array<{ module: string; specifier: string }> = []
301
+ for (const specifier of scanEffectImports(content)) {
302
+ const approved = context.policy.provenance.imports.filter((rule) =>
303
+ specifierMatches(rule.specifier, specifier),
304
+ )
305
+ const forbidden = context.policy.provenance.forbiddenImports.filter((rule) =>
306
+ specifierMatches(rule.specifier, specifier),
307
+ )
308
+ if (approved.length > 0 || forbidden.length > 0)
309
+ hits.push({ specifier, module, chain: [...chain, specifier], approved, forbidden })
310
+ if (approved.length > 0) continue
311
+ const local = resolveLocalModule(context.cwd, module, specifier, context.sources)
312
+ if (local !== undefined) next.push({ module: local, specifier })
313
+ }
314
+ return { hits, next }
315
+ }
316
+
317
+ /**
318
+ * Every effect import in the closure of the installed module `entry`, walked once per run however many
319
+ * routes reach it. Its chains start after `entry`. A package's own module count stays out of each
320
+ * route's budget: one locale-heavy dependency would otherwise truncate every route that imports it.
321
+ */
322
+ function walkInstalled(context: WalkContext, entry: string): Promise<InstalledWalk> {
323
+ const cached = context.installed.get(entry)
324
+ if (cached !== undefined) return cached
325
+ const walk = (async (): Promise<InstalledWalk> => {
326
+ const hits: EffectHit[] = []
327
+ const visited = new Set<string>()
328
+ const queue: Array<{ module: string; chain: readonly string[] }> = [
329
+ { module: entry, chain: [] },
330
+ ]
331
+ while (queue.length > 0) {
332
+ if (visited.size >= MAX_INSTALLED_MODULES) return { hits, truncated: true }
333
+ const current = queue.shift()
334
+ if (current === undefined || visited.has(current.module)) continue
335
+ visited.add(current.module)
336
+ const content = await moduleSource(context, current.module)
337
+ if (content === undefined) continue
338
+ const scanned = scanModule(context, current.module, content, current.chain)
339
+ hits.push(...scanned.hits)
340
+ for (const { module, specifier } of scanned.next)
341
+ if (!visited.has(module)) queue.push({ module, chain: [...current.chain, specifier] })
342
+ }
343
+ return { hits, truncated: false }
344
+ })()
345
+ context.installed.set(entry, walk)
346
+ return walk
347
+ }
241
348
 
242
349
  async function walkRouteModules(
243
- cwd: string,
350
+ context: WalkContext,
244
351
  modules: readonly string[],
245
352
  method: string,
246
353
  path: string,
247
- policy: CapabilityPolicy,
248
- sources: Map<string, string>,
249
354
  ): Promise<WalkResult> {
250
355
  const queue = modules.map((module) => ({ module, chain: [module] as string[] }))
251
356
  const visited = new Set<string>()
@@ -253,6 +358,25 @@ async function walkRouteModules(
253
358
  const violations: CapabilityImportViolation[] = []
254
359
  const truncations: CapabilityProvenanceTruncation[] = []
255
360
  let covered = false
361
+ const record = (hit: EffectHit, chain: readonly string[]): void => {
362
+ for (const rule of hit.approved) {
363
+ for (const id of rule.capabilities) {
364
+ if (!evidence.some((item) => item.id === id && item.source === hit.specifier)) {
365
+ evidence.push({ id, kind: "static", source: hit.specifier })
366
+ }
367
+ }
368
+ }
369
+ for (const rule of hit.forbidden) {
370
+ violations.push({
371
+ method,
372
+ path,
373
+ module: hit.module,
374
+ specifier: hit.specifier,
375
+ reason: rule.reason,
376
+ chain: Object.freeze([...chain, ...hit.chain]),
377
+ })
378
+ }
379
+ }
256
380
 
257
381
  while (queue.length > 0) {
258
382
  if (visited.size >= MAX_PROVENANCE_MODULES) {
@@ -280,45 +404,30 @@ async function walkRouteModules(
280
404
  continue
281
405
  }
282
406
  visited.add(current.module)
283
- let content = sources.get(current.module)
284
- if (content === undefined) {
285
- try {
286
- content = await Bun.file(join(cwd, current.module)).text()
287
- sources.set(current.module, content)
288
- } catch {
289
- continue
290
- }
291
- }
292
- covered = true
293
- for (const specifier of scanEffectImports(content)) {
294
- let approvedEffectBoundary = false
295
- for (const rule of policy.provenance.imports) {
296
- if (!specifierMatches(rule.specifier, specifier)) continue
297
- approvedEffectBoundary = true
298
- for (const id of rule.capabilities) {
299
- if (!evidence.some((item) => item.id === id && item.source === specifier)) {
300
- evidence.push({ id, kind: "static", source: specifier })
301
- }
302
- }
303
- }
304
- for (const rule of policy.provenance.forbiddenImports) {
305
- if (!specifierMatches(rule.specifier, specifier)) continue
306
- violations.push({
407
+ if (isInstalled(current.module)) {
408
+ const installed = await walkInstalled(context, current.module)
409
+ covered = true
410
+ for (const hit of installed.hits) record(hit, current.chain)
411
+ if (installed.truncated) {
412
+ truncations.push({
307
413
  method,
308
414
  path,
309
- module: current.module,
310
- specifier,
311
- reason: rule.reason,
312
- chain: Object.freeze([...current.chain, specifier]),
415
+ reason: "module-limit",
416
+ chain: Object.freeze([
417
+ ...current.chain,
418
+ `<${MAX_INSTALLED_MODULES}-module limit in ${current.module}>`,
419
+ ]),
313
420
  })
314
421
  }
315
- // An explicitly mapped import is the owned effect seam. Its implementation may legitimately
316
- // import the raw provider; assurance governs whether routes can reach the seam, not its internals.
317
- if (approvedEffectBoundary) continue
318
- const local = resolveLocalModule(cwd, current.module, specifier, sources)
319
- if (local !== undefined && !visited.has(local)) {
320
- queue.push({ module: local, chain: [...current.chain, specifier] })
321
- }
422
+ continue
423
+ }
424
+ const content = await moduleSource(context, current.module)
425
+ if (content === undefined) continue
426
+ covered = true
427
+ const scanned = scanModule(context, current.module, content, [])
428
+ for (const hit of scanned.hits) record(hit, current.chain)
429
+ for (const { module, specifier } of scanned.next) {
430
+ if (!visited.has(module)) queue.push({ module, chain: [...current.chain, specifier] })
322
431
  }
323
432
  }
324
433
  return { covered, evidence, violations, truncations }
@@ -345,6 +454,7 @@ export async function collectCapabilityProjectReport(
345
454
  ): Promise<CapabilityProjectReport> {
346
455
  const policy = defineCapabilityPolicy(policyInput)
347
456
  const sources = await readSources(cwd)
457
+ const context: WalkContext = { cwd, policy, sources, installed: new Map() }
348
458
  const automatic = new Map<string, Set<string>>()
349
459
  const skipped = new Map<string, string>()
350
460
  for (const [file, content] of sources) {
@@ -371,8 +481,13 @@ export async function collectCapabilityProjectReport(
371
481
  const violations: CapabilityImportViolation[] = []
372
482
  const truncations: CapabilityProvenanceTruncation[] = []
373
483
  const reflectedRoutes = options.routes ?? reflectRoutes(source)
484
+ // The module that registered each route, recorded while the app loaded: it covers the paths the
485
+ // text scan cannot read (a template literal, a server a helper builds).
486
+ const registered = reflectRouteSites(source)
374
487
  for (const route of reflectedRoutes) {
375
488
  const modules = new Set(automatic.get(routeKey(route.method, route.path)) ?? [])
489
+ const site = projectSite(cwd, registered.get(`${route.method} ${route.path}`))?.file
490
+ if (site !== undefined && sources.has(site)) modules.add(site)
376
491
  for (const association of policy.provenance.routeModules ?? []) {
377
492
  if (
378
493
  matchesAssuranceSelector(route, {
@@ -385,21 +500,15 @@ export async function collectCapabilityProjectReport(
385
500
  for (const module of association.modules) modules.add(module)
386
501
  }
387
502
  }
388
- const walked = await walkRouteModules(
389
- cwd,
390
- [...modules],
391
- route.method,
392
- route.path,
393
- policy,
394
- sources,
395
- )
396
- const site = modules.size === 0 ? skipped.get(routeKey(route.method, route.path)) : undefined
503
+ const walked = await walkRouteModules(context, [...modules], route.method, route.path)
504
+ const skippedAt =
505
+ modules.size === 0 ? skipped.get(routeKey(route.method, route.path)) : undefined
397
506
  const uncoveredReason =
398
507
  modules.size > 0
399
508
  ? undefined
400
- : site === undefined
509
+ : skippedAt === undefined
401
510
  ? "no source file registers it with a path the static scan can read; map it with capabilities.provenance.routeModules"
402
- : `${site} appears to register it on a server the static scan cannot identify (built by a helper that is neither \`server()\` nor imported from a module that calls it); call server() there, or map the route with capabilities.provenance.routeModules`
511
+ : `${skippedAt} appears to register it on a server the static scan cannot identify (built by a helper that is neither \`server()\` nor imported from a module that calls it); call server() there, or map the route with capabilities.provenance.routeModules`
403
512
  const covered = modules.size > 0 && walked.covered
404
513
  evidenceRoutes.push(
405
514
  uncoveredReason === undefined
@@ -28,8 +28,10 @@ import { parseRulePacks, runRuleRegistry } from "./rules/index.ts"
28
28
  import { islandRules } from "./rules/islands.ts"
29
29
  import { retiredLayoutRule } from "./rules/layout.ts"
30
30
  import { LEGACY_RULE_CODES, LEGACY_RULE_ORDER, legacyRules } from "./rules/legacy.ts"
31
+ import { mergeAuthGapRule } from "./rules/merge-auth.ts"
31
32
  import { nanoRules } from "./rules/nano.ts"
32
33
  import { pageRules } from "./rules/pages.ts"
34
+ import { routeStatementRule } from "./rules/route-statement.ts"
33
35
  import { routeRules } from "./rules/routes.ts"
34
36
  import { secretRules } from "./rules/secrets.ts"
35
37
  import { securityRules } from "./rules/security.ts"
@@ -94,6 +96,8 @@ export interface CheckResult {
94
96
  * better-auth). Echoed here so `--json` / the MCP tool / the report can show what the typed-client scan
95
97
  * deliberately skipped - a suppressed prefix stays auditable instead of silently hiding real drift. */
96
98
  readonly externalMounts?: readonly string[]
99
+ /** The tsconfigs `nifra.check.json` names for the typecheck, echoed so a narrowed program is visible. */
100
+ readonly tsconfigs?: readonly string[]
97
101
  /** Mounts declared `opaque` - outside capability assurance on purpose, each with its stated reason.
98
102
  * Listed on every run so the report states its own boundary; never a failure. */
99
103
  readonly knownGaps?: readonly CapabilityGap[]
@@ -160,6 +164,9 @@ export interface CheckAssuranceContext {
160
164
  export interface CheckConfig {
161
165
  readonly externalMounts: readonly string[]
162
166
  readonly rules: Readonly<Record<string, RuleOverride>>
167
+ /** The tsconfigs the typecheck runs, each its own program, project-relative. Unset: `tsconfig.json`
168
+ * and every project it references. */
169
+ readonly tsconfigs?: readonly string[]
163
170
  }
164
171
 
165
172
  /**
@@ -492,6 +499,8 @@ export async function collectCheckDiagnostics(
492
499
  ...routeRules,
493
500
  contractVisibilityRule,
494
501
  ...pageRules,
502
+ mergeAuthGapRule,
503
+ routeStatementRule,
495
504
  ...zoneRules,
496
505
  ...dataGuardRules,
497
506
  ...secretRules,
@@ -674,6 +683,7 @@ export async function collectCheckDiagnostics(
674
683
  ...(checkConfig.externalMounts.length === 0
675
684
  ? {}
676
685
  : { externalMounts: checkConfig.externalMounts }),
686
+ ...(checkConfig.tsconfigs === undefined ? {} : { tsconfigs: checkConfig.tsconfigs }),
677
687
  ...(knownGaps.length === 0 ? {} : { knownGaps }),
678
688
  ...(hooks === undefined ? {} : { hooks }),
679
689
  ...(Object.keys(checkConfig.rules).length === 0 ? {} : { ruleOverrides: checkConfig.rules }),
package/src/check-scan.ts CHANGED
@@ -352,7 +352,9 @@ export function parseSimpleFetchCall(snippet: string): SimpleFetchCall | undefin
352
352
  return { path, method, start: match.index, end: close + 1 }
353
353
  }
354
354
 
355
- const SERVER_CONSTRUCTION = /(?<![.\w])server\s*\(|new\s+Hono(?:<[^>]+>)?\s*\(/
355
+ // `createWebApp(...)` returns the same `Server`, so a route chained onto it is a backend route.
356
+ const NIFRA_SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(/
357
+ const SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(|new\s+Hono(?:<[^>]+>)?\s*\(/
356
358
 
357
359
  function isPotentialBackendSource(
358
360
  code: string,
@@ -3364,37 +3366,80 @@ function serverOnlyChains(
3364
3366
  // (redirects, files, streams). Fix is to return a plain object, or declare `{ response: t.… }` to type it.
3365
3367
  const RESPONSE_RETURN = /(?:=>\s*|return\s+)(?:new\s+Response|Response\s*\.\s*json)\s*\(/g
3366
3368
 
3367
- /** Scan a backend module (one that calls `server(`) for handlers returning a raw `Response`, which collapses
3368
- * the typed client's `data` to `never`. Pure + line-accurate; returns `[]` for files with no `server(` call. */
3369
+ /**
3370
+ * Scan a backend module (one that calls `server(` or `createWebApp(`) for handlers returning a raw
3371
+ * `Response`, which collapses the typed client's `data` to `never`. Pure + line-accurate; returns `[]`
3372
+ * for any other file. With an AST it also follows what the lexical pattern cannot see: a local holding
3373
+ * the Response, the context's `json()`/`text()`, and - given `project` - a helper imported from a
3374
+ * relative module whose export returns one, reported at each route's return. It skips a handler the
3375
+ * client still types: one that also returns a plain value, or whose route declares `response`.
3376
+ */
3369
3377
  export function scanResponseRoutes(
3370
3378
  file: string,
3371
3379
  content: string,
3372
3380
  facts?: SourceFacts,
3381
+ project?: ReadonlyMap<string, string>,
3373
3382
  ): SourceFinding[] {
3374
3383
  // Strip comments + template literals first: a commented-out or doc-example `return new Response(`
3375
3384
  // must not raise a spurious advisory. Lengths are preserved, so lineAt + the raw-line snippet align.
3376
3385
  const code = stripComments(content)
3377
- if (!/(?<![.\w])server\s*\(/.test(code)) return []
3386
+ if (!NIFRA_SERVER_CONSTRUCTION.test(code)) return []
3378
3387
  const out: SourceFinding[] = []
3379
3388
  const lines = content.split("\n")
3389
+ // A `// nifra-expect NF-C007` comment (or the `raw-response` slug) marks an intentional raw Response
3390
+ // (a file/redirect that can't be a typed route), silencing this advisory with or without a reason.
3391
+ // It counts on the return line or in the comment block directly above, so a TRAILING comment on one
3392
+ // route's return line can't leak down onto the next route. `stripComments` blanks it in `code` (so it
3393
+ // never affects the match); the raw `lines` still carry it.
3394
+ const report = (line: number): void => {
3395
+ if (commentBlockExpectation(lines, line, RAW_RESPONSE_EXPECTATION) !== undefined) return
3396
+ out.push({ file, line, snippet: (lines[line - 1] ?? "").trim() })
3397
+ }
3398
+ const source = facts?.parse(file, content)
3399
+ const exportsByImport = new Map<string, boolean>()
3400
+ const importReturnsResponse =
3401
+ facts === undefined || project === undefined
3402
+ ? undefined
3403
+ : (specifier: string, name: string): boolean => {
3404
+ const key = `${specifier}\0${name}`
3405
+ let answer = exportsByImport.get(key)
3406
+ if (answer === undefined) {
3407
+ const target = projectModule(project, file, specifier)
3408
+ const text = target === undefined ? undefined : project.get(target)
3409
+ const module =
3410
+ target === undefined || text === undefined ? undefined : facts.parse(target, text)
3411
+ answer = module !== undefined && facts.exportReturnsResponse(module, name)
3412
+ exportsByImport.set(key, answer)
3413
+ }
3414
+ return answer
3415
+ }
3416
+ const routes =
3417
+ facts === undefined || source === undefined
3418
+ ? undefined
3419
+ : facts.untypedResponseRoutes(source, importReturnsResponse)
3380
3420
  RESPONSE_RETURN.lastIndex = 0
3381
3421
  for (let m = RESPONSE_RETURN.exec(code); m !== null; m = RESPONSE_RETURN.exec(code)) {
3382
- if (facts !== undefined) {
3383
- const source = facts.parse(file, content)
3384
- // A parseable AST rejects `return new Response(` text that only lives in a normal string. On
3385
- // malformed source we keep the lexical candidate; the typecheck gate will report the syntax error.
3386
- if (source !== undefined && facts.isResponseSyntaxAt(source, m.index) !== true) continue
3387
- }
3388
- const line = lineAt(content, m.index)
3389
- // A `// nifra-expect NF-C007` comment (or the `raw-response` slug) marks an intentional raw Response
3390
- // (a file/redirect that can't be a typed route), silencing this advisory with or without a reason.
3391
- // It counts on the return line or in the comment block directly above, so a TRAILING comment on one
3392
- // route's return line can't leak down onto the next route. `stripComments` blanks it in `code` (so it
3393
- // never affects the match); the raw `lines` still carry it.
3394
- if (commentBlockExpectation(lines, line, RAW_RESPONSE_EXPECTATION) !== undefined) continue
3395
- out.push({ file, line, snippet: (lines[line - 1] ?? "").trim() })
3422
+ // A parseable AST rejects `return new Response(` text that only lives in a normal string, one
3423
+ // outside a route handler (an auth stage's `rejected` helper, say), and one in a handler the client
3424
+ // still types: it returns a plain value too, or its route declares `response`. On malformed
3425
+ // source we keep the lexical candidate; the typecheck gate will report the syntax error.
3426
+ if (
3427
+ facts !== undefined &&
3428
+ source !== undefined &&
3429
+ (facts.isResponseSyntaxAt(source, m.index) !== true || routes?.isUntypedAt(m.index) !== true)
3430
+ )
3431
+ continue
3432
+ report(lineAt(content, m.index))
3396
3433
  }
3397
- return out
3434
+ if (routes === undefined) return out
3435
+ const reported = new Set(out.map((finding) => finding.line))
3436
+ for (const position of routes.indirectReturns) {
3437
+ const line = lineAt(content, position)
3438
+ if (reported.has(line)) continue
3439
+ reported.add(line)
3440
+ report(line)
3441
+ }
3442
+ return out.sort((a, b) => a.line - b.line)
3398
3443
  }
3399
3444
 
3400
3445
  /** What suppresses the {@link scanResponseRoutes} advisory for an intentional raw Response. */