@nifrajs/cli 5.17.0 → 5.18.1

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 (178) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/check-diagnostics.d.ts +7 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +3 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan-sql.d.ts +95 -0
  7. package/dist/check-scan-sql.d.ts.map +1 -0
  8. package/dist/check-scan-sql.js +1190 -0
  9. package/dist/check-scan-sql.js.map +1 -0
  10. package/dist/check-scan.d.ts +5 -93
  11. package/dist/check-scan.d.ts.map +1 -1
  12. package/dist/check-scan.js +20 -1207
  13. package/dist/check-scan.js.map +1 -1
  14. package/dist/check.d.ts.map +1 -1
  15. package/dist/check.js +9 -0
  16. package/dist/check.js.map +1 -1
  17. package/dist/cli.d.ts +2 -6
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +249 -80
  20. package/dist/cli.js.map +1 -1
  21. package/dist/command-catalog.d.ts +3 -0
  22. package/dist/command-catalog.d.ts.map +1 -1
  23. package/dist/command-catalog.js +18 -4
  24. package/dist/command-catalog.js.map +1 -1
  25. package/dist/frontend-guidance.js +1 -1
  26. package/dist/frontend-guidance.js.map +1 -1
  27. package/dist/internal/a11y-element.d.ts +33 -0
  28. package/dist/internal/a11y-element.d.ts.map +1 -0
  29. package/dist/internal/a11y-element.js +124 -0
  30. package/dist/internal/a11y-element.js.map +1 -0
  31. package/dist/internal/a11y-jsx.d.ts +12 -0
  32. package/dist/internal/a11y-jsx.d.ts.map +1 -0
  33. package/dist/internal/a11y-jsx.js +42 -0
  34. package/dist/internal/a11y-jsx.js.map +1 -0
  35. package/dist/internal/a11y-template.d.ts +11 -0
  36. package/dist/internal/a11y-template.d.ts.map +1 -0
  37. package/dist/internal/a11y-template.js +56 -0
  38. package/dist/internal/a11y-template.js.map +1 -0
  39. package/dist/internal/aria-data.d.ts +23 -0
  40. package/dist/internal/aria-data.d.ts.map +1 -0
  41. package/dist/internal/aria-data.js +220 -0
  42. package/dist/internal/aria-data.js.map +1 -0
  43. package/dist/internal/edit-distance.d.ts +3 -0
  44. package/dist/internal/edit-distance.d.ts.map +1 -0
  45. package/dist/internal/edit-distance.js +12 -0
  46. package/dist/internal/edit-distance.js.map +1 -0
  47. package/dist/internal/imported-as.d.ts +10 -0
  48. package/dist/internal/imported-as.d.ts.map +1 -0
  49. package/dist/internal/imported-as.js +23 -0
  50. package/dist/internal/imported-as.js.map +1 -0
  51. package/dist/internal/source-facts.d.ts +3 -0
  52. package/dist/internal/source-facts.d.ts.map +1 -1
  53. package/dist/internal/source-facts.js +2 -0
  54. package/dist/internal/source-facts.js.map +1 -1
  55. package/dist/internal/template-markup.d.ts +58 -0
  56. package/dist/internal/template-markup.d.ts.map +1 -0
  57. package/dist/internal/template-markup.js +221 -0
  58. package/dist/internal/template-markup.js.map +1 -0
  59. package/dist/internal/typescript-import.d.ts.map +1 -1
  60. package/dist/internal/typescript-import.js +11 -0
  61. package/dist/internal/typescript-import.js.map +1 -1
  62. package/dist/mcp-exec.d.ts.map +1 -1
  63. package/dist/mcp-exec.js +37 -23
  64. package/dist/mcp-exec.js.map +1 -1
  65. package/dist/mcp-http.js +1 -1
  66. package/dist/mcp-io.d.ts.map +1 -1
  67. package/dist/mcp-io.js +5 -3
  68. package/dist/mcp-io.js.map +1 -1
  69. package/dist/mcp-root.js +1 -1
  70. package/dist/mcp-root.js.map +1 -1
  71. package/dist/mcp-ws.d.ts.map +1 -1
  72. package/dist/mcp-ws.js +3 -2
  73. package/dist/mcp-ws.js.map +1 -1
  74. package/dist/migrate-layout-config.d.ts +63 -0
  75. package/dist/migrate-layout-config.d.ts.map +1 -0
  76. package/dist/migrate-layout-config.js +507 -0
  77. package/dist/migrate-layout-config.js.map +1 -0
  78. package/dist/migrate-layout-split.d.ts +46 -0
  79. package/dist/migrate-layout-split.d.ts.map +1 -0
  80. package/dist/migrate-layout-split.js +687 -0
  81. package/dist/migrate-layout-split.js.map +1 -0
  82. package/dist/migrate-layout.d.ts +4 -24
  83. package/dist/migrate-layout.d.ts.map +1 -1
  84. package/dist/migrate-layout.js +8 -1183
  85. package/dist/migrate-layout.js.map +1 -1
  86. package/dist/output-schemas.d.ts.map +1 -1
  87. package/dist/output-schemas.js +78 -10
  88. package/dist/output-schemas.js.map +1 -1
  89. package/dist/recipes/5.18.0.d.ts +9 -0
  90. package/dist/recipes/5.18.0.d.ts.map +1 -0
  91. package/dist/recipes/5.18.0.js +56 -0
  92. package/dist/recipes/5.18.0.js.map +1 -0
  93. package/dist/recipes/index.d.ts.map +1 -1
  94. package/dist/recipes/index.js +2 -0
  95. package/dist/recipes/index.js.map +1 -1
  96. package/dist/review.d.ts.map +1 -1
  97. package/dist/review.js +6 -0
  98. package/dist/review.js.map +1 -1
  99. package/dist/rules/a11y.d.ts +5 -0
  100. package/dist/rules/a11y.d.ts.map +1 -0
  101. package/dist/rules/a11y.js +78 -0
  102. package/dist/rules/a11y.js.map +1 -0
  103. package/dist/rules/codes.d.ts +6 -0
  104. package/dist/rules/codes.d.ts.map +1 -1
  105. package/dist/rules/codes.js +6 -0
  106. package/dist/rules/codes.js.map +1 -1
  107. package/dist/rules/comment-markers.js +1 -1
  108. package/dist/rules/comment-markers.js.map +1 -1
  109. package/dist/rules/explanations.d.ts.map +1 -1
  110. package/dist/rules/explanations.js +30 -0
  111. package/dist/rules/explanations.js.map +1 -1
  112. package/dist/rules/host-exposure.d.ts +23 -0
  113. package/dist/rules/host-exposure.d.ts.map +1 -0
  114. package/dist/rules/host-exposure.js +380 -0
  115. package/dist/rules/host-exposure.js.map +1 -0
  116. package/dist/rules/internal-links.d.ts.map +1 -1
  117. package/dist/rules/internal-links.js +16 -141
  118. package/dist/rules/internal-links.js.map +1 -1
  119. package/dist/rules/islands.d.ts +54 -0
  120. package/dist/rules/islands.d.ts.map +1 -1
  121. package/dist/rules/islands.js +577 -80
  122. package/dist/rules/islands.js.map +1 -1
  123. package/dist/rules/security.d.ts +1 -0
  124. package/dist/rules/security.d.ts.map +1 -1
  125. package/dist/rules/security.js +34 -7
  126. package/dist/rules/security.js.map +1 -1
  127. package/dist/runtime-differences.js +3 -3
  128. package/dist/runtime-differences.js.map +1 -1
  129. package/dist/scaffold.d.ts +1 -1
  130. package/dist/scaffold.d.ts.map +1 -1
  131. package/dist/scaffold.js +2 -2
  132. package/dist/scaffold.js.map +1 -1
  133. package/dist/source-rewrites.d.ts.map +1 -1
  134. package/dist/source-rewrites.js +2 -19
  135. package/dist/source-rewrites.js.map +1 -1
  136. package/docs/examples.json +4 -4
  137. package/docs/llms-full.txt +422 -42
  138. package/docs/types.json +466 -56
  139. package/package.json +12 -12
  140. package/src/check-diagnostics.ts +11 -0
  141. package/src/check-scan-sql.ts +1746 -0
  142. package/src/check-scan.ts +34 -1754
  143. package/src/check.ts +10 -1
  144. package/src/cli.ts +258 -98
  145. package/src/command-catalog.ts +21 -4
  146. package/src/frontend-guidance.ts +1 -1
  147. package/src/internal/a11y-element.ts +227 -0
  148. package/src/internal/a11y-jsx.ts +54 -0
  149. package/src/internal/a11y-template.ts +74 -0
  150. package/src/internal/aria-data.ts +242 -0
  151. package/src/internal/edit-distance.ts +16 -0
  152. package/src/internal/imported-as.ts +30 -0
  153. package/src/internal/source-facts.ts +4 -0
  154. package/src/internal/template-markup.ts +270 -0
  155. package/src/internal/typescript-import.ts +15 -0
  156. package/src/mcp-exec.ts +43 -22
  157. package/src/mcp-http.ts +1 -1
  158. package/src/mcp-io.ts +5 -3
  159. package/src/mcp-root.ts +1 -1
  160. package/src/mcp-ws.ts +3 -2
  161. package/src/migrate-layout-config.ts +615 -0
  162. package/src/migrate-layout-split.ts +870 -0
  163. package/src/migrate-layout.ts +37 -1468
  164. package/src/output-schemas.ts +85 -17
  165. package/src/recipes/5.18.0.ts +63 -0
  166. package/src/recipes/index.ts +2 -0
  167. package/src/review.ts +6 -0
  168. package/src/rules/a11y.ts +119 -0
  169. package/src/rules/codes.ts +6 -0
  170. package/src/rules/comment-markers.ts +2 -2
  171. package/src/rules/explanations.ts +30 -0
  172. package/src/rules/host-exposure.ts +531 -0
  173. package/src/rules/internal-links.ts +21 -154
  174. package/src/rules/islands.ts +698 -86
  175. package/src/rules/security.ts +48 -7
  176. package/src/runtime-differences.ts +3 -3
  177. package/src/scaffold.ts +3 -3
  178. package/src/source-rewrites.ts +2 -15
