@algotao/uiscope 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.agents/plugins/marketplace.json +21 -0
  2. package/.cursor-plugin/plugin.json +8 -0
  3. package/LICENSE +21 -0
  4. package/README.md +255 -2
  5. package/README.zh-CN.md +256 -0
  6. package/bin/uiscope.js +8 -0
  7. package/package.json +89 -3
  8. package/plugin.json +17 -0
  9. package/presets/README.md +11 -0
  10. package/presets/ocpui/index.ts +107 -0
  11. package/skills/README.md +7 -0
  12. package/skills/uiscope-ux-optimize/SKILL.md +267 -0
  13. package/skills/uiscope-ux-optimize/scripts/uiscope.mjs +40 -0
  14. package/src/__tests__/cli-parity.spec.ts +59 -0
  15. package/src/__tests__/cli-read.spec.ts +141 -0
  16. package/src/__tests__/component-tree.spec.ts +72 -0
  17. package/src/__tests__/enhance-core-ux.spec.ts +72 -0
  18. package/src/__tests__/enhance-feedback-states.spec.ts +104 -0
  19. package/src/__tests__/facet-analyze.spec.ts +55 -0
  20. package/src/__tests__/fixtures/exmarket-integration.config.ts +19 -0
  21. package/src/__tests__/format-scan-stats.spec.ts +32 -0
  22. package/src/__tests__/install-skill.spec.ts +41 -0
  23. package/src/__tests__/merge-cli-config.spec.ts +56 -0
  24. package/src/__tests__/react-tree.spec.ts +29 -0
  25. package/src/__tests__/read-scan-report-boundaries.spec.ts +139 -0
  26. package/src/__tests__/read-scan-report.spec.ts +91 -0
  27. package/src/__tests__/resolve-enhancements.spec.ts +21 -0
  28. package/src/__tests__/resolve-presets.spec.ts +51 -0
  29. package/src/__tests__/resolve-scan-scope.spec.ts +28 -0
  30. package/src/__tests__/run-scan-ux.spec.ts +51 -0
  31. package/src/__tests__/scan-progress.spec.ts +52 -0
  32. package/src/__tests__/style-path.spec.ts +11 -0
  33. package/src/__tests__/style-rules.spec.ts +25 -0
  34. package/src/__tests__/template-hints.spec.ts +19 -0
  35. package/src/__tests__/wrapper-roles.spec.ts +31 -0
  36. package/src/adapters/react/collect-react-files.ts +17 -0
  37. package/src/adapters/react/component-tree.tsx.ts +79 -0
  38. package/src/adapters/react/index.ts +3 -0
  39. package/src/adapters/react/parse-jsx-imports.ts +38 -0
  40. package/src/adapters/vue/index.ts +4 -0
  41. package/src/cli/brand.ts +35 -0
  42. package/src/cli/install-skill.ts +90 -0
  43. package/src/cli/main.ts +578 -0
  44. package/src/cli/merge-cli-config.ts +86 -0
  45. package/src/config/defaults.ts +65 -0
  46. package/src/config/frameworks.ts +20 -0
  47. package/src/config/load-config.ts +81 -0
  48. package/src/config/normalize-legacy-config.ts +39 -0
  49. package/src/config/preset-types.ts +16 -0
  50. package/src/config/resolve-preset-library-roots.ts +49 -0
  51. package/src/config/resolve-presets.ts +142 -0
  52. package/src/config/resolve-scan-scope.ts +12 -0
  53. package/src/config/resolve-thresholds.ts +12 -0
  54. package/src/enhance/dir-utils.ts +25 -0
  55. package/src/enhance/registry.ts +107 -0
  56. package/src/enhance/resolve-enhancements.ts +56 -0
  57. package/src/enhance/rules/action-semantics.ts +60 -0
  58. package/src/enhance/rules/core-ux.ts +139 -0
  59. package/src/enhance/rules/facet-hygiene.ts +44 -0
  60. package/src/enhance/rules/feedback-states.ts +39 -0
  61. package/src/enhance/rules/form-a11y.ts +62 -0
  62. package/src/enhance/rules/hollow-shell.ts +39 -0
  63. package/src/enhance/rules/i18n-hints.ts +29 -0
  64. package/src/enhance/rules/list-templating.ts +38 -0
  65. package/src/enhance/rules/page-rollup.ts +82 -0
  66. package/src/enhance/tree-walk.ts +29 -0
  67. package/src/enhance/types.ts +48 -0
  68. package/src/enhance/ux-rule-pack.ts +40 -0
  69. package/src/enhance/workbench-defaults.ts +28 -0
  70. package/src/index.ts +80 -0
  71. package/src/manifest/consumer-wrapper-roles.ts +34 -0
  72. package/src/manifest/library-components.ts +46 -0
  73. package/src/manifest/library-style-classes.ts +31 -0
  74. package/src/manifest/library-style-whitelist.ts +82 -0
  75. package/src/manifest/library-ux-taxonomy.ts +103 -0
  76. package/src/paths/monorepo-root.ts +13 -0
  77. package/src/report/facet-output-limits.ts +56 -0
  78. package/src/report/format-scan-stats.ts +18 -0
  79. package/src/report/format-ux-scan-report.ts +59 -0
  80. package/src/report/markdown-report.ts +108 -0
  81. package/src/report/print-facets.ts +129 -0
  82. package/src/report/print-styles.ts +20 -0
  83. package/src/report/print-tree.ts +70 -0
  84. package/src/report/print-ux-findings.ts +53 -0
  85. package/src/report/read-scan-report.ts +201 -0
  86. package/src/report/run-report-scenarios.ts +139 -0
  87. package/src/run-scan.ts +341 -0
  88. package/src/scan/collect-source-files.ts +36 -0
  89. package/src/scan/component-tree.ts +155 -0
  90. package/src/scan/extract-node-attrs.ts +49 -0
  91. package/src/scan/facet-analyze.ts +318 -0
  92. package/src/scan/file-uses-library.ts +37 -0
  93. package/src/scan/library-meta.ts +71 -0
  94. package/src/scan/parse-imports.ts +88 -0
  95. package/src/scan/scan-progress.ts +89 -0
  96. package/src/scan/style-path.ts +26 -0
  97. package/src/scan/style-rules.ts +127 -0
  98. package/src/scan/style-trace.ts +181 -0
  99. package/src/scan/template-hints.ts +70 -0
  100. package/src/types.ts +274 -0
