@nifrajs/cli 5.0.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 (296) hide show
  1. package/CHANGELOG.md +3211 -0
  2. package/README.md +10 -2
  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 +5 -2
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts +12 -2
  11. package/dist/assure.d.ts.map +1 -1
  12. package/dist/assure.js +73 -9
  13. package/dist/assure.js.map +1 -1
  14. package/dist/capabilities-tool.d.ts.map +1 -1
  15. package/dist/capabilities-tool.js +152 -49
  16. package/dist/capabilities-tool.js.map +1 -1
  17. package/dist/check-diagnostics.d.ts +7 -0
  18. package/dist/check-diagnostics.d.ts.map +1 -1
  19. package/dist/check-diagnostics.js +3 -0
  20. package/dist/check-diagnostics.js.map +1 -1
  21. package/dist/check-scan.d.ts +8 -2
  22. package/dist/check-scan.d.ts.map +1 -1
  23. package/dist/check-scan.js +49 -13
  24. package/dist/check-scan.js.map +1 -1
  25. package/dist/check.d.ts.map +1 -1
  26. package/dist/check.js +91 -45
  27. package/dist/check.js.map +1 -1
  28. package/dist/cli.d.ts +2 -0
  29. package/dist/cli.d.ts.map +1 -1
  30. package/dist/cli.js +128 -59
  31. package/dist/cli.js.map +1 -1
  32. package/dist/client-module.d.ts +5 -3
  33. package/dist/client-module.d.ts.map +1 -1
  34. package/dist/client-module.js +34 -10
  35. package/dist/client-module.js.map +1 -1
  36. package/dist/command-catalog.d.ts +9 -1
  37. package/dist/command-catalog.d.ts.map +1 -1
  38. package/dist/command-catalog.js +75 -26
  39. package/dist/command-catalog.js.map +1 -1
  40. package/dist/dev-bun-config.d.ts +6 -3
  41. package/dist/dev-bun-config.d.ts.map +1 -1
  42. package/dist/dev-bun-config.js +13 -10
  43. package/dist/dev-bun-config.js.map +1 -1
  44. package/dist/dev-feed-tool.d.ts +19 -1
  45. package/dist/dev-feed-tool.d.ts.map +1 -1
  46. package/dist/dev-feed-tool.js +114 -0
  47. package/dist/dev-feed-tool.js.map +1 -1
  48. package/dist/doctor.d.ts +15 -1
  49. package/dist/doctor.d.ts.map +1 -1
  50. package/dist/doctor.js +79 -61
  51. package/dist/doctor.js.map +1 -1
  52. package/dist/fix-recipes.d.ts +2 -0
  53. package/dist/fix-recipes.d.ts.map +1 -1
  54. package/dist/fix-recipes.js +93 -12
  55. package/dist/fix-recipes.js.map +1 -1
  56. package/dist/i18n-check.d.ts +11 -1
  57. package/dist/i18n-check.d.ts.map +1 -1
  58. package/dist/i18n-check.js +170 -17
  59. package/dist/i18n-check.js.map +1 -1
  60. package/dist/init-agents.d.ts +60 -4
  61. package/dist/init-agents.d.ts.map +1 -1
  62. package/dist/init-agents.js +196 -33
  63. package/dist/init-agents.js.map +1 -1
  64. package/dist/internal/config-paths.d.ts +16 -0
  65. package/dist/internal/config-paths.d.ts.map +1 -0
  66. package/dist/internal/config-paths.js +124 -0
  67. package/dist/internal/config-paths.js.map +1 -0
  68. package/dist/internal/installed-package.d.ts +4 -0
  69. package/dist/internal/installed-package.d.ts.map +1 -0
  70. package/dist/internal/installed-package.js +17 -0
  71. package/dist/internal/installed-package.js.map +1 -0
  72. package/dist/internal/project-specifiers.d.ts +14 -1
  73. package/dist/internal/project-specifiers.d.ts.map +1 -1
  74. package/dist/internal/project-specifiers.js +63 -16
  75. package/dist/internal/project-specifiers.js.map +1 -1
  76. package/dist/internal/source-facts.d.ts +12 -1
  77. package/dist/internal/source-facts.d.ts.map +1 -1
  78. package/dist/internal/source-facts.js +117 -5
  79. package/dist/internal/source-facts.js.map +1 -1
  80. package/dist/internal/typescript-import.d.ts.map +1 -1
  81. package/dist/internal/typescript-import.js +5 -3
  82. package/dist/internal/typescript-import.js.map +1 -1
  83. package/dist/internal/workspace-packages.d.ts +22 -0
  84. package/dist/internal/workspace-packages.d.ts.map +1 -0
  85. package/dist/internal/workspace-packages.js +215 -0
  86. package/dist/internal/workspace-packages.js.map +1 -0
  87. package/dist/introspect.d.ts +9 -0
  88. package/dist/introspect.d.ts.map +1 -1
  89. package/dist/introspect.js +32 -1
  90. package/dist/introspect.js.map +1 -1
  91. package/dist/levels-tool.d.ts.map +1 -1
  92. package/dist/levels-tool.js +5 -8
  93. package/dist/levels-tool.js.map +1 -1
  94. package/dist/load.d.ts +9 -4
  95. package/dist/load.d.ts.map +1 -1
  96. package/dist/load.js +32 -3
  97. package/dist/load.js.map +1 -1
  98. package/dist/lock-links.d.ts +42 -0
  99. package/dist/lock-links.d.ts.map +1 -0
  100. package/dist/lock-links.js +144 -0
  101. package/dist/lock-links.js.map +1 -0
  102. package/dist/mcp-context.d.ts.map +1 -1
  103. package/dist/mcp-context.js +6 -21
  104. package/dist/mcp-context.js.map +1 -1
  105. package/dist/mcp-delegate.d.ts +2 -2
  106. package/dist/mcp-delegate.d.ts.map +1 -1
  107. package/dist/mcp-delegate.js +19 -7
  108. package/dist/mcp-delegate.js.map +1 -1
  109. package/dist/mcp-exec.d.ts +1 -0
  110. package/dist/mcp-exec.d.ts.map +1 -1
  111. package/dist/mcp-exec.js +13 -5
  112. package/dist/mcp-exec.js.map +1 -1
  113. package/dist/mcp-http.js +1 -1
  114. package/dist/mcp-io.d.ts +13 -0
  115. package/dist/mcp-io.d.ts.map +1 -1
  116. package/dist/mcp-io.js +23 -0
  117. package/dist/mcp-io.js.map +1 -1
  118. package/dist/mcp-path.d.ts +2 -1
  119. package/dist/mcp-path.d.ts.map +1 -1
  120. package/dist/mcp-path.js +9 -24
  121. package/dist/mcp-path.js.map +1 -1
  122. package/dist/mcp-root.d.ts +6 -4
  123. package/dist/mcp-root.d.ts.map +1 -1
  124. package/dist/mcp-root.js +12 -8
  125. package/dist/mcp-root.js.map +1 -1
  126. package/dist/mcp.d.ts.map +1 -1
  127. package/dist/mcp.js +40 -17
  128. package/dist/mcp.js.map +1 -1
  129. package/dist/migrate-layout.d.ts +41 -1
  130. package/dist/migrate-layout.d.ts.map +1 -1
  131. package/dist/migrate-layout.js +1729 -236
  132. package/dist/migrate-layout.js.map +1 -1
  133. package/dist/output-schemas.d.ts +34 -0
  134. package/dist/output-schemas.d.ts.map +1 -1
  135. package/dist/output-schemas.js +132 -21
  136. package/dist/output-schemas.js.map +1 -1
  137. package/dist/project-path.d.ts +6 -0
  138. package/dist/project-path.d.ts.map +1 -1
  139. package/dist/project-path.js +48 -14
  140. package/dist/project-path.js.map +1 -1
  141. package/dist/project-site.d.ts +7 -0
  142. package/dist/project-site.d.ts.map +1 -0
  143. package/dist/project-site.js +19 -0
  144. package/dist/project-site.js.map +1 -0
  145. package/dist/recipes/4.0.0.d.ts.map +1 -1
  146. package/dist/recipes/4.0.0.js +2 -0
  147. package/dist/recipes/4.0.0.js.map +1 -1
  148. package/dist/recipes/5.1.0.d.ts +9 -0
  149. package/dist/recipes/5.1.0.d.ts.map +1 -0
  150. package/dist/recipes/5.1.0.js +22 -0
  151. package/dist/recipes/5.1.0.js.map +1 -0
  152. package/dist/recipes/5.2.0.d.ts +10 -0
  153. package/dist/recipes/5.2.0.d.ts.map +1 -0
  154. package/dist/recipes/5.2.0.js +32 -0
  155. package/dist/recipes/5.2.0.js.map +1 -0
  156. package/dist/recipes/index.d.ts +3 -0
  157. package/dist/recipes/index.d.ts.map +1 -1
  158. package/dist/recipes/index.js +7 -0
  159. package/dist/recipes/index.js.map +1 -1
  160. package/dist/release-verification.d.ts +5 -0
  161. package/dist/release-verification.d.ts.map +1 -1
  162. package/dist/release-verification.js +14 -0
  163. package/dist/release-verification.js.map +1 -1
  164. package/dist/review.d.ts.map +1 -1
  165. package/dist/review.js +7 -0
  166. package/dist/review.js.map +1 -1
  167. package/dist/rule-explain.d.ts +26 -0
  168. package/dist/rule-explain.d.ts.map +1 -0
  169. package/dist/rule-explain.js +49 -0
  170. package/dist/rule-explain.js.map +1 -0
  171. package/dist/rules/codes.d.ts +5 -1
  172. package/dist/rules/codes.d.ts.map +1 -1
  173. package/dist/rules/codes.js +5 -1
  174. package/dist/rules/codes.js.map +1 -1
  175. package/dist/rules/contract-visibility.d.ts.map +1 -1
  176. package/dist/rules/contract-visibility.js +93 -21
  177. package/dist/rules/contract-visibility.js.map +1 -1
  178. package/dist/rules/data-guard.d.ts +6 -0
  179. package/dist/rules/data-guard.d.ts.map +1 -1
  180. package/dist/rules/data-guard.js +37 -0
  181. package/dist/rules/data-guard.js.map +1 -1
  182. package/dist/rules/explanations.d.ts +14 -0
  183. package/dist/rules/explanations.d.ts.map +1 -0
  184. package/dist/rules/explanations.js +316 -0
  185. package/dist/rules/explanations.js.map +1 -0
  186. package/dist/rules/legacy.d.ts.map +1 -1
  187. package/dist/rules/legacy.js +44 -2
  188. package/dist/rules/legacy.js.map +1 -1
  189. package/dist/rules/merge-auth.d.ts +12 -0
  190. package/dist/rules/merge-auth.d.ts.map +1 -0
  191. package/dist/rules/merge-auth.js +52 -0
  192. package/dist/rules/merge-auth.js.map +1 -0
  193. package/dist/rules/pages.d.ts +56 -3
  194. package/dist/rules/pages.d.ts.map +1 -1
  195. package/dist/rules/pages.js +412 -23
  196. package/dist/rules/pages.js.map +1 -1
  197. package/dist/rules/routes.d.ts +3 -2
  198. package/dist/rules/routes.d.ts.map +1 -1
  199. package/dist/rules/routes.js +4 -3
  200. package/dist/rules/routes.js.map +1 -1
  201. package/dist/rules/security.d.ts +3 -2
  202. package/dist/rules/security.d.ts.map +1 -1
  203. package/dist/rules/security.js +42 -11
  204. package/dist/rules/security.js.map +1 -1
  205. package/dist/rules/zones.d.ts.map +1 -1
  206. package/dist/rules/zones.js +34 -11
  207. package/dist/rules/zones.js.map +1 -1
  208. package/dist/stylex-migrate.d.ts.map +1 -1
  209. package/dist/stylex-migrate.js +127 -17
  210. package/dist/stylex-migrate.js.map +1 -1
  211. package/dist/test-tool.d.ts.map +1 -1
  212. package/dist/test-tool.js +3 -9
  213. package/dist/test-tool.js.map +1 -1
  214. package/dist/typecheck-coverage.d.ts +11 -0
  215. package/dist/typecheck-coverage.d.ts.map +1 -1
  216. package/dist/typecheck-coverage.js +50 -7
  217. package/dist/typecheck-coverage.js.map +1 -1
  218. package/dist/upgrade.d.ts +57 -6
  219. package/dist/upgrade.d.ts.map +1 -1
  220. package/dist/upgrade.js +247 -19
  221. package/dist/upgrade.js.map +1 -1
  222. package/dist/verification-plan.d.ts.map +1 -1
  223. package/dist/verification-plan.js +7 -2
  224. package/dist/verification-plan.js.map +1 -1
  225. package/dist/version-drift.d.ts.map +1 -1
  226. package/dist/version-drift.js +66 -3
  227. package/dist/version-drift.js.map +1 -1
  228. package/dist/web-app-options.d.ts +1 -1
  229. package/dist/web-app-options.d.ts.map +1 -1
  230. package/dist/web-app-options.js.map +1 -1
  231. package/docs/examples.json +21 -3
  232. package/docs/llms-full.txt +1083 -168
  233. package/docs/types.json +535 -112
  234. package/package.json +13 -12
  235. package/src/agent-files.ts +27 -17
  236. package/src/assure-hydration.ts +5 -1
  237. package/src/assure.ts +99 -11
  238. package/src/capabilities-tool.ts +188 -53
  239. package/src/check-diagnostics.ts +10 -0
  240. package/src/check-scan.ts +65 -12
  241. package/src/check.ts +122 -51
  242. package/src/cli.ts +127 -45
  243. package/src/client-module.ts +45 -9
  244. package/src/command-catalog.ts +92 -28
  245. package/src/dev-bun-config.ts +13 -9
  246. package/src/dev-feed-tool.ts +146 -1
  247. package/src/doctor.ts +102 -66
  248. package/src/fix-recipes.ts +101 -10
  249. package/src/i18n-check.ts +254 -18
  250. package/src/init-agents.ts +225 -44
  251. package/src/internal/config-paths.ts +154 -0
  252. package/src/internal/installed-package.ts +15 -0
  253. package/src/internal/project-specifiers.ts +78 -17
  254. package/src/internal/source-facts.ts +147 -5
  255. package/src/internal/typescript-import.ts +5 -3
  256. package/src/internal/workspace-packages.ts +218 -0
  257. package/src/introspect.ts +39 -1
  258. package/src/levels-tool.ts +7 -9
  259. package/src/load.ts +46 -4
  260. package/src/lock-links.ts +173 -0
  261. package/src/mcp-context.ts +5 -18
  262. package/src/mcp-delegate.ts +22 -10
  263. package/src/mcp-exec.ts +14 -4
  264. package/src/mcp-http.ts +1 -1
  265. package/src/mcp-io.ts +33 -0
  266. package/src/mcp-path.ts +8 -22
  267. package/src/mcp-root.ts +14 -8
  268. package/src/mcp.ts +48 -19
  269. package/src/migrate-layout.ts +1968 -245
  270. package/src/output-schemas.ts +179 -23
  271. package/src/project-path.ts +44 -13
  272. package/src/project-site.ts +18 -0
  273. package/src/recipes/4.0.0.ts +2 -0
  274. package/src/recipes/5.1.0.ts +23 -0
  275. package/src/recipes/5.2.0.ts +33 -0
  276. package/src/recipes/index.ts +7 -0
  277. package/src/release-verification.ts +20 -0
  278. package/src/review.ts +7 -0
  279. package/src/rule-explain.ts +75 -0
  280. package/src/rules/codes.ts +5 -1
  281. package/src/rules/contract-visibility.ts +118 -20
  282. package/src/rules/data-guard.ts +40 -0
  283. package/src/rules/explanations.ts +329 -0
  284. package/src/rules/legacy.ts +46 -2
  285. package/src/rules/merge-auth.ts +55 -0
  286. package/src/rules/pages.ts +486 -25
  287. package/src/rules/routes.ts +4 -3
  288. package/src/rules/security.ts +49 -11
  289. package/src/rules/zones.ts +33 -9
  290. package/src/stylex-migrate.ts +117 -17
  291. package/src/test-tool.ts +3 -9
  292. package/src/typecheck-coverage.ts +51 -6
  293. package/src/upgrade.ts +312 -19
  294. package/src/verification-plan.ts +15 -2
  295. package/src/version-drift.ts +68 -2
  296. package/src/web-app-options.ts +9 -1
