@tipolink/mcp 1.0.7 → 1.0.8
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.md +36 -0
- package/README.md +54 -18
- package/dist/cli.js +107 -6524
- package/dist/extractor.js +8 -4433
- package/dist/index.js +107 -6550
- package/dist/init-installer.js +50 -368
- package/dist/mcp-stdio.d.ts +1 -1
- package/dist/mcp-stdio.js +22 -5689
- package/package.json +4 -3
package/dist/extractor.js
CHANGED
|
@@ -1,4433 +1,8 @@
|
|
|
1
|
-
// src/extractor.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
realpathSync as realpathSync2,
|
|
8
|
-
rmSync,
|
|
9
|
-
statSync as statSync2,
|
|
10
|
-
writeFileSync as writeFileSync2
|
|
11
|
-
} from "node:fs";
|
|
12
|
-
import os from "node:os";
|
|
13
|
-
import path6 from "node:path";
|
|
14
|
-
|
|
15
|
-
// ../engine/src/ast-extractor.ts
|
|
16
|
-
import { createHash } from "node:crypto";
|
|
17
|
-
import path3 from "node:path";
|
|
18
|
-
import ts from "typescript";
|
|
19
|
-
|
|
20
|
-
// ../engine/src/cache.ts
|
|
21
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
22
|
-
import path2 from "node:path";
|
|
23
|
-
|
|
24
|
-
// ../engine/src/paths.ts
|
|
25
|
-
import path from "node:path";
|
|
26
|
-
function compareText(a, b) {
|
|
27
|
-
if (a < b) return -1;
|
|
28
|
-
if (a > b) return 1;
|
|
29
|
-
return 0;
|
|
30
|
-
}
|
|
31
|
-
function toPosix(value) {
|
|
32
|
-
return value.replace(/\\/g, "/");
|
|
33
|
-
}
|
|
34
|
-
function normalizeRelPath(relPath) {
|
|
35
|
-
const posix = path.posix.normalize(toPosix(relPath.trim()));
|
|
36
|
-
return posix.replace(/^\.\//, "");
|
|
37
|
-
}
|
|
38
|
-
function displayPath(root, absolute) {
|
|
39
|
-
const trimmed = absolute.trim();
|
|
40
|
-
if (!trimmed) return trimmed;
|
|
41
|
-
const resolved = path.isAbsolute(trimmed) ? path.resolve(trimmed) : path.resolve(root, trimmed);
|
|
42
|
-
const rel = path.relative(root, resolved);
|
|
43
|
-
if (!rel) return ".";
|
|
44
|
-
if (rel.startsWith("..") || path.isAbsolute(rel)) return toPosix(trimmed);
|
|
45
|
-
return toPosix(rel);
|
|
46
|
-
}
|
|
47
|
-
function computeRelativeImportSpec(fromRelPath, toRelPath) {
|
|
48
|
-
const fromDir = path.posix.dirname(normalizeRelPath(fromRelPath));
|
|
49
|
-
const target = normalizeRelPath(toRelPath);
|
|
50
|
-
let rel = path.posix.relative(fromDir, target);
|
|
51
|
-
if (!rel.startsWith("./") && !rel.startsWith("../")) {
|
|
52
|
-
rel = `./${rel}`;
|
|
53
|
-
}
|
|
54
|
-
const ext = path.posix.extname(rel).toLowerCase();
|
|
55
|
-
const stem = rel.slice(0, rel.length - ext.length);
|
|
56
|
-
if (ext === ".ts" || ext === ".tsx") return `${stem}.js`;
|
|
57
|
-
if (ext === ".mts") return `${stem}.mjs`;
|
|
58
|
-
if (ext === ".cts") return `${stem}.cjs`;
|
|
59
|
-
return rel;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// ../engine/src/cache.ts
|
|
63
|
-
var CACHE_SCHEMA_VERSION = "1.0.5";
|
|
64
|
-
function cacheEntryMatches(entry, contentSha256, mtimeMs, size) {
|
|
65
|
-
if (contentSha256 !== void 0) {
|
|
66
|
-
return entry.contentSha256 === contentSha256;
|
|
67
|
-
}
|
|
68
|
-
if (mtimeMs !== void 0 || size !== void 0) {
|
|
69
|
-
if (mtimeMs !== void 0 && entry.mtimeMs !== mtimeMs) return false;
|
|
70
|
-
if (size !== void 0 && entry.size !== size) return false;
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
return true;
|
|
74
|
-
}
|
|
75
|
-
var JsonFileAstCache = class {
|
|
76
|
-
filePath;
|
|
77
|
-
schemaInvalidated = false;
|
|
78
|
-
autoSave;
|
|
79
|
-
workspaces = /* @__PURE__ */ new Map();
|
|
80
|
-
dirty = false;
|
|
81
|
-
constructor(filePathOrOptions) {
|
|
82
|
-
if (typeof filePathOrOptions === "string") {
|
|
83
|
-
this.filePath = filePathOrOptions;
|
|
84
|
-
this.autoSave = true;
|
|
85
|
-
} else {
|
|
86
|
-
this.filePath = filePathOrOptions.filePath;
|
|
87
|
-
this.autoSave = filePathOrOptions.autoSave ?? true;
|
|
88
|
-
}
|
|
89
|
-
this.loadFromDisk();
|
|
90
|
-
}
|
|
91
|
-
loadFromDisk() {
|
|
92
|
-
if (!existsSync(this.filePath)) return;
|
|
93
|
-
try {
|
|
94
|
-
const raw = readFileSync(this.filePath, "utf8");
|
|
95
|
-
if (!raw.trim()) return;
|
|
96
|
-
const parsed = JSON.parse(raw);
|
|
97
|
-
if (!parsed || typeof parsed !== "object" || !parsed.workspaces || typeof parsed.workspaces !== "object") {
|
|
98
|
-
this.schemaInvalidated = true;
|
|
99
|
-
this.dirty = true;
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
if (parsed.manifestSchemaVersion !== CACHE_SCHEMA_VERSION) {
|
|
103
|
-
this.workspaces.clear();
|
|
104
|
-
this.schemaInvalidated = true;
|
|
105
|
-
this.dirty = true;
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
for (const [workspaceId, files] of Object.entries(parsed.workspaces)) {
|
|
109
|
-
if (!files || typeof files !== "object") continue;
|
|
110
|
-
const map = /* @__PURE__ */ new Map();
|
|
111
|
-
for (const [relPath, manifest] of Object.entries(files)) {
|
|
112
|
-
if (manifest && typeof manifest === "object" && typeof manifest.contentSha256 === "string") {
|
|
113
|
-
const norm = toPosix(relPath);
|
|
114
|
-
map.set(norm, { ...manifest, relativePath: norm });
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
this.workspaces.set(workspaceId, map);
|
|
118
|
-
}
|
|
119
|
-
} catch {
|
|
120
|
-
this.workspaces.clear();
|
|
121
|
-
this.schemaInvalidated = true;
|
|
122
|
-
this.dirty = true;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
get(workspaceId, relativePath, contentSha256, mtimeMs, size) {
|
|
126
|
-
const wsMap = this.workspaces.get(workspaceId);
|
|
127
|
-
if (!wsMap) return void 0;
|
|
128
|
-
const hit = wsMap.get(toPosix(relativePath));
|
|
129
|
-
if (!hit) return void 0;
|
|
130
|
-
return cacheEntryMatches(hit, contentSha256, mtimeMs, size) ? hit : void 0;
|
|
131
|
-
}
|
|
132
|
-
set(workspaceId, manifest) {
|
|
133
|
-
const norm = toPosix(manifest.relativePath);
|
|
134
|
-
const normalized = {
|
|
135
|
-
...manifest,
|
|
136
|
-
relativePath: norm
|
|
137
|
-
};
|
|
138
|
-
let wsMap = this.workspaces.get(workspaceId);
|
|
139
|
-
if (!wsMap) {
|
|
140
|
-
wsMap = /* @__PURE__ */ new Map();
|
|
141
|
-
this.workspaces.set(workspaceId, wsMap);
|
|
142
|
-
}
|
|
143
|
-
wsMap.set(norm, normalized);
|
|
144
|
-
this.dirty = true;
|
|
145
|
-
if (this.autoSave) {
|
|
146
|
-
this.save();
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
getAllWorkspaceManifests(workspaceId) {
|
|
150
|
-
const wsMap = this.workspaces.get(workspaceId);
|
|
151
|
-
if (!wsMap) return [];
|
|
152
|
-
return [...wsMap.values()];
|
|
153
|
-
}
|
|
154
|
-
clear(workspaceId) {
|
|
155
|
-
if (workspaceId === void 0) {
|
|
156
|
-
this.workspaces.clear();
|
|
157
|
-
} else {
|
|
158
|
-
this.workspaces.delete(workspaceId);
|
|
159
|
-
}
|
|
160
|
-
this.dirty = true;
|
|
161
|
-
if (this.autoSave) {
|
|
162
|
-
this.save();
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
save() {
|
|
166
|
-
if (!this.dirty && existsSync(this.filePath)) return;
|
|
167
|
-
const payload = {
|
|
168
|
-
version: 1,
|
|
169
|
-
manifestSchemaVersion: CACHE_SCHEMA_VERSION,
|
|
170
|
-
workspaces: {}
|
|
171
|
-
};
|
|
172
|
-
for (const [workspaceId, wsMap] of this.workspaces.entries()) {
|
|
173
|
-
const obj = {};
|
|
174
|
-
for (const [relPath, manifest] of wsMap.entries()) {
|
|
175
|
-
obj[relPath] = manifest;
|
|
176
|
-
}
|
|
177
|
-
payload.workspaces[workspaceId] = obj;
|
|
178
|
-
}
|
|
179
|
-
const dir = path2.dirname(this.filePath);
|
|
180
|
-
mkdirSync(dir, { recursive: true });
|
|
181
|
-
const serialized = JSON.stringify(payload, null, 2);
|
|
182
|
-
const tmpPath = `${this.filePath}.${process.pid}.${Date.now()}.tmp`;
|
|
183
|
-
try {
|
|
184
|
-
writeFileSync(tmpPath, serialized, "utf8");
|
|
185
|
-
renameSync(tmpPath, this.filePath);
|
|
186
|
-
} catch {
|
|
187
|
-
writeFileSync(this.filePath, serialized, "utf8");
|
|
188
|
-
}
|
|
189
|
-
this.dirty = false;
|
|
190
|
-
}
|
|
191
|
-
flush() {
|
|
192
|
-
this.save();
|
|
193
|
-
}
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
// ../engine/src/ast-extractor.ts
|
|
197
|
-
function scriptKindFor(filePath) {
|
|
198
|
-
switch (path3.extname(filePath).toLowerCase()) {
|
|
199
|
-
case ".tsx":
|
|
200
|
-
return ts.ScriptKind.TSX;
|
|
201
|
-
case ".jsx":
|
|
202
|
-
return ts.ScriptKind.JSX;
|
|
203
|
-
case ".js":
|
|
204
|
-
case ".mjs":
|
|
205
|
-
case ".cjs":
|
|
206
|
-
return ts.ScriptKind.JS;
|
|
207
|
-
default:
|
|
208
|
-
return ts.ScriptKind.TS;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
function jsTsLanguageFor(filePath) {
|
|
212
|
-
switch (path3.extname(filePath).toLowerCase()) {
|
|
213
|
-
case ".js":
|
|
214
|
-
case ".jsx":
|
|
215
|
-
case ".mjs":
|
|
216
|
-
case ".cjs":
|
|
217
|
-
return "javascript";
|
|
218
|
-
default:
|
|
219
|
-
return "typescript";
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
function collapseWhitespace(text) {
|
|
223
|
-
return text.replace(/\s+/g, " ").trim();
|
|
224
|
-
}
|
|
225
|
-
function truncateText(text, maxLen = 140) {
|
|
226
|
-
if (text.length <= maxLen) return text;
|
|
227
|
-
return `${text.slice(0, maxLen - 3)}...`;
|
|
228
|
-
}
|
|
229
|
-
function hasModifier(node, kind) {
|
|
230
|
-
if (!ts.canHaveModifiers(node)) return false;
|
|
231
|
-
const mods = ts.getModifiers(node);
|
|
232
|
-
return mods ? mods.some((mod) => mod.kind === kind) : false;
|
|
233
|
-
}
|
|
234
|
-
function isFunctionLikeNode(node) {
|
|
235
|
-
return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node);
|
|
236
|
-
}
|
|
237
|
-
function collectBindingNames(binding, out) {
|
|
238
|
-
if (ts.isIdentifier(binding)) {
|
|
239
|
-
out.add(binding.text);
|
|
240
|
-
} else if (ts.isObjectBindingPattern(binding) || ts.isArrayBindingPattern(binding)) {
|
|
241
|
-
for (const elem of binding.elements) {
|
|
242
|
-
if (ts.isBindingElement(elem)) {
|
|
243
|
-
collectBindingNames(elem.name, out);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
function collectFunctionScopeBindings(fn, out) {
|
|
249
|
-
if (fn.name && ts.isIdentifier(fn.name)) {
|
|
250
|
-
out.add(fn.name.text);
|
|
251
|
-
}
|
|
252
|
-
if (fn.typeParameters) {
|
|
253
|
-
for (const tp of fn.typeParameters) {
|
|
254
|
-
out.add(tp.name.text);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
for (const param of fn.parameters) {
|
|
258
|
-
collectBindingNames(param.name, out);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
function collectHoistedVarDeclarations(node, out) {
|
|
262
|
-
const walk = (curr) => {
|
|
263
|
-
if (isFunctionLikeNode(curr)) return;
|
|
264
|
-
if (ts.isVariableDeclarationList(curr)) {
|
|
265
|
-
const isBlockScoped = (curr.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let)) !== 0;
|
|
266
|
-
if (!isBlockScoped) {
|
|
267
|
-
for (const decl of curr.declarations) {
|
|
268
|
-
collectBindingNames(decl.name, out);
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
ts.forEachChild(curr, walk);
|
|
273
|
-
};
|
|
274
|
-
ts.forEachChild(node, walk);
|
|
275
|
-
}
|
|
276
|
-
function collectDirectStatementLocals(statements, out) {
|
|
277
|
-
for (const stmt of statements) {
|
|
278
|
-
if (ts.isVariableStatement(stmt)) {
|
|
279
|
-
for (const decl of stmt.declarationList.declarations) {
|
|
280
|
-
collectBindingNames(decl.name, out);
|
|
281
|
-
}
|
|
282
|
-
} else if (ts.isFunctionDeclaration(stmt) && stmt.name) {
|
|
283
|
-
out.add(stmt.name.text);
|
|
284
|
-
} else if (ts.isClassDeclaration(stmt) && stmt.name) {
|
|
285
|
-
out.add(stmt.name.text);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
function classifyIdentifierRole(curr, parent) {
|
|
290
|
-
if (!parent) return "variable";
|
|
291
|
-
if (ts.isPropertyAccessExpression(parent) && parent.name === curr) return "property";
|
|
292
|
-
if (ts.isQualifiedName(parent) && parent.right === curr) return "property";
|
|
293
|
-
if (ts.isBindingElement(parent) && parent.propertyName === curr) return "object_key";
|
|
294
|
-
if (ts.isPropertyAssignment(parent) && parent.name === curr) return "object_key";
|
|
295
|
-
if (ts.isPropertySignature(parent) && parent.name === curr) return "object_key";
|
|
296
|
-
if (ts.isMethodDeclaration(parent) && parent.name === curr) return "object_key";
|
|
297
|
-
if (ts.isMethodSignature(parent) && parent.name === curr) return "object_key";
|
|
298
|
-
if (ts.isGetAccessorDeclaration(parent) && parent.name === curr) return "object_key";
|
|
299
|
-
if (ts.isSetAccessorDeclaration(parent) && parent.name === curr) return "object_key";
|
|
300
|
-
if (ts.isPropertyDeclaration(parent) && parent.name === curr) return "object_key";
|
|
301
|
-
if (ts.isJsxAttribute(parent) && parent.name === curr) return "object_key";
|
|
302
|
-
if ((ts.isLabeledStatement(parent) || ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === curr) {
|
|
303
|
-
return "property";
|
|
304
|
-
}
|
|
305
|
-
if (ts.isParameter(parent) && parent.name === curr || ts.isVariableDeclaration(parent) && parent.name === curr || ts.isBindingElement(parent) && parent.name === curr || ts.isFunctionDeclaration(parent) && parent.name === curr || ts.isFunctionExpression(parent) && parent.name === curr || ts.isClassDeclaration(parent) && parent.name === curr || ts.isClassExpression(parent) && parent.name === curr || ts.isTypeParameterDeclaration(parent) && parent.name === curr) {
|
|
306
|
-
return "declaration";
|
|
307
|
-
}
|
|
308
|
-
return "variable";
|
|
309
|
-
}
|
|
310
|
-
function collectModuleLocalDeclarations(sourceFile) {
|
|
311
|
-
const decls = /* @__PURE__ */ new Set();
|
|
312
|
-
for (const stmt of sourceFile.statements) {
|
|
313
|
-
if (ts.isVariableStatement(stmt)) {
|
|
314
|
-
for (const decl of stmt.declarationList.declarations) {
|
|
315
|
-
collectBindingNames(decl.name, decls);
|
|
316
|
-
}
|
|
317
|
-
} else if (ts.isFunctionDeclaration(stmt) && stmt.name) {
|
|
318
|
-
decls.add(stmt.name.text);
|
|
319
|
-
} else if (ts.isClassDeclaration(stmt) && stmt.name) {
|
|
320
|
-
decls.add(stmt.name.text);
|
|
321
|
-
} else if (ts.isEnumDeclaration(stmt)) {
|
|
322
|
-
decls.add(stmt.name.text);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
return decls;
|
|
326
|
-
}
|
|
327
|
-
function computeStructuralHashWithCount(node, sourceFile, options) {
|
|
328
|
-
const target = ts.isVariableDeclaration(node) && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer)) ? node.initializer : node;
|
|
329
|
-
const normalizedFilePath = normalizeRelPath(options?.filePath ?? sourceFile.fileName);
|
|
330
|
-
const moduleLocalDecls = options?.moduleLocalDecls ?? collectModuleLocalDeclarations(sourceFile);
|
|
331
|
-
const tokens = [];
|
|
332
|
-
let nodeCount = 0;
|
|
333
|
-
let astNodeCount = 0;
|
|
334
|
-
const visit = (curr, countAsBody, scope, parent) => {
|
|
335
|
-
nodeCount += 1;
|
|
336
|
-
if (countAsBody) {
|
|
337
|
-
astNodeCount += 1;
|
|
338
|
-
}
|
|
339
|
-
tokens.push(`K:${curr.kind}`);
|
|
340
|
-
let childScope = scope;
|
|
341
|
-
if (ts.isPropertyAccessExpression(curr)) {
|
|
342
|
-
tokens.push(`PROP:${curr.name.text}`);
|
|
343
|
-
} else if (ts.isStringLiteral(curr) || ts.isNoSubstitutionTemplateLiteral(curr)) {
|
|
344
|
-
tokens.push(`STR:${curr.text}`);
|
|
345
|
-
} else if (ts.isTemplateExpression(curr)) {
|
|
346
|
-
tokens.push(`TPL_H:${curr.head.text}`);
|
|
347
|
-
for (const span of curr.templateSpans) {
|
|
348
|
-
tokens.push(`TPL_M:${span.literal.text}`);
|
|
349
|
-
}
|
|
350
|
-
} else if (ts.isNumericLiteral(curr)) {
|
|
351
|
-
tokens.push(`NUM:${curr.text}`);
|
|
352
|
-
} else if (ts.isRegularExpressionLiteral(curr)) {
|
|
353
|
-
tokens.push(`REGEX:${curr.text}`);
|
|
354
|
-
} else if (ts.isBinaryExpression(curr)) {
|
|
355
|
-
tokens.push(`OP:${curr.operatorToken.kind}`);
|
|
356
|
-
} else if (ts.isPrefixUnaryExpression(curr)) {
|
|
357
|
-
tokens.push(`PRE:${curr.operator}`);
|
|
358
|
-
} else if (ts.isPostfixUnaryExpression(curr)) {
|
|
359
|
-
tokens.push(`POST:${curr.operator}`);
|
|
360
|
-
} else if (ts.isVariableDeclarationList(curr)) {
|
|
361
|
-
const declFlag = curr.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let);
|
|
362
|
-
tokens.push(`VF:${declFlag}`);
|
|
363
|
-
} else if (ts.isIdentifier(curr)) {
|
|
364
|
-
const role = classifyIdentifierRole(curr, parent);
|
|
365
|
-
if (role === "declaration") {
|
|
366
|
-
tokens.push("ID:$L");
|
|
367
|
-
} else if (role === "object_key") {
|
|
368
|
-
tokens.push(`KEY:${curr.text}`);
|
|
369
|
-
} else if (role === "variable") {
|
|
370
|
-
if (scope.has(curr.text)) {
|
|
371
|
-
tokens.push("ID:$L");
|
|
372
|
-
} else if (moduleLocalDecls.has(curr.text)) {
|
|
373
|
-
tokens.push(`STATE:${normalizedFilePath}:${curr.text}`);
|
|
374
|
-
} else {
|
|
375
|
-
tokens.push(`EXT:${curr.text}`);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
if (curr !== target && isFunctionLikeNode(curr)) {
|
|
380
|
-
const next = new Set(scope);
|
|
381
|
-
collectFunctionScopeBindings(curr, next);
|
|
382
|
-
if (curr.body) {
|
|
383
|
-
collectHoistedVarDeclarations(curr.body, next);
|
|
384
|
-
}
|
|
385
|
-
childScope = next;
|
|
386
|
-
} else if (ts.isBlock(curr)) {
|
|
387
|
-
const next = new Set(scope);
|
|
388
|
-
collectDirectStatementLocals(curr.statements, next);
|
|
389
|
-
childScope = next;
|
|
390
|
-
} else if (ts.isCaseClause(curr) || ts.isDefaultClause(curr)) {
|
|
391
|
-
const next = new Set(scope);
|
|
392
|
-
collectDirectStatementLocals(curr.statements, next);
|
|
393
|
-
childScope = next;
|
|
394
|
-
} else if (ts.isForStatement(curr) || ts.isForInStatement(curr) || ts.isForOfStatement(curr)) {
|
|
395
|
-
if (curr.initializer && ts.isVariableDeclarationList(curr.initializer)) {
|
|
396
|
-
const next = new Set(scope);
|
|
397
|
-
for (const decl of curr.initializer.declarations) {
|
|
398
|
-
collectBindingNames(decl.name, next);
|
|
399
|
-
}
|
|
400
|
-
childScope = next;
|
|
401
|
-
}
|
|
402
|
-
} else if (ts.isCatchClause(curr) && curr.variableDeclaration) {
|
|
403
|
-
const next = new Set(scope);
|
|
404
|
-
collectBindingNames(curr.variableDeclaration.name, next);
|
|
405
|
-
childScope = next;
|
|
406
|
-
}
|
|
407
|
-
ts.forEachChild(curr, (child) => visit(child, countAsBody, childScope, curr));
|
|
408
|
-
};
|
|
409
|
-
if (isFunctionLikeNode(target)) {
|
|
410
|
-
const rootScope = /* @__PURE__ */ new Set();
|
|
411
|
-
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
|
|
412
|
-
rootScope.add(node.name.text);
|
|
413
|
-
}
|
|
414
|
-
collectFunctionScopeBindings(target, rootScope);
|
|
415
|
-
if (target.body) {
|
|
416
|
-
collectHoistedVarDeclarations(target.body, rootScope);
|
|
417
|
-
}
|
|
418
|
-
tokens.push("FN");
|
|
419
|
-
if (hasModifier(target, ts.SyntaxKind.AsyncKeyword)) {
|
|
420
|
-
tokens.push("MOD:ASYNC");
|
|
421
|
-
}
|
|
422
|
-
if (target.asteriskToken) {
|
|
423
|
-
tokens.push("MOD:GEN");
|
|
424
|
-
}
|
|
425
|
-
for (const param of target.parameters) {
|
|
426
|
-
visit(param, false, rootScope, target);
|
|
427
|
-
}
|
|
428
|
-
if (target.body) {
|
|
429
|
-
visit(target.body, true, rootScope, target);
|
|
430
|
-
}
|
|
431
|
-
} else {
|
|
432
|
-
visit(target, true, /* @__PURE__ */ new Set(), void 0);
|
|
433
|
-
}
|
|
434
|
-
const structuralHash = createHash("sha256").update(tokens.join("|"), "utf8").digest("hex").slice(0, 16);
|
|
435
|
-
return { structuralHash, nodeCount, astNodeCount };
|
|
436
|
-
}
|
|
437
|
-
function formatFunctionSignature(node, sourceFile) {
|
|
438
|
-
const isAsync = hasModifier(node, ts.SyntaxKind.AsyncKeyword);
|
|
439
|
-
const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
|
|
440
|
-
const params = node.parameters.map((param) => collapseWhitespace(param.getText(sourceFile))).join(", ");
|
|
441
|
-
const returnType = node.type ? `: ${collapseWhitespace(node.type.getText(sourceFile))}` : "";
|
|
442
|
-
const prefix = isAsync ? "async " : "";
|
|
443
|
-
return truncateText(`${prefix}${typeParams}(${params})${returnType}`);
|
|
444
|
-
}
|
|
445
|
-
function formatConstSummary(decl, sourceFile) {
|
|
446
|
-
if (decl.type) {
|
|
447
|
-
return truncateText(`: ${collapseWhitespace(decl.type.getText(sourceFile))}`);
|
|
448
|
-
}
|
|
449
|
-
const init = decl.initializer;
|
|
450
|
-
if (!init) return ": unknown";
|
|
451
|
-
if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {
|
|
452
|
-
return ": string";
|
|
453
|
-
}
|
|
454
|
-
if (ts.isNumericLiteral(init)) {
|
|
455
|
-
return `= ${init.text}`;
|
|
456
|
-
}
|
|
457
|
-
if (init.kind === ts.SyntaxKind.TrueKeyword) return "= true";
|
|
458
|
-
if (init.kind === ts.SyntaxKind.FalseKeyword) return "= false";
|
|
459
|
-
if (init.kind === ts.SyntaxKind.NullKeyword) return "= null";
|
|
460
|
-
if (ts.isNewExpression(init)) {
|
|
461
|
-
const className = collapseWhitespace(init.expression.getText(sourceFile));
|
|
462
|
-
return truncateText(`= new ${className}(...)`, 80);
|
|
463
|
-
}
|
|
464
|
-
if (ts.isObjectLiteralExpression(init)) {
|
|
465
|
-
const keys = init.properties.slice(0, 5).map((prop) => {
|
|
466
|
-
if (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) {
|
|
467
|
-
return prop.name.getText(sourceFile);
|
|
468
|
-
}
|
|
469
|
-
return "...";
|
|
470
|
-
});
|
|
471
|
-
const suffix = init.properties.length > 5 ? ", ..." : "";
|
|
472
|
-
return truncateText(`= { ${keys.join(", ")}${suffix} }`, 100);
|
|
473
|
-
}
|
|
474
|
-
if (ts.isArrayLiteralExpression(init)) {
|
|
475
|
-
return `= Array(${init.elements.length})`;
|
|
476
|
-
}
|
|
477
|
-
return "= <expr>";
|
|
478
|
-
}
|
|
479
|
-
function formatClassSignature(node, sourceFile) {
|
|
480
|
-
const name = node.name?.text ?? "default";
|
|
481
|
-
const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
|
|
482
|
-
const heritage = node.heritageClauses && node.heritageClauses.length > 0 ? ` ${node.heritageClauses.map((clause) => collapseWhitespace(clause.getText(sourceFile))).join(" ")}` : "";
|
|
483
|
-
return truncateText(`class ${name}${typeParams}${heritage}`);
|
|
484
|
-
}
|
|
485
|
-
function formatInterfaceSignature(node, sourceFile) {
|
|
486
|
-
const name = node.name.text;
|
|
487
|
-
const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
|
|
488
|
-
const heritage = node.heritageClauses && node.heritageClauses.length > 0 ? ` ${node.heritageClauses.map((clause) => collapseWhitespace(clause.getText(sourceFile))).join(" ")}` : "";
|
|
489
|
-
const members = node.members.slice(0, 6).map((member) => collapseWhitespace(member.getText(sourceFile)).replace(/;$/, ""));
|
|
490
|
-
const more = node.members.length > 6 ? "; ..." : "";
|
|
491
|
-
return truncateText(`interface ${name}${typeParams}${heritage} { ${members.join("; ")}${more} }`, 160);
|
|
492
|
-
}
|
|
493
|
-
function formatTypeAliasSignature(node, sourceFile) {
|
|
494
|
-
const name = node.name.text;
|
|
495
|
-
const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
|
|
496
|
-
const rhs = collapseWhitespace(node.type.getText(sourceFile));
|
|
497
|
-
return truncateText(`type ${name}${typeParams} = ${rhs}`, 160);
|
|
498
|
-
}
|
|
499
|
-
function formatEnumSignature(node, sourceFile) {
|
|
500
|
-
const members = node.members.slice(0, 8).map((member) => collapseWhitespace(member.name.getText(sourceFile)));
|
|
501
|
-
const more = node.members.length > 8 ? ", ..." : "";
|
|
502
|
-
return truncateText(`enum ${node.name.text} { ${members.join(", ")}${more} }`, 140);
|
|
503
|
-
}
|
|
504
|
-
function lineNumberOf(node, sourceFile) {
|
|
505
|
-
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
506
|
-
}
|
|
507
|
-
function endLineNumberOf(node, sourceFile) {
|
|
508
|
-
const start = node.getStart(sourceFile);
|
|
509
|
-
const pos = Math.max(start, node.getEnd() - 1);
|
|
510
|
-
return sourceFile.getLineAndCharacterOfPosition(pos).line + 1;
|
|
511
|
-
}
|
|
512
|
-
function countFunctionStatements(node) {
|
|
513
|
-
if (!node.body) return 0;
|
|
514
|
-
if (!ts.isBlock(node.body)) return 1;
|
|
515
|
-
let count = 0;
|
|
516
|
-
const countBlock = (block) => {
|
|
517
|
-
for (const s of block.statements) {
|
|
518
|
-
count += 1;
|
|
519
|
-
if (ts.isIfStatement(s)) {
|
|
520
|
-
if (ts.isBlock(s.thenStatement)) countBlock(s.thenStatement);
|
|
521
|
-
else count += 1;
|
|
522
|
-
if (s.elseStatement) {
|
|
523
|
-
if (ts.isBlock(s.elseStatement)) countBlock(s.elseStatement);
|
|
524
|
-
else if (!ts.isIfStatement(s.elseStatement)) count += 1;
|
|
525
|
-
}
|
|
526
|
-
} else if (ts.isTryStatement(s)) {
|
|
527
|
-
countBlock(s.tryBlock);
|
|
528
|
-
if (s.catchClause) countBlock(s.catchClause.block);
|
|
529
|
-
if (s.finallyBlock) countBlock(s.finallyBlock);
|
|
530
|
-
} else if (ts.isForStatement(s) || ts.isForInStatement(s) || ts.isForOfStatement(s) || ts.isWhileStatement(s) || ts.isDoStatement(s)) {
|
|
531
|
-
if (ts.isBlock(s.statement)) countBlock(s.statement);
|
|
532
|
-
else count += 1;
|
|
533
|
-
} else if (ts.isSwitchStatement(s)) {
|
|
534
|
-
for (const clause of s.caseBlock.clauses) {
|
|
535
|
-
count += clause.statements.length;
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
|
-
countBlock(node.body);
|
|
541
|
-
return count;
|
|
542
|
-
}
|
|
543
|
-
function pushImportRef(refs, keyMap, rawSpecifier, importedNames, isReExport, isTypeOnly, isDynamic = false, line) {
|
|
544
|
-
const trimmed = rawSpecifier.trim();
|
|
545
|
-
if (!trimmed) return;
|
|
546
|
-
const dedupKey = `${trimmed}\0${isReExport ? "1" : "0"}\0${isTypeOnly ? "1" : "0"}\0${isDynamic ? "1" : "0"}`;
|
|
547
|
-
const existing = keyMap.get(dedupKey);
|
|
548
|
-
if (existing) {
|
|
549
|
-
for (const name of importedNames) {
|
|
550
|
-
if (!existing.importedNames.includes(name)) {
|
|
551
|
-
existing.importedNames.push(name);
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
if (line !== void 0) {
|
|
555
|
-
existing.line = existing.line !== void 0 ? Math.min(existing.line, line) : line;
|
|
556
|
-
}
|
|
557
|
-
return;
|
|
558
|
-
}
|
|
559
|
-
const entry = {
|
|
560
|
-
rawSpecifier: trimmed,
|
|
561
|
-
importedNames: [...new Set(importedNames)],
|
|
562
|
-
isReExport,
|
|
563
|
-
isTypeOnly,
|
|
564
|
-
...isDynamic ? { isDynamic: true } : {},
|
|
565
|
-
...line !== void 0 ? { line } : {}
|
|
566
|
-
};
|
|
567
|
-
keyMap.set(dedupKey, entry);
|
|
568
|
-
refs.push(entry);
|
|
569
|
-
}
|
|
570
|
-
function extractImports(sourceFile) {
|
|
571
|
-
const refs = [];
|
|
572
|
-
const keyMap = /* @__PURE__ */ new Map();
|
|
573
|
-
const visit = (node) => {
|
|
574
|
-
if (ts.isImportDeclaration(node)) {
|
|
575
|
-
if (ts.isStringLiteral(node.moduleSpecifier)) {
|
|
576
|
-
const names = [];
|
|
577
|
-
const clause = node.importClause;
|
|
578
|
-
const allNamedTypeOnly = Boolean(
|
|
579
|
-
clause && !clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings) && clause.namedBindings.elements.length > 0 && clause.namedBindings.elements.every((elem) => elem.isTypeOnly)
|
|
580
|
-
);
|
|
581
|
-
const isTypeOnly = Boolean(clause?.isTypeOnly) || allNamedTypeOnly;
|
|
582
|
-
if (clause) {
|
|
583
|
-
if (clause.name) names.push("default");
|
|
584
|
-
if (clause.namedBindings) {
|
|
585
|
-
if (ts.isNamespaceImport(clause.namedBindings)) {
|
|
586
|
-
names.push("*");
|
|
587
|
-
} else if (ts.isNamedImports(clause.namedBindings)) {
|
|
588
|
-
for (const elem of clause.namedBindings.elements) {
|
|
589
|
-
names.push((elem.propertyName ?? elem.name).text);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
pushImportRef(
|
|
595
|
-
refs,
|
|
596
|
-
keyMap,
|
|
597
|
-
node.moduleSpecifier.text,
|
|
598
|
-
names,
|
|
599
|
-
false,
|
|
600
|
-
isTypeOnly,
|
|
601
|
-
false,
|
|
602
|
-
lineNumberOf(node, sourceFile)
|
|
603
|
-
);
|
|
604
|
-
}
|
|
605
|
-
} else if (ts.isExportDeclaration(node)) {
|
|
606
|
-
if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
607
|
-
const names = [];
|
|
608
|
-
const allNamedTypeOnly = Boolean(
|
|
609
|
-
node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements.length > 0 && node.exportClause.elements.every((elem) => elem.isTypeOnly)
|
|
610
|
-
);
|
|
611
|
-
const isTypeOnly = Boolean(node.isTypeOnly) || allNamedTypeOnly;
|
|
612
|
-
if (!node.exportClause) {
|
|
613
|
-
if (!isTypeOnly) {
|
|
614
|
-
names.push("*");
|
|
615
|
-
}
|
|
616
|
-
} else if (ts.isNamespaceExport(node.exportClause)) {
|
|
617
|
-
names.push("*");
|
|
618
|
-
} else if (ts.isNamedExports(node.exportClause)) {
|
|
619
|
-
for (const elem of node.exportClause.elements) {
|
|
620
|
-
names.push((elem.propertyName ?? elem.name).text);
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
pushImportRef(
|
|
624
|
-
refs,
|
|
625
|
-
keyMap,
|
|
626
|
-
node.moduleSpecifier.text,
|
|
627
|
-
names,
|
|
628
|
-
true,
|
|
629
|
-
isTypeOnly,
|
|
630
|
-
false,
|
|
631
|
-
lineNumberOf(node, sourceFile)
|
|
632
|
-
);
|
|
633
|
-
}
|
|
634
|
-
} else if (ts.isImportEqualsDeclaration(node)) {
|
|
635
|
-
if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) {
|
|
636
|
-
pushImportRef(
|
|
637
|
-
refs,
|
|
638
|
-
keyMap,
|
|
639
|
-
node.moduleReference.expression.text,
|
|
640
|
-
[node.name.text],
|
|
641
|
-
false,
|
|
642
|
-
false,
|
|
643
|
-
false,
|
|
644
|
-
lineNumberOf(node, sourceFile)
|
|
645
|
-
);
|
|
646
|
-
}
|
|
647
|
-
} else if (ts.isCallExpression(node)) {
|
|
648
|
-
const first = node.arguments[0];
|
|
649
|
-
if (first && ts.isStringLiteralLike(first)) {
|
|
650
|
-
const callee = node.expression;
|
|
651
|
-
if (callee.kind === ts.SyntaxKind.ImportKeyword) {
|
|
652
|
-
pushImportRef(
|
|
653
|
-
refs,
|
|
654
|
-
keyMap,
|
|
655
|
-
first.text,
|
|
656
|
-
[],
|
|
657
|
-
false,
|
|
658
|
-
false,
|
|
659
|
-
true,
|
|
660
|
-
lineNumberOf(node, sourceFile)
|
|
661
|
-
);
|
|
662
|
-
} else if (ts.isIdentifier(callee) && callee.text === "require") {
|
|
663
|
-
pushImportRef(
|
|
664
|
-
refs,
|
|
665
|
-
keyMap,
|
|
666
|
-
first.text,
|
|
667
|
-
[],
|
|
668
|
-
false,
|
|
669
|
-
false,
|
|
670
|
-
false,
|
|
671
|
-
lineNumberOf(node, sourceFile)
|
|
672
|
-
);
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
} else if (ts.isImportTypeNode(node)) {
|
|
676
|
-
const argument = node.argument;
|
|
677
|
-
if (ts.isLiteralTypeNode(argument) && ts.isStringLiteral(argument.literal)) {
|
|
678
|
-
const names = node.qualifier ? [collapseWhitespace(node.qualifier.getText(sourceFile))] : [];
|
|
679
|
-
pushImportRef(
|
|
680
|
-
refs,
|
|
681
|
-
keyMap,
|
|
682
|
-
argument.literal.text,
|
|
683
|
-
names,
|
|
684
|
-
false,
|
|
685
|
-
true,
|
|
686
|
-
false,
|
|
687
|
-
lineNumberOf(node, sourceFile)
|
|
688
|
-
);
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
ts.forEachChild(node, visit);
|
|
692
|
-
};
|
|
693
|
-
visit(sourceFile);
|
|
694
|
-
return refs;
|
|
695
|
-
}
|
|
696
|
-
function extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size) {
|
|
697
|
-
const rel = toPosix(relativePath ?? absolutePath);
|
|
698
|
-
const contentSha256 = createHash("sha256").update(source, "utf8").digest("hex");
|
|
699
|
-
const sourceFile = ts.createSourceFile(
|
|
700
|
-
absolutePath,
|
|
701
|
-
source,
|
|
702
|
-
ts.ScriptTarget.Latest,
|
|
703
|
-
true,
|
|
704
|
-
scriptKindFor(absolutePath)
|
|
705
|
-
);
|
|
706
|
-
const imports = extractImports(sourceFile);
|
|
707
|
-
const moduleLocalDecls = collectModuleLocalDeclarations(sourceFile);
|
|
708
|
-
const hashOptions = { filePath: rel, moduleLocalDecls };
|
|
709
|
-
const localDecls = /* @__PURE__ */ new Map();
|
|
710
|
-
const exportedSymbols = [];
|
|
711
|
-
const internalFunctions = [];
|
|
712
|
-
const exportedLocalNames = /* @__PURE__ */ new Set();
|
|
713
|
-
const seenExportedKeys = /* @__PURE__ */ new Set();
|
|
714
|
-
const addExported = (sym) => {
|
|
715
|
-
const key = `${sym.name}\0${sym.kind}\0${sym.line}`;
|
|
716
|
-
if (seenExportedKeys.has(key)) return;
|
|
717
|
-
seenExportedKeys.add(key);
|
|
718
|
-
exportedSymbols.push(sym);
|
|
719
|
-
};
|
|
720
|
-
for (const stmt of sourceFile.statements) {
|
|
721
|
-
const isExport = hasModifier(stmt, ts.SyntaxKind.ExportKeyword);
|
|
722
|
-
const isDefault = hasModifier(stmt, ts.SyntaxKind.DefaultKeyword);
|
|
723
|
-
if (ts.isFunctionDeclaration(stmt)) {
|
|
724
|
-
if (!stmt.body) continue;
|
|
725
|
-
const declName = stmt.name?.text;
|
|
726
|
-
const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
|
|
727
|
-
stmt,
|
|
728
|
-
sourceFile,
|
|
729
|
-
hashOptions
|
|
730
|
-
);
|
|
731
|
-
const signature = formatFunctionSignature(stmt, sourceFile);
|
|
732
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
733
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
734
|
-
const statementCount = countFunctionStatements(stmt);
|
|
735
|
-
if (declName) {
|
|
736
|
-
localDecls.set(declName, {
|
|
737
|
-
name: declName,
|
|
738
|
-
kind: "function",
|
|
739
|
-
signature,
|
|
740
|
-
line,
|
|
741
|
-
endLine,
|
|
742
|
-
structuralHash,
|
|
743
|
-
nodeCount,
|
|
744
|
-
astNodeCount,
|
|
745
|
-
statementCount,
|
|
746
|
-
isFunctionHelper: true,
|
|
747
|
-
exportedDirectly: isExport,
|
|
748
|
-
exportedDefaultDirectly: isExport && isDefault
|
|
749
|
-
});
|
|
750
|
-
}
|
|
751
|
-
if (isExport) {
|
|
752
|
-
const exportName = isDefault ? "default" : declName;
|
|
753
|
-
if (exportName) {
|
|
754
|
-
addExported({
|
|
755
|
-
name: exportName,
|
|
756
|
-
...isDefault && declName ? { localName: declName } : {},
|
|
757
|
-
kind: "function",
|
|
758
|
-
signature,
|
|
759
|
-
line,
|
|
760
|
-
endLine,
|
|
761
|
-
structuralHash,
|
|
762
|
-
nodeCount,
|
|
763
|
-
astNodeCount,
|
|
764
|
-
statementCount,
|
|
765
|
-
file: rel,
|
|
766
|
-
isExported: true
|
|
767
|
-
});
|
|
768
|
-
if (declName) exportedLocalNames.add(declName);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
} else if (ts.isVariableStatement(stmt)) {
|
|
772
|
-
for (const decl of stmt.declarationList.declarations) {
|
|
773
|
-
if (!ts.isIdentifier(decl.name)) continue;
|
|
774
|
-
const declName = decl.name.text;
|
|
775
|
-
const line = lineNumberOf(decl, sourceFile);
|
|
776
|
-
const endLine = endLineNumberOf(decl, sourceFile);
|
|
777
|
-
const init = decl.initializer;
|
|
778
|
-
if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
|
|
779
|
-
const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
|
|
780
|
-
decl,
|
|
781
|
-
sourceFile,
|
|
782
|
-
hashOptions
|
|
783
|
-
);
|
|
784
|
-
const signature = formatFunctionSignature(init, sourceFile);
|
|
785
|
-
const statementCount = countFunctionStatements(init);
|
|
786
|
-
localDecls.set(declName, {
|
|
787
|
-
name: declName,
|
|
788
|
-
kind: "function",
|
|
789
|
-
signature,
|
|
790
|
-
line,
|
|
791
|
-
endLine,
|
|
792
|
-
structuralHash,
|
|
793
|
-
nodeCount,
|
|
794
|
-
astNodeCount,
|
|
795
|
-
statementCount,
|
|
796
|
-
isFunctionHelper: true,
|
|
797
|
-
exportedDirectly: isExport,
|
|
798
|
-
exportedDefaultDirectly: false
|
|
799
|
-
});
|
|
800
|
-
if (isExport) {
|
|
801
|
-
addExported({
|
|
802
|
-
name: declName,
|
|
803
|
-
kind: "function",
|
|
804
|
-
signature,
|
|
805
|
-
line,
|
|
806
|
-
endLine,
|
|
807
|
-
structuralHash,
|
|
808
|
-
nodeCount,
|
|
809
|
-
astNodeCount,
|
|
810
|
-
statementCount,
|
|
811
|
-
file: rel,
|
|
812
|
-
isExported: true
|
|
813
|
-
});
|
|
814
|
-
exportedLocalNames.add(declName);
|
|
815
|
-
}
|
|
816
|
-
} else {
|
|
817
|
-
const signature = formatConstSummary(decl, sourceFile);
|
|
818
|
-
localDecls.set(declName, {
|
|
819
|
-
name: declName,
|
|
820
|
-
kind: "const",
|
|
821
|
-
signature,
|
|
822
|
-
line,
|
|
823
|
-
endLine,
|
|
824
|
-
isFunctionHelper: false,
|
|
825
|
-
exportedDirectly: isExport,
|
|
826
|
-
exportedDefaultDirectly: false
|
|
827
|
-
});
|
|
828
|
-
if (isExport) {
|
|
829
|
-
addExported({
|
|
830
|
-
name: declName,
|
|
831
|
-
kind: "const",
|
|
832
|
-
signature,
|
|
833
|
-
line,
|
|
834
|
-
endLine,
|
|
835
|
-
file: rel,
|
|
836
|
-
isExported: true
|
|
837
|
-
});
|
|
838
|
-
exportedLocalNames.add(declName);
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
} else if (ts.isClassDeclaration(stmt)) {
|
|
843
|
-
const declName = stmt.name?.text;
|
|
844
|
-
const signature = formatClassSignature(stmt, sourceFile);
|
|
845
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
846
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
847
|
-
if (declName) {
|
|
848
|
-
localDecls.set(declName, {
|
|
849
|
-
name: declName,
|
|
850
|
-
kind: "class",
|
|
851
|
-
signature,
|
|
852
|
-
line,
|
|
853
|
-
endLine,
|
|
854
|
-
isFunctionHelper: false,
|
|
855
|
-
exportedDirectly: isExport,
|
|
856
|
-
exportedDefaultDirectly: isExport && isDefault
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
if (isExport) {
|
|
860
|
-
const exportName = isDefault ? "default" : declName;
|
|
861
|
-
if (exportName) {
|
|
862
|
-
addExported({
|
|
863
|
-
name: exportName,
|
|
864
|
-
...isDefault && declName ? { localName: declName } : {},
|
|
865
|
-
kind: "class",
|
|
866
|
-
signature,
|
|
867
|
-
line,
|
|
868
|
-
endLine,
|
|
869
|
-
file: rel,
|
|
870
|
-
isExported: true
|
|
871
|
-
});
|
|
872
|
-
if (declName) exportedLocalNames.add(declName);
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
} else if (ts.isInterfaceDeclaration(stmt)) {
|
|
876
|
-
const declName = stmt.name.text;
|
|
877
|
-
const signature = formatInterfaceSignature(stmt, sourceFile);
|
|
878
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
879
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
880
|
-
localDecls.set(declName, {
|
|
881
|
-
name: declName,
|
|
882
|
-
kind: "interface",
|
|
883
|
-
signature,
|
|
884
|
-
line,
|
|
885
|
-
endLine,
|
|
886
|
-
isFunctionHelper: false,
|
|
887
|
-
exportedDirectly: isExport,
|
|
888
|
-
exportedDefaultDirectly: false
|
|
889
|
-
});
|
|
890
|
-
if (isExport) {
|
|
891
|
-
addExported({
|
|
892
|
-
name: declName,
|
|
893
|
-
kind: "interface",
|
|
894
|
-
signature,
|
|
895
|
-
line,
|
|
896
|
-
endLine,
|
|
897
|
-
file: rel,
|
|
898
|
-
isExported: true
|
|
899
|
-
});
|
|
900
|
-
exportedLocalNames.add(declName);
|
|
901
|
-
}
|
|
902
|
-
} else if (ts.isTypeAliasDeclaration(stmt)) {
|
|
903
|
-
const declName = stmt.name.text;
|
|
904
|
-
const signature = formatTypeAliasSignature(stmt, sourceFile);
|
|
905
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
906
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
907
|
-
localDecls.set(declName, {
|
|
908
|
-
name: declName,
|
|
909
|
-
kind: "type",
|
|
910
|
-
signature,
|
|
911
|
-
line,
|
|
912
|
-
endLine,
|
|
913
|
-
isFunctionHelper: false,
|
|
914
|
-
exportedDirectly: isExport,
|
|
915
|
-
exportedDefaultDirectly: false
|
|
916
|
-
});
|
|
917
|
-
if (isExport) {
|
|
918
|
-
addExported({
|
|
919
|
-
name: declName,
|
|
920
|
-
kind: "type",
|
|
921
|
-
signature,
|
|
922
|
-
line,
|
|
923
|
-
endLine,
|
|
924
|
-
file: rel,
|
|
925
|
-
isExported: true
|
|
926
|
-
});
|
|
927
|
-
exportedLocalNames.add(declName);
|
|
928
|
-
}
|
|
929
|
-
} else if (ts.isEnumDeclaration(stmt)) {
|
|
930
|
-
const declName = stmt.name.text;
|
|
931
|
-
const signature = formatEnumSignature(stmt, sourceFile);
|
|
932
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
933
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
934
|
-
localDecls.set(declName, {
|
|
935
|
-
name: declName,
|
|
936
|
-
kind: "enum",
|
|
937
|
-
signature,
|
|
938
|
-
line,
|
|
939
|
-
endLine,
|
|
940
|
-
isFunctionHelper: false,
|
|
941
|
-
exportedDirectly: isExport,
|
|
942
|
-
exportedDefaultDirectly: false
|
|
943
|
-
});
|
|
944
|
-
if (isExport) {
|
|
945
|
-
addExported({
|
|
946
|
-
name: declName,
|
|
947
|
-
kind: "enum",
|
|
948
|
-
signature,
|
|
949
|
-
line,
|
|
950
|
-
endLine,
|
|
951
|
-
file: rel,
|
|
952
|
-
isExported: true
|
|
953
|
-
});
|
|
954
|
-
exportedLocalNames.add(declName);
|
|
955
|
-
}
|
|
956
|
-
} else if (ts.isExportDeclaration(stmt)) {
|
|
957
|
-
if (stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier)) {
|
|
958
|
-
if (!stmt.isTypeOnly && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
|
|
959
|
-
for (const elem of stmt.exportClause.elements) {
|
|
960
|
-
if (elem.isTypeOnly) continue;
|
|
961
|
-
const localName = (elem.propertyName ?? elem.name).text;
|
|
962
|
-
const exportedName = elem.name.text;
|
|
963
|
-
addExported({
|
|
964
|
-
name: exportedName,
|
|
965
|
-
...exportedName !== localName ? { localName } : {},
|
|
966
|
-
kind: "const",
|
|
967
|
-
signature: `export { ${localName} } from '${stmt.moduleSpecifier.text}'`,
|
|
968
|
-
line: lineNumberOf(elem, sourceFile),
|
|
969
|
-
file: rel,
|
|
970
|
-
isExported: true,
|
|
971
|
-
isReExport: true
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
} else if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
|
|
976
|
-
for (const elem of stmt.exportClause.elements) {
|
|
977
|
-
const localName = (elem.propertyName ?? elem.name).text;
|
|
978
|
-
const exportedName = elem.name.text;
|
|
979
|
-
const found = localDecls.get(localName);
|
|
980
|
-
exportedLocalNames.add(localName);
|
|
981
|
-
if (found) {
|
|
982
|
-
addExported({
|
|
983
|
-
name: exportedName,
|
|
984
|
-
...exportedName !== localName ? { localName } : {},
|
|
985
|
-
kind: found.kind,
|
|
986
|
-
signature: found.signature,
|
|
987
|
-
line: found.line,
|
|
988
|
-
...found.endLine !== void 0 ? { endLine: found.endLine } : {},
|
|
989
|
-
...found.structuralHash !== void 0 ? { structuralHash: found.structuralHash } : {},
|
|
990
|
-
...found.nodeCount !== void 0 ? { nodeCount: found.nodeCount } : {},
|
|
991
|
-
...found.astNodeCount !== void 0 ? { astNodeCount: found.astNodeCount } : {},
|
|
992
|
-
...found.statementCount !== void 0 ? { statementCount: found.statementCount } : {},
|
|
993
|
-
file: rel,
|
|
994
|
-
isExported: true
|
|
995
|
-
});
|
|
996
|
-
} else if (!stmt.isTypeOnly && !elem.isTypeOnly) {
|
|
997
|
-
addExported({
|
|
998
|
-
name: exportedName,
|
|
999
|
-
...exportedName !== localName ? { localName } : {},
|
|
1000
|
-
kind: "const",
|
|
1001
|
-
signature: `export { ${localName} }`,
|
|
1002
|
-
line: lineNumberOf(elem, sourceFile),
|
|
1003
|
-
file: rel,
|
|
1004
|
-
isExported: true,
|
|
1005
|
-
isReExport: true
|
|
1006
|
-
});
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
} else if (ts.isExportAssignment(stmt) && !stmt.isExportEquals) {
|
|
1011
|
-
const line = lineNumberOf(stmt, sourceFile);
|
|
1012
|
-
const endLine = endLineNumberOf(stmt, sourceFile);
|
|
1013
|
-
if (ts.isIdentifier(stmt.expression)) {
|
|
1014
|
-
const localName = stmt.expression.text;
|
|
1015
|
-
const found = localDecls.get(localName);
|
|
1016
|
-
exportedLocalNames.add(localName);
|
|
1017
|
-
if (found) {
|
|
1018
|
-
addExported({
|
|
1019
|
-
name: "default",
|
|
1020
|
-
localName,
|
|
1021
|
-
kind: found.kind,
|
|
1022
|
-
signature: found.signature,
|
|
1023
|
-
line: found.line,
|
|
1024
|
-
...found.endLine !== void 0 ? { endLine: found.endLine } : {},
|
|
1025
|
-
...found.structuralHash !== void 0 ? { structuralHash: found.structuralHash } : {},
|
|
1026
|
-
...found.nodeCount !== void 0 ? { nodeCount: found.nodeCount } : {},
|
|
1027
|
-
...found.astNodeCount !== void 0 ? { astNodeCount: found.astNodeCount } : {},
|
|
1028
|
-
...found.statementCount !== void 0 ? { statementCount: found.statementCount } : {},
|
|
1029
|
-
file: rel,
|
|
1030
|
-
isExported: true
|
|
1031
|
-
});
|
|
1032
|
-
} else {
|
|
1033
|
-
addExported({
|
|
1034
|
-
name: "default",
|
|
1035
|
-
localName,
|
|
1036
|
-
kind: "const",
|
|
1037
|
-
signature: `export default ${localName}`,
|
|
1038
|
-
line,
|
|
1039
|
-
endLine,
|
|
1040
|
-
file: rel,
|
|
1041
|
-
isExported: true,
|
|
1042
|
-
isReExport: true
|
|
1043
|
-
});
|
|
1044
|
-
}
|
|
1045
|
-
} else if (ts.isArrowFunction(stmt.expression) || ts.isFunctionExpression(stmt.expression)) {
|
|
1046
|
-
const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
|
|
1047
|
-
stmt.expression,
|
|
1048
|
-
sourceFile,
|
|
1049
|
-
hashOptions
|
|
1050
|
-
);
|
|
1051
|
-
const statementCount = countFunctionStatements(stmt.expression);
|
|
1052
|
-
addExported({
|
|
1053
|
-
name: "default",
|
|
1054
|
-
kind: "function",
|
|
1055
|
-
signature: formatFunctionSignature(stmt.expression, sourceFile),
|
|
1056
|
-
line,
|
|
1057
|
-
endLine,
|
|
1058
|
-
structuralHash,
|
|
1059
|
-
nodeCount,
|
|
1060
|
-
astNodeCount,
|
|
1061
|
-
statementCount,
|
|
1062
|
-
file: rel,
|
|
1063
|
-
isExported: true
|
|
1064
|
-
});
|
|
1065
|
-
} else {
|
|
1066
|
-
addExported({
|
|
1067
|
-
name: "default",
|
|
1068
|
-
kind: "const",
|
|
1069
|
-
signature: "= <default>",
|
|
1070
|
-
line,
|
|
1071
|
-
endLine,
|
|
1072
|
-
file: rel,
|
|
1073
|
-
isExported: true
|
|
1074
|
-
});
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
}
|
|
1078
|
-
for (const [declName, record] of localDecls) {
|
|
1079
|
-
if (!record.isFunctionHelper) continue;
|
|
1080
|
-
if (record.exportedDirectly || exportedLocalNames.has(declName)) continue;
|
|
1081
|
-
if (record.structuralHash === void 0 || record.nodeCount === void 0) continue;
|
|
1082
|
-
internalFunctions.push({
|
|
1083
|
-
name: record.name,
|
|
1084
|
-
kind: "function",
|
|
1085
|
-
signature: record.signature,
|
|
1086
|
-
line: record.line,
|
|
1087
|
-
...record.endLine !== void 0 ? { endLine: record.endLine } : {},
|
|
1088
|
-
structuralHash: record.structuralHash,
|
|
1089
|
-
nodeCount: record.nodeCount,
|
|
1090
|
-
...record.astNodeCount !== void 0 ? { astNodeCount: record.astNodeCount } : {},
|
|
1091
|
-
...record.statementCount !== void 0 ? { statementCount: record.statementCount } : {},
|
|
1092
|
-
file: rel,
|
|
1093
|
-
isExported: false
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
return {
|
|
1097
|
-
relativePath: rel,
|
|
1098
|
-
contentSha256,
|
|
1099
|
-
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
1100
|
-
language: jsTsLanguageFor(absolutePath),
|
|
1101
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
1102
|
-
...size !== void 0 ? { size } : {},
|
|
1103
|
-
imports,
|
|
1104
|
-
exportedSymbols,
|
|
1105
|
-
internalFunctions
|
|
1106
|
-
};
|
|
1107
|
-
}
|
|
1108
|
-
|
|
1109
|
-
// ../engine/src/indexer.ts
|
|
1110
|
-
import { createHash as createHash3 } from "node:crypto";
|
|
1111
|
-
import { readFileSync as readFileSync3, readdirSync, realpathSync, statSync } from "node:fs";
|
|
1112
|
-
import { builtinModules } from "node:module";
|
|
1113
|
-
import path5 from "node:path";
|
|
1114
|
-
import ts2 from "typescript";
|
|
1115
|
-
|
|
1116
|
-
// ../engine/src/polyglot-adapters.ts
|
|
1117
|
-
import { createHash as createHash2 } from "node:crypto";
|
|
1118
|
-
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
|
|
1119
|
-
import path4 from "node:path";
|
|
1120
|
-
function sha256Hex(source) {
|
|
1121
|
-
return createHash2("sha256").update(source, "utf8").digest("hex");
|
|
1122
|
-
}
|
|
1123
|
-
function collapseWs(text) {
|
|
1124
|
-
return text.replace(/\s+/g, " ").trim();
|
|
1125
|
-
}
|
|
1126
|
-
function truncateSig(text, maxLen = 140) {
|
|
1127
|
-
if (text.length <= maxLen) return text;
|
|
1128
|
-
return `${text.slice(0, maxLen - 3)}...`;
|
|
1129
|
-
}
|
|
1130
|
-
function lineOfOffset(source, offset) {
|
|
1131
|
-
let line = 1;
|
|
1132
|
-
const end = Math.min(offset, source.length);
|
|
1133
|
-
for (let i = 0; i < end; i += 1) {
|
|
1134
|
-
if (source.charCodeAt(i) === 10) line += 1;
|
|
1135
|
-
}
|
|
1136
|
-
return line;
|
|
1137
|
-
}
|
|
1138
|
-
function lookupKnownFile(ctx, candidateRel) {
|
|
1139
|
-
const norm = normalizeRelPath(candidateRel);
|
|
1140
|
-
if (!norm || norm.startsWith("..")) return null;
|
|
1141
|
-
return ctx.knownFiles.get(norm) ?? ctx.knownFiles.get(norm.toLowerCase()) ?? null;
|
|
1142
|
-
}
|
|
1143
|
-
var CONTROL_KEYWORDS = {
|
|
1144
|
-
if: "KW:IF",
|
|
1145
|
-
elif: "KW:IF",
|
|
1146
|
-
elsif: "KW:IF",
|
|
1147
|
-
else: "KW:ELSE",
|
|
1148
|
-
for: "KW:FOR",
|
|
1149
|
-
foreach: "KW:FOR",
|
|
1150
|
-
while: "KW:WHILE",
|
|
1151
|
-
loop: "KW:WHILE",
|
|
1152
|
-
match: "KW:MATCH",
|
|
1153
|
-
switch: "KW:MATCH",
|
|
1154
|
-
case: "KW:CASE",
|
|
1155
|
-
when: "KW:CASE",
|
|
1156
|
-
default: "KW:DEFAULT",
|
|
1157
|
-
return: "KW:RETURN",
|
|
1158
|
-
await: "KW:AWAIT",
|
|
1159
|
-
try: "KW:TRY",
|
|
1160
|
-
begin: "KW:TRY",
|
|
1161
|
-
catch: "KW:CATCH",
|
|
1162
|
-
except: "KW:CATCH",
|
|
1163
|
-
rescue: "KW:CATCH",
|
|
1164
|
-
finally: "KW:FINALLY",
|
|
1165
|
-
ensure: "KW:FINALLY",
|
|
1166
|
-
throw: "KW:THROW",
|
|
1167
|
-
raise: "KW:THROW",
|
|
1168
|
-
panic: "KW:THROW",
|
|
1169
|
-
break: "KW:BREAK",
|
|
1170
|
-
continue: "KW:CONTINUE",
|
|
1171
|
-
next: "KW:CONTINUE",
|
|
1172
|
-
yield: "KW:YIELD",
|
|
1173
|
-
in: "KW:IN",
|
|
1174
|
-
new: "KW:NEW",
|
|
1175
|
-
and: "OP:AND",
|
|
1176
|
-
or: "OP:OR",
|
|
1177
|
-
not: "OP:NOT",
|
|
1178
|
-
true: "LIT:BOOL",
|
|
1179
|
-
false: "LIT:BOOL",
|
|
1180
|
-
True: "LIT:BOOL",
|
|
1181
|
-
False: "LIT:BOOL",
|
|
1182
|
-
null: "LIT:NULL",
|
|
1183
|
-
nil: "LIT:NULL",
|
|
1184
|
-
None: "LIT:NULL",
|
|
1185
|
-
nullptr: "LIT:NULL",
|
|
1186
|
-
let: "DECL",
|
|
1187
|
-
const: "DECL",
|
|
1188
|
-
var: "DECL",
|
|
1189
|
-
mut: "DECL",
|
|
1190
|
-
val: "DECL",
|
|
1191
|
-
auto: "DECL",
|
|
1192
|
-
local: "DECL"
|
|
1193
|
-
};
|
|
1194
|
-
var MULTI_CHAR_OPS = [
|
|
1195
|
-
"===",
|
|
1196
|
-
"!==",
|
|
1197
|
-
"<<=",
|
|
1198
|
-
">>=",
|
|
1199
|
-
"..=",
|
|
1200
|
-
"==",
|
|
1201
|
-
"!=",
|
|
1202
|
-
"<=",
|
|
1203
|
-
">=",
|
|
1204
|
-
"&&",
|
|
1205
|
-
"||",
|
|
1206
|
-
"+=",
|
|
1207
|
-
"-=",
|
|
1208
|
-
"*=",
|
|
1209
|
-
"/=",
|
|
1210
|
-
"%=",
|
|
1211
|
-
":=",
|
|
1212
|
-
"??",
|
|
1213
|
-
"?.",
|
|
1214
|
-
"=>",
|
|
1215
|
-
"->",
|
|
1216
|
-
"::",
|
|
1217
|
-
"..",
|
|
1218
|
-
"<<",
|
|
1219
|
-
">>",
|
|
1220
|
-
"**",
|
|
1221
|
-
"//"
|
|
1222
|
-
];
|
|
1223
|
-
function tokenizeNormalizedCode(source, hashComments) {
|
|
1224
|
-
const tokens = [];
|
|
1225
|
-
let meaningfulCount = 0;
|
|
1226
|
-
const len = source.length;
|
|
1227
|
-
let i = 0;
|
|
1228
|
-
let prevWasMemberOp = false;
|
|
1229
|
-
while (i < len) {
|
|
1230
|
-
const ch = source[i];
|
|
1231
|
-
const next = i + 1 < len ? source[i + 1] : "";
|
|
1232
|
-
if (ch === " " || ch === " " || ch === "\r" || ch === "\n") {
|
|
1233
|
-
i += 1;
|
|
1234
|
-
continue;
|
|
1235
|
-
}
|
|
1236
|
-
if (ch === "/" && next === "/") {
|
|
1237
|
-
i += 2;
|
|
1238
|
-
while (i < len && source[i] !== "\n") i += 1;
|
|
1239
|
-
continue;
|
|
1240
|
-
}
|
|
1241
|
-
if (hashComments && ch === "#") {
|
|
1242
|
-
i += 1;
|
|
1243
|
-
while (i < len && source[i] !== "\n") i += 1;
|
|
1244
|
-
continue;
|
|
1245
|
-
}
|
|
1246
|
-
if (ch === "/" && next === "*") {
|
|
1247
|
-
i += 2;
|
|
1248
|
-
while (i + 1 < len && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
|
|
1249
|
-
i = Math.min(len, i + 2);
|
|
1250
|
-
continue;
|
|
1251
|
-
}
|
|
1252
|
-
if (ch === '"' && source.slice(i, i + 3) === '"""' || ch === "'" && source.slice(i, i + 3) === "'''") {
|
|
1253
|
-
const quote = source.slice(i, i + 3);
|
|
1254
|
-
i += 3;
|
|
1255
|
-
while (i < len) {
|
|
1256
|
-
if (source[i] === "\\") {
|
|
1257
|
-
i += 2;
|
|
1258
|
-
continue;
|
|
1259
|
-
}
|
|
1260
|
-
if (source.slice(i, i + 3) === quote) {
|
|
1261
|
-
i += 3;
|
|
1262
|
-
break;
|
|
1263
|
-
}
|
|
1264
|
-
i += 1;
|
|
1265
|
-
}
|
|
1266
|
-
tokens.push("LIT:STR");
|
|
1267
|
-
meaningfulCount += 1;
|
|
1268
|
-
prevWasMemberOp = false;
|
|
1269
|
-
continue;
|
|
1270
|
-
}
|
|
1271
|
-
if (ch === '"' || ch === "'" || ch === "`") {
|
|
1272
|
-
const quote = ch;
|
|
1273
|
-
i += 1;
|
|
1274
|
-
while (i < len) {
|
|
1275
|
-
const c = source[i];
|
|
1276
|
-
if (c === "\\" && quote !== "`") {
|
|
1277
|
-
i += 2;
|
|
1278
|
-
continue;
|
|
1279
|
-
}
|
|
1280
|
-
if (c === quote) {
|
|
1281
|
-
i += 1;
|
|
1282
|
-
break;
|
|
1283
|
-
}
|
|
1284
|
-
i += 1;
|
|
1285
|
-
}
|
|
1286
|
-
tokens.push("LIT:STR");
|
|
1287
|
-
meaningfulCount += 1;
|
|
1288
|
-
prevWasMemberOp = false;
|
|
1289
|
-
continue;
|
|
1290
|
-
}
|
|
1291
|
-
if ((ch === "r" || ch === "f" || ch === "b" || ch === "u" || ch === "R") && (next === '"' || next === "'" || next === "#")) {
|
|
1292
|
-
if (next === '"' || next === "'") {
|
|
1293
|
-
i += 1;
|
|
1294
|
-
continue;
|
|
1295
|
-
}
|
|
1296
|
-
if (ch === "r" && next === "#") {
|
|
1297
|
-
let hashes = 0;
|
|
1298
|
-
let k = i + 1;
|
|
1299
|
-
while (k < len && source[k] === "#") {
|
|
1300
|
-
hashes += 1;
|
|
1301
|
-
k += 1;
|
|
1302
|
-
}
|
|
1303
|
-
if (source[k] === '"') {
|
|
1304
|
-
k += 1;
|
|
1305
|
-
const closing = '"' + "#".repeat(hashes);
|
|
1306
|
-
const endIdx = source.indexOf(closing, k);
|
|
1307
|
-
i = endIdx === -1 ? len : endIdx + closing.length;
|
|
1308
|
-
tokens.push("LIT:STR");
|
|
1309
|
-
meaningfulCount += 1;
|
|
1310
|
-
prevWasMemberOp = false;
|
|
1311
|
-
continue;
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
if (ch >= "0" && ch <= "9") {
|
|
1316
|
-
i += 1;
|
|
1317
|
-
while (i < len && /[0-9a-fA-FxXoObB._eE]/.test(source[i])) {
|
|
1318
|
-
i += 1;
|
|
1319
|
-
}
|
|
1320
|
-
tokens.push("LIT:NUM");
|
|
1321
|
-
meaningfulCount += 1;
|
|
1322
|
-
prevWasMemberOp = false;
|
|
1323
|
-
continue;
|
|
1324
|
-
}
|
|
1325
|
-
if (ch === "$" && i + 1 < len && /[a-zA-Z_]/.test(source[i + 1])) {
|
|
1326
|
-
i += 2;
|
|
1327
|
-
while (i < len && /[a-zA-Z0-9_]/.test(source[i])) i += 1;
|
|
1328
|
-
tokens.push("ID");
|
|
1329
|
-
meaningfulCount += 1;
|
|
1330
|
-
prevWasMemberOp = false;
|
|
1331
|
-
continue;
|
|
1332
|
-
}
|
|
1333
|
-
if (ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_") {
|
|
1334
|
-
const start = i;
|
|
1335
|
-
i += 1;
|
|
1336
|
-
while (i < len && /[a-zA-Z0-9_]/.test(source[i])) i += 1;
|
|
1337
|
-
const word = source.slice(start, i);
|
|
1338
|
-
if (prevWasMemberOp) {
|
|
1339
|
-
tokens.push(`PROP:.${word}`);
|
|
1340
|
-
meaningfulCount += 1;
|
|
1341
|
-
prevWasMemberOp = false;
|
|
1342
|
-
continue;
|
|
1343
|
-
}
|
|
1344
|
-
const kw = CONTROL_KEYWORDS[word];
|
|
1345
|
-
if (kw) {
|
|
1346
|
-
tokens.push(kw);
|
|
1347
|
-
meaningfulCount += 1;
|
|
1348
|
-
} else {
|
|
1349
|
-
let peek = i;
|
|
1350
|
-
while (peek < len && (source[peek] === " " || source[peek] === " ")) peek += 1;
|
|
1351
|
-
if (source[peek] === "(") {
|
|
1352
|
-
tokens.push("CALL");
|
|
1353
|
-
} else {
|
|
1354
|
-
tokens.push("ID");
|
|
1355
|
-
}
|
|
1356
|
-
meaningfulCount += 1;
|
|
1357
|
-
}
|
|
1358
|
-
prevWasMemberOp = false;
|
|
1359
|
-
continue;
|
|
1360
|
-
}
|
|
1361
|
-
let matchedOp = null;
|
|
1362
|
-
for (const op of MULTI_CHAR_OPS) {
|
|
1363
|
-
if (source.startsWith(op, i)) {
|
|
1364
|
-
matchedOp = op;
|
|
1365
|
-
break;
|
|
1366
|
-
}
|
|
1367
|
-
}
|
|
1368
|
-
if (matchedOp) {
|
|
1369
|
-
if (matchedOp === "&&") {
|
|
1370
|
-
tokens.push("OP:AND");
|
|
1371
|
-
meaningfulCount += 1;
|
|
1372
|
-
prevWasMemberOp = false;
|
|
1373
|
-
} else if (matchedOp === "||") {
|
|
1374
|
-
tokens.push("OP:OR");
|
|
1375
|
-
meaningfulCount += 1;
|
|
1376
|
-
prevWasMemberOp = false;
|
|
1377
|
-
} else if (matchedOp === "->" || matchedOp === "::" || matchedOp === "?.") {
|
|
1378
|
-
tokens.push(`OP:${matchedOp}`);
|
|
1379
|
-
prevWasMemberOp = true;
|
|
1380
|
-
} else {
|
|
1381
|
-
tokens.push(`OP:${matchedOp}`);
|
|
1382
|
-
meaningfulCount += 1;
|
|
1383
|
-
prevWasMemberOp = false;
|
|
1384
|
-
}
|
|
1385
|
-
i += matchedOp.length;
|
|
1386
|
-
continue;
|
|
1387
|
-
}
|
|
1388
|
-
if (ch === ".") {
|
|
1389
|
-
tokens.push(".");
|
|
1390
|
-
prevWasMemberOp = true;
|
|
1391
|
-
i += 1;
|
|
1392
|
-
continue;
|
|
1393
|
-
}
|
|
1394
|
-
if ("+-*/%<>=!&|^~?".includes(ch)) {
|
|
1395
|
-
tokens.push(ch === "!" ? "OP:NOT" : `OP:${ch}`);
|
|
1396
|
-
meaningfulCount += 1;
|
|
1397
|
-
prevWasMemberOp = false;
|
|
1398
|
-
i += 1;
|
|
1399
|
-
continue;
|
|
1400
|
-
}
|
|
1401
|
-
if ("()[]{},;:".includes(ch)) {
|
|
1402
|
-
tokens.push(ch);
|
|
1403
|
-
prevWasMemberOp = false;
|
|
1404
|
-
i += 1;
|
|
1405
|
-
continue;
|
|
1406
|
-
}
|
|
1407
|
-
prevWasMemberOp = false;
|
|
1408
|
-
i += 1;
|
|
1409
|
-
}
|
|
1410
|
-
return { tokens, meaningfulCount };
|
|
1411
|
-
}
|
|
1412
|
-
function computePolyglotStructuralHash(bodySource, paramsSource = "", options = {}) {
|
|
1413
|
-
const hashComments = options.hashComments ?? false;
|
|
1414
|
-
const paramRes = paramsSource.trim() ? tokenizeNormalizedCode(paramsSource, hashComments) : { tokens: [], meaningfulCount: 0 };
|
|
1415
|
-
const bodyRes = tokenizeNormalizedCode(bodySource, hashComments);
|
|
1416
|
-
const combined = ["FN"];
|
|
1417
|
-
if (options.isAsync) combined.push("MOD:ASYNC");
|
|
1418
|
-
if (paramRes.tokens.length > 0) {
|
|
1419
|
-
combined.push("PARAMS", ...paramRes.tokens);
|
|
1420
|
-
}
|
|
1421
|
-
combined.push("BODY", ...bodyRes.tokens);
|
|
1422
|
-
const structuralHash = createHash2("sha256").update(combined.join("|"), "utf8").digest("hex").slice(0, 16);
|
|
1423
|
-
const astNodeCount = bodyRes.meaningfulCount;
|
|
1424
|
-
const nodeCount = paramRes.meaningfulCount + astNodeCount;
|
|
1425
|
-
return { structuralHash, nodeCount, astNodeCount };
|
|
1426
|
-
}
|
|
1427
|
-
function findMatchingBrace(source, openIdx, hashComments = false) {
|
|
1428
|
-
let depth = 0;
|
|
1429
|
-
const len = source.length;
|
|
1430
|
-
let i = openIdx;
|
|
1431
|
-
while (i < len) {
|
|
1432
|
-
const ch = source[i];
|
|
1433
|
-
const next = i + 1 < len ? source[i + 1] : "";
|
|
1434
|
-
if (ch === "/" && next === "/") {
|
|
1435
|
-
i += 2;
|
|
1436
|
-
while (i < len && source[i] !== "\n") i += 1;
|
|
1437
|
-
continue;
|
|
1438
|
-
}
|
|
1439
|
-
if (hashComments && ch === "#") {
|
|
1440
|
-
i += 1;
|
|
1441
|
-
while (i < len && source[i] !== "\n") i += 1;
|
|
1442
|
-
continue;
|
|
1443
|
-
}
|
|
1444
|
-
if (ch === "/" && next === "*") {
|
|
1445
|
-
i += 2;
|
|
1446
|
-
while (i + 1 < len && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
|
|
1447
|
-
i = Math.min(len, i + 2);
|
|
1448
|
-
continue;
|
|
1449
|
-
}
|
|
1450
|
-
if (ch === '"' || ch === "'" || ch === "`") {
|
|
1451
|
-
const q = ch;
|
|
1452
|
-
i += 1;
|
|
1453
|
-
while (i < len) {
|
|
1454
|
-
if (source[i] === "\\" && q !== "`") {
|
|
1455
|
-
i += 2;
|
|
1456
|
-
continue;
|
|
1457
|
-
}
|
|
1458
|
-
if (source[i] === q) {
|
|
1459
|
-
i += 1;
|
|
1460
|
-
break;
|
|
1461
|
-
}
|
|
1462
|
-
i += 1;
|
|
1463
|
-
}
|
|
1464
|
-
continue;
|
|
1465
|
-
}
|
|
1466
|
-
if (ch === "{") {
|
|
1467
|
-
depth += 1;
|
|
1468
|
-
} else if (ch === "}") {
|
|
1469
|
-
depth -= 1;
|
|
1470
|
-
if (depth === 0) return i;
|
|
1471
|
-
}
|
|
1472
|
-
i += 1;
|
|
1473
|
-
}
|
|
1474
|
-
return -1;
|
|
1475
|
-
}
|
|
1476
|
-
function splitTopLevelCommas(text) {
|
|
1477
|
-
const parts = [];
|
|
1478
|
-
let depth = 0;
|
|
1479
|
-
let curr = "";
|
|
1480
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
1481
|
-
const ch = text[i];
|
|
1482
|
-
if (ch === "(" || ch === "[" || ch === "<" || ch === "{") depth += 1;
|
|
1483
|
-
else if (ch === ")" || ch === "]" || ch === ">" || ch === "}") depth = Math.max(0, depth - 1);
|
|
1484
|
-
if (ch === "," && depth === 0) {
|
|
1485
|
-
if (curr.trim()) parts.push(curr.trim());
|
|
1486
|
-
curr = "";
|
|
1487
|
-
} else {
|
|
1488
|
-
curr += ch;
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
if (curr.trim()) parts.push(curr.trim());
|
|
1492
|
-
return parts;
|
|
1493
|
-
}
|
|
1494
|
-
function pushUniqueImport(imports, seen, rawSpecifier, importedNames, isReExport, isTypeOnly = false) {
|
|
1495
|
-
const trimmed = rawSpecifier.trim();
|
|
1496
|
-
if (!trimmed) return;
|
|
1497
|
-
const key = `${trimmed}\0${isReExport ? "1" : "0"}\0${isTypeOnly ? "1" : "0"}`;
|
|
1498
|
-
const existing = seen.get(key);
|
|
1499
|
-
if (existing) {
|
|
1500
|
-
for (const name of importedNames) {
|
|
1501
|
-
if (name && !existing.importedNames.includes(name)) {
|
|
1502
|
-
existing.importedNames.push(name);
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
return;
|
|
1506
|
-
}
|
|
1507
|
-
const entry = {
|
|
1508
|
-
rawSpecifier: trimmed,
|
|
1509
|
-
importedNames: [...new Set(importedNames.filter(Boolean))],
|
|
1510
|
-
isReExport,
|
|
1511
|
-
isTypeOnly
|
|
1512
|
-
};
|
|
1513
|
-
seen.set(key, entry);
|
|
1514
|
-
imports.push(entry);
|
|
1515
|
-
}
|
|
1516
|
-
function formatJsTsImport(fromRelPath, symbol) {
|
|
1517
|
-
if (fromRelPath === null) {
|
|
1518
|
-
return `// pass fromFile to resolve the exact specifier (symbol lives in '${symbol.file}')`;
|
|
1519
|
-
}
|
|
1520
|
-
const spec = computeRelativeImportSpec(fromRelPath, symbol.file);
|
|
1521
|
-
if (symbol.name === "default") {
|
|
1522
|
-
return `import ${symbol.localName ?? "defaultExport"} from '${spec}';`;
|
|
1523
|
-
}
|
|
1524
|
-
if (symbol.kind === "interface" || symbol.kind === "type") {
|
|
1525
|
-
return `import type { ${symbol.name} } from '${spec}';`;
|
|
1526
|
-
}
|
|
1527
|
-
return `import { ${symbol.name} } from '${spec}';`;
|
|
1528
|
-
}
|
|
1529
|
-
function createJsTsAdapter(id, extensions) {
|
|
1530
|
-
return {
|
|
1531
|
-
id,
|
|
1532
|
-
extensions,
|
|
1533
|
-
extractManifest(source, absolutePath, relativePath, mtimeMs, size) {
|
|
1534
|
-
const manifest = extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size);
|
|
1535
|
-
return { ...manifest, language: id };
|
|
1536
|
-
},
|
|
1537
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
1538
|
-
const spec = imp.rawSpecifier.trim();
|
|
1539
|
-
if (spec === "." || spec === ".." || spec.startsWith("./") || spec.startsWith("../")) {
|
|
1540
|
-
const base = path4.posix.normalize(path4.posix.join(path4.posix.dirname(fromRelPath), spec));
|
|
1541
|
-
const ext = path4.posix.extname(base).toLowerCase();
|
|
1542
|
-
const swaps = {
|
|
1543
|
-
".js": [".ts", ".tsx", ".js", ".jsx"],
|
|
1544
|
-
".jsx": [".tsx", ".jsx", ".ts", ".js"],
|
|
1545
|
-
".mjs": [".mts", ".mjs"],
|
|
1546
|
-
".cjs": [".cts", ".cjs"]
|
|
1547
|
-
};
|
|
1548
|
-
const candidates = [];
|
|
1549
|
-
if (swaps[ext]) {
|
|
1550
|
-
const stem = base.slice(0, base.length - ext.length);
|
|
1551
|
-
for (const s of swaps[ext]) candidates.push(`${stem}${s}`);
|
|
1552
|
-
}
|
|
1553
|
-
candidates.push(
|
|
1554
|
-
base,
|
|
1555
|
-
`${base}.ts`,
|
|
1556
|
-
`${base}.tsx`,
|
|
1557
|
-
`${base}.mts`,
|
|
1558
|
-
`${base}.cts`,
|
|
1559
|
-
`${base}.js`,
|
|
1560
|
-
`${base}.jsx`,
|
|
1561
|
-
`${base}.mjs`,
|
|
1562
|
-
`${base}.cjs`,
|
|
1563
|
-
`${base}/index.ts`,
|
|
1564
|
-
`${base}/index.tsx`,
|
|
1565
|
-
`${base}/index.js`,
|
|
1566
|
-
`${base}/index.jsx`
|
|
1567
|
-
);
|
|
1568
|
-
for (const cand of candidates) {
|
|
1569
|
-
const hit = lookupKnownFile(ctx, cand);
|
|
1570
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
1571
|
-
}
|
|
1572
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: base };
|
|
1573
|
-
}
|
|
1574
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
1575
|
-
},
|
|
1576
|
-
formatImportStatement(fromRelPath, symbol) {
|
|
1577
|
-
return formatJsTsImport(fromRelPath, symbol);
|
|
1578
|
-
}
|
|
1579
|
-
};
|
|
1580
|
-
}
|
|
1581
|
-
var PYTHON_LEADING_DOCSTRING_RE = /^\s*(?:[rRuUfFbB]{0,2})(?:"""[\s\S]*?"""|'''[\s\S]*?''')\s*\r?\n?/;
|
|
1582
|
-
function formatPythonParams(rawParams) {
|
|
1583
|
-
const params = splitTopLevelCommas(rawParams).map((p) => collapseWs(p)).filter((p) => p && p !== "/" && p !== "*" && p !== "self" && p !== "cls");
|
|
1584
|
-
return params.map((p) => {
|
|
1585
|
-
const eqIdx = p.indexOf("=");
|
|
1586
|
-
return eqIdx === -1 ? p : p.slice(0, eqIdx).trim();
|
|
1587
|
-
}).join(", ");
|
|
1588
|
-
}
|
|
1589
|
-
function parsePythonAllExports(source) {
|
|
1590
|
-
const match = /^__all__\s*(?::[^=]+)?=\s*[\[\(]([\s\S]*?)[\]\)]/m.exec(source);
|
|
1591
|
-
if (!match || !match[1]) return null;
|
|
1592
|
-
const names = /* @__PURE__ */ new Set();
|
|
1593
|
-
const strRe = /['"]([a-zA-Z_][a-zA-Z0-9_]*)['"]/g;
|
|
1594
|
-
let m;
|
|
1595
|
-
while ((m = strRe.exec(match[1])) !== null) {
|
|
1596
|
-
if (m[1]) names.add(m[1]);
|
|
1597
|
-
}
|
|
1598
|
-
return names;
|
|
1599
|
-
}
|
|
1600
|
-
function parsePythonSource(source, relativePath, mtimeMs, size) {
|
|
1601
|
-
const rel = normalizeRelPath(relativePath);
|
|
1602
|
-
const contentSha256 = sha256Hex(source);
|
|
1603
|
-
const imports = [];
|
|
1604
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
1605
|
-
const exportedSymbols = [];
|
|
1606
|
-
const internalFunctions = [];
|
|
1607
|
-
const isInitBarrel = path4.posix.basename(rel) === "__init__.py";
|
|
1608
|
-
const allExports = parsePythonAllExports(source);
|
|
1609
|
-
const isPublicName = (name) => {
|
|
1610
|
-
if (allExports !== null) return allExports.has(name);
|
|
1611
|
-
return !name.startsWith("_");
|
|
1612
|
-
};
|
|
1613
|
-
const lines = source.split(/\r?\n/);
|
|
1614
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
1615
|
-
const line = lines[i];
|
|
1616
|
-
const trimmed = line.trim();
|
|
1617
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
1618
|
-
const fromMatch = /^from\s+(\.+[a-zA-Z0-9_.]*|[a-zA-Z_][a-zA-Z0-9_.]*)\s+import\s+(.*)$/.exec(trimmed);
|
|
1619
|
-
if (fromMatch && fromMatch[1]) {
|
|
1620
|
-
const rawMod = fromMatch[1];
|
|
1621
|
-
let rest = (fromMatch[2] ?? "").replace(/#.*$/, "").trim();
|
|
1622
|
-
if (rest.startsWith("(")) {
|
|
1623
|
-
let block = rest.slice(1);
|
|
1624
|
-
let j = i;
|
|
1625
|
-
while (!block.includes(")") && j + 1 < lines.length) {
|
|
1626
|
-
j += 1;
|
|
1627
|
-
block += " " + (lines[j] ?? "").replace(/#.*$/, "");
|
|
1628
|
-
}
|
|
1629
|
-
const closeIdx = block.indexOf(")");
|
|
1630
|
-
rest = closeIdx === -1 ? block : block.slice(0, closeIdx);
|
|
1631
|
-
i = j;
|
|
1632
|
-
}
|
|
1633
|
-
const names = rest.split(",").map((part) => part.trim()).filter(Boolean).map((part) => {
|
|
1634
|
-
const asMatch = /^([a-zA-Z0-9_*]+)(?:\s+as\s+([a-zA-Z0-9_]+))?/.exec(part);
|
|
1635
|
-
return asMatch?.[1] ?? "";
|
|
1636
|
-
}).filter(Boolean);
|
|
1637
|
-
const isReExport = isInitBarrel && (allExports === null || names.some((n) => n === "*" || allExports.has(n)));
|
|
1638
|
-
pushUniqueImport(imports, importSeen, rawMod, names, isReExport, false);
|
|
1639
|
-
continue;
|
|
1640
|
-
}
|
|
1641
|
-
const impMatch = /^import\s+(.+)$/.exec(trimmed);
|
|
1642
|
-
if (impMatch && impMatch[1]) {
|
|
1643
|
-
const rest = impMatch[1].replace(/#.*$/, "").trim();
|
|
1644
|
-
for (const seg of rest.split(",")) {
|
|
1645
|
-
const cleaned = seg.trim();
|
|
1646
|
-
const modMatch = /^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\s+as\s+([a-zA-Z_][a-zA-Z0-9_]*))?$/.exec(cleaned);
|
|
1647
|
-
if (modMatch && modMatch[1]) {
|
|
1648
|
-
pushUniqueImport(imports, importSeen, modMatch[1], [], false, false);
|
|
1649
|
-
}
|
|
1650
|
-
}
|
|
1651
|
-
continue;
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
1655
|
-
const rawLine = lines[i];
|
|
1656
|
-
if (!rawLine.trim() || rawLine.startsWith(" ") || rawLine.startsWith(" ") || rawLine.startsWith("#")) {
|
|
1657
|
-
continue;
|
|
1658
|
-
}
|
|
1659
|
-
const fnStart = /^(async\s+)?def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/.exec(rawLine);
|
|
1660
|
-
if (fnStart && fnStart[2]) {
|
|
1661
|
-
const isAsync = Boolean(fnStart[1]);
|
|
1662
|
-
const name = fnStart[2];
|
|
1663
|
-
const lineNum = i + 1;
|
|
1664
|
-
let header = rawLine;
|
|
1665
|
-
let headerEndIdx = i;
|
|
1666
|
-
let parenDepth = 0;
|
|
1667
|
-
let seenOpen = false;
|
|
1668
|
-
for (let h = i; h < lines.length; h += 1) {
|
|
1669
|
-
const l = lines[h];
|
|
1670
|
-
for (const c of l) {
|
|
1671
|
-
if (c === "(") {
|
|
1672
|
-
parenDepth += 1;
|
|
1673
|
-
seenOpen = true;
|
|
1674
|
-
} else if (c === ")") {
|
|
1675
|
-
parenDepth = Math.max(0, parenDepth - 1);
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
if (h > i) header += " " + l.trim();
|
|
1679
|
-
headerEndIdx = h;
|
|
1680
|
-
if (seenOpen && parenDepth === 0 && l.replace(/#.*$/, "").trim().endsWith(":")) {
|
|
1681
|
-
break;
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
const sigMatch = /^(?:async\s+)?def\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\(([\s\S]*)\)\s*(?:->\s*([^:]+))?\s*:/.exec(
|
|
1685
|
-
header.replace(/#[^\n]*$/gm, "").trim()
|
|
1686
|
-
);
|
|
1687
|
-
const rawParams = sigMatch?.[1] ?? "";
|
|
1688
|
-
const rawRet = sigMatch?.[2]?.trim();
|
|
1689
|
-
const formattedParams = formatPythonParams(rawParams);
|
|
1690
|
-
const signature = truncateSig(
|
|
1691
|
-
`${isAsync ? "async " : ""}(${formattedParams})${rawRet ? `: ${collapseWs(rawRet)}` : ""}`
|
|
1692
|
-
);
|
|
1693
|
-
const bodyLines = [];
|
|
1694
|
-
let b = headerEndIdx + 1;
|
|
1695
|
-
while (b < lines.length) {
|
|
1696
|
-
const bl = lines[b];
|
|
1697
|
-
if (bl.trim() === "") {
|
|
1698
|
-
bodyLines.push(bl);
|
|
1699
|
-
b += 1;
|
|
1700
|
-
continue;
|
|
1701
|
-
}
|
|
1702
|
-
if (!bl.startsWith(" ") && !bl.startsWith(" ")) {
|
|
1703
|
-
break;
|
|
1704
|
-
}
|
|
1705
|
-
bodyLines.push(bl);
|
|
1706
|
-
b += 1;
|
|
1707
|
-
}
|
|
1708
|
-
const bodySource = bodyLines.join("\n").replace(PYTHON_LEADING_DOCSTRING_RE, "");
|
|
1709
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
1710
|
-
bodySource,
|
|
1711
|
-
formattedParams,
|
|
1712
|
-
{ isAsync, hashComments: true }
|
|
1713
|
-
);
|
|
1714
|
-
if (isPublicName(name)) {
|
|
1715
|
-
exportedSymbols.push({
|
|
1716
|
-
name,
|
|
1717
|
-
kind: "function",
|
|
1718
|
-
signature,
|
|
1719
|
-
line: lineNum,
|
|
1720
|
-
structuralHash,
|
|
1721
|
-
nodeCount,
|
|
1722
|
-
astNodeCount,
|
|
1723
|
-
file: rel,
|
|
1724
|
-
isExported: true
|
|
1725
|
-
});
|
|
1726
|
-
} else {
|
|
1727
|
-
internalFunctions.push({
|
|
1728
|
-
name,
|
|
1729
|
-
kind: "function",
|
|
1730
|
-
signature,
|
|
1731
|
-
line: lineNum,
|
|
1732
|
-
structuralHash,
|
|
1733
|
-
nodeCount,
|
|
1734
|
-
astNodeCount,
|
|
1735
|
-
file: rel,
|
|
1736
|
-
isExported: false
|
|
1737
|
-
});
|
|
1738
|
-
}
|
|
1739
|
-
i = Math.max(headerEndIdx, b - 1);
|
|
1740
|
-
continue;
|
|
1741
|
-
}
|
|
1742
|
-
const clsMatch = /^class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:\(([^)]*)\))?\s*:/.exec(rawLine);
|
|
1743
|
-
if (clsMatch && clsMatch[1]) {
|
|
1744
|
-
const name = clsMatch[1];
|
|
1745
|
-
if (isPublicName(name)) {
|
|
1746
|
-
const bases = clsMatch[2]?.trim();
|
|
1747
|
-
exportedSymbols.push({
|
|
1748
|
-
name,
|
|
1749
|
-
kind: "class",
|
|
1750
|
-
signature: truncateSig(`class ${name}${bases ? `(${collapseWs(bases)})` : ""}`),
|
|
1751
|
-
line: i + 1,
|
|
1752
|
-
file: rel,
|
|
1753
|
-
isExported: true
|
|
1754
|
-
});
|
|
1755
|
-
}
|
|
1756
|
-
continue;
|
|
1757
|
-
}
|
|
1758
|
-
const constMatch = /^([A-Z][A-Z0-9_]{1,})\s*(?::\s*([^=]+))?=\s*(.+)$/.exec(rawLine);
|
|
1759
|
-
if (constMatch && constMatch[1] && constMatch[1] !== "__ALL__") {
|
|
1760
|
-
const name = constMatch[1];
|
|
1761
|
-
if (isPublicName(name)) {
|
|
1762
|
-
const typeAnn = constMatch[2]?.trim();
|
|
1763
|
-
const rhs = constMatch[3]?.trim() ?? "";
|
|
1764
|
-
const sig = typeAnn ? `: ${collapseWs(typeAnn)}` : /^(['"]).*\1$/.test(rhs) || /^\d/.test(rhs) || /^(True|False|None)$/.test(rhs) ? `= ${rhs}` : "= <expr>";
|
|
1765
|
-
exportedSymbols.push({
|
|
1766
|
-
name,
|
|
1767
|
-
kind: "const",
|
|
1768
|
-
signature: truncateSig(sig, 80),
|
|
1769
|
-
line: i + 1,
|
|
1770
|
-
file: rel,
|
|
1771
|
-
isExported: true
|
|
1772
|
-
});
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
return {
|
|
1777
|
-
relativePath: rel,
|
|
1778
|
-
contentSha256,
|
|
1779
|
-
language: "python",
|
|
1780
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
1781
|
-
...size !== void 0 ? { size } : {},
|
|
1782
|
-
imports,
|
|
1783
|
-
exportedSymbols,
|
|
1784
|
-
internalFunctions
|
|
1785
|
-
};
|
|
1786
|
-
}
|
|
1787
|
-
function resolvePythonImport(imp, fromRelPath, ctx) {
|
|
1788
|
-
const spec = imp.rawSpecifier.trim();
|
|
1789
|
-
const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
|
|
1790
|
-
const resolved = [];
|
|
1791
|
-
const tryModulePath = (baseRel) => {
|
|
1792
|
-
const clean = normalizeRelPath(baseRel);
|
|
1793
|
-
return lookupKnownFile(ctx, `${clean}.py`) ?? lookupKnownFile(ctx, `${clean}/__init__.py`);
|
|
1794
|
-
};
|
|
1795
|
-
if (spec.startsWith(".")) {
|
|
1796
|
-
let dots = 0;
|
|
1797
|
-
while (dots < spec.length && spec[dots] === ".") dots += 1;
|
|
1798
|
-
const remainder = spec.slice(dots);
|
|
1799
|
-
let targetDir = fromDir === "." ? "" : fromDir;
|
|
1800
|
-
for (let up = 1; up < dots; up += 1) {
|
|
1801
|
-
if (!targetDir) {
|
|
1802
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: spec };
|
|
1803
|
-
}
|
|
1804
|
-
const parent = path4.posix.dirname(targetDir);
|
|
1805
|
-
targetDir = parent === "." ? "" : parent;
|
|
1806
|
-
}
|
|
1807
|
-
if (remainder) {
|
|
1808
|
-
const modRel2 = remainder.split(".").join("/");
|
|
1809
|
-
const candidateBase = targetDir ? `${targetDir}/${modRel2}` : modRel2;
|
|
1810
|
-
const hit = tryModulePath(candidateBase);
|
|
1811
|
-
if (hit) {
|
|
1812
|
-
return { kind: "local", resolvedPaths: [hit] };
|
|
1813
|
-
}
|
|
1814
|
-
return {
|
|
1815
|
-
kind: "unresolved",
|
|
1816
|
-
resolvedPaths: [],
|
|
1817
|
-
unresolvedAttempt: `${normalizeRelPath(candidateBase)}.py`
|
|
1818
|
-
};
|
|
1819
|
-
}
|
|
1820
|
-
for (const name of imp.importedNames) {
|
|
1821
|
-
if (name === "*") continue;
|
|
1822
|
-
const candBase = targetDir ? `${targetDir}/${name}` : name;
|
|
1823
|
-
const hit = tryModulePath(candBase);
|
|
1824
|
-
if (hit && !resolved.includes(hit)) resolved.push(hit);
|
|
1825
|
-
}
|
|
1826
|
-
if (resolved.length > 0) {
|
|
1827
|
-
return { kind: "local", resolvedPaths: resolved.sort(compareText) };
|
|
1828
|
-
}
|
|
1829
|
-
const initHit = lookupKnownFile(ctx, targetDir ? `${targetDir}/__init__.py` : "__init__.py");
|
|
1830
|
-
if (initHit) {
|
|
1831
|
-
return { kind: "local", resolvedPaths: [initHit] };
|
|
1832
|
-
}
|
|
1833
|
-
return {
|
|
1834
|
-
kind: "unresolved",
|
|
1835
|
-
resolvedPaths: [],
|
|
1836
|
-
unresolvedAttempt: targetDir ? `${targetDir}/__init__.py` : "__init__.py"
|
|
1837
|
-
};
|
|
1838
|
-
}
|
|
1839
|
-
const parts = spec.split(".").filter(Boolean);
|
|
1840
|
-
if (parts.length === 0) {
|
|
1841
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
1842
|
-
}
|
|
1843
|
-
const modRel = parts.join("/");
|
|
1844
|
-
const roots = ctx.pythonSourceRoots.length > 0 ? ctx.pythonSourceRoots : ["", "src"];
|
|
1845
|
-
const extraRoots = [];
|
|
1846
|
-
const fromSegments = normalizeRelPath(fromRelPath).split("/");
|
|
1847
|
-
if ((fromSegments[0] === "packages" || fromSegments[0] === "apps") && fromSegments[1]) {
|
|
1848
|
-
extraRoots.push(`${fromSegments[0]}/${fromSegments[1]}`);
|
|
1849
|
-
extraRoots.push(`${fromSegments[0]}/${fromSegments[1]}/src`);
|
|
1850
|
-
}
|
|
1851
|
-
const allRoots = [.../* @__PURE__ */ new Set([...roots, ...extraRoots])];
|
|
1852
|
-
for (const rootPrefix of allRoots) {
|
|
1853
|
-
const base = rootPrefix ? `${rootPrefix}/${modRel}` : modRel;
|
|
1854
|
-
const hit = tryModulePath(base);
|
|
1855
|
-
if (hit) {
|
|
1856
|
-
if (hit.endsWith("/__init__.py") && imp.importedNames.length > 0) {
|
|
1857
|
-
const subHits = [];
|
|
1858
|
-
for (const name of imp.importedNames) {
|
|
1859
|
-
if (name === "*") continue;
|
|
1860
|
-
const subHit = tryModulePath(`${base}/${name}`);
|
|
1861
|
-
if (subHit && !subHits.includes(subHit)) subHits.push(subHit);
|
|
1862
|
-
}
|
|
1863
|
-
if (subHits.length > 0) {
|
|
1864
|
-
return { kind: "local", resolvedPaths: subHits.sort(compareText) };
|
|
1865
|
-
}
|
|
1866
|
-
}
|
|
1867
|
-
return { kind: "local", resolvedPaths: [hit] };
|
|
1868
|
-
}
|
|
1869
|
-
}
|
|
1870
|
-
const topPkg = parts[0];
|
|
1871
|
-
let localTopRoot = null;
|
|
1872
|
-
for (const rootPrefix of allRoots) {
|
|
1873
|
-
const pkgDirPrefix = rootPrefix ? `${rootPrefix}/${topPkg}/` : `${topPkg}/`;
|
|
1874
|
-
const pkgFile = rootPrefix ? `${rootPrefix}/${topPkg}.py` : `${topPkg}.py`;
|
|
1875
|
-
if (lookupKnownFile(ctx, pkgFile) || ctx.allRelativePaths.some((p) => p.startsWith(pkgDirPrefix) && p.endsWith(".py"))) {
|
|
1876
|
-
localTopRoot = rootPrefix;
|
|
1877
|
-
break;
|
|
1878
|
-
}
|
|
1879
|
-
}
|
|
1880
|
-
if (localTopRoot !== null) {
|
|
1881
|
-
const attempt = localTopRoot ? `${localTopRoot}/${modRel}.py` : `${modRel}.py`;
|
|
1882
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: normalizeRelPath(attempt) };
|
|
1883
|
-
}
|
|
1884
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
1885
|
-
}
|
|
1886
|
-
function formatPythonImport(symbol, ctx) {
|
|
1887
|
-
let modPath = normalizeRelPath(symbol.file);
|
|
1888
|
-
const roots = (ctx?.pythonSourceRoots ?? ["src"]).filter(Boolean).sort((a, b) => b.length - a.length);
|
|
1889
|
-
for (const rootPrefix of roots) {
|
|
1890
|
-
const prefix = `${normalizeRelPath(rootPrefix)}/`;
|
|
1891
|
-
if (modPath.startsWith(prefix)) {
|
|
1892
|
-
modPath = modPath.slice(prefix.length);
|
|
1893
|
-
break;
|
|
1894
|
-
}
|
|
1895
|
-
}
|
|
1896
|
-
modPath = modPath.replace(/\/__init__\.py$/i, "").replace(/\.py$/i, "");
|
|
1897
|
-
const dotted = modPath.split("/").filter(Boolean).join(".");
|
|
1898
|
-
return `from ${dotted || "."} import ${symbol.name}`;
|
|
1899
|
-
}
|
|
1900
|
-
var pythonAdapter = {
|
|
1901
|
-
id: "python",
|
|
1902
|
-
extensions: [".py"],
|
|
1903
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
1904
|
-
return parsePythonSource(source, relativePath, mtimeMs, size);
|
|
1905
|
-
},
|
|
1906
|
-
resolveImport: resolvePythonImport,
|
|
1907
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
1908
|
-
return formatPythonImport(symbol, ctx);
|
|
1909
|
-
}
|
|
1910
|
-
};
|
|
1911
|
-
function formatGoParams(rawParams) {
|
|
1912
|
-
const parts = splitTopLevelCommas(rawParams);
|
|
1913
|
-
if (parts.length === 0) return "";
|
|
1914
|
-
const parsed = [];
|
|
1915
|
-
let pendingNames = [];
|
|
1916
|
-
for (const part of parts) {
|
|
1917
|
-
const tokens = collapseWs(part).split(" ");
|
|
1918
|
-
if (tokens.length === 1) {
|
|
1919
|
-
pendingNames.push(tokens[0]);
|
|
1920
|
-
} else {
|
|
1921
|
-
const name = tokens[0];
|
|
1922
|
-
const type = tokens.slice(1).join(" ");
|
|
1923
|
-
parsed.push({ names: [...pendingNames, name], type });
|
|
1924
|
-
pendingNames = [];
|
|
1925
|
-
}
|
|
1926
|
-
}
|
|
1927
|
-
if (pendingNames.length > 0) {
|
|
1928
|
-
for (let idx = 0; idx < pendingNames.length; idx += 1) {
|
|
1929
|
-
parsed.push({ names: [`p${idx}`], type: pendingNames[idx] });
|
|
1930
|
-
}
|
|
1931
|
-
}
|
|
1932
|
-
return parsed.flatMap((group) => group.names.map((n) => `${n}: ${group.type}`)).join(", ");
|
|
1933
|
-
}
|
|
1934
|
-
function parseGoSource(source, relativePath, mtimeMs, size) {
|
|
1935
|
-
const rel = normalizeRelPath(relativePath);
|
|
1936
|
-
const contentSha256 = sha256Hex(source);
|
|
1937
|
-
const imports = [];
|
|
1938
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
1939
|
-
const exportedSymbols = [];
|
|
1940
|
-
const internalFunctions = [];
|
|
1941
|
-
const noBlockComments = source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "));
|
|
1942
|
-
const groupImportRe = /^\s*import\s*\(([\s\S]*?)\)/gm;
|
|
1943
|
-
let gm;
|
|
1944
|
-
while ((gm = groupImportRe.exec(noBlockComments)) !== null) {
|
|
1945
|
-
const block = gm[1] ?? "";
|
|
1946
|
-
for (const line of block.split(/\r?\n/)) {
|
|
1947
|
-
const cleaned = line.replace(/\/\/.*$/, "").trim();
|
|
1948
|
-
const specMatch = /^(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/.exec(cleaned);
|
|
1949
|
-
if (specMatch && specMatch[2]) {
|
|
1950
|
-
const alias = specMatch[1];
|
|
1951
|
-
const pkgBase = path4.posix.basename(specMatch[2]);
|
|
1952
|
-
pushUniqueImport(
|
|
1953
|
-
imports,
|
|
1954
|
-
importSeen,
|
|
1955
|
-
specMatch[2],
|
|
1956
|
-
alias && alias !== "_" && alias !== "." ? [alias] : [pkgBase],
|
|
1957
|
-
false
|
|
1958
|
-
);
|
|
1959
|
-
}
|
|
1960
|
-
}
|
|
1961
|
-
}
|
|
1962
|
-
const singleImportRe = /^\s*import\s+(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/gm;
|
|
1963
|
-
let sm;
|
|
1964
|
-
while ((sm = singleImportRe.exec(noBlockComments)) !== null) {
|
|
1965
|
-
if (sm[2]) {
|
|
1966
|
-
const alias = sm[1];
|
|
1967
|
-
const pkgBase = path4.posix.basename(sm[2]);
|
|
1968
|
-
pushUniqueImport(
|
|
1969
|
-
imports,
|
|
1970
|
-
importSeen,
|
|
1971
|
-
sm[2],
|
|
1972
|
-
alias && alias !== "_" && alias !== "." ? [alias] : [pkgBase],
|
|
1973
|
-
false
|
|
1974
|
-
);
|
|
1975
|
-
}
|
|
1976
|
-
}
|
|
1977
|
-
const fnRe = /^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s*\(([^)]*)\)\s*([^{;\n]*)\{/gm;
|
|
1978
|
-
let fm;
|
|
1979
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
1980
|
-
const name = fm[1];
|
|
1981
|
-
if (!name) continue;
|
|
1982
|
-
const rawParams = fm[2] ?? "";
|
|
1983
|
-
const rawRet = collapseWs(fm[3] ?? "");
|
|
1984
|
-
const openBraceIdx = fm.index + fm[0].length - 1;
|
|
1985
|
-
const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
|
|
1986
|
-
const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
|
|
1987
|
-
const formattedParams = formatGoParams(rawParams);
|
|
1988
|
-
const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
|
|
1989
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
1990
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
1991
|
-
bodySource,
|
|
1992
|
-
formattedParams,
|
|
1993
|
-
{ hashComments: false }
|
|
1994
|
-
);
|
|
1995
|
-
const isExported = /^[A-Z]/.test(name);
|
|
1996
|
-
if (isExported) {
|
|
1997
|
-
exportedSymbols.push({
|
|
1998
|
-
name,
|
|
1999
|
-
kind: "function",
|
|
2000
|
-
signature,
|
|
2001
|
-
line: lineNum,
|
|
2002
|
-
structuralHash,
|
|
2003
|
-
nodeCount,
|
|
2004
|
-
astNodeCount,
|
|
2005
|
-
file: rel,
|
|
2006
|
-
isExported: true
|
|
2007
|
-
});
|
|
2008
|
-
} else {
|
|
2009
|
-
internalFunctions.push({
|
|
2010
|
-
name,
|
|
2011
|
-
kind: "function",
|
|
2012
|
-
signature,
|
|
2013
|
-
line: lineNum,
|
|
2014
|
-
structuralHash,
|
|
2015
|
-
nodeCount,
|
|
2016
|
-
astNodeCount,
|
|
2017
|
-
file: rel,
|
|
2018
|
-
isExported: false
|
|
2019
|
-
});
|
|
2020
|
-
}
|
|
2021
|
-
}
|
|
2022
|
-
const typeRe = /^type\s+([A-Z][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s+(struct|interface|[^\s{]+)/gm;
|
|
2023
|
-
let tm;
|
|
2024
|
-
while ((tm = typeRe.exec(source)) !== null) {
|
|
2025
|
-
const name = tm[1];
|
|
2026
|
-
const kindWord = tm[2];
|
|
2027
|
-
if (!name || !kindWord) continue;
|
|
2028
|
-
const kind = kindWord === "struct" ? "class" : kindWord === "interface" ? "interface" : "type";
|
|
2029
|
-
exportedSymbols.push({
|
|
2030
|
-
name,
|
|
2031
|
-
kind,
|
|
2032
|
-
signature: truncateSig(`type ${name} ${kindWord}`),
|
|
2033
|
-
line: lineOfOffset(source, tm.index),
|
|
2034
|
-
file: rel,
|
|
2035
|
-
isExported: true
|
|
2036
|
-
});
|
|
2037
|
-
}
|
|
2038
|
-
const constRe = /^(?:const|var)\s+([A-Z][a-zA-Z0-9_]*)\s*(?:([a-zA-Z0-9_.*\[\]]+)\s*)?=\s*([^\n]+)/gm;
|
|
2039
|
-
let cm;
|
|
2040
|
-
while ((cm = constRe.exec(source)) !== null) {
|
|
2041
|
-
const name = cm[1];
|
|
2042
|
-
if (!name) continue;
|
|
2043
|
-
const typeAnn = cm[2]?.trim();
|
|
2044
|
-
exportedSymbols.push({
|
|
2045
|
-
name,
|
|
2046
|
-
kind: "const",
|
|
2047
|
-
signature: truncateSig(typeAnn ? `: ${typeAnn}` : "= <expr>", 80),
|
|
2048
|
-
line: lineOfOffset(source, cm.index),
|
|
2049
|
-
file: rel,
|
|
2050
|
-
isExported: true
|
|
2051
|
-
});
|
|
2052
|
-
}
|
|
2053
|
-
return {
|
|
2054
|
-
relativePath: rel,
|
|
2055
|
-
contentSha256,
|
|
2056
|
-
language: "go",
|
|
2057
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2058
|
-
...size !== void 0 ? { size } : {},
|
|
2059
|
-
imports,
|
|
2060
|
-
exportedSymbols,
|
|
2061
|
-
internalFunctions
|
|
2062
|
-
};
|
|
2063
|
-
}
|
|
2064
|
-
function resolveGoImport(imp, fromRelPath, ctx) {
|
|
2065
|
-
const spec = imp.rawSpecifier.trim();
|
|
2066
|
-
const fromNorm = normalizeRelPath(fromRelPath);
|
|
2067
|
-
const modEntries = [...ctx.goModuleDirs.entries()].sort((a, b) => b[1].length - a[1].length);
|
|
2068
|
-
if (modEntries.length === 0 && ctx.goModulePath) {
|
|
2069
|
-
modEntries.push(["", ctx.goModulePath]);
|
|
2070
|
-
}
|
|
2071
|
-
for (const [modDir, modPath] of modEntries) {
|
|
2072
|
-
if (spec === modPath || spec.startsWith(`${modPath}/`)) {
|
|
2073
|
-
const subPkg = spec === modPath ? "" : spec.slice(modPath.length + 1);
|
|
2074
|
-
const targetDir = normalizeRelPath(modDir ? subPkg ? `${modDir}/${subPkg}` : modDir : subPkg);
|
|
2075
|
-
const matchedFiles = ctx.allRelativePaths.filter((p) => {
|
|
2076
|
-
if (!p.endsWith(".go") || p.endsWith("_test.go")) return false;
|
|
2077
|
-
if (p === fromNorm) return false;
|
|
2078
|
-
const dir = path4.posix.dirname(p);
|
|
2079
|
-
const dirNorm = dir === "." ? "" : dir;
|
|
2080
|
-
return dirNorm === targetDir;
|
|
2081
|
-
}).sort(compareText);
|
|
2082
|
-
if (matchedFiles.length > 0) {
|
|
2083
|
-
return { kind: "local", resolvedPaths: matchedFiles };
|
|
2084
|
-
}
|
|
2085
|
-
return {
|
|
2086
|
-
kind: "unresolved",
|
|
2087
|
-
resolvedPaths: [],
|
|
2088
|
-
unresolvedAttempt: targetDir || spec
|
|
2089
|
-
};
|
|
2090
|
-
}
|
|
2091
|
-
}
|
|
2092
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2093
|
-
}
|
|
2094
|
-
function formatGoImport(symbol, ctx) {
|
|
2095
|
-
const symDirRaw = path4.posix.dirname(normalizeRelPath(symbol.file));
|
|
2096
|
-
const symDir = symDirRaw === "." ? "" : symDirRaw;
|
|
2097
|
-
let importPath = symDir || ".";
|
|
2098
|
-
if (ctx) {
|
|
2099
|
-
const modEntries = [...ctx.goModuleDirs.entries()].sort((a, b) => b[0].length - a[0].length);
|
|
2100
|
-
let matched = false;
|
|
2101
|
-
for (const [modDir, modPath] of modEntries) {
|
|
2102
|
-
if (!modDir) {
|
|
2103
|
-
importPath = symDir ? `${modPath}/${symDir}` : modPath;
|
|
2104
|
-
matched = true;
|
|
2105
|
-
break;
|
|
2106
|
-
}
|
|
2107
|
-
if (symDir === modDir || symDir.startsWith(`${modDir}/`)) {
|
|
2108
|
-
const sub = symDir.slice(modDir.length).replace(/^\//, "");
|
|
2109
|
-
importPath = sub ? `${modPath}/${sub}` : modPath;
|
|
2110
|
-
matched = true;
|
|
2111
|
-
break;
|
|
2112
|
-
}
|
|
2113
|
-
}
|
|
2114
|
-
if (!matched && ctx.goModulePath) {
|
|
2115
|
-
importPath = symDir ? `${ctx.goModulePath}/${symDir}` : ctx.goModulePath;
|
|
2116
|
-
}
|
|
2117
|
-
}
|
|
2118
|
-
const pkgAlias = path4.posix.basename(importPath);
|
|
2119
|
-
return `import "${importPath}" // ${pkgAlias}.${symbol.name}`;
|
|
2120
|
-
}
|
|
2121
|
-
var goAdapter = {
|
|
2122
|
-
id: "go",
|
|
2123
|
-
extensions: [".go"],
|
|
2124
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2125
|
-
return parseGoSource(source, relativePath, mtimeMs, size);
|
|
2126
|
-
},
|
|
2127
|
-
resolveImport: resolveGoImport,
|
|
2128
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
2129
|
-
return formatGoImport(symbol, ctx);
|
|
2130
|
-
}
|
|
2131
|
-
};
|
|
2132
|
-
function expandRustUseTree(tree) {
|
|
2133
|
-
const cleaned = collapseWs(tree).replace(/;$/, "").trim();
|
|
2134
|
-
const braceStart = cleaned.indexOf("{");
|
|
2135
|
-
if (braceStart === -1) {
|
|
2136
|
-
return [cleaned];
|
|
2137
|
-
}
|
|
2138
|
-
let depth = 0;
|
|
2139
|
-
let braceEnd = -1;
|
|
2140
|
-
for (let i = braceStart; i < cleaned.length; i += 1) {
|
|
2141
|
-
if (cleaned[i] === "{") depth += 1;
|
|
2142
|
-
else if (cleaned[i] === "}") {
|
|
2143
|
-
depth -= 1;
|
|
2144
|
-
if (depth === 0) {
|
|
2145
|
-
braceEnd = i;
|
|
2146
|
-
break;
|
|
2147
|
-
}
|
|
2148
|
-
}
|
|
2149
|
-
}
|
|
2150
|
-
if (braceEnd === -1) return [cleaned];
|
|
2151
|
-
const prefix = cleaned.slice(0, braceStart).trim();
|
|
2152
|
-
const inner = cleaned.slice(braceStart + 1, braceEnd);
|
|
2153
|
-
const suffix = cleaned.slice(braceEnd + 1).trim();
|
|
2154
|
-
const results = [];
|
|
2155
|
-
for (const item of splitTopLevelCommas(inner)) {
|
|
2156
|
-
const trimmedItem = item.trim();
|
|
2157
|
-
if (!trimmedItem) continue;
|
|
2158
|
-
if (trimmedItem === "self") {
|
|
2159
|
-
results.push(prefix.replace(/::$/, ""));
|
|
2160
|
-
} else {
|
|
2161
|
-
const joined = `${prefix}${trimmedItem}${suffix}`;
|
|
2162
|
-
results.push(...expandRustUseTree(joined));
|
|
2163
|
-
}
|
|
2164
|
-
}
|
|
2165
|
-
return results;
|
|
2166
|
-
}
|
|
2167
|
-
function parseRustSource(source, relativePath, mtimeMs, size) {
|
|
2168
|
-
const rel = normalizeRelPath(relativePath);
|
|
2169
|
-
const contentSha256 = sha256Hex(source);
|
|
2170
|
-
const imports = [];
|
|
2171
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2172
|
-
const exportedSymbols = [];
|
|
2173
|
-
const internalFunctions = [];
|
|
2174
|
-
const stripped = source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/\/\/[^\n]*/g, "");
|
|
2175
|
-
const modRe = /^\s*(pub(?:\([^)]*\))?\s+)?mod\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*;/gm;
|
|
2176
|
-
let mm;
|
|
2177
|
-
while ((mm = modRe.exec(stripped)) !== null) {
|
|
2178
|
-
if (mm[2]) {
|
|
2179
|
-
pushUniqueImport(imports, importSeen, `mod::${mm[2]}`, [mm[2]], Boolean(mm[1]), false);
|
|
2180
|
-
}
|
|
2181
|
-
}
|
|
2182
|
-
const useRe = /^\s*(pub(?:\([^)]*\))?\s+)?use\s+([\s\S]*?);/gm;
|
|
2183
|
-
let um;
|
|
2184
|
-
while ((um = useRe.exec(stripped)) !== null) {
|
|
2185
|
-
const isPubUse = Boolean(um[1]);
|
|
2186
|
-
const rawTree = um[2] ?? "";
|
|
2187
|
-
for (const expanded of expandRustUseTree(rawTree)) {
|
|
2188
|
-
const noAlias = expanded.replace(/\s+as\s+[a-zA-Z_][a-zA-Z0-9_]*$/, "").trim();
|
|
2189
|
-
if (!noAlias) continue;
|
|
2190
|
-
const segs = noAlias.split("::").filter(Boolean);
|
|
2191
|
-
const lastSeg = segs[segs.length - 1] ?? "";
|
|
2192
|
-
pushUniqueImport(
|
|
2193
|
-
imports,
|
|
2194
|
-
importSeen,
|
|
2195
|
-
noAlias,
|
|
2196
|
-
lastSeg && lastSeg !== "*" ? [lastSeg] : lastSeg === "*" ? ["*"] : [],
|
|
2197
|
-
isPubUse,
|
|
2198
|
-
false
|
|
2199
|
-
);
|
|
2200
|
-
}
|
|
2201
|
-
}
|
|
2202
|
-
const fnRe = /^(pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?:->\s*([^{\n]+?))?\s*(?:where\s+[^{]+)?\{/gm;
|
|
2203
|
-
let fm;
|
|
2204
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
2205
|
-
const isPub = Boolean(fm[1]);
|
|
2206
|
-
const name = fm[2];
|
|
2207
|
-
if (!name) continue;
|
|
2208
|
-
const isAsync = /\basync\s+fn\b/.test(fm[0]);
|
|
2209
|
-
const rawParams = collapseWs(fm[3] ?? "");
|
|
2210
|
-
const rawRet = collapseWs(fm[4] ?? "");
|
|
2211
|
-
const openBraceIdx = fm.index + fm[0].length - 1;
|
|
2212
|
-
const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
|
|
2213
|
-
const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
|
|
2214
|
-
const signature = truncateSig(
|
|
2215
|
-
`${isAsync ? "async " : ""}(${rawParams})${rawRet ? `: ${rawRet}` : ""}`
|
|
2216
|
-
);
|
|
2217
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
2218
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2219
|
-
bodySource,
|
|
2220
|
-
rawParams,
|
|
2221
|
-
{ isAsync, hashComments: false }
|
|
2222
|
-
);
|
|
2223
|
-
if (isPub) {
|
|
2224
|
-
exportedSymbols.push({
|
|
2225
|
-
name,
|
|
2226
|
-
kind: "function",
|
|
2227
|
-
signature,
|
|
2228
|
-
line: lineNum,
|
|
2229
|
-
structuralHash,
|
|
2230
|
-
nodeCount,
|
|
2231
|
-
astNodeCount,
|
|
2232
|
-
file: rel,
|
|
2233
|
-
isExported: true
|
|
2234
|
-
});
|
|
2235
|
-
} else {
|
|
2236
|
-
internalFunctions.push({
|
|
2237
|
-
name,
|
|
2238
|
-
kind: "function",
|
|
2239
|
-
signature,
|
|
2240
|
-
line: lineNum,
|
|
2241
|
-
structuralHash,
|
|
2242
|
-
nodeCount,
|
|
2243
|
-
astNodeCount,
|
|
2244
|
-
file: rel,
|
|
2245
|
-
isExported: false
|
|
2246
|
-
});
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
const itemRe = /^pub(?:\([^)]*\))?\s+(struct|enum|trait|type|const|static)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
|
|
2250
|
-
let im;
|
|
2251
|
-
while ((im = itemRe.exec(source)) !== null) {
|
|
2252
|
-
const kw = im[1];
|
|
2253
|
-
const name = im[2];
|
|
2254
|
-
if (!kw || !name) continue;
|
|
2255
|
-
const kind = kw === "struct" ? "class" : kw === "enum" ? "enum" : kw === "trait" ? "interface" : kw === "type" ? "type" : "const";
|
|
2256
|
-
exportedSymbols.push({
|
|
2257
|
-
name,
|
|
2258
|
-
kind,
|
|
2259
|
-
signature: `${kw} ${name}`,
|
|
2260
|
-
line: lineOfOffset(source, im.index),
|
|
2261
|
-
file: rel,
|
|
2262
|
-
isExported: true
|
|
2263
|
-
});
|
|
2264
|
-
}
|
|
2265
|
-
return {
|
|
2266
|
-
relativePath: rel,
|
|
2267
|
-
contentSha256,
|
|
2268
|
-
language: "rust",
|
|
2269
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2270
|
-
...size !== void 0 ? { size } : {},
|
|
2271
|
-
imports,
|
|
2272
|
-
exportedSymbols,
|
|
2273
|
-
internalFunctions
|
|
2274
|
-
};
|
|
2275
|
-
}
|
|
2276
|
-
function findRustCrateForFile(relPath, ctx) {
|
|
2277
|
-
const norm = normalizeRelPath(relPath);
|
|
2278
|
-
if (ctx && ctx.rustCrates.length > 0) {
|
|
2279
|
-
const sorted = [...ctx.rustCrates].sort((a, b) => b.srcDir.length - a.srcDir.length);
|
|
2280
|
-
for (const crate of sorted) {
|
|
2281
|
-
if (!crate.srcDir || norm === crate.srcDir || norm.startsWith(`${crate.srcDir}/`)) {
|
|
2282
|
-
return crate;
|
|
2283
|
-
}
|
|
2284
|
-
if (!crate.crateDir || norm.startsWith(`${crate.crateDir}/`)) {
|
|
2285
|
-
return crate;
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
|
-
}
|
|
2289
|
-
const srcIdx = norm.indexOf("/src/");
|
|
2290
|
-
if (srcIdx !== -1) {
|
|
2291
|
-
return {
|
|
2292
|
-
crateDir: norm.slice(0, srcIdx),
|
|
2293
|
-
srcDir: `${norm.slice(0, srcIdx)}/src`
|
|
2294
|
-
};
|
|
2295
|
-
}
|
|
2296
|
-
if (norm.startsWith("src/")) {
|
|
2297
|
-
return { crateDir: "", srcDir: "src" };
|
|
2298
|
-
}
|
|
2299
|
-
return { crateDir: "", srcDir: "" };
|
|
2300
|
-
}
|
|
2301
|
-
function resolveRustImport(imp, fromRelPath, ctx) {
|
|
2302
|
-
const spec = imp.rawSpecifier.trim();
|
|
2303
|
-
const fromNorm = normalizeRelPath(fromRelPath);
|
|
2304
|
-
const fromDirRaw = path4.posix.dirname(fromNorm);
|
|
2305
|
-
const fromDir = fromDirRaw === "." ? "" : fromDirRaw;
|
|
2306
|
-
const fromBase = path4.posix.basename(fromNorm);
|
|
2307
|
-
const crate = findRustCrateForFile(fromNorm, ctx);
|
|
2308
|
-
const tryRustModFile = (baseRel) => {
|
|
2309
|
-
const clean = normalizeRelPath(baseRel);
|
|
2310
|
-
return lookupKnownFile(ctx, `${clean}.rs`) ?? lookupKnownFile(ctx, `${clean}/mod.rs`);
|
|
2311
|
-
};
|
|
2312
|
-
if (spec.startsWith("mod::")) {
|
|
2313
|
-
const modName = spec.slice("mod::".length);
|
|
2314
|
-
const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
|
|
2315
|
-
const searchBases = [];
|
|
2316
|
-
if (isRootOrMod) {
|
|
2317
|
-
searchBases.push(fromDir ? `${fromDir}/${modName}` : modName);
|
|
2318
|
-
} else {
|
|
2319
|
-
const stem = fromBase.replace(/\.rs$/, "");
|
|
2320
|
-
searchBases.push(fromDir ? `${fromDir}/${stem}/${modName}` : `${stem}/${modName}`);
|
|
2321
|
-
searchBases.push(fromDir ? `${fromDir}/${modName}` : modName);
|
|
2322
|
-
}
|
|
2323
|
-
for (const base of searchBases) {
|
|
2324
|
-
const hit = tryRustModFile(base);
|
|
2325
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
2326
|
-
}
|
|
2327
|
-
const attempt = searchBases[0] ? `${normalizeRelPath(searchBases[0])}.rs` : `${modName}.rs`;
|
|
2328
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: attempt };
|
|
2329
|
-
}
|
|
2330
|
-
const segs = spec.split("::").filter(Boolean);
|
|
2331
|
-
if (segs.length === 0) {
|
|
2332
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2333
|
-
}
|
|
2334
|
-
let baseDir = null;
|
|
2335
|
-
let restSegs = [];
|
|
2336
|
-
if (segs[0] === "crate") {
|
|
2337
|
-
baseDir = crate.srcDir;
|
|
2338
|
-
restSegs = segs.slice(1);
|
|
2339
|
-
} else if (segs[0] === "self") {
|
|
2340
|
-
const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
|
|
2341
|
-
baseDir = isRootOrMod ? fromDir : normalizeRelPath(`${fromDir}/${fromBase.replace(/\.rs$/, "")}`);
|
|
2342
|
-
restSegs = segs.slice(1);
|
|
2343
|
-
} else if (segs[0] === "super") {
|
|
2344
|
-
let currDir = fromDir;
|
|
2345
|
-
const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
|
|
2346
|
-
let idx = 0;
|
|
2347
|
-
if (!isRootOrMod) {
|
|
2348
|
-
idx = 1;
|
|
2349
|
-
}
|
|
2350
|
-
while (idx < segs.length && segs[idx] === "super") {
|
|
2351
|
-
const parent = path4.posix.dirname(currDir);
|
|
2352
|
-
currDir = parent === "." ? "" : parent;
|
|
2353
|
-
idx += 1;
|
|
2354
|
-
}
|
|
2355
|
-
baseDir = currDir;
|
|
2356
|
-
restSegs = segs.slice(idx);
|
|
2357
|
-
} else {
|
|
2358
|
-
const matchingCrate = ctx.rustCrates.find(
|
|
2359
|
-
(c) => c.crateName && c.crateName.replace(/-/g, "_") === segs[0].replace(/-/g, "_")
|
|
2360
|
-
);
|
|
2361
|
-
if (matchingCrate) {
|
|
2362
|
-
baseDir = matchingCrate.srcDir;
|
|
2363
|
-
restSegs = segs.slice(1);
|
|
2364
|
-
}
|
|
2365
|
-
}
|
|
2366
|
-
if (baseDir === null) {
|
|
2367
|
-
const siblingBase = fromDir ? `${fromDir}/${segs[0]}` : segs[0];
|
|
2368
|
-
const siblingHit = tryRustModFile(siblingBase);
|
|
2369
|
-
if (siblingHit && siblingHit !== fromNorm) {
|
|
2370
|
-
return { kind: "local", resolvedPaths: [siblingHit] };
|
|
2371
|
-
}
|
|
2372
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2373
|
-
}
|
|
2374
|
-
const cleanSegs = restSegs.filter((s) => s !== "*");
|
|
2375
|
-
const candidateLengths = [];
|
|
2376
|
-
if (cleanSegs.length >= 1) candidateLengths.push(cleanSegs.length);
|
|
2377
|
-
if (cleanSegs.length >= 2) candidateLengths.push(cleanSegs.length - 1);
|
|
2378
|
-
if (cleanSegs.length >= 3 && /^[A-Z]/.test(cleanSegs[cleanSegs.length - 2] ?? "")) {
|
|
2379
|
-
candidateLengths.push(cleanSegs.length - 2);
|
|
2380
|
-
}
|
|
2381
|
-
for (const len of candidateLengths) {
|
|
2382
|
-
const sub = cleanSegs.slice(0, len).join("/");
|
|
2383
|
-
const candidateBase = baseDir ? `${baseDir}/${sub}` : sub;
|
|
2384
|
-
const hit = tryRustModFile(candidateBase);
|
|
2385
|
-
if (hit && hit !== fromNorm) {
|
|
2386
|
-
return { kind: "local", resolvedPaths: [hit] };
|
|
2387
|
-
}
|
|
2388
|
-
}
|
|
2389
|
-
if (cleanSegs.length <= 1) {
|
|
2390
|
-
const fallbackRoot = lookupKnownFile(ctx, baseDir ? `${baseDir}/mod.rs` : "mod.rs") ?? lookupKnownFile(ctx, baseDir ? `${baseDir}/lib.rs` : "lib.rs") ?? lookupKnownFile(ctx, baseDir ? `${baseDir}/main.rs` : "main.rs");
|
|
2391
|
-
if (fallbackRoot && fallbackRoot !== fromNorm) {
|
|
2392
|
-
return { kind: "local", resolvedPaths: [fallbackRoot] };
|
|
2393
|
-
}
|
|
2394
|
-
}
|
|
2395
|
-
const attemptPath = cleanSegs.length > 0 ? `${normalizeRelPath(baseDir ? `${baseDir}/${cleanSegs.slice(0, Math.max(1, cleanSegs.length - 1)).join("/")}` : cleanSegs[0])}.rs` : `${baseDir || "src"}/lib.rs`;
|
|
2396
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: attemptPath };
|
|
2397
|
-
}
|
|
2398
|
-
function formatRustImport(symbol, ctx) {
|
|
2399
|
-
const norm = normalizeRelPath(symbol.file);
|
|
2400
|
-
const crate = findRustCrateForFile(norm, ctx);
|
|
2401
|
-
let relToSrc = norm;
|
|
2402
|
-
if (crate.srcDir && relToSrc.startsWith(`${crate.srcDir}/`)) {
|
|
2403
|
-
relToSrc = relToSrc.slice(crate.srcDir.length + 1);
|
|
2404
|
-
}
|
|
2405
|
-
relToSrc = relToSrc.replace(/\/mod\.rs$/i, "").replace(/^(?:lib|main)\.rs$/i, "").replace(/\.rs$/i, "");
|
|
2406
|
-
const modSegs = relToSrc.split("/").filter(Boolean);
|
|
2407
|
-
const prefix = modSegs.length > 0 ? `crate::${modSegs.join("::")}` : "crate";
|
|
2408
|
-
return `use ${prefix}::${symbol.name};`;
|
|
2409
|
-
}
|
|
2410
|
-
var rustAdapter = {
|
|
2411
|
-
id: "rust",
|
|
2412
|
-
extensions: [".rs"],
|
|
2413
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2414
|
-
return parseRustSource(source, relativePath, mtimeMs, size);
|
|
2415
|
-
},
|
|
2416
|
-
resolveImport: resolveRustImport,
|
|
2417
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
2418
|
-
return formatRustImport(symbol, ctx);
|
|
2419
|
-
}
|
|
2420
|
-
};
|
|
2421
|
-
function createJvmAdapter(id, extensions) {
|
|
2422
|
-
return {
|
|
2423
|
-
id,
|
|
2424
|
-
extensions,
|
|
2425
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2426
|
-
const rel = normalizeRelPath(relativePath);
|
|
2427
|
-
const contentSha256 = sha256Hex(source);
|
|
2428
|
-
const imports = [];
|
|
2429
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2430
|
-
const exportedSymbols = [];
|
|
2431
|
-
const internalFunctions = [];
|
|
2432
|
-
const impRe = /^\s*import\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.*]*)\s*;?/gm;
|
|
2433
|
-
let im;
|
|
2434
|
-
while ((im = impRe.exec(source)) !== null) {
|
|
2435
|
-
const raw = im[1];
|
|
2436
|
-
if (!raw) continue;
|
|
2437
|
-
const lastDot = raw.lastIndexOf(".");
|
|
2438
|
-
const symName = lastDot === -1 ? raw : raw.slice(lastDot + 1);
|
|
2439
|
-
pushUniqueImport(imports, importSeen, raw, symName ? [symName] : [], false);
|
|
2440
|
-
}
|
|
2441
|
-
const typeRe = id === "java" ? /^\s*public\s+(?:abstract\s+|final\s+|sealed\s+)?(class|interface|enum|record)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm : /^\s*(?:(private|internal|protected)\s+)?(?:data\s+|sealed\s+|abstract\s+|open\s+)?(class|interface|enum\s+class|object)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
|
|
2442
|
-
let tm;
|
|
2443
|
-
while ((tm = typeRe.exec(source)) !== null) {
|
|
2444
|
-
if (id === "java") {
|
|
2445
|
-
const kw = tm[1];
|
|
2446
|
-
const name = tm[2];
|
|
2447
|
-
exportedSymbols.push({
|
|
2448
|
-
name,
|
|
2449
|
-
kind: kw === "interface" ? "interface" : kw === "enum" ? "enum" : "class",
|
|
2450
|
-
signature: `${kw} ${name}`,
|
|
2451
|
-
line: lineOfOffset(source, tm.index),
|
|
2452
|
-
file: rel,
|
|
2453
|
-
isExported: true
|
|
2454
|
-
});
|
|
2455
|
-
} else {
|
|
2456
|
-
const vis = tm[1];
|
|
2457
|
-
const kw = tm[2];
|
|
2458
|
-
const name = tm[3];
|
|
2459
|
-
if (vis === "private") continue;
|
|
2460
|
-
exportedSymbols.push({
|
|
2461
|
-
name,
|
|
2462
|
-
kind: kw === "interface" ? "interface" : kw.startsWith("enum") ? "enum" : "class",
|
|
2463
|
-
signature: `${kw} ${name}`,
|
|
2464
|
-
line: lineOfOffset(source, tm.index),
|
|
2465
|
-
file: rel,
|
|
2466
|
-
isExported: true
|
|
2467
|
-
});
|
|
2468
|
-
}
|
|
2469
|
-
}
|
|
2470
|
-
const fnRe = id === "java" ? /^\s*(public|private|protected)\s+(?:static\s+)?(?:final\s+)?(?:synchronized\s+)?(?:<[^>]+>\s+)?([a-zA-Z_][a-zA-Z0-9_<>\[\]., ?]*)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?:throws\s+[^{]+)?\{/gm : /^\s*(?:(public|private|internal|protected)\s+)?(?:suspend\s+)?fun\s+(?:<[^>]+>\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?::\s*([^{\n=]+))?\s*\{/gm;
|
|
2471
|
-
let fm;
|
|
2472
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
2473
|
-
const isJava = id === "java";
|
|
2474
|
-
const vis = fm[1] ?? "public";
|
|
2475
|
-
const name = isJava ? fm[3] : fm[2];
|
|
2476
|
-
if (!name || name === "if" || name === "for" || name === "while" || name === "switch") continue;
|
|
2477
|
-
const rawParams = collapseWs(isJava ? fm[4] ?? "" : fm[3] ?? "");
|
|
2478
|
-
const rawRet = collapseWs(isJava ? fm[2] ?? "" : fm[4] ?? "");
|
|
2479
|
-
const openBraceIdx = fm.index + fm[0].length - 1;
|
|
2480
|
-
const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
|
|
2481
|
-
const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
|
|
2482
|
-
const formattedParams = isJava ? splitTopLevelCommas(rawParams).map((p) => {
|
|
2483
|
-
const toks = collapseWs(p).split(" ");
|
|
2484
|
-
if (toks.length >= 2) {
|
|
2485
|
-
const pName = toks[toks.length - 1];
|
|
2486
|
-
const pType = toks.slice(0, -1).join(" ");
|
|
2487
|
-
return `${pName}: ${pType}`;
|
|
2488
|
-
}
|
|
2489
|
-
return p;
|
|
2490
|
-
}).join(", ") : rawParams;
|
|
2491
|
-
const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
|
|
2492
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2493
|
-
bodySource,
|
|
2494
|
-
formattedParams
|
|
2495
|
-
);
|
|
2496
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
2497
|
-
if (vis === "public" || vis === "") {
|
|
2498
|
-
exportedSymbols.push({
|
|
2499
|
-
name,
|
|
2500
|
-
kind: "function",
|
|
2501
|
-
signature,
|
|
2502
|
-
line: lineNum,
|
|
2503
|
-
structuralHash,
|
|
2504
|
-
nodeCount,
|
|
2505
|
-
astNodeCount,
|
|
2506
|
-
file: rel,
|
|
2507
|
-
isExported: true
|
|
2508
|
-
});
|
|
2509
|
-
} else {
|
|
2510
|
-
internalFunctions.push({
|
|
2511
|
-
name,
|
|
2512
|
-
kind: "function",
|
|
2513
|
-
signature,
|
|
2514
|
-
line: lineNum,
|
|
2515
|
-
structuralHash,
|
|
2516
|
-
nodeCount,
|
|
2517
|
-
astNodeCount,
|
|
2518
|
-
file: rel,
|
|
2519
|
-
isExported: false
|
|
2520
|
-
});
|
|
2521
|
-
}
|
|
2522
|
-
}
|
|
2523
|
-
return {
|
|
2524
|
-
relativePath: rel,
|
|
2525
|
-
contentSha256,
|
|
2526
|
-
language: id,
|
|
2527
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2528
|
-
...size !== void 0 ? { size } : {},
|
|
2529
|
-
imports,
|
|
2530
|
-
exportedSymbols,
|
|
2531
|
-
internalFunctions
|
|
2532
|
-
};
|
|
2533
|
-
},
|
|
2534
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
2535
|
-
const spec = imp.rawSpecifier.trim();
|
|
2536
|
-
const fromNorm = normalizeRelPath(fromRelPath);
|
|
2537
|
-
const isWildcard = spec.endsWith(".*");
|
|
2538
|
-
const basePkg = isWildcard ? spec.slice(0, -2) : spec;
|
|
2539
|
-
const slashPath = basePkg.replace(/\./g, "/");
|
|
2540
|
-
if (isWildcard) {
|
|
2541
|
-
const hits2 = ctx.allRelativePaths.filter(
|
|
2542
|
-
(p) => p !== fromNorm && (p.endsWith(".java") || p.endsWith(".kt")) && (ctx.javaPackagesByFile.get(p) === basePkg || p.includes(`/${slashPath}/`))
|
|
2543
|
-
).sort(compareText);
|
|
2544
|
-
if (hits2.length > 0) return { kind: "local", resolvedPaths: hits2 };
|
|
2545
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2546
|
-
}
|
|
2547
|
-
const lastDot = spec.lastIndexOf(".");
|
|
2548
|
-
const pkg = lastDot === -1 ? "" : spec.slice(0, lastDot);
|
|
2549
|
-
const cls = lastDot === -1 ? spec : spec.slice(lastDot + 1);
|
|
2550
|
-
const hits = ctx.allRelativePaths.filter((p) => {
|
|
2551
|
-
if (p === fromNorm) return false;
|
|
2552
|
-
if (!p.endsWith(".java") && !p.endsWith(".kt")) return false;
|
|
2553
|
-
if (p.endsWith(`/${slashPath}.java`) || p.endsWith(`/${slashPath}.kt`) || p === `${slashPath}.java` || p === `${slashPath}.kt`) {
|
|
2554
|
-
return true;
|
|
2555
|
-
}
|
|
2556
|
-
const filePkg = ctx.javaPackagesByFile.get(p);
|
|
2557
|
-
const stem = path4.posix.basename(p).replace(/\.(java|kt)$/, "");
|
|
2558
|
-
return Boolean(filePkg && filePkg === pkg && stem === cls);
|
|
2559
|
-
}).sort(compareText);
|
|
2560
|
-
if (hits.length > 0) return { kind: "local", resolvedPaths: hits };
|
|
2561
|
-
const knownPkgs = new Set(ctx.javaPackagesByFile.values());
|
|
2562
|
-
if (pkg && knownPkgs.has(pkg)) {
|
|
2563
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: `${slashPath}.${id === "java" ? "java" : "kt"}` };
|
|
2564
|
-
}
|
|
2565
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2566
|
-
},
|
|
2567
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
2568
|
-
const pkg = ctx?.javaPackagesByFile.get(normalizeRelPath(symbol.file));
|
|
2569
|
-
const full = pkg ? `${pkg}.${symbol.name}` : symbol.name;
|
|
2570
|
-
return id === "java" ? `import ${full};` : `import ${full}`;
|
|
2571
|
-
}
|
|
2572
|
-
};
|
|
2573
|
-
}
|
|
2574
|
-
var javaAdapter = createJvmAdapter("java", [".java"]);
|
|
2575
|
-
var kotlinAdapter = createJvmAdapter("kotlin", [".kt", ".kts"]);
|
|
2576
|
-
var csharpAdapter = {
|
|
2577
|
-
id: "csharp",
|
|
2578
|
-
extensions: [".cs"],
|
|
2579
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2580
|
-
const rel = normalizeRelPath(relativePath);
|
|
2581
|
-
const contentSha256 = sha256Hex(source);
|
|
2582
|
-
const imports = [];
|
|
2583
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2584
|
-
const exportedSymbols = [];
|
|
2585
|
-
const internalFunctions = [];
|
|
2586
|
-
const usingRe = /^\s*(?:global\s+)?using\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.]*)\s*;/gm;
|
|
2587
|
-
let um;
|
|
2588
|
-
while ((um = usingRe.exec(source)) !== null) {
|
|
2589
|
-
if (um[1]) pushUniqueImport(imports, importSeen, um[1], [um[1]], false);
|
|
2590
|
-
}
|
|
2591
|
-
const typeRe = /^\s*public\s+(?:static\s+|abstract\s+|sealed\s+|partial\s+)?(class|interface|struct|record|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
|
|
2592
|
-
let tm;
|
|
2593
|
-
while ((tm = typeRe.exec(source)) !== null) {
|
|
2594
|
-
const kw = tm[1];
|
|
2595
|
-
const name = tm[2];
|
|
2596
|
-
exportedSymbols.push({
|
|
2597
|
-
name,
|
|
2598
|
-
kind: kw === "interface" ? "interface" : kw === "enum" ? "enum" : "class",
|
|
2599
|
-
signature: `${kw} ${name}`,
|
|
2600
|
-
line: lineOfOffset(source, tm.index),
|
|
2601
|
-
file: rel,
|
|
2602
|
-
isExported: true
|
|
2603
|
-
});
|
|
2604
|
-
}
|
|
2605
|
-
const fnRe = /^\s*(public|private|internal|protected)\s+(?:static\s+)?(?:async\s+)?(?:virtual\s+|override\s+)?([a-zA-Z_][a-zA-Z0-9_<>\[\]., ?]*)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*\{/gm;
|
|
2606
|
-
let fm;
|
|
2607
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
2608
|
-
const vis = fm[1];
|
|
2609
|
-
const rawRet = collapseWs(fm[2] ?? "");
|
|
2610
|
-
const name = fm[3];
|
|
2611
|
-
const rawParams = collapseWs(fm[4] ?? "");
|
|
2612
|
-
const openIdx = fm.index + fm[0].length - 1;
|
|
2613
|
-
const closeIdx = findMatchingBrace(source, openIdx, false);
|
|
2614
|
-
const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
|
|
2615
|
-
const formattedParams = splitTopLevelCommas(rawParams).map((p) => {
|
|
2616
|
-
const toks = collapseWs(p).split(" ");
|
|
2617
|
-
return toks.length >= 2 ? `${toks[toks.length - 1]}: ${toks.slice(0, -1).join(" ")}` : p;
|
|
2618
|
-
}).join(", ");
|
|
2619
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2620
|
-
bodySource,
|
|
2621
|
-
formattedParams
|
|
2622
|
-
);
|
|
2623
|
-
const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
|
|
2624
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
2625
|
-
if (vis === "public") {
|
|
2626
|
-
exportedSymbols.push({
|
|
2627
|
-
name,
|
|
2628
|
-
kind: "function",
|
|
2629
|
-
signature,
|
|
2630
|
-
line: lineNum,
|
|
2631
|
-
structuralHash,
|
|
2632
|
-
nodeCount,
|
|
2633
|
-
astNodeCount,
|
|
2634
|
-
file: rel,
|
|
2635
|
-
isExported: true
|
|
2636
|
-
});
|
|
2637
|
-
} else {
|
|
2638
|
-
internalFunctions.push({
|
|
2639
|
-
name,
|
|
2640
|
-
kind: "function",
|
|
2641
|
-
signature,
|
|
2642
|
-
line: lineNum,
|
|
2643
|
-
structuralHash,
|
|
2644
|
-
nodeCount,
|
|
2645
|
-
astNodeCount,
|
|
2646
|
-
file: rel,
|
|
2647
|
-
isExported: false
|
|
2648
|
-
});
|
|
2649
|
-
}
|
|
2650
|
-
}
|
|
2651
|
-
return {
|
|
2652
|
-
relativePath: rel,
|
|
2653
|
-
contentSha256,
|
|
2654
|
-
language: "csharp",
|
|
2655
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2656
|
-
...size !== void 0 ? { size } : {},
|
|
2657
|
-
imports,
|
|
2658
|
-
exportedSymbols,
|
|
2659
|
-
internalFunctions
|
|
2660
|
-
};
|
|
2661
|
-
},
|
|
2662
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
2663
|
-
const spec = imp.rawSpecifier.trim();
|
|
2664
|
-
const fromNorm = normalizeRelPath(fromRelPath);
|
|
2665
|
-
const hits = [];
|
|
2666
|
-
for (const [fileRel, namespaces] of ctx.csharpNamespacesByFile.entries()) {
|
|
2667
|
-
if (fileRel !== fromNorm && namespaces.includes(spec)) {
|
|
2668
|
-
hits.push(fileRel);
|
|
2669
|
-
}
|
|
2670
|
-
}
|
|
2671
|
-
if (hits.length > 0) return { kind: "local", resolvedPaths: hits.sort(compareText) };
|
|
2672
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2673
|
-
},
|
|
2674
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
2675
|
-
const ns = ctx?.csharpNamespacesByFile.get(normalizeRelPath(symbol.file))?.[0];
|
|
2676
|
-
return ns ? `using ${ns}; // ${symbol.name}` : `// ${symbol.name} in ${symbol.file}`;
|
|
2677
|
-
}
|
|
2678
|
-
};
|
|
2679
|
-
var phpAdapter = {
|
|
2680
|
-
id: "php",
|
|
2681
|
-
extensions: [".php"],
|
|
2682
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2683
|
-
const rel = normalizeRelPath(relativePath);
|
|
2684
|
-
const contentSha256 = sha256Hex(source);
|
|
2685
|
-
const imports = [];
|
|
2686
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2687
|
-
const exportedSymbols = [];
|
|
2688
|
-
const internalFunctions = [];
|
|
2689
|
-
const useRe = /^\s*use\s+(?:function\s+|const\s+)?([a-zA-Z_\\][a-zA-Z0-9_\\]*)(?:\s+as\s+[a-zA-Z_][a-zA-Z0-9_]*)?\s*;/gm;
|
|
2690
|
-
let um;
|
|
2691
|
-
while ((um = useRe.exec(source)) !== null) {
|
|
2692
|
-
if (um[1]) {
|
|
2693
|
-
const clean = um[1].replace(/^\\/, "");
|
|
2694
|
-
const parts = clean.split("\\");
|
|
2695
|
-
pushUniqueImport(imports, importSeen, clean, [parts[parts.length - 1] ?? clean], false);
|
|
2696
|
-
}
|
|
2697
|
-
}
|
|
2698
|
-
const reqRe = /\b(?:require|require_once|include|include_once)\s*\(?\s*['"]([^'"]+)['"]\s*\)?\s*;/g;
|
|
2699
|
-
let rm;
|
|
2700
|
-
while ((rm = reqRe.exec(source)) !== null) {
|
|
2701
|
-
if (rm[1]) pushUniqueImport(imports, importSeen, rm[1], [], false);
|
|
2702
|
-
}
|
|
2703
|
-
const typeRe = /^\s*(?:final\s+|abstract\s+|readonly\s+)?(class|interface|trait|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
|
|
2704
|
-
let tm;
|
|
2705
|
-
while ((tm = typeRe.exec(source)) !== null) {
|
|
2706
|
-
const kw = tm[1];
|
|
2707
|
-
const name = tm[2];
|
|
2708
|
-
exportedSymbols.push({
|
|
2709
|
-
name,
|
|
2710
|
-
kind: kw === "interface" || kw === "trait" ? "interface" : kw === "enum" ? "enum" : "class",
|
|
2711
|
-
signature: `${kw} ${name}`,
|
|
2712
|
-
line: lineOfOffset(source, tm.index),
|
|
2713
|
-
file: rel,
|
|
2714
|
-
isExported: true
|
|
2715
|
-
});
|
|
2716
|
-
}
|
|
2717
|
-
const fnRe = /^\s*(?:(public|private|protected)\s+)?(?:static\s+)?function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?::\s*([^{\n]+))?\s*\{/gm;
|
|
2718
|
-
let fm;
|
|
2719
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
2720
|
-
const vis = fm[1] ?? "public";
|
|
2721
|
-
const name = fm[2];
|
|
2722
|
-
const rawParams = collapseWs(fm[3] ?? "");
|
|
2723
|
-
const rawRet = collapseWs(fm[4] ?? "");
|
|
2724
|
-
const openIdx = fm.index + fm[0].length - 1;
|
|
2725
|
-
const closeIdx = findMatchingBrace(source, openIdx, true);
|
|
2726
|
-
const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
|
|
2727
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2728
|
-
bodySource,
|
|
2729
|
-
rawParams,
|
|
2730
|
-
{ hashComments: true }
|
|
2731
|
-
);
|
|
2732
|
-
const signature = truncateSig(`(${rawParams})${rawRet ? `: ${rawRet}` : ""}`);
|
|
2733
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
2734
|
-
if (vis === "public") {
|
|
2735
|
-
exportedSymbols.push({
|
|
2736
|
-
name,
|
|
2737
|
-
kind: "function",
|
|
2738
|
-
signature,
|
|
2739
|
-
line: lineNum,
|
|
2740
|
-
structuralHash,
|
|
2741
|
-
nodeCount,
|
|
2742
|
-
astNodeCount,
|
|
2743
|
-
file: rel,
|
|
2744
|
-
isExported: true
|
|
2745
|
-
});
|
|
2746
|
-
} else {
|
|
2747
|
-
internalFunctions.push({
|
|
2748
|
-
name,
|
|
2749
|
-
kind: "function",
|
|
2750
|
-
signature,
|
|
2751
|
-
line: lineNum,
|
|
2752
|
-
structuralHash,
|
|
2753
|
-
nodeCount,
|
|
2754
|
-
astNodeCount,
|
|
2755
|
-
file: rel,
|
|
2756
|
-
isExported: false
|
|
2757
|
-
});
|
|
2758
|
-
}
|
|
2759
|
-
}
|
|
2760
|
-
return {
|
|
2761
|
-
relativePath: rel,
|
|
2762
|
-
contentSha256,
|
|
2763
|
-
language: "php",
|
|
2764
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2765
|
-
...size !== void 0 ? { size } : {},
|
|
2766
|
-
imports,
|
|
2767
|
-
exportedSymbols,
|
|
2768
|
-
internalFunctions
|
|
2769
|
-
};
|
|
2770
|
-
},
|
|
2771
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
2772
|
-
const spec = imp.rawSpecifier.trim();
|
|
2773
|
-
const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
|
|
2774
|
-
if (spec.startsWith("./") || spec.startsWith("../") || spec.endsWith(".php")) {
|
|
2775
|
-
const cand = path4.posix.normalize(path4.posix.join(fromDir, spec));
|
|
2776
|
-
const hit = lookupKnownFile(ctx, cand) ?? lookupKnownFile(ctx, spec);
|
|
2777
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
2778
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: cand };
|
|
2779
|
-
}
|
|
2780
|
-
const normalizedSpec = spec.replace(/^\\/, "");
|
|
2781
|
-
const sorted = [...ctx.phpPsr4Mappings].sort((a, b) => b.prefix.length - a.prefix.length);
|
|
2782
|
-
for (const mapping of sorted) {
|
|
2783
|
-
if (normalizedSpec.startsWith(mapping.prefix)) {
|
|
2784
|
-
const rest = normalizedSpec.slice(mapping.prefix.length).replace(/\\/g, "/");
|
|
2785
|
-
const cand = normalizeRelPath(`${mapping.dir}/${rest}.php`);
|
|
2786
|
-
const hit = lookupKnownFile(ctx, cand);
|
|
2787
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
2788
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: cand };
|
|
2789
|
-
}
|
|
2790
|
-
}
|
|
2791
|
-
const directHit = lookupKnownFile(ctx, `${normalizedSpec.replace(/\\/g, "/")}.php`);
|
|
2792
|
-
if (directHit) return { kind: "local", resolvedPaths: [directHit] };
|
|
2793
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2794
|
-
},
|
|
2795
|
-
formatImportStatement(_fromRelPath, symbol, ctx) {
|
|
2796
|
-
const ns = ctx?.phpNamespacesByFile.get(normalizeRelPath(symbol.file));
|
|
2797
|
-
return ns ? `use ${ns}\\${symbol.name};` : `require_once '${symbol.file}'; // ${symbol.name}`;
|
|
2798
|
-
}
|
|
2799
|
-
};
|
|
2800
|
-
var rubyAdapter = {
|
|
2801
|
-
id: "ruby",
|
|
2802
|
-
extensions: [".rb"],
|
|
2803
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2804
|
-
const rel = normalizeRelPath(relativePath);
|
|
2805
|
-
const contentSha256 = sha256Hex(source);
|
|
2806
|
-
const imports = [];
|
|
2807
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2808
|
-
const exportedSymbols = [];
|
|
2809
|
-
const internalFunctions = [];
|
|
2810
|
-
const lines = source.split(/\r?\n/);
|
|
2811
|
-
let inPrivateSection = false;
|
|
2812
|
-
for (let i = 0; i < lines.length; i += 1) {
|
|
2813
|
-
const line = lines[i];
|
|
2814
|
-
const trimmed = line.trim();
|
|
2815
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2816
|
-
if (trimmed === "private") {
|
|
2817
|
-
inPrivateSection = true;
|
|
2818
|
-
continue;
|
|
2819
|
-
}
|
|
2820
|
-
if (trimmed === "public") {
|
|
2821
|
-
inPrivateSection = false;
|
|
2822
|
-
continue;
|
|
2823
|
-
}
|
|
2824
|
-
const reqRel = /^require_relative\s+['"]([^'"]+)['"]/.exec(trimmed);
|
|
2825
|
-
if (reqRel && reqRel[1]) {
|
|
2826
|
-
pushUniqueImport(imports, importSeen, `rel:${reqRel[1]}`, [], false);
|
|
2827
|
-
continue;
|
|
2828
|
-
}
|
|
2829
|
-
const req = /^require\s+['"]([^'"]+)['"]/.exec(trimmed);
|
|
2830
|
-
if (req && req[1]) {
|
|
2831
|
-
pushUniqueImport(imports, importSeen, req[1], [], false);
|
|
2832
|
-
continue;
|
|
2833
|
-
}
|
|
2834
|
-
const clsMod = /^(class|module)\s+([A-Z][a-zA-Z0-9_:]*)/.exec(trimmed);
|
|
2835
|
-
if (clsMod && clsMod[1] && clsMod[2]) {
|
|
2836
|
-
inPrivateSection = false;
|
|
2837
|
-
exportedSymbols.push({
|
|
2838
|
-
name: clsMod[2],
|
|
2839
|
-
kind: "class",
|
|
2840
|
-
signature: `${clsMod[1]} ${clsMod[2]}`,
|
|
2841
|
-
line: i + 1,
|
|
2842
|
-
file: rel,
|
|
2843
|
-
isExported: true
|
|
2844
|
-
});
|
|
2845
|
-
continue;
|
|
2846
|
-
}
|
|
2847
|
-
const defMatch = /^(\s*)def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_!?]*)(?:\(([^)]*)\))?/.exec(line);
|
|
2848
|
-
if (defMatch && defMatch[2]) {
|
|
2849
|
-
const baseIndent = (defMatch[1] ?? "").length;
|
|
2850
|
-
const name = defMatch[2];
|
|
2851
|
-
const rawParams = collapseWs(defMatch[3] ?? "");
|
|
2852
|
-
const bodyLines = [];
|
|
2853
|
-
let j = i + 1;
|
|
2854
|
-
while (j < lines.length) {
|
|
2855
|
-
const jl = lines[j];
|
|
2856
|
-
const jIndent = jl.length - jl.trimStart().length;
|
|
2857
|
-
if (jl.trim() === "end" && jIndent <= baseIndent) {
|
|
2858
|
-
break;
|
|
2859
|
-
}
|
|
2860
|
-
bodyLines.push(jl);
|
|
2861
|
-
j += 1;
|
|
2862
|
-
}
|
|
2863
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2864
|
-
bodyLines.join("\n"),
|
|
2865
|
-
rawParams,
|
|
2866
|
-
{ hashComments: true }
|
|
2867
|
-
);
|
|
2868
|
-
const signature = truncateSig(`(${rawParams})`);
|
|
2869
|
-
if (!inPrivateSection && !name.startsWith("_")) {
|
|
2870
|
-
exportedSymbols.push({
|
|
2871
|
-
name,
|
|
2872
|
-
kind: "function",
|
|
2873
|
-
signature,
|
|
2874
|
-
line: i + 1,
|
|
2875
|
-
structuralHash,
|
|
2876
|
-
nodeCount,
|
|
2877
|
-
astNodeCount,
|
|
2878
|
-
file: rel,
|
|
2879
|
-
isExported: true
|
|
2880
|
-
});
|
|
2881
|
-
} else {
|
|
2882
|
-
internalFunctions.push({
|
|
2883
|
-
name,
|
|
2884
|
-
kind: "function",
|
|
2885
|
-
signature,
|
|
2886
|
-
line: i + 1,
|
|
2887
|
-
structuralHash,
|
|
2888
|
-
nodeCount,
|
|
2889
|
-
astNodeCount,
|
|
2890
|
-
file: rel,
|
|
2891
|
-
isExported: false
|
|
2892
|
-
});
|
|
2893
|
-
}
|
|
2894
|
-
i = j;
|
|
2895
|
-
}
|
|
2896
|
-
}
|
|
2897
|
-
return {
|
|
2898
|
-
relativePath: rel,
|
|
2899
|
-
contentSha256,
|
|
2900
|
-
language: "ruby",
|
|
2901
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
2902
|
-
...size !== void 0 ? { size } : {},
|
|
2903
|
-
imports,
|
|
2904
|
-
exportedSymbols,
|
|
2905
|
-
internalFunctions
|
|
2906
|
-
};
|
|
2907
|
-
},
|
|
2908
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
2909
|
-
const spec = imp.rawSpecifier.trim();
|
|
2910
|
-
const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
|
|
2911
|
-
if (spec.startsWith("rel:")) {
|
|
2912
|
-
const target = spec.slice(4);
|
|
2913
|
-
const base = path4.posix.normalize(path4.posix.join(fromDir, target));
|
|
2914
|
-
const hit = lookupKnownFile(ctx, base) ?? lookupKnownFile(ctx, `${base}.rb`);
|
|
2915
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
2916
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: base.endsWith(".rb") ? base : `${base}.rb` };
|
|
2917
|
-
}
|
|
2918
|
-
const libHit = lookupKnownFile(ctx, `lib/${spec}.rb`) ?? lookupKnownFile(ctx, `lib/${spec}`) ?? lookupKnownFile(ctx, `${spec}.rb`);
|
|
2919
|
-
if (libHit) return { kind: "local", resolvedPaths: [libHit] };
|
|
2920
|
-
return { kind: "external", resolvedPaths: [], externalLabel: spec };
|
|
2921
|
-
},
|
|
2922
|
-
formatImportStatement(fromRelPath, symbol) {
|
|
2923
|
-
const fromDir = fromRelPath ? path4.posix.dirname(normalizeRelPath(fromRelPath)) : ".";
|
|
2924
|
-
const rel = path4.posix.relative(fromDir, normalizeRelPath(symbol.file)).replace(/\.rb$/i, "");
|
|
2925
|
-
const spec = rel.startsWith(".") ? rel : `./${rel}`;
|
|
2926
|
-
return `require_relative '${spec}' # ${symbol.name}`;
|
|
2927
|
-
}
|
|
2928
|
-
};
|
|
2929
|
-
var cppAdapter = {
|
|
2930
|
-
id: "cpp",
|
|
2931
|
-
extensions: [".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"],
|
|
2932
|
-
extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
|
|
2933
|
-
const rel = normalizeRelPath(relativePath);
|
|
2934
|
-
const contentSha256 = sha256Hex(source);
|
|
2935
|
-
const imports = [];
|
|
2936
|
-
const importSeen = /* @__PURE__ */ new Map();
|
|
2937
|
-
const exportedSymbols = [];
|
|
2938
|
-
const internalFunctions = [];
|
|
2939
|
-
const incRe = /^\s*#include\s*(?:"([^"]+)"|<([^>]+)>)/gm;
|
|
2940
|
-
let im;
|
|
2941
|
-
while ((im = incRe.exec(source)) !== null) {
|
|
2942
|
-
if (im[1]) pushUniqueImport(imports, importSeen, `"${im[1]}"`, [], false);
|
|
2943
|
-
else if (im[2]) pushUniqueImport(imports, importSeen, `<${im[2]}>`, [], false);
|
|
2944
|
-
}
|
|
2945
|
-
const typeRe = /^\s*(?:typedef\s+)?(struct|class|enum(?:\s+class)?)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
|
|
2946
|
-
let tm;
|
|
2947
|
-
while ((tm = typeRe.exec(source)) !== null) {
|
|
2948
|
-
const kw = tm[1];
|
|
2949
|
-
const name = tm[2];
|
|
2950
|
-
exportedSymbols.push({
|
|
2951
|
-
name,
|
|
2952
|
-
kind: kw.startsWith("enum") ? "enum" : "class",
|
|
2953
|
-
signature: `${kw} ${name}`,
|
|
2954
|
-
line: lineOfOffset(source, tm.index),
|
|
2955
|
-
file: rel,
|
|
2956
|
-
isExported: true
|
|
2957
|
-
});
|
|
2958
|
-
}
|
|
2959
|
-
const fnRe = /^(static\s+)?(?:inline\s+|constexpr\s+|extern\s+)?([a-zA-Z_][a-zA-Z0-9_:*&<> ]*?)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?:const\s*)?(?:noexcept\s*)?\{/gm;
|
|
2960
|
-
let fm;
|
|
2961
|
-
while ((fm = fnRe.exec(source)) !== null) {
|
|
2962
|
-
const isStatic = Boolean(fm[1]);
|
|
2963
|
-
const rawRet = collapseWs(fm[2] ?? "");
|
|
2964
|
-
const name = fm[3];
|
|
2965
|
-
if (["if", "for", "while", "switch", "catch", "namespace"].includes(name)) continue;
|
|
2966
|
-
const rawParams = collapseWs(fm[4] ?? "");
|
|
2967
|
-
const openIdx = fm.index + fm[0].length - 1;
|
|
2968
|
-
const closeIdx = findMatchingBrace(source, openIdx, false);
|
|
2969
|
-
const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
|
|
2970
|
-
const formattedParams = splitTopLevelCommas(rawParams).map((p) => {
|
|
2971
|
-
const toks = collapseWs(p).split(" ");
|
|
2972
|
-
return toks.length >= 2 ? `${toks[toks.length - 1].replace(/^[*&]+/, "")}: ${toks.slice(0, -1).join(" ")}` : p;
|
|
2973
|
-
}).join(", ");
|
|
2974
|
-
const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
|
|
2975
|
-
bodySource,
|
|
2976
|
-
formattedParams
|
|
2977
|
-
);
|
|
2978
|
-
const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
|
|
2979
|
-
const lineNum = lineOfOffset(source, fm.index);
|
|
2980
|
-
if (!isStatic) {
|
|
2981
|
-
exportedSymbols.push({
|
|
2982
|
-
name,
|
|
2983
|
-
kind: "function",
|
|
2984
|
-
signature,
|
|
2985
|
-
line: lineNum,
|
|
2986
|
-
structuralHash,
|
|
2987
|
-
nodeCount,
|
|
2988
|
-
astNodeCount,
|
|
2989
|
-
file: rel,
|
|
2990
|
-
isExported: true
|
|
2991
|
-
});
|
|
2992
|
-
} else {
|
|
2993
|
-
internalFunctions.push({
|
|
2994
|
-
name,
|
|
2995
|
-
kind: "function",
|
|
2996
|
-
signature,
|
|
2997
|
-
line: lineNum,
|
|
2998
|
-
structuralHash,
|
|
2999
|
-
nodeCount,
|
|
3000
|
-
astNodeCount,
|
|
3001
|
-
file: rel,
|
|
3002
|
-
isExported: false
|
|
3003
|
-
});
|
|
3004
|
-
}
|
|
3005
|
-
}
|
|
3006
|
-
return {
|
|
3007
|
-
relativePath: rel,
|
|
3008
|
-
contentSha256,
|
|
3009
|
-
language: "cpp",
|
|
3010
|
-
...mtimeMs !== void 0 ? { mtimeMs } : {},
|
|
3011
|
-
...size !== void 0 ? { size } : {},
|
|
3012
|
-
imports,
|
|
3013
|
-
exportedSymbols,
|
|
3014
|
-
internalFunctions
|
|
3015
|
-
};
|
|
3016
|
-
},
|
|
3017
|
-
resolveImport(imp, fromRelPath, ctx) {
|
|
3018
|
-
const spec = imp.rawSpecifier.trim();
|
|
3019
|
-
const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
|
|
3020
|
-
const isQuoted = spec.startsWith('"') && spec.endsWith('"');
|
|
3021
|
-
const clean = spec.replace(/^["<]|[">]$/g, "");
|
|
3022
|
-
if (isQuoted) {
|
|
3023
|
-
const localCand = path4.posix.normalize(path4.posix.join(fromDir, clean));
|
|
3024
|
-
const hit = lookupKnownFile(ctx, localCand) ?? lookupKnownFile(ctx, `include/${clean}`) ?? lookupKnownFile(ctx, `src/${clean}`) ?? lookupKnownFile(ctx, clean);
|
|
3025
|
-
if (hit) return { kind: "local", resolvedPaths: [hit] };
|
|
3026
|
-
return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: localCand };
|
|
3027
|
-
}
|
|
3028
|
-
const incHit = lookupKnownFile(ctx, `include/${clean}`);
|
|
3029
|
-
if (incHit) return { kind: "local", resolvedPaths: [incHit] };
|
|
3030
|
-
return { kind: "external", resolvedPaths: [], externalLabel: clean };
|
|
3031
|
-
},
|
|
3032
|
-
formatImportStatement(fromRelPath, symbol) {
|
|
3033
|
-
const target = normalizeRelPath(symbol.file);
|
|
3034
|
-
if (fromRelPath) {
|
|
3035
|
-
const rel = path4.posix.relative(path4.posix.dirname(normalizeRelPath(fromRelPath)), target);
|
|
3036
|
-
return `#include "${rel}" // ${symbol.name}`;
|
|
3037
|
-
}
|
|
3038
|
-
return `#include "${target}" // ${symbol.name}`;
|
|
3039
|
-
}
|
|
3040
|
-
};
|
|
3041
|
-
var PolyglotAdapterRegistry = class {
|
|
3042
|
-
byExtension = /* @__PURE__ */ new Map();
|
|
3043
|
-
byId = /* @__PURE__ */ new Map();
|
|
3044
|
-
constructor(adapters) {
|
|
3045
|
-
for (const adapter of adapters) {
|
|
3046
|
-
this.register(adapter);
|
|
3047
|
-
}
|
|
3048
|
-
}
|
|
3049
|
-
register(adapter) {
|
|
3050
|
-
this.byId.set(adapter.id, adapter);
|
|
3051
|
-
for (const ext of adapter.extensions) {
|
|
3052
|
-
this.byExtension.set(ext.toLowerCase(), adapter);
|
|
3053
|
-
}
|
|
3054
|
-
}
|
|
3055
|
-
get supportedExtensions() {
|
|
3056
|
-
return [...this.byExtension.keys()];
|
|
3057
|
-
}
|
|
3058
|
-
detectLanguage(filePath) {
|
|
3059
|
-
const ext = path4.extname(filePath).toLowerCase();
|
|
3060
|
-
return this.byExtension.get(ext)?.id ?? "unknown";
|
|
3061
|
-
}
|
|
3062
|
-
getAdapterForFile(filePath) {
|
|
3063
|
-
const ext = path4.extname(filePath).toLowerCase();
|
|
3064
|
-
return this.byExtension.get(ext);
|
|
3065
|
-
}
|
|
3066
|
-
getAdapterById(id) {
|
|
3067
|
-
return this.byId.get(id);
|
|
3068
|
-
}
|
|
3069
|
-
extractManifest(source, absolutePath, relativePath, mtimeMs, size) {
|
|
3070
|
-
const adapter = this.getAdapterForFile(absolutePath) ?? this.getAdapterForFile(relativePath);
|
|
3071
|
-
if (adapter) {
|
|
3072
|
-
return adapter.extractManifest(source, absolutePath, relativePath, mtimeMs, size);
|
|
3073
|
-
}
|
|
3074
|
-
return extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size);
|
|
3075
|
-
}
|
|
3076
|
-
formatImportForSymbol(fromRelPath, symbol, ctx) {
|
|
3077
|
-
const adapter = this.getAdapterForFile(symbol.file);
|
|
3078
|
-
if (adapter) {
|
|
3079
|
-
return adapter.formatImportStatement(fromRelPath, symbol, ctx);
|
|
3080
|
-
}
|
|
3081
|
-
return formatJsTsImport(fromRelPath, symbol);
|
|
3082
|
-
}
|
|
3083
|
-
areLanguagesCompatible(fileA, fileB) {
|
|
3084
|
-
const langA = this.detectLanguage(fileA);
|
|
3085
|
-
const langB = this.detectLanguage(fileB);
|
|
3086
|
-
if (langA === langB) return true;
|
|
3087
|
-
const jsTs = /* @__PURE__ */ new Set(["typescript", "javascript"]);
|
|
3088
|
-
if (jsTs.has(langA) && jsTs.has(langB)) return true;
|
|
3089
|
-
const jvm = /* @__PURE__ */ new Set(["java", "kotlin"]);
|
|
3090
|
-
if (jvm.has(langA) && jvm.has(langB)) return true;
|
|
3091
|
-
return false;
|
|
3092
|
-
}
|
|
3093
|
-
};
|
|
3094
|
-
var defaultPolyglotRegistry = new PolyglotAdapterRegistry([
|
|
3095
|
-
createJsTsAdapter("typescript", [".ts", ".tsx", ".mts", ".cts"]),
|
|
3096
|
-
createJsTsAdapter("javascript", [".js", ".jsx", ".mjs", ".cjs"]),
|
|
3097
|
-
pythonAdapter,
|
|
3098
|
-
goAdapter,
|
|
3099
|
-
rustAdapter,
|
|
3100
|
-
javaAdapter,
|
|
3101
|
-
kotlinAdapter,
|
|
3102
|
-
csharpAdapter,
|
|
3103
|
-
phpAdapter,
|
|
3104
|
-
rubyAdapter,
|
|
3105
|
-
cppAdapter
|
|
3106
|
-
]);
|
|
3107
|
-
function safeReadUtf8(filePath) {
|
|
3108
|
-
try {
|
|
3109
|
-
return existsSync2(filePath) ? readFileSync2(filePath, "utf8") : null;
|
|
3110
|
-
} catch {
|
|
3111
|
-
return null;
|
|
3112
|
-
}
|
|
3113
|
-
}
|
|
3114
|
-
function buildWorkspaceResolutionContext(root, rootReal, allRelativePaths, configFileRelPaths = []) {
|
|
3115
|
-
const knownFiles = /* @__PURE__ */ new Map();
|
|
3116
|
-
const sortedPaths = [...new Set(allRelativePaths.map(normalizeRelPath))].sort(compareText);
|
|
3117
|
-
for (const rel of sortedPaths) {
|
|
3118
|
-
knownFiles.set(rel, rel);
|
|
3119
|
-
knownFiles.set(rel.toLowerCase(), rel);
|
|
3120
|
-
}
|
|
3121
|
-
const goModuleDirs = /* @__PURE__ */ new Map();
|
|
3122
|
-
const pythonSourceRoots = /* @__PURE__ */ new Set([""]);
|
|
3123
|
-
const rustCrates = [];
|
|
3124
|
-
const phpPsr4Mappings = [];
|
|
3125
|
-
const javaPackagesByFile = /* @__PURE__ */ new Map();
|
|
3126
|
-
const csharpNamespacesByFile = /* @__PURE__ */ new Map();
|
|
3127
|
-
const phpNamespacesByFile = /* @__PURE__ */ new Map();
|
|
3128
|
-
if (sortedPaths.some((p) => p.startsWith("src/"))) {
|
|
3129
|
-
pythonSourceRoots.add("src");
|
|
3130
|
-
}
|
|
3131
|
-
const inspectConfigRel = (relPath) => {
|
|
3132
|
-
const norm = normalizeRelPath(relPath);
|
|
3133
|
-
const base = path4.posix.basename(norm).toLowerCase();
|
|
3134
|
-
const dirRaw = path4.posix.dirname(norm);
|
|
3135
|
-
const dir = dirRaw === "." ? "" : dirRaw;
|
|
3136
|
-
const raw = safeReadUtf8(path4.join(rootReal, norm));
|
|
3137
|
-
if (!raw) return;
|
|
3138
|
-
if (base === "go.mod") {
|
|
3139
|
-
const m = /^\s*module\s+([^\s/]+(?:\/[^\s/]+)*)/m.exec(raw);
|
|
3140
|
-
if (m && m[1]) {
|
|
3141
|
-
goModuleDirs.set(dir, m[1].trim().replace(/^"|"$/g, ""));
|
|
3142
|
-
}
|
|
3143
|
-
} else if (base === "cargo.toml") {
|
|
3144
|
-
const pkgSection = /\[package\]([\s\S]*?)(?:\n\[|$)/.exec(raw)?.[1] ?? raw;
|
|
3145
|
-
const nameMatch = /^\s*name\s*=\s*["']([^"']+)["']/m.exec(pkgSection);
|
|
3146
|
-
const srcDir = dir ? `${dir}/src` : "src";
|
|
3147
|
-
const hasSrc = sortedPaths.some((p) => p.startsWith(`${srcDir}/`));
|
|
3148
|
-
rustCrates.push({
|
|
3149
|
-
crateDir: dir,
|
|
3150
|
-
srcDir: hasSrc ? srcDir : dir,
|
|
3151
|
-
...nameMatch?.[1] ? { crateName: nameMatch[1] } : {}
|
|
3152
|
-
});
|
|
3153
|
-
} else if (base === "pyproject.toml") {
|
|
3154
|
-
if (dir) pythonSourceRoots.add(dir);
|
|
3155
|
-
const srcCandidate = dir ? `${dir}/src` : "src";
|
|
3156
|
-
if (sortedPaths.some((p) => p.startsWith(`${srcCandidate}/`))) {
|
|
3157
|
-
pythonSourceRoots.add(srcCandidate);
|
|
3158
|
-
}
|
|
3159
|
-
const whereMatch = /where\s*=\s*\[([^\]]+)\]/.exec(raw);
|
|
3160
|
-
if (whereMatch && whereMatch[1]) {
|
|
3161
|
-
const strRe = /["']([^"']+)["']/g;
|
|
3162
|
-
let sm;
|
|
3163
|
-
while ((sm = strRe.exec(whereMatch[1])) !== null) {
|
|
3164
|
-
if (sm[1]) {
|
|
3165
|
-
const p = normalizeRelPath(dir ? `${dir}/${sm[1]}` : sm[1]);
|
|
3166
|
-
pythonSourceRoots.add(p === "." ? "" : p);
|
|
3167
|
-
}
|
|
3168
|
-
}
|
|
3169
|
-
}
|
|
3170
|
-
const pkgDirMatch = /package-dir\s*=\s*\{[^}]*["']\s*["']\s*[:=]\s*["']([^"']+)["']/.exec(raw);
|
|
3171
|
-
if (pkgDirMatch && pkgDirMatch[1]) {
|
|
3172
|
-
const p = normalizeRelPath(dir ? `${dir}/${pkgDirMatch[1]}` : pkgDirMatch[1]);
|
|
3173
|
-
pythonSourceRoots.add(p === "." ? "" : p);
|
|
3174
|
-
}
|
|
3175
|
-
} else if (base === "composer.json") {
|
|
3176
|
-
try {
|
|
3177
|
-
const json = JSON.parse(raw);
|
|
3178
|
-
const psr4Maps = [json.autoload?.["psr-4"], json["autoload-dev"]?.["psr-4"]];
|
|
3179
|
-
for (const mapObj of psr4Maps) {
|
|
3180
|
-
if (!mapObj || typeof mapObj !== "object") continue;
|
|
3181
|
-
for (const [prefix, target] of Object.entries(mapObj)) {
|
|
3182
|
-
const targets = Array.isArray(target) ? target : [target];
|
|
3183
|
-
for (const t of targets) {
|
|
3184
|
-
if (typeof t !== "string") continue;
|
|
3185
|
-
const resolvedDir = normalizeRelPath(dir ? `${dir}/${t}` : t).replace(/\/$/, "");
|
|
3186
|
-
phpPsr4Mappings.push({ prefix, dir: resolvedDir });
|
|
3187
|
-
}
|
|
3188
|
-
}
|
|
3189
|
-
}
|
|
3190
|
-
} catch {
|
|
3191
|
-
}
|
|
3192
|
-
}
|
|
3193
|
-
};
|
|
3194
|
-
for (const cfg of configFileRelPaths) {
|
|
3195
|
-
inspectConfigRel(cfg);
|
|
3196
|
-
}
|
|
3197
|
-
for (const rootCfg of ["go.mod", "Cargo.toml", "pyproject.toml", "composer.json"]) {
|
|
3198
|
-
if (!configFileRelPaths.includes(rootCfg)) {
|
|
3199
|
-
inspectConfigRel(rootCfg);
|
|
3200
|
-
}
|
|
3201
|
-
}
|
|
3202
|
-
for (const rel of sortedPaths) {
|
|
3203
|
-
const ext = path4.posix.extname(rel).toLowerCase();
|
|
3204
|
-
if (ext === ".java" || ext === ".kt" || ext === ".kts") {
|
|
3205
|
-
const content = safeReadUtf8(path4.join(rootReal, rel));
|
|
3206
|
-
if (content) {
|
|
3207
|
-
const pm = /^\s*package\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*;?/m.exec(content);
|
|
3208
|
-
if (pm && pm[1]) javaPackagesByFile.set(rel, pm[1]);
|
|
3209
|
-
}
|
|
3210
|
-
} else if (ext === ".cs") {
|
|
3211
|
-
const content = safeReadUtf8(path4.join(rootReal, rel));
|
|
3212
|
-
if (content) {
|
|
3213
|
-
const nsList = [];
|
|
3214
|
-
const nsRe = /^\s*namespace\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*[;{]/gm;
|
|
3215
|
-
let nm;
|
|
3216
|
-
while ((nm = nsRe.exec(content)) !== null) {
|
|
3217
|
-
if (nm[1]) nsList.push(nm[1]);
|
|
3218
|
-
}
|
|
3219
|
-
if (nsList.length > 0) csharpNamespacesByFile.set(rel, nsList);
|
|
3220
|
-
}
|
|
3221
|
-
} else if (ext === ".php") {
|
|
3222
|
-
const content = safeReadUtf8(path4.join(rootReal, rel));
|
|
3223
|
-
if (content) {
|
|
3224
|
-
const nm = /^\s*namespace\s+([a-zA-Z_\\][a-zA-Z0-9_\\]*)\s*[;{]/m.exec(content);
|
|
3225
|
-
if (nm && nm[1]) phpNamespacesByFile.set(rel, nm[1].replace(/^\\/, ""));
|
|
3226
|
-
}
|
|
3227
|
-
}
|
|
3228
|
-
}
|
|
3229
|
-
const goModulePath = goModuleDirs.get("") ?? [...goModuleDirs.values()][0];
|
|
3230
|
-
return {
|
|
3231
|
-
root: toPosix(root),
|
|
3232
|
-
rootReal: toPosix(rootReal),
|
|
3233
|
-
knownFiles,
|
|
3234
|
-
allRelativePaths: sortedPaths,
|
|
3235
|
-
...goModulePath ? { goModulePath } : {},
|
|
3236
|
-
goModuleDirs,
|
|
3237
|
-
pythonSourceRoots: [...pythonSourceRoots],
|
|
3238
|
-
rustCrates,
|
|
3239
|
-
phpPsr4Mappings,
|
|
3240
|
-
javaPackagesByFile,
|
|
3241
|
-
csharpNamespacesByFile,
|
|
3242
|
-
phpNamespacesByFile
|
|
3243
|
-
};
|
|
3244
|
-
}
|
|
3245
|
-
|
|
3246
|
-
// ../engine/src/indexer.ts
|
|
3247
|
-
var SOURCE_EXTENSIONS = new Set(defaultPolyglotRegistry.supportedExtensions);
|
|
3248
|
-
var NON_CODE_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
3249
|
-
".css",
|
|
3250
|
-
".scss",
|
|
3251
|
-
".less",
|
|
3252
|
-
".svg",
|
|
3253
|
-
".png",
|
|
3254
|
-
".jpg",
|
|
3255
|
-
".jpeg",
|
|
3256
|
-
".webp",
|
|
3257
|
-
".gif",
|
|
3258
|
-
".ico",
|
|
3259
|
-
".woff",
|
|
3260
|
-
".woff2",
|
|
3261
|
-
".ttf",
|
|
3262
|
-
".wasm",
|
|
3263
|
-
".json",
|
|
3264
|
-
".glsl",
|
|
3265
|
-
".sql",
|
|
3266
|
-
".txt",
|
|
3267
|
-
".md"
|
|
3268
|
-
]);
|
|
3269
|
-
function stripImportQueryAndHash(specifier) {
|
|
3270
|
-
const trimmed = specifier.trim();
|
|
3271
|
-
const qIdx = trimmed.indexOf("?");
|
|
3272
|
-
const hIdx = trimmed.indexOf("#");
|
|
3273
|
-
let cut = trimmed.length;
|
|
3274
|
-
if (qIdx !== -1 && qIdx < cut) cut = qIdx;
|
|
3275
|
-
if (hIdx !== -1 && hIdx < cut) cut = hIdx;
|
|
3276
|
-
return trimmed.slice(0, cut);
|
|
3277
|
-
}
|
|
3278
|
-
function isRelativeImportSpecifier(specifier) {
|
|
3279
|
-
const clean = stripImportQueryAndHash(specifier);
|
|
3280
|
-
return clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
|
|
3281
|
-
}
|
|
3282
|
-
function isNonCodeAssetSpecifier(specifier) {
|
|
3283
|
-
const clean = stripImportQueryAndHash(specifier);
|
|
3284
|
-
const ext = path5.posix.extname(clean).toLowerCase();
|
|
3285
|
-
return ext.length > 0 && NON_CODE_ASSET_EXTENSIONS.has(ext) && !SOURCE_EXTENSIONS.has(ext);
|
|
3286
|
-
}
|
|
3287
|
-
var FIXTURE_OR_SNAPSHOT_DIR_RE = /(^|\/)(__fixtures__|__snapshots__|__mocks__)(\/|$)/i;
|
|
3288
|
-
var FIXTURE_OR_SNAPSHOT_FILE_RE = /\.(snap|fixture)\.[cm]?[jt]sx?$/i;
|
|
3289
|
-
var GENERATED_DIR_SEGMENT_RE = /(^|\/)(generated|__generated__)(\/|$)/i;
|
|
3290
|
-
var GENERATED_FILE_SUFFIX_RE = /\.(gen|generated)(\.[cm]?[jt]sx?)?$/i;
|
|
3291
|
-
function isIntentionalFixtureOrSnapshotFile(filePath) {
|
|
3292
|
-
const norm = normalizeRelPath(filePath);
|
|
3293
|
-
return FIXTURE_OR_SNAPSHOT_DIR_RE.test(norm) || FIXTURE_OR_SNAPSHOT_FILE_RE.test(norm);
|
|
3294
|
-
}
|
|
3295
|
-
function isBuildTimeGeneratedImportTarget(specifier, resolvedCandidate) {
|
|
3296
|
-
const cleanSpec = stripImportQueryAndHash(specifier).replace(/\\/g, "/");
|
|
3297
|
-
if (GENERATED_DIR_SEGMENT_RE.test(cleanSpec) || GENERATED_FILE_SUFFIX_RE.test(cleanSpec)) {
|
|
3298
|
-
return true;
|
|
3299
|
-
}
|
|
3300
|
-
if (resolvedCandidate) {
|
|
3301
|
-
const cleanCandidate = normalizeRelPath(stripImportQueryAndHash(resolvedCandidate));
|
|
3302
|
-
if (GENERATED_DIR_SEGMENT_RE.test(cleanCandidate) || GENERATED_FILE_SUFFIX_RE.test(cleanCandidate)) {
|
|
3303
|
-
return true;
|
|
3304
|
-
}
|
|
3305
|
-
}
|
|
3306
|
-
return false;
|
|
3307
|
-
}
|
|
3308
|
-
var SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
3309
|
-
"node_modules",
|
|
3310
|
-
".git",
|
|
3311
|
-
".hg",
|
|
3312
|
-
".svn",
|
|
3313
|
-
"dist",
|
|
3314
|
-
"out",
|
|
3315
|
-
"coverage",
|
|
3316
|
-
".next",
|
|
3317
|
-
".nuxt",
|
|
3318
|
-
".turbo",
|
|
3319
|
-
".vercel",
|
|
3320
|
-
".output",
|
|
3321
|
-
".cache",
|
|
3322
|
-
".tipolink",
|
|
3323
|
-
".interlink",
|
|
3324
|
-
".chuze",
|
|
3325
|
-
// Harness vaults hold pre-edit copies of source files; indexing them creates
|
|
3326
|
-
// phantom callers, false unresolved-import reports, and bogus duplicate helpers.
|
|
3327
|
-
".moriko",
|
|
3328
|
-
// Polyglot build, cache, and virtual environment directories
|
|
3329
|
-
"__pycache__",
|
|
3330
|
-
".venv",
|
|
3331
|
-
"venv",
|
|
3332
|
-
".pytest_cache",
|
|
3333
|
-
".mypy_cache",
|
|
3334
|
-
".ruff_cache",
|
|
3335
|
-
"target",
|
|
3336
|
-
".gradle",
|
|
3337
|
-
".tox"
|
|
3338
|
-
]);
|
|
3339
|
-
var NATIVE_BUILD_PATH_RE = /(^|\/)(android\/(?:app\/)?build|ios\/build)$/i;
|
|
3340
|
-
function isRealTypeScriptSourceFile(fileName) {
|
|
3341
|
-
const lower = fileName.toLowerCase();
|
|
3342
|
-
if (lower.endsWith(".d.ts") || lower.endsWith(".d.mts") || lower.endsWith(".d.cts")) {
|
|
3343
|
-
return false;
|
|
3344
|
-
}
|
|
3345
|
-
return lower.endsWith(".ts") || lower.endsWith(".tsx") || lower.endsWith(".mts") || lower.endsWith(".cts");
|
|
3346
|
-
}
|
|
3347
|
-
function directoryContainsRealTsSource(fullDirPath) {
|
|
3348
|
-
const maxDepth = 5;
|
|
3349
|
-
const maxEntriesVisited = 500;
|
|
3350
|
-
const queue = [{ dir: fullDirPath, depth: 0 }];
|
|
3351
|
-
let head = 0;
|
|
3352
|
-
let visitedEntries = 0;
|
|
3353
|
-
while (head < queue.length && visitedEntries < maxEntriesVisited) {
|
|
3354
|
-
const current = queue[head];
|
|
3355
|
-
head += 1;
|
|
3356
|
-
if (!current) continue;
|
|
3357
|
-
let entries;
|
|
3358
|
-
try {
|
|
3359
|
-
entries = readdirSync(current.dir, { withFileTypes: true });
|
|
3360
|
-
} catch {
|
|
3361
|
-
continue;
|
|
3362
|
-
}
|
|
3363
|
-
for (const entry of entries) {
|
|
3364
|
-
visitedEntries += 1;
|
|
3365
|
-
if (visitedEntries > maxEntriesVisited) {
|
|
3366
|
-
return false;
|
|
3367
|
-
}
|
|
3368
|
-
if (entry.isFile()) {
|
|
3369
|
-
if (isRealTypeScriptSourceFile(entry.name)) {
|
|
3370
|
-
return true;
|
|
3371
|
-
}
|
|
3372
|
-
} else if (entry.isDirectory() && current.depth < maxDepth) {
|
|
3373
|
-
const lowerChild = entry.name.toLowerCase();
|
|
3374
|
-
if (!SKIP_DIRS.has(entry.name) && !SKIP_DIRS.has(lowerChild) && !lowerChild.startsWith("cmake-build-")) {
|
|
3375
|
-
queue.push({ dir: path5.join(current.dir, entry.name), depth: current.depth + 1 });
|
|
3376
|
-
}
|
|
3377
|
-
}
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
return false;
|
|
3381
|
-
}
|
|
3382
|
-
function shouldSkipDirectory(dirName, fullDirPath, relativeDirPath) {
|
|
3383
|
-
const lowerName = dirName.toLowerCase();
|
|
3384
|
-
if (SKIP_DIRS.has(dirName) || SKIP_DIRS.has(lowerName)) {
|
|
3385
|
-
return true;
|
|
3386
|
-
}
|
|
3387
|
-
if (lowerName.startsWith("cmake-build-")) {
|
|
3388
|
-
return true;
|
|
3389
|
-
}
|
|
3390
|
-
if (lowerName === "build" || lowerName === "vendor") {
|
|
3391
|
-
const relPosix = normalizeRelPath(relativeDirPath).toLowerCase();
|
|
3392
|
-
if (NATIVE_BUILD_PATH_RE.test(relPosix)) {
|
|
3393
|
-
return true;
|
|
3394
|
-
}
|
|
3395
|
-
const segments = relPosix.split("/").filter(Boolean);
|
|
3396
|
-
const parentSegments = segments.slice(0, -1);
|
|
3397
|
-
if (parentSegments.includes("src")) {
|
|
3398
|
-
return false;
|
|
3399
|
-
}
|
|
3400
|
-
return !directoryContainsRealTsSource(fullDirPath);
|
|
3401
|
-
}
|
|
3402
|
-
return false;
|
|
3403
|
-
}
|
|
3404
|
-
var NODE_BUILTINS = new Set(builtinModules);
|
|
3405
|
-
var EXT_SWAPS = {
|
|
3406
|
-
".js": [".ts", ".tsx", ".js", ".jsx"],
|
|
3407
|
-
".jsx": [".tsx", ".jsx", ".ts", ".js"],
|
|
3408
|
-
".mjs": [".mts", ".mjs"],
|
|
3409
|
-
".cjs": [".cts", ".cjs"]
|
|
3410
|
-
};
|
|
3411
|
-
var RESOLVE_SUFFIXES = [
|
|
3412
|
-
".ts",
|
|
3413
|
-
".tsx",
|
|
3414
|
-
".mts",
|
|
3415
|
-
".cts",
|
|
3416
|
-
".js",
|
|
3417
|
-
".jsx",
|
|
3418
|
-
".mjs",
|
|
3419
|
-
".cjs",
|
|
3420
|
-
"/index.ts",
|
|
3421
|
-
"/index.tsx",
|
|
3422
|
-
"/index.mts",
|
|
3423
|
-
"/index.cts",
|
|
3424
|
-
"/index.js",
|
|
3425
|
-
"/index.jsx",
|
|
3426
|
-
"/index.mjs",
|
|
3427
|
-
"/index.cjs"
|
|
3428
|
-
];
|
|
3429
|
-
var TSCONFIG_NAME = /^tsconfig(\..+)?\.json$/i;
|
|
3430
|
-
var POLYGLOT_CONFIG_NAMES = /* @__PURE__ */ new Set(["go.mod", "cargo.toml", "pyproject.toml", "composer.json"]);
|
|
3431
|
-
var TS_NO_INPUTS_CODE = 18003;
|
|
3432
|
-
function errorMessage(error) {
|
|
3433
|
-
return error instanceof Error ? error.message : String(error);
|
|
3434
|
-
}
|
|
3435
|
-
function errnoCode(error) {
|
|
3436
|
-
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
3437
|
-
return error.code;
|
|
3438
|
-
}
|
|
3439
|
-
return void 0;
|
|
3440
|
-
}
|
|
3441
|
-
function statOrNull(absolute) {
|
|
3442
|
-
try {
|
|
3443
|
-
return statSync(absolute);
|
|
3444
|
-
} catch (error) {
|
|
3445
|
-
const code = errnoCode(error);
|
|
3446
|
-
if (code === "ENOENT" || code === "ENOTDIR") return null;
|
|
3447
|
-
throw error;
|
|
3448
|
-
}
|
|
3449
|
-
}
|
|
3450
|
-
function isFile(absolute) {
|
|
3451
|
-
const stats = statOrNull(absolute);
|
|
3452
|
-
return stats !== null && stats.isFile();
|
|
3453
|
-
}
|
|
3454
|
-
function fileId(absolute) {
|
|
3455
|
-
const resolved = path5.resolve(absolute);
|
|
3456
|
-
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
3457
|
-
}
|
|
3458
|
-
function isAncestorDir(dir, file) {
|
|
3459
|
-
const rel = path5.relative(dir, file);
|
|
3460
|
-
return rel !== "" && !rel.startsWith("..") && !path5.isAbsolute(rel);
|
|
3461
|
-
}
|
|
3462
|
-
function walkWorkspace(root, notes) {
|
|
3463
|
-
const sources = [];
|
|
3464
|
-
const tsconfigs = [];
|
|
3465
|
-
const polyglotConfigs = [];
|
|
3466
|
-
const stack = [root];
|
|
3467
|
-
while (stack.length > 0) {
|
|
3468
|
-
const dir = stack.pop();
|
|
3469
|
-
if (dir === void 0) break;
|
|
3470
|
-
let entries;
|
|
3471
|
-
try {
|
|
3472
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
3473
|
-
} catch (error) {
|
|
3474
|
-
notes.push(`Directory "${displayPath(root, dir)}" could not be read: ${errorMessage(error)}`);
|
|
3475
|
-
continue;
|
|
3476
|
-
}
|
|
3477
|
-
entries.sort((a, b) => compareText(a.name, b.name));
|
|
3478
|
-
const childDirs = [];
|
|
3479
|
-
for (const entry of entries) {
|
|
3480
|
-
const full = path5.join(dir, entry.name);
|
|
3481
|
-
if (entry.isDirectory()) {
|
|
3482
|
-
const relDir = displayPath(root, full);
|
|
3483
|
-
if (!shouldSkipDirectory(entry.name, full, relDir)) {
|
|
3484
|
-
childDirs.push(full);
|
|
3485
|
-
}
|
|
3486
|
-
} else if (entry.isFile()) {
|
|
3487
|
-
const lowerName = entry.name.toLowerCase();
|
|
3488
|
-
if (SOURCE_EXTENSIONS.has(path5.extname(entry.name).toLowerCase())) {
|
|
3489
|
-
sources.push(full);
|
|
3490
|
-
} else if (TSCONFIG_NAME.test(entry.name)) {
|
|
3491
|
-
tsconfigs.push(full);
|
|
3492
|
-
} else if (POLYGLOT_CONFIG_NAMES.has(lowerName)) {
|
|
3493
|
-
polyglotConfigs.push(full);
|
|
3494
|
-
}
|
|
3495
|
-
}
|
|
3496
|
-
}
|
|
3497
|
-
for (let i = childDirs.length - 1; i >= 0; i -= 1) {
|
|
3498
|
-
const child = childDirs[i];
|
|
3499
|
-
if (child !== void 0) stack.push(child);
|
|
3500
|
-
}
|
|
3501
|
-
}
|
|
3502
|
-
sources.sort(compareText);
|
|
3503
|
-
tsconfigs.sort(compareText);
|
|
3504
|
-
polyglotConfigs.sort(compareText);
|
|
3505
|
-
return { sources, tsconfigs, polyglotConfigs };
|
|
3506
|
-
}
|
|
3507
|
-
function loadAliasConfig(root, configPath, notes) {
|
|
3508
|
-
const label = displayPath(root, configPath);
|
|
3509
|
-
const read = ts2.readConfigFile(configPath, ts2.sys.readFile);
|
|
3510
|
-
if (read.error) {
|
|
3511
|
-
notes.push(
|
|
3512
|
-
`tsconfig "${label}" could not be parsed: ${ts2.flattenDiagnosticMessageText(read.error.messageText, " ")}`
|
|
3513
|
-
);
|
|
3514
|
-
return null;
|
|
3515
|
-
}
|
|
3516
|
-
const host = {
|
|
3517
|
-
useCaseSensitiveFileNames: ts2.sys.useCaseSensitiveFileNames,
|
|
3518
|
-
readDirectory: () => [],
|
|
3519
|
-
fileExists: ts2.sys.fileExists,
|
|
3520
|
-
readFile: ts2.sys.readFile
|
|
3521
|
-
};
|
|
3522
|
-
let configDir = path5.dirname(configPath);
|
|
3523
|
-
try {
|
|
3524
|
-
configDir = realpathSync.native(configDir);
|
|
3525
|
-
} catch {
|
|
3526
|
-
}
|
|
3527
|
-
const parsed = ts2.parseJsonConfigFileContent(read.config, host, configDir, void 0, configPath);
|
|
3528
|
-
for (const diagnostic of parsed.errors) {
|
|
3529
|
-
if (diagnostic.code === TS_NO_INPUTS_CODE) continue;
|
|
3530
|
-
notes.push(`tsconfig "${label}": ${ts2.flattenDiagnosticMessageText(diagnostic.messageText, " ")}`);
|
|
3531
|
-
}
|
|
3532
|
-
const paths = parsed.options.paths;
|
|
3533
|
-
if (!paths) return null;
|
|
3534
|
-
const base = parsed.options.baseUrl ? path5.resolve(configDir, parsed.options.baseUrl) : configDir;
|
|
3535
|
-
const rules = [];
|
|
3536
|
-
for (const [pattern, targets] of Object.entries(paths)) {
|
|
3537
|
-
const star = pattern.indexOf("*");
|
|
3538
|
-
rules.push({
|
|
3539
|
-
prefix: star === -1 ? pattern : pattern.slice(0, star),
|
|
3540
|
-
suffix: star === -1 ? "" : pattern.slice(star + 1),
|
|
3541
|
-
wildcard: star !== -1,
|
|
3542
|
-
targets: targets.map((target) => path5.resolve(base, target))
|
|
3543
|
-
});
|
|
3544
|
-
}
|
|
3545
|
-
return rules.length > 0 ? { dir: configDir, rules } : null;
|
|
3546
|
-
}
|
|
3547
|
-
function resolveCandidate(base) {
|
|
3548
|
-
const ext = path5.extname(base).toLowerCase();
|
|
3549
|
-
const swaps = EXT_SWAPS[ext];
|
|
3550
|
-
if (swaps) {
|
|
3551
|
-
const stem = base.slice(0, base.length - ext.length);
|
|
3552
|
-
for (const swap of swaps) {
|
|
3553
|
-
if (isFile(`${stem}${swap}`)) return `${stem}${swap}`;
|
|
3554
|
-
}
|
|
3555
|
-
}
|
|
3556
|
-
if (isFile(base)) return base;
|
|
3557
|
-
for (const suffix of RESOLVE_SUFFIXES) {
|
|
3558
|
-
if (isFile(`${base}${suffix}`)) return `${base}${suffix}`;
|
|
3559
|
-
}
|
|
3560
|
-
return null;
|
|
3561
|
-
}
|
|
3562
|
-
function resolveAlias(spec, fromFile, index) {
|
|
3563
|
-
const configs = index.aliasConfigs.filter((config) => isAncestorDir(config.dir, fromFile)).sort((a, b) => b.dir.length - a.dir.length);
|
|
3564
|
-
for (const config of configs) {
|
|
3565
|
-
for (const rule of config.rules) {
|
|
3566
|
-
let rest;
|
|
3567
|
-
if (rule.wildcard) {
|
|
3568
|
-
if (!spec.startsWith(rule.prefix) || !spec.endsWith(rule.suffix)) continue;
|
|
3569
|
-
if (spec.length < rule.prefix.length + rule.suffix.length) continue;
|
|
3570
|
-
rest = spec.slice(rule.prefix.length, spec.length - rule.suffix.length);
|
|
3571
|
-
} else {
|
|
3572
|
-
if (spec !== rule.prefix) continue;
|
|
3573
|
-
rest = "";
|
|
3574
|
-
}
|
|
3575
|
-
for (const target of rule.targets) {
|
|
3576
|
-
const found = resolveCandidate(target.replace("*", rest));
|
|
3577
|
-
if (found) return found;
|
|
3578
|
-
}
|
|
3579
|
-
}
|
|
3580
|
-
}
|
|
3581
|
-
return null;
|
|
3582
|
-
}
|
|
3583
|
-
function buildEdgeFlags(importedNames, meta) {
|
|
3584
|
-
const isTypeOnly = meta?.isTypeOnly === true;
|
|
3585
|
-
const isDynamic = meta?.isDynamic === true;
|
|
3586
|
-
const hasStaticValueImport = !isTypeOnly && !isDynamic && meta?.verifiedAssetOnDisk !== true && importedNames.length > 0;
|
|
3587
|
-
return {
|
|
3588
|
-
...isTypeOnly ? { isTypeOnly: true } : {},
|
|
3589
|
-
...isDynamic ? { isDynamic: true } : {},
|
|
3590
|
-
hasStaticValueImport,
|
|
3591
|
-
...meta?.line !== void 0 ? { line: meta.line } : {},
|
|
3592
|
-
...meta?.verifiedAssetOnDisk !== void 0 ? { verifiedAssetOnDisk: meta.verifiedAssetOnDisk } : {}
|
|
3593
|
-
};
|
|
3594
|
-
}
|
|
3595
|
-
function localRef(found, index, importedNames, isReExport, meta) {
|
|
3596
|
-
let real;
|
|
3597
|
-
try {
|
|
3598
|
-
real = realpathSync.native(found);
|
|
3599
|
-
} catch {
|
|
3600
|
-
real = path5.resolve(found);
|
|
3601
|
-
}
|
|
3602
|
-
const label = displayPath(index.rootReal, real);
|
|
3603
|
-
return {
|
|
3604
|
-
key: `local:${label}`,
|
|
3605
|
-
kind: "local",
|
|
3606
|
-
label,
|
|
3607
|
-
importedNames: [...importedNames],
|
|
3608
|
-
isReExport,
|
|
3609
|
-
...buildEdgeFlags(importedNames, meta)
|
|
3610
|
-
};
|
|
3611
|
-
}
|
|
3612
|
-
function unresolvedRef(base, index, importedNames, isReExport, meta) {
|
|
3613
|
-
const label = displayPath(index.root, path5.resolve(base));
|
|
3614
|
-
return {
|
|
3615
|
-
key: `unresolved:${label}`,
|
|
3616
|
-
kind: "unresolved",
|
|
3617
|
-
label: `${label} (unresolved)`,
|
|
3618
|
-
importedNames: [...importedNames],
|
|
3619
|
-
isReExport,
|
|
3620
|
-
...buildEdgeFlags(importedNames, meta)
|
|
3621
|
-
};
|
|
3622
|
-
}
|
|
3623
|
-
function externalRef(spec, importedNames, isReExport, meta) {
|
|
3624
|
-
return {
|
|
3625
|
-
key: `pkg:${spec}`,
|
|
3626
|
-
kind: "external",
|
|
3627
|
-
label: spec,
|
|
3628
|
-
importedNames: [...importedNames],
|
|
3629
|
-
isReExport,
|
|
3630
|
-
...buildEdgeFlags(importedNames, meta)
|
|
3631
|
-
};
|
|
3632
|
-
}
|
|
3633
|
-
function resolveModule(rawSpec, fromFile, index, importedNames = [], isReExport = false, meta) {
|
|
3634
|
-
const spec = stripImportQueryAndHash(rawSpec);
|
|
3635
|
-
if (spec === "." || spec === ".." || spec.startsWith("./") || spec.startsWith("../")) {
|
|
3636
|
-
const base = path5.resolve(path5.dirname(fromFile), spec);
|
|
3637
|
-
const found = resolveCandidate(base);
|
|
3638
|
-
const isAsset = isNonCodeAssetSpecifier(spec);
|
|
3639
|
-
const verifiedAssetOnDisk = isAsset ? Boolean(found) : meta?.verifiedAssetOnDisk;
|
|
3640
|
-
const effectiveMeta = {
|
|
3641
|
-
...meta,
|
|
3642
|
-
...verifiedAssetOnDisk !== void 0 ? { verifiedAssetOnDisk } : {}
|
|
3643
|
-
};
|
|
3644
|
-
if (found) {
|
|
3645
|
-
return localRef(found, index, importedNames, isReExport, effectiveMeta);
|
|
3646
|
-
}
|
|
3647
|
-
const fromRel = displayPath(index.rootReal, fromFile);
|
|
3648
|
-
const candidateRel = displayPath(index.root, path5.resolve(base));
|
|
3649
|
-
if (isIntentionalFixtureOrSnapshotFile(fromRel) || isBuildTimeGeneratedImportTarget(rawSpec, candidateRel)) {
|
|
3650
|
-
return externalRef(spec, importedNames, isReExport, effectiveMeta);
|
|
3651
|
-
}
|
|
3652
|
-
return unresolvedRef(base, index, importedNames, isReExport, effectiveMeta);
|
|
3653
|
-
}
|
|
3654
|
-
if (spec.startsWith("node:")) {
|
|
3655
|
-
return externalRef(spec, importedNames, isReExport, meta);
|
|
3656
|
-
}
|
|
3657
|
-
if (NODE_BUILTINS.has(spec)) {
|
|
3658
|
-
return externalRef(`node:${spec}`, importedNames, isReExport, meta);
|
|
3659
|
-
}
|
|
3660
|
-
if (path5.isAbsolute(spec)) {
|
|
3661
|
-
const found = resolveCandidate(spec);
|
|
3662
|
-
if (found) return localRef(found, index, importedNames, isReExport, meta);
|
|
3663
|
-
}
|
|
3664
|
-
const aliased = resolveAlias(spec, fromFile, index);
|
|
3665
|
-
if (aliased) {
|
|
3666
|
-
const isAsset = isNonCodeAssetSpecifier(aliased);
|
|
3667
|
-
return localRef(aliased, index, importedNames, isReExport, {
|
|
3668
|
-
...meta,
|
|
3669
|
-
...isAsset ? { verifiedAssetOnDisk: true } : {}
|
|
3670
|
-
});
|
|
3671
|
-
}
|
|
3672
|
-
return externalRef(spec, importedNames, isReExport, meta);
|
|
3673
|
-
}
|
|
3674
|
-
function mergeModuleRef(modules, ref) {
|
|
3675
|
-
const incomingHasStatic = ref.hasStaticValueImport ?? (ref.isTypeOnly !== true && ref.isDynamic !== true && ref.verifiedAssetOnDisk !== true && ref.importedNames.length > 0);
|
|
3676
|
-
const existing = modules.get(ref.key);
|
|
3677
|
-
if (!existing) {
|
|
3678
|
-
modules.set(ref.key, {
|
|
3679
|
-
...ref,
|
|
3680
|
-
importedNames: [...ref.importedNames],
|
|
3681
|
-
hasStaticValueImport: incomingHasStatic
|
|
3682
|
-
});
|
|
3683
|
-
return;
|
|
3684
|
-
}
|
|
3685
|
-
for (const name of ref.importedNames) {
|
|
3686
|
-
if (!existing.importedNames.includes(name)) {
|
|
3687
|
-
existing.importedNames.push(name);
|
|
3688
|
-
}
|
|
3689
|
-
}
|
|
3690
|
-
if (ref.isReExport) {
|
|
3691
|
-
existing.isReExport = true;
|
|
3692
|
-
}
|
|
3693
|
-
const existingHasStatic = existing.hasStaticValueImport ?? (existing.isTypeOnly !== true && existing.isDynamic !== true && existing.verifiedAssetOnDisk !== true && existing.importedNames.length > 0);
|
|
3694
|
-
existing.hasStaticValueImport = existingHasStatic || incomingHasStatic;
|
|
3695
|
-
existing.isTypeOnly = Boolean(existing.isTypeOnly) && Boolean(ref.isTypeOnly);
|
|
3696
|
-
existing.isDynamic = Boolean(existing.isDynamic) && Boolean(ref.isDynamic);
|
|
3697
|
-
if (ref.line !== void 0) {
|
|
3698
|
-
if (incomingHasStatic && !existingHasStatic) {
|
|
3699
|
-
existing.line = ref.line;
|
|
3700
|
-
} else if (existing.line === void 0) {
|
|
3701
|
-
existing.line = ref.line;
|
|
3702
|
-
} else if (incomingHasStatic === existingHasStatic) {
|
|
3703
|
-
existing.line = Math.min(existing.line, ref.line);
|
|
3704
|
-
}
|
|
3705
|
-
}
|
|
3706
|
-
if (ref.verifiedAssetOnDisk === true) {
|
|
3707
|
-
existing.verifiedAssetOnDisk = true;
|
|
3708
|
-
} else if (ref.verifiedAssetOnDisk === false && existing.verifiedAssetOnDisk === void 0) {
|
|
3709
|
-
existing.verifiedAssetOnDisk = false;
|
|
3710
|
-
}
|
|
3711
|
-
}
|
|
3712
|
-
function addInboundEdge(index, callerRel, targetRel) {
|
|
3713
|
-
let inboundSet = index.inbound.get(targetRel);
|
|
3714
|
-
if (!inboundSet) {
|
|
3715
|
-
inboundSet = /* @__PURE__ */ new Set();
|
|
3716
|
-
index.inbound.set(targetRel, inboundSet);
|
|
3717
|
-
}
|
|
3718
|
-
inboundSet.add(callerRel);
|
|
3719
|
-
let importedBySet = index.importedBy.get(targetRel);
|
|
3720
|
-
if (!importedBySet) {
|
|
3721
|
-
importedBySet = /* @__PURE__ */ new Set();
|
|
3722
|
-
index.importedBy.set(targetRel, importedBySet);
|
|
3723
|
-
}
|
|
3724
|
-
importedBySet.add(callerRel);
|
|
3725
|
-
}
|
|
3726
|
-
function registerIndexedFile(index, file, extraId) {
|
|
3727
|
-
index.files.push(file);
|
|
3728
|
-
index.byId.set(file.id, file);
|
|
3729
|
-
if (extraId && extraId !== file.id) {
|
|
3730
|
-
index.byId.set(extraId, file);
|
|
3731
|
-
}
|
|
3732
|
-
index.byRelative.set(file.relative, file);
|
|
3733
|
-
index.outbound.set(file.relative, file.modules);
|
|
3734
|
-
for (const ref of file.modules.values()) {
|
|
3735
|
-
if (ref.kind === "local") {
|
|
3736
|
-
addInboundEdge(index, file.relative, ref.label);
|
|
3737
|
-
}
|
|
3738
|
-
}
|
|
3739
|
-
}
|
|
3740
|
-
function resolveNonJsTsImport(imp, relative, language, index, modules) {
|
|
3741
|
-
const adapter = defaultPolyglotRegistry.getAdapterById(language);
|
|
3742
|
-
const ctx = index.resolutionContext;
|
|
3743
|
-
const edgeMeta = {
|
|
3744
|
-
isTypeOnly: imp.isTypeOnly,
|
|
3745
|
-
isDynamic: imp.isDynamic,
|
|
3746
|
-
...imp.line !== void 0 ? { line: imp.line } : {},
|
|
3747
|
-
verifiedAssetOnDisk: imp.verifiedAssetOnDisk
|
|
3748
|
-
};
|
|
3749
|
-
if (!adapter || !ctx) {
|
|
3750
|
-
const ext = externalRef(imp.rawSpecifier, imp.importedNames, imp.isReExport, edgeMeta);
|
|
3751
|
-
mergeModuleRef(modules, { ...ext, rawSpecifier: imp.rawSpecifier });
|
|
3752
|
-
return { ...imp, resolvedKind: "external", resolvedPaths: [] };
|
|
3753
|
-
}
|
|
3754
|
-
const res = adapter.resolveImport(imp, relative, ctx);
|
|
3755
|
-
if (res.kind === "local" && res.resolvedPaths.length > 0) {
|
|
3756
|
-
for (const targetRel of res.resolvedPaths) {
|
|
3757
|
-
mergeModuleRef(modules, {
|
|
3758
|
-
key: `local:${targetRel}`,
|
|
3759
|
-
kind: "local",
|
|
3760
|
-
label: targetRel,
|
|
3761
|
-
importedNames: [...imp.importedNames],
|
|
3762
|
-
isReExport: imp.isReExport,
|
|
3763
|
-
...buildEdgeFlags(imp.importedNames, edgeMeta),
|
|
3764
|
-
rawSpecifier: imp.rawSpecifier
|
|
3765
|
-
});
|
|
3766
|
-
}
|
|
3767
|
-
return {
|
|
3768
|
-
...imp,
|
|
3769
|
-
resolvedKind: "local",
|
|
3770
|
-
resolvedPaths: [...res.resolvedPaths]
|
|
3771
|
-
};
|
|
3772
|
-
}
|
|
3773
|
-
if (res.kind === "unresolved") {
|
|
3774
|
-
const attempt = normalizeRelPath(res.unresolvedAttempt ?? imp.rawSpecifier);
|
|
3775
|
-
if (isIntentionalFixtureOrSnapshotFile(relative) || isBuildTimeGeneratedImportTarget(imp.rawSpecifier, attempt)) {
|
|
3776
|
-
mergeModuleRef(modules, {
|
|
3777
|
-
...externalRef(imp.rawSpecifier, imp.importedNames, imp.isReExport, edgeMeta),
|
|
3778
|
-
rawSpecifier: imp.rawSpecifier
|
|
3779
|
-
});
|
|
3780
|
-
return {
|
|
3781
|
-
...imp,
|
|
3782
|
-
resolvedKind: "external",
|
|
3783
|
-
resolvedPaths: []
|
|
3784
|
-
};
|
|
3785
|
-
}
|
|
3786
|
-
mergeModuleRef(modules, {
|
|
3787
|
-
key: `unresolved:${attempt}`,
|
|
3788
|
-
kind: "unresolved",
|
|
3789
|
-
label: `${attempt} (unresolved)`,
|
|
3790
|
-
importedNames: [...imp.importedNames],
|
|
3791
|
-
isReExport: imp.isReExport,
|
|
3792
|
-
...buildEdgeFlags(imp.importedNames, edgeMeta),
|
|
3793
|
-
rawSpecifier: imp.rawSpecifier
|
|
3794
|
-
});
|
|
3795
|
-
return {
|
|
3796
|
-
...imp,
|
|
3797
|
-
resolvedKind: "unresolved",
|
|
3798
|
-
resolvedPaths: attempt ? [attempt] : []
|
|
3799
|
-
};
|
|
3800
|
-
}
|
|
3801
|
-
const extLabel = res.externalLabel ?? imp.rawSpecifier;
|
|
3802
|
-
mergeModuleRef(modules, {
|
|
3803
|
-
...externalRef(extLabel, imp.importedNames, imp.isReExport, edgeMeta),
|
|
3804
|
-
rawSpecifier: imp.rawSpecifier
|
|
3805
|
-
});
|
|
3806
|
-
return {
|
|
3807
|
-
...imp,
|
|
3808
|
-
resolvedKind: "external",
|
|
3809
|
-
resolvedPaths: []
|
|
3810
|
-
};
|
|
3811
|
-
}
|
|
3812
|
-
function indexFileOnDisk(absolute, index, options) {
|
|
3813
|
-
let realAbs;
|
|
3814
|
-
try {
|
|
3815
|
-
realAbs = realpathSync.native(absolute);
|
|
3816
|
-
} catch {
|
|
3817
|
-
realAbs = path5.resolve(absolute);
|
|
3818
|
-
}
|
|
3819
|
-
const relative = displayPath(index.rootReal, realAbs);
|
|
3820
|
-
const stats = statOrNull(absolute);
|
|
3821
|
-
const cache = options?.cache;
|
|
3822
|
-
let manifest;
|
|
3823
|
-
if (cache && stats) {
|
|
3824
|
-
manifest = cache.get(index.workspaceId, relative, void 0, stats.mtimeMs, stats.size);
|
|
3825
|
-
}
|
|
3826
|
-
if (!manifest) {
|
|
3827
|
-
const source = readFileSync3(absolute, "utf8");
|
|
3828
|
-
if (cache) {
|
|
3829
|
-
const sha256 = createHash3("sha256").update(source, "utf8").digest("hex");
|
|
3830
|
-
const shaHit = cache.get(index.workspaceId, relative, sha256);
|
|
3831
|
-
if (shaHit) {
|
|
3832
|
-
manifest = {
|
|
3833
|
-
...shaHit,
|
|
3834
|
-
relativePath: relative,
|
|
3835
|
-
...stats ? { mtimeMs: stats.mtimeMs, size: stats.size } : {}
|
|
3836
|
-
};
|
|
3837
|
-
cache.set(index.workspaceId, manifest);
|
|
3838
|
-
} else {
|
|
3839
|
-
manifest = defaultPolyglotRegistry.extractManifest(
|
|
3840
|
-
source,
|
|
3841
|
-
realAbs,
|
|
3842
|
-
relative,
|
|
3843
|
-
stats?.mtimeMs,
|
|
3844
|
-
stats?.size
|
|
3845
|
-
);
|
|
3846
|
-
cache.set(index.workspaceId, manifest);
|
|
3847
|
-
}
|
|
3848
|
-
} else {
|
|
3849
|
-
manifest = defaultPolyglotRegistry.extractManifest(
|
|
3850
|
-
source,
|
|
3851
|
-
realAbs,
|
|
3852
|
-
relative,
|
|
3853
|
-
stats?.mtimeMs,
|
|
3854
|
-
stats?.size
|
|
3855
|
-
);
|
|
3856
|
-
}
|
|
3857
|
-
}
|
|
3858
|
-
const language = manifest.language ?? defaultPolyglotRegistry.detectLanguage(realAbs);
|
|
3859
|
-
const isJsTs = language === "typescript" || language === "javascript" || language === "unknown";
|
|
3860
|
-
const modules = /* @__PURE__ */ new Map();
|
|
3861
|
-
const resolvedImports = [];
|
|
3862
|
-
for (const imp of manifest.imports) {
|
|
3863
|
-
if (isJsTs) {
|
|
3864
|
-
const cleanSpec = stripImportQueryAndHash(imp.rawSpecifier);
|
|
3865
|
-
let verifiedAssetOnDisk = imp.verifiedAssetOnDisk;
|
|
3866
|
-
if (isRelativeImportSpecifier(cleanSpec) && isNonCodeAssetSpecifier(cleanSpec)) {
|
|
3867
|
-
verifiedAssetOnDisk = isFile(path5.resolve(path5.dirname(realAbs), cleanSpec));
|
|
3868
|
-
}
|
|
3869
|
-
const ref = resolveModule(
|
|
3870
|
-
imp.rawSpecifier,
|
|
3871
|
-
realAbs,
|
|
3872
|
-
index,
|
|
3873
|
-
imp.importedNames,
|
|
3874
|
-
imp.isReExport,
|
|
3875
|
-
{
|
|
3876
|
-
isTypeOnly: imp.isTypeOnly,
|
|
3877
|
-
isDynamic: imp.isDynamic,
|
|
3878
|
-
...imp.line !== void 0 ? { line: imp.line } : {},
|
|
3879
|
-
verifiedAssetOnDisk
|
|
3880
|
-
}
|
|
3881
|
-
);
|
|
3882
|
-
mergeModuleRef(modules, { ...ref, rawSpecifier: imp.rawSpecifier });
|
|
3883
|
-
const resolvedPaths = ref.kind === "local" ? [ref.label] : ref.kind === "unresolved" ? [ref.label.replace(/ \(unresolved\)$/, "")] : [];
|
|
3884
|
-
const effectiveVerifiedAsset = ref.verifiedAssetOnDisk !== void 0 ? ref.verifiedAssetOnDisk : verifiedAssetOnDisk;
|
|
3885
|
-
resolvedImports.push({
|
|
3886
|
-
...imp,
|
|
3887
|
-
...effectiveVerifiedAsset !== void 0 ? { verifiedAssetOnDisk: effectiveVerifiedAsset } : {},
|
|
3888
|
-
resolvedKind: ref.kind,
|
|
3889
|
-
resolvedPaths
|
|
3890
|
-
});
|
|
3891
|
-
} else {
|
|
3892
|
-
resolvedImports.push(resolveNonJsTsImport(imp, relative, language, index, modules));
|
|
3893
|
-
}
|
|
3894
|
-
}
|
|
3895
|
-
const enrichedManifest = {
|
|
3896
|
-
...manifest,
|
|
3897
|
-
relativePath: relative,
|
|
3898
|
-
language,
|
|
3899
|
-
imports: resolvedImports
|
|
3900
|
-
};
|
|
3901
|
-
return {
|
|
3902
|
-
absolute: realAbs,
|
|
3903
|
-
id: fileId(realAbs),
|
|
3904
|
-
relative,
|
|
3905
|
-
contentSha256: enrichedManifest.contentSha256,
|
|
3906
|
-
language,
|
|
3907
|
-
modules,
|
|
3908
|
-
exportedSymbols: enrichedManifest.exportedSymbols.map((sym) => ({ ...sym, file: relative })),
|
|
3909
|
-
internalFunctions: enrichedManifest.internalFunctions.map((fn) => ({ ...fn, file: relative })),
|
|
3910
|
-
manifest: enrichedManifest
|
|
3911
|
-
};
|
|
3912
|
-
}
|
|
3913
|
-
function buildIndex(root, options) {
|
|
3914
|
-
const notes = [];
|
|
3915
|
-
let rootReal;
|
|
3916
|
-
try {
|
|
3917
|
-
rootReal = realpathSync.native(root);
|
|
3918
|
-
} catch {
|
|
3919
|
-
rootReal = path5.resolve(root);
|
|
3920
|
-
}
|
|
3921
|
-
const workspaceId = options?.workspaceId ?? toPosix(rootReal);
|
|
3922
|
-
const { sources, tsconfigs, polyglotConfigs } = walkWorkspace(root, notes);
|
|
3923
|
-
const aliasConfigs = [];
|
|
3924
|
-
for (const configPath of tsconfigs) {
|
|
3925
|
-
const config = loadAliasConfig(root, configPath, notes);
|
|
3926
|
-
if (config) aliasConfigs.push(config);
|
|
3927
|
-
}
|
|
3928
|
-
const sourceRelPaths = sources.map((abs) => {
|
|
3929
|
-
try {
|
|
3930
|
-
return displayPath(rootReal, realpathSync.native(abs));
|
|
3931
|
-
} catch {
|
|
3932
|
-
return displayPath(rootReal, path5.resolve(abs));
|
|
3933
|
-
}
|
|
3934
|
-
});
|
|
3935
|
-
const polyglotConfigRelPaths = polyglotConfigs.map((abs) => {
|
|
3936
|
-
try {
|
|
3937
|
-
return displayPath(rootReal, realpathSync.native(abs));
|
|
3938
|
-
} catch {
|
|
3939
|
-
return displayPath(rootReal, path5.resolve(abs));
|
|
3940
|
-
}
|
|
3941
|
-
});
|
|
3942
|
-
const resolutionContext = buildWorkspaceResolutionContext(
|
|
3943
|
-
root,
|
|
3944
|
-
rootReal,
|
|
3945
|
-
sourceRelPaths,
|
|
3946
|
-
polyglotConfigRelPaths
|
|
3947
|
-
);
|
|
3948
|
-
const index = {
|
|
3949
|
-
workspaceId,
|
|
3950
|
-
root,
|
|
3951
|
-
rootReal,
|
|
3952
|
-
files: [],
|
|
3953
|
-
byId: /* @__PURE__ */ new Map(),
|
|
3954
|
-
byRelative: /* @__PURE__ */ new Map(),
|
|
3955
|
-
outbound: /* @__PURE__ */ new Map(),
|
|
3956
|
-
inbound: /* @__PURE__ */ new Map(),
|
|
3957
|
-
importedBy: /* @__PURE__ */ new Map(),
|
|
3958
|
-
aliasConfigs,
|
|
3959
|
-
resolutionContext,
|
|
3960
|
-
notes
|
|
3961
|
-
};
|
|
3962
|
-
for (const absolute of sources) {
|
|
3963
|
-
try {
|
|
3964
|
-
const file = indexFileOnDisk(absolute, index, options);
|
|
3965
|
-
registerIndexedFile(index, file, fileId(absolute));
|
|
3966
|
-
} catch (error) {
|
|
3967
|
-
notes.push(`"${displayPath(root, absolute)}" could not be analysed: ${errorMessage(error)}`);
|
|
3968
|
-
}
|
|
3969
|
-
}
|
|
3970
|
-
index.files.sort((a, b) => compareText(a.relative, b.relative));
|
|
3971
|
-
return index;
|
|
3972
|
-
}
|
|
3973
|
-
|
|
3974
|
-
// src/extractor.ts
|
|
3975
|
-
function sha256Text(text) {
|
|
3976
|
-
return createHash4("sha256").update(text, "utf8").digest("hex");
|
|
3977
|
-
}
|
|
3978
|
-
function computeManifestSyncHash(manifest) {
|
|
3979
|
-
const assetSig = manifest.imports.map((imp) => {
|
|
3980
|
-
const assetFlag = imp.verifiedAssetOnDisk === true ? "1" : imp.verifiedAssetOnDisk === false ? "0" : "-";
|
|
3981
|
-
const dynFlag = imp.isDynamic === true ? "D" : "S";
|
|
3982
|
-
const typeFlag = imp.isTypeOnly ? "T" : "V";
|
|
3983
|
-
return `${imp.rawSpecifier}:${typeFlag}${dynFlag}${assetFlag}:${imp.line ?? 0}:${imp.importedNames.length}`;
|
|
3984
|
-
}).join("|");
|
|
3985
|
-
const symSig = manifest.exportedSymbols.map((s) => `${s.name}:${s.line}:${s.endLine ?? 0}:${s.structuralHash ?? ""}`).join(",");
|
|
3986
|
-
const internalSig = manifest.internalFunctions.map((f) => `${f.name}:${f.line}:${f.endLine ?? 0}:${f.structuralHash}`).join(",");
|
|
3987
|
-
const schema = manifest.schemaVersion ?? CACHE_SCHEMA_VERSION;
|
|
3988
|
-
return sha256Text(`${schema}\0${manifest.contentSha256}\0${assetSig}\0${symSig}\0${internalSig}`);
|
|
3989
|
-
}
|
|
3990
|
-
function verifyRelativeAssetsOnDisk(manifest, sourceAbsPath) {
|
|
3991
|
-
const sourceDir = path6.dirname(sourceAbsPath);
|
|
3992
|
-
let changed = false;
|
|
3993
|
-
const updatedImports = manifest.imports.map((imp) => {
|
|
3994
|
-
const cleanSpec = stripImportQueryAndHash(imp.rawSpecifier);
|
|
3995
|
-
if (!isRelativeImportSpecifier(cleanSpec) || !isNonCodeAssetSpecifier(cleanSpec)) {
|
|
3996
|
-
return imp;
|
|
3997
|
-
}
|
|
3998
|
-
const resolvedDiskPath = path6.resolve(sourceDir, cleanSpec);
|
|
3999
|
-
const verified = existsSync3(resolvedDiskPath);
|
|
4000
|
-
if (imp.verifiedAssetOnDisk !== verified) {
|
|
4001
|
-
changed = true;
|
|
4002
|
-
}
|
|
4003
|
-
return {
|
|
4004
|
-
...imp,
|
|
4005
|
-
verifiedAssetOnDisk: verified
|
|
4006
|
-
};
|
|
4007
|
-
});
|
|
4008
|
-
if (!changed) {
|
|
4009
|
-
return { manifest, changed: false };
|
|
4010
|
-
}
|
|
4011
|
-
return {
|
|
4012
|
-
manifest: {
|
|
4013
|
-
...manifest,
|
|
4014
|
-
imports: updatedImports
|
|
4015
|
-
},
|
|
4016
|
-
changed: true
|
|
4017
|
-
};
|
|
4018
|
-
}
|
|
4019
|
-
function invalidateStaleCloudSyncFile(cachePath, workspaceId) {
|
|
4020
|
-
const syncPath = path6.join(path6.dirname(cachePath), "cloud-sync.json");
|
|
4021
|
-
if (!existsSync3(syncPath)) return;
|
|
4022
|
-
try {
|
|
4023
|
-
const parsed = JSON.parse(readFileSync4(syncPath, "utf8"));
|
|
4024
|
-
if (!parsed || typeof parsed !== "object") return;
|
|
4025
|
-
if (parsed.manifestSchemaVersion !== CACHE_SCHEMA_VERSION) {
|
|
4026
|
-
writeFileSync2(
|
|
4027
|
-
syncPath,
|
|
4028
|
-
JSON.stringify(
|
|
4029
|
-
{
|
|
4030
|
-
version: 1,
|
|
4031
|
-
manifestSchemaVersion: CACHE_SCHEMA_VERSION,
|
|
4032
|
-
workspaces: {}
|
|
4033
|
-
},
|
|
4034
|
-
null,
|
|
4035
|
-
2
|
|
4036
|
-
),
|
|
4037
|
-
"utf8"
|
|
4038
|
-
);
|
|
4039
|
-
return;
|
|
4040
|
-
}
|
|
4041
|
-
if (parsed.workspaces && typeof parsed.workspaces === "object") {
|
|
4042
|
-
let modified = false;
|
|
4043
|
-
for (const key of Object.keys(parsed.workspaces)) {
|
|
4044
|
-
if (key === workspaceId || key.endsWith(`::${workspaceId}`)) {
|
|
4045
|
-
delete parsed.workspaces[key];
|
|
4046
|
-
modified = true;
|
|
4047
|
-
}
|
|
4048
|
-
}
|
|
4049
|
-
if (modified) {
|
|
4050
|
-
writeFileSync2(syncPath, JSON.stringify(parsed, null, 2), "utf8");
|
|
4051
|
-
}
|
|
4052
|
-
}
|
|
4053
|
-
} catch {
|
|
4054
|
-
}
|
|
4055
|
-
}
|
|
4056
|
-
function hasSkippedPathSegment(relPath) {
|
|
4057
|
-
const segments = toPosix(relPath).replace(/^\.\//, "").split("/");
|
|
4058
|
-
return segments.some((seg) => {
|
|
4059
|
-
if (seg.length === 0) return false;
|
|
4060
|
-
const lower = seg.toLowerCase();
|
|
4061
|
-
return SKIP_DIRS.has(seg) || SKIP_DIRS.has(lower) || lower.startsWith("cmake-build-");
|
|
4062
|
-
});
|
|
4063
|
-
}
|
|
4064
|
-
function deriveWorkspaceId(rootDir) {
|
|
4065
|
-
const real = realpathSync2.native(path6.resolve(rootDir));
|
|
4066
|
-
return `ws_${sha256Text(real).slice(0, 16)}`;
|
|
4067
|
-
}
|
|
4068
|
-
function realpathOrResolved(dirPath) {
|
|
4069
|
-
const resolved = path6.resolve(dirPath);
|
|
4070
|
-
try {
|
|
4071
|
-
return realpathSync2.native(resolved);
|
|
4072
|
-
} catch {
|
|
4073
|
-
return resolved;
|
|
4074
|
-
}
|
|
4075
|
-
}
|
|
4076
|
-
function normalizeDirCompareKey(dirPath) {
|
|
4077
|
-
const norm = realpathOrResolved(dirPath);
|
|
4078
|
-
return process.platform === "win32" ? norm.toLowerCase() : norm;
|
|
4079
|
-
}
|
|
4080
|
-
function isSameOrSubdirectory(ancestorDir, targetDir) {
|
|
4081
|
-
const anc = realpathOrResolved(ancestorDir);
|
|
4082
|
-
const tgt = realpathOrResolved(targetDir);
|
|
4083
|
-
const rel = path6.relative(anc, tgt);
|
|
4084
|
-
return rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel);
|
|
4085
|
-
}
|
|
4086
|
-
function hasWorkspaceRootMarker(dirPath, isAncestor) {
|
|
4087
|
-
return existsSync3(path6.join(dirPath, ".git")) || existsSync3(path6.join(dirPath, "pnpm-workspace.yaml")) || existsSync3(path6.join(dirPath, ".tipolink", "cloud-sync.json")) || isAncestor && existsSync3(path6.join(dirPath, ".tipolink", "cache.json")) || existsSync3(path6.join(dirPath, "tsconfig.base.json"));
|
|
4088
|
-
}
|
|
4089
|
-
function hoistToCanonicalWorkspaceRoot(inputDir) {
|
|
4090
|
-
let startDir = path6.resolve(inputDir);
|
|
4091
|
-
try {
|
|
4092
|
-
if (existsSync3(startDir) && statSync2(startDir).isFile()) {
|
|
4093
|
-
startDir = path6.dirname(startDir);
|
|
4094
|
-
}
|
|
4095
|
-
} catch {
|
|
4096
|
-
}
|
|
4097
|
-
const startKey = normalizeDirCompareKey(startDir);
|
|
4098
|
-
const tmpKey = normalizeDirCompareKey(os.tmpdir());
|
|
4099
|
-
const homeKey = normalizeDirCompareKey(os.homedir());
|
|
4100
|
-
const fsRootKey = normalizeDirCompareKey(path6.parse(startDir).root);
|
|
4101
|
-
const envRootRaw = process.env["TIPOLINK_WORKSPACE_ROOT"]?.trim();
|
|
4102
|
-
const envCeiling = envRootRaw && envRootRaw.length > 0 && isSameOrSubdirectory(path6.resolve(envRootRaw), startDir) ? path6.resolve(envRootRaw) : null;
|
|
4103
|
-
const envCeilingKey = envCeiling ? normalizeDirCompareKey(envCeiling) : null;
|
|
4104
|
-
let highestRoot = null;
|
|
4105
|
-
let curr = startDir;
|
|
4106
|
-
while (true) {
|
|
4107
|
-
const currKey = normalizeDirCompareKey(curr);
|
|
4108
|
-
if (currKey !== startKey && (currKey === fsRootKey || currKey === tmpKey || currKey === homeKey)) {
|
|
4109
|
-
break;
|
|
4110
|
-
}
|
|
4111
|
-
if (envCeilingKey !== null && currKey === envCeilingKey) {
|
|
4112
|
-
highestRoot = envCeiling;
|
|
4113
|
-
break;
|
|
4114
|
-
}
|
|
4115
|
-
if (hasWorkspaceRootMarker(curr, currKey !== startKey)) {
|
|
4116
|
-
highestRoot = curr;
|
|
4117
|
-
}
|
|
4118
|
-
const parent = path6.dirname(curr);
|
|
4119
|
-
if (parent === curr) {
|
|
4120
|
-
break;
|
|
4121
|
-
}
|
|
4122
|
-
curr = parent;
|
|
4123
|
-
}
|
|
4124
|
-
const canonicalRoot = highestRoot ?? startDir;
|
|
4125
|
-
const canonicalReal = realpathOrResolved(canonicalRoot);
|
|
4126
|
-
const startReal = realpathOrResolved(startDir);
|
|
4127
|
-
const rel = toPosix(path6.relative(canonicalReal, startReal)).replace(/^\/+|\/+$/g, "");
|
|
4128
|
-
if (!rel || rel === "." || rel.startsWith("..")) {
|
|
4129
|
-
return {
|
|
4130
|
-
canonicalRoot,
|
|
4131
|
-
subScopePrefix: null
|
|
4132
|
-
};
|
|
4133
|
-
}
|
|
4134
|
-
return {
|
|
4135
|
-
canonicalRoot,
|
|
4136
|
-
subScopePrefix: `${rel}/`
|
|
4137
|
-
};
|
|
4138
|
-
}
|
|
4139
|
-
function isSafeOrphanNestedTipolinkDir(tipolinkDir, canonicalRoot) {
|
|
4140
|
-
if (normalizeDirCompareKey(path6.dirname(tipolinkDir)) === normalizeDirCompareKey(canonicalRoot)) {
|
|
4141
|
-
return false;
|
|
4142
|
-
}
|
|
4143
|
-
if (existsSync3(path6.join(tipolinkDir, "server.env")) || existsSync3(path6.join(tipolinkDir, "tipolink.sqlite")) || existsSync3(path6.join(tipolinkDir, "data", "tipolink.sqlite")) || existsSync3(path6.join(tipolinkDir, "data", ".tipolink-auth.key"))) {
|
|
4144
|
-
return false;
|
|
4145
|
-
}
|
|
4146
|
-
return true;
|
|
4147
|
-
}
|
|
4148
|
-
function cleanupNestedTipolinkDirs(canonicalRoot, extraSubDir) {
|
|
4149
|
-
const resolvedCanonical = path6.resolve(canonicalRoot);
|
|
4150
|
-
const cleaned = [];
|
|
4151
|
-
const tryRemoveNested = (candidateTipolinkDir) => {
|
|
4152
|
-
if (!existsSync3(candidateTipolinkDir)) return;
|
|
4153
|
-
if (!isSafeOrphanNestedTipolinkDir(candidateTipolinkDir, resolvedCanonical)) return;
|
|
4154
|
-
try {
|
|
4155
|
-
rmSync(candidateTipolinkDir, { recursive: true, force: true });
|
|
4156
|
-
cleaned.push(toPosix(path6.relative(resolvedCanonical, candidateTipolinkDir)));
|
|
4157
|
-
} catch {
|
|
4158
|
-
}
|
|
4159
|
-
};
|
|
4160
|
-
if (extraSubDir) {
|
|
4161
|
-
const resolvedExtra = path6.resolve(extraSubDir);
|
|
4162
|
-
if (isSameOrSubdirectory(resolvedCanonical, resolvedExtra) && normalizeDirCompareKey(resolvedExtra) !== normalizeDirCompareKey(resolvedCanonical)) {
|
|
4163
|
-
tryRemoveNested(path6.join(resolvedExtra, ".tipolink"));
|
|
4164
|
-
}
|
|
4165
|
-
}
|
|
4166
|
-
const stack = [resolvedCanonical];
|
|
4167
|
-
while (stack.length > 0) {
|
|
4168
|
-
const dir = stack.pop();
|
|
4169
|
-
if (dir === void 0) break;
|
|
4170
|
-
let entries;
|
|
4171
|
-
try {
|
|
4172
|
-
entries = readdirSync2(dir, { withFileTypes: true });
|
|
4173
|
-
} catch {
|
|
4174
|
-
continue;
|
|
4175
|
-
}
|
|
4176
|
-
for (const entry of entries) {
|
|
4177
|
-
if (!entry.isDirectory()) continue;
|
|
4178
|
-
const fullPath = path6.join(dir, entry.name);
|
|
4179
|
-
if (entry.name === ".tipolink") {
|
|
4180
|
-
if (normalizeDirCompareKey(dir) !== normalizeDirCompareKey(resolvedCanonical)) {
|
|
4181
|
-
tryRemoveNested(fullPath);
|
|
4182
|
-
}
|
|
4183
|
-
continue;
|
|
4184
|
-
}
|
|
4185
|
-
const relDir = toPosix(path6.relative(resolvedCanonical, fullPath));
|
|
4186
|
-
if (!shouldSkipDirectory(entry.name, fullPath, relDir)) {
|
|
4187
|
-
stack.push(fullPath);
|
|
4188
|
-
}
|
|
4189
|
-
}
|
|
4190
|
-
}
|
|
4191
|
-
return cleaned;
|
|
4192
|
-
}
|
|
4193
|
-
function sanitizeManifest(manifest) {
|
|
4194
|
-
return {
|
|
4195
|
-
relativePath: toPosix(manifest.relativePath),
|
|
4196
|
-
contentSha256: manifest.contentSha256,
|
|
4197
|
-
schemaVersion: manifest.schemaVersion ?? CACHE_SCHEMA_VERSION,
|
|
4198
|
-
...manifest.language !== void 0 ? { language: manifest.language } : {},
|
|
4199
|
-
...manifest.mtimeMs !== void 0 ? { mtimeMs: manifest.mtimeMs } : {},
|
|
4200
|
-
...manifest.size !== void 0 ? { size: manifest.size } : {},
|
|
4201
|
-
imports: manifest.imports.map((imp) => ({
|
|
4202
|
-
rawSpecifier: imp.rawSpecifier,
|
|
4203
|
-
importedNames: [...imp.importedNames],
|
|
4204
|
-
isReExport: imp.isReExport,
|
|
4205
|
-
isTypeOnly: imp.isTypeOnly,
|
|
4206
|
-
...imp.isDynamic === true ? { isDynamic: true } : {},
|
|
4207
|
-
...typeof imp.line === "number" && Number.isFinite(imp.line) ? { line: imp.line } : {},
|
|
4208
|
-
...typeof imp.verifiedAssetOnDisk === "boolean" ? { verifiedAssetOnDisk: imp.verifiedAssetOnDisk } : {},
|
|
4209
|
-
...Array.isArray(imp.resolvedPaths) ? { resolvedPaths: imp.resolvedPaths.map((p) => toPosix(p)) } : {},
|
|
4210
|
-
...imp.resolvedKind !== void 0 ? { resolvedKind: imp.resolvedKind } : {}
|
|
4211
|
-
})),
|
|
4212
|
-
exportedSymbols: manifest.exportedSymbols.map((sym) => ({
|
|
4213
|
-
name: sym.name,
|
|
4214
|
-
...sym.localName !== void 0 ? { localName: sym.localName } : {},
|
|
4215
|
-
kind: sym.kind,
|
|
4216
|
-
signature: sym.signature,
|
|
4217
|
-
line: sym.line,
|
|
4218
|
-
...sym.endLine !== void 0 ? { endLine: sym.endLine } : {},
|
|
4219
|
-
...sym.structuralHash !== void 0 ? { structuralHash: sym.structuralHash } : {},
|
|
4220
|
-
...sym.nodeCount !== void 0 ? { nodeCount: sym.nodeCount } : {},
|
|
4221
|
-
...sym.astNodeCount !== void 0 ? { astNodeCount: sym.astNodeCount } : {},
|
|
4222
|
-
...sym.statementCount !== void 0 ? { statementCount: sym.statementCount } : {},
|
|
4223
|
-
file: toPosix(sym.file),
|
|
4224
|
-
isExported: true,
|
|
4225
|
-
...sym.isReExport !== void 0 ? { isReExport: sym.isReExport } : {}
|
|
4226
|
-
})),
|
|
4227
|
-
internalFunctions: manifest.internalFunctions.map((fn) => ({
|
|
4228
|
-
name: fn.name,
|
|
4229
|
-
kind: "function",
|
|
4230
|
-
signature: fn.signature,
|
|
4231
|
-
line: fn.line,
|
|
4232
|
-
...fn.endLine !== void 0 ? { endLine: fn.endLine } : {},
|
|
4233
|
-
structuralHash: fn.structuralHash,
|
|
4234
|
-
nodeCount: fn.nodeCount,
|
|
4235
|
-
...fn.astNodeCount !== void 0 ? { astNodeCount: fn.astNodeCount } : {},
|
|
4236
|
-
...fn.statementCount !== void 0 ? { statementCount: fn.statementCount } : {},
|
|
4237
|
-
file: toPosix(fn.file),
|
|
4238
|
-
isExported: false
|
|
4239
|
-
}))
|
|
4240
|
-
};
|
|
4241
|
-
}
|
|
4242
|
-
function walkSourceFiles(rootDir, cleanNestedTipolink = true) {
|
|
4243
|
-
const results = [];
|
|
4244
|
-
const stack = [rootDir];
|
|
4245
|
-
const rootKey = normalizeDirCompareKey(rootDir);
|
|
4246
|
-
while (stack.length > 0) {
|
|
4247
|
-
const dir = stack.pop();
|
|
4248
|
-
if (dir === void 0) break;
|
|
4249
|
-
let entries;
|
|
4250
|
-
try {
|
|
4251
|
-
entries = readdirSync2(dir, { withFileTypes: true });
|
|
4252
|
-
} catch {
|
|
4253
|
-
continue;
|
|
4254
|
-
}
|
|
4255
|
-
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
4256
|
-
const childDirs = [];
|
|
4257
|
-
for (const entry of entries) {
|
|
4258
|
-
const fullPath = path6.join(dir, entry.name);
|
|
4259
|
-
if (entry.isDirectory()) {
|
|
4260
|
-
if (cleanNestedTipolink && entry.name === ".tipolink" && normalizeDirCompareKey(dir) !== rootKey && isSafeOrphanNestedTipolinkDir(fullPath, rootDir)) {
|
|
4261
|
-
try {
|
|
4262
|
-
rmSync(fullPath, { recursive: true, force: true });
|
|
4263
|
-
} catch {
|
|
4264
|
-
}
|
|
4265
|
-
continue;
|
|
4266
|
-
}
|
|
4267
|
-
const relDir = toPosix(path6.relative(rootDir, fullPath));
|
|
4268
|
-
if (!shouldSkipDirectory(entry.name, fullPath, relDir)) {
|
|
4269
|
-
childDirs.push(fullPath);
|
|
4270
|
-
}
|
|
4271
|
-
} else if (entry.isFile()) {
|
|
4272
|
-
if (SOURCE_EXTENSIONS.has(path6.extname(entry.name).toLowerCase())) {
|
|
4273
|
-
results.push(fullPath);
|
|
4274
|
-
}
|
|
4275
|
-
}
|
|
4276
|
-
}
|
|
4277
|
-
for (let i = childDirs.length - 1; i >= 0; i -= 1) {
|
|
4278
|
-
const child = childDirs[i];
|
|
4279
|
-
if (child !== void 0) {
|
|
4280
|
-
stack.push(child);
|
|
4281
|
-
}
|
|
4282
|
-
}
|
|
4283
|
-
}
|
|
4284
|
-
results.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
4285
|
-
return results;
|
|
4286
|
-
}
|
|
4287
|
-
function scanWorkspaceManifests(rootDir, options = {}) {
|
|
4288
|
-
const rawInputResolved = path6.resolve(rootDir);
|
|
4289
|
-
const hoisted = options.disableRootHoisting === true || options.cachePath !== void 0 ? { canonicalRoot: rawInputResolved, subScopePrefix: null } : hoistToCanonicalWorkspaceRoot(rawInputResolved);
|
|
4290
|
-
const resolvedRoot = hoisted.canonicalRoot;
|
|
4291
|
-
const subScopePrefix = hoisted.subScopePrefix;
|
|
4292
|
-
const writeCache = options.writeCache ?? true;
|
|
4293
|
-
if (writeCache && subScopePrefix !== null) {
|
|
4294
|
-
cleanupNestedTipolinkDirs(resolvedRoot, rawInputResolved);
|
|
4295
|
-
}
|
|
4296
|
-
const rootReal = realpathSync2.native(resolvedRoot);
|
|
4297
|
-
const workspaceId = options.workspaceId ?? deriveWorkspaceId(rootReal);
|
|
4298
|
-
const cachePath = options.cachePath ?? path6.join(resolvedRoot, ".tipolink", "cache.json");
|
|
4299
|
-
const cache = new JsonFileAstCache({ filePath: cachePath, autoSave: false });
|
|
4300
|
-
const schemaInvalidated = cache.schemaInvalidated;
|
|
4301
|
-
const priorManifests = cache.getAllWorkspaceManifests(workspaceId);
|
|
4302
|
-
const priorPaths = /* @__PURE__ */ new Set();
|
|
4303
|
-
let prunedSkippedEntries = false;
|
|
4304
|
-
for (const m of priorManifests) {
|
|
4305
|
-
const norm = toPosix(m.relativePath);
|
|
4306
|
-
if (hasSkippedPathSegment(norm)) {
|
|
4307
|
-
prunedSkippedEntries = true;
|
|
4308
|
-
}
|
|
4309
|
-
priorPaths.add(norm);
|
|
4310
|
-
}
|
|
4311
|
-
const sourceFiles = walkSourceFiles(resolvedRoot, writeCache);
|
|
4312
|
-
const activeRelPaths = /* @__PURE__ */ new Set();
|
|
4313
|
-
const rawAllManifests = [];
|
|
4314
|
-
const deltaRelPaths = /* @__PURE__ */ new Set();
|
|
4315
|
-
let cacheHits = 0;
|
|
4316
|
-
let parsedCount = 0;
|
|
4317
|
-
let cacheMutated = schemaInvalidated;
|
|
4318
|
-
for (const absPath of sourceFiles) {
|
|
4319
|
-
let realAbs;
|
|
4320
|
-
try {
|
|
4321
|
-
realAbs = realpathSync2.native(absPath);
|
|
4322
|
-
} catch {
|
|
4323
|
-
realAbs = absPath;
|
|
4324
|
-
}
|
|
4325
|
-
const relPath = toPosix(path6.relative(rootReal, realAbs));
|
|
4326
|
-
if (hasSkippedPathSegment(relPath)) continue;
|
|
4327
|
-
activeRelPaths.add(relPath);
|
|
4328
|
-
let stats;
|
|
4329
|
-
try {
|
|
4330
|
-
stats = statSync2(realAbs);
|
|
4331
|
-
} catch {
|
|
4332
|
-
continue;
|
|
4333
|
-
}
|
|
4334
|
-
if (!stats.isFile()) continue;
|
|
4335
|
-
const statHit = cache.get(workspaceId, relPath, void 0, stats.mtimeMs, stats.size);
|
|
4336
|
-
if (statHit && statHit.schemaVersion === CACHE_SCHEMA_VERSION) {
|
|
4337
|
-
cacheHits += 1;
|
|
4338
|
-
const verified = verifyRelativeAssetsOnDisk(sanitizeManifest(statHit), realAbs);
|
|
4339
|
-
if (verified.changed) {
|
|
4340
|
-
cache.set(workspaceId, verified.manifest);
|
|
4341
|
-
cacheMutated = true;
|
|
4342
|
-
deltaRelPaths.add(relPath);
|
|
4343
|
-
}
|
|
4344
|
-
rawAllManifests.push(verified.manifest);
|
|
4345
|
-
continue;
|
|
4346
|
-
}
|
|
4347
|
-
const source = readFileSync4(realAbs, "utf8");
|
|
4348
|
-
const contentSha256 = sha256Text(source);
|
|
4349
|
-
const hashHit = cache.get(workspaceId, relPath, contentSha256);
|
|
4350
|
-
if (hashHit && hashHit.schemaVersion === CACHE_SCHEMA_VERSION) {
|
|
4351
|
-
cacheHits += 1;
|
|
4352
|
-
const verified = verifyRelativeAssetsOnDisk(
|
|
4353
|
-
sanitizeManifest({
|
|
4354
|
-
...hashHit,
|
|
4355
|
-
mtimeMs: stats.mtimeMs,
|
|
4356
|
-
size: stats.size
|
|
4357
|
-
}),
|
|
4358
|
-
realAbs
|
|
4359
|
-
);
|
|
4360
|
-
cache.set(workspaceId, verified.manifest);
|
|
4361
|
-
cacheMutated = true;
|
|
4362
|
-
if (verified.changed) {
|
|
4363
|
-
deltaRelPaths.add(relPath);
|
|
4364
|
-
}
|
|
4365
|
-
rawAllManifests.push(verified.manifest);
|
|
4366
|
-
continue;
|
|
4367
|
-
}
|
|
4368
|
-
const extracted = verifyRelativeAssetsOnDisk(
|
|
4369
|
-
sanitizeManifest(
|
|
4370
|
-
defaultPolyglotRegistry.extractManifest(source, realAbs, relPath, stats.mtimeMs, stats.size)
|
|
4371
|
-
),
|
|
4372
|
-
realAbs
|
|
4373
|
-
).manifest;
|
|
4374
|
-
parsedCount += 1;
|
|
4375
|
-
cache.set(workspaceId, extracted);
|
|
4376
|
-
cacheMutated = true;
|
|
4377
|
-
rawAllManifests.push(extracted);
|
|
4378
|
-
deltaRelPaths.add(relPath);
|
|
4379
|
-
}
|
|
4380
|
-
const removedPaths = [];
|
|
4381
|
-
for (const oldRel of priorPaths) {
|
|
4382
|
-
if (!activeRelPaths.has(oldRel)) {
|
|
4383
|
-
removedPaths.push(oldRel);
|
|
4384
|
-
}
|
|
4385
|
-
}
|
|
4386
|
-
if (removedPaths.length > 0 || prunedSkippedEntries) {
|
|
4387
|
-
cache.clear(workspaceId);
|
|
4388
|
-
for (const manifest of rawAllManifests) {
|
|
4389
|
-
cache.set(workspaceId, manifest);
|
|
4390
|
-
}
|
|
4391
|
-
cacheMutated = true;
|
|
4392
|
-
}
|
|
4393
|
-
if (writeCache && cacheMutated) {
|
|
4394
|
-
cache.flush();
|
|
4395
|
-
if (schemaInvalidated) {
|
|
4396
|
-
invalidateStaleCloudSyncFile(cachePath, workspaceId);
|
|
4397
|
-
}
|
|
4398
|
-
}
|
|
4399
|
-
const index = buildIndex(resolvedRoot, { workspaceId, cache });
|
|
4400
|
-
const allManifests = [];
|
|
4401
|
-
const manifestDelta = [];
|
|
4402
|
-
for (const file of index.files) {
|
|
4403
|
-
if (hasSkippedPathSegment(file.relative)) continue;
|
|
4404
|
-
const verified = verifyRelativeAssetsOnDisk(sanitizeManifest(file.manifest), file.absolute).manifest;
|
|
4405
|
-
allManifests.push(verified);
|
|
4406
|
-
if (deltaRelPaths.has(file.relative)) {
|
|
4407
|
-
manifestDelta.push(verified);
|
|
4408
|
-
}
|
|
4409
|
-
}
|
|
4410
|
-
return {
|
|
4411
|
-
workspaceId,
|
|
4412
|
-
rootDir: resolvedRoot,
|
|
4413
|
-
subScopePrefix,
|
|
4414
|
-
cachePath,
|
|
4415
|
-
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
4416
|
-
schemaInvalidated,
|
|
4417
|
-
allManifests,
|
|
4418
|
-
manifestDelta,
|
|
4419
|
-
removedPaths,
|
|
4420
|
-
cacheHits,
|
|
4421
|
-
parsedCount,
|
|
4422
|
-
index
|
|
4423
|
-
};
|
|
4424
|
-
}
|
|
4425
|
-
export {
|
|
4426
|
-
CACHE_SCHEMA_VERSION,
|
|
4427
|
-
cleanupNestedTipolinkDirs,
|
|
4428
|
-
computeManifestSyncHash,
|
|
4429
|
-
deriveWorkspaceId,
|
|
4430
|
-
hoistToCanonicalWorkspaceRoot,
|
|
4431
|
-
sanitizeManifest,
|
|
4432
|
-
scanWorkspaceManifests
|
|
4433
|
-
};
|
|
1
|
+
import{createHash as Ln}from"node:crypto";import{existsSync as J,readdirSync as Ct,readFileSync as Pt,realpathSync as _e,rmSync as Et,statSync as It,writeFileSync as wt}from"node:fs";import Rt from"node:os";import N from"node:path";import{createHash as nt}from"node:crypto";import st from"node:path";import p from"typescript";import{existsSync as Xe,mkdirSync as Nt,readFileSync as Dt,renameSync as Tt,writeFileSync as Ye}from"node:fs";import Ot from"node:path";import te from"node:path";function W(e,t){return e<t?-1:e>t?1:0}function D(e){return e.replace(/\\/g,"/")}function C(e){return te.posix.normalize(D(e.trim())).replace(/^\.\//,"")}function B(e,t){let n=t.trim();if(!n)return n;let i=te.isAbsolute(n)?te.resolve(n):te.resolve(e,n),r=te.relative(e,i);return r?r.startsWith("..")||te.isAbsolute(r)?D(n):D(r):"."}function Ne(e,t){let n=te.posix.dirname(C(e)),i=C(t),r=te.posix.relative(n,i);!r.startsWith("./")&&!r.startsWith("../")&&(r=`./${r}`);let s=te.posix.extname(r).toLowerCase(),o=r.slice(0,r.length-s.length);return s===".ts"||s===".tsx"?`${o}.js`:s===".mts"?`${o}.mjs`:s===".cts"?`${o}.cjs`:r}var q="1.0.5";function Ft(e,t,n,i){return t!==void 0?e.contentSha256===t:n!==void 0||i!==void 0?!(n!==void 0&&e.mtimeMs!==n||i!==void 0&&e.size!==i):!0}var ye=class{filePath;schemaInvalidated=!1;autoSave;workspaces=new Map;dirty=!1;constructor(t){typeof t=="string"?(this.filePath=t,this.autoSave=!0):(this.filePath=t.filePath,this.autoSave=t.autoSave??!0),this.loadFromDisk()}loadFromDisk(){if(Xe(this.filePath))try{let t=Dt(this.filePath,"utf8");if(!t.trim())return;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.workspaces||typeof n.workspaces!="object"){this.schemaInvalidated=!0,this.dirty=!0;return}if(n.manifestSchemaVersion!==q){this.workspaces.clear(),this.schemaInvalidated=!0,this.dirty=!0;return}for(let[i,r]of Object.entries(n.workspaces)){if(!r||typeof r!="object")continue;let s=new Map;for(let[o,a]of Object.entries(r))if(a&&typeof a=="object"&&typeof a.contentSha256=="string"){let l=D(o);s.set(l,{...a,relativePath:l})}this.workspaces.set(i,s)}}catch{this.workspaces.clear(),this.schemaInvalidated=!0,this.dirty=!0}}get(t,n,i,r,s){let o=this.workspaces.get(t);if(!o)return;let a=o.get(D(n));if(a)return Ft(a,i,r,s)?a:void 0}set(t,n){let i=D(n.relativePath),r={...n,relativePath:i},s=this.workspaces.get(t);s||(s=new Map,this.workspaces.set(t,s)),s.set(i,r),this.dirty=!0,this.autoSave&&this.save()}getAllWorkspaceManifests(t){let n=this.workspaces.get(t);return n?[...n.values()]:[]}clear(t){t===void 0?this.workspaces.clear():this.workspaces.delete(t),this.dirty=!0,this.autoSave&&this.save()}save(){if(!this.dirty&&Xe(this.filePath))return;let t={version:1,manifestSchemaVersion:q,workspaces:{}};for(let[s,o]of this.workspaces.entries()){let a={};for(let[l,f]of o.entries())a[l]=f;t.workspaces[s]=a}let n=Ot.dirname(this.filePath);Nt(n,{recursive:!0});let i=JSON.stringify(t,null,2),r=`${this.filePath}.${process.pid}.${Date.now()}.tmp`;try{Ye(r,i,"utf8"),Tt(r,this.filePath)}catch{Ye(this.filePath,i,"utf8")}this.dirty=!1}flush(){this.save()}};function Lt(e){switch(st.extname(e).toLowerCase()){case".tsx":return p.ScriptKind.TSX;case".jsx":return p.ScriptKind.JSX;case".js":case".mjs":case".cjs":return p.ScriptKind.JS;default:return p.ScriptKind.TS}}function jt(e){switch(st.extname(e).toLowerCase()){case".js":case".jsx":case".mjs":case".cjs":return"javascript";default:return"typescript"}}function H(e){return e.replace(/\s+/g," ").trim()}function re(e,t=140){return e.length<=t?e:`${e.slice(0,t-3)}...`}function we(e,t){if(!p.canHaveModifiers(e))return!1;let n=p.getModifiers(e);return n?n.some(i=>i.kind===t):!1}function Fe(e){return p.isFunctionDeclaration(e)||p.isFunctionExpression(e)||p.isArrowFunction(e)||p.isMethodDeclaration(e)}function ue(e,t){if(p.isIdentifier(e))t.add(e.text);else if(p.isObjectBindingPattern(e)||p.isArrayBindingPattern(e))for(let n of e.elements)p.isBindingElement(n)&&ue(n.name,t)}function Qe(e,t){if(e.name&&p.isIdentifier(e.name)&&t.add(e.name.text),e.typeParameters)for(let n of e.typeParameters)t.add(n.name.text);for(let n of e.parameters)ue(n.name,t)}function et(e,t){let n=i=>{if(!Fe(i)){if(p.isVariableDeclarationList(i)&&!((i.flags&(p.NodeFlags.Const|p.NodeFlags.Let))!==0))for(let s of i.declarations)ue(s.name,t);p.forEachChild(i,n)}};p.forEachChild(e,n)}function tt(e,t){for(let n of e)if(p.isVariableStatement(n))for(let i of n.declarationList.declarations)ue(i.name,t);else(p.isFunctionDeclaration(n)&&n.name||p.isClassDeclaration(n)&&n.name)&&t.add(n.name.text)}function Wt(e,t){return t?p.isPropertyAccessExpression(t)&&t.name===e||p.isQualifiedName(t)&&t.right===e?"property":p.isBindingElement(t)&&t.propertyName===e||p.isPropertyAssignment(t)&&t.name===e||p.isPropertySignature(t)&&t.name===e||p.isMethodDeclaration(t)&&t.name===e||p.isMethodSignature(t)&&t.name===e||p.isGetAccessorDeclaration(t)&&t.name===e||p.isSetAccessorDeclaration(t)&&t.name===e||p.isPropertyDeclaration(t)&&t.name===e||p.isJsxAttribute(t)&&t.name===e?"object_key":(p.isLabeledStatement(t)||p.isBreakStatement(t)||p.isContinueStatement(t))&&t.label===e?"property":p.isParameter(t)&&t.name===e||p.isVariableDeclaration(t)&&t.name===e||p.isBindingElement(t)&&t.name===e||p.isFunctionDeclaration(t)&&t.name===e||p.isFunctionExpression(t)&&t.name===e||p.isClassDeclaration(t)&&t.name===e||p.isClassExpression(t)&&t.name===e||p.isTypeParameterDeclaration(t)&&t.name===e?"declaration":"variable":"variable"}function it(e){let t=new Set;for(let n of e.statements)if(p.isVariableStatement(n))for(let i of n.declarationList.declarations)ue(i.name,t);else(p.isFunctionDeclaration(n)&&n.name||p.isClassDeclaration(n)&&n.name||p.isEnumDeclaration(n))&&t.add(n.name.text);return t}function De(e,t,n){let i=p.isVariableDeclaration(e)&&e.initializer&&(p.isArrowFunction(e.initializer)||p.isFunctionExpression(e.initializer))?e.initializer:e,r=C(n?.filePath??t.fileName),s=n?.moduleLocalDecls??it(t),o=[],a=0,l=0,f=(c,A,y,b)=>{if(p.isTypeNode(c)||p.isTypeParameterDeclaration(c)||b&&p.isVariableDeclaration(b)&&c===b.exclamationToken)return;if(p.isNonNullExpression(c)||p.isAsExpression(c)||p.isTypeAssertionExpression(c)||p.isSatisfiesExpression(c)){f(c.expression,A,y,c);return}a+=1,A&&(l+=1),o.push(`K:${c.kind}`);let v=y;if(p.isPropertyAccessExpression(c))o.push(`PROP:${c.name.text}`);else if(p.isStringLiteral(c)||p.isNoSubstitutionTemplateLiteral(c))o.push(`STR:${c.text}`);else if(p.isTemplateExpression(c)){o.push(`TPL_H:${c.head.text}`);for(let u of c.templateSpans)o.push(`TPL_M:${u.literal.text}`)}else if(p.isNumericLiteral(c))o.push(`NUM:${c.text}`);else if(p.isRegularExpressionLiteral(c))o.push(`REGEX:${c.text}`);else if(p.isBinaryExpression(c))o.push(`OP:${c.operatorToken.kind}`);else if(p.isPrefixUnaryExpression(c))o.push(`PRE:${c.operator}`);else if(p.isPostfixUnaryExpression(c))o.push(`POST:${c.operator}`);else if(p.isVariableDeclarationList(c)){let u=c.flags&(p.NodeFlags.Const|p.NodeFlags.Let);o.push(`VF:${u}`)}else if(p.isIdentifier(c)){let u=Wt(c,b);u==="declaration"?o.push("ID:$L"):u==="object_key"?o.push(`KEY:${c.text}`):u==="variable"&&(y.has(c.text)?o.push("ID:$L"):s.has(c.text)?o.push(`STATE:${r}:${c.text}`):o.push(`EXT:${c.text}`))}if(c!==i&&Fe(c)){let u=new Set(y);Qe(c,u),c.body&&et(c.body,u),v=u}else if(p.isBlock(c)){let u=new Set(y);tt(c.statements,u),v=u}else if(p.isCaseClause(c)||p.isDefaultClause(c)){let u=new Set(y);tt(c.statements,u),v=u}else if(p.isForStatement(c)||p.isForInStatement(c)||p.isForOfStatement(c)){if(c.initializer&&p.isVariableDeclarationList(c.initializer)){let u=new Set(y);for(let d of c.initializer.declarations)ue(d.name,u);v=u}}else if(p.isCatchClause(c)&&c.variableDeclaration){let u=new Set(y);ue(c.variableDeclaration.name,u),v=u}p.forEachChild(c,u=>f(u,A,v,c))};if(Fe(i)){let c=new Set;p.isVariableDeclaration(e)&&p.isIdentifier(e.name)&&c.add(e.name.text),Qe(i,c),i.body&&et(i.body,c),o.push("FN"),we(i,p.SyntaxKind.AsyncKeyword)&&o.push("MOD:ASYNC"),i.asteriskToken&&o.push("MOD:GEN");for(let A of i.parameters)f(A,!1,c,i);i.body&&f(i.body,!0,c,i)}else f(i,!0,new Set,void 0);return{structuralHash:nt("sha256").update(o.join("|"),"utf8").digest("hex").slice(0,16),nodeCount:a,astNodeCount:l}}function Te(e,t){let n=we(e,p.SyntaxKind.AsyncKeyword),i=e.typeParameters&&e.typeParameters.length>0?`<${e.typeParameters.map(a=>H(a.getText(t))).join(", ")}>`:"",r=e.parameters.map(a=>H(a.getText(t))).join(", "),s=e.type?`: ${H(e.type.getText(t))}`:"";return re(`${n?"async ":""}${i}(${r})${s}`)}function Bt(e,t){if(e.type)return re(`: ${H(e.type.getText(t))}`);let n=e.initializer;if(!n)return": unknown";if(p.isStringLiteral(n)||p.isNoSubstitutionTemplateLiteral(n))return": string";if(p.isNumericLiteral(n))return`= ${n.text}`;if(n.kind===p.SyntaxKind.TrueKeyword)return"= true";if(n.kind===p.SyntaxKind.FalseKeyword)return"= false";if(n.kind===p.SyntaxKind.NullKeyword)return"= null";if(p.isNewExpression(n)){let i=H(n.expression.getText(t));return re(`= new ${i}(...)`,80)}if(p.isObjectLiteralExpression(n)){let i=n.properties.slice(0,5).map(s=>p.isPropertyAssignment(s)||p.isShorthandPropertyAssignment(s)||p.isMethodDeclaration(s)?s.name.getText(t):"..."),r=n.properties.length>5?", ...":"";return re(`= { ${i.join(", ")}${r} }`,100)}return p.isArrayLiteralExpression(n)?`= Array(${n.elements.length})`:"= <expr>"}function zt(e,t){let n=e.name?.text??"default",i=e.typeParameters&&e.typeParameters.length>0?`<${e.typeParameters.map(s=>H(s.getText(t))).join(", ")}>`:"",r=e.heritageClauses&&e.heritageClauses.length>0?` ${e.heritageClauses.map(s=>H(s.getText(t))).join(" ")}`:"";return re(`class ${n}${i}${r}`)}function Ht(e,t){let n=e.name.text,i=e.typeParameters&&e.typeParameters.length>0?`<${e.typeParameters.map(a=>H(a.getText(t))).join(", ")}>`:"",r=e.heritageClauses&&e.heritageClauses.length>0?` ${e.heritageClauses.map(a=>H(a.getText(t))).join(" ")}`:"",s=e.members.slice(0,6).map(a=>H(a.getText(t)).replace(/;$/,"")),o=e.members.length>6?"; ...":"";return re(`interface ${n}${i}${r} { ${s.join("; ")}${o} }`,160)}function Kt(e,t){let n=e.name.text,i=e.typeParameters&&e.typeParameters.length>0?`<${e.typeParameters.map(s=>H(s.getText(t))).join(", ")}>`:"",r=H(e.type.getText(t));return re(`type ${n}${i} = ${r}`,160)}function Vt(e,t){let n=e.members.slice(0,8).map(r=>H(r.name.getText(t))),i=e.members.length>8?", ...":"";return re(`enum ${e.name.text} { ${n.join(", ")}${i} }`,140)}function z(e,t){return t.getLineAndCharacterOfPosition(e.getStart(t)).line+1}function ce(e,t){let n=e.getStart(t),i=Math.max(n,e.getEnd()-1);return t.getLineAndCharacterOfPosition(i).line+1}function Oe(e){if(!e.body)return 0;if(!p.isBlock(e.body))return 1;let t=0,n=i=>{for(let r of i.statements)if(t+=1,p.isIfStatement(r))p.isBlock(r.thenStatement)?n(r.thenStatement):t+=1,r.elseStatement&&(p.isBlock(r.elseStatement)?n(r.elseStatement):p.isIfStatement(r.elseStatement)||(t+=1));else if(p.isTryStatement(r))n(r.tryBlock),r.catchClause&&n(r.catchClause.block),r.finallyBlock&&n(r.finallyBlock);else if(p.isForStatement(r)||p.isForInStatement(r)||p.isForOfStatement(r)||p.isWhileStatement(r)||p.isDoStatement(r))p.isBlock(r.statement)?n(r.statement):t+=1;else if(p.isSwitchStatement(r))for(let s of r.caseBlock.clauses)t+=s.statements.length};return n(e.body),t}function de(e,t,n,i,r,s,o=!1,a){let l=n.trim();if(!l)return;let f=`${l}\0${r?"1":"0"}\0${s?"1":"0"}\0${o?"1":"0"}`,m=t.get(f);if(m){for(let A of i)m.importedNames.includes(A)||m.importedNames.push(A);a!==void 0&&(m.line=m.line!==void 0?Math.min(m.line,a):a);return}let c={rawSpecifier:l,importedNames:[...new Set(i)],isReExport:r,isTypeOnly:s,...o?{isDynamic:!0}:{},...a!==void 0?{line:a}:{}};t.set(f,c),e.push(c)}function Zt(e){let t=[],n=new Map,i=r=>{if(p.isImportDeclaration(r)){if(p.isStringLiteral(r.moduleSpecifier)){let s=[],o=r.importClause,a=!!(o&&!o.name&&o.namedBindings&&p.isNamedImports(o.namedBindings)&&o.namedBindings.elements.length>0&&o.namedBindings.elements.every(f=>f.isTypeOnly)),l=!!o?.isTypeOnly||a;if(o&&(o.name&&s.push("default"),o.namedBindings)){if(p.isNamespaceImport(o.namedBindings))s.push("*");else if(p.isNamedImports(o.namedBindings))for(let f of o.namedBindings.elements)s.push((f.propertyName??f.name).text)}de(t,n,r.moduleSpecifier.text,s,!1,l,!1,z(r,e))}}else if(p.isExportDeclaration(r)){if(r.moduleSpecifier&&p.isStringLiteral(r.moduleSpecifier)){let s=[],o=!!(r.exportClause&&p.isNamedExports(r.exportClause)&&r.exportClause.elements.length>0&&r.exportClause.elements.every(l=>l.isTypeOnly)),a=!!r.isTypeOnly||o;if(!r.exportClause)a||s.push("*");else if(p.isNamespaceExport(r.exportClause))s.push("*");else if(p.isNamedExports(r.exportClause))for(let l of r.exportClause.elements)s.push((l.propertyName??l.name).text);de(t,n,r.moduleSpecifier.text,s,!0,a,!1,z(r,e))}}else if(p.isImportEqualsDeclaration(r))p.isExternalModuleReference(r.moduleReference)&&p.isStringLiteral(r.moduleReference.expression)&&de(t,n,r.moduleReference.expression.text,[r.name.text],!1,!1,!1,z(r,e));else if(p.isCallExpression(r)){let s=r.arguments[0];if(s&&p.isStringLiteralLike(s)){let o=r.expression;o.kind===p.SyntaxKind.ImportKeyword?de(t,n,s.text,[],!1,!1,!0,z(r,e)):p.isIdentifier(o)&&o.text==="require"&&de(t,n,s.text,[],!1,!1,!1,z(r,e))}}else if(p.isImportTypeNode(r)){let s=r.argument;if(p.isLiteralTypeNode(s)&&p.isStringLiteral(s.literal)){let o=r.qualifier?[H(r.qualifier.getText(e))]:[];de(t,n,s.literal.text,o,!1,!0,!1,z(r,e))}}p.forEachChild(r,i)};return i(e),t}function Le(e,t,n,i,r){let s=D(n??t),o=nt("sha256").update(e,"utf8").digest("hex"),a=p.createSourceFile(t,e,p.ScriptTarget.Latest,!0,Lt(t)),l=Zt(a),f=it(a),m={filePath:s,moduleLocalDecls:f},c=new Map,A=[],y=[],b=new Set,v=new Set,u=d=>{let g=`${d.name}\0${d.kind}\0${d.line}`;v.has(g)||(v.add(g),A.push(d))};for(let d of a.statements){let g=we(d,p.SyntaxKind.ExportKeyword),S=we(d,p.SyntaxKind.DefaultKeyword);if(p.isFunctionDeclaration(d)){if(!d.body)continue;let h=d.name?.text,{structuralHash:x,nodeCount:$,astNodeCount:k}=De(d,a,m),w=Te(d,a),R=z(d,a),P=ce(d,a),E=Oe(d);if(h&&c.set(h,{name:h,kind:"function",signature:w,line:R,endLine:P,structuralHash:x,nodeCount:$,astNodeCount:k,statementCount:E,isFunctionHelper:!0,exportedDirectly:g,exportedDefaultDirectly:g&&S}),g){let I=S?"default":h;I&&(u({name:I,...S&&h?{localName:h}:{},kind:"function",signature:w,line:R,endLine:P,structuralHash:x,nodeCount:$,astNodeCount:k,statementCount:E,file:s,isExported:!0}),h&&b.add(h))}}else if(p.isVariableStatement(d))for(let h of d.declarationList.declarations){if(!p.isIdentifier(h.name))continue;let x=h.name.text,$=z(h,a),k=ce(h,a),w=h.initializer;if(w&&(p.isArrowFunction(w)||p.isFunctionExpression(w))){let{structuralHash:R,nodeCount:P,astNodeCount:E}=De(h,a,m),I=Te(w,a),M=Oe(w);c.set(x,{name:x,kind:"function",signature:I,line:$,endLine:k,structuralHash:R,nodeCount:P,astNodeCount:E,statementCount:M,isFunctionHelper:!0,exportedDirectly:g,exportedDefaultDirectly:!1}),g&&(u({name:x,kind:"function",signature:I,line:$,endLine:k,structuralHash:R,nodeCount:P,astNodeCount:E,statementCount:M,file:s,isExported:!0}),b.add(x))}else{let R=Bt(h,a);c.set(x,{name:x,kind:"const",signature:R,line:$,endLine:k,isFunctionHelper:!1,exportedDirectly:g,exportedDefaultDirectly:!1}),g&&(u({name:x,kind:"const",signature:R,line:$,endLine:k,file:s,isExported:!0}),b.add(x))}}else if(p.isClassDeclaration(d)){let h=d.name?.text,x=zt(d,a),$=z(d,a),k=ce(d,a);if(h&&c.set(h,{name:h,kind:"class",signature:x,line:$,endLine:k,isFunctionHelper:!1,exportedDirectly:g,exportedDefaultDirectly:g&&S}),g){let w=S?"default":h;w&&(u({name:w,...S&&h?{localName:h}:{},kind:"class",signature:x,line:$,endLine:k,file:s,isExported:!0}),h&&b.add(h))}}else if(p.isInterfaceDeclaration(d)){let h=d.name.text,x=Ht(d,a),$=z(d,a),k=ce(d,a);c.set(h,{name:h,kind:"interface",signature:x,line:$,endLine:k,isFunctionHelper:!1,exportedDirectly:g,exportedDefaultDirectly:!1}),g&&(u({name:h,kind:"interface",signature:x,line:$,endLine:k,file:s,isExported:!0}),b.add(h))}else if(p.isTypeAliasDeclaration(d)){let h=d.name.text,x=Kt(d,a),$=z(d,a),k=ce(d,a);c.set(h,{name:h,kind:"type",signature:x,line:$,endLine:k,isFunctionHelper:!1,exportedDirectly:g,exportedDefaultDirectly:!1}),g&&(u({name:h,kind:"type",signature:x,line:$,endLine:k,file:s,isExported:!0}),b.add(h))}else if(p.isEnumDeclaration(d)){let h=d.name.text,x=Vt(d,a),$=z(d,a),k=ce(d,a);c.set(h,{name:h,kind:"enum",signature:x,line:$,endLine:k,isFunctionHelper:!1,exportedDirectly:g,exportedDefaultDirectly:!1}),g&&(u({name:h,kind:"enum",signature:x,line:$,endLine:k,file:s,isExported:!0}),b.add(h))}else if(p.isExportDeclaration(d)){if(d.moduleSpecifier&&p.isStringLiteral(d.moduleSpecifier)){if(!d.isTypeOnly&&d.exportClause&&p.isNamedExports(d.exportClause))for(let h of d.exportClause.elements){if(h.isTypeOnly)continue;let x=(h.propertyName??h.name).text,$=h.name.text;u({name:$,...$!==x?{localName:x}:{},kind:"const",signature:`export { ${x} } from '${d.moduleSpecifier.text}'`,line:z(h,a),file:s,isExported:!0,isReExport:!0})}}else if(d.exportClause&&p.isNamedExports(d.exportClause))for(let h of d.exportClause.elements){let x=(h.propertyName??h.name).text,$=h.name.text,k=c.get(x);b.add(x),k?u({name:$,...$!==x?{localName:x}:{},kind:k.kind,signature:k.signature,line:k.line,...k.endLine!==void 0?{endLine:k.endLine}:{},...k.structuralHash!==void 0?{structuralHash:k.structuralHash}:{},...k.nodeCount!==void 0?{nodeCount:k.nodeCount}:{},...k.astNodeCount!==void 0?{astNodeCount:k.astNodeCount}:{},...k.statementCount!==void 0?{statementCount:k.statementCount}:{},file:s,isExported:!0}):!d.isTypeOnly&&!h.isTypeOnly&&u({name:$,...$!==x?{localName:x}:{},kind:"const",signature:`export { ${x} }`,line:z(h,a),file:s,isExported:!0,isReExport:!0})}}else if(p.isExportAssignment(d)&&!d.isExportEquals){let h=z(d,a),x=ce(d,a);if(p.isIdentifier(d.expression)){let $=d.expression.text,k=c.get($);b.add($),u(k?{name:"default",localName:$,kind:k.kind,signature:k.signature,line:k.line,...k.endLine!==void 0?{endLine:k.endLine}:{},...k.structuralHash!==void 0?{structuralHash:k.structuralHash}:{},...k.nodeCount!==void 0?{nodeCount:k.nodeCount}:{},...k.astNodeCount!==void 0?{astNodeCount:k.astNodeCount}:{},...k.statementCount!==void 0?{statementCount:k.statementCount}:{},file:s,isExported:!0}:{name:"default",localName:$,kind:"const",signature:`export default ${$}`,line:h,endLine:x,file:s,isExported:!0,isReExport:!0})}else if(p.isArrowFunction(d.expression)||p.isFunctionExpression(d.expression)){let{structuralHash:$,nodeCount:k,astNodeCount:w}=De(d.expression,a,m),R=Oe(d.expression);u({name:"default",kind:"function",signature:Te(d.expression,a),line:h,endLine:x,structuralHash:$,nodeCount:k,astNodeCount:w,statementCount:R,file:s,isExported:!0})}else u({name:"default",kind:"const",signature:"= <default>",line:h,endLine:x,file:s,isExported:!0})}}for(let[d,g]of c)g.isFunctionHelper&&(g.exportedDirectly||b.has(d)||g.structuralHash===void 0||g.nodeCount===void 0||y.push({name:g.name,kind:"function",signature:g.signature,line:g.line,...g.endLine!==void 0?{endLine:g.endLine}:{},structuralHash:g.structuralHash,nodeCount:g.nodeCount,...g.astNodeCount!==void 0?{astNodeCount:g.astNodeCount}:{},...g.statementCount!==void 0?{statementCount:g.statementCount}:{},file:s,isExported:!1}));return{relativePath:s,contentSha256:o,schemaVersion:q,language:jt(t),...i!==void 0?{mtimeMs:i}:{},...r!==void 0?{size:r}:{},imports:l,exportedSymbols:A,internalFunctions:y}}import{createHash as kn}from"node:crypto";import{readFileSync as bn,readdirSync as mt,realpathSync as ge,statSync as $n}from"node:fs";import{builtinModules as An}from"node:module";import L from"node:path";import ae from"typescript";import{createHash as at}from"node:crypto";import{existsSync as Ut,readFileSync as qt}from"node:fs";import _ from"node:path";function oe(e){return at("sha256").update(e,"utf8").digest("hex")}function j(e){return e.replace(/\s+/g," ").trim()}function X(e,t=140){return e.length<=t?e:`${e.slice(0,t-3)}...`}function K(e,t){let n=1,i=Math.min(t,e.length);for(let r=0;r<i;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function F(e,t){let n=C(t);return!n||n.startsWith("..")?null:e.knownFiles.get(n)??e.knownFiles.get(n.toLowerCase())??null}var Jt={if:"KW:IF",elif:"KW:IF",elsif:"KW:IF",else:"KW:ELSE",for:"KW:FOR",foreach:"KW:FOR",while:"KW:WHILE",loop:"KW:WHILE",match:"KW:MATCH",switch:"KW:MATCH",case:"KW:CASE",when:"KW:CASE",default:"KW:DEFAULT",return:"KW:RETURN",await:"KW:AWAIT",try:"KW:TRY",begin:"KW:TRY",catch:"KW:CATCH",except:"KW:CATCH",rescue:"KW:CATCH",finally:"KW:FINALLY",ensure:"KW:FINALLY",throw:"KW:THROW",raise:"KW:THROW",panic:"KW:THROW",break:"KW:BREAK",continue:"KW:CONTINUE",next:"KW:CONTINUE",yield:"KW:YIELD",in:"KW:IN",new:"KW:NEW",and:"OP:AND",or:"OP:OR",not:"OP:NOT",true:"LIT:BOOL",false:"LIT:BOOL",True:"LIT:BOOL",False:"LIT:BOOL",null:"LIT:NULL",nil:"LIT:NULL",None:"LIT:NULL",nullptr:"LIT:NULL",let:"DECL",const:"DECL",var:"DECL",mut:"DECL",val:"DECL",auto:"DECL",local:"DECL"},Gt=["===","!==","<<=",">>=","..=","==","!=","<=",">=","&&","||","+=","-=","*=","/=","%=",":=","??","?.","=>","->","::","..","<<",">>","**","//"];function rt(e,t){let n=[],i=0,r=e.length,s=0,o=!1;for(;s<r;){let a=e[s],l=s+1<r?e[s+1]:"";if(a===" "||a===" "||a==="\r"||a===`
|
|
2
|
+
`){s+=1;continue}if(a==="/"&&l==="/"){for(s+=2;s<r&&e[s]!==`
|
|
3
|
+
`;)s+=1;continue}if(t&&a==="#"){for(s+=1;s<r&&e[s]!==`
|
|
4
|
+
`;)s+=1;continue}if(a==="/"&&l==="*"){for(s+=2;s+1<r&&!(e[s]==="*"&&e[s+1]==="/");)s+=1;s=Math.min(r,s+2);continue}if(a==='"'&&e.slice(s,s+3)==='"""'||a==="'"&&e.slice(s,s+3)==="'''"){let m=e.slice(s,s+3);for(s+=3;s<r;){if(e[s]==="\\"){s+=2;continue}if(e.slice(s,s+3)===m){s+=3;break}s+=1}n.push("LIT:STR"),i+=1,o=!1;continue}if(a==='"'||a==="'"||a==="`"){let m=a;for(s+=1;s<r;){let c=e[s];if(c==="\\"&&m!=="`"){s+=2;continue}if(c===m){s+=1;break}s+=1}n.push("LIT:STR"),i+=1,o=!1;continue}if((a==="r"||a==="f"||a==="b"||a==="u"||a==="R")&&(l==='"'||l==="'"||l==="#")){if(l==='"'||l==="'"){s+=1;continue}if(a==="r"&&l==="#"){let m=0,c=s+1;for(;c<r&&e[c]==="#";)m+=1,c+=1;if(e[c]==='"'){c+=1;let A='"'+"#".repeat(m),y=e.indexOf(A,c);s=y===-1?r:y+A.length,n.push("LIT:STR"),i+=1,o=!1;continue}}}if(a>="0"&&a<="9"){for(s+=1;s<r&&/[0-9a-fA-FxXoObB._eE]/.test(e[s]);)s+=1;n.push("LIT:NUM"),i+=1,o=!1;continue}if(a==="$"&&s+1<r&&/[a-zA-Z_]/.test(e[s+1])){for(s+=2;s<r&&/[a-zA-Z0-9_]/.test(e[s]);)s+=1;n.push("ID"),i+=1,o=!1;continue}if(a>="a"&&a<="z"||a>="A"&&a<="Z"||a==="_"){let m=s;for(s+=1;s<r&&/[a-zA-Z0-9_]/.test(e[s]);)s+=1;let c=e.slice(m,s);if(o){n.push(`PROP:.${c}`),i+=1,o=!1;continue}let A=Jt[c];if(A)n.push(A),i+=1;else{let y=s;for(;y<r&&(e[y]===" "||e[y]===" ");)y+=1;e[y]==="("?n.push("CALL"):n.push("ID"),i+=1}o=!1;continue}let f=null;for(let m of Gt)if(e.startsWith(m,s)){f=m;break}if(f){f==="&&"?(n.push("OP:AND"),i+=1,o=!1):f==="||"?(n.push("OP:OR"),i+=1,o=!1):f==="->"||f==="::"||f==="?."?(n.push(`OP:${f}`),o=!0):(n.push(`OP:${f}`),i+=1,o=!1),s+=f.length;continue}if(a==="."){n.push("."),o=!0,s+=1;continue}if("+-*/%<>=!&|^~?".includes(a)){n.push(a==="!"?"OP:NOT":`OP:${a}`),i+=1,o=!1,s+=1;continue}if("()[]{},;:".includes(a)){n.push(a),o=!1,s+=1;continue}o=!1,s+=1}return{tokens:n,meaningfulCount:i}}function ne(e,t="",n={}){let i=n.hashComments??!1,r=t.trim()?rt(t,i):{tokens:[],meaningfulCount:0},s=rt(e,i),o=["FN"];n.isAsync&&o.push("MOD:ASYNC"),r.tokens.length>0&&o.push("PARAMS",...r.tokens),o.push("BODY",...s.tokens);let a=at("sha256").update(o.join("|"),"utf8").digest("hex").slice(0,16),l=s.meaningfulCount,f=r.meaningfulCount+l;return{structuralHash:a,nodeCount:f,astNodeCount:l}}function pe(e,t,n=!1){let i=0,r=e.length,s=t;for(;s<r;){let o=e[s],a=s+1<r?e[s+1]:"";if(o==="/"&&a==="/"){for(s+=2;s<r&&e[s]!==`
|
|
5
|
+
`;)s+=1;continue}if(n&&o==="#"){for(s+=1;s<r&&e[s]!==`
|
|
6
|
+
`;)s+=1;continue}if(o==="/"&&a==="*"){for(s+=2;s+1<r&&!(e[s]==="*"&&e[s+1]==="/");)s+=1;s=Math.min(r,s+2);continue}if(o==='"'||o==="'"||o==="`"){let l=o;for(s+=1;s<r;){if(e[s]==="\\"&&l!=="`"){s+=2;continue}if(e[s]===l){s+=1;break}s+=1}continue}if(o==="{")i+=1;else if(o==="}"&&(i-=1,i===0))return s;s+=1}return-1}function me(e){let t=[],n=0,i="";for(let r=0;r<e.length;r+=1){let s=e[r];s==="("||s==="["||s==="<"||s==="{"?n+=1:(s===")"||s==="]"||s===">"||s==="}")&&(n=Math.max(0,n-1)),s===","&&n===0?(i.trim()&&t.push(i.trim()),i=""):i+=s}return i.trim()&&t.push(i.trim()),t}function V(e,t,n,i,r,s=!1){let o=n.trim();if(!o)return;let a=`${o}\0${r?"1":"0"}\0${s?"1":"0"}`,l=t.get(a);if(l){for(let m of i)m&&!l.importedNames.includes(m)&&l.importedNames.push(m);return}let f={rawSpecifier:o,importedNames:[...new Set(i.filter(Boolean))],isReExport:r,isTypeOnly:s};t.set(a,f),e.push(f)}function lt(e,t){if(e===null)return`// pass fromFile to resolve the exact specifier (symbol lives in '${t.file}')`;let n=Ne(e,t.file);return t.name==="default"?`import ${t.localName??"defaultExport"} from '${n}';`:t.kind==="interface"||t.kind==="type"?`import type { ${t.name} } from '${n}';`:`import { ${t.name} } from '${n}';`}function ot(e,t){return{id:e,extensions:t,extractManifest(n,i,r,s,o){return{...Le(n,i,r,s,o),language:e}},resolveImport(n,i,r){let s=n.rawSpecifier.trim();if(s==="."||s===".."||s.startsWith("./")||s.startsWith("../")){let o=_.posix.normalize(_.posix.join(_.posix.dirname(i),s)),a=_.posix.extname(o).toLowerCase(),l={".js":[".ts",".tsx",".js",".jsx"],".jsx":[".tsx",".jsx",".ts",".js"],".mjs":[".mts",".mjs"],".cjs":[".cts",".cjs"]},f=[];if(l[a]){let m=o.slice(0,o.length-a.length);for(let c of l[a])f.push(`${m}${c}`)}f.push(o,`${o}.ts`,`${o}.tsx`,`${o}.mts`,`${o}.cts`,`${o}.js`,`${o}.jsx`,`${o}.mjs`,`${o}.cjs`,`${o}/index.ts`,`${o}/index.tsx`,`${o}/index.js`,`${o}/index.jsx`);for(let m of f){let c=F(r,m);if(c)return{kind:"local",resolvedPaths:[c]}}return{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:o}}return{kind:"external",resolvedPaths:[],externalLabel:s}},formatImportStatement(n,i){return lt(n,i)}}}var Xt=/^\s*(?:[rRuUfFbB]{0,2})(?:"""[\s\S]*?"""|'''[\s\S]*?''')\s*\r?\n?/;function Yt(e){return me(e).map(n=>j(n)).filter(n=>n&&n!=="/"&&n!=="*"&&n!=="self"&&n!=="cls").map(n=>{let i=n.indexOf("=");return i===-1?n:n.slice(0,i).trim()}).join(", ")}function Qt(e){let t=/^__all__\s*(?::[^=]+)?=\s*[\[\(]([\s\S]*?)[\]\)]/m.exec(e);if(!t||!t[1])return null;let n=new Set,i=/['"]([a-zA-Z_][a-zA-Z0-9_]*)['"]/g,r;for(;(r=i.exec(t[1]))!==null;)r[1]&&n.add(r[1]);return n}function en(e,t,n,i){let r=C(t),s=oe(e),o=[],a=new Map,l=[],f=[],m=_.posix.basename(r)==="__init__.py",c=Qt(e),A=b=>c!==null?c.has(b):!b.startsWith("_"),y=e.split(/\r?\n/);for(let b=0;b<y.length;b+=1){let u=y[b].trim();if(!u||u.startsWith("#"))continue;let d=/^from\s+(\.+[a-zA-Z0-9_.]*|[a-zA-Z_][a-zA-Z0-9_.]*)\s+import\s+(.*)$/.exec(u);if(d&&d[1]){let S=d[1],h=(d[2]??"").replace(/#.*$/,"").trim();if(h.startsWith("(")){let k=h.slice(1),w=b;for(;!k.includes(")")&&w+1<y.length;)w+=1,k+=" "+(y[w]??"").replace(/#.*$/,"");let R=k.indexOf(")");h=R===-1?k:k.slice(0,R),b=w}let x=h.split(",").map(k=>k.trim()).filter(Boolean).map(k=>/^([a-zA-Z0-9_*]+)(?:\s+as\s+([a-zA-Z0-9_]+))?/.exec(k)?.[1]??"").filter(Boolean),$=m&&(c===null||x.some(k=>k==="*"||c.has(k)));V(o,a,S,x,$,!1);continue}let g=/^import\s+(.+)$/.exec(u);if(g&&g[1]){let S=g[1].replace(/#.*$/,"").trim();for(let h of S.split(",")){let x=h.trim(),$=/^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\s+as\s+([a-zA-Z_][a-zA-Z0-9_]*))?$/.exec(x);$&&$[1]&&V(o,a,$[1],[],!1,!1)}continue}}for(let b=0;b<y.length;b+=1){let v=y[b];if(!v.trim()||v.startsWith(" ")||v.startsWith(" ")||v.startsWith("#"))continue;let u=/^(async\s+)?def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/.exec(v);if(u&&u[2]){let S=!!u[1],h=u[2],x=b+1,$=v,k=b,w=0,R=!1;for(let Y=b;Y<y.length;Y+=1){let Me=y[Y];for(let Ge of Me)Ge==="("?(w+=1,R=!0):Ge===")"&&(w=Math.max(0,w-1));if(Y>b&&($+=" "+Me.trim()),k=Y,R&&w===0&&Me.replace(/#.*$/,"").trim().endsWith(":"))break}let P=/^(?:async\s+)?def\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\(([\s\S]*)\)\s*(?:->\s*([^:]+))?\s*:/.exec($.replace(/#[^\n]*$/gm,"").trim()),E=P?.[1]??"",I=P?.[2]?.trim(),M=Yt(E),T=X(`${S?"async ":""}(${M})${I?`: ${j(I)}`:""}`),O=[],U=k+1;for(;U<y.length;){let Y=y[U];if(Y.trim()===""){O.push(Y),U+=1;continue}if(!Y.startsWith(" ")&&!Y.startsWith(" "))break;O.push(Y),U+=1}let ee=O.join(`
|
|
7
|
+
`).replace(Xt,""),{structuralHash:Q,nodeCount:G,astNodeCount:Ae}=ne(ee,M,{isAsync:S,hashComments:!0});A(h)?l.push({name:h,kind:"function",signature:T,line:x,structuralHash:Q,nodeCount:G,astNodeCount:Ae,file:r,isExported:!0}):f.push({name:h,kind:"function",signature:T,line:x,structuralHash:Q,nodeCount:G,astNodeCount:Ae,file:r,isExported:!1}),b=Math.max(k,U-1);continue}let d=/^class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:\(([^)]*)\))?\s*:/.exec(v);if(d&&d[1]){let S=d[1];if(A(S)){let h=d[2]?.trim();l.push({name:S,kind:"class",signature:X(`class ${S}${h?`(${j(h)})`:""}`),line:b+1,file:r,isExported:!0})}continue}let g=/^([A-Z][A-Z0-9_]{1,})\s*(?::\s*([^=]+))?=\s*(.+)$/.exec(v);if(g&&g[1]&&g[1]!=="__ALL__"){let S=g[1];if(A(S)){let h=g[2]?.trim(),x=g[3]?.trim()??"",$=h?`: ${j(h)}`:/^(['"]).*\1$/.test(x)||/^\d/.test(x)||/^(True|False|None)$/.test(x)?`= ${x}`:"= <expr>";l.push({name:S,kind:"const",signature:X($,80),line:b+1,file:r,isExported:!0})}}}return{relativePath:r,contentSha256:s,language:"python",...n!==void 0?{mtimeMs:n}:{},...i!==void 0?{size:i}:{},imports:o,exportedSymbols:l,internalFunctions:f}}function tn(e,t,n){let i=e.rawSpecifier.trim(),r=_.posix.dirname(C(t)),s=[],o=v=>{let u=C(v);return F(n,`${u}.py`)??F(n,`${u}/__init__.py`)};if(i.startsWith(".")){let v=0;for(;v<i.length&&i[v]===".";)v+=1;let u=i.slice(v),d=r==="."?"":r;for(let S=1;S<v;S+=1){if(!d)return{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:i};let h=_.posix.dirname(d);d=h==="."?"":h}if(u){let S=u.split(".").join("/"),h=d?`${d}/${S}`:S,x=o(h);return x?{kind:"local",resolvedPaths:[x]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:`${C(h)}.py`}}for(let S of e.importedNames){if(S==="*")continue;let h=d?`${d}/${S}`:S,x=o(h);x&&!s.includes(x)&&s.push(x)}if(s.length>0)return{kind:"local",resolvedPaths:s.sort(W)};let g=F(n,d?`${d}/__init__.py`:"__init__.py");return g?{kind:"local",resolvedPaths:[g]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:d?`${d}/__init__.py`:"__init__.py"}}let a=i.split(".").filter(Boolean);if(a.length===0)return{kind:"external",resolvedPaths:[],externalLabel:i};let l=a.join("/"),f=n.pythonSourceRoots.length>0?n.pythonSourceRoots:["","src"],m=[],c=C(t).split("/");(c[0]==="packages"||c[0]==="apps")&&c[1]&&(m.push(`${c[0]}/${c[1]}`),m.push(`${c[0]}/${c[1]}/src`));let A=[...new Set([...f,...m])];for(let v of A){let u=v?`${v}/${l}`:l,d=o(u);if(d){if(d.endsWith("/__init__.py")&&e.importedNames.length>0){let g=[];for(let S of e.importedNames){if(S==="*")continue;let h=o(`${u}/${S}`);h&&!g.includes(h)&&g.push(h)}if(g.length>0)return{kind:"local",resolvedPaths:g.sort(W)}}return{kind:"local",resolvedPaths:[d]}}}let y=a[0],b=null;for(let v of A){let u=v?`${v}/${y}/`:`${y}/`,d=v?`${v}/${y}.py`:`${y}.py`;if(F(n,d)||n.allRelativePaths.some(g=>g.startsWith(u)&&g.endsWith(".py"))){b=v;break}}if(b!==null){let v=b?`${b}/${l}.py`:`${l}.py`;return{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:C(v)}}return{kind:"external",resolvedPaths:[],externalLabel:i}}function nn(e,t){let n=C(e.file),i=(t?.pythonSourceRoots??["src"]).filter(Boolean).sort((s,o)=>o.length-s.length);for(let s of i){let o=`${C(s)}/`;if(n.startsWith(o)){n=n.slice(o.length);break}}return n=n.replace(/\/__init__\.py$/i,"").replace(/\.py$/i,""),`from ${n.split("/").filter(Boolean).join(".")||"."} import ${e.name}`}var sn={id:"python",extensions:[".py"],extractManifest(e,t,n,i,r){return en(e,n,i,r)},resolveImport:tn,formatImportStatement(e,t,n){return nn(t,n)}};function rn(e){let t=me(e);if(t.length===0)return"";let n=[],i=[];for(let r of t){let s=j(r).split(" ");if(s.length===1)i.push(s[0]);else{let o=s[0],a=s.slice(1).join(" ");n.push({names:[...i,o],type:a}),i=[]}}if(i.length>0)for(let r=0;r<i.length;r+=1)n.push({names:[`p${r}`],type:i[r]});return n.flatMap(r=>r.names.map(s=>`${s}: ${r.type}`)).join(", ")}function on(e,t,n,i){let r=C(t),s=oe(e),o=[],a=new Map,l=[],f=[],m=e.replace(/\/\*[\s\S]*?\*\//g,x=>x.replace(/[^\n]/g," ")),c=/^\s*import\s*\(([\s\S]*?)\)/gm,A;for(;(A=c.exec(m))!==null;){let x=A[1]??"";for(let $ of x.split(/\r?\n/)){let k=$.replace(/\/\/.*$/,"").trim(),w=/^(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/.exec(k);if(w&&w[2]){let R=w[1],P=_.posix.basename(w[2]);V(o,a,w[2],R&&R!=="_"&&R!=="."?[R]:[P],!1)}}}let y=/^\s*import\s+(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/gm,b;for(;(b=y.exec(m))!==null;)if(b[2]){let x=b[1],$=_.posix.basename(b[2]);V(o,a,b[2],x&&x!=="_"&&x!=="."?[x]:[$],!1)}let v=/^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s*\(([^)]*)\)\s*([^{;\n]*)\{/gm,u;for(;(u=v.exec(e))!==null;){let x=u[1];if(!x)continue;let $=u[2]??"",k=j(u[3]??""),w=u.index+u[0].length-1,R=pe(e,w,!1),P=R>w?e.slice(w+1,R):"",E=rn($),I=X(`(${E})${k?`: ${k}`:""}`),M=K(e,u.index),{structuralHash:T,nodeCount:O,astNodeCount:U}=ne(P,E,{hashComments:!1});/^[A-Z]/.test(x)?l.push({name:x,kind:"function",signature:I,line:M,structuralHash:T,nodeCount:O,astNodeCount:U,file:r,isExported:!0}):f.push({name:x,kind:"function",signature:I,line:M,structuralHash:T,nodeCount:O,astNodeCount:U,file:r,isExported:!1})}let d=/^type\s+([A-Z][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s+(struct|interface|[^\s{]+)/gm,g;for(;(g=d.exec(e))!==null;){let x=g[1],$=g[2];if(!x||!$)continue;let k=$==="struct"?"class":$==="interface"?"interface":"type";l.push({name:x,kind:k,signature:X(`type ${x} ${$}`),line:K(e,g.index),file:r,isExported:!0})}let S=/^(?:const|var)\s+([A-Z][a-zA-Z0-9_]*)\s*(?:([a-zA-Z0-9_.*\[\]]+)\s*)?=\s*([^\n]+)/gm,h;for(;(h=S.exec(e))!==null;){let x=h[1];if(!x)continue;let $=h[2]?.trim();l.push({name:x,kind:"const",signature:X($?`: ${$}`:"= <expr>",80),line:K(e,h.index),file:r,isExported:!0})}return{relativePath:r,contentSha256:s,language:"go",...n!==void 0?{mtimeMs:n}:{},...i!==void 0?{size:i}:{},imports:o,exportedSymbols:l,internalFunctions:f}}function an(e,t,n){let i=e.rawSpecifier.trim(),r=C(t),s=[...n.goModuleDirs.entries()].sort((o,a)=>a[1].length-o[1].length);s.length===0&&n.goModulePath&&s.push(["",n.goModulePath]);for(let[o,a]of s)if(i===a||i.startsWith(`${a}/`)){let l=i===a?"":i.slice(a.length+1),f=C(o?l?`${o}/${l}`:o:l),m=n.allRelativePaths.filter(c=>{if(!c.endsWith(".go")||c.endsWith("_test.go")||c===r)return!1;let A=_.posix.dirname(c);return(A==="."?"":A)===f}).sort(W);return m.length>0?{kind:"local",resolvedPaths:m}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:f||i}}return{kind:"external",resolvedPaths:[],externalLabel:i}}function ln(e,t){let n=_.posix.dirname(C(e.file)),i=n==="."?"":n,r=i||".";if(t){let o=[...t.goModuleDirs.entries()].sort((l,f)=>f[0].length-l[0].length),a=!1;for(let[l,f]of o){if(!l){r=i?`${f}/${i}`:f,a=!0;break}if(i===l||i.startsWith(`${l}/`)){let m=i.slice(l.length).replace(/^\//,"");r=m?`${f}/${m}`:f,a=!0;break}}!a&&t.goModulePath&&(r=i?`${t.goModulePath}/${i}`:t.goModulePath)}let s=_.posix.basename(r);return`import "${r}" // ${s}.${e.name}`}var cn={id:"go",extensions:[".go"],extractManifest(e,t,n,i,r){return on(e,n,i,r)},resolveImport:an,formatImportStatement(e,t,n){return ln(t,n)}};function ct(e){let t=j(e).replace(/;$/,"").trim(),n=t.indexOf("{");if(n===-1)return[t];let i=0,r=-1;for(let f=n;f<t.length;f+=1)if(t[f]==="{")i+=1;else if(t[f]==="}"&&(i-=1,i===0)){r=f;break}if(r===-1)return[t];let s=t.slice(0,n).trim(),o=t.slice(n+1,r),a=t.slice(r+1).trim(),l=[];for(let f of me(o)){let m=f.trim();if(m)if(m==="self")l.push(s.replace(/::$/,""));else{let c=`${s}${m}${a}`;l.push(...ct(c))}}return l}function un(e,t,n,i){let r=C(t),s=oe(e),o=[],a=new Map,l=[],f=[],m=e.replace(/\/\*[\s\S]*?\*\//g,S=>S.replace(/[^\n]/g," ")).replace(/\/\/[^\n]*/g,""),c=/^\s*(pub(?:\([^)]*\))?\s+)?mod\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*;/gm,A;for(;(A=c.exec(m))!==null;)A[2]&&V(o,a,`mod::${A[2]}`,[A[2]],!!A[1],!1);let y=/^\s*(pub(?:\([^)]*\))?\s+)?use\s+([\s\S]*?);/gm,b;for(;(b=y.exec(m))!==null;){let S=!!b[1],h=b[2]??"";for(let x of ct(h)){let $=x.replace(/\s+as\s+[a-zA-Z_][a-zA-Z0-9_]*$/,"").trim();if(!$)continue;let k=$.split("::").filter(Boolean),w=k[k.length-1]??"";V(o,a,$,w&&w!=="*"?[w]:w==="*"?["*"]:[],S,!1)}}let v=/^(pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([a-zA-Z_][a-zA-Z0-9_]*)(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?:->\s*([^{\n]+?))?\s*(?:where\s+[^{]+)?\{/gm,u;for(;(u=v.exec(e))!==null;){let S=!!u[1],h=u[2];if(!h)continue;let x=/\basync\s+fn\b/.test(u[0]),$=j(u[3]??""),k=j(u[4]??""),w=u.index+u[0].length-1,R=pe(e,w,!1),P=R>w?e.slice(w+1,R):"",E=X(`${x?"async ":""}(${$})${k?`: ${k}`:""}`),I=K(e,u.index),{structuralHash:M,nodeCount:T,astNodeCount:O}=ne(P,$,{isAsync:x,hashComments:!1});S?l.push({name:h,kind:"function",signature:E,line:I,structuralHash:M,nodeCount:T,astNodeCount:O,file:r,isExported:!0}):f.push({name:h,kind:"function",signature:E,line:I,structuralHash:M,nodeCount:T,astNodeCount:O,file:r,isExported:!1})}let d=/^pub(?:\([^)]*\))?\s+(struct|enum|trait|type|const|static)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm,g;for(;(g=d.exec(e))!==null;){let S=g[1],h=g[2];if(!S||!h)continue;let x=S==="struct"?"class":S==="enum"?"enum":S==="trait"?"interface":S==="type"?"type":"const";l.push({name:h,kind:x,signature:`${S} ${h}`,line:K(e,g.index),file:r,isExported:!0})}return{relativePath:r,contentSha256:s,language:"rust",...n!==void 0?{mtimeMs:n}:{},...i!==void 0?{size:i}:{},imports:o,exportedSymbols:l,internalFunctions:f}}function ut(e,t){let n=C(e);if(t&&t.rustCrates.length>0){let r=[...t.rustCrates].sort((s,o)=>o.srcDir.length-s.srcDir.length);for(let s of r)if(!s.srcDir||n===s.srcDir||n.startsWith(`${s.srcDir}/`)||!s.crateDir||n.startsWith(`${s.crateDir}/`))return s}let i=n.indexOf("/src/");return i!==-1?{crateDir:n.slice(0,i),srcDir:`${n.slice(0,i)}/src`}:n.startsWith("src/")?{crateDir:"",srcDir:"src"}:{crateDir:"",srcDir:""}}function fn(e,t,n){let i=e.rawSpecifier.trim(),r=C(t),s=_.posix.dirname(r),o=s==="."?"":s,a=_.posix.basename(r),l=ut(r,n),f=u=>{let d=C(u);return F(n,`${d}.rs`)??F(n,`${d}/mod.rs`)};if(i.startsWith("mod::")){let u=i.slice(5),d=a==="lib.rs"||a==="main.rs"||a==="mod.rs",g=[];if(d)g.push(o?`${o}/${u}`:u);else{let h=a.replace(/\.rs$/,"");g.push(o?`${o}/${h}/${u}`:`${h}/${u}`),g.push(o?`${o}/${u}`:u)}for(let h of g){let x=f(h);if(x)return{kind:"local",resolvedPaths:[x]}}let S=g[0]?`${C(g[0])}.rs`:`${u}.rs`;return{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:S}}let m=i.split("::").filter(Boolean);if(m.length===0)return{kind:"external",resolvedPaths:[],externalLabel:i};let c=null,A=[];if(m[0]==="crate")c=l.srcDir,A=m.slice(1);else if(m[0]==="self")c=a==="lib.rs"||a==="main.rs"||a==="mod.rs"?o:C(`${o}/${a.replace(/\.rs$/,"")}`),A=m.slice(1);else if(m[0]==="super"){let u=o,d=a==="lib.rs"||a==="main.rs"||a==="mod.rs",g=0;for(d||(g=1);g<m.length&&m[g]==="super";){let S=_.posix.dirname(u);u=S==="."?"":S,g+=1}c=u,A=m.slice(g)}else{let u=n.rustCrates.find(d=>d.crateName&&d.crateName.replace(/-/g,"_")===m[0].replace(/-/g,"_"));u&&(c=u.srcDir,A=m.slice(1))}if(c===null){let u=o?`${o}/${m[0]}`:m[0],d=f(u);return d&&d!==r?{kind:"local",resolvedPaths:[d]}:{kind:"external",resolvedPaths:[],externalLabel:i}}let y=A.filter(u=>u!=="*"),b=[];y.length>=1&&b.push(y.length),y.length>=2&&b.push(y.length-1),y.length>=3&&/^[A-Z]/.test(y[y.length-2]??"")&&b.push(y.length-2);for(let u of b){let d=y.slice(0,u).join("/"),g=c?`${c}/${d}`:d,S=f(g);if(S&&S!==r)return{kind:"local",resolvedPaths:[S]}}if(y.length<=1){let u=F(n,c?`${c}/mod.rs`:"mod.rs")??F(n,c?`${c}/lib.rs`:"lib.rs")??F(n,c?`${c}/main.rs`:"main.rs");if(u&&u!==r)return{kind:"local",resolvedPaths:[u]}}let v=y.length>0?`${C(c?`${c}/${y.slice(0,Math.max(1,y.length-1)).join("/")}`:y[0])}.rs`:`${c||"src"}/lib.rs`;return{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:v}}function dn(e,t){let n=C(e.file),i=ut(n,t),r=n;i.srcDir&&r.startsWith(`${i.srcDir}/`)&&(r=r.slice(i.srcDir.length+1)),r=r.replace(/\/mod\.rs$/i,"").replace(/^(?:lib|main)\.rs$/i,"").replace(/\.rs$/i,"");let s=r.split("/").filter(Boolean);return`use ${s.length>0?`crate::${s.join("::")}`:"crate"}::${e.name};`}var pn={id:"rust",extensions:[".rs"],extractManifest(e,t,n,i,r){return un(e,n,i,r)},resolveImport:fn,formatImportStatement(e,t,n){return dn(t,n)}};function ft(e,t){return{id:e,extensions:t,extractManifest(n,i,r,s,o){let a=C(r),l=oe(n),f=[],m=new Map,c=[],A=[],y=/^\s*import\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.*]*)\s*;?/gm,b;for(;(b=y.exec(n))!==null;){let S=b[1];if(!S)continue;let h=S.lastIndexOf("."),x=h===-1?S:S.slice(h+1);V(f,m,S,x?[x]:[],!1)}let v=e==="java"?/^\s*public\s+(?:abstract\s+|final\s+|sealed\s+)?(class|interface|enum|record)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm:/^\s*(?:(private|internal|protected)\s+)?(?:data\s+|sealed\s+|abstract\s+|open\s+)?(class|interface|enum\s+class|object)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm,u;for(;(u=v.exec(n))!==null;)if(e==="java"){let S=u[1],h=u[2];c.push({name:h,kind:S==="interface"?"interface":S==="enum"?"enum":"class",signature:`${S} ${h}`,line:K(n,u.index),file:a,isExported:!0})}else{let S=u[1],h=u[2],x=u[3];if(S==="private")continue;c.push({name:x,kind:h==="interface"?"interface":h.startsWith("enum")?"enum":"class",signature:`${h} ${x}`,line:K(n,u.index),file:a,isExported:!0})}let d=e==="java"?/^\s*(public|private|protected)\s+(?:static\s+)?(?:final\s+)?(?:synchronized\s+)?(?:<[^>]+>\s+)?([a-zA-Z_][a-zA-Z0-9_<>\[\]., ?]*)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?:throws\s+[^{]+)?\{/gm:/^\s*(?:(public|private|internal|protected)\s+)?(?:suspend\s+)?fun\s+(?:<[^>]+>\s+)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?::\s*([^{\n=]+))?\s*\{/gm,g;for(;(g=d.exec(n))!==null;){let S=e==="java",h=g[1]??"public",x=S?g[3]:g[2];if(!x||x==="if"||x==="for"||x==="while"||x==="switch")continue;let $=j(S?g[4]??"":g[3]??""),k=j(S?g[2]??"":g[4]??""),w=g.index+g[0].length-1,R=pe(n,w,!1),P=R>w?n.slice(w+1,R):"",E=S?me($).map(ee=>{let Q=j(ee).split(" ");if(Q.length>=2){let G=Q[Q.length-1],Ae=Q.slice(0,-1).join(" ");return`${G}: ${Ae}`}return ee}).join(", "):$,I=X(`(${E})${k?`: ${k}`:""}`),{structuralHash:M,nodeCount:T,astNodeCount:O}=ne(P,E),U=K(n,g.index);h==="public"||h===""?c.push({name:x,kind:"function",signature:I,line:U,structuralHash:M,nodeCount:T,astNodeCount:O,file:a,isExported:!0}):A.push({name:x,kind:"function",signature:I,line:U,structuralHash:M,nodeCount:T,astNodeCount:O,file:a,isExported:!1})}return{relativePath:a,contentSha256:l,language:e,...s!==void 0?{mtimeMs:s}:{},...o!==void 0?{size:o}:{},imports:f,exportedSymbols:c,internalFunctions:A}},resolveImport(n,i,r){let s=n.rawSpecifier.trim(),o=C(i),a=s.endsWith(".*"),l=a?s.slice(0,-2):s,f=l.replace(/\./g,"/");if(a){let v=r.allRelativePaths.filter(u=>u!==o&&(u.endsWith(".java")||u.endsWith(".kt"))&&(r.javaPackagesByFile.get(u)===l||u.includes(`/${f}/`))).sort(W);return v.length>0?{kind:"local",resolvedPaths:v}:{kind:"external",resolvedPaths:[],externalLabel:s}}let m=s.lastIndexOf("."),c=m===-1?"":s.slice(0,m),A=m===-1?s:s.slice(m+1),y=r.allRelativePaths.filter(v=>{if(v===o||!v.endsWith(".java")&&!v.endsWith(".kt"))return!1;if(v.endsWith(`/${f}.java`)||v.endsWith(`/${f}.kt`)||v===`${f}.java`||v===`${f}.kt`)return!0;let u=r.javaPackagesByFile.get(v),d=_.posix.basename(v).replace(/\.(java|kt)$/,"");return!!(u&&u===c&&d===A)}).sort(W);if(y.length>0)return{kind:"local",resolvedPaths:y};let b=new Set(r.javaPackagesByFile.values());return c&&b.has(c)?{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:`${f}.${e==="java"?"java":"kt"}`}:{kind:"external",resolvedPaths:[],externalLabel:s}},formatImportStatement(n,i,r){let s=r?.javaPackagesByFile.get(C(i.file)),o=s?`${s}.${i.name}`:i.name;return e==="java"?`import ${o};`:`import ${o}`}}}var mn=ft("java",[".java"]),hn=ft("kotlin",[".kt",".kts"]),gn={id:"csharp",extensions:[".cs"],extractManifest(e,t,n,i,r){let s=C(n),o=oe(e),a=[],l=new Map,f=[],m=[],c=/^\s*(?:global\s+)?using\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.]*)\s*;/gm,A;for(;(A=c.exec(e))!==null;)A[1]&&V(a,l,A[1],[A[1]],!1);let y=/^\s*public\s+(?:static\s+|abstract\s+|sealed\s+|partial\s+)?(class|interface|struct|record|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm,b;for(;(b=y.exec(e))!==null;){let d=b[1],g=b[2];f.push({name:g,kind:d==="interface"?"interface":d==="enum"?"enum":"class",signature:`${d} ${g}`,line:K(e,b.index),file:s,isExported:!0})}let v=/^\s*(public|private|internal|protected)\s+(?:static\s+)?(?:async\s+)?(?:virtual\s+|override\s+)?([a-zA-Z_][a-zA-Z0-9_<>\[\]., ?]*)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*\{/gm,u;for(;(u=v.exec(e))!==null;){let d=u[1],g=j(u[2]??""),S=u[3],h=j(u[4]??""),x=u.index+u[0].length-1,$=pe(e,x,!1),k=$>x?e.slice(x+1,$):"",w=me(h).map(T=>{let O=j(T).split(" ");return O.length>=2?`${O[O.length-1]}: ${O.slice(0,-1).join(" ")}`:T}).join(", "),{structuralHash:R,nodeCount:P,astNodeCount:E}=ne(k,w),I=X(`(${w})${g?`: ${g}`:""}`),M=K(e,u.index);d==="public"?f.push({name:S,kind:"function",signature:I,line:M,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!0}):m.push({name:S,kind:"function",signature:I,line:M,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!1})}return{relativePath:s,contentSha256:o,language:"csharp",...i!==void 0?{mtimeMs:i}:{},...r!==void 0?{size:r}:{},imports:a,exportedSymbols:f,internalFunctions:m}},resolveImport(e,t,n){let i=e.rawSpecifier.trim(),r=C(t),s=[];for(let[o,a]of n.csharpNamespacesByFile.entries())o!==r&&a.includes(i)&&s.push(o);return s.length>0?{kind:"local",resolvedPaths:s.sort(W)}:{kind:"external",resolvedPaths:[],externalLabel:i}},formatImportStatement(e,t,n){let i=n?.csharpNamespacesByFile.get(C(t.file))?.[0];return i?`using ${i}; // ${t.name}`:`// ${t.name} in ${t.file}`}},xn={id:"php",extensions:[".php"],extractManifest(e,t,n,i,r){let s=C(n),o=oe(e),a=[],l=new Map,f=[],m=[],c=/^\s*use\s+(?:function\s+|const\s+)?([a-zA-Z_\\][a-zA-Z0-9_\\]*)(?:\s+as\s+[a-zA-Z_][a-zA-Z0-9_]*)?\s*;/gm,A;for(;(A=c.exec(e))!==null;)if(A[1]){let S=A[1].replace(/^\\/,""),h=S.split("\\");V(a,l,S,[h[h.length-1]??S],!1)}let y=/\b(?:require|require_once|include|include_once)\s*\(?\s*['"]([^'"]+)['"]\s*\)?\s*;/g,b;for(;(b=y.exec(e))!==null;)b[1]&&V(a,l,b[1],[],!1);let v=/^\s*(?:final\s+|abstract\s+|readonly\s+)?(class|interface|trait|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm,u;for(;(u=v.exec(e))!==null;){let S=u[1],h=u[2];f.push({name:h,kind:S==="interface"||S==="trait"?"interface":S==="enum"?"enum":"class",signature:`${S} ${h}`,line:K(e,u.index),file:s,isExported:!0})}let d=/^\s*(?:(public|private|protected)\s+)?(?:static\s+)?function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?::\s*([^{\n]+))?\s*\{/gm,g;for(;(g=d.exec(e))!==null;){let S=g[1]??"public",h=g[2],x=j(g[3]??""),$=j(g[4]??""),k=g.index+g[0].length-1,w=pe(e,k,!0),R=w>k?e.slice(k+1,w):"",{structuralHash:P,nodeCount:E,astNodeCount:I}=ne(R,x,{hashComments:!0}),M=X(`(${x})${$?`: ${$}`:""}`),T=K(e,g.index);S==="public"?f.push({name:h,kind:"function",signature:M,line:T,structuralHash:P,nodeCount:E,astNodeCount:I,file:s,isExported:!0}):m.push({name:h,kind:"function",signature:M,line:T,structuralHash:P,nodeCount:E,astNodeCount:I,file:s,isExported:!1})}return{relativePath:s,contentSha256:o,language:"php",...i!==void 0?{mtimeMs:i}:{},...r!==void 0?{size:r}:{},imports:a,exportedSymbols:f,internalFunctions:m}},resolveImport(e,t,n){let i=e.rawSpecifier.trim(),r=_.posix.dirname(C(t));if(i.startsWith("./")||i.startsWith("../")||i.endsWith(".php")){let l=_.posix.normalize(_.posix.join(r,i)),f=F(n,l)??F(n,i);return f?{kind:"local",resolvedPaths:[f]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:l}}let s=i.replace(/^\\/,""),o=[...n.phpPsr4Mappings].sort((l,f)=>f.prefix.length-l.prefix.length);for(let l of o)if(s.startsWith(l.prefix)){let f=s.slice(l.prefix.length).replace(/\\/g,"/"),m=C(`${l.dir}/${f}.php`),c=F(n,m);return c?{kind:"local",resolvedPaths:[c]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:m}}let a=F(n,`${s.replace(/\\/g,"/")}.php`);return a?{kind:"local",resolvedPaths:[a]}:{kind:"external",resolvedPaths:[],externalLabel:i}},formatImportStatement(e,t,n){let i=n?.phpNamespacesByFile.get(C(t.file));return i?`use ${i}\\${t.name};`:`require_once '${t.file}'; // ${t.name}`}},yn={id:"ruby",extensions:[".rb"],extractManifest(e,t,n,i,r){let s=C(n),o=oe(e),a=[],l=new Map,f=[],m=[],c=e.split(/\r?\n/),A=!1;for(let y=0;y<c.length;y+=1){let b=c[y],v=b.trim();if(!v||v.startsWith("#"))continue;if(v==="private"){A=!0;continue}if(v==="public"){A=!1;continue}let u=/^require_relative\s+['"]([^'"]+)['"]/.exec(v);if(u&&u[1]){V(a,l,`rel:${u[1]}`,[],!1);continue}let d=/^require\s+['"]([^'"]+)['"]/.exec(v);if(d&&d[1]){V(a,l,d[1],[],!1);continue}let g=/^(class|module)\s+([A-Z][a-zA-Z0-9_:]*)/.exec(v);if(g&&g[1]&&g[2]){A=!1,f.push({name:g[2],kind:"class",signature:`${g[1]} ${g[2]}`,line:y+1,file:s,isExported:!0});continue}let S=/^(\s*)def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_!?]*)(?:\(([^)]*)\))?/.exec(b);if(S&&S[2]){let h=(S[1]??"").length,x=S[2],$=j(S[3]??""),k=[],w=y+1;for(;w<c.length;){let M=c[w],T=M.length-M.trimStart().length;if(M.trim()==="end"&&T<=h)break;k.push(M),w+=1}let{structuralHash:R,nodeCount:P,astNodeCount:E}=ne(k.join(`
|
|
8
|
+
`),$,{hashComments:!0}),I=X(`(${$})`);!A&&!x.startsWith("_")?f.push({name:x,kind:"function",signature:I,line:y+1,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!0}):m.push({name:x,kind:"function",signature:I,line:y+1,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!1}),y=w}}return{relativePath:s,contentSha256:o,language:"ruby",...i!==void 0?{mtimeMs:i}:{},...r!==void 0?{size:r}:{},imports:a,exportedSymbols:f,internalFunctions:m}},resolveImport(e,t,n){let i=e.rawSpecifier.trim(),r=_.posix.dirname(C(t));if(i.startsWith("rel:")){let o=i.slice(4),a=_.posix.normalize(_.posix.join(r,o)),l=F(n,a)??F(n,`${a}.rb`);return l?{kind:"local",resolvedPaths:[l]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:a.endsWith(".rb")?a:`${a}.rb`}}let s=F(n,`lib/${i}.rb`)??F(n,`lib/${i}`)??F(n,`${i}.rb`);return s?{kind:"local",resolvedPaths:[s]}:{kind:"external",resolvedPaths:[],externalLabel:i}},formatImportStatement(e,t){let n=e?_.posix.dirname(C(e)):".",i=_.posix.relative(n,C(t.file)).replace(/\.rb$/i,"");return`require_relative '${i.startsWith(".")?i:`./${i}`}' # ${t.name}`}},Sn={id:"cpp",extensions:[".c",".cc",".cpp",".cxx",".h",".hh",".hpp",".hxx"],extractManifest(e,t,n,i,r){let s=C(n),o=oe(e),a=[],l=new Map,f=[],m=[],c=/^\s*#include\s*(?:"([^"]+)"|<([^>]+)>)/gm,A;for(;(A=c.exec(e))!==null;)A[1]?V(a,l,`"${A[1]}"`,[],!1):A[2]&&V(a,l,`<${A[2]}>`,[],!1);let y=/^\s*(?:typedef\s+)?(struct|class|enum(?:\s+class)?)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm,b;for(;(b=y.exec(e))!==null;){let d=b[1],g=b[2];f.push({name:g,kind:d.startsWith("enum")?"enum":"class",signature:`${d} ${g}`,line:K(e,b.index),file:s,isExported:!0})}let v=/^(static\s+)?(?:inline\s+|constexpr\s+|extern\s+)?([a-zA-Z_][a-zA-Z0-9_:*&<> ]*?)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?:const\s*)?(?:noexcept\s*)?\{/gm,u;for(;(u=v.exec(e))!==null;){let d=!!u[1],g=j(u[2]??""),S=u[3];if(["if","for","while","switch","catch","namespace"].includes(S))continue;let h=j(u[4]??""),x=u.index+u[0].length-1,$=pe(e,x,!1),k=$>x?e.slice(x+1,$):"",w=me(h).map(T=>{let O=j(T).split(" ");return O.length>=2?`${O[O.length-1].replace(/^[*&]+/,"")}: ${O.slice(0,-1).join(" ")}`:T}).join(", "),{structuralHash:R,nodeCount:P,astNodeCount:E}=ne(k,w),I=X(`(${w})${g?`: ${g}`:""}`),M=K(e,u.index);d?m.push({name:S,kind:"function",signature:I,line:M,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!1}):f.push({name:S,kind:"function",signature:I,line:M,structuralHash:R,nodeCount:P,astNodeCount:E,file:s,isExported:!0})}return{relativePath:s,contentSha256:o,language:"cpp",...i!==void 0?{mtimeMs:i}:{},...r!==void 0?{size:r}:{},imports:a,exportedSymbols:f,internalFunctions:m}},resolveImport(e,t,n){let i=e.rawSpecifier.trim(),r=_.posix.dirname(C(t)),s=i.startsWith('"')&&i.endsWith('"'),o=i.replace(/^["<]|[">]$/g,"");if(s){let l=_.posix.normalize(_.posix.join(r,o)),f=F(n,l)??F(n,`include/${o}`)??F(n,`src/${o}`)??F(n,o);return f?{kind:"local",resolvedPaths:[f]}:{kind:"unresolved",resolvedPaths:[],unresolvedAttempt:l}}let a=F(n,`include/${o}`);return a?{kind:"local",resolvedPaths:[a]}:{kind:"external",resolvedPaths:[],externalLabel:o}},formatImportStatement(e,t){let n=C(t.file);return e?`#include "${_.posix.relative(_.posix.dirname(C(e)),n)}" // ${t.name}`:`#include "${n}" // ${t.name}`}},Ce=class{byExtension=new Map;byId=new Map;constructor(t){for(let n of t)this.register(n)}register(t){this.byId.set(t.id,t);for(let n of t.extensions)this.byExtension.set(n.toLowerCase(),t)}get supportedExtensions(){return[...this.byExtension.keys()]}detectLanguage(t){let n=_.extname(t).toLowerCase();return this.byExtension.get(n)?.id??"unknown"}getAdapterForFile(t){let n=_.extname(t).toLowerCase();return this.byExtension.get(n)}getAdapterById(t){return this.byId.get(t)}extractManifest(t,n,i,r,s){let o=this.getAdapterForFile(n)??this.getAdapterForFile(i);return o?o.extractManifest(t,n,i,r,s):Le(t,n,i,r,s)}formatImportForSymbol(t,n,i){let r=this.getAdapterForFile(n.file);return r?r.formatImportStatement(t,n,i):lt(t,n)}areLanguagesCompatible(t,n){let i=this.detectLanguage(t),r=this.detectLanguage(n);if(i===r)return!0;let s=new Set(["typescript","javascript"]);if(s.has(i)&&s.has(r))return!0;let o=new Set(["java","kotlin"]);return!!(o.has(i)&&o.has(r))}},se=new Ce([ot("typescript",[".ts",".tsx",".mts",".cts"]),ot("javascript",[".js",".jsx",".mjs",".cjs"]),sn,cn,pn,mn,hn,gn,xn,yn,Sn]);function Re(e){try{return Ut(e)?qt(e,"utf8"):null}catch{return null}}function je(e,t,n,i=[]){let r=new Map,s=[...new Set(n.map(C))].sort(W);for(let v of s)r.set(v,v),r.set(v.toLowerCase(),v);let o=new Map,a=new Set([""]),l=[],f=[],m=new Map,c=new Map,A=new Map;s.some(v=>v.startsWith("src/"))&&a.add("src");let y=v=>{let u=C(v),d=_.posix.basename(u).toLowerCase(),g=_.posix.dirname(u),S=g==="."?"":g,h=Re(_.join(t,u));if(h){if(d==="go.mod"){let x=/^\s*module\s+([^\s/]+(?:\/[^\s/]+)*)/m.exec(h);x&&x[1]&&o.set(S,x[1].trim().replace(/^"|"$/g,""))}else if(d==="cargo.toml"){let x=/\[package\]([\s\S]*?)(?:\n\[|$)/.exec(h)?.[1]??h,$=/^\s*name\s*=\s*["']([^"']+)["']/m.exec(x),k=S?`${S}/src`:"src",w=s.some(R=>R.startsWith(`${k}/`));l.push({crateDir:S,srcDir:w?k:S,...$?.[1]?{crateName:$[1]}:{}})}else if(d==="pyproject.toml"){S&&a.add(S);let x=S?`${S}/src`:"src";s.some(w=>w.startsWith(`${x}/`))&&a.add(x);let $=/where\s*=\s*\[([^\]]+)\]/.exec(h);if($&&$[1]){let w=/["']([^"']+)["']/g,R;for(;(R=w.exec($[1]))!==null;)if(R[1]){let P=C(S?`${S}/${R[1]}`:R[1]);a.add(P==="."?"":P)}}let k=/package-dir\s*=\s*\{[^}]*["']\s*["']\s*[:=]\s*["']([^"']+)["']/.exec(h);if(k&&k[1]){let w=C(S?`${S}/${k[1]}`:k[1]);a.add(w==="."?"":w)}}else if(d==="composer.json")try{let x=JSON.parse(h),$=[x.autoload?.["psr-4"],x["autoload-dev"]?.["psr-4"]];for(let k of $)if(!(!k||typeof k!="object"))for(let[w,R]of Object.entries(k)){let P=Array.isArray(R)?R:[R];for(let E of P){if(typeof E!="string")continue;let I=C(S?`${S}/${E}`:E).replace(/\/$/,"");f.push({prefix:w,dir:I})}}}catch{}}};for(let v of i)y(v);for(let v of["go.mod","Cargo.toml","pyproject.toml","composer.json"])i.includes(v)||y(v);for(let v of s){let u=_.posix.extname(v).toLowerCase();if(u===".java"||u===".kt"||u===".kts"){let d=Re(_.join(t,v));if(d){let g=/^\s*package\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*;?/m.exec(d);g&&g[1]&&m.set(v,g[1])}}else if(u===".cs"){let d=Re(_.join(t,v));if(d){let g=[],S=/^\s*namespace\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*[;{]/gm,h;for(;(h=S.exec(d))!==null;)h[1]&&g.push(h[1]);g.length>0&&c.set(v,g)}}else if(u===".php"){let d=Re(_.join(t,v));if(d){let g=/^\s*namespace\s+([a-zA-Z_\\][a-zA-Z0-9_\\]*)\s*[;{]/m.exec(d);g&&g[1]&&A.set(v,g[1].replace(/^\\/,""))}}}let b=o.get("")??[...o.values()][0];return{root:D(e),rootReal:D(t),knownFiles:r,allRelativePaths:s,...b?{goModulePath:b}:{},goModuleDirs:o,pythonSourceRoots:[...a],rustCrates:l,phpPsr4Mappings:f,javaPackagesByFile:m,csharpNamespacesByFile:c,phpNamespacesByFile:A}}var ke=new Set(se.supportedExtensions),ht=new Set([".css",".scss",".less",".svg",".png",".jpg",".jpeg",".webp",".gif",".ico",".woff",".woff2",".ttf",".wasm",".json",".glsl",".sql",".txt",".md"]);function ie(e){let t=e.trim(),n=t.indexOf("?"),i=t.indexOf("#"),r=t.length;return n!==-1&&n<r&&(r=n),i!==-1&&i<r&&(r=i),t.slice(0,r)}function Pe(e){let t=ie(e);return t==="."||t===".."||t.startsWith("./")||t.startsWith("../")}function xe(e){let t=ie(e),n=L.posix.extname(t).toLowerCase();return n.length>0&&ht.has(n)&&!ke.has(n)}var wn=/(^|\/)(__fixtures__|__snapshots__|__mocks__)(\/|$)/i,Rn=/\.(snap|fixture)\.[cm]?[jt]sx?$/i,dt=/(^|\/)(generated|__generated__)(\/|$)/i,pt=/\.(gen|generated)(\.[cm]?[jt]sx?)?$/i;function ze(e){let t=C(e);return wn.test(t)||Rn.test(t)}function He(e,t){let n=ie(e).replace(/\\/g,"/");if(dt.test(n)||pt.test(n))return!0;if(t){let i=C(ie(t));if(dt.test(i)||pt.test(i))return!0}return!1}var le=new Set(["node_modules",".git",".hg",".svn","dist","out","coverage",".next",".nuxt",".turbo",".vercel",".output",".cache",".tipolink",".interlink",".chuze",".moriko","__pycache__",".venv","venv",".pytest_cache",".mypy_cache",".ruff_cache","target",".gradle",".tox"]),Cn=/(^|\/)(android\/(?:app\/)?build|ios\/build)$/i;function Pn(e){let t=e.toLowerCase();return t.endsWith(".d.ts")||t.endsWith(".d.mts")||t.endsWith(".d.cts")?!1:t.endsWith(".ts")||t.endsWith(".tsx")||t.endsWith(".mts")||t.endsWith(".cts")}function En(e){let i=[{dir:e,depth:0}],r=0,s=0;for(;r<i.length&&s<500;){let o=i[r];if(r+=1,!o)continue;let a;try{a=mt(o.dir,{withFileTypes:!0})}catch{continue}for(let l of a){if(s+=1,s>500)return!1;if(l.isFile()){if(Pn(l.name))return!0}else if(l.isDirectory()&&o.depth<5){let f=l.name.toLowerCase();!le.has(l.name)&&!le.has(f)&&!f.startsWith("cmake-build-")&&i.push({dir:L.join(o.dir,l.name),depth:o.depth+1})}}}return!1}function be(e,t,n){let i=e.toLowerCase();if(le.has(e)||le.has(i)||i.startsWith("cmake-build-"))return!0;if(i==="build"||i==="vendor"){let r=C(n).toLowerCase();return Cn.test(r)?!0:r.split("/").filter(Boolean).slice(0,-1).includes("src")?!1:!En(t)}return!1}var gt=new Set(An),xt={".js":[".ts",".tsx",".js",".jsx"],".jsx":[".tsx",".jsx",".ts",".js"],".mjs":[".mts",".mjs"],".cjs":[".cts",".cjs"]},yt=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs","/index.ts","/index.tsx","/index.mts","/index.cts","/index.js","/index.jsx","/index.mjs","/index.cjs"],In=/^tsconfig(\..+)?\.json$/i,_n=new Set(["go.mod","cargo.toml","pyproject.toml","composer.json"]),Mn=18003;function Ke(e){return e instanceof Error?e.message:String(e)}function St(e){if(e instanceof Error&&"code"in e&&typeof e.code=="string")return e.code}function Ve(e){try{return $n(e)}catch(t){let n=St(t);if(n==="ENOENT"||n==="ENOTDIR")return null;throw t}}function Se(e){let t=Ve(e);return t!==null&&t.isFile()}function Ze(e){let t=L.resolve(e);return process.platform==="win32"?t.toLowerCase():t}function Nn(e,t){let n=L.relative(e,t);return n!==""&&!n.startsWith("..")&&!L.isAbsolute(n)}function vt(e,t){let n=[],i=[],r=[],s=[e];for(;s.length>0;){let o=s.pop();if(o===void 0)break;let a;try{a=mt(o,{withFileTypes:!0})}catch(f){t.push(`Directory "${B(e,o)}" could not be read: ${Ke(f)}`);continue}a.sort((f,m)=>W(f.name,m.name));let l=[];for(let f of a){let m=L.join(o,f.name);if(f.isDirectory()){let c=B(e,m);be(f.name,m,c)||l.push(m)}else if(f.isFile()){let c=f.name.toLowerCase();ke.has(L.extname(f.name).toLowerCase())?n.push(m):In.test(f.name)?i.push(m):_n.has(c)&&r.push(m)}}for(let f=l.length-1;f>=0;f-=1){let m=l[f];m!==void 0&&s.push(m)}}return n.sort(W),i.sort(W),r.sort(W),{sources:n,tsconfigs:i,polyglotConfigs:r}}function kt(e,t,n){let i=B(e,t),r=ae.readConfigFile(t,ae.sys.readFile);if(r.error)return n.push(`tsconfig "${i}" could not be parsed: ${ae.flattenDiagnosticMessageText(r.error.messageText," ")}`),null;let s={useCaseSensitiveFileNames:ae.sys.useCaseSensitiveFileNames,readDirectory:()=>[],fileExists:ae.sys.fileExists,readFile:ae.sys.readFile},o=L.dirname(t);try{o=ge.native(o)}catch{}let a=ae.parseJsonConfigFileContent(r.config,s,o,void 0,t);for(let c of a.errors)c.code!==Mn&&n.push(`tsconfig "${i}": ${ae.flattenDiagnosticMessageText(c.messageText," ")}`);let l=a.options.paths;if(!l)return null;let f=a.options.baseUrl?L.resolve(o,a.options.baseUrl):o,m=[];for(let[c,A]of Object.entries(l)){let y=c.indexOf("*");m.push({prefix:y===-1?c:c.slice(0,y),suffix:y===-1?"":c.slice(y+1),wildcard:y!==-1,targets:A.map(b=>L.resolve(f,b))})}return m.length>0?{dir:o,rules:m}:null}function Be(e){let t=L.extname(e).toLowerCase(),n=xt[t];if(n){let i=e.slice(0,e.length-t.length);for(let r of n)if(Se(`${i}${r}`))return`${i}${r}`}if(Se(e))return e;for(let i of yt)if(Se(`${e}${i}`))return`${e}${i}`;return null}function bt(e,t,n){let i=n.aliasConfigs.filter(r=>Nn(r.dir,t)).sort((r,s)=>s.dir.length-r.dir.length);for(let r of i)for(let s of r.rules){let o;if(s.wildcard){if(!e.startsWith(s.prefix)||!e.endsWith(s.suffix)||e.length<s.prefix.length+s.suffix.length)continue;o=e.slice(s.prefix.length,e.length-s.suffix.length)}else{if(e!==s.prefix)continue;o=""}for(let a of s.targets){let l=Be(a.replace("*",o));if(l)return l}}return null}function ve(e,t){let n=t?.isTypeOnly===!0,i=t?.isDynamic===!0,r=!n&&!i&&t?.verifiedAssetOnDisk!==!0&&e.length>0;return{...n?{isTypeOnly:!0}:{},...i?{isDynamic:!0}:{},hasStaticValueImport:r,...t?.line!==void 0?{line:t.line}:{},...t?.verifiedAssetOnDisk!==void 0?{verifiedAssetOnDisk:t.verifiedAssetOnDisk}:{}}}function We(e,t,n,i,r){let s;try{s=ge.native(e)}catch{s=L.resolve(e)}let o=B(t.rootReal,s);return{key:`local:${o}`,kind:"local",label:o,importedNames:[...n],isReExport:i,...ve(n,r)}}function Dn(e,t,n,i,r){let s=B(t.root,L.resolve(e));return{key:`unresolved:${s}`,kind:"unresolved",label:`${s} (unresolved)`,importedNames:[...n],isReExport:i,...ve(n,r)}}function fe(e,t,n,i){return{key:`pkg:${e}`,kind:"external",label:e,importedNames:[...t],isReExport:n,...ve(t,i)}}function $t(e,t,n,i=[],r=!1,s){let o=ie(e);if(o==="."||o===".."||o.startsWith("./")||o.startsWith("../")){let l=L.resolve(L.dirname(t),o),f=Be(l),c=xe(o)?!!f:s?.verifiedAssetOnDisk,A={...s,...c!==void 0?{verifiedAssetOnDisk:c}:{}};if(f)return We(f,n,i,r,A);let y=B(n.rootReal,t),b=B(n.root,L.resolve(l));return ze(y)||He(e,b)?fe(o,i,r,A):Dn(l,n,i,r,A)}if(o.startsWith("node:"))return fe(o,i,r,s);if(gt.has(o))return fe(`node:${o}`,i,r,s);if(L.isAbsolute(o)){let l=Be(o);if(l)return We(l,n,i,r,s)}let a=bt(o,t,n);if(a){let l=xe(a);return We(a,n,i,r,{...s,...l?{verifiedAssetOnDisk:!0}:{}})}return fe(o,i,r,s)}function he(e,t){let n=t.hasStaticValueImport??(t.isTypeOnly!==!0&&t.isDynamic!==!0&&t.verifiedAssetOnDisk!==!0&&t.importedNames.length>0),i=e.get(t.key);if(!i){e.set(t.key,{...t,importedNames:[...t.importedNames],hasStaticValueImport:n});return}for(let s of t.importedNames)i.importedNames.includes(s)||i.importedNames.push(s);t.isReExport&&(i.isReExport=!0);let r=i.hasStaticValueImport??(i.isTypeOnly!==!0&&i.isDynamic!==!0&&i.verifiedAssetOnDisk!==!0&&i.importedNames.length>0);i.hasStaticValueImport=r||n,i.isTypeOnly=!!i.isTypeOnly&&!!t.isTypeOnly,i.isDynamic=!!i.isDynamic&&!!t.isDynamic,t.line!==void 0&&(n&&!r||i.line===void 0?i.line=t.line:n===r&&(i.line=Math.min(i.line,t.line))),t.verifiedAssetOnDisk===!0?i.verifiedAssetOnDisk=!0:t.verifiedAssetOnDisk===!1&&i.verifiedAssetOnDisk===void 0&&(i.verifiedAssetOnDisk=!1)}function Tn(e,t,n){let i=e.inbound.get(n);i||(i=new Set,e.inbound.set(n,i)),i.add(t);let r=e.importedBy.get(n);r||(r=new Set,e.importedBy.set(n,r)),r.add(t)}function On(e,t,n){e.files.push(t),e.byId.set(t.id,t),n&&n!==t.id&&e.byId.set(n,t),e.byRelative.set(t.relative,t),e.outbound.set(t.relative,t.modules);for(let i of t.modules.values())i.kind==="local"&&Tn(e,t.relative,i.label)}function Fn(e,t,n,i,r){let s=se.getAdapterById(n),o=i.resolutionContext,a={isTypeOnly:e.isTypeOnly,isDynamic:e.isDynamic,...e.line!==void 0?{line:e.line}:{},verifiedAssetOnDisk:e.verifiedAssetOnDisk};if(!s||!o){let m=fe(e.rawSpecifier,e.importedNames,e.isReExport,a);return he(r,{...m,rawSpecifier:e.rawSpecifier}),{...e,resolvedKind:"external",resolvedPaths:[]}}let l=s.resolveImport(e,t,o);if(l.kind==="local"&&l.resolvedPaths.length>0){for(let m of l.resolvedPaths)he(r,{key:`local:${m}`,kind:"local",label:m,importedNames:[...e.importedNames],isReExport:e.isReExport,...ve(e.importedNames,a),rawSpecifier:e.rawSpecifier});return{...e,resolvedKind:"local",resolvedPaths:[...l.resolvedPaths]}}if(l.kind==="unresolved"){let m=C(l.unresolvedAttempt??e.rawSpecifier);return ze(t)||He(e.rawSpecifier,m)?(he(r,{...fe(e.rawSpecifier,e.importedNames,e.isReExport,a),rawSpecifier:e.rawSpecifier}),{...e,resolvedKind:"external",resolvedPaths:[]}):(he(r,{key:`unresolved:${m}`,kind:"unresolved",label:`${m} (unresolved)`,importedNames:[...e.importedNames],isReExport:e.isReExport,...ve(e.importedNames,a),rawSpecifier:e.rawSpecifier}),{...e,resolvedKind:"unresolved",resolvedPaths:m?[m]:[]})}let f=l.externalLabel??e.rawSpecifier;return he(r,{...fe(f,e.importedNames,e.isReExport,a),rawSpecifier:e.rawSpecifier}),{...e,resolvedKind:"external",resolvedPaths:[]}}function At(e,t,n){let i;try{i=ge.native(e)}catch{i=L.resolve(e)}let r=B(t.rootReal,i),s=Ve(e),o=n?.cache,a;if(o&&s&&(a=o.get(t.workspaceId,r,void 0,s.mtimeMs,s.size)),!a){let y=bn(e,"utf8");if(o){let b=kn("sha256").update(y,"utf8").digest("hex"),v=o.get(t.workspaceId,r,b);v?(a={...v,relativePath:r,...s?{mtimeMs:s.mtimeMs,size:s.size}:{}},o.set(t.workspaceId,a)):(a=se.extractManifest(y,i,r,s?.mtimeMs,s?.size),o.set(t.workspaceId,a))}else a=se.extractManifest(y,i,r,s?.mtimeMs,s?.size)}let l=a.language??se.detectLanguage(i),f=l==="typescript"||l==="javascript"||l==="unknown",m=new Map,c=[];for(let y of a.imports)if(f){let b=ie(y.rawSpecifier),v=y.verifiedAssetOnDisk;Pe(b)&&xe(b)&&(v=Se(L.resolve(L.dirname(i),b)));let u=$t(y.rawSpecifier,i,t,y.importedNames,y.isReExport,{isTypeOnly:y.isTypeOnly,isDynamic:y.isDynamic,...y.line!==void 0?{line:y.line}:{},verifiedAssetOnDisk:v});he(m,{...u,rawSpecifier:y.rawSpecifier});let d=u.kind==="local"?[u.label]:u.kind==="unresolved"?[u.label.replace(/ \(unresolved\)$/,"")]:[],g=u.verifiedAssetOnDisk!==void 0?u.verifiedAssetOnDisk:v;c.push({...y,...g!==void 0?{verifiedAssetOnDisk:g}:{},resolvedKind:u.kind,resolvedPaths:d})}else c.push(Fn(y,r,l,t,m));let A={...a,relativePath:r,language:l,imports:c};return{absolute:i,id:Ze(i),relative:r,contentSha256:A.contentSha256,language:l,modules:m,exportedSymbols:A.exportedSymbols.map(y=>({...y,file:r})),internalFunctions:A.internalFunctions.map(y=>({...y,file:r})),manifest:A}}function Ue(e,t){let n=[],i;try{i=ge.native(e)}catch{i=L.resolve(e)}let r=t?.workspaceId??D(i),{sources:s,tsconfigs:o,polyglotConfigs:a}=vt(e,n),l=[];for(let y of o){let b=kt(e,y,n);b&&l.push(b)}let f=s.map(y=>{try{return B(i,ge.native(y))}catch{return B(i,L.resolve(y))}}),m=a.map(y=>{try{return B(i,ge.native(y))}catch{return B(i,L.resolve(y))}}),c=je(e,i,f,m),A={workspaceId:r,root:e,rootReal:i,files:[],byId:new Map,byRelative:new Map,outbound:new Map,inbound:new Map,importedBy:new Map,aliasConfigs:l,resolutionContext:c,notes:n};for(let y of s)try{let b=At(y,A,t);On(A,b,Ze(y))}catch(b){n.push(`"${B(e,y)}" could not be analysed: ${Ke(b)}`)}return A.files.sort((y,b)=>W(y.relative,b.relative)),A}function Je(e){return Ln("sha256").update(e,"utf8").digest("hex")}function Ms(e){let t=e.imports.map(s=>{let o=s.verifiedAssetOnDisk===!0?"1":s.verifiedAssetOnDisk===!1?"0":"-",a=s.isDynamic===!0?"D":"S",l=s.isTypeOnly?"T":"V";return`${s.rawSpecifier}:${l}${a}${o}:${s.line??0}:${s.importedNames.length}`}).join("|"),n=e.exportedSymbols.map(s=>`${s.name}:${s.line}:${s.endLine??0}:${s.structuralHash??""}`).join(","),i=e.internalFunctions.map(s=>`${s.name}:${s.line}:${s.endLine??0}:${s.structuralHash}`).join(","),r=e.schemaVersion??q;return Je(`${r}\0${e.contentSha256}\0${t}\0${n}\0${i}`)}function Ee(e,t){let n=N.dirname(t),i=!1,r=e.imports.map(s=>{let o=ie(s.rawSpecifier);if(!Pe(o)||!xe(o))return s;let a=N.resolve(n,o),l=J(a);return s.verifiedAssetOnDisk!==l&&(i=!0),{...s,verifiedAssetOnDisk:l}});return i?{manifest:{...e,imports:r},changed:!0}:{manifest:e,changed:!1}}function jn(e,t){let n=N.join(N.dirname(e),"cloud-sync.json");if(J(n))try{let i=JSON.parse(Pt(n,"utf8"));if(!i||typeof i!="object")return;if(i.manifestSchemaVersion!==q){wt(n,JSON.stringify({version:1,manifestSchemaVersion:q,workspaces:{}},null,2),"utf8");return}if(i.workspaces&&typeof i.workspaces=="object"){let r=!1;for(let s of Object.keys(i.workspaces))(s===t||s.endsWith(`::${t}`))&&(delete i.workspaces[s],r=!0);r&&wt(n,JSON.stringify(i,null,2),"utf8")}}catch{}}function qe(e){return D(e).replace(/^\.\//,"").split("/").some(n=>{if(n.length===0)return!1;let i=n.toLowerCase();return le.has(n)||le.has(i)||i.startsWith("cmake-build-")})}function Wn(e){let t=_e.native(N.resolve(e));return`ws_${Je(t).slice(0,16)}`}function $e(e){let t=N.resolve(e);try{return _e.native(t)}catch{return t}}function Z(e){let t=$e(e);return process.platform==="win32"?t.toLowerCase():t}function _t(e,t){let n=$e(e),i=$e(t),r=N.relative(n,i);return r===""||!r.startsWith("..")&&!N.isAbsolute(r)}function Bn(e,t){return J(N.join(e,".git"))||J(N.join(e,"pnpm-workspace.yaml"))||J(N.join(e,".tipolink","cloud-sync.json"))||t&&J(N.join(e,".tipolink","cache.json"))||J(N.join(e,"tsconfig.base.json"))}function zn(e){let t=N.resolve(e);try{J(t)&&It(t).isFile()&&(t=N.dirname(t))}catch{}let n=Z(t),i=Z(Rt.tmpdir()),r=Z(Rt.homedir()),s=Z(N.parse(t).root),o=process.env.TIPOLINK_WORKSPACE_ROOT?.trim(),a=o&&o.length>0&&_t(N.resolve(o),t)?N.resolve(o):null,l=a?Z(a):null,f=null,m=t;for(;;){let v=Z(m);if(v!==n&&(v===s||v===i||v===r))break;if(l!==null&&v===l){f=a;break}Bn(m,v!==n)&&(f=m);let u=N.dirname(m);if(u===m)break;m=u}let c=f??t,A=$e(c),y=$e(t),b=D(N.relative(A,y)).replace(/^\/+|\/+$/g,"");return!b||b==="."||b.startsWith("..")?{canonicalRoot:c,subScopePrefix:null}:{canonicalRoot:c,subScopePrefix:`${b}/`}}function Mt(e,t){return!(Z(N.dirname(e))===Z(t)||J(N.join(e,"server.env"))||J(N.join(e,"tipolink.sqlite"))||J(N.join(e,"data","tipolink.sqlite"))||J(N.join(e,"data",".tipolink-auth.key")))}function Hn(e,t){let n=N.resolve(e),i=[],r=o=>{if(J(o)&&Mt(o,n))try{Et(o,{recursive:!0,force:!0}),i.push(D(N.relative(n,o)))}catch{}};if(t){let o=N.resolve(t);_t(n,o)&&Z(o)!==Z(n)&&r(N.join(o,".tipolink"))}let s=[n];for(;s.length>0;){let o=s.pop();if(o===void 0)break;let a;try{a=Ct(o,{withFileTypes:!0})}catch{continue}for(let l of a){if(!l.isDirectory())continue;let f=N.join(o,l.name);if(l.name===".tipolink"){Z(o)!==Z(n)&&r(f);continue}let m=D(N.relative(n,f));be(l.name,f,m)||s.push(f)}}return i}function Ie(e){return{relativePath:D(e.relativePath),contentSha256:e.contentSha256,schemaVersion:e.schemaVersion??q,...e.language!==void 0?{language:e.language}:{},...e.mtimeMs!==void 0?{mtimeMs:e.mtimeMs}:{},...e.size!==void 0?{size:e.size}:{},imports:e.imports.map(t=>({rawSpecifier:t.rawSpecifier,importedNames:[...t.importedNames],isReExport:t.isReExport,isTypeOnly:t.isTypeOnly,...t.isDynamic===!0?{isDynamic:!0}:{},...typeof t.line=="number"&&Number.isFinite(t.line)?{line:t.line}:{},...typeof t.verifiedAssetOnDisk=="boolean"?{verifiedAssetOnDisk:t.verifiedAssetOnDisk}:{},...Array.isArray(t.resolvedPaths)?{resolvedPaths:t.resolvedPaths.map(n=>D(n))}:{},...t.resolvedKind!==void 0?{resolvedKind:t.resolvedKind}:{}})),exportedSymbols:e.exportedSymbols.map(t=>({name:t.name,...t.localName!==void 0?{localName:t.localName}:{},kind:t.kind,signature:t.signature,line:t.line,...t.endLine!==void 0?{endLine:t.endLine}:{},...t.structuralHash!==void 0?{structuralHash:t.structuralHash}:{},...t.nodeCount!==void 0?{nodeCount:t.nodeCount}:{},...t.astNodeCount!==void 0?{astNodeCount:t.astNodeCount}:{},...t.statementCount!==void 0?{statementCount:t.statementCount}:{},file:D(t.file),isExported:!0,...t.isReExport!==void 0?{isReExport:t.isReExport}:{}})),internalFunctions:e.internalFunctions.map(t=>({name:t.name,kind:"function",signature:t.signature,line:t.line,...t.endLine!==void 0?{endLine:t.endLine}:{},structuralHash:t.structuralHash,nodeCount:t.nodeCount,...t.astNodeCount!==void 0?{astNodeCount:t.astNodeCount}:{},...t.statementCount!==void 0?{statementCount:t.statementCount}:{},file:D(t.file),isExported:!1}))}}function Kn(e,t=!0){let n=[],i=[e],r=Z(e);for(;i.length>0;){let s=i.pop();if(s===void 0)break;let o;try{o=Ct(s,{withFileTypes:!0})}catch{continue}o.sort((l,f)=>l.name<f.name?-1:l.name>f.name?1:0);let a=[];for(let l of o){let f=N.join(s,l.name);if(l.isDirectory()){if(t&&l.name===".tipolink"&&Z(s)!==r&&Mt(f,e)){try{Et(f,{recursive:!0,force:!0})}catch{}continue}let m=D(N.relative(e,f));be(l.name,f,m)||a.push(f)}else l.isFile()&&ke.has(N.extname(l.name).toLowerCase())&&n.push(f)}for(let l=a.length-1;l>=0;l-=1){let f=a[l];f!==void 0&&i.push(f)}}return n.sort((s,o)=>s<o?-1:s>o?1:0),n}function Ns(e,t={}){let n=N.resolve(e),i=t.disableRootHoisting===!0||t.cachePath!==void 0?{canonicalRoot:n,subScopePrefix:null}:zn(n),r=i.canonicalRoot,s=i.subScopePrefix,o=t.writeCache??!0;o&&s!==null&&Hn(r,n);let a=_e.native(r),l=t.workspaceId??Wn(a),f=t.cachePath??N.join(r,".tipolink","cache.json"),m=new ye({filePath:f,autoSave:!1}),c=m.schemaInvalidated,A=m.getAllWorkspaceManifests(l),y=new Set,b=!1;for(let P of A){let E=D(P.relativePath);qe(E)&&(b=!0),y.add(E)}let v=Kn(r,o),u=new Set,d=[],g=new Set,S=0,h=0,x=c;for(let P of v){let E;try{E=_e.native(P)}catch{E=P}let I=D(N.relative(a,E));if(qe(I))continue;u.add(I);let M;try{M=It(E)}catch{continue}if(!M.isFile())continue;let T=m.get(l,I,void 0,M.mtimeMs,M.size);if(T&&T.schemaVersion===q){S+=1;let G=Ee(Ie(T),E);G.changed&&(m.set(l,G.manifest),x=!0,g.add(I)),d.push(G.manifest);continue}let O=Pt(E,"utf8"),U=Je(O),ee=m.get(l,I,U);if(ee&&ee.schemaVersion===q){S+=1;let G=Ee(Ie({...ee,mtimeMs:M.mtimeMs,size:M.size}),E);m.set(l,G.manifest),x=!0,G.changed&&g.add(I),d.push(G.manifest);continue}let Q=Ee(Ie(se.extractManifest(O,E,I,M.mtimeMs,M.size)),E).manifest;h+=1,m.set(l,Q),x=!0,d.push(Q),g.add(I)}let $=[];for(let P of y)u.has(P)||$.push(P);if($.length>0||b){m.clear(l);for(let P of d)m.set(l,P);x=!0}o&&x&&(m.flush(),c&&jn(f,l));let k=Ue(r,{workspaceId:l,cache:m}),w=[],R=[];for(let P of k.files){if(qe(P.relative))continue;let E=Ee(Ie(P.manifest),P.absolute).manifest;w.push(E),g.has(P.relative)&&R.push(E)}return{workspaceId:l,rootDir:r,subScopePrefix:s,cachePath:f,schemaVersion:q,schemaInvalidated:c,allManifests:w,manifestDelta:R,removedPaths:$,cacheHits:S,parsedCount:h,index:k}}export{q as CACHE_SCHEMA_VERSION,Hn as cleanupNestedTipolinkDirs,Ms as computeManifestSyncHash,Wn as deriveWorkspaceId,zn as hoistToCanonicalWorkspaceRoot,Ie as sanitizeManifest,Ns as scanWorkspaceManifests};
|