@@ -156,6 +156,13 @@ const TYPED_ARRAY = /^(?:Big)?(?:Int|Uint|Float)(?:8|16|32|64)(?:Clamped)?Array$
156
156
 
157
157
  const sameShape = (a: Shape, b: Shape): boolean => JSON.stringify(a) === JSON.stringify(b)
158
158
 
159
+ // Only object shapes have a fields array. Sort it at every depth for ranking, leaving the field
160
+ // order in the generated declaration intact.
161
+ const orderFieldsForRank = (key: string, value: unknown): unknown =>
162
+ key === "fields" && Array.isArray(value)
163
+ ? [...value].sort((a: Field, b: Field) => codeUnitOrder(a.name, b.name))
164
+ : value
165
+
159
166
  function unionOf(input: readonly Shape[]): Shape {
160
167
  const flat = input
161
168
  .flatMap((member) => (member.kind === "union" ? member.members : [member]))
@@ -174,11 +181,14 @@ function unionOf(input: readonly Shape[]): Shape {
174
181
  }
175
182
  if (members.length === 0) return { kind: "never" }
176
183
  if (members.length === 1 && members[0] !== undefined) return members[0]
177
- // TypeScript versions order union members differently; a canonical order keeps the generated text,
178
- // and the hash in its marker, the same under each. `null` reads best last.
179
- const rank = (shape: Shape): string =>
180
- `${shape.kind === "null" || shape.kind === "undefined" ? 1 : 0}${JSON.stringify(shape)}`
181
- return { kind: "union", members: members.sort((a, b) => codeUnitOrder(rank(a), rank(b))) }
184
+ // Checker enumeration order must not decide which matching union branch decodes a value.
185
+ // Keep null and undefined last as before.
186
+ const ranked = members.map((member) => ({
187
+ member,
188
+ key: `${member.kind === "null" || member.kind === "undefined" ? 1 : 0}${JSON.stringify(member, orderFieldsForRank)}`,
189
+ }))
190
+ ranked.sort((a, b) => codeUnitOrder(a.key, b.key))
191
+ return { kind: "union", members: ranked.map(({ member }) => member) }
182
192
  }
