@md-code/component-uniqueness 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -90,4 +90,14 @@ Options are read from the rule in `eslint.config.js`.
90
90
  | `--app-roots a:b` | Folders to scan for the report (default: repo root) |
91
91
  | `--repo-root <dir>` | Repo root (default: auto-detected) |
92
92
  | `--out <file>` | Catalog path |
93
+ | `--include a.tsx:b.tsx` | Only scan matching app files |
94
+ | `--ignore-dirs a:b` | Extra directories to skip |
95
+ | `--thresholds dup:sim` | Confidence cut-offs, e.g. `0.5:0.3` |
96
+ | `--raw-html` | Also report raw HTML that should be a canonical component |
97
+ | `--parts` | Also report blocks inside components that duplicate a canonical |
98
+ | `--config file` | Read rule options from a specific `eslint.config.js` or options file |
99
+ | `--min-cluster N` | Min app components matching one canonical to flag it as a missing component (default 3) |
100
+ | `--log file` | Write a per-stage JSON log |
93
101
  | `--verbose` | Also list what the filters dropped |
102
+
103
+ Rule options (`weights`, `thresholds`, `rawHtml`, `parts`, `include`, `ignoreDirs`) are always 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.
package/config.js CHANGED
@@ -244,7 +244,21 @@ const loadLegacyOptions = async (file) => {
244
244
  return v === undefined || v === null ? null : pickOptions(v);
245
245
  };
246
246
 
247
- const loadRuleOptions = async (dir) => {
247
+ const loadRuleOptions = async (dir, explicitFile = null) => {
248
+ if (explicitFile) {
249
+ const file = path.isAbsolute(explicitFile) ? explicitFile : path.resolve(dir, explicitFile);
250
+ if (!fs.existsSync(file)) return null;
251
+ if (file.endsWith(".json")) {
252
+ const options = pickOptions(JSON.parse(fs.readFileSync(file, "utf8")));
253
+ return options ? { options, source: file } : null;
254
+ }
255
+ try {
256
+ const options = file.startsWith("eslint.config") ? await loadFlatOptions(file) : pickOptions(await loadModule(file));
257
+ return options ? { options, source: file } : null;
258
+ } catch {
259
+ return null;
260
+ }
261
+ }
248
262
  let d = dir;
249
263
  for (;;) {
250
264
  const standalone = path.join(d, "md-code-component-uniqueness.config.js");
@@ -21,14 +21,20 @@ const suggestName = (appNames, canonName = null) => {
21
21
  }
22
22
  const common = order.filter((k) => counts.get(k) >= 2);
23
23
  const meaningful = common.filter((k) => !GENERIC_WORDS.has(k));
24
- const base = (meaningful.length > 0 ? meaningful : common).map((k) => k[0].toUpperCase() + k.slice(1));
24
+ const base = (meaningful.length > 0 ? meaningful : common).slice(0, 3).map((k) => k[0].toUpperCase() + k.slice(1));
25
25
  if (base.length > 0) {
26
26
  const name = pascalCase(base);
27
27
  if (meaningful.length > 0) return name;
28
28
  return canonName ? `${name}${canonName}` : name;
29
29
  }
30
- const first = appNames[0];
31
- return first ? pascalWords(first).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()).join("") : "Component";
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)]);
34
+ }
35
+ return `Shared${canonName}`;
36
+ }
37
+ return "SharedComponent";
32
38
  };
33
39
 
