@rien7/design-surface 0.0.0-stage → 0.1.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 (214) hide show
  1. package/bin/design-surface.mjs +286 -0
  2. package/dist/cli/init.mjs +411 -0
  3. package/dist/cli/propose.mjs +172 -0
  4. package/dist/cli/reviewOps.mjs +127 -0
  5. package/dist/editor/AgentProposalCard.d.ts +10 -0
  6. package/dist/editor/AgentProposalCard.d.ts.map +1 -0
  7. package/dist/editor/AgentProposalCard.js +28 -0
  8. package/dist/editor/AgentProposalCard.js.map +1 -0
  9. package/dist/editor/App.d.ts +2 -0
  10. package/dist/editor/App.d.ts.map +1 -0
  11. package/dist/editor/App.js +1813 -0
  12. package/dist/editor/App.js.map +1 -0
  13. package/dist/editor/CanvasHud.d.ts +12 -0
  14. package/dist/editor/CanvasHud.d.ts.map +1 -0
  15. package/dist/editor/CanvasHud.js +13 -0
  16. package/dist/editor/CanvasHud.js.map +1 -0
  17. package/dist/editor/CanvasSurface.d.ts +20 -0
  18. package/dist/editor/CanvasSurface.d.ts.map +1 -0
  19. package/dist/editor/CanvasSurface.js +252 -0
  20. package/dist/editor/CanvasSurface.js.map +1 -0
  21. package/dist/editor/Changes.d.ts +17 -0
  22. package/dist/editor/Changes.d.ts.map +1 -0
  23. package/dist/editor/Changes.js +59 -0
  24. package/dist/editor/Changes.js.map +1 -0
  25. package/dist/editor/CommentPopover.d.ts +17 -0
  26. package/dist/editor/CommentPopover.d.ts.map +1 -0
  27. package/dist/editor/CommentPopover.js +62 -0
  28. package/dist/editor/CommentPopover.js.map +1 -0
  29. package/dist/editor/Comments.d.ts +13 -0
  30. package/dist/editor/Comments.d.ts.map +1 -0
  31. package/dist/editor/Comments.js +39 -0
  32. package/dist/editor/Comments.js.map +1 -0
  33. package/dist/editor/History.d.ts +7 -0
  34. package/dist/editor/History.d.ts.map +1 -0
  35. package/dist/editor/History.js +43 -0
  36. package/dist/editor/History.js.map +1 -0
  37. package/dist/editor/Inspector.d.ts +22 -0
  38. package/dist/editor/Inspector.d.ts.map +1 -0
  39. package/dist/editor/Inspector.js +241 -0
  40. package/dist/editor/Inspector.js.map +1 -0
  41. package/dist/editor/LazyMount.d.ts +10 -0
  42. package/dist/editor/LazyMount.d.ts.map +1 -0
  43. package/dist/editor/LazyMount.js +29 -0
  44. package/dist/editor/LazyMount.js.map +1 -0
  45. package/dist/editor/LocaleSwitch.d.ts +2 -0
  46. package/dist/editor/LocaleSwitch.d.ts.map +1 -0
  47. package/dist/editor/LocaleSwitch.js +13 -0
  48. package/dist/editor/LocaleSwitch.js.map +1 -0
  49. package/dist/editor/NodeInspector.d.ts +9 -0
  50. package/dist/editor/NodeInspector.d.ts.map +1 -0
  51. package/dist/editor/NodeInspector.js +9 -0
  52. package/dist/editor/NodeInspector.js.map +1 -0
  53. package/dist/editor/PreviewFrame.d.ts +10 -0
  54. package/dist/editor/PreviewFrame.d.ts.map +1 -0
  55. package/dist/editor/PreviewFrame.js +22 -0
  56. package/dist/editor/PreviewFrame.js.map +1 -0
  57. package/dist/editor/ProjectIndex.d.ts +12 -0
  58. package/dist/editor/ProjectIndex.d.ts.map +1 -0
  59. package/dist/editor/ProjectIndex.js +43 -0
  60. package/dist/editor/ProjectIndex.js.map +1 -0
  61. package/dist/editor/StyleEditor.d.ts +37 -0
  62. package/dist/editor/StyleEditor.d.ts.map +1 -0
  63. package/dist/editor/StyleEditor.js +275 -0
  64. package/dist/editor/StyleEditor.js.map +1 -0
  65. package/dist/editor/TokenWorkbench.d.ts +37 -0
  66. package/dist/editor/TokenWorkbench.d.ts.map +1 -0
  67. package/dist/editor/TokenWorkbench.js +146 -0
  68. package/dist/editor/TokenWorkbench.js.map +1 -0
  69. package/dist/editor/Tokens.d.ts +21 -0
  70. package/dist/editor/Tokens.d.ts.map +1 -0
  71. package/dist/editor/Tokens.js +56 -0
  72. package/dist/editor/Tokens.js.map +1 -0
  73. package/dist/editor/VariablesPage.d.ts +28 -0
  74. package/dist/editor/VariablesPage.d.ts.map +1 -0
  75. package/dist/editor/VariablesPage.js +14 -0
  76. package/dist/editor/VariablesPage.js.map +1 -0
  77. package/dist/editor/api.d.ts +13 -0
  78. package/dist/editor/api.d.ts.map +1 -0
  79. package/dist/editor/api.js +70 -0
  80. package/dist/editor/api.js.map +1 -0
  81. package/dist/editor/camera.d.ts +18 -0
  82. package/dist/editor/camera.d.ts.map +1 -0
  83. package/dist/editor/camera.js +40 -0
  84. package/dist/editor/camera.js.map +1 -0
  85. package/dist/editor/canvas.d.ts +26 -0
  86. package/dist/editor/canvas.d.ts.map +1 -0
  87. package/dist/editor/canvas.js +51 -0
  88. package/dist/editor/canvas.js.map +1 -0
  89. package/dist/editor/chrome/EditorChrome.d.ts +42 -0
  90. package/dist/editor/chrome/EditorChrome.d.ts.map +1 -0
  91. package/dist/editor/chrome/EditorChrome.js +21 -0
  92. package/dist/editor/chrome/EditorChrome.js.map +1 -0
  93. package/dist/editor/i18n.d.ts +18 -0
  94. package/dist/editor/i18n.d.ts.map +1 -0
  95. package/dist/editor/i18n.js +762 -0
  96. package/dist/editor/i18n.js.map +1 -0
  97. package/dist/editor/main.d.ts +3 -0
  98. package/dist/editor/main.d.ts.map +1 -0
  99. package/dist/editor/main.js +12 -0
  100. package/dist/editor/main.js.map +1 -0
  101. package/dist/editor/model.d.ts +17 -0
  102. package/dist/editor/model.d.ts.map +1 -0
  103. package/dist/editor/model.js +12 -0
  104. package/dist/editor/model.js.map +1 -0
  105. package/dist/editor/reviewLifecycle.d.ts +9 -0
  106. package/dist/editor/reviewLifecycle.d.ts.map +1 -0
  107. package/dist/editor/reviewLifecycle.js +30 -0
  108. package/dist/editor/reviewLifecycle.js.map +1 -0
  109. package/dist/editor/styles.css +6626 -0
  110. package/dist/editor/ui/Button.d.ts +3 -0
  111. package/dist/editor/ui/Button.d.ts.map +1 -0
  112. package/dist/editor/ui/Button.js +6 -0
  113. package/dist/editor/ui/Button.js.map +1 -0
  114. package/dist/editor/ui/CommentBox.d.ts +23 -0
  115. package/dist/editor/ui/CommentBox.d.ts.map +1 -0
  116. package/dist/editor/ui/CommentBox.js +41 -0
  117. package/dist/editor/ui/CommentBox.js.map +1 -0
  118. package/dist/editor/ui/Icon.d.ts +9 -0
  119. package/dist/editor/ui/Icon.d.ts.map +1 -0
  120. package/dist/editor/ui/Icon.js +6 -0
  121. package/dist/editor/ui/Icon.js.map +1 -0
  122. package/dist/editor/ui/IconButton.d.ts +11 -0
  123. package/dist/editor/ui/IconButton.d.ts.map +1 -0
  124. package/dist/editor/ui/IconButton.js +6 -0
  125. package/dist/editor/ui/IconButton.js.map +1 -0
  126. package/dist/editor/ui/NumberInput.d.ts +14 -0
  127. package/dist/editor/ui/NumberInput.d.ts.map +1 -0
  128. package/dist/editor/ui/NumberInput.js +6 -0
  129. package/dist/editor/ui/NumberInput.js.map +1 -0
  130. package/dist/editor/ui/PageLine.d.ts +14 -0
  131. package/dist/editor/ui/PageLine.d.ts.map +1 -0
  132. package/dist/editor/ui/PageLine.js +7 -0
  133. package/dist/editor/ui/PageLine.js.map +1 -0
  134. package/dist/editor/ui/Select.d.ts +15 -0
  135. package/dist/editor/ui/Select.d.ts.map +1 -0
  136. package/dist/editor/ui/Select.js +11 -0
  137. package/dist/editor/ui/Select.js.map +1 -0
  138. package/dist/editor/ui/TokenField.d.ts +14 -0
  139. package/dist/editor/ui/TokenField.d.ts.map +1 -0
  140. package/dist/editor/ui/TokenField.js +41 -0
  141. package/dist/editor/ui/TokenField.js.map +1 -0
  142. package/dist/editor-ui.d.ts +14 -0
  143. package/dist/editor-ui.d.ts.map +1 -0
  144. package/dist/editor-ui.js +13 -0
  145. package/dist/editor-ui.js.map +1 -0
  146. package/dist/inspector/runtime.d.ts +18 -0
  147. package/dist/inspector/runtime.d.ts.map +1 -0
  148. package/dist/inspector/runtime.js +987 -0
  149. package/dist/inspector/runtime.js.map +1 -0
  150. package/dist/preview/main.d.ts +3 -0
  151. package/dist/preview/main.d.ts.map +1 -0
  152. package/dist/preview/main.js +72 -0
  153. package/dist/preview/main.js.map +1 -0
  154. package/dist/preview/preview.css +39 -0
  155. package/dist/runtime/flow.d.ts +15 -0
  156. package/dist/runtime/flow.d.ts.map +1 -0
  157. package/dist/runtime/flow.js +48 -0
  158. package/dist/runtime/flow.js.map +1 -0
  159. package/dist/runtime/free.d.ts +18 -0
  160. package/dist/runtime/free.d.ts.map +1 -0
  161. package/dist/runtime/free.js +8 -0
  162. package/dist/runtime/free.js.map +1 -0
  163. package/dist/runtime/index.d.ts +11 -0
  164. package/dist/runtime/index.d.ts.map +1 -0
  165. package/dist/runtime/index.js +46 -0
  166. package/dist/runtime/index.js.map +1 -0
  167. package/dist/runtime/types.d.ts +57 -0
  168. package/dist/runtime/types.d.ts.map +1 -0
  169. package/dist/runtime/types.js +14 -0
  170. package/dist/runtime/types.js.map +1 -0
  171. package/dist/shared/prompt.d.mts +13 -0
  172. package/dist/shared/prompt.mjs +97 -0
  173. package/dist/shared/protocol.d.ts +79 -0
  174. package/dist/shared/protocol.d.ts.map +1 -0
  175. package/dist/shared/protocol.js +7 -0
  176. package/dist/shared/protocol.js.map +1 -0
  177. package/dist/shared/tokens.d.ts +66 -0
  178. package/dist/shared/tokens.d.ts.map +1 -0
  179. package/dist/shared/tokens.js +2 -0
  180. package/dist/shared/tokens.js.map +1 -0
  181. package/dist/shared/types.d.ts +301 -0
  182. package/dist/shared/types.d.ts.map +1 -0
  183. package/dist/shared/types.js +13 -0
  184. package/dist/shared/types.js.map +1 -0
  185. package/dist/tokens/adapters/css.mjs +44 -0
  186. package/dist/tokens/adapters/cssInCode.mjs +277 -0
  187. package/dist/tokens/adapters/oxcShared.mjs +59 -0
  188. package/dist/tokens/adapters/preprocessor.mjs +63 -0
  189. package/dist/tokens/adapters/registry.mjs +53 -0
  190. package/dist/tokens/adapters/tailwindcss.mjs +360 -0
  191. package/dist/tokens/adapters/types.mjs +117 -0
  192. package/dist/tokens/extract.mjs +328 -0
  193. package/dist/tokens/pipeline.mjs +688 -0
  194. package/dist/vite/events.d.ts +25 -0
  195. package/dist/vite/events.d.ts.map +1 -0
  196. package/dist/vite/events.js +137 -0
  197. package/dist/vite/events.js.map +1 -0
  198. package/dist/vite/layout.d.ts +4 -0
  199. package/dist/vite/layout.d.ts.map +1 -0
  200. package/dist/vite/layout.js +78 -0
  201. package/dist/vite/layout.js.map +1 -0
  202. package/dist/vite/plugin.d.ts +33 -0
  203. package/dist/vite/plugin.d.ts.map +1 -0
  204. package/dist/vite/plugin.js +403 -0
  205. package/dist/vite/plugin.js.map +1 -0
  206. package/dist/vite/review.d.ts +7 -0
  207. package/dist/vite/review.d.ts.map +1 -0
  208. package/dist/vite/review.js +334 -0
  209. package/dist/vite/review.js.map +1 -0
  210. package/package.json +86 -4
  211. package/skills/design-surface/SKILL.md +190 -0
  212. package/skills/design-surface-authoring/SKILL.md +257 -0
  213. package/skills/design-surface-tokens/SKILL.md +235 -0
  214. package/README.md +0 -3
