@tipolink/mcp 1.0.2 → 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/dist/extractor.js CHANGED
@@ -1,4022 +1,8 @@
1
- // src/extractor.ts
2
- import { createHash as createHash4 } from "node:crypto";
3
- import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, realpathSync as realpathSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
4
- import path6 from "node:path";
5
-
6
- // ../engine/src/ast-extractor.ts
7
- import { createHash } from "node:crypto";
8
- import path3 from "node:path";
9
- import ts from "typescript";
10
-
11
- // ../engine/src/cache.ts
12
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13
- import path2 from "node:path";
14
-
15
- // ../engine/src/paths.ts
16
- import path from "node:path";
17
- function compareText(a, b) {
18
- if (a < b) return -1;
19
- if (a > b) return 1;
20
- return 0;
21
- }
22
- function toPosix(value) {
23
- return value.replace(/\\/g, "/");
24
- }
25
- function normalizeRelPath(relPath) {
26
- const posix = path.posix.normalize(toPosix(relPath.trim()));
27
- return posix.replace(/^\.\//, "");
28
- }
29
- function displayPath(root, absolute) {
30
- const trimmed = absolute.trim();
31
- if (!trimmed) return trimmed;
32
- const resolved = path.isAbsolute(trimmed) ? path.resolve(trimmed) : path.resolve(root, trimmed);
33
- const rel = path.relative(root, resolved);
34
- if (!rel) return ".";
35
- if (rel.startsWith("..") || path.isAbsolute(rel)) return toPosix(trimmed);
36
- return toPosix(rel);
37
- }
38
- function computeRelativeImportSpec(fromRelPath, toRelPath) {
39
- const fromDir = path.posix.dirname(normalizeRelPath(fromRelPath));
40
- const target = normalizeRelPath(toRelPath);
41
- let rel = path.posix.relative(fromDir, target);
42
- if (!rel.startsWith("./") && !rel.startsWith("../")) {
43
- rel = `./${rel}`;
44
- }
45
- const ext = path.posix.extname(rel).toLowerCase();
46
- const stem = rel.slice(0, rel.length - ext.length);
47
- if (ext === ".ts" || ext === ".tsx") return `${stem}.js`;
48
- if (ext === ".mts") return `${stem}.mjs`;
49
- if (ext === ".cts") return `${stem}.cjs`;
50
- return rel;
51
- }
52
-
53
- // ../engine/src/cache.ts
54
- var CACHE_SCHEMA_VERSION = "1.0.2";
55
- function cacheEntryMatches(entry, contentSha256, mtimeMs, size) {
56
- if (contentSha256 !== void 0) {
57
- return entry.contentSha256 === contentSha256;
58
- }
59
- if (mtimeMs !== void 0 || size !== void 0) {
60
- if (mtimeMs !== void 0 && entry.mtimeMs !== mtimeMs) return false;
61
- if (size !== void 0 && entry.size !== size) return false;
62
- return true;
63
- }
64
- return true;
65
- }
66
- var JsonFileAstCache = class {
67
- filePath;
68
- schemaInvalidated = false;
69
- autoSave;
70
- workspaces = /* @__PURE__ */ new Map();
71
- dirty = false;
72
- constructor(filePathOrOptions) {
73
- if (typeof filePathOrOptions === "string") {
74
- this.filePath = filePathOrOptions;
75
- this.autoSave = true;
76
- } else {
77
- this.filePath = filePathOrOptions.filePath;
78
- this.autoSave = filePathOrOptions.autoSave ?? true;
79
- }
80
- this.loadFromDisk();
81
- }
82
- loadFromDisk() {
83
- if (!existsSync(this.filePath)) return;
84
- try {
85
- const raw = readFileSync(this.filePath, "utf8");
86
- if (!raw.trim()) return;
87
- const parsed = JSON.parse(raw);
88
- if (!parsed || typeof parsed !== "object" || !parsed.workspaces || typeof parsed.workspaces !== "object") {
89
- this.schemaInvalidated = true;
90
- this.dirty = true;
91
- return;
92
- }
93
- if (parsed.manifestSchemaVersion !== CACHE_SCHEMA_VERSION) {
94
- this.workspaces.clear();
95
- this.schemaInvalidated = true;
96
- this.dirty = true;
97
- return;
98
- }
99
- for (const [workspaceId, files] of Object.entries(parsed.workspaces)) {
100
- if (!files || typeof files !== "object") continue;
101
- const map = /* @__PURE__ */ new Map();
102
- for (const [relPath, manifest] of Object.entries(files)) {
103
- if (manifest && typeof manifest === "object" && typeof manifest.contentSha256 === "string") {
104
- const norm = toPosix(relPath);
105
- map.set(norm, { ...manifest, relativePath: norm });
106
- }
107
- }
108
- this.workspaces.set(workspaceId, map);
109
- }
110
- } catch {
111
- this.workspaces.clear();
112
- this.schemaInvalidated = true;
113
- this.dirty = true;
114
- }
115
- }
116
- get(workspaceId, relativePath, contentSha256, mtimeMs, size) {
117
- const wsMap = this.workspaces.get(workspaceId);
118
- if (!wsMap) return void 0;
119
- const hit = wsMap.get(toPosix(relativePath));
120
- if (!hit) return void 0;
121
- return cacheEntryMatches(hit, contentSha256, mtimeMs, size) ? hit : void 0;
122
- }
123
- set(workspaceId, manifest) {
124
- const norm = toPosix(manifest.relativePath);
125
- const normalized = {
126
- ...manifest,
127
- relativePath: norm
128
- };
129
- let wsMap = this.workspaces.get(workspaceId);
130
- if (!wsMap) {
131
- wsMap = /* @__PURE__ */ new Map();
132
- this.workspaces.set(workspaceId, wsMap);
133
- }
134
- wsMap.set(norm, normalized);
135
- this.dirty = true;
136
- if (this.autoSave) {
137
- this.save();
138
- }
139
- }
140
- getAllWorkspaceManifests(workspaceId) {
141
- const wsMap = this.workspaces.get(workspaceId);
142
- if (!wsMap) return [];
143
- return [...wsMap.values()];
144
- }
145
- clear(workspaceId) {
146
- if (workspaceId === void 0) {
147
- this.workspaces.clear();
148
- } else {
149
- this.workspaces.delete(workspaceId);
150
- }
151
- this.dirty = true;
152
- if (this.autoSave) {
153
- this.save();
154
- }
155
- }
156
- save() {
157
- if (!this.dirty && existsSync(this.filePath)) return;
158
- const payload = {
159
- version: 1,
160
- manifestSchemaVersion: CACHE_SCHEMA_VERSION,
161
- workspaces: {}
162
- };
163
- for (const [workspaceId, wsMap] of this.workspaces.entries()) {
164
- const obj = {};
165
- for (const [relPath, manifest] of wsMap.entries()) {
166
- obj[relPath] = manifest;
167
- }
168
- payload.workspaces[workspaceId] = obj;
169
- }
170
- const dir = path2.dirname(this.filePath);
171
- mkdirSync(dir, { recursive: true });
172
- const serialized = JSON.stringify(payload, null, 2);
173
- const tmpPath = `${this.filePath}.${process.pid}.${Date.now()}.tmp`;
174
- try {
175
- writeFileSync(tmpPath, serialized, "utf8");
176
- renameSync(tmpPath, this.filePath);
177
- } catch {
178
- writeFileSync(this.filePath, serialized, "utf8");
179
- }
180
- this.dirty = false;
181
- }
182
- flush() {
183
- this.save();
184
- }
185
- };
186
-
187
- // ../engine/src/ast-extractor.ts
188
- function scriptKindFor(filePath) {
189
- switch (path3.extname(filePath).toLowerCase()) {
190
- case ".tsx":
191
- return ts.ScriptKind.TSX;
192
- case ".jsx":
193
- return ts.ScriptKind.JSX;
194
- case ".js":
195
- case ".mjs":
196
- case ".cjs":
197
- return ts.ScriptKind.JS;
198
- default:
199
- return ts.ScriptKind.TS;
200
- }
201
- }
202
- function jsTsLanguageFor(filePath) {
203
- switch (path3.extname(filePath).toLowerCase()) {
204
- case ".js":
205
- case ".jsx":
206
- case ".mjs":
207
- case ".cjs":
208
- return "javascript";
209
- default:
210
- return "typescript";
211
- }
212
- }
213
- function collapseWhitespace(text) {
214
- return text.replace(/\s+/g, " ").trim();
215
- }
216
- function truncateText(text, maxLen = 140) {
217
- if (text.length <= maxLen) return text;
218
- return `${text.slice(0, maxLen - 3)}...`;
219
- }
220
- function hasModifier(node, kind) {
221
- if (!ts.canHaveModifiers(node)) return false;
222
- const mods = ts.getModifiers(node);
223
- return mods ? mods.some((mod) => mod.kind === kind) : false;
224
- }
225
- function isFunctionLikeNode(node) {
226
- return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node);
227
- }
228
- function collectBindingNames(binding, out) {
229
- if (ts.isIdentifier(binding)) {
230
- out.add(binding.text);
231
- } else if (ts.isObjectBindingPattern(binding) || ts.isArrayBindingPattern(binding)) {
232
- for (const elem of binding.elements) {
233
- if (ts.isBindingElement(elem)) {
234
- collectBindingNames(elem.name, out);
235
- }
236
- }
237
- }
238
- }
239
- function collectFunctionScopeBindings(fn, out) {
240
- if (fn.name && ts.isIdentifier(fn.name)) {
241
- out.add(fn.name.text);
242
- }
243
- if (fn.typeParameters) {
244
- for (const tp of fn.typeParameters) {
245
- out.add(tp.name.text);
246
- }
247
- }
248
- for (const param of fn.parameters) {
249
- collectBindingNames(param.name, out);
250
- }
251
- }
252
- function collectHoistedVarDeclarations(node, out) {
253
- const walk = (curr) => {
254
- if (isFunctionLikeNode(curr)) return;
255
- if (ts.isVariableDeclarationList(curr)) {
256
- const isBlockScoped = (curr.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let)) !== 0;
257
- if (!isBlockScoped) {
258
- for (const decl of curr.declarations) {
259
- collectBindingNames(decl.name, out);
260
- }
261
- }
262
- }
263
- ts.forEachChild(curr, walk);
264
- };
265
- ts.forEachChild(node, walk);
266
- }
267
- function collectDirectStatementLocals(statements, out) {
268
- for (const stmt of statements) {
269
- if (ts.isVariableStatement(stmt)) {
270
- for (const decl of stmt.declarationList.declarations) {
271
- collectBindingNames(decl.name, out);
272
- }
273
- } else if (ts.isFunctionDeclaration(stmt) && stmt.name) {
274
- out.add(stmt.name.text);
275
- } else if (ts.isClassDeclaration(stmt) && stmt.name) {
276
- out.add(stmt.name.text);
277
- }
278
- }
279
- }
280
- function classifyIdentifierRole(curr, parent) {
281
- if (!parent) return "variable";
282
- if (ts.isPropertyAccessExpression(parent) && parent.name === curr) return "property";
283
- if (ts.isQualifiedName(parent) && parent.right === curr) return "property";
284
- if (ts.isBindingElement(parent) && parent.propertyName === curr) return "object_key";
285
- if (ts.isPropertyAssignment(parent) && parent.name === curr) return "object_key";
286
- if (ts.isPropertySignature(parent) && parent.name === curr) return "object_key";
287
- if (ts.isMethodDeclaration(parent) && parent.name === curr) return "object_key";
288
- if (ts.isMethodSignature(parent) && parent.name === curr) return "object_key";
289
- if (ts.isGetAccessorDeclaration(parent) && parent.name === curr) return "object_key";
290
- if (ts.isSetAccessorDeclaration(parent) && parent.name === curr) return "object_key";
291
- if (ts.isPropertyDeclaration(parent) && parent.name === curr) return "object_key";
292
- if (ts.isJsxAttribute(parent) && parent.name === curr) return "object_key";
293
- if ((ts.isLabeledStatement(parent) || ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === curr) {
294
- return "property";
295
- }
296
- 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) {
297
- return "declaration";
298
- }
299
- return "variable";
300
- }
301
- function collectModuleLocalDeclarations(sourceFile) {
302
- const decls = /* @__PURE__ */ new Set();
303
- for (const stmt of sourceFile.statements) {
304
- if (ts.isVariableStatement(stmt)) {
305
- for (const decl of stmt.declarationList.declarations) {
306
- collectBindingNames(decl.name, decls);
307
- }
308
- } else if (ts.isFunctionDeclaration(stmt) && stmt.name) {
309
- decls.add(stmt.name.text);
310
- } else if (ts.isClassDeclaration(stmt) && stmt.name) {
311
- decls.add(stmt.name.text);
312
- } else if (ts.isEnumDeclaration(stmt)) {
313
- decls.add(stmt.name.text);
314
- }
315
- }
316
- return decls;
317
- }
318
- function computeStructuralHashWithCount(node, sourceFile, options) {
319
- const target = ts.isVariableDeclaration(node) && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer)) ? node.initializer : node;
320
- const normalizedFilePath = normalizeRelPath(options?.filePath ?? sourceFile.fileName);
321
- const moduleLocalDecls = options?.moduleLocalDecls ?? collectModuleLocalDeclarations(sourceFile);
322
- const tokens = [];
323
- let nodeCount = 0;
324
- let astNodeCount = 0;
325
- const visit = (curr, countAsBody, scope, parent) => {
326
- nodeCount += 1;
327
- if (countAsBody) {
328
- astNodeCount += 1;
329
- }
330
- tokens.push(`K:${curr.kind}`);
331
- let childScope = scope;
332
- if (ts.isPropertyAccessExpression(curr)) {
333
- tokens.push(`PROP:${curr.name.text}`);
334
- } else if (ts.isStringLiteral(curr) || ts.isNoSubstitutionTemplateLiteral(curr)) {
335
- tokens.push(`STR:${curr.text}`);
336
- } else if (ts.isTemplateExpression(curr)) {
337
- tokens.push(`TPL_H:${curr.head.text}`);
338
- for (const span of curr.templateSpans) {
339
- tokens.push(`TPL_M:${span.literal.text}`);
340
- }
341
- } else if (ts.isNumericLiteral(curr)) {
342
- tokens.push(`NUM:${curr.text}`);
343
- } else if (ts.isRegularExpressionLiteral(curr)) {
344
- tokens.push(`REGEX:${curr.text}`);
345
- } else if (ts.isBinaryExpression(curr)) {
346
- tokens.push(`OP:${curr.operatorToken.kind}`);
347
- } else if (ts.isPrefixUnaryExpression(curr)) {
348
- tokens.push(`PRE:${curr.operator}`);
349
- } else if (ts.isPostfixUnaryExpression(curr)) {
350
- tokens.push(`POST:${curr.operator}`);
351
- } else if (ts.isVariableDeclarationList(curr)) {
352
- const declFlag = curr.flags & (ts.NodeFlags.Const | ts.NodeFlags.Let);
353
- tokens.push(`VF:${declFlag}`);
354
- } else if (ts.isIdentifier(curr)) {
355
- const role = classifyIdentifierRole(curr, parent);
356
- if (role === "declaration") {
357
- tokens.push("ID:$L");
358
- } else if (role === "object_key") {
359
- tokens.push(`KEY:${curr.text}`);
360
- } else if (role === "variable") {
361
- if (scope.has(curr.text)) {
362
- tokens.push("ID:$L");
363
- } else if (moduleLocalDecls.has(curr.text)) {
364
- tokens.push(`STATE:${normalizedFilePath}:${curr.text}`);
365
- } else {
366
- tokens.push(`EXT:${curr.text}`);
367
- }
368
- }
369
- }
370
- if (curr !== target && isFunctionLikeNode(curr)) {
371
- const next = new Set(scope);
372
- collectFunctionScopeBindings(curr, next);
373
- if (curr.body) {
374
- collectHoistedVarDeclarations(curr.body, next);
375
- }
376
- childScope = next;
377
- } else if (ts.isBlock(curr)) {
378
- const next = new Set(scope);
379
- collectDirectStatementLocals(curr.statements, next);
380
- childScope = next;
381
- } else if (ts.isCaseClause(curr) || ts.isDefaultClause(curr)) {
382
- const next = new Set(scope);
383
- collectDirectStatementLocals(curr.statements, next);
384
- childScope = next;
385
- } else if (ts.isForStatement(curr) || ts.isForInStatement(curr) || ts.isForOfStatement(curr)) {
386
- if (curr.initializer && ts.isVariableDeclarationList(curr.initializer)) {
387
- const next = new Set(scope);
388
- for (const decl of curr.initializer.declarations) {
389
- collectBindingNames(decl.name, next);
390
- }
391
- childScope = next;
392
- }
393
- } else if (ts.isCatchClause(curr) && curr.variableDeclaration) {
394
- const next = new Set(scope);
395
- collectBindingNames(curr.variableDeclaration.name, next);
396
- childScope = next;
397
- }
398
- ts.forEachChild(curr, (child) => visit(child, countAsBody, childScope, curr));
399
- };
400
- if (isFunctionLikeNode(target)) {
401
- const rootScope = /* @__PURE__ */ new Set();
402
- if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
403
- rootScope.add(node.name.text);
404
- }
405
- collectFunctionScopeBindings(target, rootScope);
406
- if (target.body) {
407
- collectHoistedVarDeclarations(target.body, rootScope);
408
- }
409
- tokens.push("FN");
410
- if (hasModifier(target, ts.SyntaxKind.AsyncKeyword)) {
411
- tokens.push("MOD:ASYNC");
412
- }
413
- if (target.asteriskToken) {
414
- tokens.push("MOD:GEN");
415
- }
416
- for (const param of target.parameters) {
417
- visit(param, false, rootScope, target);
418
- }
419
- if (target.body) {
420
- visit(target.body, true, rootScope, target);
421
- }
422
- } else {
423
- visit(target, true, /* @__PURE__ */ new Set(), void 0);
424
- }
425
- const structuralHash = createHash("sha256").update(tokens.join("|"), "utf8").digest("hex").slice(0, 16);
426
- return { structuralHash, nodeCount, astNodeCount };
427
- }
428
- function formatFunctionSignature(node, sourceFile) {
429
- const isAsync = hasModifier(node, ts.SyntaxKind.AsyncKeyword);
430
- const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
431
- const params = node.parameters.map((param) => collapseWhitespace(param.getText(sourceFile))).join(", ");
432
- const returnType = node.type ? `: ${collapseWhitespace(node.type.getText(sourceFile))}` : "";
433
- const prefix = isAsync ? "async " : "";
434
- return truncateText(`${prefix}${typeParams}(${params})${returnType}`);
435
- }
436
- function formatConstSummary(decl, sourceFile) {
437
- if (decl.type) {
438
- return truncateText(`: ${collapseWhitespace(decl.type.getText(sourceFile))}`);
439
- }
440
- const init = decl.initializer;
441
- if (!init) return ": unknown";
442
- if (ts.isStringLiteral(init) || ts.isNoSubstitutionTemplateLiteral(init)) {
443
- return ": string";
444
- }
445
- if (ts.isNumericLiteral(init)) {
446
- return `= ${init.text}`;
447
- }
448
- if (init.kind === ts.SyntaxKind.TrueKeyword) return "= true";
449
- if (init.kind === ts.SyntaxKind.FalseKeyword) return "= false";
450
- if (init.kind === ts.SyntaxKind.NullKeyword) return "= null";
451
- if (ts.isNewExpression(init)) {
452
- const className = collapseWhitespace(init.expression.getText(sourceFile));
453
- return truncateText(`= new ${className}(...)`, 80);
454
- }
455
- if (ts.isObjectLiteralExpression(init)) {
456
- const keys = init.properties.slice(0, 5).map((prop) => {
457
- if (ts.isPropertyAssignment(prop) || ts.isShorthandPropertyAssignment(prop) || ts.isMethodDeclaration(prop)) {
458
- return prop.name.getText(sourceFile);
459
- }
460
- return "...";
461
- });
462
- const suffix = init.properties.length > 5 ? ", ..." : "";
463
- return truncateText(`= { ${keys.join(", ")}${suffix} }`, 100);
464
- }
465
- if (ts.isArrayLiteralExpression(init)) {
466
- return `= Array(${init.elements.length})`;
467
- }
468
- return "= <expr>";
469
- }
470
- function formatClassSignature(node, sourceFile) {
471
- const name = node.name?.text ?? "default";
472
- const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
473
- const heritage = node.heritageClauses && node.heritageClauses.length > 0 ? ` ${node.heritageClauses.map((clause) => collapseWhitespace(clause.getText(sourceFile))).join(" ")}` : "";
474
- return truncateText(`class ${name}${typeParams}${heritage}`);
475
- }
476
- function formatInterfaceSignature(node, sourceFile) {
477
- const name = node.name.text;
478
- const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
479
- const heritage = node.heritageClauses && node.heritageClauses.length > 0 ? ` ${node.heritageClauses.map((clause) => collapseWhitespace(clause.getText(sourceFile))).join(" ")}` : "";
480
- const members = node.members.slice(0, 6).map((member) => collapseWhitespace(member.getText(sourceFile)).replace(/;$/, ""));
481
- const more = node.members.length > 6 ? "; ..." : "";
482
- return truncateText(`interface ${name}${typeParams}${heritage} { ${members.join("; ")}${more} }`, 160);
483
- }
484
- function formatTypeAliasSignature(node, sourceFile) {
485
- const name = node.name.text;
486
- const typeParams = node.typeParameters && node.typeParameters.length > 0 ? `<${node.typeParameters.map((tp) => collapseWhitespace(tp.getText(sourceFile))).join(", ")}>` : "";
487
- const rhs = collapseWhitespace(node.type.getText(sourceFile));
488
- return truncateText(`type ${name}${typeParams} = ${rhs}`, 160);
489
- }
490
- function formatEnumSignature(node, sourceFile) {
491
- const members = node.members.slice(0, 8).map((member) => collapseWhitespace(member.name.getText(sourceFile)));
492
- const more = node.members.length > 8 ? ", ..." : "";
493
- return truncateText(`enum ${node.name.text} { ${members.join(", ")}${more} }`, 140);
494
- }
495
- function lineNumberOf(node, sourceFile) {
496
- return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
497
- }
498
- function pushImportRef(refs, keyMap, rawSpecifier, importedNames, isReExport, isTypeOnly, isDynamic = false) {
499
- const trimmed = rawSpecifier.trim();
500
- if (!trimmed) return;
501
- const dedupKey = `${trimmed}\0${isReExport ? "1" : "0"}\0${isTypeOnly ? "1" : "0"}\0${isDynamic ? "1" : "0"}`;
502
- const existing = keyMap.get(dedupKey);
503
- if (existing) {
504
- for (const name of importedNames) {
505
- if (!existing.importedNames.includes(name)) {
506
- existing.importedNames.push(name);
507
- }
508
- }
509
- return;
510
- }
511
- const entry = {
512
- rawSpecifier: trimmed,
513
- importedNames: [...new Set(importedNames)],
514
- isReExport,
515
- isTypeOnly,
516
- ...isDynamic ? { isDynamic: true } : {}
517
- };
518
- keyMap.set(dedupKey, entry);
519
- refs.push(entry);
520
- }
521
- function extractImports(sourceFile) {
522
- const refs = [];
523
- const keyMap = /* @__PURE__ */ new Map();
524
- const visit = (node) => {
525
- if (ts.isImportDeclaration(node)) {
526
- if (ts.isStringLiteral(node.moduleSpecifier)) {
527
- const names = [];
528
- const clause = node.importClause;
529
- const allNamedTypeOnly = Boolean(
530
- clause && !clause.name && clause.namedBindings && ts.isNamedImports(clause.namedBindings) && clause.namedBindings.elements.length > 0 && clause.namedBindings.elements.every((elem) => elem.isTypeOnly)
531
- );
532
- const isTypeOnly = Boolean(clause?.isTypeOnly) || allNamedTypeOnly;
533
- if (clause) {
534
- if (clause.name) names.push("default");
535
- if (clause.namedBindings) {
536
- if (ts.isNamespaceImport(clause.namedBindings)) {
537
- names.push("*");
538
- } else if (ts.isNamedImports(clause.namedBindings)) {
539
- for (const elem of clause.namedBindings.elements) {
540
- names.push((elem.propertyName ?? elem.name).text);
541
- }
542
- }
543
- }
544
- }
545
- pushImportRef(refs, keyMap, node.moduleSpecifier.text, names, false, isTypeOnly, false);
546
- }
547
- } else if (ts.isExportDeclaration(node)) {
548
- if (node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
549
- const names = [];
550
- const allNamedTypeOnly = Boolean(
551
- node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements.length > 0 && node.exportClause.elements.every((elem) => elem.isTypeOnly)
552
- );
553
- const isTypeOnly = Boolean(node.isTypeOnly) || allNamedTypeOnly;
554
- if (!node.exportClause) {
555
- if (!isTypeOnly) {
556
- names.push("*");
557
- }
558
- } else if (ts.isNamespaceExport(node.exportClause)) {
559
- names.push("*");
560
- } else if (ts.isNamedExports(node.exportClause)) {
561
- for (const elem of node.exportClause.elements) {
562
- names.push((elem.propertyName ?? elem.name).text);
563
- }
564
- }
565
- pushImportRef(refs, keyMap, node.moduleSpecifier.text, names, true, isTypeOnly, false);
566
- }
567
- } else if (ts.isImportEqualsDeclaration(node)) {
568
- if (ts.isExternalModuleReference(node.moduleReference) && ts.isStringLiteral(node.moduleReference.expression)) {
569
- pushImportRef(refs, keyMap, node.moduleReference.expression.text, [node.name.text], false, false, false);
570
- }
571
- } else if (ts.isCallExpression(node)) {
572
- const first = node.arguments[0];
573
- if (first && ts.isStringLiteralLike(first)) {
574
- const callee = node.expression;
575
- if (callee.kind === ts.SyntaxKind.ImportKeyword) {
576
- pushImportRef(refs, keyMap, first.text, [], false, false, true);
577
- } else if (ts.isIdentifier(callee) && callee.text === "require") {
578
- pushImportRef(refs, keyMap, first.text, [], false, false, false);
579
- }
580
- }
581
- } else if (ts.isImportTypeNode(node)) {
582
- const argument = node.argument;
583
- if (ts.isLiteralTypeNode(argument) && ts.isStringLiteral(argument.literal)) {
584
- const names = node.qualifier ? [collapseWhitespace(node.qualifier.getText(sourceFile))] : [];
585
- pushImportRef(refs, keyMap, argument.literal.text, names, false, true, false);
586
- }
587
- }
588
- ts.forEachChild(node, visit);
589
- };
590
- visit(sourceFile);
591
- return refs;
592
- }
593
- function extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size) {
594
- const rel = toPosix(relativePath ?? absolutePath);
595
- const contentSha256 = createHash("sha256").update(source, "utf8").digest("hex");
596
- const sourceFile = ts.createSourceFile(
597
- absolutePath,
598
- source,
599
- ts.ScriptTarget.Latest,
600
- true,
601
- scriptKindFor(absolutePath)
602
- );
603
- const imports = extractImports(sourceFile);
604
- const moduleLocalDecls = collectModuleLocalDeclarations(sourceFile);
605
- const hashOptions = { filePath: rel, moduleLocalDecls };
606
- const localDecls = /* @__PURE__ */ new Map();
607
- const exportedSymbols = [];
608
- const internalFunctions = [];
609
- const exportedLocalNames = /* @__PURE__ */ new Set();
610
- const seenExportedKeys = /* @__PURE__ */ new Set();
611
- const addExported = (sym) => {
612
- const key = `${sym.name}\0${sym.kind}\0${sym.line}`;
613
- if (seenExportedKeys.has(key)) return;
614
- seenExportedKeys.add(key);
615
- exportedSymbols.push(sym);
616
- };
617
- for (const stmt of sourceFile.statements) {
618
- const isExport = hasModifier(stmt, ts.SyntaxKind.ExportKeyword);
619
- const isDefault = hasModifier(stmt, ts.SyntaxKind.DefaultKeyword);
620
- if (ts.isFunctionDeclaration(stmt)) {
621
- if (!stmt.body) continue;
622
- const declName = stmt.name?.text;
623
- const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
624
- stmt,
625
- sourceFile,
626
- hashOptions
627
- );
628
- const signature = formatFunctionSignature(stmt, sourceFile);
629
- const line = lineNumberOf(stmt, sourceFile);
630
- if (declName) {
631
- localDecls.set(declName, {
632
- name: declName,
633
- kind: "function",
634
- signature,
635
- line,
636
- structuralHash,
637
- nodeCount,
638
- astNodeCount,
639
- isFunctionHelper: true,
640
- exportedDirectly: isExport,
641
- exportedDefaultDirectly: isExport && isDefault
642
- });
643
- }
644
- if (isExport) {
645
- const exportName = isDefault ? "default" : declName;
646
- if (exportName) {
647
- addExported({
648
- name: exportName,
649
- ...isDefault && declName ? { localName: declName } : {},
650
- kind: "function",
651
- signature,
652
- line,
653
- structuralHash,
654
- nodeCount,
655
- astNodeCount,
656
- file: rel,
657
- isExported: true
658
- });
659
- if (declName) exportedLocalNames.add(declName);
660
- }
661
- }
662
- } else if (ts.isVariableStatement(stmt)) {
663
- for (const decl of stmt.declarationList.declarations) {
664
- if (!ts.isIdentifier(decl.name)) continue;
665
- const declName = decl.name.text;
666
- const line = lineNumberOf(decl, sourceFile);
667
- const init = decl.initializer;
668
- if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
669
- const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
670
- decl,
671
- sourceFile,
672
- hashOptions
673
- );
674
- const signature = formatFunctionSignature(init, sourceFile);
675
- localDecls.set(declName, {
676
- name: declName,
677
- kind: "function",
678
- signature,
679
- line,
680
- structuralHash,
681
- nodeCount,
682
- astNodeCount,
683
- isFunctionHelper: true,
684
- exportedDirectly: isExport,
685
- exportedDefaultDirectly: false
686
- });
687
- if (isExport) {
688
- addExported({
689
- name: declName,
690
- kind: "function",
691
- signature,
692
- line,
693
- structuralHash,
694
- nodeCount,
695
- astNodeCount,
696
- file: rel,
697
- isExported: true
698
- });
699
- exportedLocalNames.add(declName);
700
- }
701
- } else {
702
- const signature = formatConstSummary(decl, sourceFile);
703
- localDecls.set(declName, {
704
- name: declName,
705
- kind: "const",
706
- signature,
707
- line,
708
- isFunctionHelper: false,
709
- exportedDirectly: isExport,
710
- exportedDefaultDirectly: false
711
- });
712
- if (isExport) {
713
- addExported({
714
- name: declName,
715
- kind: "const",
716
- signature,
717
- line,
718
- file: rel,
719
- isExported: true
720
- });
721
- exportedLocalNames.add(declName);
722
- }
723
- }
724
- }
725
- } else if (ts.isClassDeclaration(stmt)) {
726
- const declName = stmt.name?.text;
727
- const signature = formatClassSignature(stmt, sourceFile);
728
- const line = lineNumberOf(stmt, sourceFile);
729
- if (declName) {
730
- localDecls.set(declName, {
731
- name: declName,
732
- kind: "class",
733
- signature,
734
- line,
735
- isFunctionHelper: false,
736
- exportedDirectly: isExport,
737
- exportedDefaultDirectly: isExport && isDefault
738
- });
739
- }
740
- if (isExport) {
741
- const exportName = isDefault ? "default" : declName;
742
- if (exportName) {
743
- addExported({
744
- name: exportName,
745
- ...isDefault && declName ? { localName: declName } : {},
746
- kind: "class",
747
- signature,
748
- line,
749
- file: rel,
750
- isExported: true
751
- });
752
- if (declName) exportedLocalNames.add(declName);
753
- }
754
- }
755
- } else if (ts.isInterfaceDeclaration(stmt)) {
756
- const declName = stmt.name.text;
757
- const signature = formatInterfaceSignature(stmt, sourceFile);
758
- const line = lineNumberOf(stmt, sourceFile);
759
- localDecls.set(declName, {
760
- name: declName,
761
- kind: "interface",
762
- signature,
763
- line,
764
- isFunctionHelper: false,
765
- exportedDirectly: isExport,
766
- exportedDefaultDirectly: false
767
- });
768
- if (isExport) {
769
- addExported({
770
- name: declName,
771
- kind: "interface",
772
- signature,
773
- line,
774
- file: rel,
775
- isExported: true
776
- });
777
- exportedLocalNames.add(declName);
778
- }
779
- } else if (ts.isTypeAliasDeclaration(stmt)) {
780
- const declName = stmt.name.text;
781
- const signature = formatTypeAliasSignature(stmt, sourceFile);
782
- const line = lineNumberOf(stmt, sourceFile);
783
- localDecls.set(declName, {
784
- name: declName,
785
- kind: "type",
786
- signature,
787
- line,
788
- isFunctionHelper: false,
789
- exportedDirectly: isExport,
790
- exportedDefaultDirectly: false
791
- });
792
- if (isExport) {
793
- addExported({
794
- name: declName,
795
- kind: "type",
796
- signature,
797
- line,
798
- file: rel,
799
- isExported: true
800
- });
801
- exportedLocalNames.add(declName);
802
- }
803
- } else if (ts.isEnumDeclaration(stmt)) {
804
- const declName = stmt.name.text;
805
- const signature = formatEnumSignature(stmt, sourceFile);
806
- const line = lineNumberOf(stmt, sourceFile);
807
- localDecls.set(declName, {
808
- name: declName,
809
- kind: "enum",
810
- signature,
811
- line,
812
- isFunctionHelper: false,
813
- exportedDirectly: isExport,
814
- exportedDefaultDirectly: false
815
- });
816
- if (isExport) {
817
- addExported({
818
- name: declName,
819
- kind: "enum",
820
- signature,
821
- line,
822
- file: rel,
823
- isExported: true
824
- });
825
- exportedLocalNames.add(declName);
826
- }
827
- } else if (ts.isExportDeclaration(stmt)) {
828
- if (stmt.moduleSpecifier && ts.isStringLiteral(stmt.moduleSpecifier)) {
829
- if (!stmt.isTypeOnly && stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
830
- for (const elem of stmt.exportClause.elements) {
831
- if (elem.isTypeOnly) continue;
832
- const localName = (elem.propertyName ?? elem.name).text;
833
- const exportedName = elem.name.text;
834
- addExported({
835
- name: exportedName,
836
- ...exportedName !== localName ? { localName } : {},
837
- kind: "const",
838
- signature: `export { ${localName} } from '${stmt.moduleSpecifier.text}'`,
839
- line: lineNumberOf(elem, sourceFile),
840
- file: rel,
841
- isExported: true,
842
- isReExport: true
843
- });
844
- }
845
- }
846
- } else if (stmt.exportClause && ts.isNamedExports(stmt.exportClause)) {
847
- for (const elem of stmt.exportClause.elements) {
848
- const localName = (elem.propertyName ?? elem.name).text;
849
- const exportedName = elem.name.text;
850
- const found = localDecls.get(localName);
851
- exportedLocalNames.add(localName);
852
- if (found) {
853
- addExported({
854
- name: exportedName,
855
- ...exportedName !== localName ? { localName } : {},
856
- kind: found.kind,
857
- signature: found.signature,
858
- line: found.line,
859
- ...found.structuralHash !== void 0 ? { structuralHash: found.structuralHash } : {},
860
- ...found.nodeCount !== void 0 ? { nodeCount: found.nodeCount } : {},
861
- ...found.astNodeCount !== void 0 ? { astNodeCount: found.astNodeCount } : {},
862
- file: rel,
863
- isExported: true
864
- });
865
- } else if (!stmt.isTypeOnly && !elem.isTypeOnly) {
866
- addExported({
867
- name: exportedName,
868
- ...exportedName !== localName ? { localName } : {},
869
- kind: "const",
870
- signature: `export { ${localName} }`,
871
- line: lineNumberOf(elem, sourceFile),
872
- file: rel,
873
- isExported: true,
874
- isReExport: true
875
- });
876
- }
877
- }
878
- }
879
- } else if (ts.isExportAssignment(stmt) && !stmt.isExportEquals) {
880
- const line = lineNumberOf(stmt, sourceFile);
881
- if (ts.isIdentifier(stmt.expression)) {
882
- const localName = stmt.expression.text;
883
- const found = localDecls.get(localName);
884
- exportedLocalNames.add(localName);
885
- if (found) {
886
- addExported({
887
- name: "default",
888
- localName,
889
- kind: found.kind,
890
- signature: found.signature,
891
- line: found.line,
892
- ...found.structuralHash !== void 0 ? { structuralHash: found.structuralHash } : {},
893
- ...found.nodeCount !== void 0 ? { nodeCount: found.nodeCount } : {},
894
- ...found.astNodeCount !== void 0 ? { astNodeCount: found.astNodeCount } : {},
895
- file: rel,
896
- isExported: true
897
- });
898
- } else {
899
- addExported({
900
- name: "default",
901
- localName,
902
- kind: "const",
903
- signature: `export default ${localName}`,
904
- line,
905
- file: rel,
906
- isExported: true,
907
- isReExport: true
908
- });
909
- }
910
- } else if (ts.isArrowFunction(stmt.expression) || ts.isFunctionExpression(stmt.expression)) {
911
- const { structuralHash, nodeCount, astNodeCount } = computeStructuralHashWithCount(
912
- stmt.expression,
913
- sourceFile,
914
- hashOptions
915
- );
916
- addExported({
917
- name: "default",
918
- kind: "function",
919
- signature: formatFunctionSignature(stmt.expression, sourceFile),
920
- line,
921
- structuralHash,
922
- nodeCount,
923
- astNodeCount,
924
- file: rel,
925
- isExported: true
926
- });
927
- } else {
928
- addExported({
929
- name: "default",
930
- kind: "const",
931
- signature: "= <default>",
932
- line,
933
- file: rel,
934
- isExported: true
935
- });
936
- }
937
- }
938
- }
939
- for (const [declName, record] of localDecls) {
940
- if (!record.isFunctionHelper) continue;
941
- if (record.exportedDirectly || exportedLocalNames.has(declName)) continue;
942
- if (record.structuralHash === void 0 || record.nodeCount === void 0) continue;
943
- internalFunctions.push({
944
- name: record.name,
945
- kind: "function",
946
- signature: record.signature,
947
- line: record.line,
948
- structuralHash: record.structuralHash,
949
- nodeCount: record.nodeCount,
950
- ...record.astNodeCount !== void 0 ? { astNodeCount: record.astNodeCount } : {},
951
- file: rel,
952
- isExported: false
953
- });
954
- }
955
- return {
956
- relativePath: rel,
957
- contentSha256,
958
- schemaVersion: CACHE_SCHEMA_VERSION,
959
- language: jsTsLanguageFor(absolutePath),
960
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
961
- ...size !== void 0 ? { size } : {},
962
- imports,
963
- exportedSymbols,
964
- internalFunctions
965
- };
966
- }
967
-
968
- // ../engine/src/indexer.ts
969
- import { createHash as createHash3 } from "node:crypto";
970
- import { readFileSync as readFileSync3, readdirSync, realpathSync, statSync } from "node:fs";
971
- import { builtinModules } from "node:module";
972
- import path5 from "node:path";
973
- import ts2 from "typescript";
974
-
975
- // ../engine/src/polyglot-adapters.ts
976
- import { createHash as createHash2 } from "node:crypto";
977
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
978
- import path4 from "node:path";
979
- function sha256Hex(source) {
980
- return createHash2("sha256").update(source, "utf8").digest("hex");
981
- }
982
- function collapseWs(text) {
983
- return text.replace(/\s+/g, " ").trim();
984
- }
985
- function truncateSig(text, maxLen = 140) {
986
- if (text.length <= maxLen) return text;
987
- return `${text.slice(0, maxLen - 3)}...`;
988
- }
989
- function lineOfOffset(source, offset) {
990
- let line = 1;
991
- const end = Math.min(offset, source.length);
992
- for (let i = 0; i < end; i += 1) {
993
- if (source.charCodeAt(i) === 10) line += 1;
994
- }
995
- return line;
996
- }
997
- function lookupKnownFile(ctx, candidateRel) {
998
- const norm = normalizeRelPath(candidateRel);
999
- if (!norm || norm.startsWith("..")) return null;
1000
- return ctx.knownFiles.get(norm) ?? ctx.knownFiles.get(norm.toLowerCase()) ?? null;
1001
- }
1002
- var CONTROL_KEYWORDS = {
1003
- if: "KW:IF",
1004
- elif: "KW:IF",
1005
- elsif: "KW:IF",
1006
- else: "KW:ELSE",
1007
- for: "KW:FOR",
1008
- foreach: "KW:FOR",
1009
- while: "KW:WHILE",
1010
- loop: "KW:WHILE",
1011
- match: "KW:MATCH",
1012
- switch: "KW:MATCH",
1013
- case: "KW:CASE",
1014
- when: "KW:CASE",
1015
- default: "KW:DEFAULT",
1016
- return: "KW:RETURN",
1017
- await: "KW:AWAIT",
1018
- try: "KW:TRY",
1019
- begin: "KW:TRY",
1020
- catch: "KW:CATCH",
1021
- except: "KW:CATCH",
1022
- rescue: "KW:CATCH",
1023
- finally: "KW:FINALLY",
1024
- ensure: "KW:FINALLY",
1025
- throw: "KW:THROW",
1026
- raise: "KW:THROW",
1027
- panic: "KW:THROW",
1028
- break: "KW:BREAK",
1029
- continue: "KW:CONTINUE",
1030
- next: "KW:CONTINUE",
1031
- yield: "KW:YIELD",
1032
- in: "KW:IN",
1033
- new: "KW:NEW",
1034
- and: "OP:AND",
1035
- or: "OP:OR",
1036
- not: "OP:NOT",
1037
- true: "LIT:BOOL",
1038
- false: "LIT:BOOL",
1039
- True: "LIT:BOOL",
1040
- False: "LIT:BOOL",
1041
- null: "LIT:NULL",
1042
- nil: "LIT:NULL",
1043
- None: "LIT:NULL",
1044
- nullptr: "LIT:NULL",
1045
- let: "DECL",
1046
- const: "DECL",
1047
- var: "DECL",
1048
- mut: "DECL",
1049
- val: "DECL",
1050
- auto: "DECL",
1051
- local: "DECL"
1052
- };
1053
- var MULTI_CHAR_OPS = [
1054
- "===",
1055
- "!==",
1056
- "<<=",
1057
- ">>=",
1058
- "..=",
1059
- "==",
1060
- "!=",
1061
- "<=",
1062
- ">=",
1063
- "&&",
1064
- "||",
1065
- "+=",
1066
- "-=",
1067
- "*=",
1068
- "/=",
1069
- "%=",
1070
- ":=",
1071
- "??",
1072
- "?.",
1073
- "=>",
1074
- "->",
1075
- "::",
1076
- "..",
1077
- "<<",
1078
- ">>",
1079
- "**",
1080
- "//"
1081
- ];
1082
- function tokenizeNormalizedCode(source, hashComments) {
1083
- const tokens = [];
1084
- let meaningfulCount = 0;
1085
- const len = source.length;
1086
- let i = 0;
1087
- let prevWasMemberOp = false;
1088
- while (i < len) {
1089
- const ch = source[i];
1090
- const next = i + 1 < len ? source[i + 1] : "";
1091
- if (ch === " " || ch === " " || ch === "\r" || ch === "\n") {
1092
- i += 1;
1093
- continue;
1094
- }
1095
- if (ch === "/" && next === "/") {
1096
- i += 2;
1097
- while (i < len && source[i] !== "\n") i += 1;
1098
- continue;
1099
- }
1100
- if (hashComments && ch === "#") {
1101
- i += 1;
1102
- while (i < len && source[i] !== "\n") i += 1;
1103
- continue;
1104
- }
1105
- if (ch === "/" && next === "*") {
1106
- i += 2;
1107
- while (i + 1 < len && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
1108
- i = Math.min(len, i + 2);
1109
- continue;
1110
- }
1111
- if (ch === '"' && source.slice(i, i + 3) === '"""' || ch === "'" && source.slice(i, i + 3) === "'''") {
1112
- const quote = source.slice(i, i + 3);
1113
- i += 3;
1114
- while (i < len) {
1115
- if (source[i] === "\\") {
1116
- i += 2;
1117
- continue;
1118
- }
1119
- if (source.slice(i, i + 3) === quote) {
1120
- i += 3;
1121
- break;
1122
- }
1123
- i += 1;
1124
- }
1125
- tokens.push("LIT:STR");
1126
- meaningfulCount += 1;
1127
- prevWasMemberOp = false;
1128
- continue;
1129
- }
1130
- if (ch === '"' || ch === "'" || ch === "`") {
1131
- const quote = ch;
1132
- i += 1;
1133
- while (i < len) {
1134
- const c = source[i];
1135
- if (c === "\\" && quote !== "`") {
1136
- i += 2;
1137
- continue;
1138
- }
1139
- if (c === quote) {
1140
- i += 1;
1141
- break;
1142
- }
1143
- i += 1;
1144
- }
1145
- tokens.push("LIT:STR");
1146
- meaningfulCount += 1;
1147
- prevWasMemberOp = false;
1148
- continue;
1149
- }
1150
- if ((ch === "r" || ch === "f" || ch === "b" || ch === "u" || ch === "R") && (next === '"' || next === "'" || next === "#")) {
1151
- if (next === '"' || next === "'") {
1152
- i += 1;
1153
- continue;
1154
- }
1155
- if (ch === "r" && next === "#") {
1156
- let hashes = 0;
1157
- let k = i + 1;
1158
- while (k < len && source[k] === "#") {
1159
- hashes += 1;
1160
- k += 1;
1161
- }
1162
- if (source[k] === '"') {
1163
- k += 1;
1164
- const closing = '"' + "#".repeat(hashes);
1165
- const endIdx = source.indexOf(closing, k);
1166
- i = endIdx === -1 ? len : endIdx + closing.length;
1167
- tokens.push("LIT:STR");
1168
- meaningfulCount += 1;
1169
- prevWasMemberOp = false;
1170
- continue;
1171
- }
1172
- }
1173
- }
1174
- if (ch >= "0" && ch <= "9") {
1175
- i += 1;
1176
- while (i < len && /[0-9a-fA-FxXoObB._eE]/.test(source[i])) {
1177
- i += 1;
1178
- }
1179
- tokens.push("LIT:NUM");
1180
- meaningfulCount += 1;
1181
- prevWasMemberOp = false;
1182
- continue;
1183
- }
1184
- if (ch === "$" && i + 1 < len && /[a-zA-Z_]/.test(source[i + 1])) {
1185
- i += 2;
1186
- while (i < len && /[a-zA-Z0-9_]/.test(source[i])) i += 1;
1187
- tokens.push("ID");
1188
- meaningfulCount += 1;
1189
- prevWasMemberOp = false;
1190
- continue;
1191
- }
1192
- if (ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_") {
1193
- const start = i;
1194
- i += 1;
1195
- while (i < len && /[a-zA-Z0-9_]/.test(source[i])) i += 1;
1196
- const word = source.slice(start, i);
1197
- if (prevWasMemberOp) {
1198
- tokens.push(`PROP:.${word}`);
1199
- meaningfulCount += 1;
1200
- prevWasMemberOp = false;
1201
- continue;
1202
- }
1203
- const kw = CONTROL_KEYWORDS[word];
1204
- if (kw) {
1205
- tokens.push(kw);
1206
- meaningfulCount += 1;
1207
- } else {
1208
- let peek = i;
1209
- while (peek < len && (source[peek] === " " || source[peek] === " ")) peek += 1;
1210
- if (source[peek] === "(") {
1211
- tokens.push("CALL");
1212
- } else {
1213
- tokens.push("ID");
1214
- }
1215
- meaningfulCount += 1;
1216
- }
1217
- prevWasMemberOp = false;
1218
- continue;
1219
- }
1220
- let matchedOp = null;
1221
- for (const op of MULTI_CHAR_OPS) {
1222
- if (source.startsWith(op, i)) {
1223
- matchedOp = op;
1224
- break;
1225
- }
1226
- }
1227
- if (matchedOp) {
1228
- if (matchedOp === "&&") {
1229
- tokens.push("OP:AND");
1230
- meaningfulCount += 1;
1231
- prevWasMemberOp = false;
1232
- } else if (matchedOp === "||") {
1233
- tokens.push("OP:OR");
1234
- meaningfulCount += 1;
1235
- prevWasMemberOp = false;
1236
- } else if (matchedOp === "->" || matchedOp === "::" || matchedOp === "?.") {
1237
- tokens.push(`OP:${matchedOp}`);
1238
- prevWasMemberOp = true;
1239
- } else {
1240
- tokens.push(`OP:${matchedOp}`);
1241
- meaningfulCount += 1;
1242
- prevWasMemberOp = false;
1243
- }
1244
- i += matchedOp.length;
1245
- continue;
1246
- }
1247
- if (ch === ".") {
1248
- tokens.push(".");
1249
- prevWasMemberOp = true;
1250
- i += 1;
1251
- continue;
1252
- }
1253
- if ("+-*/%<>=!&|^~?".includes(ch)) {
1254
- tokens.push(ch === "!" ? "OP:NOT" : `OP:${ch}`);
1255
- meaningfulCount += 1;
1256
- prevWasMemberOp = false;
1257
- i += 1;
1258
- continue;
1259
- }
1260
- if ("()[]{},;:".includes(ch)) {
1261
- tokens.push(ch);
1262
- prevWasMemberOp = false;
1263
- i += 1;
1264
- continue;
1265
- }
1266
- prevWasMemberOp = false;
1267
- i += 1;
1268
- }
1269
- return { tokens, meaningfulCount };
1270
- }
1271
- function computePolyglotStructuralHash(bodySource, paramsSource = "", options = {}) {
1272
- const hashComments = options.hashComments ?? false;
1273
- const paramRes = paramsSource.trim() ? tokenizeNormalizedCode(paramsSource, hashComments) : { tokens: [], meaningfulCount: 0 };
1274
- const bodyRes = tokenizeNormalizedCode(bodySource, hashComments);
1275
- const combined = ["FN"];
1276
- if (options.isAsync) combined.push("MOD:ASYNC");
1277
- if (paramRes.tokens.length > 0) {
1278
- combined.push("PARAMS", ...paramRes.tokens);
1279
- }
1280
- combined.push("BODY", ...bodyRes.tokens);
1281
- const structuralHash = createHash2("sha256").update(combined.join("|"), "utf8").digest("hex").slice(0, 16);
1282
- const astNodeCount = bodyRes.meaningfulCount;
1283
- const nodeCount = paramRes.meaningfulCount + astNodeCount;
1284
- return { structuralHash, nodeCount, astNodeCount };
1285
- }
1286
- function findMatchingBrace(source, openIdx, hashComments = false) {
1287
- let depth = 0;
1288
- const len = source.length;
1289
- let i = openIdx;
1290
- while (i < len) {
1291
- const ch = source[i];
1292
- const next = i + 1 < len ? source[i + 1] : "";
1293
- if (ch === "/" && next === "/") {
1294
- i += 2;
1295
- while (i < len && source[i] !== "\n") i += 1;
1296
- continue;
1297
- }
1298
- if (hashComments && ch === "#") {
1299
- i += 1;
1300
- while (i < len && source[i] !== "\n") i += 1;
1301
- continue;
1302
- }
1303
- if (ch === "/" && next === "*") {
1304
- i += 2;
1305
- while (i + 1 < len && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
1306
- i = Math.min(len, i + 2);
1307
- continue;
1308
- }
1309
- if (ch === '"' || ch === "'" || ch === "`") {
1310
- const q = ch;
1311
- i += 1;
1312
- while (i < len) {
1313
- if (source[i] === "\\" && q !== "`") {
1314
- i += 2;
1315
- continue;
1316
- }
1317
- if (source[i] === q) {
1318
- i += 1;
1319
- break;
1320
- }
1321
- i += 1;
1322
- }
1323
- continue;
1324
- }
1325
- if (ch === "{") {
1326
- depth += 1;
1327
- } else if (ch === "}") {
1328
- depth -= 1;
1329
- if (depth === 0) return i;
1330
- }
1331
- i += 1;
1332
- }
1333
- return -1;
1334
- }
1335
- function splitTopLevelCommas(text) {
1336
- const parts = [];
1337
- let depth = 0;
1338
- let curr = "";
1339
- for (let i = 0; i < text.length; i += 1) {
1340
- const ch = text[i];
1341
- if (ch === "(" || ch === "[" || ch === "<" || ch === "{") depth += 1;
1342
- else if (ch === ")" || ch === "]" || ch === ">" || ch === "}") depth = Math.max(0, depth - 1);
1343
- if (ch === "," && depth === 0) {
1344
- if (curr.trim()) parts.push(curr.trim());
1345
- curr = "";
1346
- } else {
1347
- curr += ch;
1348
- }
1349
- }
1350
- if (curr.trim()) parts.push(curr.trim());
1351
- return parts;
1352
- }
1353
- function pushUniqueImport(imports, seen, rawSpecifier, importedNames, isReExport, isTypeOnly = false) {
1354
- const trimmed = rawSpecifier.trim();
1355
- if (!trimmed) return;
1356
- const key = `${trimmed}\0${isReExport ? "1" : "0"}\0${isTypeOnly ? "1" : "0"}`;
1357
- const existing = seen.get(key);
1358
- if (existing) {
1359
- for (const name of importedNames) {
1360
- if (name && !existing.importedNames.includes(name)) {
1361
- existing.importedNames.push(name);
1362
- }
1363
- }
1364
- return;
1365
- }
1366
- const entry = {
1367
- rawSpecifier: trimmed,
1368
- importedNames: [...new Set(importedNames.filter(Boolean))],
1369
- isReExport,
1370
- isTypeOnly
1371
- };
1372
- seen.set(key, entry);
1373
- imports.push(entry);
1374
- }
1375
- function formatJsTsImport(fromRelPath, symbol) {
1376
- if (fromRelPath === null) {
1377
- return `// pass fromFile to resolve the exact specifier (symbol lives in '${symbol.file}')`;
1378
- }
1379
- const spec = computeRelativeImportSpec(fromRelPath, symbol.file);
1380
- if (symbol.name === "default") {
1381
- return `import ${symbol.localName ?? "defaultExport"} from '${spec}';`;
1382
- }
1383
- if (symbol.kind === "interface" || symbol.kind === "type") {
1384
- return `import type { ${symbol.name} } from '${spec}';`;
1385
- }
1386
- return `import { ${symbol.name} } from '${spec}';`;
1387
- }
1388
- function createJsTsAdapter(id, extensions) {
1389
- return {
1390
- id,
1391
- extensions,
1392
- extractManifest(source, absolutePath, relativePath, mtimeMs, size) {
1393
- const manifest = extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size);
1394
- return { ...manifest, language: id };
1395
- },
1396
- resolveImport(imp, fromRelPath, ctx) {
1397
- const spec = imp.rawSpecifier.trim();
1398
- if (spec === "." || spec === ".." || spec.startsWith("./") || spec.startsWith("../")) {
1399
- const base = path4.posix.normalize(path4.posix.join(path4.posix.dirname(fromRelPath), spec));
1400
- const ext = path4.posix.extname(base).toLowerCase();
1401
- const swaps = {
1402
- ".js": [".ts", ".tsx", ".js", ".jsx"],
1403
- ".jsx": [".tsx", ".jsx", ".ts", ".js"],
1404
- ".mjs": [".mts", ".mjs"],
1405
- ".cjs": [".cts", ".cjs"]
1406
- };
1407
- const candidates = [];
1408
- if (swaps[ext]) {
1409
- const stem = base.slice(0, base.length - ext.length);
1410
- for (const s of swaps[ext]) candidates.push(`${stem}${s}`);
1411
- }
1412
- candidates.push(
1413
- base,
1414
- `${base}.ts`,
1415
- `${base}.tsx`,
1416
- `${base}.mts`,
1417
- `${base}.cts`,
1418
- `${base}.js`,
1419
- `${base}.jsx`,
1420
- `${base}.mjs`,
1421
- `${base}.cjs`,
1422
- `${base}/index.ts`,
1423
- `${base}/index.tsx`,
1424
- `${base}/index.js`,
1425
- `${base}/index.jsx`
1426
- );
1427
- for (const cand of candidates) {
1428
- const hit = lookupKnownFile(ctx, cand);
1429
- if (hit) return { kind: "local", resolvedPaths: [hit] };
1430
- }
1431
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: base };
1432
- }
1433
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
1434
- },
1435
- formatImportStatement(fromRelPath, symbol) {
1436
- return formatJsTsImport(fromRelPath, symbol);
1437
- }
1438
- };
1439
- }
1440
- var PYTHON_LEADING_DOCSTRING_RE = /^\s*(?:[rRuUfFbB]{0,2})(?:"""[\s\S]*?"""|'''[\s\S]*?''')\s*\r?\n?/;
1441
- function formatPythonParams(rawParams) {
1442
- const params = splitTopLevelCommas(rawParams).map((p) => collapseWs(p)).filter((p) => p && p !== "/" && p !== "*" && p !== "self" && p !== "cls");
1443
- return params.map((p) => {
1444
- const eqIdx = p.indexOf("=");
1445
- return eqIdx === -1 ? p : p.slice(0, eqIdx).trim();
1446
- }).join(", ");
1447
- }
1448
- function parsePythonAllExports(source) {
1449
- const match = /^__all__\s*(?::[^=]+)?=\s*[\[\(]([\s\S]*?)[\]\)]/m.exec(source);
1450
- if (!match || !match[1]) return null;
1451
- const names = /* @__PURE__ */ new Set();
1452
- const strRe = /['"]([a-zA-Z_][a-zA-Z0-9_]*)['"]/g;
1453
- let m;
1454
- while ((m = strRe.exec(match[1])) !== null) {
1455
- if (m[1]) names.add(m[1]);
1456
- }
1457
- return names;
1458
- }
1459
- function parsePythonSource(source, relativePath, mtimeMs, size) {
1460
- const rel = normalizeRelPath(relativePath);
1461
- const contentSha256 = sha256Hex(source);
1462
- const imports = [];
1463
- const importSeen = /* @__PURE__ */ new Map();
1464
- const exportedSymbols = [];
1465
- const internalFunctions = [];
1466
- const isInitBarrel = path4.posix.basename(rel) === "__init__.py";
1467
- const allExports = parsePythonAllExports(source);
1468
- const isPublicName = (name) => {
1469
- if (allExports !== null) return allExports.has(name);
1470
- return !name.startsWith("_");
1471
- };
1472
- const lines = source.split(/\r?\n/);
1473
- for (let i = 0; i < lines.length; i += 1) {
1474
- const line = lines[i];
1475
- const trimmed = line.trim();
1476
- if (!trimmed || trimmed.startsWith("#")) continue;
1477
- const fromMatch = /^from\s+(\.+[a-zA-Z0-9_.]*|[a-zA-Z_][a-zA-Z0-9_.]*)\s+import\s+(.*)$/.exec(trimmed);
1478
- if (fromMatch && fromMatch[1]) {
1479
- const rawMod = fromMatch[1];
1480
- let rest = (fromMatch[2] ?? "").replace(/#.*$/, "").trim();
1481
- if (rest.startsWith("(")) {
1482
- let block = rest.slice(1);
1483
- let j = i;
1484
- while (!block.includes(")") && j + 1 < lines.length) {
1485
- j += 1;
1486
- block += " " + (lines[j] ?? "").replace(/#.*$/, "");
1487
- }
1488
- const closeIdx = block.indexOf(")");
1489
- rest = closeIdx === -1 ? block : block.slice(0, closeIdx);
1490
- i = j;
1491
- }
1492
- const names = rest.split(",").map((part) => part.trim()).filter(Boolean).map((part) => {
1493
- const asMatch = /^([a-zA-Z0-9_*]+)(?:\s+as\s+([a-zA-Z0-9_]+))?/.exec(part);
1494
- return asMatch?.[1] ?? "";
1495
- }).filter(Boolean);
1496
- const isReExport = isInitBarrel && (allExports === null || names.some((n) => n === "*" || allExports.has(n)));
1497
- pushUniqueImport(imports, importSeen, rawMod, names, isReExport, false);
1498
- continue;
1499
- }
1500
- const impMatch = /^import\s+(.+)$/.exec(trimmed);
1501
- if (impMatch && impMatch[1]) {
1502
- const rest = impMatch[1].replace(/#.*$/, "").trim();
1503
- for (const seg of rest.split(",")) {
1504
- const cleaned = seg.trim();
1505
- const modMatch = /^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\s+as\s+([a-zA-Z_][a-zA-Z0-9_]*))?$/.exec(cleaned);
1506
- if (modMatch && modMatch[1]) {
1507
- pushUniqueImport(imports, importSeen, modMatch[1], [], false, false);
1508
- }
1509
- }
1510
- continue;
1511
- }
1512
- }
1513
- for (let i = 0; i < lines.length; i += 1) {
1514
- const rawLine = lines[i];
1515
- if (!rawLine.trim() || rawLine.startsWith(" ") || rawLine.startsWith(" ") || rawLine.startsWith("#")) {
1516
- continue;
1517
- }
1518
- const fnStart = /^(async\s+)?def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/.exec(rawLine);
1519
- if (fnStart && fnStart[2]) {
1520
- const isAsync = Boolean(fnStart[1]);
1521
- const name = fnStart[2];
1522
- const lineNum = i + 1;
1523
- let header = rawLine;
1524
- let headerEndIdx = i;
1525
- let parenDepth = 0;
1526
- let seenOpen = false;
1527
- for (let h = i; h < lines.length; h += 1) {
1528
- const l = lines[h];
1529
- for (const c of l) {
1530
- if (c === "(") {
1531
- parenDepth += 1;
1532
- seenOpen = true;
1533
- } else if (c === ")") {
1534
- parenDepth = Math.max(0, parenDepth - 1);
1535
- }
1536
- }
1537
- if (h > i) header += " " + l.trim();
1538
- headerEndIdx = h;
1539
- if (seenOpen && parenDepth === 0 && l.replace(/#.*$/, "").trim().endsWith(":")) {
1540
- break;
1541
- }
1542
- }
1543
- const sigMatch = /^(?:async\s+)?def\s+[a-zA-Z_][a-zA-Z0-9_]*\s*\(([\s\S]*)\)\s*(?:->\s*([^:]+))?\s*:/.exec(
1544
- header.replace(/#[^\n]*$/gm, "").trim()
1545
- );
1546
- const rawParams = sigMatch?.[1] ?? "";
1547
- const rawRet = sigMatch?.[2]?.trim();
1548
- const formattedParams = formatPythonParams(rawParams);
1549
- const signature = truncateSig(
1550
- `${isAsync ? "async " : ""}(${formattedParams})${rawRet ? `: ${collapseWs(rawRet)}` : ""}`
1551
- );
1552
- const bodyLines = [];
1553
- let b = headerEndIdx + 1;
1554
- while (b < lines.length) {
1555
- const bl = lines[b];
1556
- if (bl.trim() === "") {
1557
- bodyLines.push(bl);
1558
- b += 1;
1559
- continue;
1560
- }
1561
- if (!bl.startsWith(" ") && !bl.startsWith(" ")) {
1562
- break;
1563
- }
1564
- bodyLines.push(bl);
1565
- b += 1;
1566
- }
1567
- const bodySource = bodyLines.join("\n").replace(PYTHON_LEADING_DOCSTRING_RE, "");
1568
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
1569
- bodySource,
1570
- formattedParams,
1571
- { isAsync, hashComments: true }
1572
- );
1573
- if (isPublicName(name)) {
1574
- exportedSymbols.push({
1575
- name,
1576
- kind: "function",
1577
- signature,
1578
- line: lineNum,
1579
- structuralHash,
1580
- nodeCount,
1581
- astNodeCount,
1582
- file: rel,
1583
- isExported: true
1584
- });
1585
- } else {
1586
- internalFunctions.push({
1587
- name,
1588
- kind: "function",
1589
- signature,
1590
- line: lineNum,
1591
- structuralHash,
1592
- nodeCount,
1593
- astNodeCount,
1594
- file: rel,
1595
- isExported: false
1596
- });
1597
- }
1598
- i = Math.max(headerEndIdx, b - 1);
1599
- continue;
1600
- }
1601
- const clsMatch = /^class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:\(([^)]*)\))?\s*:/.exec(rawLine);
1602
- if (clsMatch && clsMatch[1]) {
1603
- const name = clsMatch[1];
1604
- if (isPublicName(name)) {
1605
- const bases = clsMatch[2]?.trim();
1606
- exportedSymbols.push({
1607
- name,
1608
- kind: "class",
1609
- signature: truncateSig(`class ${name}${bases ? `(${collapseWs(bases)})` : ""}`),
1610
- line: i + 1,
1611
- file: rel,
1612
- isExported: true
1613
- });
1614
- }
1615
- continue;
1616
- }
1617
- const constMatch = /^([A-Z][A-Z0-9_]{1,})\s*(?::\s*([^=]+))?=\s*(.+)$/.exec(rawLine);
1618
- if (constMatch && constMatch[1] && constMatch[1] !== "__ALL__") {
1619
- const name = constMatch[1];
1620
- if (isPublicName(name)) {
1621
- const typeAnn = constMatch[2]?.trim();
1622
- const rhs = constMatch[3]?.trim() ?? "";
1623
- const sig = typeAnn ? `: ${collapseWs(typeAnn)}` : /^(['"]).*\1$/.test(rhs) || /^\d/.test(rhs) || /^(True|False|None)$/.test(rhs) ? `= ${rhs}` : "= <expr>";
1624
- exportedSymbols.push({
1625
- name,
1626
- kind: "const",
1627
- signature: truncateSig(sig, 80),
1628
- line: i + 1,
1629
- file: rel,
1630
- isExported: true
1631
- });
1632
- }
1633
- }
1634
- }
1635
- return {
1636
- relativePath: rel,
1637
- contentSha256,
1638
- language: "python",
1639
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
1640
- ...size !== void 0 ? { size } : {},
1641
- imports,
1642
- exportedSymbols,
1643
- internalFunctions
1644
- };
1645
- }
1646
- function resolvePythonImport(imp, fromRelPath, ctx) {
1647
- const spec = imp.rawSpecifier.trim();
1648
- const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
1649
- const resolved = [];
1650
- const tryModulePath = (baseRel) => {
1651
- const clean = normalizeRelPath(baseRel);
1652
- return lookupKnownFile(ctx, `${clean}.py`) ?? lookupKnownFile(ctx, `${clean}/__init__.py`);
1653
- };
1654
- if (spec.startsWith(".")) {
1655
- let dots = 0;
1656
- while (dots < spec.length && spec[dots] === ".") dots += 1;
1657
- const remainder = spec.slice(dots);
1658
- let targetDir = fromDir === "." ? "" : fromDir;
1659
- for (let up = 1; up < dots; up += 1) {
1660
- if (!targetDir) {
1661
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: spec };
1662
- }
1663
- const parent = path4.posix.dirname(targetDir);
1664
- targetDir = parent === "." ? "" : parent;
1665
- }
1666
- if (remainder) {
1667
- const modRel2 = remainder.split(".").join("/");
1668
- const candidateBase = targetDir ? `${targetDir}/${modRel2}` : modRel2;
1669
- const hit = tryModulePath(candidateBase);
1670
- if (hit) {
1671
- return { kind: "local", resolvedPaths: [hit] };
1672
- }
1673
- return {
1674
- kind: "unresolved",
1675
- resolvedPaths: [],
1676
- unresolvedAttempt: `${normalizeRelPath(candidateBase)}.py`
1677
- };
1678
- }
1679
- for (const name of imp.importedNames) {
1680
- if (name === "*") continue;
1681
- const candBase = targetDir ? `${targetDir}/${name}` : name;
1682
- const hit = tryModulePath(candBase);
1683
- if (hit && !resolved.includes(hit)) resolved.push(hit);
1684
- }
1685
- if (resolved.length > 0) {
1686
- return { kind: "local", resolvedPaths: resolved.sort(compareText) };
1687
- }
1688
- const initHit = lookupKnownFile(ctx, targetDir ? `${targetDir}/__init__.py` : "__init__.py");
1689
- if (initHit) {
1690
- return { kind: "local", resolvedPaths: [initHit] };
1691
- }
1692
- return {
1693
- kind: "unresolved",
1694
- resolvedPaths: [],
1695
- unresolvedAttempt: targetDir ? `${targetDir}/__init__.py` : "__init__.py"
1696
- };
1697
- }
1698
- const parts = spec.split(".").filter(Boolean);
1699
- if (parts.length === 0) {
1700
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
1701
- }
1702
- const modRel = parts.join("/");
1703
- const roots = ctx.pythonSourceRoots.length > 0 ? ctx.pythonSourceRoots : ["", "src"];
1704
- const extraRoots = [];
1705
- const fromSegments = normalizeRelPath(fromRelPath).split("/");
1706
- if ((fromSegments[0] === "packages" || fromSegments[0] === "apps") && fromSegments[1]) {
1707
- extraRoots.push(`${fromSegments[0]}/${fromSegments[1]}`);
1708
- extraRoots.push(`${fromSegments[0]}/${fromSegments[1]}/src`);
1709
- }
1710
- const allRoots = [.../* @__PURE__ */ new Set([...roots, ...extraRoots])];
1711
- for (const rootPrefix of allRoots) {
1712
- const base = rootPrefix ? `${rootPrefix}/${modRel}` : modRel;
1713
- const hit = tryModulePath(base);
1714
- if (hit) {
1715
- if (hit.endsWith("/__init__.py") && imp.importedNames.length > 0) {
1716
- const subHits = [];
1717
- for (const name of imp.importedNames) {
1718
- if (name === "*") continue;
1719
- const subHit = tryModulePath(`${base}/${name}`);
1720
- if (subHit && !subHits.includes(subHit)) subHits.push(subHit);
1721
- }
1722
- if (subHits.length > 0) {
1723
- return { kind: "local", resolvedPaths: subHits.sort(compareText) };
1724
- }
1725
- }
1726
- return { kind: "local", resolvedPaths: [hit] };
1727
- }
1728
- }
1729
- const topPkg = parts[0];
1730
- let localTopRoot = null;
1731
- for (const rootPrefix of allRoots) {
1732
- const pkgDirPrefix = rootPrefix ? `${rootPrefix}/${topPkg}/` : `${topPkg}/`;
1733
- const pkgFile = rootPrefix ? `${rootPrefix}/${topPkg}.py` : `${topPkg}.py`;
1734
- if (lookupKnownFile(ctx, pkgFile) || ctx.allRelativePaths.some((p) => p.startsWith(pkgDirPrefix) && p.endsWith(".py"))) {
1735
- localTopRoot = rootPrefix;
1736
- break;
1737
- }
1738
- }
1739
- if (localTopRoot !== null) {
1740
- const attempt = localTopRoot ? `${localTopRoot}/${modRel}.py` : `${modRel}.py`;
1741
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: normalizeRelPath(attempt) };
1742
- }
1743
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
1744
- }
1745
- function formatPythonImport(symbol, ctx) {
1746
- let modPath = normalizeRelPath(symbol.file);
1747
- const roots = (ctx?.pythonSourceRoots ?? ["src"]).filter(Boolean).sort((a, b) => b.length - a.length);
1748
- for (const rootPrefix of roots) {
1749
- const prefix = `${normalizeRelPath(rootPrefix)}/`;
1750
- if (modPath.startsWith(prefix)) {
1751
- modPath = modPath.slice(prefix.length);
1752
- break;
1753
- }
1754
- }
1755
- modPath = modPath.replace(/\/__init__\.py$/i, "").replace(/\.py$/i, "");
1756
- const dotted = modPath.split("/").filter(Boolean).join(".");
1757
- return `from ${dotted || "."} import ${symbol.name}`;
1758
- }
1759
- var pythonAdapter = {
1760
- id: "python",
1761
- extensions: [".py"],
1762
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
1763
- return parsePythonSource(source, relativePath, mtimeMs, size);
1764
- },
1765
- resolveImport: resolvePythonImport,
1766
- formatImportStatement(_fromRelPath, symbol, ctx) {
1767
- return formatPythonImport(symbol, ctx);
1768
- }
1769
- };
1770
- function formatGoParams(rawParams) {
1771
- const parts = splitTopLevelCommas(rawParams);
1772
- if (parts.length === 0) return "";
1773
- const parsed = [];
1774
- let pendingNames = [];
1775
- for (const part of parts) {
1776
- const tokens = collapseWs(part).split(" ");
1777
- if (tokens.length === 1) {
1778
- pendingNames.push(tokens[0]);
1779
- } else {
1780
- const name = tokens[0];
1781
- const type = tokens.slice(1).join(" ");
1782
- parsed.push({ names: [...pendingNames, name], type });
1783
- pendingNames = [];
1784
- }
1785
- }
1786
- if (pendingNames.length > 0) {
1787
- for (let idx = 0; idx < pendingNames.length; idx += 1) {
1788
- parsed.push({ names: [`p${idx}`], type: pendingNames[idx] });
1789
- }
1790
- }
1791
- return parsed.flatMap((group) => group.names.map((n) => `${n}: ${group.type}`)).join(", ");
1792
- }
1793
- function parseGoSource(source, relativePath, mtimeMs, size) {
1794
- const rel = normalizeRelPath(relativePath);
1795
- const contentSha256 = sha256Hex(source);
1796
- const imports = [];
1797
- const importSeen = /* @__PURE__ */ new Map();
1798
- const exportedSymbols = [];
1799
- const internalFunctions = [];
1800
- const noBlockComments = source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "));
1801
- const groupImportRe = /^\s*import\s*\(([\s\S]*?)\)/gm;
1802
- let gm;
1803
- while ((gm = groupImportRe.exec(noBlockComments)) !== null) {
1804
- const block = gm[1] ?? "";
1805
- for (const line of block.split(/\r?\n/)) {
1806
- const cleaned = line.replace(/\/\/.*$/, "").trim();
1807
- const specMatch = /^(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/.exec(cleaned);
1808
- if (specMatch && specMatch[2]) {
1809
- const alias = specMatch[1];
1810
- const pkgBase = path4.posix.basename(specMatch[2]);
1811
- pushUniqueImport(
1812
- imports,
1813
- importSeen,
1814
- specMatch[2],
1815
- alias && alias !== "_" && alias !== "." ? [alias] : [pkgBase],
1816
- false
1817
- );
1818
- }
1819
- }
1820
- }
1821
- const singleImportRe = /^\s*import\s+(?:([a-zA-Z0-9_.]+)\s+)?"([^"]+)"/gm;
1822
- let sm;
1823
- while ((sm = singleImportRe.exec(noBlockComments)) !== null) {
1824
- if (sm[2]) {
1825
- const alias = sm[1];
1826
- const pkgBase = path4.posix.basename(sm[2]);
1827
- pushUniqueImport(
1828
- imports,
1829
- importSeen,
1830
- sm[2],
1831
- alias && alias !== "_" && alias !== "." ? [alias] : [pkgBase],
1832
- false
1833
- );
1834
- }
1835
- }
1836
- const fnRe = /^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s*\(([^)]*)\)\s*([^{;\n]*)\{/gm;
1837
- let fm;
1838
- while ((fm = fnRe.exec(source)) !== null) {
1839
- const name = fm[1];
1840
- if (!name) continue;
1841
- const rawParams = fm[2] ?? "";
1842
- const rawRet = collapseWs(fm[3] ?? "");
1843
- const openBraceIdx = fm.index + fm[0].length - 1;
1844
- const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
1845
- const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
1846
- const formattedParams = formatGoParams(rawParams);
1847
- const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
1848
- const lineNum = lineOfOffset(source, fm.index);
1849
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
1850
- bodySource,
1851
- formattedParams,
1852
- { hashComments: false }
1853
- );
1854
- const isExported = /^[A-Z]/.test(name);
1855
- if (isExported) {
1856
- exportedSymbols.push({
1857
- name,
1858
- kind: "function",
1859
- signature,
1860
- line: lineNum,
1861
- structuralHash,
1862
- nodeCount,
1863
- astNodeCount,
1864
- file: rel,
1865
- isExported: true
1866
- });
1867
- } else {
1868
- internalFunctions.push({
1869
- name,
1870
- kind: "function",
1871
- signature,
1872
- line: lineNum,
1873
- structuralHash,
1874
- nodeCount,
1875
- astNodeCount,
1876
- file: rel,
1877
- isExported: false
1878
- });
1879
- }
1880
- }
1881
- const typeRe = /^type\s+([A-Z][a-zA-Z0-9_]*)(?:\[[^\]]*\])?\s+(struct|interface|[^\s{]+)/gm;
1882
- let tm;
1883
- while ((tm = typeRe.exec(source)) !== null) {
1884
- const name = tm[1];
1885
- const kindWord = tm[2];
1886
- if (!name || !kindWord) continue;
1887
- const kind = kindWord === "struct" ? "class" : kindWord === "interface" ? "interface" : "type";
1888
- exportedSymbols.push({
1889
- name,
1890
- kind,
1891
- signature: truncateSig(`type ${name} ${kindWord}`),
1892
- line: lineOfOffset(source, tm.index),
1893
- file: rel,
1894
- isExported: true
1895
- });
1896
- }
1897
- const constRe = /^(?:const|var)\s+([A-Z][a-zA-Z0-9_]*)\s*(?:([a-zA-Z0-9_.*\[\]]+)\s*)?=\s*([^\n]+)/gm;
1898
- let cm;
1899
- while ((cm = constRe.exec(source)) !== null) {
1900
- const name = cm[1];
1901
- if (!name) continue;
1902
- const typeAnn = cm[2]?.trim();
1903
- exportedSymbols.push({
1904
- name,
1905
- kind: "const",
1906
- signature: truncateSig(typeAnn ? `: ${typeAnn}` : "= <expr>", 80),
1907
- line: lineOfOffset(source, cm.index),
1908
- file: rel,
1909
- isExported: true
1910
- });
1911
- }
1912
- return {
1913
- relativePath: rel,
1914
- contentSha256,
1915
- language: "go",
1916
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
1917
- ...size !== void 0 ? { size } : {},
1918
- imports,
1919
- exportedSymbols,
1920
- internalFunctions
1921
- };
1922
- }
1923
- function resolveGoImport(imp, fromRelPath, ctx) {
1924
- const spec = imp.rawSpecifier.trim();
1925
- const fromNorm = normalizeRelPath(fromRelPath);
1926
- const modEntries = [...ctx.goModuleDirs.entries()].sort((a, b) => b[1].length - a[1].length);
1927
- if (modEntries.length === 0 && ctx.goModulePath) {
1928
- modEntries.push(["", ctx.goModulePath]);
1929
- }
1930
- for (const [modDir, modPath] of modEntries) {
1931
- if (spec === modPath || spec.startsWith(`${modPath}/`)) {
1932
- const subPkg = spec === modPath ? "" : spec.slice(modPath.length + 1);
1933
- const targetDir = normalizeRelPath(modDir ? subPkg ? `${modDir}/${subPkg}` : modDir : subPkg);
1934
- const matchedFiles = ctx.allRelativePaths.filter((p) => {
1935
- if (!p.endsWith(".go") || p.endsWith("_test.go")) return false;
1936
- if (p === fromNorm) return false;
1937
- const dir = path4.posix.dirname(p);
1938
- const dirNorm = dir === "." ? "" : dir;
1939
- return dirNorm === targetDir;
1940
- }).sort(compareText);
1941
- if (matchedFiles.length > 0) {
1942
- return { kind: "local", resolvedPaths: matchedFiles };
1943
- }
1944
- return {
1945
- kind: "unresolved",
1946
- resolvedPaths: [],
1947
- unresolvedAttempt: targetDir || spec
1948
- };
1949
- }
1950
- }
1951
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
1952
- }
1953
- function formatGoImport(symbol, ctx) {
1954
- const symDirRaw = path4.posix.dirname(normalizeRelPath(symbol.file));
1955
- const symDir = symDirRaw === "." ? "" : symDirRaw;
1956
- let importPath = symDir || ".";
1957
- if (ctx) {
1958
- const modEntries = [...ctx.goModuleDirs.entries()].sort((a, b) => b[0].length - a[0].length);
1959
- let matched = false;
1960
- for (const [modDir, modPath] of modEntries) {
1961
- if (!modDir) {
1962
- importPath = symDir ? `${modPath}/${symDir}` : modPath;
1963
- matched = true;
1964
- break;
1965
- }
1966
- if (symDir === modDir || symDir.startsWith(`${modDir}/`)) {
1967
- const sub = symDir.slice(modDir.length).replace(/^\//, "");
1968
- importPath = sub ? `${modPath}/${sub}` : modPath;
1969
- matched = true;
1970
- break;
1971
- }
1972
- }
1973
- if (!matched && ctx.goModulePath) {
1974
- importPath = symDir ? `${ctx.goModulePath}/${symDir}` : ctx.goModulePath;
1975
- }
1976
- }
1977
- const pkgAlias = path4.posix.basename(importPath);
1978
- return `import "${importPath}" // ${pkgAlias}.${symbol.name}`;
1979
- }
1980
- var goAdapter = {
1981
- id: "go",
1982
- extensions: [".go"],
1983
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
1984
- return parseGoSource(source, relativePath, mtimeMs, size);
1985
- },
1986
- resolveImport: resolveGoImport,
1987
- formatImportStatement(_fromRelPath, symbol, ctx) {
1988
- return formatGoImport(symbol, ctx);
1989
- }
1990
- };
1991
- function expandRustUseTree(tree) {
1992
- const cleaned = collapseWs(tree).replace(/;$/, "").trim();
1993
- const braceStart = cleaned.indexOf("{");
1994
- if (braceStart === -1) {
1995
- return [cleaned];
1996
- }
1997
- let depth = 0;
1998
- let braceEnd = -1;
1999
- for (let i = braceStart; i < cleaned.length; i += 1) {
2000
- if (cleaned[i] === "{") depth += 1;
2001
- else if (cleaned[i] === "}") {
2002
- depth -= 1;
2003
- if (depth === 0) {
2004
- braceEnd = i;
2005
- break;
2006
- }
2007
- }
2008
- }
2009
- if (braceEnd === -1) return [cleaned];
2010
- const prefix = cleaned.slice(0, braceStart).trim();
2011
- const inner = cleaned.slice(braceStart + 1, braceEnd);
2012
- const suffix = cleaned.slice(braceEnd + 1).trim();
2013
- const results = [];
2014
- for (const item of splitTopLevelCommas(inner)) {
2015
- const trimmedItem = item.trim();
2016
- if (!trimmedItem) continue;
2017
- if (trimmedItem === "self") {
2018
- results.push(prefix.replace(/::$/, ""));
2019
- } else {
2020
- const joined = `${prefix}${trimmedItem}${suffix}`;
2021
- results.push(...expandRustUseTree(joined));
2022
- }
2023
- }
2024
- return results;
2025
- }
2026
- function parseRustSource(source, relativePath, mtimeMs, size) {
2027
- const rel = normalizeRelPath(relativePath);
2028
- const contentSha256 = sha256Hex(source);
2029
- const imports = [];
2030
- const importSeen = /* @__PURE__ */ new Map();
2031
- const exportedSymbols = [];
2032
- const internalFunctions = [];
2033
- const stripped = source.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/\/\/[^\n]*/g, "");
2034
- const modRe = /^\s*(pub(?:\([^)]*\))?\s+)?mod\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*;/gm;
2035
- let mm;
2036
- while ((mm = modRe.exec(stripped)) !== null) {
2037
- if (mm[2]) {
2038
- pushUniqueImport(imports, importSeen, `mod::${mm[2]}`, [mm[2]], Boolean(mm[1]), false);
2039
- }
2040
- }
2041
- const useRe = /^\s*(pub(?:\([^)]*\))?\s+)?use\s+([\s\S]*?);/gm;
2042
- let um;
2043
- while ((um = useRe.exec(stripped)) !== null) {
2044
- const isPubUse = Boolean(um[1]);
2045
- const rawTree = um[2] ?? "";
2046
- for (const expanded of expandRustUseTree(rawTree)) {
2047
- const noAlias = expanded.replace(/\s+as\s+[a-zA-Z_][a-zA-Z0-9_]*$/, "").trim();
2048
- if (!noAlias) continue;
2049
- const segs = noAlias.split("::").filter(Boolean);
2050
- const lastSeg = segs[segs.length - 1] ?? "";
2051
- pushUniqueImport(
2052
- imports,
2053
- importSeen,
2054
- noAlias,
2055
- lastSeg && lastSeg !== "*" ? [lastSeg] : lastSeg === "*" ? ["*"] : [],
2056
- isPubUse,
2057
- false
2058
- );
2059
- }
2060
- }
2061
- 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;
2062
- let fm;
2063
- while ((fm = fnRe.exec(source)) !== null) {
2064
- const isPub = Boolean(fm[1]);
2065
- const name = fm[2];
2066
- if (!name) continue;
2067
- const isAsync = /\basync\s+fn\b/.test(fm[0]);
2068
- const rawParams = collapseWs(fm[3] ?? "");
2069
- const rawRet = collapseWs(fm[4] ?? "");
2070
- const openBraceIdx = fm.index + fm[0].length - 1;
2071
- const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
2072
- const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
2073
- const signature = truncateSig(
2074
- `${isAsync ? "async " : ""}(${rawParams})${rawRet ? `: ${rawRet}` : ""}`
2075
- );
2076
- const lineNum = lineOfOffset(source, fm.index);
2077
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2078
- bodySource,
2079
- rawParams,
2080
- { isAsync, hashComments: false }
2081
- );
2082
- if (isPub) {
2083
- exportedSymbols.push({
2084
- name,
2085
- kind: "function",
2086
- signature,
2087
- line: lineNum,
2088
- structuralHash,
2089
- nodeCount,
2090
- astNodeCount,
2091
- file: rel,
2092
- isExported: true
2093
- });
2094
- } else {
2095
- internalFunctions.push({
2096
- name,
2097
- kind: "function",
2098
- signature,
2099
- line: lineNum,
2100
- structuralHash,
2101
- nodeCount,
2102
- astNodeCount,
2103
- file: rel,
2104
- isExported: false
2105
- });
2106
- }
2107
- }
2108
- const itemRe = /^pub(?:\([^)]*\))?\s+(struct|enum|trait|type|const|static)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
2109
- let im;
2110
- while ((im = itemRe.exec(source)) !== null) {
2111
- const kw = im[1];
2112
- const name = im[2];
2113
- if (!kw || !name) continue;
2114
- const kind = kw === "struct" ? "class" : kw === "enum" ? "enum" : kw === "trait" ? "interface" : kw === "type" ? "type" : "const";
2115
- exportedSymbols.push({
2116
- name,
2117
- kind,
2118
- signature: `${kw} ${name}`,
2119
- line: lineOfOffset(source, im.index),
2120
- file: rel,
2121
- isExported: true
2122
- });
2123
- }
2124
- return {
2125
- relativePath: rel,
2126
- contentSha256,
2127
- language: "rust",
2128
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2129
- ...size !== void 0 ? { size } : {},
2130
- imports,
2131
- exportedSymbols,
2132
- internalFunctions
2133
- };
2134
- }
2135
- function findRustCrateForFile(relPath, ctx) {
2136
- const norm = normalizeRelPath(relPath);
2137
- if (ctx && ctx.rustCrates.length > 0) {
2138
- const sorted = [...ctx.rustCrates].sort((a, b) => b.srcDir.length - a.srcDir.length);
2139
- for (const crate of sorted) {
2140
- if (!crate.srcDir || norm === crate.srcDir || norm.startsWith(`${crate.srcDir}/`)) {
2141
- return crate;
2142
- }
2143
- if (!crate.crateDir || norm.startsWith(`${crate.crateDir}/`)) {
2144
- return crate;
2145
- }
2146
- }
2147
- }
2148
- const srcIdx = norm.indexOf("/src/");
2149
- if (srcIdx !== -1) {
2150
- return {
2151
- crateDir: norm.slice(0, srcIdx),
2152
- srcDir: `${norm.slice(0, srcIdx)}/src`
2153
- };
2154
- }
2155
- if (norm.startsWith("src/")) {
2156
- return { crateDir: "", srcDir: "src" };
2157
- }
2158
- return { crateDir: "", srcDir: "" };
2159
- }
2160
- function resolveRustImport(imp, fromRelPath, ctx) {
2161
- const spec = imp.rawSpecifier.trim();
2162
- const fromNorm = normalizeRelPath(fromRelPath);
2163
- const fromDirRaw = path4.posix.dirname(fromNorm);
2164
- const fromDir = fromDirRaw === "." ? "" : fromDirRaw;
2165
- const fromBase = path4.posix.basename(fromNorm);
2166
- const crate = findRustCrateForFile(fromNorm, ctx);
2167
- const tryRustModFile = (baseRel) => {
2168
- const clean = normalizeRelPath(baseRel);
2169
- return lookupKnownFile(ctx, `${clean}.rs`) ?? lookupKnownFile(ctx, `${clean}/mod.rs`);
2170
- };
2171
- if (spec.startsWith("mod::")) {
2172
- const modName = spec.slice("mod::".length);
2173
- const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
2174
- const searchBases = [];
2175
- if (isRootOrMod) {
2176
- searchBases.push(fromDir ? `${fromDir}/${modName}` : modName);
2177
- } else {
2178
- const stem = fromBase.replace(/\.rs$/, "");
2179
- searchBases.push(fromDir ? `${fromDir}/${stem}/${modName}` : `${stem}/${modName}`);
2180
- searchBases.push(fromDir ? `${fromDir}/${modName}` : modName);
2181
- }
2182
- for (const base of searchBases) {
2183
- const hit = tryRustModFile(base);
2184
- if (hit) return { kind: "local", resolvedPaths: [hit] };
2185
- }
2186
- const attempt = searchBases[0] ? `${normalizeRelPath(searchBases[0])}.rs` : `${modName}.rs`;
2187
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: attempt };
2188
- }
2189
- const segs = spec.split("::").filter(Boolean);
2190
- if (segs.length === 0) {
2191
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2192
- }
2193
- let baseDir = null;
2194
- let restSegs = [];
2195
- if (segs[0] === "crate") {
2196
- baseDir = crate.srcDir;
2197
- restSegs = segs.slice(1);
2198
- } else if (segs[0] === "self") {
2199
- const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
2200
- baseDir = isRootOrMod ? fromDir : normalizeRelPath(`${fromDir}/${fromBase.replace(/\.rs$/, "")}`);
2201
- restSegs = segs.slice(1);
2202
- } else if (segs[0] === "super") {
2203
- let currDir = fromDir;
2204
- const isRootOrMod = fromBase === "lib.rs" || fromBase === "main.rs" || fromBase === "mod.rs";
2205
- let idx = 0;
2206
- if (!isRootOrMod) {
2207
- idx = 1;
2208
- }
2209
- while (idx < segs.length && segs[idx] === "super") {
2210
- const parent = path4.posix.dirname(currDir);
2211
- currDir = parent === "." ? "" : parent;
2212
- idx += 1;
2213
- }
2214
- baseDir = currDir;
2215
- restSegs = segs.slice(idx);
2216
- } else {
2217
- const matchingCrate = ctx.rustCrates.find(
2218
- (c) => c.crateName && c.crateName.replace(/-/g, "_") === segs[0].replace(/-/g, "_")
2219
- );
2220
- if (matchingCrate) {
2221
- baseDir = matchingCrate.srcDir;
2222
- restSegs = segs.slice(1);
2223
- }
2224
- }
2225
- if (baseDir === null) {
2226
- const siblingBase = fromDir ? `${fromDir}/${segs[0]}` : segs[0];
2227
- const siblingHit = tryRustModFile(siblingBase);
2228
- if (siblingHit && siblingHit !== fromNorm) {
2229
- return { kind: "local", resolvedPaths: [siblingHit] };
2230
- }
2231
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2232
- }
2233
- const cleanSegs = restSegs.filter((s) => s !== "*");
2234
- const candidateLengths = [];
2235
- if (cleanSegs.length >= 1) candidateLengths.push(cleanSegs.length);
2236
- if (cleanSegs.length >= 2) candidateLengths.push(cleanSegs.length - 1);
2237
- if (cleanSegs.length >= 3 && /^[A-Z]/.test(cleanSegs[cleanSegs.length - 2] ?? "")) {
2238
- candidateLengths.push(cleanSegs.length - 2);
2239
- }
2240
- for (const len of candidateLengths) {
2241
- const sub = cleanSegs.slice(0, len).join("/");
2242
- const candidateBase = baseDir ? `${baseDir}/${sub}` : sub;
2243
- const hit = tryRustModFile(candidateBase);
2244
- if (hit && hit !== fromNorm) {
2245
- return { kind: "local", resolvedPaths: [hit] };
2246
- }
2247
- }
2248
- if (cleanSegs.length <= 1) {
2249
- 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");
2250
- if (fallbackRoot && fallbackRoot !== fromNorm) {
2251
- return { kind: "local", resolvedPaths: [fallbackRoot] };
2252
- }
2253
- }
2254
- 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`;
2255
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: attemptPath };
2256
- }
2257
- function formatRustImport(symbol, ctx) {
2258
- const norm = normalizeRelPath(symbol.file);
2259
- const crate = findRustCrateForFile(norm, ctx);
2260
- let relToSrc = norm;
2261
- if (crate.srcDir && relToSrc.startsWith(`${crate.srcDir}/`)) {
2262
- relToSrc = relToSrc.slice(crate.srcDir.length + 1);
2263
- }
2264
- relToSrc = relToSrc.replace(/\/mod\.rs$/i, "").replace(/^(?:lib|main)\.rs$/i, "").replace(/\.rs$/i, "");
2265
- const modSegs = relToSrc.split("/").filter(Boolean);
2266
- const prefix = modSegs.length > 0 ? `crate::${modSegs.join("::")}` : "crate";
2267
- return `use ${prefix}::${symbol.name};`;
2268
- }
2269
- var rustAdapter = {
2270
- id: "rust",
2271
- extensions: [".rs"],
2272
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2273
- return parseRustSource(source, relativePath, mtimeMs, size);
2274
- },
2275
- resolveImport: resolveRustImport,
2276
- formatImportStatement(_fromRelPath, symbol, ctx) {
2277
- return formatRustImport(symbol, ctx);
2278
- }
2279
- };
2280
- function createJvmAdapter(id, extensions) {
2281
- return {
2282
- id,
2283
- extensions,
2284
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2285
- const rel = normalizeRelPath(relativePath);
2286
- const contentSha256 = sha256Hex(source);
2287
- const imports = [];
2288
- const importSeen = /* @__PURE__ */ new Map();
2289
- const exportedSymbols = [];
2290
- const internalFunctions = [];
2291
- const impRe = /^\s*import\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.*]*)\s*;?/gm;
2292
- let im;
2293
- while ((im = impRe.exec(source)) !== null) {
2294
- const raw = im[1];
2295
- if (!raw) continue;
2296
- const lastDot = raw.lastIndexOf(".");
2297
- const symName = lastDot === -1 ? raw : raw.slice(lastDot + 1);
2298
- pushUniqueImport(imports, importSeen, raw, symName ? [symName] : [], false);
2299
- }
2300
- 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;
2301
- let tm;
2302
- while ((tm = typeRe.exec(source)) !== null) {
2303
- if (id === "java") {
2304
- const kw = tm[1];
2305
- const name = tm[2];
2306
- exportedSymbols.push({
2307
- name,
2308
- kind: kw === "interface" ? "interface" : kw === "enum" ? "enum" : "class",
2309
- signature: `${kw} ${name}`,
2310
- line: lineOfOffset(source, tm.index),
2311
- file: rel,
2312
- isExported: true
2313
- });
2314
- } else {
2315
- const vis = tm[1];
2316
- const kw = tm[2];
2317
- const name = tm[3];
2318
- if (vis === "private") continue;
2319
- exportedSymbols.push({
2320
- name,
2321
- kind: kw === "interface" ? "interface" : kw.startsWith("enum") ? "enum" : "class",
2322
- signature: `${kw} ${name}`,
2323
- line: lineOfOffset(source, tm.index),
2324
- file: rel,
2325
- isExported: true
2326
- });
2327
- }
2328
- }
2329
- 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;
2330
- let fm;
2331
- while ((fm = fnRe.exec(source)) !== null) {
2332
- const isJava = id === "java";
2333
- const vis = fm[1] ?? "public";
2334
- const name = isJava ? fm[3] : fm[2];
2335
- if (!name || name === "if" || name === "for" || name === "while" || name === "switch") continue;
2336
- const rawParams = collapseWs(isJava ? fm[4] ?? "" : fm[3] ?? "");
2337
- const rawRet = collapseWs(isJava ? fm[2] ?? "" : fm[4] ?? "");
2338
- const openBraceIdx = fm.index + fm[0].length - 1;
2339
- const closeBraceIdx = findMatchingBrace(source, openBraceIdx, false);
2340
- const bodySource = closeBraceIdx > openBraceIdx ? source.slice(openBraceIdx + 1, closeBraceIdx) : "";
2341
- const formattedParams = isJava ? splitTopLevelCommas(rawParams).map((p) => {
2342
- const toks = collapseWs(p).split(" ");
2343
- if (toks.length >= 2) {
2344
- const pName = toks[toks.length - 1];
2345
- const pType = toks.slice(0, -1).join(" ");
2346
- return `${pName}: ${pType}`;
2347
- }
2348
- return p;
2349
- }).join(", ") : rawParams;
2350
- const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
2351
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2352
- bodySource,
2353
- formattedParams
2354
- );
2355
- const lineNum = lineOfOffset(source, fm.index);
2356
- if (vis === "public" || vis === "") {
2357
- exportedSymbols.push({
2358
- name,
2359
- kind: "function",
2360
- signature,
2361
- line: lineNum,
2362
- structuralHash,
2363
- nodeCount,
2364
- astNodeCount,
2365
- file: rel,
2366
- isExported: true
2367
- });
2368
- } else {
2369
- internalFunctions.push({
2370
- name,
2371
- kind: "function",
2372
- signature,
2373
- line: lineNum,
2374
- structuralHash,
2375
- nodeCount,
2376
- astNodeCount,
2377
- file: rel,
2378
- isExported: false
2379
- });
2380
- }
2381
- }
2382
- return {
2383
- relativePath: rel,
2384
- contentSha256,
2385
- language: id,
2386
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2387
- ...size !== void 0 ? { size } : {},
2388
- imports,
2389
- exportedSymbols,
2390
- internalFunctions
2391
- };
2392
- },
2393
- resolveImport(imp, fromRelPath, ctx) {
2394
- const spec = imp.rawSpecifier.trim();
2395
- const fromNorm = normalizeRelPath(fromRelPath);
2396
- const isWildcard = spec.endsWith(".*");
2397
- const basePkg = isWildcard ? spec.slice(0, -2) : spec;
2398
- const slashPath = basePkg.replace(/\./g, "/");
2399
- if (isWildcard) {
2400
- const hits2 = ctx.allRelativePaths.filter(
2401
- (p) => p !== fromNorm && (p.endsWith(".java") || p.endsWith(".kt")) && (ctx.javaPackagesByFile.get(p) === basePkg || p.includes(`/${slashPath}/`))
2402
- ).sort(compareText);
2403
- if (hits2.length > 0) return { kind: "local", resolvedPaths: hits2 };
2404
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2405
- }
2406
- const lastDot = spec.lastIndexOf(".");
2407
- const pkg = lastDot === -1 ? "" : spec.slice(0, lastDot);
2408
- const cls = lastDot === -1 ? spec : spec.slice(lastDot + 1);
2409
- const hits = ctx.allRelativePaths.filter((p) => {
2410
- if (p === fromNorm) return false;
2411
- if (!p.endsWith(".java") && !p.endsWith(".kt")) return false;
2412
- if (p.endsWith(`/${slashPath}.java`) || p.endsWith(`/${slashPath}.kt`) || p === `${slashPath}.java` || p === `${slashPath}.kt`) {
2413
- return true;
2414
- }
2415
- const filePkg = ctx.javaPackagesByFile.get(p);
2416
- const stem = path4.posix.basename(p).replace(/\.(java|kt)$/, "");
2417
- return Boolean(filePkg && filePkg === pkg && stem === cls);
2418
- }).sort(compareText);
2419
- if (hits.length > 0) return { kind: "local", resolvedPaths: hits };
2420
- const knownPkgs = new Set(ctx.javaPackagesByFile.values());
2421
- if (pkg && knownPkgs.has(pkg)) {
2422
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: `${slashPath}.${id === "java" ? "java" : "kt"}` };
2423
- }
2424
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2425
- },
2426
- formatImportStatement(_fromRelPath, symbol, ctx) {
2427
- const pkg = ctx?.javaPackagesByFile.get(normalizeRelPath(symbol.file));
2428
- const full = pkg ? `${pkg}.${symbol.name}` : symbol.name;
2429
- return id === "java" ? `import ${full};` : `import ${full}`;
2430
- }
2431
- };
2432
- }
2433
- var javaAdapter = createJvmAdapter("java", [".java"]);
2434
- var kotlinAdapter = createJvmAdapter("kotlin", [".kt", ".kts"]);
2435
- var csharpAdapter = {
2436
- id: "csharp",
2437
- extensions: [".cs"],
2438
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2439
- const rel = normalizeRelPath(relativePath);
2440
- const contentSha256 = sha256Hex(source);
2441
- const imports = [];
2442
- const importSeen = /* @__PURE__ */ new Map();
2443
- const exportedSymbols = [];
2444
- const internalFunctions = [];
2445
- const usingRe = /^\s*(?:global\s+)?using\s+(?:static\s+)?([a-zA-Z_][a-zA-Z0-9_.]*)\s*;/gm;
2446
- let um;
2447
- while ((um = usingRe.exec(source)) !== null) {
2448
- if (um[1]) pushUniqueImport(imports, importSeen, um[1], [um[1]], false);
2449
- }
2450
- 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;
2451
- let tm;
2452
- while ((tm = typeRe.exec(source)) !== null) {
2453
- const kw = tm[1];
2454
- const name = tm[2];
2455
- exportedSymbols.push({
2456
- name,
2457
- kind: kw === "interface" ? "interface" : kw === "enum" ? "enum" : "class",
2458
- signature: `${kw} ${name}`,
2459
- line: lineOfOffset(source, tm.index),
2460
- file: rel,
2461
- isExported: true
2462
- });
2463
- }
2464
- 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;
2465
- let fm;
2466
- while ((fm = fnRe.exec(source)) !== null) {
2467
- const vis = fm[1];
2468
- const rawRet = collapseWs(fm[2] ?? "");
2469
- const name = fm[3];
2470
- const rawParams = collapseWs(fm[4] ?? "");
2471
- const openIdx = fm.index + fm[0].length - 1;
2472
- const closeIdx = findMatchingBrace(source, openIdx, false);
2473
- const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
2474
- const formattedParams = splitTopLevelCommas(rawParams).map((p) => {
2475
- const toks = collapseWs(p).split(" ");
2476
- return toks.length >= 2 ? `${toks[toks.length - 1]}: ${toks.slice(0, -1).join(" ")}` : p;
2477
- }).join(", ");
2478
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2479
- bodySource,
2480
- formattedParams
2481
- );
2482
- const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
2483
- const lineNum = lineOfOffset(source, fm.index);
2484
- if (vis === "public") {
2485
- exportedSymbols.push({
2486
- name,
2487
- kind: "function",
2488
- signature,
2489
- line: lineNum,
2490
- structuralHash,
2491
- nodeCount,
2492
- astNodeCount,
2493
- file: rel,
2494
- isExported: true
2495
- });
2496
- } else {
2497
- internalFunctions.push({
2498
- name,
2499
- kind: "function",
2500
- signature,
2501
- line: lineNum,
2502
- structuralHash,
2503
- nodeCount,
2504
- astNodeCount,
2505
- file: rel,
2506
- isExported: false
2507
- });
2508
- }
2509
- }
2510
- return {
2511
- relativePath: rel,
2512
- contentSha256,
2513
- language: "csharp",
2514
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2515
- ...size !== void 0 ? { size } : {},
2516
- imports,
2517
- exportedSymbols,
2518
- internalFunctions
2519
- };
2520
- },
2521
- resolveImport(imp, fromRelPath, ctx) {
2522
- const spec = imp.rawSpecifier.trim();
2523
- const fromNorm = normalizeRelPath(fromRelPath);
2524
- const hits = [];
2525
- for (const [fileRel, namespaces] of ctx.csharpNamespacesByFile.entries()) {
2526
- if (fileRel !== fromNorm && namespaces.includes(spec)) {
2527
- hits.push(fileRel);
2528
- }
2529
- }
2530
- if (hits.length > 0) return { kind: "local", resolvedPaths: hits.sort(compareText) };
2531
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2532
- },
2533
- formatImportStatement(_fromRelPath, symbol, ctx) {
2534
- const ns = ctx?.csharpNamespacesByFile.get(normalizeRelPath(symbol.file))?.[0];
2535
- return ns ? `using ${ns}; // ${symbol.name}` : `// ${symbol.name} in ${symbol.file}`;
2536
- }
2537
- };
2538
- var phpAdapter = {
2539
- id: "php",
2540
- extensions: [".php"],
2541
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2542
- const rel = normalizeRelPath(relativePath);
2543
- const contentSha256 = sha256Hex(source);
2544
- const imports = [];
2545
- const importSeen = /* @__PURE__ */ new Map();
2546
- const exportedSymbols = [];
2547
- const internalFunctions = [];
2548
- 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;
2549
- let um;
2550
- while ((um = useRe.exec(source)) !== null) {
2551
- if (um[1]) {
2552
- const clean = um[1].replace(/^\\/, "");
2553
- const parts = clean.split("\\");
2554
- pushUniqueImport(imports, importSeen, clean, [parts[parts.length - 1] ?? clean], false);
2555
- }
2556
- }
2557
- const reqRe = /\b(?:require|require_once|include|include_once)\s*\(?\s*['"]([^'"]+)['"]\s*\)?\s*;/g;
2558
- let rm;
2559
- while ((rm = reqRe.exec(source)) !== null) {
2560
- if (rm[1]) pushUniqueImport(imports, importSeen, rm[1], [], false);
2561
- }
2562
- const typeRe = /^\s*(?:final\s+|abstract\s+|readonly\s+)?(class|interface|trait|enum)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
2563
- let tm;
2564
- while ((tm = typeRe.exec(source)) !== null) {
2565
- const kw = tm[1];
2566
- const name = tm[2];
2567
- exportedSymbols.push({
2568
- name,
2569
- kind: kw === "interface" || kw === "trait" ? "interface" : kw === "enum" ? "enum" : "class",
2570
- signature: `${kw} ${name}`,
2571
- line: lineOfOffset(source, tm.index),
2572
- file: rel,
2573
- isExported: true
2574
- });
2575
- }
2576
- const fnRe = /^\s*(?:(public|private|protected)\s+)?(?:static\s+)?function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)\)\s*(?::\s*([^{\n]+))?\s*\{/gm;
2577
- let fm;
2578
- while ((fm = fnRe.exec(source)) !== null) {
2579
- const vis = fm[1] ?? "public";
2580
- const name = fm[2];
2581
- const rawParams = collapseWs(fm[3] ?? "");
2582
- const rawRet = collapseWs(fm[4] ?? "");
2583
- const openIdx = fm.index + fm[0].length - 1;
2584
- const closeIdx = findMatchingBrace(source, openIdx, true);
2585
- const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
2586
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2587
- bodySource,
2588
- rawParams,
2589
- { hashComments: true }
2590
- );
2591
- const signature = truncateSig(`(${rawParams})${rawRet ? `: ${rawRet}` : ""}`);
2592
- const lineNum = lineOfOffset(source, fm.index);
2593
- if (vis === "public") {
2594
- exportedSymbols.push({
2595
- name,
2596
- kind: "function",
2597
- signature,
2598
- line: lineNum,
2599
- structuralHash,
2600
- nodeCount,
2601
- astNodeCount,
2602
- file: rel,
2603
- isExported: true
2604
- });
2605
- } else {
2606
- internalFunctions.push({
2607
- name,
2608
- kind: "function",
2609
- signature,
2610
- line: lineNum,
2611
- structuralHash,
2612
- nodeCount,
2613
- astNodeCount,
2614
- file: rel,
2615
- isExported: false
2616
- });
2617
- }
2618
- }
2619
- return {
2620
- relativePath: rel,
2621
- contentSha256,
2622
- language: "php",
2623
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2624
- ...size !== void 0 ? { size } : {},
2625
- imports,
2626
- exportedSymbols,
2627
- internalFunctions
2628
- };
2629
- },
2630
- resolveImport(imp, fromRelPath, ctx) {
2631
- const spec = imp.rawSpecifier.trim();
2632
- const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
2633
- if (spec.startsWith("./") || spec.startsWith("../") || spec.endsWith(".php")) {
2634
- const cand = path4.posix.normalize(path4.posix.join(fromDir, spec));
2635
- const hit = lookupKnownFile(ctx, cand) ?? lookupKnownFile(ctx, spec);
2636
- if (hit) return { kind: "local", resolvedPaths: [hit] };
2637
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: cand };
2638
- }
2639
- const normalizedSpec = spec.replace(/^\\/, "");
2640
- const sorted = [...ctx.phpPsr4Mappings].sort((a, b) => b.prefix.length - a.prefix.length);
2641
- for (const mapping of sorted) {
2642
- if (normalizedSpec.startsWith(mapping.prefix)) {
2643
- const rest = normalizedSpec.slice(mapping.prefix.length).replace(/\\/g, "/");
2644
- const cand = normalizeRelPath(`${mapping.dir}/${rest}.php`);
2645
- const hit = lookupKnownFile(ctx, cand);
2646
- if (hit) return { kind: "local", resolvedPaths: [hit] };
2647
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: cand };
2648
- }
2649
- }
2650
- const directHit = lookupKnownFile(ctx, `${normalizedSpec.replace(/\\/g, "/")}.php`);
2651
- if (directHit) return { kind: "local", resolvedPaths: [directHit] };
2652
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2653
- },
2654
- formatImportStatement(_fromRelPath, symbol, ctx) {
2655
- const ns = ctx?.phpNamespacesByFile.get(normalizeRelPath(symbol.file));
2656
- return ns ? `use ${ns}\\${symbol.name};` : `require_once '${symbol.file}'; // ${symbol.name}`;
2657
- }
2658
- };
2659
- var rubyAdapter = {
2660
- id: "ruby",
2661
- extensions: [".rb"],
2662
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2663
- const rel = normalizeRelPath(relativePath);
2664
- const contentSha256 = sha256Hex(source);
2665
- const imports = [];
2666
- const importSeen = /* @__PURE__ */ new Map();
2667
- const exportedSymbols = [];
2668
- const internalFunctions = [];
2669
- const lines = source.split(/\r?\n/);
2670
- let inPrivateSection = false;
2671
- for (let i = 0; i < lines.length; i += 1) {
2672
- const line = lines[i];
2673
- const trimmed = line.trim();
2674
- if (!trimmed || trimmed.startsWith("#")) continue;
2675
- if (trimmed === "private") {
2676
- inPrivateSection = true;
2677
- continue;
2678
- }
2679
- if (trimmed === "public") {
2680
- inPrivateSection = false;
2681
- continue;
2682
- }
2683
- const reqRel = /^require_relative\s+['"]([^'"]+)['"]/.exec(trimmed);
2684
- if (reqRel && reqRel[1]) {
2685
- pushUniqueImport(imports, importSeen, `rel:${reqRel[1]}`, [], false);
2686
- continue;
2687
- }
2688
- const req = /^require\s+['"]([^'"]+)['"]/.exec(trimmed);
2689
- if (req && req[1]) {
2690
- pushUniqueImport(imports, importSeen, req[1], [], false);
2691
- continue;
2692
- }
2693
- const clsMod = /^(class|module)\s+([A-Z][a-zA-Z0-9_:]*)/.exec(trimmed);
2694
- if (clsMod && clsMod[1] && clsMod[2]) {
2695
- inPrivateSection = false;
2696
- exportedSymbols.push({
2697
- name: clsMod[2],
2698
- kind: "class",
2699
- signature: `${clsMod[1]} ${clsMod[2]}`,
2700
- line: i + 1,
2701
- file: rel,
2702
- isExported: true
2703
- });
2704
- continue;
2705
- }
2706
- const defMatch = /^(\s*)def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_!?]*)(?:\(([^)]*)\))?/.exec(line);
2707
- if (defMatch && defMatch[2]) {
2708
- const baseIndent = (defMatch[1] ?? "").length;
2709
- const name = defMatch[2];
2710
- const rawParams = collapseWs(defMatch[3] ?? "");
2711
- const bodyLines = [];
2712
- let j = i + 1;
2713
- while (j < lines.length) {
2714
- const jl = lines[j];
2715
- const jIndent = jl.length - jl.trimStart().length;
2716
- if (jl.trim() === "end" && jIndent <= baseIndent) {
2717
- break;
2718
- }
2719
- bodyLines.push(jl);
2720
- j += 1;
2721
- }
2722
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2723
- bodyLines.join("\n"),
2724
- rawParams,
2725
- { hashComments: true }
2726
- );
2727
- const signature = truncateSig(`(${rawParams})`);
2728
- if (!inPrivateSection && !name.startsWith("_")) {
2729
- exportedSymbols.push({
2730
- name,
2731
- kind: "function",
2732
- signature,
2733
- line: i + 1,
2734
- structuralHash,
2735
- nodeCount,
2736
- astNodeCount,
2737
- file: rel,
2738
- isExported: true
2739
- });
2740
- } else {
2741
- internalFunctions.push({
2742
- name,
2743
- kind: "function",
2744
- signature,
2745
- line: i + 1,
2746
- structuralHash,
2747
- nodeCount,
2748
- astNodeCount,
2749
- file: rel,
2750
- isExported: false
2751
- });
2752
- }
2753
- i = j;
2754
- }
2755
- }
2756
- return {
2757
- relativePath: rel,
2758
- contentSha256,
2759
- language: "ruby",
2760
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2761
- ...size !== void 0 ? { size } : {},
2762
- imports,
2763
- exportedSymbols,
2764
- internalFunctions
2765
- };
2766
- },
2767
- resolveImport(imp, fromRelPath, ctx) {
2768
- const spec = imp.rawSpecifier.trim();
2769
- const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
2770
- if (spec.startsWith("rel:")) {
2771
- const target = spec.slice(4);
2772
- const base = path4.posix.normalize(path4.posix.join(fromDir, target));
2773
- const hit = lookupKnownFile(ctx, base) ?? lookupKnownFile(ctx, `${base}.rb`);
2774
- if (hit) return { kind: "local", resolvedPaths: [hit] };
2775
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: base.endsWith(".rb") ? base : `${base}.rb` };
2776
- }
2777
- const libHit = lookupKnownFile(ctx, `lib/${spec}.rb`) ?? lookupKnownFile(ctx, `lib/${spec}`) ?? lookupKnownFile(ctx, `${spec}.rb`);
2778
- if (libHit) return { kind: "local", resolvedPaths: [libHit] };
2779
- return { kind: "external", resolvedPaths: [], externalLabel: spec };
2780
- },
2781
- formatImportStatement(fromRelPath, symbol) {
2782
- const fromDir = fromRelPath ? path4.posix.dirname(normalizeRelPath(fromRelPath)) : ".";
2783
- const rel = path4.posix.relative(fromDir, normalizeRelPath(symbol.file)).replace(/\.rb$/i, "");
2784
- const spec = rel.startsWith(".") ? rel : `./${rel}`;
2785
- return `require_relative '${spec}' # ${symbol.name}`;
2786
- }
2787
- };
2788
- var cppAdapter = {
2789
- id: "cpp",
2790
- extensions: [".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"],
2791
- extractManifest(source, _absolutePath, relativePath, mtimeMs, size) {
2792
- const rel = normalizeRelPath(relativePath);
2793
- const contentSha256 = sha256Hex(source);
2794
- const imports = [];
2795
- const importSeen = /* @__PURE__ */ new Map();
2796
- const exportedSymbols = [];
2797
- const internalFunctions = [];
2798
- const incRe = /^\s*#include\s*(?:"([^"]+)"|<([^>]+)>)/gm;
2799
- let im;
2800
- while ((im = incRe.exec(source)) !== null) {
2801
- if (im[1]) pushUniqueImport(imports, importSeen, `"${im[1]}"`, [], false);
2802
- else if (im[2]) pushUniqueImport(imports, importSeen, `<${im[2]}>`, [], false);
2803
- }
2804
- const typeRe = /^\s*(?:typedef\s+)?(struct|class|enum(?:\s+class)?)\s+([a-zA-Z_][a-zA-Z0-9_]*)/gm;
2805
- let tm;
2806
- while ((tm = typeRe.exec(source)) !== null) {
2807
- const kw = tm[1];
2808
- const name = tm[2];
2809
- exportedSymbols.push({
2810
- name,
2811
- kind: kw.startsWith("enum") ? "enum" : "class",
2812
- signature: `${kw} ${name}`,
2813
- line: lineOfOffset(source, tm.index),
2814
- file: rel,
2815
- isExported: true
2816
- });
2817
- }
2818
- 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;
2819
- let fm;
2820
- while ((fm = fnRe.exec(source)) !== null) {
2821
- const isStatic = Boolean(fm[1]);
2822
- const rawRet = collapseWs(fm[2] ?? "");
2823
- const name = fm[3];
2824
- if (["if", "for", "while", "switch", "catch", "namespace"].includes(name)) continue;
2825
- const rawParams = collapseWs(fm[4] ?? "");
2826
- const openIdx = fm.index + fm[0].length - 1;
2827
- const closeIdx = findMatchingBrace(source, openIdx, false);
2828
- const bodySource = closeIdx > openIdx ? source.slice(openIdx + 1, closeIdx) : "";
2829
- const formattedParams = splitTopLevelCommas(rawParams).map((p) => {
2830
- const toks = collapseWs(p).split(" ");
2831
- return toks.length >= 2 ? `${toks[toks.length - 1].replace(/^[*&]+/, "")}: ${toks.slice(0, -1).join(" ")}` : p;
2832
- }).join(", ");
2833
- const { structuralHash, nodeCount, astNodeCount } = computePolyglotStructuralHash(
2834
- bodySource,
2835
- formattedParams
2836
- );
2837
- const signature = truncateSig(`(${formattedParams})${rawRet ? `: ${rawRet}` : ""}`);
2838
- const lineNum = lineOfOffset(source, fm.index);
2839
- if (!isStatic) {
2840
- exportedSymbols.push({
2841
- name,
2842
- kind: "function",
2843
- signature,
2844
- line: lineNum,
2845
- structuralHash,
2846
- nodeCount,
2847
- astNodeCount,
2848
- file: rel,
2849
- isExported: true
2850
- });
2851
- } else {
2852
- internalFunctions.push({
2853
- name,
2854
- kind: "function",
2855
- signature,
2856
- line: lineNum,
2857
- structuralHash,
2858
- nodeCount,
2859
- astNodeCount,
2860
- file: rel,
2861
- isExported: false
2862
- });
2863
- }
2864
- }
2865
- return {
2866
- relativePath: rel,
2867
- contentSha256,
2868
- language: "cpp",
2869
- ...mtimeMs !== void 0 ? { mtimeMs } : {},
2870
- ...size !== void 0 ? { size } : {},
2871
- imports,
2872
- exportedSymbols,
2873
- internalFunctions
2874
- };
2875
- },
2876
- resolveImport(imp, fromRelPath, ctx) {
2877
- const spec = imp.rawSpecifier.trim();
2878
- const fromDir = path4.posix.dirname(normalizeRelPath(fromRelPath));
2879
- const isQuoted = spec.startsWith('"') && spec.endsWith('"');
2880
- const clean = spec.replace(/^["<]|[">]$/g, "");
2881
- if (isQuoted) {
2882
- const localCand = path4.posix.normalize(path4.posix.join(fromDir, clean));
2883
- const hit = lookupKnownFile(ctx, localCand) ?? lookupKnownFile(ctx, `include/${clean}`) ?? lookupKnownFile(ctx, `src/${clean}`) ?? lookupKnownFile(ctx, clean);
2884
- if (hit) return { kind: "local", resolvedPaths: [hit] };
2885
- return { kind: "unresolved", resolvedPaths: [], unresolvedAttempt: localCand };
2886
- }
2887
- const incHit = lookupKnownFile(ctx, `include/${clean}`);
2888
- if (incHit) return { kind: "local", resolvedPaths: [incHit] };
2889
- return { kind: "external", resolvedPaths: [], externalLabel: clean };
2890
- },
2891
- formatImportStatement(fromRelPath, symbol) {
2892
- const target = normalizeRelPath(symbol.file);
2893
- if (fromRelPath) {
2894
- const rel = path4.posix.relative(path4.posix.dirname(normalizeRelPath(fromRelPath)), target);
2895
- return `#include "${rel}" // ${symbol.name}`;
2896
- }
2897
- return `#include "${target}" // ${symbol.name}`;
2898
- }
2899
- };
2900
- var PolyglotAdapterRegistry = class {
2901
- byExtension = /* @__PURE__ */ new Map();
2902
- byId = /* @__PURE__ */ new Map();
2903
- constructor(adapters) {
2904
- for (const adapter of adapters) {
2905
- this.register(adapter);
2906
- }
2907
- }
2908
- register(adapter) {
2909
- this.byId.set(adapter.id, adapter);
2910
- for (const ext of adapter.extensions) {
2911
- this.byExtension.set(ext.toLowerCase(), adapter);
2912
- }
2913
- }
2914
- get supportedExtensions() {
2915
- return [...this.byExtension.keys()];
2916
- }
2917
- detectLanguage(filePath) {
2918
- const ext = path4.extname(filePath).toLowerCase();
2919
- return this.byExtension.get(ext)?.id ?? "unknown";
2920
- }
2921
- getAdapterForFile(filePath) {
2922
- const ext = path4.extname(filePath).toLowerCase();
2923
- return this.byExtension.get(ext);
2924
- }
2925
- getAdapterById(id) {
2926
- return this.byId.get(id);
2927
- }
2928
- extractManifest(source, absolutePath, relativePath, mtimeMs, size) {
2929
- const adapter = this.getAdapterForFile(absolutePath) ?? this.getAdapterForFile(relativePath);
2930
- if (adapter) {
2931
- return adapter.extractManifest(source, absolutePath, relativePath, mtimeMs, size);
2932
- }
2933
- return extractFileAstManifest(source, absolutePath, relativePath, mtimeMs, size);
2934
- }
2935
- formatImportForSymbol(fromRelPath, symbol, ctx) {
2936
- const adapter = this.getAdapterForFile(symbol.file);
2937
- if (adapter) {
2938
- return adapter.formatImportStatement(fromRelPath, symbol, ctx);
2939
- }
2940
- return formatJsTsImport(fromRelPath, symbol);
2941
- }
2942
- areLanguagesCompatible(fileA, fileB) {
2943
- const langA = this.detectLanguage(fileA);
2944
- const langB = this.detectLanguage(fileB);
2945
- if (langA === langB) return true;
2946
- const jsTs = /* @__PURE__ */ new Set(["typescript", "javascript"]);
2947
- if (jsTs.has(langA) && jsTs.has(langB)) return true;
2948
- const jvm = /* @__PURE__ */ new Set(["java", "kotlin"]);
2949
- if (jvm.has(langA) && jvm.has(langB)) return true;
2950
- return false;
2951
- }
2952
- };
2953
- var defaultPolyglotRegistry = new PolyglotAdapterRegistry([
2954
- createJsTsAdapter("typescript", [".ts", ".tsx", ".mts", ".cts"]),
2955
- createJsTsAdapter("javascript", [".js", ".jsx", ".mjs", ".cjs"]),
2956
- pythonAdapter,
2957
- goAdapter,
2958
- rustAdapter,
2959
- javaAdapter,
2960
- kotlinAdapter,
2961
- csharpAdapter,
2962
- phpAdapter,
2963
- rubyAdapter,
2964
- cppAdapter
2965
- ]);
2966
- function safeReadUtf8(filePath) {
2967
- try {
2968
- return existsSync2(filePath) ? readFileSync2(filePath, "utf8") : null;
2969
- } catch {
2970
- return null;
2971
- }
2972
- }
2973
- function buildWorkspaceResolutionContext(root, rootReal, allRelativePaths, configFileRelPaths = []) {
2974
- const knownFiles = /* @__PURE__ */ new Map();
2975
- const sortedPaths = [...new Set(allRelativePaths.map(normalizeRelPath))].sort(compareText);
2976
- for (const rel of sortedPaths) {
2977
- knownFiles.set(rel, rel);
2978
- knownFiles.set(rel.toLowerCase(), rel);
2979
- }
2980
- const goModuleDirs = /* @__PURE__ */ new Map();
2981
- const pythonSourceRoots = /* @__PURE__ */ new Set([""]);
2982
- const rustCrates = [];
2983
- const phpPsr4Mappings = [];
2984
- const javaPackagesByFile = /* @__PURE__ */ new Map();
2985
- const csharpNamespacesByFile = /* @__PURE__ */ new Map();
2986
- const phpNamespacesByFile = /* @__PURE__ */ new Map();
2987
- if (sortedPaths.some((p) => p.startsWith("src/"))) {
2988
- pythonSourceRoots.add("src");
2989
- }
2990
- const inspectConfigRel = (relPath) => {
2991
- const norm = normalizeRelPath(relPath);
2992
- const base = path4.posix.basename(norm).toLowerCase();
2993
- const dirRaw = path4.posix.dirname(norm);
2994
- const dir = dirRaw === "." ? "" : dirRaw;
2995
- const raw = safeReadUtf8(path4.join(rootReal, norm));
2996
- if (!raw) return;
2997
- if (base === "go.mod") {
2998
- const m = /^\s*module\s+([^\s/]+(?:\/[^\s/]+)*)/m.exec(raw);
2999
- if (m && m[1]) {
3000
- goModuleDirs.set(dir, m[1].trim().replace(/^"|"$/g, ""));
3001
- }
3002
- } else if (base === "cargo.toml") {
3003
- const pkgSection = /\[package\]([\s\S]*?)(?:\n\[|$)/.exec(raw)?.[1] ?? raw;
3004
- const nameMatch = /^\s*name\s*=\s*["']([^"']+)["']/m.exec(pkgSection);
3005
- const srcDir = dir ? `${dir}/src` : "src";
3006
- const hasSrc = sortedPaths.some((p) => p.startsWith(`${srcDir}/`));
3007
- rustCrates.push({
3008
- crateDir: dir,
3009
- srcDir: hasSrc ? srcDir : dir,
3010
- ...nameMatch?.[1] ? { crateName: nameMatch[1] } : {}
3011
- });
3012
- } else if (base === "pyproject.toml") {
3013
- if (dir) pythonSourceRoots.add(dir);
3014
- const srcCandidate = dir ? `${dir}/src` : "src";
3015
- if (sortedPaths.some((p) => p.startsWith(`${srcCandidate}/`))) {
3016
- pythonSourceRoots.add(srcCandidate);
3017
- }
3018
- const whereMatch = /where\s*=\s*\[([^\]]+)\]/.exec(raw);
3019
- if (whereMatch && whereMatch[1]) {
3020
- const strRe = /["']([^"']+)["']/g;
3021
- let sm;
3022
- while ((sm = strRe.exec(whereMatch[1])) !== null) {
3023
- if (sm[1]) {
3024
- const p = normalizeRelPath(dir ? `${dir}/${sm[1]}` : sm[1]);
3025
- pythonSourceRoots.add(p === "." ? "" : p);
3026
- }
3027
- }
3028
- }
3029
- const pkgDirMatch = /package-dir\s*=\s*\{[^}]*["']\s*["']\s*[:=]\s*["']([^"']+)["']/.exec(raw);
3030
- if (pkgDirMatch && pkgDirMatch[1]) {
3031
- const p = normalizeRelPath(dir ? `${dir}/${pkgDirMatch[1]}` : pkgDirMatch[1]);
3032
- pythonSourceRoots.add(p === "." ? "" : p);
3033
- }
3034
- } else if (base === "composer.json") {
3035
- try {
3036
- const json = JSON.parse(raw);
3037
- const psr4Maps = [json.autoload?.["psr-4"], json["autoload-dev"]?.["psr-4"]];
3038
- for (const mapObj of psr4Maps) {
3039
- if (!mapObj || typeof mapObj !== "object") continue;
3040
- for (const [prefix, target] of Object.entries(mapObj)) {
3041
- const targets = Array.isArray(target) ? target : [target];
3042
- for (const t of targets) {
3043
- if (typeof t !== "string") continue;
3044
- const resolvedDir = normalizeRelPath(dir ? `${dir}/${t}` : t).replace(/\/$/, "");
3045
- phpPsr4Mappings.push({ prefix, dir: resolvedDir });
3046
- }
3047
- }
3048
- }
3049
- } catch {
3050
- }
3051
- }
3052
- };
3053
- for (const cfg of configFileRelPaths) {
3054
- inspectConfigRel(cfg);
3055
- }
3056
- for (const rootCfg of ["go.mod", "Cargo.toml", "pyproject.toml", "composer.json"]) {
3057
- if (!configFileRelPaths.includes(rootCfg)) {
3058
- inspectConfigRel(rootCfg);
3059
- }
3060
- }
3061
- for (const rel of sortedPaths) {
3062
- const ext = path4.posix.extname(rel).toLowerCase();
3063
- if (ext === ".java" || ext === ".kt" || ext === ".kts") {
3064
- const content = safeReadUtf8(path4.join(rootReal, rel));
3065
- if (content) {
3066
- const pm = /^\s*package\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*;?/m.exec(content);
3067
- if (pm && pm[1]) javaPackagesByFile.set(rel, pm[1]);
3068
- }
3069
- } else if (ext === ".cs") {
3070
- const content = safeReadUtf8(path4.join(rootReal, rel));
3071
- if (content) {
3072
- const nsList = [];
3073
- const nsRe = /^\s*namespace\s+([a-zA-Z_][a-zA-Z0-9_.]*)\s*[;{]/gm;
3074
- let nm;
3075
- while ((nm = nsRe.exec(content)) !== null) {
3076
- if (nm[1]) nsList.push(nm[1]);
3077
- }
3078
- if (nsList.length > 0) csharpNamespacesByFile.set(rel, nsList);
3079
- }
3080
- } else if (ext === ".php") {
3081
- const content = safeReadUtf8(path4.join(rootReal, rel));
3082
- if (content) {
3083
- const nm = /^\s*namespace\s+([a-zA-Z_\\][a-zA-Z0-9_\\]*)\s*[;{]/m.exec(content);
3084
- if (nm && nm[1]) phpNamespacesByFile.set(rel, nm[1].replace(/^\\/, ""));
3085
- }
3086
- }
3087
- }
3088
- const goModulePath = goModuleDirs.get("") ?? [...goModuleDirs.values()][0];
3089
- return {
3090
- root: toPosix(root),
3091
- rootReal: toPosix(rootReal),
3092
- knownFiles,
3093
- allRelativePaths: sortedPaths,
3094
- ...goModulePath ? { goModulePath } : {},
3095
- goModuleDirs,
3096
- pythonSourceRoots: [...pythonSourceRoots],
3097
- rustCrates,
3098
- phpPsr4Mappings,
3099
- javaPackagesByFile,
3100
- csharpNamespacesByFile,
3101
- phpNamespacesByFile
3102
- };
3103
- }
3104
-
3105
- // ../engine/src/indexer.ts
3106
- var SOURCE_EXTENSIONS = new Set(defaultPolyglotRegistry.supportedExtensions);
3107
- var NON_CODE_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
3108
- ".css",
3109
- ".scss",
3110
- ".less",
3111
- ".svg",
3112
- ".png",
3113
- ".jpg",
3114
- ".jpeg",
3115
- ".webp",
3116
- ".gif",
3117
- ".ico",
3118
- ".woff",
3119
- ".woff2",
3120
- ".ttf",
3121
- ".wasm",
3122
- ".json",
3123
- ".glsl",
3124
- ".sql",
3125
- ".txt",
3126
- ".md"
3127
- ]);
3128
- function stripImportQueryAndHash(specifier) {
3129
- const trimmed = specifier.trim();
3130
- const qIdx = trimmed.indexOf("?");
3131
- const hIdx = trimmed.indexOf("#");
3132
- let cut = trimmed.length;
3133
- if (qIdx !== -1 && qIdx < cut) cut = qIdx;
3134
- if (hIdx !== -1 && hIdx < cut) cut = hIdx;
3135
- return trimmed.slice(0, cut);
3136
- }
3137
- function isRelativeImportSpecifier(specifier) {
3138
- const clean = stripImportQueryAndHash(specifier);
3139
- return clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
3140
- }
3141
- function isNonCodeAssetSpecifier(specifier) {
3142
- const clean = stripImportQueryAndHash(specifier);
3143
- const ext = path5.posix.extname(clean).toLowerCase();
3144
- return ext.length > 0 && NON_CODE_ASSET_EXTENSIONS.has(ext) && !SOURCE_EXTENSIONS.has(ext);
3145
- }
3146
- var SKIP_DIRS = /* @__PURE__ */ new Set([
3147
- "node_modules",
3148
- ".git",
3149
- ".hg",
3150
- ".svn",
3151
- "dist",
3152
- "build",
3153
- "out",
3154
- "coverage",
3155
- ".next",
3156
- ".nuxt",
3157
- ".turbo",
3158
- ".cache",
3159
- ".tipolink",
3160
- ".interlink",
3161
- ".chuze",
3162
- // Harness vaults hold pre-edit copies of source files; indexing them creates
3163
- // phantom callers, false unresolved-import reports, and bogus duplicate helpers.
3164
- ".moriko",
3165
- // Polyglot build, cache, and virtual environment directories
3166
- "__pycache__",
3167
- ".venv",
3168
- "venv",
3169
- ".pytest_cache",
3170
- ".mypy_cache",
3171
- ".ruff_cache",
3172
- "target",
3173
- "vendor",
3174
- ".gradle",
3175
- ".tox"
3176
- ]);
3177
- var NODE_BUILTINS = new Set(builtinModules);
3178
- var EXT_SWAPS = {
3179
- ".js": [".ts", ".tsx", ".js", ".jsx"],
3180
- ".jsx": [".tsx", ".jsx", ".ts", ".js"],
3181
- ".mjs": [".mts", ".mjs"],
3182
- ".cjs": [".cts", ".cjs"]
3183
- };
3184
- var RESOLVE_SUFFIXES = [
3185
- ".ts",
3186
- ".tsx",
3187
- ".mts",
3188
- ".cts",
3189
- ".js",
3190
- ".jsx",
3191
- ".mjs",
3192
- ".cjs",
3193
- "/index.ts",
3194
- "/index.tsx",
3195
- "/index.mts",
3196
- "/index.cts",
3197
- "/index.js",
3198
- "/index.jsx",
3199
- "/index.mjs",
3200
- "/index.cjs"
3201
- ];
3202
- var TSCONFIG_NAME = /^tsconfig(\..+)?\.json$/i;
3203
- var POLYGLOT_CONFIG_NAMES = /* @__PURE__ */ new Set(["go.mod", "cargo.toml", "pyproject.toml", "composer.json"]);
3204
- var TS_NO_INPUTS_CODE = 18003;
3205
- function errorMessage(error) {
3206
- return error instanceof Error ? error.message : String(error);
3207
- }
3208
- function errnoCode(error) {
3209
- if (error instanceof Error && "code" in error && typeof error.code === "string") {
3210
- return error.code;
3211
- }
3212
- return void 0;
3213
- }
3214
- function statOrNull(absolute) {
3215
- try {
3216
- return statSync(absolute);
3217
- } catch (error) {
3218
- const code = errnoCode(error);
3219
- if (code === "ENOENT" || code === "ENOTDIR") return null;
3220
- throw error;
3221
- }
3222
- }
3223
- function isFile(absolute) {
3224
- const stats = statOrNull(absolute);
3225
- return stats !== null && stats.isFile();
3226
- }
3227
- function fileId(absolute) {
3228
- const resolved = path5.resolve(absolute);
3229
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
3230
- }
3231
- function isAncestorDir(dir, file) {
3232
- const rel = path5.relative(dir, file);
3233
- return rel !== "" && !rel.startsWith("..") && !path5.isAbsolute(rel);
3234
- }
3235
- function walkWorkspace(root, notes) {
3236
- const sources = [];
3237
- const tsconfigs = [];
3238
- const polyglotConfigs = [];
3239
- const stack = [root];
3240
- while (stack.length > 0) {
3241
- const dir = stack.pop();
3242
- if (dir === void 0) break;
3243
- let entries;
3244
- try {
3245
- entries = readdirSync(dir, { withFileTypes: true });
3246
- } catch (error) {
3247
- notes.push(`Directory "${displayPath(root, dir)}" could not be read: ${errorMessage(error)}`);
3248
- continue;
3249
- }
3250
- entries.sort((a, b) => compareText(a.name, b.name));
3251
- const childDirs = [];
3252
- for (const entry of entries) {
3253
- const full = path5.join(dir, entry.name);
3254
- if (entry.isDirectory()) {
3255
- if (!SKIP_DIRS.has(entry.name)) {
3256
- childDirs.push(full);
3257
- }
3258
- } else if (entry.isFile()) {
3259
- const lowerName = entry.name.toLowerCase();
3260
- if (SOURCE_EXTENSIONS.has(path5.extname(entry.name).toLowerCase())) {
3261
- sources.push(full);
3262
- } else if (TSCONFIG_NAME.test(entry.name)) {
3263
- tsconfigs.push(full);
3264
- } else if (POLYGLOT_CONFIG_NAMES.has(lowerName)) {
3265
- polyglotConfigs.push(full);
3266
- }
3267
- }
3268
- }
3269
- for (let i = childDirs.length - 1; i >= 0; i -= 1) {
3270
- const child = childDirs[i];
3271
- if (child !== void 0) stack.push(child);
3272
- }
3273
- }
3274
- sources.sort(compareText);
3275
- tsconfigs.sort(compareText);
3276
- polyglotConfigs.sort(compareText);
3277
- return { sources, tsconfigs, polyglotConfigs };
3278
- }
3279
- function loadAliasConfig(root, configPath, notes) {
3280
- const label = displayPath(root, configPath);
3281
- const read = ts2.readConfigFile(configPath, ts2.sys.readFile);
3282
- if (read.error) {
3283
- notes.push(
3284
- `tsconfig "${label}" could not be parsed: ${ts2.flattenDiagnosticMessageText(read.error.messageText, " ")}`
3285
- );
3286
- return null;
3287
- }
3288
- const host = {
3289
- useCaseSensitiveFileNames: ts2.sys.useCaseSensitiveFileNames,
3290
- readDirectory: () => [],
3291
- fileExists: ts2.sys.fileExists,
3292
- readFile: ts2.sys.readFile
3293
- };
3294
- let configDir = path5.dirname(configPath);
3295
- try {
3296
- configDir = realpathSync.native(configDir);
3297
- } catch {
3298
- }
3299
- const parsed = ts2.parseJsonConfigFileContent(read.config, host, configDir, void 0, configPath);
3300
- for (const diagnostic of parsed.errors) {
3301
- if (diagnostic.code === TS_NO_INPUTS_CODE) continue;
3302
- notes.push(`tsconfig "${label}": ${ts2.flattenDiagnosticMessageText(diagnostic.messageText, " ")}`);
3303
- }
3304
- const paths = parsed.options.paths;
3305
- if (!paths) return null;
3306
- const base = parsed.options.baseUrl ? path5.resolve(configDir, parsed.options.baseUrl) : configDir;
3307
- const rules = [];
3308
- for (const [pattern, targets] of Object.entries(paths)) {
3309
- const star = pattern.indexOf("*");
3310
- rules.push({
3311
- prefix: star === -1 ? pattern : pattern.slice(0, star),
3312
- suffix: star === -1 ? "" : pattern.slice(star + 1),
3313
- wildcard: star !== -1,
3314
- targets: targets.map((target) => path5.resolve(base, target))
3315
- });
3316
- }
3317
- return rules.length > 0 ? { dir: configDir, rules } : null;
3318
- }
3319
- function resolveCandidate(base) {
3320
- const ext = path5.extname(base).toLowerCase();
3321
- const swaps = EXT_SWAPS[ext];
3322
- if (swaps) {
3323
- const stem = base.slice(0, base.length - ext.length);
3324
- for (const swap of swaps) {
3325
- if (isFile(`${stem}${swap}`)) return `${stem}${swap}`;
3326
- }
3327
- }
3328
- if (isFile(base)) return base;
3329
- for (const suffix of RESOLVE_SUFFIXES) {
3330
- if (isFile(`${base}${suffix}`)) return `${base}${suffix}`;
3331
- }
3332
- return null;
3333
- }
3334
- function resolveAlias(spec, fromFile, index) {
3335
- const configs = index.aliasConfigs.filter((config) => isAncestorDir(config.dir, fromFile)).sort((a, b) => b.dir.length - a.dir.length);
3336
- for (const config of configs) {
3337
- for (const rule of config.rules) {
3338
- let rest;
3339
- if (rule.wildcard) {
3340
- if (!spec.startsWith(rule.prefix) || !spec.endsWith(rule.suffix)) continue;
3341
- if (spec.length < rule.prefix.length + rule.suffix.length) continue;
3342
- rest = spec.slice(rule.prefix.length, spec.length - rule.suffix.length);
3343
- } else {
3344
- if (spec !== rule.prefix) continue;
3345
- rest = "";
3346
- }
3347
- for (const target of rule.targets) {
3348
- const found = resolveCandidate(target.replace("*", rest));
3349
- if (found) return found;
3350
- }
3351
- }
3352
- }
3353
- return null;
3354
- }
3355
- function buildEdgeFlags(importedNames, meta) {
3356
- const isTypeOnly = meta?.isTypeOnly === true;
3357
- const isDynamic = meta?.isDynamic === true;
3358
- const hasStaticValueImport = !isTypeOnly && !isDynamic && meta?.verifiedAssetOnDisk !== true && importedNames.length > 0;
3359
- return {
3360
- ...isTypeOnly ? { isTypeOnly: true } : {},
3361
- ...isDynamic ? { isDynamic: true } : {},
3362
- hasStaticValueImport,
3363
- ...meta?.verifiedAssetOnDisk !== void 0 ? { verifiedAssetOnDisk: meta.verifiedAssetOnDisk } : {}
3364
- };
3365
- }
3366
- function localRef(found, index, importedNames, isReExport, meta) {
3367
- let real;
3368
- try {
3369
- real = realpathSync.native(found);
3370
- } catch {
3371
- real = path5.resolve(found);
3372
- }
3373
- const label = displayPath(index.rootReal, real);
3374
- return {
3375
- key: `local:${label}`,
3376
- kind: "local",
3377
- label,
3378
- importedNames: [...importedNames],
3379
- isReExport,
3380
- ...buildEdgeFlags(importedNames, meta)
3381
- };
3382
- }
3383
- function unresolvedRef(base, index, importedNames, isReExport, meta) {
3384
- const label = displayPath(index.root, path5.resolve(base));
3385
- return {
3386
- key: `unresolved:${label}`,
3387
- kind: "unresolved",
3388
- label: `${label} (unresolved)`,
3389
- importedNames: [...importedNames],
3390
- isReExport,
3391
- ...buildEdgeFlags(importedNames, meta)
3392
- };
3393
- }
3394
- function externalRef(spec, importedNames, isReExport, meta) {
3395
- return {
3396
- key: `pkg:${spec}`,
3397
- kind: "external",
3398
- label: spec,
3399
- importedNames: [...importedNames],
3400
- isReExport,
3401
- ...buildEdgeFlags(importedNames, meta)
3402
- };
3403
- }
3404
- function resolveModule(rawSpec, fromFile, index, importedNames = [], isReExport = false, meta) {
3405
- const spec = stripImportQueryAndHash(rawSpec);
3406
- if (spec === "." || spec === ".." || spec.startsWith("./") || spec.startsWith("../")) {
3407
- const base = path5.resolve(path5.dirname(fromFile), spec);
3408
- const found = resolveCandidate(base);
3409
- const isAsset = isNonCodeAssetSpecifier(spec);
3410
- const verifiedAssetOnDisk = isAsset ? Boolean(found) : meta?.verifiedAssetOnDisk;
3411
- const effectiveMeta = {
3412
- ...meta,
3413
- ...verifiedAssetOnDisk !== void 0 ? { verifiedAssetOnDisk } : {}
3414
- };
3415
- return found ? localRef(found, index, importedNames, isReExport, effectiveMeta) : unresolvedRef(base, index, importedNames, isReExport, effectiveMeta);
3416
- }
3417
- if (spec.startsWith("node:")) {
3418
- return externalRef(spec, importedNames, isReExport, meta);
3419
- }
3420
- if (NODE_BUILTINS.has(spec)) {
3421
- return externalRef(`node:${spec}`, importedNames, isReExport, meta);
3422
- }
3423
- if (path5.isAbsolute(spec)) {
3424
- const found = resolveCandidate(spec);
3425
- if (found) return localRef(found, index, importedNames, isReExport, meta);
3426
- }
3427
- const aliased = resolveAlias(spec, fromFile, index);
3428
- if (aliased) {
3429
- const isAsset = isNonCodeAssetSpecifier(aliased);
3430
- return localRef(aliased, index, importedNames, isReExport, {
3431
- ...meta,
3432
- ...isAsset ? { verifiedAssetOnDisk: true } : {}
3433
- });
3434
- }
3435
- return externalRef(spec, importedNames, isReExport, meta);
3436
- }
3437
- function mergeModuleRef(modules, ref) {
3438
- const incomingHasStatic = ref.hasStaticValueImport ?? (ref.isTypeOnly !== true && ref.isDynamic !== true && ref.verifiedAssetOnDisk !== true && ref.importedNames.length > 0);
3439
- const existing = modules.get(ref.key);
3440
- if (!existing) {
3441
- modules.set(ref.key, {
3442
- ...ref,
3443
- importedNames: [...ref.importedNames],
3444
- hasStaticValueImport: incomingHasStatic
3445
- });
3446
- return;
3447
- }
3448
- for (const name of ref.importedNames) {
3449
- if (!existing.importedNames.includes(name)) {
3450
- existing.importedNames.push(name);
3451
- }
3452
- }
3453
- if (ref.isReExport) {
3454
- existing.isReExport = true;
3455
- }
3456
- const existingHasStatic = existing.hasStaticValueImport ?? (existing.isTypeOnly !== true && existing.isDynamic !== true && existing.verifiedAssetOnDisk !== true && existing.importedNames.length > 0);
3457
- existing.hasStaticValueImport = existingHasStatic || incomingHasStatic;
3458
- existing.isTypeOnly = Boolean(existing.isTypeOnly) && Boolean(ref.isTypeOnly);
3459
- existing.isDynamic = Boolean(existing.isDynamic) && Boolean(ref.isDynamic);
3460
- if (ref.verifiedAssetOnDisk === true) {
3461
- existing.verifiedAssetOnDisk = true;
3462
- } else if (ref.verifiedAssetOnDisk === false && existing.verifiedAssetOnDisk === void 0) {
3463
- existing.verifiedAssetOnDisk = false;
3464
- }
3465
- }
3466
- function addInboundEdge(index, callerRel, targetRel) {
3467
- let inboundSet = index.inbound.get(targetRel);
3468
- if (!inboundSet) {
3469
- inboundSet = /* @__PURE__ */ new Set();
3470
- index.inbound.set(targetRel, inboundSet);
3471
- }
3472
- inboundSet.add(callerRel);
3473
- let importedBySet = index.importedBy.get(targetRel);
3474
- if (!importedBySet) {
3475
- importedBySet = /* @__PURE__ */ new Set();
3476
- index.importedBy.set(targetRel, importedBySet);
3477
- }
3478
- importedBySet.add(callerRel);
3479
- }
3480
- function registerIndexedFile(index, file, extraId) {
3481
- index.files.push(file);
3482
- index.byId.set(file.id, file);
3483
- if (extraId && extraId !== file.id) {
3484
- index.byId.set(extraId, file);
3485
- }
3486
- index.byRelative.set(file.relative, file);
3487
- index.outbound.set(file.relative, file.modules);
3488
- for (const ref of file.modules.values()) {
3489
- if (ref.kind === "local") {
3490
- addInboundEdge(index, file.relative, ref.label);
3491
- }
3492
- }
3493
- }
3494
- function resolveNonJsTsImport(imp, relative, language, index, modules) {
3495
- const adapter = defaultPolyglotRegistry.getAdapterById(language);
3496
- const ctx = index.resolutionContext;
3497
- const edgeMeta = {
3498
- isTypeOnly: imp.isTypeOnly,
3499
- isDynamic: imp.isDynamic,
3500
- verifiedAssetOnDisk: imp.verifiedAssetOnDisk
3501
- };
3502
- if (!adapter || !ctx) {
3503
- const ext = externalRef(imp.rawSpecifier, imp.importedNames, imp.isReExport, edgeMeta);
3504
- mergeModuleRef(modules, { ...ext, rawSpecifier: imp.rawSpecifier });
3505
- return { ...imp, resolvedKind: "external", resolvedPaths: [] };
3506
- }
3507
- const res = adapter.resolveImport(imp, relative, ctx);
3508
- if (res.kind === "local" && res.resolvedPaths.length > 0) {
3509
- for (const targetRel of res.resolvedPaths) {
3510
- mergeModuleRef(modules, {
3511
- key: `local:${targetRel}`,
3512
- kind: "local",
3513
- label: targetRel,
3514
- importedNames: [...imp.importedNames],
3515
- isReExport: imp.isReExport,
3516
- ...buildEdgeFlags(imp.importedNames, edgeMeta),
3517
- rawSpecifier: imp.rawSpecifier
3518
- });
3519
- }
3520
- return {
3521
- ...imp,
3522
- resolvedKind: "local",
3523
- resolvedPaths: [...res.resolvedPaths]
3524
- };
3525
- }
3526
- if (res.kind === "unresolved") {
3527
- const attempt = normalizeRelPath(res.unresolvedAttempt ?? imp.rawSpecifier);
3528
- mergeModuleRef(modules, {
3529
- key: `unresolved:${attempt}`,
3530
- kind: "unresolved",
3531
- label: `${attempt} (unresolved)`,
3532
- importedNames: [...imp.importedNames],
3533
- isReExport: imp.isReExport,
3534
- ...buildEdgeFlags(imp.importedNames, edgeMeta),
3535
- rawSpecifier: imp.rawSpecifier
3536
- });
3537
- return {
3538
- ...imp,
3539
- resolvedKind: "unresolved",
3540
- resolvedPaths: attempt ? [attempt] : []
3541
- };
3542
- }
3543
- const extLabel = res.externalLabel ?? imp.rawSpecifier;
3544
- mergeModuleRef(modules, {
3545
- ...externalRef(extLabel, imp.importedNames, imp.isReExport, edgeMeta),
3546
- rawSpecifier: imp.rawSpecifier
3547
- });
3548
- return {
3549
- ...imp,
3550
- resolvedKind: "external",
3551
- resolvedPaths: []
3552
- };
3553
- }
3554
- function indexFileOnDisk(absolute, index, options) {
3555
- let realAbs;
3556
- try {
3557
- realAbs = realpathSync.native(absolute);
3558
- } catch {
3559
- realAbs = path5.resolve(absolute);
3560
- }
3561
- const relative = displayPath(index.rootReal, realAbs);
3562
- const stats = statOrNull(absolute);
3563
- const cache = options?.cache;
3564
- let manifest;
3565
- if (cache && stats) {
3566
- manifest = cache.get(index.workspaceId, relative, void 0, stats.mtimeMs, stats.size);
3567
- }
3568
- if (!manifest) {
3569
- const source = readFileSync3(absolute, "utf8");
3570
- if (cache) {
3571
- const sha256 = createHash3("sha256").update(source, "utf8").digest("hex");
3572
- const shaHit = cache.get(index.workspaceId, relative, sha256);
3573
- if (shaHit) {
3574
- manifest = {
3575
- ...shaHit,
3576
- relativePath: relative,
3577
- ...stats ? { mtimeMs: stats.mtimeMs, size: stats.size } : {}
3578
- };
3579
- cache.set(index.workspaceId, manifest);
3580
- } else {
3581
- manifest = defaultPolyglotRegistry.extractManifest(
3582
- source,
3583
- realAbs,
3584
- relative,
3585
- stats?.mtimeMs,
3586
- stats?.size
3587
- );
3588
- cache.set(index.workspaceId, manifest);
3589
- }
3590
- } else {
3591
- manifest = defaultPolyglotRegistry.extractManifest(
3592
- source,
3593
- realAbs,
3594
- relative,
3595
- stats?.mtimeMs,
3596
- stats?.size
3597
- );
3598
- }
3599
- }
3600
- const language = manifest.language ?? defaultPolyglotRegistry.detectLanguage(realAbs);
3601
- const isJsTs = language === "typescript" || language === "javascript" || language === "unknown";
3602
- const modules = /* @__PURE__ */ new Map();
3603
- const resolvedImports = [];
3604
- for (const imp of manifest.imports) {
3605
- if (isJsTs) {
3606
- const cleanSpec = stripImportQueryAndHash(imp.rawSpecifier);
3607
- let verifiedAssetOnDisk = imp.verifiedAssetOnDisk;
3608
- if (isRelativeImportSpecifier(cleanSpec) && isNonCodeAssetSpecifier(cleanSpec)) {
3609
- verifiedAssetOnDisk = isFile(path5.resolve(path5.dirname(realAbs), cleanSpec));
3610
- }
3611
- const ref = resolveModule(
3612
- imp.rawSpecifier,
3613
- realAbs,
3614
- index,
3615
- imp.importedNames,
3616
- imp.isReExport,
3617
- {
3618
- isTypeOnly: imp.isTypeOnly,
3619
- isDynamic: imp.isDynamic,
3620
- verifiedAssetOnDisk
3621
- }
3622
- );
3623
- mergeModuleRef(modules, { ...ref, rawSpecifier: imp.rawSpecifier });
3624
- const resolvedPaths = ref.kind === "local" ? [ref.label] : ref.kind === "unresolved" ? [ref.label.replace(/ \(unresolved\)$/, "")] : [];
3625
- const effectiveVerifiedAsset = ref.verifiedAssetOnDisk !== void 0 ? ref.verifiedAssetOnDisk : verifiedAssetOnDisk;
3626
- resolvedImports.push({
3627
- ...imp,
3628
- ...effectiveVerifiedAsset !== void 0 ? { verifiedAssetOnDisk: effectiveVerifiedAsset } : {},
3629
- resolvedKind: ref.kind,
3630
- resolvedPaths
3631
- });
3632
- } else {
3633
- resolvedImports.push(resolveNonJsTsImport(imp, relative, language, index, modules));
3634
- }
3635
- }
3636
- const enrichedManifest = {
3637
- ...manifest,
3638
- relativePath: relative,
3639
- language,
3640
- imports: resolvedImports
3641
- };
3642
- return {
3643
- absolute: realAbs,
3644
- id: fileId(realAbs),
3645
- relative,
3646
- contentSha256: enrichedManifest.contentSha256,
3647
- language,
3648
- modules,
3649
- exportedSymbols: enrichedManifest.exportedSymbols.map((sym) => ({ ...sym, file: relative })),
3650
- internalFunctions: enrichedManifest.internalFunctions.map((fn) => ({ ...fn, file: relative })),
3651
- manifest: enrichedManifest
3652
- };
3653
- }
3654
- function buildIndex(root, options) {
3655
- const notes = [];
3656
- let rootReal;
3657
- try {
3658
- rootReal = realpathSync.native(root);
3659
- } catch {
3660
- rootReal = path5.resolve(root);
3661
- }
3662
- const workspaceId = options?.workspaceId ?? toPosix(rootReal);
3663
- const { sources, tsconfigs, polyglotConfigs } = walkWorkspace(root, notes);
3664
- const aliasConfigs = [];
3665
- for (const configPath of tsconfigs) {
3666
- const config = loadAliasConfig(root, configPath, notes);
3667
- if (config) aliasConfigs.push(config);
3668
- }
3669
- const sourceRelPaths = sources.map((abs) => {
3670
- try {
3671
- return displayPath(rootReal, realpathSync.native(abs));
3672
- } catch {
3673
- return displayPath(rootReal, path5.resolve(abs));
3674
- }
3675
- });
3676
- const polyglotConfigRelPaths = polyglotConfigs.map((abs) => {
3677
- try {
3678
- return displayPath(rootReal, realpathSync.native(abs));
3679
- } catch {
3680
- return displayPath(rootReal, path5.resolve(abs));
3681
- }
3682
- });
3683
- const resolutionContext = buildWorkspaceResolutionContext(
3684
- root,
3685
- rootReal,
3686
- sourceRelPaths,
3687
- polyglotConfigRelPaths
3688
- );
3689
- const index = {
3690
- workspaceId,
3691
- root,
3692
- rootReal,
3693
- files: [],
3694
- byId: /* @__PURE__ */ new Map(),
3695
- byRelative: /* @__PURE__ */ new Map(),
3696
- outbound: /* @__PURE__ */ new Map(),
3697
- inbound: /* @__PURE__ */ new Map(),
3698
- importedBy: /* @__PURE__ */ new Map(),
3699
- aliasConfigs,
3700
- resolutionContext,
3701
- notes
3702
- };
3703
- for (const absolute of sources) {
3704
- try {
3705
- const file = indexFileOnDisk(absolute, index, options);
3706
- registerIndexedFile(index, file, fileId(absolute));
3707
- } catch (error) {
3708
- notes.push(`"${displayPath(root, absolute)}" could not be analysed: ${errorMessage(error)}`);
3709
- }
3710
- }
3711
- index.files.sort((a, b) => compareText(a.relative, b.relative));
3712
- return index;
3713
- }
3714
-
3715
- // src/extractor.ts
3716
- function sha256Text(text) {
3717
- return createHash4("sha256").update(text, "utf8").digest("hex");
3718
- }
3719
- function computeManifestSyncHash(manifest) {
3720
- const assetSig = manifest.imports.map((imp) => {
3721
- const assetFlag = imp.verifiedAssetOnDisk === true ? "1" : imp.verifiedAssetOnDisk === false ? "0" : "-";
3722
- const dynFlag = imp.isDynamic === true ? "D" : "S";
3723
- const typeFlag = imp.isTypeOnly ? "T" : "V";
3724
- return `${imp.rawSpecifier}:${typeFlag}${dynFlag}${assetFlag}:${imp.importedNames.length}`;
3725
- }).join("|");
3726
- const symSig = manifest.exportedSymbols.map((s) => `${s.name}:${s.structuralHash ?? ""}`).join(",");
3727
- const internalSig = manifest.internalFunctions.map((f) => `${f.name}:${f.structuralHash}`).join(",");
3728
- const schema = manifest.schemaVersion ?? CACHE_SCHEMA_VERSION;
3729
- return sha256Text(`${schema}\0${manifest.contentSha256}\0${assetSig}\0${symSig}\0${internalSig}`);
3730
- }
3731
- function verifyRelativeAssetsOnDisk(manifest, sourceAbsPath) {
3732
- const sourceDir = path6.dirname(sourceAbsPath);
3733
- let changed = false;
3734
- const updatedImports = manifest.imports.map((imp) => {
3735
- const cleanSpec = stripImportQueryAndHash(imp.rawSpecifier);
3736
- if (!isRelativeImportSpecifier(cleanSpec) || !isNonCodeAssetSpecifier(cleanSpec)) {
3737
- return imp;
3738
- }
3739
- const resolvedDiskPath = path6.resolve(sourceDir, cleanSpec);
3740
- const verified = existsSync3(resolvedDiskPath);
3741
- if (imp.verifiedAssetOnDisk !== verified) {
3742
- changed = true;
3743
- }
3744
- return {
3745
- ...imp,
3746
- verifiedAssetOnDisk: verified
3747
- };
3748
- });
3749
- if (!changed) {
3750
- return { manifest, changed: false };
3751
- }
3752
- return {
3753
- manifest: {
3754
- ...manifest,
3755
- imports: updatedImports
3756
- },
3757
- changed: true
3758
- };
3759
- }
3760
- function invalidateStaleCloudSyncFile(cachePath, workspaceId) {
3761
- const syncPath = path6.join(path6.dirname(cachePath), "cloud-sync.json");
3762
- if (!existsSync3(syncPath)) return;
3763
- try {
3764
- const parsed = JSON.parse(readFileSync4(syncPath, "utf8"));
3765
- if (!parsed || typeof parsed !== "object") return;
3766
- if (parsed.manifestSchemaVersion !== CACHE_SCHEMA_VERSION) {
3767
- writeFileSync2(
3768
- syncPath,
3769
- JSON.stringify(
3770
- {
3771
- version: 1,
3772
- manifestSchemaVersion: CACHE_SCHEMA_VERSION,
3773
- workspaces: {}
3774
- },
3775
- null,
3776
- 2
3777
- ),
3778
- "utf8"
3779
- );
3780
- return;
3781
- }
3782
- if (parsed.workspaces && typeof parsed.workspaces === "object") {
3783
- let modified = false;
3784
- for (const key of Object.keys(parsed.workspaces)) {
3785
- if (key === workspaceId || key.endsWith(`::${workspaceId}`)) {
3786
- delete parsed.workspaces[key];
3787
- modified = true;
3788
- }
3789
- }
3790
- if (modified) {
3791
- writeFileSync2(syncPath, JSON.stringify(parsed, null, 2), "utf8");
3792
- }
3793
- }
3794
- } catch {
3795
- }
3796
- }
3797
- function hasSkippedPathSegment(relPath) {
3798
- const segments = toPosix(relPath).replace(/^\.\//, "").split("/");
3799
- return segments.some((seg) => seg.length > 0 && SKIP_DIRS.has(seg));
3800
- }
3801
- function deriveWorkspaceId(rootDir) {
3802
- const real = realpathSync2.native(path6.resolve(rootDir));
3803
- return `ws_${sha256Text(real).slice(0, 16)}`;
3804
- }
3805
- function sanitizeManifest(manifest) {
3806
- return {
3807
- relativePath: toPosix(manifest.relativePath),
3808
- contentSha256: manifest.contentSha256,
3809
- schemaVersion: manifest.schemaVersion ?? CACHE_SCHEMA_VERSION,
3810
- ...manifest.language !== void 0 ? { language: manifest.language } : {},
3811
- ...manifest.mtimeMs !== void 0 ? { mtimeMs: manifest.mtimeMs } : {},
3812
- ...manifest.size !== void 0 ? { size: manifest.size } : {},
3813
- imports: manifest.imports.map((imp) => ({
3814
- rawSpecifier: imp.rawSpecifier,
3815
- importedNames: [...imp.importedNames],
3816
- isReExport: imp.isReExport,
3817
- isTypeOnly: imp.isTypeOnly,
3818
- ...imp.isDynamic === true ? { isDynamic: true } : {},
3819
- ...typeof imp.verifiedAssetOnDisk === "boolean" ? { verifiedAssetOnDisk: imp.verifiedAssetOnDisk } : {},
3820
- ...Array.isArray(imp.resolvedPaths) ? { resolvedPaths: imp.resolvedPaths.map((p) => toPosix(p)) } : {},
3821
- ...imp.resolvedKind !== void 0 ? { resolvedKind: imp.resolvedKind } : {}
3822
- })),
3823
- exportedSymbols: manifest.exportedSymbols.map((sym) => ({
3824
- name: sym.name,
3825
- ...sym.localName !== void 0 ? { localName: sym.localName } : {},
3826
- kind: sym.kind,
3827
- signature: sym.signature,
3828
- line: sym.line,
3829
- ...sym.structuralHash !== void 0 ? { structuralHash: sym.structuralHash } : {},
3830
- ...sym.nodeCount !== void 0 ? { nodeCount: sym.nodeCount } : {},
3831
- ...sym.astNodeCount !== void 0 ? { astNodeCount: sym.astNodeCount } : {},
3832
- file: toPosix(sym.file),
3833
- isExported: true,
3834
- ...sym.isReExport !== void 0 ? { isReExport: sym.isReExport } : {}
3835
- })),
3836
- internalFunctions: manifest.internalFunctions.map((fn) => ({
3837
- name: fn.name,
3838
- kind: "function",
3839
- signature: fn.signature,
3840
- line: fn.line,
3841
- structuralHash: fn.structuralHash,
3842
- nodeCount: fn.nodeCount,
3843
- ...fn.astNodeCount !== void 0 ? { astNodeCount: fn.astNodeCount } : {},
3844
- file: toPosix(fn.file),
3845
- isExported: false
3846
- }))
3847
- };
3848
- }
3849
- function walkSourceFiles(rootDir) {
3850
- const results = [];
3851
- const stack = [rootDir];
3852
- while (stack.length > 0) {
3853
- const dir = stack.pop();
3854
- if (dir === void 0) break;
3855
- let entries;
3856
- try {
3857
- entries = readdirSync2(dir, { withFileTypes: true });
3858
- } catch {
3859
- continue;
3860
- }
3861
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3862
- const childDirs = [];
3863
- for (const entry of entries) {
3864
- const fullPath = path6.join(dir, entry.name);
3865
- if (entry.isDirectory()) {
3866
- if (!SKIP_DIRS.has(entry.name)) {
3867
- childDirs.push(fullPath);
3868
- }
3869
- } else if (entry.isFile()) {
3870
- if (SOURCE_EXTENSIONS.has(path6.extname(entry.name).toLowerCase())) {
3871
- results.push(fullPath);
3872
- }
3873
- }
3874
- }
3875
- for (let i = childDirs.length - 1; i >= 0; i -= 1) {
3876
- const child = childDirs[i];
3877
- if (child !== void 0) {
3878
- stack.push(child);
3879
- }
3880
- }
3881
- }
3882
- results.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
3883
- return results;
3884
- }
3885
- function scanWorkspaceManifests(rootDir, options = {}) {
3886
- const resolvedRoot = path6.resolve(rootDir);
3887
- const rootReal = realpathSync2.native(resolvedRoot);
3888
- const workspaceId = options.workspaceId ?? deriveWorkspaceId(rootReal);
3889
- const cachePath = options.cachePath ?? path6.join(resolvedRoot, ".tipolink", "cache.json");
3890
- const writeCache = options.writeCache ?? true;
3891
- const cache = new JsonFileAstCache({ filePath: cachePath, autoSave: false });
3892
- const schemaInvalidated = cache.schemaInvalidated;
3893
- const priorManifests = cache.getAllWorkspaceManifests(workspaceId);
3894
- const priorPaths = /* @__PURE__ */ new Set();
3895
- let prunedSkippedEntries = false;
3896
- for (const m of priorManifests) {
3897
- const norm = toPosix(m.relativePath);
3898
- if (hasSkippedPathSegment(norm)) {
3899
- prunedSkippedEntries = true;
3900
- }
3901
- priorPaths.add(norm);
3902
- }
3903
- const sourceFiles = walkSourceFiles(resolvedRoot);
3904
- const activeRelPaths = /* @__PURE__ */ new Set();
3905
- const rawAllManifests = [];
3906
- const deltaRelPaths = /* @__PURE__ */ new Set();
3907
- let cacheHits = 0;
3908
- let parsedCount = 0;
3909
- let cacheMutated = schemaInvalidated;
3910
- for (const absPath of sourceFiles) {
3911
- let realAbs;
3912
- try {
3913
- realAbs = realpathSync2.native(absPath);
3914
- } catch {
3915
- realAbs = absPath;
3916
- }
3917
- const relPath = toPosix(path6.relative(rootReal, realAbs));
3918
- if (hasSkippedPathSegment(relPath)) continue;
3919
- activeRelPaths.add(relPath);
3920
- let stats;
3921
- try {
3922
- stats = statSync2(realAbs);
3923
- } catch {
3924
- continue;
3925
- }
3926
- if (!stats.isFile()) continue;
3927
- const statHit = cache.get(workspaceId, relPath, void 0, stats.mtimeMs, stats.size);
3928
- if (statHit && statHit.schemaVersion === CACHE_SCHEMA_VERSION) {
3929
- cacheHits += 1;
3930
- const verified = verifyRelativeAssetsOnDisk(sanitizeManifest(statHit), realAbs);
3931
- if (verified.changed) {
3932
- cache.set(workspaceId, verified.manifest);
3933
- cacheMutated = true;
3934
- deltaRelPaths.add(relPath);
3935
- }
3936
- rawAllManifests.push(verified.manifest);
3937
- continue;
3938
- }
3939
- const source = readFileSync4(realAbs, "utf8");
3940
- const contentSha256 = sha256Text(source);
3941
- const hashHit = cache.get(workspaceId, relPath, contentSha256);
3942
- if (hashHit && hashHit.schemaVersion === CACHE_SCHEMA_VERSION) {
3943
- cacheHits += 1;
3944
- const verified = verifyRelativeAssetsOnDisk(
3945
- sanitizeManifest({
3946
- ...hashHit,
3947
- mtimeMs: stats.mtimeMs,
3948
- size: stats.size
3949
- }),
3950
- realAbs
3951
- );
3952
- cache.set(workspaceId, verified.manifest);
3953
- cacheMutated = true;
3954
- if (verified.changed) {
3955
- deltaRelPaths.add(relPath);
3956
- }
3957
- rawAllManifests.push(verified.manifest);
3958
- continue;
3959
- }
3960
- const extracted = verifyRelativeAssetsOnDisk(
3961
- sanitizeManifest(
3962
- defaultPolyglotRegistry.extractManifest(source, realAbs, relPath, stats.mtimeMs, stats.size)
3963
- ),
3964
- realAbs
3965
- ).manifest;
3966
- parsedCount += 1;
3967
- cache.set(workspaceId, extracted);
3968
- cacheMutated = true;
3969
- rawAllManifests.push(extracted);
3970
- deltaRelPaths.add(relPath);
3971
- }
3972
- const removedPaths = [];
3973
- for (const oldRel of priorPaths) {
3974
- if (!activeRelPaths.has(oldRel)) {
3975
- removedPaths.push(oldRel);
3976
- }
3977
- }
3978
- if (removedPaths.length > 0 || prunedSkippedEntries) {
3979
- cache.clear(workspaceId);
3980
- for (const manifest of rawAllManifests) {
3981
- cache.set(workspaceId, manifest);
3982
- }
3983
- cacheMutated = true;
3984
- }
3985
- if (writeCache && cacheMutated) {
3986
- cache.flush();
3987
- if (schemaInvalidated) {
3988
- invalidateStaleCloudSyncFile(cachePath, workspaceId);
3989
- }
3990
- }
3991
- const index = buildIndex(resolvedRoot, { workspaceId, cache });
3992
- const allManifests = [];
3993
- const manifestDelta = [];
3994
- for (const file of index.files) {
3995
- if (hasSkippedPathSegment(file.relative)) continue;
3996
- const verified = verifyRelativeAssetsOnDisk(sanitizeManifest(file.manifest), file.absolute).manifest;
3997
- allManifests.push(verified);
3998
- if (deltaRelPaths.has(file.relative)) {
3999
- manifestDelta.push(verified);
4000
- }
4001
- }
4002
- return {
4003
- workspaceId,
4004
- rootDir: resolvedRoot,
4005
- cachePath,
4006
- schemaVersion: CACHE_SCHEMA_VERSION,
4007
- schemaInvalidated,
4008
- allManifests,
4009
- manifestDelta,
4010
- removedPaths,
4011
- cacheHits,
4012
- parsedCount,
4013
- index
4014
- };
4015
- }
4016
- export {
4017
- CACHE_SCHEMA_VERSION,
4018
- computeManifestSyncHash,
4019
- deriveWorkspaceId,
4020
- sanitizeManifest,
4021
- scanWorkspaceManifests
4022
- };
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};