@@ -74,8 +74,9 @@ function unexpectedMessage(
74
74
  const parentOf = (dir: string): string => dir.slice(0, Math.max(dir.lastIndexOf("/"), 0))
75
75
 
76
76
  /**
77
- * Whether NF-S002 may treat `file` as browser code, which compares values the client already holds,
78
- * so a finding there is advisory. It must be browser code by path (a route's frontend half,
77
+ * Whether NF-S001 and NF-S002 may treat `file` as browser code, where a finding is advisory: a
78
+ * browser compares values the client already holds, and a gate there that fails open grants nothing
79
+ * the server does not check again. It must be browser code by path (a route's frontend half,
79
80
  * `frontend/`) and sit inside a nifra web app: a `routes/` folder in an API-only project or a package
80
81
  * without a web dependency runs on the server. `shared/` also runs on the server, and a file that
81
82
  * cannot be classified is treated as server - fail closed.
@@ -557,29 +558,46 @@ const GATE_NAMES = [
557
558
  /^(?:require|assert|authori[sz]e|authenticate)/i,
558
559
  /^can[A-Z]/,
559
560
  /.Guard$/,
560
- /^(?:ensure|verify|check|validate)(?:Auth|LoggedIn|Login|Session|Token|Jwt|JWT|Signature|Webhook|Hmac|HMAC|Password|Credential|Permission|Access|Role|Admin|Owner|Scope|Csrf|CSRF|ApiKey|Origin|Tenant|User|Member)/,
561
+ /^(?:ensure|verify|check|validate)(?:Auth\w*|LoggedIn|Login|Session|Token|Jwt|JWT|Signatures?|Webhook|Hmac|HMAC|Password|Credentials?|Permissions?|Access|Roles?|Admin(?:istrator)?|Owner(?:ship)?|Scopes?|Csrf|CSRF|ApiKey|Origin|Tenant|User|Member(?:ship)?)(?![a-z])/,
561
562
  ]
562
563
 
564
+ /** An authenticator returns who is calling, so its "nobody" result (`null`, `undefined`) is a denial. */
565
+ const AUTHENTICATOR = /^authenticate/i
566
+
567
+ /** Result-object fields whose `false` is the denial (`{ ok: false, error }`). */
568
+ const DECISION_FIELDS = new Set([
569
+ "ok",
570
+ "allowed",
571
+ "authorized",
572
+ "authenticated",
573
+ "valid",
574
+ "success",
575
+ "granted",
576
+ ])
577
+
563
578
  /** Helpers whose whole job is to fail (`fail(…)`, `deny(…)`, `reject(…)`, …). */
564
579
  const FAILING_HELPERS = new Set(["fail", "deny", "reject", "forbid", "unauthorized", "abort"])
565
580
 
566
581
  /**
567
- * Whether a gate's catch block fails closed: it throws, returns `false`, a `new Response(…)` or a
568
- * `deny…(…)` call, or hands the failure to a {@link FAILING_HELPERS} helper. The last form is why
582
+ * Whether a gate's catch block fails closed: it throws, returns `false`, a result object whose decision
583
+ * field is `false`, a `new Response(…)` or a `deny…(…)` call (an authenticator also `null` or
584
+ * nothing), or hands the failure to a {@link FAILING_HELPERS} helper. The last form is why
569
585
  * conformance/invariant asserts that funnel every error through a `never`-returning `fail()` are not
570
586
  * fail-open - the scanner reads no types, so it trusts the helper by name, the same trade the SQL and
571
587
  * gate-name heuristics already make. Read from the syntax, so a "throw" in a comment or a string counts
572
588
  * for nothing, and a nested function's statements are not the catch's own.
573
589
  */
574
- function failsClosed(ts: typeof TSApi, block: TSApi.Block): boolean {
590
+ function failsClosed(ts: typeof TSApi, block: TSApi.Block, gate: string): boolean {
591
+ const authenticator = AUTHENTICATOR.test(gate)
575
592
  let closed = false
576
593
  const visit = (node: TSApi.Node): void => {
577
594
  if (closed || ts.isFunctionLike(node)) return
578
595
  if (
579
596
  ts.isThrowStatement(node) ||
580
597
  (ts.isReturnStatement(node) &&
581
- node.expression !== undefined &&
582
- isDenial(ts, node.expression)) ||
598
+ (node.expression === undefined
599
+ ? authenticator
600
+ : isDenial(ts, node.expression, authenticator))) ||
583
601
  (ts.isCallExpression(node) &&
584
602
  ts.isIdentifier(node.expression) &&
585
603
  FAILING_HELPERS.has(node.expression.text))
@@ -593,7 +611,7 @@ function failsClosed(ts: typeof TSApi, block: TSApi.Block): boolean {
593
611
  return closed
594
612
  }
595
613
 
596
- function isDenial(ts: typeof TSApi, expression: TSApi.Expression): boolean {
614
+ function isDenial(ts: typeof TSApi, expression: TSApi.Expression, authenticator: boolean): boolean {
597
615
  let value = expression
598
616
  while (
599
617
  ts.isParenthesizedExpression(value) ||
@@ -603,6 +621,22 @@ function isDenial(ts: typeof TSApi, expression: TSApi.Expression): boolean {
603
621
  )
604
622
  value = value.expression
605
623
  if (value.kind === ts.SyntaxKind.FalseKeyword) return true
624
+ if (
625
+ authenticator &&
626
+ (value.kind === ts.SyntaxKind.NullKeyword ||
627
+ ts.isVoidExpression(value) ||
628
+ (ts.isIdentifier(value) && value.text === "undefined"))
629
+ )
630
+ return true
631
+ if (ts.isObjectLiteralExpression(value)) {
632
+ return value.properties.some(
633
+ (property) =>
634
+ ts.isPropertyAssignment(property) &&
635
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
636
+ DECISION_FIELDS.has(property.name.text) &&
637
+ property.initializer.kind === ts.SyntaxKind.FalseKeyword,
638
+ )
639
+ }
606
640
  if (ts.isNewExpression(value))
607
641
  return ts.isIdentifier(value.expression) && value.expression.text === "Response"
608
642
  return (
@@ -621,23 +655,26 @@ export const failOpenGateRule: CheckRule = {
621
655
  const ts = loaded.compiler
622
656
  if (ts === undefined) return didNotRun("NF-S001", "Fail-open gate scan")
623
657
  const findings: Diagnostic[] = []
658
+ const webDirs = createWebAppProbe(ctx.root)
624
659
  for (const file of ctx.project.source.files) {
625
660
  const parsed = parsedFile(ts, ctx.project.source, file)
626
661
  if (parsed === undefined) continue
627
662
  const { tree, lines } = parsed
663
+ let browser: boolean | undefined
628
664
  const visit = (node: TSApi.Node): void => {
629
665
  if (ts.isCatchClause(node)) {
630
666
  let parent: TSApi.Node | undefined = node.parent
631
667
  while (parent !== undefined && !ts.isFunctionLike(parent)) parent = parent.parent
632
668
  const name = parent === undefined ? undefined : functionName(ts, parent)
633
669
  if (name !== undefined && GATE_NAMES.some((gate) => gate.test(name))) {
634
- if (!failsClosed(ts, node.block)) {
670
+ if (!failsClosed(ts, node.block, name)) {
635
671
  const line = tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1
636
672
  const reviewed = expectedReason(lines, line, "NF-S001") !== undefined
673
+ browser ??= provenBrowserFile(ctx.root, file, webDirs)
637
674
  findings.push(
638
675
  diagnostic({
639
676
  code: "NF-S001",
640
- severity: reviewed ? "info" : "error",
677
+ severity: reviewed ? "info" : browser ? "warn" : "error",
641
678
  file,
642
679
  line,
643
680
  message: reviewed
@@ -651,6 +688,7 @@ export const failOpenGateRule: CheckRule = {
651
688
  evidence: [
652
689
  name,
653
690
  "catch block has no denial or rethrow",
691
+ ...(browser ? ["browser code: the server's own gate decides"] : []),
654
692
  ...expectationEvidence(lines, line, "NF-S001"),
655
693
  ],
656
694
  verify: "nifra check --lints-only",
@@ -17,6 +17,7 @@ import {
17
17
  importRuleMessage,
18
18
  privateEnvReads,
19
19
  privateEnvReason,
20
+ specifierPackage,
20
21
  type ZoneClassifier,
21
22
  ZoneConfigError,
22
23
  } from "@nifrajs/web/zones"
@@ -26,6 +27,7 @@ import { appDirs, clientModuleRoot } from "../client-module.ts"
26
27
  import { componentCheckReceipts } from "../component-check.ts"
27
28
  import { type Diagnostic, diagnostic } from "../diagnostics.ts"
28
29
  import { codeUnitOrder } from "../internal/code-unit-order.ts"
30
+ import { installedManifest } from "../internal/installed-package.ts"
29
31
  import {
30
32
  createApiOnlyProbe,
31
33
  createKindProbe,
@@ -35,7 +37,9 @@ import {
35
37
  withApiKindHint,
36
38
  } from "../internal/nifra-project.ts"
37
39
  import { createSpecifierResolver } from "../internal/project-specifiers.ts"
40
+ import { createSourceFacts } from "../internal/source-facts.ts"
38
41
  import type { CheckRule, RuleContext } from "./index.ts"
42
+ import { loadRuleTypeScript } from "./typescript.ts"
39
43
 
40
44
  const ZONE_FOLDER = new Set(["routes", "frontend", "backend", "shared"])
41
45
  const FRONTEND = new Set(["route-frontend", "frontend"])
@@ -186,6 +190,15 @@ export const zoneImportRule: CheckRule = {
186
190
  // Outside any web app, a finding may only mean the project serves no pages: say how to declare it.
187
191
  const inWebApp = createWebAppProbe(ctx.root)
188
192
  const resolveSpecifier = createSpecifierResolver()
193
+ // Without a compiler nothing proves an import erased, so every import stays an edge.
194
+ const { compiler } = await loadRuleTypeScript(ctx)
195
+ const facts =
196
+ compiler === undefined
197
+ ? undefined
198
+ : createSourceFacts(compiler, {
199
+ keepsTypeOnlyImports: (file) =>
200
+ resolveSpecifier.keepsTypeOnlyImports(isAbsolute(file) ? file : join(ctx.root, file)),
201
+ })
189
202
  const queue: Importer[] = []
190
203
  const queued = new Set<string>()
191
204
  const follow = (importer: Importer): void => {
@@ -201,7 +214,7 @@ export const zoneImportRule: CheckRule = {
201
214
  // The browser entry imports the app's `clientModule`, so the build classifies it like any file it
202
215
  // loads, and loads what it imports.
203
216
  for (const app of appDirs(ctx.sources.files)) {
204
- const entry = clientModuleRoot(ctx.root, app, resolveSpecifier)
217
+ const entry = clientModuleRoot(ctx.root, app, resolveSpecifier, compiler)
205
218
  if (entry === undefined) continue
206
219
  let classification: Classification
207
220
  try {
@@ -235,11 +248,21 @@ export const zoneImportRule: CheckRule = {
235
248
  for (const { file, app, zone: from } of queue) {
236
249
  const content = ctx.sources.read(file)
237
250
  if (content === undefined) continue
238
- for (const { specifier, line } of importSites(content, file)) {
239
- const target = resolveSpecifier(join(ctx.root, file), specifier)
240
- if (target === undefined) continue
241
- const to = classifierFor(app).classify(target)
242
- const targetName = display(ctx.root, target)
251
+ for (const { specifier, line } of importSites(content, file, facts)) {
252
+ let target = resolveSpecifier(join(ctx.root, file), specifier)
253
+ let to: Classification
254
+ if (target === undefined) {
255
+ // An installed package is judged here only by the entry it names, when it gives each
256
+ // entry its own side; a package-wide side is NF-C004's in browser code.
257
+ const name = specifierPackage(specifier)
258
+ const manifest =
259
+ name === undefined ? undefined : installedManifest(join(ctx.root, file), name)
260
+ if (manifest === undefined) continue
261
+ to = classifierFor(app).classify(manifest, specifier)
262
+ if (to.entry === undefined) continue
263
+ target = manifest
264
+ } else to = classifierFor(app).classify(target, specifier)
265
+ const targetName = to.entry === undefined ? display(ctx.root, target) : specifier
243
266
  if (
244
267
  ["frontend", "route-frontend", "shared"].includes(from) &&
245
268
  (receipts.has(target) || receipts.has(targetName))
@@ -250,7 +273,7 @@ export const zoneImportRule: CheckRule = {
250
273
  if (to.package !== undefined) {
251
274
  if (reportedPackages.has(to.package)) continue
252
275
  reportedPackages.add(to.package)
253
- } else {
276
+ } else if (to.entry === undefined) {
254
277
  // A file in no zone loads what it imports too: the build refuses each one it reaches.
255
278
  follow({ file: targetName, app, zone: "error" })
256
279
  }
@@ -311,9 +334,10 @@ export const apiKindRule: CheckRule = {
311
334
  const PREFIX_EXPORT =
312
335
  /\bexport\s+const\s+publicEnvPrefix\s*(?::\s*string\s*)?=\s*(?:"([^"\\\r\n]*)"|'([^'\\\r\n]*)')/
313
336
 
314
- /** The app's public-env prefix when its config declares it as a string literal, else the default. */
337
+ /** The app's public-env prefix when its config declares it as a string literal, else the default.
338
+ * nifra.config.ts is read first, as `loadApp` does. */
315
339
  function publicPrefix(root: string, app: string): string {
316
- for (const config of [FRAMEWORK_FILE, CONFIG_FILE]) {
340
+ for (const config of [CONFIG_FILE, FRAMEWORK_FILE]) {
317
341
  const path = join(root, app, config)
318
342
  if (!existsSync(path)) continue
319
343
  const match = PREFIX_EXPORT.exec(stripComments(readFileSync(path, "utf8")))
@@ -1099,27 +1099,126 @@ const existingStylexImport = (source: string): string | undefined => {
1099
1099
  return match?.[1]
1100
1100
  }
1101
1101
 
1102
- const insertionOffset = (source: string): number => {
1103
- let offset = source.startsWith("#!") ? source.indexOf("\n") + 1 || source.length : 0
1104
- const lines = source.slice(offset).split(/(?<=\n)/)
1105
- let consumed = 0
1106
- let inImport = false
1107
- for (const line of lines) {
1108
- const trimmed = line.trim()
1109
- const directive = /^(['"])(?:use client|use server)\1;?$/.test(trimmed)
1110
- if (inImport || trimmed.startsWith("import ") || trimmed.startsWith("import{")) {
1111
- inImport = !/(?:from\s+["'][^"']+["']|import\s+["'][^"']+["'])\s*;?$/.test(trimmed)
1112
- consumed += line.length
1102
+ const isIdentifierChar = (char: string | undefined): boolean =>
1103
+ char !== undefined && /[\w$]/.test(char)
1104
+
1105
+ /** Past the whitespace and comments at `index`. `inLine` stops at the end of the line. */
1106
+ function skipTrivia(source: string, index: number, inLine = false): number {
1107
+ let at = index
1108
+ while (at < source.length) {
1109
+ const char = source[at]
1110
+ if (char === " " || char === "\t" || char === "\r" || (char === "\n" && !inLine)) at++
1111
+ else if (source.startsWith("//", at)) {
1112
+ const end = source.indexOf("\n", at)
1113
+ if (end === -1) return source.length
1114
+ at = inLine ? end : end + 1
1115
+ } else if (source.startsWith("/*", at)) {
1116
+ const end = source.indexOf("*/", at + 2)
1117
+ if (end === -1) return source.length
1118
+ at = end + 2
1119
+ } else break
1120
+ }
1121
+ return at
1122
+ }
1123
+
1124
+ function skipString(source: string, index: number): number {
1125
+ const quote = source[index]
1126
+ let at = index + 1
1127
+ while (at < source.length && source[at] !== quote && source[at] !== "\n")
1128
+ at += source[at] === "\\" ? 2 : 1
1129
+ return Math.min(at + 1, source.length)
1130
+ }
1131
+
1132
+ /** Past an import's specifier: its `with { ... }` (or `assert`) attributes and a `;`. */
1133
+ function afterSpecifier(source: string, index: number): number {
1134
+ let at = index
1135
+ const next = skipTrivia(source, at, true)
1136
+ for (const keyword of ["with", "assert"]) {
1137
+ if (!source.startsWith(keyword, next) || isIdentifierChar(source[next + keyword.length]))
1138
+ continue
1139
+ const open = skipTrivia(source, next + keyword.length)
1140
+ const close = source[open] === "{" ? source.indexOf("}", open) : -1
1141
+ if (close !== -1) at = close + 1
1142
+ }
1143
+ const semicolon = skipTrivia(source, at, true)
1144
+ return source[semicolon] === ";" ? semicolon + 1 : at
1145
+ }
1146
+
1147
+ /** Where the import declaration whose `import` keyword is at `index` ends, or `undefined` for an
1148
+ * `import(...)` / `import.meta` expression or a declaration this scan cannot read. */
1149
+ function importEnd(source: string, index: number): number | undefined {
1150
+ let at = skipTrivia(source, index + "import".length)
1151
+ if (source[at] === "(" || source[at] === ".") return undefined
1152
+ if (source[at] === '"' || source[at] === "'")
1153
+ return afterSpecifier(source, skipString(source, at))
1154
+ let depth = 0
1155
+ while (at < source.length) {
1156
+ const char = source[at]
1157
+ if (char === '"' || char === "'") {
1158
+ at = skipString(source, at)
1113
1159
  continue
1114
1160
  }
1115
- if (directive || trimmed === "") {
1116
- consumed += line.length
1161
+ if (source.startsWith("//", at) || source.startsWith("/*", at)) {
1162
+ at = skipTrivia(source, at)
1117
1163
  continue
1118
1164
  }
1119
- break
1165
+ if (char === "{") depth++
1166
+ else if (char === "}") depth--
1167
+ else if (depth === 0 && (char === ";" || char === "=")) return undefined
1168
+ else if (
1169
+ depth === 0 &&
1170
+ source.startsWith("from", at) &&
1171
+ !isIdentifierChar(source[at - 1]) &&
1172
+ !isIdentifierChar(source[at + 4])
1173
+ ) {
1174
+ const specifier = skipTrivia(source, at + 4)
1175
+ if (source[specifier] === '"' || source[specifier] === "'")
1176
+ return afterSpecifier(source, skipString(source, specifier))
1177
+ }
1178
+ at++
1179
+ }
1180
+ return undefined
1181
+ }
1182
+
1183
+ /** Past the rest of the line `index` is on when only trivia is left on it, then any blank lines. */
1184
+ function nextLine(source: string, index: number): number {
1185
+ let at = skipTrivia(source, index, true)
1186
+ if (at < source.length && source[at] !== "\n") return index
1187
+ for (;;) {
1188
+ if (source[at] !== "\n") return at
1189
+ let next = at + 1
1190
+ while (source[next] === " " || source[next] === "\t" || source[next] === "\r") next++
1191
+ if (next < source.length && source[next] !== "\n") return at + 1
1192
+ at = next
1193
+ }
1194
+ }
1195
+
1196
+ /**
1197
+ * Where the generated block goes: after the directive prologue and the import declarations. Comments
1198
+ * are read as comments, so one before `"use client"` keeps the directive first, and a trailing
1199
+ * `// note` on the last import does not hide where it ends.
1200
+ */
1201
+ const insertionOffset = (source: string): number => {
1202
+ let end = source.startsWith("#!") ? source.indexOf("\n") + 1 || source.length : 0
1203
+ let prologue = true
1204
+ for (;;) {
1205
+ const at = skipTrivia(source, end)
1206
+ const char = source[at]
1207
+ let statementEnd: number | undefined
1208
+ if (prologue && (char === '"' || char === "'")) {
1209
+ const literal = skipString(source, at)
1210
+ const after = skipTrivia(source, literal, true)
1211
+ // A string with more of an expression after it on its line is not a directive.
1212
+ if (source[after] === ";") statementEnd = after + 1
1213
+ else if (after === source.length || source[after] === "\n") statementEnd = literal
1214
+ } else if (source.startsWith("import", at) && !isIdentifierChar(source[at + 6])) {
1215
+ prologue = false
1216
+ statementEnd = importEnd(source, at)
1217
+ }
1218
+ if (statementEnd === undefined) break
1219
+ end = nextLine(source, statementEnd)
1120
1220
  }
1121
- offset += consumed
1122
- return offset
1221
+ return end
1123
1222
  }
1124
1223
 
1125
1224
  /** Transform one source file. The returned source is unchanged when every match is unsupported. */
@@ -1196,7 +1295,8 @@ export function migrateTailwindSource(source: string, file: string): SourceMigra
1196
1295
  const needsImport = existingStylexImport(source) === undefined
1197
1296
  const generated = `${needsImport ? `import * as ${stylexName} from "${STYLEX_SPECIFIER}"\n\n` : ""}const ${stylesName} = ${stylexName}.create(${JSON.stringify(Object.fromEntries(styles), null, 2)})\n\n`
1198
1297
  const offset = insertionOffset(rewritten)
1199
- const withGenerated = `${rewritten.slice(0, offset)}${generated}${rewritten.slice(offset)}`
1298
+ const separator = offset > 0 && rewritten[offset - 1] !== "\n" ? "\n" : ""
1299
+ const withGenerated = `${rewritten.slice(0, offset)}${separator}${generated}${rewritten.slice(offset)}`
1200
1300
  return { source: withGenerated, changed: true, replacements: replacements.length, issues }
1201
1301
  }
1202
1302
 
package/src/test-tool.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ escalatingStop,
2
3
  type HeadTailOutput,
3
4
  OWN_PROCESS_GROUP,
4
5
  readHeadTail,
@@ -63,8 +64,6 @@ function normalizeTimeout(value: unknown): number {
63
64
  return Math.min(Math.max(Math.trunc(value), 1_000), MAX_TIMEOUT_MS)
64
65
  }
65
66
 
66
- const KILL_GRACE_MS = 2_000
67
-
68
67
  const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g")
69
68
 
70
69
  // A UTF-8 character is at most four bytes, so these hold every character the result can show.
@@ -157,12 +156,7 @@ export async function collectTestResult(
157
156
  })
158
157
  let timedOut = false
159
158
  let cancelled = false
160
- let escalation: ReturnType<typeof setTimeout> | undefined
161
- // A test can ignore SIGTERM, so the group gets SIGKILL once the grace period runs out.
162
- const stop = (): void => {
163
- signalProcessGroup(proc, "SIGTERM")
164
- escalation ??= setTimeout(() => signalProcessGroup(proc, "SIGKILL"), KILL_GRACE_MS)
165
- }
159
+ const { stop, dispose } = escalatingStop((name) => signalProcessGroup(proc, name))
166
160
  const abort = (): void => {
167
161
  cancelled = true
168
162
  stop()
@@ -189,7 +183,7 @@ export async function collectTestResult(
189
183
  exitCode = result[2]
190
184
  } finally {
191
185
  clearTimeout(timer)
192
- clearTimeout(escalation)
186
+ dispose()
193
187
  opts.signal?.removeEventListener("abort", abort)
194
188
  }
195
189
  const stdout = clean(stdoutRaw)
@@ -13,6 +13,56 @@ const TS_SOURCE = /\.(?:[cm]?ts|tsx)$/
13
13
  const NOT_PROGRAM_CODE = /\.d\.[cm]?ts$|\.(?:test|spec)\.[cm]?tsx?$/
14
14
  const TSC_DIAGNOSTIC = /\(\d+,\d+\):\s*(?:error|warning)\s+TS\d+:/
15
15
 
16
+ const readTsconfig = (path: string): unknown => {
17
+ try {
18
+ return JSON.parse(stripComments(readFileSync(path, "utf8")).replace(/,(\s*[}\]])/g, "$1"))
19
+ } catch {
20
+ return undefined
21
+ }
22
+ }
23
+
24
+ /** A `references[].path`, which names a tsconfig or the folder holding one, as a file. */
25
+ const referencedConfig = (from: string, path: string): string => {
26
+ const target = resolve(dirname(from), path)
27
+ return target.endsWith(".json") ? target : join(target, "tsconfig.json")
28
+ }
29
+
30
+ /**
31
+ * The tsconfigs `nifra check` typechecks, each as its own program: `configured` (nifra.check.json
32
+ * `tsconfigs`) when given, else `tsconfig.json` and every project it references, transitively. A
33
+ * solution-style tsconfig (`"files": []` plus `references`) holds no files itself, so without its
34
+ * references the typecheck would pass having read nothing. `missing` lists configured paths that do not
35
+ * exist; references that do not exist are tsc's to report.
36
+ */
37
+ export function typecheckProjects(
38
+ cwd: string,
39
+ configured?: readonly string[],
40
+ ): { readonly paths: readonly string[]; readonly missing: readonly string[] } {
41
+ if (configured !== undefined) {
42
+ const paths = configured.map((path) => resolve(cwd, path))
43
+ return {
44
+ paths: paths.filter((path) => existsSync(path)),
45
+ missing: configured.filter((_, index) => !existsSync(paths[index] ?? "")),
46
+ }
47
+ }
48
+ const root = join(cwd, "tsconfig.json")
49
+ if (!existsSync(root)) return { paths: [], missing: [] }
50
+ const paths: string[] = []
51
+ const queue = [root]
52
+ while (queue.length > 0 && paths.length < 64) {
53
+ const path = queue.shift()
54
+ if (path === undefined || paths.includes(path) || !existsSync(path)) continue
55
+ paths.push(path)
56
+ const references: unknown = Reflect.get(Object(readTsconfig(path)), "references")
57
+ if (!Array.isArray(references)) continue
58
+ for (const reference of references) {
59
+ const target: unknown = Reflect.get(Object(reference), "path")
60
+ if (typeof target === "string") queue.push(referencedConfig(path, target))
61
+ }
62
+ }
63
+ return { paths, missing: [] }
64
+ }
65
+
16
66
  /** Split `tsc --listFiles` output into the program's files and the compiler's own output. */
17
67
  export function splitListedFiles(output: string): {
18
68
  readonly programFiles: readonly string[]
@@ -68,12 +118,7 @@ function hasOwnProgram(cwd: string, app: string): boolean {
68
118
  export function tsconfigExcludes(cwd: string): string[] {
69
119
  let path = join(cwd, "tsconfig.json")
70
120
  for (let depth = 0; depth < 8 && existsSync(path); depth++) {
71
- let config: unknown
72
- try {
73
- config = JSON.parse(stripComments(readFileSync(path, "utf8")).replace(/,(\s*[}\]])/g, "$1"))
74
- } catch {
75
- return []
76
- }
121
+ const config = readTsconfig(path)
77
122
  if (typeof config !== "object" || config === null) return []
78
123
  const exclude: unknown = Reflect.get(config, "exclude")
79
124
  if (Array.isArray(exclude)) {