devlensio 1.0.3 → 1.1.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 (75) hide show
  1. package/dist/config/backcompat.test.d.ts +1 -0
  2. package/dist/config/backcompat.test.js +188 -0
  3. package/dist/config/index.d.ts +5 -3
  4. package/dist/config/index.js +37 -54
  5. package/dist/config/providers/file.d.ts +3 -1
  6. package/dist/config/providers/file.js +47 -53
  7. package/dist/config/providers/providers.default.js +0 -1
  8. package/dist/config/providers/request.js +1 -1
  9. package/dist/config/types.d.ts +0 -1
  10. package/dist/config/types.js +2 -18
  11. package/dist/graph/edges/callEdges.js +97 -5
  12. package/dist/graph/edges/callEdges.test.js +154 -0
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/jobs/queue/memory.js +12 -1
  16. package/dist/parser/extractors/classes.js +23 -4
  17. package/dist/parser/extractors/functions.d.ts +10 -3
  18. package/dist/parser/extractors/functions.js +135 -65
  19. package/dist/parser/extractors/hooks.js +5 -29
  20. package/dist/parser/extractors/objectMethods.js +3 -4
  21. package/dist/parser/index.js +11 -6
  22. package/dist/parser/overloads.d.ts +2 -0
  23. package/dist/parser/overloads.js +96 -0
  24. package/dist/parser/overloads.test.d.ts +1 -0
  25. package/dist/parser/overloads.test.js +175 -0
  26. package/dist/parser/typeUtils.d.ts +2 -0
  27. package/dist/parser/typeUtils.js +2 -0
  28. package/dist/summarizer/providers/index.js +4 -4
  29. package/dist/summarizer/providers/openai.js +1 -1
  30. package/dist/types.d.ts +6 -0
  31. package/extractors/go/bin/darwin-amd64/devlens_go_extractor +0 -0
  32. package/extractors/go/bin/darwin-arm64/devlens_go_extractor +0 -0
  33. package/extractors/go/bin/linux-amd64/devlens_go_extractor +0 -0
  34. package/extractors/go/bin/linux-arm64/devlens_go_extractor +0 -0
  35. package/extractors/go/bin/windows-amd64/devlens_go_extractor.exe +0 -0
  36. package/extractors/go/calls.go +134 -2
  37. package/extractors/go/contract.go +1 -0
  38. package/extractors/go/exports.go +107 -0
  39. package/extractors/go/exports_test.go +64 -0
  40. package/extractors/go/extractor.go +1 -0
  41. package/extractors/go/lookup.go +63 -7
  42. package/extractors/go/nodes.go +28 -0
  43. package/extractors/go/parser.go +51 -8
  44. package/extractors/java/devlens_java_extractor.jar +0 -0
  45. package/extractors/java/src/devlens/extractor/ExportsMapBuilder.java +148 -0
  46. package/extractors/java/src/devlens/extractor/Extractor.java +34 -0
  47. package/extractors/java/src/devlens/extractor/LookupMaps.java +12 -0
  48. package/extractors/java/src/devlens/extractor/Overloads.java +290 -0
  49. package/extractors/java/src/devlens/extractor/Parser.java +39 -0
  50. package/extractors/java/src/devlens/extractor/TypeSolverFactory.java +9 -0
  51. package/extractors/java/src/devlens/extractor/edges/Calls.java +42 -36
  52. package/extractors/java/src/devlens/extractor/edges/Routes.java +10 -3
  53. package/extractors/python/devlens_extractors_python/edges/calls.py +127 -26
  54. package/extractors/python/devlens_extractors_python/exports_map.py +263 -0
  55. package/extractors/python/devlens_extractors_python/extractor.py +7 -1
  56. package/extractors/python/devlens_extractors_python/lookup.py +6 -0
  57. package/extractors/python/devlens_extractors_python/parser/__init__.py +6 -0
  58. package/extractors/python/devlens_extractors_python/parser/functions.py +103 -6
  59. package/extractors/python/devlens_extractors_python/parser/overloads.py +105 -0
  60. package/extractors/rust/bin/darwin-amd64/devlens_rust_extractor +0 -0
  61. package/extractors/rust/bin/darwin-arm64/devlens_rust_extractor +0 -0
  62. package/extractors/rust/bin/linux-amd64/devlens_rust_extractor +0 -0
  63. package/extractors/rust/bin/linux-arm64/devlens_rust_extractor +0 -0
  64. package/extractors/rust/bin/windows-amd64/devlens_rust_extractor.exe +0 -0
  65. package/extractors/rust/src/calls.rs +27 -16
  66. package/extractors/rust/src/contract.rs +2 -0
  67. package/extractors/rust/src/exports.rs +387 -0
  68. package/extractors/rust/src/exports_test.rs +105 -0
  69. package/extractors/rust/src/extractor.rs +2 -0
  70. package/extractors/rust/src/lookup.rs +60 -0
  71. package/extractors/rust/src/main.rs +4 -0
  72. package/extractors/rust/src/nodes.rs +19 -0
  73. package/extractors/rust/src/parser.rs +66 -1
  74. package/extractors/rust/src/routes.rs +2 -1
  75. package/package.json +10 -3
