@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
package/src/cli.ts CHANGED
@@ -129,6 +129,8 @@ Usage:
129
129
  nifra explain [<message>] [--stack <s>] [--name <n>] A structured diagnostic for an error: its
130
130
  code, the frame in your source, and the cause and fix when
131
131
  nifra knows them. No message: the dev server's latest error.
132
+ A rule code (NF-C007): what that check rule reports and how
133
+ to fix it.
132
134
  nifra cdn-check <url> Check a deployed page behind a CDN: served from cache, no
133
135
  internal or CDN-only headers reaching the visitor, and soft
134
136
  navigations get page data, not the cached document. Exits 1
@@ -180,12 +182,16 @@ Usage:
180
182
  structure" sections. No-clobber by default (skips a file you've
181
183
  customized); --force overwrites the owned files. AGENTS.md is
182
184
  only appended to, never overwritten.
183
- nifra init-agents --sync-mcp [--json] Re-pin an existing app's MCP launch to the nifra the project
185
+ nifra init-agents --sync-mcp [--json] Move an existing app's MCP launch to the nifra the project
184
186
  installs: rewrites only the @nifrajs/cli@x.y.z version in
185
187
  .mcp.json, .cursor/mcp.json, CLAUDE.md and AGENTS.md's MCP
186
- section - every other byte stays as it is. Creates nothing.
188
+ section - every other byte stays as it is - and drops it
189
+ when the project declares @nifrajs/cli, so the launch runs
190
+ that install from then on. Creates nothing.
187
191
  At a workspace root with one nifra member, the two registries'
188
- launch also names that member (\`mcp app\`).
192
+ launch also names that member (\`mcp app\`). Run in a member,
193
+ it also re-pins the files above it, up to the repository
194
+ root, whose every nifra launch serves that member.
189
195
  nifra mcp [dir] Start an MCP server (stdio) exposing this project to a coding
190
196
  agent. The project root is [dir] when given, else resolved from
191
197
  cwd (marker walk-up + the client's MCP roots); tools refuse
@@ -271,11 +277,13 @@ Usage:
271
277
  [--list] [--json] apply exact imports, pin every matching dependency (keeping
272
278
  [--exact] ^/~, or exact with --exact), then verify with nifra check.
273
279
  [--allow-downgrade] Dry-run by default; --write applies then verifies (--no-verify
274
- [--no-hooks] to skip), then prints how hook scope changed (--no-hooks to
275
- skip). --list shows available targets. A version newer than
276
- this CLI prints the command for that release's CLI. Fail-closed
277
- on an unknown version or a rollback (--allow-downgrade
278
- overrides). Deterministic + idempotent.
280
+ [--allow-linked-skew] to skip), then prints how hook scope changed (--no-hooks to
281
+ [--no-hooks] skip). --list shows the targets with each newer release's
282
+ notes. A version newer than this CLI prints the command for
283
+ that release's CLI. Fail-closed on an unknown version, a
284
+ rollback (--allow-downgrade overrides), or a linked repository
285
+ that loads its own nifra at another version
286
+ (--allow-linked-skew overrides). Deterministic + idempotent.
279
287
  nifra migrate layout [--write] [--zones] [--json]
280
288
  Move an app onto the frontend/backend split: split each route
281
289
  into x.tsx + x.backend.ts, fold _middleware.ts into
@@ -303,8 +311,9 @@ Usage:
303
311
  [--json] [--strict] placeholder + tag parity, plural cases, script purity,
304
312
  untranslated messages. IMPORTS the entry (default: the first
305
313
  i18n.ts in ., lib/, src/, src/lib/, app/), which exports
306
- \`locales\` + \`catalogs\` (+ optional \`ignore\`). Exits 1 on
307
- errors; --strict also on warnings.
314
+ \`locales\` + \`catalogs\` (+ optional \`ignore\`), or a
315
+ \`copy\` from defineCopy(), whose tables it finds in the
316
+ source. Exits 1 on errors; --strict also on warnings.
308
317
 
309
318
  Reads nifra.config.ts (adapter + clientModule + plugins; or backend/framework.ts), backend/app.ts
310
319
  (optional), and routes/ from the current directory. Run from your project root.
@@ -321,7 +330,7 @@ set in the process environment is never overwritten by a file.
321
330
  ${renderCommandCatalogHelp()}`
322
331
 
323
332
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
324
- const CLI_VERSION = "5.1.0"
333
+ const CLI_VERSION = "5.2.0"
325
334
 
326
335
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
327
336
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
@@ -444,6 +453,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
444
453
  app.cwd,
445
454
  app.configPath,
446
455
  app.framework.define,
456
+ app.framework.publicEnvPrefix,
447
457
  )
448
458
  // Bun 1.4 on Windows may discard the script-relative portion of argv when `--config` is
449
459
  // present. Keep a second, authenticated copy of the user vector in the child's environment so