183
193
 
184
194
  function withoutUndefined(shape: Shape): Shape {
@@ -444,19 +454,32 @@ const hashOf = (body: string): string => createHash("sha256").update(body).diges
444
454
  /**
445
455
  * A schema expression as a formatter cannot change it: comments, whitespace, a comma before a closing
446
456
  * bracket and a trailing semicolon dropped, every string written with double quotes, and a quoted key
447
- * that needs no quotes written bare. Two texts
448
- * that read the same here are the same schema; an edit to what it declares is not.
457
+ * that needs no quotes written bare. The order-insensitive comparison also keeps the generator's
458
+ * notes about fields it omitted or types it could not describe.
449
459
  */
450
- function schemaTokens(text: string): string {
460
+ function schemaTokens(text: string, keepDraftNotes = false): string {
451
461
  let out = ""
452
462
  let i = 0
453
463
  while (i < text.length) {
454
464
  const c = text.charAt(i)
455
465
  if (c === "/" && text[i + 1] === "/") {
456
466
  const end = text.indexOf("\n", i)
467
+ const comment = text.slice(i + 2, end === -1 ? text.length : end).trim()
468
+ if (keepDraftNotes && comment.startsWith("left out: ")) {
469
+ // Treat an omitted field as an object member so its note follows that field when sorted.
470
+ if (!out.endsWith("{") && !out.endsWith(",")) out += ","
471
+ out += `#${JSON.stringify(comment)},`
472
+ }
457
473
  i = end === -1 ? text.length : end
458
474
  } else if (c === "/" && text[i + 1] === "*") {
459
475
  const end = text.indexOf("*/", i + 2)
476
+ const comment = text.slice(i + 2, end === -1 ? text.length : end).trim()
477
+ if (
478
+ keepDraftNotes &&
479
+ out.endsWith("t.json()") &&
480
+ (comment.endsWith(" in the source type") || comment.endsWith(", which is not JSON"))
481
+ )
482
+ out += `#${JSON.stringify(comment)}`
460
483
  i = end === -1 ? text.length : end + 2
461
484
  } else if (c === '"' || c === "'" || c === "`") {
462
485
  let value = ""
@@ -478,11 +501,53 @@ function schemaTokens(text: string): string {
478
501
  out +=
479
502
  text[after] === ":" && IDENTIFIER.test(value) ? value : `"${value.replaceAll('"', '\\"')}"`
480
503
  } else {
504
+ if ((c === "}" || c === "]" || c === ")") && out.endsWith(",")) out = out.slice(0, -1)
481
505
  if (!/\s/.test(c)) out += c
482
506
  i++
483
507
  }
484
508
  }
485
- return out.replace(/,(?=[}\])])/g, "").replace(/(?<!;);+$/, "")
509
+ return out.replace(/(?<!;);+$/, "")
510
+ }
511
+
512
+ /**
513
+ * Sort object fields after normalizing their contents. Older drafts can also differ in union order
514
+ * because the generator ranked members using checker property order. A union containing a date
515
+ * keeps its order because the first matching branch decides whether a string becomes a Date.
516
+ */
517
+ function schemaIgnoringOrder(text: string, sortUnions: boolean): string {
518
+ const tokens = schemaTokens(text, true)
519
+ let at = 0
520
+ let lastDate = -1
521
+ const follows = (prefix: string): boolean => tokens.startsWith(prefix, at - prefix.length)
522
+ const group = (close: string): string[] => {
523
+ const parts: string[] = []
524
+ let part = ""
525
+ while (at < tokens.length) {
526
+ const c = tokens.charAt(at++)
527
+ if (c === close) break
528
+ if (c === ",") {
529
+ parts.push(part)
530
+ part = ""
531
+ } else if (c === "{") part += `{${group("}").sort(codeUnitOrder).join(",")}}`
532
+ else if (c === "[") {
533
+ const sort = sortUnions && follows("t.union([")
534
+ const start = at
535
+ const members = group("]")
536
+ if (sort && lastDate < start) members.sort(codeUnitOrder)
537
+ part += `[${members.join(",")}]`
538
+ } else if (c === "(") {
539
+ if (follows("t.date(")) lastDate = at
540
+ part += `(${group(")").join(",")})`
541
+ } else if (c === '"') {
542
+ const start = at - 1
543
+ while (at < tokens.length && tokens[at] !== '"') at += tokens[at] === "\\" ? 2 : 1
544
+ part += tokens.slice(start, ++at)
545
+ } else part += c
546
+ }
547
+ parts.push(part)
548
+ return parts
549
+ }
550
+ return group("").join(",")
486
551
  }