@@ -0,0 +1,175 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { parseRepo } from "./index.js";
5
+ function createFakeRepo(files) {
6
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "devlens-overloads-test-"));
7
+ for (const [filePath, content] of Object.entries(files)) {
8
+ const fullPath = path.join(tmpDir, filePath);
9
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
10
+ fs.writeFileSync(fullPath, content);
11
+ }
12
+ return tmpDir;
13
+ }
14
+ function deleteFakeRepo(repoPath) {
15
+ fs.rmSync(repoPath, { recursive: true, force: true });
16
+ }
17
+ describe("overload disambiguation (same-name function-likes in one file)", () => {
18
+ it("keeps the clean unsuffixed id when the name is unique in the file", () => {
19
+ const repo = createFakeRepo({
20
+ "src/unique.ts": `
21
+ export function formatValue(v: string) { return v.trim(); }
22
+ `,
23
+ });
24
+ const { nodes } = parseRepo(repo);
25
+ const fn = nodes.find((n) => n.name === "formatValue");
26
+ expect(fn?.id).toBe("src/unique.ts::formatValue");
27
+ expect(fn?.metadata.isOverloadSignature).toBeUndefined();
28
+ deleteFakeRepo(repo);
29
+ });
30
+ it("suffixes each same-name function with its OWN arity (no ordinals)", () => {
31
+ const repo = createFakeRepo({
32
+ "src/arity.ts": `
33
+ export function formatValue(v: string) { return v.trim(); }
34
+ export function formatValue(v: string, n: number) { return v.repeat(n); }
35
+ export function formatValue(v: string, n: number, flag: boolean) { return v; }
36
+ `,
37
+ });
38
+ const { nodes } = parseRepo(repo);
39
+ const ids = nodes.filter((n) => n.name === "formatValue").map((n) => n.id).sort();
40
+ expect(ids).toEqual([
41
+ "src/arity.ts::formatValue#1",
42
+ "src/arity.ts::formatValue#2",
43
+ "src/arity.ts::formatValue#3",
44
+ ]);
45
+ deleteFakeRepo(repo);
46
+ });
47
+ it("suffixes same-arity different-type overloads with an arity+signature hash", () => {
48
+ const repo = createFakeRepo({
49
+ "src/types.ts": `
50
+ export function decode(input: string, mode: string) { return input; }
51
+ export function decode(input: number, mode: string) { return String(input); }
52
+ `,
53
+ });
54
+ const { nodes } = parseRepo(repo);
55
+ const fns = nodes.filter((n) => n.name === "decode");
56
+ expect(fns.length).toBe(2);
57
+ const ids = fns.map((n) => n.id).sort();
58
+ // both share arity 2, differ only by types → distinct sig hashes
59
+ expect(ids[0]).toMatch(/^src\/types\.ts::decode#2#[0-9a-f]{8}$/);
60
+ expect(ids[1]).toMatch(/^src\/types\.ts::decode#2#[0-9a-f]{8}$/);
61
+ expect(ids[0]).not.toBe(ids[1]);
62
+ // deterministic: same signature → same hash across runs
63
+ expect(ids).toEqual([...ids].sort());
64
+ deleteFakeRepo(repo);
65
+ });
66
+ it("collapses an overload signature into a signature-identical implementation", () => {
67
+ const repo = createFakeRepo({
68
+ "src/collapse.ts": `
69
+ export function greet(name: string): string;
70
+ export function greet(name: string) { return "hi " + name; }
71
+ `,
72
+ });
73
+ const { nodes } = parseRepo(repo);
74
+ const greets = nodes.filter((n) => n.name === "greet");
75
+ expect(greets.length).toBe(1);
76
+ expect(greets[0].id).toBe("src/collapse.ts::greet");
77
+ expect(greets[0].rawCode).toContain("return");
78
+ deleteFakeRepo(repo);
79
+ });
80
+ it("keeps an overload signature separate when the implementation has different params", () => {
81
+ const repo = createFakeRepo({
82
+ "src/keepboth.ts": `
83
+ export function parse(input: string): string;
84
+ export function parse(input: string | number) { return String(input); }
85
+ `,
86
+ });
87
+ const { nodes } = parseRepo(repo);
88
+ const parses = nodes.filter((n) => n.name === "parse");
89
+ expect(parses.length).toBe(2);
90
+ // one of them is the bare signature
91
+ const sig = parses.find((n) => n.metadata.isOverloadSignature === true);
92
+ const impl = parses.find((n) => n.metadata.isOverloadSignature === undefined);
93
+ expect(sig).toBeDefined();
94
+ expect(impl).toBeDefined();
95
+ // distinct ids, both arity 1 with different type shapes → hash suffixes
96
+ expect(sig.id).not.toBe(impl.id);
97
+ expect(sig.id).toMatch(/^src\/keepboth\.ts::parse#1#[0-9a-f]{8}$/);
98
+ deleteFakeRepo(repo);
99
+ });
100
+ it("suffixes class method overloads with dotted names, not cross-class names", () => {
101
+ const repo = createFakeRepo({
102
+ "src/logger.ts": `
103
+ export class Logger {
104
+ log(msg: string) { console.log(msg); }
105
+ log(msg: string, level: number) { console.log(level, msg); }
106
+ }
107
+ export class Auditor {
108
+ log(entry: string) { console.log(entry); }
109
+ }
110
+ `,
111
+ });
112
+ const { nodes } = parseRepo(repo);
113
+ const logMethods = nodes.filter((n) => n.type === "METHOD" && n.name.endsWith(".log"));
114
+ const ids = logMethods.map((n) => n.id).sort();
115
+ expect(ids).toEqual([
116
+ "src/logger.ts::Auditor.log", // unique within its class → no suffix
117
+ "src/logger.ts::Logger.log#1",
118
+ "src/logger.ts::Logger.log#2",
119
+ ]);
120
+ deleteFakeRepo(repo);
121
+ });
122
+ it("never changes ids of different-name or different-file nodes", () => {
123
+ const repo = createFakeRepo({
124
+ "src/a.ts": `
125
+ export function helper() { return 1; }
126
+ `,
127
+ "src/b.ts": `
128
+ export function helper() { return 2; }
129
+ `,
130
+ });
131
+ const { nodes } = parseRepo(repo);
132
+ const helpers = nodes.filter((n) => n.name === "helper").map((n) => n.id).sort();
133
+ expect(helpers).toEqual(["src/a.ts::helper", "src/b.ts::helper"]);
134
+ deleteFakeRepo(repo);
135
+ });
136
+ it("captures callSites with argCount, argTypes and hasSpread", () => {
137
+ const repo = createFakeRepo({
138
+ "src/caller.ts": `
139
+ export function run() {
140
+ formatValue("abc");
141
+ formatValue("abc", 3);
142
+ logAll("a", "b", ...rest);
143
+ }
144
+ `,
145
+ });
146
+ const { nodes } = parseRepo(repo);
147
+ const run = nodes.find((n) => n.name === "run");
148
+ const sites = run?.metadata.callSites;
149
+ expect(sites).toBeDefined();
150
+ const byName = new Map(sites.map((s) => [`${s.name}/${s.argCount}`, s]));
151
+ expect(byName.get("formatValue/1")?.argTypes).toEqual(["string"]);
152
+ expect(byName.get("formatValue/2")?.argTypes).toEqual(["string", "number"]);
153
+ expect(byName.get("logAll/3")?.hasSpread).toBe(true);
154
+ // legacy calls list stays in sync
155
+ expect(run?.metadata.calls).toContain("formatValue");
156
+ deleteFakeRepo(repo);
157
+ });
158
+ it("does not treat same-name functions in different files as overloads (per-file scope)", () => {
159
+ const repo = createFakeRepo({
160
+ "src/x.ts": `
161
+ export function handle(a: string) { return a; }
162
+ `,
163
+ "src/y.ts": `
164
+ export function handle(a: string, b: string) { return a + b; }
165
+ `,
166
+ });
167
+ const { nodes } = parseRepo(repo);
168
+ const handlers = nodes.filter((n) => n.name === "handle");
169
+ expect(handlers.map((n) => n.id).sort()).toEqual([
170
+ "src/x.ts::handle",
171
+ "src/y.ts::handle",
172
+ ]);
173
+ deleteFakeRepo(repo);
174
+ });
175
+ });
@@ -2,6 +2,8 @@ import { SourceFile } from "ts-morph";
2
2
  export interface ParamInfo {
3
3
  name: string;
4
4
  type?: string;
5
+ isOptional?: boolean;
6
+ isRest?: boolean;
5
7
  }
6
8
  export declare function extractParams(node: any): ParamInfo[];
7
9
  export declare function extractReturnTypeAnnotation(node: any): string | undefined;
@@ -3,6 +3,8 @@ export function extractParams(node) {
3
3
  return params.map((p) => ({
4
4
  name: p.getName(),
5
5
  type: p.getTypeNode()?.getText() ?? undefined,
6
+ isOptional: typeof p.isOptional === "function" ? p.isOptional() : undefined,
7
+ isRest: typeof p.isRestParameter === "function" ? p.isRestParameter() : undefined,
6
8
  }));
7
9
  }
8
10
  export function extractReturnTypeAnnotation(node) {
@@ -12,13 +12,13 @@ export function createLLMClient(config) {
12
12
  const effectiveBase = baseUrl ?? entry?.baseUrl;
13
13
  switch (provider) {
14
14
  case "openai": {
15
- if (needsKey && !apiKey)
16
- throw new Error(`Provider "${providerName}" requires an API key`);
17
- return new OpenAIClient(apiKey ?? "ollama", model, effectiveBase, providerName);
15
+ if (!apiKey)
16
+ throw new Error(`No API key configured for "${providerName}" — run "devlens init" to set one up.`);
17
+ return new OpenAIClient(apiKey, model, effectiveBase, providerName);
18
18
  }
19
19
  case "anthropic": {
20
20
  if (!apiKey)
21
- throw new Error(`Provider "${providerName}" requires an API key`);
21
+ throw new Error(`No API key configured for "${providerName}" — run "devlens init" to set one up.`);
22
22
  return new AnthropicClient(apiKey, model, effectiveBase, providerName);
23
23
  }
24
24
  default:
@@ -26,7 +26,7 @@ function parseResponse(raw) {
26
26
  tokensUsed: 0,
27
27
  };
28
28
  }
29
- // Also used as the base for OpenRouter and Ollama —
29
+ // Also used as the base for other OpenAI-compatible providers —
30
30
  // both expose OpenAI-compatible APIs, just with a different baseURL.
31
31
  export class OpenAIClient {
32
32
  constructor(apiKey, model, baseURL, providerName) {
package/dist/types.d.ts CHANGED
@@ -48,6 +48,12 @@ export interface BackendRouteNode {
48
48
  };
49
49
  }
50
50
  export type NodeType = "COMPONENT" | "HOOK" | "FUNCTION" | "STATE_STORE" | "UTILITY" | "FILE" | "GHOST" | "ROUTE" | "TEST" | "STORY" | "THIRD_PARTY" | "CLASS" | "METHOD" | "INTERFACE" | "ENUM" | "STRUCT" | "MODULE" | "TRAIT" | "IMPL_BLOCK" | "PACKAGE";
51
+ export interface CallSite {
52
+ name: string;
53
+ argCount: number;
54
+ argTypes?: string[];
55
+ hasSpread?: boolean;
56
+ }
51
57
  export interface CodeNode {
52
58
  id: string;
53
59
  name: string;
@@ -152,8 +152,11 @@ func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
152
152
  if id, ok := l.MethodNodeByPkgTypeName[pkgPath+"::"+c.Receiver+"."+c.Sel]; ok {
153
153
  return id, c.Sel, c.Receiver, callEdge(callerID, id, c.Sel, c.Receiver)
154
154
  }
155
- // receiver is a plain variable whose type we can't see — unresolvable
156
- // tier (documented; type info covers the exact cases)
155
+ // receiver is a plain variable whose type we can't see — bare-method-name
156
+ // candidates across packages, filtered by arity/type shape
157
+ if id, matchedBy := resolveByCandidates(l.MethodCandidatesByName[c.Sel], c, pf.RelPath); id != "" {
158
+ return id, c.Sel, "", callEdgeMatched(callerID, id, c.Sel, "", matchedBy)
159
+ }
157
160
  return "", "", "", nil
158
161
  }
159
162
 
@@ -161,6 +164,11 @@ func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
161
164
  if id, ok := l.FuncNodeByPkgName[pkgPath+"::"+c.Str]; ok {
162
165
  return id, "", "", callEdge(callerID, id, "", "")
163
166
  }
167
+ // same-package miss: bare-name candidates across packages, filtered by
168
+ // arity/type shape (fire only where resolution previously gave up)
169
+ if id, matchedBy := resolveByCandidates(l.FuncCandidatesByName[c.Str], c, pf.RelPath); id != "" {
170
+ return id, "", "", callEdgeMatched(callerID, id, "", "", matchedBy)
171
+ }
164
172
  return "", "", "", nil
165
173
  }
166
174
 
@@ -175,6 +183,130 @@ func callEdge(from, to, method, class string) map[string]any {
175
183
  return edgeWithMeta(from, to, EdgeCalls, meta)
176
184
  }
177
185
 
186
+ // callEdgeMatched — callEdge plus resolution confidence from the arity-aware
187
+ // candidate tier: "arity" (arg count singled out the target), "signature"
188
+ // (arg type agreement decided it), "name" (path proximity fallback).
189
+ func callEdgeMatched(from, to, method, class, matchedBy string) map[string]any {
190
+ e := callEdge(from, to, method, class)
191
+ e["metadata"].(map[string]any)["matchedBy"] = matchedBy
192
+ return e
193
+ }
194
+
195
+ // ── arity-aware candidate resolution ──
196
+
197
+ // arityAccepts — Go call compatibility: exact arg count, except a variadic
198
+ // tail accepts any count >= required. Spread calls (f(xs...)) have an
199
+ // unknowable runtime arity — every candidate stays admissible.
200
+ func arityAccepts(cand funcCandidate, argCount int, hasSpread bool) bool {
201
+ if hasSpread {
202
+ return true
203
+ }
204
+ if cand.Variadic {
205
+ return argCount >= cand.Required
206
+ }
207
+ return argCount == cand.Required
208
+ }
209
+
210
+ // typeAgrees — loose agreement between a call-site arg tag and a declared
211
+ // param type text; "unknown" tags never match (parity with the TS resolver).
212
+ func typeAgrees(argType, paramType string) bool {
213
+ if argType == "" || argType == "unknown" || paramType == "" {
214
+ return false
215
+ }
216
+ return paramType == argType || strings.Contains(paramType, argType)
217
+ }
218
+
219
+ // typeScore — how many argument tags agree with the declared params.
220
+ func typeScore(cand funcCandidate, argTypes []string) int {
221
+ score := 0
222
+ for i, at := range argTypes {
223
+ if i < len(cand.ParamTypes) && typeAgrees(at, cand.ParamTypes[i]) {
224
+ score++
225
+ }
226
+ }
227
+ return score
228
+ }
229
+
230
+ // pathProximity — shared leading path segments between two rel paths
231
+ // (mirrors the TS engine's closestByPath tiebreak).
232
+ func pathProximity(candidate, reference string) int {
233
+ a := strings.Split(candidate, "/")
234
+ b := strings.Split(reference, "/")
235
+ score := 0
236
+ for i := 0; i < len(a) && i < len(b); i++ {
237
+ if a[i] != b[i] {
238
+ break
239
+ }
240
+ score++
241
+ }
242
+ return score
243
+ }
244
+
245
+ // resolveByCandidates — pick among same-name declarations by argument shape:
246
+ // arity filter first, then arg-type agreement tiebreak, then path proximity.
247
+ // Single-candidate groups return immediately (matchedBy "arity" only when the
248
+ // call shape actually participated). Returns ("", "") when nothing applies.
249
+ func resolveByCandidates(candidates []funcCandidate, c CallSite, callerRel string) (string, string) {
250
+ if len(candidates) == 0 {
251
+ return "", ""
252
+ }
253
+ if len(candidates) == 1 {
254
+ // a lone same-name declaration elsewhere — arity still gates it
255
+ if arityAccepts(candidates[0], c.ArgCount, c.HasSpread) {
256
+ return candidates[0].ID, "arity"
257
+ }
258
+ return "", ""
259
+ }
260
+
261
+ pool := make([]funcCandidate, 0, len(candidates))
262
+ for _, cand := range candidates {
263
+ if arityAccepts(cand, c.ArgCount, c.HasSpread) {
264
+ pool = append(pool, cand)
265
+ }
266
+ }
267
+ if len(pool) == 0 {
268
+ return "", "" // nothing accepts this shape — stay unresolvable
269
+ }
270
+ if len(pool) == 1 {
271
+ return pool[0].ID, "arity"
272
+ }
273
+
274
+ // type agreement tiebreak — needs usable (non-unknown) arg tags
275
+ usable := false
276
+ for _, at := range c.ArgTypes {
277
+ if at != "unknown" {
278
+ usable = true
279
+ break
280
+ }
281
+ }
282
+ if usable {
283
+ best := pool[0]
284
+ bestScore := typeScore(pool[0], c.ArgTypes)
285
+ tie := 1
286
+ for _, cand := range pool[1:] {
287
+ s := typeScore(cand, c.ArgTypes)
288
+ if s > bestScore {
289
+ best, bestScore, tie = cand, s, 1
290
+ } else if s == bestScore {
291
+ tie++
292
+ }
293
+ }
294
+ if bestScore > 0 && tie == 1 {
295
+ return best.ID, "signature"
296
+ }
297
+ }
298
+
299
+ // path proximity fallback
300
+ best := pool[0]
301
+ bestScore := pathProximity(best.RelPath, callerRel)
302
+ for _, cand := range pool[1:] {
303
+ if s := pathProximity(cand.RelPath, callerRel); s > bestScore {
304
+ best, bestScore = cand, s
305
+ }
306
+ }
307
+ return best.ID, "name"
308
+ }
309
+
178
310
  // receiverDeclaredType — the receiver's type from its DECLARATION: function
179
311
  // parameters first (func(c *gin.Context) — the documented handler signature),
180
312
  // then package-level typed vars (var DB *gorm.DB). Returns (importPath,
@@ -89,6 +89,7 @@ type ExtractorResult struct {
89
89
  Nodes []map[string]any `json:"nodes"`
90
90
  Edges []map[string]any `json:"edges"`
91
91
  Routes []map[string]any `json:"routes"`
92
+ Exports *ExportsMap `json:"exports,omitempty"`
92
93
  Stats Stats `json:"stats"`
93
94
  Errors []ExtractorError `json:"errors"`
94
95
  }
@@ -0,0 +1,107 @@
1
+ // exports.go — the flattened public surface of a Go module, shipped in the
2
+ // ExtractorResult for cross-repo linking (docs/EXPORTS_MAP.md).
3
+ //
4
+ // Go-specific concerns:
5
+ // - Export = capitalized identifier (token.IsExported); Go has no
6
+ // package.json "door" — every package is importable, so the map is keyed
7
+ // by package: subpath "." for the module-root package, "./rel/dir" for
8
+ // the rest (mirrors the TS multi-door shape).
9
+ // - The map key is the name an importer writes: plain funcs/structs/
10
+ // interfaces/enums use their bare name; exported methods of exported
11
+ // types use "Type.Method" (that is what consumer code writes).
12
+ // - Go has no overloads → values are always single-element arrays.
13
+ // - Test files are excluded (their symbols are not importable surface).
14
+ // - Same-name duplicates within a package cannot compile, but if the
15
+ // walker ever yields them, all ids are emitted rather than guessing.
16
+ // - Requires go.mod: without a module path the consumer-side join key
17
+ // ([mod]/importPath) is undefined, so no map is emitted.
18
+ package main
19
+
20
+ import (
21
+ "go/token"
22
+ "sort"
23
+ "strings"
24
+ )
25
+
26
+ type ExportsMap struct {
27
+ Exports map[string]map[string][]string `json:"exports"`
28
+ AmbiguousNames map[string][]string `json:"ambiguousNames"`
29
+ }
30
+
31
+ func buildExportsMap(pr *parsedRepo) *ExportsMap {
32
+ if pr.mod == nil || !pr.mod.HasMod || pr.mod.ModulePath == "" {
33
+ return nil
34
+ }
35
+
36
+ exports := map[string]map[string][]string{}
37
+ ambiguous := map[string][]string{}
38
+
39
+ for _, pkg := range pr.packages {
40
+ rel := strings.TrimPrefix(pkg.ImportPath, pr.mod.ModulePath)
41
+ rel = strings.TrimPrefix(rel, "/")
42
+ subpath := "."
43
+ if rel != "" && rel != "." {
44
+ subpath = "./" + rel
45
+ }
46
+
47
+ perPath := map[string][]string{}
48
+ for _, pf := range pkg.Files {
49
+ if pf.IsTest {
50
+ continue
51
+ }
52
+ for _, fn := range pf.Funcs {
53
+ if fn.IsTest {
54
+ continue
55
+ }
56
+ if fn.IsMethod {
57
+ if !token.IsExported(fn.RecvType) || !token.IsExported(fn.Name) {
58
+ continue
59
+ }
60
+ addExport(perPath, fn.RecvType+"."+fn.Name, methodNodeID(pf.RelPath, fn))
61
+ } else {
62
+ if !token.IsExported(fn.Name) {
63
+ continue
64
+ }
65
+ addExport(perPath, fn.Name, funcNodeID(pf.RelPath, fn.Name))
66
+ }
67
+ }
68
+ for _, st := range pf.Structs {
69
+ if !token.IsExported(st.Name) {
70
+ continue
71
+ }
72
+ addExport(perPath, st.Name, structNodeID(pf.RelPath, st.Name))
73
+ }
74
+ for _, it := range pf.Interfaces {
75
+ if !token.IsExported(it.Name) {
76
+ continue
77
+ }
78
+ addExport(perPath, it.Name, interfaceNodeID(pf.RelPath, it.Name))
79
+ }
80
+ for _, en := range pf.numericEnums {
81
+ if !token.IsExported(en.TypeName) {
82
+ continue
83
+ }
84
+ addExport(perPath, en.TypeName, structNodeID(pf.RelPath, en.TypeName))
85
+ }
86
+ }
87
+
88
+ if len(perPath) > 0 {
89
+ exports[subpath] = perPath
90
+ }
91
+ }
92
+
93
+ if len(exports) == 0 {
94
+ return nil
95
+ }
96
+ return &ExportsMap{Exports: exports, AmbiguousNames: ambiguous}
97
+ }
98
+
99
+ func addExport(perPath map[string][]string, name, id string) {
100
+ for _, existing := range perPath[name] {
101
+ if existing == id {
102
+ return
103
+ }
104
+ }
105
+ perPath[name] = append(perPath[name], id)
106
+ sort.Strings(perPath[name])
107
+ }
@@ -0,0 +1,64 @@
1
+ package main
2
+
3
+ import (
4
+ "reflect"
5
+ "testing"
6
+ )
7
+
8
+ func TestBuildExportsMapPublicSurface(t *testing.T) {
9
+ repo := parseRepo("tests/fixtures/plainfix", parseGoMod("tests/fixtures/plainfix"), func(string, string) {})
10
+ m := buildExportsMap(repo)
11
+ if m == nil {
12
+ t.Fatal("expected exports map for a module with go.mod")
13
+ }
14
+
15
+ perPath, ok := m.Exports["."]
16
+ if !ok {
17
+ t.Fatalf("expected root package subpath '.', got subpaths %v", keys(m.Exports))
18
+ }
19
+
20
+ expectIds(perPath, t, "Shape", []string{"shapes.go::Shape"})
21
+ expectIds(perPath, t, "Circle", []string{"shapes.go::Circle"})
22
+ expectIds(perPath, t, "Circle.Area", []string{"shapes.go::Circle.Area"})
23
+ expectIds(perPath, t, "Circle.Perimeter", []string{"shapes.go::Circle.Perimeter"})
24
+ expectIds(perPath, t, "Square.Scale", []string{"shapes.go::Square.Scale"})
25
+ expectIds(perPath, t, "Color", []string{"shapes.go::Color"})
26
+
27
+ if len(m.AmbiguousNames) != 0 {
28
+ t.Fatalf("expected no ambiguous names, got %v", m.AmbiguousNames)
29
+ }
30
+ }
31
+
32
+ func TestBuildExportsMapRequiresGoMod(t *testing.T) {
33
+ repo := parseRepo("tests/fixtures/plainfix", &modFile{}, func(string, string) {})
34
+ if m := buildExportsMap(repo); m != nil {
35
+ t.Fatal("expected no exports map without a module path")
36
+ }
37
+ }
38
+
39
+ func expectIds(perPath map[string][]string, t *testing.T, name string, want []string) {
40
+ t.Helper()
41
+ got, ok := perPath[name]
42
+ if !ok {
43
+ t.Fatalf("expected exported name %q in map, got keys %v", name, keysOf(perPath))
44
+ }
45
+ if !reflect.DeepEqual(got, want) {
46
+ t.Fatalf("%s: got %v, want %v", name, got, want)
47
+ }
48
+ }
49
+
50
+ func keys(m map[string]map[string][]string) []string {
51
+ out := []string{}
52
+ for k := range m {
53
+ out = append(out, k)
54
+ }
55
+ return out
56
+ }
57
+
58
+ func keysOf(m map[string][]string) []string {
59
+ out := []string{}
60
+ for k := range m {
61
+ out = append(out, k)
62
+ }
63
+ return out
64
+ }
@@ -109,6 +109,7 @@ func runExtractor(repoPath string, opts *Options) *ExtractorResult {
109
109
  result.Nodes = nodes
110
110
  result.Edges = allEdges
111
111
  result.Routes = routes
112
+ result.Exports = buildExportsMap(parsed)
112
113
  result.Stats = Stats{
113
114
  TotalFiles: len(parsed.files),
114
115
  TotalNodes: len(nodes),