@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,62 @@
1
+ /**
2
+ * lab-lint: the shared runner for the source-level design lints in this folder
3
+ * (even-padding, spacing-scale, proximity, content-hierarchy, control-baseline,
4
+ * label-case, copy-punctuation, arbitrary-tokens).
5
+ *
6
+ * Each lint supplies one pure function, `detect(src, rel) => [{ line, text }]`, and this
7
+ * module does the rest: discovers files through scan-roots (so a fork whose tree matches no
8
+ * default root gets an error, never a false "clean"), reads each file, and hands the findings
9
+ * to counted-lint for the strict / --warn / --init / --ratchet modes.
10
+ */
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ import { createRequire } from "node:module";
14
+ import { finishCountedLint } from "./counted-lint.mjs";
15
+
16
+ const require = createRequire(import.meta.url);
17
+ const { resolveScanFiles, guardEmptyScan } = require("./scan-roots.cjs");
18
+
19
+ /**
20
+ * An exemption marker with a reason, on the finding's line or the line above.
21
+ * Read from the RAW lines: the marker lives in a comment and the scan blanks those.
22
+ * A bare marker does not count; the reason is the mechanism, because writing it is what
23
+ * forces the author to name the decision.
24
+ */
25
+ export function markedNear(rawLines, line1, marker, { lines = 1 } = {}) {
26
+ const re = new RegExp(`${marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[^\\s*/]`);
27
+ for (let k = 0; k <= lines; k++) {
28
+ if (re.test(rawLines[line1 - 1 - k] ?? "")) return true;
29
+ }
30
+ return false;
31
+ }
32
+
33
+ /** 1-based line of `index` in `src`. */
34
+ export const lineAt = (src, index) => src.slice(0, index).split("\n").length;
35
+
36
+ /**
37
+ * @param {object} o
38
+ * @param {string} o.ruleId key in .bads-ratchet.json
39
+ * @param {string} o.bin name for messages
40
+ * @param {string} o.fix how to fix a finding
41
+ * @param {(src: string, rel: string) => {line: number, text: string}[]} o.detect
42
+ * @param {boolean} [o.tsxOnly] only .tsx files (JSX rules); default is .ts and .tsx
43
+ */
44
+ export function runLint({ ruleId, bin, fix, detect, tsxOnly = false, argv = process.argv.slice(2), root = process.cwd() }) {
45
+ const scan = resolveScanFiles({ root, argv, excludeStories: true, allowDirArgs: true });
46
+ guardEmptyScan(scan, bin);
47
+ const findings = [];
48
+ const scanned = [];
49
+ for (const abs of scan.files) {
50
+ if (tsxOnly ? !/\.tsx$/.test(abs) : !/\.tsx?$/.test(abs) || /\.d\.ts$/.test(abs)) continue;
51
+ let src;
52
+ try {
53
+ src = fs.readFileSync(abs, "utf8");
54
+ } catch {
55
+ continue;
56
+ }
57
+ const rel = path.relative(root, abs);
58
+ scanned.push(rel);
59
+ for (const f of detect(src, rel)) findings.push({ file: rel, ...f });
60
+ }
61
+ return finishCountedLint({ ruleId, bin, findings, scanned, fix, argv, root });
62
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The marketing composition library (disciplines/marketing/library/): 20 directions,
3
+ * 48 heroes and 172 sections, derived from taste-skill (MIT; see that folder's
4
+ * NOTICE.md). This module loads it, deals directions, and builds the direction sheet.
5
+ * Pure except for loadLibrary(), which reads the three JSON files.
6
+ *
7
+ * Dealing, not choosing: a model asked to invent a look returns the category default.
8
+ * Three dealt directions make the choice a real one. A sheet then deals a hero and a
9
+ * section per role from the chosen direction's own pool, so the page is composed from
10
+ * parts drawn for each other.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { shuffle } from "./random.mjs";
15
+
16
+ export const LIB_DIR = "disciplines/marketing/library";
17
+
18
+ /** Load the library from a repo root, or null when it isn't there (a fork may delete it). */
19
+ export function loadLibrary(root) {
20
+ const read = (f) => JSON.parse(fs.readFileSync(path.join(root, LIB_DIR, f), "utf8"));
21
+ try { return { directions: read("directions.json"), heroes: read("heroes.json"), sections: read("sections.json") }; } catch { return null; }
22
+ }
23
+
24
+ const uniq = (a) => [...new Set(a.flat())].sort();
25
+ export function vocab(lib) {
26
+ return { sectors: uniq(lib.directions.map((d) => d.sectors)), tones: uniq(lib.directions.map((d) => d.tones)), roles: uniq(lib.sections.map((s) => s.role)) };
27
+ }
28
+
29
+ /**
30
+ * Whether an entry's asset needs are met. Pictures of the client's world ("photography") are
31
+ * assumed findable with bads-source-images. A software product can show a real interface built
32
+ * from its own components, so "product-ui" is met when `software` is set. "product-photo" must
33
+ * be listed in `have`.
34
+ */
35
+ export function feasible(entry, { have = [], software = false } = {}) {
36
+ return (entry.needs || []).every((n) => n === "photography" || have.includes(n) || (n === "product-ui" && software));
37
+ }
38
+
39
+ const trim = (s, n) => { const t = String(s || "").replace(/\s+/g, " ").trim(); return t.length <= n ? t : t.slice(0, t.lastIndexOf(" ", n - 1)) + "…"; };
40
+
41
+ /** Deal `count` directions that fit the sector and tone, skipping the fork's recent ones. */
42
+ export function dealDirections(lib, { sector, tone, have = [], software = false, exclude = [], count = 3, random = Math.random } = {}) {
43
+ const skip = new Set(exclude);
44
+ const ok = (d) => feasible(d, { have, software });
45
+ const base = lib.directions.filter(ok);
46
+ const tiers = [
47
+ (d) => (!sector || d.sectors.includes(sector)) && (!tone || d.tones.includes(tone)),
48
+ (d) => !sector || d.sectors.includes(sector),
49
+ () => true,
50
+ ];
51
+ const notes = [];
52
+ let pool = [];
53
+ for (const [i, fits] of tiers.entries()) {
54
+ pool = base.filter((d) => fits(d) && !skip.has(d.id));
55
+ if (pool.length >= count) { if (i === 1) notes.push(`Fewer than ${count} directions fit both the sector and the tone, so the tone was relaxed.`); if (i === 2) notes.push(`Fewer than ${count} directions fit the sector, so the whole library was used.`); break; }
56
+ }
57
+ if (pool.length < count) { pool = base; notes.push("The recent-direction exclusions left too few, so a recent direction may appear. Say why in the sketch."); }
58
+ return { directions: shuffle(pool, random).slice(0, count), notes, skipped: exclude.filter((id) => lib.directions.some((d) => d.id === id)) };
59
+ }
60
+
61
+ /** Deal one hero and one section per role for a chosen direction. */
62
+ export function dealSheet(lib, { direction, roles, have = [], software = false, random = Math.random }) {
63
+ const dir = lib.directions.find((d) => d.id === direction);
64
+ if (!dir) throw new Error(`no direction "${direction}". List them with --list directions.`);
65
+ const opts = { have, software };
66
+ const heroes = lib.heroes.filter((h) => h.directions.includes(dir.id) && feasible(h, opts));
67
+ const notes = [];
68
+ if (!heroes.length) throw new Error(`no hero for "${dir.id}" fits the assets you have. Pass --have, or --software for a software product.`);
69
+ const hero = shuffle(heroes, random)[0];
70
+ const used = new Set([hero.archetype]);
71
+ const sections = roles.map((role) => {
72
+ let pool = lib.sections.filter((s) => s.role === role && s.directions.includes(dir.id) && feasible(s, opts));
73
+ let drawnFor = true;
74
+ if (!pool.length) { pool = lib.sections.filter((s) => s.role === role && feasible(s, opts)); drawnFor = false; }
75
+ if (!pool.length) { notes.push(`No section for the role "${role}" fits the assets you have.`); return { role, section: null, drawnFor }; }
76
+ // Prefer a shape not yet used, so the page doesn't repeat one composition.
77
+ const fresh = pool.filter((s) => !used.has(s.shape));
78
+ const pick = shuffle(fresh.length ? fresh : pool, random)[0];
79
+ used.add(pick.shape);
80
+ if (!drawnFor) notes.push(`No "${role}" section is drawn for ${dir.id}; this one comes from the wider library.`);
81
+ return { role, section: pick, drawnFor };
82
+ });
83
+ return { direction: dir, hero, sections, notes };
84
+ }
85
+
86
+ /** The sections available for one role under a direction, for swapping a section that can't hold the real content. */
87
+ export function alternatives(lib, { direction, role, have = [], software = false }) {
88
+ return lib.sections.filter((s) => s.role === role && s.directions.includes(direction) && feasible(s, { have, software }));
89
+ }
90
+
91
+ export function formatDirections(result, { sector, tone } = {}) {
92
+ const L = [];
93
+ L.push(`Dealt ${result.directions.length} directions${sector || tone ? ` for ${[sector, tone].filter(Boolean).join(", ")}` : ""}.`);
94
+ L.push(result.skipped.length ? `Skipped this fork's recent: ${result.skipped.join(", ")}.` : "No library direction recorded in ledgers/prototypes.jsonl (libraryDirection), so nothing is skipped.");
95
+ for (const n of result.notes) L.push(n);
96
+ L.push("");
97
+ result.directions.forEach((d, i) => {
98
+ L.push(`${i + 1}. ${d.name} [${d.id}]`);
99
+ L.push(` ${trim(d.idea, 360)}`);
100
+ L.push(` Tones: ${d.tones.join(", ")}.${d.needs.length ? ` Needs: ${d.needs.join(", ")}.` : ""}${d.needsPictures ? " Many pictures: find real ones with bads-source-images." : ""}`);
101
+ L.push(` Watch out: ${trim(d.pitfalls, 220)}`);
102
+ L.push("");
103
+ });
104
+ L.push("Hold each against the subject inventory (prompts/subject-inventory.md): which can carry something only this client has? Choose one and write why in one line. Then deal its sheet:");
105
+ L.push(" bads-deal-directions --surface marketing --direction <id> --sections <roles in the order of your argument>");
106
+ return L.join("\n");
107
+ }
108
+
109
+ export function formatSheet(s) {
110
+ const L = [];
111
+ const { direction: d, hero } = s;
112
+ L.push(`DIRECTION SHEET: ${d.name} [${d.id}]`, "");
113
+ L.push("Brand tokens decide colors and fonts. The fields below give proportions and treatment, not values. Adopt the sheet; don't blend it with the layout you would have made anyway. Redraw a slot only for a reason you can state, such as a brand constraint, and record the redraw.", "");
114
+ L.push("THE IDEA", d.idea, "");
115
+ L.push("COMPOSITION", d.composition, "");
116
+ L.push("TYPE TREATMENT", d.typography, "");
117
+ L.push("COLOUR PROPORTIONS", d.colour, "");
118
+ L.push("IMAGERY", d.imagery, "");
119
+ L.push("WHAT MAKES IT RICH", d.richness, "");
120
+ L.push("PITFALLS", d.pitfalls, "");
121
+ L.push(`HERO: ${hero.name} [${hero.id}] (${hero.archetype})`, hero.blueprint, `Mobile: ${hero.mobile}`, `Headline: ${hero.headline}`, "");
122
+ for (const { role, section } of s.sections) {
123
+ if (!section) { L.push(`SECTION ${role.toUpperCase()}: none available`, ""); continue; }
124
+ L.push(`SECTION ${role.toUpperCase()}: ${section.name} [${section.id}] (${section.shape})`, section.blueprint, `Mobile: ${section.mobile}`, "");
125
+ }
126
+ for (const n of s.notes) L.push(`Note: ${n}`);
127
+ L.push("Next: record the direction id as libraryDirection on the prototype's ledger row. Source the pictures (bads-source-images), build, then run bads-ux-tells on the result.");
128
+ return L.join("\n");
129
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Mounts everything a page defers, before a rendered check measures it. Shared by the rendered checks @core ships.
3
+ *
4
+ * A showcase that defers its blocks until they near the viewport keeps first paint fast, and is a trap for a check: a
5
+ * measure taken on load sees only the opening screen and reports the rest as clean because it was never drawn. So the
6
+ * page is scrolled to the bottom until its height holds still for several reads in a row (lazy blocks mount in waves,
7
+ * and the page plateaus between them, so one repeat is not enough), then back to the top.
8
+ *
9
+ * Returns the number of `lazySelector` placeholders still on the page afterwards. A caller treats more than zero as a
10
+ * failure of the run: silence from a block that never mounted is not a pass.
11
+ */
12
+ export async function mountEverything(page, { lazySelector = "[data-lazy-skeleton]", maxSteps = 120, stableReads = 4, stepMs = 250 } = {}) {
13
+ let lastHeight = -1;
14
+ let stable = 0;
15
+ for (let i = 0; i < maxSteps && stable < stableReads; i += 1) {
16
+ await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
17
+ await page.waitForTimeout(stepMs);
18
+ const h = await page.evaluate(() => document.body.scrollHeight);
19
+ stable = h === lastHeight ? stable + 1 : 0;
20
+ lastHeight = h;
21
+ }
22
+ await page.evaluate(() => window.scrollTo(0, 0));
23
+ await page.waitForTimeout(600);
24
+ return lazySelector ? page.evaluate((sel) => document.querySelectorAll(sel).length, lazySelector) : 0;
25
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * on-system: classify every styling decision in a source file as on the design system or off it.
3
+ *
4
+ * A design system video called this an "on system %" for a screen: what share of what got styled uses the
5
+ * system's tokens, and what is rogue type, off-scale spacing or a stray color. This is the same idea for code,
6
+ * as a deterministic count, not a judgment.
7
+ *
8
+ * WHAT COUNTS. Five categories: color, spacing, type, radius, shadow. A Tailwind utility is one decision.
9
+ * - ON: a semantic color (bg-primary, text-muted-foreground), a step on the spacing scale (p-4, gap-6), a named
10
+ * type size or weight (text-sm, font-medium), a named radius or shadow, or any arbitrary value that points
11
+ * at a token (bg-[var(--brand)], p-[var(--gutter)]).
12
+ * - OFF: a raw palette color (bg-blue-500, text-white), a literal color (bg-[#fff]), an arbitrary length
13
+ * (p-[13px], text-[15px], rounded-[7px]), an off-scale step (p-13), a literal shadow (shadow-[0_2px_...]),
14
+ * and a hex color written straight into code.
15
+ * Utilities that are not a styling choice against the system (flex, w-full, grid-cols-3, text-center) are not counted.
16
+ *
17
+ * LIMITS, said plainly. It reads class strings, not rendered CSS: a class built at runtime ("p-" + n) is invisible,
18
+ * and prose that happens to contain "gap-4" would count. It reads the source, not what the browser shows, so it
19
+ * cannot see a component that is on-system by itself and wrong in context. Treat the score as a trend and a pointer
20
+ * to the files worth opening, never as a verdict. Escape hatch: `allow-off-system: <reason>` on the line, or the
21
+ * line above, stops that line's off-system tokens from counting.
22
+ */
23
+
24
+ export const CATEGORIES = ["color", "spacing", "type", "radius", "shadow"];
25
+
26
+ const PALETTE = "slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose";
27
+ const PALETTE_RE = new RegExp(`^(?:${PALETTE})-\\d{2,3}$`);
28
+ const COLOR_LITERAL = /^(?:#[0-9a-fA-F]{3,8}|(?:rgb|rgba|hsl|hsla|oklch|oklab|lab|lch|color)\()/;
29
+ const LENGTH_LITERAL = /^-?\d*\.?\d+(?:px|rem|em|%|vh|vw|dvh|svh|ch|pt)$/;
30
+
31
+ const SPACING_STEPS = new Set(
32
+ ["0", "px", "0.5", "1", "1.5", "2", "2.5", "3", "3.5", "4", "5", "6", "7", "8", "9", "10", "11", "12", "14", "16", "20", "24", "28", "32", "36", "40", "44", "48", "52", "56", "60", "64", "72", "80", "96"],
33
+ );
34
+ const SPACING_PREFIXES = new Set(["p", "px", "py", "pt", "pr", "pb", "pl", "ps", "pe", "m", "mx", "my", "mt", "mr", "mb", "ml", "ms", "me", "gap", "gap-x", "gap-y", "space-x", "space-y"]);
35
+ const POSITION_PREFIXES = new Set(["inset", "inset-x", "inset-y", "top", "right", "bottom", "left", "start", "end"]);
36
+
37
+ const TEXT_SIZES = /^(?:xs|sm|base|lg|xl|[2-9]xl)$/;
38
+ const TEXT_NOT_COLOR = /^(?:left|center|right|justify|start|end|wrap|nowrap|balance|pretty|ellipsis|clip|xs|sm|base|lg|xl|[2-9]xl)$/;
39
+ const WEIGHTS = /^(?:thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/;
40
+ const FONT_FAMILIES = /^(?:sans|serif|mono)$/;
41
+
42
+ const COLOR_PREFIXES = new Set(["bg", "text", "border", "ring", "outline", "fill", "stroke", "divide", "from", "via", "to", "accent", "caret", "decoration", "placeholder"]);
43
+ const NEUTRAL_COLOR_VALUES = /^(?:transparent|current|inherit|none|auto)$/;
44
+ const NOT_A_COLOR = {
45
+ bg: /^(?:cover|contain|center|no-repeat|repeat(?:-[xy]|-round|-space)?|fixed|local|scroll|none|top|bottom|left|right|auto|clip-.+|origin-.+|blend-.+|linear-.+|radial-.+|conic-.+|gradient-.+|size-.+|position-.+|\[(?:url|image|length|position|size).*\])$/,
46
+ border: /^(?:[trblxyse]|[trblxyse]-\d+|\d+|0|px|solid|dashed|dotted|double|hidden|none|collapse|separate|spacing.*)$/,
47
+ divide: /^(?:[xy]|[xy]-\d+|[xy]-reverse|solid|dashed|dotted|double|none)$/,
48
+ ring: /^(?:\d+|0|inset|offset-.+)$/,
49
+ outline: /^(?:\d+|0|none|dashed|dotted|double|hidden|offset-.+)$/,
50
+ stroke: /^(?:\d+|0|none)$/,
51
+ fill: /^(?:none)$/,
52
+ };
53
+
54
+ /** Splits "md:hover:-translate-x-1" style variants off. Returns { utility, important }. */
55
+ function stripVariants(token) {
56
+ let depth = 0;
57
+ let cut = -1;
58
+ for (let i = 0; i < token.length; i++) {
59
+ const c = token[i];
60
+ if (c === "[" || c === "(") depth++;
61
+ else if (c === "]" || c === ")") depth--;
62
+ else if (c === ":" && depth === 0) cut = i;
63
+ }
64
+ let utility = cut === -1 ? token : token.slice(cut + 1);
65
+ if (utility.startsWith("!")) utility = utility.slice(1);
66
+ return utility;
67
+ }
68
+
69
+ /** Splits "p-4" into { prefix: "p", value: "4" }, preferring the longest known prefix. */
70
+ function splitUtility(utility) {
71
+ const u = utility.startsWith("-") ? utility.slice(1) : utility;
72
+ const all = [...SPACING_PREFIXES, ...POSITION_PREFIXES, ...COLOR_PREFIXES, "rounded", "shadow", "text", "font", "leading", "tracking"]
73
+ .sort((a, b) => b.length - a.length);
74
+ for (const prefix of all) {
75
+ if (u === prefix) return { prefix, value: "" };
76
+ if (u.startsWith(prefix + "-")) return { prefix, value: u.slice(prefix.length + 1) };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ const refsToken = (arbitrary) => /^\[.*var\(--/.test(arbitrary) || /^\(--/.test(arbitrary);
82
+ const inner = (arbitrary) => arbitrary.replace(/^\[/, "").replace(/\]$/, "");
83
+
84
+ /**
85
+ * Classify one class token. Returns { category, on } or null when it is not a styling decision against the system.
86
+ */
87
+ export function classifyToken(rawToken) {
88
+ const utility = stripVariants(rawToken.trim());
89
+ if (!utility) return null;
90
+ const parts = splitUtility(utility);
91
+ if (!parts) return null;
92
+ const { prefix } = parts;
93
+ let { value } = parts;
94
+ const arbitrary = value.startsWith("[") || value.startsWith("(");
95
+
96
+ // ---- radius, shadow --------------------------------------------------------------------------------------------
97
+ if (prefix === "rounded") {
98
+ const side = value.replace(/^(?:t|r|b|l|s|e|tl|tr|bl|br|ss|se|ee|es)(?:-|$)/, "");
99
+ if (side === "" || /^(?:none|xs|sm|md|lg|xl|[2-4]xl|full)$/.test(side)) return { category: "radius", on: true };
100
+ if (side.startsWith("[") || side.startsWith("(")) return { category: "radius", on: refsToken(side) };
101
+ return { category: "radius", on: false };
102
+ }
103
+ if (prefix === "shadow") {
104
+ if (value === "" || /^(?:2xs|xs|sm|md|lg|xl|2xl|inner|none)$/.test(value)) return { category: "shadow", on: true };
105
+ if (arbitrary) {
106
+ // shadow-[#fff] is a shadow COLOR; shadow-[0_2px_4px_...] is a literal shadow; shadow-[var(--x)] is a token.
107
+ return { category: COLOR_LITERAL.test(inner(value)) ? "color" : "shadow", on: refsToken(value) };
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // ---- type ------------------------------------------------------------------------------------------------------
113
+ if (prefix === "font") {
114
+ if (WEIGHTS.test(value) || FONT_FAMILIES.test(value)) return { category: "type", on: true };
115
+ if (arbitrary) return { category: "type", on: refsToken(value) };
116
+ return null;
117
+ }
118
+ if (prefix === "leading") {
119
+ if (/^(?:none|tight|snug|normal|relaxed|loose|\d+)$/.test(value)) return { category: "type", on: true };
120
+ if (arbitrary) return { category: "type", on: refsToken(value) };
121
+ return null;
122
+ }
123
+ if (prefix === "tracking") {
124
+ if (/^(?:tighter|tight|normal|wide|wider|widest)$/.test(value)) return { category: "type", on: true };
125
+ if (arbitrary) return { category: "type", on: refsToken(value) };
126
+ return null;
127
+ }
128
+ if (prefix === "text") {
129
+ if (TEXT_SIZES.test(value)) return { category: "type", on: true };
130
+ if (arbitrary) {
131
+ const body = inner(value.replace(/^\(/, "[").replace(/\)$/, "]"));
132
+ if (COLOR_LITERAL.test(body)) return { category: "color", on: false };
133
+ if (LENGTH_LITERAL.test(body)) return { category: "type", on: false };
134
+ return { category: LENGTH_LITERAL.test(body) ? "type" : "color", on: refsToken(value) };
135
+ }
136
+ if (TEXT_NOT_COLOR.test(value)) return null;
137
+ // fall through to color
138
+ }
139
+
140
+ // ---- spacing ---------------------------------------------------------------------------------------------------
141
+ if (SPACING_PREFIXES.has(prefix) || POSITION_PREFIXES.has(prefix)) {
142
+ const positional = POSITION_PREFIXES.has(prefix);
143
+ if (arbitrary) {
144
+ const body = inner(value);
145
+ if (refsToken(value)) return { category: "spacing", on: true };
146
+ if (LENGTH_LITERAL.test(body)) return { category: "spacing", on: false };
147
+ return null; // calc(), percentages of something else: not decidable here
148
+ }
149
+ if (SPACING_STEPS.has(value)) return { category: "spacing", on: true };
150
+ if (/^\d+(?:\.\d+)?$/.test(value)) return positional ? null : { category: "spacing", on: false };
151
+ return null; // auto, full, fractions, screen
152
+ }
153
+
154
+ // ---- color -----------------------------------------------------------------------------------------------------
155
+ if (COLOR_PREFIXES.has(prefix)) {
156
+ const notColor = NOT_A_COLOR[prefix];
157
+ if (notColor && notColor.test(value)) return null;
158
+ const color = value.replace(/\/(?:\d+|\[[^\]]+\])$/, ""); // drop an opacity modifier
159
+ if (color === "" || NEUTRAL_COLOR_VALUES.test(color)) return null;
160
+ if (color.startsWith("[") || color.startsWith("(")) {
161
+ if (COLOR_LITERAL.test(inner(color))) return { category: "color", on: false };
162
+ if (refsToken(color)) return { category: "color", on: true };
163
+ return null;
164
+ }
165
+ if (PALETTE_RE.test(color) || color === "white" || color === "black") return { category: "color", on: false };
166
+ if (/^[a-z][a-z0-9-]*$/.test(color)) return { category: "color", on: true };
167
+ }
168
+ return null;
169
+ }
170
+
171
+ const STRING_LITERAL = /(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/g;
172
+ const HEX_IN_CODE = /(?<![\w&])#(?:[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?|[0-9a-fA-F]{3})(?![\w-])/g;
173
+
174
+ const emptyCounts = () => Object.fromEntries(CATEGORIES.map((c) => [c, { on: 0, off: 0 }]));
175
+
176
+ /**
177
+ * Score one source file. Returns the counts per category and the off-system decisions with their line numbers.
178
+ */
179
+ export function scoreSource(source) {
180
+ const counts = emptyCounts();
181
+ const offenders = [];
182
+ const lines = source.split("\n");
183
+ const lineStart = [];
184
+ let pos = 0;
185
+ for (const l of lines) {
186
+ lineStart.push(pos);
187
+ pos += l.length + 1;
188
+ }
189
+ const lineOf = (index) => {
190
+ let lo = 0;
191
+ let hi = lineStart.length - 1;
192
+ while (lo < hi) {
193
+ const mid = Math.ceil((lo + hi) / 2);
194
+ if (lineStart[mid] <= index) lo = mid;
195
+ else hi = mid - 1;
196
+ }
197
+ return lo + 1;
198
+ };
199
+ const allowed = (line) => /allow-off-system/.test(lines[line - 1] ?? "") || /allow-off-system/.test(lines[line - 2] ?? "");
200
+ const record = (category, on, line, what) => {
201
+ if (on) counts[category].on++;
202
+ else if (!allowed(line)) {
203
+ counts[category].off++;
204
+ offenders.push({ category, line, what });
205
+ }
206
+ };
207
+
208
+ // Hex colors written straight into code or a style object (outside class strings handled below).
209
+ for (const m of source.matchAll(HEX_IN_CODE)) {
210
+ const line = lineOf(m.index);
211
+ const text = lines[line - 1] ?? "";
212
+ if (/^\s*(?:\/\/|\*|\/\*)/.test(text) || /\b(?:href|id|src)=/.test(text) || /\[#[0-9a-fA-F]+\]/.test(text)) continue;
213
+ record("color", false, line, m[0]);
214
+ }
215
+
216
+ for (const m of source.matchAll(STRING_LITERAL)) {
217
+ const body = m[2].replace(/\$\{[^}]*\}/g, " ");
218
+ if (!/\s|-/.test(body) && body.length < 3) continue;
219
+ let offset = 0;
220
+ for (const token of body.split(/(\s+)/)) {
221
+ if (token.trim()) {
222
+ const c = classifyToken(token);
223
+ if (c) record(c.category, c.on, lineOf(m.index + 1 + offset), token);
224
+ }
225
+ offset += token.length;
226
+ }
227
+ }
228
+ return { counts, offenders };
229
+ }
230
+
231
+ /** Add `b`'s counts into `a`. */
232
+ export function addCounts(a, b) {
233
+ for (const c of CATEGORIES) {
234
+ a[c].on += b[c].on;
235
+ a[c].off += b[c].off;
236
+ }
237
+ return a;
238
+ }
239
+
240
+ /** Percentage on-system for a { on, off } pair, or null when nothing in that category was decided. */
241
+ export function percent({ on, off }) {
242
+ const total = on + off;
243
+ return total === 0 ? null : Math.round((on / total) * 1000) / 10;
244
+ }
245
+
246
+ export function overall(counts) {
247
+ const t = CATEGORIES.reduce((s, c) => ({ on: s.on + counts[c].on, off: s.off + counts[c].off }), { on: 0, off: 0 });
248
+ return { ...t, percent: percent(t) };
249
+ }
@@ -0,0 +1,22 @@
1
+ /** Seeded randomness for dealing, so a deal can be repeated. A small PRNG (mulberry32). */
2
+ export function rng(seed) {
3
+ let a = seed >>> 0;
4
+ return () => {
5
+ a = (a + 0x6d2b79f5) >>> 0;
6
+ let t = a;
7
+ t = Math.imul(t ^ (t >>> 15), t | 1);
8
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
9
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
10
+ };
11
+ }
12
+
13
+ /** Shuffle a copy with the given random source. */
14
+ export function shuffle(list, random) {
15
+ const a = [...list];
16
+ for (let i = a.length - 1; i > 0; i--) {
17
+ const j = Math.floor(random() * (i + 1));
18
+ [a[i], a[j]] = [a[j], a[i]];
19
+ }
20
+ return a;
21
+ }
22
+
@@ -0,0 +1,173 @@
1
+ /**
2
+ * source-scan: one source scanner, shared by every line-wise lint that reads class names or copy.
3
+ *
4
+ * WHY THIS EXISTS. A regex over source text will eventually read something that is not code. Blanking
5
+ * comments is the easy half and not enough: the failure that actually recurs is deciding a match is code
6
+ * without knowing whether the cursor is inside a STRING. A lint hunting `px-4 py-6` must not fail over a
7
+ * sentence in a description that quotes `px-4 py-6` to explain a rule; a lint hunting import specifiers
8
+ * must not read the word "from" inside prose.
9
+ *
10
+ * It cannot simply blank every string, because the thing most lints look for lives inside one: Tailwind
11
+ * classes are string content (`className="px-4 py-6"`, `cn("flex", open && "p-4")`). So the useful
12
+ * question is "is this inside a string that holds CLASSES". `codeAndClasses` answers it: comments out,
13
+ * class-bearing strings kept, every other string blanked.
14
+ *
15
+ * Line numbers and column offsets are preserved exactly (everything blanked is replaced space-for-space),
16
+ * so a caller reports positions against the real file and can still read the RAW line to find an `*-ok:`
17
+ * exemption marker, which lives in a comment and would otherwise be blanked away.
18
+ */
19
+
20
+ /** Class-bearing contexts. A string inside one of these is kept. */
21
+ const CLASS_ATTR = /(?:^|[^\w$])(?:className|class)\s*=\s*$/;
22
+ const CLASS_CALL = /(?:^|[^\w$])(?:cn|clsx|cva|twMerge|classNames)\s*\($/;
23
+
24
+ /** Replace every character except newlines, so positions do not move. */
25
+ const blank = (s) => s.replace(/[^\n]/g, " ");
26
+
27
+ /**
28
+ * Blank comments only. Exported because a few checks genuinely want string
29
+ * content regardless of context, and because it makes the difference between
30
+ * the two passes explicit at the call site rather than implied.
31
+ */
32
+ export function withoutComments(src) {
33
+ let out = "";
34
+ let i = 0;
35
+ while (i < src.length) {
36
+ const c = src[i];
37
+ const n = src[i + 1];
38
+ if (c === "/" && n === "*") {
39
+ const end = src.indexOf("*/", i + 2);
40
+ const stop = end < 0 ? src.length : end + 2;
41
+ out += blank(src.slice(i, stop));
42
+ i = stop;
43
+ continue;
44
+ }
45
+ if (c === "/" && n === "/") {
46
+ const end = src.indexOf("\n", i);
47
+ const stop = end < 0 ? src.length : end;
48
+ out += blank(src.slice(i, stop));
49
+ i = stop;
50
+ continue;
51
+ }
52
+ if (c === '"' || c === "'" || c === "`") {
53
+ const stop = endOfString(src, i);
54
+ out += src.slice(i, stop);
55
+ i = stop;
56
+ continue;
57
+ }
58
+ out += c;
59
+ i++;
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /** Index just past the string literal that starts at `start`. */
65
+ function endOfString(src, start) {
66
+ const quote = src[start];
67
+ let i = start + 1;
68
+ while (i < src.length) {
69
+ const c = src[i];
70
+ if (c === "\\") {
71
+ i += 2;
72
+ continue;
73
+ }
74
+ if (quote === "`" && c === "$" && src[i + 1] === "{") {
75
+ // Skip a ${ ... } interpolation, braces balanced.
76
+ let depth = 1;
77
+ i += 2;
78
+ while (i < src.length && depth > 0) {
79
+ if (src[i] === "{") depth++;
80
+ else if (src[i] === "}") depth--;
81
+ else if (src[i] === '"' || src[i] === "'" || src[i] === "`") {
82
+ i = endOfString(src, i);
83
+ continue;
84
+ }
85
+ i++;
86
+ }
87
+ continue;
88
+ }
89
+ if (c === quote) return i + 1;
90
+ i++;
91
+ }
92
+ return src.length;
93
+ }
94
+
95
+ /**
96
+ * Comments blanked, and every string blanked EXCEPT those holding classes.
97
+ *
98
+ * A string counts as class-bearing when it is the value of a `className` /
99
+ * `class` attribute, or an argument to `cn` / `clsx` / `cva` / `twMerge` /
100
+ * `classNames`, or sits anywhere inside such an attribute's `{ ... }`
101
+ * expression — which covers the ternaries and `&&` chains codebases write
102
+ * constantly:
103
+ *
104
+ * className={cn("grid", wide && "px-4 py-6", open ? "p-2" : "p-4")}
105
+ *
106
+ * Everything else — a description, a blurb, a note, a piece of copy that quotes
107
+ * a class name in order to talk about it — is blanked.
108
+ */
109
+ export function codeAndClasses(src) {
110
+ const stripped = withoutComments(src);
111
+ const out = [];
112
+ let i = 0;
113
+ /** Stack of open brackets; entries flagged true are class context. */
114
+ const stack = [];
115
+ let classDepth = 0;
116
+
117
+ /*
118
+ * A short trailing window of the code emitted so far, NOT the whole output.
119
+ *
120
+ * The first version of this tested `out.replace(/\s+$/, "")` at every bracket
121
+ * and every string. `out` grows to the length of the file, so that is a
122
+ * fresh full-length regex over the whole accumulated source per token —
123
+ * quadratic, and on a file thousands of
124
+ * lines long it ran for minutes and looked like a hang. The lookbehind patterns
125
+ * only ever need the last few dozen characters, so keep exactly that.
126
+ */
127
+ let tail = "";
128
+ const TAIL = 64;
129
+ const pushTail = (text) => {
130
+ tail = (tail + text).slice(-TAIL);
131
+ };
132
+ const before = () => tail.replace(/\s+$/, "");
133
+
134
+ while (i < stripped.length) {
135
+ const c = stripped[i];
136
+
137
+ if (c === '"' || c === "'" || c === "`") {
138
+ const stop = endOfString(stripped, i);
139
+ const raw = stripped.slice(i, stop);
140
+ const keep =
141
+ classDepth > 0 || CLASS_ATTR.test(before()) || CLASS_CALL.test(before());
142
+ out.push(keep ? raw : blank(raw));
143
+ pushTail(keep ? raw : " ");
144
+ i = stop;
145
+ continue;
146
+ }
147
+
148
+ if (c === "{" || c === "(" || c === "[") {
149
+ const b = before();
150
+ const isClass =
151
+ c === "(" ? CLASS_CALL.test(b + "(") : CLASS_ATTR.test(b);
152
+ stack.push(isClass);
153
+ if (isClass) classDepth++;
154
+ out.push(c);
155
+ pushTail(c);
156
+ i++;
157
+ continue;
158
+ }
159
+
160
+ if (c === "}" || c === ")" || c === "]") {
161
+ if (stack.pop()) classDepth--;
162
+ out.push(c);
163
+ pushTail(c);
164
+ i++;
165
+ continue;
166
+ }
167
+
168
+ out.push(c);
169
+ pushTail(c);
170
+ i++;
171
+ }
172
+ return out.join("");
173
+ }