scip-query 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/chunk-2DSS2NGF.js +10 -0
  2. package/dist/chunk-2RLP74AO.js +2 -0
  3. package/dist/chunk-4QJ7LVW5.js +2 -0
  4. package/dist/chunk-4TYGGOLO.js +5 -0
  5. package/dist/chunk-5IADAU5B.js +7 -0
  6. package/dist/chunk-7754WFFV.js +18 -0
  7. package/dist/chunk-7VOF4ZG6.js +2 -0
  8. package/dist/chunk-7Z4COVMC.js +2 -0
  9. package/dist/chunk-AJ5PWKD4.js +2 -0
  10. package/dist/chunk-BDBRZPX3.js +7 -0
  11. package/dist/chunk-BE6EQIWY.js +2 -0
  12. package/dist/chunk-BQ3INTYT.js +8 -0
  13. package/dist/chunk-D7KLLMPB.js +2 -0
  14. package/dist/chunk-D7YBWSON.js +29 -0
  15. package/dist/chunk-DE5ZBHMK.js +39 -0
  16. package/dist/chunk-DHYIJHXZ.js +33 -0
  17. package/dist/chunk-EEF3YEHW.js +2 -0
  18. package/dist/chunk-F2LLHRRZ.js +2 -0
  19. package/dist/chunk-FCC3XJTI.js +2 -0
  20. package/dist/chunk-GNXRLK5G.js +2 -0
  21. package/dist/chunk-GXVB36TG.js +62 -0
  22. package/dist/chunk-HMKJTAZD.js +2 -0
  23. package/dist/chunk-IBGBI3VU.js +2 -0
  24. package/dist/chunk-IYFZS4PV.js +84 -0
  25. package/dist/chunk-JH3A7HTU.js +2 -0
  26. package/dist/chunk-JS2RNIC7.js +2 -0
  27. package/dist/chunk-K5FQFCSN.js +41 -0
  28. package/dist/chunk-K6GBKEQE.js +6 -0
  29. package/dist/chunk-KO7YJRWP.js +12 -0
  30. package/dist/chunk-KYT47WU2.js +4 -0
  31. package/dist/chunk-LORWXBOO.js +2 -0
  32. package/dist/chunk-LX4H4LLG.js +89 -0
  33. package/dist/chunk-N3Z2SJCR.js +2 -0
  34. package/dist/chunk-NTDA4A2D.js +25 -0
  35. package/dist/chunk-NXMYYHDO.js +24 -0
  36. package/dist/chunk-PZ6ESKRH.js +7 -0
  37. package/dist/chunk-QXE6EDY2.js +6 -0
  38. package/dist/chunk-RJ7SPBJ5.js +5 -0
  39. package/dist/chunk-RWE6FHG3.js +3 -0
  40. package/dist/chunk-SDX6MDBL.js +2 -0
  41. package/dist/chunk-SG35Y7J2.js +2 -0
  42. package/dist/chunk-STOGKRJH.js +4 -0
  43. package/dist/chunk-TINPMWJK.js +2 -0
  44. package/dist/chunk-UJB62HV3.js +2 -0
  45. package/dist/chunk-VEUMRDHW.js +2 -0
  46. package/dist/chunk-WCDXJGYT.js +65 -0
  47. package/dist/chunk-WTSTDJZ7.js +6 -0
  48. package/dist/chunk-XAZTIDST.js +2 -0
  49. package/dist/chunk-XVDASCN7.js +35 -0
  50. package/dist/chunk-Y7H6D2EV.js +2 -0
  51. package/dist/chunk-Y7LOQSWY.js +2 -0
  52. package/dist/chunk-YIPCV7M7.js +70 -0
  53. package/dist/chunk-ZSRXMNMK.js +5 -0
  54. package/dist/chunk-ZXKURFVB.js +56 -0
  55. package/dist/cli.js +509 -8938
  56. package/dist/{db-6F9R9e_t.d.ts → db-BSTtBG_H.d.ts} +146 -1
  57. package/dist/index.d.ts +11 -2
  58. package/dist/index.js +13 -1616
  59. package/dist/postinstall.js +4 -100
  60. package/dist/queries/affected.d.ts +1 -1
  61. package/dist/queries/affected.js +1 -8
  62. package/dist/queries/bottlenecks.d.ts +1 -1
  63. package/dist/queries/bottlenecks.js +1 -8
  64. package/dist/queries/by-kind.d.ts +1 -4
  65. package/dist/queries/by-kind.js +1 -10
  66. package/dist/queries/call-graph.d.ts +1 -1
  67. package/dist/queries/call-graph.js +1 -8
  68. package/dist/queries/change-surface.d.ts +4 -1
  69. package/dist/queries/change-surface.js +1 -8
  70. package/dist/queries/code.d.ts +1 -1
  71. package/dist/queries/code.js +1 -8
  72. package/dist/queries/complexity-hotspots.d.ts +5 -3
  73. package/dist/queries/complexity-hotspots.js +1 -8
  74. package/dist/queries/complexity.d.ts +1 -1
  75. package/dist/queries/complexity.js +1 -8
  76. package/dist/queries/convergence.d.ts +1 -1
  77. package/dist/queries/convergence.js +1 -8
  78. package/dist/queries/coupling.d.ts +1 -1
  79. package/dist/queries/coupling.js +1 -10
  80. package/dist/queries/cycles.d.ts +1 -1
  81. package/dist/queries/cycles.js +1 -8
  82. package/dist/queries/dataflow.d.ts +1 -1
  83. package/dist/queries/dataflow.js +1 -8
  84. package/dist/queries/dead.d.ts +1 -1
  85. package/dist/queries/dead.js +1 -9
  86. package/dist/queries/deep-chains.d.ts +9 -1
  87. package/dist/queries/deep-chains.js +1 -8
  88. package/dist/queries/deps.d.ts +1 -1
  89. package/dist/queries/deps.js +1 -10
  90. package/dist/queries/diff-impact.d.ts +1 -1
  91. package/dist/queries/diff-impact.js +1 -7
  92. package/dist/queries/drift.d.ts +1 -1
  93. package/dist/queries/drift.js +1 -8
  94. package/dist/queries/extract-candidates.d.ts +1 -1
  95. package/dist/queries/extract-candidates.js +1 -8
  96. package/dist/queries/fan.d.ts +1 -1
  97. package/dist/queries/fan.js +1 -14
  98. package/dist/queries/files.d.ts +1 -1
  99. package/dist/queries/files.js +1 -6
  100. package/dist/queries/health.d.ts +1 -1
  101. package/dist/queries/health.js +1 -20
  102. package/dist/queries/hierarchy.d.ts +1 -1
  103. package/dist/queries/hierarchy.js +1 -8
  104. package/dist/queries/hotspots.d.ts +1 -1
  105. package/dist/queries/hotspots.js +1 -8
  106. package/dist/queries/imports.d.ts +1 -1
  107. package/dist/queries/imports.js +1 -12
  108. package/dist/queries/index.d.ts +1 -1
  109. package/dist/queries/index.js +1 -197
  110. package/dist/queries/isolated.d.ts +1 -1
  111. package/dist/queries/isolated.js +1 -9
  112. package/dist/queries/members.d.ts +4 -1
  113. package/dist/queries/members.js +1 -8
  114. package/dist/queries/methods.d.ts +1 -1
  115. package/dist/queries/methods.js +1 -8
  116. package/dist/queries/outline.d.ts +4 -1
  117. package/dist/queries/outline.js +1 -8
  118. package/dist/queries/passthrough-candidates.d.ts +1 -1
  119. package/dist/queries/passthrough-candidates.js +1 -8
  120. package/dist/queries/redundant-reexports.d.ts +1 -1
  121. package/dist/queries/redundant-reexports.js +1 -9
  122. package/dist/queries/refs.d.ts +1 -1
  123. package/dist/queries/refs.js +1 -8
  124. package/dist/queries/similar-chains.d.ts +1 -1
  125. package/dist/queries/similar-chains.js +1 -8
  126. package/dist/queries/similar-files.d.ts +1 -1
  127. package/dist/queries/similar-files.js +1 -8
  128. package/dist/queries/similar-signatures.d.ts +1 -1
  129. package/dist/queries/similar-signatures.js +1 -8
  130. package/dist/queries/similar.d.ts +1 -1
  131. package/dist/queries/similar.js +1 -10
  132. package/dist/queries/slice.d.ts +1 -1
  133. package/dist/queries/slice.js +1 -8
  134. package/dist/queries/stale-abstractions.d.ts +15 -5
  135. package/dist/queries/stale-abstractions.js +1 -8
  136. package/dist/queries/stats.d.ts +1 -1
  137. package/dist/queries/stats.js +1 -6
  138. package/dist/queries/surface.d.ts +1 -1
  139. package/dist/queries/surface.js +1 -8
  140. package/dist/queries/symbols.d.ts +1 -1
  141. package/dist/queries/symbols.js +1 -9
  142. package/dist/queries/system.d.ts +6 -2
  143. package/dist/queries/system.js +1 -9
  144. package/dist/queries/trace.d.ts +1 -1
  145. package/dist/queries/trace.js +1 -9
  146. package/dist/queries/wrapper-candidates.d.ts +1 -1
  147. package/dist/queries/wrapper-candidates.js +1 -8
  148. package/dist/reindex-worker.js +7 -672
  149. package/package.json +20 -2
  150. package/dist/chunk-334PCFO3.js +0 -221
  151. package/dist/chunk-46ZTW4AI.js +0 -61
  152. package/dist/chunk-4TYLS5XX.js +0 -10
  153. package/dist/chunk-4YN3PE57.js +0 -124
  154. package/dist/chunk-5YB6UXQ3.js +0 -101
  155. package/dist/chunk-6PVHJ332.js +0 -44
  156. package/dist/chunk-74RFWB5T.js +0 -24
  157. package/dist/chunk-7KGTWDAX.js +0 -87
  158. package/dist/chunk-7OGXSMLY.js +0 -105
  159. package/dist/chunk-AEBM56CO.js +0 -69
  160. package/dist/chunk-B747RITP.js +0 -38
  161. package/dist/chunk-B7LDMCUS.js +0 -110
  162. package/dist/chunk-C2VSV54P.js +0 -110
  163. package/dist/chunk-DIYEUFVP.js +0 -81
  164. package/dist/chunk-E74RY6AQ.js +0 -93
  165. package/dist/chunk-FIMTTUGE.js +0 -165
  166. package/dist/chunk-FMAYH7GS.js +0 -2542
  167. package/dist/chunk-FO2CBB7U.js +0 -23
  168. package/dist/chunk-HESWGDIV.js +0 -162
  169. package/dist/chunk-HL2LXSBW.js +0 -34
  170. package/dist/chunk-HW76DVE4.js +0 -216
  171. package/dist/chunk-IC5NTO47.js +0 -53
  172. package/dist/chunk-J34HAAEQ.js +0 -59
  173. package/dist/chunk-JSXGC2EH.js +0 -151
  174. package/dist/chunk-LQXBFCP2.js +0 -87
  175. package/dist/chunk-NML6M5AS.js +0 -37
  176. package/dist/chunk-NNFP4ZRF.js +0 -72
  177. package/dist/chunk-NWXTQGUE.js +0 -49
  178. package/dist/chunk-NYZ6INK3.js +0 -95
  179. package/dist/chunk-OMVF3BHY.js +0 -84
  180. package/dist/chunk-P3VCDYMJ.js +0 -269
  181. package/dist/chunk-PGQXIAJF.js +0 -79
  182. package/dist/chunk-PKDFXASW.js +0 -76
  183. package/dist/chunk-PSK5BPFE.js +0 -82
  184. package/dist/chunk-QZ4FRB65.js +0 -341
  185. package/dist/chunk-R2QBMQQN.js +0 -185
  186. package/dist/chunk-T3ALCNCP.js +0 -113
  187. package/dist/chunk-T6UVM534.js +0 -213
  188. package/dist/chunk-U74VYTLX.js +0 -46
  189. package/dist/chunk-UIRCHPOU.js +0 -34
  190. package/dist/chunk-UNS6ZQVX.js +0 -71
  191. package/dist/chunk-VJMTX3OR.js +0 -115
  192. package/dist/chunk-XJSPWHNT.js +0 -64
  193. package/dist/chunk-XMZAC2VU.js +0 -84
  194. package/dist/chunk-Y7FKURZG.js +0 -130
  195. package/dist/chunk-YMSJCSRG.js +0 -213
  196. package/dist/chunk-YQIWS5V6.js +0 -172
  197. package/dist/chunk-ZPEI7DRJ.js +0 -66
  198. package/dist/queries/clean-signature.d.ts +0 -9
  199. package/dist/queries/clean-signature.js +0 -7