@@ -936,6 +946,7 @@ async function buildPrerenderApp(
936
946
  ...(client.routes ? { routePreload: client.routes } : {}),
937
947
  ...(client.css ? { styles: client.css } : {}),
938
948
  ...(client.routeStyles ? { routeStyles: client.routeStyles } : {}),
949
+ ...(client.copyChunks ? { copyChunks: client.copyChunks } : {}),
939
950
  ...(client.cssLoading !== undefined ? { cssLoading: client.cssLoading } : {}),
940
951
  })
941
952
  }
@@ -945,6 +956,7 @@ interface BuiltManifest {
945
956
  readonly routes?: Readonly<Record<string, readonly string[]>>
946
957
  readonly css?: readonly string[]
947
958
  readonly routeStyles?: Readonly<Record<string, readonly string[]>>
959
+ readonly copyChunks?: Readonly<Record<string, string>>
948
960
  readonly cssLoading?: CssLoadingMode
949
961
  }
950
962
 
@@ -1323,6 +1335,7 @@ async function main(): Promise<void> {
1323
1335
  verify: !argv.includes("--no-verify"),
1324
1336
  hooks: !argv.includes("--no-hooks"),
1325
1337
  allowDowngrade: argv.includes("--allow-downgrade"),
1338
+ allowLinkedSkew: argv.includes("--allow-linked-skew"),
1326
1339
  exact: argv.includes("--exact"),
1327
1340
  cliVersion: CLI_VERSION,
1328
1341
  })
@@ -1382,6 +1382,9 @@ const openApiSpec: CommandSpec<OpenApiInput, OpenApiCommandOutput> = {
1382
1382
  json: (out) => (out.format === "json" ? JSON.parse(out.text) : out.text),
1383
1383
  }
1384
1384
 
1385
+ // `render` cannot load doctor.ts, so each run's report is built beside its result.
1386
+ const doctorReports = new WeakMap<DoctorResult, readonly string[]>()
1387
+
1385
1388
  const doctorSpec: CommandSpec<DoctorInput, DoctorResult> = {
1386
1389
  name: "doctor",
1387
1390
  summary: "Find undeclared imports, duplicate identity installs, and pipeline readiness drift.",
@@ -1409,14 +1412,18 @@ const doctorSpec: CommandSpec<DoctorInput, DoctorResult> = {
1409
1412
  ...(value.strict === undefined ? {} : { strict: value.strict }),
1410
1413
  ...(ctx.cliVersion === undefined ? {} : { cliVersion: ctx.cliVersion }),
1411
1414
  }
1412
- return value.autoFix === true
1413
- ? mod.applyDoctorAutoFix(ctx.cwd, options)
1414
- : mod.collectDoctorResult(ctx.cwd, options)
1415
+ const result =
1416
+ value.autoFix === true
1417
+ ? await mod.applyDoctorAutoFix(ctx.cwd, options)
1418
+ : await mod.collectDoctorResult(ctx.cwd, options)
1419
+ doctorReports.set(result, mod.doctorReport(result, ctx.cliVersion))
1420
+ return result
1415
1421
  },
1416
- render: (out) => [
1417
- out.ok ? "✓ doctor passed" : "✖ doctor found issues",
1418
- ...out.findings.map((f) => ` ${f.file}:${f.line} ${f.package}`),
1419
- ],
1422
+ render: (out) =>
1423
+ doctorReports.get(out) ?? [
1424
+ out.ok ? "✓ doctor passed" : "✖ doctor found issues",
1425
+ ...out.findings.map((f) => ` ${f.file}:${f.line} ${f.package}`),
1426
+ ],
1420
1427
  success: (out) => out.ok,
1421
1428
  }
1422
1429
 
@@ -1570,7 +1577,8 @@ const migrateSpec: CommandSpec<MigrateInput, MigrateCommandOutput> = {
1570
1577
  ),
1571
1578
  ...out.issues.map((issue) => ` ⚠ ${issue.file}: ${issue.reason}`),
1572
1579
  ...out.followUps.map(
1573
- (step) => ` next ${step.file}: ${step.reason} - \`${step.command}\``,
1580
+ (step) =>
1581
+ ` next ${step.file}: ${step.reason}${step.command === undefined ? "" : ` - \`${step.command}\``}`,
1574
1582
  ),
1575
1583
  ...(out.write ? [] : [" dry run: pass --write to apply"]),
1576
1584
  ]
@@ -221,12 +221,16 @@ function relativeSpecifier(fromDir: string, target: string): string {
221
221
  * `singleCopy` is whether `package.json` declares `"nifra": { "singleCopy": [...] }`. The declared
222
222
  * resolver then runs where `buildClient` runs it, after the zone guard; an app that also lists
223
223
  * `singleCopyPlugin()` in `clientPlugins` gets its own instance in that place, once.
224
+ *
225
+ * `publicEnvPrefix` is the value `loadApp` resolved across both configs, written in as a literal:
226
+ * importing it from `configPath` would miss one set only in `backend/framework.ts`.
224
227
  */
225
228
  export function renderBoundaryPluginModule(
226
229
  configPath?: string,
227
230
  pluginDir?: string,
228
231
  servePlugins: readonly string[] = [],
229
232
  singleCopy = false,
233
+ publicEnvPrefix?: string,
230
234
  ): string {
231
235
  const appImport =
232
236
  configPath !== undefined && pluginDir !== undefined
@@ -264,22 +268,18 @@ export function renderBoundaryPluginModule(
264
268
  }
265
269
  `
