@nifrajs/cli 5.1.0 → 5.2.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 (201) hide show
  1. package/CHANGELOG.md +3211 -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 +1 -0
  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 +3 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts.map +1 -1
  21. package/dist/check-scan.js +6 -3
  22. package/dist/check-scan.js.map +1 -1
  23. package/dist/check.d.ts.map +1 -1
  24. package/dist/check.js +52 -12
  25. package/dist/check.js.map +1 -1
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +23 -12
  28. package/dist/cli.js.map +1 -1
  29. package/dist/command-catalog.d.ts.map +1 -1
  30. package/dist/command-catalog.js +9 -5
  31. package/dist/command-catalog.js.map +1 -1
  32. package/dist/dev-bun-config.d.ts +6 -3
  33. package/dist/dev-bun-config.d.ts.map +1 -1
  34. package/dist/dev-bun-config.js +13 -10
  35. package/dist/dev-bun-config.js.map +1 -1
  36. package/dist/dev-feed-tool.d.ts +3 -2
  37. package/dist/dev-feed-tool.d.ts.map +1 -1
  38. package/dist/dev-feed-tool.js +26 -5
  39. package/dist/dev-feed-tool.js.map +1 -1
  40. package/dist/doctor.d.ts +15 -1
  41. package/dist/doctor.d.ts.map +1 -1
  42. package/dist/doctor.js +79 -61
  43. package/dist/doctor.js.map +1 -1
  44. package/dist/i18n-check.d.ts +11 -1
  45. package/dist/i18n-check.d.ts.map +1 -1
  46. package/dist/i18n-check.js +170 -17
  47. package/dist/i18n-check.js.map +1 -1
  48. package/dist/init-agents.d.ts +46 -6
  49. package/dist/init-agents.d.ts.map +1 -1
  50. package/dist/init-agents.js +193 -31
  51. package/dist/init-agents.js.map +1 -1
  52. package/dist/internal/project-specifiers.d.ts.map +1 -1
  53. package/dist/internal/project-specifiers.js +9 -1
  54. package/dist/internal/project-specifiers.js.map +1 -1
  55. package/dist/internal/source-facts.d.ts +6 -0
  56. package/dist/internal/source-facts.d.ts.map +1 -1
  57. package/dist/internal/source-facts.js +106 -0
  58. package/dist/internal/source-facts.js.map +1 -1
  59. package/dist/internal/workspace-packages.d.ts +22 -0
  60. package/dist/internal/workspace-packages.d.ts.map +1 -0
  61. package/dist/internal/workspace-packages.js +215 -0
  62. package/dist/internal/workspace-packages.js.map +1 -0
  63. package/dist/load.d.ts +7 -2
  64. package/dist/load.d.ts.map +1 -1
  65. package/dist/load.js +11 -2
  66. package/dist/load.js.map +1 -1
  67. package/dist/lock-links.d.ts +42 -0
  68. package/dist/lock-links.d.ts.map +1 -0
  69. package/dist/lock-links.js +144 -0
  70. package/dist/lock-links.js.map +1 -0
  71. package/dist/mcp-exec.d.ts.map +1 -1
  72. package/dist/mcp-exec.js +5 -2
  73. package/dist/mcp-exec.js.map +1 -1
  74. package/dist/mcp-http.js +1 -1
  75. package/dist/mcp-root.d.ts +6 -4
  76. package/dist/mcp-root.d.ts.map +1 -1
  77. package/dist/mcp-root.js +12 -8
  78. package/dist/mcp-root.js.map +1 -1
  79. package/dist/migrate-layout.d.ts +2 -1
  80. package/dist/migrate-layout.d.ts.map +1 -1
  81. package/dist/migrate-layout.js +434 -29
  82. package/dist/migrate-layout.js.map +1 -1
  83. package/dist/project-site.d.ts +7 -0
  84. package/dist/project-site.d.ts.map +1 -0
  85. package/dist/project-site.js +19 -0
  86. package/dist/project-site.js.map +1 -0
  87. package/dist/recipes/4.0.0.d.ts.map +1 -1
  88. package/dist/recipes/4.0.0.js +2 -0
  89. package/dist/recipes/4.0.0.js.map +1 -1
  90. package/dist/recipes/5.1.0.d.ts +9 -0
  91. package/dist/recipes/5.1.0.d.ts.map +1 -0
  92. package/dist/recipes/5.1.0.js +22 -0
  93. package/dist/recipes/5.1.0.js.map +1 -0
  94. package/dist/recipes/5.2.0.d.ts +10 -0
  95. package/dist/recipes/5.2.0.d.ts.map +1 -0
  96. package/dist/recipes/5.2.0.js +32 -0
  97. package/dist/recipes/5.2.0.js.map +1 -0
  98. package/dist/recipes/index.d.ts +3 -0
  99. package/dist/recipes/index.d.ts.map +1 -1
  100. package/dist/recipes/index.js +7 -0
  101. package/dist/recipes/index.js.map +1 -1
  102. package/dist/review.d.ts.map +1 -1
  103. package/dist/review.js +2 -0
  104. package/dist/review.js.map +1 -1
  105. package/dist/rule-explain.d.ts +26 -0
  106. package/dist/rule-explain.d.ts.map +1 -0
  107. package/dist/rule-explain.js +49 -0
  108. package/dist/rule-explain.js.map +1 -0
  109. package/dist/rules/codes.d.ts +2 -0
  110. package/dist/rules/codes.d.ts.map +1 -1
  111. package/dist/rules/codes.js +2 -0
  112. package/dist/rules/codes.js.map +1 -1
  113. package/dist/rules/contract-visibility.d.ts.map +1 -1
  114. package/dist/rules/contract-visibility.js +93 -21
  115. package/dist/rules/contract-visibility.js.map +1 -1
  116. package/dist/rules/explanations.d.ts +14 -0
  117. package/dist/rules/explanations.d.ts.map +1 -0
  118. package/dist/rules/explanations.js +316 -0
  119. package/dist/rules/explanations.js.map +1 -0
  120. package/dist/rules/legacy.d.ts.map +1 -1
  121. package/dist/rules/legacy.js +24 -1
  122. package/dist/rules/legacy.js.map +1 -1
  123. package/dist/rules/merge-auth.d.ts +12 -0
  124. package/dist/rules/merge-auth.d.ts.map +1 -0
  125. package/dist/rules/merge-auth.js +52 -0
  126. package/dist/rules/merge-auth.js.map +1 -0
  127. package/dist/rules/pages.d.ts +27 -0
  128. package/dist/rules/pages.d.ts.map +1 -1
  129. package/dist/rules/pages.js +177 -2
  130. package/dist/rules/pages.js.map +1 -1
  131. package/dist/rules/routes.d.ts +3 -2
  132. package/dist/rules/routes.d.ts.map +1 -1
  133. package/dist/rules/routes.js +4 -3
  134. package/dist/rules/routes.js.map +1 -1
  135. package/dist/rules/zones.d.ts.map +1 -1
  136. package/dist/rules/zones.js +3 -2
  137. package/dist/rules/zones.js.map +1 -1
  138. package/dist/typecheck-coverage.d.ts +11 -0
  139. package/dist/typecheck-coverage.d.ts.map +1 -1
  140. package/dist/typecheck-coverage.js +50 -7
  141. package/dist/typecheck-coverage.js.map +1 -1
  142. package/dist/upgrade.d.ts +37 -1
  143. package/dist/upgrade.d.ts.map +1 -1
  144. package/dist/upgrade.js +171 -20
  145. package/dist/upgrade.js.map +1 -1
  146. package/dist/verification-plan.d.ts.map +1 -1
  147. package/dist/verification-plan.js +2 -0
  148. package/dist/verification-plan.js.map +1 -1
  149. package/dist/version-drift.d.ts.map +1 -1
  150. package/dist/version-drift.js +12 -1
  151. package/dist/version-drift.js.map +1 -1
  152. package/dist/web-app-options.d.ts +1 -1
  153. package/dist/web-app-options.d.ts.map +1 -1
  154. package/dist/web-app-options.js.map +1 -1
  155. package/docs/examples.json +19 -1
  156. package/docs/llms-full.txt +625 -130
  157. package/docs/types.json +396 -50
  158. package/package.json +13 -12
  159. package/src/agent-files.ts +27 -17
  160. package/src/assure-hydration.ts +1 -0
  161. package/src/assure.ts +11 -1
  162. package/src/capabilities-tool.ts +159 -50
  163. package/src/check-diagnostics.ts +8 -0
  164. package/src/check-scan.ts +9 -3
  165. package/src/check.ts +67 -12
  166. package/src/cli.ts +24 -11
  167. package/src/command-catalog.ts +16 -8
  168. package/src/dev-bun-config.ts +13 -9
  169. package/src/dev-feed-tool.ts +40 -6
  170. package/src/doctor.ts +102 -66
  171. package/src/i18n-check.ts +254 -18
  172. package/src/init-agents.ts +221 -41
  173. package/src/internal/project-specifiers.ts +9 -1
  174. package/src/internal/source-facts.ts +124 -0
  175. package/src/internal/workspace-packages.ts +218 -0
  176. package/src/load.ts +19 -3
  177. package/src/lock-links.ts +173 -0
  178. package/src/mcp-exec.ts +5 -2
  179. package/src/mcp-http.ts +1 -1
  180. package/src/mcp-root.ts +14 -8
  181. package/src/migrate-layout.ts +495 -31
  182. package/src/project-site.ts +18 -0
  183. package/src/recipes/4.0.0.ts +2 -0
  184. package/src/recipes/5.1.0.ts +23 -0
  185. package/src/recipes/5.2.0.ts +33 -0
  186. package/src/recipes/index.ts +7 -0
  187. package/src/review.ts +2 -0
  188. package/src/rule-explain.ts +75 -0
  189. package/src/rules/codes.ts +2 -0
  190. package/src/rules/contract-visibility.ts +118 -20
  191. package/src/rules/explanations.ts +329 -0
  192. package/src/rules/legacy.ts +24 -1
  193. package/src/rules/merge-auth.ts +55 -0
  194. package/src/rules/pages.ts +221 -2
  195. package/src/rules/routes.ts +4 -3
  196. package/src/rules/zones.ts +3 -2
  197. package/src/typecheck-coverage.ts +51 -6
  198. package/src/upgrade.ts +227 -22
  199. package/src/verification-plan.ts +6 -0
  200. package/src/version-drift.ts +15 -0
  201. package/src/web-app-options.ts +9 -1
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Bare specifiers that name a package the project owns, resolved through that package's `exports`
3
+ * the way Bun resolves them. A package is the project's when it is a workspace member, or when its
4
+ * `node_modules` entry links to a directory outside every `node_modules`; one installed from a
5
+ * registry is never read, because its source is not the project's to check.
6
+ */
7
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"
8
+ import { dirname, join, relative, sep } from "node:path"
9
+ import { workspaceMemberDirs } from "../mcp-root.ts"
10
+
11
+ /** Bun's runtime conditions, in the order a conditions object is read; `types` is taken only when it
12
+ * names a TypeScript source, which is what Bun would run. */
13
+ const CONDITIONS: ReadonlySet<string> = new Set(["bun", "import", "default"])
14
+ const TS_SOURCE = /\.[cm]?tsx?$/
15
+ const DECLARATION = /\.d\.[cm]?tsx?$/
16
+ /** Tried in order when a package without `exports` names a file without its extension. */
17
+ const EXTENSIONS: readonly string[] = ["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".jsx"]
18
+ const PACKAGE_NAME = /^(?:@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/i
19
+
20
+ /** The file a specifier names, or why a package the project owns does not export it. */
21
+ export type ExportedFile =
22
+ | { readonly path: string }
23
+ | { readonly package: string; readonly reason: string }
24
+
25
+ const record = (value: unknown): Readonly<Record<string, unknown>> | undefined =>
26
+ typeof value === "object" && value !== null && !Array.isArray(value)
27
+ ? Object.fromEntries(Object.entries(value))
28
+ : undefined
29
+
30
+ const isFile = (path: string): boolean => {
31
+ try {
32
+ return statSync(path).isFile()
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ const manifestOf = (dir: string): Readonly<Record<string, unknown>> | undefined => {
39
+ try {
40
+ return record(JSON.parse(readFileSync(join(dir, "package.json"), "utf8")))
41
+ } catch {
42
+ return undefined
43
+ }
44
+ }
45
+
46
+ /** `@scope/name/sub/path` -> `["@scope/name", "./sub/path"]`; `undefined` for a relative, absolute,
47
+ * `#` or `scheme:` specifier. */
48
+ export function splitBareSpecifier(specifier: string): [string, string] | undefined {
49
+ if (/^[./#]/.test(specifier) || specifier.includes(":")) return undefined
50
+ const parts = specifier.split("/")
51
+ const take = specifier.startsWith("@") ? 2 : 1
52
+ const name = parts.slice(0, take).join("/")
53
+ if (!PACKAGE_NAME.test(name)) return undefined
54
+ const rest = parts.slice(take)
55
+ return [name, rest.length === 0 ? "." : `./${rest.join("/")}`]
56
+ }
57
+
58
+ /** The target a conditions value selects, with `*` replaced; `null` when the package excludes it. */
59
+ function conditionTarget(value: unknown, match: string): string | null | undefined {
60
+ if (value === null) return null
61
+ if (typeof value === "string") {
62
+ // As Node and Bun refuse them: a target leaves the package only through `..` or `node_modules`.
63
+ const segments = value.split("/")
64
+ if (segments[0] !== "." || segments.some((part) => part === ".." || part === "node_modules"))
65
+ return undefined
66
+ return value.replaceAll("*", match)
67
+ }
68
+ if (Array.isArray(value)) {
69
+ for (const item of value) {
70
+ const target = conditionTarget(item, match)
71
+ if (target !== undefined) return target
72
+ }
73
+ return undefined
74
+ }
75
+ const conditions = record(value)
76
+ if (conditions === undefined) return undefined
77
+ for (const [key, inner] of Object.entries(conditions)) {
78
+ if (CONDITIONS.has(key)) {
79
+ const target = conditionTarget(inner, match)
80
+ if (target !== undefined) return target
81
+ } else if (key === "types") {
82
+ const target = conditionTarget(inner, match)
83
+ if (typeof target === "string" && TS_SOURCE.test(target) && !DECLARATION.test(target))
84
+ return target
85
+ }
86
+ }
87
+ return undefined
88
+ }
89
+
90
+ /** What `exports` maps `subpath` to: an exact key first, then the `*` pattern with the longest
91
+ * prefix, as Node and Bun match them. */
92
+ export function exportsTarget(exports: unknown, subpath: string): string | null | undefined {
93
+ const map = record(exports)
94
+ const subpaths =
95
+ map !== undefined && Object.keys(map).some((key) => key.startsWith("."))
96
+ ? map
97
+ : { ".": exports }
98
+ if (Object.hasOwn(subpaths, subpath)) return conditionTarget(subpaths[subpath], "")
99
+ let best: { readonly key: string; readonly match: string } | undefined
100
+ for (const key of Object.keys(subpaths)) {
101
+ const star = key.indexOf("*")
102
+ if (star === -1 || key.indexOf("*", star + 1) !== -1) continue
103
+ const prefix = key.slice(0, star)
104
+ const suffix = key.slice(star + 1)
105
+ if (
106
+ subpath.length < key.length ||
107
+ !subpath.startsWith(prefix) ||
108
+ !subpath.endsWith(suffix) ||
109
+ (best !== undefined && prefix.length <= best.key.indexOf("*"))
110
+ )
111
+ continue
112
+ best = { key, match: subpath.slice(prefix.length, subpath.length - suffix.length) }
113
+ }
114
+ if (best === undefined) return undefined
115
+ if (best.match.split("/").includes("..")) return undefined
116
+ return conditionTarget(subpaths[best.key], best.match)
117
+ }
118
+
119
+ const inside = (dir: string, path: string): boolean => {
120
+ const rel = relative(dir, path)
121
+ return rel !== "" && !rel.startsWith("..") && !rel.split(sep).includes("node_modules")
122
+ }
123
+
124
+ /** The file `subpath` names in the package at `dir`, or why it names none. */
125
+ function entryIn(dir: string, name: string, subpath: string): ExportedFile {
126
+ const manifest = manifestOf(dir)
127
+ const shown = subpath === "." ? name : `${name}/${subpath.slice(2)}`
128
+ const exported =
129
+ manifest?.exports !== undefined
130
+ ? exportsTarget(manifest.exports, subpath)
131
+ : subpath === "."
132
+ ? typeof manifest?.module === "string"
133
+ ? manifest.module
134
+ : typeof manifest?.main === "string"
135
+ ? manifest.main
136
+ : "./index"
137
+ : subpath
138
+ if (exported === null || exported === undefined)
139
+ return { package: name, reason: `${name} does not export "${subpath}"` }
140
+ // An `exports` target is a file; a package without `exports` is probed the way Bun probes it.
141
+ const base = join(dir, exported)
142
+ const probes =
143
+ manifest?.exports !== undefined
144
+ ? [base]
145
+ : [
146
+ ...EXTENSIONS.map((extension) => `${base}${extension}`),
147
+ ...EXTENSIONS.slice(1).map((extension) => join(base, `index${extension}`)),
148
+ ]
149
+ const found = probes.find(isFile)
150
+ if (found === undefined)
151
+ return { package: name, reason: `${shown} resolves to ${exported}, which does not exist` }
152
+ let real: string
153
+ try {
154
+ real = realpathSync(found)
155
+ } catch {
156
+ return { package: name, reason: `${shown} resolves to ${exported}, which cannot be read` }
157
+ }
158
+ return inside(realpathSync(dir), real)
159
+ ? { path: real }
160
+ : { package: name, reason: `${shown} resolves outside the package` }
161
+ }
162
+
163
+ /** The nearest directory at or above `start`, up to the repository root, whose package.json declares
164
+ * `workspaces`. */
165
+ function workspaceRoot(start: string): string | undefined {
166
+ for (let dir = start; ; ) {
167
+ const workspaces = manifestOf(dir)?.workspaces
168
+ if (workspaces !== undefined) return dir
169
+ const parent = dirname(dir)
170
+ if (parent === dir || existsSync(join(dir, ".git"))) return undefined
171
+ dir = parent
172
+ }
173
+ }
174
+
175
+ /** Resolves a bare specifier from an absolute importing file; `undefined` when it is not bare. */
176
+ export type ExportedFileResolver = (from: string, specifier: string) => ExportedFile | undefined
177
+
178
+ /**
179
+ * A resolver over the workspace `root` belongs to. Workspace members are read from their manifests
180
+ * once; any other package is looked up in the `node_modules` above the importing file and read only
181
+ * when that entry links outside every `node_modules`.
182
+ */
183
+ export async function createExportedFileResolver(root: string): Promise<ExportedFileResolver> {
184
+ const members = new Map<string, string>()
185
+ const top = workspaceRoot(root)
186
+ for (const dir of top === undefined ? [] : ((await workspaceMemberDirs(top)) ?? [])) {
187
+ const name = manifestOf(dir)?.name
188
+ if (typeof name === "string" && !members.has(name)) members.set(name, dir)
189
+ }
190
+ return (from, specifier) => {
191
+ const split = splitBareSpecifier(specifier)
192
+ if (split === undefined) return undefined
193
+ const [name, subpath] = split
194
+ const member = members.get(name)
195
+ if (member !== undefined) return entryIn(member, name, subpath)
196
+ for (let dir = dirname(from); ; ) {
197
+ const linked = join(dir, "node_modules", name)
198
+ if (existsSync(linked)) {
199
+ let real: string
200
+ try {
201
+ real = realpathSync(linked)
202
+ } catch {
203
+ break
204
+ }
205
+ return real.split(sep).includes("node_modules")
206
+ ? {
207
+ package: name,
208
+ reason: `${name} is installed from a registry, not a workspace package`,
209
+ }
210
+ : entryIn(real, name, subpath)
211
+ }
212
+ const parent = dirname(dir)
213
+ if (parent === dir) break
214
+ dir = parent
215
+ }
216
+ return { package: name, reason: `${name} is not a workspace package and is not installed` }
217
+ }
218
+ }
package/src/load.ts CHANGED
@@ -85,7 +85,8 @@ export interface NifraFramework {
85
85
  readonly dev?: { readonly indicator?: boolean; readonly allowedHosts?: readonly string[] }
86
86
  /** Static files directory. Defaults to `<app>/public`; `false` disables it. */
87
87
  readonly publicDir?: string | false
88
- /** Client-visible environment prefix (default `"PUBLIC_"`; empty disables exposure). */
88
+ /** Client-visible environment prefix (default `"PUBLIC_"`; empty disables exposure). With both
89
+ * configs, `nifra.config.ts` wins and `backend/framework.ts` fills it in when left unset. */
89
90
  readonly publicEnvPrefix?: string
90
91
  /** Reviewed false positives of `nifra build`'s secret scan, each `{ rule, file, reason }` (or
91
92
  * `{ rule: "private-env-value", env, reason }`). There is no exemption by value. */
@@ -111,6 +112,10 @@ export interface NifraFramework {
111
112
  readonly csp?: CreateWebAppOptions["csp"]
112
113
  /** A per-request CSP nonce resolver. Exclusive with {@link csp}. */
113
114
  readonly nonce?: CreateWebAppOptions["nonce"]
115
+ /** The app's locale routing, `defineI18nRouting()` from `@nifrajs/i18n/routing`: every document
116
+ * takes its `<html lang dir>`, `Content-Language` and adapter locale from it. See `createWebApp`'s
117
+ * `i18n`. */
118
+ readonly i18n?: CreateWebAppOptions["i18n"]
114
119
  }
115
120
 
116
121
  /** The {@link NifraFramework} fields forwarded to `createWebApp` and imported by the generated server
@@ -122,6 +127,7 @@ export const FRAMEWORK_WEB_OPTIONS = [
122
127
  "csp",
123
128
  "nonce",
124
129
  "serverComponents",
130
+ "i18n",
125
131
  ] as const
126
132
  export type FrameworkWebOption = (typeof FRAMEWORK_WEB_OPTIONS)[number]
127
133
 
@@ -162,6 +168,15 @@ function assertFrameworkWebOptions(fw: Partial<NifraFramework>, configFile: stri
162
168
  if (fw.nonce !== undefined && typeof fw.nonce !== "function") {
163
169
  wrong("nonce", "a nonce resolver function, such as createNonceResolver() returns")
164
170
  }
171
+ if (
172
+ fw.i18n !== undefined &&
173
+ (typeof fw.i18n !== "object" || fw.i18n === null || typeof fw.i18n.localeOf !== "function")
174
+ ) {
175
+ wrong("i18n", "the router defineI18nRouting() from @nifrajs/i18n/routing returns")
176
+ }
177
+ if (fw.publicEnvPrefix !== undefined && typeof fw.publicEnvPrefix !== "string") {
178
+ wrong("publicEnvPrefix", 'a string such as "PUBLIC_", or "" to expose no environment variable')
179
+ }
165
180
  if (fw.secretExemptions !== undefined && !Array.isArray(fw.secretExemptions)) {
166
181
  wrong("secretExemptions", "an array of { rule, file, reason } entries")
167
182
  }
@@ -342,8 +357,9 @@ export async function loadBackendApp(
342
357
  return { cwd, backend }
343
358
  }
344
359
 
345
- /** The fields the generated server entry imports from backend/framework.ts. */
346
- const SERVER_OPTIONS = [...FRAMEWORK_WEB_OPTIONS, "use"] as const
360
+ /** The fields the generated server entry imports from backend/framework.ts, and `publicEnvPrefix`,
361
+ * which `nifra check` reads there too: each command must draw the browser-env line in one place. */
362
+ const SERVER_OPTIONS = [...FRAMEWORK_WEB_OPTIONS, "use", "publicEnvPrefix"] as const
347
363
 
348
364
  /**
349
365
  * `config` with each server option it leaves unset taken from backend/framework.ts, so `nifra dev` and
@@ -0,0 +1,173 @@
1
+ /**
2
+ * A `file:` dependency's own dependencies, as bun.lock records them. Bun records them when it first
3
+ * installs the linked package and does not read its package.json again, so once the linked package
4
+ * moves to another version of a dependency the lock still names the old one and Bun installs a second
5
+ * copy under the linked package. Checked on Bun 1.4.2: `bun install --force` keeps the stale entry;
6
+ * `bun update <name>`, or dropping the entry and its scoped entries before `bun install`, clears it.
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs"
9
+ import { dirname, join, resolve } from "node:path"
10
+ import { parseJsonc } from "./internal/project-specifiers.ts"
11
+
12
+ export const BUN_LOCK = "bun.lock"
13
+
14
+ /** The fields Bun installs from a linked package's manifest. */
15
+ const INSTALLED_FIELDS: readonly string[] = [
16
+ "dependencies",
17
+ "optionalDependencies",
18
+ "peerDependencies",
19
+ ]
20
+
21
+ /** One dependency whose recorded spec is not the one the linked package.json declares now. */
22
+ export interface LinkLockChange {
23
+ readonly name: string
24
+ /** As bun.lock recorded it; absent when the linked package added it since. */
25
+ readonly recorded?: string
26
+ /** As the linked package.json declares it; absent when it was removed since. */
27
+ readonly declared?: string
28
+ }
29
+
30
+ /** A `file:` entry of bun.lock whose recorded dependencies the linked package.json no longer declares. */
31
+ export interface StaleLinkLock {
32
+ /** The package, as the lock keys it. */
33
+ readonly package: string
34
+ /** The linked directory, as the lock names it relative to the lockfile. */
35
+ readonly path: string
36
+ readonly changes: readonly LinkLockChange[]
37
+ }
38
+
39
+ const recordOf = (value: unknown): Readonly<Record<string, unknown>> =>
40
+ typeof value === "object" && value !== null && !Array.isArray(value)
41
+ ? Object.fromEntries(Object.entries(value))
42
+ : {}
43
+
44
+ const textOf = (value: unknown): string | undefined =>
45
+ typeof value === "string" ? value : undefined
46
+
47
+ /** A top-level lock key (`name`, `@scope/name`), not a dependency scoped under one (`name/dep`). */
48
+ const topLevel = (key: string): boolean =>
49
+ key.startsWith("@") ? key.split("/").length === 2 : !key.includes("/")
50
+
51
+ /** The directory of the nearest bun.lock at or above `cwd`, up to the repository root. */
52
+ export function bunLockDir(cwd: string): string | undefined {
53
+ for (let dir = resolve(cwd); ; ) {
54
+ if (existsSync(join(dir, BUN_LOCK))) return dir
55
+ const parent = dirname(dir)
56
+ if (parent === dir || existsSync(join(dir, ".git"))) return undefined
57
+ dir = parent
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Each `file:` entry of the bun.lock in `dir` whose recorded dependencies differ from what the linked
63
+ * package.json declares. `manifests` (absolute path -> text) stands in for package.json files an edit
64
+ * has planned but not written yet. A lock or manifest that cannot be read reports nothing.
65
+ */
66
+ export function staleLinkLocks(
67
+ dir: string,
68
+ manifests: ReadonlyMap<string, string> = new Map(),
69
+ ): StaleLinkLock[] {
70
+ let lock: unknown
71
+ try {
72
+ lock = parseJsonc(readFileSync(join(dir, BUN_LOCK), "utf8"))
73
+ } catch {
74
+ return []
75
+ }
76
+ const stale: StaleLinkLock[] = []
77
+ for (const [key, entry] of Object.entries(recordOf(Reflect.get(Object(lock), "packages")))) {
78
+ if (!topLevel(key) || !Array.isArray(entry)) continue
79
+ const spec = textOf(entry[0])
80
+ const at = spec?.indexOf("@file:", 1) ?? -1
81
+ if (spec === undefined || at === -1) continue
82
+ const path = spec.slice(at + "@file:".length)
83
+ const manifestPath = resolve(dir, path, "package.json")
84
+ let declared: unknown
85
+ try {
86
+ declared = JSON.parse(manifests.get(manifestPath) ?? readFileSync(manifestPath, "utf8"))
87
+ } catch {
88
+ continue
89
+ }
90
+ const recorded = recordOf(entry[1])
91
+ const changes: LinkLockChange[] = []
92
+ for (const field of INSTALLED_FIELDS) {
93
+ const was = recordOf(recorded[field])
94
+ const now = recordOf(Reflect.get(Object(declared), field))
95
+ for (const name of new Set([...Object.keys(was), ...Object.keys(now)])) {
96
+ const before = textOf(was[name])
97
+ const after = textOf(now[name])
98
+ if (before === after) continue
99
+ const change: { name: string; recorded?: string; declared?: string } = { name }
100
+ if (before !== undefined) change.recorded = before
101
+ if (after !== undefined) change.declared = after
102
+ changes.push(change)
103
+ }
104
+ }
105
+ if (changes.length > 0) stale.push({ package: key, path, changes })
106
+ }
107
+ return stale
108
+ }
109
+
110
+ /** `name 1.0.0 -> 2.0.0`, with `(none)` for a side that does not have it. */
111
+ export const describeChange = (change: LinkLockChange): string =>
112
+ `${change.name} ${change.recorded ?? "(none)"} -> ${change.declared ?? "(none)"}`
113
+
114
+ const ENTRY_KEY = /^ {4}("(?:[^"\\]|\\.)*"): \[/
115
+
116
+ /**
117
+ * bun.lock text without the `packages` entries of `names` and the dependencies scoped under them,
118
+ * so the next `bun install` reads each linked package.json again. `undefined` unless the text is laid
119
+ * out one entry per line, as Bun writes it, and the result parses to the same lock less those
120
+ * entries: the caller names `bun update` instead.
121
+ */
122
+ export function pruneLinkLocks(text: string, names: readonly string[]): string | undefined {
123
+ const lines = text.split("\n")
124
+ const start = lines.findIndex((line) => /^ {2}"packages": \{\s*$/.test(line))
125
+ if (start === -1) return undefined
126
+ const end = lines.findIndex((line, index) => index > start && /^ {2}\}/.test(line))
127
+ if (end === -1) return undefined
128
+ const dropped = (key: string): boolean =>
129
+ names.some((name) => key === name || key.startsWith(`${name}/`))
130
+ const kept = lines.filter((line, index) => {
131
+ if (index <= start || index >= end) return true
132
+ const key = ENTRY_KEY.exec(line)?.[1]
133
+ return key === undefined || !dropped(String(JSON.parse(key)))
134
+ })
135
+ const pruned = kept.join("\n")
136
+ try {
137
+ const before = recordOf(parseJsonc(text))
138
+ const after = recordOf(parseJsonc(pruned))
139
+ const expected = Object.fromEntries(
140
+ Object.entries(recordOf(before.packages)).filter(([key]) => !dropped(key)),
141
+ )
142
+ const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)
143
+ if (!same(recordOf(after.packages), expected)) return undefined
144
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
145
+ if (key !== "packages" && !same(before[key], after[key])) return undefined
146
+ }
147
+ } catch {
148
+ return undefined
149
+ }
150
+ return pruned
151
+ }
152
+
153
+ /** The `bun update` that makes Bun read each linked package.json again. */
154
+ export const linkLockUpdate = (entries: readonly StaleLinkLock[]): string =>
155
+ `bun update ${entries.map((entry) => entry.package).join(" ")}`
156
+
157
+ /** The advisory both `nifra doctor` and `nifra check` print. */
158
+ export function staleLinkLockMessage(stale: {
159
+ readonly lock: string
160
+ readonly entries: readonly StaleLinkLock[]
161
+ }): string {
162
+ const listed = stale.entries
163
+ .map((entry) => {
164
+ const shown = entry.changes.slice(0, 3).map(describeChange).join(", ")
165
+ const more = entry.changes.length > 3 ? ` and ${entry.changes.length - 3} more` : ""
166
+ return `${entry.package} (file:${entry.path}): ${shown}${more}`
167
+ })
168
+ .join("; ")
169
+ return (
170
+ `${stale.lock} records dependencies its file: packages no longer declare, and Bun never reads a linked package.json again, so it installs those versions beside the declared ones: ${listed}. ` +
171
+ `Run \`${linkLockUpdate(stale.entries)}\`, or \`nifra upgrade --write\` to drop the entries, then \`bun install\`.`
172
+ )
173
+ }
package/src/mcp-exec.ts CHANGED
@@ -292,14 +292,14 @@ export function projectTools(
292
292
  {
293
293
  name: "nifra_explain",
294
294
  description:
295
- "Turn a nifra error into a STRUCTURED diagnostic instead of eyeballing a stack trace: a stable `code`, the top frame in YOUR source, a codeframe around the offending line, and - when nifra recognises the failure - the plain-language `cause` + `fix` + docs anchor. Pass `error` (and `stack` if you have it, e.g. from nifra_run/nifra_test output or a failing build) to explain a specific failure. With no `error`, returns the running dev server's most recent error of any kind (SSR, loader, API, build, browser, hydration) with its request id - the server is found automatically; `port`/`dir` pick one when several run. nifra_errors lists them all. Returns the same JSON the dev overlay renders.",
295
+ "Turn a nifra error into a STRUCTURED diagnostic instead of eyeballing a stack trace: a stable `code`, the top frame in YOUR source, a codeframe around the offending line, and - when nifra recognises the failure - the plain-language `cause` + `fix` + docs anchor. Pass `error` (and `stack` if you have it, e.g. from nifra_run/nifra_test output or a failing build) to explain a specific failure. With no `error`, returns the running dev server's most recent error of any kind (SSR, loader, API, build, browser, hydration) with its request id - the server is found automatically; `port`/`dir` pick one when several run. nifra_errors lists them all. Returns the same JSON the dev overlay renders. Pass a rule code such as `NF-C007` as `error` (no `stack`) to get that `nifra check` rule's title, why it matters, its fix and its docs page.",
296
296
  inputSchema: {
297
297
  type: "object",
298
298
  properties: {
299
299
  error: {
300
300
  type: "string",
301
301
  description:
302
- "The error message to explain (copy it from nifra_run/nifra_test output or a failing build).",
302
+ "The error message to explain (copy it from nifra_run/nifra_test output or a failing build), or a rule code such as NF-C007.",
303
303
  },
304
304
  stack: {
305
305
  type: "string",
@@ -331,6 +331,9 @@ export function projectTools(
331
331
  port?: number
332
332
  dir?: string
333
333
  }
334
+ const { explainRule, RULE_CODE_SHAPE } = await import("./rule-explain.ts")
335
+ if (stack === undefined && error !== undefined && RULE_CODE_SHAPE.test(error.trim()))
336
+ return JSON.stringify(await explainRule(error.trim()), null, 2)
334
337
  if (error !== undefined || stack !== undefined) {
335
338
  const { buildDiagnostic } = await import("@nifrajs/web/diagnostic")
336
339
  const e = new Error(error ?? "")
package/src/mcp-http.ts CHANGED
@@ -29,7 +29,7 @@ export { docsTools } from "./mcp-docs-tools.ts"
29
29
  export type { TypeEntry } from "./types-search.ts"
30
30
 
31
31
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
32
- const VERSION = "5.1.0"
32
+ const VERSION = "5.2.0"
33
33
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
34
34
  // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
35
35
  const docsHealth = (tools: McpTool[]): string =>
package/src/mcp-root.ts CHANGED
@@ -156,13 +156,13 @@ const isFile = (path: string): Promise<boolean> =>
156
156
  .catch(() => false)
157
157
 
158
158
  /**
159
- * The nifra projects among `dir`'s package-manager workspace members, in declaration order. Empty when
160
- * `dir` declares no `workspaces`. A member is a directory a pattern matches that holds a `package.json`;
161
- * `node_modules` is never a member.
159
+ * `dir`'s package-manager workspace members, in declaration order; `null` when `dir` declares no
160
+ * `workspaces`. A member is a directory a pattern matches that holds a `package.json`; `node_modules`
161
+ * is never a member.
162
162
  */
163
- export async function workspaceProjects(dir: string): Promise<string[]> {
163
+ export async function workspaceMemberDirs(dir: string): Promise<string[] | null> {
164
164
  const patterns = await workspacePatterns(dir)
165
- if (patterns === null) return []
165
+ if (patterns === null) return null
166
166
  const members = new Set<string>()
167
167
  const budget = { directories: MAX_WORKSPACE_DIRECTORIES }
168
168
  for (const pattern of patterns) {
@@ -171,8 +171,14 @@ export async function workspaceProjects(dir: string): Promise<string[]> {
171
171
  members.add(join(dir, member))
172
172
  }
173
173
  }
174
+ return [...members]
175
+ }
176
+
177
+ /** The nifra projects among `dir`'s workspace members, in declaration order. */
178
+ export async function workspaceProjects(dir: string): Promise<string[]> {
174
179
  const projects: string[] = []
175
- for (const member of members) if (await isNifraProjectDir(member)) projects.push(member)
180
+ for (const member of (await workspaceMemberDirs(dir)) ?? [])
181
+ if (await isNifraProjectDir(member)) projects.push(member)
176
182
  return projects
177
183
  }
178
184
 
@@ -376,7 +382,7 @@ export interface ToolingDrift {
376
382
  export const driftNote = (drift: ToolingDrift): string =>
377
383
  `WARNING: this server runs nifra CLI ${drift.cli}, but the project installs ${drift.package} ${drift.project}. ` +
378
384
  "Types, checks, and docs may describe a different version than your code builds with. " +
379
- `Fix: re-pin the project's MCP launch to the nifra it installs with \`${syncMcpCommand(drift.cli)}\` (run in the project directory), then restart the agent. ` +
385
+ `Fix: point the project's MCP launch at the nifra it installs with \`${syncMcpCommand(drift.cli)}\` (run in the project directory), then restart the agent. ` +
380
386
  "If this server is not launched from the project's .mcp.json, run the project's own CLI instead (`bunx --bun nifra mcp` from the project directory, or point the client at ./node_modules/.bin/nifra)."
381
387
 
382
388
  /** Feature-level agreement. Patch drift is not reported: it never changes the surface being described. */
@@ -434,7 +440,7 @@ export async function installedNifraVersion(
434
440
  return undefined
435
441
  }
436
442
 
437
- /** The command that re-pins a project's MCP launch to the nifra it installs. Named with the running
443
+ /** The command that points a project's MCP launch at the nifra it installs. Named with the running
438
444
  * CLI's own exact version: the binary printing this is the one known to have `--sync-mcp`, and it pins
439
445
  * to the project's version, not its own. */
440
446
  export const syncMcpCommand = (cliVersion: string): string =>