@@ -0,0 +1,318 @@
1
+ import { DEFAULT_FACET_THRESHOLDS } from '../config/defaults.js';
2
+ import type {
3
+ ComponentTreeNode,
4
+ FacetRegion,
5
+ FacetScanConfig,
6
+ FileFacetReport,
7
+ UiscopeFacetThresholds,
8
+ TemplatePatternSignal,
9
+ } from '../types.js';
10
+ import { buildUxRoleResolver, type UxRoleFn, type UxRoleKind } from '../manifest/consumer-wrapper-roles.js';
11
+ import type { UiscopeConfig } from '../types.js';
12
+ import {
13
+ classKeywordFingerprint,
14
+ layoutHintsFromClass,
15
+ type LayoutHint,
16
+ uxRoleForComponent,
17
+ type UxComponentRole,
18
+ } from '../manifest/library-ux-taxonomy.js';
19
+
20
+ function defaultRoleFn(name: string, kind: UxRoleKind): UxComponentRole | undefined {
21
+ return uxRoleForComponent(name, kind);
22
+ }
23
+
24
+ function nodeRoleKind(node: ComponentTreeNode): UxRoleKind {
25
+ if (node.kind === 'root') return 'unknown';
26
+ return node.kind;
27
+ }
28
+
29
+ export const DEFAULT_FACET_CONFIG: FacetScanConfig = facetSlice(DEFAULT_FACET_THRESHOLDS);
30
+
31
+ export function facetSlice(t: UiscopeFacetThresholds): FacetScanConfig {
32
+ return {
33
+ minSubtreeNodes: t.minSubtreeNodes,
34
+ minInteractiveControls: t.minInteractiveControls,
35
+ minFacetComponents: t.minFacetComponents,
36
+ minRepeatedSiblings: t.minRepeatedSiblings,
37
+ classOverlapRatio: t.classOverlapRatio,
38
+ };
39
+ }
40
+
41
+ interface SubtreeStats {
42
+ nodeCount: number;
43
+ byRole: Partial<Record<UxComponentRole, number>>;
44
+ layoutHints: Set<LayoutHint>;
45
+ depth: number;
46
+ }
47
+
48
+ function collectStats(node: ComponentTreeNode, depth: number, roleFn: UxRoleFn): SubtreeStats {
49
+ const stats: SubtreeStats = {
50
+ nodeCount: 1,
51
+ byRole: {},
52
+ layoutHints: new Set(),
53
+ depth,
54
+ };
55
+ const role = roleFn(node.name, nodeRoleKind(node));
56
+ if (role) stats.byRole[role] = (stats.byRole[role] ?? 0) + 1;
57
+ const cls = node.attrs?.class ?? node.attrs?.['custom-class'];
58
+ for (const h of layoutHintsFromClass(cls)) stats.layoutHints.add(h);
59
+
60
+ for (const child of node.children) {
61
+ const sub = collectStats(child, depth + 1, roleFn);
62
+ stats.nodeCount += sub.nodeCount;
63
+ stats.depth = Math.max(stats.depth, sub.depth);
64
+ for (const [k, v] of Object.entries(sub.byRole)) {
65
+ const key = k as UxComponentRole;
66
+ stats.byRole[key] = (stats.byRole[key] ?? 0) + v;
67
+ }
68
+ for (const h of sub.layoutHints) stats.layoutHints.add(h);
69
+ }
70
+ return stats;
71
+ }
72
+
73
+ function interactiveCount(stats: SubtreeStats): number {
74
+ const f = stats.byRole.filter ?? 0;
75
+ const fc = stats.byRole['form-control'] ?? 0;
76
+ return f + fc;
77
+ }
78
+
79
+ function structuralSignature(node: ComponentTreeNode, roleFn: UxRoleFn): string {
80
+ const role = roleFn(node.name, nodeRoleKind(node)) ?? 'x';
81
+ const cls = classKeywordFingerprint(node.attrs?.class).join(',');
82
+ const childOcp = node.children
83
+ .filter((c) => c.kind === 'library')
84
+ .map((c) => c.name)
85
+ .sort()
86
+ .join('+');
87
+ return `${node.kind}:${node.name}:${role}:${cls}:${childOcp}`;
88
+ }
89
+
90
+ function classOverlap(a: string[], b: string[]): number {
91
+ if (!a.length && !b.length) return 1;
92
+ if (!a.length || !b.length) return 0;
93
+ const setB = new Set(b);
94
+ const inter = a.filter((x) => setB.has(x)).length;
95
+ return inter / Math.max(a.length, b.length);
96
+ }
97
+
98
+ function analyzeTemplatePatterns(
99
+ container: ComponentTreeNode,
100
+ config: FacetScanConfig,
101
+ roleFn: UxRoleFn,
102
+ ): TemplatePatternSignal[] {
103
+ const children = flattenStructuralChildren(container);
104
+ if (children.length < config.minRepeatedSiblings) return [];
105
+
106
+ const signatures = children.map((c) => structuralSignature(c, roleFn));
107
+ const classFps = children.map((c) => classKeywordFingerprint(c.attrs?.class));
108
+
109
+ const groups = new Map<string, number[]>();
110
+ signatures.forEach((sig, i) => {
111
+ const list = groups.get(sig) ?? [];
112
+ list.push(i);
113
+ groups.set(sig, list);
114
+ });
115
+
116
+ const signals: TemplatePatternSignal[] = [];
117
+
118
+ for (const [sig, indices] of groups) {
119
+ if (indices.length < config.minRepeatedSiblings) continue;
120
+ const rate = indices.length / children.length;
121
+ signals.push({
122
+ kind: 'repeated-sibling',
123
+ signature: sig,
124
+ count: indices.length,
125
+ templatingRate: Math.round(rate * 1000) / 1000,
126
+ positions: indices,
127
+ note: `同级 ${indices.length}/${children.length} 结构签名一致`,
128
+ });
129
+ }
130
+
131
+ const headN = Math.min(2, children.length);
132
+ const tailN = Math.min(2, children.length);
133
+ if (children.length >= config.minRepeatedSiblings + headN + tailN) {
134
+ const headSig = structuralSignature(children[0], roleFn);
135
+ const tailSig = structuralSignature(children[children.length - 1], roleFn);
136
+ if (headSig === tailSig) {
137
+ const headCls = classFps[0];
138
+ const tailCls = classFps[classFps.length - 1];
139
+ if (classOverlap(headCls, tailCls) >= config.classOverlapRatio) {
140
+ signals.push({
141
+ kind: 'head-tail-mirror',
142
+ signature: headSig,
143
+ count: 2,
144
+ templatingRate: 1,
145
+ positions: [0, children.length - 1],
146
+ note: '容器首尾子节点结构+样式关键词雷同,疑似列表项模板或页眉页脚重复',
147
+ });
148
+ }
149
+ }
150
+ }
151
+
152
+ for (let i = 0; i < children.length - 1; i++) {
153
+ for (let j = i + 1; j < children.length; j++) {
154
+ if (signatures[i] !== signatures[j]) continue;
155
+ if (classOverlap(classFps[i], classFps[j]) >= config.classOverlapRatio && j - i >= 1) {
156
+ const exists = signals.some((s) => s.kind === 'similar-style-cluster' && s.signature === signatures[i]);
157
+ if (!exists) {
158
+ signals.push({
159
+ kind: 'similar-style-cluster',
160
+ signature: signatures[i],
161
+ count: 2,
162
+ templatingRate: 0.5,
163
+ positions: [i, j],
164
+ note: '非相邻但样式关键词重叠的结构重复',
165
+ });
166
+ }
167
+ }
168
+ }
169
+ }
170
+
171
+ return signals;
172
+ }
173
+
174
+ function flattenStructuralChildren(node: ComponentTreeNode): ComponentTreeNode[] {
175
+ const out: ComponentTreeNode[] = [];
176
+ for (const child of node.children) {
177
+ if (child.name === 'template' && child.children.length) {
178
+ out.push(...child.children);
179
+ } else {
180
+ out.push(child);
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+
186
+ function inferFacetKind(
187
+ stats: SubtreeStats,
188
+ layoutHints: LayoutHint[],
189
+ node: ComponentTreeNode,
190
+ ): FacetRegion['kind'] {
191
+ const filters = stats.byRole.filter ?? 0;
192
+ const lists = stats.byRole.list ?? 0;
193
+ const forms = stats.byRole['form-control'] ?? 0;
194
+ const media = stats.byRole.media ?? 0;
195
+ const text = stats.byRole.text ?? 0;
196
+
197
+ if (layoutHints.includes('filter') || filters >= 2) return 'filter-bar';
198
+ if (lists >= 1 || layoutHints.includes('list')) return 'list-region';
199
+ if (layoutHints.includes('grid')) return 'grid-region';
200
+ if (node.name === 'Form' || layoutHints.includes('form')) return 'form-region';
201
+ if (media >= 1 && text >= 2 || layoutHints.includes('mixed')) return 'mixed-media';
202
+ if (forms >= 3 && filters === 0) return 'action-cluster';
203
+ if (node.kind === 'library' && ['Modal', 'Tabs', 'Drawer'].includes(node.name)) return 'composite-chrome';
204
+ return 'interactive-surface';
205
+ }
206
+
207
+ function qualifiesAsFacetRoot(
208
+ stats: SubtreeStats,
209
+ config: FacetScanConfig,
210
+ node: ComponentTreeNode,
211
+ roleFn: UxRoleFn,
212
+ ): boolean {
213
+ const interact = interactiveCount(stats);
214
+ if (stats.nodeCount >= config.minFacetComponents) return true;
215
+ if (stats.nodeCount >= config.minSubtreeNodes) return true;
216
+ if (interact >= config.minInteractiveControls) return true;
217
+ if ((stats.byRole.filter ?? 0) >= 2) return true;
218
+ if ((stats.byRole.list ?? 0) >= 1) return true;
219
+ if (node.kind === 'library' && roleFn(node.name, 'library') === 'container' && stats.nodeCount >= 4) {
220
+ return true;
221
+ }
222
+ return false;
223
+ }
224
+
225
+ function walkFacetCandidates(
226
+ node: ComponentTreeNode,
227
+ path: string,
228
+ config: FacetScanConfig,
229
+ parentCaptured: boolean,
230
+ facets: FacetRegion[],
231
+ depth: number,
232
+ roleFn: UxRoleFn,
233
+ ): void {
234
+ const stats = collectStats(node, 0, roleFn);
235
+ const layoutHints = [...stats.layoutHints];
236
+ const qualified = qualifiesAsFacetRoot(stats, config, node, roleFn);
237
+
238
+ let captured = false;
239
+ if (qualified && (!parentCaptured || depth <= 1)) {
240
+ const children = flattenStructuralChildren(node);
241
+ const templateSignals = analyzeTemplatePatterns(node, config, roleFn);
242
+ const templatingRate =
243
+ templateSignals.length
244
+ ? Math.max(...templateSignals.map((s) => s.templatingRate))
245
+ : 0;
246
+
247
+ facets.push({
248
+ id: path || 'root',
249
+ anchorNode: `${node.kind}:${node.name}`,
250
+ kind: inferFacetKind(stats, layoutHints, node),
251
+ layoutHints,
252
+ depth,
253
+ stats: {
254
+ nodes: stats.nodeCount,
255
+ interactiveControls: interactiveCount(stats),
256
+ roles: stats.byRole,
257
+ },
258
+ templatingRate,
259
+ templateSignals,
260
+ aria: pickAria(node),
261
+ });
262
+ captured = true;
263
+ }
264
+
265
+ for (let i = 0; i < node.children.length; i++) {
266
+ const child = node.children[i];
267
+ const childPath = `${path}/${child.kind}:${child.name}[${i}]`;
268
+ walkFacetCandidates(child, childPath, config, captured || parentCaptured, facets, depth + 1, roleFn);
269
+ }
270
+ }
271
+
272
+ function pickAria(node: ComponentTreeNode): Record<string, string> | undefined {
273
+ if (!node.attrs) return undefined;
274
+ const keys = ['role', 'aria-label', 'aria-labelledby', 'aria-describedby', 'alt', 'title'];
275
+ const out: Record<string, string> = {};
276
+ for (const k of keys) {
277
+ if (node.attrs[k]) out[k] = node.attrs[k];
278
+ }
279
+ return Object.keys(out).length ? out : undefined;
280
+ }
281
+
282
+ export function analyzeFileFacets(
283
+ file: string,
284
+ tree: ComponentTreeNode,
285
+ config: FacetScanConfig = DEFAULT_FACET_CONFIG,
286
+ scanConfig?: UiscopeConfig,
287
+ roleFn?: UxRoleFn,
288
+ ): FileFacetReport {
289
+ const resolve = roleFn ?? (scanConfig ? buildUxRoleResolver(scanConfig) : defaultRoleFn);
290
+ const facets: FacetRegion[] = [];
291
+ walkFacetCandidates(tree, '', config, false, facets, 0, resolve);
292
+
293
+ const deduped = dedupeOverlappingFacets(facets);
294
+ const avgTemplate =
295
+ deduped.length
296
+ ? deduped.reduce((s, f) => s + f.templatingRate, 0) / deduped.length
297
+ : 0;
298
+
299
+ return {
300
+ file,
301
+ facetCount: deduped.length,
302
+ avgTemplatingRate: Math.round(avgTemplate * 1000) / 1000,
303
+ facets: deduped,
304
+ };
305
+ }
306
+
307
+ /** 去掉完全被父切面包含且同类的小切面 */
308
+ function dedupeOverlappingFacets(facets: FacetRegion[]): FacetRegion[] {
309
+ const sorted = [...facets].sort((a, b) => b.stats.nodes - a.stats.nodes);
310
+ const kept: FacetRegion[] = [];
311
+ for (const f of sorted) {
312
+ const dominated = kept.some(
313
+ (k) => k.id.length < f.id.length && f.id.startsWith(k.id) && k.kind === f.kind && f.stats.nodes <= k.stats.nodes * 0.6,
314
+ );
315
+ if (!dominated) kept.push(f);
316
+ }
317
+ return kept.sort((a, b) => a.id.localeCompare(b.id));
318
+ }
@@ -0,0 +1,37 @@
1
+ import { parse as parseSfc } from '@vue/compiler-sfc';
2
+ import type { UiscopeConfig } from '../types.js';
3
+ import { parseScriptImports } from './parse-imports.js';
4
+
5
+ /**
6
+ * 判断 Vue 文件是否消费设计库:脚本 import 或模板中出现库组件名。
7
+ */
8
+ export function fileUsesLibrary(
9
+ source: string,
10
+ config: UiscopeConfig,
11
+ libraryComponentNames: Set<string>,
12
+ ): boolean {
13
+ const { descriptor, errors } = parseSfc(source);
14
+ if (errors.length) return false;
15
+
16
+ const script =
17
+ descriptor.scriptSetup?.content ?? descriptor.script?.content ?? '';
18
+ if (parseScriptImports(script, config).some((b) => b.fromLibrary)) return true;
19
+
20
+ const tpl = descriptor.template?.content ?? '';
21
+ if (!tpl) return false;
22
+
23
+ for (const name of libraryComponentNames) {
24
+ const pascal = name;
25
+ const kebab = name.replace(/([A-Z])/g, '-$1').replace(/^-/, '').toLowerCase();
26
+ if (new RegExp(`<${pascal}[\\s/>]`, '').test(tpl)) return true;
27
+ if (new RegExp(`<${kebab}[\\s/>]`, 'i').test(tpl)) return true;
28
+ }
29
+
30
+ for (const tag of config.consumerWrapperTags ?? []) {
31
+ const kebab = tag.replace(/([A-Z])/g, '-$1').replace(/^-/, '').toLowerCase();
32
+ if (new RegExp(`<${tag}[\\s/>]`, '').test(tpl)) return true;
33
+ if (new RegExp(`<${kebab}[\\s/>]`, 'i').test(tpl)) return true;
34
+ }
35
+
36
+ return false;
37
+ }
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const FILE_HEADER_DOC_RE = /^[\s\S]*?<template[\s>]/i;
5
+
6
+ /** 取 SFC 顶部 HTML 注释块(组件自述文档) */
7
+ export function extractSfcHeaderComment(source: string): string | undefined {
8
+ const head = source.slice(0, Math.min(source.length, 8000));
9
+ const match = head.match(/^\s*<!--([\s\S]*?)-->/);
10
+ if (!match) return undefined;
11
+ return match[1]
12
+ .replace(/&lt;/g, '<')
13
+ .replace(/&gt;/g, '>')
14
+ .replace(/&amp;/g, '&')
15
+ .trim();
16
+ }
17
+
18
+ function findComponentVuePath(libraryRoot: string, componentName: string): string | undefined {
19
+ if (!fs.existsSync(libraryRoot)) return undefined;
20
+ let found: string | undefined;
21
+ const walk = (dir: string) => {
22
+ if (found) return;
23
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
24
+ const full = path.join(dir, ent.name);
25
+ if (ent.isDirectory()) walk(full);
26
+ else if (ent.name === `${componentName}.vue`) found = full;
27
+ }
28
+ };
29
+ walk(libraryRoot);
30
+ return found;
31
+ }
32
+
33
+ const docCache = new Map<string, string | undefined>();
34
+
35
+ export function libraryComponentDoc(
36
+ libraryRoot: string,
37
+ componentName: string,
38
+ ): string | undefined {
39
+ const key = `${libraryRoot}::${componentName}`;
40
+ if (docCache.has(key)) return docCache.get(key);
41
+ const file = findComponentVuePath(libraryRoot, componentName);
42
+ if (!file) {
43
+ docCache.set(key, undefined);
44
+ return undefined;
45
+ }
46
+ const doc = extractSfcHeaderComment(fs.readFileSync(file, 'utf8'));
47
+ docCache.set(key, doc);
48
+ return doc;
49
+ }
50
+
51
+ /** 从库组件 SFC 收集模板/样式中出现的白名单候选类名 */
52
+ export function discoverClassesInVueSource(source: string): Set<string> {
53
+ const classes = new Set<string>();
54
+ const patterns = [
55
+ /class=["']([^"']+)["']/g,
56
+ /class:\s*["']([^"']+)["']/g,
57
+ /\.([a-z][\w-]*)/gi,
58
+ ];
59
+ for (const re of patterns) {
60
+ let m: RegExpExecArray | null;
61
+ re.lastIndex = 0;
62
+ while ((m = re.exec(source)) !== null) {
63
+ const chunk = m[1];
64
+ for (const token of chunk.split(/\s+/)) {
65
+ const norm = token.replace(/^['"]|['"]$/g, '');
66
+ if (/^[a-z][\w-]*$/i.test(norm)) classes.add(norm);
67
+ }
68
+ }
69
+ }
70
+ return classes;
71
+ }
@@ -0,0 +1,88 @@
1
+ import type { UiscopeConfig } from '../types.js';
2
+
3
+ export interface ImportBinding {
4
+ local: string;
5
+ fromLibrary: boolean;
6
+ source: string;
7
+ }
8
+
9
+ const IMPORT_RE =
10
+ /import\s+(?:type\s+)?(?:(\*\s+as\s+(\w+))|(?:\{([^}]+)\})|(\w+))\s+from\s+['"]([^'"]+)['"]/g;
11
+
12
+ function isLibrarySource(source: string, patterns: string[]): boolean {
13
+ return patterns.some((p) => source === p || source.startsWith(p));
14
+ }
15
+
16
+ export function parseScriptImports(script: string, config: UiscopeConfig): ImportBinding[] {
17
+ const bindings: ImportBinding[] = [];
18
+ let match: RegExpExecArray | null;
19
+ IMPORT_RE.lastIndex = 0;
20
+ while ((match = IMPORT_RE.exec(script)) !== null) {
21
+ const namespace = match[2];
22
+ const named = match[3];
23
+ const defaultName = match[4];
24
+ const source = match[5];
25
+ const fromLibrary = isLibrarySource(source, config.libraryImportSources);
26
+ if (namespace) {
27
+ bindings.push({ local: namespace, fromLibrary, source });
28
+ }
29
+ if (defaultName) {
30
+ bindings.push({ local: defaultName, fromLibrary, source });
31
+ }
32
+ if (named) {
33
+ for (const part of named.split(',')) {
34
+ const trimmed = part.trim();
35
+ if (!trimmed) continue;
36
+ const aliasMatch = trimmed.match(/^(\w+)(?:\s+as\s+(\w+))?$/);
37
+ if (!aliasMatch) continue;
38
+ const exported = aliasMatch[1];
39
+ const local = aliasMatch[2] ?? exported;
40
+ bindings.push({ local, fromLibrary, source: fromLibrary ? `lib:${exported}` : source });
41
+ }
42
+ }
43
+ }
44
+ return bindings;
45
+ }
46
+
47
+ export function buildTagResolver(
48
+ bindings: ImportBinding[],
49
+ libraryComponentNames: Set<string>,
50
+ ): (tag: string) => { kind: 'library' | 'local' | 'html' | 'unknown'; name: string; source?: string } {
51
+ const localToBinding = new Map(bindings.map((b) => [b.local, b]));
52
+ const libraryLower = new Map([...libraryComponentNames].map((n) => [n.toLowerCase(), n]));
53
+
54
+ return (rawTag: string) => {
55
+ const tag = rawTag;
56
+ if (tag.includes('.')) {
57
+ const [base] = tag.split('.');
58
+ return resolve(base);
59
+ }
60
+ return resolve(tag);
61
+ };
62
+
63
+ function resolve(tag: string) {
64
+ const pascal =
65
+ tag.includes('-')
66
+ ? tag
67
+ .split('-')
68
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
69
+ .join('')
70
+ : tag;
71
+
72
+ const binding = localToBinding.get(pascal) ?? localToBinding.get(tag);
73
+ if (binding?.fromLibrary) {
74
+ return { kind: 'library' as const, name: pascal, source: binding.source };
75
+ }
76
+ if (binding) {
77
+ return { kind: 'local' as const, name: pascal, source: binding.source };
78
+ }
79
+ const libraryName = libraryLower.get(pascal.toLowerCase()) ?? libraryLower.get(tag.toLowerCase());
80
+ if (libraryName) {
81
+ return { kind: 'library' as const, name: libraryName, source: 'lib:intrinsic' };
82
+ }
83
+ if (/^[a-z][\w-]*$/.test(tag)) {
84
+ return { kind: 'html' as const, name: tag };
85
+ }
86
+ return { kind: 'unknown' as const, name: pascal };
87
+ }
88
+ }
@@ -0,0 +1,89 @@
1
+ import path from 'node:path';
2
+
3
+ export type ScanPhase = 'collect' | 'vue' | 'facets' | 'ux-enhance' | 'styles' | 'done';
4
+
5
+ export interface ScanProgressEvent {
6
+ phase: ScanPhase;
7
+ current: number;
8
+ total: number;
9
+ /** 当前文件或阶段摘要 */
10
+ label?: string;
11
+ }
12
+
13
+ export type ScanProgressHandler = (event: ScanProgressEvent) => void;
14
+
15
+ const PHASE_LABEL: Record<ScanPhase, string> = {
16
+ collect: '发现源文件',
17
+ vue: '解析 Vue',
18
+ facets: '切面分析',
19
+ 'ux-enhance': 'UX 规则',
20
+ styles: '样式扫描',
21
+ done: '完成',
22
+ };
23
+
24
+ export function emitScanProgress(
25
+ handler: ScanProgressHandler | undefined,
26
+ event: ScanProgressEvent,
27
+ ): void {
28
+ handler?.(event);
29
+ }
30
+
31
+ export interface TerminalProgressOptions {
32
+ /** 默认 stderr */
33
+ stream?: NodeJS.WritableStream;
34
+ /** 最小刷新间隔 ms,默认 80 */
35
+ throttleMs?: number;
36
+ /** 非 TTY 时每隔多少步输出一行,默认 25 */
37
+ nonTtyStep?: number;
38
+ }
39
+
40
+ export function createTerminalProgressReporter(
41
+ options: TerminalProgressOptions = {},
42
+ ): ScanProgressHandler {
43
+ const stream = options.stream ?? process.stderr;
44
+ const throttleMs = options.throttleMs ?? 80;
45
+ const nonTtyStep = options.nonTtyStep ?? 25;
46
+ const isTty = Boolean((stream as NodeJS.WriteStream).isTTY);
47
+ let lastWrite = 0;
48
+ let lastLine = '';
49
+
50
+ return (event) => {
51
+ if (event.phase === 'done') {
52
+ if (isTty && lastLine) {
53
+ stream.write('\r\x1b[K');
54
+ }
55
+ stream.write(`[uiscope] ${PHASE_LABEL.done}\n`);
56
+ return;
57
+ }
58
+
59
+ const phaseName = PHASE_LABEL[event.phase] ?? event.phase;
60
+ const total = event.total > 0 ? event.total : 1;
61
+ const pct = Math.min(100, Math.round((event.current / total) * 100));
62
+ const file = event.label ? ` ${basenameLabel(event.label)}` : '';
63
+ const line = `[uiscope] ${phaseName} ${event.current}/${event.total} (${pct}%)${file}`;
64
+
65
+ const now = Date.now();
66
+ const isLast = event.current >= event.total;
67
+
68
+ if (!isTty) {
69
+ const shouldLog =
70
+ isLast
71
+ || event.current === 1
72
+ || event.current % nonTtyStep === 0;
73
+ if (shouldLog) stream.write(`${line}\n`);
74
+ return;
75
+ }
76
+
77
+ if (!isLast && now - lastWrite < throttleMs) return;
78
+ lastWrite = now;
79
+ lastLine = line;
80
+ stream.write(`\r\x1b[K${line}`);
81
+ if (isLast) stream.write('\n');
82
+ };
83
+ }
84
+
85
+ function basenameLabel(label: string): string {
86
+ const trimmed = label.trim();
87
+ if (trimmed.includes(' vue')) return trimmed;
88
+ return path.basename(trimmed);
89
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 样式文件路径排除(轻量 glob,无额外依赖)
3
+ */
4
+ export function isStylePathExcluded(filePath: string, globs: string[]): boolean {
5
+ if (!globs.length) return false;
6
+ const norm = filePath.replace(/\\/g, '/').toLowerCase();
7
+ for (const raw of globs) {
8
+ const g = raw.replace(/\\/g, '/').toLowerCase();
9
+ if (g.includes('*')) {
10
+ const parts = g.split('**');
11
+ if (parts.length === 2) {
12
+ const [prefix, suffix] = parts;
13
+ if (prefix && !norm.includes(prefix.replace(/^\//, ''))) continue;
14
+ if (suffix && !norm.endsWith(suffix.replace(/^\//, ''))) continue;
15
+ return true;
16
+ }
17
+ const re = new RegExp(
18
+ `^${g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '.*').replace(/\*/g, '[^/]*')}$`,
19
+ );
20
+ if (re.test(norm)) return true;
21
+ } else if (norm.endsWith(g) || norm.includes(`/${g}`) || norm.includes(g)) {
22
+ return true;
23
+ }
24
+ }
25
+ return false;
26
+ }