Repository navigation
Expand file tree
/
Copy pathserver.mjs
More file actions
294 lines (243 loc) Β· 8.16 KB
/
Copy pathserver.mjs
File metadata and controls
294 lines (243 loc) Β· 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/**
* node_modules Graph Analyzer - WebSocket Server
* Parses pnpm-lock.yaml and runs RLLM queries
*/
import 'dotenv/config';
import { WebSocketServer } from 'ws';
import { readWantedLockfile } from '@pnpm/lockfile-file';
import { resolve } from 'path';
import { createRLLM } from 'rllm';
import { z } from 'zod';
// Define Zod schema for the dependency context
const PackageSchema = z.object({
id: z.string().describe('Package identifier in format "name@version"'),
name: z.string().describe('Package name'),
version: z.string().describe('Semver version'),
val: z.number().describe('Node size for visualization'),
color: z.string().describe('Node color for visualization'),
});
const DependencySchema = z.object({
from: z.string().describe('Source package id'),
to: z.string().describe('Target package id (dependency)'),
});
const StatsSchema = z.object({
totalPackages: z.number().describe('Total number of packages'),
totalLinks: z.number().describe('Total number of dependency links'),
directDeps: z.number().describe('Number of direct dependencies'),
});
const ContextSchema = z.object({
packages: z.record(z.string(), PackageSchema).describe('Map of package id to package info'),
dependencies: z.array(DependencySchema).describe('List of dependency relationships'),
stats: StatsSchema.describe('Summary statistics'),
});
const PORT = 4242;
const TARGET = resolve(process.cwd(), '../../');
console.log('π node_modules Graph Analyzer');
console.log(`Target: ${TARGET}\n`);
// Check for API key based on provider
const provider = process.env.PROVIDER || 'gemini';
const apiKeyName = {
gemini: 'GEMINI_API_KEY or GOOGLE_API_KEY',
openai: 'OPENAI_API_KEY',
anthropic: 'ANTHROPIC_API_KEY',
openrouter: 'OPENROUTER_API_KEY',
cerebras: 'CEREBRAS_API_KEY',
}[provider] || 'API key';
const hasApiKey = provider === 'gemini'
? (process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY)
: process.env[`${provider.toUpperCase()}_API_KEY`];
if (!hasApiKey) {
console.warn(`β οΈ ${apiKeyName} not set - queries will not work`);
}
// Initialize RLLM
const rlm = createRLLM({
model: process.env.MODEL || 'gemini-3-flash-preview',
provider: process.env.PROVIDER || 'gemini',
verbose: true,
});
// Parse pnpm lockfile
console.log('π¦ Parsing pnpm-lock.yaml...');
const lockfile = await readWantedLockfile(TARGET, { ignoreIncompatible: true });
if (!lockfile) {
console.error('β No pnpm-lock.yaml found');
process.exit(1);
}
// Build graph from lockfile
const nodes = new Map();
const links = [];
// Get root dependencies from importers
const rootImporter = lockfile.importers?.['.'];
const rootDeps = {
...(rootImporter?.dependencies || {}),
...(rootImporter?.devDependencies || {})
};
// Add root node
nodes.set('root', {
id: 'root',
name: 'root',
version: '',
val: 20,
color: '#ff6b6b'
});
// Process all packages from lockfile
const packages = lockfile.packages || {};
for (const [pkgPath, pkgInfo] of Object.entries(packages)) {
const match = pkgPath.match(/^\/?(.+)@([^@]+)$/);
if (!match) continue;
const [, name, version] = match;
const id = `${name}@${version}`;
if (nodes.has(id)) continue;
const isDirect = Object.values(rootDeps).some(dep => {
const depVersion = dep.version || dep;
return depVersion.includes(version) || depVersion === version;
});
nodes.set(id, {
id,
name,
version,
val: isDirect ? 10 : 5,
color: isDirect ? '#4ecdc4' : '#6c9bcf'
});
// Add edges for dependencies
const deps = pkgInfo.dependencies || {};
for (const [depName, depVersion] of Object.entries(deps)) {
const depId = `${depName}@${depVersion}`;
links.push({ source: id, target: depId });
}
}
// Add links from root to direct dependencies
for (const [depName, depInfo] of Object.entries(rootDeps)) {
const depVersion = depInfo.version || depInfo;
const cleanVersion = depVersion.replace(/\(.*\)/, '');
const depId = `${depName}@${cleanVersion}`;
if (nodes.has(depId)) {
links.push({ source: 'root', target: depId });
}
}
// Filter links to only include existing nodes
const validLinks = links.filter(link =>
nodes.has(link.source) && nodes.has(link.target)
);
const graphData = {
nodes: Array.from(nodes.values()),
links: validLinks
};
const stats = {
totalPackages: nodes.size,
totalLinks: validLinks.length,
directDeps: Object.keys(rootDeps).length
};
// Build context object for RLLM
const rawContext = {
packages: Object.fromEntries(nodes),
dependencies: validLinks.map(l => ({ from: l.source, to: l.target })),
stats
};
// Create tracked context with Proxy to emit access events
function createTrackedContext(target, onAccess, path = []) {
if (target === null || typeof target !== 'object') {
return target;
}
return new Proxy(target, {
get(obj, prop) {
if (typeof prop === 'symbol' || String(prop).startsWith('__')) {
return obj[prop];
}
const propStr = String(prop);
const currentPath = [...path, propStr];
// Emit access event for packages
if (currentPath[0] === 'packages' && currentPath.length >= 2) {
const nodeId = currentPath[1];
console.log(`π Accessing: ${nodeId}`);
onAccess({ type: 'node_access', nodeId, path: currentPath });
}
const value = obj[prop];
// Recursively wrap objects
if (value !== null && typeof value === 'object' && typeof value !== 'function') {
return createTrackedContext(value, onAccess, currentPath);
}
return value;
},
ownKeys(obj) {
console.log(`π Enumerating: ${path.join('.')}`);
return Reflect.ownKeys(obj);
}
});
}
console.log(`π Found ${stats.totalPackages} packages, ${stats.totalLinks} dependency links\n`);
// Create WebSocket server
console.log(`π Starting WebSocket server on port ${PORT}...`);
const wss = new WebSocketServer({ port: PORT });
const clients = new Set();
function broadcast(msg) {
const data = JSON.stringify(msg);
for (const client of clients) {
if (client.readyState === 1) { // WebSocket.OPEN
client.send(data);
}
}
}
wss.on('listening', () => {
console.log(`π Server running at ws://localhost:${PORT}`);
console.log('β¨ Ready! Open http://localhost:3000\n');
});
wss.on('error', (err) => {
console.error('β Server error:', err.message);
});
wss.on('connection', (ws) => {
console.log('β
Client connected');
clients.add(ws);
// Send graph data
ws.send(JSON.stringify({
type: 'graph_data',
data: { graph: graphData, stats }
}));
ws.on('message', async (data) => {
try {
const msg = JSON.parse(data.toString());
if (msg.type === 'run_query') {
console.log(`\nπ€ Running query: ${msg.query}`);
broadcast({ type: 'status', status: 'running' });
// Create tracked context that emits access events
const trackedContext = createTrackedContext(rawContext, (event) => {
if (event.nodeId) {
broadcast({ type: 'access_event', data: event });
}
});
try {
const result = await rlm.completion(msg.query, {
context: trackedContext,
contextSchema: ContextSchema,
onEvent: (event) => {
// Broadcast RLLM events to frontend for the activity log
broadcast({ type: 'rllm_event', data: event });
}
});
console.log('β
Query complete');
console.log('Result:', result);
broadcast({ type: 'result', data: result });
broadcast({ type: 'status', status: 'completed' });
} catch (err) {
console.error('β Query error:', err.message);
broadcast({
type: 'result',
data: { answer: { message: `Error: ${err.message}`, data: null } }
});
broadcast({ type: 'status', status: 'error' });
}
}
} catch (err) {
console.error('Failed to parse message:', err);
}
});
ws.on('close', () => {
console.log('Client disconnected');
clients.delete(ws);
});
});
// Keep alive
process.on('SIGINT', () => {
console.log('\nπ Shutting down...');
wss.close();
process.exit(0);
});