designmockdown 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/README.zh-CN.md +129 -0
  4. package/dist/app/assets/index-CmugGtLS.js +15 -0
  5. package/dist/app/assets/index-CwhgxL4e.css +1 -0
  6. package/dist/app/index.html +13 -0
  7. package/dist/lib/cli.d.ts +11 -0
  8. package/dist/lib/cli.d.ts.map +1 -0
  9. package/dist/lib/cli.js +968 -0
  10. package/dist/lib/cli.js.map +1 -0
  11. package/dist/lib/collab/client.d.ts +20 -0
  12. package/dist/lib/collab/client.d.ts.map +1 -0
  13. package/dist/lib/collab/client.js +126 -0
  14. package/dist/lib/collab/client.js.map +1 -0
  15. package/dist/lib/collab/index.d.ts +40 -0
  16. package/dist/lib/collab/index.d.ts.map +1 -0
  17. package/dist/lib/collab/index.js +154 -0
  18. package/dist/lib/collab/index.js.map +1 -0
  19. package/dist/lib/collab/room.d.ts +111 -0
  20. package/dist/lib/collab/room.d.ts.map +1 -0
  21. package/dist/lib/collab/room.js +120 -0
  22. package/dist/lib/collab/room.js.map +1 -0
  23. package/dist/lib/collab/ws.d.ts +33 -0
  24. package/dist/lib/collab/ws.d.ts.map +1 -0
  25. package/dist/lib/collab/ws.js +191 -0
  26. package/dist/lib/collab/ws.js.map +1 -0
  27. package/dist/lib/components/basic.d.ts +8 -0
  28. package/dist/lib/components/basic.d.ts.map +1 -0
  29. package/dist/lib/components/basic.js +181 -0
  30. package/dist/lib/components/basic.js.map +1 -0
  31. package/dist/lib/components/config.d.ts +26 -0
  32. package/dist/lib/components/config.d.ts.map +1 -0
  33. package/dist/lib/components/config.js +94 -0
  34. package/dist/lib/components/config.js.map +1 -0
  35. package/dist/lib/components/containers.d.ts +9 -0
  36. package/dist/lib/components/containers.d.ts.map +1 -0
  37. package/dist/lib/components/containers.js +102 -0
  38. package/dist/lib/components/containers.js.map +1 -0
  39. package/dist/lib/components/controls.d.ts +8 -0
  40. package/dist/lib/components/controls.d.ts.map +1 -0
  41. package/dist/lib/components/controls.js +376 -0
  42. package/dist/lib/components/controls.js.map +1 -0
  43. package/dist/lib/components/data.d.ts +8 -0
  44. package/dist/lib/components/data.d.ts.map +1 -0
  45. package/dist/lib/components/data.js +494 -0
  46. package/dist/lib/components/data.js.map +1 -0
  47. package/dist/lib/components/feedback.d.ts +8 -0
  48. package/dist/lib/components/feedback.d.ts.map +1 -0
  49. package/dist/lib/components/feedback.js +151 -0
  50. package/dist/lib/components/feedback.js.map +1 -0
  51. package/dist/lib/components/icons.d.ts +28 -0
  52. package/dist/lib/components/icons.d.ts.map +1 -0
  53. package/dist/lib/components/icons.js +85 -0
  54. package/dist/lib/components/icons.js.map +1 -0
  55. package/dist/lib/components/layout.d.ts +10 -0
  56. package/dist/lib/components/layout.d.ts.map +1 -0
  57. package/dist/lib/components/layout.js +82 -0
  58. package/dist/lib/components/layout.js.map +1 -0
  59. package/dist/lib/components/nav.d.ts +8 -0
  60. package/dist/lib/components/nav.d.ts.map +1 -0
  61. package/dist/lib/components/nav.js +216 -0
  62. package/dist/lib/components/nav.js.map +1 -0
  63. package/dist/lib/components/plugin.d.ts +27 -0
  64. package/dist/lib/components/plugin.d.ts.map +1 -0
  65. package/dist/lib/components/plugin.js +152 -0
  66. package/dist/lib/components/plugin.js.map +1 -0
  67. package/dist/lib/components/registry.d.ts +111 -0
  68. package/dist/lib/components/registry.d.ts.map +1 -0
  69. package/dist/lib/components/registry.js +375 -0
  70. package/dist/lib/components/registry.js.map +1 -0
  71. package/dist/lib/components/types.d.ts +111 -0
  72. package/dist/lib/components/types.d.ts.map +1 -0
  73. package/dist/lib/components/types.js +6 -0
  74. package/dist/lib/components/types.js.map +1 -0
  75. package/dist/lib/core/anim.d.ts +31 -0
  76. package/dist/lib/core/anim.d.ts.map +1 -0
  77. package/dist/lib/core/anim.js +95 -0
  78. package/dist/lib/core/anim.js.map +1 -0
  79. package/dist/lib/core/ast.d.ts +174 -0
  80. package/dist/lib/core/ast.d.ts.map +1 -0
  81. package/dist/lib/core/ast.js +42 -0
  82. package/dist/lib/core/ast.js.map +1 -0
  83. package/dist/lib/core/chart-source.d.ts +37 -0
  84. package/dist/lib/core/chart-source.d.ts.map +1 -0
  85. package/dist/lib/core/chart-source.js +125 -0
  86. package/dist/lib/core/chart-source.js.map +1 -0
  87. package/dist/lib/core/data.d.ts +32 -0
  88. package/dist/lib/core/data.d.ts.map +1 -0
  89. package/dist/lib/core/data.js +150 -0
  90. package/dist/lib/core/data.js.map +1 -0
  91. package/dist/lib/core/define.d.ts +16 -0
  92. package/dist/lib/core/define.d.ts.map +1 -0
  93. package/dist/lib/core/define.js +232 -0
  94. package/dist/lib/core/define.js.map +1 -0
  95. package/dist/lib/core/diagnostics.d.ts +64 -0
  96. package/dist/lib/core/diagnostics.d.ts.map +1 -0
  97. package/dist/lib/core/diagnostics.js +62 -0
  98. package/dist/lib/core/diagnostics.js.map +1 -0
  99. package/dist/lib/core/errors.d.ts +27 -0
  100. package/dist/lib/core/errors.d.ts.map +1 -0
  101. package/dist/lib/core/errors.js +70 -0
  102. package/dist/lib/core/errors.js.map +1 -0
  103. package/dist/lib/core/expand.d.ts +21 -0
  104. package/dist/lib/core/expand.d.ts.map +1 -0
  105. package/dist/lib/core/expand.js +226 -0
  106. package/dist/lib/core/expand.js.map +1 -0
  107. package/dist/lib/core/expr.d.ts +29 -0
  108. package/dist/lib/core/expr.d.ts.map +1 -0
  109. package/dist/lib/core/expr.js +313 -0
  110. package/dist/lib/core/expr.js.map +1 -0
  111. package/dist/lib/core/format.d.ts +30 -0
  112. package/dist/lib/core/format.d.ts.map +1 -0
  113. package/dist/lib/core/format.js +106 -0
  114. package/dist/lib/core/format.js.map +1 -0
  115. package/dist/lib/core/lexer.d.ts +54 -0
  116. package/dist/lib/core/lexer.d.ts.map +1 -0
  117. package/dist/lib/core/lexer.js +311 -0
  118. package/dist/lib/core/lexer.js.map +1 -0
  119. package/dist/lib/core/parser.d.ts +29 -0
  120. package/dist/lib/core/parser.d.ts.map +1 -0
  121. package/dist/lib/core/parser.js +674 -0
  122. package/dist/lib/core/parser.js.map +1 -0
  123. package/dist/lib/core/resolver.d.ts +37 -0
  124. package/dist/lib/core/resolver.d.ts.map +1 -0
  125. package/dist/lib/core/resolver.js +240 -0
  126. package/dist/lib/core/resolver.js.map +1 -0
  127. package/dist/lib/core/spec.d.ts +87 -0
  128. package/dist/lib/core/spec.d.ts.map +1 -0
  129. package/dist/lib/core/spec.js +207 -0
  130. package/dist/lib/core/spec.js.map +1 -0
  131. package/dist/lib/core/state.d.ts +19 -0
  132. package/dist/lib/core/state.d.ts.map +1 -0
  133. package/dist/lib/core/state.js +64 -0
  134. package/dist/lib/core/state.js.map +1 -0
  135. package/dist/lib/core/tokens.d.ts +36 -0
  136. package/dist/lib/core/tokens.d.ts.map +1 -0
  137. package/dist/lib/core/tokens.js +198 -0
  138. package/dist/lib/core/tokens.js.map +1 -0
  139. package/dist/lib/export/pages.d.ts +39 -0
  140. package/dist/lib/export/pages.d.ts.map +1 -0
  141. package/dist/lib/export/pages.js +95 -0
  142. package/dist/lib/export/pages.js.map +1 -0
  143. package/dist/lib/export/raster.d.ts +39 -0
  144. package/dist/lib/export/raster.d.ts.map +1 -0
  145. package/dist/lib/export/raster.js +152 -0
  146. package/dist/lib/export/raster.js.map +1 -0
  147. package/dist/lib/index.d.ts +33 -0
  148. package/dist/lib/index.d.ts.map +1 -0
  149. package/dist/lib/index.js +30 -0
  150. package/dist/lib/index.js.map +1 -0
  151. package/dist/lib/layout/engine.d.ts +32 -0
  152. package/dist/lib/layout/engine.d.ts.map +1 -0
  153. package/dist/lib/layout/engine.js +1063 -0
  154. package/dist/lib/layout/engine.js.map +1 -0
  155. package/dist/lib/layout/measure.d.ts +30 -0
  156. package/dist/lib/layout/measure.d.ts.map +1 -0
  157. package/dist/lib/layout/measure.js +148 -0
  158. package/dist/lib/layout/measure.js.map +1 -0
  159. package/dist/lib/layout/types.d.ts +94 -0
  160. package/dist/lib/layout/types.d.ts.map +1 -0
  161. package/dist/lib/layout/types.js +16 -0
  162. package/dist/lib/layout/types.js.map +1 -0
  163. package/dist/lib/lsp/server.d.ts +76 -0
  164. package/dist/lib/lsp/server.d.ts.map +1 -0
  165. package/dist/lib/lsp/server.js +264 -0
  166. package/dist/lib/lsp/server.js.map +1 -0
  167. package/dist/lib/output/docs.d.ts +26 -0
  168. package/dist/lib/output/docs.d.ts.map +1 -0
  169. package/dist/lib/output/docs.js +231 -0
  170. package/dist/lib/output/docs.js.map +1 -0
  171. package/dist/lib/output/ir.d.ts +105 -0
  172. package/dist/lib/output/ir.d.ts.map +1 -0
  173. package/dist/lib/output/ir.js +89 -0
  174. package/dist/lib/output/ir.js.map +1 -0
  175. package/dist/lib/output/schema.d.ts +69 -0
  176. package/dist/lib/output/schema.d.ts.map +1 -0
  177. package/dist/lib/output/schema.js +84 -0
  178. package/dist/lib/output/schema.js.map +1 -0
  179. package/dist/lib/paths.d.ts +12 -0
  180. package/dist/lib/paths.d.ts.map +1 -0
  181. package/dist/lib/paths.js +27 -0
  182. package/dist/lib/paths.js.map +1 -0
  183. package/dist/lib/playground/examples.d.ts +16 -0
  184. package/dist/lib/playground/examples.d.ts.map +1 -0
  185. package/dist/lib/playground/examples.js +515 -0
  186. package/dist/lib/playground/examples.js.map +1 -0
  187. package/dist/lib/playground/index.d.ts +51 -0
  188. package/dist/lib/playground/index.d.ts.map +1 -0
  189. package/dist/lib/playground/index.js +598 -0
  190. package/dist/lib/playground/index.js.map +1 -0
  191. package/dist/lib/render/assets.d.ts +35 -0
  192. package/dist/lib/render/assets.d.ts.map +1 -0
  193. package/dist/lib/render/assets.js +114 -0
  194. package/dist/lib/render/assets.js.map +1 -0
  195. package/dist/lib/render/backends.d.ts +31 -0
  196. package/dist/lib/render/backends.d.ts.map +1 -0
  197. package/dist/lib/render/backends.js +57 -0
  198. package/dist/lib/render/backends.js.map +1 -0
  199. package/dist/lib/render/css.d.ts +24 -0
  200. package/dist/lib/render/css.d.ts.map +1 -0
  201. package/dist/lib/render/css.js +148 -0
  202. package/dist/lib/render/css.js.map +1 -0
  203. package/dist/lib/render/document-html.d.ts +28 -0
  204. package/dist/lib/render/document-html.d.ts.map +1 -0
  205. package/dist/lib/render/document-html.js +214 -0
  206. package/dist/lib/render/document-html.js.map +1 -0
  207. package/dist/lib/render/dom.d.ts +32 -0
  208. package/dist/lib/render/dom.d.ts.map +1 -0
  209. package/dist/lib/render/dom.js +531 -0
  210. package/dist/lib/render/dom.js.map +1 -0
  211. package/dist/lib/render/primitives.d.ts +81 -0
  212. package/dist/lib/render/primitives.d.ts.map +1 -0
  213. package/dist/lib/render/primitives.js +172 -0
  214. package/dist/lib/render/primitives.js.map +1 -0
  215. package/dist/lib/render/react.d.ts +23 -0
  216. package/dist/lib/render/react.d.ts.map +1 -0
  217. package/dist/lib/render/react.js +447 -0
  218. package/dist/lib/render/react.js.map +1 -0
  219. package/dist/lib/render/svg.d.ts +45 -0
  220. package/dist/lib/render/svg.d.ts.map +1 -0
  221. package/dist/lib/render/svg.js +179 -0
  222. package/dist/lib/render/svg.js.map +1 -0
  223. package/dist/lib/runtime/proto.d.ts +19 -0
  224. package/dist/lib/runtime/proto.d.ts.map +1 -0
  225. package/dist/lib/runtime/proto.js +81 -0
  226. package/dist/lib/runtime/proto.js.map +1 -0
  227. package/dist/lib/skill/install.d.ts +28 -0
  228. package/dist/lib/skill/install.d.ts.map +1 -0
  229. package/dist/lib/skill/install.js +89 -0
  230. package/dist/lib/skill/install.js.map +1 -0
  231. package/dist/lib/workbench/app.d.ts +24 -0
  232. package/dist/lib/workbench/app.d.ts.map +1 -0
  233. package/dist/lib/workbench/app.js +45 -0
  234. package/dist/lib/workbench/app.js.map +1 -0
  235. package/dist/lib/workbench/assets.d.ts +21 -0
  236. package/dist/lib/workbench/assets.d.ts.map +1 -0
  237. package/dist/lib/workbench/assets.js +44 -0
  238. package/dist/lib/workbench/assets.js.map +1 -0
  239. package/dist/lib/workbench/client.d.ts +18 -0
  240. package/dist/lib/workbench/client.d.ts.map +1 -0
  241. package/dist/lib/workbench/client.js +736 -0
  242. package/dist/lib/workbench/client.js.map +1 -0
  243. package/dist/lib/workbench/drag.d.ts +90 -0
  244. package/dist/lib/workbench/drag.d.ts.map +1 -0
  245. package/dist/lib/workbench/drag.js +109 -0
  246. package/dist/lib/workbench/drag.js.map +1 -0
  247. package/dist/lib/workbench/geometry.d.ts +28 -0
  248. package/dist/lib/workbench/geometry.d.ts.map +1 -0
  249. package/dist/lib/workbench/geometry.js +28 -0
  250. package/dist/lib/workbench/geometry.js.map +1 -0
  251. package/dist/lib/workbench/select.d.ts +56 -0
  252. package/dist/lib/workbench/select.d.ts.map +1 -0
  253. package/dist/lib/workbench/select.js +111 -0
  254. package/dist/lib/workbench/select.js.map +1 -0
  255. package/dist/lib/workbench/server.d.ts +223 -0
  256. package/dist/lib/workbench/server.d.ts.map +1 -0
  257. package/dist/lib/workbench/server.js +576 -0
  258. package/dist/lib/workbench/server.js.map +1 -0
  259. package/dist/lib/workbench/source.d.ts +124 -0
  260. package/dist/lib/workbench/source.d.ts.map +1 -0
  261. package/dist/lib/workbench/source.js +405 -0
  262. package/dist/lib/workbench/source.js.map +1 -0
  263. package/docs/README.md +49 -0
  264. package/docs/cheatsheet.md +243 -0
  265. package/docs/cli.md +95 -0
  266. package/docs/data.md +112 -0
  267. package/docs/export.md +106 -0
  268. package/docs/getting-started.md +105 -0
  269. package/docs/language.md +136 -0
  270. package/docs/layout.md +159 -0
  271. package/docs/plugins.md +82 -0
  272. package/docs/reference.md +1156 -0
  273. package/docs/roadmap.md +54 -0
  274. package/docs/syntax.md +312 -0
  275. package/docs/workbench.md +125 -0
  276. package/examples/app.dm +76 -0
  277. package/examples/assets/avatar.png +0 -0
  278. package/examples/assets/cover.png +0 -0
  279. package/examples/assets/logo.svg +4 -0
  280. package/examples/assets.dm +49 -0
  281. package/examples/dashboard.dm +64 -0
  282. package/examples/data.dm +107 -0
  283. package/examples/layout.dm +93 -0
  284. package/examples/login.dm +43 -0
  285. package/examples/login.html +61 -0
  286. package/examples/plugins/rating/README.md +67 -0
  287. package/examples/plugins/rating/example.dm +29 -0
  288. package/examples/plugins/rating/index.ts +122 -0
  289. package/examples/plugins/rating/package.json +22 -0
  290. package/examples/recipe/assets/broccoli.jpg +0 -0
  291. package/examples/recipe/assets/cheesecake.jpg +0 -0
  292. package/examples/recipe/assets/chicken-pot.jpg +0 -0
  293. package/examples/recipe/assets/noodles.jpg +0 -0
  294. package/examples/recipe/assets/shrimp.jpg +0 -0
  295. package/examples/recipe/assets/tomato-beef.jpg +0 -0
  296. package/examples/recipe/detail.dm +105 -0
  297. package/examples/recipe/discover.dm +116 -0
  298. package/examples/recipe/favorites.dm +115 -0
  299. package/examples/recipe/index.dm +124 -0
  300. package/examples/recipe/profile.dm +134 -0
  301. package/examples/recipe/steps.dm +89 -0
  302. package/examples/settings.dm +108 -0
  303. package/package.json +85 -4
  304. package/skills/designmockdown/REFERENCE.md +373 -0
  305. package/skills/designmockdown/SKILL.md +179 -0
