@snap/valdi 1.0.11 → 1.1.7

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 (74) hide show
  1. package/.metadata/.bazelrc.template +7 -6
  2. package/.metadata/MODULE.bazel.template +154 -0
  3. package/bundled-skills/registry.json +13 -2
  4. package/bundled-skills/skills/valdi-animations/skill.md +197 -0
  5. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +1 -1
  6. package/bundled-skills/skills/valdi-compiler/skill.md +4 -4
  7. package/bundled-skills/skills/valdi-component-dedup/skill.md +263 -0
  8. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +1 -1
  9. package/bundled-skills/skills/valdi-custom-view/skill.md +43 -1
  10. package/bundled-skills/skills/valdi-error-handling/skill.md +238 -0
  11. package/bundled-skills/skills/valdi-gestures/skill.md +198 -0
  12. package/bundled-skills/skills/valdi-inspect/skill.md +19 -1
  13. package/bundled-skills/skills/valdi-localization/skill.md +142 -0
  14. package/bundled-skills/skills/valdi-mock-breakdown/skill.md +327 -0
  15. package/bundled-skills/skills/valdi-mock-iterate/skill.md +216 -0
  16. package/bundled-skills/skills/valdi-mock-to-module/scripts/diff.py +392 -0
  17. package/bundled-skills/skills/valdi-mock-to-module/scripts/extract_colors.py +277 -0
  18. package/bundled-skills/skills/valdi-mock-to-module/scripts/find_icon.py +303 -0
  19. package/bundled-skills/skills/valdi-mock-to-module/scripts/snapshot-and-diff.sh +53 -0
  20. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_diff.py +207 -0
  21. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_extract_colors.py +167 -0
  22. package/bundled-skills/skills/valdi-mock-to-module/scripts/test_find_icon.py +188 -0
  23. package/bundled-skills/skills/valdi-mock-to-module/scripts/watch-and-diff.sh +181 -0
  24. package/bundled-skills/skills/valdi-mock-to-module/skill.md +451 -0
  25. package/bundled-skills/skills/valdi-navigation/skill.md +187 -0
  26. package/bundled-skills/skills/valdi-overview/skill.md +7 -4
  27. package/bundled-skills/skills/valdi-perf/skill.md +223 -0
  28. package/bundled-skills/skills/valdi-polyglot-module/skill.md +80 -0
  29. package/bundled-skills/skills/valdi-preview/skill.md +303 -0
  30. package/bundled-skills/skills/valdi-setup/skill.md +55 -5
  31. package/bundled-skills/skills/valdi-testing/skill.md +23 -7
  32. package/bundled-skills/skills/valdi-tsx/skill.md +69 -5
  33. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +29 -5
  34. package/dist/commands/agentCheck.js +184 -0
  35. package/dist/commands/analyze.js +16 -0
  36. package/dist/commands/analyze_commands/duplicates.js +134 -0
  37. package/dist/commands/bootstrap.js +57 -73
  38. package/dist/commands/build.js +6 -0
  39. package/dist/commands/doctor.js +42 -266
  40. package/dist/commands/hotreload.js +15 -0
  41. package/dist/commands/inspect_commands/snapshot.js +71 -6
  42. package/dist/commands/inspect_commands/snapshot.spec.js +105 -0
  43. package/dist/commands/install.js +6 -0
  44. package/dist/commands/preview.js +81 -0
  45. package/dist/commands/projectsync.js +9 -7
  46. package/dist/commands/skills_commands/install.js +6 -1
  47. package/dist/commands/skills_commands/update.js +2 -1
  48. package/dist/core/analyze/clusterer.js +150 -0
  49. package/dist/core/analyze/fingerprint.js +2 -0
  50. package/dist/core/analyze/knownPatterns.js +76 -0
  51. package/dist/core/analyze/parser.js +177 -0
  52. package/dist/core/analyze/reporter.js +83 -0
  53. package/dist/core/analyze/scanner.js +172 -0
  54. package/dist/core/analyze/similarity.js +56 -0
  55. package/dist/core/constants.js +6 -3
  56. package/dist/core/packageFiles.spec.js +1 -1
  57. package/dist/preview/previewGenerator.js +240 -0
  58. package/dist/preview/previewGenerator.spec.js +203 -0
  59. package/dist/preview/viewModelParser.js +86 -0
  60. package/dist/preview/viewModelParser.spec.js +171 -0
  61. package/dist/setup/DevSetupHelper.js +0 -54
  62. package/dist/setup/linuxSetup.js +0 -16
  63. package/dist/setup/macOSSetup.js +1 -5
  64. package/dist/utils/BazelClient.js +15 -0
  65. package/dist/utils/applicationUtils.js +15 -0
  66. package/dist/utils/daemonClient.js +3 -1
  67. package/dist/utils/linuxDistro.js +0 -21
  68. package/dist/utils/linuxDistro.spec.js +0 -48
  69. package/dist/utils/skillsAdapters.js +126 -19
  70. package/dist/utils/skillsAdapters.spec.js +141 -0
  71. package/dist/utils/skillsRegistry.js +8 -0
  72. package/package.json +16 -8
  73. package/.metadata/WORKSPACE.template +0 -57
  74. package/dist/setup/versions.js +0 -8
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handler = exports.builder = exports.describe = exports.command = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs_1 = tslib_1.__importDefault(require("fs"));
6
+ const path_1 = tslib_1.__importDefault(require("path"));
7
+ const constants_1 = require("../core/constants");
8
+ const errors_1 = require("../core/errors");
9
+ const BazelClient_1 = require("../utils/BazelClient");
10
+ const errorUtils_1 = require("../utils/errorUtils");
11
+ const logUtils_1 = require("../utils/logUtils");
12
+ const previewGenerator_1 = require("../preview/previewGenerator");
13
+ const viewModelParser_1 = require("../preview/viewModelParser");
14
+ function resolveComponentFile(component, workspaceRoot) {
15
+ if (component.endsWith('.tsx') || component.endsWith('.ts')) {
16
+ const abs = path_1.default.resolve(component);
17
+ if (fs_1.default.existsSync(abs))
18
+ return abs;
19
+ throw new errors_1.CliError(`Component file not found: ${abs}`);
20
+ }
21
+ const candidates = [
22
+ path_1.default.join(workspaceRoot, 'valdi_modules', component + '.tsx'),
23
+ path_1.default.join(workspaceRoot, 'src/valdi_modules/src/valdi', component + '.tsx'),
24
+ ];
25
+ for (const candidate of candidates) {
26
+ if (fs_1.default.existsSync(candidate))
27
+ return candidate;
28
+ }
29
+ throw new errors_1.CliError(`Could not find component file for "${component}". Searched:\n` +
30
+ candidates.map(c => ` ${c}`).join('\n'));
31
+ }
32
+ function computeImportPath(filePath, moduleDir) {
33
+ const moduleName = path_1.default.basename(moduleDir);
34
+ const relFromModule = path_1.default.relative(moduleDir, filePath);
35
+ const withoutExt = relFromModule.replace(/\.tsx?$/, '');
36
+ return `${moduleName}/${withoutExt}`;
37
+ }
38
+ async function valdiPreview(argv) {
39
+ const bazel = new BazelClient_1.BazelClient();
40
+ const workspaceRoot = await bazel.getWorkspaceRoot();
41
+ const component = argv.getArgument('component');
42
+ console.log(`Resolving component: ${(0, logUtils_1.wrapInColor)(component, constants_1.ANSI_COLORS.GREEN_COLOR)}`);
43
+ const componentFile = resolveComponentFile(component, workspaceRoot);
44
+ const moduleDir = (0, previewGenerator_1.findModuleDir)(componentFile);
45
+ const moduleLabel = (0, previewGenerator_1.computeModuleLabel)(moduleDir, workspaceRoot);
46
+ const importPath = computeImportPath(componentFile, moduleDir);
47
+ console.log(`Module: ${(0, logUtils_1.wrapInColor)(moduleLabel, constants_1.ANSI_COLORS.BLUE_COLOR)}`);
48
+ console.log(`Import: ${(0, logUtils_1.wrapInColor)(importPath, constants_1.ANSI_COLORS.BLUE_COLOR)}`);
49
+ console.log('Parsing ViewModel...');
50
+ const viewModel = (0, viewModelParser_1.parseComponentFile)(componentFile);
51
+ const requiredProps = viewModel.props.filter(p => !p.optional);
52
+ console.log(`Found ${viewModel.props.length} props (${requiredProps.length} required) on ${(0, logUtils_1.wrapInColor)(viewModel.componentName, constants_1.ANSI_COLORS.GREEN_COLOR)}`);
53
+ const isValdi = (0, previewGenerator_1.isValdiWorkspace)(workspaceRoot);
54
+ (0, previewGenerator_1.generatePreviewFiles)({
55
+ componentFilePath: componentFile,
56
+ importPath,
57
+ moduleLabel,
58
+ workspaceRoot,
59
+ isValdiRepo: isValdi,
60
+ viewModel,
61
+ });
62
+ const previewDir = (0, previewGenerator_1.getPreviewDir)(workspaceRoot);
63
+ console.log(`Preview harness written to ${(0, logUtils_1.wrapInColor)(previewDir, constants_1.ANSI_COLORS.GRAY_COLOR)}`);
64
+ const target = '//apps/preview:preview_app_macos';
65
+ const buildFlags = constants_1.MACOS_BUILD_FLAGS.join(' ');
66
+ console.log(`\nBuilding and launching ${(0, logUtils_1.wrapInColor)(target, constants_1.ANSI_COLORS.GREEN_COLOR)}...`);
67
+ await bazel.runTarget(target, buildFlags);
68
+ }
69
+ exports.command = 'preview <component>';
70
+ exports.describe = 'Preview a Valdi component in a macOS window';
71
+ const builder = (yargs) => {
72
+ yargs.positional('component', {
73
+ describe: 'Component import path or file path\n' +
74
+ ' e.g. widgets/src/components/button/Checkbox\n' +
75
+ ' e.g. ./valdi_modules/widgets/src/components/button/Checkbox.tsx',
76
+ type: 'string',
77
+ demandOption: true,
78
+ });
79
+ };
80
+ exports.builder = builder;
81
+ exports.handler = (0, errorUtils_1.makeCommandHandler)(valdiPreview);
@@ -47,7 +47,7 @@ function isExternalLabel(workspaceInfo, label) {
47
47
  return !!label.repo && label.repo !== workspaceInfo.workspaceName;
48
48
  }
