@behavioral-agentic-design-system/core 0.42.0 → 0.47.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 (314) hide show
  1. package/package.json +38 -8
  2. package/scripts/a11y-lint.cjs +101 -14
  3. package/scripts/bads-sync.mjs +1 -1
  4. package/scripts/build-tokens.cjs +122 -7
  5. package/scripts/check-dark-contrast.mjs +204 -0
  6. package/scripts/check-flush-edges.mjs +245 -0
  7. package/scripts/check-spec.mjs +73 -0
  8. package/scripts/deal-directions.mjs +186 -0
  9. package/scripts/design-system-advisory/README.md +239 -0
  10. package/scripts/design-system-advisory/check-copy-punctuation.mjs +44 -0
  11. package/scripts/design-system-advisory/check-even-padding.mjs +35 -0
  12. package/scripts/design-system-advisory/check-hand-built-button.mjs +46 -0
  13. package/scripts/design-system-advisory/check-html-nesting.mjs +51 -0
  14. package/scripts/design-system-advisory/check-icon-sizing.mjs +79 -0
  15. package/scripts/design-system-advisory/check-label-case.mjs +92 -0
  16. package/scripts/design-system-advisory/check-native-form-controls.mjs +53 -0
  17. package/scripts/design-system-advisory/check-radius.mjs +56 -0
  18. package/scripts/design-system-advisory/check-raw-values.mjs +61 -0
  19. package/scripts/design-system-advisory/check-small-text.mjs +72 -0
  20. package/scripts/design-system-advisory/check-tap-target.mjs +70 -0
  21. package/scripts/design-system-advisory/defaults.mjs +90 -0
  22. package/scripts/design-system-advisory/fixtures/clean.tsx.fixture +12 -0
  23. package/scripts/design-system-advisory/fixtures/violations.tsx.fixture +19 -0
  24. package/scripts/design-system-advisory/lib.mjs +255 -0
  25. package/scripts/design-system-advisory/run.mjs +189 -0
  26. package/scripts/design-system-advisory/workflow.yml +82 -0
  27. package/scripts/health-report.mjs +20 -14
  28. package/scripts/lib/copy-strings.mjs +146 -0
  29. package/scripts/lib/counted-lint.mjs +100 -0
  30. package/scripts/lib/dark-contrast.mjs +120 -0
  31. package/scripts/lib/flush-edges.mjs +294 -0
  32. package/scripts/lib/lab-lint.mjs +62 -0
  33. package/scripts/lib/marketing-library.mjs +129 -0
  34. package/scripts/lib/mount-page.mjs +25 -0
  35. package/scripts/lib/on-system.mjs +249 -0
  36. package/scripts/lib/random.mjs +22 -0
  37. package/scripts/lib/source-scan.mjs +173 -0
  38. package/scripts/lib/spec-parse.d.mts +25 -0
  39. package/scripts/lib/spec-parse.mjs +188 -0
  40. package/scripts/lib/tells.mjs +366 -0
  41. package/scripts/lint-arbitrary-tokens.mjs +47 -0
  42. package/scripts/lint-component-token-refs.mjs +63 -0
  43. package/scripts/lint-content-hierarchy.mjs +114 -0
  44. package/scripts/lint-control-baseline.mjs +72 -0
  45. package/scripts/lint-copy-punctuation.mjs +60 -0
  46. package/scripts/lint-css-vars.mjs +175 -0
  47. package/scripts/lint-even-padding.mjs +58 -0
  48. package/scripts/lint-html-nesting.mjs +116 -0
  49. package/scripts/lint-label-case.mjs +219 -0
  50. package/scripts/lint-live-ctas.mjs +138 -0
  51. package/scripts/lint-microanimation.mjs +2 -2
  52. package/scripts/lint-proximity.mjs +181 -0
  53. package/scripts/lint-slop.mjs +1 -1
  54. package/scripts/lint-spacing-scale.mjs +78 -0
  55. package/scripts/lint-target-size.cjs +132 -0
  56. package/scripts/lint-token-primitives.mjs +307 -0
  57. package/scripts/on-system-score.mjs +95 -0
  58. package/scripts/size-audit.cjs +2 -2
  59. package/scripts/slop-rules.mjs +1 -1
  60. package/scripts/source-images.mjs +180 -0
  61. package/scripts/ux-tells.mjs +80 -0
  62. package/scripts/wcag-audit.cjs +25 -4
  63. package/src/api/brand-colors.ts +3 -0
  64. package/src/api/brand-fonts.ts +3 -0
  65. package/src/api/brand-mark.ts +6 -1
  66. package/src/api/dev-write-guard.ts +53 -0
  67. package/src/api/layers/file.ts +9 -4
  68. package/src/api/onboarding-extract.ts +85 -30
  69. package/src/api/onboarding.ts +3 -0
  70. package/src/api/save-tokens.ts +3 -0
  71. package/src/api/site-auth.ts +14 -2
  72. package/src/app/layout.tsx +6 -0
  73. package/src/app/preview/canvas/page.tsx +12 -0
  74. package/src/app/preview/components/page.tsx +828 -14
  75. package/src/app/preview/sticker-sheet/page.tsx +329 -0
  76. package/src/app/preview/sticker-sheet/specimens.tsx +296 -0
  77. package/src/app/preview/studio/blank-screen.tsx +143 -0
  78. package/src/app/preview/studio/page.tsx +7 -0
  79. package/src/app/shell.tsx +164 -47
  80. package/src/components/Foundations/Colors.stories.tsx +119 -8
  81. package/src/components/canvas/canvas.tsx +458 -0
  82. package/src/components/canvas/layout.ts +72 -0
  83. package/src/components/canvas/parse-canvas.ts +32 -0
  84. package/src/components/canvas/sample.ts +90 -0
  85. package/src/components/canvas/spec-frame.tsx +43 -0
  86. package/src/components/canvas/types.ts +33 -0
  87. package/src/components/docs-tab.tsx +7 -7
  88. package/src/components/home-recent.tsx +73 -0
  89. package/src/components/home-tab.tsx +19 -14
  90. package/src/components/layers-tab.tsx +2 -2
  91. package/src/components/markdown-preview.tsx +60 -12
  92. package/src/components/onboarding-wizard.tsx +1 -1
  93. package/src/components/studio/control-panel.tsx +299 -0
  94. package/src/components/studio/control-row.tsx +77 -0
  95. package/src/components/studio/preview-frame.tsx +165 -0
  96. package/src/components/studio/preview-pane.tsx +247 -0
  97. package/src/components/studio/studio.tsx +133 -128
  98. package/src/components/studio/types.ts +218 -0
  99. package/src/components/studio/use-studio-tweaks.ts +128 -0
  100. package/src/components/studio/use-studio-view-state.ts +72 -0
  101. package/src/components/ui/autocomplete.tsx +1 -1
  102. package/src/components/ui/avatar.tsx +4 -0
  103. package/src/components/ui/chart.tsx +134 -42
  104. package/src/components/ui/checkbox-group.tsx +1 -1
  105. package/src/components/ui/checkbox.tsx +1 -1
  106. package/src/components/ui/color-picker.tsx +20 -4
  107. package/src/components/ui/combobox.tsx +1 -0
  108. package/src/components/ui/command.tsx +1 -1
  109. package/src/components/ui/data-table.tsx +64 -3
  110. package/src/components/ui/date-field.tsx +1 -1
  111. package/src/components/ui/date-picker.tsx +2 -0
  112. package/src/components/ui/date-range-picker.tsx +4 -0
  113. package/src/components/ui/editable.tsx +1 -0
  114. package/src/components/ui/faceted-filter.tsx +187 -0
  115. package/src/components/ui/file-upload.tsx +21 -2
  116. package/src/components/ui/gauge-chart.tsx +18 -4
  117. package/src/components/ui/heatmap.tsx +3 -1
  118. package/src/components/ui/inline-edit.tsx +175 -0
  119. package/src/components/ui/input-group.tsx +5 -2
  120. package/src/components/ui/month-picker.tsx +1 -1
  121. package/src/components/ui/multi-select.tsx +1 -0
  122. package/src/components/ui/number-input.tsx +28 -5
  123. package/src/components/ui/otp-input.tsx +208 -0
  124. package/src/components/ui/phone-input.tsx +274 -0
  125. package/src/components/ui/radio-group.tsx +2 -2
  126. package/src/components/ui/search-input.tsx +1 -1
  127. package/src/components/ui/sparkline.tsx +33 -4
  128. package/src/components/ui/spinner.tsx +23 -4
  129. package/src/components/ui/table.tsx +9 -0
  130. package/src/components/ui/tags-input.tsx +1 -1
  131. package/src/components/ui/timer.tsx +1 -0
  132. package/src/components/ui/transfer-list.tsx +13 -26
  133. package/src/components/ui/week-picker.tsx +1 -13
  134. package/src/components/ui/year-picker.tsx +1 -1
  135. package/src/data/component-added.json +966 -0
  136. package/src/data/docs-index.ts +35 -2
  137. package/src/data/history.json +161 -161
  138. package/src/data/sticker-sheet.json +9244 -0
  139. package/src/docs-trace-globs.json +1 -0
  140. package/src/hooks/use-global-mono-font.ts +1 -0
  141. package/src/hooks/use-global-primary-color.ts +1 -0
  142. package/src/hooks/use-global-sans-font.ts +1 -0
  143. package/src/hooks/use-global-serif-font.ts +1 -0
  144. package/src/hooks/use-global-type-scale.ts +17 -2
  145. package/src/hooks/use-mobile.ts +2 -0
  146. package/src/hooks/use-sync-type-scale.ts +7 -11
  147. package/src/lib/chart-motion.ts +41 -0
  148. package/src/lib/get-icon-color.ts +1 -1
  149. package/src/lib/spec-parse.ts +4 -0
  150. package/src/lib/svg-sanitize.ts +19 -9
  151. package/src/stories/Accordion.stories.tsx +7 -0
  152. package/src/stories/ActionBar.stories.tsx +5 -0
  153. package/src/stories/Affix.stories.tsx +4 -0
  154. package/src/stories/AiBadge.stories.tsx +9 -7
  155. package/src/stories/Alert.stories.tsx +13 -0
  156. package/src/stories/AlertDialog.stories.tsx +4 -0
  157. package/src/stories/Anchor.stories.tsx +5 -0
  158. package/src/stories/AngleSlider.stories.tsx +6 -3
  159. package/src/stories/AspectRatio.stories.tsx +4 -0
  160. package/src/stories/Autocomplete.stories.tsx +8 -0
  161. package/src/stories/Avatar.stories.tsx +10 -0
  162. package/src/stories/Badge.stories.tsx +14 -6
  163. package/src/stories/Blockquote.stories.tsx +6 -0
  164. package/src/stories/BottomNavigation.stories.tsx +4 -0
  165. package/src/stories/Breadcrumb.stories.tsx +3 -0
  166. package/src/stories/Burger.stories.tsx +1 -0
  167. package/src/stories/Button.stories.tsx +24 -0
  168. package/src/stories/ButtonGroup.stories.tsx +9 -0
  169. package/src/stories/Calendar.stories.tsx +3 -0
  170. package/src/stories/Canvas.stories.tsx +45 -0
  171. package/src/stories/Card.stories.tsx +4 -0
  172. package/src/stories/Carousel.stories.tsx +6 -0
  173. package/src/stories/Cascader.stories.tsx +4 -0
  174. package/src/stories/Chart.stories.tsx +46 -1
  175. package/src/stories/ChatBubble.stories.tsx +8 -2
  176. package/src/stories/ChatMarker.stories.tsx +1 -0
  177. package/src/stories/Checkbox.stories.tsx +40 -0
  178. package/src/stories/CheckboxCard.stories.tsx +8 -0
  179. package/src/stories/CheckboxGroup.stories.tsx +19 -0
  180. package/src/stories/Chip.stories.tsx +10 -19
  181. package/src/stories/CircularProgress.stories.tsx +13 -27
  182. package/src/stories/Clipboard.stories.tsx +6 -0
  183. package/src/stories/CloseButton.stories.tsx +6 -4
  184. package/src/stories/Code.stories.tsx +8 -1
  185. package/src/stories/Collapsible.stories.tsx +2 -0
  186. package/src/stories/ColorPicker.stories.tsx +46 -0
  187. package/src/stories/ColorSwatch.stories.tsx +1 -0
  188. package/src/stories/Combobox.stories.tsx +9 -0
  189. package/src/stories/Command.stories.tsx +2 -0
  190. package/src/stories/Container.stories.tsx +8 -0
  191. package/src/stories/ContextMenu.stories.tsx +9 -0
  192. package/src/stories/CopyButton.stories.tsx +12 -36
  193. package/src/stories/DataList.stories.tsx +8 -0
  194. package/src/stories/DataTable.stories.tsx +39 -0
  195. package/src/stories/DateField.stories.tsx +28 -0
  196. package/src/stories/DatePicker.stories.tsx +34 -0
  197. package/src/stories/DateRangePicker.stories.tsx +32 -0
  198. package/src/stories/Dialog.stories.tsx +8 -0
  199. package/src/stories/Drawer.stories.tsx +6 -0
  200. package/src/stories/DropdownMenu.stories.tsx +2 -0
  201. package/src/stories/Editable.stories.tsx +12 -0
  202. package/src/stories/EmptyState.stories.tsx +9 -0
  203. package/src/stories/FacetedFilter.stories.tsx +197 -0
  204. package/src/stories/Field.stories.tsx +7 -0
  205. package/src/stories/Fieldset.stories.tsx +8 -0
  206. package/src/stories/FileButton.stories.tsx +4 -0
  207. package/src/stories/FileUpload.stories.tsx +16 -17
  208. package/src/stories/FloatLabel.stories.tsx +3 -8
  209. package/src/stories/FloatingActionButton.stories.tsx +10 -0
  210. package/src/stories/FloatingIndicator.stories.tsx +4 -0
  211. package/src/stories/FloatingPanel.stories.tsx +6 -0
  212. package/src/stories/FocusTrap.stories.tsx +5 -0
  213. package/src/stories/FormatByte.stories.tsx +6 -0
  214. package/src/stories/FormatDate.stories.tsx +8 -0
  215. package/src/stories/FormatNumber.stories.tsx +9 -0
  216. package/src/stories/GaugeChart.stories.tsx +9 -3
  217. package/src/stories/Heatmap.stories.tsx +11 -0
  218. package/src/stories/Highlight.stories.tsx +6 -0
  219. package/src/stories/HoverCard.stories.tsx +4 -0
  220. package/src/stories/Image.stories.tsx +9 -0
  221. package/src/stories/Indicator.stories.tsx +19 -0
  222. package/src/stories/InlineEdit.stories.tsx +106 -0
  223. package/src/stories/Input.stories.tsx +7 -0
  224. package/src/stories/InputClearButton.stories.tsx +3 -0
  225. package/src/stories/InputGroup.stories.tsx +40 -0
  226. package/src/stories/Kbd.stories.tsx +7 -1
  227. package/src/stories/KeyboardShortcut.stories.tsx +2 -0
  228. package/src/stories/Label.stories.tsx +2 -0
  229. package/src/stories/Link.stories.tsx +9 -0
  230. package/src/stories/List.stories.tsx +8 -0
  231. package/src/stories/Listbox.stories.tsx +1 -0
  232. package/src/stories/LoadingDots.stories.tsx +5 -3
  233. package/src/stories/LoadingOverlay.stories.tsx +5 -1
  234. package/src/stories/Mark.stories.tsx +5 -0
  235. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  236. package/src/stories/Marquee.stories.tsx +4 -0
  237. package/src/stories/Masonry.stories.tsx +5 -0
  238. package/src/stories/Menubar.stories.tsx +3 -0
  239. package/src/stories/Meter.stories.tsx +11 -17
  240. package/src/stories/MonthPicker.stories.tsx +26 -1
  241. package/src/stories/MotionToggle.stories.tsx +1 -0
  242. package/src/stories/MultiSelect.stories.tsx +9 -0
  243. package/src/stories/NativeSelect.stories.tsx +1 -0
  244. package/src/stories/NavLink.stories.tsx +7 -0
  245. package/src/stories/NavigationMenu.stories.tsx +5 -0
  246. package/src/stories/NavigationRail.stories.tsx +10 -0
  247. package/src/stories/Notification.stories.tsx +13 -34
  248. package/src/stories/NumberInput.stories.tsx +33 -1
  249. package/src/stories/OtpInput.stories.tsx +110 -0
  250. package/src/stories/Overlay.stories.tsx +5 -1
  251. package/src/stories/Pagination.stories.tsx +8 -0
  252. package/src/stories/PasswordInput.stories.tsx +2 -0
  253. package/src/stories/PhoneInput.stories.tsx +127 -0
  254. package/src/stories/PinInput.stories.tsx +9 -2
  255. package/src/stories/Popover.stories.tsx +2 -0
  256. package/src/stories/Progress.stories.tsx +6 -1
  257. package/src/stories/Prose.stories.tsx +8 -0
  258. package/src/stories/QrCode.stories.tsx +2 -0
  259. package/src/stories/Questionnaire.stories.tsx +7 -0
  260. package/src/stories/RadioGroup.stories.tsx +40 -0
  261. package/src/stories/RatingGroup.stories.tsx +8 -4
  262. package/src/stories/Resizable.stories.tsx +4 -2
  263. package/src/stories/Result.stories.tsx +3 -0
  264. package/src/stories/Reveal.stories.tsx +2 -0
  265. package/src/stories/RollingNumber.stories.tsx +5 -0
  266. package/src/stories/ScrollArea.stories.tsx +3 -1
  267. package/src/stories/SearchInput.stories.tsx +10 -6
  268. package/src/stories/SegmentedControl.stories.tsx +11 -0
  269. package/src/stories/Select.stories.tsx +7 -0
  270. package/src/stories/Separator.stories.tsx +6 -0
  271. package/src/stories/Sheet.stories.tsx +5 -0
  272. package/src/stories/Sidebar.stories.tsx +40 -1
  273. package/src/stories/SimpleGrid.stories.tsx +5 -0
  274. package/src/stories/Skeleton.stories.tsx +8 -0
  275. package/src/stories/SkeletonTable.stories.tsx +6 -5
  276. package/src/stories/SkipLink.stories.tsx +3 -0
  277. package/src/stories/Slider.stories.tsx +2 -1
  278. package/src/stories/Sonner.stories.tsx +7 -0
  279. package/src/stories/Sparkline.stories.tsx +14 -1
  280. package/src/stories/Spinner.stories.tsx +20 -10
  281. package/src/stories/Spoiler.stories.tsx +5 -0
  282. package/src/stories/Squircle.stories.tsx +7 -0
  283. package/src/stories/Stack.stories.tsx +7 -0
  284. package/src/stories/StatusBadge.stories.tsx +12 -6
  285. package/src/stories/Stepper.stories.tsx +5 -0
  286. package/src/stories/Switch.stories.tsx +4 -0
  287. package/src/stories/Table.stories.tsx +10 -1
  288. package/src/stories/Tabs.stories.tsx +8 -0
  289. package/src/stories/Tag.stories.tsx +13 -5
  290. package/src/stories/TagsInput.stories.tsx +15 -0
  291. package/src/stories/Text.stories.tsx +12 -0
  292. package/src/stories/Textarea.stories.tsx +9 -0
  293. package/src/stories/ThemeIcon.stories.tsx +6 -3
  294. package/src/stories/TimePicker.stories.tsx +2 -0
  295. package/src/stories/Timeline.stories.tsx +12 -0
  296. package/src/stories/Timer.stories.tsx +30 -0
  297. package/src/stories/Toggle.stories.tsx +7 -5
  298. package/src/stories/ToggleGroup.stories.tsx +5 -0
  299. package/src/stories/ToggleTip.stories.tsx +4 -0
  300. package/src/stories/Toolbar.stories.tsx +6 -0
  301. package/src/stories/Tooltip.stories.tsx +3 -0
  302. package/src/stories/Tour.stories.tsx +3 -0
  303. package/src/stories/TransferList.stories.tsx +7 -0
  304. package/src/stories/TreeSelect.stories.tsx +4 -0
  305. package/src/stories/TreeView.stories.tsx +5 -0
  306. package/src/stories/TypingIndicator.stories.tsx +4 -0
  307. package/src/stories/VisuallyHidden.stories.tsx +3 -0
  308. package/src/stories/Watermark.stories.tsx +6 -0
  309. package/src/stories/WeekPicker.stories.tsx +25 -1
  310. package/src/stories/WordRotate.stories.tsx +5 -0
  311. package/src/stories/YearPicker.stories.tsx +26 -11
  312. package/src/stories/story-groups.json +22 -16
  313. package/src/styles.css +50 -2
  314. package/src/tokens.json +86 -58
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-component-token-refs.mjs: a component token's colour must come from the SEMANTIC layer.
4
+ *
5
+ * The three layers are primitive (a value: blue-600), semantic (an intent: action.primary), and component (a use:
6
+ * button.primary.background). The layering only pays off if each layer points one step down. A component token
7
+ * that points straight at a primitive, or holds a raw hex, skips the semantic layer, so a rebrand that re-points
8
+ * `action.primary` leaves that component behind, and dark mode (which re-maps semantics, not primitives) breaks
9
+ * for it. Today every component colour token goes through `color.semantic`; this keeps it that way.
10
+ *
11
+ * RULE. In tokens.json under `component`, any token whose $type is "color" must have a $value that is either a
12
+ * reference to `{color.semantic.*}` or a CSS colour keyword (transparent, currentColor, inherit). A reference to
13
+ * any other colour path, or a literal colour, fails. Non-colour tokens (radius, spacing, shadow) point at their
14
+ * scales and are not checked: those scales are the semantic layer for those types.
15
+ *
16
+ * Pattern from Jens Merkel, "Design token naming that scales" (2026): component tokens reference semantic tokens,
17
+ * never primitives.
18
+ *
19
+ * Strict (exits 1): it has no violations to grandfather. Escape hatch: none, because the fix is always to add or
20
+ * pick a semantic token.
21
+ *
22
+ * pnpm lint:component-token-refs
23
+ */
24
+ import { readFileSync } from "node:fs";
25
+ import { join } from "node:path";
26
+
27
+ const KEYWORDS = new Set(["transparent", "currentcolor", "inherit"]);
28
+
29
+ /** Every violation as { path, value, why }. `tokens` is the parsed tokens.json. */
30
+ export function findViolations(tokens) {
31
+ const out = [];
32
+ (function walk(node, path) {
33
+ for (const [key, v] of Object.entries(node ?? {})) {
34
+ if (key.startsWith("$") || !v || typeof v !== "object") continue;
35
+ if (!("$value" in v)) {
36
+ walk(v, [...path, key]);
37
+ continue;
38
+ }
39
+ if (v.$type !== "color") continue;
40
+ const value = String(v.$value).trim();
41
+ const here = ["component", ...path, key].join(".");
42
+ if (KEYWORDS.has(value.toLowerCase())) continue;
43
+ const ref = /^\{([^}]+)\}$/.exec(value);
44
+ if (!ref) out.push({ path: here, value, why: "a literal colour; reference a color.semantic token" });
45
+ else if (!ref[1].startsWith("color.semantic.")) out.push({ path: here, value, why: `points at ${ref[1].split(".").slice(0, 2).join(".")}, not the semantic layer` });
46
+ }
47
+ })(tokens.component, []);
48
+ return out;
49
+ }
50
+
51
+ function main() {
52
+ const file = join(process.cwd(), "packages/core/src/tokens.json");
53
+ const violations = findViolations(JSON.parse(readFileSync(file, "utf8")));
54
+ if (violations.length) {
55
+ console.error(`✗ component-token-refs: ${violations.length} component colour token(s) skip the semantic layer:\n`);
56
+ for (const v of violations) console.error(` ${v.path} = ${v.value}\n ${v.why}`);
57
+ console.error("\nFix: reference a {color.semantic.*} token. If none says what you mean, add a semantic token first.");
58
+ process.exit(1);
59
+ }
60
+ console.log("✓ component-token-refs: every component colour token goes through color.semantic");
61
+ }
62
+
63
+ if (import.meta.url === `file://${process.argv[1]}`) main();
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-content-hierarchy: semantic hierarchy is decided before typography, and two roles never share one treatment.
4
+ *
5
+ * Enforces layer-6-patterns-and-rules/content-hierarchy.md.
6
+ *
7
+ * WHY. A card's own title and the titles of the two options inside it rendered at the SAME font size.
8
+ * Nothing looked broken: both were legible, both correctly bold. What was lost is containment. The
9
+ * card's subject and the options inside it read as three equal headings rather than one statement with
10
+ * two choices under it. It is a structural failure with no visual symptom, which is exactly the kind a
11
+ * lint earns its place on.
12
+ *
13
+ * WHAT IT ASSERTS
14
+ * R1 A component that names itself a title or a heading must RENDER one. `<span className="text-sm
15
+ * font-semibold">` is not a heading, and the moment it has to be `<h3>` the author is forced to
16
+ * choose a level, which is the point. Deciding the level is the work; the size is the consequence.
17
+ * R2 Two different heading levels in one file must not share a type-size class.
18
+ * R3 Heading levels must not skip. h2 straight to h4 leaves a reader (and a screen reader) guessing.
19
+ * R4 One primary heading per file. Two h1s means the surface is about two things.
20
+ * R5 One heading level must not carry two different type sizes ("same role = same treatment").
21
+ *
22
+ * WHAT IT DELIBERATELY DOES NOT ASSERT. "Same role = same treatment" for peers (two cards in a row, two
23
+ * rows in a list) is not checked: peers are nearly always emitted from one `.map()` over one component,
24
+ * so they agree by construction, and the static signal for a hand-written pair is too weak to be worth
25
+ * the false positives.
26
+ *
27
+ * ESCAPE HATCH. R2 and R5 compare file-wide, so a file holding two genuinely separate documents (a docs
28
+ * page wrapping a simulated screen whose card titles belong to the simulation) trips them. Put
29
+ * `hierarchy-ok: <reason>` on the heading's line or the line above. A bare marker does not count.
30
+ *
31
+ * node packages/core/scripts/lint-content-hierarchy.mjs [--warn | --init | --ratchet] [paths]
32
+ */
33
+ import { withoutComments } from "./lib/source-scan.mjs";
34
+ import { runLint, markedNear, lineAt } from "./lib/lab-lint.mjs";
35
+ import { isMain } from "./lib/counted-lint.mjs";
36
+
37
+ /**
38
+ * Tailwind type-size utilities, the size half of "treatment". The lookbehind excludes a
39
+ * breakpoint-prefixed size: `text-4xl md:text-5xl` is ONE treatment expressed responsively.
40
+ */
41
+ const SIZE = /(?<![\w:-])text-(xs|sm|base|lg|xl|[2-9]xl)\b/g;
42
+
43
+ /** Comments and template literals blanked, so prose explaining a rule can never trip it. */
44
+ const blankNonCode = (src) => withoutComments(src).replace(/`(?:[^`\\]|\\.)*`/g, (m) => m.replace(/[^\n]/g, " "));
45
+
46
+ export function findHierarchyProblems(raw) {
47
+ const src = blankNonCode(raw);
48
+ const rawLines = raw.split("\n");
49
+ const problems = [];
50
+ const add = (rule, line, what) => problems.push({ line, text: `[${rule}] ${what}` });
51
+
52
+ // R1: a component named *Title / *Heading must render a heading.
53
+ const decl = /(?:function|const)\s+([A-Z][A-Za-z0-9]*(?:Title|Heading)[A-Za-z0-9]*)\s*[=(]/g;
54
+ for (const m of src.matchAll(decl)) {
55
+ const rest = src.slice(m.index + 1);
56
+ const nextDecl = rest.search(/\n(?:export\s+)?(?:function|const)\s+[A-Z]/);
57
+ const body = rest.slice(0, nextDecl === -1 ? rest.length : nextDecl);
58
+ const name = m[1];
59
+ // shadcn-style primitives leave the heading level to the caller (Radix's Title renders its own).
60
+ if (/^(?:Card|Dialog|AlertDialog|Drawer|Sheet)Title$/.test(name)) continue;
61
+ const rendersHeading =
62
+ /<\s*h[1-6][\s>]/.test(body) ||
63
+ /`h\$\{/.test(raw.slice(m.index, m.index + body.length)) ||
64
+ /\bas\s*=\s*\{?["'`]?h[1-6]/.test(body) ||
65
+ /role\s*=\s*["']heading["']/.test(body) ||
66
+ /\bHeading\b\s*[\s/>]/.test(body) ||
67
+ // A wrapper that forwards to another *Title component: the level is that component's problem.
68
+ /<\s*[A-Z][A-Za-z0-9]*(?:Title|Heading)/.test(body);
69
+ if (!rendersHeading) add("R1", lineAt(src, m.index), `${name} is named a title but renders no heading element (a title that is a span has no level, so nothing forces a decision about where it sits)`);
70
+ }
71
+
72
+ // R2/R3/R4/R5: the heading elements actually present in this file.
73
+ const levels = new Map(); // level -> Set of size classes
74
+ const seen = [];
75
+ for (const m of src.matchAll(/<\s*h([1-6])\b([^>]*)>/g)) {
76
+ const level = Number(m[1]);
77
+ const line = lineAt(src, m.index);
78
+ if (markedNear(rawLines, line, "hierarchy-ok:")) continue;
79
+ seen.push({ level, line });
80
+ if (!levels.has(level)) levels.set(level, new Set());
81
+ for (const s of m[2].match(SIZE) ?? []) levels.get(level).add(s);
82
+ }
83
+ const firstLine = (pred) => seen.find(pred)?.line ?? 1;
84
+
85
+ const bySize = new Map();
86
+ for (const [level, sizes] of levels) {
87
+ for (const s of sizes) bySize.set(s, (bySize.get(s) ?? new Set()).add(level));
88
+ }
89
+ for (const [size, lv] of bySize) {
90
+ if (lv.size > 1) add("R2", firstLine((s) => lv.has(s.level)), `h${[...lv].sort().join(" and h")} both use "${size}" (two roles, one treatment)`);
91
+ }
92
+ const present = [...levels.keys()].sort((a, b) => a - b);
93
+ for (let i = 1; i < present.length; i++) {
94
+ if (present[i] - present[i - 1] > 1) add("R3", firstLine((s) => s.level === present[i]), `h${present[i - 1]} jumps straight to h${present[i]}`);
95
+ }
96
+ for (const [level, sizes] of levels) {
97
+ if (sizes.size > 1) add("R5", firstLine((s) => s.level === level), `h${level} uses ${[...sizes].sort().map((s) => `"${s}"`).join(" and ")} (same role, two treatments)`);
98
+ }
99
+ const h1s = seen.filter((s) => s.level === 1);
100
+ if (h1s.length > 1) add("R4", h1s[1].line, `${h1s.length} h1 elements in one file (a surface is about one thing)`);
101
+ return problems;
102
+ }
103
+
104
+ if (isMain(import.meta.url)) {
105
+ process.exit(
106
+ runLint({
107
+ ruleId: "content-hierarchy",
108
+ bin: "bads-lint-content-hierarchy",
109
+ tsxOnly: true,
110
+ detect: (src) => findHierarchyProblems(src),
111
+ fix: "Decide the structure first: name the one primary heading, then what is subordinate to it, then which things are peers. The type scale follows. Genuine exceptions: `{/* hierarchy-ok: <why> */}`. See layer-6-patterns-and-rules/content-hierarchy.md.",
112
+ }),
113
+ );
114
+ }
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-control-baseline: a button beside text in a row aligned to the top.
4
+ *
5
+ * WHY. A tap target is at least 44px tall; a line of label text is about 20px. A button centres its
6
+ * own label, so in a row set to `items-start` the two BOXES line up at the top and the button's word
7
+ * lands (44 - 20) / 2 = 12px below the line it belongs to. A constant offset is a rule being followed,
8
+ * not a mistake being made, which is why it is easy to miss and always the same.
9
+ *
10
+ * The trap is that `items-start` is the obviously correct choice: the label can wrap to two lines, so
11
+ * centring would float the button in the middle of a paragraph. `items-start` fixes the wrapping case
12
+ * and silently breaks the alignment case, and nothing complains, because both boxes really are flush
13
+ * at the top.
14
+ *
15
+ * WHAT IT FLAGS. A flex ROW (not a column) set to `items-start` with a button among its children.
16
+ *
17
+ * THE FIX is `items-baseline`. It aligns the TEXT rather than the boxes, so it is right whether the
18
+ * label is one line or four, and the button keeps its 44px. It is NOT a top margin on the button:
19
+ * that is a hand-tuned nudge that is right at one size and wrong at every other, and pulling a 44px
20
+ * target upward clips the thing it exists for.
21
+ *
22
+ * ESCAPE HATCH. `control-baseline-ok: <reason>` on the line directly above the row. A genuine case:
23
+ * a dismiss X meant to sit level with the top of a block, not with a line of text.
24
+ *
25
+ * Children are found by indentation (a child is more indented than the tag that opened it). That is
26
+ * crude next to a parser and right for formatter-written code.
27
+ *
28
+ * node packages/core/scripts/lint-control-baseline.mjs [--warn | --init | --ratchet] [paths]
29
+ */
30
+ import { codeAndClasses } from "./lib/source-scan.mjs";
31
+ import { runLint, markedNear } from "./lib/lab-lint.mjs";
32
+ import { isMain } from "./lib/counted-lint.mjs";
33
+
34
+ /** Anything that renders as a control tall enough to out-measure a line of text. */
35
+ const CONTROLS = /<(Button|CloseButton|ActionButton|IconButton|button)\b/;
36
+
37
+ export function findTopAlignedControls(src) {
38
+ const rawLines = src.split("\n");
39
+ const lines = codeAndClasses(src).split("\n");
40
+ const findings = [];
41
+ for (let i = 0; i < lines.length; i++) {
42
+ const line = lines[i];
43
+ if (!/\bitems-start\b/.test(line) || /\bflex-col\b/.test(line)) continue;
44
+ const indent = line.length - line.trimStart().length;
45
+ let found = null;
46
+ for (let j = i + 1; j < lines.length; j++) {
47
+ const child = lines[j];
48
+ if (!child.trim()) continue;
49
+ if (child.length - child.trimStart().length <= indent) break;
50
+ if (CONTROLS.test(child)) {
51
+ found = j + 1;
52
+ break;
53
+ }
54
+ }
55
+ if (!found) continue;
56
+ if (markedNear(rawLines, i + 1, "control-baseline-ok:", { lines: 1 })) continue;
57
+ findings.push({ line: i + 1, text: `items-start row with a button on line ${found} (its label sits ~12px below the text beside it)` });
58
+ }
59
+ return findings;
60
+ }
61
+
62
+ if (isMain(import.meta.url)) {
63
+ process.exit(
64
+ runLint({
65
+ ruleId: "control-baseline",
66
+ bin: "bads-lint-control-baseline",
67
+ tsxOnly: true,
68
+ detect: (src) => findTopAlignedControls(src),
69
+ fix: "Use `items-baseline`, or mark the line above `control-baseline-ok: <why>`. Do not nudge the button with a top margin.",
70
+ }),
71
+ );
72
+ }
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-copy-punctuation: the punctuation mistakes that read as unfinished typing, caught where the copy lives.
4
+ *
5
+ * language-lint already enforces BADS-3a (banned terms) and BADS-3b (no em dash). This covers two
6
+ * adjacent mistakes it does not:
7
+ *
8
+ * P2 Three periods where an ellipsis belongs. `…` (U+2026), never `...`. Three periods are wider,
9
+ * break awkwardly at the end of a line, and read as unfinished typing.
10
+ * P3 A literal `\uXXXX` escape sitting in copy: the six characters, not the character they stand
11
+ * for. Nobody types this by hand. It comes from writing TSX through a script or a heredoc, and it
12
+ * renders to the reader exactly as written while every other check passes.
13
+ *
14
+ * WHAT COUNTS AS COPY is defined once in lib/copy-strings.mjs: JSX text, the values of copy-carrying
15
+ * props and keys, and the items of copy lists. Comments are blanked first. It reads `.ts` as well as
16
+ * `.tsx`, because a copy file (`copy.ts`, a scenario file) is where the most-read strings often live.
17
+ *
18
+ * ESCAPE HATCH. `copy-ok: <reason>` on the line or the line above, for strings read by the team rather
19
+ * than by a user. The reason is the mechanism.
20
+ *
21
+ * node packages/core/scripts/lint-copy-punctuation.mjs [--warn | --init | --ratchet] [paths]
22
+ */
23
+ import { blankComments, copyStrings } from "./lib/copy-strings.mjs";
24
+ import { runLint, markedNear, lineAt } from "./lib/lab-lint.mjs";
25
+ import { isMain } from "./lib/counted-lint.mjs";
26
+
27
+ const RULES = [
28
+ { id: "P2", test: (t) => (t.includes("...") ? "..." : null), message: "three periods where an ellipsis belongs; use the glyph … (U+2026)" },
29
+ {
30
+ id: "P3",
31
+ test: (t) => t.match(/\\u[0-9a-fA-F]{4}/)?.[0] ?? null,
32
+ message: "a literal \\uXXXX escape in copy: the escape sequence as six characters, not the character it stands for",
33
+ },
34
+ ];
35
+
36
+ export function findCopyPunctuation(raw) {
37
+ const rawLines = raw.split("\n");
38
+ const src = blankComments(raw);
39
+ const findings = [];
40
+ for (const { text, index } of copyStrings(src)) {
41
+ const line = lineAt(src, index);
42
+ if (markedNear(rawLines, line, "copy-ok:")) continue;
43
+ for (const rule of RULES) {
44
+ if (!rule.test(text)) continue;
45
+ findings.push({ line, text: `[${rule.id}] ${rule.message}: "${text.length > 80 ? `${text.slice(0, 80)}…` : text}"` });
46
+ }
47
+ }
48
+ return findings;
49
+ }
50
+
51
+ if (isMain(import.meta.url)) {
52
+ process.exit(
53
+ runLint({
54
+ ruleId: "copy-punctuation",
55
+ bin: "bads-lint-copy-punctuation",
56
+ detect: (src) => findCopyPunctuation(src),
57
+ fix: "Rewrite it. If the string is read by the team rather than by a user: `{/* copy-ok: <why> */}` on the line above.",
58
+ }),
59
+ );
60
+ }
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-css-vars — a custom property that is referenced but never declared.
4
+ *
5
+ * Enforces layer-6-patterns-and-rules/declared-custom-properties.md. CSS does
6
+ * not error on `var(--missing)`. `border-radius: var(--missing)` computes to 0px
7
+ * and `color: var(--missing)` falls back to the inherited colour, so the page
8
+ * renders, the build passes, and the defect ships looking like a design
9
+ * decision. The case that wrote this: four radius properties were deleted from a
10
+ * brand stylesheet with a comment saying every call site now used a utility, ten
11
+ * call sites still referenced them, and eight pills and status circles shipped
12
+ * square while every check stayed green.
13
+ *
14
+ * What counts as declared:
15
+ * - `--name:` in any stylesheet the BUILD emitted. Read the built CSS, not the
16
+ * source: hundreds of properties come from a Tailwind `@theme` block at build
17
+ * time and appear in no stylesheet on disk.
18
+ * - `--name:` anywhere in source, which covers `@property`, a CSS file, a style
19
+ * prop key (`style={{ "--progress": "40%" }}`) and `setProperty("--name", …)`.
20
+ *
21
+ * What it skips: a reference with a fallback (`var(--x, 9999px)`), which cannot
22
+ * render as nothing by construction; a name built at runtime (`var(--color-${key})`);
23
+ * anything inside a comment; and, with a reason, a line marked
24
+ * `css-var-ok: <why this is set at runtime>`. Property families a library sets at
25
+ * runtime (a chart's `--color-<series>`) are named once with --allow; Radix's
26
+ * `--radix-*`, Tailwind's `--tw-*` and cmdk's `--cmdk-*` are built in.
27
+ *
28
+ * It fails rather than skips when there is no built CSS to read. A check that
29
+ * quietly passes when it could not run is how this defect survives in the first
30
+ * place.
31
+ *
32
+ * Run (after a build):
33
+ * npx bads-lint-css-vars # looks for out/, then .next/static
34
+ * npx bads-lint-css-vars --css dist/assets # name the built CSS directory
35
+ * npx bads-lint-css-vars --allow --color- # property families set at runtime (chart series)
36
+ * npx bads-lint-css-vars --warn | --init | --ratchet
37
+ */
38
+
39
+ import fs from "node:fs";
40
+ import path from "node:path";
41
+ import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
42
+
43
+ /** Families that libraries set on elements at runtime, so no stylesheet declares them. */
44
+ export const RUNTIME_FAMILIES = ["--radix-", "--tw-", "--cmdk-"];
45
+
46
+ const SOURCE_ROOTS = ["app", "components", "src", "styles", "packages/core/src"];
47
+ const SOURCE_EXT = /\.(tsx?|jsx?|css|mdx?)$/;
48
+ const SKIP = new Set(["node_modules", ".next", "out", "dist", ".scratch", ".git", "vendor"]);
49
+
50
+ /** Strip comments, keeping line structure, so prose that names a property is not a reference. */
51
+ export function stripComments(src) {
52
+ return src
53
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
54
+ .replace(/(^|[^:])\/\/.*$/gm, (m, pre) => pre + " ".repeat(m.length - pre.length));
55
+ }
56
+
57
+ /** Every `--name` this text declares: `--name:` in CSS, a quoted style-prop key, or setProperty. */
58
+ export function extractDeclared(text) {
59
+ const out = new Set();
60
+ for (const m of text.matchAll(/(--[A-Za-z0-9_-]+)\s*:/g)) out.add(m[1]);
61
+ for (const m of text.matchAll(/["'`](--[A-Za-z0-9_-]+)["'`]\s*:/g)) out.add(m[1]);
62
+ for (const m of text.matchAll(/setProperty\(\s*["'`](--[A-Za-z0-9_-]+)["'`]/g)) out.add(m[1]);
63
+ return out;
64
+ }
65
+
66
+ const MARKER = /css-var-ok:([^\n*]*)/;
67
+
68
+ /**
69
+ * @param {string} src
70
+ * @param {Set<string>} declared
71
+ * @param {{ allowPrefixes?: string[] }} [opts] property families set at runtime, e.g. ["--color-"] for chart series
72
+ * @returns {{line: number, prop: string, text?: string}[]}
73
+ */
74
+ export function findUndeclared(src, declared, { allowPrefixes = [] } = {}) {
75
+ const raw = src.split("\n");
76
+ const findings = [];
77
+ stripComments(src)
78
+ .split("\n")
79
+ .forEach((line, i) => {
80
+ // group 2: `${` right after the name means var(--color-${key}), a name built at runtime.
81
+ for (const m of line.matchAll(/var\(\s*(--[A-Za-z0-9_-]+)(\$\{)?\s*(,)?/g)) {
82
+ if (m[3]) continue; // has a fallback: cannot render as nothing
83
+ if (m[2]) continue; // the name is built at runtime, so it cannot be checked statically
84
+ const name = m[1];
85
+ if (declared.has(name) || allowPrefixes.some((p) => name.startsWith(p))) continue;
86
+ const marker = [raw[i], raw[i - 1]].map((l) => (l ?? "").match(MARKER)).find(Boolean);
87
+ if (marker) {
88
+ if (marker[1].trim()) continue;
89
+ findings.push({ line: i + 1, prop: name, text: "css-var-ok marker needs a reason after the colon" });
90
+ continue;
91
+ }
92
+ findings.push({ line: i + 1, prop: name });
93
+ }
94
+ });
95
+ return findings;
96
+ }
97
+
98
+ function walk(dir, exts, out = []) {
99
+ let entries;
100
+ try {
101
+ entries = fs.readdirSync(dir, { withFileTypes: true });
102
+ } catch {
103
+ return out;
104
+ }
105
+ for (const e of entries) {
106
+ if (SKIP.has(e.name) || e.name.startsWith(".")) continue;
107
+ const p = path.join(dir, e.name);
108
+ if (e.isDirectory()) walk(p, exts, out);
109
+ else if (exts.test(e.name)) out.push(p);
110
+ }
111
+ return out;
112
+ }
113
+
114
+ if (isMain(import.meta.url)) {
115
+ const root = process.cwd();
116
+ const argv = process.argv.slice(2);
117
+ const cssArg = flagValue(argv, "css", null);
118
+ const cssDirs = (cssArg ? [cssArg] : ["out", ".next/static"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
119
+
120
+ if (!cssDirs.length) {
121
+ console.error("bads-lint-css-vars: no built CSS found (looked for out/ and .next/static).");
122
+ console.error(" This lint reads the BUILT stylesheet, because most custom properties are emitted at build time and appear in no file on disk.");
123
+ console.error(" Build first, or point at the output with --css <dir>. Failing rather than skipping on purpose.");
124
+ process.exit(1);
125
+ }
126
+
127
+ const declared = new Set();
128
+ let cssFiles = 0;
129
+ for (const d of cssDirs) {
130
+ for (const f of walkAll(d, /\.css$/)) {
131
+ cssFiles++;
132
+ for (const p of extractDeclared(fs.readFileSync(f, "utf8"))) declared.add(p);
133
+ }
134
+ }
135
+ if (declared.size === 0) {
136
+ console.error(`bads-lint-css-vars: parsed 0 custom properties from ${cssFiles} built CSS file(s). The build output moved or the parser drifted. Not reporting success on an empty read.`);
137
+ process.exit(1);
138
+ }
139
+
140
+ // Prefix values start with "--", so the generic flag parser would read the value as another flag.
141
+ const allowIdx = argv.findIndex((a) => a === "--allow" || a.startsWith("--allow="));
142
+ const allowArg = allowIdx < 0 ? "" : argv[allowIdx].includes("=") ? argv[allowIdx].slice(argv[allowIdx].indexOf("=") + 1) : (argv[allowIdx + 1] ?? "");
143
+ const allowPrefixes = [...RUNTIME_FAMILIES, ...allowArg.split(",").map((x) => x.trim()).filter(Boolean)];
144
+ const sourceRoots = argv.filter((a) => !a.startsWith("--") && a !== cssArg && a !== allowArg);
145
+ const files = (sourceRoots.length ? sourceRoots : SOURCE_ROOTS).map((r) => path.join(root, r)).filter((r) => fs.existsSync(r)).flatMap((r) => (fs.statSync(r).isDirectory() ? walk(r, SOURCE_EXT) : [r]));
146
+ const sources = files.map((f) => ({ f, src: fs.readFileSync(f, "utf8") }));
147
+ for (const { src } of sources) for (const p of extractDeclared(src)) declared.add(p);
148
+
149
+ const findings = [];
150
+ const scanned = [];
151
+ for (const { f, src } of sources) {
152
+ const rel = path.relative(root, f);
153
+ scanned.push(rel);
154
+ for (const u of findUndeclared(src, declared, { allowPrefixes })) findings.push({ file: rel, line: u.line, text: u.text ?? `${u.prop} is referenced but never declared` });
155
+ }
156
+
157
+ process.exit(
158
+ finishCountedLint({
159
+ ruleId: "undeclared-css-vars",
160
+ bin: "bads-lint-css-vars",
161
+ findings,
162
+ scanned,
163
+ fix: "Declare the property, switch to a utility class that exists, or give the reference a fallback: var(--radius-pill, 9999px). See layer-6-patterns-and-rules/declared-custom-properties.md.",
164
+ }),
165
+ );
166
+ }
167
+
168
+ function walkAll(dir, re, out = []) {
169
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
170
+ const p = path.join(dir, e.name);
171
+ if (e.isDirectory()) walkAll(p, re, out);
172
+ else if (re.test(e.name)) out.push(p);
173
+ }
174
+ return out;
175
+ }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-even-padding: padding is the same on all sides unless somebody chose otherwise.
4
+ *
5
+ * Enforces layer-6-patterns-and-rules/even-padding.md. `px-3 py-1` is 12px beside and 4px above, and
6
+ * nobody decided it: it is what comes of reaching for a horizontal value and a vertical value
7
+ * independently, and it reads as a squashed shape rather than a considered one.
8
+ *
9
+ * UNEVEN PADDING IS NOT BANNED, and a lint that banned it would be wrong. A full-width band whose
10
+ * horizontal inset is the page gutter and whose vertical inset is rhythm, a table row, a pill whose
11
+ * label needs room beside it that would look absurd above it: all honest. The requirement is that it
12
+ * was a DECISION, so mark it and say why, on the same line or the line above:
13
+ *
14
+ * {/* uneven-padding-ok: page gutter beside, rhythm above *\/}
15
+ *
16
+ * WHAT IT SEES. `px-*` paired with `py-*` on the same line, resolved through the spacing scale so
17
+ * `p-px` and `p-0.5` compare correctly. It does NOT see padding assembled by `cn()` across several
18
+ * lines, or `pt`/`pb`/`pl`/`pr` written out separately. Those are real gaps and this says so rather
19
+ * than implying full coverage.
20
+ *
21
+ * ADOPTION. Existing pairs are recorded with `--init` and ratcheted with `--ratchet`: a listed file may
22
+ * not get worse and no file may join the list.
23
+ *
24
+ * node packages/core/scripts/lint-even-padding.mjs [--warn | --init | --ratchet] [paths]
25
+ */
26
+ import { codeAndClasses } from "./lib/source-scan.mjs";
27
+ import { runLint, markedNear } from "./lib/lab-lint.mjs";
28
+ import { isMain } from "./lib/counted-lint.mjs";
29
+
30
+ /** Tailwind's spacing scale in CSS pixels. `--spacing` is 0.25rem, so step N is N * 4px. */
31
+ const px = (step) => (step === "px" ? 1 : parseFloat(step) * 4);
32
+
33
+ export function findUnevenPadding(src) {
34
+ const rawLines = src.split("\n");
35
+ const findings = [];
36
+ codeAndClasses(src)
37
+ .split("\n")
38
+ .forEach((line, i) => {
39
+ const x = line.match(/(?<![\w-])px-(\d+(?:\.\d+)?|px)(?![\w.-])/);
40
+ const y = line.match(/(?<![\w-])py-(\d+(?:\.\d+)?|px)(?![\w.-])/);
41
+ if (!x || !y || px(x[1]) === px(y[1])) return;
42
+ if (markedNear(rawLines, i + 1, "uneven-padding-ok:")) return;
43
+ findings.push({ line: i + 1, text: `px-${x[1]} py-${y[1]} (${px(x[1])}px beside, ${px(y[1])}px above)` });
44
+ });
45
+ return findings;
46
+ }
47
+
48
+ if (isMain(import.meta.url)) {
49
+ process.exit(
50
+ runLint({
51
+ ruleId: "even-padding",
52
+ bin: "bads-lint-even-padding",
53
+ tsxOnly: true,
54
+ detect: (src) => findUnevenPadding(src),
55
+ fix: "Use `p-N`, or keep the uneven pair and say why with `{/* uneven-padding-ok: <reason> */}` on the line above. See layer-6-patterns-and-rules/even-padding.md.",
56
+ }),
57
+ );
58
+ }
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lint-html-nesting — invalid HTML nesting in the built output.
4
+ *
5
+ * Enforces layer-6-patterns-and-rules/valid-html-nesting.md. `Separator` renders
6
+ * a <div>, so putting one inside a <p> is invalid HTML and throws React
7
+ * hydration error #418 in the browser, while `next build` reports success.
8
+ * Nothing in a component's documentation says what element it produces, so there
9
+ * is no way to know in advance, and the only signal is a console error someone
10
+ * has to be looking for. A passing build that emits a broken page is worse than
11
+ * a failing one, because people stop looking, so this reads the emitted HTML
12
+ * instead of trusting the build.
13
+ *
14
+ * It flags, per HTML file:
15
+ * <p> containing flow content (div, p, ul, ol, li, section, article, hr,
16
+ * table, h1-h6) a <p> may only hold phrasing content
17
+ * <button> inside <button> interactive content may not nest
18
+ * <a> inside <a> likewise
19
+ *
20
+ * <script> blocks are removed first: the framework payload is full of strings
21
+ * that look like markup.
22
+ *
23
+ * It fails rather than skips when there is no built HTML to read, because a
24
+ * check that quietly passes when it could not run is the anti-pattern it exists
25
+ * to catch. (Set BADS_ALLOW_MISSING_BUILD=1 to skip locally.)
26
+ *
27
+ * Run (after a build):
28
+ * npx bads-lint-html-nesting # looks for out/, then .next/server/app
29
+ * npx bads-lint-html-nesting --html dist # name the built HTML directory
30
+ * npx bads-lint-html-nesting --warn | --init | --ratchet
31
+ */
32
+
33
+ import fs from "node:fs";
34
+ import path from "node:path";
35
+ import { finishCountedLint, flagValue, isMain } from "./lib/counted-lint.mjs";
36
+
37
+ const FORBIDDEN_IN_P = ["div", "p", "ul", "ol", "li", "section", "article", "hr", "table", "h1", "h2", "h3", "h4", "h5", "h6"];
38
+
39
+ /**
40
+ * @param {string} html
41
+ * @returns {{tag: string, parent: string, snippet: string}[]}
42
+ */
43
+ export function findInvalidNesting(html) {
44
+ const doc = html.replace(/<script\b[\s\S]*?<\/script>/gi, "").replace(/<style\b[\s\S]*?<\/style>/gi, "");
45
+ const found = [];
46
+
47
+ // <p> cannot nest, so the span from an opening <p> to the next </p> is its content.
48
+ for (const m of doc.matchAll(/<p(\s[^>]*)?>/g)) {
49
+ const start = m.index + m[0].length;
50
+ const close = doc.indexOf("</p>", start);
51
+ if (close === -1) continue;
52
+ const inner = doc.slice(start, close);
53
+ const tag = FORBIDDEN_IN_P.find((t) => new RegExp(`<${t}(\\s|>|/)`, "i").test(inner));
54
+ if (tag) found.push({ tag, parent: "p", snippet: doc.slice(m.index, Math.min(close + 4, m.index + 150)).replace(/\s+/g, " ") });
55
+ }
56
+
57
+ for (const t of ["button", "a"]) {
58
+ for (const m of doc.matchAll(new RegExp(`<${t}(\\s[^>]*)?>`, "gi"))) {
59
+ const start = m.index + m[0].length;
60
+ const close = doc.indexOf(`</${t}>`, start);
61
+ if (close === -1) continue;
62
+ if (new RegExp(`<${t}(\\s|>)`, "i").test(doc.slice(start, close))) {
63
+ found.push({ tag: t, parent: t, snippet: doc.slice(m.index, Math.min(close + t.length + 3, m.index + 150)).replace(/\s+/g, " ") });
64
+ }
65
+ }
66
+ }
67
+ return found;
68
+ }
69
+
70
+ function walkHtml(dir, out = []) {
71
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
72
+ const p = path.join(dir, e.name);
73
+ if (e.isDirectory()) walkHtml(p, out);
74
+ else if (e.name.endsWith(".html")) out.push(p);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ if (isMain(import.meta.url)) {
80
+ const root = process.cwd();
81
+ const argv = process.argv.slice(2);
82
+ const htmlArg = flagValue(argv, "html", null);
83
+ const dirs = (htmlArg ? [htmlArg] : ["out", ".next/server/app"]).map((d) => path.join(root, d)).filter((d) => fs.existsSync(d));
84
+
85
+ if (!dirs.length) {
86
+ if (process.env.BADS_ALLOW_MISSING_BUILD && !process.env.CI) {
87
+ console.log("bads-lint-html-nesting: SKIPPED, no built HTML (BADS_ALLOW_MISSING_BUILD is set).");
88
+ process.exit(0);
89
+ }
90
+ console.error("bads-lint-html-nesting: no built HTML found (looked for out/ and .next/server/app).");
91
+ console.error(" This lint reads the HTML the build emitted. Build first, or point at it with --html <dir>.");
92
+ process.exit(1);
93
+ }
94
+
95
+ const findings = [];
96
+ const scanned = [];
97
+ for (const d of dirs) {
98
+ for (const f of walkHtml(d)) {
99
+ const rel = path.relative(root, f);
100
+ scanned.push(rel);
101
+ for (const n of findInvalidNesting(fs.readFileSync(f, "utf8"))) {
102
+ findings.push({ file: rel, text: `<${n.tag}> inside <${n.parent}>: ${n.snippet.slice(0, 110)}` });
103
+ }
104
+ }
105
+ }
106
+
107
+ process.exit(
108
+ finishCountedLint({
109
+ ruleId: "html-nesting",
110
+ bin: "bads-lint-html-nesting",
111
+ findings,
112
+ scanned,
113
+ fix: "Usually a component renders an element you did not expect (Separator renders a div). Check what it produces, and use a span, a wrapper outside the paragraph, or a different component. See layer-6-patterns-and-rules/valid-html-nesting.md.",
114
+ }),
115
+ );
116
+ }