@@ -0,0 +1,968 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DesignMockdown CLI。
4
+ *
5
+ * designmockdown check <file.dm> Validate and report errors/warnings
6
+ * designmockdown export <file.dm> [-o out] Export SVG / HTML
7
+ * designmockdown preview <file.dm> [--port] Local preview server
8
+ * designmockdown schema Export the component schema (for LLMs)
9
+ */
10
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'node:fs';
11
+ import { resolve as pathResolve, dirname, basename, extname, join as pathJoin } from 'node:path';
12
+ import { spawn } from 'node:child_process';
13
+ import { parseDocument } from "./core/parser.js";
14
+ import { resolve } from "./core/resolver.js";
15
+ import { renderSvg } from "./render/svg.js";
16
+ import { renderDocumentHtml } from "./render/document-html.js";
17
+ import { renderDomPage } from "./render/dom.js";
18
+ import { emitReact } from "./render/react.js";
19
+ import { rasterize, NoConverterError } from "./export/raster.js";
20
+ import { exportDomPages, exportReactPages } from "./export/pages.js";
21
+ import { pickBackend, isRasterFlag } from "./render/backends.js";
22
+ import { createPlayground, PLAYGROUND_EXAMPLES } from "./playground/index.js";
23
+ import { clearAssetCache } from "./render/assets.js";
24
+ import { DesignMockdownError } from "./core/errors.js";
25
+ import { errorToDiagnostic } from "./core/diagnostics.js";
26
+ import { formatSource } from "./core/format.js";
27
+ import { documentToIr, pageToIr } from "./output/ir.js";
28
+ import { buildSchema, schemaMarkdown } from "./output/schema.js";
29
+ import { REFERENCE_PATH, SKILL_REFERENCE_PATH, renderReference, renderSkillReference } from "./output/docs.js";
30
+ import { defaultSkillsDir, installSkill, skillDir } from "./skill/install.js";
31
+ import { packageRootOf } from "./paths.js";
32
+ import { PRESET_THEMES } from "./core/tokens.js";
33
+ import { createWorkbench } from "./workbench/server.js";
34
+ import { hasEditor } from "./workbench/assets.js";
35
+ import { serveStdio } from "./lsp/server.js";
36
+ import { loadConfig } from "./components/config.js";
37
+ import { loadPlugins } from "./components/plugin.js";
38
+ const USAGE = `DesignMockdown - text as a UI design language
39
+
40
+ Usage:
41
+ designmockdown check <file|dir>... Validate; --json for machine-readable output
42
+ designmockdown fmt <file|dir>... Format in place; --check reports instead of writing
43
+ designmockdown ir <file.dm> [-o out] Export the layout IR as JSON
44
+ designmockdown render <file.dm> [-o out] Export SVG (default) or HTML (--html)
45
+ designmockdown export Alias of render
46
+ designmockdown preview <file.dm> [--port N] Start a local preview server
47
+ designmockdown workbench <file.dm> [--port N]
48
+ Start the design workbench (canvas + source editor)
49
+ designmockdown playground [file.dm] [--port N]
50
+ Type-and-see playground; no file is ever written
51
+ designmockdown build <dir> [-o out/] [--html|--dom|--react]
52
+ Batch-export every .dm in a directory
53
+ designmockdown schema [--format json|markdown]
54
+ Export the component schema (JSON by default, for LLMs)
55
+ designmockdown docs [--check]
56
+ Regenerate docs/reference.md and the skill reference
57
+ designmockdown skill [install] [--project|--dir <path>] [--link]
58
+ Print the bundled skill path, or install it for an agent
59
+ designmockdown lsp
60
+ Language server on stdio (diagnostics + completion)
61
+
62
+ Alias:
63
+ dmd <command> ... The same binary, three letters shorter
64
+
65
+ Options:
66
+ -o, --output <path> Output file path (a directory when a multi-page file has several pages)
67
+ --theme <name> Override the theme (${Object.keys(PRESET_THEMES).join(' / ')})
68
+ --html Export interactive HTML instead of plain SVG
69
+ --dom Export semantic HTML + flexbox (inspectable, not pixel-identical to SVG)
70
+ --react Export a .tsx module (inline styles, not pixel-identical to SVG)
71
+ --dom / --react write one page module per page plus an index when the file has
72
+ more than one @page
73
+ --state <name> Render an interaction state declared with @state (e.g. hover)
74
+ --page <name> Pick one page by name, key or 1-based index
75
+ --json Machine-readable output (check)
76
+ --quiet Only the exit code (check)
77
+ --max-warnings <n> Exit 1 when there are more warnings than n (check)
78
+ --check Report instead of writing (fmt, docs)
79
+ --format <name> Output format (schema: json / markdown)
80
+ --components <p> Load a component plugin: a path, a glob, or a package name (repeatable)
81
+ --no-config Ignore designmockdown.config.* found above the working directory
82
+ --collab Enable live collaboration (presence + document sync) in preview
83
+ --png Export PNG (needs rsvg-convert / inkscape / magick / cairosvg on PATH)
84
+ --pdf Export PDF (needs rsvg-convert / inkscape / cairosvg on PATH)
85
+ --port <n> Preview port (default 5173); workbench 5879; playground 5880
86
+ --no-open Do not open the browser automatically
87
+ --project Install into .lingxi/skills of the current directory (skill)
88
+ --dir <path> Install into an explicit skills directory (skill)
89
+ --link Link instead of copy, so edits in the repo take effect (skill)
90
+ -v, --version Print the version
91
+ -h, --help Show this help
92
+ `;
93
+ /**
94
+ * The version npm installed.
95
+ *
96
+ * Read from the package root instead of a literal: `src/cli.ts` and `dist/lib/cli.js` are the same
97
+ * command, and a hardcoded string drifts the first time someone bumps the version.
98
+ */
99
+ function packageVersion() {
100
+ const file = pathJoin(packageRootOf(import.meta.url), 'package.json');
101
+ return JSON.parse(readFileSync(file, 'utf8')).version;
102
+ }
103
+ function fail(msg, hint, exitCode = 1) {
104
+ process.stderr.write(`\n✗ ${msg}\n`);
105
+ if (hint)
106
+ process.stderr.write(` → ${hint}\n`);
107
+ process.stderr.write('\n');
108
+ process.exit(exitCode);
109
+ }
110
+ function readSource(file) {
111
+ if (!existsSync(file))
112
+ fail(`file not found: ${file}`, 'check that the path is correct');
113
+ return readFileSync(file, 'utf8');
114
+ }
115
+ function parseArgs(argv) {
116
+ // A leading -h/--help must not be mistaken for a command name: `designmockdown --help` used to fall
117
+ // through to "unknown command" because the first argv slot is read as the command
118
+ const [first = 'help', ...rest] = argv;
119
+ const cmd = first === '-h' || first === '--help' ? 'help' : first;
120
+ const opts = {};
121
+ const files = [];
122
+ const components = [];
123
+ let noConfig = false;
124
+ for (let i = 0; i < rest.length; i++) {
125
+ const a = rest[i];
126
+ if (a === '-o' || a === '--output') {
127
+ opts.output = rest[++i] ?? '';
128
+ }
129
+ else if (a === '--components') {
130
+ const value = rest[++i];
131
+ if (value)
132
+ components.push(value);
133
+ }
134
+ else if (a === '--no-config') {
135
+ noConfig = true;
136
+ }
137
+ else if (a === '--theme' ||
138
+ a === '--port' ||
139
+ a === '--state' ||
140
+ a === '--page' ||
141
+ a === '--format' ||
142
+ a === '--dir' ||
143
+ a === '--max-warnings') {
144
+ opts[a.slice(2)] = rest[++i] ?? '';
145
+ }
146
+ else if (a === '--html' ||
147
+ a === '--dom' ||
148
+ a === '--react' ||
149
+ a === '--collab' ||
150
+ a === '--png' ||
151
+ a === '--pdf' ||
152
+ a === '--json' ||
153
+ a === '--quiet' ||
154
+ a === '--check' ||
155
+ a === '--no-open' ||
156
+ a === '--project' ||
157
+ a === '--link' ||
158
+ a === '--version' ||
159
+ a === '--help') {
160
+ opts[a.slice(2)] = true;
161
+ }
162
+ else if (a.startsWith('--') && a.includes('=')) {
163
+ // `--format=markdown` is what people type; splitting on the first = keeps values that
164
+ // contain = themselves (a regex, a URL) intact
165
+ const eq = a.indexOf('=');
166
+ // `--components=x` and `--components x` must land in the same place
167
+ if (a.slice(2, eq) === 'components')
168
+ components.push(a.slice(eq + 1));
169
+ else
170
+ opts[a.slice(2, eq)] = a.slice(eq + 1);
171
+ }
172
+ else if (a === '-h') {
173
+ opts.help = true;
174
+ }
175
+ else if (a === '-v') {
176
+ opts.version = true;
177
+ }
178
+ else if (!a.startsWith('-')) {
179
+ files.push(a);
180
+ }
181
+ }
182
+ // `file` stays first for the single-file commands; check / fmt read the whole list
183
+ const file = files[0];
184
+ return { cmd, file, files, opts, components, noConfig };
185
+ }
186
+ /**
187
+ * Parse a document and render every page.
188
+ *
189
+ * key / x / y are read before resolve(): resolve rewrites the tree during expansion, and the
190
+ * canvas position is a parser fact that must survive that rewrite.
191
+ */
192
+ function parseAndRender(file, source, themeOverride, interactive = false, state) {
193
+ const doc = parseDocument(source, basename(file));
194
+ const baseDir = dirname(pathResolve(file));
195
+ const pages = doc.pages.map((page) => {
196
+ const key = page.key ?? page.title;
197
+ const x = page.x;
198
+ const y = page.y;
199
+ const result = resolve(page, { state });
200
+ const theme = themeOverride
201
+ ? { ...result.theme, name: themeOverride, tokens: { ...PRESET_THEMES[themeOverride] ?? result.theme.tokens } }
202
+ : result.theme;
203
+ // interactive must reach renderSvg, not just the HTML shell: the runtime script looks for
204
+ // data-mk-onclick hooks that only the SVG renderer emits
205
+ const svg = renderSvg(result.page, theme, result.canvas, { withTitle: true, interactive, baseDir });
206
+ return { key, title: page.title, x, y, node: result.page, canvas: result.canvas, theme, svg, warnings: result.warnings };
207
+ });
208
+ return { doc, pages };
209
+ }
210
+ /** Select a page by 1-based index, key or title */
211
+ function pickPage(pages, name) {
212
+ const n = Number(name);
213
+ if (Number.isInteger(n) && n >= 1 && n <= pages.length)
214
+ return pages[n - 1];
215
+ return pages.find((p) => p.key === name || p.title === name);
216
+ }
217
+ function toDocumentPage(p) {
218
+ return { key: p.key, title: p.title, x: p.x, y: p.y, width: p.canvas.width, height: p.canvas.height, svg: p.svg };
219
+ }
220
+ /** A page key safe to use in a filename */
221
+ function safeName(key) {
222
+ return key.replace(/[\\/:*?"<>|\s]+/g, '-').replace(/^-+|-+$/g, '') || 'page';
223
+ }
224
+ /** Directories that never hold hand-written design files */
225
+ const SKIP_DIRS = new Set(['node_modules', 'dist', '.git', '.run']);
226
+ /**
227
+ * Expand a file or directory argument into the .dm files it names.
228
+ *
229
+ * Recursive on purpose: `designmockdown check examples/` should cover `examples/recipe/` too, and a
230
+ * silently-partial check is worse than a slow one - it reports OK for the files it never read.
231
+ */
232
+ function collectDmFiles(target) {
233
+ if (!existsSync(target))
234
+ fail(`file not found: ${target}`, 'check that the path is correct');
235
+ const info = statSync(target);
236
+ if (info.isFile())
237
+ return [target];
238
+ const out = [];
239
+ const walk = (dir) => {
240
+ const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
241
+ for (const entry of entries) {
242
+ if (entry.name.startsWith('.') || SKIP_DIRS.has(entry.name))
243
+ continue;
244
+ const full = pathResolve(dir, entry.name);
245
+ if (entry.isDirectory())
246
+ walk(full);
247
+ else if (entry.name.endsWith('.dm'))
248
+ out.push(full);
249
+ }
250
+ };
251
+ walk(target);
252
+ return out;
253
+ }
254
+ /**
255
+ * Validate one file without throwing.
256
+ *
257
+ * A page that fails to resolve must not hide the pages after it: the whole point of `check` is to
258
+ * hand an editor or an LLM the complete list of things to fix, not the first one.
259
+ */
260
+ function checkFile(file) {
261
+ const source = readFileSync(file, 'utf8');
262
+ let doc;
263
+ try {
264
+ doc = parseDocument(source, basename(file));
265
+ }
266
+ catch (e) {
267
+ if (!(e instanceof DesignMockdownError))
268
+ throw e;
269
+ return { file, ok: false, pages: [], diagnostics: [errorToDiagnostic(e)] };
270
+ }
271
+ const pages = [];
272
+ const diagnostics = [];
273
+ for (const page of doc.pages) {
274
+ try {
275
+ const result = resolve(page);
276
+ pages.push({
277
+ title: page.title,
278
+ line: page.startLine ?? 1,
279
+ canvas: `${result.canvas.width} x ${result.canvas.height} (${page.meta.canvas ?? 'custom'})`,
280
+ theme: result.theme.name,
281
+ nodes: countNodes(page),
282
+ warnings: result.warnings,
283
+ diagnostics: result.diagnostics,
284
+ });
285
+ }
286
+ catch (e) {
287
+ if (!(e instanceof DesignMockdownError))
288
+ throw e;
289
+ diagnostics.push(errorToDiagnostic(e, page.title));
290
+ }
291
+ }
292
+ return { file, ok: diagnostics.length === 0, pages, diagnostics };
293
+ }
294
+ function printCheckResult(result, quiet) {
295
+ if (quiet)
296
+ return;
297
+ const name = basename(result.file);
298
+ if (!result.ok) {
299
+ for (const d of result.diagnostics) {
300
+ const where = d.pos ? ` (line ${d.pos.line})` : '';
301
+ process.stderr.write(`\n✗ ${name}${d.page ? ` [${d.page}]` : ''}: ${d.message}${where}\n`);
302
+ if (d.hint)
303
+ process.stderr.write(` → ${d.hint}\n`);
304
+ }
305
+ return;
306
+ }
307
+ process.stdout.write(`\nOK ${name} parsed (${result.pages.length} page${result.pages.length === 1 ? '' : 's'})\n`);
308
+ let totalWarnings = 0;
309
+ for (const page of result.pages) {
310
+ totalWarnings += page.warnings.length;
311
+ process.stdout.write(` Page: ${page.title} (line ${page.line})\n`);
312
+ process.stdout.write(` Canvas: ${page.canvas}\n`);
313
+ process.stdout.write(` Theme: ${page.theme}\n`);
314
+ process.stdout.write(` Nodes: ${page.nodes}\n`);
315
+ for (const w of page.warnings)
316
+ process.stdout.write(` WARN ${w}\n`);
317
+ }
318
+ process.stdout.write(` Warnings: ${totalWarnings}\n`);
319
+ }
320
+ function cmdCheck(targets, opts) {
321
+ if (targets.length === 0)
322
+ fail('check needs a .dm file or directory', 'designmockdown check login.dm', 2);
323
+ const files = [...new Set(targets.flatMap((t) => collectDmFiles(t)).map((f) => pathResolve(f)))];
324
+ if (files.length === 0)
325
+ fail(`no .dm files in ${targets.join(', ')}`, 'point check at a file or a directory', 2);
326
+ const results = files.map(checkFile);
327
+ const warnings = results.reduce((n, r) => n + r.pages.reduce((m, p) => m + p.warnings.length, 0), 0);
328
+ const errors = results.reduce((n, r) => n + r.diagnostics.length, 0);
329
+ const quiet = opts.quiet === true;
330
+ const asJson = opts.json === true;
331
+ if (asJson) {
332
+ const payload = {
333
+ ok: errors === 0,
334
+ files: results.map((r) => ({
335
+ file: r.file,
336
+ ok: r.ok,
337
+ pages: r.pages,
338
+ diagnostics: r.diagnostics,
339
+ })),
340
+ summary: { files: results.length, pages: results.reduce((n, r) => n + r.pages.length, 0), errors, warnings },
341
+ };
342
+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
343
+ }
344
+ else {
345
+ for (const result of results)
346
+ printCheckResult(result, quiet);
347
+ if (!quiet) {
348
+ if (results.length > 1)
349
+ process.stdout.write(` Checked ${results.length} files - ${errors} error(s), ${warnings} warning(s)\n`);
350
+ process.stdout.write('\n');
351
+ }
352
+ }
353
+ if (errors > 0)
354
+ process.exitCode = 1;
355
+ // --max-warnings turns "the design is technically valid but suspicious" into a failing gate
356
+ const max = typeof opts['max-warnings'] === 'string' ? Number(opts['max-warnings']) : NaN;
357
+ if (Number.isFinite(max) && warnings > max)
358
+ process.exitCode = 1;
359
+ }
360
+ function countNodes(page) {
361
+ let n = 0;
362
+ const visit = (node) => {
363
+ n++;
364
+ for (const c of node.children ?? [])
365
+ visit(c);
366
+ for (const list of Object.values(node.slots ?? {}))
367
+ for (const c of list)
368
+ visit(c);
369
+ };
370
+ visit(page);
371
+ return n;
372
+ }
373
+ function cmdExport(file, opts) {
374
+ const source = readSource(file);
375
+ const themeOverride = typeof opts.theme === 'string' ? opts.theme : undefined;
376
+ const state = typeof opts.state === 'string' && opts.state ? opts.state : undefined;
377
+ const { doc, pages } = parseAndRender(file, source, themeOverride, false, state);
378
+ const pageName = typeof opts.page === 'string' && opts.page ? opts.page : undefined;
379
+ const chosen = pageName ? pickPage(pages, pageName) : undefined;
380
+ if (pageName && !chosen) {
381
+ fail(`no page named "${pageName}"`, `pages: ${pages.map((p) => p.key).join(', ')}`);
382
+ }
383
+ // The flag set picks one backend from the registry; --png / --pdf are raster post-steps over
384
+ // the SVG output, not backends (see src/export/raster.ts)
385
+ const backend = pickBackend(opts);
386
+ const raster = isRasterFlag(opts);
387
+ const asDom = backend.name === 'dom';
388
+ const asReact = backend.name === 'react';
389
+ const asHtml = backend.name === 'html' || asDom;
390
+ const ext = raster ?? backend.ext;
391
+ const base = basename(file, extname(file));
392
+ const outPath = typeof opts.output === 'string' && opts.output
393
+ ? pathResolve(opts.output)
394
+ : pathResolve(dirname(file), `${base}.${ext}`);
395
+ const targets = chosen ? [chosen] : pages;
396
+ const multi = targets.length > 1;
397
+ const warnings = targets.reduce((n, p) => n + p.warnings.length, 0);
398
+ // --dom and --react emit one module per page; a multi-page file becomes a directory of pages
399
+ // plus an index (see src/export/pages.ts). Single-page files keep the old single-file output.
400
+ if (raster) {
401
+ // Rasterising needs a converter on PATH. A missing one is a hard error with the install
402
+ // command, not a silent empty file the user finds out about later.
403
+ if (multi && typeof opts.output === 'string' && opts.output && extname(outPath) !== '') {
404
+ fail('with multiple pages -o must be a directory', 'add --page <name> to export a single file');
405
+ }
406
+ const outDir = multi ? outPath : dirname(outPath);
407
+ mkdirSync(outDir, { recursive: true });
408
+ for (let i = 0; i < targets.length; i++) {
409
+ const page = targets[i];
410
+ const target = multi ? pathResolve(outDir, `${base}-${i + 1}-${safeName(page.key)}.${ext}`) : outPath;
411
+ try {
412
+ rasterize(page.svg, raster, target);
413
+ }
414
+ catch (e) {
415
+ if (e instanceof NoConverterError) {
416
+ process.stderr.write(`\nERROR ${e.message}\n`);
417
+ process.exitCode = 1;
418
+ return;
419
+ }
420
+ throw e;
421
+ }
422
+ process.stdout.write(`\nOK exported ${target}\n`);
423
+ process.stdout.write(` ${page.title}: ${page.canvas.width} x ${page.canvas.height} - theme ${page.theme.name}\n`);
424
+ }
425
+ process.stdout.write(` backend: ${raster} (rasterised from the SVG output)\n`);
426
+ if (warnings > 0)
427
+ process.stdout.write(` WARN ${warnings} warning(s) - run check for details\n`);
428
+ process.stdout.write('\n');
429
+ return;
430
+ }
431
+ if (asDom || asReact) {
432
+ const baseDir = dirname(pathResolve(file));
433
+ if (!multi) {
434
+ const page = targets[0];
435
+ const content = asReact
436
+ ? emitReact(page.node, page.theme, page.canvas, { baseDir })
437
+ : renderDomPage(page.node, page.theme, page.canvas, { baseDir });
438
+ mkdirSync(dirname(outPath), { recursive: true });
439
+ writeFileSync(outPath, content, 'utf8');
440
+ process.stdout.write(`\nOK exported ${outPath}\n`);
441
+ process.stdout.write(` ${page.title}: ${page.canvas.width} x ${page.canvas.height} - theme ${page.theme.name}\n`);
442
+ process.stdout.write(` backend: ${backend.label}\n\n`);
443
+ return;
444
+ }
445
+ // Multi-page: `-o` names the directory. A file-like path here is a usage error, not a
446
+ // silent overwrite of the first page
447
+ if (typeof opts.output === 'string' && opts.output && extname(outPath) !== '') {
448
+ fail('with multiple pages -o must be a directory', 'add --page <name> to export a single file');
449
+ }
450
+ const outDir = typeof opts.output === 'string' && opts.output ? outPath : pathResolve(dirname(file));
451
+ const result = asReact
452
+ ? exportReactPages(targets, { dir: outDir, base, baseDir })
453
+ : exportDomPages(targets, { dir: outDir, base, baseDir });
454
+ process.stdout.write(`\nOK exported ${targets.length} pages -> ${outDir}\n`);
455
+ for (const f of result.files)
456
+ process.stdout.write(` ${basename(f)}\n`);
457
+ process.stdout.write(` index: ${basename(result.index)}\n`);
458
+ process.stdout.write(` backend: ${backend.label}\n`);
459
+ if (warnings > 0)
460
+ process.stdout.write(` WARN ${warnings} warning(s) - run check for details\n`);
461
+ process.stdout.write('\n');
462
+ return;
463
+ }
464
+ if (asHtml) {
465
+ // Even a single page uses the canvas shell: the sticky-header wrapper is gone for good.
466
+ const html = renderDocumentHtml(targets.map(toDocumentPage), {
467
+ // front-matter `title:` is what the browser tab should say; the file name is the fallback
468
+ title: doc.pages[0]?.meta.title?.trim() || base,
469
+ dark: targets[0].theme.name === 'dark',
470
+ interactive: false,
471
+ });
472
+ mkdirSync(dirname(outPath), { recursive: true });
473
+ writeFileSync(outPath, html, 'utf8');
474
+ process.stdout.write(`\nOK exported ${outPath}\n`);
475
+ process.stdout.write(` ${targets.length} page${multi ? 's' : ''} - ${(html.length / 1024).toFixed(1)} KB\n`);
476
+ if (warnings > 0)
477
+ process.stdout.write(` WARN ${warnings} warning(s) - run check for details\n`);
478
+ process.stdout.write('\n');
479
+ return;
480
+ }
481
+ if (multi && typeof opts.output === 'string' && opts.output && extname(outPath) !== '') {
482
+ fail('with multiple pages -o must be a directory', 'add --page <name> to export a single file');
483
+ }
484
+ const outDir = multi ? outPath : dirname(outPath);
485
+ mkdirSync(outDir, { recursive: true });
486
+ for (let i = 0; i < targets.length; i++) {
487
+ const page = targets[i];
488
+ const target = multi ? pathResolve(outDir, `${base}-${i + 1}-${safeName(page.key)}.${ext}`) : outPath;
489
+ writeFileSync(target, page.svg, 'utf8');
490
+ process.stdout.write(`\nOK exported ${target}\n`);
491
+ process.stdout.write(` ${page.title}: ${page.canvas.width} x ${page.canvas.height} - theme ${page.theme.name} - ${(page.svg.length / 1024).toFixed(1)} KB\n`);
492
+ }
493
+ if (warnings > 0)
494
+ process.stdout.write(` WARN ${warnings} warning(s) - run check for details\n`);
495
+ process.stdout.write('\n');
496
+ }
497
+ function cmdPreview(file, opts) {
498
+ const abs = pathResolve(file);
499
+ const port = typeof opts.port === 'string' ? Number(opts.port) : 5173;
500
+ const themeOverride = typeof opts.theme === 'string' ? opts.theme : undefined;
501
+ // Preview is the same canvas as the workbench, minus the write path: one UI, one mental model.
502
+ // Edits still apply in memory so a review can nudge spacing, but nothing reaches the file.
503
+ const { server } = createWorkbench({
504
+ file: abs,
505
+ port,
506
+ theme: themeOverride,
507
+ allowSave: false,
508
+ // Two reviewers on the same link share one document; the room is the file, not the port
509
+ collab: opts.collab === true,
510
+ });
511
+ server.listen(port, () => {
512
+ const url = `http://localhost:${port}/`;
513
+ process.stdout.write(`\n>> DesignMockdown preview started\n`);
514
+ process.stdout.write(` File: ${abs}\n`);
515
+ process.stdout.write(` URL: ${url}\n`);
516
+ process.stdout.write(` Mode: canvas (edits stay in memory; the file is never written)\n`);
517
+ if (opts.collab === true) {
518
+ process.stdout.write(' Collab: on (presence + document sync; last write wins on conflicts)\n');
519
+ }
520
+ process.stdout.write(` Stop: Ctrl+C\n\n`);
521
+ try {
522
+ spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref();
523
+ }
524
+ catch {
525
+ /* If the browser cannot be opened, the printed URL is enough */
526
+ }
527
+ });
528
+ server.on('error', (e) => {
529
+ if (e.code === 'EADDRINUSE')
530
+ fail(`port ${port} is already in use`, `try another port: --port ${port + 1}`);
531
+ throw e;
532
+ });
533
+ }
534
+ function readSourceSyncSafe(file) {
535
+ if (!existsSync(file))
536
+ fail(`file not found: ${file}`);
537
+ return readFileSync(file, 'utf8');
538
+ }
539
+ /** Default workbench port. Deliberately not the preview port: the two servers can run side by side. */
540
+ const WORKBENCH_PORT = 5879;
541
+ function cmdWorkbench(file, opts) {
542
+ const abs = pathResolve(file);
543
+ if (!existsSync(abs))
544
+ fail(`file not found: ${abs}`, 'check that the path is correct');
545
+ if (extname(abs) !== '.dm')
546
+ fail(`not a .dm file: ${abs}`);
547
+ const port = typeof opts.port === 'string' ? Number(opts.port) : WORKBENCH_PORT;
548
+ const themeOverride = typeof opts.theme === 'string' ? opts.theme : undefined;
549
+ if (!hasEditor()) {
550
+ // The workbench still runs without it - the client falls back to a textarea - but say so rather
551
+ // than letting the user wonder why there is no syntax highlighting.
552
+ process.stdout.write('\n! codemirror is not installed; the editor falls back to a plain textarea\n');
553
+ process.stdout.write(' install it for syntax highlighting: npm i codemirror\n\n');
554
+ }
555
+ const { server } = createWorkbench({ file: abs, port, theme: themeOverride, collab: opts.collab === true });
556
+ server.on('error', (e) => {
557
+ if (e.code === 'EADDRINUSE')
558
+ fail(`port ${port} is already in use`, `try another port: --port ${port + 1}`);
559
+ throw e;
560
+ });
561
+ server.listen(port, () => {
562
+ const url = `http://localhost:${port}/`;
563
+ process.stdout.write(`\n>> DesignMockdown workbench started\n`);
564
+ process.stdout.write(` File: ${abs}\n`);
565
+ process.stdout.write(` URL: ${url}\n`);
566
+ process.stdout.write(` Save: Ctrl+S (writes back to the file above)\n`);
567
+ process.stdout.write(` Stop: Ctrl+C\n\n`);
568
+ if (opts['no-open'] !== true) {
569
+ try {
570
+ spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref();
571
+ }
572
+ catch {
573
+ /* If the browser cannot be opened, the printed URL is enough */
574
+ }
575
+ }
576
+ });
577
+ }
578
+ /**
579
+ * `designmockdown playground`: type-and-see, nothing written.
580
+ *
581
+ * The file argument is only a starting point - it is read once, and the playground never writes it
582
+ * back. That is the whole difference from `workbench`.
583
+ */
584
+ function cmdPlayground(file, opts) {
585
+ const port = typeof opts.port === 'string' ? Number(opts.port) : 5880;
586
+ const theme = typeof opts.theme === 'string' ? opts.theme : undefined;
587
+ const source = file ? readSource(file) : PLAYGROUND_EXAMPLES[0].source;
588
+ const { server } = createPlayground({ source, port, theme });
589
+ server.on('error', (e) => {
590
+ if (e.code === 'EADDRINUSE')
591
+ fail(`port ${port} is already in use`, `try another port: --port ${port + 1}`);
592
+ throw e;
593
+ });
594
+ server.listen(port, () => {
595
+ const url = `http://localhost:${port}/`;
596
+ process.stdout.write(`\n>> DesignMockdown playground started\n`);
597
+ if (file)
598
+ process.stdout.write(` Started from: ${pathResolve(file)}\n`);
599
+ process.stdout.write(` URL: ${url}\n`);
600
+ process.stdout.write(' Nothing is written to disk; use the download buttons to keep a result\n');
601
+ process.stdout.write(' Stop: Ctrl+C\n\n');
602
+ if (opts['no-open'] !== true) {
603
+ try {
604
+ spawn('cmd', ['/c', 'start', '', url], { detached: true, stdio: 'ignore' }).unref();
605
+ }
606
+ catch {
607
+ /* If the browser cannot be opened, the printed URL is enough */
608
+ }
609
+ }
610
+ });
611
+ }
612
+ function cmdSchema(opts) {
613
+ const schema = buildSchema();
614
+ const format = typeof opts.format === 'string' ? opts.format : 'json';
615
+ if (format === 'json') {
616
+ process.stdout.write(`${JSON.stringify(schema, null, 2)}\n`);
617
+ return;
618
+ }
619
+ if (format === 'markdown' || format === 'md') {
620
+ process.stdout.write(schemaMarkdown(schema));
621
+ return;
622
+ }
623
+ fail(`unknown schema format "${format}"`, 'use --format json or --format markdown', 2);
624
+ }
625
+ /**
626
+ * `designmockdown docs`: write the generated docs, or check that the committed copies are fresh.
627
+ *
628
+ * Two artifacts come out of one set of facts: the human reference under `docs/`, and the compact
629
+ * table that ships inside the agent skill. Both are build artifacts kept in git (a reader should
630
+ * not need Node installed), and `--check` is what keeps them honest - the contract `fmt --check`
631
+ * has.
632
+ */
633
+ function cmdDocs(opts) {
634
+ // Package-relative, like `skill` does: an installed copy has to check its own files instead of
635
+ // creating a docs/ in whatever directory the consumer happened to be standing in
636
+ const root = packageRootOf(import.meta.url);
637
+ const targets = [
638
+ { path: REFERENCE_PATH, render: renderReference },
639
+ { path: SKILL_REFERENCE_PATH, render: renderSkillReference },
640
+ ];
641
+ const stale = [];
642
+ for (const target of targets) {
643
+ const file = pathJoin(root, target.path);
644
+ const next = target.render();
645
+ const existing = existsSync(file) ? readFileSync(file, 'utf8') : null;
646
+ if (opts.check === true) {
647
+ if (existing === next)
648
+ process.stdout.write(`${target.path} is up to date\n`);
649
+ else
650
+ stale.push(target.path);
651
+ continue;
652
+ }
653
+ mkdirSync(dirname(file), { recursive: true });
654
+ writeFileSync(file, next, 'utf8');
655
+ process.stdout.write(`wrote ${target.path} (${next.split('\n').length} lines)\n`);
656
+ }
657
+ if (stale.length > 0) {
658
+ fail(`${stale.join(', ')} ${stale.length > 1 ? 'are' : 'is'} stale`, 'run "designmockdown docs" and commit the result (attributes, scales, components or syntax changed)');
659
+ }
660
+ }
661
+ /**
662
+ * `designmockdown skill`: where the shipped skill lives, and how to hand it to an agent.
663
+ *
664
+ * The skill travels inside the package, so a consumer that installed DesignMockdown from npm can
665
+ * install the same instructions without cloning this repository - the path is resolved from the
666
+ * package root, which works from `src/` and from `dist/lib/` alike.
667
+ */
668
+ function cmdSkill(sub, opts) {
669
+ const source = skillDir();
670
+ if (sub === undefined) {
671
+ process.stdout.write(`${source}\n`);
672
+ process.stdout.write(' designmockdown skill install # NearWork, global\n');
673
+ process.stdout.write(' designmockdown skill install --project # this repository only\n');
674
+ process.stdout.write(' designmockdown skill install --dir <path> # any agent, e.g. --dir .claude/skills\n');
675
+ return;
676
+ }
677
+ if (sub !== 'install') {
678
+ fail(`unknown skill command "${sub}"`, 'use "skill" for the path, "skill install" to install it', 2);
679
+ }
680
+ const where = typeof opts.dir === 'string' ? pathResolve(opts.dir) : defaultSkillsDir(opts.project === true);
681
+ const result = installSkill(where, { link: opts.link === true });
682
+ process.stdout.write(`${result.linked ? 'linked' : 'copied'} ${source}\n -> ${result.target}\n`);
683
+ if (opts.link === true && !result.linked) {
684
+ process.stdout.write(' linking is not available here, copied instead\n');
685
+ }
686
+ process.stdout.write(' restart the agent session (or its skill scan) to pick it up\n');
687
+ }
688
+ /**
689
+ * `designmockdown fmt`: canonical spelling of the parts the parser does not read for meaning.
690
+ *
691
+ * Never touches indentation or text content - see the note at the top of format.ts. `--check`
692
+ * reports instead of writing, which is what CI wants.
693
+ */
694
+ function cmdFmt(targets, opts) {
695
+ if (targets.length === 0)
696
+ fail('fmt needs a .dm file or directory', 'designmockdown fmt login.dm', 2);
697
+ const files = [...new Set(targets.flatMap((t) => collectDmFiles(t)).map((f) => pathResolve(f)))];
698
+ const check = opts.check === true;
699
+ let changed = 0;
700
+ for (const file of files) {
701
+ const source = readFileSync(file, 'utf8');
702
+ const out = formatSource(source);
703
+ if (out === source)
704
+ continue;
705
+ changed++;
706
+ if (check) {
707
+ process.stdout.write(` ✗ ${file}\n`);
708
+ }
709
+ else {
710
+ writeFileSync(file, out, 'utf8');
711
+ process.stdout.write(` fmt ${file}\n`);
712
+ }
713
+ }
714
+ if (check) {
715
+ process.stdout.write(changed === 0 ? `\nAll ${files.length} file(s) already formatted\n\n` : `\n${changed} of ${files.length} file(s) need formatting\n\n`);
716
+ if (changed > 0)
717
+ process.exitCode = 1;
718
+ }
719
+ else {
720
+ process.stdout.write(`\nFormatted ${changed}/${files.length} file(s)\n\n`);
721
+ }
722
+ }
723
+ /** `designmockdown ir`: the layout tree as JSON, for consumers outside this package */
724
+ function cmdIr(file, opts) {
725
+ const source = readSource(file);
726
+ const doc = parseDocument(source, basename(file));
727
+ const themeOverride = typeof opts.theme === 'string' ? opts.theme : undefined;
728
+ const pages = doc.pages.map((page) => {
729
+ // key is a parser fact; resolve() rewrites the tree, so read it first
730
+ const key = page.key ?? page.title;
731
+ const result = resolve(page);
732
+ const theme = themeOverride
733
+ ? { ...result.theme, name: themeOverride, tokens: { ...PRESET_THEMES[themeOverride] ?? result.theme.tokens } }
734
+ : result.theme;
735
+ return pageToIr(result.page, theme, result.canvas, key);
736
+ });
737
+ const name = typeof opts.page === 'string' && opts.page ? opts.page : undefined;
738
+ let chosen = pages;
739
+ if (name) {
740
+ const n = Number(name);
741
+ const found = Number.isInteger(n) && n >= 1 && n <= pages.length
742
+ ? pages[n - 1]
743
+ : pages.find((p) => p.key === name || p.title === name);
744
+ if (!found)
745
+ fail(`no page named "${name}"`, `pages: ${pages.map((p) => p.key).join(', ')}`);
746
+ chosen = [found];
747
+ }
748
+ const ir = documentToIr(basename(file), chosen);
749
+ const json = `${JSON.stringify(ir, null, 2)}\n`;
750
+ if (typeof opts.output === 'string' && opts.output) {
751
+ const outPath = pathResolve(opts.output);
752
+ mkdirSync(dirname(outPath), { recursive: true });
753
+ writeFileSync(outPath, json, 'utf8');
754
+ process.stdout.write(`\nOK exported ${outPath}\n`);
755
+ process.stdout.write(` ${chosen.length} page${chosen.length === 1 ? '' : 's'} - irVersion ${ir.irVersion}\n\n`);
756
+ return;
757
+ }
758
+ process.stdout.write(json);
759
+ }
760
+ /**
761
+ * Batch export: every .dm in a directory becomes one output file.
762
+ *
763
+ * The point is a design system's source of truth living in text - `build` turns a folder of drafts
764
+ * into a folder of artifacts without naming each file. Failures are collected, not thrown, so one
765
+ * broken draft never blocks the rest of the build.
766
+ */
767
+ function cmdBuild(dir, opts) {
768
+ const absDir = pathResolve(dir);
769
+ if (!existsSync(absDir) || !statSync(absDir).isDirectory())
770
+ fail(`not a directory: ${dir}`, 'designmockdown build examples/');
771
+ const raster = isRasterFlag(opts);
772
+ const backend = pickBackend(opts);
773
+ const ext = raster ?? backend.ext;
774
+ const outDir = typeof opts.output === 'string' && opts.output ? pathResolve(opts.output) : pathResolve(absDir, '../dist');
775
+ const themeOverride = typeof opts.theme === 'string' ? opts.theme : undefined;
776
+ const files = readdirSync(absDir)
777
+ .filter((f) => f.endsWith('.dm'))
778
+ .sort();
779
+ if (files.length === 0) {
780
+ process.stdout.write(`\nNo .dm files in ${absDir}\n\n`);
781
+ return;
782
+ }
783
+ let ok = 0;
784
+ const failures = [];
785
+ for (const f of files) {
786
+ const src = pathResolve(absDir, f);
787
+ const stem = basename(f, '.dm');
788
+ try {
789
+ clearAssetCache();
790
+ const source = readSourceSyncSafe(src);
791
+ const { doc, pages } = parseAndRender(src, source, themeOverride);
792
+ mkdirSync(outDir, { recursive: true });
793
+ if (backend.multiPage === 'document') {
794
+ const out = pathResolve(outDir, `${stem}.html`);
795
+ const html = renderDocumentHtml(pages.map(toDocumentPage), {
796
+ // front-matter `title:` wins; the file name is only the fallback
797
+ title: doc.pages[0]?.meta.title?.trim() || stem,
798
+ dark: pages[0].theme.name === 'dark',
799
+ });
800
+ writeFileSync(out, html, 'utf8');
801
+ ok++;
802
+ process.stdout.write(` ok ${f} -> ${basename(out)} (${pages.length} page${pages.length > 1 ? 's' : ''})\n`);
803
+ continue;
804
+ }
805
+ if (backend.multiPage === 'pages-dir') {
806
+ // One page keeps the historical single-file name; more than one becomes a directory of
807
+ // `stem.page-N` modules plus an index (see src/export/pages.ts)
808
+ if (pages.length === 1) {
809
+ const page = pages[0];
810
+ const out = pathResolve(outDir, `${stem}.${ext}`);
811
+ const content = backend.name === 'react'
812
+ ? emitReact(page.node, page.theme, page.canvas, { baseDir: dirname(src) })
813
+ : renderDomPage(page.node, page.theme, page.canvas, { baseDir: dirname(src) });
814
+ writeFileSync(out, content, 'utf8');
815
+ ok++;
816
+ process.stdout.write(` ok ${f} -> ${basename(out)} (${(content.length / 1024).toFixed(1)} KB)\n`);
817
+ continue;
818
+ }
819
+ const result = backend.name === 'react'
820
+ ? exportReactPages(pages, { dir: outDir, base: stem, baseDir: dirname(src) })
821
+ : exportDomPages(pages, { dir: outDir, base: stem, baseDir: dirname(src) });
822
+ ok++;
823
+ process.stdout.write(` ok ${f} -> ${pages.length} page(s) + ${basename(result.index)}\n`);
824
+ continue;
825
+ }
826
+ // svg / png / pdf: one file per page, with an index suffix when there is more than one
827
+ const multi = pages.length > 1;
828
+ for (let i = 0; i < pages.length; i++) {
829
+ const page = pages[i];
830
+ const name = multi ? `${stem}-${i + 1}-${safeName(page.key)}.${ext}` : `${stem}.${ext}`;
831
+ const out = pathResolve(outDir, name);
832
+ if (raster)
833
+ rasterize(page.svg, raster, out);
834
+ else
835
+ writeFileSync(out, page.svg, 'utf8');
836
+ process.stdout.write(` ok ${f} -> ${basename(out)}\n`);
837
+ }
838
+ ok++;
839
+ }
840
+ catch (e) {
841
+ const msg = e instanceof DesignMockdownError ? `${e.message} (line ${e.pos?.line ?? '?'})` : String(e);
842
+ failures.push(`${f}: ${msg}`);
843
+ process.stdout.write(` FAIL ${f} ${msg}\n`);
844
+ }
845
+ }
846
+ process.stdout.write(`\nBuilt ${ok}/${files.length} -> ${outDir} [backend: ${raster ?? backend.name}]\n`);
847
+ if (failures.length > 0) {
848
+ process.stdout.write(`\n${failures.length} failure(s):\n`);
849
+ for (const f of failures)
850
+ process.stdout.write(` ${f}\n`);
851
+ process.exitCode = 1;
852
+ }
853
+ process.stdout.write('\n');
854
+ }
855
+ /**
856
+ * Register component plugins, then return.
857
+ *
858
+ * Called before the command switch, not inside a command: `check`, `export`, `preview`,
859
+ * `workbench`, `build` and the LSP each validate component names against the same registry. A
860
+ * plugin loaded by only one of them would make the same document valid in one place and
861
+ * "unknown component @rating" in another - and the LSP would paint a correct file red.
862
+ *
863
+ * stdout stays untouched: for `designmockdown lsp` it is the JSON-RPC transport.
864
+ */
865
+ async function loadComponentPlugins(entries, noConfig) {
866
+ const cwd = process.cwd();
867
+ const warn = (message) => {
868
+ process.stderr.write(`! ${message}\n`);
869
+ };
870
+ const pluginError = (e) => {
871
+ if (e instanceof DesignMockdownError)
872
+ fail(e.message, e.hint, 2);
873
+ fail(e instanceof Error ? e.message : String(e), undefined, 2);
874
+ };
875
+ // Explicit flags first: when a flag and the config name the same component, the message then
876
+ // points at the config as the duplicate instead of blaming the command line
877
+ if (entries.length) {
878
+ try {
879
+ await loadPlugins(entries, { baseDir: cwd });
880
+ }
881
+ catch (e) {
882
+ pluginError(e);
883
+ }
884
+ }
885
+ if (noConfig)
886
+ return;
887
+ try {
888
+ const config = await loadConfig(cwd, warn);
889
+ if (config)
890
+ await loadPlugins(config.components, { baseDir: dirname(config.file) });
891
+ }
892
+ catch (e) {
893
+ pluginError(e);
894
+ }
895
+ }
896
+ async function main() {
897
+ const { cmd, file, files, opts, components, noConfig } = parseArgs(process.argv.slice(2));
898
+ if (opts.help || cmd === 'help') {
899
+ process.stdout.write(USAGE);
900
+ return;
901
+ }
902
+ // `--version` can arrive as the command slot (`designmockdown --version`) or as a flag
903
+ if (cmd === '--version' || cmd === '-v' || opts.version === true) {
904
+ process.stdout.write(`${packageVersion()}\n`);
905
+ return;
906
+ }
907
+ await loadComponentPlugins(components, noConfig);
908
+ switch (cmd) {
909
+ case 'check':
910
+ // cmdCheck owns the argument check: an empty target list is a usage error (exit 2)
911
+ cmdCheck(files, opts);
912
+ return;
913
+ case 'fmt':
914
+ case 'format':
915
+ cmdFmt(files, opts);
916
+ return;
917
+ case 'ir':
918
+ if (!file)
919
+ fail('ir needs a .dm file', 'designmockdown ir login.dm -o login.ir.json');
920
+ cmdIr(file, opts);
921
+ return;
922
+ case 'export':
923
+ case 'render':
924
+ if (!file)
925
+ fail('export needs a .dm file', 'designmockdown export login.dm -o out.svg');
926
+ cmdExport(file, opts);
927
+ return;
928
+ case 'preview':
929
+ case 'dev':
930
+ if (!file)
931
+ fail('preview needs a .dm file', 'designmockdown preview login.dm');
932
+ cmdPreview(file, opts);
933
+ return;
934
+ case 'workbench':
935
+ if (!file)
936
+ fail('workbench needs a .dm file', 'designmockdown workbench login.dm');
937
+ cmdWorkbench(file, opts);
938
+ return;
939
+ case 'playground':
940
+ cmdPlayground(file, opts);
941
+ return;
942
+ case 'build':
943
+ if (!file)
944
+ fail('build needs a directory', 'designmockdown build examples/ -o dist/');
945
+ cmdBuild(file, opts);
946
+ return;
947
+ case 'schema':
948
+ cmdSchema(opts);
949
+ return;
950
+ case 'docs':
951
+ cmdDocs(opts);
952
+ return;
953
+ case 'skill':
954
+ cmdSkill(file, opts);
955
+ return;
956
+ case 'lsp':
957
+ // Besides the LSP there is nothing to print: stdout is the JSON-RPC transport, so a banner
958
+ // written here would corrupt the stream
959
+ serveStdio();
960
+ return;
961
+ default:
962
+ fail(`unknown command "${cmd}"`, USAGE.split('\n').filter((l) => l.trim().startsWith('designmockdown')).join('\n'));
963
+ }
964
+ }
965
+ main().catch((e) => {
966
+ fail(e instanceof Error ? e.message : String(e));
967
+ });
968
+ //# sourceMappingURL=cli.js.map