49
49
  function getSymlinkedBazelExecutionRoot(workspaceInfo) {
50
- return path_1.default.join(workspaceInfo.workspaceRoot, `bazel-${workspaceInfo.workspaceName}`);
50
+ return path_1.default.join(workspaceInfo.workspaceRoot, `bazel-${path_1.default.basename(workspaceInfo.workspaceRoot)}`);
51
51
  }
52
52
  function bazelLabelToAbsolutePath(workspaceInfo, label) {
53
53
  const targetPath = label.target.slice(2);
@@ -73,17 +73,19 @@ async function syncPathsByLabel(client, workspaceInfo, pathsByLabel, projectSync
73
73
  }
74
74
  pathsByLabel.set(projectSyncOutput.target.toString(), paths);
75
75
  }
76
- const missingTargets = new Set();
76
+ const missingLabels = new Map();
77
77
  for (const projectSyncOutput of projectSyncOutputs) {
78
78
  for (const dependency of projectSyncOutput.dependencies) {
79
- const target = dependency.toString();
80
- if (!pathsByLabel.has(target)) {
81
- missingTargets.add(target);
79
+ const key = dependency.toString();
80
+ if (!pathsByLabel.has(key)) {
81
+ missingLabels.set(key, dependency);
82
82
  }
83
83
  }
84
84
  }
85
- if (missingTargets.size > 0) {
86
- const targets = [...missingTargets.values()].sort().map(f => `${f}_projectsync`);
85
+ if (missingLabels.size > 0) {
86
+ const targets = [...missingLabels.values()]
87
+ .sort((a, b) => a.toString().localeCompare(b.toString()))
88
+ .map(label => `${label.toBuildableString()}_projectsync`);
87
89
  const newProjectSyncOutputs = await buildProjectSyncs(client, workspaceInfo.workspaceRoot, targets);
88
90
  await syncPathsByLabel(client, workspaceInfo, pathsByLabel, newProjectSyncOutputs);
89
91
  }
@@ -58,8 +58,9 @@ async function skillsInstall(argv) {
58
58
  const installSpinner = (0, ora_1.default)(`Installing ${skill.name}…`).start();
59
59
  try {
60
60
  const content = await (0, skillsRegistry_1.fetchSkillContent)(skill.path);
61
+ const resourceDir = (0, skillsRegistry_1.getSkillResourceDir)(skill.path) ?? undefined;
61
62
  for (const adapter of adapters) {
62
- adapter.install(skill.name, content, skill);
63
+ adapter.install(skill.name, content, skill, resourceDir);
63
64
  }
64
65
  installSpinner.succeed(`Installed ${(0, logUtils_1.wrapInColor)(skill.name, constants_1.ANSI_COLORS.GREEN_COLOR)}`);
65
66
  }
@@ -68,7 +69,11 @@ async function skillsInstall(argv) {
68
69
  installSpinner.fail(`Failed to install ${skill.name}: ${message}`);
69
70
  }
70
71
  }
72
+ const claudeInstalled = adapters.some((a) => a.name === 'claude');
71
73
  console.log(`\nDone. Run ${(0, logUtils_1.wrapInColor)('valdi skills list', constants_1.ANSI_COLORS.BLUE_COLOR)} to see installed skills.`);
74
+ if (claudeInstalled) {
75
+ console.log((0, logUtils_1.wrapInColor)('Restart Claude Code to activate the new skills.', constants_1.ANSI_COLORS.YELLOW_COLOR));
76
+ }
72
77
  if (!categoryFilter) {
73
78
  console.log(`Tip: install only module-development skills with ${(0, logUtils_1.wrapInColor)('valdi skills install --category=client', constants_1.ANSI_COLORS.BLUE_COLOR)}`);
74
79
  }
@@ -39,9 +39,10 @@ async function skillsUpdate(_argv) {
39
39
  const updateSpinner = (0, ora_1.default)(`Updating ${skill.name}…`).start();
40
40
  try {
41
41
  const content = await (0, skillsRegistry_1.fetchSkillContent)(skill.path);
42
+ const resourceDir = (0, skillsRegistry_1.getSkillResourceDir)(skill.path) ?? undefined;
42
43
  for (const adapter of adapters) {
43
44
  if (adapter.listInstalled().includes(skill.name)) {
44
- adapter.install(skill.name, content, skill);
45
+ adapter.install(skill.name, content, skill, resourceDir);
45
46
  }
46
47
  }
47
48
  updateSpinner.succeed(`Updated ${(0, logUtils_1.wrapInColor)(skill.name, constants_1.ANSI_COLORS.GREEN_COLOR)}`);
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clusterFingerprints = clusterFingerprints;
4
+ const scanner_1 = require("./scanner");
5
+ const similarity_1 = require("./similarity");
6
+ function clusterFingerprints(fingerprints, config, threshold) {
7
+ const nonSharedFingerprints = fingerprints.filter(fp => !(0, scanner_1.isSharedLibFile)(fp.filePath, config));
8
+ const buckets = bucketBySharedImports(nonSharedFingerprints);
9
+ const allPairs = [];
10
+ for (const bucket of buckets.values()) {
11
+ if (bucket.length < 2)
12
+ continue;
13
+ for (let i = 0; i < bucket.length; i++) {
14
+ for (let j = i + 1; j < bucket.length; j++) {
15
+ if (bucket[i].moduleName === bucket[j].moduleName)
16
+ continue;
17
+ const similarity = (0, similarity_1.computeSimilarity)(bucket[i], bucket[j]);
18
+ if (similarity >= threshold) {
19
+ allPairs.push({ a: bucket[i], b: bucket[j], similarity });
20
+ }
21
+ }
22
+ }
23
+ }
24
+ const clusters = singleLinkageMerge(allPairs, threshold);
25
+ return clusters
26
+ .filter(c => c.length >= 2)
27
+ .map((cluster, idx) => buildCluster(idx, cluster))
28
+ .sort((a, b) => b.files.length - a.files.length);
29
+ }
30
+ function bucketBySharedImports(fingerprints) {
31
+ const buckets = new Map();
32
+ for (const fp of fingerprints) {
33
+ const key = fp.sharedLibImports.length > 0 ? [...fp.sharedLibImports].sort().join('|') : '__no_shared_imports__';
34
+ let bucket = buckets.get(key);
35
+ if (!bucket) {
36
+ bucket = [];
37
+ buckets.set(key, bucket);
38
+ }
39
+ bucket.push(fp);
40
+ }
41
+ const noShared = buckets.get('__no_shared_imports__');
42
+ if (noShared && noShared.length > 0) {
43
+ const subBuckets = bucketByRenderSignature(noShared);
44
+ buckets.delete('__no_shared_imports__');
45
+ for (const [key, bucket] of subBuckets) {
46
+ buckets.set(`render:${key}`, bucket);
47
+ }
48
+ }
49
+ return buckets;
50
+ }
51
+ function bucketByRenderSignature(fingerprints) {
52
+ const buckets = new Map();
53
+ for (const fp of fingerprints) {
54
+ const nativeElements = fp.renderElements.filter(el => el === el.toLowerCase());
55
+ const key = nativeElements.length > 0 ? [...new Set(nativeElements)].sort().join('|') : '__misc__';
56
+ let bucket = buckets.get(key);
57
+ if (!bucket) {
58
+ bucket = [];
59
+ buckets.set(key, bucket);
60
+ }
61
+ bucket.push(fp);
62
+ }
63
+ return buckets;
64
+ }
65
+ function singleLinkageMerge(pairs, _threshold) {
66
+ const parent = new Map();
67
+ const nodes = new Map();
68
+ function find(x) {
69
+ let root = x;
70
+ while (parent.get(root) !== root)
71
+ root = parent.get(root);
72
+ let curr = x;
73
+ while (curr !== root) {
74
+ const next = parent.get(curr);
75
+ parent.set(curr, root);
76
+ curr = next;
77
+ }
78
+ return root;
79
+ }
80
+ function union(x, y) {
81
+ const rx = find(x);
82
+ const ry = find(y);
83
+ if (rx !== ry)
84
+ parent.set(rx, ry);
85
+ }
86
+ for (const { a, b } of pairs) {
87
+ if (!parent.has(a.filePath))
88
+ parent.set(a.filePath, a.filePath);
89
+ if (!parent.has(b.filePath))
90
+ parent.set(b.filePath, b.filePath);
91
+ nodes.set(a.filePath, a);
92
+ nodes.set(b.filePath, b);
93
+ union(a.filePath, b.filePath);
94
+ }
95
+ const clusters = new Map();
96
+ for (const [filePath, fp] of nodes) {
97
+ const root = find(filePath);
98
+ let cluster = clusters.get(root);
99
+ if (!cluster) {
100
+ cluster = [];
101
+ clusters.set(root, cluster);
102
+ }
103
+ cluster.push(fp);
104
+ }
105
+ return [...clusters.values()];
106
+ }
107
+ function buildCluster(id, members) {
108
+ let totalSim = 0;
109
+ let pairCount = 0;
110
+ for (let i = 0; i < members.length; i++) {
111
+ for (let j = i + 1; j < members.length; j++) {
112
+ totalSim += (0, similarity_1.computeSimilarity)(members[i], members[j]);
113
+ pairCount++;
114
+ }
115
+ }
116
+ const allVmProps = members.map(m => m.viewModelProps);
117
+ const sharedVmProps = intersectAll(allVmProps);
118
+ const allImports = members.map(m => m.importPaths);
119
+ const sharedImports = intersectAll(allImports);
120
+ const avgSimilarity = pairCount > 0 ? totalSim / pairCount : 0;
121
+ return {
122
+ id,
123
+ avgSimilarity: Math.round(avgSimilarity * 1000) / 1000,
124
+ files: members.map(m => ({ path: m.filePath, module: m.moduleName, className: m.className })),
125
+ sharedViewModelProps: sharedVmProps,
126
+ sharedImports,
127
+ suggestedExtraction: suggestExtraction(members, sharedVmProps, sharedImports),
128
+ };
129
+ }
130
+ function intersectAll(arrays) {
131
+ if (arrays.length === 0)
132
+ return [];
133
+ let result = new Set(arrays[0]);
134
+ for (let i = 1; i < arrays.length; i++) {
135
+ const current = new Set(arrays[i]);
136
+ result = new Set([...result].filter(x => current.has(x)));
137
+ }
138
+ return [...result];
139
+ }
140
+ function suggestExtraction(members, sharedProps, sharedImports) {
141
+ const allStateful = members.every(m => m.flags.isStateful);
142
+ const allLoading = members.every(m => m.flags.hasLoadingState);
143
+ if (allLoading)
144
+ return 'Extract async state container with loading/error/content rendering';
145
+ if (allStateful && sharedProps.length >= 3)
146
+ return `Extract stateful component with shared props: ${sharedProps.slice(0, 5).join(', ')}`;
147
+ if (sharedImports.length >= 2)
148
+ return `Extract shared component reusing: ${sharedImports.slice(0, 3).join(', ')}`;
149
+ return `Extract shared pattern across ${members.length} modules`;
150
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.detectKnownPatterns = detectKnownPatterns;
4
+ const scanner_1 = require("./scanner");
5
+ const DETECTORS = {
6
+ async: detectAsyncStatePattern,
7
+ button: detectButtonWrapperPattern,
8
+ shimmer: detectShimmerPattern,
9
+ };
10
+ function detectKnownPatterns(fingerprints, config, patternFilter) {
11
+ const nonShared = fingerprints.filter(fp => !(0, scanner_1.isSharedLibFile)(fp.filePath, config));
12
+ const results = [];
13
+ const detectorsToRun = patternFilter ? { [patternFilter]: DETECTORS[patternFilter] } : DETECTORS;
14
+ for (const [name, detector] of Object.entries(detectorsToRun)) {
15
+ if (!detector)
16
+ continue;
17
+ const match = detector(nonShared, config);
18
+ if (match)
19
+ results.push(match);
20
+ }
21
+ return results.sort((a, b) => severityRank(a.severity) - severityRank(b.severity));
22
+ }
23
+ function severityRank(s) {
24
+ return s === 'HIGH' ? 0 : s === 'MEDIUM' ? 1 : 2;
25
+ }
26
+ function detectAsyncStatePattern(fingerprints, _config) {
27
+ const loadingOnly = fingerprints.filter(fp => fp.flags.hasLoadingState);
28
+ const existingImpls = fingerprints.filter(fp => fp.className.includes('AsyncContentContainer') || fp.className.includes('AsyncStateContainer'));
29
+ if (loadingOnly.length < 3)
30
+ return undefined;
31
+ return {
32
+ patternName: 'Async State Container',
33
+ severity: loadingOnly.length >= 50 ? 'HIGH' : loadingOnly.length >= 15 ? 'MEDIUM' : 'LOW',
34
+ matchCount: loadingOnly.length,
35
+ files: loadingOnly.map(fp => fp.filePath),
36
+ existingImplementations: existingImpls.map(fp => fp.filePath),
37
+ recommendation: `${loadingOnly.length} components implement loading/error/content state machines. ` +
38
+ (existingImpls.length > 0
39
+ ? `${existingImpls.length} shared implementation(s) already exist — consolidate into one and migrate consumers.`
40
+ : `Extract a generic AsyncStateContainer to the shared component library.`),
41
+ };
42
+ }
43
+ function detectButtonWrapperPattern(fingerprints, _config) {
44
+ const buttonComponentNames = ['CoreButton', 'PillButton'];
45
+ const matches = fingerprints.filter(fp => {
46
+ const importsButton = fp.sharedLibImports.some(imp => buttonComponentNames.some(name => imp.includes(name))) ||
47
+ fp.importPaths.some(imp => buttonComponentNames.some(name => imp.includes(name)));
48
+ const isWrapper = fp.renderElements.length <= 5 && fp.className.toLowerCase().includes('button');
49
+ return importsButton && isWrapper;
50
+ });
51
+ if (matches.length < 5)
52
+ return undefined;
53
+ return {
54
+ patternName: 'Button Wrapper',
55
+ severity: matches.length >= 30 ? 'HIGH' : matches.length >= 10 ? 'MEDIUM' : 'LOW',
56
+ matchCount: matches.length,
57
+ files: matches.map(fp => fp.filePath),
58
+ existingImplementations: [],
59
+ recommendation: `${matches.length} thin button wrapper components found. Add preset enums to the shared button component instead of per-module wrappers.`,
60
+ };
61
+ }
62
+ function detectShimmerPattern(fingerprints, _config) {
63
+ const matches = fingerprints.filter(fp => fp.flags.usesAnimationShimmer ||
64
+ fp.className.toLowerCase().includes('shimmer') ||
65
+ fp.className.toLowerCase().includes('skeleton'));
66
+ if (matches.length < 3)
67
+ return undefined;
68
+ return {
69
+ patternName: 'Shimmer / Skeleton Layout',
70
+ severity: matches.length >= 20 ? 'HIGH' : matches.length >= 8 ? 'MEDIUM' : 'LOW',
71
+ matchCount: matches.length,
72
+ files: matches.map(fp => fp.filePath),
73
+ existingImplementations: [],
74
+ recommendation: `${matches.length} shimmer/skeleton components found. Extract a configurable ShimmerLayout to the shared component library.`,
75
+ };
76
+ }
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseFile = parseFile;
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
6
+ const ts = tslib_1.__importStar(require("typescript"));
7
+ const scanner_1 = require("./scanner");
8
+ function parseFile(filePath, config) {
9
+ let content;
10
+ try {
11
+ content = fs.readFileSync(filePath, 'utf8');
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);
17
+ const imports = extractImports(sourceFile);
18
+ const sharedLibImports = imports.filter(imp => isSharedLibImport(imp, config));
19
+ const className = findComponentClassName(sourceFile);
20
+ if (!className)
21
+ return undefined;
22
+ const viewModelProps = extractViewModelProps(sourceFile);
23
+ const stateProps = extractStateProps(sourceFile);
24
+ const renderElements = extractRenderElements(sourceFile);
25
+ const flags = detectFlags(sourceFile, content, imports);
26
+ return {
27
+ filePath,
28
+ moduleName: (0, scanner_1.extractModuleName)(filePath, config) ?? 'unknown',
29
+ className,
30
+ viewModelProps,
31
+ stateProps,
32
+ importPaths: imports,
33
+ sharedLibImports,
34
+ renderElements,
35
+ flags,
36
+ };
37
+ }
38
+ function extractImports(sourceFile) {
39
+ const imports = [];
40
+ for (const statement of sourceFile.statements) {
41
+ if (ts.isImportDeclaration(statement) &&
42
+ statement.moduleSpecifier &&
43
+ ts.isStringLiteral(statement.moduleSpecifier)) {
44
+ imports.push(statement.moduleSpecifier.text);
45
+ }
46
+ }
47
+ return imports;
48
+ }
49
+ function isSharedLibImport(importPath, config) {
50
+ return config.sharedLibNames.some(name => importPath.startsWith(`${name}/`) || importPath === name);
51
+ }
52
+ function findComponentClassName(sourceFile) {
53
+ for (const statement of sourceFile.statements) {
54
+ if (!ts.isClassDeclaration(statement) || !statement.name)
55
+ continue;
56
+ if (statement.heritageClauses) {
57
+ for (const clause of statement.heritageClauses) {
58
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword)
59
+ continue;
60
+ for (const type of clause.types) {
61
+ const text = type.expression.getText(sourceFile);
62
+ if (text === 'Component' || text === 'StatefulComponent') {
63
+ return statement.name.text;
64
+ }
65
+ }
66
+ }
67
+ }
68
+ }
69
+ return undefined;
70
+ }
71
+ function extractViewModelProps(sourceFile) {
72
+ const props = [];
73
+ for (const statement of sourceFile.statements) {
74
+ if (!ts.isInterfaceDeclaration(statement))
75
+ continue;
76
+ const name = statement.name.text;
77
+ if (!name.endsWith('ViewModel') && !name.endsWith('VM') && !name.endsWith('Props'))
78
+ continue;
79
+ for (const member of statement.members) {
80
+ if (ts.isPropertySignature(member) && member.name && ts.isIdentifier(member.name)) {
81
+ props.push(member.name.text);
82
+ }
83
+ }
84
+ if (props.length > 0)
85
+ break;
86
+ }
87
+ return props;
88
+ }
89
+ function extractStateProps(sourceFile) {
90
+ const props = [];
91
+ for (const statement of sourceFile.statements) {
92
+ if (!ts.isInterfaceDeclaration(statement))
93
+ continue;
94
+ const name = statement.name.text;
95
+ if (!name.endsWith('State') && !name.includes('State'))
96
+ continue;
97
+ if (name.endsWith('ViewModel') || name.endsWith('VM'))
98
+ continue;
99
+ for (const member of statement.members) {
100
+ if (ts.isPropertySignature(member) && member.name && ts.isIdentifier(member.name)) {
101
+ props.push(member.name.text);
102
+ }
103
+ }
104
+ if (props.length > 0)
105
+ break;
106
+ }
107
+ return props;
108
+ }
109
+ function extractRenderElements(sourceFile) {
110
+ const elements = [];
111
+ function visit(node) {
112
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
113
+ const tagName = node.tagName.getText(sourceFile);
114
+ elements.push(tagName);
115
+ }
116
+ ts.forEachChild(node, visit);
117
+ }
118
+ const onRender = findMethod(sourceFile, 'onRender');
119
+ if (onRender) {
120
+ ts.forEachChild(onRender, visit);
121
+ }
122
+ return elements;
123
+ }
124
+ function findMethod(sourceFile, methodName) {
125
+ for (const statement of sourceFile.statements) {
126
+ if (!ts.isClassDeclaration(statement))
127
+ continue;
128
+ for (const member of statement.members) {
129
+ if (ts.isMethodDeclaration(member) &&
130
+ member.name &&
131
+ ts.isIdentifier(member.name) &&
132
+ member.name.text === methodName) {
133
+ return member.body;
134
+ }
135
+ }
136
+ }
137
+ return undefined;
138
+ }
139
+ function detectFlags(sourceFile, content, imports) {
140
+ const hasLoadingKeywords = /\bloading\b/i.test(content) &&
141
+ (/\bshimmer\b/i.test(content) ||
142
+ /\bspinner\b/i.test(content) ||
143
+ /isLoading\b/.test(content) ||
144
+ /\bLoadingState\b/.test(content));
145
+ const hasErrorKeywords = /\berror\b/i.test(content) &&
146
+ (/\bretry\b/i.test(content) || /\berrorState\b/.test(content) || /\bshowError\b/i.test(content));
147
+ const hasLoadingEnum = /loading|loaded|error|empty/i.test(content) && /enum\s+\w*[Ss]tate/i.test(content);
148
+ const usesPromise = imports.some(imp => imp.includes('CancelablePromise')) || /\bCancelablePromise\b/.test(content);
149
+ const usesObservable = imports.some(imp => imp.includes('Observable') || imp.includes('observable')) || /\bObservable\b/.test(content);
150
+ const usesAnimationShimmer = imports.some(imp => imp.includes('AnimationShimmer')) || /\bAnimationShimmer\b/.test(content);
151
+ let isStateful = false;
152
+ let extendsComponent = false;
153
+ for (const statement of sourceFile.statements) {
154
+ if (!ts.isClassDeclaration(statement) || !statement.heritageClauses)
155
+ continue;
156
+ for (const clause of statement.heritageClauses) {
157
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword)
158
+ continue;
159
+ for (const type of clause.types) {
160
+ const text = type.expression.getText(sourceFile);
161
+ if (text === 'StatefulComponent')
162
+ isStateful = true;
163
+ if (text === 'Component' || text === 'StatefulComponent')
164
+ extendsComponent = true;
165
+ }
166
+ }
167
+ }
168
+ return {
169
+ hasLoadingState: hasLoadingKeywords || hasLoadingEnum,
170
+ hasErrorState: hasErrorKeywords,
171
+ usesPromise,
172
+ usesObservable,
173
+ usesAnimationShimmer,
174
+ isStateful,
175
+ extendsComponent,
176
+ };
177
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.printHumanReport = printHumanReport;
4
+ exports.formatJsonReport = formatJsonReport;
5
+ const constants_1 = require("../constants");
6
+ const logUtils_1 = require("../../utils/logUtils");
7
+ function printHumanReport(report, verbose) {
8
+ console.log((0, logUtils_1.wrapInColor)('Valdi Component Duplication Report', constants_1.ANSI_COLORS.BLUE_COLOR));
9
+ console.log('='.repeat(50));
10
+ console.log();
11
+ const { scanStats } = report;
12
+ console.log(`Scanned ${(0, logUtils_1.wrapInColor)(String(scanStats.filesScanned), constants_1.ANSI_COLORS.GREEN_COLOR)} files across ${(0, logUtils_1.wrapInColor)(String(scanStats.modulesScanned), constants_1.ANSI_COLORS.GREEN_COLOR)} modules in ${scanStats.durationMs}ms`);
13
+ console.log(`Scan roots: ${report.config.scanRoots.join(', ')}`);
14
+ console.log(`Shared libraries: ${report.config.sharedLibNames.join(', ') || '(none configured)'}`);
15
+ console.log();
16
+ if (report.knownPatterns.length > 0) {
17
+ console.log((0, logUtils_1.wrapInColor)('Known Patterns', constants_1.ANSI_COLORS.BLUE_COLOR));
18
+ console.log('-'.repeat(30));
19
+ for (const pattern of report.knownPatterns) {
20
+ printKnownPattern(pattern, verbose);
21
+ }
22
+ console.log();
23
+ }
24
+ if (report.genericClusters.length > 0) {
25
+ console.log((0, logUtils_1.wrapInColor)('Similar Component Clusters', constants_1.ANSI_COLORS.BLUE_COLOR));
26
+ console.log('-'.repeat(30));
27
+ const clustersToShow = verbose ? report.genericClusters : report.genericClusters.slice(0, 10);
28
+ for (const cluster of clustersToShow) {
29
+ printCluster(cluster, verbose);
30
+ }
31
+ if (!verbose && report.genericClusters.length > 10) {
32
+ console.log((0, logUtils_1.wrapInColor)(` ... and ${report.genericClusters.length - 10} more clusters (use --verbose to see all)`, constants_1.ANSI_COLORS.GRAY_COLOR));
33
+ }
34
+ console.log();
35
+ }
36
+ console.log('='.repeat(50));
37
+ console.log((0, logUtils_1.wrapInColor)('Summary', constants_1.ANSI_COLORS.BLUE_COLOR));
38
+ console.log(` Known pattern matches: ${report.summary.totalKnownPatternMatches}`);
39
+ console.log(` Similar clusters: ${report.summary.totalClusters}`);
40
+ console.log(` Total duplicated files: ${report.summary.totalDuplicatedFiles}`);
41
+ }
42
+ function printKnownPattern(pattern, verbose) {
43
+ const severityColor = pattern.severity === 'HIGH'
44
+ ? constants_1.ANSI_COLORS.RED_COLOR
45
+ : pattern.severity === 'MEDIUM'
46
+ ? constants_1.ANSI_COLORS.YELLOW_COLOR
47
+ : constants_1.ANSI_COLORS.GRAY_COLOR;
48
+ console.log(` ${(0, logUtils_1.wrapInColor)(`[${pattern.severity}]`, severityColor)} ${pattern.patternName} — ${pattern.matchCount} matches`);
49
+ console.log(` ${pattern.recommendation}`);
50
+ if (pattern.existingImplementations.length > 0) {
51
+ console.log(` Existing implementations:`);
52
+ for (const impl of pattern.existingImplementations) {
53
+ console.log(` ${(0, logUtils_1.wrapInColor)('→', constants_1.ANSI_COLORS.GREEN_COLOR)} ${impl}`);
54
+ }
55
+ }
56
+ if (verbose) {
57
+ const filesToShow = pattern.files.slice(0, 20);
58
+ for (const file of filesToShow) {
59
+ console.log(` ${(0, logUtils_1.wrapInColor)('·', constants_1.ANSI_COLORS.GRAY_COLOR)} ${file}`);
60
+ }
61
+ if (pattern.files.length > 20) {
62
+ console.log((0, logUtils_1.wrapInColor)(` ... and ${pattern.files.length - 20} more`, constants_1.ANSI_COLORS.GRAY_COLOR));
63
+ }
64
+ }
65
+ console.log();
66
+ }
67
+ function printCluster(cluster, verbose) {
68
+ console.log(` Cluster #${cluster.id} (${cluster.files.length} files, avg similarity: ${(cluster.avgSimilarity * 100).toFixed(0)}%)`);
69
+ console.log(` ${cluster.suggestedExtraction}`);
70
+ if (cluster.sharedViewModelProps.length > 0) {
71
+ console.log(` Shared ViewModel props: ${cluster.sharedViewModelProps.join(', ')}`);
72
+ }
73
+ for (const file of cluster.files) {
74
+ console.log(` ${(0, logUtils_1.wrapInColor)('·', constants_1.ANSI_COLORS.GRAY_COLOR)} ${file.module}/${file.className} — ${file.path}`);
75
+ }
76
+ if (verbose && cluster.sharedImports.length > 0) {
77
+ console.log(` Shared imports: ${cluster.sharedImports.slice(0, 5).join(', ')}`);
78
+ }
79
+ console.log();
80
+ }
81
+ function formatJsonReport(report) {
82
+ return JSON.stringify(report, null, 2);
83
+ }