banhaten 0.3.0 → 0.5.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 (348) hide show
  1. package/CHANGELOG.md +139 -73
  2. package/CONTRIBUTING.md +46 -44
  3. package/README.md +192 -190
  4. package/SECURITY.md +15 -15
  5. package/banhaten.config.example.json +11 -11
  6. package/docs/design-spacing.md +13 -0
  7. package/docs/design-system/README.md +22 -20
  8. package/docs/design-system/adoption-quality-remediation.md +87 -87
  9. package/docs/design-system/agent-usage.md +13 -13
  10. package/docs/design-system/appearance-presets.md +189 -189
  11. package/docs/design-system/appearances/default.md +94 -94
  12. package/docs/design-system/appearances/rounded.md +95 -95
  13. package/docs/design-system/appearances/sharp.md +95 -95
  14. package/docs/design-system/component-docs-pattern.md +81 -81
  15. package/docs/design-system/component-implementation-ownership-audit.md +245 -244
  16. package/docs/design-system/component-quality-audit-2026-08-20.md +225 -223
  17. package/docs/design-system/component-showcase-consistency-report.md +219 -219
  18. package/docs/design-system/component-token-consistency-audit.md +173 -173
  19. package/docs/design-system/components/README.md +90 -76
  20. package/docs/design-system/components/accordion.md +53 -53
  21. package/docs/design-system/components/activity-feed.md +94 -94
  22. package/docs/design-system/components/activity-heatmap.md +57 -57
  23. package/docs/design-system/components/agent-input.md +85 -0
  24. package/docs/design-system/components/alert-dialog.md +72 -72
  25. package/docs/design-system/components/alert.md +98 -98
  26. package/docs/design-system/components/approval-card.md +134 -0
  27. package/docs/design-system/components/aspect-ratio.md +45 -45
  28. package/docs/design-system/components/attribute.md +89 -89
  29. package/docs/design-system/components/autocomplete.md +75 -75
  30. package/docs/design-system/components/avatar.md +54 -54
  31. package/docs/design-system/components/badge.md +54 -54
  32. package/docs/design-system/components/banner.md +87 -87
  33. package/docs/design-system/components/breadcrumbs.md +177 -176
  34. package/docs/design-system/components/button-group.md +98 -98
  35. package/docs/design-system/components/button.md +83 -80
  36. package/docs/design-system/components/card.md +88 -88
  37. package/docs/design-system/components/carousel.md +46 -46
  38. package/docs/design-system/components/catalog-components.md +47 -47
  39. package/docs/design-system/components/chart.md +95 -24
  40. package/docs/design-system/components/checkbox.md +54 -54
  41. package/docs/design-system/components/collapsible.md +67 -53
  42. package/docs/design-system/components/command.md +62 -62
  43. package/docs/design-system/components/context-menu.md +46 -46
  44. package/docs/design-system/components/date-picker.md +81 -79
  45. package/docs/design-system/components/divider.md +102 -102
  46. package/docs/design-system/components/empty-state.md +56 -56
  47. package/docs/design-system/components/field.md +70 -70
  48. package/docs/design-system/components/file-upload.md +187 -187
  49. package/docs/design-system/components/hover-card.md +48 -48
  50. package/docs/design-system/components/icons.md +48 -48
  51. package/docs/design-system/components/inline-citations.md +93 -0
  52. package/docs/design-system/components/input-group.md +58 -58
  53. package/docs/design-system/components/input-otp.md +56 -56
  54. package/docs/design-system/components/input.md +117 -61
  55. package/docs/design-system/components/item.md +59 -57
  56. package/docs/design-system/components/kbd.md +54 -49
  57. package/docs/design-system/components/label.md +49 -49
  58. package/docs/design-system/components/menu.md +71 -61
  59. package/docs/design-system/components/menubar.md +47 -47
  60. package/docs/design-system/components/modal.md +105 -105
  61. package/docs/design-system/components/native-select.md +54 -54
  62. package/docs/design-system/components/navigation-menu.md +50 -50
  63. package/docs/design-system/components/onboarding-step-list-item.md +82 -82
  64. package/docs/design-system/components/page-header.md +93 -86
  65. package/docs/design-system/components/pagination.md +57 -57
  66. package/docs/design-system/components/popover.md +60 -60
  67. package/docs/design-system/components/progress-slider.md +50 -50
  68. package/docs/design-system/components/progress.md +76 -76
  69. package/docs/design-system/components/radio-card.md +51 -51
  70. package/docs/design-system/components/radio-group.md +57 -57
  71. package/docs/design-system/components/resizable.md +44 -44
  72. package/docs/design-system/components/rolling-count.md +61 -0
  73. package/docs/design-system/components/scroll-area.md +51 -51
  74. package/docs/design-system/components/segmented-control.md +54 -54
  75. package/docs/design-system/components/select.md +68 -62
  76. package/docs/design-system/components/sheet.md +67 -67
  77. package/docs/design-system/components/shimmer-text.md +67 -0
  78. package/docs/design-system/components/sidebar.md +127 -76
  79. package/docs/design-system/components/skeleton.md +75 -75
  80. package/docs/design-system/components/slideout.md +65 -65
  81. package/docs/design-system/components/slider.md +63 -63
  82. package/docs/design-system/components/social-button.md +50 -50
  83. package/docs/design-system/components/spinner.md +62 -62
  84. package/docs/design-system/components/steps.md +65 -65
  85. package/docs/design-system/components/streaming-text.md +82 -0
  86. package/docs/design-system/components/table.md +419 -414
  87. package/docs/design-system/components/tabs.md +59 -55
  88. package/docs/design-system/components/tag.md +80 -80
  89. package/docs/design-system/components/task-list.md +95 -0
  90. package/docs/design-system/components/textarea.md +50 -50
  91. package/docs/design-system/components/thinking-reasoning.md +72 -0
  92. package/docs/design-system/components/thinking-state.md +67 -0
  93. package/docs/design-system/components/timeline.md +83 -83
  94. package/docs/design-system/components/toast.md +58 -58
  95. package/docs/design-system/components/toggle.md +81 -81
  96. package/docs/design-system/components/toolbar.md +92 -87
  97. package/docs/design-system/components/tooltip.md +94 -92
  98. package/docs/design-system/components/typography.md +18 -18
  99. package/docs/design-system/density-and-elevation.md +65 -61
  100. package/docs/design-system/design-system-test-missing-items.md +368 -368
  101. package/docs/design-system/direction-and-localization.md +23 -23
  102. package/docs/design-system/form-recipes.md +73 -73
  103. package/docs/design-system/gap-promotion-policy.md +21 -21
  104. package/docs/design-system/icons.md +74 -69
  105. package/docs/design-system/installation.md +70 -68
  106. package/docs/design-system/launch-comparison-shadcn.md +98 -98
  107. package/docs/design-system/registry-and-cli.md +64 -64
  108. package/docs/design-system/release-policy.md +30 -30
  109. package/docs/design-system/roadmap.md +14 -14
  110. package/docs/design-system/support-matrix.md +23 -23
  111. package/docs/design-system/tabs.md +54 -53
  112. package/docs/design-system/template-gap-audit.md +32 -0
  113. package/docs/design-system/templates.md +59 -0
  114. package/docs/design-system/token-governance.md +72 -60
  115. package/package.json +98 -98
  116. package/registry/component-contract.json +40 -40
  117. package/registry/components/accordion.tsx +155 -155
  118. package/registry/components/agent-input-parts.tsx +552 -0
  119. package/registry/components/agent-input-state.ts +156 -0
  120. package/registry/components/agent-input.css +307 -0
  121. package/registry/components/agent-input.tsx +382 -0
  122. package/registry/components/alert-dialog.tsx +297 -297
  123. package/registry/components/alert.tsx +293 -293
  124. package/registry/components/approval-card.css +409 -0
  125. package/registry/components/approval-card.tsx +401 -0
  126. package/registry/components/approval-frame.tsx +108 -0
  127. package/registry/components/approval-questions.tsx +559 -0
  128. package/registry/components/aspect-ratio.tsx +30 -30
  129. package/registry/components/attribute.tsx +454 -448
  130. package/registry/components/autocomplete.tsx +598 -651
  131. package/registry/components/avatar.tsx +385 -381
  132. package/registry/components/badge.tsx +629 -629
  133. package/registry/components/button-group.tsx +565 -565
  134. package/registry/components/button.tsx +127 -123
  135. package/registry/components/card.tsx +638 -638
  136. package/registry/components/carousel.tsx +296 -296
  137. package/registry/components/chart-block-data.ts +177 -0
  138. package/registry/components/chart-block.css +171 -0
  139. package/registry/components/chart-block.tsx +260 -0
  140. package/registry/components/chart-interactions.ts +123 -0
  141. package/registry/components/chart-options.cartesian.ts +162 -0
  142. package/registry/components/chart-options.paint.ts +99 -0
  143. package/registry/components/chart-options.parts.ts +72 -0
  144. package/registry/components/chart-options.radial.ts +109 -0
  145. package/registry/components/chart-options.ts +44 -0
  146. package/registry/components/chart-options.types.ts +67 -0
  147. package/registry/components/chart.tsx +203 -203
  148. package/registry/components/checkbox.tsx +247 -247
  149. package/registry/components/collapsible.tsx +109 -69
  150. package/registry/components/command.tsx +208 -208
  151. package/registry/components/context-menu.tsx +236 -236
  152. package/registry/components/data-chart.tsx +40 -0
  153. package/registry/components/date-picker.tsx +1289 -1277
  154. package/registry/components/echart-theme.ts +246 -0
  155. package/registry/components/echart.css +49 -0
  156. package/registry/components/echart.tsx +178 -0
  157. package/registry/components/expanded/ActivityFeed.tsx +227 -227
  158. package/registry/components/expanded/ActivityHeatmap.tsx +64 -64
  159. package/registry/components/expanded/Banner.tsx +179 -179
  160. package/registry/components/expanded/Breadcrumbs.tsx +131 -131
  161. package/registry/components/expanded/CatalogComponentsShowcase.tsx +205 -205
  162. package/registry/components/expanded/CatalogDivider.tsx +49 -49
  163. package/registry/components/expanded/EmptyState.tsx +155 -155
  164. package/registry/components/expanded/FileUpload.tsx +543 -543
  165. package/registry/components/expanded/OnboardingStepListItem.tsx +60 -59
  166. package/registry/components/expanded/PageHeader.tsx +179 -166
  167. package/registry/components/expanded/Slideout.tsx +108 -108
  168. package/registry/components/expanded/Steps.tsx +402 -402
  169. package/registry/components/expanded/Table.tsx +1092 -1071
  170. package/registry/components/expanded/Timeline.tsx +203 -203
  171. package/registry/components/expanded/activityFeed.css +248 -248
  172. package/registry/components/expanded/activityHeatmap.css +66 -66
  173. package/registry/components/expanded/banner.css +260 -255
  174. package/registry/components/expanded/breadcrumbs.css +140 -140
  175. package/registry/components/expanded/catalogComponentsShowcase.css +87 -87
  176. package/registry/components/expanded/divider.css +75 -75
  177. package/registry/components/expanded/emptyState.css +111 -111
  178. package/registry/components/expanded/fileUpload.css +457 -457
  179. package/registry/components/expanded/onboardingStepListItem.css +135 -126
  180. package/registry/components/expanded/pageHeader.css +248 -290
  181. package/registry/components/expanded/slideout.css +276 -276
  182. package/registry/components/expanded/steps.css +356 -356
  183. package/registry/components/expanded/table.css +606 -603
  184. package/registry/components/expanded/timeline.css +286 -286
  185. package/registry/components/field.tsx +283 -283
  186. package/registry/components/hover-card.tsx +48 -48
  187. package/registry/components/inline-citations.css +126 -0
  188. package/registry/components/inline-citations.tsx +292 -0
  189. package/registry/components/input-content.ts +107 -107
  190. package/registry/components/input-group.tsx +130 -130
  191. package/registry/components/input-otp.tsx +584 -584
  192. package/registry/components/input.tsx +990 -972
  193. package/registry/components/item.tsx +189 -189
  194. package/registry/components/kbd.tsx +246 -151
  195. package/registry/components/label.tsx +78 -78
  196. package/registry/components/menu.tsx +978 -986
  197. package/registry/components/menubar.tsx +226 -226
  198. package/registry/components/modal.tsx +872 -872
  199. package/registry/components/native-select.tsx +205 -205
  200. package/registry/components/navigation-menu.tsx +171 -171
  201. package/registry/components/pagination.css +36 -36
  202. package/registry/components/pagination.tsx +560 -555
  203. package/registry/components/popover.tsx +338 -338
  204. package/registry/components/progress-slider.tsx +216 -216
  205. package/registry/components/radio-card.tsx +676 -677
  206. package/registry/components/radio-group.tsx +570 -570
  207. package/registry/components/resizable.tsx +108 -108
  208. package/registry/components/rolling-count.css +37 -0
  209. package/registry/components/rolling-count.tsx +110 -0
  210. package/registry/components/scroll-area.tsx +91 -91
  211. package/registry/components/segmented-control.tsx +87 -87
  212. package/registry/components/select-content.tsx +218 -218
  213. package/registry/components/select.tsx +937 -932
  214. package/registry/components/sheet.tsx +305 -305
  215. package/registry/components/shimmer-text.css +69 -0
  216. package/registry/components/shimmer-text.tsx +43 -0
  217. package/registry/components/sidebar.tsx +1433 -358
  218. package/registry/components/skeleton.css +54 -54
  219. package/registry/components/skeleton.tsx +482 -482
  220. package/registry/components/slider.tsx +380 -380
  221. package/registry/components/social-button.tsx +387 -387
  222. package/registry/components/spinner.tsx +78 -78
  223. package/registry/components/streaming-text.css +45 -0
  224. package/registry/components/streaming-text.tsx +165 -0
  225. package/registry/components/table-elements.tsx +128 -128
  226. package/registry/components/tabs.css +222 -218
  227. package/registry/components/tabs.tsx +241 -241
  228. package/registry/components/tag.tsx +423 -423
  229. package/registry/components/task-list.css +328 -0
  230. package/registry/components/task-list.tsx +429 -0
  231. package/registry/components/textarea.tsx +610 -610
  232. package/registry/components/thinking-reasoning.css +178 -0
  233. package/registry/components/thinking-reasoning.tsx +253 -0
  234. package/registry/components/thinking-state.css +8 -0
  235. package/registry/components/thinking-state.tsx +46 -0
  236. package/registry/components/toast.tsx +136 -136
  237. package/registry/components/toggle.tsx +256 -256
  238. package/registry/components/toolbar.tsx +539 -539
  239. package/registry/components/tooltip.tsx +433 -431
  240. package/registry/examples/agent-input-demo.tsx +90 -0
  241. package/registry/examples/alert-demo.tsx +34 -34
  242. package/registry/examples/alert-dialog-demo.tsx +42 -42
  243. package/registry/examples/approval-card-demo.tsx +83 -0
  244. package/registry/examples/aspect-ratio-demo.tsx +11 -11
  245. package/registry/examples/attribute-demo.tsx +65 -65
  246. package/registry/examples/autocomplete-demo.tsx +109 -109
  247. package/registry/examples/avatar-demo.tsx +132 -132
  248. package/registry/examples/badge-demo.tsx +69 -69
  249. package/registry/examples/button-demo.tsx +86 -83
  250. package/registry/examples/button-group-demo.tsx +63 -63
  251. package/registry/examples/card-demo.tsx +86 -86
  252. package/registry/examples/carousel-demo.tsx +43 -43
  253. package/registry/examples/chart-block-demo.tsx +5 -0
  254. package/registry/examples/chart-demo.tsx +18 -33
  255. package/registry/examples/checkbox-demo.tsx +62 -62
  256. package/registry/examples/collapsible-demo.tsx +16 -16
  257. package/registry/examples/collection-filter-bar-demo.tsx +135 -135
  258. package/registry/examples/command-demo.tsx +42 -42
  259. package/registry/examples/command-palette-demo.tsx +235 -236
  260. package/registry/examples/context-menu-demo.tsx +29 -29
  261. package/registry/examples/control-density-contract-demo.tsx +65 -61
  262. package/registry/examples/date-picker-demo.tsx +127 -127
  263. package/registry/examples/divider-demo.tsx +17 -17
  264. package/registry/examples/expanded/activity-heatmap-demo.tsx +29 -29
  265. package/registry/examples/expanded/banner-demo.tsx +48 -48
  266. package/registry/examples/expanded/breadcrumbs-demo.tsx +59 -59
  267. package/registry/examples/expanded/empty-state-demo.tsx +39 -39
  268. package/registry/examples/expanded/file-upload-demo.tsx +60 -60
  269. package/registry/examples/expanded/onboarding-step-demo.tsx +11 -11
  270. package/registry/examples/expanded/slideout-demo.tsx +15 -15
  271. package/registry/examples/expanded/steps-demo.tsx +29 -29
  272. package/registry/examples/expanded/tabs-demo.tsx +13 -13
  273. package/registry/examples/expanded/timeline-demo.tsx +18 -18
  274. package/registry/examples/field-demo.tsx +51 -51
  275. package/registry/examples/hover-card-demo.tsx +23 -23
  276. package/registry/examples/inline-citations-demo.tsx +31 -0
  277. package/registry/examples/input-actions-demo.tsx +36 -0
  278. package/registry/examples/input-demo.tsx +87 -87
  279. package/registry/examples/input-group-demo.tsx +16 -16
  280. package/registry/examples/input-otp-demo.tsx +72 -72
  281. package/registry/examples/item-demo.tsx +46 -46
  282. package/registry/examples/kbd-demo.tsx +12 -11
  283. package/registry/examples/label-demo.tsx +20 -20
  284. package/registry/examples/menu-demo.tsx +122 -122
  285. package/registry/examples/menubar-demo.tsx +34 -34
  286. package/registry/examples/modal-demo.tsx +74 -74
  287. package/registry/examples/native-select-demo.tsx +16 -16
  288. package/registry/examples/navigation-menu-demo.tsx +29 -29
  289. package/registry/examples/pagination-demo.tsx +20 -20
  290. package/registry/examples/popover-demo.tsx +547 -546
  291. package/registry/examples/progress-demo.tsx +37 -37
  292. package/registry/examples/progress-slider-demo.tsx +29 -29
  293. package/registry/examples/radio-card-demo.tsx +51 -51
  294. package/registry/examples/radio-group-demo.tsx +62 -62
  295. package/registry/examples/resizable-demo.tsx +22 -22
  296. package/registry/examples/results-toolbar-demo.tsx +44 -44
  297. package/registry/examples/rolling-count-demo.tsx +39 -0
  298. package/registry/examples/scroll-area-demo.tsx +15 -15
  299. package/registry/examples/segmented-control-demo.tsx +39 -39
  300. package/registry/examples/select-demo.tsx +87 -87
  301. package/registry/examples/sheet-demo.tsx +47 -47
  302. package/registry/examples/shimmer-text-demo.tsx +20 -0
  303. package/registry/examples/sidebar-demo.tsx +101 -57
  304. package/registry/examples/slider-demo.tsx +31 -31
  305. package/registry/examples/social-button-demo.tsx +61 -61
  306. package/registry/examples/spinner-demo.tsx +59 -59
  307. package/registry/examples/streaming-text-demo.tsx +28 -0
  308. package/registry/examples/tabs-demo.tsx +13 -13
  309. package/registry/examples/tag-demo.tsx +29 -29
  310. package/registry/examples/task-list-demo.tsx +74 -0
  311. package/registry/examples/textarea-demo.tsx +79 -79
  312. package/registry/examples/thinking-reasoning-demo.tsx +74 -0
  313. package/registry/examples/thinking-state-demo.tsx +13 -0
  314. package/registry/examples/toast-demo.tsx +35 -35
  315. package/registry/examples/toggle-demo.tsx +59 -59
  316. package/registry/examples/tooltip-demo.tsx +115 -115
  317. package/registry/guidance/USAGE.md +27 -27
  318. package/registry/guidance/charts.LICENSE.txt +24 -0
  319. package/registry/hooks/use-controllable-state.ts +33 -0
  320. package/registry/hooks/use-direction.ts +207 -207
  321. package/registry/hooks/use-listbox-navigation.ts +73 -0
  322. package/registry/hooks/use-motion-end.ts +55 -0
  323. package/registry/hooks/use-reduced-motion.ts +28 -0
  324. package/registry/index.json +1634 -184
  325. package/registry/styles/globals.css +1462 -1570
  326. package/registry.json +364 -10
  327. package/schema/config.schema.json +51 -51
  328. package/schema/registry.schema.json +194 -190
  329. package/schema/tokens.schema.json +167 -163
  330. package/src/cli/command-line.js +194 -194
  331. package/src/cli/config-editors.js +9 -9
  332. package/src/cli/doctor.js +399 -399
  333. package/src/cli/file-transaction.js +302 -295
  334. package/src/cli/global-css.js +153 -153
  335. package/src/cli/index.js +1002 -1009
  336. package/src/cli/install-plan.js +592 -592
  337. package/src/cli/install-receipt.js +171 -171
  338. package/src/cli/jsonc.js +203 -203
  339. package/src/cli/package-install-state.js +254 -254
  340. package/src/cli/package-manager.js +238 -238
  341. package/src/cli/package-plan.js +185 -185
  342. package/src/cli/package-version.js +97 -97
  343. package/src/cli/registry-query.js +207 -207
  344. package/src/cli/reporting.js +55 -55
  345. package/src/cli/schema-validation.js +19 -19
  346. package/src/cli/source-scanner.js +686 -686
  347. package/src/cli/vite-config.js +478 -478
  348. package/tokens/banhaten.tokens.json +458 -224