@@ -0,0 +1,688 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
3
+ import { dirname, join, relative, resolve, sep } from 'node:path'
4
+
5
+ import { analyzeFilesWithAdapters } from './adapters/registry.mjs'
6
+
7
+ const TIERS = ['primitive', 'semantic', 'component']
8
+ const TIER_ORDER = Object.fromEntries(TIERS.map((tier, index) => [tier, index]))
9
+
10
+ export const DEFAULT_TOKEN_CONFIG = {
11
+ tokenDir: 'design/tokens',
12
+ cssOut: 'src/tokens.generated.css',
13
+ tsOut: 'design/tokens.generated.ts',
14
+ manifestOut: 'design/tokens.manifest.json',
15
+ scanDirs: ['src', 'design'],
16
+ cssFormat: 'theme',
17
+ contrastPairs: [],
18
+ localAliases: [],
19
+ }
20
+
21
+ const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'))
22
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex')
23
+ const toPosix = (file) => file.split(sep).join('/')
24
+
25
+ export const cssNameOf = (tokenPath) => `--${tokenPath.join('-')}`
26
+
27
+ export const aliasPath = (value) => {
28
+ if (typeof value !== 'string') return null
29
+ const match = /^\{([^}]+)\}$/.exec(value)
30
+ return match ? match[1] : null
31
+ }
32
+
33
+ function mergeMeta(base, next) {
34
+ return { ...base, ...(next ?? {}) }
35
+ }
36
+
37
+ export function loadTokenConfig(root, overrides = {}) {
38
+ const configPath = join(root, 'design/tokens.config.json')
39
+ const fileConfig = existsSync(configPath) ? readJson(configPath) : {}
40
+ const merged = {
41
+ ...DEFAULT_TOKEN_CONFIG,
42
+ ...fileConfig,
43
+ ...overrides,
44
+ }
45
+ if (merged.cssFormat !== 'theme' && merged.cssFormat !== 'root') {
46
+ throw new Error(`Invalid cssFormat "${merged.cssFormat}". Expected "theme" or "root".`)
47
+ }
48
+ return {
49
+ tokenDir: String(merged.tokenDir),
50
+ cssOut: String(merged.cssOut),
51
+ tsOut: String(merged.tsOut),
52
+ manifestOut: String(merged.manifestOut),
53
+ scanDirs: Array.isArray(merged.scanDirs) ? merged.scanDirs.map(String) : DEFAULT_TOKEN_CONFIG.scanDirs,
54
+ cssFormat: merged.cssFormat,
55
+ contrastPairs: Array.isArray(merged.contrastPairs) ? merged.contrastPairs : [],
56
+ localAliases: Array.isArray(merged.localAliases) ? merged.localAliases.map(String) : [],
57
+ adapters: Array.isArray(merged.adapters) ? merged.adapters.map(String) : undefined,
58
+ }
59
+ }
60
+
61
+ export function walkTokens(node, tokenPath, inheritedMeta, inheritedType, file, root, records) {
62
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return
63
+ if ('$value' in node) {
64
+ const own = node.$extensions?.['design-surface'] ?? {}
65
+ const meta = mergeMeta(inheritedMeta, own)
66
+ const type = node.$type ?? inheritedType
67
+ if (!type) throw new Error(`${file}: ${tokenPath.join('.')} has no $type`)
68
+ const cssName = meta.cssName ?? cssNameOf(tokenPath)
69
+ records.push({
70
+ path: tokenPath,
71
+ cssName,
72
+ raw: node.$value,
73
+ alias: aliasPath(node.$value),
74
+ dtcgType: type,
75
+ type: meta.uiType ?? (type === 'color' ? 'color' : type === 'dimension' ? 'length' : 'text'),
76
+ tier: meta.tier ?? 'primitive',
77
+ group: meta.group ?? tokenPath[0],
78
+ label: meta.label ?? tokenPath[tokenPath.length - 1],
79
+ labelZh: meta.labelZh,
80
+ description: node.$description,
81
+ groupLabel: inheritedMeta.label,
82
+ groupLabelZh: inheritedMeta.labelZh,
83
+ min: typeof meta.min === 'number' ? meta.min : undefined,
84
+ max: typeof meta.max === 'number' ? meta.max : undefined,
85
+ step: typeof meta.step === 'number' ? meta.step : undefined,
86
+ source: toPosix(relative(root, file)),
87
+ })
88
+ return
89
+ }
90
+ const own = node.$extensions?.['design-surface'] ?? {}
91
+ const meta = mergeMeta(inheritedMeta, own)
92
+ const type = node.$type ?? inheritedType
93
+ for (const [key, value] of Object.entries(node)) {
94
+ if (key.startsWith('$')) continue
95
+ walkTokens(value, [...tokenPath, key], meta, type, file, root, records)
96
+ }
97
+ }
98
+
99
+ export function readTokenRecords(root, tokenDir) {
100
+ const tokenRoot = resolve(root, tokenDir)
101
+ if (!existsSync(tokenRoot)) {
102
+ throw new Error(`Missing token source directory: ${tokenRoot}`)
103
+ }
104
+ const files = readdirSync(tokenRoot)
105
+ .filter((file) => file.endsWith('.tokens.json'))
106
+ .sort()
107
+ .map((file) => join(tokenRoot, file))
108
+ if (!files.length) throw new Error(`No *.tokens.json files found in ${tokenRoot}`)
109
+ const records = []
110
+ for (const file of files) {
111
+ const json = readJson(file)
112
+ walkTokens(json, [], {}, undefined, file, root, records)
113
+ }
114
+ return { files, records }
115
+ }
116
+
117
+ function resolveRecords(records) {
118
+ const byPath = new Map(records.map((record) => [record.path.join('.'), record]))
119
+ const byCss = new Map(records.map((record) => [record.cssName, record]))
120
+ const seen = new Map()
121
+
122
+ const resolveToken = (record, stack = []) => {
123
+ const key = record.path.join('.')
124
+ if (seen.has(key)) return seen.get(key)
125
+ if (stack.includes(key)) {
126
+ throw new Error(`Circular token alias: ${[...stack, key].join(' -> ')}`)
127
+ }
128
+ let value
129
+ if (record.alias) {
130
+ const target = byPath.get(record.alias)
131
+ if (!target) throw new Error(`${key} references missing token ${record.alias}`)
132
+ value = resolveToken(target, [...stack, key])
133
+ } else if (record.raw && typeof record.raw === 'object' && !Array.isArray(record.raw)) {
134
+ if ('value' in record.raw && 'unit' in record.raw) {
135
+ value = `${record.raw.value}${record.raw.unit}`
136
+ } else {
137
+ throw new Error(`${key} has an unsupported composite value`)
138
+ }
139
+ } else {
140
+ value = String(record.raw).replace(/var\((--[a-zA-Z0-9_-]+)\)/g, (match, name) => {
141
+ const target = byCss.get(name)
142
+ return target ? resolveToken(target, stack) : match
143
+ })
144
+ }
145
+ seen.set(key, value)
146
+ return value
147
+ }
148
+
149
+ for (const record of records) {
150
+ record.value = resolveToken(record)
151
+ if (record.alias) {
152
+ const target = byPath.get(record.alias)
153
+ if (target && record.dtcgType !== target.dtcgType) {
154
+ // DTCG aliases inherit the target type; a mismatched explicit type is a bug.
155
+ throw new Error(
156
+ `${record.path.join('.')} type ${record.dtcgType} does not match alias ${record.alias} type ${target.dtcgType}`,
157
+ )
158
+ }
159
+ }
160
+ }
161
+
162
+ const seenCss = new Map()
163
+ for (const record of records) {
164
+ if (seenCss.has(record.cssName)) {
165
+ throw new Error(
166
+ `Duplicate CSS variable ${record.cssName}: ${seenCss.get(record.cssName)} and ${record.path.join('.')}`,
167
+ )
168
+ }
169
+ seenCss.set(record.cssName, record.path.join('.'))
170
+ if (!/^--[a-zA-Z0-9_-]+$/.test(record.cssName)) {
171
+ throw new Error(`Invalid CSS variable ${record.cssName}`)
172
+ }
173
+ }
174
+ return { byPath, byCss: new Map(records.map((record) => [record.cssName, record])) }
175
+ }
176
+
177
+ function cssValue(record, byPath) {
178
+ if (record.alias) {
179
+ const target = byPath.get(record.alias)
180
+ if (!target) throw new Error(`Missing alias target ${record.alias}`)
181
+ return `var(${target.cssName})`
182
+ }
183
+ if (record.raw && typeof record.raw === 'object' && 'value' in record.raw && 'unit' in record.raw) {
184
+ return `${record.raw.value}${record.raw.unit}`
185
+ }
186
+ return String(record.raw)
187
+ }
188
+
189
+ function scanFiles(root, config) {
190
+ const roots = config.scanDirs.map((dir) => resolve(root, dir))
191
+ const ignoredFiles = new Set([
192
+ resolve(root, config.cssOut),
193
+ resolve(root, config.tsOut),
194
+ resolve(root, config.manifestOut),
195
+ ])
196
+ const files = []
197
+ const visit = (dir) => {
198
+ if (!existsSync(dir)) return
199
+ for (const entry of readdirSync(dir)) {
200
+ if (
201
+ entry === 'node_modules' ||
202
+ entry === 'dist' ||
203
+ entry === '.git' ||
204
+ entry === 'tokens.generated.css' ||
205
+ entry === 'tokens.generated.ts'
206
+ ) {
207
+ continue
208
+ }
209
+ const file = join(dir, entry)
210
+ if (ignoredFiles.has(file)) continue
211
+ const stat = statSync(file)
212
+ if (stat.isDirectory()) {
213
+ visit(file)
214
+ } else if (
215
+ /\.(css|scss|sass|less|tsx|ts|jsx|js|mts|cts|mjs|cjs)$/i.test(entry) &&
216
+ !file.endsWith('tokens.manifest.json')
217
+ ) {
218
+ files.push(file)
219
+ }
220
+ }
221
+ }
222
+ roots.forEach(visit)
223
+ return files
224
+ }
225
+
226
+ function collectProposedTokenRefs(root) {
227
+ const designRoot = join(root, 'design')
228
+ const proposed = new Set()
229
+ if (!existsSync(designRoot)) return proposed
230
+ for (const entry of readdirSync(designRoot, { withFileTypes: true })) {
231
+ if (!entry.isDirectory()) continue
232
+ const reviewFile = join(designRoot, entry.name, 'review.json')
233
+ if (!existsSync(reviewFile)) continue
234
+ try {
235
+ const review = readJson(reviewFile)
236
+ for (const item of review?.items ?? []) {
237
+ if (
238
+ item?.kind === 'token' &&
239
+ item?.author === 'agent' &&
240
+ item?.status !== 'archived' &&
241
+ item?.proposalDecision !== 'rejected' &&
242
+ item?.target?.type === 'token' &&
243
+ typeof item.target.token === 'string' &&
244
+ item.target.token.startsWith('--')
245
+ ) {
246
+ proposed.add(item.target.token)
247
+ }
248
+ }
249
+ } catch {
250
+ // ignore malformed review ledgers during token scan
251
+ }
252
+ }
253
+ return proposed
254
+ }
255
+
256
+ async function scanUsage(root, records, config) {
257
+ const files = scanFiles(root, config)
258
+ const diagnostics = await analyzeFilesWithAdapters({
259
+ root,
260
+ files,
261
+ adapters: config.adapters,
262
+ })
263
+
264
+ const tokenNames = new Set(records.map((record) => record.cssName))
265
+ const usedIn = new Map(records.map((record) => [record.cssName, []]))
266
+ const defined = new Set(records.map((record) => record.cssName))
267
+ const localAliases = new Set(config.localAliases)
268
+ const proposedTokens = collectProposedTokenRefs(root)
269
+ const usedProposedTokens = new Map()
270
+ const unknown = new Set()
271
+
272
+ const hardcodedByFile = new Map()
273
+ const clusterMap = new Map()
274
+ const unsupportedMap = new Map()
275
+
276
+ for (const diag of diagnostics) {
277
+ if (diag.kind === 'token-ref' && diag.token) {
278
+ const name = diag.token
279
+ if (
280
+ name.startsWith('--tw-') ||
281
+ name.startsWith('--anchor-') ||
282
+ name.startsWith('--available-') ||
283
+ name.startsWith('--transform-')
284
+ ) {
285
+ continue
286
+ }
287
+ if (tokenNames.has(name)) {
288
+ usedIn.get(name).push(diag.file)
289
+ } else if (proposedTokens.has(name)) {
290
+ let filesForProposed = usedProposedTokens.get(name)
291
+ if (!filesForProposed) {
292
+ filesForProposed = new Set()
293
+ usedProposedTokens.set(name, filesForProposed)
294
+ }
295
+ filesForProposed.add(diag.file)
296
+ } else if (!localAliases.has(name) && !defined.has(name)) {
297
+ unknown.add(`${name} (${diag.file})`)
298
+ }
299
+ continue
300
+ }
301
+
302
+ if (diag.kind === 'literal') {
303
+ let fileMap = hardcodedByFile.get(diag.file)
304
+ if (!fileMap) {
305
+ fileMap = new Map()
306
+ hardcodedByFile.set(diag.file, fileMap)
307
+ }
308
+ fileMap.set(diag.value, (fileMap.get(diag.value) ?? 0) + 1)
309
+
310
+ let cluster = clusterMap.get(diag.value)
311
+ if (!cluster) {
312
+ cluster = { value: diag.value, count: 0, files: new Set(), adapters: new Set() }
313
+ clusterMap.set(diag.value, cluster)
314
+ }
315
+ cluster.count += 1
316
+ cluster.files.add(diag.file)
317
+ cluster.adapters.add(diag.adapter)
318
+ continue
319
+ }
320
+
321
+ if (diag.kind === 'unsupported') {
322
+ const reason = diag.reason ?? 'unsupported'
323
+ const key = `${diag.file}\0${diag.adapter}\0${reason}`
324
+ const existing = unsupportedMap.get(key)
325
+ if (existing) {
326
+ existing.count += 1
327
+ } else {
328
+ unsupportedMap.set(key, {
329
+ file: diag.file,
330
+ adapter: diag.adapter,
331
+ reason,
332
+ count: 1,
333
+ ...(typeof diag.line === 'number' ? { line: diag.line } : {}),
334
+ })
335
+ }
336
+ }
337
+ }
338
+
339
+ for (const [name, filesUsed] of usedIn) {
340
+ usedIn.set(name, [...new Set(filesUsed)].sort())
341
+ }
342
+
343
+ const hardcoded = [...hardcodedByFile.entries()]
344
+ .map(([file, valueCounts]) => {
345
+ const values = [...valueCounts.entries()]
346
+ .map(([value, count]) => ({ value, count }))
347
+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))
348
+ const count = values.reduce((sum, entry) => sum + entry.count, 0)
349
+ return { file, count, values }
350
+ })
351
+ .sort((a, b) => b.count - a.count || a.file.localeCompare(b.file))
352
+
353
+ const clusters = [...clusterMap.values()]
354
+ .map((cluster) => ({
355
+ value: cluster.value,
356
+ count: cluster.count,
357
+ files: [...cluster.files].sort(),
358
+ adapters: [...cluster.adapters].sort(),
359
+ }))
360
+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))
361
+
362
+ const unsupported = [...unsupportedMap.values()].sort(
363
+ (a, b) => b.count - a.count || a.file.localeCompare(b.file),
364
+ )
365
+
366
+ const proposedRefs = [...usedProposedTokens.entries()]
367
+ .map(([token, filesSet]) => ({ token, files: [...filesSet].sort() }))
368
+ .sort((a, b) => a.token.localeCompare(b.token))
369
+
370
+ return { usedIn, unknown: [...unknown].sort(), hardcoded, clusters, unsupported, proposedRefs }
371
+ }
372
+
373
+ export function colorToRgb(value) {
374
+ if (typeof value !== 'string') return null
375
+ const hex = value.trim().match(/^#([0-9a-f]{3,8})$/i)
376
+ if (hex) {
377
+ const raw = hex[1]
378
+ if (raw.length === 3) {
379
+ return [0, 1, 2].map((i) => parseInt(raw[i] + raw[i], 16))
380
+ }
381
+ if (raw.length === 6 || raw.length === 8) {
382
+ return [0, 2, 4].map((i) => parseInt(raw.slice(i, i + 2), 16))
383
+ }
384
+ }
385
+ const rgb = value.trim().match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i)
386
+ if (rgb) return [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
387
+ return null
388
+ }
389
+
390
+ function luminance(rgb) {
391
+ const channels = rgb.map((channel) => {
392
+ const value = channel / 255
393
+ return value <= 0.03928 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
394
+ })
395
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
396
+ }
397
+
398
+ function contrast(fg, bg) {
399
+ const a = luminance(fg)
400
+ const b = luminance(bg)
401
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
402
+ }
403
+
404
+ function checkContrast(byPath, contrastPairs) {
405
+ const results = []
406
+ for (const pair of contrastPairs) {
407
+ if (!Array.isArray(pair) || pair.length < 2) continue
408
+ const [fgPath, bgPath] = pair
409
+ const fgToken = byPath.get(fgPath)
410
+ const bgToken = byPath.get(bgPath)
411
+ if (!fgToken || !bgToken) continue
412
+ const fg = colorToRgb(fgToken.value)
413
+ const bg = colorToRgb(bgToken.value)
414
+ if (!fg || !bg) continue
415
+ const ratio = contrast(fg, bg)
416
+ results.push({ fg: fgPath, bg: bgPath, ratio: Math.round(ratio * 100) / 100, pass: ratio >= 4.5 })
417
+ }
418
+ return results
419
+ }
420
+
421
+ function buildOutputs(records, files, usage, config) {
422
+ const byPath = new Map(records.map((record) => [record.path.join('.'), record]))
423
+ const sourceHash = sha256(files.map((file) => readFileSync(file, 'utf8')).join('\n'))
424
+ const sorted = [...records].sort((a, b) => {
425
+ const tier = (TIER_ORDER[a.tier] ?? 99) - (TIER_ORDER[b.tier] ?? 99)
426
+ if (tier) return tier
427
+ if (a.group !== b.group) return a.group.localeCompare(b.group)
428
+ return a.path.join('.').localeCompare(b.path.join('.'))
429
+ })
430
+
431
+ const groups = new Map()
432
+ for (const record of sorted) {
433
+ const key = `${record.tier}:${record.group}`
434
+ if (!groups.has(key)) {
435
+ groups.set(key, {
436
+ id: key,
437
+ tier: record.tier,
438
+ tokens: [],
439
+ })
440
+ }
441
+ groups.get(key).tokens.push(record)
442
+ }
443
+ // Group labels come from the group metadata, captured on each token's walk.
444
+ // The group label is stable even when a token has its own label.
445
+ for (const record of records) {
446
+ const key = `${record.tier}:${record.group}`
447
+ const group = groups.get(key)
448
+ if (!group) continue
449
+ if (!group.label) {
450
+ group.label = record.groupLabel ?? record.group
451
+ group.labelZh = record.groupLabelZh
452
+ }
453
+ }
454
+
455
+ const cssBlock = config.cssFormat === 'root' ? ':root {' : '@theme {'
456
+ const css = [
457
+ `/* Generated from ${config.tokenDir}/*.tokens.json. Do not edit by hand. */`,
458
+ `/* sourceHash: ${sourceHash} */`,
459
+ cssBlock,
460
+ ...sorted.map((record) => ` ${record.cssName}: ${cssValue(record, byPath)};`),
461
+ '}',
462
+ '',
463
+ ].join('\n')
464
+
465
+ const aliasedBy = new Map(records.map((record) => [record.path.join('.'), []]))
466
+ for (const record of records) {
467
+ if (record.alias) aliasedBy.get(record.alias)?.push(record.path.join('.'))
468
+ }
469
+
470
+ const tokenDefs = sorted.map((record) => ({
471
+ name: record.cssName,
472
+ path: record.path.join('.'),
473
+ label: record.label,
474
+ ...(record.labelZh ? { labelZh: record.labelZh } : {}),
475
+ type: record.type,
476
+ ...(record.description ? { description: record.description } : {}),
477
+ ...(record.min !== undefined ? { min: record.min } : {}),
478
+ ...(record.max !== undefined ? { max: record.max } : {}),
479
+ ...(record.step !== undefined ? { step: record.step } : {}),
480
+ tier: record.tier,
481
+ ...(record.alias ? { alias: record.alias } : {}),
482
+ source: record.source,
483
+ value: record.value,
484
+ ...(usage.usedIn.get(record.cssName)?.length ? { usedIn: usage.usedIn.get(record.cssName) } : {}),
485
+ ...(aliasedBy.get(record.path.join('.'))?.length
486
+ ? { aliasedBy: [...new Set(aliasedBy.get(record.path.join('.')))].sort() }
487
+ : {}),
488
+ }))
489
+
490
+ const groupList = [...groups.values()].map((group) => ({
491
+ id: group.id,
492
+ label: group.label ?? group.id,
493
+ ...(group.labelZh ? { labelZh: group.labelZh } : {}),
494
+ tier: group.tier,
495
+ tokens: group.tokens.map((record) => tokenDefs.find((token) => token.name === record.cssName)),
496
+ }))
497
+
498
+ const values = Object.fromEntries(sorted.map((record) => [record.cssName, record.value]))
499
+ const sources = Object.fromEntries(sorted.map((record) => [record.cssName, record.source]))
500
+ const aliases = Object.fromEntries(
501
+ sorted.filter((record) => record.alias).map((record) => [record.cssName, record.alias]),
502
+ )
503
+
504
+ const byPathAll = new Map(records.map((record) => [record.path.join('.'), record]))
505
+ const duplicateGroups = new Map()
506
+ for (const record of records) {
507
+ if (record.alias) continue
508
+ const key = `${record.group}:${record.value}`
509
+ const list = duplicateGroups.get(key) ?? []
510
+ list.push(record)
511
+ duplicateGroups.set(key, list)
512
+ }
513
+ const duplicates = [...duplicateGroups.values()]
514
+ .filter((list) => list.length > 1)
515
+ .map((list) => ({
516
+ group: list[0].group,
517
+ value: list[0].value,
518
+ tokens: list.map((record) => record.path.join('.')),
519
+ }))
520
+ const orphans = sorted
521
+ .filter(
522
+ (record) =>
523
+ !(usage.usedIn.get(record.cssName)?.length) &&
524
+ !(aliasedBy.get(record.path.join('.'))?.length),
525
+ )
526
+ .map((record) => record.path.join('.'))
527
+ const semanticLiterals = sorted
528
+ .filter((record) => record.tier === 'semantic' && !record.alias)
529
+ .map((record) => record.path.join('.'))
530
+ const componentPrimitive = sorted
531
+ .filter(
532
+ (record) =>
533
+ record.tier === 'component' &&
534
+ record.alias &&
535
+ byPathAll.get(record.alias)?.tier === 'primitive',
536
+ )
537
+ .map((record) => ({ token: record.path.join('.'), alias: record.alias }))
538
+ const health = {
539
+ duplicates,
540
+ orphans,
541
+ semanticLiterals,
542
+ componentPrimitive,
543
+ hardcoded: usage.hardcoded,
544
+ clusters: usage.clusters,
545
+ unsupported: usage.unsupported,
546
+ }
547
+
548
+ const ts = [
549
+ `// Generated from ${config.tokenDir}/*.tokens.json. Do not edit by hand.`,
550
+ `// sourceHash: ${sourceHash}`,
551
+ "import type { TokenGroup } from '@rien7/design-surface/runtime'",
552
+ '',
553
+ `export const tokenSourceHash = ${JSON.stringify(sourceHash)}`,
554
+ `export const tokenGroups: TokenGroup[] = ${JSON.stringify(groupList, null, 2)}`,
555
+ '',
556
+ `export const tokenValues: Record<string, string> = ${JSON.stringify(values, null, 2)}`,
557
+ '',
558
+ `export const tokenSources: Record<string, string> = ${JSON.stringify(sources, null, 2)}`,
559
+ '',
560
+ `export const tokenAliases: Record<string, string> = ${JSON.stringify(aliases, null, 2)}`,
561
+ '',
562
+ `export const tokenHealth = ${JSON.stringify(health, null, 2)}`,
563
+ '',
564
+ ].join('\n')
565
+
566
+ const manifest = {
567
+ version: 1,
568
+ sourceHash,
569
+ generatedAt: 'generated',
570
+ counts: {
571
+ total: sorted.length,
572
+ byTier: Object.fromEntries(
573
+ TIERS.map((tier) => [tier, sorted.filter((record) => record.tier === tier).length]),
574
+ ),
575
+ },
576
+ tokens: sorted.map((record) => ({
577
+ path: record.path.join('.'),
578
+ cssName: record.cssName,
579
+ type: record.dtcgType,
580
+ tier: record.tier,
581
+ group: record.group,
582
+ value: record.value,
583
+ alias: record.alias,
584
+ source: record.source,
585
+ description: record.description,
586
+ usedIn: usage.usedIn.get(record.cssName) ?? [],
587
+ aliasedBy: [...new Set(aliasedBy.get(record.path.join('.')) ?? [])].sort(),
588
+ })),
589
+ contrast: checkContrast(byPath, config.contrastPairs),
590
+ unknownVars: usage.unknown,
591
+ hardcoded: usage.hardcoded,
592
+ clusters: usage.clusters,
593
+ unsupported: usage.unsupported,
594
+ health,
595
+ }
596
+ return { css, ts, manifest, sorted, groupList, health }
597
+ }
598
+
599
+ function validate(records, usage, outputs) {
600
+ const errors = []
601
+ const warnings = []
602
+ for (const record of records) {
603
+ if (
604
+ record.dtcgType === 'dimension' &&
605
+ !record.alias &&
606
+ !/^-?\d+(\.\d+)?(px|rem|em|%)$/.test(record.value)
607
+ ) {
608
+ errors.push(`${record.path.join('.')} is not a valid dimension: ${record.value}`)
609
+ }
610
+ if (
611
+ record.dtcgType === 'color' &&
612
+ !record.alias &&
613
+ !colorToRgb(record.value) &&
614
+ !/^(color-mix|rgb|hsl|oklch|var\()/i.test(record.value)
615
+ ) {
616
+ errors.push(`${record.path.join('.')} is not a valid color: ${record.value}`)
617
+ }
618
+ }
619
+ for (const item of outputs.manifest.contrast) {
620
+ if (!item.pass) errors.push(`Contrast ${item.fg} on ${item.bg} is ${item.ratio}:1, needs 4.5:1`)
621
+ }
622
+ for (const item of usage.unknown) {
623
+ errors.push(`Unknown CSS variable ${item}`)
624
+ }
625
+ if (usage.proposedRefs?.length) {
626
+ warnings.push(
627
+ `${usage.proposedRefs.length} unrejected agent proposal token(s) referenced (${usage.proposedRefs.map((entry) => entry.token).join(', ')}); report-only until approved and built`,
628
+ )
629
+ }
630
+ if (usage.hardcoded.length) {
631
+ const total = usage.hardcoded.reduce((sum, item) => sum + item.count, 0)
632
+ warnings.push(
633
+ `${total} hardcoded color literal(s) in ${usage.hardcoded.length} file(s); report-only for now`,
634
+ )
635
+ }
636
+ if (usage.unsupported.length) {
637
+ const total = usage.unsupported.reduce((sum, item) => sum + item.count, 0)
638
+ warnings.push(
639
+ `${total} unsupported style expression(s) across ${usage.unsupported.length} entry/entries; report-only`,
640
+ )
641
+ }
642
+ return { errors, warnings }
643
+ }
644
+
645
+ function compareOrWrite(root, file, content, check) {
646
+ const existing = existsSync(file) ? readFileSync(file, 'utf8') : ''
647
+ if (check) {
648
+ if (existing !== content) {
649
+ throw new Error(`${toPosix(relative(root, file))} is stale. Run tokens build.`)
650
+ }
651
+ return
652
+ }
653
+ mkdirSync(dirname(file), { recursive: true })
654
+ writeFileSync(file, content)
655
+ }
656
+
657
+ export async function runTokenPipeline({ root = process.cwd(), check = false, config: overrides = {} } = {}) {
658
+ const config = loadTokenConfig(root, overrides)
659
+ const { files, records } = readTokenRecords(root, config.tokenDir)
660
+ resolveRecords(records)
661
+ const usage = await scanUsage(root, records, config)
662
+ const outputs = buildOutputs(records, files, usage, config)
663
+ const { errors, warnings } = validate(records, usage, outputs)
664
+
665
+ if (errors.length) {
666
+ const error = new Error(`Token validation failed (${errors.length}):\n${errors.map((e) => ` - ${e}`).join('\n')}`)
667
+ error.validationErrors = errors
668
+ throw error
669
+ }
670
+
671
+ compareOrWrite(root, resolve(root, config.cssOut), outputs.css, check)
672
+ compareOrWrite(root, resolve(root, config.tsOut), outputs.ts, check)
673
+ compareOrWrite(
674
+ root,
675
+ resolve(root, config.manifestOut),
676
+ `${JSON.stringify(outputs.manifest, null, 2)}\n`,
677
+ check,
678
+ )
679
+
680
+ return {
681
+ check,
682
+ config,
683
+ counts: outputs.manifest.counts,
684
+ contrast: outputs.manifest.contrast,
685
+ unsupported: usage.unsupported,
686
+ warnings,
687
+ }
688
+ }