# Usage:
# 1. Save the extractor code as `extractor.js`
# 2. cd to your monorepo root (must be Yarn workspaces)
# 3. node ../extractor.js . > graph.json
# (Pass '.' for current dir, or full path)
# 4. Save viz.html, put graph.json next to it
# 5. Open viz.html in browser
#
# Features:
# - Graph extraction: Internal dep graph from yarn workspaces deps/dev/peer/optional
# - Impact surfacing: Click a node -> highlights all impacted packages (transitive dependents)
# - Freshness SLAs: Worst-case days-since-last-publish across direct external deps.
# Green: <30d, Orange: 30-90d, Red: >90d (edit style mapper in HTML for custom SLAs)
# Fetches npm registry for each unique external dep (sequential to avoid rate limits)
#
# Notes:
# - Only internal packages as nodes (external deps contribute to freshness score)
# - Assumes Node.js 14+ (top-level await)
# - Zero runtime deps
# - Handles scoped pkgs (@org/pkg)
# - Anon pkgs (no name) get fallback ID
# - Failed fetches = 999 days (red)
# - Large monorepos: extractor may take 1-5min for 500+ externals
extractor.js
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const https = require('https');
(async () => {
const root = process.argv[2];
if (!root) {
console.error('Usage: node extractor.js <monorepo-root>');
process.exit(1);
}
const yarnOut = spawnSync('yarn', ['workspaces', 'list', '--json'], {
cwd: root,
encoding: 'utf8',
});
if (yarnOut.status !== 0) {
console.error('Error: Run from Yarn workspaces monorepo root. Install yarn if needed.');
process.exit(1);
}
const workspaceList = JSON.parse(yarnOut.stdout);
// Collect all packages and parse package.json once
const packages = [];
const internalNames = new Set();
for (const ws of workspaceList) {
const dir = path.join(root, ws.location);
const pkgPath = path.join(dir, 'package.json');
if (!fs.existsSync(pkgPath)) continue;
let content;
try {
content = fs.readFileSync(pkgPath, 'utf8');
} catch (e) {
continue;
}
let pkg;
try {
pkg = JSON.parse(content);
} catch (e) {
continue;
}
const name = pkg.name || `anon-${path.basename(dir)}`;
packages.push({ name, dir, pkg });
internalNames.add(name);
}
if (packages.length === 0) {
console.error('No packages found.');
process.exit(1);
}
// Build edges and per-pkg externalDeps
const pkgMap = {};
const edgeSet = new Set();
packages.forEach(({ name, dir, pkg }) => {
const allDeps = {
... (pkg.dependencies || {}),
... (pkg.devDependencies || {}),
... (pkg.peerDependencies || {}),
... (pkg.optionalDependencies || {}),
};
const externalDeps = [];
for (const [depName] of Object.entries(allDeps)) {
if (internalNames.has(depName)) {
edgeSet.add(`${name}-${depName}`);
} else {
externalDeps.push(depName);
}
}
const label = name.split('/').pop() || (name.startsWith('@') ? name.split('/').pop() : name);
pkgMap[name] = {
id: name,
label,
path: dir,
externalDeps,
};
});
// Collect unique externals
const allExternals = new Set();
Object.values(pkgMap).forEach(p => {
p.externalDeps.forEach(d => allExternals.add(d));
});
// Fetch freshness for unique externals
const externalFreshness = {};
const fetchFreshness = (depName) => new Promise((resolve) => {
const url = `https://registry.npmjs.org/${depName}`;
https.get(url, (res) => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
try {
const json = JSON.parse(data);
const latest = json['dist-tags']?.latest;
const time = json.time;
if (latest && time?.[latest]) {
const pubDate = new Date(time[latest]);
const daysAgo = Math.round((Date.now() - pubDate.getTime()) / 86400000);
externalFreshness[depName] = daysAgo;
resolve();
return;
}
} catch (e) {
// ignore
}
externalFreshness[depName] = 999;
resolve();
});
}).on('error', () => {
externalFreshness[depName] = 999;
resolve();
});
});
console.error(`Fetching freshness for ${allExternals.size} unique external deps...`);
for (const dep of Array.from(allExternals)) {
await fetchFreshness(dep);
// Optional: console.error(`Fetched ${dep}`);
}
// Compute scores
Object.values(pkgMap).forEach(p => {
const daysAgoList = p.externalDeps.map(d => externalFreshness[d] ?? 999);
const score = daysAgoList.length ? Math.max(...daysAgoList) : 0;
p.freshnessScore = score;
});
// Build graph
const nodes = Object.values(pkgMap).map(p => ({
data: {
id: p.id,
label: p.label,
path: p.path,
freshnessScore: p.freshnessScore,
},
}));
const edges = Array.from(edgeSet).map(e => {
const [source, target] = e.split('-');
return {
data: { source, target },
};
});
const graph = { nodes, edges };
console.log(JSON.stringify(graph, null, 2));
})();
viz.html
<!DOCTYPE html>
<html>
<head>
<title>Monorepo Dependency Visualizer</title>
<script src="https://unpkg.com/cytoscape@3.26.0/dist/cytoscape.min.js"></script>
<style>
body { margin: 0; font-family: Arial, sans-serif; }
#toolbar { position: absolute; top: 10px; left: 10px; z-index: 100; background: white; padding: 10px; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
#cy { width: 100vw; height: 100vh; }
#info { position: absolute; top: 10px; right: 10px; z-index: 100; background: white; padding: 15px; border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); max-width: 300px; max-height: 80vh; overflow: auto; display: none; }
input { padding: 5px; margin-right: 10px; }
button { padding: 5px 10px; cursor: pointer; }
.highlight { border-width: 5px !important; border-color: blue !important; border-opacity: 1 !important; }
.impacted { background-color: yellow !important; background-opacity: 0.8 !important; }
.hidden { display: none !important; }
</style>
</head>
<body>
<div id="toolbar">
<input id="search" placeholder="Search packages..." />
<button id="clearSearch">Clear</button>
<button id="resetLayout">Reset Layout</button>
<br><small>Click node: select & show impact<br>Legend: <span style="color:green">🟢 <30d</span> <span style="color:orange">🟠 30-90d</span> <span style="color:red">🔴 >90d</span> (max dep age)</small>
</div>
<div id="info"></div>
<div id="cy"></div>
<script>
let cy;
let revAdj = {};
let selectedNodeId = null;
// Load graph
fetch('graph.json')
.then(r => r.json())
.then(graph => {
cy = cytoscape({
container: document.getElementById('cy'),
elements: [...graph.nodes, ...graph.edges],
style: [
{
selector: 'node',
style: {
'background-color': 'data(freshnessScore)',
width: 40,
height: 40,
'text-valign': 'center',
'text-halign': 'center',
label: 'data(label)',
'font-size': 12,
'background-color': function(ele) {
const score = ele.data('freshnessScore');
if (score === 0) return '#90EE90'; // lightgreen, no deps
if (score < 30) return '#32CD32'; // green
if (score < 90) return '#FFA500'; // orange
return '#FF4500'; // red/orangered
},
'border-width': 1,
'border-color': '#666',
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle',
width: 2,
'line-color': '#999',
'target-arrow-color': '#999',
}
},
{ selector: '.highlight', style: { 'border-width': 6, 'border-color': '#0000FF', 'border-opacity': 1 } },
{ selector: '.impacted', style: { 'background-color': '#FFFF99', 'background-opacity': 0.7 } },
{ selector: '.hidden', style: { display: 'none' } },
],
layout: { name: 'cose', animate: true, animationDuration: 1000, idealEdgeLength: 120 },
});
// Build reverse adj for impact
revAdj = {};
cy.edges().forEach(edge => {
const tgt = edge.target().id();
const src = edge.source().id();
if (!revAdj[tgt]) revAdj[tgt] = [];
revAdj[tgt].push(src);
});
// Events
cy.on('click', 'node', evt => {
const ele = evt.target;
cy.nodes().removeClass('highlight impacted');
const impactedIds = getImpacted(ele.id());
cy.nodes().filter(n => impactedIds.has(n.id())).addClass('impacted');
ele.addClass('highlight');
selectedNodeId = ele.id();
updateInfo(ele);
});
cy.on('mouseover', 'node', evt => {
evt.target.addClass('highlight');
});
cy.on('mouseout', 'node', evt => {
if (evt.target.id() !== selectedNodeId) evt.target.removeClass('highlight');
});
});
function getImpacted(startId) {
const visited = new Set();
const queue = [startId];
while (queue.length) {
const cur = queue.pop();
if (visited.has(cur)) continue;
visited.add(cur);
const neighbors = revAdj[cur] || [];
neighbors.forEach(nei => queue.push(nei));
}
return visited;
}
function updateInfo(ele) {
const impactedCount = getImpacted(ele.id()).size;
const score = ele.data('freshnessScore');
document.getElementById('info').innerHTML = `
<h3>${ele.data('label')}</h3>
<p><strong>ID:</strong> ${ele.id()}</p>
<p><strong>Path:</strong> ${ele.data('path')}</p>
<p><strong>Freshness:</strong> ${score} days (worst external dep)</p>
<p><strong>Impact:</strong> ${impactedCount} packages (transitive dependents)</p>
<p><strong>Direct deps:</strong> ${cy.getElementById(ele.id()).outdegree()} (internal)</p>
`;
document.getElementById('info').style.display = 'block';
}
// Toolbar
document.getElementById('search').addEventListener('input', evt => {
const val = evt.target.value.toLowerCase();
cy.nodes().removeClass('hidden');
if (val) {
cy.nodes().filter(node => !node.data('label').toLowerCase().includes(val)).addClass('hidden');
}
cy.elements().edges().connectedEdges().show(); // Show connected edges
cy.resize().fit();
});
document.getElementById('clearSearch').onclick = () => {
document.getElementById('search').value = '';
cy.nodes().removeClass('hidden');
cy.resize().fit();
};
document.getElementById('resetLayout').onclick = () => {
cy.nodes().removeClass('hidden');
cy.layout({ name: 'cose', animate: true, animationDuration: 1500 }).run();
};
// Hide info on esc
document.addEventListener('keydown', evt => {
if (evt.key === 'Escape') {
cy.nodes().removeClass('highlight impacted');
document.getElementById('info').style.display = 'none';
selectedNodeId = null;
}
});
window.onresize = () => cy && cy.resize();
</script>
</body>
</html>
This is a fully functional, zero-dep (runtime) monorepo visualizer. Test on a real monorepo like Create React App or Babel (they use Yarn workspaces). Customize SLAs by editing the background-color mapper in style (e.g., change thresholds). For non-Yarn, adapt the extractor to parse workspaces globs manually. Enjoy debugging your monorepo! 🔍