266
270
  return `// Generated by \`nifra dev\` (Bun pipeline) - do not edit. Regenerated on every dev start.
267
- import { serverFnStubPlugin, zoneGuardPlugin } from "@nifrajs/web/build"
271
+ import { importGlobPlugin, serverFnStubPlugin, zoneGuardPlugin } from "@nifrajs/web/build"
268
272
  import { reserveDevSpecifiers } from "@nifrajs/web/internal/dev-reserved"
269
273
  import { cssModulesBunPlugin } from "@nifrajs/web/plugins/css-modules"
270
274
  ${singleCopy ? 'import { singleCopyPlugin } from "@nifrajs/core/single-copy"\n' : ""}${appImport}
271
275
  // This module lives at <app>/.nifra/dev-bun/, so the app root is two directories up.
272
276
  const appRoot = Bun.fileURLToPath(new URL("../../", import.meta.url))
273
277
  const zones = zoneGuardPlugin({
274
- appRoot,${
275
- appImport === ""
276
- ? ""
277
- : `
278
- ...(typeof appConfig.publicEnvPrefix === "string" ? { publicEnvPrefix: appConfig.publicEnvPrefix } : {}),`
279
- }
278
+ appRoot,${publicEnvPrefix === undefined ? "" : `\n publicEnvPrefix: ${JSON.stringify(publicEnvPrefix)},`}
280
279
  })
281
280
  const fn = serverFnStubPlugin()
282
281
  const cssModules = cssModulesBunPlugin("dom")
282
+ const globs = importGlobPlugin({ root: appRoot })
283
283
 
284
284
  export default {
285
285
  name: "nifra-dev-boundary",
@@ -292,7 +292,9 @@ ${singleCopy ? appPluginsSetup : ""} // Boundary first: an app plugin must ne
292
292
  zones.setup(guarded)
293
293
  ${singleCopySetup} fn.setup(guarded)
294
294
  cssModules.setup(guarded)
295
- ${appSetup}${serveSetup} },
295
+ ${appSetup}${serveSetup} // Last, as in buildClient: a module another plugin loads is that plugin's.
296
+ globs.setup(guarded)
297
+ },
296
298
  }
297
299
  `
298
300
  }
@@ -308,11 +310,12 @@ const TOKEN_FILE = "launch-token"
308
310
  /** Write the generated config for an app; returns the bunfig path to re-exec with and the fresh
309
311
  * launch token to pass in the child's environment. `configPath` (the app's `nifra.config.ts` /
310
312
  * `backend/framework.ts`) is what lets the app's own `clientPlugins` reach Bun's dev-server
311
- * bundler; `define` is the config's own. */
313
+ * bundler; `define` and `publicEnvPrefix` are the loaded config's own. */
312
314
  export async function writeBunDevConfig(
313
315
  appRoot: string,
314
316
  configPath?: string,
315
317
  define?: Readonly<Record<string, string>>,
318
+ publicEnvPrefix?: string,
316
319
  ): Promise<BunDevConfig> {
317
320
  const dir = resolve(appRoot, ".nifra", "dev-bun")
318
321
  mkdirSync(dir, { recursive: true })
@@ -328,6 +331,7 @@ export async function writeBunDevConfig(
328
331
  dir,
329
332
  userServePlugins(user, appRoot),
330
333
  readSingleCopyDeclaration(appRoot) !== undefined,
334
+ publicEnvPrefix,
331
335
  ),
332
336
  )
333
337
  const bunfigPath = resolve(dir, "bunfig.toml")