package/src/cli/index.js CHANGED
@@ -1,1009 +1,1002 @@
1
- #!/usr/bin/env node
2
-
3
- import { createHash } from "node:crypto"
4
- import fs from "node:fs/promises"
5
- import path from "node:path"
6
- import process from "node:process"
7
- import { fileURLToPath } from "node:url"
8
- import { parseCommandLine } from "./command-line.js"
9
- import {
10
- inspectBanhatenProject,
11
- printBanhatenDoctor,
12
- } from "./doctor.js"
13
- import {
14
- assertFileUnchanged,
15
- deferUntilApplied,
16
- formatUnifiedDiff,
17
- runFileTransaction,
18
- writeFile,
19
- } from "./file-transaction.js"
20
- import {
21
- applyPackageDependencyPlan,
22
- createPackageDependencyPlan,
23
- mergeDependencyRequirements,
24
- } from "./package-plan.js"
25
- import { inspectPackageInstallState } from "./package-install-state.js"
26
- import {
27
- createInstallPlan,
28
- resolveInstallTarget,
29
- } from "./install-plan.js"
30
- import {
31
- createInstallPlanReceipt,
32
- normalizeReceiptComponents,
33
- normalizeReceiptTarget,
34
- validateReceiptDestinations,
35
- } from "./install-receipt.js"
36
- import {
37
- ensureGlobalCssImports,
38
- removeExistingTokenBlock,
39
- } from "./global-css.js"
40
- import {
41
- printInstallHint,
42
- printResult,
43
- resolveInstallAction,
44
- } from "./reporting.js"
45
- import { assertSchema } from "./schema-validation.js"
46
- import {
47
- listComponents,
48
- searchComponents,
49
- showComponentDocs,
50
- viewComponent,
51
- } from "./registry-query.js"
52
-
53
- const packageRoot = path.resolve(
54
- path.dirname(fileURLToPath(import.meta.url)),
55
- "..",
56
- ".."
57
- )
58
- const registryRoot = path.join(packageRoot, "registry")
59
- const registryIndexPath = path.join(registryRoot, "index.json")
60
- const packageJsonPath = path.join(packageRoot, "package.json")
61
- const schemaRoot = path.join(packageRoot, "schema")
62
-
63
- const CONFIG_FILE = "banhaten.config.json"
64
- const INSTALL_RECEIPT_FILE = ".banhaten/installed.json"
65
- const SETUP_DEV_DEPENDENCIES = {
66
- tailwindcss: "^4.0.0",
67
- }
68
- const VITE_DEV_DEPENDENCIES = {
69
- "@tailwindcss/vite": "^4.0.0",
70
- }
71
- let runtimeOptions = {
72
- json: false,
73
- silent: false,
74
- }
75
-
76
- const DEFAULT_CONFIG = {
77
- $schema: ".banhaten/schema/config.schema.json",
78
- tailwind: {
79
- css: "app/globals.css",
80
- },
81
- aliases: {
82
- ui: "@/components/ui",
83
- utils: "@/lib/utils",
84
- hooks: "@/hooks",
85
- },
86
- }
87
-
88
- // Top-level keys from the shadcn-shaped config this CLI grew out of. They are
89
- // deliberately migrated away rather than rejected, so an existing project can
90
- // upgrade in place. Every *other* unknown key is a real error: without this
91
- // list, dropping unknown keys wholesale is indistinguishable from silently
92
- // destroying a setting the user meant to keep.
93
- const LEGACY_CONFIG_KEYS = Object.freeze(["style", "tsx", "rsc", "iconLibrary"])
94
-
95
- function stripLegacyConfigKeys(config) {
96
- const next = { ...config }
97
- for (const key of LEGACY_CONFIG_KEYS) delete next[key]
98
- return next
99
- }
100
-
101
- function findLegacyConfigKeys(config) {
102
- return LEGACY_CONFIG_KEYS.filter((key) => key in config)
103
- }
104
-
105
- const registry = await readJson(registryIndexPath)
106
- const packageManifest = await readJson(packageJsonPath)
107
- const registrySchema = await readJson(path.join(schemaRoot, "registry.schema.json"))
108
- const configSchema = await readJson(path.join(schemaRoot, "config.schema.json"))
109
- assertSchema(registry, registrySchema, "registry/index.json")
110
-
111
- main().catch((error) => {
112
- console.error(`banhaten: ${error.message}`)
113
- process.exitCode = 1
114
- })
115
-
116
- async function main() {
117
- const { command, positionals, flags } = parseCommandLine(process.argv.slice(2))
118
- runtimeOptions = {
119
- json: Boolean(flags.json),
120
- silent: Boolean(flags.silent),
121
- }
122
-
123
- if (command === "version" || flags.version) {
124
- console.log(packageManifest.version)
125
- return
126
- }
127
-
128
- if (!command || command === "help" || flags.help) {
129
- printHelp()
130
- return
131
- }
132
-
133
- if (command === "list") {
134
- listComponents(registry, runtimeOptions)
135
- return
136
- }
137
-
138
- if (command === "search") {
139
- searchComponents(registry, positionals, runtimeOptions)
140
- return
141
- }
142
-
143
- if (command === "docs") {
144
- await showComponentDocs(registry, packageRoot, positionals, runtimeOptions)
145
- return
146
- }
147
-
148
- if (command === "view") {
149
- await viewComponent(
150
- registry,
151
- registryRoot,
152
- positionals,
153
- flags,
154
- runtimeOptions
155
- )
156
- return
157
- }
158
-
159
- if (command === "doctor") {
160
- const report = await inspectBanhatenProject({
161
- cwd: path.resolve(flags.cwd || process.cwd()),
162
- registryVersion: packageManifest.version,
163
- })
164
- printBanhatenDoctor(report, runtimeOptions)
165
- if (report.summary.errors > 0) process.exitCode = 1
166
- return
167
- }
168
-
169
- if (command === "init") {
170
- await runFileTransaction(() => initProject(flags))
171
- return
172
- }
173
-
174
- if (command === "add") {
175
- await runFileTransaction(() => addComponents(positionals, flags))
176
- return
177
- }
178
-
179
- if (command === "diff") {
180
- await runFileTransaction(() => diffComponents(positionals, flags))
181
- return
182
- }
183
-
184
- if (command === "update") {
185
- await runFileTransaction(() => updateComponents(positionals, flags))
186
- return
187
- }
188
-
189
- throw new Error(`unknown command "${command}"`)
190
- }
191
-
192
- function printHelp() {
193
- console.log(`Banhaten design system
194
-
195
- Usage:
196
- banhaten init [--cwd <path>] [--force] [--dry-run] [--json]
197
- banhaten add <component...> [--cwd <path>] [--force] [--dry-run] [--json]
198
- banhaten diff [component...] [--cwd <path>] [--json]
199
- banhaten update [component...] [--cwd <path>] [--force] [--dry-run] [--json]
200
- banhaten list [--json]
201
- banhaten search <query> [--json]
202
- banhaten docs <component> [--json]
203
- banhaten view <component> [--file <registry-source>] [--json]
204
- banhaten doctor [--cwd <path>] [--json]
205
- banhaten version
206
-
207
- Examples:
208
- npx banhaten init
209
- npx banhaten add button
210
- npx banhaten diff
211
- npx banhaten update button
212
- npx banhaten search input
213
- npx banhaten docs button
214
- npx banhaten view button
215
- npx banhaten doctor
216
-
217
- Command flags:
218
- --cwd <path> Run project-aware commands against a project directory.
219
- --dry-run Preview init, add, or update writes.
220
- --force Replace locally modified generated files after review.
221
- --json Print machine-readable output where shown above.
222
-
223
- Global flags:
224
- --help, -h Print help.
225
- --silent, -s Suppress normal command output.
226
- --yes, -y Accepted for non-interactive scripts.
227
- --version, -v Print the installed CLI version.
228
- `)
229
- }
230
-
231
- async function initProject(flags) {
232
- const cwd = path.resolve(flags.cwd || process.cwd())
233
- const dryRun = Boolean(flags["dry-run"])
234
- const force = Boolean(flags.force)
235
- const config = await loadConfig(cwd)
236
- const installPlan = await createInstallPlan(cwd, config)
237
- const receipt = await readInstallReceipt(cwd)
238
- validateReceiptDestinations(installPlan, receipt, registry)
239
- const managedOptions = { dryRun, force, receipt }
240
- const writes = []
241
-
242
- writes.push(
243
- ...(await writeConfig(cwd, config, { dryRun, force })),
244
- ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
245
- ...(await writeBaseFiles(installPlan, managedOptions)),
246
- ...(await writeGlobalCss(installPlan, managedOptions)),
247
- ...(await writeAliasConfig(installPlan, { dryRun, force }))
248
- )
249
-
250
- const packageResult = await updatePackageJson(
251
- cwd,
252
- getPackageChanges(installPlan, registry.base.dependencies || {}),
253
- { dryRun }
254
- )
255
- writes.push(...packageResult.writes)
256
- writes.push(...(await writeInstallReceipt(installPlan, [], { dryRun })))
257
- const installResolution = await resolveInstallAction(
258
- cwd,
259
- packageResult.installRequired
260
- )
261
- for (const evidence of installResolution.evidence) {
262
- await assertFileUnchanged(evidence.path, evidence.source)
263
- }
264
- const { install } = installResolution
265
-
266
- deferUntilApplied(() => {
267
- printResult(
268
- "Initialized Banhaten design system",
269
- writes,
270
- dryRun,
271
- runtimeOptions,
272
- install
273
- )
274
- printInstallHint(install, dryRun, runtimeOptions)
275
- })
276
- }
277
-
278
- async function addComponents(names, flags) {
279
- if (names.length === 0) {
280
- throw new Error("missing component name. Try `banhaten add button`.")
281
- }
282
-
283
- await writeComponents(names, flags, {
284
- inferInstalled: false,
285
- title: `Added ${names.join(", ")}`,
286
- })
287
- }
288
-
289
- async function diffComponents(names, flags) {
290
- await writeComponents(names, { ...flags, "dry-run": true, "show-diff": true }, {
291
- inferInstalled: true,
292
- title: names.length
293
- ? `Checked ${names.join(", ")} for updates`
294
- : "Checked installed components for updates",
295
- })
296
- }
297
-
298
- async function updateComponents(names, flags) {
299
- await writeComponents(names, flags, {
300
- inferInstalled: true,
301
- title: names.length
302
- ? `Updated ${names.join(", ")}`
303
- : "Updated installed components",
304
- })
305
- }
306
-
307
- async function writeComponents(requestedNames, flags, options) {
308
- const cwd = path.resolve(flags.cwd || process.cwd())
309
- const dryRun = Boolean(flags["dry-run"])
310
- const force = Boolean(flags.force)
311
- const showDiff = Boolean(flags["show-diff"])
312
- const config = await loadConfig(cwd)
313
- const installPlan = await createInstallPlan(cwd, config)
314
- const receipt = await readInstallReceipt(cwd)
315
- validateReceiptDestinations(installPlan, receipt, registry)
316
- const managedOptions = { dryRun, force, receipt, showDiff }
317
- const selectedNames =
318
- requestedNames.length > 0
319
- ? requestedNames
320
- : options.inferInstalled
321
- ? await findInstalledComponents(installPlan)
322
- : requestedNames
323
-
324
- if (selectedNames.length === 0) {
325
- throw new Error(
326
- "no installed components found. Run `banhaten add button` first, or pass component names."
327
- )
328
- }
329
-
330
- const names = resolveRegistryDependencies(selectedNames)
331
-
332
- const writes = []
333
- const deps = {}
334
- const components = []
335
-
336
- mergeDependencyRequirements(
337
- deps,
338
- registry.base.dependencies || {},
339
- "registry base"
340
- )
341
-
342
- for (const name of names) {
343
- const component = registry.components[name]
344
- if (!component) {
345
- throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
346
- }
347
-
348
- mergeDependencyRequirements(
349
- deps,
350
- component.dependencies || {},
351
- `registry component "${name}"`
352
- )
353
- components.push({ component, name })
354
- }
355
-
356
- writes.push(
357
- ...(await writeConfig(cwd, config, { dryRun, force })),
358
- ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
359
- ...(await writeBaseFiles(installPlan, managedOptions)),
360
- ...(await writeGlobalCss(installPlan, managedOptions)),
361
- ...(await writeAliasConfig(installPlan, { dryRun, force }))
362
- )
363
-
364
- for (const { component, name } of components) {
365
- writes.push(
366
- ...(await writeRegistryFiles(installPlan, component.files || [], {
367
- ...managedOptions,
368
- owner: name,
369
- }))
370
- )
371
- }
372
-
373
- const packageResult = await updatePackageJson(
374
- cwd,
375
- getPackageChanges(installPlan, deps),
376
- { dryRun }
377
- )
378
- writes.push(...packageResult.writes)
379
- writes.push(...(await writeInstallReceipt(installPlan, names, { dryRun })))
380
- const installResolution = await resolveInstallAction(
381
- cwd,
382
- packageResult.installRequired
383
- )
384
- for (const evidence of installResolution.evidence) {
385
- await assertFileUnchanged(evidence.path, evidence.source)
386
- }
387
- const { install } = installResolution
388
-
389
- deferUntilApplied(() => {
390
- printResult(options.title, writes, dryRun, runtimeOptions, install)
391
- printInstallHint(install, dryRun, runtimeOptions)
392
- })
393
- }
394
-
395
- async function readInstallReceipt(cwd) {
396
- const receipt = await readJsonIfExists(path.join(cwd, INSTALL_RECEIPT_FILE))
397
- if (!receipt) return null
398
- if (receipt.schemaVersion !== 1 || !receipt.components) {
399
- throw new Error(
400
- `${INSTALL_RECEIPT_FILE} is invalid. Re-run an explicit \`banhaten add <component> --force\` command to rebuild it.`
401
- )
402
- }
403
- return receipt
404
- }
405
-
406
- async function findInstalledComponents(installPlan) {
407
- const { cwd } = installPlan
408
- const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
409
- const receipt = await readInstallReceipt(cwd)
410
- if (receipt) {
411
- const installed = []
412
- for (const [name, record] of Object.entries(receipt.components)) {
413
- if (!registry.components[name] || !Array.isArray(record.files)) continue
414
- if (
415
- record.files.length > 0 &&
416
- (await allPathsExist(
417
- record.files.map((file) =>
418
- path.join(cwd, normalizeReceiptTarget(file.target))
419
- )
420
- ))
421
- ) {
422
- installed.push(name)
423
- }
424
- }
425
-
426
- return installed
427
- }
428
-
429
- const installed = []
430
-
431
- for (const [name, component] of Object.entries(registry.components)) {
432
- const files = component.files || []
433
- if (files.length === 0) continue
434
-
435
- const targetPaths = files.map((file) =>
436
- path.join(cwd, resolveInstallTarget(installPlan, file.target))
437
- )
438
- if (await allPathsExist(targetPaths)) {
439
- installed.push(name)
440
- }
441
- }
442
-
443
- return installed
444
- }
445
-
446
- async function writeInstallReceipt(installPlan, names, options) {
447
- const { cwd } = installPlan
448
- const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
449
- const current = (await readJsonIfExists(receiptPath)) || {
450
- schemaVersion: 1,
451
- components: {},
452
- }
453
- const components = normalizeReceiptComponents(current.components || {})
454
- const managedFiles = Object.fromEntries(
455
- Object.entries(current.managedFiles || {}).map(([target, record]) => [
456
- normalizeReceiptTarget(target),
457
- record,
458
- ])
459
- )
460
-
461
- await addManagedFileRecords(
462
- managedFiles,
463
- installPlan,
464
- registry.base.files || [],
465
- "base"
466
- )
467
-
468
- for (const name of names) {
469
- const component = registry.components[name]
470
- await addManagedFileRecords(
471
- managedFiles,
472
- installPlan,
473
- component.files || [],
474
- name
475
- )
476
- components[name] = {
477
- files: await Promise.all(
478
- (component.files || []).map(async (file) => {
479
- const sourcePath = path.join(registryRoot, file.source)
480
- const source = await fs.readFile(sourcePath)
481
- const target = resolveInstallTarget(installPlan, file.target)
482
- const content = isTextRegistryFile(file.source)
483
- ? applyTemplate(source.toString("utf8"), installPlan, target)
484
- : source
485
-
486
- return {
487
- target,
488
- sha256: createHash("sha256").update(content).digest("hex"),
489
- }
490
- })
491
- ),
492
- }
493
- }
494
-
495
- const next = {
496
- schemaVersion: 1,
497
- registryVersion: packageManifest.version,
498
- installPlan: createInstallPlanReceipt(installPlan),
499
- components: sortObject(components),
500
- managedFiles: sortObject(managedFiles),
501
- tokenCss: await createTokenCssReceipt(installPlan),
502
- }
503
- const status = await writeFile(
504
- receiptPath,
505
- `${JSON.stringify(next, null, 2)}\n`,
506
- { dryRun: options.dryRun, force: true }
507
- )
508
-
509
- return [`${status} ${INSTALL_RECEIPT_FILE}`]
510
- }
511
-
512
- async function addManagedFileRecords(records, installPlan, files, owner) {
513
- for (const file of files) {
514
- const source = await fs.readFile(path.join(registryRoot, file.source))
515
- const target = resolveInstallTarget(installPlan, file.target)
516
- const content = isTextRegistryFile(file.source)
517
- ? applyTemplate(source.toString("utf8"), installPlan, target)
518
- : source
519
- records[target] = {
520
- owner,
521
- sha256: hashContent(content),
522
- }
523
- }
524
- }
525
-
526
- async function createTokenCssReceipt(installPlan) {
527
- const tokenCss = await fs.readFile(
528
- path.join(registryRoot, "styles", "globals.css"),
529
- "utf8"
530
- )
531
- return {
532
- target: installPlan.destinations.css,
533
- sha256: hashNormalizedText(tokenCss),
534
- }
535
- }
536
-
537
- async function allPathsExist(paths) {
538
- const results = await Promise.all(paths.map((targetPath) => exists(targetPath)))
539
- return results.every(Boolean)
540
- }
541
-
542
- function resolveRegistryDependencies(names) {
543
- const resolved = []
544
- const seen = new Set()
545
- const visiting = new Set()
546
-
547
- for (const name of names) {
548
- visit(name)
549
- }
550
-
551
- return resolved
552
-
553
- function visit(name) {
554
- const component = registry.components[name]
555
- if (!component) {
556
- throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
557
- }
558
-
559
- if (seen.has(name)) return
560
- if (visiting.has(name)) {
561
- throw new Error(`circular registry dependency detected at "${name}".`)
562
- }
563
-
564
- visiting.add(name)
565
- for (const dependency of component.registryDependencies || []) {
566
- visit(dependency)
567
- }
568
- visiting.delete(name)
569
-
570
- seen.add(name)
571
- resolved.push(name)
572
- }
573
- }
574
-
575
- async function loadConfig(cwd) {
576
- const configPath = path.join(cwd, CONFIG_FILE)
577
- const componentsPath = path.join(cwd, "components.json")
578
- const config = structuredClone(DEFAULT_CONFIG)
579
-
580
- const componentsConfig = await readJsonIfExists(componentsPath)
581
- let hasExplicitCssPath = false
582
- if (componentsConfig) {
583
- if (componentsConfig.tailwind?.css) {
584
- config.tailwind.css = componentsConfig.tailwind.css
585
- hasExplicitCssPath = true
586
- }
587
- config.aliases.utils = componentsConfig.aliases?.utils || config.aliases.utils
588
- config.aliases.hooks = componentsConfig.aliases?.hooks || config.aliases.hooks
589
- config.aliases.ui =
590
- componentsConfig.aliases?.ui ||
591
- appendAliasSegment(componentsConfig.aliases?.components, "ui") ||
592
- config.aliases.ui
593
- }
594
-
595
- const localConfig = await readJsonIfExists(configPath)
596
- if (localConfig) {
597
- // Validate what the user actually wrote, before it is merged onto the
598
- // defaults. Validating the merged object instead would apply
599
- // `additionalProperties: false` to something that structurally cannot carry
600
- // an unknown top-level key, so a stray key would pass here and then be
601
- // silently dropped by writeConfig. Known legacy keys are stripped first so
602
- // they migrate instead of failing.
603
- assertSchema(stripLegacyConfigKeys(localConfig), configSchema, CONFIG_FILE)
604
-
605
- if (localConfig.tailwind?.css) hasExplicitCssPath = true
606
- config.tailwind = { ...config.tailwind, ...(localConfig.tailwind || {}) }
607
- config.aliases = { ...config.aliases, ...(localConfig.aliases || {}) }
608
- }
609
-
610
- if (!hasExplicitCssPath) {
611
- config.tailwind.css = await detectCssPath(cwd, config.tailwind.css)
612
- }
613
-
614
- assertSchema(config, configSchema, CONFIG_FILE)
615
-
616
- return config
617
- }
618
-
619
- async function detectCssPath(cwd, fallback) {
620
- const candidates = [
621
- "app/globals.css",
622
- "src/app/globals.css",
623
- "src/index.css",
624
- "src/globals.css",
625
- "styles/globals.css",
626
- ]
627
-
628
- for (const candidate of candidates) {
629
- if (await exists(path.join(cwd, candidate))) return candidate
630
- }
631
-
632
- if (await exists(path.join(cwd, "src", "app"))) return "src/app/globals.css"
633
-
634
- return fallback
635
- }
636
-
637
- async function writeConfig(cwd, config, options) {
638
- const configPath = path.join(cwd, CONFIG_FILE)
639
- if ((await exists(configPath)) && !options.force) {
640
- const current = await fs.readFile(configPath, "utf8")
641
- const currentConfig = JSON.parse(current)
642
- // Spread the existing file first so any key this version does not manage
643
- // survives the rewrite. Rebuilding from a fixed whitelist would delete it
644
- // and still report the write as a plain "updated". Legacy keys are the one
645
- // intentional exception, and the removal is reported rather than silent.
646
- const legacyKeys = findLegacyConfigKeys(currentConfig)
647
- const nextConfig = {
648
- ...stripLegacyConfigKeys(currentConfig),
649
- $schema: DEFAULT_CONFIG.$schema,
650
- tailwind: config.tailwind,
651
- aliases: config.aliases,
652
- }
653
-
654
- if (JSON.stringify(currentConfig) !== JSON.stringify(nextConfig)) {
655
- const status = await writeFile(
656
- configPath,
657
- `${JSON.stringify(nextConfig, null, 2)}\n`,
658
- { dryRun: options.dryRun }
659
- )
660
-
661
- const notes = [`${status} ${relative(cwd, configPath)}`]
662
- if (legacyKeys.length > 0) {
663
- notes.push(
664
- `removed legacy config ${legacyKeys.length === 1 ? "key" : "keys"} ` +
665
- `${legacyKeys.map((key) => JSON.stringify(key)).join(", ")} from ` +
666
- `${relative(cwd, configPath)}`
667
- )
668
- }
669
- return notes
670
- }
671
-
672
- return [`kept ${relative(cwd, configPath)}`]
673
- }
674
-
675
- const status = await writeFile(
676
- configPath,
677
- `${JSON.stringify(config, null, 2)}\n`,
678
- options
679
- )
680
- return [`${status} ${relative(cwd, configPath)}`]
681
- }
682
-
683
- async function writeProjectSchemaFiles(cwd, options) {
684
- const schemaFiles = [
685
- "config.schema.json",
686
- "registry.schema.json",
687
- "tokens.schema.json",
688
- ]
689
- const writes = []
690
-
691
- for (const schemaFile of schemaFiles) {
692
- const sourcePath = path.join(schemaRoot, schemaFile)
693
- const targetPath = path.join(cwd, ".banhaten", "schema", schemaFile)
694
- const source = await fs.readFile(sourcePath, "utf8")
695
- const status = await writeFile(targetPath, source, options)
696
-
697
- writes.push(`${status} ${relative(cwd, targetPath)}`)
698
- }
699
-
700
- return writes
701
- }
702
-
703
- async function writeBaseFiles(installPlan, options) {
704
- return writeRegistryFiles(installPlan, registry.base.files || [], {
705
- ...options,
706
- owner: "base",
707
- })
708
- }
709
-
710
- async function writeRegistryFiles(installPlan, files, options) {
711
- const { cwd } = installPlan
712
- const writes = []
713
-
714
- for (const file of files) {
715
- const sourcePath = path.join(registryRoot, file.source)
716
- const targetPath = path.join(
717
- cwd,
718
- resolveInstallTarget(installPlan, file.target)
719
- )
720
- const source = await fs.readFile(sourcePath)
721
- const content = isTextRegistryFile(file.source)
722
- ? applyTemplate(
723
- source.toString("utf8"),
724
- installPlan,
725
- relative(cwd, targetPath)
726
- )
727
- : source
728
- const target = relative(cwd, targetPath)
729
-
730
- await assertManagedFileSafe(targetPath, content, target, options)
731
-
732
- const status = await writeFile(targetPath, content, options)
733
- writes.push(`${status} ${target}`)
734
- if (options.showDiff && status === "would update") {
735
- const current = await fs.readFile(
736
- targetPath,
737
- isTextRegistryFile(file.source) ? "utf8" : undefined
738
- )
739
- writes.push(formatUnifiedDiff(target, current, content))
740
- }
741
- }
742
-
743
- return writes
744
- }
745
-
746
- async function writeGlobalCss(installPlan, options) {
747
- const { cwd } = installPlan
748
- const cssPath = path.join(cwd, installPlan.destinations.css)
749
- const sourcePath = path.join(registryRoot, "styles", "globals.css")
750
- const tokenCss = await fs.readFile(sourcePath, "utf8")
751
- const current = await readTextIfExists(cssPath)
752
- const tokenBlock = current
753
- ? removeExistingTokenBlock(current, relative(cwd, cssPath))
754
- : { content: "", found: false }
755
-
756
- const nextCss = current
757
- ? `${tokenBlock.content.trimEnd()}\n\n${tokenCss}\n`
758
- : `${tokenCss}\n`
759
- const next = ensureGlobalCssImports(nextCss)
760
-
761
- if (
762
- current &&
763
- tokenBlock.found &&
764
- next !== current &&
765
- !options.dryRun &&
766
- !options.force
767
- ) {
768
- const expectedHash = options.receipt?.tokenCss?.sha256
769
- const currentHash = hashNormalizedText(tokenBlock.block)
770
- if (!expectedHash || currentHash !== expectedHash) {
771
- throw new Error(
772
- `${relative(cwd, cssPath)} contains local changes inside the generated Banhaten token block. ` +
773
- "Run `banhaten diff` to inspect them, move intentional overrides outside the generated block, or re-run with `--force`."
774
- )
775
- }
776
- }
777
-
778
- const status = await writeFile(cssPath, next, options)
779
- const writes = [`${status} ${relative(cwd, cssPath)}`]
780
- if (options.showDiff && status === "would update" && current !== null) {
781
- writes.push(formatUnifiedDiff(relative(cwd, cssPath), current, next))
782
- }
783
- return writes
784
- }
785
-
786
- async function writeAliasConfig(installPlan, options) {
787
- const writes = []
788
-
789
- for (const plannedConfig of [installPlan.typescript, installPlan.vite]) {
790
- if (!plannedConfig) continue
791
- const status = await writeFile(
792
- plannedConfig.targetPath,
793
- plannedConfig.nextSource,
794
- {
795
- dryRun: options.dryRun,
796
- expectedCurrent: plannedConfig.currentSource,
797
- force: true,
798
- }
799
- )
800
- writes.push(
801
- `${status} ${relative(installPlan.cwd, plannedConfig.targetPath)}`
802
- )
803
- }
804
-
805
- return writes
806
- }
807
-
808
- function getPackageChanges(installPlan, dependencies) {
809
- const devDependencies = { ...SETUP_DEV_DEPENDENCIES }
810
- if (installPlan.vite) {
811
- Object.assign(devDependencies, VITE_DEV_DEPENDENCIES)
812
- }
813
-
814
- return {
815
- dependencies,
816
- devDependencies,
817
- }
818
- }
819
-
820
- async function updatePackageJson(cwd, changes, options) {
821
- const packagePath = path.join(cwd, "package.json")
822
- const currentSource = await readTextIfExists(packagePath)
823
- const packageExists = currentSource !== null
824
- const packageJson = currentSource !== null ? JSON.parse(currentSource) : {
825
- name: path.basename(cwd).toLowerCase(),
826
- version: "0.0.0",
827
- private: true,
828
- }
829
- const packagePlan = createPackageDependencyPlan(packageJson, changes)
830
-
831
- if (packagePlan.operations.length === 0 && packageExists) {
832
- await assertFileUnchanged(packagePath, currentSource)
833
- const installState = await inspectPackageInstallState({
834
- cwd,
835
- packageJson,
836
- requirements: packagePlan.requirements,
837
- })
838
- for (const evidence of installState.evidence) {
839
- await assertFileUnchanged(evidence.path, evidence.source)
840
- }
841
- return {
842
- installRequired: installState.required,
843
- writes: [`kept ${relative(cwd, packagePath)}`],
844
- }
845
- }
846
-
847
- applyPackageDependencyPlan(packageJson, packagePlan.operations)
848
-
849
- const status = await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, {
850
- dryRun: options.dryRun,
851
- expectedCurrent: currentSource,
852
- force: true,
853
- })
854
-
855
- return {
856
- installRequired: packagePlan.operations.length > 0,
857
- writes: [`${status} ${relative(cwd, packagePath)}`],
858
- }
859
- }
860
-
861
- function applyTemplate(source, installPlan, target) {
862
- const replacements = {
863
- "@/components/ui": resolveTemplateImport(
864
- installPlan,
865
- target,
866
- "ui"
867
- ),
868
- "@/lib/utils": resolveTemplateImport(
869
- installPlan,
870
- target,
871
- "utils"
872
- ),
873
- "@/hooks": resolveTemplateImport(
874
- installPlan,
875
- target,
876
- "hooks"
877
- ),
878
- }
879
-
880
- return source.replace(
881
- /@\/components\/ui|@\/lib\/utils|@\/hooks/g,
882
- (match) => replacements[match]
883
- )
884
- }
885
-
886
- function resolveTemplateImport(installPlan, target, destinationName) {
887
- const configuredAlias = installPlan.config.aliases[destinationName]
888
- if (
889
- configuredAlias === "@" ||
890
- configuredAlias === "~" ||
891
- configuredAlias.startsWith("@/") ||
892
- configuredAlias.startsWith("~/")
893
- ) {
894
- return configuredAlias.replace(/\/$/, "")
895
- }
896
-
897
- const targetDirectory = path.posix.dirname(
898
- normalizeReceiptTarget(target)
899
- )
900
- const destination = installPlan.destinations[destinationName]
901
- const relativeImport = path.posix.relative(targetDirectory, destination)
902
-
903
- if (!relativeImport) return "."
904
- return relativeImport.startsWith(".")
905
- ? relativeImport
906
- : `./${relativeImport}`
907
- }
908
-
909
- function isTextRegistryFile(source) {
910
- return !/\.(avif|eot|gif|ico|jpe?g|otf|png|ttf|webp|woff2?)$/i.test(source)
911
- }
912
-
913
- async function readJson(filePath) {
914
- return JSON.parse(await fs.readFile(filePath, "utf8"))
915
- }
916
-
917
- async function readJsonIfExists(filePath) {
918
- try {
919
- return await readJson(filePath)
920
- } catch (error) {
921
- if (error.code === "ENOENT") return null
922
- throw error
923
- }
924
- }
925
-
926
- async function readTextIfExists(filePath) {
927
- try {
928
- return await fs.readFile(filePath, "utf8")
929
- } catch (error) {
930
- if (error.code === "ENOENT") return null
931
- throw error
932
- }
933
- }
934
-
935
- async function assertManagedFileSafe(targetPath, nextContent, target, options) {
936
- if (options.dryRun || options.force || !(await exists(targetPath))) return
937
-
938
- const current = await fs.readFile(targetPath)
939
- const next = Buffer.isBuffer(nextContent)
940
- ? nextContent
941
- : Buffer.from(nextContent, "utf8")
942
- if (current.equals(next)) return
943
-
944
- const expectedHash = findManagedFileHash(options.receipt, target)
945
- const currentHash = hashContent(current)
946
- if (expectedHash && currentHash === expectedHash) return
947
-
948
- const owner = options.owner ? ` (${options.owner})` : ""
949
- const reason = expectedHash
950
- ? "has local changes since Banhaten installed it"
951
- : "already exists without a Banhaten ownership receipt"
952
- const diffCommand = ["banhaten", "diff", options.owner === "base" ? "" : options.owner]
953
- .filter(Boolean)
954
- .join(" ")
955
- throw new Error(
956
- `${target}${owner} ${reason}. Run \`${diffCommand}\` to inspect the registry version, ` +
957
- "or re-run the command with `--force` to replace the file."
958
- )
959
- }
960
-
961
- function findManagedFileHash(receipt, target) {
962
- const normalizedTarget = normalizeReceiptTarget(target)
963
- const direct = Object.entries(receipt?.managedFiles || {}).find(
964
- ([recordedTarget]) =>
965
- normalizeReceiptTarget(recordedTarget) === normalizedTarget
966
- )?.[1]?.sha256
967
- if (direct) return direct
968
-
969
- for (const component of Object.values(receipt?.components || {})) {
970
- const match = component.files?.find(
971
- (file) => normalizeReceiptTarget(file.target) === normalizedTarget
972
- )
973
- if (match?.sha256) return match.sha256
974
- }
975
-
976
- return null
977
- }
978
-
979
- function hashContent(content) {
980
- return createHash("sha256").update(content).digest("hex")
981
- }
982
-
983
- function hashNormalizedText(content) {
984
- return hashContent(String(content).replace(/\r\n/g, "\n").trim())
985
- }
986
-
987
- async function exists(filePath) {
988
- try {
989
- await fs.access(filePath)
990
- return true
991
- } catch {
992
- return false
993
- }
994
- }
995
-
996
- function appendAliasSegment(alias, segment) {
997
- if (!alias) return null
998
- return `${alias.replace(/\/$/, "")}/${segment}`
999
- }
1000
-
1001
- function sortObject(value) {
1002
- return Object.fromEntries(
1003
- Object.entries(value).sort(([left], [right]) => left.localeCompare(right))
1004
- )
1005
- }
1006
-
1007
- function relative(cwd, targetPath) {
1008
- return path.relative(cwd, targetPath).replaceAll("\\", "/")
1009
- }
1
+ #!/usr/bin/env node
2
+
3
+ import { createHash } from "node:crypto"
4
+ import fs from "node:fs/promises"
5
+ import path from "node:path"
6
+ import process from "node:process"
7
+ import { fileURLToPath } from "node:url"
8
+ import { parseCommandLine } from "./command-line.js"
9
+ import {
10
+ inspectBanhatenProject,
11
+ printBanhatenDoctor,
12
+ } from "./doctor.js"
13
+ import {
14
+ assertFileUnchanged,
15
+ deferUntilApplied,
16
+ formatUnifiedDiff,
17
+ readFileForUpdate,
18
+ runFileTransaction,
19
+ writeFile,
20
+ } from "./file-transaction.js"
21
+ import {
22
+ applyPackageDependencyPlan,
23
+ createPackageDependencyPlan,
24
+ mergeDependencyRequirements,
25
+ } from "./package-plan.js"
26
+ import { inspectPackageInstallState } from "./package-install-state.js"
27
+ import {
28
+ createInstallPlan,
29
+ resolveInstallTarget,
30
+ } from "./install-plan.js"
31
+ import {
32
+ createInstallPlanReceipt,
33
+ normalizeReceiptComponents,
34
+ normalizeReceiptTarget,
35
+ validateReceiptDestinations,
36
+ } from "./install-receipt.js"
37
+ import {
38
+ ensureGlobalCssImports,
39
+ removeExistingTokenBlock,
40
+ } from "./global-css.js"
41
+ import {
42
+ printInstallHint,
43
+ printResult,
44
+ resolveInstallAction,
45
+ } from "./reporting.js"
46
+ import { assertSchema } from "./schema-validation.js"
47
+ import {
48
+ listComponents,
49
+ searchComponents,
50
+ showComponentDocs,
51
+ viewComponent,
52
+ } from "./registry-query.js"
53
+
54
+ const packageRoot = path.resolve(
55
+ path.dirname(fileURLToPath(import.meta.url)),
56
+ "..",
57
+ ".."
58
+ )
59
+ const registryRoot = path.join(packageRoot, "registry")
60
+ const registryIndexPath = path.join(registryRoot, "index.json")
61
+ const packageJsonPath = path.join(packageRoot, "package.json")
62
+ const schemaRoot = path.join(packageRoot, "schema")
63
+
64
+ const CONFIG_FILE = "banhaten.config.json"
65
+ const INSTALL_RECEIPT_FILE = ".banhaten/installed.json"
66
+ const SETUP_DEV_DEPENDENCIES = {
67
+ tailwindcss: "^4.0.0",
68
+ }
69
+ const VITE_DEV_DEPENDENCIES = {
70
+ "@tailwindcss/vite": "^4.0.0",
71
+ }
72
+ let runtimeOptions = {
73
+ json: false,
74
+ silent: false,
75
+ }
76
+
77
+ const DEFAULT_CONFIG = {
78
+ $schema: ".banhaten/schema/config.schema.json",
79
+ tailwind: {
80
+ css: "app/globals.css",
81
+ },
82
+ aliases: {
83
+ ui: "@/components/ui",
84
+ utils: "@/lib/utils",
85
+ hooks: "@/hooks",
86
+ },
87
+ }
88
+
89
+ // Top-level keys from the shadcn-shaped config this CLI grew out of. They are
90
+ // deliberately migrated away rather than rejected, so an existing project can
91
+ // upgrade in place. Every *other* unknown key is a real error: without this
92
+ // list, dropping unknown keys wholesale is indistinguishable from silently
93
+ // destroying a setting the user meant to keep.
94
+ const LEGACY_CONFIG_KEYS = Object.freeze(["style", "tsx", "rsc", "iconLibrary"])
95
+
96
+ function stripLegacyConfigKeys(config) {
97
+ const next = { ...config }
98
+ for (const key of LEGACY_CONFIG_KEYS) delete next[key]
99
+ return next
100
+ }
101
+
102
+ function findLegacyConfigKeys(config) {
103
+ return LEGACY_CONFIG_KEYS.filter((key) => key in config)
104
+ }
105
+
106
+ const registry = await readJson(registryIndexPath)
107
+ const packageManifest = await readJson(packageJsonPath)
108
+ const registrySchema = await readJson(path.join(schemaRoot, "registry.schema.json"))
109
+ const configSchema = await readJson(path.join(schemaRoot, "config.schema.json"))
110
+ assertSchema(registry, registrySchema, "registry/index.json")
111
+
112
+ main().catch((error) => {
113
+ console.error(`banhaten: ${error.message}`)
114
+ process.exitCode = 1
115
+ })
116
+
117
+ async function main() {
118
+ const { command, positionals, flags } = parseCommandLine(process.argv.slice(2))
119
+ runtimeOptions = {
120
+ json: Boolean(flags.json),
121
+ silent: Boolean(flags.silent),
122
+ }
123
+
124
+ if (command === "version" || flags.version) {
125
+ console.log(packageManifest.version)
126
+ return
127
+ }
128
+
129
+ if (!command || command === "help" || flags.help) {
130
+ printHelp()
131
+ return
132
+ }
133
+
134
+ if (command === "list") {
135
+ listComponents(registry, runtimeOptions)
136
+ return
137
+ }
138
+
139
+ if (command === "search") {
140
+ searchComponents(registry, positionals, runtimeOptions)
141
+ return
142
+ }
143
+
144
+ if (command === "docs") {
145
+ await showComponentDocs(registry, packageRoot, positionals, runtimeOptions)
146
+ return
147
+ }
148
+
149
+ if (command === "view") {
150
+ await viewComponent(
151
+ registry,
152
+ registryRoot,
153
+ positionals,
154
+ flags,
155
+ runtimeOptions
156
+ )
157
+ return
158
+ }
159
+
160
+ if (command === "doctor") {
161
+ const report = await inspectBanhatenProject({
162
+ cwd: path.resolve(flags.cwd || process.cwd()),
163
+ registryVersion: packageManifest.version,
164
+ })
165
+ printBanhatenDoctor(report, runtimeOptions)
166
+ if (report.summary.errors > 0) process.exitCode = 1
167
+ return
168
+ }
169
+
170
+ if (command === "init") {
171
+ await runFileTransaction(() => initProject(flags))
172
+ return
173
+ }
174
+
175
+ if (command === "add") {
176
+ await runFileTransaction(() => addComponents(positionals, flags))
177
+ return
178
+ }
179
+
180
+ if (command === "diff") {
181
+ await runFileTransaction(() => diffComponents(positionals, flags))
182
+ return
183
+ }
184
+
185
+ if (command === "update") {
186
+ await runFileTransaction(() => updateComponents(positionals, flags))
187
+ return
188
+ }
189
+
190
+ throw new Error(`unknown command "${command}"`)
191
+ }
192
+
193
+ function printHelp() {
194
+ console.log(`Banhaten design system
195
+
196
+ Usage:
197
+ banhaten init [--cwd <path>] [--force] [--dry-run] [--json]
198
+ banhaten add <component...> [--cwd <path>] [--force] [--dry-run] [--json]
199
+ banhaten diff [component...] [--cwd <path>] [--json]
200
+ banhaten update [component...] [--cwd <path>] [--force] [--dry-run] [--json]
201
+ banhaten list [--json]
202
+ banhaten search <query> [--json]
203
+ banhaten docs <component> [--json]
204
+ banhaten view <component> [--file <registry-source>] [--json]
205
+ banhaten doctor [--cwd <path>] [--json]
206
+ banhaten version
207
+
208
+ Examples:
209
+ npx banhaten init
210
+ npx banhaten add button
211
+ npx banhaten diff
212
+ npx banhaten update button
213
+ npx banhaten search input
214
+ npx banhaten docs button
215
+ npx banhaten view button
216
+ npx banhaten doctor
217
+
218
+ Command flags:
219
+ --cwd <path> Run project-aware commands against a project directory.
220
+ --dry-run Preview init, add, or update writes.
221
+ --force Replace locally modified generated files after review.
222
+ --json Print machine-readable output where shown above.
223
+
224
+ Global flags:
225
+ --help, -h Print help.
226
+ --silent, -s Suppress normal command output.
227
+ --yes, -y Accepted for non-interactive scripts.
228
+ --version, -v Print the installed CLI version.
229
+ `)
230
+ }
231
+
232
+ async function initProject(flags) {
233
+ const cwd = path.resolve(flags.cwd || process.cwd())
234
+ const dryRun = Boolean(flags["dry-run"])
235
+ const force = Boolean(flags.force)
236
+ const config = await loadConfig(cwd)
237
+ const installPlan = await createInstallPlan(cwd, config)
238
+ const receipt = await readInstallReceipt(cwd)
239
+ validateReceiptDestinations(installPlan, receipt, registry)
240
+ const managedOptions = { dryRun, force, receipt }
241
+ const writes = []
242
+
243
+ writes.push(
244
+ ...(await writeConfig(cwd, config, { dryRun, force })),
245
+ ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
246
+ ...(await writeBaseFiles(installPlan, managedOptions)),
247
+ ...(await writeGlobalCss(installPlan, managedOptions)),
248
+ ...(await writeAliasConfig(installPlan, { dryRun, force }))
249
+ )
250
+
251
+ const packageResult = await updatePackageJson(
252
+ cwd,
253
+ getPackageChanges(installPlan, registry.base.dependencies || {}),
254
+ { dryRun }
255
+ )
256
+ writes.push(...packageResult.writes)
257
+ writes.push(...(await writeInstallReceipt(installPlan, [], { dryRun })))
258
+ const installResolution = await resolveInstallAction(
259
+ cwd,
260
+ packageResult.installRequired
261
+ )
262
+ for (const evidence of installResolution.evidence) {
263
+ await assertFileUnchanged(evidence.path, evidence.source)
264
+ }
265
+ const { install } = installResolution
266
+
267
+ deferUntilApplied(() => {
268
+ printResult(
269
+ "Initialized Banhaten design system",
270
+ writes,
271
+ dryRun,
272
+ runtimeOptions,
273
+ install
274
+ )
275
+ printInstallHint(install, dryRun, runtimeOptions)
276
+ })
277
+ }
278
+
279
+ async function addComponents(names, flags) {
280
+ if (names.length === 0) {
281
+ throw new Error("missing component name. Try `banhaten add button`.")
282
+ }
283
+
284
+ await writeComponents(names, flags, {
285
+ inferInstalled: false,
286
+ title: `Added ${names.join(", ")}`,
287
+ })
288
+ }
289
+
290
+ async function diffComponents(names, flags) {
291
+ await writeComponents(names, { ...flags, "dry-run": true, "show-diff": true }, {
292
+ inferInstalled: true,
293
+ title: names.length
294
+ ? `Checked ${names.join(", ")} for updates`
295
+ : "Checked installed components for updates",
296
+ })
297
+ }
298
+
299
+ async function updateComponents(names, flags) {
300
+ await writeComponents(names, flags, {
301
+ inferInstalled: true,
302
+ title: names.length
303
+ ? `Updated ${names.join(", ")}`
304
+ : "Updated installed components",
305
+ })
306
+ }
307
+
308
+ async function writeComponents(requestedNames, flags, options) {
309
+ const cwd = path.resolve(flags.cwd || process.cwd())
310
+ const dryRun = Boolean(flags["dry-run"])
311
+ const force = Boolean(flags.force)
312
+ const showDiff = Boolean(flags["show-diff"])
313
+ const config = await loadConfig(cwd)
314
+ const installPlan = await createInstallPlan(cwd, config)
315
+ const receipt = await readInstallReceipt(cwd)
316
+ validateReceiptDestinations(installPlan, receipt, registry)
317
+ const managedOptions = { dryRun, force, receipt, showDiff }
318
+ const selectedNames =
319
+ requestedNames.length > 0
320
+ ? requestedNames
321
+ : options.inferInstalled
322
+ ? await findInstalledComponents(installPlan)
323
+ : requestedNames
324
+
325
+ if (selectedNames.length === 0) {
326
+ throw new Error(
327
+ "no installed components found. Run `banhaten add button` first, or pass component names."
328
+ )
329
+ }
330
+
331
+ const names = resolveRegistryDependencies(selectedNames)
332
+
333
+ const writes = []
334
+ const deps = {}
335
+ const components = []
336
+
337
+ mergeDependencyRequirements(
338
+ deps,
339
+ registry.base.dependencies || {},
340
+ "registry base"
341
+ )
342
+
343
+ for (const name of names) {
344
+ const component = registry.components[name]
345
+ if (!component) {
346
+ throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
347
+ }
348
+
349
+ mergeDependencyRequirements(
350
+ deps,
351
+ component.dependencies || {},
352
+ `registry component "${name}"`
353
+ )
354
+ components.push({ component, name })
355
+ }
356
+
357
+ writes.push(
358
+ ...(await writeConfig(cwd, config, { dryRun, force })),
359
+ ...(await writeProjectSchemaFiles(cwd, { dryRun, force })),
360
+ ...(await writeBaseFiles(installPlan, managedOptions)),
361
+ ...(await writeGlobalCss(installPlan, managedOptions)),
362
+ ...(await writeAliasConfig(installPlan, { dryRun, force }))
363
+ )
364
+
365
+ for (const { component, name } of components) {
366
+ writes.push(
367
+ ...(await writeRegistryFiles(installPlan, component.files || [], {
368
+ ...managedOptions,
369
+ owner: name,
370
+ }))
371
+ )
372
+ }
373
+
374
+ const packageResult = await updatePackageJson(
375
+ cwd,
376
+ getPackageChanges(installPlan, deps),
377
+ { dryRun }
378
+ )
379
+ writes.push(...packageResult.writes)
380
+ writes.push(...(await writeInstallReceipt(installPlan, names, { dryRun })))
381
+ const installResolution = await resolveInstallAction(
382
+ cwd,
383
+ packageResult.installRequired
384
+ )
385
+ for (const evidence of installResolution.evidence) {
386
+ await assertFileUnchanged(evidence.path, evidence.source)
387
+ }
388
+ const { install } = installResolution
389
+
390
+ deferUntilApplied(() => {
391
+ printResult(options.title, writes, dryRun, runtimeOptions, install)
392
+ printInstallHint(install, dryRun, runtimeOptions)
393
+ })
394
+ }
395
+
396
+ async function readInstallReceipt(cwd) {
397
+ const receipt = await readJsonForUpdate(path.join(cwd, INSTALL_RECEIPT_FILE))
398
+ if (!receipt) return null
399
+ if (receipt.schemaVersion !== 1 || !receipt.components) {
400
+ throw new Error(
401
+ `${INSTALL_RECEIPT_FILE} is invalid. Re-run an explicit \`banhaten add <component> --force\` command to rebuild it.`
402
+ )
403
+ }
404
+ return receipt
405
+ }
406
+
407
+ async function findInstalledComponents(installPlan) {
408
+ const { cwd } = installPlan
409
+ const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
410
+ const receipt = await readInstallReceipt(cwd)
411
+ if (receipt) {
412
+ const installed = []
413
+ for (const [name, record] of Object.entries(receipt.components)) {
414
+ if (!registry.components[name] || !Array.isArray(record.files)) continue
415
+ if (
416
+ record.files.length > 0 &&
417
+ (await allPathsExist(
418
+ record.files.map((file) =>
419
+ path.join(cwd, normalizeReceiptTarget(file.target))
420
+ )
421
+ ))
422
+ ) {
423
+ installed.push(name)
424
+ }
425
+ }
426
+
427
+ return installed
428
+ }
429
+
430
+ const installed = []
431
+
432
+ for (const [name, component] of Object.entries(registry.components)) {
433
+ const files = component.files || []
434
+ if (files.length === 0) continue
435
+
436
+ const targetPaths = files.map((file) =>
437
+ path.join(cwd, resolveInstallTarget(installPlan, file.target))
438
+ )
439
+ if (await allPathsExist(targetPaths)) {
440
+ installed.push(name)
441
+ }
442
+ }
443
+
444
+ return installed
445
+ }
446
+
447
+ async function writeInstallReceipt(installPlan, names, options) {
448
+ const { cwd } = installPlan
449
+ const receiptPath = path.join(cwd, INSTALL_RECEIPT_FILE)
450
+ const current = (await readJsonForUpdate(receiptPath)) || {
451
+ schemaVersion: 1,
452
+ components: {},
453
+ }
454
+ const components = normalizeReceiptComponents(current.components || {})
455
+ const managedFiles = Object.fromEntries(
456
+ Object.entries(current.managedFiles || {}).map(([target, record]) => [
457
+ normalizeReceiptTarget(target),
458
+ record,
459
+ ])
460
+ )
461
+
462
+ await addManagedFileRecords(
463
+ managedFiles,
464
+ installPlan,
465
+ registry.base.files || [],
466
+ "base"
467
+ )
468
+
469
+ for (const name of names) {
470
+ const component = registry.components[name]
471
+ await addManagedFileRecords(
472
+ managedFiles,
473
+ installPlan,
474
+ component.files || [],
475
+ name
476
+ )
477
+ components[name] = {
478
+ files: await Promise.all(
479
+ (component.files || []).map(async (file) => {
480
+ const sourcePath = path.join(registryRoot, file.source)
481
+ const source = await fs.readFile(sourcePath)
482
+ const target = resolveInstallTarget(installPlan, file.target)
483
+ const content = isTextRegistryFile(file.source)
484
+ ? applyTemplate(source.toString("utf8"), installPlan, target)
485
+ : source
486
+
487
+ return {
488
+ target,
489
+ sha256: createHash("sha256").update(content).digest("hex"),
490
+ }
491
+ })
492
+ ),
493
+ }
494
+ }
495
+
496
+ const next = {
497
+ schemaVersion: 1,
498
+ registryVersion: packageManifest.version,
499
+ installPlan: createInstallPlanReceipt(installPlan),
500
+ components: sortObject(components),
501
+ managedFiles: sortObject(managedFiles),
502
+ tokenCss: await createTokenCssReceipt(installPlan),
503
+ }
504
+ const status = await writeFile(
505
+ receiptPath,
506
+ `${JSON.stringify(next, null, 2)}\n`,
507
+ { dryRun: options.dryRun, force: true }
508
+ )
509
+
510
+ return [`${status} ${INSTALL_RECEIPT_FILE}`]
511
+ }
512
+
513
+ async function addManagedFileRecords(records, installPlan, files, owner) {
514
+ for (const file of files) {
515
+ const source = await fs.readFile(path.join(registryRoot, file.source))
516
+ const target = resolveInstallTarget(installPlan, file.target)
517
+ const content = isTextRegistryFile(file.source)
518
+ ? applyTemplate(source.toString("utf8"), installPlan, target)
519
+ : source
520
+ records[target] = {
521
+ owner,
522
+ sha256: hashContent(content),
523
+ }
524
+ }
525
+ }
526
+
527
+ async function createTokenCssReceipt(installPlan) {
528
+ const tokenCss = await fs.readFile(
529
+ path.join(registryRoot, "styles", "globals.css"),
530
+ "utf8"
531
+ )
532
+ return {
533
+ target: installPlan.destinations.css,
534
+ sha256: hashNormalizedText(tokenCss),
535
+ }
536
+ }
537
+
538
+ async function allPathsExist(paths) {
539
+ const results = await Promise.all(paths.map((targetPath) => exists(targetPath)))
540
+ return results.every(Boolean)
541
+ }
542
+
543
+ function resolveRegistryDependencies(names) {
544
+ const resolved = []
545
+ const seen = new Set()
546
+ const visiting = new Set()
547
+
548
+ for (const name of names) {
549
+ visit(name)
550
+ }
551
+
552
+ return resolved
553
+
554
+ function visit(name) {
555
+ const component = registry.components[name]
556
+ if (!component) {
557
+ throw new Error(`unknown component "${name}". Run \`banhaten list\`.`)
558
+ }
559
+
560
+ if (seen.has(name)) return
561
+ if (visiting.has(name)) {
562
+ throw new Error(`circular registry dependency detected at "${name}".`)
563
+ }
564
+
565
+ visiting.add(name)
566
+ for (const dependency of component.registryDependencies || []) {
567
+ visit(dependency)
568
+ }
569
+ visiting.delete(name)
570
+
571
+ seen.add(name)
572
+ resolved.push(name)
573
+ }
574
+ }
575
+
576
+ async function loadConfig(cwd) {
577
+ const configPath = path.join(cwd, CONFIG_FILE)
578
+ const componentsPath = path.join(cwd, "components.json")
579
+ const config = structuredClone(DEFAULT_CONFIG)
580
+
581
+ const componentsConfig = await readJsonForUpdate(componentsPath)
582
+ let hasExplicitCssPath = false
583
+ if (componentsConfig) {
584
+ if (componentsConfig.tailwind?.css) {
585
+ config.tailwind.css = componentsConfig.tailwind.css
586
+ hasExplicitCssPath = true
587
+ }
588
+ config.aliases.utils = componentsConfig.aliases?.utils || config.aliases.utils
589
+ config.aliases.hooks = componentsConfig.aliases?.hooks || config.aliases.hooks
590
+ config.aliases.ui =
591
+ componentsConfig.aliases?.ui ||
592
+ appendAliasSegment(componentsConfig.aliases?.components, "ui") ||
593
+ config.aliases.ui
594
+ }
595
+
596
+ const localConfig = await readJsonForUpdate(configPath)
597
+ if (localConfig) {
598
+ // Validate what the user actually wrote, before it is merged onto the
599
+ // defaults. Validating the merged object instead would apply
600
+ // `additionalProperties: false` to something that structurally cannot carry
601
+ // an unknown top-level key, so a stray key would pass here and then be
602
+ // silently dropped by writeConfig. Known legacy keys are stripped first so
603
+ // they migrate instead of failing.
604
+ assertSchema(stripLegacyConfigKeys(localConfig), configSchema, CONFIG_FILE)
605
+
606
+ if (localConfig.tailwind?.css) hasExplicitCssPath = true
607
+ config.tailwind = { ...config.tailwind, ...(localConfig.tailwind || {}) }
608
+ config.aliases = { ...config.aliases, ...(localConfig.aliases || {}) }
609
+ }
610
+
611
+ if (!hasExplicitCssPath) {
612
+ config.tailwind.css = await detectCssPath(cwd, config.tailwind.css)
613
+ }
614
+
615
+ assertSchema(config, configSchema, CONFIG_FILE)
616
+
617
+ return config
618
+ }
619
+
620
+ async function detectCssPath(cwd, fallback) {
621
+ const candidates = [
622
+ "app/globals.css",
623
+ "src/app/globals.css",
624
+ "src/index.css",
625
+ "src/globals.css",
626
+ "styles/globals.css",
627
+ ]
628
+
629
+ for (const candidate of candidates) {
630
+ if (await exists(path.join(cwd, candidate))) return candidate
631
+ }
632
+
633
+ if (await exists(path.join(cwd, "src", "app"))) return "src/app/globals.css"
634
+
635
+ return fallback
636
+ }
637
+
638
+ async function writeConfig(cwd, config, options) {
639
+ const configPath = path.join(cwd, CONFIG_FILE)
640
+ if ((await exists(configPath)) && !options.force) {
641
+ const current = await fs.readFile(configPath, "utf8")
642
+ const currentConfig = JSON.parse(current)
643
+ // Spread the existing file first so any key this version does not manage
644
+ // survives the rewrite. Rebuilding from a fixed whitelist would delete it
645
+ // and still report the write as a plain "updated". Legacy keys are the one
646
+ // intentional exception, and the removal is reported rather than silent.
647
+ const legacyKeys = findLegacyConfigKeys(currentConfig)
648
+ const nextConfig = {
649
+ ...stripLegacyConfigKeys(currentConfig),
650
+ $schema: DEFAULT_CONFIG.$schema,
651
+ tailwind: config.tailwind,
652
+ aliases: config.aliases,
653
+ }
654
+
655
+ if (JSON.stringify(currentConfig) !== JSON.stringify(nextConfig)) {
656
+ const status = await writeFile(
657
+ configPath,
658
+ `${JSON.stringify(nextConfig, null, 2)}\n`,
659
+ { dryRun: options.dryRun }
660
+ )
661
+
662
+ const notes = [`${status} ${relative(cwd, configPath)}`]
663
+ if (legacyKeys.length > 0) {
664
+ notes.push(
665
+ `removed legacy config ${legacyKeys.length === 1 ? "key" : "keys"} ` +
666
+ `${legacyKeys.map((key) => JSON.stringify(key)).join(", ")} from ` +
667
+ `${relative(cwd, configPath)}`
668
+ )
669
+ }
670
+ return notes
671
+ }
672
+
673
+ return [`kept ${relative(cwd, configPath)}`]
674
+ }
675
+
676
+ const status = await writeFile(
677
+ configPath,
678
+ `${JSON.stringify(config, null, 2)}\n`,
679
+ options
680
+ )
681
+ return [`${status} ${relative(cwd, configPath)}`]
682
+ }
683
+
684
+ async function writeProjectSchemaFiles(cwd, options) {
685
+ const schemaFiles = [
686
+ "config.schema.json",
687
+ "registry.schema.json",
688
+ "tokens.schema.json",
689
+ ]
690
+ const writes = []
691
+
692
+ for (const schemaFile of schemaFiles) {
693
+ const sourcePath = path.join(schemaRoot, schemaFile)
694
+ const targetPath = path.join(cwd, ".banhaten", "schema", schemaFile)
695
+ const source = await fs.readFile(sourcePath, "utf8")
696
+ const status = await writeFile(targetPath, source, options)
697
+
698
+ writes.push(`${status} ${relative(cwd, targetPath)}`)
699
+ }
700
+
701
+ return writes
702
+ }
703
+
704
+ async function writeBaseFiles(installPlan, options) {
705
+ return writeRegistryFiles(installPlan, registry.base.files || [], {
706
+ ...options,
707
+ owner: "base",
708
+ })
709
+ }
710
+
711
+ async function writeRegistryFiles(installPlan, files, options) {
712
+ const { cwd } = installPlan
713
+ const writes = []
714
+
715
+ for (const file of files) {
716
+ const sourcePath = path.join(registryRoot, file.source)
717
+ const targetPath = path.join(
718
+ cwd,
719
+ resolveInstallTarget(installPlan, file.target)
720
+ )
721
+ const source = await fs.readFile(sourcePath)
722
+ const content = isTextRegistryFile(file.source)
723
+ ? applyTemplate(
724
+ source.toString("utf8"),
725
+ installPlan,
726
+ relative(cwd, targetPath)
727
+ )
728
+ : source
729
+ const target = relative(cwd, targetPath)
730
+
731
+ const current = await readFileForUpdate(targetPath)
732
+ assertManagedFileSafe(current, content, target, options)
733
+
734
+ const status = await writeFile(targetPath, content, options)
735
+ writes.push(`${status} ${target}`)
736
+ if (options.showDiff && status === "would update") {
737
+ writes.push(formatUnifiedDiff(
738
+ target,
739
+ isTextRegistryFile(file.source) ? current.toString("utf8") : current,
740
+ content
741
+ ))
742
+ }
743
+ }
744
+
745
+ return writes
746
+ }
747
+
748
+ async function writeGlobalCss(installPlan, options) {
749
+ const { cwd } = installPlan
750
+ const cssPath = path.join(cwd, installPlan.destinations.css)
751
+ const sourcePath = path.join(registryRoot, "styles", "globals.css")
752
+ const tokenCss = await fs.readFile(sourcePath, "utf8")
753
+ const current = await readTextForUpdate(cssPath)
754
+ const tokenBlock = current
755
+ ? removeExistingTokenBlock(current, relative(cwd, cssPath))
756
+ : { content: "", found: false }
757
+
758
+ const nextCss = current
759
+ ? `${tokenBlock.content.trimEnd()}\n\n${tokenCss}\n`
760
+ : `${tokenCss}\n`
761
+ const next = ensureGlobalCssImports(nextCss)
762
+
763
+ if (
764
+ current &&
765
+ tokenBlock.found &&
766
+ next !== current &&
767
+ !options.dryRun &&
768
+ !options.force
769
+ ) {
770
+ const expectedHash = options.receipt?.tokenCss?.sha256
771
+ const currentHash = hashNormalizedText(tokenBlock.block)
772
+ if (!expectedHash || currentHash !== expectedHash) {
773
+ throw new Error(
774
+ `${relative(cwd, cssPath)} contains local changes inside the generated Banhaten token block. ` +
775
+ "Run `banhaten diff` to inspect them, move intentional overrides outside the generated block, or re-run with `--force`."
776
+ )
777
+ }
778
+ }
779
+
780
+ const status = await writeFile(cssPath, next, options)
781
+ const writes = [`${status} ${relative(cwd, cssPath)}`]
782
+ if (options.showDiff && status === "would update" && current !== null) {
783
+ writes.push(formatUnifiedDiff(relative(cwd, cssPath), current, next))
784
+ }
785
+ return writes
786
+ }
787
+
788
+ async function writeAliasConfig(installPlan, options) {
789
+ const writes = []
790
+
791
+ for (const plannedConfig of [installPlan.typescript, installPlan.vite]) {
792
+ if (!plannedConfig) continue
793
+ const status = await writeFile(
794
+ plannedConfig.targetPath,
795
+ plannedConfig.nextSource,
796
+ {
797
+ dryRun: options.dryRun,
798
+ expectedCurrent: plannedConfig.currentSource,
799
+ force: true,
800
+ }
801
+ )
802
+ writes.push(
803
+ `${status} ${relative(installPlan.cwd, plannedConfig.targetPath)}`
804
+ )
805
+ }
806
+
807
+ return writes
808
+ }
809
+
810
+ function getPackageChanges(installPlan, dependencies) {
811
+ const devDependencies = { ...SETUP_DEV_DEPENDENCIES }
812
+ if (installPlan.vite) {
813
+ Object.assign(devDependencies, VITE_DEV_DEPENDENCIES)
814
+ }
815
+
816
+ return {
817
+ dependencies,
818
+ devDependencies,
819
+ }
820
+ }
821
+
822
+ async function updatePackageJson(cwd, changes, options) {
823
+ const packagePath = path.join(cwd, "package.json")
824
+ const currentSource = await readTextForUpdate(packagePath)
825
+ const packageExists = currentSource !== null
826
+ const packageJson = currentSource !== null ? JSON.parse(currentSource) : {
827
+ name: path.basename(cwd).toLowerCase(),
828
+ version: "0.0.0",
829
+ private: true,
830
+ }
831
+ const packagePlan = createPackageDependencyPlan(packageJson, changes)
832
+
833
+ if (packagePlan.operations.length === 0 && packageExists) {
834
+ await assertFileUnchanged(packagePath, currentSource)
835
+ const installState = await inspectPackageInstallState({
836
+ cwd,
837
+ packageJson,
838
+ requirements: packagePlan.requirements,
839
+ })
840
+ for (const evidence of installState.evidence) {
841
+ await assertFileUnchanged(evidence.path, evidence.source)
842
+ }
843
+ return {
844
+ installRequired: installState.required,
845
+ writes: [`kept ${relative(cwd, packagePath)}`],
846
+ }
847
+ }
848
+
849
+ applyPackageDependencyPlan(packageJson, packagePlan.operations)
850
+
851
+ const status = await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`, {
852
+ dryRun: options.dryRun,
853
+ expectedCurrent: currentSource,
854
+ force: true,
855
+ })
856
+
857
+ return {
858
+ installRequired: packagePlan.operations.length > 0,
859
+ writes: [`${status} ${relative(cwd, packagePath)}`],
860
+ }
861
+ }
862
+
863
+ function applyTemplate(source, installPlan, target) {
864
+ const replacements = {
865
+ "@/components/ui": resolveTemplateImport(
866
+ installPlan,
867
+ target,
868
+ "ui"
869
+ ),
870
+ "@/lib/utils": resolveTemplateImport(
871
+ installPlan,
872
+ target,
873
+ "utils"
874
+ ),
875
+ "@/hooks": resolveTemplateImport(
876
+ installPlan,
877
+ target,
878
+ "hooks"
879
+ ),
880
+ }
881
+
882
+ return source.replace(
883
+ /@\/components\/ui|@\/lib\/utils|@\/hooks/g,
884
+ (match) => replacements[match]
885
+ )
886
+ }
887
+
888
+ function resolveTemplateImport(installPlan, target, destinationName) {
889
+ const configuredAlias = installPlan.config.aliases[destinationName]
890
+ if (
891
+ configuredAlias === "@" ||
892
+ configuredAlias === "~" ||
893
+ configuredAlias.startsWith("@/") ||
894
+ configuredAlias.startsWith("~/")
895
+ ) {
896
+ return configuredAlias.replace(/\/$/, "")
897
+ }
898
+
899
+ const targetDirectory = path.posix.dirname(
900
+ normalizeReceiptTarget(target)
901
+ )
902
+ const destination = installPlan.destinations[destinationName]
903
+ const relativeImport = path.posix.relative(targetDirectory, destination)
904
+
905
+ if (!relativeImport) return "."
906
+ return relativeImport.startsWith(".")
907
+ ? relativeImport
908
+ : `./${relativeImport}`
909
+ }
910
+
911
+ function isTextRegistryFile(source) {
912
+ return !/\.(avif|eot|gif|ico|jpe?g|otf|png|ttf|webp|woff2?)$/i.test(source)
913
+ }
914
+
915
+ async function readJson(filePath) {
916
+ return JSON.parse(await fs.readFile(filePath, "utf8"))
917
+ }
918
+
919
+ async function readJsonForUpdate(filePath) {
920
+ const source = await readTextForUpdate(filePath)
921
+ return source === null ? null : JSON.parse(source)
922
+ }
923
+
924
+ async function readTextForUpdate(filePath) {
925
+ const source = await readFileForUpdate(filePath)
926
+ return source === null ? null : source.toString("utf8")
927
+ }
928
+
929
+ function assertManagedFileSafe(current, nextContent, target, options) {
930
+ if (options.dryRun || options.force || current === null) return
931
+
932
+ const next = Buffer.isBuffer(nextContent)
933
+ ? nextContent
934
+ : Buffer.from(nextContent, "utf8")
935
+ if (current.equals(next)) return
936
+
937
+ const expectedHash = findManagedFileHash(options.receipt, target)
938
+ const currentHash = hashContent(current)
939
+ if (expectedHash && currentHash === expectedHash) return
940
+
941
+ const owner = options.owner ? ` (${options.owner})` : ""
942
+ const reason = expectedHash
943
+ ? "has local changes since Banhaten installed it"
944
+ : "already exists without a Banhaten ownership receipt"
945
+ const diffCommand = ["banhaten", "diff", options.owner === "base" ? "" : options.owner]
946
+ .filter(Boolean)
947
+ .join(" ")
948
+ throw new Error(
949
+ `${target}${owner} ${reason}. Run \`${diffCommand}\` to inspect the registry version, ` +
950
+ "or re-run the command with `--force` to replace the file."
951
+ )
952
+ }
953
+
954
+ function findManagedFileHash(receipt, target) {
955
+ const normalizedTarget = normalizeReceiptTarget(target)
956
+ const direct = Object.entries(receipt?.managedFiles || {}).find(
957
+ ([recordedTarget]) =>
958
+ normalizeReceiptTarget(recordedTarget) === normalizedTarget
959
+ )?.[1]?.sha256
960
+ if (direct) return direct
961
+
962
+ for (const component of Object.values(receipt?.components || {})) {
963
+ const match = component.files?.find(
964
+ (file) => normalizeReceiptTarget(file.target) === normalizedTarget
965
+ )
966
+ if (match?.sha256) return match.sha256
967
+ }
968
+
969
+ return null
970
+ }
971
+
972
+ function hashContent(content) {
973
+ return createHash("sha256").update(content).digest("hex")
974
+ }
975
+
976
+ function hashNormalizedText(content) {
977
+ return hashContent(String(content).replace(/\r\n/g, "\n").trim())
978
+ }
979
+
980
+ async function exists(filePath) {
981
+ try {
982
+ await fs.access(filePath)
983
+ return true
984
+ } catch {
985
+ return false
986
+ }
987
+ }
988
+
989
+ function appendAliasSegment(alias, segment) {
990
+ if (!alias) return null
991
+ return `${alias.replace(/\/$/, "")}/${segment}`
992
+ }
993
+
994
+ function sortObject(value) {
995
+ return Object.fromEntries(
996
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right))
997
+ )
998
+ }
999
+
1000
+ function relative(cwd, targetPath) {
1001
+ return path.relative(cwd, targetPath).replaceAll("\\", "/")
1002
+ }