@md-code/component-uniqueness 0.1.3 → 0.3.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 (188) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +202 -0
  3. package/README.md +21 -3
  4. package/dist/config.d.ts +50 -0
  5. package/dist/config.js +402 -0
  6. package/dist/constants.d.ts +55 -0
  7. package/dist/constants.js +86 -0
  8. package/dist/decision-maker.d.ts +39 -0
  9. package/dist/decision-maker.js +119 -0
  10. package/dist/filter/child-element.d.ts +3 -0
  11. package/dist/filter/child-element.js +17 -0
  12. package/dist/filter/missing-component.d.ts +10 -0
  13. package/dist/filter/missing-component.js +96 -0
  14. package/dist/filter/no-structure.d.ts +3 -0
  15. package/dist/filter/no-structure.js +16 -0
  16. package/dist/filter/usages.d.ts +3 -0
  17. package/dist/filter/usages.js +14 -0
  18. package/dist/index.d.ts +105 -0
  19. package/dist/index.js +244 -0
  20. package/dist/lib-registry.d.ts +4 -0
  21. package/dist/lib-registry.js +376 -0
  22. package/dist/logger.d.ts +7 -0
  23. package/dist/logger.js +70 -0
  24. package/dist/main.d.ts +25 -0
  25. package/dist/main.js +666 -0
  26. package/dist/matcher/a11y.d.ts +19 -0
  27. package/dist/matcher/a11y.js +311 -0
  28. package/dist/matcher/behavior.d.ts +10 -0
  29. package/dist/matcher/behavior.js +32 -0
  30. package/dist/matcher/css-matching.d.ts +18 -0
  31. package/dist/matcher/css-matching.js +159 -0
  32. package/dist/matcher/framework/index.d.ts +2 -0
  33. package/dist/matcher/framework/index.js +37 -0
  34. package/dist/matcher/framework/react.d.ts +12 -0
  35. package/dist/matcher/framework/react.js +70 -0
  36. package/dist/matcher/index.d.ts +64 -0
  37. package/dist/matcher/index.js +38 -0
  38. package/dist/matcher/name.d.ts +15 -0
  39. package/dist/matcher/name.js +154 -0
  40. package/dist/matcher/structure.d.ts +22 -0
  41. package/dist/matcher/structure.js +329 -0
  42. package/dist/matcher/styles.d.ts +20 -0
  43. package/dist/matcher/styles.js +49 -0
  44. package/dist/normalize/candidate.d.ts +3 -0
  45. package/dist/normalize/candidate.js +21 -0
  46. package/dist/normalize/dom.d.ts +22 -0
  47. package/dist/normalize/dom.js +180 -0
  48. package/dist/normalize/external-html.d.ts +5 -0
  49. package/dist/normalize/external-html.js +40 -0
  50. package/dist/normalize/framework.d.ts +20 -0
  51. package/dist/normalize/framework.js +130 -0
  52. package/dist/normalize/resolver.d.ts +7 -0
  53. package/dist/normalize/resolver.js +28 -0
  54. package/dist/normalize/style-resolver.d.ts +7 -0
  55. package/dist/normalize/style-resolver.js +28 -0
  56. package/dist/normalize/style.d.ts +15 -0
  57. package/dist/normalize/style.js +174 -0
  58. package/dist/normalize/words.d.ts +3 -0
  59. package/dist/normalize/words.js +40 -0
  60. package/dist/package.json +88 -0
  61. package/dist/playgrounds/angular.d.ts +7 -0
  62. package/dist/playgrounds/angular.js +9 -0
  63. package/dist/playgrounds/framework-entrypoint.d.ts +10 -0
  64. package/dist/playgrounds/framework-entrypoint.js +102 -0
  65. package/dist/playgrounds/framework.d.ts +10 -0
  66. package/dist/playgrounds/framework.js +102 -0
  67. package/dist/playgrounds/react.d.ts +14 -0
  68. package/dist/playgrounds/react.js +1288 -0
  69. package/dist/playgrounds/scss.d.ts +6 -0
  70. package/dist/playgrounds/scss.js +9 -0
  71. package/dist/playgrounds/style-entrypoint.d.ts +13 -0
  72. package/dist/playgrounds/style-entrypoint.js +82 -0
  73. package/dist/playgrounds/style.d.ts +13 -0
  74. package/dist/playgrounds/style.js +82 -0
  75. package/dist/playgrounds/styled-components.d.ts +7 -0
  76. package/dist/playgrounds/styled-components.js +190 -0
  77. package/dist/playgrounds/tailwind.d.ts +15 -0
  78. package/dist/playgrounds/tailwind.js +256 -0
  79. package/dist/playgrounds/vue.d.ts +7 -0
  80. package/dist/playgrounds/vue.js +9 -0
  81. package/dist/report/asks.d.ts +27 -0
  82. package/dist/report/asks.js +28 -0
  83. package/dist/report/cli-report.d.ts +7 -0
  84. package/dist/report/cli-report.js +187 -0
  85. package/dist/report/codes/index.d.ts +37 -0
  86. package/dist/report/codes/index.js +31 -0
  87. package/dist/report/errorTypes/index.d.ts +92 -0
  88. package/dist/report/errorTypes/index.js +186 -0
  89. package/dist/report/evidence.d.ts +2 -0
  90. package/dist/report/evidence.js +8 -0
  91. package/dist/report/explain.d.ts +27 -0
  92. package/dist/report/explain.js +76 -0
  93. package/dist/report/index.d.ts +2 -0
  94. package/dist/report/index.js +24 -0
  95. package/dist/report/matchers/a11y/model.d.ts +20 -0
  96. package/dist/report/matchers/a11y/model.js +14 -0
  97. package/dist/report/matchers/a11y/text.d.ts +2 -0
  98. package/dist/report/matchers/a11y/text.js +22 -0
  99. package/dist/report/matchers/behavior/model.d.ts +20 -0
  100. package/dist/report/matchers/behavior/model.js +12 -0
  101. package/dist/report/matchers/behavior/text.d.ts +2 -0
  102. package/dist/report/matchers/behavior/text.js +22 -0
  103. package/dist/report/matchers/framework/model.d.ts +10 -0
  104. package/dist/report/matchers/framework/model.js +39 -0
  105. package/dist/report/matchers/framework/text.d.ts +2 -0
  106. package/dist/report/matchers/framework/text.js +26 -0
  107. package/dist/report/matchers/index.d.ts +5 -0
  108. package/dist/report/matchers/index.js +97 -0
  109. package/dist/report/matchers/name/model.d.ts +20 -0
  110. package/dist/report/matchers/name/model.js +30 -0
  111. package/dist/report/matchers/name/text.d.ts +2 -0
  112. package/dist/report/matchers/name/text.js +17 -0
  113. package/dist/report/matchers/set-model.d.ts +31 -0
  114. package/dist/report/matchers/set-model.js +42 -0
  115. package/dist/report/matchers/structure/model.d.ts +10 -0
  116. package/dist/report/matchers/structure/model.js +58 -0
  117. package/dist/report/matchers/structure/text.d.ts +2 -0
  118. package/dist/report/matchers/structure/text.js +40 -0
  119. package/dist/report/matchers/styles/model.d.ts +11 -0
  120. package/dist/report/matchers/styles/model.js +36 -0
  121. package/dist/report/matchers/styles/text.d.ts +2 -0
  122. package/dist/report/matchers/styles/text.js +40 -0
  123. package/dist/report/user-report/build/bundle.d.ts +3 -0
  124. package/dist/report/user-report/build/bundle.js +185 -0
  125. package/dist/report/user-report/build/bundle.prebuilt.js +955 -0
  126. package/dist/report/user-report/data/collect.d.ts +68 -0
  127. package/dist/report/user-report/data/collect.js +150 -0
  128. package/dist/report/user-report/data/folders.d.ts +3 -0
  129. package/dist/report/user-report/data/folders.js +73 -0
  130. package/dist/report/user-report/data/groups.d.ts +13 -0
  131. package/dist/report/user-report/data/groups.js +76 -0
  132. package/dist/report/user-report/data/links.d.ts +39 -0
  133. package/dist/report/user-report/data/links.js +222 -0
  134. package/dist/report/user-report/data/snapshot.d.ts +9 -0
  135. package/dist/report/user-report/data/snapshot.js +180 -0
  136. package/dist/report/user-report/data/source.d.ts +13 -0
  137. package/dist/report/user-report/data/source.js +58 -0
  138. package/dist/report/user-report/data/word.d.ts +3 -0
  139. package/dist/report/user-report/data/word.js +32 -0
  140. package/dist/report/user-report/html/shell.d.ts +2 -0
  141. package/dist/report/user-report/html/shell.js +27 -0
  142. package/dist/report/user-report/index.d.ts +7 -0
  143. package/dist/report/user-report/index.js +47 -0
  144. package/dist/report/vocabulary/evidence.d.ts +48 -0
  145. package/dist/report/vocabulary/evidence.js +66 -0
  146. package/dist/report/vocabulary/format.d.ts +4 -0
  147. package/dist/report/vocabulary/format.js +20 -0
  148. package/dist/report/vocabulary/labels.d.ts +134 -0
  149. package/dist/report/vocabulary/labels.js +87 -0
  150. package/dist/report/vocabulary/phrases.d.ts +20 -0
  151. package/dist/report/vocabulary/phrases.js +34 -0
  152. package/dist/self-catalog.d.ts +4 -0
  153. package/dist/self-catalog.js +179 -0
  154. package/dist/utils.d.ts +6 -0
  155. package/dist/utils.js +125 -0
  156. package/package.json +86 -60
  157. package/config.js +0 -362
  158. package/decision-maker.js +0 -109
  159. package/filter/drop-child-element.js +0 -13
  160. package/filter/drop-usages.js +0 -13
  161. package/filter/missing-component.js +0 -68
  162. package/index.js +0 -184
  163. package/logger.js +0 -44
  164. package/main.js +0 -539
  165. package/matcher/a11y.js +0 -65
  166. package/matcher/behavior.js +0 -31
  167. package/matcher/framework/index.js +0 -15
  168. package/matcher/framework/react.js +0 -25
  169. package/matcher/index.js +0 -36
  170. package/matcher/name.js +0 -132
  171. package/matcher/structure.js +0 -208
  172. package/normalize/candidate.js +0 -22
  173. package/normalize/dom.js +0 -167
  174. package/normalize/framework.js +0 -129
  175. package/normalize/style-resolver.js +0 -24
  176. package/normalize/style.js +0 -175
  177. package/normalize/words.js +0 -40
  178. package/playgrounds/angular.js +0 -11
  179. package/playgrounds/framework-entrypoint.js +0 -90
  180. package/playgrounds/react.js +0 -997
  181. package/playgrounds/scss.js +0 -7
  182. package/playgrounds/style-entrypoint.js +0 -78
  183. package/playgrounds/styled-components.js +0 -138
  184. package/playgrounds/tailwind.js +0 -186
  185. package/playgrounds/vue.js +0 -11
  186. package/plugin.js +0 -3
  187. package/report.js +0 -159
  188. package/utils.js +0 -92
