graphlore 0.7.0__py3-none-any.whl

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.
graphlore/apis.py ADDED
@@ -0,0 +1,617 @@
1
+ """External-package API-surface extraction: which names a file actually USES.
2
+
3
+ The difference between "this module imports fastapi" (package level) and "this
4
+ module uses Depends, APIRouter, CORSMiddleware from fastapi" (symbol level). A
5
+ version upgrade is audited at the symbol level: a breaking change in a release
6
+ note only matters if it touches a symbol you use.
7
+
8
+ Two capture paths per file:
9
+ * **from-imports**: ``from fastapi import Depends, Query`` -> the symbol names
10
+ directly (``fastapi: {Depends, Query}``). ``import *`` is skipped (what was
11
+ taken can't be known) and relative imports are skipped (internal modules,
12
+ not external surface).
13
+ * **attribute access through an alias**: ``import numpy as np`` first builds an
14
+ alias -> package map; then every attribute chain is inspected — ``np.array(...)``
15
+ resolves the alias and records ``numpy: {array}``. The symbol comes from the
16
+ real use site, not the import line.
17
+
18
+ Both paths also record the **qualified path** variant: ``np.linalg.norm([1])``
19
+ resolves the whole chain to ``numpy.linalg.norm``, and ``from
20
+ fastapi.middleware.cors import CORSMiddleware`` keeps the full module path
21
+ (``fastapi.middleware.cors.CORSMiddleware``). The short symbol is the "what is
22
+ used" summary; the qualified path is the precise input for a version-diff audit.
23
+
24
+ Honest limits: dynamic import (``importlib.import_module``), ``getattr(pkg,
25
+ name)``, ``import *``, indirect use through a wrapper function and names inside
26
+ strings are all invisible. The symbol list is therefore a LOWER BOUND — it says
27
+ "at least these must be audited", never "only these"; zero visible symbols
28
+ reads as "no visibility", not "no usage".
29
+
30
+ Python via the stdlib ``ast``; JS/TS, Go and Java (imports plus use sites), and
31
+ Kotlin, Scala, C#, Rust, Swift, C / C++, Ruby and PHP (imports only: what each
32
+ file imports by name) via the optional tree-sitter backend. Results are cached
33
+ per (path, mtime) like the span index.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import ast
38
+ from typing import Any
39
+
40
+ from .spans import _cached_file_analysis, _ts_parser_for
41
+
42
+ # (packages, symbols, paths): every absolutely-imported package (even with no
43
+ # visible symbol), package -> short symbols used, package -> qualified use paths.
44
+ ApiUses = tuple[set[str], dict[str, set[str]], dict[str, set[str]]]
45
+
46
+ # Per-file API-use index, keyed by absolute path -> (mtime, ApiUses). Same
47
+ # bounded-FIFO scheme as spans._SPAN_CACHE (see there for the rationale).
48
+ _API_CACHE: dict[str, tuple[float, ApiUses]] = {}
49
+ _API_CACHE_MAX = 4096
50
+
51
+
52
+ def _empty() -> ApiUses:
53
+ return set(), {}, {}
54
+
55
+
56
+ def _record(
57
+ uses: ApiUses, pkg: str, module: str, chain: list[str], sep: str = "."
58
+ ) -> None:
59
+ """Record one use site: ``chain`` is the attribute/symbol chain after ``module``,
60
+ joined with the language's separator (``::`` in Rust, ``\\`` in PHP)."""
61
+ packages, symbols, paths = uses
62
+ packages.add(pkg)
63
+ if not chain:
64
+ return
65
+ symbols.setdefault(pkg, set()).add(chain[0])
66
+ paths.setdefault(pkg, set()).add(sep.join([module, *chain]))
67
+
68
+
69
+ def _txt(node: Any) -> str:
70
+ return node.text.decode("utf-8", "replace")
71
+
72
+
73
+ def _dotted_import(uses: ApiUses, full: str, wildcard: bool, sep: str = ".") -> None:
74
+ """``a.b.C`` -> a.b: {C}; a wildcard or a one-part name records the package only.
75
+ The import-level reading the JVM / .NET / PHP extractors share."""
76
+ full = full.strip().strip(sep)
77
+ if not full:
78
+ return
79
+ if wildcard or sep not in full:
80
+ uses[0].add(full)
81
+ return
82
+ module, _, symbol = full.rpartition(sep)
83
+ _record(uses, module, module, [symbol], sep)
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Python (stdlib ast)
88
+ # ---------------------------------------------------------------------------
89
+
90
+
91
+ def _api_uses_python(src: bytes) -> ApiUses:
92
+ uses = _empty()
93
+ packages, _symbols, _paths = uses
94
+ try:
95
+ tree = ast.parse(src)
96
+ except Exception:
97
+ return uses
98
+
99
+ # Pass 1 — imports. from-imports yield symbols directly; plain imports build
100
+ # the alias -> package map for pass 2 (``import numpy as np`` -> np: numpy).
101
+ aliases: dict[str, str] = {}
102
+ for node in ast.walk(tree):
103
+ if isinstance(node, ast.Import):
104
+ for a in node.names:
105
+ if a.asname:
106
+ aliases[a.asname] = a.name
107
+ else:
108
+ # `import a.b.c` binds only the top name `a`
109
+ top = a.name.split(".")[0]
110
+ aliases[top] = top
111
+ packages.add(a.name.split(".")[0])
112
+ elif isinstance(node, ast.ImportFrom):
113
+ if node.level or not node.module:
114
+ continue # relative import: internal module, not external surface
115
+ pkg = node.module.split(".")[0]
116
+ packages.add(pkg)
117
+ for a in node.names:
118
+ if a.name == "*":
119
+ continue # what was taken can't be known
120
+ _record(uses, pkg, node.module, [a.name])
121
+
122
+ # Pass 2 — attribute chains through an alias. ``np.linalg.norm([1])`` resolves
123
+ # outermost-first so the full chain is recorded once (never also ``np.linalg``).
124
+ class _AttrVisitor(ast.NodeVisitor):
125
+ def visit_Attribute(self, node: ast.Attribute) -> None:
126
+ chain: list[str] = []
127
+ cur: ast.expr = node
128
+ while isinstance(cur, ast.Attribute):
129
+ chain.append(cur.attr)
130
+ cur = cur.value
131
+ if isinstance(cur, ast.Name) and cur.id in aliases:
132
+ module = aliases[cur.id]
133
+ chain.reverse()
134
+ _record(uses, module.split(".")[0], module, chain)
135
+ return # chain consumed; don't re-visit its inner attributes
136
+ self.generic_visit(node)
137
+
138
+ try:
139
+ _AttrVisitor().visit(tree)
140
+ except RecursionError:
141
+ pass
142
+ return uses
143
+
144
+
145
+ # ---------------------------------------------------------------------------
146
+ # JS/TS, Go, Java (optional tree-sitter backend)
147
+ # ---------------------------------------------------------------------------
148
+
149
+
150
+ def _strip_quotes(text: str) -> str:
151
+ return text.strip().strip("'\"`")
152
+
153
+
154
+ def _js_package(source: str) -> str:
155
+ """npm package name from an import source: ``got/dist/x`` -> ``got``,
156
+ ``@scope/pkg/sub`` -> ``@scope/pkg``, ``node:fs`` kept whole."""
157
+ parts = source.split("/")
158
+ return "/".join(parts[:2]) if source.startswith("@") else parts[0]
159
+
160
+
161
+ def _js_internal_source(source: str) -> bool:
162
+ """Heuristically internal, i.e. NOT an npm package: relative imports
163
+ (``./x``), absolute paths (``/lib/x`` — whose "package" would be the empty
164
+ string), package.json ``#`` subpath imports, and the common bundler aliases
165
+ ``~/x`` and ``@/x``. A scoped ``@app/utils`` stays external: without reading
166
+ tsconfig it is indistinguishable from a real scoped npm package, so counting
167
+ it keeps the audit an over-approximation there rather than dropping real
168
+ packages."""
169
+ return not source or source.startswith((".", "/", "#", "~", "@/"))
170
+
171
+
172
+ def _api_uses_js(root: Any) -> ApiUses:
173
+ """import statements + member-expression chains through an alias (JS/TS/TSX).
174
+
175
+ ``import got from 'got'`` / ``* as ns`` / ``const x = require('pkg')`` feed the
176
+ alias map; ``import {HTTPError} from 'got'`` yields the symbol directly.
177
+ Relative sources (``./x``) are internal, not external surface.
178
+ """
179
+ uses = _empty()
180
+ aliases: dict[str, str] = {}
181
+
182
+ def handle_import(stmt: Any) -> None:
183
+ src_node = stmt.child_by_field_name("source")
184
+ if src_node is None:
185
+ return
186
+ source = _strip_quotes(src_node.text.decode("utf-8", "replace"))
187
+ if _js_internal_source(source):
188
+ return
189
+ pkg = _js_package(source)
190
+ uses[0].add(pkg)
191
+ stack = [c for c in stmt.named_children if c.type == "import_clause"]
192
+ while stack:
193
+ n = stack.pop()
194
+ if n.type == "import_specifier": # import { HTTPError as E }
195
+ name = n.child_by_field_name("name")
196
+ if name is not None:
197
+ _record(uses, pkg, source, [name.text.decode("utf-8", "replace")])
198
+ elif n.type == "namespace_import": # import * as ns
199
+ for c in n.named_children:
200
+ if c.type == "identifier":
201
+ aliases[c.text.decode("utf-8", "replace")] = source
202
+ elif n.type == "identifier": # default import
203
+ aliases[n.text.decode("utf-8", "replace")] = source
204
+ else:
205
+ stack.extend(n.named_children)
206
+
207
+ def require_source(call: Any) -> str | None:
208
+ fn = call.child_by_field_name("function")
209
+ args = call.child_by_field_name("arguments")
210
+ if fn is None or args is None or fn.text != b"require":
211
+ return None
212
+ for a in args.named_children:
213
+ if "string" in a.type:
214
+ source = _strip_quotes(a.text.decode("utf-8", "replace"))
215
+ return source if source and not source.startswith(".") else None
216
+ return None
217
+
218
+ def walk(node: Any) -> None:
219
+ for child in node.named_children:
220
+ t = child.type
221
+ if t == "import_statement":
222
+ handle_import(child)
223
+ continue
224
+ if t == "variable_declarator": # const x = require('pkg')
225
+ value = child.child_by_field_name("value")
226
+ name = child.child_by_field_name("name")
227
+ if (value is not None and value.type == "call_expression"
228
+ and name is not None
229
+ and (source := require_source(value)) is not None
230
+ and not _js_internal_source(source)):
231
+ pkg = _js_package(source)
232
+ uses[0].add(pkg)
233
+ if name.type == "identifier":
234
+ aliases[name.text.decode("utf-8", "replace")] = source
235
+ elif name.type == "object_pattern":
236
+ # const { HTTPError } = require('got') -> symbol-level
237
+ for p in name.named_children:
238
+ if "identifier" in p.type:
239
+ _record(uses, pkg, source,
240
+ [p.text.decode("utf-8", "replace")])
241
+ continue
242
+ if t == "call_expression" and (source := require_source(child)) is not None:
243
+ if not _js_internal_source(source):
244
+ uses[0].add(_js_package(source)) # bare require('pkg')
245
+ continue
246
+ if t == "member_expression":
247
+ chain: list[str] = []
248
+ cur = child
249
+ while cur.type == "member_expression":
250
+ prop = cur.child_by_field_name("property")
251
+ obj = cur.child_by_field_name("object")
252
+ if prop is None or obj is None:
253
+ break
254
+ chain.append(prop.text.decode("utf-8", "replace"))
255
+ cur = obj
256
+ if cur.type == "identifier":
257
+ name = cur.text.decode("utf-8", "replace")
258
+ if name in aliases:
259
+ source = aliases[name]
260
+ chain.reverse()
261
+ _record(uses, _js_package(source), source, chain)
262
+ continue # chain consumed
263
+ walk(child)
264
+
265
+ walk(root)
266
+ return uses
267
+
268
+
269
+ def _api_uses_go(root: Any) -> ApiUses:
270
+ """import specs + selector expressions / qualified types through the package name."""
271
+ uses = _empty()
272
+ aliases: dict[str, str] = {}
273
+
274
+ def walk(node: Any) -> None:
275
+ for child in node.named_children:
276
+ t = child.type
277
+ if t == "import_spec":
278
+ path_node = child.child_by_field_name("path")
279
+ if path_node is None:
280
+ continue
281
+ path = _strip_quotes(path_node.text.decode("utf-8", "replace"))
282
+ if not path:
283
+ continue
284
+ uses[0].add(path)
285
+ name_node = child.child_by_field_name("name")
286
+ local = (name_node.text.decode("utf-8", "replace")
287
+ if name_node is not None else path.split("/")[-1])
288
+ if local not in ("_", "."): # blank/dot imports bind no usable name
289
+ aliases[local] = path
290
+ elif t in ("selector_expression", "qualified_type"):
291
+ left = (child.child_by_field_name("operand")
292
+ or child.child_by_field_name("package"))
293
+ right = (child.child_by_field_name("field")
294
+ or child.child_by_field_name("name"))
295
+ if (left is not None and right is not None
296
+ and left.type in ("identifier", "package_identifier")):
297
+ name = left.text.decode("utf-8", "replace")
298
+ if name in aliases:
299
+ path = aliases[name]
300
+ _record(uses, path, path,
301
+ [right.text.decode("utf-8", "replace")])
302
+ continue
303
+ walk(child)
304
+
305
+ walk(root)
306
+ return uses
307
+
308
+
309
+ def _api_uses_java(root: Any) -> ApiUses:
310
+ """Java imports are already symbol-level: ``import a.b.Bar`` -> a.b: {Bar}.
311
+ Wildcard imports (``a.b.*``) record the package only (surface unknown)."""
312
+ uses = _empty()
313
+
314
+ def walk(node: Any) -> None:
315
+ for child in node.named_children:
316
+ if child.type == "import_declaration":
317
+ wildcard = any(c.type == "asterisk" for c in child.children)
318
+ dotted = next(
319
+ (c for c in child.named_children
320
+ if c.type in ("scoped_identifier", "identifier")), None)
321
+ if dotted is None:
322
+ continue
323
+ full = dotted.text.decode("utf-8", "replace")
324
+ if wildcard or "." not in full:
325
+ uses[0].add(full)
326
+ continue
327
+ module, _, symbol = full.rpartition(".")
328
+ _record(uses, module, module, [symbol])
329
+ else:
330
+ walk(child)
331
+
332
+ walk(root)
333
+ return uses
334
+
335
+
336
+ def _api_uses_kotlin(root: Any) -> ApiUses:
337
+ """``import a.b.C`` / ``import a.b.C as D`` -> a.b: {C}; ``import a.b.*`` -> a.b."""
338
+ uses = _empty()
339
+ for header in _descendants(root, "import_header"):
340
+ ident = next((c for c in header.named_children if c.type == "identifier"), None)
341
+ if ident is not None:
342
+ wildcard = any(c.type == "wildcard_import" for c in header.named_children)
343
+ _dotted_import(uses, _txt(ident), wildcard)
344
+ return uses
345
+
346
+
347
+ def _api_uses_scala(root: Any) -> ApiUses:
348
+ """``import a.b.C``, ``import a.b.{C, D => E}``, ``import a.b._`` and the
349
+ comma form ``import x.Y, p.q.{R}`` (one node, split on the commas)."""
350
+ uses = _empty()
351
+ for decl in _descendants(root, "import_declaration"):
352
+ groups: list[list[Any]] = [[]]
353
+ for c in decl.children:
354
+ if c.type == ",":
355
+ groups.append([])
356
+ elif c.is_named:
357
+ groups[-1].append(c)
358
+ for group in groups:
359
+ path = [_txt(c) for c in group if c.type == "identifier"]
360
+ selectors = next((c for c in group if c.type == "namespace_selectors"), None)
361
+ wildcard = any(c.type == "namespace_wildcard" for c in group)
362
+ if len(path) < 2 and selectors is None and not wildcard:
363
+ continue # `import Y` alone is relative to an earlier import
364
+ if selectors is not None and path:
365
+ module = ".".join(path)
366
+ for sel in selectors.named_children:
367
+ name = sel.child_by_field_name("name") or sel
368
+ if name.type == "identifier":
369
+ _record(uses, module, module, [_txt(name)])
370
+ else:
371
+ uses[0].add(module)
372
+ elif path:
373
+ _dotted_import(uses, ".".join(path), wildcard)
374
+ return uses
375
+
376
+
377
+ def _api_uses_csharp(root: Any) -> ApiUses:
378
+ """``using A.B;`` -> A.B; ``using static A.B.C;`` -> A.B: {C}; an alias
379
+ ``using X = A.B;`` -> A.B (it may name a type, so no symbol is claimed)."""
380
+ uses = _empty()
381
+ for decl in _descendants(root, "using_directive"):
382
+ target = next((c for c in decl.named_children
383
+ if c.type in ("qualified_name", "identifier")
384
+ and c != decl.child_by_field_name("name")), None)
385
+ if target is None:
386
+ continue
387
+ full = _txt(target)
388
+ if any(c.type == "static" for c in decl.children):
389
+ _dotted_import(uses, full, False)
390
+ else:
391
+ uses[0].add(full)
392
+ return uses
393
+
394
+
395
+ _RUST_LOCAL_ROOTS = frozenset({"crate", "self", "super", "Self"})
396
+
397
+
398
+ def _api_uses_rust(root: Any) -> ApiUses:
399
+ """``use a::b::{c, d as e};`` -> a: {b::c, b::d}; ``use a::*`` -> a;
400
+ ``extern crate x`` -> x. ``crate::`` / ``self::`` / ``super::`` and modules
401
+ declared in the same file (``mod request;``) are the crate itself."""
402
+ uses = _empty()
403
+ local = {_txt(n) for m in _descendants(root, "mod_item")
404
+ if (n := m.child_by_field_name("name")) is not None}
405
+
406
+ def paths(node: Any, prefix: list[str]) -> list[list[str]]:
407
+ t = node.type
408
+ if t in ("identifier", "crate", "self", "super", "scoped_identifier"):
409
+ return [prefix + [p for p in _txt(node).split("::") if p]]
410
+ if t == "use_as_clause":
411
+ inner = node.child_by_field_name("path")
412
+ return paths(inner, prefix) if inner is not None else []
413
+ if t == "use_wildcard":
414
+ base = next(iter(node.named_children), None)
415
+ return [prefix + ([p for p in _txt(base).split("::") if p] if base else [])]
416
+ if t == "scoped_use_list":
417
+ base = node.child_by_field_name("path")
418
+ lst = node.child_by_field_name("list")
419
+ head = prefix + ([p for p in _txt(base).split("::") if p] if base else [])
420
+ return [p for item in (lst.named_children if lst else ()) for p in paths(item, head)]
421
+ if t == "use_list":
422
+ return [p for item in node.named_children for p in paths(item, prefix)]
423
+ return []
424
+
425
+ for decl in _descendants(root, "use_declaration"):
426
+ arg = decl.child_by_field_name("argument")
427
+ for parts in paths(arg, []) if arg is not None else []:
428
+ parts = [p for p in parts if p != "self"] if len(parts) > 1 else parts
429
+ if not parts or parts[0] in _RUST_LOCAL_ROOTS or parts[0] in local:
430
+ continue
431
+ crate = parts[0]
432
+ if len(parts) == 1:
433
+ uses[0].add(crate)
434
+ else:
435
+ _record(uses, crate, crate, ["::".join(parts[1:])], "::")
436
+ for decl in _descendants(root, "extern_crate_declaration"):
437
+ name = decl.child_by_field_name("name")
438
+ if name is not None and _txt(name) not in _RUST_LOCAL_ROOTS:
439
+ uses[0].add(_txt(name))
440
+ return uses
441
+
442
+
443
+ def _api_uses_swift(root: Any) -> ApiUses:
444
+ """``import Foundation`` -> Foundation; ``import struct A.B`` -> A: {B}."""
445
+ uses = _empty()
446
+ for decl in _descendants(root, "import_declaration"):
447
+ ident = next((c for c in decl.named_children if c.type == "identifier"), None)
448
+ if ident is None:
449
+ continue
450
+ parts = [_txt(c) for c in ident.named_children if c.type == "simple_identifier"]
451
+ if not parts:
452
+ continue
453
+ if len(parts) > 1:
454
+ _record(uses, parts[0], parts[0], [".".join(parts[1:])])
455
+ else:
456
+ uses[0].add(parts[0])
457
+ return uses
458
+
459
+
460
+ def _api_uses_c(root: Any) -> ApiUses:
461
+ """``#include <curl/curl.h>`` -> curl: {curl.h}; ``#include <stdio.h>`` ->
462
+ stdio.h. A quoted ``#include "x.h"`` is the project's own header."""
463
+ uses = _empty()
464
+ for inc in _descendants(root, "preproc_include"):
465
+ path = inc.child_by_field_name("path")
466
+ if path is None or path.type != "system_lib_string":
467
+ continue
468
+ header = _txt(path).strip("<>").strip()
469
+ if not header:
470
+ continue
471
+ pkg, sep, rest = header.partition("/")
472
+ if sep:
473
+ _record(uses, pkg, pkg, [rest], "/")
474
+ else:
475
+ uses[0].add(header)
476
+ return uses
477
+
478
+
479
+ def _api_uses_ruby(root: Any) -> ApiUses:
480
+ """``require 'faraday/utils'`` -> faraday: {faraday/utils}; ``gem 'x'`` -> x.
481
+ ``require_relative`` and a path (``./x``) are the project's own files."""
482
+ uses = _empty()
483
+ for call in _descendants(root, "call"):
484
+ if call.child_by_field_name("receiver") is not None:
485
+ continue
486
+ method = call.child_by_field_name("method")
487
+ args = call.child_by_field_name("arguments")
488
+ if method is None or args is None or _txt(method) not in ("require", "gem"):
489
+ continue
490
+ first = next(iter(args.named_children), None)
491
+ if first is None or first.type != "string" or any(
492
+ c.type == "interpolation" for c in first.named_children):
493
+ continue
494
+ feature = "".join(_txt(c) for c in first.named_children if c.type == "string_content")
495
+ if not feature or feature.startswith((".", "/")):
496
+ continue
497
+ pkg = feature.split("/", 1)[0]
498
+ if "/" in feature:
499
+ _record(uses, pkg, pkg, [feature.split("/", 1)[1]], "/")
500
+ else:
501
+ uses[0].add(pkg)
502
+ return uses
503
+
504
+
505
+ def _api_uses_php(root: Any) -> ApiUses:
506
+ """``use A\\B\\C;`` -> A\\B: {C}; ``use A\\B\\{C, D as E};`` -> A\\B: {C, D};
507
+ ``use function A\\b;`` likewise. A trait ``use`` inside a class is no import."""
508
+ uses = _empty()
509
+ for decl in _descendants(root, "namespace_use_declaration"):
510
+ group = decl.child_by_field_name("body")
511
+ base = next((c for c in decl.named_children if c.type == "namespace_name"), None)
512
+ clauses = (group.named_children if group is not None
513
+ else [c for c in decl.named_children if c.type == "namespace_use_clause"])
514
+ for clause in clauses:
515
+ if clause.type != "namespace_use_clause":
516
+ continue
517
+ name = next((c for c in clause.named_children
518
+ if c.type in ("qualified_name", "name")), None)
519
+ if name is None:
520
+ continue
521
+ full = _txt(name).lstrip("\\")
522
+ if base is not None:
523
+ full = _txt(base).strip("\\") + "\\" + full
524
+ _dotted_import(uses, full, False, "\\")
525
+ return uses
526
+
527
+
528
+ def _descendants(root: Any, node_type: str) -> list[Any]:
529
+ """Every node of ``node_type`` under ``root``, iteratively (deep files)."""
530
+ out: list[Any] = []
531
+ stack = [root]
532
+ while stack:
533
+ n = stack.pop()
534
+ if n.type == node_type:
535
+ out.append(n)
536
+ stack.extend(reversed(n.named_children))
537
+ return out
538
+
539
+
540
+ _TS_EXTRACTORS = {
541
+ "javascript": _api_uses_js,
542
+ "typescript": _api_uses_js,
543
+ "tsx": _api_uses_js,
544
+ "jsx": _api_uses_js,
545
+ "go": _api_uses_go,
546
+ "java": _api_uses_java,
547
+ "kotlin": _api_uses_kotlin,
548
+ "scala": _api_uses_scala,
549
+ "csharp": _api_uses_csharp,
550
+ "rust": _api_uses_rust,
551
+ "swift": _api_uses_swift,
552
+ "c": _api_uses_c,
553
+ "cpp": _api_uses_c,
554
+ "objc": _api_uses_c,
555
+ "ruby": _api_uses_ruby,
556
+ "php": _api_uses_php,
557
+ }
558
+
559
+
560
+ def _api_uses_treesitter(src: bytes, rel: str) -> ApiUses:
561
+ parser, lang = _ts_parser_for(rel)
562
+ extractor = _TS_EXTRACTORS.get(str(lang or "").lower())
563
+ if parser is None or extractor is None:
564
+ return _empty()
565
+ try:
566
+ root = parser.parse(src).root_node
567
+ return extractor(root)
568
+ except Exception: # parse failure / grammar drift: degrade to no visibility
569
+ return _empty()
570
+
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # Public entry points
574
+ # ---------------------------------------------------------------------------
575
+
576
+
577
+ def api_uses_for_source(src: bytes | str, rel: str) -> ApiUses:
578
+ """PUBLIC: external-package API uses for one source blob — the stable contract
579
+ for external consumers (importable as ``from graphlore.apis import
580
+ api_uses_for_source``); the underscore-prefixed extractors behind it are
581
+ internal and may be renamed.
582
+
583
+ ``rel`` is the file's (relative) path and only selects the parser — ``.py``
584
+ goes through the stdlib ``ast``, anything else through the optional
585
+ tree-sitter backend (empty result when that backend or the language is
586
+ unavailable). No file IO, no caching, no project-dir confinement: the caller
587
+ owns the source bytes.
588
+
589
+ Returns ``(packages, symbols, paths)``:
590
+ * ``packages``: every absolutely-imported package, even with no visible symbol
591
+ * ``symbols``: package -> short symbol names used (``numpy: {array}``)
592
+ * ``paths``: package -> qualified use paths (``numpy: {numpy.linalg.norm}``)
593
+ All three are lower bounds — see the module docstring for what is invisible.
594
+ """
595
+ data = src if isinstance(src, bytes) else src.encode("utf-8", "replace")
596
+ if str(rel).lower().endswith(".py"):
597
+ return _api_uses_python(data)
598
+ return _api_uses_treesitter(data, str(rel))
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # Per-file entry point
603
+ # ---------------------------------------------------------------------------
604
+
605
+
606
+ def _api_uses_for_file(file_path: str) -> ApiUses:
607
+ """(packages, symbols, paths) for one source file under PROJECT_DIR.
608
+
609
+ Python via stdlib ``ast``; the other languages of ``_TS_EXTRACTORS`` via the
610
+ optional tree-sitter backend when present; empty for other / missing /
611
+ unparseable files (cached
612
+ either way). Confined to PROJECT_DIR like the span index. Cached by
613
+ (path, mtime).
614
+ """
615
+ return _cached_file_analysis(
616
+ _API_CACHE, file_path, api_uses_for_source, _empty, _API_CACHE_MAX
617
+ )