487
552
 
488
553
  function declarationText(schema: OutputExport, fn: RouteFn, body: string): string {
@@ -1120,15 +1185,18 @@ export async function planOutputSchemas(
1120
1185
  const written = declarationText(target.schema, target.fn, body)
1121
1186
  const text = target.insertAt === content.length ? `\n${written}\n` : `${written}\n\n`
1122
1187
  replacements.push({ start: target.insertAt, end: target.insertAt, text, entry: at })
1123
- } else if (
1124
- declaration.hash === hashOf(body) &&
1125
- schemaTokens(declaration.value) === schemaTokens(body)
1126
- ) {
1127
- entry("current", [], undefined, false, [], open)
1128
1188
  } else {
1129
- // The marker still matches what would be written, so the text under it was edited.
1130
- const edited = declaration.hash === hashOf(body)
1131
- const at = entry("stale", dropped, undefined, edited, omitted, open)
1189
+ // A matching marker makes a union reorder an edit to the declaration.
1190
+ const markerMatches = declaration.hash === hashOf(body)
1191
+ const current =
1192
+ (markerMatches && schemaTokens(declaration.value) === schemaTokens(body)) ||
1193
+ schemaIgnoringOrder(declaration.value, !markerMatches) ===
1194
+ schemaIgnoringOrder(body, !markerMatches)
1195
+ if (current) {
1196
+ entry("current", [], undefined, false, [], open)
1197
+ continue
1198
+ }
1199
+ const at = entry("stale", dropped, undefined, markerMatches, omitted, open)
1132
1200
  const text = declarationText(target.schema, target.fn, body)
1133
1201
  replacements.push({ start: declaration.start, end: declaration.end, text, entry: at })
1134
1202
  }
@@ -0,0 +1,63 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.18.
5
+ *
6
+ * No import or dependency moves and no source rewrites. Each note names a refusal, a limit or a
7
+ * diagnostic an app can observe.
8
+ */
9
+ export const recipe: UpgradeRecipe = {
10
+ version: "5.18.0",
11
+ pins: [
12
+ { match: "@nifrajs/", to: "5.18.0" },
13
+ { match: "create-nifra", to: "5.18.0" },
14
+ { match: "nifra", to: "5.18.0" },
15
+ ],
16
+ importMoves: [],
17
+ sourceRewrites: [],
18
+ affects: [
19
+ "@nifrajs/a2a",
20
+ "@nifrajs/ag-ui",
21
+ "@nifrajs/agent",
22
+ "@nifrajs/agent-app",
23
+ "@nifrajs/agent-review",
24
+ "@nifrajs/auth",
25
+ "@nifrajs/cli",
26
+ "@nifrajs/client",
27
+ "@nifrajs/coding-agent",
28
+ "@nifrajs/content",
29
+ "@nifrajs/core",
30
+ "@nifrajs/cron",
31
+ "@nifrajs/deno",
32
+ "@nifrajs/graphql",
33
+ "@nifrajs/i18n",
34
+ "@nifrajs/island-trigger",
35
+ "@nifrajs/mcp-db",
36
+ "@nifrajs/middleware",
37
+ "@nifrajs/node",
38
+ "@nifrajs/node-engine",
39
+ "@nifrajs/node-uws",
40
+ "@nifrajs/otel",
41
+ "@nifrajs/proxy",
42
+ "@nifrajs/storage",
43
+ "@nifrajs/testing",
44
+ "@nifrajs/uploads",
45
+ "@nifrajs/web",
46
+ "@nifrajs/web-preact",
47
+ "@nifrajs/web-react",
48
+ "@nifrajs/web-svelte",
49
+ "@nifrajs/workers",
50
+ "create-nifra",
51
+ ],
52
+ notes: [
53
+ "A form write with no `Origin` header is now judged by the browser's Fetch Metadata headers, and a request with a malformed origin is refused on routes without a body schema too.",
54
+ "Structured logs redact common secret formats in values by default. A log search or test that expects such a value verbatim will no longer find it.",
55
+ "Island bindings block active content and network-path URLs, refuse URL attributes on `script`, `iframe`, `object`, `embed`, `link` and `base`, and refuse every attribute on the SVG animation elements.",
56
+ "`FileStorage.get` reads at most 16 MiB per object and per metadata file and throws a `RangeError` above either. Pass `new FileStorage(root, { maxReadBytes, maxMetadataBytes })` to read larger entries.",
57
+ "Request hooks now count against the local request timeout, and Web hooks' request signals abort on expiry. A slow hook that used to finish can now time out.",
58
+ "A GraphQL `authorize` hook that throws answers a `500` envelope instead of rejecting, and with `introspection: false` validation errors carry no suggestions.",
59
+ "An idempotency key too large for `MemoryIdempotencyStore` is answered `400 idempotency_key_too_large` instead of `500`.",
60
+ "`nifra check` has new warnings: NF-C062 and NF-C063 for accessibility markup, NF-C064 to NF-C066 for islands, and NF-S010 for a TLS-terminating Deno or Bun listener that does not check `Host`. A date-bearing union drafted in a different order may need its output schema regenerated.",
61
+ "`@nifrajs/node-engine` (experimental) ships prebuilt addons per platform. A self-built addon must be rebuilt together with the package; `serve` refuses an older one. Response header values are written as latin-1 and characters above U+00FF are refused.",
62
+ ],
63
+ }
@@ -29,6 +29,7 @@ import { recipe as v5_14_0 } from "./5.14.0.ts"
29
29
  import { recipe as v5_15_0 } from "./5.15.0.ts"
30
30
  import { recipe as v5_16_0 } from "./5.16.0.ts"
31
31
  import { recipe as v5_17_0 } from "./5.17.0.ts"
32
+ import { recipe as v5_18_0 } from "./5.18.0.ts"
32
33
 
33
34
  /** A pin rule: every dependency whose name starts with `match` is set to version `to`. */
34
35
  export interface PinRule {
@@ -117,6 +118,7 @@ const RECIPES: Record<string, UpgradeRecipe> = {
117
118
  [v5_15_0.version]: v5_15_0,
118
119
  [v5_16_0.version]: v5_16_0,
119
120
  [v5_17_0.version]: v5_17_0,
121
+ [v5_18_0.version]: v5_18_0,
120
122
  }
121
123
 
122
124
  export function getRecipe(version: string): UpgradeRecipe | undefined {
package/src/review.ts CHANGED
@@ -168,6 +168,11 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
168
168
  "NF-C059": "typed-client",
169
169
  "NF-C060": "typed-client",
170
170
  "NF-C061": "configuration",
171
+ "NF-C062": "configuration",
172
+ "NF-C063": "configuration",
173
+ "NF-C064": "route-boundary",
174
+ "NF-C065": "route-boundary",
175
+ "NF-C066": "security",
171
176
  "NF-C046": "dependency",
172
177
  "NF-D001": "dependency",
173
178
  "NF-D002": "dependency",
@@ -187,6 +192,7 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
187
192
  "NF-S007": "security",
188
193
  "NF-S008": "security",
189
194
  "NF-S009": "security",
195
+ "NF-S010": "security",
190
196
  }
191
197
 
192
198
  const REVIEW_INPUT_SCHEMA = {
@@ -0,0 +1,119 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { join } from "node:path"
3
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
4
+ import type { A11yCode, A11yFinding } from "../internal/a11y-element.ts"
5
+ import { a11yTemplateFindings } from "../internal/a11y-template.ts"
6
+ import { lineLookup, templateFiles } from "../internal/template-markup.ts"
7
+ import { commentBlockExpectation, MISSING_EXPECTATION_REASON } from "./comment-markers.ts"
8
+ import type { CheckRule, RuleContext } from "./index.ts"
9
+ import { scanSources } from "./source-scan.ts"
10
+
11
+ const TEST_DIR = /(?:^|\/)(?:tests?|__tests__)\//
12
+ const SCRIPT_MAY_MATCH = /\brole\s*=|\baria-|\btabindex\s*=|<(?:img|html|area|input)\b/i
13
+ const TEMPLATE_MAY_MATCH = /\brole\b|\baria-|tabindex|<(?:img|html|area|input)\b/i
14
+
15
+ function report(
16
+ code: A11yCode,
17
+ file: string,
18
+ line: number,
19
+ found: A11yFinding,
20
+ note: string | undefined,
21
+ template: boolean,
22
+ ): Diagnostic {
23
+ const marker = template
24
+ ? `<!-- nifra-expect ${code}: <reason> -->`
25
+ : `// nifra-expect ${code}: <reason>`
26
+ return diagnostic({
27
+ code,
28
+ severity: "warn",
29
+ file,
30
+ line,
31
+ message: note === undefined ? found.message : `${found.message} (${note})`,
32
+ evidence: [
33
+ `kind: ${found.kind}`,
34
+ "WAI-ARIA 1.2 and ARIA in HTML, read from the markup in this file",
35
+ `a use kept on purpose: \`${marker}\` above the element`,
36
+ ],
37
+ verify: "nifra check",
38
+ })
39
+ }
40
+
41
+ /** The findings in the `<template>` of every `.vue` file and the markup of every `.svelte` file. */
42
+ async function templateDiagnostics(ctx: RuleContext, code: A11yCode): Promise<Diagnostic[]> {
43
+ const expectation = [code, "a11y"]
44
+ const out: Diagnostic[] = []
45
+ for (const file of await templateFiles(ctx.root)) {
46
+ const text = readFileSync(join(ctx.root, file), "utf8")
47
+ if (!TEMPLATE_MAY_MATCH.test(text)) continue
48
+ const { findings, expectationLines } = a11yTemplateFindings(text, file.endsWith(".vue"))
49
+ const lineOf = lineLookup(text)
50
+ for (const found of findings) {
51
+ if (found.code !== code) continue
52
+ const line = lineOf(found.position)
53
+ const expected =
54
+ commentBlockExpectation(expectationLines, lineOf(found.expectAt), expectation) ??
55
+ commentBlockExpectation(expectationLines, line, expectation)
56
+ if (expected?.reason !== undefined) continue
57
+ out.push(
58
+ report(
59
+ code,
60
+ file,
61
+ line,
62
+ found,
63
+ expected === undefined ? undefined : MISSING_EXPECTATION_REASON,
64
+ true,
65
+ ),
66
+ )
67
+ }
68
+ }
69
+ return out
70
+ }
71
+
72
+ /**
73
+ * NF-C062 and NF-C063 - accessibility of the markup a page renders, judged from what it spells out:
74
+ * the JSX of `.tsx` files (React, Preact, Solid) and the templates of `.vue` and `.svelte` files. The
75
+ * two codes split by what a user loses: C062 is markup assistive technology cannot read at all (a role
76
+ * that does not exist, a misspelled `aria-*` attribute, a role missing the state it requires), and C063
77
+ * is markup it reads worse than it could (no `alt`, a positive `tabindex`, a `<div role="button">`).
78
+ * A `nifra-expect a11y: <reason>` comment accepts a finding of either.
79
+ *
80
+ * What it cannot see stays out: contrast, focus order, keyboard operation and anything a spread or an
81
+ * expression supplies. Pair it with axe-core in a browser test.
82
+ */
83
+ function a11yRule(code: A11yCode, title: string): CheckRule {
84
+ return {
85
+ code,
86
+ title,
87
+ async scan(ctx) {
88
+ const scripts = await scanSources(ctx, {
89
+ expectation: [code, "a11y"],
90
+ requireReason: true,
91
+ mayMatch: (text) => SCRIPT_MAY_MATCH.test(text),
92
+ find: (facts, tree) =>
93
+ TEST_DIR.test(tree.fileName)
94
+ ? []
95
+ : facts
96
+ .a11yFindings(tree)
97
+ .filter((found) => found.code === code)
98
+ .map((found) => ({
99
+ position: found.position,
100
+ expectAt: found.expectAt,
101
+ report: (line: number, note?: string) =>
102
+ report(code, tree.fileName, line, found, note, false),
103
+ })),
104
+ })
105
+ return [...scripts, ...(await templateDiagnostics(ctx, code))]
106
+ },
107
+ }
108
+ }
109
+
110
+ export const unreadableAriaRule = a11yRule(
111
+ "NF-C062",
112
+ "ARIA markup assistive technology cannot read",
113
+ )
114
+ export const weakAccessibleMarkupRule = a11yRule(
115
+ "NF-C063",
116
+ "Markup assistive technology reads worse than it could",
117
+ )
118
+
119
+ export const a11yRules = Object.freeze([unreadableAriaRule, weakAccessibleMarkupRule])
@@ -60,6 +60,11 @@ export const RULE_CODES = Object.freeze({
60
60
  "NF-C059": "Route hook names another route than its page's",
61
61
  "NF-C060": "Value cast to Href",
62
62
  "NF-C061": "SSE stream with no heartbeat under Bun's idle timeout",
63
+ "NF-C062": "ARIA markup assistive technology cannot read",
64
+ "NF-C063": "Markup assistive technology reads worse than it could",
65
+ "NF-C064": "Island host with no enhancer",
66
+ "NF-C065": "Island props differ from the enhancer's props type",
67
+ "NF-C066": "Island attribute binding the runtime refuses",
63
68
  "NF-D001": "Doctor check",
64
69
  "NF-D002": "Mixed nifra versions",
65
70
  "NF-D003": "Stale file: dependencies in bun.lock",
@@ -78,6 +83,7 @@ export const RULE_CODES = Object.freeze({
78
83
  "NF-S007": "Secure cookie without a __Host-/__Secure- prefix",
79
84
  "NF-S008": "Authenticated route validates input before authentication",
80
85
  "NF-S009": "WebSocket frames parsed without a messageSchema",
86
+ "NF-S010": "Server answers requests with Host unchecked",
81
87
  } as const)
82
88
 
83
89
  /** Codes that no longer fire but remain reserved forever. */
@@ -79,10 +79,10 @@ export function commentBlockExpectation(
79
79
  found = true
80
80
  const rest = (match[1] ?? "").trimStart()
81
81
  if (!rest.startsWith(":")) return undefined
82
- // A block comment's `*/` closer is not part of the reason.
82
+ // A block comment's `*/` closer, and the `}` that ends a JSX comment, are not part of the reason.
83
83
  const reason = rest
84
84
  .slice(1)
85
- .replace(/\*\/\s*$/, "")
85
+ .replace(/\*\/\}?\s*$/, "")
86
86
  .trim()
87
87
  return reason.length > 0 ? reason : undefined
88
88
  }
@@ -319,6 +319,31 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
319
319
  fix: "Pass `{ keepAlive: 5_000 }` to the stream so a ping goes out well inside the timeout, or raise the timeout: `withIdleTimeout(c, seconds, work)` from `@nifrajs/core/idle-timeout` under `listen()`, or the `idleTimeout` option of `Bun.serve()`. A stream kept on purpose takes `// nifra-expect NF-C061: <reason>` above the registration.",
320
320
  docs: "/docs/api",
321
321
  },
322
+ "NF-C062": {
323
+ why: "An ARIA role or attribute that is misspelled, abstract, given a value it does not take, or missing something its role requires. Browsers drop it without a sound, so the control looks right and a screen reader reads it as plain text, or not at all. `tsc` cannot tell: every attribute type-checks as a string.",
324
+ fix: 'Name a concrete ARIA 1.2 role and spell each `aria-*` attribute as the spec does (`aria-labelledby`, not `aria-labeledby`). Give a role what it requires: `role="checkbox"` needs `aria-checked`, `role="slider"` needs `aria-valuenow`. A native element needs none of this: `<input type="checkbox">` carries its own state. A use kept on purpose takes `{/* nifra-expect NF-C062: <reason> */}` above the element in JSX (`// nifra-expect NF-C062: <reason>` outside JSX braces), or `<!-- nifra-expect NF-C062: <reason> -->` in a Vue or Svelte template.',
325
+ docs: "/docs/errors",
326
+ },
327
+ "NF-C063": {
328
+ why: 'Markup that works but reads worse to assistive technology than it could: an image with no `alt`, a positive `tabindex` that jumps the page\'s tab order, a `<div role="button">` that has to rebuild what `<button>` gives for free, a role the element already has, or an `<html>` with no `lang`.',
329
+ fix: 'Describe the image in `alt`, or write `alt=""` when it is decoration. Use `tabindex="0"` or `-1`. Use the native element. Remove the repeated role. Give `<html>` a `lang` naming the page\'s language, such as `lang="en"` for English. A use kept on purpose takes `{/* nifra-expect NF-C063: <reason> */}` above the element in JSX (`// nifra-expect NF-C063: <reason>` outside JSX braces), or `<!-- nifra-expect NF-C063: <reason> -->` in a Vue or Svelte template; `nifra-expect a11y: <reason>` covers both codes.',
330
+ docs: "/docs/errors",
331
+ },
332
+ "NF-C064": {
333
+ why: "A data-island host names an id that no mountIslands or enableSwap call in the project lists, so no enhancer ever runs on it. The server-rendered markup stays as it is and nothing warns at runtime.",
334
+ fix: "Add the id to the mountIslands map, or fix the id in the markup (the check lists the ids the project mounts). For a host mounted from outside the project, put `// nifra-expect NF-C064: <reason>` above it. In an html template, put `<!-- nifra-expect NF-C064: <reason> -->` on its own line directly above the host.",
335
+ docs: "/docs/islands",
336
+ },
337
+ "NF-C065": {
338
+ why: "The props a host passes in data-island-props do not match the props type the enhancer declares: a required prop is missing, a prop is not declared, or a literal has another primitive type. The props travel as JSON in an attribute, so TypeScript never compares the two.",
339
+ fix: "Pass what the enhancer's props type declares, or change the type. The check reads plain type literals from enhancer type arguments and inline props parameter annotations. It reads literal JSON, JSX object props, and object literals passed to `islandProps` or `JSON.stringify`. It checks only types and values it can establish from these forms. To keep an intentional difference, put `// nifra-expect NF-C065: <reason>` above the host. In an html template, put `<!-- nifra-expect NF-C065: <reason> -->` on its own line directly above the host.",
340
+ docs: "/docs/islands",
341
+ },
342
+ "NF-C066": {
343
+ why: "A data-bind-attr pair names an attribute the binding runtime refuses to set: an event-handler or srcdoc attribute, a URL attribute on a script, iframe, object, embed, link or base element, or any attribute of an SVG animation element (set, animate, animateMotion, animateTransform: an animation can set a link's href to a script URL). The binding is skipped with a console warning, so the attribute never changes.",
344
+ fix: "Bind a different attribute. A URL that must change on such an element is set by the server render, or by an enhancer you review.",
345
+ docs: "/docs/islands",
346
+ },
322
347
  "NF-D001": {
323
348
  why: "The doctor gate of `nifra assure` found an undeclared import or a package installed more than once.",
324
349
  fix: "Run `nifra doctor` for the details and the fix of each finding.",
@@ -412,4 +437,9 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
412
437
  fix: "Declare messageSchema (a discriminated union for several frame kinds): message() receives the parsed, validated value and invalid frames go to onInvalidMessage.",
413
438
  docs: "/docs/websockets",
414
439
  },
440
+ "NF-S010": {
441
+ why: "A Deno or Bun listener answers every request without checking Host, and the project does not say a proxy does. Deno builds the request URL from Host, so a Host such as `evil.test/admin?` routes a `/pub/x` request to `/admin`, past a path rule in front of the app; Bun leaves `req.url` relative, or built on a Host the URL parser refuses.",
442
+ fix: 'Set `validateHost: true` on the Nifra server (one header read per request); a bare `Deno.serve` or `Bun.serve` handler has no such option, so check Host there before routing on it. Behind a proxy that checks Host, say so instead: `"hostTopology": "proxied"` in nifra.check.json, or `// nifra-expect NF-S010: <reason>` above the listener.',
443
+ docs: "/docs/security",
444
+ },
415
445
  })