@md-code/component-uniqueness 0.1.3 → 0.1.4

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.
package/config.js CHANGED
@@ -214,7 +214,7 @@ const pickOptions = (v) => {
214
214
  return {};
215
215
  };
216
216
 
217
- const isRuleKey = (key) => key === RULE_NAME || key === RULE_SHORT || key === "component-uniqueness" || key.endsWith("/component-uniqueness");
217
+ const isRuleKey = (key) => typeof key === "string" && (key === RULE_NAME || key === RULE_SHORT || key === "component-uniqueness" || key.endsWith("/component-uniqueness"));
218
218
 
219
219
  const ruleValue = (rules) => {
220
220
  for (const [key, v] of Object.entries(rules)) {
@@ -225,13 +225,22 @@ const ruleValue = (rules) => {
225
225
  return null;
226
226
  };
227
227
 
228
+ const pluginRuleValue = (plugins) => {
229
+ for (const plugin of Object.values(plugins || {})) {
230
+ if (!plugin || typeof plugin !== "object") continue;
231
+ const v = ruleValue(plugin.rules || {});
232
+ if (v !== null && v !== undefined) return v;
233
+ }
234
+ return null;
235
+ };
236
+
228
237
  const loadFlatOptions = async (file) => {
229
238
  const mod = await loadModule(file);
230
239
  const list = mod && mod.default !== undefined ? mod.default : mod;
231
240
  if (!Array.isArray(list)) return null;
232
241
  for (const entry of list) {
233
- if (!entry || typeof entry !== "object" || !entry.rules) continue;
234
- const v = ruleValue(entry.rules);
242
+ if (!entry || typeof entry !== "object") continue;
243
+ const v = (entry.rules && ruleValue(entry.rules)) || (entry.plugins && pluginRuleValue(entry.plugins)) || null;
235
244
  if (v === undefined || v === null) continue;
236
245
  return pickOptions(v);
237
246
  }
@@ -253,7 +262,8 @@ const loadRuleOptions = async (dir, explicitFile = null) => {
253
262
  return options ? { options, source: file } : null;
254
263
  }
255
264
  try {
256
- const options = file.startsWith("eslint.config") ? await loadFlatOptions(file) : pickOptions(await loadModule(file));
265
+ const isFlat = path.basename(file).startsWith("eslint.config");
266
+ const options = isFlat ? await loadFlatOptions(file) : pickOptions(await loadModule(file));
257
267
  return options ? { options, source: file } : null;
258
268
  } catch {
259
269
  return null;
@@ -2,6 +2,7 @@
2
2
 
3
3
  const test = (match) => {
4
4
  if (match.tier === "name" || match.tier === "name-fuzzy" || match.tier === "jsx-block") return null;
5
+ if (match.app.partial) return null;
5
6
  const appEls = (match.app.elementProps || []).length;
6
7
  const canonEls = (match.canon.elementProps || []).length;
7
8
  if (canonEls > 0 && appEls > 3 * canonEls) {
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+
3
+ const test = (match) => {
4
+ if (!match.app.partial) return null;
5
+ const structure = match.decision.signals && match.decision.signals.structure;
6
+ if (!structure) return null;
7
+ if (structure.score <= 0) {
8
+ return "partial shares no structure with the canonical — match is driven only by framework/a11y/behavior";
9
+ }
10
+ return null;
11
+ };
12
+
13
+ module.exports = { name: "drop-no-structure", test };
@@ -1,42 +1,70 @@
1
1
  "use strict";
2
2
 
3
3
  const { pascalWords, GENERIC_WORDS } = require("../normalize/words.js");
4
+ const { matchStructure } = require("../matcher/structure.js");
4
5
 
5
6
  const DEFAULT_MIN_CLUSTER = 3;
7
+ const MIN_PAIRWISE_STRUCTURE = 0.4;
8
+ const MIN_PAIR_FLOOR = 0.3;
9
+ const CANON_CONF_FLOOR = 0.25;
6
10
 
7
11
  const pascalCase = (words) => words.map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join("");
8
12
 
9
13
  const suggestName = (appNames, canonName = null) => {
10
- const counts = new Map();
11
- const order = [];
12
- for (const name of appNames) {
13
- for (const w of pascalWords(name)) {
14
- const k = w.toLowerCase();
15
- if (!counts.has(k)) {
16
- counts.set(k, 0);
17
- order.push(k);
14
+ if (canonName) {
15
+ const counts = new Map();
16
+ const order = [];
17
+ for (const name of appNames) {
18
+ for (const w of pascalWords(name)) {
19
+ const k = w.toLowerCase();
20
+ if (!counts.has(k)) {
21
+ counts.set(k, 0);
22
+ order.push(k);
23
+ }
24
+ counts.set(k, counts.get(k) + 1);
18
25
  }
19
- counts.set(k, counts.get(k) + 1);
20
26
  }
21
- }
22
- const common = order.filter((k) => counts.get(k) >= 2);
23
- const meaningful = common.filter((k) => !GENERIC_WORDS.has(k));
24
- const base = (meaningful.length > 0 ? meaningful : common).slice(0, 3).map((k) => k[0].toUpperCase() + k.slice(1));
25
- if (base.length > 0) {
26
- const name = pascalCase(base);
27
- if (meaningful.length > 0) return name;
28
- return canonName ? `${name}${canonName}` : name;
29
- }
30
- if (canonName) {
31
- const canonWords = pascalWords(canonName).filter((w) => !GENERIC_WORDS.has(w.toLowerCase()));
32
- if (canonWords.length > 0) {
33
- return pascalCase(["shared", ...canonWords.slice(0, 2)]);
27
+ const common = order.filter((k) => counts.get(k) >= Math.ceil(appNames.length * 0.6));
28
+ const meaningful = common.filter((k) => !GENERIC_WORDS.has(k));
29
+ if (meaningful.length > 0) {
30
+ return pascalCase([meaningful[0], ...pascalWords(canonName).slice(0, 2)]);
34
31
  }
35
- return `Shared${canonName}`;
36
32
  }
33
+ if (canonName) return `Shared${canonName}`;
37
34
  return "SharedComponent";
38
35
  };
39
36
 
37
+ const pairwiseAverage = (apps) => {
38
+ let total = 0;
39
+ let pairs = 0;
40
+ for (let i = 0; i < apps.length; i += 1) {
41
+ for (let j = i + 1; j < apps.length; j += 1) {
42
+ const s = matchStructure(apps[i], apps[j]);
43
+ total += s.score;
44
+ pairs += 1;
45
+ }
46
+ }
47
+
48
+ return pairs === 0 ? 0 : total / pairs;
49
+ };
50
+
51
+ const pairwiseAllAbove = (apps, floor) => {
52
+ for (let i = 0; i < apps.length; i += 1)
53
+ for (let j = i + 1; j < apps.length; j += 1) if (matchStructure(apps[i], apps[j]).score < floor) return false;
54
+
55
+ return true;
56
+ };
57
+
58
+ const resolveClusterMembers = (group) => {
59
+ const strong = group.filter((m) => m.decision.confidence >= CANON_CONF_FLOOR);
60
+ const apps = [...new Map(strong.map((m) => [m.app.name, m.app])).values()];
61
+ if (apps.length >= 2 && pairwiseAllAbove(apps, MIN_PAIR_FLOOR)) return strong;
62
+ const dups = strong.filter((m) => m.decision.tier === "duplicate");
63
+ const dupApps = [...new Map(dups.map((m) => [m.app.name, m.app])).values()];
64
+
65
+ return dups.length >= 2 && pairwiseAllAbove(dupApps, MIN_PAIR_FLOOR) ? dups : null;
66
+ };
67
+
40
68
  const findMissingComponents = (matches, { minCluster = DEFAULT_MIN_CLUSTER } = {}) => {
41
69
  const byCanon = new Map();
42
70
  for (const match of matches) {
@@ -45,19 +73,22 @@ const findMissingComponents = (matches, { minCluster = DEFAULT_MIN_CLUSTER } = {
45
73
  byCanon.get(key).push(match);
46
74
  }
47
75
  const clusters = [];
48
- const clusteredKeys = new Set();
49
76
  for (const [canonName, group] of byCanon) {
50
- const distinctApps = new Set(group.map((m) => m.app.name));
51
- if (distinctApps.size < minCluster) continue;
52
- clusteredKeys.add(canonName);
77
+ const members = resolveClusterMembers(group);
78
+ if (!members) continue;
79
+ if (new Set(members.map((m) => m.app.name)).size < minCluster) continue;
53
80
  clusters.push({
54
- name: suggestName(group.map((m) => m.app.name), canonName),
81
+ name: suggestName(members.map((m) => m.app.name), canonName),
55
82
  canon: group[0].canon,
56
- matches: [...group].sort((a, b) => b.decision.confidence - a.decision.confidence),
83
+ matches: [...members].sort((a, b) => b.decision.confidence - a.decision.confidence),
57
84
  });
58
85
  }
59
86
  clusters.sort((a, b) => b.matches.length - a.matches.length || a.name.localeCompare(b.name));
60
- const remaining = matches.filter((m) => !clusteredKeys.has(m.canon.name));
87
+ const clusteredKeys = new Set();
88
+ for (const c of clusters) {
89
+ for (const m of c.matches) clusteredKeys.add(m.app.name + "::" + m.canon.name);
90
+ }
91
+ const remaining = matches.filter((m) => !clusteredKeys.has(m.app.name + "::" + m.canon.name));
61
92
  return { clusters, remaining };
62
93
  };
63
94
 
@@ -65,4 +96,5 @@ module.exports = {
65
96
  findMissingComponents,
66
97
  suggestName,
67
98
  DEFAULT_MIN_CLUSTER,
99
+ MIN_PAIRWISE_STRUCTURE,
68
100
  };
package/main.js CHANGED
@@ -19,16 +19,18 @@ const {
19
19
  const { walk, writeCatalog } = require("./utils");
20
20
  const { parseComponents: parseComponentsViaEntrypoint, parseElements: parseElementsViaEntrypoint, parseParts: parsePartsViaEntrypoint } = require("./playgrounds/framework-entrypoint.js");
21
21
  const { buildCandidate, buildElementCandidate } = require("./normalize/candidate.js");
22
+ const { tagAffinity } = require("./normalize/dom.js");
22
23
  const { matchSignals } = require("./matcher");
23
24
  const { getFrameworkMatcher } = require("./matcher/framework");
24
25
  const { decide, bestOf } = require("./decision-maker");
25
26
  const dropUsages = require("./filter/drop-usages");
26
27
  const dropChildElement = require("./filter/drop-child-element");
28
+ const dropNoStructure = require("./filter/drop-no-structure");
27
29
  const { findMissingComponents } = require("./filter/missing-component");
28
30
  const { renderComponentReport } = require("./report");
29
31
  const log = require("./logger");
30
32
 
31
- const FILTERS = [dropUsages, dropChildElement];
33
+ const FILTERS = [dropUsages, dropChildElement, dropNoStructure];
32
34
  const frameworkMatcher = getFrameworkMatcher("react");
33
35
 
34
36
  const treeSummary = (tree) => {
@@ -242,6 +244,23 @@ const dedupPairs = (matches) => {
242
244
  return [...best.values()];
243
245
  };
244
246
 
247
+ const SIMILAR_FANOUT_CAP = 2;
248
+
249
+ const capSimilarFanout = (matches) => {
250
+ const byApp = new Map();
251
+ for (const m of matches) {
252
+ if (m.decision.tier !== "similar") continue;
253
+ if (!byApp.has(m.app.name)) byApp.set(m.app.name, []);
254
+ byApp.get(m.app.name).push(m);
255
+ }
256
+ const keep = new Set(matches.filter((m) => m.decision.tier !== "similar"));
257
+ for (const group of byApp.values()) {
258
+ group.sort((a, b) => b.decision.confidence - a.decision.confidence || a.canon.name.localeCompare(b.canon.name));
259
+ for (const m of group.slice(0, SIMILAR_FANOUT_CAP)) keep.add(m);
260
+ }
261
+ return [...keep];
262
+ };
263
+
245
264
  const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
246
265
  if (!config.rawHtml) return [];
247
266
  const rows = [];
@@ -274,7 +293,7 @@ const collectRawHtml = (appFiles, canonComponents, config, canonNames) => {
274
293
  };
275
294
 
276
295
  const SIZE_RATIO = 3;
277
- const MIN_PART_CANON_NODES = 3;
296
+ const MIN_PART_CANON_NODES = 1;
278
297
  const sizeCache = new WeakMap();
279
298
 
280
299
  const nodeCount = (tree) => {
@@ -318,14 +337,23 @@ const bagDice = (a, b) => {
318
337
 
319
338
  const MIN_TAG_DICE = 0.5;
320
339
 
340
+ const rootTagMatches = (partTag, canonTag) => tagAffinity(partTag, canonTag) > 0;
341
+
321
342
  const comparableCanons = (part, canonComponents) => {
322
343
  const partSize = sizeOf(part);
323
344
  const partBag = bagOf(part);
324
345
 
325
346
  return canonComponents.filter((canon) => {
326
347
  const size = sizeOf(canon);
348
+ if (size < MIN_PART_CANON_NODES) return false;
349
+ const canonBag = bagOf(canon);
350
+ if (size === 1) {
351
+ const tag = [...canonBag.keys()][0];
352
+
353
+ return rootTagMatches(part.rootTag, tag) && partBag.has(tag);
354
+ }
327
355
 
328
- return size >= MIN_PART_CANON_NODES && size <= partSize * SIZE_RATIO && partSize <= size * SIZE_RATIO && bagDice(partBag, bagOf(canon)) >= MIN_TAG_DICE;
356
+ return size <= partSize * SIZE_RATIO && partSize <= size * SIZE_RATIO && bagDice(partBag, canonBag) >= MIN_TAG_DICE;
329
357
  });
330
358
  };
331
359
 
@@ -355,8 +383,9 @@ const findParts = (file, rel, canonComponents, config, canonNames) => {
355
383
  if (pool.length === 0) continue;
356
384
  const candidate = { ...buildCandidate(part, config), path: rel };
357
385
  const { kept } = applyFilters(matchPairs([candidate], pool, config));
358
- const best = bestOf(kept);
359
- if (best) found.push({ part, best });
386
+ const ranked = [...kept].sort((a, b) => b.decision.confidence - a.decision.confidence);
387
+ if (ranked.length === 0) continue;
388
+ found.push({ part, best: ranked[0], alt: ranked[1] || null });
360
389
  }
361
390
 
362
391
  return largestParts(found);
@@ -366,16 +395,16 @@ const collectParts = (appFiles, canonComponents, config, canonNames) => {
366
395
  if (!config.parts) return [];
367
396
  const rows = [];
368
397
  for (const { file, rel } of appFiles) {
369
- for (const { part, best } of findParts(file, rel, canonComponents, config, canonNames)) {
398
+ for (const { part, best, alt } of findParts(file, rel, canonComponents, config, canonNames)) {
399
+ const suggestions = [{ component: best.canon.name, path: best.canon.path, confidence: best.decision.confidence, reason: best.decision.reason }];
400
+ if (alt) suggestions.push({ component: alt.canon.name, path: alt.canon.path, confidence: alt.decision.confidence, reason: alt.decision.reason });
370
401
  rows.push({
371
402
  owner: part.owner,
372
403
  tag: part.rootTag,
373
404
  path: rel,
374
405
  line: part.line,
375
406
  endLine: part.endLine,
376
- suggestion: { component: best.canon.name, path: best.canon.path },
377
- confidence: best.decision.confidence,
378
- reason: best.decision.reason,
407
+ suggestions,
379
408
  });
380
409
  }
381
410
  }
@@ -396,19 +425,32 @@ const stageLog = (enabled) => {
396
425
  const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, registry, catalogComponents) => {
397
426
  const exts = config.exts || DEFAULT_EXTS;
398
427
  const ignoreDirs = config.ignoreDirs;
399
- const stage = stageLog(args.verbose);
428
+ const dedupeFiles = (files) => {
429
+ const seen = new Set();
430
+ const out = [];
431
+ for (const f of files) {
432
+ if (seen.has(f.file)) continue;
433
+ seen.add(f.file);
434
+ out.push(f);
435
+ }
436
+
437
+ return out;
438
+ };
439
+
440
+ const stage = stageLog(args.verbose);
400
441
 
401
442
  const shouldSkipCanon = (abs) => isIgnored(relPosix(repoRoot, abs), [], config.exclude);
402
- const canonFiles = collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files;
443
+ const canonFiles = dedupeFiles(collectFiles(roots, repoRoot, shouldSkipCanon, null, exts, ignoreDirs).files);
403
444
  const canonComponents = parseComponents(canonFiles, null, config);
404
445
  const canonNames = new Set(canonComponents.map((c) => c.name));
405
446
  const uniqueCanon = parseComponents(canonFiles, canonNames, config);
406
447
  stage(`canonical parsed (${uniqueCanon.length})`);
407
448
 
449
+ const appInclude = args.appRoots ? [] : config.include;
408
450
  const appShouldSkip = (abs) => {
409
451
  const rel = relPosix(repoRoot, abs);
410
452
 
411
- return isIgnored(rel, inComponentsFolder(rel, config.componentsFolder) ? [] : config.include, config.exclude);
453
+ return isIgnored(rel, appInclude, config.exclude);
412
454
  };
413
455
  const appFiles = collectFiles(args.appRoots || ["."], repoRoot, appShouldSkip, null, exts, ignoreDirs);
414
456
  const appComponents = parseComponents(appFiles.files, canonNames, config, "CANDIDATE");
@@ -419,9 +461,10 @@ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, r
419
461
  const deduped = dedupPairs(kept);
420
462
  stage("components matched");
421
463
  const inLayer = (p) => (config.componentsFolder || []).some((d) => p.startsWith(d));
422
- const layerMatches = deduped.filter((m) => inLayer(m.app.path));
464
+ const layerMatches = capSimilarFanout(deduped.filter((m) => inLayer(m.app.path)));
423
465
  const appMatches = deduped.filter((m) => !inLayer(m.app.path));
424
- const { clusters, remaining } = findMissingComponents(appMatches, { minCluster: args.minCluster });
466
+ const cappedAppMatches = capSimilarFanout(appMatches);
467
+ const { clusters, remaining } = findMissingComponents(cappedAppMatches, { minCluster: args.minCluster });
425
468
  if (log.enabled()) {
426
469
  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 });
427
470
  }
@@ -536,4 +579,6 @@ module.exports = {
536
579
  collectRawHtml,
537
580
  findParts,
538
581
  frameworkMatcher,
582
+ comparableCanons,
583
+ buildComponentReport,
539
584
  };
package/matcher/index.js CHANGED
@@ -7,17 +7,17 @@ const { matchA11y, tokensOf } = require("./a11y");
7
7
 
8
8
  const restrictTo = (candidate, canon) => {
9
9
  const events = new Set(candidate.framework.events);
10
- const props = new Set(candidate.framework.props);
11
10
  const a11y = tokensOf(candidate, "a11y");
11
+ const openProps = canon.framework.open ? [] : canon.framework.props || [];
12
12
 
13
13
  return {
14
14
  ...canon,
15
15
  framework: {
16
- props: canon.framework.open ? [...props] : (canon.framework.props || []).filter((p) => props.has(p)),
16
+ props: openProps,
17
17
  events: (canon.framework.events || []).filter((e) => events.has(e)),
18
18
  names: [],
19
19
  },
20
- a11y: canon.framework.open ? candidate.a11y || [] : (canon.a11y || []).filter((t) => a11y.has(String(t).toLowerCase())),
20
+ a11y: (canon.a11y || []).filter((t) => a11y.has(String(t).toLowerCase())),
21
21
  };
22
22
  };
23
23
 
@@ -1,17 +1,20 @@
1
1
  "use strict";
2
2
 
3
- const { NON_SEMANTIC_TAGS, isPascalCase } = require("../normalize/dom.js");
3
+ const { isPascalCase, tagAffinity, GENERIC_CONTAINER_TAGS } = require("../normalize/dom.js");
4
4
 
5
5
  const CONFLICT_PENALTY = 0.6;
6
- const CONFLICTED_RICH_CEILING = 0.8;
7
- const RICH_DISTINCT_MIN = 3;
8
- const CEILING_LADDER = [0.3, 0.5, 0.7, 0.9, 1.0];
9
- const MISSING_CHILD_PENALTY = 0.15;
10
6
  const NEAR_IDENTICAL_CEILING = 0.98;
11
7
 
12
8
  const isTextNode = (node) => node.tag === "children" || node.tag === "text";
13
9
  const isIconNode = (node) => isPascalCase(node.tag);
14
10
 
11
+ const nodeCount = (tree) => {
12
+ if (!tree) return 0;
13
+ const own = tree.tag === "fragment" || tree.tag === "children" ? 0 : 1;
14
+
15
+ return own + (tree.children || []).reduce((sum, child) => sum + nodeCount(child), 0);
16
+ };
17
+
15
18
  const pairsOf = (css) => new Set(Object.entries(css || {}).map(([prop, value]) => `${prop}:${value}`));
16
19
 
17
20
  const overlap = (a, b) => [...a].filter((pair) => b.has(pair)).length;
@@ -22,8 +25,6 @@ const jaccard = (a, b) => {
22
25
  return union === 0 ? 0 : overlap(a, b) / union;
23
26
  };
24
27
 
25
- const coverage = (a, b) => (a.size === 0 ? 0 : overlap(a, b) / a.size);
26
-
27
28
  const textSim = (a, b) => {
28
29
  const ta = String(a.text || "").toLowerCase().trim();
29
30
  const tb = String(b.text || "").toLowerCase().trim();
@@ -34,8 +35,9 @@ const textSim = (a, b) => {
34
35
  };
35
36
 
36
37
  const tagMatch = (a, b) => {
37
- if (a.tag === b.tag) return 1;
38
38
  if (a.interactive && b.interactive) return 1;
39
+ const affinity = tagAffinity(a.tag, b.tag);
40
+ if (affinity > 0) return affinity;
39
41
 
40
42
  return 0;
41
43
  };
@@ -54,47 +56,62 @@ const nodeSimilarity = (a, b) => {
54
56
  return score;
55
57
  };
56
58
 
57
- const forestOf = (node) => (node.tag === "fragment" ? (node.children || []).flatMap(forestOf) : [node]);
59
+ const chainList = (node) => {
60
+ const list = [];
61
+ const walk = (n, parentIdx) => {
62
+ if (!n) return;
63
+ if (n.tag === "fragment" || n.tag === "children") {
64
+ for (const child of n.children || []) walk(child, parentIdx);
65
+ return;
66
+ }
67
+ if (n.tag === "text") return;
68
+ const idx = list.length;
69
+ list.push({ node: n, parent: parentIdx });
70
+ for (const child of n.children || []) walk(child, idx);
71
+ };
72
+ walk(node, -1);
73
+
74
+ return list;
75
+ };
58
76
 
59
- const align = (xs, ys) => {
60
- const cells = xs.map((x) => ys.map((y) => compare(x, y)));
61
- const table = Array.from({ length: xs.length + 1 }, () => new Array(ys.length + 1).fill(0));
62
- for (let i = 1; i <= xs.length; i += 1) {
63
- for (let j = 1; j <= ys.length; j += 1) {
64
- table[i][j] = Math.max(table[i - 1][j], table[i][j - 1], table[i - 1][j - 1] + cells[i - 1][j - 1].score);
77
+ const bestChain = (a, b) => {
78
+ const xs = chainList(a);
79
+ const ys = chainList(b);
80
+ const refSize = Math.max(xs.length, ys.length);
81
+ if (xs.length === 0 || ys.length === 0) return { score: 0, quality: 0, chainSize: 0, refSize, pairs: [] };
82
+ const dp = xs.map(() => new Array(ys.length).fill(0));
83
+ const len = xs.map(() => new Array(ys.length).fill(0));
84
+ let best = { score: 0, quality: 0, chainSize: 0, i: -1, j: -1 };
85
+ for (let i = 0; i < xs.length; i += 1) {
86
+ for (let j = 0; j < ys.length; j += 1) {
87
+ const sim = nodeSimilarity(xs[i].node, ys[j].node);
88
+ let value = sim;
89
+ let length = 1;
90
+ const pi = xs[i].parent;
91
+ const pj = ys[j].parent;
92
+ if (pi >= 0 && pj >= 0 && dp[pi][pj] > 0) {
93
+ value += dp[pi][pj];
94
+ length += len[pi][pj];
95
+ }
96
+ dp[i][j] = value;
97
+ len[i][j] = length;
98
+ const quality = value / length;
99
+ const score = quality * (length / refSize);
100
+ if (score > best.score) best = { score, quality, chainSize: length, i, j };
65
101
  }
66
102
  }
67
103
  const pairs = [];
68
- let i = xs.length;
69
- let j = ys.length;
70
- while (i > 0 && j > 0) {
71
- if (table[i][j] === table[i - 1][j]) i -= 1;
72
- else if (table[i][j] === table[i][j - 1]) j -= 1;
73
- else {
74
- pairs.push(...cells[i - 1][j - 1].pairs);
75
- i -= 1;
76
- j -= 1;
104
+ if (best.i >= 0) {
105
+ let i = best.i;
106
+ let j = best.j;
107
+ while (i >= 0 && j >= 0) {
108
+ pairs.unshift([xs[i].node, ys[j].node]);
109
+ i = xs[i].parent;
110
+ j = ys[j].parent;
77
111
  }
78
112
  }
79
113
 
80
- return { total: table[xs.length][ys.length], pairs };
81
- };
82
-
83
- const compare = (a, b) => {
84
- const kidsA = (a.children || []).flatMap(forestOf);
85
- const kidsB = (b.children || []).flatMap(forestOf);
86
- const { total, pairs } = align(kidsA, kidsB);
87
-
88
- return { score: (nodeSimilarity(a, b) + total) / (1 + Math.max(kidsA.length, kidsB.length)), pairs: [[a, b], ...pairs] };
89
- };
90
-
91
- const compareForests = (a, b) => {
92
- const xs = forestOf(a);
93
- const ys = forestOf(b);
94
- const longest = Math.max(xs.length, ys.length);
95
- const { total, pairs } = align(xs, ys);
96
-
97
- return { score: longest === 0 ? 0 : total / longest, pairs };
114
+ return { score: best.score, quality: best.quality, chainSize: best.chainSize, refSize, pairs };
98
115
  };
99
116
 
100
117
  const cssStats = (pairs) => {
@@ -117,88 +134,105 @@ const cssStats = (pairs) => {
117
134
  return { conflicts, ratio: comparable === 0 ? 0 : conflicts / comparable, agreement: union === 0 ? 0 : shared / union };
118
135
  };
119
136
 
120
- const rootNodeScore = (cand, target) => {
121
- const parts = [];
122
- if (!NON_SEMANTIC_TAGS.has(cand.tag)) parts.push({ w: 0.6, v: tagMatch(cand, target) });
123
- const candPairs = pairsOf(cand.css);
124
- if (candPairs.size > 0) parts.push({ w: 0.4, v: coverage(candPairs, pairsOf(target.css)) });
125
- const totalW = parts.reduce((sum, part) => sum + part.w, 0);
126
-
127
- return totalW === 0 ? 0 : parts.reduce((sum, part) => sum + part.w * part.v, 0) / totalW;
128
- };
129
-
130
137
  const isInformative = (node) => !!node && (node.tag !== "fragment" || (node.children || []).some(isInformative));
131
138
 
132
- const shapeOf = (node) => {
133
- const tags = new Set();
134
- let nodes = 0;
135
- const visit = (n) => {
136
- if (n.tag !== "fragment") {
137
- tags.add(n.tag);
138
- nodes += 1;
139
- }
140
- for (const child of n.children || []) visit(child);
141
- };
142
- visit(node);
139
+ const classTokensDiffer = (a, b) => {
140
+ const A = new Set(a || []);
141
+ const B = new Set(b || []);
142
+ if (A.size === 0 && B.size === 0) return false;
143
+ for (const token of A) if (!B.has(token)) return true;
144
+ for (const token of B) if (!A.has(token)) return true;
143
145
 
144
- return { tags, nodes };
146
+ return false;
145
147
  };
146
148
 
147
- const componentNamesOf = (tree, out = new Set()) => {
148
- if (!tree) return out;
149
- for (const name of tree.via || []) out.add(name);
150
- for (const child of tree.children || []) componentNamesOf(child, out);
151
-
152
- return out;
149
+ const treeSimilarity = (a, b) => {
150
+ const result = bestChain(a, b);
151
+ return { score: result.score, quality: result.quality, detail: { similarity: result.score, quality: result.quality, chainSize: result.chainSize, refSize: result.refSize, pairs: result.pairs.length } };
153
152
  };
154
153
 
155
- const sizeOf = (candidate) => {
156
- const { tags, nodes } = shapeOf(candidate.dom.tree);
157
- const distinct = new Set([...tags, ...componentNamesOf(candidate.tree)]).size;
158
-
159
- return { nodes, distinct };
154
+ const firstReal = (node) => {
155
+ if (!node) return null;
156
+ if (node.tag === "fragment" || node.tag === "children" || node.tag === "text") {
157
+ for (const child of node.children || []) {
158
+ const found = firstReal(child);
159
+ if (found) return found;
160
+ }
161
+ return null;
162
+ }
163
+ return node;
160
164
  };
161
165
 
162
- const ceilingOf = (nodes, distinct, stats) => {
163
- const base = CEILING_LADDER[Math.min(nodes - 1, CEILING_LADDER.length - 1)];
164
- if (distinct >= RICH_DISTINCT_MIN && stats.conflicts > 0) return Math.min(base, CONFLICTED_RICH_CEILING);
166
+ const rootSimilarity = (a, b) => {
167
+ const ra = firstReal(a);
168
+ const rb = firstReal(b);
169
+ if (!ra || !rb) return { score: 0, detail: { rootSim: 0 } };
165
170
 
166
- return base;
171
+ return { score: nodeSimilarity(ra, rb), detail: { rootSim: nodeSimilarity(ra, rb) } };
167
172
  };
168
173
 
169
- const classTokensDiffer = (a, b) => {
170
- const A = new Set(a || []);
171
- const B = new Set(b || []);
172
- if (A.size === 0 && B.size === 0) return false;
173
- for (const token of A) if (!B.has(token)) return true;
174
- for (const token of B) if (!A.has(token)) return true;
174
+ const MIN_CROSS_TAG_CLASS_OVERLAP = 3;
175
175
 
176
- return false;
176
+ const rootClassOverlap = (candidate, canon) => {
177
+ const rt = firstReal(candidate.tree);
178
+ if (!rt) return 0;
179
+ const partToks = new Set(String(rt.className || "").split(/\s+/).filter(Boolean));
180
+ const canonToks = new Set(canon.rawClasses || []);
181
+ let n = 0;
182
+ for (const t of partToks) if (canonToks.has(t)) n += 1;
183
+
184
+ return n;
177
185
  };
178
186
 
179
187
  const matchStructure = (candidate, canon) => {
180
188
  const cand = candidate.dom && candidate.dom.tree;
181
189
  const target = canon.dom && canon.dom.tree;
182
- const mode = candidate.partial ? "root-node" : "tree";
190
+ const mode = candidate.partial ? "partial" : "tree";
183
191
  const applicable = isInformative(cand) || isInformative(target);
184
192
  let score = 0;
185
193
  let detail = null;
186
194
  if (applicable && cand && target) {
187
195
  if (candidate.partial) {
196
+ const singleton = nodeCount(target) === 1;
197
+ const partNodes = nodeCount(cand);
188
198
  const classesDiffer = classTokensDiffer(candidate.rawClasses, canon.rawClasses);
189
- const base = rootNodeScore(cand, target);
190
- score = Math.min(base, classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
191
- detail = { similarity: base, ceiling: classesDiffer ? NEAR_IDENTICAL_CEILING : 1, classesDiffer };
199
+ if (singleton) {
200
+ const ra = firstReal(cand);
201
+ const rb = firstReal(target);
202
+ const partTag = ra ? ra.tag : "";
203
+ const canonTag = rb ? rb.tag : "";
204
+ const crossTag = GENERIC_CONTAINER_TAGS.has(partTag) && GENERIC_CONTAINER_TAGS.has(canonTag) && partTag !== canonTag;
205
+ if (crossTag) {
206
+ const overlap = rootClassOverlap(candidate, canon);
207
+ if (overlap < MIN_CROSS_TAG_CLASS_OVERLAP) {
208
+ score = 0;
209
+ detail = { singleton, crossTag, overlap, rejected: true };
210
+ } else {
211
+ score = Math.min(0.9, 0.5 + 0.05 * overlap);
212
+ detail = { singleton, crossTag, overlap };
213
+ }
214
+ } else if (partNodes > 4) {
215
+ score = 0;
216
+ detail = { singleton, partNodes, leafVsWrapper: true };
217
+ } else {
218
+ const { score: q, detail: d } = rootSimilarity(cand, target);
219
+ score = Math.min(q, classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
220
+ detail = { ...d, singleton, classesDiffer };
221
+ }
222
+ } else {
223
+ const { quality, detail: d } = treeSimilarity(cand, target);
224
+ const sizeFactor = Math.min(1, nodeCount(target) / nodeCount(cand));
225
+ const base = quality * sizeFactor;
226
+ score = Math.min(base, classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
227
+ detail = { ...d, singleton, sizeFactor, classesDiffer };
228
+ }
192
229
  } else {
193
- const result = compareForests(cand, target);
230
+ const result = bestChain(cand, target);
194
231
  const stats = cssStats(result.pairs);
195
- const a = sizeOf(candidate);
196
- const b = sizeOf(canon);
197
232
  const classesDiffer = classTokensDiffer(candidate.rawClasses, canon.rawClasses);
198
- const ceiling = Math.min(ceilingOf(Math.min(a.nodes, b.nodes), Math.min(a.distinct, b.distinct), stats), classesDiffer ? NEAR_IDENTICAL_CEILING : 1);
199
- const missingRatio = Math.max(0, Math.max(a.nodes, b.nodes) - Math.min(a.nodes, b.nodes)) / Math.max(1, Math.max(a.nodes, b.nodes));
200
- score = Math.max(0, Math.min(result.score, ceiling) - CONFLICT_PENALTY * stats.ratio - MISSING_CHILD_PENALTY * missingRatio);
201
- detail = { similarity: result.score, ceiling, classesDiffer, conflicts: stats.conflicts, conflictRatio: stats.ratio, agreement: stats.agreement, missingRatio: Math.round(missingRatio * 100) / 100, nodes: Math.min(a.nodes, b.nodes), distinct: Math.min(a.distinct, b.distinct) };
233
+ const ceiling = classesDiffer ? NEAR_IDENTICAL_CEILING : 1;
234
+ score = Math.max(0, Math.min(result.score, ceiling) - CONFLICT_PENALTY * stats.ratio);
235
+ detail = { similarity: result.score, quality: result.quality, chainSize: result.chainSize, refSize: result.refSize, ceiling, classesDiffer, conflicts: stats.conflicts, conflictRatio: stats.ratio, agreement: stats.agreement };
202
236
  }
203
237
  }
204
238
 
package/normalize/dom.js CHANGED
@@ -126,6 +126,23 @@ const HTML_TAGS = new Set([
126
126
 
127
127
  const INTERACTIVE_TAGS = new Set(["a", "area", "audio", "button", "details", "embed", "iframe", "input", "label", "optgroup", "option", "select", "summary", "textarea", "video"]);
128
128
  const NON_SEMANTIC_TAGS = new Set(["div", "span"]);
129
+ const SEMANTIC_CONTAINER_TAGS = new Set(["section", "header", "footer", "article", "aside", "nav"]);
130
+ const GENERIC_CONTAINER_TAGS = new Set([...NON_SEMANTIC_TAGS, ...SEMANTIC_CONTAINER_TAGS]);
131
+ const TAG_SYNONYMS = new Map([
132
+ ["b", "strong"],
133
+ ["strong", "b"],
134
+ ["i", "em"],
135
+ ["em", "i"],
136
+ ]);
137
+
138
+ const tagAffinity = (a, b) => {
139
+ const ta = String(a || "").toLowerCase();
140
+ const tb = String(b || "").toLowerCase();
141
+ if (ta === tb) return 1;
142
+ if (TAG_SYNONYMS.get(ta) === tb) return 1;
143
+ if (GENERIC_CONTAINER_TAGS.has(ta) && GENERIC_CONTAINER_TAGS.has(tb)) return 0.75;
144
+ return 0;
145
+ };
129
146
 
130
147
  const isPascalCase = (name) => /^[A-Z][A-Za-z0-9]*$/.test(name);
131
148
 
@@ -160,6 +177,9 @@ module.exports = {
160
177
  HTML_TAGS,
161
178
  INTERACTIVE_TAGS,
162
179
  NON_SEMANTIC_TAGS,
180
+ SEMANTIC_CONTAINER_TAGS,
181
+ GENERIC_CONTAINER_TAGS,
182
+ tagAffinity,
163
183
  isPascalCase,
164
184
  isHtmlTag,
165
185
  styleObjectToCssText,
@@ -84,31 +84,12 @@ const smallSetDiscount = (arrA, arrB) => {
84
84
  return union === 0 ? 1 : Math.min(1, union / 2);
85
85
  };
86
86
 
87
- const setEqual = (a, b) => {
88
- const A = new Set(a || []);
89
- const B = new Set(b || []);
90
- if (A.size !== B.size) return false;
91
- for (const item of A) if (!B.has(item)) return false;
92
-
93
- return true;
94
- };
95
-
96
- const SAME_NAMES_PROP_FLOOR = 0.95;
97
- const SAME_NAMES_PROP_SPAN = 0.04;
98
-
99
87
  const frameworkSimilarity = (a, b, label) => {
100
88
  const A = a || { props: [], events: [], names: [] };
101
89
  const B = b || { props: [], events: [], names: [] };
102
90
  const props = jaccard(A.props, B.props) * smallSetDiscount(A.props, B.props);
103
91
  const events = jaccard(A.events, B.events) * smallSetDiscount(A.events, B.events);
104
92
  const names = jaccard(A.names, B.names);
105
- const passed = (p) => [...new Set([...p.props, ...p.events])];
106
- const passedA = passed(A);
107
- const passedB = passed(B);
108
- if (A.names.length > 0 && names >= 1) {
109
- if (setEqual(passedA, passedB)) return { score: 1, props, events, names };
110
- return { score: SAME_NAMES_PROP_FLOOR + SAME_NAMES_PROP_SPAN * jaccard(passedA, passedB), props, events, names };
111
- }
112
93
  const parts = [];
113
94
  if (A.props.length || B.props.length) parts.push({ w: 0.5, v: props });
114
95
  if (A.events.length || B.events.length) parts.push({ w: 0.2, v: events });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@md-code/component-uniqueness",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "ESLint rule and CLI that find duplicate components, raw HTML that should be a canonical component, and copied parts of components, by comparing structure, CSS, behavior, accessibility and framework profile.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -51,11 +51,22 @@
51
51
  "typescript": ">=5.5.0 <7"
52
52
  },
53
53
  "scripts": {
54
- "gen:catalog": "node main.js"
54
+ "gen:catalog": "node main.js",
55
+ "test": "vitest run"
55
56
  },
56
57
  "peerDependencies": {
57
58
  "eslint": ">=8.40.0"
58
59
  },
60
+ "devDependencies": {
61
+ "@mui/icons-material": "^7.0.0",
62
+ "@mui/material": "^7.0.0",
63
+ "@emotion/react": "^11.0.0",
64
+ "@emotion/styled": "^11.0.0",
65
+ "react": "^19.0.0",
66
+ "react-dom": "^19.0.0",
67
+ "styled-components": "^6.1.0",
68
+ "vitest": "^4.1.0"
69
+ },
59
70
  "publishConfig": {
60
71
  "access": "public"
61
72
  }
@@ -801,8 +801,7 @@ const parseParts = (fileAbs, canonicalNames, opts) => {
801
801
  endLine: end.line + 1,
802
802
  tree,
803
803
  rootTags: [rootTag],
804
- a11y: [...a11y].sort(),
805
- usesCanonical: names.size > 0 ? [...new Set([...canonicalTagsUsed(n, names), ...viaNames(tree, names)])].sort() : [],
804
+ a11y: [...a11y].sort(), partial: true, usesCanonical: names.size > 0 ? [...new Set([...canonicalTagsUsed(n, names), ...viaNames(tree, names)])].sort() : [],
806
805
  });
807
806
  }
808
807
  }
@@ -906,6 +905,7 @@ const buildDom = (tree, doc) => {
906
905
  }
907
906
  const tag = String(tree.tag || "").toLowerCase();
908
907
  const el = isHtmlTag(tag) ? doc.createElement(tag) : doc.createElement("cu-root");
908
+ if (!isHtmlTag(tag)) el.__cuTag = String(tree.tag);
909
909
  for (const [key, value] of entries(tree.attrs || {})) {
910
910
  if (value === true) el.setAttribute(key, "");
911
911
  else if (value !== null && value !== undefined) el.setAttribute(key, String(value));
@@ -927,7 +927,8 @@ const buildDom = (tree, doc) => {
927
927
 
928
928
  const nodesOf = (el, win, baselineOf) => {
929
929
  const kids = [...el.children].flatMap((child) => nodesOf(child, win, baselineOf));
930
- if (el.tagName === "CU-ROOT") return kids;
930
+ const compTag = el.tagName === "CU-ROOT" ? el.__cuTag || null : null;
931
+ if (el.tagName === "CU-ROOT" && !compTag) return kids;
931
932
  const computed = win.getComputedStyle(el);
932
933
  const base = baselineOf(el);
933
934
  const css = {};
@@ -935,7 +936,7 @@ const nodesOf = (el, win, baselineOf) => {
935
936
  const value = computed.getPropertyValue(prop).trim();
936
937
  if (value && value !== base.getPropertyValue(prop).trim()) css[prop] = value;
937
938
  }
938
- const tag = el.tagName.toLowerCase();
939
+ const tag = compTag || el.tagName.toLowerCase();
939
940
  const interactive = INTERACTIVE_TAGS.has(tag) || el.getAttribute("role") === "button" || el.getAttribute("role") === "link" || [...el.attributes].some((attr) => /^(on|@)/.test(attr.name));
940
941
  const text = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.nodeValue).join("").replace(/\s+/g, " ").trim();
941
942
 
package/report.js CHANGED
@@ -87,9 +87,13 @@ const renderPartsSection = (rows, title = "Parts of components that duplicate a
87
87
  lines.push("");
88
88
  lines.push("| Part | Location | Replace with | From | Why |");
89
89
  lines.push("| --- | --- | --- | --- | --- |");
90
- const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
90
+ const primaryConf = (r) => (r.suggestions && r.suggestions[0] ? r.suggestions[0].confidence : r.confidence) || 0;
91
+ const sorted = [...rows].sort((a, b) => primaryConf(b) - primaryConf(a) || a.path.localeCompare(b.path) || a.line - b.line);
91
92
  for (const r of sorted) {
92
- lines.push(`| ${r.owner} \u203a <${r.tag}> | \`${r.path}:${r.line}-${r.endLine}\` | \`${r.suggestion.component}\` | ${r.suggestion.path} | ${r.reason} |`);
93
+ const s = r.suggestions || [r];
94
+ const primary = s[0];
95
+ const alt = s.length > 1 ? `; alt: \`${s[1].component}\` (${s[1].confidence.toFixed(2)})` : "";
96
+ lines.push(`| ${r.owner} \u203a <${r.tag}> | \`${r.path}:${r.line}-${r.endLine}\` | \`${primary.component}\` (${primary.confidence.toFixed(2)})${alt} | ${primary.path} | ${primary.reason} |`);
93
97
  }
94
98
  lines.push("");
95
99
  return lines;
@@ -133,7 +137,6 @@ const renderComponentReport = (comp, verbose) => {
133
137
  const missingClusters = (comp.missingClusters || []).filter((c) => c.matches.every((m) => !inLayer(m.app.path)));
134
138
  lines.push(...renderMissingSection(missingClusters));
135
139
  if (comp.rawHtml && comp.rawHtml.length > 0) lines.push(...renderRawHtmlSection(comp.rawHtml));
136
- lines.push(...renderPartsSection(appParts));
137
140
  const layerIdx = (p) => folders.findIndex((d) => p.startsWith(d));
138
141
  const layerName = (d) => d.split("/").filter(Boolean).pop();
139
142
  for (let li = 0; li < folders.length; li += 1) {
@@ -145,7 +148,7 @@ const renderComponentReport = (comp, verbose) => {
145
148
  lines.push(...renderTierSection(tier, rows, `Inside ${layerName(folders[li])}: ${TIER_LABEL[tier]}${suffix}`));
146
149
  }
147
150
  }
148
- lines.push(...renderPartsSection(layerParts, "Inside canonical layers: parts that duplicate a lower layer"));
151
+ lines.push(...renderPartsSection([...appParts, ...layerParts], "Partial duplicates (parts)"));
149
152
  if (verbose && comp.dropped && comp.dropped.length > 0) lines.push(...renderFilteredSection(comp.dropped));
150
153
  return lines.join("\n");
151
154
  };