package/dist/main.js ADDED
@@ -0,0 +1,666 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || function (mod) {
20
+ if (mod && mod.__esModule) return mod;
21
+ var result = {};
22
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
+ __setModuleDefault(result, mod);
24
+ return result;
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.buildComponentReport = exports.comparableCanons = exports.frameworkMatcher = exports.findParts = exports.collectRawHtml = exports.applyFilters = exports.matchPairs = exports.parseComponents = exports.buildCandidate = void 0;
28
+ const fs = __importStar(require("node:fs"));
29
+ const path = __importStar(require("node:path"));
30
+ const node_module_1 = require("node:module");
31
+ // The overview bundle is loaded lazily so the ESLint rule never touches esbuild;
32
+ // `createRequire` keeps it out of the module's import graph.
33
+ const lazyRequire = (0, node_module_1.createRequire)(__filename);
34
+ const config_1 = require("./config");
35
+ const utils_1 = require("./utils");
36
+ const framework_js_1 = require("./playgrounds/framework.js");
37
+ const candidate_js_1 = require("./normalize/candidate.js");
38
+ Object.defineProperty(exports, "buildCandidate", { enumerable: true, get: function () { return candidate_js_1.buildCandidate; } });
39
+ const dom_js_1 = require("./normalize/dom.js");
40
+ const matcher_1 = require("./matcher");
41
+ const framework_1 = require("./matcher/framework");
42
+ const decision_maker_1 = require("./decision-maker");
43
+ const dropUsages = __importStar(require("./filter/usages"));
44
+ const dropChildElement = __importStar(require("./filter/child-element"));
45
+ const dropNoStructure = __importStar(require("./filter/no-structure"));
46
+ const missing_component_1 = require("./filter/missing-component");
47
+ const report_1 = require("./report");
48
+ const log = __importStar(require("./logger"));
49
+ const FILTERS = [dropUsages, dropChildElement, dropNoStructure];
50
+ const frameworkMatcher = (0, framework_1.getFrameworkMatcher)("react");
51
+ exports.frameworkMatcher = frameworkMatcher;
52
+ const treeSummary = (tree) => {
53
+ if (!tree)
54
+ return null;
55
+ const walk = (n) => {
56
+ const kids = (n.children || []).map(walk);
57
+ return { tag: n.tag, css: n.css ? Object.keys(n.css).length : 0, children: kids };
58
+ };
59
+ return walk(tree);
60
+ };
61
+ const candidateSummary = (c, role) => ({
62
+ role,
63
+ name: c.name,
64
+ path: c.path,
65
+ rootTags: c.rootTags,
66
+ tree: treeSummary(c.tree),
67
+ domTree: treeSummary(c.dom && c.dom.tree),
68
+ framework: c.framework ? { props: c.framework.props, events: c.framework.events, names: c.framework.names, open: c.framework.open } : null,
69
+ a11y: c.a11y,
70
+ });
71
+ const fail = (message) => {
72
+ console.error(`[component-uniqueness] ${message}`);
73
+ process.exit(1);
74
+ };
75
+ const parseArgs = (argv) => {
76
+ const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, overview: null, appRoots: null, files: null, ignoreDirs: null, verbose: false, include: null, log: null, minCluster: 3, thresholds: null, rawHtml: false, parts: false, configFile: null };
77
+ for (let i = 0; i < argv.length; i += 1) {
78
+ const a = argv[i];
79
+ if (a === "--check") {
80
+ cfg.check = true;
81
+ }
82
+ else if (a === "--report") {
83
+ const next = argv[i + 1];
84
+ if (next && !next.startsWith("--")) {
85
+ cfg.report = argv[++i];
86
+ }
87
+ else {
88
+ cfg.report = "reports/component-duplicates-components.md";
89
+ }
90
+ }
91
+ else if (a === "--overview") {
92
+ const next = argv[i + 1];
93
+ cfg.overview = next && !next.startsWith("--") ? argv[++i] : "reports/component-overview.html";
94
+ }
95
+ else if (a === "--roots") {
96
+ if (!argv[i + 1])
97
+ fail("--roots requires a value (colon-separated list of directories)");
98
+ cfg.roots = argv[++i].split(":").filter(Boolean);
99
+ }
100
+ else if (a === "--out") {
101
+ if (!argv[i + 1])
102
+ fail("--out requires a value");
103
+ cfg.out = argv[++i];
104
+ }
105
+ else if (a === "--registry") {
106
+ if (!argv[i + 1])
107
+ fail("--registry requires a value");
108
+ cfg.registry = argv[++i];
109
+ }
110
+ else if (a === "--repo-root") {
111
+ if (!argv[i + 1])
112
+ fail("--repo-root requires a value");
113
+ cfg.repoRoot = argv[++i];
114
+ }
115
+ else if (a === "--app-roots") {
116
+ if (!argv[i + 1])
117
+ fail("--app-roots requires a value (colon-separated list of directories)");
118
+ cfg.appRoots = argv[++i].split(":").filter(Boolean);
119
+ }
120
+ else if (a === "--files") {
121
+ if (!argv[i + 1])
122
+ fail("--files requires a value (colon-separated list of files)");
123
+ cfg.files = argv[++i].split(":").filter(Boolean);
124
+ }
125
+ else if (a === "--ignore-dirs") {
126
+ if (!argv[i + 1])
127
+ fail("--ignore-dirs requires a value (colon-separated list of directory names)");
128
+ cfg.ignoreDirs = argv[++i].split(":").filter(Boolean);
129
+ }
130
+ else if (a === "--raw-html") {
131
+ cfg.rawHtml = true;
132
+ }
133
+ else if (a === "--parts") {
134
+ cfg.parts = true;
135
+ }
136
+ else if (a === "--verbose") {
137
+ cfg.verbose = true;
138
+ }
139
+ else if (a === "--include") {
140
+ if (!argv[i + 1])
141
+ fail("--include requires a value (colon-separated list of file globs, e.g. a.tsx:b.tsx)");
142
+ cfg.include = argv[++i].split(":").filter(Boolean);
143
+ }
144
+ else if (a === "--log") {
145
+ if (!argv[i + 1])
146
+ fail("--log requires a value (path to the stage log file)");
147
+ cfg.log = argv[++i];
148
+ }
149
+ else if (a === "--thresholds") {
150
+ if (!argv[i + 1])
151
+ fail("--thresholds requires a value (duplicate:similar, e.g. 0.5:0.2)");
152
+ const [dup, sim] = argv[++i].split(":").map((s) => Number.parseFloat(s));
153
+ if (!Number.isFinite(dup) || !Number.isFinite(sim))
154
+ fail("--thresholds must be two numbers separated by a colon (duplicate:similar)");
155
+ cfg.thresholds = { duplicate: dup, similar: sim };
156
+ }
157
+ else if (a === "--min-cluster") {
158
+ if (!argv[i + 1])
159
+ fail("--min-cluster requires a value (min app components matching one canonical to flag it as a missing component)");
160
+ const n = Number.parseInt(argv[i + 1], 10);
161
+ if (!Number.isFinite(n) || n < 2)
162
+ fail("--min-cluster must be an integer >= 2");
163
+ cfg.minCluster = n;
164
+ i += 1;
165
+ }
166
+ else if (a === "--config") {
167
+ if (!argv[i + 1])
168
+ fail("--config requires a value (path to an eslint.config.js or a standalone options file)");
169
+ cfg.configFile = argv[++i];
170
+ }
171
+ else if (a === "--help" || a === "-h") {
172
+ console.log("Usage: component-uniqueness [--roots a:b] [--out file] [--registry file] [--repo-root dir] [--check] [--report [file.md]] [--app-roots a:b] [--files a.tsx:b.tsx] [--ignore-dirs a:b] [--include a.tsx:b.tsx] [--thresholds dup:sim] [--raw-html] [--parts] [--config file] [--log file] [--min-cluster N] [--verbose]");
173
+ console.log("Rule options (weights, thresholds, rawHtml, parts, include, ignoreDirs) are read from the consumer's eslint.config.js (rule md-code/component-uniqueness) or md-code-component-uniqueness.config.js; --config points to a specific file. CLI flags override the config.");
174
+ process.exit(0);
175
+ }
176
+ else {
177
+ fail(`unknown argument: ${a} (see --help)`);
178
+ }
179
+ }
180
+ return cfg;
181
+ };
182
+ const resolveAgainst = (value, repoRoot) => {
183
+ return path.isAbsolute(value) ? value : path.resolve(repoRoot, value);
184
+ };
185
+ const relPosix = (repoRoot, abs) => {
186
+ return path.relative(repoRoot, abs).split(path.sep).join("/");
187
+ };
188
+ const collectFiles = (roots, repoRoot, shouldSkip, skipDirs, exts, ignoreDirs) => {
189
+ const files = [];
190
+ let count = 0;
191
+ for (const relRoot of roots) {
192
+ const rootDir = resolveAgainst(relRoot, repoRoot);
193
+ if (!fs.existsSync(rootDir))
194
+ continue;
195
+ for (const file of (0, utils_1.walk)(rootDir, exts, ignoreDirs)) {
196
+ if (shouldSkip(file))
197
+ continue;
198
+ if (skipDirs && [...skipDirs].some((d) => file === d || file.startsWith(d + path.sep)))
199
+ continue;
200
+ const rel = relPosix(repoRoot, file);
201
+ count += 1;
202
+ files.push({ file, rel });
203
+ }
204
+ }
205
+ return { files, count };
206
+ };
207
+ const parseComponents = (files, canonNames, config, role = "CANONICAL") => {
208
+ const comps = [];
209
+ for (const { file, rel } of files) {
210
+ let parsed;
211
+ let source;
212
+ try {
213
+ source = fs.readFileSync(file, "utf8");
214
+ parsed = (0, framework_js_1.parseComponents)(file, canonNames, config);
215
+ }
216
+ catch (err) {
217
+ console.warn(`[component-uniqueness] could not parse ${rel}: ${err && err.message ? err.message : err}`);
218
+ continue;
219
+ }
220
+ for (const c of parsed) {
221
+ if (log.enabled()) {
222
+ log.stage("normalizer:before", { role, file: rel, name: c.name, tree: treeSummary(c.tree), rootTags: c.rootTags, a11y: c.a11y });
223
+ }
224
+ const candidate = (0, candidate_js_1.buildCandidate)(c, config);
225
+ const withPath = { ...candidate, path: rel };
226
+ if (log.enabled()) {
227
+ log.stage("normalizer:after", { role, file: rel, name: c.name, tree: treeSummary(c.tree), domTree: treeSummary(candidate.dom && candidate.dom.tree), framework: { props: candidate.framework.props, events: candidate.framework.events, names: candidate.framework.names, open: candidate.framework.open } });
228
+ }
229
+ comps.push(withPath);
230
+ }
231
+ }
232
+ return comps;
233
+ };
234
+ exports.parseComponents = parseComponents;
235
+ const matchPairs = (appComponents, canonComponents, config) => {
236
+ const canonNames = [...new Set(canonComponents.map((c) => c.name))];
237
+ const matches = [];
238
+ for (const app of appComponents) {
239
+ for (const canon of canonComponents) {
240
+ if (canon.path === app.path && canon.name === app.name)
241
+ continue;
242
+ if (!(0, config_1.canSeeCanon)(app.path, canon.path, config.componentsFolder, config.compareAll))
243
+ continue;
244
+ if (log.enabled()) {
245
+ log.stage("matcher:before", { app: candidateSummary(app, "candidate"), canon: candidateSummary(canon, "canonical") });
246
+ }
247
+ const signals = (0, matcher_1.matchSignals)(app, canon, { canonNames, frameworkMatcher });
248
+ if (log.enabled()) {
249
+ log.stage("matcher:after", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
250
+ }
251
+ if (log.enabled()) {
252
+ log.stage("decision:before", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, signals });
253
+ }
254
+ const decision = (0, decision_maker_1.decide)(app, canon, { signals, weights: config.weights, thresholds: config.thresholds });
255
+ if (log.enabled()) {
256
+ log.stage("decision:after", { app: { name: app.name, path: app.path }, canon: { name: canon.name, path: canon.path }, confidence: decision.confidence, tier: decision.tier, isDuplicate: decision.isDuplicate, weights: decision.weights, signals: Object.fromEntries(Object.entries(decision.signals).map(([k, s]) => [k, s.score])) });
257
+ }
258
+ if (!decision.tier)
259
+ continue;
260
+ matches.push({ app, canon, decision, tier: decision.tier, reason: decision.reason });
261
+ }
262
+ }
263
+ return matches;
264
+ };
265
+ exports.matchPairs = matchPairs;
266
+ const applyFilters = (matches) => {
267
+ const kept = [];
268
+ const dropped = [];
269
+ for (const match of matches) {
270
+ if (log.enabled()) {
271
+ log.stage("filter:before", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, confidence: match.decision.confidence });
272
+ }
273
+ let hit = null;
274
+ for (const f of FILTERS) {
275
+ const reason = f.test(match);
276
+ if (reason) {
277
+ hit = { match, filter: f.name, reason };
278
+ break;
279
+ }
280
+ }
281
+ if (hit) {
282
+ dropped.push(hit);
283
+ if (log.enabled())
284
+ log.stage("filter:after", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, outcome: "dropped", filter: hit.filter, reason: hit.reason });
285
+ }
286
+ else {
287
+ kept.push(match);
288
+ if (log.enabled())
289
+ log.stage("filter:after", { app: { name: match.app.name, path: match.app.path }, canon: { name: match.canon.name, path: match.canon.path }, outcome: "kept", confidence: match.decision.confidence });
290
+ }
291
+ }
292
+ return { kept, dropped };
293
+ };
294
+ exports.applyFilters = applyFilters;
295
+ const pairKey = (match) => [match.app.name, match.canon.name].sort().join("::");
296
+ const dedupPairs = (matches) => {
297
+ const best = new Map();
298
+ for (const match of matches) {
299
+ const key = pairKey(match);
300
+ const prev = best.get(key);
301
+ if (!prev || match.decision.confidence > prev.decision.confidence)
302
+ best.set(key, match);
303
+ }
304
+ return [...best.values()];
305
+ };
306
+ const SIMILAR_FANOUT_CAP = 2;
307
+ const capSimilarFanout = (matches) => {
308
+ const byApp = new Map();
309
+ for (const m of matches) {
310
+ if (m.decision.tier !== "similar")
311
+ continue;
312
+ if (!byApp.has(m.app.name))
313
+ byApp.set(m.app.name, []);
314
+ byApp.get(m.app.name).push(m);
315
+ }
316
+ const keep = new Set(matches.filter((m) => m.decision.tier !== "similar"));
317
+ for (const group of byApp.values()) {
318
+ group.sort((a, b) => b.decision.confidence - a.decision.confidence || a.canon.name.localeCompare(b.canon.name));
319
+ for (const m of group.slice(0, SIMILAR_FANOUT_CAP))
320
+ keep.add(m);
321
+ }
322
+ return [...keep];
323
+ };
324
+ const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
325
+ if (!config.rawHtml)
326
+ return [];
327
+ const rows = [];
328
+ for (const { file, rel } of appFiles) {
329
+ if ((0, config_1.inComponentsFolder)(rel, config.componentsFolder))
330
+ continue;
331
+ let elements;
332
+ try {
333
+ elements = (0, framework_js_1.parseElements)(file, canonNames, config);
334
+ }
335
+ catch (err) {
336
+ console.warn(`[component-uniqueness] could not parse elements of ${rel}: ${err && err.message ? err.message : err}`);
337
+ continue;
338
+ }
339
+ for (const element of elements) {
340
+ const candidate = (0, candidate_js_1.buildElementCandidate)(element, config);
341
+ if (!candidate)
342
+ continue;
343
+ const best = (0, decision_maker_1.bestOf)(matchPairs([{ ...candidate, path: rel }], canonComponents, config));
344
+ if (!best)
345
+ continue;
346
+ rows.push({
347
+ tag: element.name,
348
+ path: rel,
349
+ line: element.line,
350
+ suggestion: { component: best.canon.name, path: best.canon.path },
351
+ confidence: best.decision.confidence,
352
+ reason: best.decision.reason,
353
+ });
354
+ }
355
+ }
356
+ return rows;
357
+ };
358
+ exports.collectRawHtml = collectRawHtml;
359
+ const SIZE_RATIO = 3;
360
+ const MIN_PART_CANON_NODES = 1;
361
+ const sizeCache = new WeakMap();
362
+ const nodeCount = (tree) => {
363
+ if (!tree)
364
+ return 0;
365
+ const own = tree.tag === "fragment" || tree.tag === "children" ? 0 : 1;
366
+ return own + (tree.children || []).reduce((sum, child) => sum + nodeCount(child), 0);
367
+ };
368
+ const sizeOf = (item) => {
369
+ if (!sizeCache.has(item))
370
+ sizeCache.set(item, nodeCount(item.tree));
371
+ return sizeCache.get(item);
372
+ };
373
+ const tagBag = (tree, bag = new Map()) => {
374
+ if (!tree)
375
+ return bag;
376
+ if (tree.tag !== "fragment" && tree.tag !== "children")
377
+ bag.set(tree.tag, (bag.get(tree.tag) || 0) + 1);
378
+ for (const child of tree.children || [])
379
+ tagBag(child, bag);
380
+ return bag;
381
+ };
382
+ const bagCache = new WeakMap();
383
+ const bagOf = (item) => {
384
+ if (!bagCache.has(item))
385
+ bagCache.set(item, tagBag(item.tree));
386
+ return bagCache.get(item);
387
+ };
388
+ const bagDice = (a, b) => {
389
+ let shared = 0;
390
+ let total = 0;
391
+ for (const n of a.values())
392
+ total += n;
393
+ for (const n of b.values())
394
+ total += n;
395
+ for (const [tag, n] of a)
396
+ shared += Math.min(n, b.get(tag) || 0);
397
+ return total === 0 ? 0 : (2 * shared) / total;
398
+ };
399
+ const MIN_TAG_DICE = 0.5;
400
+ const rootTagMatches = (partTag, canonTag) => (0, dom_js_1.tagAffinity)(partTag, canonTag) > 0;
401
+ const comparableCanons = (part, canonComponents) => {
402
+ const partSize = sizeOf(part);
403
+ const partBag = bagOf(part);
404
+ return canonComponents.filter((canon) => {
405
+ const size = sizeOf(canon);
406
+ if (size < MIN_PART_CANON_NODES)
407
+ return false;
408
+ const canonBag = bagOf(canon);
409
+ if (size === 1) {
410
+ const tag = [...canonBag.keys()][0];
411
+ return rootTagMatches(part.rootTag, tag) && partBag.has(tag);
412
+ }
413
+ return size <= partSize * SIZE_RATIO && partSize <= size * SIZE_RATIO && bagDice(partBag, canonBag) >= MIN_TAG_DICE;
414
+ });
415
+ };
416
+ exports.comparableCanons = comparableCanons;
417
+ const largestParts = (found) => {
418
+ const sorted = [...found].sort((a, b) => b.part.endLine - b.part.line - (a.part.endLine - a.part.line));
419
+ const kept = [];
420
+ for (const item of sorted) {
421
+ const inside = kept.some((k) => k.best.canon.name === item.best.canon.name && k.part.line <= item.part.line && k.part.endLine >= item.part.endLine);
422
+ if (!inside)
423
+ kept.push(item);
424
+ }
425
+ return kept.sort((a, b) => a.part.line - b.part.line);
426
+ };
427
+ const findParts = (file, rel, canonComponents, config, canonNames) => {
428
+ let parts;
429
+ try {
430
+ parts = (0, framework_js_1.parseParts)(file, canonNames, config);
431
+ }
432
+ catch (err) {
433
+ console.warn(`[component-uniqueness] could not parse parts of ${rel}: ${err && err.message ? err.message : err}`);
434
+ return [];
435
+ }
436
+ const found = [];
437
+ for (const part of parts) {
438
+ const pool = comparableCanons(part, canonComponents);
439
+ if (pool.length === 0)
440
+ continue;
441
+ const candidate = { ...(0, candidate_js_1.buildCandidate)(part, config), path: rel };
442
+ const { kept } = applyFilters(matchPairs([candidate], pool, config));
443
+ const ranked = [...kept].sort((a, b) => b.decision.confidence - a.decision.confidence);
444
+ if (ranked.length === 0)
445
+ continue;
446
+ found.push({ part, best: ranked[0], alt: ranked[1] || null });
447
+ }
448
+ return largestParts(found);
449
+ };
450
+ exports.findParts = findParts;
451
+ const collectParts = (appFiles, canonComponents, config, canonNames) => {
452
+ if (!config.parts)
453
+ return { rows: [], candidates: [] };
454
+ const rows = [];
455
+ const candidates = [];
456
+ for (const { file, rel } of appFiles) {
457
+ for (const { part, best, alt } of findParts(file, rel, canonComponents, config, canonNames)) {
458
+ const suggestions = [{ component: best.canon.name, path: best.canon.path, line: best.canon.line ?? null, endLine: best.canon.endLine ?? null, confidence: best.decision.confidence, reason: best.decision.reason }];
459
+ if (alt)
460
+ suggestions.push({ component: alt.canon.name, path: alt.canon.path, line: alt.canon.line ?? null, endLine: alt.canon.endLine ?? null, confidence: alt.decision.confidence, reason: alt.decision.reason });
461
+ rows.push({
462
+ owner: part.owner,
463
+ tag: part.rootTag,
464
+ path: rel,
465
+ line: part.line,
466
+ endLine: part.endLine,
467
+ suggestions,
468
+ engine: best.decision,
469
+ });
470
+ // The part IS a candidate: the report draws its snapshot and lanes from
471
+ // the same parsed tree the decision used. It is registered under the
472
+ // finding's left name (`owner › <tag>`) so `path#name` resolves it.
473
+ candidates.push({ ...best.app, name: `${part.owner} › <${part.rootTag}>` });
474
+ }
475
+ }
476
+ return { rows, candidates };
477
+ };
478
+ const stageLog = (enabled) => {
479
+ const started = Date.now();
480
+ return (label) => {
481
+ if (!enabled)
482
+ return;
483
+ if (global.gc)
484
+ global.gc();
485
+ console.log(`[component-uniqueness] ${label}: ${((Date.now() - started) / 1000).toFixed(1)}s, heap ${Math.round(process.memoryUsage().heapUsed / 1048576)} MB`);
486
+ };
487
+ };
488
+ // The interactive overview (`--overview`): the same findings the markdown report
489
+ // prints, drawn side-by-side on code-diff. Required lazily so the ESLint rule
490
+ // never pulls in esbuild / React.
491
+ const writeOverviewFor = (comp, outFlag, repoRoot, config) => {
492
+ const { collectOverviewData, writeOverview } = lazyRequire("./report/user-report");
493
+ const data = collectOverviewData({ comp, repoRoot, config, candidates: comp.candidates ?? [] });
494
+ const outPath = path.isAbsolute(outFlag) ? outFlag : path.resolve(repoRoot, outFlag);
495
+ const written = writeOverview(data, outPath);
496
+ console.log(`[component-uniqueness] wrote overview ${path.relative(process.cwd(), written.path)} (${data.findings.length} finding(s), ${Math.round(written.bytes / 1024)} kB)`);
497
+ };
498
+ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, registry, catalogComponents) => {
499
+ const exts = config.exts || config_1.DEFAULT_EXTS;
500
+ const ignoreDirs = config.ignoreDirs;
501
+ const dedupeFiles = (files) => {
502
+ const seen = new Set();
503
+ const out = [];
504
+ for (const f of files) {
505
+ if (seen.has(f.file))
506
+ continue;
507
+ seen.add(f.file);
508
+ out.push(f);
509
+ }
510
+ return out;
511
+ };
512
+ const stage = stageLog(args.verbose);
513
+ const shouldSkipCanon = (abs) => (0, config_1.isIgnored)(relPosix(repoRoot, abs), [], config.exclude);
514
+ const canonFiles = dedupeFiles(collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files);
515
+ const canonComponents = parseComponents(canonFiles, null, config);
516
+ const canonNames = new Set(canonComponents.map((c) => c.name));
517
+ const uniqueCanon = parseComponents(canonFiles, canonNames, config);
518
+ stage(`canonical parsed (${uniqueCanon.length})`);
519
+ const appInclude = args.appRoots ? [] : config.include;
520
+ const appShouldSkip = (abs) => {
521
+ const rel = relPosix(repoRoot, abs);
522
+ return (0, config_1.isIgnored)(rel, appInclude, config.exclude);
523
+ };
524
+ // --files restricts the app-side candidate scan to the given files (agent
525
+ // stop-hooks lint only changed files); the canonical (roots) scan stays folder-based.
526
+ const appFiles = args.files
527
+ ? (() => {
528
+ const files = args.files.map((rel) => ({ file: resolveAgainst(rel, repoRoot), rel: rel.split(path.sep).join("/") })).filter((f) => fs.existsSync(f.file) && fs.statSync(f.file).isFile());
529
+ return { files, count: files.length };
530
+ })()
531
+ : collectFiles(args.appRoots || ["."], repoRoot, appShouldSkip, null, exts, ignoreDirs);
532
+ const appComponents = parseComponents(appFiles.files, canonNames, config, "CANDIDATE");
533
+ stage(`app parsed (${appComponents.length})`);
534
+ const matches = matchPairs(appComponents, uniqueCanon, config);
535
+ const { kept, dropped } = applyFilters(matches);
536
+ const deduped = dedupPairs(kept);
537
+ stage("components matched");
538
+ const inLayer = (p) => (config.componentsFolder || []).some((d) => p.startsWith(d));
539
+ const layerMatches = capSimilarFanout(deduped.filter((m) => inLayer(m.app.path)));
540
+ const appMatches = deduped.filter((m) => !inLayer(m.app.path));
541
+ const cappedAppMatches = capSimilarFanout(appMatches);
542
+ const { clusters, remaining } = (0, missing_component_1.findMissingComponents)(cappedAppMatches, { minCluster: args.minCluster });
543
+ if (log.enabled()) {
544
+ log.stage("missing-component", { minCluster: args.minCluster, clusters: clusters.map((c) => ({ name: c.name, canon: c.canon.name, apps: c.matches.map((m) => m.app.name) })), remaining: remaining.length });
545
+ }
546
+ stage("missing-component clustered");
547
+ const rawHtml = collectRawHtml(appFiles.files, uniqueCanon, config, canonNames);
548
+ stage("raw html done");
549
+ const parts = collectParts(appFiles.files, uniqueCanon, config, canonNames);
550
+ stage("parts done");
551
+ return {
552
+ matches: [...remaining, ...layerMatches],
553
+ dropped,
554
+ missingClusters: clusters,
555
+ rawHtml,
556
+ parts: parts.rows,
557
+ layerFolders: config.componentsFolder,
558
+ files: appFiles.count,
559
+ canonCount: uniqueCanon.length,
560
+ appCount: appComponents.length,
561
+ candidates: [...appComponents, ...uniqueCanon, ...parts.candidates],
562
+ };
563
+ };
564
+ exports.buildComponentReport = buildComponentReport;
565
+ const main = async () => {
566
+ const args = parseArgs(process.argv.slice(2));
567
+ const cwd = process.cwd();
568
+ const loaded = await (0, config_1.loadRuleOptions)(cwd, args.configFile);
569
+ const configOptions = loaded ? { ...loaded.options } : {};
570
+ if (loaded) {
571
+ console.log(`[component-uniqueness] config from ${loaded.source}`);
572
+ }
573
+ else if (!args.configFile) {
574
+ console.log("[component-uniqueness] no rule options found in eslint.config.js / md-code-component-uniqueness.config.js; using defaults");
575
+ }
576
+ if (args.ignoreDirs) {
577
+ const base = Array.isArray(configOptions.ignoreDirs) ? configOptions.ignoreDirs : [];
578
+ configOptions.ignoreDirs = [...new Set([...base, ...args.ignoreDirs])];
579
+ }
580
+ const config = (0, config_1.normalizeOptions)(configOptions);
581
+ if (args.include)
582
+ config.include = [...new Set([...(config.include || []), ...args.include])];
583
+ if (args.thresholds)
584
+ config.thresholds = { ...(config.thresholds || {}), ...args.thresholds };
585
+ if (args.rawHtml)
586
+ config.rawHtml = true;
587
+ if (args.parts)
588
+ config.parts = true;
589
+ if (args.log)
590
+ log.enable(args.log);
591
+ await lazyRequire("./playgrounds/style.js").whenReady(config);
592
+ const rootMarkers = config.rootMarkers;
593
+ const repoRoot = args.repoRoot ? path.resolve(cwd, args.repoRoot) : (0, config_1.findRepoRoot)(cwd, rootMarkers) || cwd;
594
+ const configRoots = (config.componentsFolder || []).map((d) => String(d).replace(/\\/g, "/").replace(/\/+$/, ""));
595
+ const roots = args.roots || configRoots;
596
+ const include = config.include;
597
+ const exclude = config.exclude;
598
+ const shouldSkip = (abs) => (0, config_1.isIgnored)(relPosix(repoRoot, abs), include, exclude);
599
+ const exts = config.exts;
600
+ const ignoreDirs = config.ignoreDirs;
601
+ // --files is a partial scan (agent stop-hooks) — skip the catalog entirely
602
+ // so a single-file scan does not clobber the folder-based catalog. Roots
603
+ // may be empty (the catalog is only read for the canonical name set).
604
+ if (args.files?.length) {
605
+ const reportPath = args.report ? (path.isAbsolute(args.report) ? args.report : path.resolve(process.cwd(), args.report)) : null;
606
+ if (reportPath || args.overview) {
607
+ const comp = await buildComponentReport(args, repoRoot, roots, shouldSkip, config, (0, config_1.loadRegistry)(config), (((0, config_1.loadCatalog)(config) || {}).components) || []);
608
+ if (reportPath) {
609
+ fs.mkdirSync(path.dirname(reportPath), { recursive: true });
610
+ fs.writeFileSync(reportPath, (0, report_1.renderComponentReport)(comp, args.verbose));
611
+ console.log(`[component-uniqueness] wrote report ${reportPath} (${comp.matches.length} duplicate component(s), ${comp.files} file(s))`);
612
+ }
613
+ if (args.overview)
614
+ writeOverviewFor(comp, args.overview, repoRoot, config);
615
+ }
616
+ log.flush();
617
+ return;
618
+ }
619
+ if (!roots || roots.length === 0) {
620
+ fail("no scan roots: pass --roots <dir1>:<dir2> or set componentsFolder in the rule options (eslint.config.js / component-uniqueness.config.js)");
621
+ }
622
+ if (!config.componentsFolder || config.componentsFolder.length === 0) {
623
+ config.componentsFolder = roots;
624
+ }
625
+ const outPath = resolveAgainst(args.out || config.exportPath, repoRoot);
626
+ const registry = args.registry ? (0, config_1.loadRegistry)({ ...config, registry: null, registryPath: args.registry }) : (0, config_1.loadRegistry)(config);
627
+ const catalogComponents = (((0, config_1.loadCatalog)(config) || {}).components) || [];
628
+ const shouldSkipCanon = (abs) => (0, config_1.isIgnored)(relPosix(repoRoot, abs), [], config.exclude);
629
+ const canonFiles = collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files;
630
+ const canonComponents = parseComponents(canonFiles, null, config);
631
+ const canonNames = new Set(canonComponents.map((c) => c.name));
632
+ const final = parseComponents(canonFiles, canonNames, config);
633
+ if (args.check) {
634
+ let current = null;
635
+ try {
636
+ current = JSON.parse(fs.readFileSync(outPath, "utf8"));
637
+ }
638
+ catch { }
639
+ const same = current && JSON.stringify(current.components || []) === JSON.stringify(final);
640
+ if (!same) {
641
+ fail(`catalog is out of date (${final.length} component(s) expected at ${path.relative(repoRoot, outPath)}); regenerate it (node main.js)`);
642
+ }
643
+ console.log(`[component-uniqueness] catalog up to date (${final.length} component(s))`);
644
+ return;
645
+ }
646
+ (0, utils_1.writeCatalog)(outPath, final);
647
+ const tagCount = new Set(final.map((c) => (c.rootTags || [])[0]).filter(Boolean)).size;
648
+ console.log(`[component-uniqueness] wrote ${path.relative(repoRoot, outPath)} (${final.length} component(s), ${tagCount} root tag(s), ${canonFiles.length} file(s) scanned)`);
649
+ if (args.report || args.overview) {
650
+ const comp = await buildComponentReport(args, repoRoot, roots, shouldSkip, config, registry, catalogComponents);
651
+ if (args.report) {
652
+ const reportPath = path.isAbsolute(args.report) ? args.report : path.resolve(process.cwd(), args.report);
653
+ fs.mkdirSync(path.dirname(reportPath), { recursive: true });
654
+ fs.writeFileSync(reportPath, (0, report_1.renderComponentReport)(comp, args.verbose));
655
+ console.log(`[component-uniqueness] wrote report ${reportPath} (${comp.matches.length} duplicate component(s), ${comp.rawHtml.length} raw-html element(s) across ${comp.files} file(s))`);
656
+ }
657
+ if (args.overview)
658
+ writeOverviewFor(comp, args.overview, repoRoot, config);
659
+ }
660
+ log.flush();
661
+ };
662
+ if (require.main === module) {
663
+ main().catch((err) => {
664
+ fail(err && err.message ? err.message : String(err));
665
+ });
666
+ }
@@ -0,0 +1,19 @@
1
+ declare const TEST_ID_WEIGHT = 0.5;
2
+ declare const classify: (token: any) => "a11y" | "testid";
3
+ declare const tokensOf: (c: any, kind: any) => Set<unknown>;
4
+ declare const announcementsOf: (tree: any) => any[];
5
+ declare const matchA11y: (candidate: any, canon: any) => {
6
+ score: number;
7
+ evidence: {
8
+ candidateAnnouncements?: string[];
9
+ canonicalAnnouncements?: string[];
10
+ candidateA11y: unknown[];
11
+ canonicalA11y: unknown[];
12
+ candidateTestId: unknown[];
13
+ canonicalTestId: unknown[];
14
+ a11ySimilarity: any;
15
+ testIdSimilarity: number;
16
+ form: any;
17
+ };
18
+ };
19
+ export { matchA11y, tokensOf, classify, announcementsOf, TEST_ID_WEIGHT };