34
40
  const findMissingComponents = (matches, { minCluster = DEFAULT_MIN_CLUSTER } = {}) => {
package/main.js CHANGED
@@ -57,7 +57,7 @@ const fail = (message) => {
57
57
  };
58
58
 
59
59
  const parseArgs = (argv) => {
60
- const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, appRoots: null, ignoreDirs: null, verbose: false, include: null, log: null, minCluster: 3 };
60
+ const cfg = { roots: null, out: null, registry: null, repoRoot: null, check: false, report: null, appRoots: null, ignoreDirs: null, verbose: false, include: null, log: null, minCluster: 3, thresholds: null, rawHtml: false, parts: false, configFile: null };
61
61
  for (let i = 0; i < argv.length; i += 1) {
62
62
  const a = argv[i];
63
63
  if (a === "--check") {
@@ -87,6 +87,10 @@ const parseArgs = (argv) => {
87
87
  } else if (a === "--ignore-dirs") {
88
88
  if (!argv[i + 1]) fail("--ignore-dirs requires a value (colon-separated list of directory names)");
89
89
  cfg.ignoreDirs = argv[++i].split(":").filter(Boolean);
90
+ } else if (a === "--raw-html") {
91
+ cfg.rawHtml = true;
92
+ } else if (a === "--parts") {
93
+ cfg.parts = true;
90
94
  } else if (a === "--verbose") {
91
95
  cfg.verbose = true;
92
96
  } else if (a === "--include") {
@@ -95,15 +99,23 @@ const parseArgs = (argv) => {
95
99
  } else if (a === "--log") {
96
100
  if (!argv[i + 1]) fail("--log requires a value (path to the stage log file)");
97
101
  cfg.log = argv[++i];
102
+ } else if (a === "--thresholds") {
103
+ if (!argv[i + 1]) fail("--thresholds requires a value (duplicate:similar, e.g. 0.5:0.2)");
104
+ const [dup, sim] = argv[++i].split(":").map((s) => Number.parseFloat(s));
105
+ if (!Number.isFinite(dup) || !Number.isFinite(sim)) fail("--thresholds must be two numbers separated by a colon (duplicate:similar)");
106
+ cfg.thresholds = { duplicate: dup, similar: sim };
98
107
  } else if (a === "--min-cluster") {
99
108
  if (!argv[i + 1]) fail("--min-cluster requires a value (min app components matching one canonical to flag it as a missing component)");
100
109
  const n = Number.parseInt(argv[i + 1], 10);
101
110
  if (!Number.isFinite(n) || n < 2) fail("--min-cluster must be an integer >= 2");
102
111
  cfg.minCluster = n;
103
112
  i += 1;
113
+ } else if (a === "--config") {
114
+ if (!argv[i + 1]) fail("--config requires a value (path to an eslint.config.js or a standalone options file)");
115
+ cfg.configFile = argv[++i];
104
116
  } else if (a === "--help" || a === "-h") {
105
- console.log("Usage: component-uniqueness [--roots a:b] [--out file] [--registry file] [--repo-root dir] [--check] [--report [file.md]] [--app-roots a:b] [--ignore-dirs a:b] [--include a.tsx:b.tsx] [--log file] [--min-cluster N] [--verbose]");
106
- console.log("Without --roots, the options are read from the consumer's eslint.config.js (rule md-code/component-uniqueness) or component-uniqueness.config.js.");
117
+ console.log("Usage: component-uniqueness [--roots a:b] [--out file] [--registry file] [--repo-root dir] [--check] [--report [file.md]] [--app-roots a:b] [--ignore-dirs a:b] [--include a.tsx:b.tsx] [--thresholds dup:sim] [--raw-html] [--parts] [--config file] [--log file] [--min-cluster N] [--verbose]");
118
+ 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.");
107
119
  process.exit(0);
108
120
  } else {
109
121
  fail(`unknown argument: ${a} (see --help)`);
@@ -406,7 +418,10 @@ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, r
406
418
  const { kept, dropped } = applyFilters(matches);
407
419
  const deduped = dedupPairs(kept);
408
420
  stage("components matched");
409
- const { clusters, remaining } = findMissingComponents(deduped, { minCluster: args.minCluster });
421
+ const inLayer = (p) => (config.componentsFolder || []).some((d) => p.startsWith(d));
422
+ const layerMatches = deduped.filter((m) => inLayer(m.app.path));
423
+ const appMatches = deduped.filter((m) => !inLayer(m.app.path));
424
+ const { clusters, remaining } = findMissingComponents(appMatches, { minCluster: args.minCluster });
410
425
  if (log.enabled()) {
411
426
  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 });
412
427
  }
@@ -417,7 +432,7 @@ const buildComponentReport = async (args, repoRoot, roots, shouldSkip, config, r
417
432
  stage("parts done");
418
433
 
419
434
  return {
420
- matches: remaining,
435
+ matches: [...remaining, ...layerMatches],
421
436
  dropped,
422
437
  missingClusters: clusters,
423
438
  rawHtml,
@@ -433,10 +448,12 @@ const main = async () => {
433
448
  const args = parseArgs(process.argv.slice(2));
434
449
  const cwd = process.cwd();
435
450
 
436
- const loaded = args.roots ? null : await loadRuleOptions(cwd);
451
+ const loaded = await loadRuleOptions(cwd, args.configFile);
437
452
  const configOptions = loaded ? { ...loaded.options } : {};
438
453
  if (loaded) {
439
454
  console.log(`[component-uniqueness] config from ${loaded.source}`);
455
+ } else if (!args.configFile) {
456
+ console.log("[component-uniqueness] no rule options found in eslint.config.js / md-code-component-uniqueness.config.js; using defaults");
440
457
  }
441
458
  if (args.ignoreDirs) {
442
459
  const base = Array.isArray(configOptions.ignoreDirs) ? configOptions.ignoreDirs : [];
@@ -445,6 +462,9 @@ const main = async () => {
445
462
 
446
463
  const config = normalizeOptions(configOptions);
447
464
  if (args.include) config.include = [...new Set([...(config.include || []), ...args.include])];
465
+ if (args.thresholds) config.thresholds = { ...(config.thresholds || {}), ...args.thresholds };
466
+ if (args.rawHtml) config.rawHtml = true;
467
+ if (args.parts) config.parts = true;
448
468
  if (args.log) log.enable(args.log);
449
469
  await require("./playgrounds/style-entrypoint.js").whenReady(config);
450
470
  const rootMarkers = config.rootMarkers;
@@ -455,6 +475,9 @@ const main = async () => {
455
475
  if (!roots || roots.length === 0) {
456
476
  fail("no scan roots: pass --roots <dir1>:<dir2> or set componentsFolder in the rule options (eslint.config.js / component-uniqueness.config.js)");
457
477
  }
478
+ if (!config.componentsFolder || config.componentsFolder.length === 0) {
479
+ config.componentsFolder = roots;
480
+ }
458
481
 
459
482
  const outPath = resolveAgainst(args.out || config.catalogPath, repoRoot);
460
483
  const registry = args.registry ? loadRegistry({ ...config, registry: null, registryPath: args.registry }) : loadRegistry(config);
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+
3
+ const { styledDeclarations, available: styledAvailable } = require("../playgrounds/styled-components.js");
4
+ const { cssTextToStyles } = require("./style.js");
5
+
6
+ const declarationsCache = new WeakMap();
7
+
8
+ const declarationsOf = (sf) => {
9
+ if (!declarationsCache.has(sf)) declarationsCache.set(sf, styledDeclarations(sf));
10
+ return declarationsCache.get(sf);
11
+ };
12
+
13
+ const buildStyledResolver = () => {
14
+ if (!styledAvailable()) return null;
15
+ return (tag, sf) => {
16
+ if (!sf || !tag) return null;
17
+ const info = declarationsOf(sf).get(tag);
18
+ if (!info) return null;
19
+ const { css, unresolved } = cssTextToStyles(info.cssText);
20
+ return { baseTag: info.baseTag, componentRef: info.componentRef, styleObj: css, unresolved: [...unresolved, ...info.unresolved] };
21
+ };
22
+ };
23
+
24
+ module.exports = { buildStyledResolver };
@@ -71,6 +71,7 @@ const LAYOUT_PROPS = new Set([
71
71
  "overflow-wrap",
72
72
  "text-overflow",
73
73
  "white-space",
74
+ "font-size",
74
75
  "box-sizing",
75
76
  "object-fit",
76
77
  "object-position",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@md-code/component-uniqueness",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
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": [
@@ -2,6 +2,13 @@
2
2
 
3
3
  const { normalizeOptions } = require("../config.js");
4
4
  const { buildStylesheet } = require("./style-entrypoint.js");
5
+ const { buildStyledResolver } = require("../normalize/style-resolver.js");
6
+
7
+ let styledResolver = null;
8
+ const withStyledResolver = (opts) => {
9
+ if (!styledResolver) styledResolver = buildStyledResolver();
10
+ return styledResolver ? { ...opts, styledResolver } : opts;
11
+ };
5
12
 
6
13
  const PLAYGROUNDS = {
7
14
  react: () => require("./react.js"),
@@ -25,19 +32,19 @@ const getFramework = (opts) => normalizeOptions(opts).framework;
25
32
  const parseComponents = (fileAbs, canonicalNames, opts) => {
26
33
  const pg = getPlayground(getFramework(opts));
27
34
  if (!pg.available || !pg.available()) return [];
28
- return pg.parseComponents(fileAbs, canonicalNames, opts);
35
+ return pg.parseComponents(fileAbs, canonicalNames, withStyledResolver(opts));
29
36
  };
30
37
 
31
38
  const parseElements = (fileAbs, canonicalNames, opts) => {
32
39
  const pg = getPlayground(getFramework(opts));
33
40
  if (!pg.available || !pg.available() || !pg.parseElements) return [];
34
- return pg.parseElements(fileAbs, canonicalNames, opts);
41
+ return pg.parseElements(fileAbs, canonicalNames, withStyledResolver(opts));
35
42
  };
36
43
 
37
44
  const parseParts = (fileAbs, canonicalNames, opts) => {
38
45
  const pg = getPlayground(getFramework(opts));
39
46
  if (!pg.available || !pg.available() || !pg.parseParts) return [];
40
- return pg.parseParts(fileAbs, canonicalNames, opts);
47
+ return pg.parseParts(fileAbs, canonicalNames, withStyledResolver(opts));
41
48
  };
42
49
 
43
50
  const resolveCss = (tree, opts) => {
@@ -372,7 +372,7 @@ const memberTarget = (sf, head, prop) => {
372
372
  return found;
373
373
  };
374
374
 
375
- const resolveTag = (name, fileAbs, depth, props) => {
375
+ const resolveTag = (name, fileAbs, depth, props, styledResolver) => {
376
376
  const staticProps = Object.entries(props || {}).filter(([, v]) => typeof v === "string").sort();
377
377
  const key = `${fileAbs}::${name}::${JSON.stringify(staticProps)}`;
378
378
  if (resolvedTags.has(key)) return resolvedTags.get(key);
@@ -395,7 +395,7 @@ const resolveTag = (name, fileAbs, depth, props) => {
395
395
  const inner = firstComponentNodeIn(decl.body);
396
396
  if (!inner) return null;
397
397
  resolvedTags.set(key, null);
398
- const built = buildTree(inner, targetSf, { bodies: localComponentBodies(targetSf), depth: depth + 1, nodes: 0, props: Object.fromEntries(staticProps), resolveTag: (tag, nested) => resolveTag(tag, located.file, depth + 1, nested) });
398
+ const built = buildTree(inner, targetSf, { bodies: localComponentBodies(targetSf), depth: depth + 1, nodes: 0, props: Object.fromEntries(staticProps), styledResolver, resolveTag: (tag, nested) => resolveTag(tag, located.file, depth + 1, nested, styledResolver) });
399
399
  const tree = built && { ...built, via: [declName, ...(built.via || [])] };
400
400
  resolvedTags.set(key, tree);
401
401
  return tree;
@@ -489,6 +489,8 @@ const buildTree = (node, sf, ctx) => {
489
489
  }
490
490
  const resolved = ctx.resolveTag ? ctx.resolveTag(tag, attrs) : null;
491
491
  if (resolved) return graftChildren(resolved, children, tree);
492
+ const styledInfo = ctx.styledResolver ? ctx.styledResolver(tag, sf) : null;
493
+ if (styledInfo) return styledNode(tag, styledInfo, tree, children, sf, ctx);
492
494
  dynamic = true;
493
495
  dynamicRefs.push(tag);
494
496
  }
@@ -552,6 +554,34 @@ const graftChildren = (resolved, children, usage) => {
552
554
  return fillSlot(clone, children).node;
553
555
  };
554
556
 
557
+ const styledNode = (tag, info, usage, children, sf, ctx) => {
558
+ let base = null;
559
+ if (info.componentRef) {
560
+ const body = ctx.bodies.get(info.componentRef);
561
+ if (body && ctx.depth < MAX_UNFOLD_DEPTH) {
562
+ const inner = firstComponentNodeIn(body);
563
+ if (inner) base = buildTree(inner, sf, { ...ctx, depth: ctx.depth + 1, props: {} });
564
+ }
565
+ if (!base) base = ctx.resolveTag ? ctx.resolveTag(info.componentRef, {}) : null;
566
+ }
567
+ if (base) {
568
+ const merged = { ...(base.style || {}) };
569
+ for (const [k, v] of Object.entries(info.styleObj || {})) merged[k] = v;
570
+ const clone = { ...base, style: Object.keys(merged).length > 0 ? merged : null, cssText: styleObjectToCssText(merged), via: [tag, ...(base.via || [])] };
571
+ return graftChildren(clone, children, usage);
572
+ }
573
+ return {
574
+ tag: info.baseTag || tag,
575
+ spread: usage.spread,
576
+ attrs: usage.attrs,
577
+ className: usage.className,
578
+ style: Object.keys(info.styleObj || {}).length > 0 ? info.styleObj : null,
579
+ cssText: styleObjectToCssText(info.styleObj || {}),
580
+ children,
581
+ via: [tag],
582
+ };
583
+ };
584
+
555
585
  const a11yOfOpening = (opening, sf, out) => {
556
586
  for (const attr of opening.attributes.properties) {
557
587
  if (!ts.isJsxAttribute(attr) || !attr.name) continue;
@@ -711,7 +741,7 @@ const parseElements = (fileAbs, canonicalNames, opts) => {
711
741
  const opening = openingOf(n);
712
742
  const tag = tagOf(opening.tagName);
713
743
  if (tag && isHtmlTag(tag)) {
714
- const tree = buildTree(n, sf, { bodies, depth: 0, nodes: 0, props: {}, resolveTag: (name, props) => resolveTag(name, fileAbs, 0, props) });
744
+ const tree = buildTree(n, sf, { bodies, depth: 0, nodes: 0, props: {}, styledResolver: opts.styledResolver, resolveTag: (name, props) => resolveTag(name, fileAbs, 0, props, opts.styledResolver) });
715
745
  if (tree) {
716
746
  const a11y = new Set();
717
747
  a11yOfOpening(opening, sf, a11y);
@@ -755,7 +785,7 @@ const parseParts = (fileAbs, canonicalNames, opts) => {
755
785
  if (n !== root && isJsxNode(n)) {
756
786
  const size = jsxCount(n);
757
787
  if (size >= MIN_PART_NODES && size <= MAX_PART_NODES) {
758
- const tree = buildTree(n, sf, { bodies, depth: 0, nodes: 0, props: {}, resolveTag: (name, props) => resolveTag(name, fileAbs, 0, props) });
788
+ const tree = buildTree(n, sf, { bodies, depth: 0, nodes: 0, props: {}, styledResolver: opts.styledResolver, resolveTag: (name, props) => resolveTag(name, fileAbs, 0, props, opts.styledResolver) });
759
789
  if (tree && treeSize(tree) >= MIN_PART_NODES) {
760
790
  const rootTag = tagOf(openingOf(n).tagName);
761
791
  const a11y = new Set();
@@ -832,7 +862,7 @@ const parseComponents = (fileAbs, canonicalNames, opts) => {
832
862
  for (const d of decls) {
833
863
  if (!hasComponentMarkup(d.body)) continue;
834
864
  const root = firstComponentNodeIn(d.body);
835
- const tree = root ? buildTree(root, sf, { bodies, depth: 0, nodes: 0, resolveTag: (tag, props) => resolveTag(tag, fileAbs, 0, props) }) : null;
865
+ const tree = root ? buildTree(root, sf, { bodies, depth: 0, nodes: 0, styledResolver: opts.styledResolver, resolveTag: (tag, props) => resolveTag(tag, fileAbs, 0, props, opts.styledResolver) }) : null;
836
866
  const rawTree = root ? buildTree(root, sf, { bodies, depth: 0, nodes: 0, noUnfold: true }) : null;
837
867
  const a11y = new Set();
838
868
  gatherA11y(d.body, sf, a11y);
@@ -1,7 +1,138 @@
1
1
  "use strict";
2
2
 
3
+ const ts = require("typescript");
4
+
5
+ const MAX_LITERAL_DEPTH = 4;
6
+ const MAX_LITERAL_COUNT = 12;
7
+
8
+ const stringLiterals = (node, out, depth = 0) => {
9
+ if (!node || depth > MAX_LITERAL_DEPTH || out.length >= MAX_LITERAL_COUNT) return;
10
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
11
+ out.push(node.text);
12
+ return;
13
+ }
14
+ if (ts.isNumericLiteral(node)) {
15
+ out.push(node.text);
16
+ return;
17
+ }
18
+ if (ts.isParenthesizedExpression(node)) {
19
+ stringLiterals(node.expression, out, depth + 1);
20
+ return;
21
+ }
22
+ if (ts.isTemplateExpression(node)) {
23
+ if (node.head.text) out.push(node.head.text);
24
+ for (const span of node.templateSpans) {
25
+ if (span.literal.text) out.push(span.literal.text);
26
+ stringLiterals(span.expression, out, depth + 1);
27
+ }
28
+ return;
29
+ }
30
+ if (ts.isCallExpression(node)) {
31
+ for (const arg of node.arguments) stringLiterals(arg, out, depth + 1);
32
+ return;
33
+ }
34
+ if (ts.isConditionalExpression(node)) {
35
+ stringLiterals(node.whenTrue, out, depth + 1);
36
+ stringLiterals(node.whenFalse, out, depth + 1);
37
+ return;
38
+ }
39
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.Plus) {
40
+ stringLiterals(node.left, out, depth + 1);
41
+ stringLiterals(node.right, out, depth + 1);
42
+ return;
43
+ }
44
+ };
45
+
46
+ const localDeclarations = (sf) => {
47
+ const map = new Map();
48
+ const visit = (node) => {
49
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && !map.has(node.name.text)) {
50
+ map.set(node.name.text, node.initializer);
51
+ }
52
+ ts.forEachChild(node, visit);
53
+ };
54
+ visit(sf);
55
+ return map;
56
+ };
57
+
58
+ const literalOf = (expr, decls, depth = 0) => {
59
+ if (!expr || depth > 3) return null;
60
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) return expr.text;
61
+ if (ts.isNumericLiteral(expr)) return expr.text;
62
+ if (ts.isParenthesizedExpression(expr)) return literalOf(expr.expression, decls, depth + 1);
63
+ if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
64
+ let body = expr.body;
65
+ if (ts.isBlock(body)) {
66
+ const ret = body.statements.find((s) => ts.isReturnStatement(s) && s.expression);
67
+ if (!ret) return null;
68
+ body = ret.expression;
69
+ }
70
+ return literalOf(body, decls, depth + 1);
71
+ }
72
+ if (ts.isIdentifier(expr)) {
73
+ const decl = decls.get(expr.text);
74
+ if (!decl) return null;
75
+ return literalOf(decl, decls, depth + 1);
76
+ }
77
+ if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression)) {
78
+ const decl = decls.get(expr.expression.text);
79
+ if (!decl) return null;
80
+ return literalOf(decl, decls, depth + 1);
81
+ }
82
+ return null;
83
+ };
84
+
85
+ const templateToCss = (template, decls, sf) => {
86
+ const unresolved = [];
87
+ if (ts.isNoSubstitutionTemplateLiteral(template)) return { cssText: template.text, unresolved };
88
+ if (!ts.isTemplateExpression(template)) return { cssText: "", unresolved };
89
+ let text = template.head.text;
90
+ for (const span of template.templateSpans) {
91
+ const value = literalOf(span.expression, decls);
92
+ if (value !== null) {
93
+ text += value;
94
+ } else {
95
+ const strs = [];
96
+ stringLiterals(span.expression, strs);
97
+ if (strs.length > 0) text += strs.join(" ");
98
+ else unresolved.push(span.expression.getText(sf));
99
+ }
100
+ text += span.literal.text;
101
+ }
102
+ return { cssText: text, unresolved };
103
+ };
104
+
105
+ const styledTagInfo = (tag) => {
106
+ if (ts.isPropertyAccessExpression(tag) && ts.isIdentifier(tag.expression) && tag.expression.text === "styled" && ts.isIdentifier(tag.name)) {
107
+ return { baseTag: tag.name.text, componentRef: null };
108
+ }
109
+ if (ts.isCallExpression(tag) && ts.isIdentifier(tag.expression) && tag.expression.text === "styled" && tag.arguments.length === 1 && ts.isIdentifier(tag.arguments[0])) {
110
+ return { baseTag: null, componentRef: tag.arguments[0].text };
111
+ }
112
+ return null;
113
+ };
114
+
115
+ const styledDeclarations = (sf) => {
116
+ const out = new Map();
117
+ const decls = localDeclarations(sf);
118
+ const visit = (node) => {
119
+ if (ts.isVariableStatement(node)) {
120
+ for (const d of node.declarationList.declarations) {
121
+ if (!ts.isIdentifier(d.name) || !d.initializer || !ts.isTaggedTemplateExpression(d.initializer)) continue;
122
+ const info = styledTagInfo(d.initializer.tag);
123
+ if (!info) continue;
124
+ const { cssText, unresolved } = templateToCss(d.initializer.template, decls, sf);
125
+ out.set(d.name.text, { baseTag: info.baseTag, componentRef: info.componentRef, cssText, unresolved });
126
+ }
127
+ }
128
+ ts.forEachChild(node, visit);
129
+ };
130
+ visit(sf);
131
+ return out;
132
+ };
133
+
3
134
  const resolveClasses = (classes) => {
4
135
  return { css: {}, unresolved: [...(classes || [])] };
5
136
  };
6
137
 
7
- module.exports = { resolveClasses, available: () => false };
138
+ module.exports = { styledDeclarations, resolveClasses, available: () => true };
package/report.js CHANGED
@@ -1,153 +1,159 @@
1
- "use strict";
2
-
3
- const TIERS = ["duplicate", "similar"];
4
-
5
- const TIER_LABEL = {
6
- duplicate: "Duplicate (confidence ≥ threshold)",
7
- similar: "Similar (below duplicate threshold)",
8
- };
9
-
10
- const duplicateText = (match) => {
11
- const d = match.decision;
12
- return `Component \`${match.app.name}\` duplicates canonical \`${match.canon.name}\` (${match.canon.path}) — ${d.reason}. Use the canonical component instead.`;
13
- };
14
-
15
- const rawHtmlText = (tag, suggestion) => {
16
- return `Raw <${tag}> outside the canonical packages → replace with \`${suggestion.component}\` from ${suggestion.path}.`;
17
- };
18
-
19
- const renderHeader = (comp) => {
20
- const lines = [];
21
- lines.push("# Component duplicates (component-level funnel)");
22
- lines.push("");
23
- lines.push(`Scanned ${comp.files} app file(s), ${comp.appCount} app component(s) against ${comp.canonCount} canonical component(s).`);
24
- const dupCount = comp.matches.filter((m) => m.decision.tier === "duplicate").length;
25
- const simCount = comp.matches.filter((m) => m.decision.tier === "similar").length;
26
- const missingCount = (comp.missingClusters || []).reduce((n, c) => n + c.matches.length, 0);
27
- lines.push(`Found ${dupCount} duplicate component(s) and ${simCount} similar component(s)${comp.dropped && comp.dropped.length > 0 ? ` (after filtering out ${comp.dropped.length} match(es))` : ""}${missingCount > 0 ? `, plus ${missingCount} component(s) grouped under ${(comp.missingClusters || []).length} potentially missing component(s)` : ""}.`);
28
- lines.push("");
29
- return lines;
30
- };
31
-
32
- const renderTierSection = (tier, rows, title = TIER_LABEL[tier]) => {
33
- const lines = [];
34
- lines.push(`## ${title} (${rows.length})`);
35
- lines.push("");
36
- lines.push("| Local component | Location | Duplicates canonical | Canonical location | Confidence | Why |");
37
- lines.push("| --- | --- | --- | --- | --- | --- |");
38
- const sorted = [...rows].sort((a, b) => b.decision.confidence - a.decision.confidence || a.canon.name.localeCompare(b.canon.name));
39
- for (const m of sorted) {
40
- lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | \`${m.canon.path}\` | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
41
- }
42
- lines.push("");
43
- return lines;
44
- };
45
-
46
- const renderMissingSection = (clusters) => {
47
- if (!clusters || clusters.length === 0) return [];
48
- const lines = [];
49
- lines.push(`## Potentially missing component (${clusters.length})`);
50
- lines.push("");
51
- lines.push("Several distinct components all matched the same canonical. This usually means the codebase is missing a shared component that would unify them — not that any single one is a duplicate. Consider extracting a new canonical component for each group below.");
52
- lines.push("");
53
- for (const cluster of clusters) {
54
- lines.push(`### ${cluster.name}`);
55
- lines.push("");
56
- lines.push(`All ${cluster.matches.length} components below matched canonical \`${cluster.canon.name}\` (\`${cluster.canon.path}\`). They are structurally similar to each other but distinct enough that none is a clean duplicate — a shared \`${cluster.name}\` would likely cover them.`);
57
- lines.push("");
58
- lines.push("| Local component | Location | Matched canonical | Confidence | Why |");
59
- lines.push("| --- | --- | --- | --- | --- |");
60
- for (const m of cluster.matches) {
61
- lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
62
- }
63
- lines.push("");
64
- }
65
- return lines;
66
- };
67
-
68
- const renderRawHtmlSection = (rows) => {
69
- if (rows.length === 0) return [];
70
- const lines = [];
71
- lines.push(`## Raw HTML outside canonical packages (${rows.length})`);
72
- lines.push("");
73
- lines.push("| Element | Location | Replace with | From | Why |");
74
- lines.push("| --- | --- | --- | --- | --- |");
75
- const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path));
76
- for (const r of sorted) {
77
- lines.push(`| <${r.tag}> | \`${r.path}:${r.line}\` | \`${r.suggestion.component}\` | ${r.suggestion.path} | ${r.reason} |`);
78
- }
79
- lines.push("");
80
- return lines;
81
- };
82
-
83
- const renderPartsSection = (rows, title = "Parts of components that duplicate a canonical") => {
84
- if (rows.length === 0) return [];
85
- const lines = [];
86
- lines.push(`## ${title} (${rows.length})`);
87
- lines.push("");
88
- lines.push("| Part | Location | Replace with | From | Why |");
89
- lines.push("| --- | --- | --- | --- | --- |");
90
- const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
91
- 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
- }
94
- lines.push("");
95
- return lines;
96
- };
97
-
98
- const renderFilteredSection = (dropped) => {
99
- const lines = [];
100
- const byFilter = new Map();
101
- for (const d of dropped) {
102
- if (!byFilter.has(d.filter)) byFilter.set(d.filter, []);
103
- byFilter.get(d.filter).push(d);
104
- }
105
- for (const [filter, rows] of byFilter) {
106
- lines.push(`## Filtered out by \`${filter}\` (${rows.length})`);
107
- lines.push("");
108
- lines.push("| Local component | Location | Canonical | Why dropped |");
109
- lines.push("| --- | --- | --- | --- |");
110
- const sorted = [...rows].sort((a, b) => a.match.canon.name.localeCompare(b.match.canon.name));
111
- for (const d of sorted) {
112
- lines.push(`| ${d.match.app.name} | \`${d.match.app.path}:${d.match.app.line}\` | ${d.match.canon.name} | ${d.reason} |`);
113
- }
114
- lines.push("");
115
- }
116
- return lines;
117
- };
118
-
119
- const renderComponentReport = (comp, verbose) => {
120
- const lines = [];
121
- const folders = comp.layerFolders || [];
122
- const inLayer = (p) => folders.some((d) => p.startsWith(d));
123
- const appMatches = comp.matches.filter((m) => !inLayer(m.app.path));
124
- const layerMatches = comp.matches.filter((m) => inLayer(m.app.path));
125
- const appParts = (comp.parts || []).filter((r) => !inLayer(r.path));
126
- const layerParts = (comp.parts || []).filter((r) => inLayer(r.path));
127
- lines.push(...renderHeader(comp));
128
- for (const tier of TIERS) {
129
- const rows = appMatches.filter((m) => m.decision.tier === tier);
130
- if (rows.length === 0) continue;
131
- lines.push(...renderTierSection(tier, rows));
132
- }
133
- const missingClusters = (comp.missingClusters || []).filter((c) => !inLayer(c.canon.path));
134
- lines.push(...renderMissingSection(missingClusters));
135
- if (comp.rawHtml && comp.rawHtml.length > 0) lines.push(...renderRawHtmlSection(comp.rawHtml));
136
- lines.push(...renderPartsSection(appParts));
137
- for (const tier of TIERS) {
138
- const rows = layerMatches.filter((m) => m.decision.tier === tier);
139
- if (rows.length === 0) continue;
140
- lines.push(...renderTierSection(tier, rows, `Inside canonical layers: ${TIER_LABEL[tier]}`));
141
- }
142
- lines.push(...renderPartsSection(layerParts, "Inside canonical layers: parts that duplicate a lower layer"));
143
- if (verbose && comp.dropped && comp.dropped.length > 0) lines.push(...renderFilteredSection(comp.dropped));
144
- return lines.join("\n");
145
- };
146
-
147
- module.exports = {
148
- renderComponentReport,
149
- duplicateText,
150
- rawHtmlText,
151
- TIERS,
152
- TIER_LABEL,
153
- };
1
+ "use strict";
2
+
3
+ const TIERS = ["duplicate", "similar"];
4
+
5
+ const TIER_LABEL = {
6
+ duplicate: "Duplicate (confidence ≥ threshold)",
7
+ similar: "Similar (below duplicate threshold)",
8
+ };
9
+
10
+ const duplicateText = (match) => {
11
+ const d = match.decision;
12
+ return `Component \`${match.app.name}\` duplicates canonical \`${match.canon.name}\` (${match.canon.path}) — ${d.reason}. Use the canonical component instead.`;
13
+ };
14
+
15
+ const rawHtmlText = (tag, suggestion) => {
16
+ return `Raw <${tag}> outside the canonical packages → replace with \`${suggestion.component}\` from ${suggestion.path}.`;
17
+ };
18
+
19
+ const renderHeader = (comp) => {
20
+ const lines = [];
21
+ lines.push("# Component duplicates (component-level funnel)");
22
+ lines.push("");
23
+ lines.push(`Scanned ${comp.files} app file(s), ${comp.appCount} app component(s) against ${comp.canonCount} canonical component(s).`);
24
+ const dupCount = comp.matches.filter((m) => m.decision.tier === "duplicate").length;
25
+ const simCount = comp.matches.filter((m) => m.decision.tier === "similar").length;
26
+ const missingCount = (comp.missingClusters || []).reduce((n, c) => n + c.matches.length, 0);
27
+ lines.push(`Found ${dupCount} duplicate component(s) and ${simCount} similar component(s)${comp.dropped && comp.dropped.length > 0 ? ` (after filtering out ${comp.dropped.length} match(es))` : ""}${missingCount > 0 ? `, plus ${missingCount} component(s) grouped under ${(comp.missingClusters || []).length} potentially missing component(s)` : ""}.`);
28
+ lines.push("");
29
+ return lines;
30
+ };
31
+
32
+ const renderTierSection = (tier, rows, title = TIER_LABEL[tier]) => {
33
+ const lines = [];
34
+ lines.push(`## ${title} (${rows.length})`);
35
+ lines.push("");
36
+ lines.push("| Local component | Location | Duplicates canonical | Canonical location | Confidence | Why |");
37
+ lines.push("| --- | --- | --- | --- | --- | --- |");
38
+ const sorted = [...rows].sort((a, b) => b.decision.confidence - a.decision.confidence || a.canon.name.localeCompare(b.canon.name));
39
+ for (const m of sorted) {
40
+ lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | \`${m.canon.path}\` | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
41
+ }
42
+ lines.push("");
43
+ return lines;
44
+ };
45
+
46
+ const renderMissingSection = (clusters) => {
47
+ if (!clusters || clusters.length === 0) return [];
48
+ const lines = [];
49
+ lines.push(`## Potentially missing component (${clusters.length})`);
50
+ lines.push("");
51
+ lines.push("Several distinct components all matched the same canonical. This usually means the codebase is missing a shared component that would unify them — not that any single one is a duplicate. Consider extracting a new canonical component for each group below.");
52
+ lines.push("");
53
+ for (const cluster of clusters) {
54
+ lines.push(`### ${cluster.name}`);
55
+ lines.push("");
56
+ lines.push(`All ${cluster.matches.length} components below matched canonical \`${cluster.canon.name}\` (\`${cluster.canon.path}\`). They are structurally similar to each other but distinct enough that none is a clean duplicate — a shared \`${cluster.name}\` would likely cover them.`);
57
+ lines.push("");
58
+ lines.push("| Local component | Location | Matched canonical | Confidence | Why |");
59
+ lines.push("| --- | --- | --- | --- | --- |");
60
+ for (const m of cluster.matches) {
61
+ lines.push(`| ${m.app.name} | \`${m.app.path}:${m.app.line}\` | ${m.canon.name} | ${m.decision.confidence.toFixed(2)} | ${m.decision.reason} |`);
62
+ }
63
+ lines.push("");
64
+ }
65
+ return lines;
66
+ };
67
+
68
+ const renderRawHtmlSection = (rows) => {
69
+ if (rows.length === 0) return [];
70
+ const lines = [];
71
+ lines.push(`## Raw HTML outside canonical packages (${rows.length})`);
72
+ lines.push("");
73
+ lines.push("| Element | Location | Replace with | From | Why |");
74
+ lines.push("| --- | --- | --- | --- | --- |");
75
+ const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path));
76
+ for (const r of sorted) {
77
+ lines.push(`| <${r.tag}> | \`${r.path}:${r.line}\` | \`${r.suggestion.component}\` | ${r.suggestion.path} | ${r.reason} |`);
78
+ }
79
+ lines.push("");
80
+ return lines;
81
+ };
82
+
83
+ const renderPartsSection = (rows, title = "Parts of components that duplicate a canonical") => {
84
+ if (rows.length === 0) return [];
85
+ const lines = [];
86
+ lines.push(`## ${title} (${rows.length})`);
87
+ lines.push("");
88
+ lines.push("| Part | Location | Replace with | From | Why |");
89
+ lines.push("| --- | --- | --- | --- | --- |");
90
+ const sorted = [...rows].sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
91
+ 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
+ }
94
+ lines.push("");
95
+ return lines;
96
+ };
97
+
98
+ const renderFilteredSection = (dropped) => {
99
+ const lines = [];
100
+ const byFilter = new Map();
101
+ for (const d of dropped) {
102
+ if (!byFilter.has(d.filter)) byFilter.set(d.filter, []);
103
+ byFilter.get(d.filter).push(d);
104
+ }
105
+ for (const [filter, rows] of byFilter) {
106
+ lines.push(`## Filtered out by \`${filter}\` (${rows.length})`);
107
+ lines.push("");
108
+ lines.push("| Local component | Location | Canonical | Why dropped |");
109
+ lines.push("| --- | --- | --- | --- |");
110
+ const sorted = [...rows].sort((a, b) => a.match.canon.name.localeCompare(b.match.canon.name));
111
+ for (const d of sorted) {
112
+ lines.push(`| ${d.match.app.name} | \`${d.match.app.path}:${d.match.app.line}\` | ${d.match.canon.name} | ${d.reason} |`);
113
+ }
114
+ lines.push("");
115
+ }
116
+ return lines;
117
+ };
118
+
119
+ const renderComponentReport = (comp, verbose) => {
120
+ const lines = [];
121
+ const folders = comp.layerFolders || [];
122
+ const inLayer = (p) => folders.some((d) => p.startsWith(d));
123
+ const appMatches = comp.matches.filter((m) => !inLayer(m.app.path));
124
+ const layerMatches = comp.matches.filter((m) => inLayer(m.app.path));
125
+ const appParts = (comp.parts || []).filter((r) => !inLayer(r.path));
126
+ const layerParts = (comp.parts || []).filter((r) => inLayer(r.path));
127
+ lines.push(...renderHeader(comp));
128
+ for (const tier of TIERS) {
129
+ const rows = appMatches.filter((m) => m.decision.tier === tier);
130
+ if (rows.length === 0) continue;
131
+ lines.push(...renderTierSection(tier, rows));
132
+ }
133
+ const missingClusters = (comp.missingClusters || []).filter((c) => c.matches.every((m) => !inLayer(m.app.path)));
134
+ lines.push(...renderMissingSection(missingClusters));
135
+ if (comp.rawHtml && comp.rawHtml.length > 0) lines.push(...renderRawHtmlSection(comp.rawHtml));
136
+ lines.push(...renderPartsSection(appParts));
137
+ const layerIdx = (p) => folders.findIndex((d) => p.startsWith(d));
138
+ const layerName = (d) => d.split("/").filter(Boolean).pop();
139
+ for (let li = 0; li < folders.length; li += 1) {
140
+ const seen = folders.slice(0, li).map(layerName);
141
+ const suffix = seen.length > 0 ? ` (vs ${seen.join(" + ")})` : "";
142
+ for (const tier of TIERS) {
143
+ const rows = layerMatches.filter((m) => layerIdx(m.app.path) === li && m.decision.tier === tier);
144
+ if (rows.length === 0) continue;
145
+ lines.push(...renderTierSection(tier, rows, `Inside ${layerName(folders[li])}: ${TIER_LABEL[tier]}${suffix}`));
146
+ }
147
+ }
148
+ lines.push(...renderPartsSection(layerParts, "Inside canonical layers: parts that duplicate a lower layer"));
149
+ if (verbose && comp.dropped && comp.dropped.length > 0) lines.push(...renderFilteredSection(comp.dropped));
150
+ return lines.join("\n");
151
+ };
152
+
153
+ module.exports = {
154
+ renderComponentReport,
155
+ duplicateText,
156
+ rawHtmlText,
157
+ TIERS,
158
+ TIER_LABEL,
159
+ };