@@ -1,2542 +0,0 @@
1
- import {
2
- isFunctionLikeSymbol,
3
- isModuleLikeSymbol,
4
- leafName,
5
- leafSuffix,
6
- parseSymbol,
7
- shortenSymbol
8
- } from "./chunk-YMSJCSRG.js";
9
-
10
- // src/source-analysis.ts
11
- import {
12
- existsSync,
13
- readFileSync
14
- } from "fs";
15
- import {
16
- basename,
17
- dirname,
18
- extname,
19
- join,
20
- relative,
21
- resolve
22
- } from "path";
23
- var SOURCE_IMPORT_CACHE = /* @__PURE__ */ new WeakMap();
24
- var SOURCE_EXPORT_CACHE = /* @__PURE__ */ new WeakMap();
25
- var SOURCE_TEXT_CACHE = /* @__PURE__ */ new WeakMap();
26
- var SOURCE_CALL_CACHE = /* @__PURE__ */ new WeakMap();
27
- var SOURCE_BINDING_CACHE = /* @__PURE__ */ new WeakMap();
28
- var INDEXED_PATH_CACHE = /* @__PURE__ */ new WeakMap();
29
- var SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
30
- var PYTHON_SOURCE_EXTENSIONS = [".py", ".pyi"];
31
- var JVM_SOURCE_EXTENSIONS = [".java", ".scala", ".kt", ".kts"];
32
- var RUST_SOURCE_EXTENSIONS = [".rs"];
33
- var RUBY_SOURCE_EXTENSIONS = [".rb"];
34
- var C_LIKE_SOURCE_EXTENSIONS = [".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".hh", ".hxx"];
35
- var DOTNET_SOURCE_EXTENSIONS = [".cs", ".vb"];
36
- var DART_SOURCE_EXTENSIONS = [".dart"];
37
- var PHP_SOURCE_EXTENSIONS = [".php"];
38
- function getSourceImports(db, relativePath) {
39
- const cache = getCachedMap(SOURCE_IMPORT_CACHE, db);
40
- const normalized = normalizePath(relativePath);
41
- const cached = cache.get(normalized);
42
- if (cached) {
43
- return cached;
44
- }
45
- const fullPath = join(db.config.projectRoot, normalized);
46
- if (!existsSync(fullPath)) {
47
- cache.set(normalized, []);
48
- return [];
49
- }
50
- const source = readFileSync(fullPath, "utf-8");
51
- const parsed = isPythonSourcePath(normalized) ? parsePythonImports(db, normalized, source) : isJavaScriptSourcePath(normalized) ? parseJavaScriptImports(db, normalized, source) : isJvmSourcePath(normalized) ? parseJvmImports(db, normalized, source) : isRustSourcePath(normalized) ? parseRustImports(db, normalized, source) : isRubySourcePath(normalized) ? parseRubyImports(db, normalized, source) : isCLikeSourcePath(normalized) ? parseCLikeImports(db, normalized, source) : isDotNetSourcePath(normalized) ? parseDotNetImports(db, normalized, source) : isDartSourcePath(normalized) ? parseDartImports(db, normalized, source) : isPhpSourcePath(normalized) ? parsePhpImports(db, normalized, source) : [];
52
- cache.set(normalized, parsed);
53
- return parsed;
54
- }
55
- function getSourceExports(db, relativePath) {
56
- const cache = getCachedMap(SOURCE_EXPORT_CACHE, db);
57
- const normalized = normalizePath(relativePath);
58
- const cached = cache.get(normalized);
59
- if (cached) {
60
- return cached;
61
- }
62
- const fullPath = join(db.config.projectRoot, normalized);
63
- if (!existsSync(fullPath)) {
64
- cache.set(normalized, []);
65
- return [];
66
- }
67
- const source = readFileSync(fullPath, "utf-8");
68
- const parsed = isDartSourcePath(normalized) ? parseDartExports(db, normalized, source) : isRustSourcePath(normalized) ? parseRustExports(db, normalized, source) : [];
69
- cache.set(normalized, parsed);
70
- return parsed;
71
- }
72
- function getSourceCalls(db, relativePath, opts = {}) {
73
- const normalized = normalizePath(relativePath);
74
- if (!isPythonSourcePath(normalized) && !isJavaScriptSourcePath(normalized)) {
75
- return [];
76
- }
77
- const cache = getCachedMap(SOURCE_CALL_CACHE, db);
78
- const key = `${normalized}:${opts.startLine ?? 0}:${opts.endLine ?? Number.MAX_SAFE_INTEGER}`;
79
- const cached = cache.get(key);
80
- if (cached) {
81
- return cached;
82
- }
83
- const source = getSourceText(db, normalized);
84
- if (!source) {
85
- cache.set(key, []);
86
- return [];
87
- }
88
- const lines = source.split("\n");
89
- const startLine = Math.max(0, opts.startLine ?? 0);
90
- const endLine = Math.min(lines.length - 1, opts.endLine ?? lines.length - 1);
91
- const scopedLines = lines.slice(startLine, endLine + 1);
92
- const calls = isPythonSourcePath(normalized) ? parsePythonCalls(scopedLines, startLine) : parseJavaScriptCalls(scopedLines, startLine);
93
- cache.set(key, calls);
94
- return calls;
95
- }
96
- function getSourceConstructorBindings(db, relativePath, opts = {}) {
97
- const normalized = normalizePath(relativePath);
98
- if (!isPythonSourcePath(normalized) && !isJavaScriptSourcePath(normalized)) {
99
- return [];
100
- }
101
- const cache = getCachedMap(SOURCE_BINDING_CACHE, db);
102
- const key = `${normalized}:${opts.startLine ?? 0}:${opts.endLine ?? Number.MAX_SAFE_INTEGER}`;
103
- const cached = cache.get(key);
104
- if (cached) {
105
- return cached;
106
- }
107
- const source = getSourceText(db, normalized);
108
- if (!source) {
109
- cache.set(key, []);
110
- return [];
111
- }
112
- const lines = source.split("\n");
113
- const startLine = Math.max(0, opts.startLine ?? 0);
114
- const endLine = Math.min(lines.length - 1, opts.endLine ?? lines.length - 1);
115
- const scopedLines = lines.slice(startLine, endLine + 1);
116
- const bindings = isPythonSourcePath(normalized) ? parsePythonConstructorBindings(scopedLines) : parseJavaScriptConstructorBindings(scopedLines);
117
- cache.set(key, bindings);
118
- return bindings;
119
- }
120
- function findIdentifierLines(db, relativePath, identifier, opts = {}) {
121
- if (!identifier) {
122
- return [];
123
- }
124
- const source = getSourceText(db, normalizePath(relativePath));
125
- if (!source) {
126
- return [];
127
- }
128
- const lines = stripCommentsAndStrings(source).split("\n");
129
- const regex = new RegExp(`\\b${escapeRegex(identifier)}\\b`);
130
- const results = [];
131
- for (let line = 0; line < lines.length; line++) {
132
- if (typeof opts.excludeStartLine === "number" && typeof opts.excludeEndLine === "number" && line >= opts.excludeStartLine && line <= opts.excludeEndLine) {
133
- continue;
134
- }
135
- if (regex.test(lines[line] ?? "")) {
136
- results.push(line);
137
- }
138
- }
139
- return results;
140
- }
141
- function parseJavaScriptImports(db, importerPath, source) {
142
- return parseJavaScriptImportStatements(source).flatMap((statement) => parseJavaScriptImportStatement(
143
- db,
144
- importerPath,
145
- statement.clause,
146
- statement.specifier,
147
- statement.start,
148
- statement.end,
149
- source
150
- ));
151
- }
152
- function parseJavaScriptImportStatements(source) {
153
- const statements = [];
154
- const importFromRegex = /^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;
155
- for (const match of source.matchAll(importFromRegex)) {
156
- const full = match[0];
157
- const clause = match[1];
158
- const specifier = match[2];
159
- if (!full || !specifier || typeof match.index !== "number") continue;
160
- statements.push({
161
- clause,
162
- specifier,
163
- start: match.index,
164
- end: match.index + full.length
165
- });
166
- }
167
- const sideEffectRegex = /^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;
168
- for (const match of source.matchAll(sideEffectRegex)) {
169
- const full = match[0];
170
- const specifier = match[1];
171
- if (!full || !specifier || typeof match.index !== "number") continue;
172
- statements.push({
173
- clause: null,
174
- specifier,
175
- start: match.index,
176
- end: match.index + full.length
177
- });
178
- }
179
- return statements.sort((a, b) => a.start - b.start);
180
- }
181
- function parseJavaScriptImportStatement(db, importerPath, clause, specifier, start, end, source) {
182
- const resolvedSource = resolveImportPath(db, importerPath, specifier);
183
- const body = buildUsageBody(source, start, end);
184
- if (!clause) {
185
- return [{
186
- importedName: "*",
187
- localName: null,
188
- sourcePath: resolvedSource,
189
- kind: "side-effect",
190
- used: true,
191
- usedMembers: []
192
- }];
193
- }
194
- const bindings = parseImportClause(clause).map((binding) => ({
195
- ...binding,
196
- sourcePath: resolvedSource
197
- }));
198
- return bindings.map((binding) => {
199
- if (binding.kind === "namespace") {
200
- const usedMembers = collectNamespaceMembers(body, binding.localName);
201
- return {
202
- ...binding,
203
- used: usedMembers.length > 0 || hasIdentifierUsage(body, binding.localName),
204
- usedMembers
205
- };
206
- }
207
- if (binding.kind === "side-effect") {
208
- return { ...binding, used: true, usedMembers: [] };
209
- }
210
- return {
211
- ...binding,
212
- used: binding.localName ? hasIdentifierUsage(body, binding.localName) : false,
213
- usedMembers: []
214
- };
215
- });
216
- }
217
- function parseJvmImports(db, importerPath, source) {
218
- const statements = [];
219
- for (const match of source.matchAll(/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm)) {
220
- const clause = match[1]?.trim();
221
- const full = match[0];
222
- if (!clause || !full || typeof match.index !== "number") continue;
223
- const body = buildUsageBody(source, match.index, match.index + full.length);
224
- statements.push(...parseJvmImportClause(db, importerPath, clause, body));
225
- }
226
- return statements;
227
- }
228
- function parseJvmImportClause(db, importerPath, clause, body) {
229
- if (clause.includes("{") && clause.includes("}")) {
230
- const prefix = clause.slice(0, clause.indexOf("{")).replace(/\.$/, "").trim();
231
- const inner = clause.slice(clause.indexOf("{") + 1, clause.lastIndexOf("}")).trim();
232
- return splitTopLevel(inner).flatMap((entry) => {
233
- const cleaned = entry.trim();
234
- if (!cleaned) return [];
235
- const [importedPart, aliasPart] = cleaned.includes("=>") ? cleaned.split(/\s*=>\s*/) : cleaned.split(/\s+as\s+/);
236
- const importedName = importedPart?.trim();
237
- if (!importedName || importedName === "_") return [];
238
- const localName = (aliasPart ?? importedName.split(".").pop() ?? importedName).trim();
239
- const qualified = importedName === "_" ? prefix : `${prefix}.${importedName}`.replace(/\.\./g, ".");
240
- return [buildSimpleImport(db, importerPath, body, qualified, importedName, localName)];
241
- });
242
- }
243
- return [buildSimpleImport(
244
- db,
245
- importerPath,
246
- body,
247
- clause,
248
- clause.split(".").pop() ?? clause,
249
- clause.split(".").pop() ?? clause
250
- )];
251
- }
252
- function parseRustImports(db, importerPath, source) {
253
- const statements = [];
254
- for (const match of source.matchAll(/^[ \t]*use\s+(.+?)\s*;$/gm)) {
255
- const clause = match[1]?.trim();
256
- const full = match[0];
257
- if (!clause || !full || typeof match.index !== "number") continue;
258
- const body = buildUsageBody(source, match.index, match.index + full.length);
259
- statements.push(...parseRustUseClause(db, importerPath, clause, body));
260
- }
261
- return statements;
262
- }
263
- function parseRustUseClause(db, importerPath, clause, body) {
264
- const trimmed = clause.trim();
265
- if (trimmed.includes("{") && trimmed.includes("}")) {
266
- const prefix = trimmed.slice(0, trimmed.indexOf("{")).replace(/::$/, "").trim();
267
- const inner = trimmed.slice(trimmed.indexOf("{") + 1, trimmed.lastIndexOf("}")).trim();
268
- return splitTopLevel(inner).flatMap((entry) => {
269
- const cleaned = entry.trim();
270
- if (!cleaned || cleaned === "self") return [];
271
- const [importedPart2, aliasPart2] = cleaned.split(/\s+as\s+/);
272
- const importedName2 = importedPart2?.trim();
273
- if (!importedName2) return [];
274
- const localName2 = (aliasPart2 ?? importedName2.split("::").pop() ?? importedName2).trim();
275
- const moduleSpecifier = `${prefix}::${importedName2}`.replace(/::::/g, "::");
276
- return [buildSimpleImport(
277
- db,
278
- importerPath,
279
- body,
280
- moduleSpecifier,
281
- importedName2.split("::").pop() ?? importedName2,
282
- localName2,
283
- resolveRustImportPath(db, importerPath, prefix)
284
- )];
285
- });
286
- }
287
- const [importedPart, aliasPart] = trimmed.split(/\s+as\s+/);
288
- const importedName = importedPart?.trim() ?? trimmed;
289
- const localName = (aliasPart ?? importedName.split("::").pop() ?? importedName).trim();
290
- const resolved = resolveRustImportPath(db, importerPath, importedName) ?? resolveRustImportPath(db, importerPath, importedName.split("::").slice(0, -1).join("::"));
291
- return [buildSimpleImport(
292
- db,
293
- importerPath,
294
- body,
295
- importedName,
296
- importedName.split("::").pop() ?? importedName,
297
- localName,
298
- resolved
299
- )];
300
- }
301
- function parseRustExports(db, importerPath, source) {
302
- const statements = [];
303
- for (const match of source.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)) {
304
- const clause = match[1]?.trim();
305
- if (!clause) continue;
306
- statements.push(...parseRustExportClause(db, importerPath, clause));
307
- }
308
- return statements;
309
- }
310
- function parseRustExportClause(db, importerPath, clause) {
311
- const trimmed = clause.trim();
312
- if (trimmed.includes("{") && trimmed.includes("}")) {
313
- const prefix = trimmed.slice(0, trimmed.indexOf("{")).replace(/::$/, "").trim();
314
- const inner = trimmed.slice(trimmed.indexOf("{") + 1, trimmed.lastIndexOf("}")).trim();
315
- return splitTopLevel(inner).flatMap((entry) => {
316
- const cleaned = entry.trim();
317
- if (!cleaned || cleaned === "self") return [];
318
- const [qualifiedPart] = cleaned.split(/\s+as\s+/);
319
- const qualified = `${prefix}::${qualifiedPart?.trim() ?? cleaned}`.replace(/::::/g, "::");
320
- return [buildRustExport(db, importerPath, qualified)];
321
- });
322
- }
323
- return [buildRustExport(db, importerPath, trimmed)];
324
- }
325
- function buildRustExport(db, importerPath, specifier) {
326
- return {
327
- specifier,
328
- sourcePath: resolveRustImportPath(db, importerPath, specifier) ?? resolveRustImportPath(db, importerPath, specifier.split("::").slice(0, -1).join("::"))
329
- };
330
- }
331
- function parseRubyImports(db, importerPath, source) {
332
- const statements = [];
333
- for (const match of source.matchAll(/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm)) {
334
- const kind = match[1];
335
- const specifier = match[2];
336
- const full = match[0];
337
- if (!kind || !specifier || !full || typeof match.index !== "number") continue;
338
- const body = buildUsageBody(source, match.index, match.index + full.length);
339
- const sourcePath = kind === "require_relative" ? resolveRubyImportPath(db, importerPath, specifier) : null;
340
- if (sourcePath) {
341
- const localName = rubyConstantName(specifier);
342
- statements.push({
343
- importedName: localName,
344
- localName,
345
- sourcePath,
346
- kind: "named",
347
- used: hasIdentifierUsage(body, localName),
348
- usedMembers: []
349
- });
350
- continue;
351
- }
352
- statements.push({
353
- importedName: specifier,
354
- localName: null,
355
- sourcePath,
356
- kind: "side-effect",
357
- used: true,
358
- usedMembers: []
359
- });
360
- }
361
- return statements;
362
- }
363
- function rubyConstantName(specifier) {
364
- return basename(specifier).replace(/\.[^.]+$/, "").split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
365
- }
366
- function parseCLikeImports(db, importerPath, source) {
367
- const statements = [];
368
- for (const match of source.matchAll(/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm)) {
369
- const specifier = match[1]?.trim();
370
- const full = match[0];
371
- if (!specifier || !full || typeof match.index !== "number") continue;
372
- const body = buildUsageBody(source, match.index, match.index + full.length);
373
- const localName = basename(specifier).replace(/\.[^.]+$/, "");
374
- statements.push({
375
- importedName: specifier,
376
- localName,
377
- sourcePath: resolveCLikeImportPath(db, importerPath, specifier),
378
- kind: "named",
379
- used: hasIdentifierUsage(body, localName),
380
- usedMembers: []
381
- });
382
- }
383
- return statements;
384
- }
385
- function parseDotNetImports(db, importerPath, source) {
386
- const statements = [];
387
- const lineRegex = isVisualBasicSourcePath(importerPath) ? /^[ \t]*Imports\s+(.+?)\s*$/gm : /^[ \t]*using\s+(.+?)\s*;$/gm;
388
- for (const match of source.matchAll(lineRegex)) {
389
- const clause = match[1]?.trim();
390
- const full = match[0];
391
- if (!clause || !full || typeof match.index !== "number") continue;
392
- const body = buildUsageBody(source, match.index, match.index + full.length);
393
- const [aliasPart, targetPart] = isVisualBasicSourcePath(importerPath) ? clause.split(/\s*=\s*/) : clause.split(/\s*=\s*/);
394
- const hasAlias = Boolean(targetPart);
395
- const qualified = (hasAlias ? targetPart : aliasPart)?.trim() ?? clause;
396
- const importedName = qualified.split(".").pop() ?? qualified;
397
- const localName = hasAlias ? aliasPart?.trim() ?? importedName : importedName;
398
- statements.push(buildSimpleImport(
399
- db,
400
- importerPath,
401
- body,
402
- qualified,
403
- importedName,
404
- localName,
405
- resolveQualifiedImportPath(db, qualified, DOTNET_SOURCE_EXTENSIONS)
406
- ));
407
- }
408
- return statements;
409
- }
410
- function parseDartImports(db, importerPath, source) {
411
- const statements = [];
412
- for (const match of source.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)) {
413
- const specifier = match[1]?.trim();
414
- const alias = match[2]?.trim() ?? null;
415
- const full = match[0];
416
- if (!specifier || !full || typeof match.index !== "number") continue;
417
- const body = buildUsageBody(source, match.index, match.index + full.length);
418
- statements.push({
419
- importedName: specifier,
420
- localName: alias,
421
- sourcePath: resolveDartImportPath(db, importerPath, specifier),
422
- kind: alias ? "namespace" : "side-effect",
423
- used: alias ? hasIdentifierUsage(body, alias) : true,
424
- usedMembers: alias ? collectNamespaceMembers(body, alias) : []
425
- });
426
- }
427
- return statements;
428
- }
429
- function parseDartExports(db, importerPath, source) {
430
- const statements = [];
431
- for (const match of source.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)) {
432
- const specifier = match[1]?.trim();
433
- if (!specifier) continue;
434
- statements.push({
435
- specifier,
436
- sourcePath: resolveDartImportPath(db, importerPath, specifier)
437
- });
438
- }
439
- return statements;
440
- }
441
- function parsePhpImports(db, importerPath, source) {
442
- const statements = [];
443
- for (const match of source.matchAll(/^[ \t]*use\s+(.+?)\s*;$/gm)) {
444
- const clause = match[1]?.trim();
445
- const full = match[0];
446
- if (!clause || !full || typeof match.index !== "number") continue;
447
- const body = buildUsageBody(source, match.index, match.index + full.length);
448
- for (const entry of splitTopLevel(clause)) {
449
- const cleaned = entry.trim();
450
- if (!cleaned) continue;
451
- const [qualifiedPart, aliasPart] = cleaned.split(/\s+as\s+/i);
452
- const qualified = qualifiedPart?.trim() ?? cleaned;
453
- const importedName = qualified.split("\\").pop() ?? qualified;
454
- const localName = (aliasPart ?? importedName).trim();
455
- statements.push(buildSimpleImport(
456
- db,
457
- importerPath,
458
- body,
459
- qualified,
460
- importedName,
461
- localName,
462
- resolveQualifiedImportPath(db, qualified.replace(/\\/g, "."), PHP_SOURCE_EXTENSIONS)
463
- ));
464
- }
465
- }
466
- return statements;
467
- }
468
- function buildSimpleImport(db, importerPath, body, qualifiedName, importedName, localName, sourcePath) {
469
- return {
470
- importedName,
471
- localName,
472
- sourcePath: sourcePath ?? resolveQualifiedImportPath(db, qualifiedName, extensionFamilyFor(importerPath)),
473
- kind: "named",
474
- used: hasIdentifierUsage(body, localName),
475
- usedMembers: []
476
- };
477
- }
478
- function parsePythonCalls(lines, baseLine) {
479
- const calls = [];
480
- const controlKeywords = /* @__PURE__ */ new Set([
481
- "if",
482
- "for",
483
- "while",
484
- "with",
485
- "except",
486
- "elif",
487
- "return",
488
- "yield",
489
- "assert",
490
- "raise",
491
- "lambda",
492
- "class",
493
- "def"
494
- ]);
495
- for (let index = 0; index < lines.length; index++) {
496
- const rawLine = lines[index] ?? "";
497
- const stripped = stripCommentsAndStrings(rawLine);
498
- if (!stripped.trim()) continue;
499
- const attributeMatches = [...stripped.matchAll(/\b([A-Za-z_][\w]*)\s*\.\s*([A-Za-z_][\w]*)\s*\(/g)];
500
- const attributeRanges = attributeMatches.map((match) => ({
501
- start: match.index ?? -1,
502
- end: (match.index ?? -1) + match[0].length
503
- }));
504
- for (const match of attributeMatches) {
505
- const receiverName = match[1];
506
- const calleeName = match[2];
507
- if (!receiverName || !calleeName) continue;
508
- calls.push({
509
- receiverName,
510
- calleeName,
511
- line: baseLine + index
512
- });
513
- }
514
- for (const match of stripped.matchAll(/\b([A-Za-z_][\w]*)\s*\(/g)) {
515
- const calleeName = match[1];
516
- const start = match.index ?? -1;
517
- if (!calleeName || start < 0) continue;
518
- if (controlKeywords.has(calleeName)) continue;
519
- if (attributeRanges.some((range) => start >= range.start && start < range.end)) continue;
520
- const prefix = stripped.slice(0, start).trimEnd();
521
- if (prefix.endsWith("def") || prefix.endsWith("class") || prefix.endsWith("async def")) {
522
- continue;
523
- }
524
- calls.push({
525
- receiverName: null,
526
- calleeName,
527
- line: baseLine + index
528
- });
529
- }
530
- }
531
- return calls;
532
- }
533
- function parseJavaScriptCalls(lines, baseLine) {
534
- const calls = [];
535
- const controlKeywords = /* @__PURE__ */ new Set([
536
- "if",
537
- "for",
538
- "while",
539
- "switch",
540
- "catch",
541
- "function",
542
- "class",
543
- "return",
544
- "typeof",
545
- "import"
546
- ]);
547
- for (let index = 0; index < lines.length; index++) {
548
- const stripped = stripCommentsAndStrings(lines[index] ?? "");
549
- if (!stripped.trim()) continue;
550
- const attributeMatches = [
551
- ...stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)\s*\(/g),
552
- ...stripped.matchAll(/\bthis\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)\s*\(/g)
553
- ];
554
- const attributeRanges = attributeMatches.map((match) => ({
555
- start: match.index ?? -1,
556
- end: (match.index ?? -1) + match[0].length
557
- }));
558
- for (const match of attributeMatches) {
559
- const receiverName = match[2] ? match[1] : "this";
560
- const calleeName = match[2] ?? match[1];
561
- if (!receiverName || !calleeName) continue;
562
- calls.push({
563
- receiverName,
564
- calleeName,
565
- line: baseLine + index
566
- });
567
- }
568
- for (const match of stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)) {
569
- const calleeName = match[1];
570
- const start = match.index ?? -1;
571
- if (!calleeName || start < 0) continue;
572
- if (controlKeywords.has(calleeName)) continue;
573
- if (attributeRanges.some((range) => start >= range.start && start < range.end)) continue;
574
- const prefix = stripped.slice(0, start).trimEnd();
575
- if (prefix.endsWith("function") || prefix.endsWith("class") || prefix.endsWith("new")) {
576
- continue;
577
- }
578
- calls.push({
579
- receiverName: null,
580
- calleeName,
581
- line: baseLine + index
582
- });
583
- }
584
- }
585
- return calls;
586
- }
587
- function parsePythonConstructorBindings(lines) {
588
- const bindings = /* @__PURE__ */ new Map();
589
- for (const rawLine of lines) {
590
- const stripped = stripCommentsAndStrings(rawLine);
591
- const constructorMatch = stripped.match(/\b([A-Za-z_][\w]*)\s*=\s*([A-Z][\w]*)\s*\(/);
592
- if (constructorMatch?.[1] && constructorMatch[2]) {
593
- bindings.set(constructorMatch[1], constructorMatch[2]);
594
- }
595
- }
596
- return [...bindings.entries()].map(([localName, typeName]) => ({ localName, typeName }));
597
- }
598
- function parseJavaScriptConstructorBindings(lines) {
599
- const bindings = /* @__PURE__ */ new Map();
600
- for (const rawLine of lines) {
601
- const stripped = stripCommentsAndStrings(rawLine);
602
- for (const match of stripped.matchAll(/\b([A-Za-z_$][\w$]*)\s*:\s*([A-Z][A-Za-z0-9_$]*)\b/g)) {
603
- const localName = match[1];
604
- const typeName = match[2];
605
- if (localName && typeName) {
606
- bindings.set(localName, typeName);
607
- }
608
- }
609
- const constructorMatch = stripped.match(/\b(?:const|let|var)?\s*([A-Za-z_$][\w$]*)\s*(?::\s*[A-Z][A-Za-z0-9_$<> ,]*)?\s*=\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\(/);
610
- if (constructorMatch?.[1] && constructorMatch[2]) {
611
- bindings.set(constructorMatch[1], constructorMatch[2]);
612
- }
613
- }
614
- return [...bindings.entries()].map(([localName, typeName]) => ({ localName, typeName }));
615
- }
616
- function parsePythonImports(db, importerPath, source) {
617
- return collectPythonImportStatements(source).flatMap(
618
- (statement) => parsePythonImportStatement(db, importerPath, statement, source)
619
- );
620
- }
621
- function collectPythonImportStatements(source) {
622
- const lines = source.split("\n");
623
- const statements = [];
624
- let offset = 0;
625
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
626
- const line = lines[lineIndex];
627
- const trimmed = line.trimStart();
628
- const lineStart = offset;
629
- offset += line.length + 1;
630
- if (!trimmed.startsWith("import ") && !trimmed.startsWith("from ")) {
631
- continue;
632
- }
633
- let statement = line;
634
- let statementEnd = lineStart + line.length;
635
- let balance = pythonParenBalance(line);
636
- while (lineIndex + 1 < lines.length && (balance > 0 || statement.trimEnd().endsWith("\\"))) {
637
- lineIndex++;
638
- const nextLine = lines[lineIndex];
639
- statement += `
640
- ${nextLine}`;
641
- statementEnd += 1 + nextLine.length;
642
- balance += pythonParenBalance(nextLine);
643
- offset += nextLine.length + 1;
644
- }
645
- const parsed = parsePythonStatementHeader(statement);
646
- if (parsed) {
647
- statements.push({
648
- ...parsed,
649
- start: lineStart,
650
- end: statementEnd
651
- });
652
- }
653
- }
654
- return statements;
655
- }
656
- function parsePythonStatementHeader(statement) {
657
- const normalized = statement.replace(/\\\s*\n/g, " ").trim();
658
- if (normalized.startsWith("import ")) {
659
- return {
660
- kind: "import",
661
- module: null,
662
- clause: normalized.slice("import ".length).trim()
663
- };
664
- }
665
- const fromMatch = normalized.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);
666
- if (!fromMatch) {
667
- return null;
668
- }
669
- let clause = fromMatch[2].trim();
670
- if (clause.startsWith("(") && clause.endsWith(")")) {
671
- clause = clause.slice(1, -1).trim();
672
- }
673
- return {
674
- kind: "from",
675
- module: fromMatch[1],
676
- clause
677
- };
678
- }
679
- function parsePythonImportStatement(db, importerPath, statement, source) {
680
- const body = buildUsageBody(source, statement.start, statement.end);
681
- const normalizedClause = statement.clause.replace(/\n/g, " ").trim();
682
- if (statement.kind === "import") {
683
- return splitTopLevel(normalizedClause).flatMap((entry) => {
684
- const cleaned = entry.trim().replace(/,$/, "");
685
- if (!cleaned) return [];
686
- const [moduleName, alias] = cleaned.split(/\s+as\s+/);
687
- const importedName = moduleName.trim();
688
- const localName = (alias ?? importedName.split(".")[0] ?? importedName).trim();
689
- const sourcePath2 = resolvePythonImportPath(db, importerPath, importedName);
690
- const usedMembers = collectNamespaceMembers(body, localName);
691
- return [{
692
- importedName,
693
- localName,
694
- sourcePath: sourcePath2,
695
- kind: "namespace",
696
- used: hasIdentifierUsage(body, localName) || usedMembers.length > 0,
697
- usedMembers
698
- }];
699
- });
700
- }
701
- const sourcePath = statement.module ? resolvePythonImportPath(db, importerPath, statement.module) : null;
702
- const results = [];
703
- for (const entry of splitTopLevel(normalizedClause)) {
704
- const cleaned = entry.trim().replace(/,$/, "");
705
- if (!cleaned) continue;
706
- if (cleaned === "*") {
707
- results.push({
708
- importedName: "*",
709
- localName: null,
710
- sourcePath,
711
- kind: "side-effect",
712
- used: true,
713
- usedMembers: []
714
- });
715
- continue;
716
- }
717
- const [importedName, alias] = cleaned.split(/\s+as\s+/);
718
- const localName = (alias ?? importedName).trim();
719
- results.push({
720
- importedName: importedName.trim(),
721
- localName,
722
- sourcePath,
723
- kind: "named",
724
- used: hasIdentifierUsage(body, localName),
725
- usedMembers: []
726
- });
727
- }
728
- return results;
729
- }
730
- function parseImportClause(clause) {
731
- const trimmed = clause.trim().replace(/^type\s+/, "");
732
- const [first, second] = splitImportClause(trimmed);
733
- const entries = [];
734
- if (first) {
735
- entries.push(...parseImportBinding(first));
736
- }
737
- if (second) {
738
- entries.push(...parseImportBinding(second));
739
- }
740
- return entries;
741
- }
742
- function parseImportBinding(binding) {
743
- const trimmed = binding.trim();
744
- if (!trimmed) return [];
745
- if (trimmed.startsWith("{")) {
746
- const inner = trimmed.slice(1, -1).trim();
747
- if (!inner) return [];
748
- return splitTopLevel(inner).map((entry) => {
749
- const cleaned = entry.trim().replace(/^type\s+/, "");
750
- const [importedName, alias] = cleaned.split(/\s+as\s+/);
751
- return {
752
- importedName: importedName.trim(),
753
- localName: (alias ?? importedName).trim(),
754
- kind: "named"
755
- };
756
- });
757
- }
758
- if (trimmed.startsWith("* as ")) {
759
- return [{
760
- importedName: "*",
761
- localName: trimmed.slice(5).trim(),
762
- kind: "namespace"
763
- }];
764
- }
765
- return [{
766
- importedName: "default",
767
- localName: trimmed,
768
- kind: "default"
769
- }];
770
- }
771
- function splitImportClause(clause) {
772
- let depth = 0;
773
- for (let i = 0; i < clause.length; i++) {
774
- const char = clause[i];
775
- if (char === "{") depth++;
776
- if (char === "}") depth--;
777
- if (char === "," && depth === 0) {
778
- return [clause.slice(0, i).trim(), clause.slice(i + 1).trim()];
779
- }
780
- }
781
- return [clause.trim(), null];
782
- }
783
- function splitTopLevel(input) {
784
- const parts = [];
785
- let depth = 0;
786
- let start = 0;
787
- for (let i = 0; i < input.length; i++) {
788
- const char = input[i];
789
- if (char === "{" || char === "[" || char === "(") depth++;
790
- if (char === "}" || char === "]" || char === ")") depth--;
791
- if (char === "," && depth === 0) {
792
- parts.push(input.slice(start, i));
793
- start = i + 1;
794
- }
795
- }
796
- parts.push(input.slice(start));
797
- return parts;
798
- }
799
- function buildUsageBody(source, start, end) {
800
- const masked = `${source.slice(0, start)}${" ".repeat(end - start)}${source.slice(end)}`;
801
- return stripCommentsAndStrings(masked);
802
- }
803
- function stripCommentsAndStrings(source) {
804
- return source.replace(/'''[\s\S]*?'''/g, maskPreservingLines).replace(/"""[\s\S]*?"""/g, maskPreservingLines).replace(/#.*$/gm, maskPreservingLines).replace(/\/\/.*$/gm, maskPreservingLines).replace(/\/\*[\s\S]*?\*\//g, maskPreservingLines).replace(/`(?:\\[\s\S]|[^`])*`/g, maskPreservingLines).replace(/'(?:\\.|[^'\\\r\n])*'/g, maskPreservingLines).replace(/"(?:\\.|[^"\\\r\n])*"/g, maskPreservingLines);
805
- }
806
- function maskPreservingLines(segment) {
807
- return segment.replace(/[^\r\n]/g, " ");
808
- }
809
- function hasIdentifierUsage(body, identifier) {
810
- return new RegExp(`\\b${escapeRegex(identifier)}\\b`, "m").test(body);
811
- }
812
- function collectNamespaceMembers(body, namespaceName) {
813
- const members = /* @__PURE__ */ new Set();
814
- const regex = new RegExp(`\\b${escapeRegex(namespaceName)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`, "g");
815
- for (const match of body.matchAll(regex)) {
816
- const member = match[1];
817
- if (member) {
818
- members.add(member);
819
- }
820
- }
821
- return [...members];
822
- }
823
- function resolveImportPath(db, importerPath, specifier) {
824
- if (isPythonSourcePath(importerPath)) {
825
- return resolvePythonImportPath(db, importerPath, specifier);
826
- }
827
- if (isRustSourcePath(importerPath)) {
828
- return resolveRustImportPath(db, importerPath, specifier);
829
- }
830
- if (isRubySourcePath(importerPath)) {
831
- return resolveRubyImportPath(db, importerPath, specifier);
832
- }
833
- if (isCLikeSourcePath(importerPath)) {
834
- return resolveCLikeImportPath(db, importerPath, specifier);
835
- }
836
- if (isJvmSourcePath(importerPath) || isDotNetSourcePath(importerPath) || isPhpSourcePath(importerPath)) {
837
- return resolveQualifiedImportPath(db, specifier.replace(/\\/g, "."), extensionFamilyFor(importerPath));
838
- }
839
- if (isDartSourcePath(importerPath)) {
840
- return resolveDartImportPath(db, importerPath, specifier);
841
- }
842
- return resolveJavaScriptImportPath(db, importerPath, specifier);
843
- }
844
- function resolveJavaScriptImportPath(db, importerPath, specifier) {
845
- if (!specifier.startsWith(".") && !specifier.startsWith("/")) {
846
- return null;
847
- }
848
- const importerDir = dirname(join(db.config.projectRoot, importerPath));
849
- const absolute = resolve(importerDir, specifier);
850
- const indexedPaths = getIndexedPaths(db);
851
- for (const candidate of candidateImportPaths(absolute)) {
852
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
853
- if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
854
- return relativeCandidate;
855
- }
856
- }
857
- return normalizePath(relative(db.config.projectRoot, absolute));
858
- }
859
- function resolvePythonImportPath(db, importerPath, specifier) {
860
- const indexedPaths = getIndexedPaths(db);
861
- let basePath;
862
- if (specifier.startsWith(".")) {
863
- const match = specifier.match(/^(\.+)(.*)$/);
864
- if (!match) return null;
865
- const dots = match[1].length;
866
- const remainder = match[2].replace(/^\./, "");
867
- let baseDir = dirname(join(db.config.projectRoot, importerPath));
868
- for (let i = 1; i < dots; i++) {
869
- baseDir = dirname(baseDir);
870
- }
871
- basePath = remainder ? resolve(baseDir, remainder.replace(/\./g, "/")) : baseDir;
872
- } else {
873
- basePath = resolve(db.config.projectRoot, specifier.replace(/\./g, "/"));
874
- }
875
- for (const candidate of pythonCandidateImportPaths(basePath)) {
876
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
877
- if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
878
- return relativeCandidate;
879
- }
880
- }
881
- return null;
882
- }
883
- function resolveRustImportPath(db, importerPath, specifier) {
884
- if (!specifier) return null;
885
- const normalizedSpecifier = specifier.replace(/\s+as\s+.+$/, "").trim();
886
- if (!normalizedSpecifier.startsWith("crate::") && !normalizedSpecifier.startsWith("self::") && !normalizedSpecifier.startsWith("super::")) {
887
- return null;
888
- }
889
- const importerDir = dirname(join(db.config.projectRoot, importerPath));
890
- let basePath;
891
- if (normalizedSpecifier.startsWith("crate::")) {
892
- basePath = resolve(db.config.projectRoot, "src", normalizedSpecifier.slice("crate::".length).replace(/::/g, "/"));
893
- } else if (normalizedSpecifier.startsWith("self::")) {
894
- basePath = resolve(importerDir, normalizedSpecifier.slice("self::".length).replace(/::/g, "/"));
895
- } else {
896
- basePath = resolve(dirname(importerDir), normalizedSpecifier.slice("super::".length).replace(/::/g, "/"));
897
- }
898
- for (const candidate of rustCandidateImportPaths(basePath)) {
899
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
900
- if (getIndexedPaths(db).has(relativeCandidate) || existsSync(candidate)) {
901
- return relativeCandidate;
902
- }
903
- }
904
- return null;
905
- }
906
- function resolveRubyImportPath(db, importerPath, specifier) {
907
- const importerDir = dirname(join(db.config.projectRoot, importerPath));
908
- const absolute = resolve(importerDir, specifier);
909
- for (const candidate of rubyCandidateImportPaths(absolute)) {
910
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
911
- if (getIndexedPaths(db).has(relativeCandidate) || existsSync(candidate)) {
912
- return relativeCandidate;
913
- }
914
- }
915
- return null;
916
- }
917
- function resolveCLikeImportPath(db, importerPath, specifier) {
918
- const indexedPaths = getIndexedPaths(db);
919
- const importerDir = dirname(join(db.config.projectRoot, importerPath));
920
- const candidates = [
921
- resolve(importerDir, specifier),
922
- resolve(db.config.projectRoot, specifier),
923
- resolve(db.config.projectRoot, "include", specifier),
924
- resolve(db.config.projectRoot, "src", specifier)
925
- ];
926
- for (const candidate of candidates) {
927
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
928
- if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
929
- return relativeCandidate;
930
- }
931
- }
932
- return null;
933
- }
934
- function resolveQualifiedImportPath(db, specifier, extensions) {
935
- const indexedPaths = getIndexedPaths(db);
936
- const normalized = specifier.replace(/\\/g, ".").replace(/::/g, ".").replace(/^global::/, "");
937
- const pathified = normalized.replace(/\./g, "/");
938
- const basenameOnly = normalized.split(".").pop() ?? normalized;
939
- for (const ext of extensions) {
940
- const exactSuffix = `${pathified}${ext}`;
941
- const exact = [...indexedPaths].find((relativePath) => relativePath.endsWith(exactSuffix));
942
- if (exact) return exact;
943
- }
944
- for (const ext of extensions) {
945
- const basenameMatch = [...indexedPaths].find((relativePath) => basename(relativePath) === `${basenameOnly}${ext}`);
946
- if (basenameMatch) return basenameMatch;
947
- }
948
- const folderMatches = [...indexedPaths].filter((relativePath) => extensions.includes(extname(relativePath).toLowerCase())).filter((relativePath) => relativePath.includes(`/${pathified}/`) || relativePath.includes(`/${basenameOnly}/`)).sort((left, right) => left.localeCompare(right));
949
- if (folderMatches.length === 1) {
950
- return folderMatches[0];
951
- }
952
- return null;
953
- }
954
- function resolveDartImportPath(db, importerPath, specifier) {
955
- const indexedPaths = getIndexedPaths(db);
956
- if (specifier.startsWith("package:")) {
957
- const withoutScheme = specifier.slice("package:".length);
958
- const slashIndex = withoutScheme.indexOf("/");
959
- if (slashIndex < 0) return null;
960
- const packageRelative = withoutScheme.slice(slashIndex + 1);
961
- const candidate = normalizePath(packageRelative.startsWith("lib/") ? packageRelative : `lib/${packageRelative}`);
962
- if (indexedPaths.has(candidate)) return candidate;
963
- return null;
964
- }
965
- const importerDir = dirname(join(db.config.projectRoot, importerPath));
966
- const absolute = resolve(importerDir, specifier);
967
- for (const candidate of dartCandidateImportPaths(absolute)) {
968
- const relativeCandidate = normalizePath(relative(db.config.projectRoot, candidate));
969
- if (indexedPaths.has(relativeCandidate) || existsSync(candidate)) {
970
- return relativeCandidate;
971
- }
972
- }
973
- return null;
974
- }
975
- function pythonCandidateImportPaths(basePath) {
976
- const ext = extname(basePath);
977
- if (PYTHON_SOURCE_EXTENSIONS.includes(ext)) {
978
- return [basePath];
979
- }
980
- return [
981
- `${basePath}.py`,
982
- `${basePath}.pyi`,
983
- join(basePath, "__init__.py"),
984
- join(basePath, "__init__.pyi")
985
- ];
986
- }
987
- function rustCandidateImportPaths(basePath) {
988
- const ext = extname(basePath);
989
- if (RUST_SOURCE_EXTENSIONS.includes(ext)) {
990
- return [basePath];
991
- }
992
- return [
993
- `${basePath}.rs`,
994
- join(basePath, "mod.rs")
995
- ];
996
- }
997
- function rubyCandidateImportPaths(basePath) {
998
- const ext = extname(basePath);
999
- if (RUBY_SOURCE_EXTENSIONS.includes(ext)) {
1000
- return [basePath];
1001
- }
1002
- return [
1003
- `${basePath}.rb`,
1004
- join(basePath, "index.rb")
1005
- ];
1006
- }
1007
- function dartCandidateImportPaths(basePath) {
1008
- const ext = extname(basePath);
1009
- if (DART_SOURCE_EXTENSIONS.includes(ext)) {
1010
- return [basePath];
1011
- }
1012
- return [`${basePath}.dart`, basePath];
1013
- }
1014
- function candidateImportPaths(absolute) {
1015
- const ext = extname(absolute);
1016
- const candidates = /* @__PURE__ */ new Set();
1017
- if (ext) {
1018
- candidates.add(absolute);
1019
- for (const sourceExt of SOURCE_EXTENSIONS) {
1020
- candidates.add(absolute.slice(0, -ext.length) + sourceExt);
1021
- }
1022
- } else {
1023
- for (const sourceExt of SOURCE_EXTENSIONS) {
1024
- candidates.add(`${absolute}${sourceExt}`);
1025
- candidates.add(join(absolute, `index${sourceExt}`));
1026
- }
1027
- }
1028
- return [...candidates];
1029
- }
1030
- function getIndexedPaths(db) {
1031
- const cached = INDEXED_PATH_CACHE.get(db);
1032
- if (cached) {
1033
- return cached;
1034
- }
1035
- const paths = new Set(
1036
- db.all(
1037
- `SELECT relative_path
1038
- FROM documents
1039
- WHERE 1 = 1
1040
- ${db.pathExclusionsFor("documents")}`
1041
- ).map((row) => normalizePath(row.relative_path)).filter((relativePath) => !db.isIgnored(relativePath))
1042
- );
1043
- INDEXED_PATH_CACHE.set(db, paths);
1044
- return paths;
1045
- }
1046
- function getCachedMap(cache, db) {
1047
- let map = cache.get(db);
1048
- if (!map) {
1049
- map = /* @__PURE__ */ new Map();
1050
- cache.set(db, map);
1051
- }
1052
- return map;
1053
- }
1054
- function normalizePath(path) {
1055
- return path.replace(/\\/g, "/");
1056
- }
1057
- var LANGUAGE_EXTENSION_FAMILIES = [
1058
- SOURCE_EXTENSIONS,
1059
- PYTHON_SOURCE_EXTENSIONS,
1060
- JVM_SOURCE_EXTENSIONS,
1061
- RUST_SOURCE_EXTENSIONS,
1062
- RUBY_SOURCE_EXTENSIONS,
1063
- C_LIKE_SOURCE_EXTENSIONS,
1064
- DOTNET_SOURCE_EXTENSIONS,
1065
- DART_SOURCE_EXTENSIONS,
1066
- PHP_SOURCE_EXTENSIONS
1067
- ];
1068
- function hasExtensionIn(relativePath, extensions) {
1069
- return extensions.includes(extname(relativePath).toLowerCase());
1070
- }
1071
- function isJavaScriptSourcePath(relativePath) {
1072
- return hasExtensionIn(relativePath, SOURCE_EXTENSIONS);
1073
- }
1074
- function isPythonSourcePath(relativePath) {
1075
- return hasExtensionIn(relativePath, PYTHON_SOURCE_EXTENSIONS);
1076
- }
1077
- function isJvmSourcePath(relativePath) {
1078
- return hasExtensionIn(relativePath, JVM_SOURCE_EXTENSIONS);
1079
- }
1080
- function isRustSourcePath(relativePath) {
1081
- return hasExtensionIn(relativePath, RUST_SOURCE_EXTENSIONS);
1082
- }
1083
- function isRubySourcePath(relativePath) {
1084
- return hasExtensionIn(relativePath, RUBY_SOURCE_EXTENSIONS);
1085
- }
1086
- function isCLikeSourcePath(relativePath) {
1087
- return hasExtensionIn(relativePath, C_LIKE_SOURCE_EXTENSIONS);
1088
- }
1089
- function isDotNetSourcePath(relativePath) {
1090
- return hasExtensionIn(relativePath, DOTNET_SOURCE_EXTENSIONS);
1091
- }
1092
- function isVisualBasicSourcePath(relativePath) {
1093
- return extname(relativePath).toLowerCase() === ".vb";
1094
- }
1095
- function isDartSourcePath(relativePath) {
1096
- return hasExtensionIn(relativePath, DART_SOURCE_EXTENSIONS);
1097
- }
1098
- function isPhpSourcePath(relativePath) {
1099
- return hasExtensionIn(relativePath, PHP_SOURCE_EXTENSIONS);
1100
- }
1101
- function extensionFamilyFor(relativePath) {
1102
- const ext = extname(relativePath).toLowerCase();
1103
- for (const family of LANGUAGE_EXTENSION_FAMILIES) {
1104
- if (family.includes(ext)) return family;
1105
- }
1106
- return SOURCE_EXTENSIONS;
1107
- }
1108
- function getSourceText(db, relativePath) {
1109
- const cache = getCachedMap(SOURCE_TEXT_CACHE, db);
1110
- const normalized = normalizePath(relativePath);
1111
- const cached = cache.get(normalized);
1112
- if (typeof cached === "string") {
1113
- return cached;
1114
- }
1115
- const fullPath = join(db.config.projectRoot, normalized);
1116
- if (!existsSync(fullPath)) {
1117
- cache.set(normalized, "");
1118
- return "";
1119
- }
1120
- const source = readFileSync(fullPath, "utf-8");
1121
- cache.set(normalized, source);
1122
- return source;
1123
- }
1124
- function pythonParenBalance(value) {
1125
- let balance = 0;
1126
- for (const char of value) {
1127
- if (char === "(") balance++;
1128
- if (char === ")") balance--;
1129
- }
1130
- return balance;
1131
- }
1132
- function escapeRegex(value) {
1133
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1134
- }
1135
-
1136
- // src/query-support.ts
1137
- import { basename as basename2 } from "path";
1138
- var FILE_DEFINITION_CACHE = /* @__PURE__ */ new WeakMap();
1139
- var TEST_FILE_PATTERNS = [
1140
- "%/__tests__/%",
1141
- "%.test.%",
1142
- "%.spec.%",
1143
- "%/test/%",
1144
- "%/tests/%",
1145
- "%_test.%",
1146
- "%_spec.%",
1147
- "%/test_%.%",
1148
- "%/spec_%.%"
1149
- ];
1150
- var TEST_SUPPORT_PATH_PATTERNS = [
1151
- "%/test-utils/%"
1152
- ];
1153
- function testFileExclusionSql(alias, extraPatterns = []) {
1154
- const patterns = uniquePatterns([...TEST_FILE_PATTERNS, ...extraPatterns]);
1155
- return patterns.map((pattern) => `${alias}.relative_path NOT LIKE '${pattern}'`).join("\n AND ");
1156
- }
1157
- function buildFileDepGraph(db, scope) {
1158
- const scopeFilter = scope ? `AND d1.relative_path LIKE '%${scope}%'` : "";
1159
- const edges = db.all(
1160
- `SELECT DISTINCT
1161
- d1.relative_path AS from_file,
1162
- d2.relative_path AS to_file
1163
- FROM mentions m
1164
- JOIN chunks c ON m.chunk_id = c.id
1165
- JOIN documents d1 ON c.document_id = d1.id
1166
- JOIN global_symbols gs ON m.symbol_id = gs.id
1167
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1168
- JOIN documents d2 ON der.document_id = d2.id
1169
- WHERE d1.id != d2.id
1170
- AND m.role != 1
1171
- ${db.pathExclusionsFor("d1", "d2")}
1172
- ${scopeFilter}`
1173
- );
1174
- const graph = /* @__PURE__ */ new Map();
1175
- const indexedFiles = new Set(
1176
- db.all(
1177
- `SELECT relative_path
1178
- FROM documents
1179
- WHERE 1 = 1
1180
- ${db.pathExclusionsFor("documents")}
1181
- ORDER BY relative_path`
1182
- ).map((row) => row.relative_path).filter((relativePath) => !db.isIgnored(relativePath))
1183
- );
1184
- const addEdge = (fromFile, toFile) => {
1185
- if (fromFile === toFile) return;
1186
- if (db.isIgnored(fromFile) || db.isIgnored(toFile)) return;
1187
- if (!indexedFiles.has(toFile)) return;
1188
- if (!graph.has(fromFile)) graph.set(fromFile, /* @__PURE__ */ new Set());
1189
- graph.get(fromFile).add(toFile);
1190
- };
1191
- for (const edge of edges) {
1192
- addEdge(edge.from_file, edge.to_file);
1193
- }
1194
- for (const relativePath of indexedFiles) {
1195
- if (scope && !relativePath.includes(scope)) continue;
1196
- for (const entry of getSourceImports(db, relativePath)) {
1197
- if (!entry.sourcePath) continue;
1198
- addEdge(relativePath, entry.sourcePath);
1199
- }
1200
- }
1201
- return graph;
1202
- }
1203
- function findFirstSymbolMatch(db, symbolPattern) {
1204
- const exact = findExactSymbolMatch(db, symbolPattern.trim());
1205
- if (exact) {
1206
- return exact;
1207
- }
1208
- const fileLineMatch = symbolPattern.match(/^(.+):(\d+)-(\d+)$/);
1209
- if (fileLineMatch) {
1210
- const [, filePath, startStr, endStr] = fileLineMatch;
1211
- let row = db.get(
1212
- `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
1213
- FROM global_symbols gs
1214
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1215
- JOIN documents d ON der.document_id = d.id
1216
- WHERE d.relative_path LIKE ?
1217
- AND der.start_line <= ? AND der.end_line >= ?
1218
- ${db.pathExclusionsFor("d")}
1219
- ORDER BY (der.end_line - der.start_line) ASC
1220
- LIMIT 1`,
1221
- `%${filePath}%`,
1222
- parseInt(startStr, 10),
1223
- parseInt(endStr, 10)
1224
- );
1225
- if (!row) {
1226
- row = db.get(
1227
- `SELECT gs.id, gs.symbol, c.document_id, MIN(c.start_line) AS start_line, MAX(c.end_line) AS end_line, d.relative_path
1228
- FROM global_symbols gs
1229
- JOIN mentions m ON m.symbol_id = gs.id
1230
- JOIN chunks c ON m.chunk_id = c.id
1231
- JOIN documents d ON c.document_id = d.id
1232
- WHERE m.role = 1
1233
- AND d.relative_path LIKE ?
1234
- AND c.start_line <= ? AND c.end_line >= ?
1235
- ${db.pathExclusionsFor("d")}
1236
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
1237
- ORDER BY (MAX(c.end_line) - MIN(c.start_line)) ASC
1238
- LIMIT 1`,
1239
- `%${filePath}%`,
1240
- parseInt(startStr, 10),
1241
- parseInt(endStr, 10)
1242
- );
1243
- }
1244
- if (row && !db.isIgnored(row.relative_path)) {
1245
- return hydrateSymbolMatch(db, row);
1246
- }
1247
- }
1248
- const cleaned = normalizeLookupPattern(symbolPattern);
1249
- const tokens = lookupTokens(symbolPattern);
1250
- const candidates = getSymbolLookupCandidates(db, tokens);
1251
- const direct = findDirectSymbolCandidate(candidates, symbolPattern, cleaned);
1252
- if (direct && !db.isIgnored(direct.relative_path)) {
1253
- return hydrateSymbolMatch(db, direct);
1254
- }
1255
- let best = null;
1256
- for (const row of candidates) {
1257
- if (db.isIgnored(row.relative_path)) continue;
1258
- const score = scoreSymbolCandidate(row, symbolPattern, cleaned, tokens);
1259
- if (score <= 0) continue;
1260
- if (!best || score > best.score) {
1261
- best = { row, score };
1262
- }
1263
- }
1264
- if (best) {
1265
- return hydrateSymbolMatch(db, best.row);
1266
- }
1267
- return null;
1268
- }
1269
- function findExactSymbolMatch(db, symbol) {
1270
- const row = db.get(
1271
- `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path
1272
- FROM global_symbols gs
1273
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1274
- JOIN documents d ON der.document_id = d.id
1275
- WHERE gs.symbol = ?
1276
- ${db.pathExclusionsFor("d")}
1277
- ORDER BY d.relative_path, der.start_line
1278
- LIMIT 1`,
1279
- symbol
1280
- );
1281
- if (!row || db.isIgnored(row.relative_path)) {
1282
- return null;
1283
- }
1284
- return hydrateSymbolMatch(db, row);
1285
- }
1286
- function resolveIndexedFile(db, filePattern) {
1287
- return resolveDocumentCandidates(db, filePattern, { allowMultiple: false })[0]?.relativePath ?? null;
1288
- }
1289
- function resolveIndexedPaths(db, filePattern) {
1290
- return resolveDocumentCandidates(db, filePattern, { allowMultiple: true }).map((candidate) => candidate.relativePath);
1291
- }
1292
- function normalizeLookupPattern(symbolPattern) {
1293
- return symbolPattern.trim().replace(/\(\)$/, "").replace(/\(.*$/, "");
1294
- }
1295
- function lookupTokens(symbolPattern) {
1296
- const cleaned = normalizeLookupPattern(symbolPattern);
1297
- const tokens = cleaned.split(/[^A-Za-z0-9_]+/).map((token) => token.trim()).filter((token) => token.length > 0);
1298
- return tokens.length > 0 ? [...new Set(tokens)] : [cleaned];
1299
- }
1300
- function getSymbolLookupCandidates(db, tokens) {
1301
- const tokenClauses = tokens.map(
1302
- () => `(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)`
1303
- );
1304
- const params = tokens.flatMap((token) => {
1305
- const like = `%${token}%`;
1306
- return [like, like, like];
1307
- });
1308
- const primary = db.all(
1309
- `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name
1310
- FROM global_symbols gs
1311
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1312
- JOIN documents d ON der.document_id = d.id
1313
- WHERE ${tokenClauses.join("\n AND ")}
1314
- ${db.pathExclusionsFor("d")}
1315
- LIMIT 200`,
1316
- ...params
1317
- );
1318
- if (primary.length > 0) {
1319
- return primary;
1320
- }
1321
- return db.all(
1322
- `SELECT
1323
- gs.id,
1324
- gs.symbol,
1325
- c.document_id,
1326
- MIN(c.start_line) AS start_line,
1327
- MAX(c.end_line) AS end_line,
1328
- d.relative_path,
1329
- gs.display_name
1330
- FROM global_symbols gs
1331
- JOIN mentions m ON m.symbol_id = gs.id
1332
- JOIN chunks c ON m.chunk_id = c.id
1333
- JOIN documents d ON c.document_id = d.id
1334
- WHERE m.role = 1
1335
- AND ${tokenClauses.join("\n AND ")}
1336
- ${db.pathExclusionsFor("d")}
1337
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name
1338
- LIMIT 200`,
1339
- ...params
1340
- );
1341
- }
1342
- function scoreSymbolCandidate(row, originalPattern, cleanedPattern, tokens) {
1343
- const originalCase = originalPattern.trim();
1344
- const cleanedCase = cleanedPattern;
1345
- const noParensCase = cleanedCase.replace(/\(\)$/, "");
1346
- const original = originalPattern.toLowerCase();
1347
- const cleaned = cleanedPattern.toLowerCase();
1348
- const noParens = cleaned.replace(/\(\)$/, "");
1349
- const rawCase = row.symbol;
1350
- const shortCase = shortenSymbol(row.symbol);
1351
- const leafCase = leafName(row.symbol);
1352
- const displayCase = row.display_name ?? "";
1353
- const raw = row.symbol.toLowerCase();
1354
- const short = shortCase.toLowerCase();
1355
- const leaf = leafCase.toLowerCase();
1356
- const display = displayCase.toLowerCase();
1357
- const path = row.relative_path.toLowerCase();
1358
- const looksPathLike = /[/:.]/.test(cleanedPattern);
1359
- let score = 0;
1360
- if (rawCase === originalCase || rawCase === cleanedCase) score += 1150;
1361
- if (shortCase === originalCase || shortCase === cleanedCase) score += 1100;
1362
- if (displayCase === noParensCase) score += 980;
1363
- if (leafCase === noParensCase) score += 960;
1364
- if (`${leafCase}()` === originalCase || `${leafCase}()` === cleanedCase) score += 955;
1365
- if (raw === original || raw === cleaned) score += 1e3;
1366
- if (short === original || short === cleaned) score += 950;
1367
- if (path === original || path === cleaned) score += 925;
1368
- if (path.endsWith(`/${cleaned}`) || path.endsWith(`/${original}`)) score += 875;
1369
- if (display === noParens) score += 850;
1370
- if (leaf === noParens) score += 825;
1371
- if (`${leaf}()` === original || `${leaf}()` === cleaned) score += 820;
1372
- if (short.endsWith(`:${cleaned}`) || short.endsWith(`:${noParens}`) || short.endsWith(`:${noParens}()`)) score += 800;
1373
- if (raw.includes(cleaned)) score += 120;
1374
- if (short.includes(cleaned)) score += 140;
1375
- if (path.includes(cleaned)) score += 140;
1376
- if (display.includes(cleaned)) score += 110;
1377
- if (tokens.every((token) => {
1378
- const lower = token.toLowerCase();
1379
- return raw.includes(lower) || short.includes(lower) || path.includes(lower) || display.includes(lower);
1380
- })) {
1381
- score += 100 + tokens.length * 15;
1382
- }
1383
- if (isFunctionLikeSymbol(row.symbol) && leaf === noParens) {
1384
- score += 60;
1385
- }
1386
- if (!looksPathLike && isModuleLikeSymbol(row.symbol)) {
1387
- score -= 160;
1388
- }
1389
- score -= Math.min(50, Math.max(0, row.end_line - row.start_line));
1390
- return score;
1391
- }
1392
- function getCalleeRowsForSymbol(db, symbol, opts = {}) {
1393
- const mentions = db.all(
1394
- `SELECT DISTINCT m.symbol_id, c.id AS chunk_id
1395
- FROM mentions m
1396
- JOIN chunks c ON m.chunk_id = c.id
1397
- WHERE c.document_id = ?
1398
- AND c.start_line >= ?
1399
- AND c.end_line <= ?
1400
- AND m.role != 1
1401
- AND m.symbol_id != ?
1402
- ${opts.limit ? "LIMIT ?" : ""}`,
1403
- ...calleeQueryParams(symbol, opts.limit)
1404
- );
1405
- const primary = [];
1406
- const directSeen = /* @__PURE__ */ new Set();
1407
- for (const mention of mentions) {
1408
- const callee = getFullSymbolMatch(db, {
1409
- symbolId: mention.symbol_id,
1410
- documentId: symbol.documentId,
1411
- startLine: symbol.startLine,
1412
- endLine: symbol.endLine
1413
- });
1414
- if (!callee || db.isIgnored(callee.relativePath)) continue;
1415
- const key = `${callee.symbol}|${callee.relativePath}|${mention.chunk_id}`;
1416
- if (directSeen.has(key)) continue;
1417
- directSeen.add(key);
1418
- primary.push({
1419
- symbol: callee.symbol,
1420
- file: callee.relativePath,
1421
- chunkId: mention.chunk_id
1422
- });
1423
- }
1424
- const sourceFallback = getSourceBackedCalleeRows(db, symbol, opts.limit);
1425
- if (sourceFallback.length > 0) {
1426
- return applyLimit(sourceFallback, opts.limit);
1427
- }
1428
- return primary;
1429
- }
1430
- function getCallerRowsForSymbol(db, symbol, opts = {}) {
1431
- const match = getFullSymbolMatch(db, symbol);
1432
- if (!match) {
1433
- return [];
1434
- }
1435
- const primary = db.all(
1436
- `SELECT DISTINCT ref_d.relative_path AS caller_file, c.start_line AS line
1437
- FROM mentions m
1438
- JOIN chunks c ON m.chunk_id = c.id
1439
- JOIN documents ref_d ON c.document_id = ref_d.id
1440
- WHERE m.symbol_id = ?
1441
- AND m.role != 1
1442
- ${db.pathExclusionsFor("ref_d")}
1443
- ORDER BY ref_d.relative_path
1444
- ${opts.limit ? "LIMIT ?" : ""}`,
1445
- ...referenceQueryParams(match, opts.limit)
1446
- ).filter((row) => !db.isIgnored(row.caller_file)).flatMap((row) => {
1447
- const enclosing = findEnclosingDefinition(getDefinitionsForFile(db, row.caller_file), row.line);
1448
- if (!enclosing || enclosing.symbolId === match.symbolId) {
1449
- return [];
1450
- }
1451
- return [{
1452
- symbol: enclosing.symbol,
1453
- file: row.caller_file
1454
- }];
1455
- });
1456
- const sourceFallback = dedupeCallerRows([
1457
- ...getPythonSourceCallerRows(db, match, opts.limit),
1458
- ...getGenericSourceCallerRows(db, match, opts.limit)
1459
- ]);
1460
- if (sourceFallback.length === 0) {
1461
- return dedupeCallerRows(primary);
1462
- }
1463
- const merged = [...sourceFallback];
1464
- const fallbackFiles = new Set(sourceFallback.map((row) => row.file));
1465
- const seen = new Set(merged.map((row) => `${row.symbol}|${row.file}`));
1466
- for (const row of primary) {
1467
- if (fallbackFiles.has(row.file)) continue;
1468
- const key = `${row.symbol}|${row.file}`;
1469
- if (seen.has(key)) continue;
1470
- if (isFunctionLikeSymbol(row.symbol) || merged.length === 0) {
1471
- seen.add(key);
1472
- merged.push(row);
1473
- }
1474
- }
1475
- return applyLimit(merged, opts.limit);
1476
- }
1477
- function getGenericSourceCallerRows(db, symbol, limit) {
1478
- return applyLimit(
1479
- getSourceReferenceSites(db, symbol).filter((site) => site.enclosingSymbol && site.enclosingSymbol !== symbol.symbol).map((site) => ({
1480
- symbol: site.enclosingSymbol,
1481
- file: site.file
1482
- })),
1483
- limit
1484
- );
1485
- }
1486
- function dedupeCallerRows(rows) {
1487
- const seen = /* @__PURE__ */ new Set();
1488
- const unique = [];
1489
- for (const row of rows) {
1490
- const key = `${row.symbol}|${row.file}`;
1491
- if (seen.has(key)) continue;
1492
- seen.add(key);
1493
- unique.push(row);
1494
- }
1495
- return unique;
1496
- }
1497
- function getSourceReferenceSites(db, symbol) {
1498
- const match = getFullSymbolMatch(db, symbol);
1499
- if (!match) {
1500
- return [];
1501
- }
1502
- const identifier = leafName(match.symbol);
1503
- if (!identifier || !hasUniqueLeafDefinition(db, identifier, match.symbolId)) {
1504
- return [];
1505
- }
1506
- const documents = db.all(
1507
- `SELECT relative_path
1508
- FROM documents
1509
- WHERE 1 = 1
1510
- ${db.pathExclusionsFor("documents")}
1511
- ORDER BY relative_path`
1512
- );
1513
- const sites = [];
1514
- const seen = /* @__PURE__ */ new Set();
1515
- for (const document of documents) {
1516
- if (db.isIgnored(document.relative_path)) continue;
1517
- const lines = findIdentifierLines(db, document.relative_path, identifier, document.relative_path === match.relativePath ? { excludeStartLine: match.startLine, excludeEndLine: match.endLine } : {});
1518
- const definitions = getDefinitionsForFile(db, document.relative_path);
1519
- for (const line of lines) {
1520
- const enclosing = findEnclosingDefinition(definitions, line);
1521
- const key = `${document.relative_path}|${line}|${enclosing?.symbol ?? ""}`;
1522
- if (seen.has(key)) continue;
1523
- seen.add(key);
1524
- sites.push({
1525
- file: document.relative_path,
1526
- line,
1527
- enclosingSymbol: enclosing?.symbol ?? null
1528
- });
1529
- }
1530
- }
1531
- return sites;
1532
- }
1533
- function calleeQueryParams(symbol, limit) {
1534
- const params = [
1535
- symbol.documentId,
1536
- symbol.startLine,
1537
- symbol.endLine,
1538
- symbol.symbolId
1539
- ];
1540
- if (typeof limit === "number") {
1541
- params.push(limit);
1542
- }
1543
- return params;
1544
- }
1545
- function referenceQueryParams(symbol, limit) {
1546
- const params = [symbol.symbolId];
1547
- if (typeof limit === "number") {
1548
- params.push(limit);
1549
- }
1550
- return params;
1551
- }
1552
- function findEnclosingDefinition(definitions, line) {
1553
- let best = null;
1554
- for (const definition of definitions) {
1555
- if (definition.startLine > line || definition.endLine < line) continue;
1556
- if (!best || definition.endLine - definition.startLine < best.endLine - best.startLine) {
1557
- best = definition;
1558
- }
1559
- }
1560
- return best;
1561
- }
1562
- var LANGUAGE_CALLEE_CONFIGS = [
1563
- // Python (index 0) — complex resolver
1564
- { kind: "complex", languageIndex: 0, resolver: resolvePythonCallTarget },
1565
- // JavaScript/TypeScript (index 1) — complex resolver
1566
- { kind: "complex", languageIndex: 1, resolver: resolveJavaScriptCallTarget },
1567
- // Java (index 2) — simple with field bindings
1568
- { kind: "simple", languageIndex: 2, parseBindings: (_db, source) => parseJavaFieldBindings(source) },
1569
- // Kotlin (index 3) — simple with field bindings
1570
- { kind: "simple", languageIndex: 3, parseBindings: (_db, source) => parseKotlinFieldBindings(source) },
1571
- // Scala (index 4) — simple, no bindings
1572
- { kind: "simple", languageIndex: 4, parseBindings: null },
1573
- // C# (index 5) — simple, no bindings
1574
- { kind: "simple", languageIndex: 5, parseBindings: null },
1575
- // Visual Basic (index 6) — simple, no bindings
1576
- { kind: "simple", languageIndex: 6, parseBindings: null },
1577
- // C++ (index 7) — simple with receiver bindings
1578
- { kind: "simple", languageIndex: 7, parseBindings: (_db, source) => parseCppReceiverBindings(source) },
1579
- // Rust (index 8) — simple, no bindings
1580
- { kind: "simple", languageIndex: 8, parseBindings: null },
1581
- // Ruby (index 9) — simple with dual-attempt logic
1582
- {
1583
- kind: "simple",
1584
- languageIndex: 9,
1585
- parseBindings: (db, source) => parseRubyReceiverBindings(db, source),
1586
- dualAttempt: {
1587
- baseOpts: { allowInstanceVariables: true },
1588
- extendedOpts: { allowInstanceVariables: true, allowBareMemberCalls: true }
1589
- }
1590
- },
1591
- // Dart (index 10) — simple, no bindings
1592
- { kind: "simple", languageIndex: 10, parseBindings: null },
1593
- // PHP (index 11) — simple, no bindings
1594
- { kind: "simple", languageIndex: 11, parseBindings: null }
1595
- ];
1596
- function getComplexSourceCalleeRows(db, match, config, limit) {
1597
- const definitions = getDefinitionsForFile(db, match.relativePath);
1598
- const current = definitions.find((definition) => definition.symbolId === match.symbolId);
1599
- if (!current) {
1600
- return [];
1601
- }
1602
- const imports = getSourceImports(db, match.relativePath);
1603
- const bindings = new Map(
1604
- getSourceConstructorBindings(db, match.relativePath, {
1605
- startLine: match.startLine,
1606
- endLine: match.endLine
1607
- }).map((binding) => [binding.localName, binding.typeName])
1608
- );
1609
- const rows = [];
1610
- const seen = /* @__PURE__ */ new Set();
1611
- for (const call of getSourceCalls(db, match.relativePath, {
1612
- startLine: match.startLine,
1613
- endLine: match.endLine
1614
- })) {
1615
- const resolved = config.resolver(
1616
- db,
1617
- current,
1618
- definitions,
1619
- imports,
1620
- bindings,
1621
- call.receiverName,
1622
- call.calleeName
1623
- );
1624
- if (!resolved || resolved.symbolId === match.symbolId || db.isIgnored(resolved.relativePath)) continue;
1625
- const chunkId = 1e9 + call.line;
1626
- const key = `${resolved.symbol}|${resolved.relativePath}|${chunkId}`;
1627
- if (seen.has(key)) continue;
1628
- seen.add(key);
1629
- rows.push({
1630
- symbol: resolved.symbol,
1631
- file: resolved.relativePath,
1632
- chunkId
1633
- });
1634
- }
1635
- return applyLimit(rows, limit);
1636
- }
1637
- function getSimpleLanguageCalleeRows(db, match, config, limit) {
1638
- let calls;
1639
- if (config.dualAttempt) {
1640
- const baseCalls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine, config.dualAttempt.baseOpts);
1641
- const extendedCalls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine, config.dualAttempt.extendedOpts);
1642
- calls = extendedCalls.length > 0 ? extendedCalls : baseCalls;
1643
- } else {
1644
- calls = getSimpleSourceCalls(db, match.relativePath, match.startLine, match.endLine, config.sourceCallOpts);
1645
- }
1646
- const bindings = config.parseBindings ? config.parseBindings(db, getSourceText(db, match.relativePath)) : /* @__PURE__ */ new Map();
1647
- return resolveSimpleSourceCallees(db, match, calls, bindings, limit);
1648
- }
1649
- function getSourceBackedCalleeRows(db, symbol, limit) {
1650
- const match = getFullSymbolMatch(db, symbol);
1651
- if (!match) {
1652
- return [];
1653
- }
1654
- for (const config of LANGUAGE_CALLEE_CONFIGS) {
1655
- if (!isDocumentLanguage(db, match.relativePath, DOCUMENT_LANGUAGE_TABLE[config.languageIndex])) {
1656
- continue;
1657
- }
1658
- if (config.kind === "complex") {
1659
- return getComplexSourceCalleeRows(db, match, config, limit);
1660
- }
1661
- return getSimpleLanguageCalleeRows(db, match, config, limit);
1662
- }
1663
- return [];
1664
- }
1665
- function getPythonSourceCallerRows(db, target, limit) {
1666
- if (!isPythonDocument(db, target.relativePath)) {
1667
- return [];
1668
- }
1669
- const rows = [];
1670
- const seen = /* @__PURE__ */ new Set();
1671
- const pythonConfig = LANGUAGE_CALLEE_CONFIGS[0];
1672
- for (const candidate of getAllFunctionLikeDefinitions(db)) {
1673
- if (candidate.symbolId === target.symbolId) continue;
1674
- if (!isDocumentLanguage(db, candidate.relativePath, DOCUMENT_LANGUAGE_TABLE[pythonConfig.languageIndex])) continue;
1675
- const callees = getComplexSourceCalleeRows(db, candidate, pythonConfig);
1676
- if (!callees.some((callee) => callee.symbol === target.symbol)) continue;
1677
- const key = `${candidate.symbol}|${candidate.relativePath}`;
1678
- if (seen.has(key) || db.isIgnored(candidate.relativePath)) continue;
1679
- seen.add(key);
1680
- rows.push({
1681
- symbol: candidate.symbol,
1682
- file: candidate.relativePath
1683
- });
1684
- if (typeof limit === "number" && rows.length >= limit) {
1685
- break;
1686
- }
1687
- }
1688
- return rows;
1689
- }
1690
- function getDefinitionRowsForSymbolId(db, symbolId) {
1691
- const primary = db.all(
1692
- `SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.end_line, d.relative_path, gs.display_name
1693
- FROM global_symbols gs
1694
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1695
- JOIN documents d ON der.document_id = d.id
1696
- WHERE gs.id = ?
1697
- ORDER BY der.start_line, der.end_line`,
1698
- symbolId
1699
- );
1700
- if (primary.length > 0) {
1701
- return primary;
1702
- }
1703
- return db.all(
1704
- `SELECT
1705
- gs.id,
1706
- gs.symbol,
1707
- c.document_id,
1708
- MIN(c.start_line) AS start_line,
1709
- MAX(c.end_line) AS end_line,
1710
- d.relative_path,
1711
- gs.display_name
1712
- FROM global_symbols gs
1713
- JOIN mentions m ON m.symbol_id = gs.id
1714
- JOIN chunks c ON m.chunk_id = c.id
1715
- JOIN documents d ON c.document_id = d.id
1716
- WHERE gs.id = ?
1717
- AND m.role = 1
1718
- ${db.pathExclusionsFor("d")}
1719
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name
1720
- ORDER BY start_line, end_line`,
1721
- symbolId
1722
- );
1723
- }
1724
- function getFullSymbolMatch(db, symbol) {
1725
- if ("symbol" in symbol && "relativePath" in symbol) {
1726
- return symbol;
1727
- }
1728
- const row = getDefinitionRowsForSymbolId(db, symbol.symbolId)[0];
1729
- if (!row) {
1730
- return null;
1731
- }
1732
- return hydrateSymbolMatch(db, row);
1733
- }
1734
- function getDefinitionsForFile(db, relativePath) {
1735
- let cache = FILE_DEFINITION_CACHE.get(db);
1736
- if (!cache) {
1737
- cache = /* @__PURE__ */ new Map();
1738
- FILE_DEFINITION_CACHE.set(db, cache);
1739
- }
1740
- const cached = cache.get(relativePath);
1741
- if (cached) {
1742
- return cached;
1743
- }
1744
- const primary = db.all(
1745
- `SELECT
1746
- gs.id,
1747
- gs.symbol,
1748
- der.document_id,
1749
- der.start_line,
1750
- der.end_line,
1751
- d.relative_path,
1752
- gs.display_name,
1753
- gs.kind,
1754
- gs.documentation,
1755
- gs.enclosing_symbol
1756
- FROM global_symbols gs
1757
- JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
1758
- JOIN documents d ON der.document_id = d.id
1759
- WHERE d.relative_path = ?
1760
- ${db.symbolNoiseFor("gs")}
1761
- ORDER BY der.start_line, der.end_line`,
1762
- relativePath
1763
- );
1764
- const fallback = primary.length > 0 ? [] : db.all(
1765
- `SELECT
1766
- gs.id,
1767
- gs.symbol,
1768
- c.document_id,
1769
- MIN(c.start_line) AS start_line,
1770
- MAX(c.end_line) AS end_line,
1771
- d.relative_path,
1772
- gs.display_name,
1773
- gs.kind,
1774
- gs.documentation,
1775
- gs.enclosing_symbol
1776
- FROM global_symbols gs
1777
- JOIN mentions m ON m.symbol_id = gs.id
1778
- JOIN chunks c ON m.chunk_id = c.id
1779
- JOIN documents d ON c.document_id = d.id
1780
- WHERE d.relative_path = ?
1781
- AND m.role = 1
1782
- ${db.symbolNoiseFor("gs")}
1783
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
1784
- ORDER BY start_line, end_line`,
1785
- relativePath
1786
- );
1787
- const definitions = correctDefinitionRangesFromSource(
1788
- db,
1789
- relativePath,
1790
- (primary.length > 0 ? primary : fallback).map((row) => ({
1791
- symbolId: row.id,
1792
- symbol: row.symbol,
1793
- documentId: row.document_id,
1794
- startLine: row.start_line,
1795
- endLine: row.end_line,
1796
- relativePath: row.relative_path,
1797
- leaf: leafName(row.symbol),
1798
- parentTypeName: parentTypeName(row.symbol),
1799
- isFunctionLike: isFunctionLikeSymbol(row.symbol),
1800
- isTypeLike: leafSuffix(row.symbol) === "type",
1801
- kind: row.kind ?? null,
1802
- documentation: row.documentation ?? null,
1803
- enclosingSymbol: row.enclosing_symbol ?? null
1804
- }))
1805
- );
1806
- cache.set(relativePath, definitions);
1807
- return definitions;
1808
- }
1809
- function hydrateSymbolMatch(db, row) {
1810
- const corrected = getDefinitionsForFile(db, row.relative_path).find((definition) => definition.symbolId === row.id);
1811
- if (corrected) {
1812
- return {
1813
- symbolId: corrected.symbolId,
1814
- symbol: corrected.symbol,
1815
- documentId: corrected.documentId,
1816
- startLine: corrected.startLine,
1817
- endLine: corrected.endLine,
1818
- relativePath: corrected.relativePath
1819
- };
1820
- }
1821
- return {
1822
- symbolId: row.id,
1823
- symbol: row.symbol,
1824
- documentId: row.document_id,
1825
- startLine: row.start_line,
1826
- endLine: row.end_line,
1827
- relativePath: row.relative_path
1828
- };
1829
- }
1830
- function findDirectSymbolCandidate(candidates, symbolPattern, cleanedPattern) {
1831
- const trimmed = symbolPattern.trim();
1832
- const directMatches = candidates.filter((row) => {
1833
- const short = shortenSymbol(row.symbol);
1834
- const display = (row.display_name ?? "").trim();
1835
- return row.symbol === trimmed || short === trimmed || short === cleanedPattern || display === trimmed || display === cleanedPattern || `${display}()` === trimmed || row.relative_path === trimmed;
1836
- });
1837
- if (directMatches.length === 0) {
1838
- return null;
1839
- }
1840
- directMatches.sort(
1841
- (left, right) => left.end_line - left.start_line - (right.end_line - right.start_line) || left.relative_path.localeCompare(right.relative_path) || left.symbol.localeCompare(right.symbol)
1842
- );
1843
- return directMatches[0] ?? null;
1844
- }
1845
- function correctDefinitionRangesFromSource(db, relativePath, definitions) {
1846
- const source = getSourceText(db, relativePath);
1847
- if (!source) {
1848
- return definitions;
1849
- }
1850
- const lines = source.split(/\r?\n/);
1851
- const correctedStarts = /* @__PURE__ */ new Map();
1852
- for (const definition of definitions) {
1853
- correctedStarts.set(
1854
- definition.symbolId,
1855
- resolveCallableDefinitionStartLine(lines, definition)
1856
- );
1857
- }
1858
- const correctedRanges = /* @__PURE__ */ new Map();
1859
- const callableDefinitions = definitions.filter((definition) => isCallableDefinition(definition.symbol)).map((definition) => ({
1860
- definition,
1861
- startLine: correctedStarts.get(definition.symbolId) ?? definition.startLine
1862
- })).sort(
1863
- (left, right) => left.startLine - right.startLine || left.definition.startLine - right.definition.startLine || left.definition.symbol.localeCompare(right.definition.symbol)
1864
- );
1865
- for (let index = 0; index < callableDefinitions.length; index += 1) {
1866
- const current = callableDefinitions[index];
1867
- const next = callableDefinitions[index + 1];
1868
- const maxEndLine = next ? Math.max(current.startLine, next.startLine - 1) : lines.length - 1;
1869
- correctedRanges.set(current.definition.symbolId, {
1870
- startLine: current.startLine,
1871
- endLine: resolveCallableDefinitionEndLine(
1872
- lines,
1873
- current.definition,
1874
- current.startLine,
1875
- maxEndLine
1876
- )
1877
- });
1878
- }
1879
- return definitions.map((definition) => {
1880
- const corrected = correctedRanges.get(definition.symbolId);
1881
- if (!corrected) {
1882
- return definition;
1883
- }
1884
- return {
1885
- ...definition,
1886
- startLine: corrected.startLine,
1887
- endLine: corrected.endLine
1888
- };
1889
- });
1890
- }
1891
- function resolveCallableDefinitionStartLine(lines, definition) {
1892
- if (!isCallableDefinition(definition.symbol)) {
1893
- return definition.startLine;
1894
- }
1895
- const escapedLeaf = escapeRegex2(definition.leaf);
1896
- const strongPatterns = [
1897
- new RegExp(`\\b(?:function|def|fn)\\s+${escapedLeaf}\\b`),
1898
- new RegExp(`\\b${escapedLeaf}\\b\\s*[:=]\\s*(?:async\\s*)?(?:function\\b|\\()`)
1899
- ];
1900
- const fallbackPatterns = [
1901
- new RegExp(`\\b${escapedLeaf}\\b\\s*\\(`)
1902
- ];
1903
- return findNearestMatchingLine(
1904
- lines,
1905
- [...strongPatterns, ...fallbackPatterns],
1906
- definition.startLine,
1907
- definition.endLine
1908
- );
1909
- }
1910
- function findNearestMatchingLine(lines, patterns, preferredStartLine, preferredEndLine) {
1911
- const windowStart = Math.max(0, preferredStartLine - 40);
1912
- const windowEnd = Math.min(lines.length - 1, Math.max(preferredEndLine + 40, preferredStartLine + 5));
1913
- const windowMatch = matchNearestLine(lines, patterns, preferredStartLine, windowStart, windowEnd);
1914
- if (windowMatch !== null) {
1915
- return windowMatch;
1916
- }
1917
- const fullMatch = matchNearestLine(lines, patterns, preferredStartLine, 0, lines.length - 1);
1918
- return fullMatch ?? Math.max(0, Math.min(preferredStartLine, lines.length - 1));
1919
- }
1920
- function matchNearestLine(lines, patterns, preferredLine, startLine, endLine) {
1921
- let best = null;
1922
- for (let lineIndex = startLine; lineIndex <= endLine; lineIndex += 1) {
1923
- const line = lines[lineIndex] ?? "";
1924
- if (!patterns.some((pattern) => pattern.test(line))) continue;
1925
- const distance = Math.abs(lineIndex - preferredLine);
1926
- if (!best || distance < best.distance) {
1927
- best = { line: lineIndex, distance };
1928
- }
1929
- }
1930
- return best?.line ?? null;
1931
- }
1932
- function resolveCallableDefinitionEndLine(lines, definition, startLine, maxEndLine) {
1933
- const boundedEndLine = Math.max(startLine, Math.min(lines.length - 1, maxEndLine));
1934
- const fallbackEndLine = Math.max(startLine, Math.min(boundedEndLine, definition.endLine));
1935
- let braceDepth = 0;
1936
- let parenDepth = 0;
1937
- let sawOpeningBrace = false;
1938
- for (let lineIndex = startLine; lineIndex <= boundedEndLine; lineIndex += 1) {
1939
- const masked = maskStructuralLine(lines[lineIndex] ?? "");
1940
- for (const char of masked) {
1941
- if (char === "{") {
1942
- braceDepth += 1;
1943
- sawOpeningBrace = true;
1944
- } else if (char === "}") {
1945
- braceDepth = Math.max(0, braceDepth - 1);
1946
- } else if (char === "(") {
1947
- parenDepth += 1;
1948
- } else if (char === ")") {
1949
- parenDepth = Math.max(0, parenDepth - 1);
1950
- }
1951
- }
1952
- if (sawOpeningBrace && braceDepth === 0) {
1953
- return lineIndex;
1954
- }
1955
- if (!sawOpeningBrace && parenDepth === 0 && lineIndex >= fallbackEndLine) {
1956
- return lineIndex;
1957
- }
1958
- }
1959
- return fallbackEndLine;
1960
- }
1961
- function maskStructuralLine(line) {
1962
- let masked = "";
1963
- let quote = null;
1964
- let escaping = false;
1965
- for (let index = 0; index < line.length; index += 1) {
1966
- const char = line[index];
1967
- const next = line[index + 1];
1968
- if (!quote && char === "/" && next === "/") {
1969
- masked += " ".repeat(line.length - index);
1970
- break;
1971
- }
1972
- if (quote) {
1973
- if (escaping) {
1974
- escaping = false;
1975
- masked += " ";
1976
- continue;
1977
- }
1978
- if (char === "\\") {
1979
- escaping = true;
1980
- masked += " ";
1981
- continue;
1982
- }
1983
- if (char === quote) {
1984
- quote = null;
1985
- }
1986
- masked += " ";
1987
- continue;
1988
- }
1989
- if (char === '"' || char === "'" || char === "`") {
1990
- quote = char;
1991
- masked += " ";
1992
- continue;
1993
- }
1994
- masked += char;
1995
- }
1996
- return masked;
1997
- }
1998
- function isCallableDefinition(symbol) {
1999
- return symbol.includes("().");
2000
- }
2001
- function escapeRegex2(value) {
2002
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2003
- }
2004
- function getAllDefinitions(db, opts = {}) {
2005
- const { scope } = opts;
2006
- const rows = db.all(
2007
- `SELECT relative_path
2008
- FROM documents
2009
- WHERE 1 = 1
2010
- ${db.pathExclusionsFor("documents")}
2011
- ${scope ? "AND relative_path LIKE ?" : ""}
2012
- ORDER BY relative_path`,
2013
- ...scope ? [`%${scope}%`] : []
2014
- );
2015
- return rows.filter((row) => !db.isIgnored(row.relative_path)).flatMap((row) => getDefinitionsForFile(db, row.relative_path));
2016
- }
2017
- function getScopedDefinitions(db, scope) {
2018
- const scopeFilter = scope ? `AND relative_path LIKE '%${scope}%'` : "";
2019
- return db.all(
2020
- `SELECT relative_path
2021
- FROM documents
2022
- WHERE 1 = 1
2023
- ${db.pathExclusionsFor("documents")}
2024
- ${scopeFilter}
2025
- ORDER BY relative_path`
2026
- ).flatMap((row) => getDefinitionsForFile(db, row.relative_path)).filter((row) => !db.isIgnored(row.relativePath));
2027
- }
2028
- function getAllFunctionLikeDefinitions(db) {
2029
- return getAllDefinitions(db).filter((definition) => definition.isFunctionLike);
2030
- }
2031
- function resolvePythonCallTarget(db, current, currentFileDefinitions, imports, constructorBindings, receiverName, calleeName) {
2032
- if (receiverName === "self" || receiverName === "cls") {
2033
- return findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2034
- }
2035
- if (receiverName) {
2036
- const inferredType = constructorBindings.get(receiverName);
2037
- if (inferredType) {
2038
- const boundMethod = findDefinitionByName(currentFileDefinitions, calleeName, inferredType, ["function"]);
2039
- if (boundMethod) {
2040
- return boundMethod;
2041
- }
2042
- for (const entry of imports) {
2043
- if (entry.localName !== inferredType || !entry.sourcePath) continue;
2044
- const importedDefinitions = getDefinitionsForFile(db, entry.sourcePath);
2045
- const importedMethod = findDefinitionByName(importedDefinitions, calleeName, entry.importedName, ["function"]);
2046
- if (importedMethod) {
2047
- return importedMethod;
2048
- }
2049
- }
2050
- }
2051
- const localClassMethod = findDefinitionByName(currentFileDefinitions, calleeName, receiverName, ["function"]);
2052
- if (localClassMethod) {
2053
- return localClassMethod;
2054
- }
2055
- const namespaceImport = imports.find((entry) => entry.localName === receiverName && entry.sourcePath);
2056
- if (namespaceImport?.sourcePath) {
2057
- const importedDefinitions = getDefinitionsForFile(db, namespaceImport.sourcePath);
2058
- const importedTypeMethod = namespaceImport.kind === "named" ? findDefinitionByName(importedDefinitions, calleeName, namespaceImport.importedName, ["function"]) : null;
2059
- if (importedTypeMethod) {
2060
- return importedTypeMethod;
2061
- }
2062
- return findDefinitionByName(importedDefinitions, calleeName, null, ["function", "type"]);
2063
- }
2064
- return null;
2065
- }
2066
- const importedBinding = imports.find((entry) => entry.localName === calleeName && entry.sourcePath);
2067
- if (importedBinding?.sourcePath) {
2068
- const importedDefinitions = getDefinitionsForFile(db, importedBinding.sourcePath);
2069
- const importedName = importedBinding.importedName === "*" ? calleeName : importedBinding.importedName;
2070
- const importedDefinition = findDefinitionByName(importedDefinitions, importedName, null, ["function", "type"]);
2071
- if (importedDefinition) {
2072
- return importedDefinition;
2073
- }
2074
- }
2075
- return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2076
- }
2077
- function resolveJavaScriptCallTarget(db, current, currentFileDefinitions, imports, constructorBindings, receiverName, calleeName) {
2078
- if (receiverName === "this") {
2079
- return findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2080
- }
2081
- if (receiverName) {
2082
- const inferredType = constructorBindings.get(receiverName);
2083
- if (inferredType) {
2084
- const boundMethod = findDefinitionByName(currentFileDefinitions, calleeName, inferredType, ["function"]);
2085
- if (boundMethod) {
2086
- return boundMethod;
2087
- }
2088
- for (const entry of imports) {
2089
- if (entry.localName !== inferredType || !entry.sourcePath) continue;
2090
- const importedDefinitions = getDefinitionsForFile(db, entry.sourcePath);
2091
- const importedMethod = findDefinitionByName(importedDefinitions, calleeName, entry.importedName, ["function"]);
2092
- if (importedMethod) {
2093
- return importedMethod;
2094
- }
2095
- }
2096
- }
2097
- const localClassMethod = findDefinitionByName(currentFileDefinitions, calleeName, receiverName, ["function"]);
2098
- if (localClassMethod) {
2099
- return localClassMethod;
2100
- }
2101
- const namespaceImport = imports.find((entry) => entry.localName === receiverName && entry.sourcePath);
2102
- if (namespaceImport?.sourcePath) {
2103
- const importedDefinitions = getDefinitionsForFile(db, namespaceImport.sourcePath);
2104
- if (namespaceImport.kind === "named" || namespaceImport.kind === "default") {
2105
- const importedTypeMethod = findDefinitionByName(
2106
- importedDefinitions,
2107
- calleeName,
2108
- namespaceImport.importedName,
2109
- ["function"]
2110
- );
2111
- if (importedTypeMethod) {
2112
- return importedTypeMethod;
2113
- }
2114
- }
2115
- return findDefinitionByName(importedDefinitions, calleeName, null, ["function", "type"]);
2116
- }
2117
- return null;
2118
- }
2119
- const importedBinding = imports.find((entry) => entry.localName === calleeName && entry.sourcePath && entry.kind !== "namespace");
2120
- if (importedBinding?.sourcePath) {
2121
- const importedDefinitions = getDefinitionsForFile(db, importedBinding.sourcePath);
2122
- const importedName = importedBinding.importedName === "default" ? importedBinding.localName ?? calleeName : importedBinding.importedName;
2123
- const importedDefinition = findDefinitionByName(importedDefinitions, importedName, null, ["function", "type"]);
2124
- if (importedDefinition) {
2125
- return importedDefinition;
2126
- }
2127
- }
2128
- return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2129
- }
2130
- function resolveSimpleSourceCallees(db, current, calls, bindings, limit) {
2131
- const currentFileDefinitions = getDefinitionsForFile(db, current.relativePath);
2132
- const currentDefinition = currentFileDefinitions.find((definition) => definition.symbolId === current.symbolId);
2133
- if (!currentDefinition) {
2134
- return [];
2135
- }
2136
- const rows = [];
2137
- const seen = /* @__PURE__ */ new Set();
2138
- for (const call of calls) {
2139
- const resolved = resolveSimpleSourceCallTarget(
2140
- db,
2141
- currentDefinition,
2142
- currentFileDefinitions,
2143
- bindings,
2144
- call.receiverName,
2145
- call.calleeName
2146
- );
2147
- if (!resolved || resolved.symbolId === current.symbolId || db.isIgnored(resolved.relativePath)) continue;
2148
- const chunkId = 2e9 + call.line;
2149
- const key = `${resolved.symbol}|${resolved.relativePath}|${chunkId}`;
2150
- if (seen.has(key)) continue;
2151
- seen.add(key);
2152
- rows.push({
2153
- symbol: resolved.symbol,
2154
- file: resolved.relativePath,
2155
- chunkId
2156
- });
2157
- }
2158
- return applyLimit(rows, limit);
2159
- }
2160
- function resolveSimpleSourceCallTarget(db, current, currentFileDefinitions, bindings, receiverName, calleeName) {
2161
- if (!receiverName) {
2162
- const localMethod = findDefinitionByName(currentFileDefinitions, calleeName, current.parentTypeName, ["function"]);
2163
- if (localMethod) {
2164
- return localMethod;
2165
- }
2166
- if (current.parentTypeName) {
2167
- return findProjectDefinitionByTypeAndLeaf(db, current.parentTypeName, calleeName);
2168
- }
2169
- return findDefinitionByName(currentFileDefinitions, calleeName, null, ["function", "type"]);
2170
- }
2171
- const normalizedReceiver = normalizeReceiverName(receiverName);
2172
- const inferredType = bindings.get(normalizedReceiver) ?? inferTypeNameFromReceiver(db, normalizedReceiver);
2173
- if (!inferredType) {
2174
- return null;
2175
- }
2176
- return findProjectDefinitionByTypeAndLeaf(db, inferredType, calleeName);
2177
- }
2178
- function findProjectDefinitionByTypeAndLeaf(db, typeName, calleeName) {
2179
- const definitions = getAllDefinitions(db).filter((definition) => definition.isFunctionLike || definition.symbol.endsWith("()."));
2180
- const exact = definitions.find((definition) => definition.leaf === calleeName && (definition.parentTypeName === typeName || definition.symbol.includes(typeName)));
2181
- if (exact) {
2182
- return exact;
2183
- }
2184
- const normalizedType = normalizeLookupName(typeName);
2185
- const normalizedMatch = definitions.find((definition) => definition.leaf === calleeName && normalizeLookupName(definition.parentTypeName ?? "").includes(normalizedType));
2186
- if (normalizedMatch) {
2187
- return normalizedMatch;
2188
- }
2189
- return findLooseProjectDefinitionByTypeAndLeaf(db, typeName, calleeName);
2190
- }
2191
- function inferTypeNameFromReceiver(db, receiverName) {
2192
- const normalizedReceiver = normalizeLookupName(receiverName);
2193
- if (!normalizedReceiver) {
2194
- return null;
2195
- }
2196
- const candidates = getAllDefinitions(db).filter((definition) => definition.isTypeLike || definition.symbol.endsWith("#")).map((definition) => definition.leaf).filter((leaf) => leaf.length > 0);
2197
- let best = null;
2198
- for (const candidate of candidates) {
2199
- const normalizedCandidate = normalizeLookupName(candidate);
2200
- let score = 0;
2201
- if (normalizedCandidate === normalizedReceiver) score += 100;
2202
- if (normalizedCandidate.endsWith(normalizedReceiver)) score += 80;
2203
- if (normalizedCandidate.includes(normalizedReceiver)) score += 40;
2204
- if (normalizedReceiver.includes(normalizedCandidate)) score += 20;
2205
- if (score > 0 && (!best || score > best.score || score === best.score && candidate.length < best.name.length)) {
2206
- best = { name: candidate, score };
2207
- }
2208
- }
2209
- return best?.name ?? null;
2210
- }
2211
- function getSimpleSourceCalls(db, relativePath, startLine, endLine, opts = {}) {
2212
- const source = getSourceText(db, relativePath);
2213
- if (!source) {
2214
- return [];
2215
- }
2216
- const lines = source.split("\n");
2217
- const scoped = lines.slice(startLine, endLine + 1);
2218
- const calls = [];
2219
- const seen = /* @__PURE__ */ new Set();
2220
- const pattern = opts.allowInstanceVariables ? /(@?[A-Za-z_][\w]*)\s*(?:\.|::)\s*([A-Za-z_][\w!?=]*)\s*\(/g : /\b([A-Za-z_][\w]*)\s*(?:\.|::)\s*([A-Za-z_][\w]*)\s*\(/g;
2221
- for (let index = 0; index < scoped.length; index++) {
2222
- const rawLine = scoped[index] ?? "";
2223
- for (const match of rawLine.matchAll(pattern)) {
2224
- const receiverName = match[1];
2225
- const calleeName = match[2];
2226
- if (!receiverName || !calleeName) continue;
2227
- const key = `${startLine + index}|${receiverName}|${calleeName}`;
2228
- if (seen.has(key)) continue;
2229
- seen.add(key);
2230
- calls.push({
2231
- receiverName,
2232
- calleeName,
2233
- line: startLine + index
2234
- });
2235
- }
2236
- if (opts.allowBareMemberCalls) {
2237
- for (const match of rawLine.matchAll(/(@?[A-Za-z_][\w]*)\s*\.\s*([A-Za-z_][\w!?=]*)\b(?!\s*[:=])/g)) {
2238
- const receiverName = match[1];
2239
- const calleeName = match[2];
2240
- if (!receiverName || !calleeName) continue;
2241
- const key = `${startLine + index}|${receiverName}|${calleeName}`;
2242
- if (seen.has(key)) continue;
2243
- seen.add(key);
2244
- calls.push({
2245
- receiverName,
2246
- calleeName,
2247
- line: startLine + index
2248
- });
2249
- }
2250
- }
2251
- for (const match of rawLine.matchAll(/\b([A-Za-z_][\w]*)\s*\(/g)) {
2252
- const calleeName = match[1];
2253
- const start = match.index ?? -1;
2254
- if (!calleeName || start < 0) continue;
2255
- const prefix = rawLine.slice(0, start).trimEnd();
2256
- if (prefix.endsWith("def") || prefix.endsWith("fun") || prefix.endsWith("fn") || /\b(?:class|interface|trait|module|object)\s*$/.test(prefix)) {
2257
- continue;
2258
- }
2259
- if (rawLine.slice(Math.max(0, start - 3), start).includes(".")) {
2260
- continue;
2261
- }
2262
- calls.push({
2263
- receiverName: null,
2264
- calleeName,
2265
- line: startLine + index
2266
- });
2267
- }
2268
- }
2269
- return calls;
2270
- }
2271
- function parseJavaFieldBindings(source) {
2272
- const bindings = /* @__PURE__ */ new Map();
2273
- for (const match of source.matchAll(/\b(?:private|protected|public)\s+(?:final\s+)?([A-Z][A-Za-z0-9_$<>?, ]*)\s+([A-Za-z_][\w$]*)\s*;/g)) {
2274
- const typeName = stripGenericType(match[1]);
2275
- const localName = match[2];
2276
- if (typeName && localName) {
2277
- bindings.set(localName, typeName);
2278
- }
2279
- }
2280
- return bindings;
2281
- }
2282
- function parseKotlinFieldBindings(source) {
2283
- const bindings = /* @__PURE__ */ new Map();
2284
- for (const match of source.matchAll(/\b(?:private|protected|public)?\s*(?:val|var)\s+([A-Za-z_][\w]*)\s*:\s*([A-Z][A-Za-z0-9_.<>?]*)/g)) {
2285
- const localName = match[1];
2286
- const typeName = stripGenericType(match[2]);
2287
- if (typeName && localName) {
2288
- bindings.set(localName, typeName);
2289
- }
2290
- }
2291
- return bindings;
2292
- }
2293
- function parseCppReceiverBindings(source) {
2294
- const bindings = /* @__PURE__ */ new Map();
2295
- const constructorMatch = source.match(/RunCoordinator::RunCoordinator\s*\(([\s\S]*?)\)\s*(?::\s*([\s\S]*?))?\s*\{/);
2296
- if (!constructorMatch) {
2297
- return bindings;
2298
- }
2299
- const params = constructorMatch[1] ?? "";
2300
- const initializers = constructorMatch[2] ?? "";
2301
- const parameterTypes = /* @__PURE__ */ new Map();
2302
- for (const param of params.split(",")) {
2303
- const trimmed = param.trim();
2304
- const match = trimmed.match(/(.+?)\s+([A-Za-z_][\w]*)$/);
2305
- if (!match) continue;
2306
- const [, rawType, rawName] = match;
2307
- if (!rawType || !rawName) continue;
2308
- const typeName = stripGenericType(rawType.replace(/[&*]+/g, " ").replace(/\bconst\b/g, " ").trim());
2309
- if (!typeName) continue;
2310
- parameterTypes.set(normalizeReceiverName(rawName), typeName);
2311
- }
2312
- for (const initializer of initializers.split(",")) {
2313
- const trimmed = initializer.trim();
2314
- const match = trimmed.match(/([A-Za-z_][\w]*)\s*\(\s*([A-Za-z_][\w]*)\s*\)$/);
2315
- if (!match) continue;
2316
- const [, fieldName, sourceName] = match;
2317
- if (!fieldName || !sourceName) continue;
2318
- const typeName = parameterTypes.get(normalizeReceiverName(sourceName));
2319
- if (!typeName) continue;
2320
- bindings.set(normalizeReceiverName(fieldName), typeName);
2321
- }
2322
- return bindings;
2323
- }
2324
- function parseRubyReceiverBindings(db, source) {
2325
- const bindings = /* @__PURE__ */ new Map();
2326
- for (const match of source.matchAll(/@([A-Za-z_][\w]*)\s*=\s*([A-Za-z_][\w]*)/g)) {
2327
- const ivarName = `@${match[1]}`;
2328
- const localName = match[2];
2329
- const typeName = inferTypeNameFromReceiver(db, localName ?? match[1] ?? "");
2330
- if (typeName) {
2331
- bindings.set(ivarName, typeName);
2332
- bindings.set(match[1], typeName);
2333
- }
2334
- }
2335
- return bindings;
2336
- }
2337
- function stripGenericType(typeName) {
2338
- return (typeName ?? "").replace(/<.*$/, "").replace(/^.*\./, "").trim();
2339
- }
2340
- function normalizeReceiverName(receiverName) {
2341
- return receiverName.replace(/^@/, "").replace(/^this(?:\.|->)/, "").replace(/^_+/, "").replace(/_+$/, "").trim();
2342
- }
2343
- function normalizeLookupName(value) {
2344
- return value.replace(/[^A-Za-z0-9]+/g, "").toLowerCase();
2345
- }
2346
- function isLikelyTestPath(relativePath) {
2347
- return /(^|\/)(tests?|__tests__)\//.test(relativePath) || /\.(?:spec|test)\./.test(relativePath) || /_test\./.test(relativePath);
2348
- }
2349
- function findDefinitionByName(definitions, leaf, parentType, preference) {
2350
- const candidates = definitions.filter((definition) => definition.leaf === leaf && definition.parentTypeName === parentType);
2351
- if (candidates.length === 0) {
2352
- return null;
2353
- }
2354
- for (const preferred of preference) {
2355
- const match = candidates.find((candidate) => preferred === "function" ? candidate.isFunctionLike : candidate.isTypeLike);
2356
- if (match) {
2357
- return match;
2358
- }
2359
- }
2360
- return candidates[0] ?? null;
2361
- }
2362
- function findLooseProjectDefinitionByTypeAndLeaf(db, typeName, calleeName) {
2363
- const rows = db.all(
2364
- `SELECT
2365
- gs.id,
2366
- gs.symbol,
2367
- c.document_id,
2368
- MIN(c.start_line) AS start_line,
2369
- MAX(c.end_line) AS end_line,
2370
- d.relative_path,
2371
- gs.kind,
2372
- gs.documentation,
2373
- gs.enclosing_symbol
2374
- FROM global_symbols gs
2375
- JOIN mentions m ON m.symbol_id = gs.id
2376
- JOIN chunks c ON c.id = m.chunk_id
2377
- JOIN documents d ON d.id = c.document_id
2378
- WHERE gs.symbol LIKE ?
2379
- AND gs.symbol LIKE ?
2380
- ${db.pathExclusionsFor("d")}
2381
- GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.kind, gs.documentation, gs.enclosing_symbol`,
2382
- `%${typeName}%`,
2383
- `%${calleeName}%`
2384
- );
2385
- const normalizedType = normalizeLookupName(typeName);
2386
- const candidates = rows.filter((row2) => leafName(row2.symbol) === calleeName).filter((row2) => {
2387
- const parentType = parentTypeName(row2.symbol);
2388
- return parentType === typeName || row2.symbol.includes(typeName) || normalizeLookupName(parentType ?? "").includes(normalizedType);
2389
- }).sort((left, right) => {
2390
- const leftTest = isLikelyTestPath(left.relative_path) ? 1 : 0;
2391
- const rightTest = isLikelyTestPath(right.relative_path) ? 1 : 0;
2392
- return leftTest - rightTest || left.relative_path.localeCompare(right.relative_path) || left.start_line - right.start_line;
2393
- });
2394
- const row = candidates[0];
2395
- if (!row) {
2396
- return null;
2397
- }
2398
- return {
2399
- symbolId: row.id,
2400
- symbol: row.symbol,
2401
- documentId: row.document_id,
2402
- startLine: row.start_line,
2403
- endLine: row.end_line,
2404
- relativePath: row.relative_path,
2405
- leaf: leafName(row.symbol),
2406
- parentTypeName: parentTypeName(row.symbol),
2407
- isFunctionLike: isFunctionLikeSymbol(row.symbol),
2408
- isTypeLike: leafSuffix(row.symbol) === "type",
2409
- kind: row.kind,
2410
- documentation: row.documentation,
2411
- enclosingSymbol: row.enclosing_symbol
2412
- };
2413
- }
2414
- function hasUniqueLeafDefinition(db, leaf, symbolId) {
2415
- const rows = db.all(
2416
- `SELECT id, symbol
2417
- FROM global_symbols
2418
- WHERE symbol LIKE ?
2419
- LIMIT 50`,
2420
- `%${leaf}%`
2421
- );
2422
- let count = 0;
2423
- for (const row of rows) {
2424
- if (leafName(row.symbol) !== leaf) continue;
2425
- count++;
2426
- if (count > 1 && row.id !== symbolId) {
2427
- return false;
2428
- }
2429
- }
2430
- return count === 1;
2431
- }
2432
- function parentTypeName(rawSymbol) {
2433
- const parsed = parseSymbol(rawSymbol);
2434
- if ("kind" in parsed) {
2435
- return null;
2436
- }
2437
- for (let index = parsed.descriptors.length - 2; index >= 0; index--) {
2438
- const descriptor = parsed.descriptors[index];
2439
- if (descriptor?.suffix === "type") {
2440
- return descriptor.name;
2441
- }
2442
- }
2443
- return null;
2444
- }
2445
- var DOCUMENT_LANGUAGE_TABLE = [
2446
- { languages: ["python"], extensionPattern: /\.(?:py|pyi)$/ },
2447
- { languages: ["typescript", "javascript"], extensionPattern: /\.(?:[cm]?[jt]sx?)$/ },
2448
- { languages: ["java"], extensionPattern: /\.java$/ },
2449
- { languages: ["kotlin"], extensionPattern: /\.(?:kt|kts)$/ },
2450
- { languages: ["scala"], extensionPattern: /\.scala$/ },
2451
- { languages: ["C#"], extensionPattern: /\.cs$/ },
2452
- { languages: ["Visual Basic"], extensionPattern: /\.vb$/ },
2453
- { languages: ["CPP"], extensionPattern: /\.(?:cc|cpp|cxx|hpp|hh|hxx)$/ },
2454
- { languages: ["Rust"], extensionPattern: /\.rs$/ },
2455
- { languages: ["ruby"], extensionPattern: /\.rb$/ },
2456
- { languages: ["Dart"], extensionPattern: /\.dart$/ },
2457
- { languages: ["PHP"], extensionPattern: /\.php$/ }
2458
- ];
2459
- function isDocumentLanguage(db, relativePath, entry) {
2460
- const row = db.get(
2461
- `SELECT language FROM documents WHERE relative_path = ? LIMIT 1`,
2462
- relativePath
2463
- );
2464
- return entry.languages.includes(row?.language ?? "") || entry.extensionPattern.test(relativePath);
2465
- }
2466
- function isPythonDocument(db, relativePath) {
2467
- return isDocumentLanguage(db, relativePath, DOCUMENT_LANGUAGE_TABLE[0]);
2468
- }
2469
- function applyLimit(values, limit) {
2470
- return typeof limit === "number" ? values.slice(0, limit) : values;
2471
- }
2472
- function resolveDocumentCandidates(db, filePattern, opts) {
2473
- const normalizedPattern = normalizeLookupPath(filePattern);
2474
- if (!normalizedPattern) {
2475
- return [];
2476
- }
2477
- const rows = db.all(
2478
- `SELECT relative_path
2479
- FROM documents
2480
- WHERE 1 = 1
2481
- ${db.pathExclusionsFor("documents")}
2482
- ORDER BY relative_path`
2483
- );
2484
- const scored = rows.filter((row) => !db.isIgnored(row.relative_path)).map((row) => ({
2485
- relativePath: row.relative_path,
2486
- score: scoreDocumentPath(row.relative_path, normalizedPattern)
2487
- })).filter((row) => row.score > 0).sort((a, b) => b.score - a.score || a.relativePath.localeCompare(b.relativePath));
2488
- if (scored.length === 0) {
2489
- const symbolMatch = findFirstSymbolMatch(db, filePattern);
2490
- if (!symbolMatch || db.isIgnored(symbolMatch.relativePath)) {
2491
- return [];
2492
- }
2493
- return [{
2494
- relativePath: symbolMatch.relativePath,
2495
- score: 700
2496
- }];
2497
- }
2498
- const exactish = scored.filter((row) => row.score >= 800);
2499
- if (exactish.length > 0) {
2500
- return opts.allowMultiple ? exactish : [exactish[0]];
2501
- }
2502
- return opts.allowMultiple ? scored : [scored[0]];
2503
- }
2504
- function scoreDocumentPath(relativePath, rawPattern) {
2505
- const normalizedPath = normalizeLookupPath(relativePath);
2506
- const pathBase = basename2(normalizedPath);
2507
- const patternBase = basename2(rawPattern);
2508
- let score = 0;
2509
- if (normalizedPath === rawPattern) score += 1200;
2510
- if (normalizedPath.endsWith(`/${rawPattern}`)) score += 1100;
2511
- if (pathBase === patternBase) score += 900;
2512
- if (normalizedPath.startsWith(`${rawPattern}/`)) score += 850;
2513
- if (normalizedPath.includes(rawPattern)) score += 250;
2514
- return score;
2515
- }
2516
- function normalizeLookupPath(filePattern) {
2517
- return filePattern.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
2518
- }
2519
- function uniquePatterns(patterns) {
2520
- return [...new Set(patterns)];
2521
- }
2522
-
2523
- export {
2524
- getSourceImports,
2525
- getSourceExports,
2526
- getSourceText,
2527
- TEST_FILE_PATTERNS,
2528
- TEST_SUPPORT_PATH_PATTERNS,
2529
- testFileExclusionSql,
2530
- buildFileDepGraph,
2531
- findFirstSymbolMatch,
2532
- findExactSymbolMatch,
2533
- resolveIndexedFile,
2534
- resolveIndexedPaths,
2535
- getCalleeRowsForSymbol,
2536
- getCallerRowsForSymbol,
2537
- getSourceReferenceSites,
2538
- getDefinitionsForFile,
2539
- getAllDefinitions,
2540
- getScopedDefinitions
2541
- };
2542
- //# sourceMappingURL=chunk-FMAYH7GS.js.map