remimem 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +218 -2
- package/dist/chunker/index.js +129 -0
- package/dist/cli/commands.js +256 -0
- package/dist/cli/index.js +39 -0
- package/dist/cli/program.js +328 -0
- package/dist/cli/ui.js +138 -0
- package/dist/config/index.js +116 -0
- package/dist/dashboard/api.js +196 -0
- package/dist/dashboard/graph.js +58 -0
- package/dist/dashboard/server.js +164 -0
- package/dist/dashboard/ui/app.css +1 -0
- package/dist/dashboard/ui/app.js +324 -0
- package/dist/dashboard/ui/app.js.LEGAL.txt +18 -0
- package/dist/dashboard/ui/index.html +32 -0
- package/dist/embedder/index.js +226 -0
- package/dist/errors.js +15 -0
- package/dist/graph/describe.js +90 -0
- package/dist/graph/index.js +224 -0
- package/dist/indexer/index.js +183 -0
- package/dist/indexer/overview.js +75 -0
- package/dist/indexer/watch.js +55 -0
- package/dist/log.js +16 -0
- package/dist/mcp/server.js +82 -0
- package/dist/mcp/tools.js +273 -0
- package/dist/memory/index.js +262 -0
- package/dist/packer/index.js +149 -0
- package/dist/parser/index.js +294 -0
- package/dist/retriever/index.js +186 -0
- package/dist/scanner/index.js +129 -0
- package/dist/stats/index.js +32 -0
- package/dist/store/fts.js +26 -0
- package/dist/store/index.js +658 -0
- package/dist/tokens.js +8 -0
- package/grammars/README.md +15 -0
- package/grammars/ecma.scm +42 -0
- package/grammars/go.scm +37 -0
- package/grammars/go.wasm +0 -0
- package/grammars/javascript.scm +6 -0
- package/grammars/javascript.wasm +0 -0
- package/grammars/python.scm +21 -0
- package/grammars/python.wasm +0 -0
- package/grammars/tsx.wasm +0 -0
- package/grammars/typescript.scm +20 -0
- package/grammars/typescript.wasm +0 -0
- package/package.json +71 -4
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Bundled license information:
|
|
2
|
+
|
|
3
|
+
cytoscape/dist/cytoscape.esm.mjs:
|
|
4
|
+
/*!
|
|
5
|
+
Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
|
|
6
|
+
Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com)
|
|
7
|
+
Licensed under The MIT License (http://opensource.org/licenses/MIT)
|
|
8
|
+
*/
|
|
9
|
+
/*!
|
|
10
|
+
Event object based on jQuery events, MIT license
|
|
11
|
+
|
|
12
|
+
https://jquery.org/license/
|
|
13
|
+
https://tldrlegal.com/license/mit-license
|
|
14
|
+
https://github.com/jquery/jquery/blob/master/src/event.js
|
|
15
|
+
*/
|
|
16
|
+
/*! Bezier curve function generator. Copyright 2014-2026 Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License
|
|
17
|
+
* https://github.com/gre/bezier-easing */
|
|
18
|
+
/*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<meta name="referrer" content="no-referrer" />
|
|
7
|
+
<title>remimem dashboard</title>
|
|
8
|
+
<link rel="stylesheet" href="/app.css" />
|
|
9
|
+
</head>
|
|
10
|
+
<body>
|
|
11
|
+
<div class="shell">
|
|
12
|
+
<aside class="side">
|
|
13
|
+
<div class="brand">
|
|
14
|
+
<span class="mark" aria-hidden="true">μ</span>
|
|
15
|
+
<span class="name">remimem</span>
|
|
16
|
+
</div>
|
|
17
|
+
<p class="root" id="root" title=""></p>
|
|
18
|
+
<nav class="tabs" aria-label="Views">
|
|
19
|
+
<a href="#health" data-view="health">Health</a>
|
|
20
|
+
<a href="#graph" data-view="graph">Graph</a>
|
|
21
|
+
<a href="#search" data-view="search">Search</a>
|
|
22
|
+
<a href="#memory" data-view="memory">Memory</a>
|
|
23
|
+
<a href="#settings" data-view="settings">Settings</a>
|
|
24
|
+
</nav>
|
|
25
|
+
<p class="version" id="version"></p>
|
|
26
|
+
</aside>
|
|
27
|
+
<main id="main" tabindex="-1"></main>
|
|
28
|
+
</div>
|
|
29
|
+
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
|
30
|
+
<script type="module" src="/app.js"></script>
|
|
31
|
+
</body>
|
|
32
|
+
</html>
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { RemimemError, ConfigError } from '../errors.js';
|
|
5
|
+
export class EmbeddingError extends RemimemError {
|
|
6
|
+
}
|
|
7
|
+
const DEFAULT_MODELS = {
|
|
8
|
+
local: 'Xenova/all-MiniLM-L6-v2',
|
|
9
|
+
openai: 'text-embedding-3-small',
|
|
10
|
+
voyage: 'voyage-code-3',
|
|
11
|
+
};
|
|
12
|
+
const REMOTE = {
|
|
13
|
+
openai: { url: 'https://api.openai.com/v1/embeddings', keyEnv: 'OPENAI_API_KEY' },
|
|
14
|
+
voyage: { url: 'https://api.voyageai.com/v1/embeddings', keyEnv: 'VOYAGE_API_KEY' },
|
|
15
|
+
};
|
|
16
|
+
/** Where downloaded models are kept. Override with REMIMEM_CACHE_DIR. */
|
|
17
|
+
export function modelCacheDir() {
|
|
18
|
+
return join(process.env['REMIMEM_CACHE_DIR'] ?? join(homedir(), '.cache', 'remimem'), 'models');
|
|
19
|
+
}
|
|
20
|
+
function normalize(vector) {
|
|
21
|
+
let sum = 0;
|
|
22
|
+
for (const x of vector)
|
|
23
|
+
sum += x * x;
|
|
24
|
+
const norm = Math.sqrt(sum) || 1;
|
|
25
|
+
return vector.map((x) => x / norm);
|
|
26
|
+
}
|
|
27
|
+
let downloadListener;
|
|
28
|
+
/**
|
|
29
|
+
* Lets the CLI draw the first download of a local model. The MCP server never sets it, so
|
|
30
|
+
* nothing extra is ever written while it serves.
|
|
31
|
+
*/
|
|
32
|
+
export function onModelDownload(listener) {
|
|
33
|
+
downloadListener = listener;
|
|
34
|
+
}
|
|
35
|
+
/** Sums byte progress across a model's files, and reports it only while files download. */
|
|
36
|
+
function progressReporter(model) {
|
|
37
|
+
const files = new Map();
|
|
38
|
+
let downloading = false;
|
|
39
|
+
return (info) => {
|
|
40
|
+
const event = info;
|
|
41
|
+
// Files read from the cache also report progress; only a real download is shown.
|
|
42
|
+
if (event.status === 'download')
|
|
43
|
+
downloading = true;
|
|
44
|
+
if (!downloading || !downloadListener || event.status !== 'progress' || !event.file)
|
|
45
|
+
return;
|
|
46
|
+
files.set(event.file, { loaded: event.loaded ?? 0, total: event.total ?? 0 });
|
|
47
|
+
let loaded = 0;
|
|
48
|
+
let total = 0;
|
|
49
|
+
for (const f of files.values()) {
|
|
50
|
+
loaded += f.loaded;
|
|
51
|
+
total += f.total;
|
|
52
|
+
}
|
|
53
|
+
downloadListener(model, loaded, total);
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function localProvider(model, maxTokens) {
|
|
57
|
+
// Loaded on first use: importing the runtime and reading the model takes a while.
|
|
58
|
+
let ready;
|
|
59
|
+
const load = async () => {
|
|
60
|
+
const { AutoModel, AutoTokenizer, env, mean_pooling } = await import('@huggingface/transformers');
|
|
61
|
+
env.cacheDir = modelCacheDir();
|
|
62
|
+
const progress_callback = progressReporter(model);
|
|
63
|
+
const tokenizer = await AutoTokenizer.from_pretrained(model, { progress_callback });
|
|
64
|
+
const network = await AutoModel.from_pretrained(model, { dtype: 'q8', progress_callback });
|
|
65
|
+
return async (texts) => {
|
|
66
|
+
const inputs = tokenizer(texts, { padding: true, truncation: true, max_length: maxTokens });
|
|
67
|
+
const output = await network(inputs);
|
|
68
|
+
const pooled = mean_pooling(output.last_hidden_state, inputs.attention_mask);
|
|
69
|
+
const [rows = 0, dim = 0] = pooled.dims;
|
|
70
|
+
const data = pooled.data;
|
|
71
|
+
return Array.from({ length: rows }, (_, i) => normalize(data.slice(i * dim, (i + 1) * dim)));
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
id: `local:${model}`,
|
|
76
|
+
local: true,
|
|
77
|
+
async embed(texts) {
|
|
78
|
+
if (texts.length === 0)
|
|
79
|
+
return [];
|
|
80
|
+
ready ??= load().catch((cause) => {
|
|
81
|
+
ready = undefined;
|
|
82
|
+
throw new EmbeddingError(`Embedding model ${model} failed to load (the first run downloads it); run \`remimem doctor\``, { cause });
|
|
83
|
+
});
|
|
84
|
+
return (await ready)(texts);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function remoteProvider(provider, model) {
|
|
89
|
+
const { url, keyEnv } = REMOTE[provider];
|
|
90
|
+
return {
|
|
91
|
+
id: `${provider}:${model}`,
|
|
92
|
+
local: false,
|
|
93
|
+
async embed(texts, kind) {
|
|
94
|
+
if (texts.length === 0)
|
|
95
|
+
return [];
|
|
96
|
+
// Keys come from the environment only, never from the config file.
|
|
97
|
+
const key = process.env[keyEnv];
|
|
98
|
+
if (!key)
|
|
99
|
+
throw new ConfigError(`Set ${keyEnv} to use the ${provider} embedding provider`);
|
|
100
|
+
const body = JSON.stringify({
|
|
101
|
+
model,
|
|
102
|
+
input: texts,
|
|
103
|
+
...(provider === 'voyage' ? { input_type: kind } : {}),
|
|
104
|
+
});
|
|
105
|
+
let lastError = '';
|
|
106
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
107
|
+
if (attempt > 0)
|
|
108
|
+
await new Promise((done) => setTimeout(done, 500 * 2 ** attempt));
|
|
109
|
+
let response;
|
|
110
|
+
try {
|
|
111
|
+
response = await fetch(url, {
|
|
112
|
+
method: 'POST',
|
|
113
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
114
|
+
body,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
lastError = String(error);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (response.ok) {
|
|
122
|
+
const json = (await response.json());
|
|
123
|
+
return [...json.data]
|
|
124
|
+
.sort((a, b) => a.index - b.index)
|
|
125
|
+
.map((item) => normalize(Float32Array.from(item.embedding)));
|
|
126
|
+
}
|
|
127
|
+
lastError = `HTTP ${response.status}: ${(await response.text()).slice(0, 200)}`;
|
|
128
|
+
// Only rate limits and server errors are worth another try.
|
|
129
|
+
if (response.status !== 429 && response.status < 500)
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
throw new EmbeddingError(`${provider} embedding request failed: ${lastError}`);
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** The provider the config asks for, or null when embeddings are turned off. */
|
|
137
|
+
export function createProvider(config) {
|
|
138
|
+
if (config.provider === 'none')
|
|
139
|
+
return null;
|
|
140
|
+
const model = config.model || DEFAULT_MODELS[config.provider];
|
|
141
|
+
return config.provider === 'local'
|
|
142
|
+
? localProvider(model, config.maxTokens)
|
|
143
|
+
: remoteProvider(config.provider, model);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The text that is embedded for a chunk: path, signature, docstring, then the body. Local
|
|
147
|
+
* models cut their input after a few hundred tokens, and this order means the cut only ever
|
|
148
|
+
* removes the end of the body.
|
|
149
|
+
*/
|
|
150
|
+
export function embeddingText(chunk) {
|
|
151
|
+
const { path, content, signature, docstring } = chunk;
|
|
152
|
+
if (!signature)
|
|
153
|
+
return `${path}\n${content}`;
|
|
154
|
+
// Drop the doc comment above the symbol, then the signature the code starts with, so
|
|
155
|
+
// neither appears twice. A later part of a split function also starts with the signature.
|
|
156
|
+
let body = content.split('\n').slice(chunk.docLines).join('\n');
|
|
157
|
+
const wanted = signature.replace(/\s+/g, '');
|
|
158
|
+
let end = 0;
|
|
159
|
+
for (let matched = 0; end < body.length && matched < wanted.length; end++) {
|
|
160
|
+
const ch = body[end];
|
|
161
|
+
if (/\s/.test(ch))
|
|
162
|
+
continue;
|
|
163
|
+
if (ch !== wanted[matched])
|
|
164
|
+
break;
|
|
165
|
+
matched++;
|
|
166
|
+
if (matched === wanted.length) {
|
|
167
|
+
body = body.slice(end + 1);
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// shortcut: a Python docstring stays in the body as well, since it is part of the code.
|
|
172
|
+
// Strip it there if the repeated text turns out to cost recall.
|
|
173
|
+
return [path, signature, docstring, body.trim()].filter(Boolean).join('\n');
|
|
174
|
+
}
|
|
175
|
+
const hashOf = (text) => createHash('sha256').update(text).digest('hex');
|
|
176
|
+
/** True when the stored vectors came from a different model than `provider`. */
|
|
177
|
+
export function modelChanged(store, provider) {
|
|
178
|
+
const stored = store.embeddingModel();
|
|
179
|
+
return stored !== undefined && stored !== provider.id;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Gives every chunk that lacks a vector one, reusing cached vectors for text that was
|
|
183
|
+
* embedded before. Safe to interrupt: the next run continues with what is still missing.
|
|
184
|
+
*/
|
|
185
|
+
export async function embedMissing(store, provider, batchSize, onProgress) {
|
|
186
|
+
if (modelChanged(store, provider)) {
|
|
187
|
+
throw new EmbeddingError(`The index holds vectors from ${store.embeddingModel()} but the configured model is ${provider.id}; run \`remimem index --full\` to rebuild them`);
|
|
188
|
+
}
|
|
189
|
+
const stats = { embedded: 0, cached: 0, hashes: new Set() };
|
|
190
|
+
// Cheap check first: finding the chunks that lack a vector scans the whole table.
|
|
191
|
+
if (store.embeddingModel() !== undefined && store.vectorCount() === store.counts().chunks) {
|
|
192
|
+
return stats;
|
|
193
|
+
}
|
|
194
|
+
const pending = store.chunksWithoutVectors();
|
|
195
|
+
for (let start = 0; start < pending.length; start += batchSize) {
|
|
196
|
+
const batch = pending.slice(start, start + batchSize).map((chunk) => {
|
|
197
|
+
const text = embeddingText(chunk);
|
|
198
|
+
const hash = hashOf(text);
|
|
199
|
+
return { id: chunk.id, text, hash, vector: store.cachedEmbedding(hash, provider.id) };
|
|
200
|
+
});
|
|
201
|
+
const misses = batch.filter((item) => !item.vector);
|
|
202
|
+
const fresh = await provider.embed(misses.map((item) => item.text), 'document');
|
|
203
|
+
if (fresh.length !== misses.length) {
|
|
204
|
+
throw new EmbeddingError(`${provider.id} returned ${fresh.length} vectors for ${misses.length} texts`);
|
|
205
|
+
}
|
|
206
|
+
for (const [i, item] of misses.entries())
|
|
207
|
+
item.vector = fresh[i];
|
|
208
|
+
const first = batch[0]?.vector;
|
|
209
|
+
if (first && store.embeddingModel() === undefined)
|
|
210
|
+
store.resetVectors(provider.id, first.length);
|
|
211
|
+
store.transaction(() => {
|
|
212
|
+
for (const item of batch) {
|
|
213
|
+
const vector = item.vector;
|
|
214
|
+
store.setVector(item.id, vector);
|
|
215
|
+
if (misses.includes(item))
|
|
216
|
+
store.cacheEmbedding(item.hash, provider.id, vector);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
for (const item of batch)
|
|
220
|
+
stats.hashes.add(item.hash);
|
|
221
|
+
stats.embedded += batch.length;
|
|
222
|
+
stats.cached += batch.length - misses.length;
|
|
223
|
+
onProgress?.(stats.embedded, pending.length);
|
|
224
|
+
}
|
|
225
|
+
return stats;
|
|
226
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Base class for errors whose message is safe and useful to show to the user. */
|
|
2
|
+
export class RemimemError extends Error {
|
|
3
|
+
constructor(message, options) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export class GrammarError extends RemimemError {
|
|
9
|
+
}
|
|
10
|
+
export class PathError extends RemimemError {
|
|
11
|
+
}
|
|
12
|
+
export class ConfigError extends RemimemError {
|
|
13
|
+
}
|
|
14
|
+
export class StoreError extends RemimemError {
|
|
15
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { render } from '../packer/index.js';
|
|
2
|
+
/** Section titles for each relation, in display order. */
|
|
3
|
+
const SECTIONS = [
|
|
4
|
+
['calls', 'Calls'],
|
|
5
|
+
['calls by', 'Called by'],
|
|
6
|
+
['extends', 'Extends'],
|
|
7
|
+
['extends by', 'Extended by'],
|
|
8
|
+
['implements', 'Implements'],
|
|
9
|
+
['implements by', 'Implemented by'],
|
|
10
|
+
['uses-type', 'Uses types'],
|
|
11
|
+
['uses-type by', 'Used as a type by'],
|
|
12
|
+
['inside', 'Inside'],
|
|
13
|
+
['contains', 'Contains'],
|
|
14
|
+
];
|
|
15
|
+
const location = (s) => `${s.path}:${s.startLine}-${s.endLine}`;
|
|
16
|
+
/** The symbols a name refers to: an exact qualified name wins over plain name matches. */
|
|
17
|
+
function lookup(store, name) {
|
|
18
|
+
const matches = store.symbolsNamed(name);
|
|
19
|
+
const qualified = matches.filter((s) => s.qualifiedName === name);
|
|
20
|
+
return qualified.length > 0 ? qualified : matches;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A symbol with its neighbors, as text for an agent. `depth` is how many hops of callers
|
|
24
|
+
* and callees to follow (0 to 2); other relations are listed for the symbol itself.
|
|
25
|
+
*/
|
|
26
|
+
export function describeSymbol(store, name, options = {}) {
|
|
27
|
+
const matches = lookup(store, name);
|
|
28
|
+
const symbol = matches[0];
|
|
29
|
+
if (!symbol)
|
|
30
|
+
return `No symbol named "${name}" in the index.`;
|
|
31
|
+
if (matches.length > 1) {
|
|
32
|
+
const list = matches.map((s) => ` ${s.kind} ${s.qualifiedName} ${location(s)}`);
|
|
33
|
+
return `${matches.length} symbols are named "${name}". Ask again with a qualified name:\n${list.join('\n')}`;
|
|
34
|
+
}
|
|
35
|
+
const depth = Math.max(0, Math.min(2, Math.trunc(options.depth ?? 1)));
|
|
36
|
+
const chunks = store.chunksOfSymbol(symbol.id);
|
|
37
|
+
const body = options.include === 'signature' || chunks.length === 0
|
|
38
|
+
? `--- ${location(symbol)} ${symbol.kind} ${symbol.qualifiedName}\n${symbol.signature}${symbol.docstring ? `\n${symbol.docstring.replace(/^/gm, ' ')}` : ''}`
|
|
39
|
+
: render(chunks.map((chunk) => ({ chunk, score: 0, reasons: [], detail: 'full' }))).replaceAll(' []', '');
|
|
40
|
+
if (depth === 0)
|
|
41
|
+
return body;
|
|
42
|
+
const out = [body];
|
|
43
|
+
const direct = store.neighbors([symbol.id]);
|
|
44
|
+
for (const [relation, title] of SECTIONS) {
|
|
45
|
+
const rows = direct.filter((n) => n.relation === relation);
|
|
46
|
+
if (rows.length === 0)
|
|
47
|
+
continue;
|
|
48
|
+
out.push('', `${title}:`);
|
|
49
|
+
const follow = relation === 'calls' || relation === 'calls by';
|
|
50
|
+
const seen = new Set([symbol.id]);
|
|
51
|
+
const walk = (level, hop) => {
|
|
52
|
+
for (const n of level) {
|
|
53
|
+
const again = seen.has(n.id);
|
|
54
|
+
seen.add(n.id);
|
|
55
|
+
out.push(`${' '.repeat(hop)}${n.qualifiedName} ${location(n)} [${n.confidence}]${again ? ' (shown above)' : ''}`);
|
|
56
|
+
if (follow && !again && hop < depth) {
|
|
57
|
+
walk(store.neighbors([n.id]).filter((next) => next.relation === relation), hop + 1);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
walk(rows, 1);
|
|
62
|
+
}
|
|
63
|
+
return out.join('\n');
|
|
64
|
+
}
|
|
65
|
+
/** Every place a symbol is called, extended, used as a type, or imported, grouped by file. */
|
|
66
|
+
export function findReferences(store, name) {
|
|
67
|
+
const matches = lookup(store, name);
|
|
68
|
+
if (matches.length === 0)
|
|
69
|
+
return `No symbol named "${name}" in the index.`;
|
|
70
|
+
const references = store.referencesTo(matches.map((s) => s.id));
|
|
71
|
+
const defined = matches.map((s) => `${s.kind} ${s.qualifiedName} at ${location(s)}`).join('; ');
|
|
72
|
+
if (references.length === 0)
|
|
73
|
+
return `No references found to ${defined}.`;
|
|
74
|
+
const paths = new Set(references.map((r) => r.path));
|
|
75
|
+
const out = [
|
|
76
|
+
`${references.length} reference${references.length === 1 ? '' : 's'} in ${paths.size} file${paths.size === 1 ? '' : 's'} to ${defined}`,
|
|
77
|
+
];
|
|
78
|
+
let current = '';
|
|
79
|
+
for (const r of references) {
|
|
80
|
+
if (r.path !== current) {
|
|
81
|
+
current = r.path;
|
|
82
|
+
out.push('', r.path);
|
|
83
|
+
}
|
|
84
|
+
const what = r.kind === 'import'
|
|
85
|
+
? 'import'
|
|
86
|
+
: `${r.kind} in ${r.fromSymbol ?? 'file scope'} [${r.confidence}]`;
|
|
87
|
+
out.push(` ${r.path}:${r.line} ${what}`);
|
|
88
|
+
}
|
|
89
|
+
return out.join('\n');
|
|
90
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { posix } from 'node:path';
|
|
2
|
+
/** Languages that can refer to each other's symbols. */
|
|
3
|
+
const FAMILY = {
|
|
4
|
+
typescript: 'ecma',
|
|
5
|
+
tsx: 'ecma',
|
|
6
|
+
javascript: 'ecma',
|
|
7
|
+
python: 'python',
|
|
8
|
+
go: 'go',
|
|
9
|
+
};
|
|
10
|
+
const ECMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
|
|
11
|
+
const TYPE_KINDS = new Set(['class', 'interface', 'type', 'enum']);
|
|
12
|
+
const SELF = new Set(['this', 'self', 'cls']);
|
|
13
|
+
const dirOf = (path) => {
|
|
14
|
+
const dir = posix.dirname(path);
|
|
15
|
+
return dir === '.' ? '' : dir;
|
|
16
|
+
};
|
|
17
|
+
function push(map, key, value) {
|
|
18
|
+
const list = map.get(key);
|
|
19
|
+
if (list)
|
|
20
|
+
list.push(value);
|
|
21
|
+
else
|
|
22
|
+
map.set(key, [value]);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Resolves every reference and import to the symbol it most likely means. Best effort, in
|
|
26
|
+
* this order: the same file (`exact`), a name the file imports (`import`), then a name that
|
|
27
|
+
* is unique in the repo (`name-match`). A call through an import that leads outside the
|
|
28
|
+
* repo, such as `fmt.Println`, is left unresolved instead of guessed.
|
|
29
|
+
*/
|
|
30
|
+
export function resolveReferences(input) {
|
|
31
|
+
const files = new Map(input.files.map((f) => [f.id, { ...f, dir: dirOf(f.path) }]));
|
|
32
|
+
const fileIdByPath = new Map(input.files.map((f) => [f.path, f.id]));
|
|
33
|
+
const filesByDir = new Map();
|
|
34
|
+
for (const f of files.values())
|
|
35
|
+
push(filesByDir, f.dir, f.id);
|
|
36
|
+
const familyOf = (fileId) => FAMILY[files.get(fileId)?.language ?? ''] ?? '';
|
|
37
|
+
const symbols = new Map(input.symbols.map((s) => [s.id, s]));
|
|
38
|
+
const inFile = new Map(); // "fileId:name", every symbol
|
|
39
|
+
const topLevel = new Map(); // "fileId:name", symbols without a parent
|
|
40
|
+
const children = new Map();
|
|
41
|
+
const byName = new Map();
|
|
42
|
+
const byQualified = new Map(); // "dir:qualifiedName"
|
|
43
|
+
for (const s of input.symbols) {
|
|
44
|
+
push(inFile, `${s.fileId}:${s.name}`, s);
|
|
45
|
+
if (s.parentId === null)
|
|
46
|
+
push(topLevel, `${s.fileId}:${s.name}`, s);
|
|
47
|
+
else
|
|
48
|
+
push(children, s.parentId, s);
|
|
49
|
+
push(byName, s.name, s);
|
|
50
|
+
byQualified.set(`${files.get(s.fileId)?.dir}:${s.qualifiedName}`, s);
|
|
51
|
+
}
|
|
52
|
+
const locals = new Map(); // "fileId:localName"
|
|
53
|
+
for (const i of input.imports)
|
|
54
|
+
if (i.local)
|
|
55
|
+
locals.set(`${i.fileId}:${i.local}`, i);
|
|
56
|
+
const moduleCache = new Map();
|
|
57
|
+
/** The repo files an import source refers to; empty when it leads outside the repo. */
|
|
58
|
+
const moduleFiles = (fileId, source) => {
|
|
59
|
+
const file = files.get(fileId);
|
|
60
|
+
if (!file || !source)
|
|
61
|
+
return [];
|
|
62
|
+
const family = familyOf(fileId);
|
|
63
|
+
const key = `${family}|${source.startsWith('.') ? file.dir : ''}|${source}`;
|
|
64
|
+
let found = moduleCache.get(key);
|
|
65
|
+
if (!found) {
|
|
66
|
+
found = findModule(family, file.dir, source);
|
|
67
|
+
moduleCache.set(key, found);
|
|
68
|
+
}
|
|
69
|
+
return found;
|
|
70
|
+
};
|
|
71
|
+
const existing = (paths) => {
|
|
72
|
+
const id = paths.map((p) => fileIdByPath.get(p)).find((x) => x !== undefined);
|
|
73
|
+
return id === undefined ? [] : [id];
|
|
74
|
+
};
|
|
75
|
+
/** The one file of a family whose path ends with one of the given paths. */
|
|
76
|
+
const bySuffix = (family, endings) => {
|
|
77
|
+
const hits = input.files.filter((f) => FAMILY[f.language ?? ''] === family &&
|
|
78
|
+
endings.some((end) => f.path === end || f.path.endsWith(`/${end}`)));
|
|
79
|
+
return hits.length === 1 ? [hits[0].id] : [];
|
|
80
|
+
};
|
|
81
|
+
function findModule(family, dir, source) {
|
|
82
|
+
if (family === 'ecma') {
|
|
83
|
+
const bare = source.replace(/\.(js|jsx|mjs|cjs|ts|tsx)$/, '');
|
|
84
|
+
const endings = (base) => ECMA_EXTENSIONS.flatMap((ext) => [`${base}${ext}`, `${base}/index${ext}`]);
|
|
85
|
+
return source.startsWith('.')
|
|
86
|
+
? existing(endings(posix.normalize(posix.join(dir, bare))))
|
|
87
|
+
: bySuffix(family, endings(bare.replace(/^[@~]\//, '')));
|
|
88
|
+
}
|
|
89
|
+
if (family === 'python') {
|
|
90
|
+
const dots = /^\.*/.exec(source)?.[0].length ?? 0;
|
|
91
|
+
const rest = source.slice(dots).split('.').filter(Boolean).join('/');
|
|
92
|
+
if (dots === 0)
|
|
93
|
+
return bySuffix(family, [`${rest}.py`, `${rest}/__init__.py`]);
|
|
94
|
+
let base = dir;
|
|
95
|
+
for (let i = 1; i < dots; i++)
|
|
96
|
+
base = dirOf(base);
|
|
97
|
+
const target = posix.join(base, rest);
|
|
98
|
+
return existing(rest ? [`${target}.py`, `${target}/__init__.py`] : [`${target}/__init__.py`]);
|
|
99
|
+
}
|
|
100
|
+
if (family === 'go') {
|
|
101
|
+
for (const { dir: root, module } of input.goModules) {
|
|
102
|
+
if (source !== module && !source.startsWith(`${module}/`))
|
|
103
|
+
continue;
|
|
104
|
+
const packageDir = posix.join(root, source.slice(module.length + 1));
|
|
105
|
+
return (filesByDir.get(packageDir === '.' ? '' : packageDir) ?? []).filter((id) => familyOf(id) === 'go');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return [];
|
|
109
|
+
}
|
|
110
|
+
const kindOk = (s, refKind) => refKind === 'call' || TYPE_KINDS.has(s.kind);
|
|
111
|
+
const topIn = (fileIds, name, refKind = 'call') => {
|
|
112
|
+
for (const id of fileIds) {
|
|
113
|
+
const hit = topLevel.get(`${id}:${name}`)?.find((s) => kindOk(s, refKind));
|
|
114
|
+
if (hit)
|
|
115
|
+
return hit;
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
};
|
|
119
|
+
/** A member of a class or struct. Go methods can live in another file of the package. */
|
|
120
|
+
const member = (owner, name) => children.get(owner.id)?.find((s) => s.name === name) ??
|
|
121
|
+
byQualified.get(`${files.get(owner.fileId)?.dir}:${owner.qualifiedName}.${name}`);
|
|
122
|
+
const hit = (s, confidence) => s ? { target: s.id, confidence } : null;
|
|
123
|
+
function resolve(ref) {
|
|
124
|
+
const { fileId, name, receiver, kind } = ref;
|
|
125
|
+
const caller = ref.symbolId === null ? undefined : symbols.get(ref.symbolId);
|
|
126
|
+
const family = familyOf(fileId);
|
|
127
|
+
if (receiver === null) {
|
|
128
|
+
// Enclosing functions, innermost first, then the top level of the file.
|
|
129
|
+
for (let s = caller; s; s = s.parentId === null ? undefined : symbols.get(s.parentId)) {
|
|
130
|
+
if (s.kind === 'class')
|
|
131
|
+
continue;
|
|
132
|
+
const nested = children.get(s.id)?.find((c) => c.name === name && kindOk(c, kind));
|
|
133
|
+
if (nested)
|
|
134
|
+
return hit(nested, 'exact');
|
|
135
|
+
}
|
|
136
|
+
const sameFile = topIn([fileId], name, kind);
|
|
137
|
+
if (sameFile)
|
|
138
|
+
return hit(sameFile, 'exact');
|
|
139
|
+
if (family === 'go') {
|
|
140
|
+
// A Go package is a directory: its files share one scope.
|
|
141
|
+
const samePackage = topIn(filesByDir.get(files.get(fileId)?.dir ?? '') ?? [], name, kind);
|
|
142
|
+
if (samePackage)
|
|
143
|
+
return hit(samePackage, 'exact');
|
|
144
|
+
}
|
|
145
|
+
const imported = locals.get(`${fileId}:${name}`);
|
|
146
|
+
if (imported) {
|
|
147
|
+
if (imported.name === '*')
|
|
148
|
+
return null;
|
|
149
|
+
const original = imported.name === 'default' ? name : imported.name;
|
|
150
|
+
return hit(topIn(moduleFiles(fileId, imported.source), original, kind), 'import');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else if (SELF.has(receiver)) {
|
|
154
|
+
let owner = caller;
|
|
155
|
+
while (owner && owner.kind !== 'class') {
|
|
156
|
+
owner = owner.parentId === null ? undefined : symbols.get(owner.parentId);
|
|
157
|
+
}
|
|
158
|
+
const own = owner && member(owner, name);
|
|
159
|
+
if (own)
|
|
160
|
+
return hit(own, 'exact');
|
|
161
|
+
}
|
|
162
|
+
else if (receiver !== '') {
|
|
163
|
+
const imported = locals.get(`${fileId}:${receiver}`) ?? locals.get(`${fileId}:${receiver.split('.')[0]}`);
|
|
164
|
+
if (imported) {
|
|
165
|
+
const targets = moduleFiles(fileId, imported.source);
|
|
166
|
+
if (imported.name === '*')
|
|
167
|
+
return hit(topIn(targets, name), 'import');
|
|
168
|
+
// The receiver is an imported class, or (Python) an imported submodule.
|
|
169
|
+
const owner = topIn(targets, imported.name === 'default' ? imported.local : imported.name);
|
|
170
|
+
if (owner)
|
|
171
|
+
return hit(member(owner, name), 'import');
|
|
172
|
+
const separator = imported.source.endsWith('.') ? '' : '.';
|
|
173
|
+
const submodule = family === 'python'
|
|
174
|
+
? moduleFiles(fileId, `${imported.source}${separator}${imported.name}`)
|
|
175
|
+
: [];
|
|
176
|
+
return hit(topIn(submodule, name), 'import');
|
|
177
|
+
}
|
|
178
|
+
const owner = topIn([fileId], receiver);
|
|
179
|
+
const own = owner && TYPE_KINDS.has(owner.kind) ? member(owner, name) : undefined;
|
|
180
|
+
if (own)
|
|
181
|
+
return hit(own, 'exact');
|
|
182
|
+
// A capitalized receiver names a class or namespace. One that is neither in this file
|
|
183
|
+
// nor imported is a global such as `Object` or `Math`, so the call is not ours.
|
|
184
|
+
if (/^\p{Lu}[\p{L}\p{N}_$]*$/u.test(receiver))
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
if (receiver !== null) {
|
|
188
|
+
// The receiver is a value of unknown type: one symbol of that name in this file.
|
|
189
|
+
const sameFile = (inFile.get(`${fileId}:${name}`) ?? []).filter((s) => kindOk(s, kind));
|
|
190
|
+
if (sameFile.length === 1)
|
|
191
|
+
return hit(sameFile[0], 'exact');
|
|
192
|
+
}
|
|
193
|
+
const candidates = (byName.get(name) ?? []).filter((s) => {
|
|
194
|
+
const parent = s.parentId === null ? undefined : symbols.get(s.parentId);
|
|
195
|
+
return (familyOf(s.fileId) === family &&
|
|
196
|
+
kindOk(s, kind) &&
|
|
197
|
+
s.kind !== 'constant' &&
|
|
198
|
+
// A function nested in another function cannot be reached from elsewhere.
|
|
199
|
+
(!parent || parent.kind === 'class'));
|
|
200
|
+
});
|
|
201
|
+
return candidates.length === 1 ? hit(candidates[0], 'name-match') : null;
|
|
202
|
+
}
|
|
203
|
+
const refs = [];
|
|
204
|
+
for (const ref of input.refs) {
|
|
205
|
+
const resolved = resolve(ref);
|
|
206
|
+
if (resolved)
|
|
207
|
+
refs.push({ id: ref.id, ...resolved });
|
|
208
|
+
}
|
|
209
|
+
const imports = [];
|
|
210
|
+
for (const i of input.imports) {
|
|
211
|
+
if (i.name === '' || i.name === '*')
|
|
212
|
+
continue;
|
|
213
|
+
const target = topIn(moduleFiles(i.fileId, i.source), i.name === 'default' ? i.local : i.name);
|
|
214
|
+
if (target)
|
|
215
|
+
imports.push({ id: i.id, target: target.id });
|
|
216
|
+
}
|
|
217
|
+
return { refs, imports };
|
|
218
|
+
}
|
|
219
|
+
/** Resolves every reference in the store again and rebuilds the edges. */
|
|
220
|
+
export function updateGraph(store) {
|
|
221
|
+
const { refs, imports } = resolveReferences(store.graphInput());
|
|
222
|
+
store.saveResolution(refs, imports);
|
|
223
|
+
return { edges: store.edgeCount() };
|
|
224
|
+
}
|