@@ -18,6 +18,13 @@ import type {
18
18
  import type { Diagnostic } from "@nifrajs/web/diagnostic"
19
19
  import type { CommandCtx, CommandSpec } from "./command-catalog.ts"
20
20
  import type { DevServerLookup, LiveDevServer } from "./dev-server-client.ts"
21
+ import {
22
+ isRuleExplanation,
23
+ RULE_CODE_SHAPE,
24
+ type RuleExplainOutput,
25
+ renderRuleExplanation,
26
+ type UnknownRuleOutput,
27
+ } from "./rule-explain.ts"
21
28
 
22
29
  const CATEGORIES: readonly DevErrorCategory[] = [
23
30
  "ssr",
@@ -802,22 +809,30 @@ export interface ExplainInput {
802
809
  readonly json?: boolean | undefined
803
810
  }
804
811
 
805
- /** A diagnostic, or `NIFRA_NONE` with why there was nothing to explain. */
812
+ /** A diagnostic, a rule code's catalog entry, or why there was nothing to explain. */
806
813
  export type ExplainOutput =
807
814
  | (Diagnostic & { readonly entry?: object; readonly note?: string })
815
+ | RuleExplainOutput
816
+ | UnknownRuleOutput
808
817
  | { code: "NIFRA_NONE"; message: string }
809
818
 
810
- const explained = (out: ExplainOutput): out is Diagnostic => out.code !== "NIFRA_NONE"
819
+ const isRuleOutput = (out: ExplainOutput): out is RuleExplainOutput =>
820
+ "kind" in out && out.kind === "rule"
821
+ const explained = (out: ExplainOutput): out is Diagnostic =>
822
+ out.code !== "NIFRA_NONE" && out.code !== "NIFRA_UNKNOWN_RULE" && !isRuleOutput(out)
811
823
 
812
824
  export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
813
825
  name: "explain",
814
826
  summary:
815
- "Turn an error into a structured diagnostic: its code, the frame in your source with a codeframe, and the cause and fix when nifra recognises it. With no message, the running dev server's latest error.",
827
+ "Turn an error into a structured diagnostic: its code, the frame in your source with a codeframe, and the cause and fix when nifra recognises it. With no message, the running dev server's latest error. A rule code such as NF-C007 explains that rule.",
816
828
  input: {
817
829
  jsonSchema: {
818
830
  type: "object",
819
831
  properties: {
820
- error: { type: "string", description: "The error message to explain." },
832
+ error: {
833
+ type: "string",
834
+ description: "The error message to explain, or a rule code such as NF-C007.",
835
+ },
821
836
  stack: {
822
837
  type: "string",
823
838
  description: "Its stack trace, for the codeframe and source frame.",
@@ -849,7 +864,17 @@ export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
849
864
  required: ["code", "message"],
850
865
  },
851
866
  parse: (value) => {
867
+ if (isRuleExplanation(value)) return value
852
868
  if (isDiagnostic(value)) return value
869
+ if (
870
+ typeof value === "object" &&
871
+ value !== null &&
872
+ "code" in value &&
873
+ value.code === "NIFRA_UNKNOWN_RULE" &&
874
+ "message" in value &&
875
+ typeof value.message === "string"
876
+ )
877
+ return { code: "NIFRA_UNKNOWN_RULE", message: value.message }
853
878
  if (
854
879
  typeof value === "object" &&
855
880
  value !== null &&
@@ -859,7 +884,9 @@ export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
859
884
  typeof value.message === "string"
860
885
  )
861
886
  return { code: "NIFRA_NONE", message: value.message }
862
- throw new TypeError("explain output must be a diagnostic or NIFRA_NONE")
887
+ throw new TypeError(
888
+ "explain output must be a diagnostic, a rule explanation, NIFRA_UNKNOWN_RULE or NIFRA_NONE",
889
+ )
863
890
  },
864
891
  },
865
892
  transports: ["cli"],
@@ -875,6 +902,11 @@ export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
875
902
  ],
876
903
  },
877
904
  async run(input, ctx) {
905
+ const code = input.error?.trim()
906
+ if (input.stack === undefined && code !== undefined && RULE_CODE_SHAPE.test(code)) {
907
+ const { explainRule } = await import("./rule-explain.ts")
908
+ return explainRule(code)
909
+ }
878
910
  const root = resolve(ctx.cwd, input.dir ?? ".")
879
911
  if (input.error === undefined && input.stack === undefined) {
880
912
  return explainLatest(root, input.port, ctx.signal)
@@ -888,6 +920,7 @@ export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
888
920
  return buildDiagnostic(error, { root, showSource: explainSourceGate(root) })
889
921
  },
890
922
  render: (out) => {
923
+ if (isRuleOutput(out)) return renderRuleExplanation(out)
891
924
  if (!explained(out)) return [out.message]
892
925
  const at = topFrame(out)
893
926
  return [
@@ -900,7 +933,8 @@ export const explainSpec: CommandSpec<ExplainInput, ExplainOutput> = {
900
933
  ...(out.fix === undefined ? [] : [` fix: ${out.fix}`]),
901
934
  ]
902
935
  },
903
- exitCode: (out) => (explained(out) ? 0 : 2),
936
+ exitCode: (out) =>
937
+ explained(out) || isRuleOutput(out) ? 0 : out.code === "NIFRA_UNKNOWN_RULE" ? 1 : 2,
904
938
  json: (out) => out,
905
939
  }
906
940
 
package/src/doctor.ts CHANGED
@@ -39,6 +39,12 @@ import {
39
39
  import { collectStaleMcpPins, type StaleMcpPin } from "./init-agents.ts"
40
40
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
41
41
  import { createSpecifierResolver } from "./internal/project-specifiers.ts"
42
+ import {
43
+ bunLockDir,
44
+ type StaleLinkLock,
45
+ staleLinkLockMessage,
46
+ staleLinkLocks,
47
+ } from "./lock-links.ts"
42
48
  import { detectToolingDrift, syncMcpCommand, type ToolingDrift } from "./mcp-root.ts"
43
49
  import { collectPipelineReport, type PipelineReport } from "./pipeline-report.ts"
44
50
  import { type ResolvedTarget, resolveTarget } from "./port.ts"
@@ -203,7 +209,18 @@ export interface DoctorResult {
203
209
  * the agent's server answers for a release the code no longer builds with. Advisory (never folded
204
210
  * into `ok`). Present only when at least one file is stale. Computed by {@link collectStaleMcpPins}.
205
211
  */
206
- readonly staleMcpPins?: { readonly target: string; readonly files: readonly StaleMcpPin[] }
212
+ readonly staleMcpPins?: {
213
+ /** The installed version a pin moves to, or `null` when the project declares `@nifrajs/cli` and
214
+ * the launch should drop its pin. */
215
+ readonly target: string | null
216
+ readonly files: readonly StaleMcpPin[]
217
+ }
218
+ /**
219
+ * `file:` entries of the project's bun.lock whose recorded dependencies the linked package.json no
220
+ * longer declares: Bun never refreshes them, so it installs a second copy under the linked package.
221
+ * Advisory (never folded into `ok`). `lock` is the lockfile, relative to the project.
222
+ */
223
+ readonly staleLinkLocks?: { readonly lock: string; readonly entries: readonly StaleLinkLock[] }
207
224
  /** Static production-readiness evidence for the selected deploy target. */
208
225
  readonly readiness?: DoctorReadiness
209
226
  /** The explicit source boundary used by the dependency scan. */
@@ -842,6 +859,8 @@ export async function collectDoctorResult(
842
859
  opts.cliVersion !== undefined ? await detectToolingDrift(cwd, opts.cliVersion) : undefined
843
860
  const staleMcpPins = await collectStaleMcpPins(cwd).catch(() => undefined)
844
861
  const versionDrift = collectVersionDrift(cwd, opts.cliVersion)
862
+ const lockDir = bunLockDir(cwd)
863
+ const linkLocks = lockDir === undefined ? [] : staleLinkLocks(lockDir)
845
864
  const handBuilt = handBuiltManifests(cwd, manifestLists)
846
865
  // `staleDists`, `toolingDrift` and `staleMcpPins` are advisory (see DoctorResult): they never fail `ok`.
847
866
  return {
@@ -863,6 +882,14 @@ export async function collectDoctorResult(
863
882
  ...(versionDrift !== undefined ? { versionDrift } : {}),
864
883
  ...(handBuilt.length > 0 ? { handBuiltManifests: handBuilt } : {}),
865
884
  ...(staleMcpPins !== undefined && staleMcpPins.files.length > 0 ? { staleMcpPins } : {}),
885
+ ...(lockDir !== undefined && linkLocks.length > 0
886
+ ? {
887
+ staleLinkLocks: {
888
+ lock: relative(cwd, join(lockDir, "bun.lock")).split(sep).join("/"),
889
+ entries: linkLocks,
890
+ },
891
+ }
892
+ : {}),
866
893
  ...(pipeline.ran ? { pipeline } : {}),
867
894
  }
868
895
  }
@@ -956,133 +983,142 @@ export async function runDoctor(
956
983
  const result = opts.autoFix
957
984
  ? await applyDoctorAutoFix(cwd, opts)
958
985
  : await collectDoctorResult(cwd, opts)
959
- if (opts.json) {
960
- console.log(JSON.stringify(result, null, 2))
961
- return result.ok
962
- }
963
- console.log("nifra doctor\n")
986
+ console.log(
987
+ opts.json ? JSON.stringify(result, null, 2) : doctorReport(result, opts.cliVersion).join("\n"),
988
+ )
989
+ return result.ok
990
+ }
991
+
992
+ /** The human report of a doctor run, one printed line per entry. */
993
+ export function doctorReport(result: DoctorResult, cliVersion?: string): string[] {
994
+ const lines: string[] = []
995
+ lines.push("nifra doctor\n")
964
996
  if (!result.ran) {
965
- console.log("• no package.json at this directory - nothing to check")
966
- return true
997
+ lines.push("• no package.json at this directory - nothing to check")
998
+ return lines
967
999
  }
968
1000
  if (result.fixed && result.fixed.length > 0) {
969
- console.log("✓ updated package.json dependencies:")
1001
+ lines.push("✓ updated package.json dependencies:")
970
1002
  for (const f of result.fixed) {
971
- console.log(` ${f.package}@${f.version} (${f.source})`)
1003
+ lines.push(` ${f.package}@${f.version} (${f.source})`)
972
1004
  }
973
- console.log("")
1005
+ lines.push("")
974
1006
  }
975
1007
  if (result.skippedFixes && result.skippedFixes.length > 0) {
976
- console.log("• not auto-fixed:")
1008
+ lines.push("• not auto-fixed:")
977
1009
  for (const f of result.skippedFixes) {
978
- console.log(` ${f.package} - ${f.reason}; run \`${f.command.join(" ")}\``)
1010
+ lines.push(` ${f.package} - ${f.reason}; run \`${f.command.join(" ")}\``)
979
1011
  }
980
- console.log("")
1012
+ lines.push("")
981
1013
  }
982
1014
  // Printed before the findings and regardless of ok: which bundler owns this app is the frame the
983
1015
  // rest of the report is read in, not a footnote to it.
984
1016
  if (result.pipeline !== undefined) {
985
1017
  const p = result.pipeline
986
- console.log(
1018
+ lines.push(
987
1019
  p.pipeline === "unknown"
988
1020
  ? `• bundler: could not be read from ${p.configFile} - ${p.reason}\n`
989
1021
  : `• bundler: ${p.pipeline} (${p.reason})\n`,
990
1022
  )
991
1023
  for (const f of p.findings) {
992
- console.log(`${f.severity === "error" ? "✗" : "⚠"} ${f.file}:${f.line ?? 0} ${f.message}`)
993
- console.log(` fix: ${f.fix}\n`)
1024
+ lines.push(`${f.severity === "error" ? "✗" : "⚠"} ${f.file}:${f.line ?? 0} ${f.message}`)
1025
+ lines.push(` fix: ${f.fix}\n`)
994
1026
  }
995
1027
  }
996
1028
  if (result.scanScope !== undefined) {
997
- console.log(
1029
+ lines.push(
998
1030
  `• dependency scan scope: ${result.scanScope.kind} (${result.scanScope.includeTests ? "includes tests" : "production package source only"})`,
999
1031
  )
1000
1032
  if (result.scanScope.excluded.length > 0)
1001
- console.log(` excluded: ${result.scanScope.excluded.join(", ")}`)
1002
- console.log("")
1033
+ lines.push(` excluded: ${result.scanScope.excluded.join(", ")}`)
1034
+ lines.push("")
1003
1035
  }
1004
1036
  // Advisory, printed regardless of ok: a stale linked dist doesn't fail doctor, but silently eating
1005
1037
  // it costs an hour of misdiagnosis when the dev server 500s inside the package.
1006
1038
  if (result.staleDists.length > 0) {
1007
- console.log(
1039
+ lines.push(
1008
1040
  `⚠ ${result.staleDists.length} workspace-linked package(s) with a build artifact older than their source (Bun reads src, Vite SSR/node consumers read dist):\n`,
1009
1041
  )
1010
1042
  for (const f of result.staleDists) {
1011
- console.log(
1043
+ lines.push(
1012
1044
  f.missing
1013
1045
  ? ` ${f.package} - ${f.distFile} was never built`
1014
1046
  : ` ${f.package} - ${f.distFile} is ${f.behindSeconds}s behind ${f.sourceFile}`,
1015
1047
  )
1016
- console.log(` rebuild ${f.package}`)
1048
+ lines.push(` rebuild ${f.package}`)
1017
1049
  }
1018
- console.log("")
1050
+ lines.push("")
1019
1051
  }
1020
1052
  if (result.readiness !== undefined) {
1021
1053
  const readiness = result.readiness
1022
- console.log(
1054
+ lines.push(
1023
1055
  `production readiness (${readiness.target}${readiness.targetSource === null ? "" : `, detected from ${readiness.targetSource}`}):\n`,
1024
1056
  )
1025
1057
  for (const item of readiness.items) {
1026
1058
  const marker =
1027
1059
  item.status === "configured" ? "✓" : item.status === "not-applicable" ? "-" : "✗"
1028
1060
  const evidence = item.evidence === undefined ? "" : ` (${item.evidence})`
1029
- console.log(` ${marker} ${item.label}: ${item.status}${evidence}`)
1061
+ lines.push(` ${marker} ${item.label}: ${item.status}${evidence}`)
1030
1062
  }
1031
1063
  if (readiness.strict && !readiness.ok) {
1032
- console.log("\n --strict: every applicable readiness rule must be configured")
1064
+ lines.push("\n --strict: every applicable readiness rule must be configured")
1033
1065
  }
1034
- console.log("")
1066
+ lines.push("")
1035
1067
  }
1036
1068
  // Advisory, printed regardless of ok: the binary answering is a different feature version than the
1037
1069
  // one the project builds with, so its types/checks/docs describe a surface the code does not have.
1038
1070
  if (result.toolingDrift !== undefined) {
1039
1071
  const drift = result.toolingDrift
1040
- console.log(
1072
+ lines.push(
1041
1073
  `⚠ this CLI is nifra ${drift.cli}, but the project installs ${drift.package} ${drift.project} - ` +
1042
1074
  "its types, checks, and docs may describe a different version than your code builds with.",
1043
1075
  )
1044
- console.log(
1045
- ` fix: \`${syncMcpCommand(drift.cli)}\` re-pins the project's MCP launch to the nifra it installs; ` +
1076
+ lines.push(
1077
+ ` fix: \`${syncMcpCommand(drift.cli)}\` points the project's MCP launch at the nifra it installs; ` +
1046
1078
  "for the CLI itself, run the project's own (`bunx --bun nifra doctor` from the project directory, " +
1047
1079
  "or ./node_modules/.bin/nifra)\n",
1048
1080
  )
1049
1081
  }
1050
1082
  if (result.versionDrift !== undefined) {
1051
- console.log(`⚠ ${versionDriftMessage(result.versionDrift)}\n`)
1083
+ lines.push(`⚠ ${versionDriftMessage(result.versionDrift)}\n`)
1084
+ }
1085
+ if (result.staleLinkLocks !== undefined) {
1086
+ lines.push(`⚠ ${staleLinkLockMessage(result.staleLinkLocks)}\n`)
1052
1087
  }
1053
1088
  for (const finding of result.handBuiltManifests ?? []) {
1054
- console.log(`⚠ ${handBuiltManifestMessage(finding)}\n`)
1089
+ lines.push(`⚠ ${handBuiltManifestMessage(finding)}\n`)
1055
1090
  }
1056
1091
  // Advisory: the agent's MCP server is launched from these pins, so a stale one answers for an old
1057
1092
  // release even when the CLI running doctor matches the project.
1058
1093
  if (result.staleMcpPins !== undefined) {
1059
1094
  const { target, files } = result.staleMcpPins
1060
- console.log(
1061
- `⚠ the MCP launch pins a nifra other than the project's ${target} - an agent's nifra server answers for that release:`,
1095
+ lines.push(
1096
+ target === null
1097
+ ? "⚠ the MCP launch pins a nifra release while the project installs its own CLI - an agent's nifra server answers for the pinned release:"
1098
+ : `⚠ the MCP launch pins a nifra other than the project's ${target} - an agent's nifra server answers for that release:`,
1062
1099
  )
1063
- for (const file of files)
1064
- console.log(` ${file.path}: @nifrajs/cli@${file.pinned.join(", ")}`)
1100
+ for (const file of files) lines.push(` ${file.path}: @nifrajs/cli@${file.pinned.join(", ")}`)
1065
1101
  const command =
1066
- opts.cliVersion !== undefined
1067
- ? syncMcpCommand(opts.cliVersion)
1068
- : "nifra init-agents --sync-mcp"
1069
- console.log(
1070
- ` fix: \`${command}\` rewrites only the pinned version, then restart the agent\n`,
1102
+ cliVersion !== undefined ? syncMcpCommand(cliVersion) : "nifra init-agents --sync-mcp"
1103
+ lines.push(
1104
+ target === null
1105
+ ? ` fix: \`${command}\` drops the pin so the launch runs the installed CLI from then on, then restart the agent\n`
1106
+ : ` fix: \`${command}\` rewrites only the pinned version, then restart the agent\n`,
1071
1107
  )
1072
1108
  }
1073
1109
  if (result.ok) {
1074
- console.log(
1110
+ lines.push(
1075
1111
  "✓ every imported package is declared and identity-sensitive installs are deduplicated",
1076
1112
  )
1077
- if (result.identityBasis !== undefined) console.log(` identity scan: ${result.identityBasis}`)
1113
+ if (result.identityBasis !== undefined) lines.push(` identity scan: ${result.identityBasis}`)
1078
1114
  // A partial scan that prints a bare ✓ is a lie by omission - the packages past the cap were never
1079
1115
  // looked at, and the reader has no way to know that from the tick alone.
1080
1116
  if (result.identityScanTruncated === true) {
1081
- console.log(
1117
+ lines.push(
1082
1118
  " ! the identity scan was truncated, so this is not a clean bill for the whole workspace",
1083
1119
  )
1084
1120
  }
1085
- return true
1121
+ return lines
1086
1122
  }
1087
1123
  // Group by package so the fix ("add X to dependencies") is stated once with its import sites.
1088
1124
  const byPkg = new Map<string, DoctorFinding[]>()
@@ -1092,52 +1128,52 @@ export async function runDoctor(
1092
1128
  byPkg.set(f.package, list)
1093
1129
  }
1094
1130
  if (byPkg.size > 0) {
1095
- console.log(`✗ ${byPkg.size} package(s) imported but not declared in package.json:\n`)
1131
+ lines.push(`✗ ${byPkg.size} package(s) imported but not declared in package.json:\n`)
1096
1132
  for (const [pkg, sites] of [...byPkg.entries()].sort()) {
1097
- console.log(` ${pkg} - add to dependencies (\`bun add ${pkg}\`)`)
1098
- for (const s of sites) console.log(` ${s.file}:${s.line}`)
1133
+ lines.push(` ${pkg} - add to dependencies (\`bun add ${pkg}\`)`)
1134
+ for (const s of sites) lines.push(` ${s.file}:${s.line}`)
1099
1135
  }
1100
1136
  }
1101
1137
  if (result.duplicateInstalls.length > 0) {
1102
- console.log(
1138
+ lines.push(
1103
1139
  `${byPkg.size > 0 ? "\n" : ""}✗ identity-sensitive packages resolve to multiple physical copies:\n`,
1104
1140
  )
1105
- if (result.identityBasis !== undefined) console.log(` scan: ${result.identityBasis}\n`)
1141
+ if (result.identityBasis !== undefined) lines.push(` scan: ${result.identityBasis}\n`)
1106
1142
  for (const finding of result.duplicateInstalls) {
1107
- console.log(` ${finding.package} [${finding.cause}]`)
1108
- console.log(` versions: ${finding.versions.join(", ")}`)
1143
+ lines.push(` ${finding.package} [${finding.cause}]`)
1144
+ lines.push(` versions: ${finding.versions.join(", ")}`)
1109
1145
  for (const copy of finding.copies) {
1110
- console.log(` ${copy.version} at ${copy.path} ← ${copy.importers.join(", ")}`)
1146
+ lines.push(` ${copy.version} at ${copy.path} ← ${copy.importers.join(", ")}`)
1111
1147
  }
1112
- console.log(` ${finding.explanation}`)
1148
+ lines.push(` ${finding.explanation}`)
1113
1149
  // A planted symlink is the cause no reinstall here can see, so it is named before the fix.
1114
- if (finding.provenance !== undefined) console.log(` links: ${finding.provenance}`)
1150
+ if (finding.provenance !== undefined) lines.push(` links: ${finding.provenance}`)
1115
1151
  // The shape of the split decides which fix can work, so it is printed above the fix itself.
1116
- if (finding.topology !== undefined) console.log(` topology: ${finding.topology}`)
1152
+ if (finding.topology !== undefined) lines.push(` topology: ${finding.topology}`)
1117
1153
  // Why a copy this directory never imports still counts. Without it, a workspace-wide answer
1118
1154
  // read from inside one app looks like the tool checking the wrong project.
1119
- if (finding.scope !== undefined) console.log(` scope: ${finding.scope}`)
1120
- console.log(` fix: ${finding.remediation}`)
1155
+ if (finding.scope !== undefined) lines.push(` scope: ${finding.scope}`)
1156
+ lines.push(` fix: ${finding.remediation}`)
1121
1157
  }
1122
1158
  }
1123
1159
  // Not a failure and not silence: the copies are real, and whoever reads this report needs to know
1124
1160
  // the graph is held together by a declaration rather than by the install.
1125
1161
  if (result.deduplicatedInstalls !== undefined && result.deduplicatedInstalls.length > 0) {
1126
- console.log("\n• identity-sensitive packages deduplicated by declaration:\n")
1162
+ lines.push("\n• identity-sensitive packages deduplicated by declaration:\n")
1127
1163
  for (const finding of result.deduplicatedInstalls) {
1128
- console.log(` ${finding.package} @ ${finding.versions.join(", ")}`)
1164
+ lines.push(` ${finding.package} @ ${finding.versions.join(", ")}`)
1129
1165
  for (const copy of finding.copies) {
1130
- console.log(` ${copy.path} ← ${copy.importers.join(", ")}`)
1166
+ lines.push(` ${copy.path} ← ${copy.importers.join(", ")}`)
1131
1167
  }
1132
- console.log(` ${finding.remediation}`)
1168
+ lines.push(` ${finding.remediation}`)
1133
1169
  }
1134
1170
  }
1135
1171
  if (result.readiness?.strict === true && result.readiness.ok === false) {
1136
- console.log("\n✗ production readiness is incomplete under --strict")
1172
+ lines.push("\n✗ production readiness is incomplete under --strict")
1137
1173
  }
1138
1174
  if (byPkg.size > 0)
1139
- console.log(
1175
+ lines.push(
1140
1176
  "\nThese resolve at Bun runtime via hoisting/workspace but break `tsc` and a standalone install.",
1141
1177
  )
1142
- return false
1178
+ return lines
1143
1179
  }