circle-ir-ai 4.42.0 → 4.44.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.
- package/CHANGELOG.md +85 -0
- package/dist/blast-radius/radius.d.ts +1 -1
- package/dist/blast-radius/types.d.ts +1 -1
- package/dist/blast-radius/types.d.ts.map +1 -1
- package/dist/bom/usage.d.ts +2 -0
- package/dist/bom/usage.d.ts.map +1 -1
- package/dist/bom/usage.js +2 -2
- package/dist/bom/usage.js.map +1 -1
- package/dist/change-scope/canonical.d.ts +35 -0
- package/dist/change-scope/canonical.d.ts.map +1 -0
- package/dist/change-scope/canonical.js +84 -0
- package/dist/change-scope/canonical.js.map +1 -0
- package/dist/change-scope/index.d.ts +73 -0
- package/dist/change-scope/index.d.ts.map +1 -0
- package/dist/change-scope/index.js +1503 -0
- package/dist/change-scope/index.js.map +1 -0
- package/dist/change-scope/scope.d.ts +63 -0
- package/dist/change-scope/scope.d.ts.map +1 -0
- package/dist/change-scope/scope.js +725 -0
- package/dist/change-scope/scope.js.map +1 -0
- package/dist/change-scope/side.d.ts +161 -0
- package/dist/change-scope/side.d.ts.map +1 -0
- package/dist/change-scope/side.js +148 -0
- package/dist/change-scope/side.js.map +1 -0
- package/dist/change-scope/slice-rules.d.ts +129 -0
- package/dist/change-scope/slice-rules.d.ts.map +1 -0
- package/dist/change-scope/slice-rules.js +190 -0
- package/dist/change-scope/slice-rules.js.map +1 -0
- package/dist/change-scope/types.d.ts +191 -0
- package/dist/change-scope/types.d.ts.map +1 -0
- package/dist/change-scope/types.js +41 -0
- package/dist/change-scope/types.js.map +1 -0
- package/dist/dead-code/engine.d.ts +8 -0
- package/dist/dead-code/engine.d.ts.map +1 -1
- package/dist/dead-code/engine.js +3 -3
- package/dist/dead-code/engine.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.d.ts +7 -1
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +10 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/tools/change-scope.d.ts +35 -0
- package/dist/mcp/tools/change-scope.d.ts.map +1 -0
- package/dist/mcp/tools/change-scope.js +112 -0
- package/dist/mcp/tools/change-scope.js.map +1 -0
- package/dist/scope/product-paths.d.ts +8 -3
- package/dist/scope/product-paths.d.ts.map +1 -1
- package/dist/scope/product-paths.js +22 -3
- package/dist/scope/product-paths.js.map +1 -1
- package/dist/specifica/evidence-extractor.d.ts +4 -0
- package/dist/specifica/evidence-extractor.d.ts.map +1 -1
- package/dist/specifica/evidence-extractor.js +39 -9
- package/dist/specifica/evidence-extractor.js.map +1 -1
- package/dist/specifica/file-routes.d.ts +10 -3
- package/dist/specifica/file-routes.d.ts.map +1 -1
- package/dist/specifica/file-routes.js +52 -9
- package/dist/specifica/file-routes.js.map +1 -1
- package/dist/specifica/generator.d.ts.map +1 -1
- package/dist/specifica/generator.js +13 -2
- package/dist/specifica/generator.js.map +1 -1
- package/dist/specifica/index.d.ts +1 -1
- package/dist/specifica/index.d.ts.map +1 -1
- package/dist/specifica/index.js +1 -1
- package/dist/specifica/index.js.map +1 -1
- package/dist/specifica/java-erp-entries.d.ts +130 -0
- package/dist/specifica/java-erp-entries.d.ts.map +1 -0
- package/dist/specifica/java-erp-entries.js +867 -0
- package/dist/specifica/java-erp-entries.js.map +1 -0
- package/dist/specifica/learned-tree.d.ts +2 -0
- package/dist/specifica/learned-tree.d.ts.map +1 -1
- package/dist/specifica/learned-tree.js.map +1 -1
- package/dist/specifica/level-design.d.ts +41 -4
- package/dist/specifica/level-design.d.ts.map +1 -1
- package/dist/specifica/level-design.js +847 -24
- package/dist/specifica/level-design.js.map +1 -1
- package/dist/specifica/library-surface-java.d.ts +49 -0
- package/dist/specifica/library-surface-java.d.ts.map +1 -0
- package/dist/specifica/library-surface-java.js +235 -0
- package/dist/specifica/library-surface-java.js.map +1 -0
- package/dist/specifica/library-surface-python-rust.d.ts.map +1 -1
- package/dist/specifica/library-surface-python-rust.js +13 -0
- package/dist/specifica/library-surface-python-rust.js.map +1 -1
- package/dist/specifica/library-surface.d.ts +4 -1
- package/dist/specifica/library-surface.d.ts.map +1 -1
- package/dist/specifica/library-surface.js +5 -2
- package/dist/specifica/library-surface.js.map +1 -1
- package/dist/specifica/modules.d.ts +20 -1
- package/dist/specifica/modules.d.ts.map +1 -1
- package/dist/specifica/modules.js +403 -66
- package/dist/specifica/modules.js.map +1 -1
- package/dist/specifica/provenance.d.ts +6 -2
- package/dist/specifica/provenance.d.ts.map +1 -1
- package/dist/specifica/provenance.js +8 -3
- package/dist/specifica/provenance.js.map +1 -1
- package/dist/specifica/python-entries.d.ts +96 -0
- package/dist/specifica/python-entries.d.ts.map +1 -0
- package/dist/specifica/python-entries.js +475 -0
- package/dist/specifica/python-entries.js.map +1 -0
- package/dist/specifica/python-modules.d.ts +64 -0
- package/dist/specifica/python-modules.d.ts.map +1 -0
- package/dist/specifica/python-modules.js +433 -0
- package/dist/specifica/python-modules.js.map +1 -0
- package/dist/specifica/rule-facts.d.ts +105 -0
- package/dist/specifica/rule-facts.d.ts.map +1 -0
- package/dist/specifica/rule-facts.js +512 -0
- package/dist/specifica/rule-facts.js.map +1 -0
- package/dist/specifica/spec-generator.d.ts +3 -1
- package/dist/specifica/spec-generator.d.ts.map +1 -1
- package/dist/specifica/spec-generator.js +13 -7
- package/dist/specifica/spec-generator.js.map +1 -1
- package/dist/specifica/spec-tree.d.ts +48 -0
- package/dist/specifica/spec-tree.d.ts.map +1 -1
- package/dist/specifica/spec-tree.js +257 -51
- package/dist/specifica/spec-tree.js.map +1 -1
- package/dist/specifica/state-machines.d.ts +85 -0
- package/dist/specifica/state-machines.d.ts.map +1 -0
- package/dist/specifica/state-machines.js +1073 -0
- package/dist/specifica/state-machines.js.map +1 -0
- package/dist/specifica/throw-scopes.d.ts +94 -0
- package/dist/specifica/throw-scopes.d.ts.map +1 -0
- package/dist/specifica/throw-scopes.js +757 -0
- package/dist/specifica/throw-scopes.js.map +1 -0
- package/dist/specifica/tree-types.d.ts +24 -2
- package/dist/specifica/tree-types.d.ts.map +1 -1
- package/dist/specifica/tree-types.js.map +1 -1
- package/dist/specifica/ts-entries.d.ts +137 -0
- package/dist/specifica/ts-entries.d.ts.map +1 -0
- package/dist/specifica/ts-entries.js +616 -0
- package/dist/specifica/ts-entries.js.map +1 -0
- package/dist/specifica/ts-rule-sources.d.ts +51 -6
- package/dist/specifica/ts-rule-sources.d.ts.map +1 -1
- package/dist/specifica/ts-rule-sources.js +499 -38
- package/dist/specifica/ts-rule-sources.js.map +1 -1
- package/dist/specifica/types.d.ts +19 -1
- package/dist/specifica/types.d.ts.map +1 -1
- package/dist/specifica/use-cases.d.ts +36 -6
- package/dist/specifica/use-cases.d.ts.map +1 -1
- package/dist/specifica/use-cases.js +350 -46
- package/dist/specifica/use-cases.js.map +1 -1
- package/dist/specifica/validation-constraints.d.ts +36 -0
- package/dist/specifica/validation-constraints.d.ts.map +1 -0
- package/dist/specifica/validation-constraints.js +184 -0
- package/dist/specifica/validation-constraints.js.map +1 -0
- package/dist/utils/file-skip.d.ts.map +1 -1
- package/dist/utils/file-skip.js +19 -1
- package/dist/utils/file-skip.js.map +1 -1
- package/package.json +3 -2
|
@@ -0,0 +1,1503 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Change scope engine op — `changeScope(baseRoot, headRoot, anchors)`
|
|
3
|
+
* (techspec end-to-end-model plan, task A7, D29, D30 and D32; C4 0.7.1 §15–§16).
|
|
4
|
+
*
|
|
5
|
+
* Reads each checked-out tree into a `Side`, over **git's tracked files**
|
|
6
|
+
* (`git ls-files -s`): symlinks by their link text and gitlinks by their
|
|
7
|
+
* commit, as git stores them; untracked `node_modules` and `dist/` are not in
|
|
8
|
+
* the repository. Bytes are read **as stored**, from the object store
|
|
9
|
+
* (`git cat-file --batch`, no filters), never from the working tree: a
|
|
10
|
+
* changed path is one whose object id or mode differs (review 6147162752 S1,
|
|
11
|
+
* S2). For each side:
|
|
12
|
+
* - circle-ir's graphs (TypeScript and JavaScript, Java, Python, Go), after
|
|
13
|
+
* rewriting tsconfig-path and workspace imports (`blast-radius/import-map.ts`);
|
|
14
|
+
* - each graphed file's imports, resolved to repository paths per language.
|
|
15
|
+
* An import whose name matches a package, module or source directory of
|
|
16
|
+
* the repository must resolve inside it (C4 §16.1 *In-repository names*):
|
|
17
|
+
* a `package.json` `name` or a `workspace:`/`file:`/`link:`/`portal:`
|
|
18
|
+
* dependency, through every conditional target of `exports`, `main` or
|
|
19
|
+
* `#imports` (built `dist/` targets mapped to their source); a Python module
|
|
20
|
+
* or package directory anywhere in the tree; a Java package prefix of a
|
|
21
|
+
* tree package (Java, Kotlin, Scala, Groovy, proto). A bare specifier that is
|
|
22
|
+
* neither a builtin nor declared by a `package.json` from the importing
|
|
23
|
+
* file's package up to its workspace root is `missing` too;
|
|
24
|
+
* - the import forms each graphed file uses that the engine does not follow
|
|
25
|
+
* (C4 §16.1 *Unfollowed forms*), read from circle-ir's parse tree;
|
|
26
|
+
* - stylesheet imports (every string of an `@import` list, `@use`,
|
|
27
|
+
* `@forward`, `@require`, `composes … from`, `url()`), and HTML `src`/`href`;
|
|
28
|
+
* - the app entries: `main` entries, and the modules an HTML file or a
|
|
29
|
+
* `package.json` names;
|
|
30
|
+
* - the build and tool configuration over each file (`BUILD_CONFIG`);
|
|
31
|
+
* - each declaration's stored bytes from its first decorator, comments included
|
|
32
|
+
* (a Java declaration from its syntax node, a Go one from its directives);
|
|
33
|
+
* - each symlink resolved hop by hop against the tracked listing.
|
|
34
|
+
* `scope.ts` computes the answer over the two sides.
|
|
35
|
+
*
|
|
36
|
+
* 0.1 reuses only self-contained reads (plan D32): closure and route anchors
|
|
37
|
+
* always re-run, and tests are advisory. D30's closure-reuse rules run only
|
|
38
|
+
* with `closureReuse`, or `CIRCLE_IR_AI_CHANGE_SCOPE_CLOSURE_REUSE=1`: off by
|
|
39
|
+
* default, experimental for 0.2.
|
|
40
|
+
*
|
|
41
|
+
* Deterministic, model-free and read-only: git runs with its fsmonitor, hooks
|
|
42
|
+
* and optional locks off, every transport denied and lazy fetch off, and with
|
|
43
|
+
* no `GIT_*` variable inherited, so a checkout's own config cannot run a
|
|
44
|
+
* command (review 6146528338 S3) and a partial clone's missing blob is not
|
|
45
|
+
* fetched. Nothing
|
|
46
|
+
* calls it unless asked (the MCP tool is registered only behind
|
|
47
|
+
* `CIRCLE_IR_AI_CHANGE_SCOPE=1`).
|
|
48
|
+
* Where Illata replaces this (task A1, blocked; A9): the sides load from the
|
|
49
|
+
* stored snapshots by digest instead.
|
|
50
|
+
*/
|
|
51
|
+
import { execFileSync, spawn } from 'child_process';
|
|
52
|
+
import { blake3 } from '@noble/hashes/blake3.js';
|
|
53
|
+
import { bytesToHex } from '@noble/hashes/utils.js';
|
|
54
|
+
import * as fs from 'fs';
|
|
55
|
+
import * as path from 'path';
|
|
56
|
+
import { builtinModules } from 'module';
|
|
57
|
+
import { minimatch } from 'minimatch';
|
|
58
|
+
import { buildGoGraph, buildJavaGraph, buildPythonGraph, buildTsCallGraph, extractImports, parse } from 'circle-ir';
|
|
59
|
+
import { EXT_LANG } from '../bom/usage.js';
|
|
60
|
+
import { consoleScripts, goModulePath, manifests as packageManifests } from '../dead-code/engine.js';
|
|
61
|
+
import { FileResolver, importMapIsEmpty, loadImportMap, parseJsonc, resolveSpecifier, rewriteImports } from '../blast-radius/import-map.js';
|
|
62
|
+
import { productScope } from '../scope/product-paths.js';
|
|
63
|
+
import { blake3Hex, byCodePoints } from './canonical.js';
|
|
64
|
+
import { checkAnchors, scopeOf } from './scope.js';
|
|
65
|
+
import { BUILD_CONFIG, CONFIG_FILES, CONVENTIONS, HTML, MAX_GRAPH_BYTES, MAX_LINK_HOPS, MAX_PARSE_BYTES, SKIPPED_ROOT_DIRS, STYLES, UNSUPPORTED } from './slice-rules.js';
|
|
66
|
+
export * from './types.js';
|
|
67
|
+
export { jcs, anchorDigest, blake3Of } from './canonical.js';
|
|
68
|
+
export { checkAnchors, scopeOf, MAX_ANCHORS } from './scope.js';
|
|
69
|
+
export { BUILD_CONFIG, FULLY_RESOLVED, SLICE_RULES } from './slice-rules.js';
|
|
70
|
+
const FAMILIES = ['typescript', 'java', 'python', 'go'];
|
|
71
|
+
const FAMILY_OF_LANG = {
|
|
72
|
+
typescript: 'typescript', tsx: 'typescript', javascript: 'typescript', java: 'java', python: 'python', go: 'go',
|
|
73
|
+
};
|
|
74
|
+
const CODE_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
|
|
75
|
+
const VENV_DIRS = new Set(['venv', '.venv', 'env', 'site-packages', 'node_modules', '__pycache__', '.tox', '.nox']);
|
|
76
|
+
const JVM_SOURCE = new Set(['.kt', '.kts', '.scala', '.groovy']);
|
|
77
|
+
const SPRING_SCAN = /^(SpringBootApplication|ComponentScan|EnableAutoConfiguration|SpringBootTest|WebMvcTest|WebFluxTest|DataJpaTest|JdbcTest|DataMongoTest)$/;
|
|
78
|
+
const SPRING_APP = /^(SpringBootApplication|ComponentScan|EnableAutoConfiguration)$/;
|
|
79
|
+
const DOTTED = /^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/;
|
|
80
|
+
/**
|
|
81
|
+
* Class members tree-sitter's TypeScript and JavaScript grammars misread when a line break follows them: `static`,
|
|
82
|
+
* `get` and `set` are modifiers across a line break (tsc), but the grammars read a field of that name, which takes the
|
|
83
|
+
* decorators, and a plain member on the next line (`@D() static` / `split() {}`). `async` and `accessor` may not be
|
|
84
|
+
* followed by a line break, so a field is right for them.
|
|
85
|
+
*/
|
|
86
|
+
const LINE_BREAK_MODIFIERS = new Set(['static', 'get', 'set']);
|
|
87
|
+
/**
|
|
88
|
+
* Java declaration nodes by the kind of circle-ir declaration they hold: each starts at its modifiers, annotations
|
|
89
|
+
* included. A record's components (`formal_parameter`) are fields too.
|
|
90
|
+
*/
|
|
91
|
+
const JAVA_DECL_KIND = {
|
|
92
|
+
field_declaration: 'field', constant_declaration: 'field', enum_constant: 'field',
|
|
93
|
+
method_declaration: 'method', constructor_declaration: 'method', compact_constructor_declaration: 'method', annotation_type_element_declaration: 'method',
|
|
94
|
+
class_declaration: 'type', interface_declaration: 'type', enum_declaration: 'type', record_declaration: 'type', annotation_type_declaration: 'type',
|
|
95
|
+
};
|
|
96
|
+
/** Modules Django loads from each installed app by convention. */
|
|
97
|
+
const DJANGO_APP_MODULES = ['models.py', 'models/**', 'signals.py', 'signals/**', 'admin.py', 'admin/**', 'apps.py', 'middleware.py', 'middleware/**', 'templatetags/**', 'management/**', 'urls.py', 'context_processors.py', 'receivers.py', 'checks.py', 'tasks.py', 'migrations/**'];
|
|
98
|
+
/** The walk's bound: past it every anchor is incomplete. `maxDepth` bounds the tsconfig search only. */
|
|
99
|
+
export const CHANGE_SCOPE_WALK = { maxFiles: 200_000, maxDepth: 32 };
|
|
100
|
+
export const CHANGE_SCOPE_CLOSURE_REUSE_FLAG = 'CIRCLE_IR_AI_CHANGE_SCOPE_CLOSURE_REUSE';
|
|
101
|
+
/** Whether the experimental closure reuse is on: the flag set to `1` or `true`. */
|
|
102
|
+
export function closureReuseEnabled(env = process.env) {
|
|
103
|
+
return env[CHANGE_SCOPE_CLOSURE_REUSE_FLAG] === '1' || env[CHANGE_SCOPE_CLOSURE_REUSE_FLAG] === 'true';
|
|
104
|
+
}
|
|
105
|
+
/** git's arguments and environment for a read that a checkout's own config cannot turn into a command (S3). */
|
|
106
|
+
const GIT_SAFE = [
|
|
107
|
+
'-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false',
|
|
108
|
+
// No transport at all: a partial clone's lazy fetch would run the remote's command (`ext::`, `core.sshCommand`).
|
|
109
|
+
...['allow', 'ext.allow', 'file.allow', 'ssh.allow', 'git.allow', 'http.allow', 'https.allow'].flatMap((k) => ['-c', `protocol.${k}=never`]),
|
|
110
|
+
'--no-pager', '--no-optional-locks',
|
|
111
|
+
];
|
|
112
|
+
function gitEnv() {
|
|
113
|
+
const env = {};
|
|
114
|
+
for (const [k, v] of Object.entries(process.env))
|
|
115
|
+
if (!k.startsWith('GIT_'))
|
|
116
|
+
env[k] = v;
|
|
117
|
+
// A partial clone's missing blob is not fetched: it is a path the walk cannot read.
|
|
118
|
+
return { ...env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_PAGER: 'cat', GIT_NO_LAZY_FETCH: '1' };
|
|
119
|
+
}
|
|
120
|
+
/** Extensions whose stored bytes are kept for parsing when small enough: code, and the text the reader parses (manifests, config, HTML). */
|
|
121
|
+
const KEPT_TEXT = new Set(['.json', '.jsonc', '.json5', '.html', '.htm', '.yaml', '.yml', '.toml', '.xml', '.txt', '.cfg', '.ini', '.mod', '.properties']);
|
|
122
|
+
/**
|
|
123
|
+
* Git's tracked files under `root` (C4 0.7.1 §16 *The walk*), sorted by path, read as stored (S1): the index's
|
|
124
|
+
* modes and object ids, and every blob's bytes from the object store through one `git cat-file --batch`, never
|
|
125
|
+
* `--filters`, so no checkout conversion, clean filter or `textconv` applies and nothing in the checkout runs.
|
|
126
|
+
* The working tree is not read. A blob the object store does not have cuts the walk.
|
|
127
|
+
*/
|
|
128
|
+
async function listTracked(root, maxFiles) {
|
|
129
|
+
let out;
|
|
130
|
+
try {
|
|
131
|
+
out = execFileSync('git', [...GIT_SAFE, '-C', root, 'ls-files', '-s', '-z'], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'], env: gitEnv() });
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
throw new Error(`not a git checkout, or git cannot list it: ${root} (the change scope walks git's tracked files, C4 0.7.1 §16)`);
|
|
135
|
+
}
|
|
136
|
+
const entries = [];
|
|
137
|
+
const seen = new Set();
|
|
138
|
+
let cut = false;
|
|
139
|
+
for (const entry of out.split('\0')) {
|
|
140
|
+
const tab = entry.indexOf('\t');
|
|
141
|
+
if (tab < 0)
|
|
142
|
+
continue;
|
|
143
|
+
const [mode = '', sha = ''] = entry.slice(0, tab).split(' ');
|
|
144
|
+
const rel = entry.slice(tab + 1);
|
|
145
|
+
if (seen.has(rel))
|
|
146
|
+
continue; // a conflict's stages
|
|
147
|
+
seen.add(rel);
|
|
148
|
+
if (entries.length >= maxFiles) {
|
|
149
|
+
cut = true;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
entries.push({ rel, mode, sha });
|
|
153
|
+
}
|
|
154
|
+
const keep = new Set();
|
|
155
|
+
for (const e of entries)
|
|
156
|
+
if (e.mode === '120000' || familyOf(e.rel) || KEPT_TEXT.has(extOf(e.rel)) || UNSUPPORTED.has(extOf(e.rel)))
|
|
157
|
+
keep.add(e.sha);
|
|
158
|
+
const blobs = await readBlobs(root, [...new Set(entries.filter((e) => e.mode !== '160000').map((e) => e.sha))], keep);
|
|
159
|
+
const files = [];
|
|
160
|
+
for (const e of entries) {
|
|
161
|
+
if (e.mode === '160000') {
|
|
162
|
+
files.push({ ...e, size: 0, hash: blake3Hex(e.sha), link: null, gitlink: e.sha });
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
const b = blobs.get(e.sha);
|
|
166
|
+
if (!b || (e.mode === '120000' && !b.bytes)) {
|
|
167
|
+
cut = true;
|
|
168
|
+
continue;
|
|
169
|
+
} // tracked, but its stored bytes cannot be read
|
|
170
|
+
files.push({ ...e, size: b.size, hash: b.hash, link: e.mode === '120000' ? b.bytes.toString('utf8') : null, gitlink: null });
|
|
171
|
+
}
|
|
172
|
+
files.sort((a, b) => byCodePoints(a.rel, b.rel));
|
|
173
|
+
const kept = new Map();
|
|
174
|
+
for (const [sha, b] of blobs)
|
|
175
|
+
if (b.bytes)
|
|
176
|
+
kept.set(sha, b.bytes);
|
|
177
|
+
return { files, cut, kept };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Blobs by object id from `git cat-file --batch` (raw stored bytes): each one's size and blake3, with the bytes
|
|
181
|
+
* kept for the ids in `keep` up to `MAX_PARSE_BYTES`. An id the object store does not have is left out, and so is
|
|
182
|
+
* every id after it when git stops there.
|
|
183
|
+
*/
|
|
184
|
+
async function readBlobs(root, ids, keep) {
|
|
185
|
+
const out = new Map();
|
|
186
|
+
if (ids.length === 0)
|
|
187
|
+
return out;
|
|
188
|
+
const child = spawn('git', [...GIT_SAFE, '-C', root, 'cat-file', '--batch'], { env: gitEnv(), stdio: ['pipe', 'pipe', 'ignore'] });
|
|
189
|
+
let header = '';
|
|
190
|
+
let cur = null;
|
|
191
|
+
child.stdout.on('data', (chunk) => {
|
|
192
|
+
let off = 0;
|
|
193
|
+
while (off < chunk.length) {
|
|
194
|
+
if (!cur) {
|
|
195
|
+
const nl = chunk.indexOf(10, off);
|
|
196
|
+
if (nl < 0) {
|
|
197
|
+
header += chunk.toString('latin1', off);
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
const line = header + chunk.toString('latin1', off, nl);
|
|
201
|
+
header = '';
|
|
202
|
+
off = nl + 1;
|
|
203
|
+
const m = /^([0-9a-f]+) (\w+) (\d+)$/.exec(line);
|
|
204
|
+
if (!m)
|
|
205
|
+
continue; // `<id> missing`: not in the object store
|
|
206
|
+
const size = Number(m[3]);
|
|
207
|
+
cur = { sha: m[1], size, left: size + 1, blob: m[2] === 'blob', h: blake3.create(), parts: keep.has(m[1]) && size <= MAX_PARSE_BYTES ? [] : null };
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const take = Math.min(cur.left, chunk.length - off);
|
|
211
|
+
const content = chunk.subarray(off, off + Math.min(take, cur.left - 1));
|
|
212
|
+
if (content.length > 0) {
|
|
213
|
+
cur.h.update(content);
|
|
214
|
+
cur.parts?.push(Buffer.from(content));
|
|
215
|
+
}
|
|
216
|
+
cur.left -= take;
|
|
217
|
+
off += take;
|
|
218
|
+
if (cur.left === 0) {
|
|
219
|
+
if (cur.blob)
|
|
220
|
+
out.set(cur.sha, { size: cur.size, hash: bytesToHex(cur.h.digest()), bytes: cur.parts ? Buffer.concat(cur.parts) : null });
|
|
221
|
+
cur = null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
const done = new Promise((resolve, reject) => { child.on('error', reject); child.on('close', resolve); });
|
|
226
|
+
child.stdin.on('error', () => { });
|
|
227
|
+
child.stdin.end(`${ids.join('\n')}\n`);
|
|
228
|
+
// A blob git cannot give (a partial clone's, with lazy fetch off, ends the batch) is left out: the walk is cut.
|
|
229
|
+
await done;
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
/** A blob's stored bytes, read alone (`git cat-file blob`, raw): for a path whose bytes the batch did not keep. */
|
|
233
|
+
function readBlob(root, sha) {
|
|
234
|
+
try {
|
|
235
|
+
return execFileSync('git', [...GIT_SAFE, '-C', root, 'cat-file', 'blob', sha], { maxBuffer: MAX_PARSE_BYTES + 1, stdio: ['ignore', 'pipe', 'ignore'], env: gitEnv() });
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const extOf = (rel) => path.extname(rel).toLowerCase();
|
|
242
|
+
const familyOf = (rel) => FAMILY_OF_LANG[EXT_LANG[extOf(rel)] ?? ''];
|
|
243
|
+
const dirOf = (rel) => { const d = path.posix.dirname(rel); return d === '.' ? '' : d; };
|
|
244
|
+
const joinIn = (dir, p) => path.posix.normalize(dir ? `${dir}/${p}` : p);
|
|
245
|
+
function kindOf(f) {
|
|
246
|
+
if (f.gitlink !== null)
|
|
247
|
+
return 'gitlink';
|
|
248
|
+
if (f.link !== null)
|
|
249
|
+
return 'symlink';
|
|
250
|
+
if (familyOf(f.rel))
|
|
251
|
+
return 'code';
|
|
252
|
+
const ext = extOf(f.rel);
|
|
253
|
+
return UNSUPPORTED.has(ext) || EXT_LANG[ext] ? 'unsupported' : 'non_code';
|
|
254
|
+
}
|
|
255
|
+
/** Resolves code paths against git's tracked files only (never an untracked `dist/`), `.d.ts` last (S7). */
|
|
256
|
+
class TrackedResolver extends FileResolver {
|
|
257
|
+
tracked;
|
|
258
|
+
constructor(root, tracked) {
|
|
259
|
+
super(root);
|
|
260
|
+
this.tracked = tracked;
|
|
261
|
+
}
|
|
262
|
+
resolve(candidate) {
|
|
263
|
+
const rel = path.posix.normalize(candidate);
|
|
264
|
+
if (rel.startsWith('..') || rel.split('/').includes('node_modules'))
|
|
265
|
+
return null;
|
|
266
|
+
const stems = [rel];
|
|
267
|
+
const js = /^(.*)\.(?:m|c)?jsx?$/.exec(rel);
|
|
268
|
+
if (js)
|
|
269
|
+
stems.push(js[1]);
|
|
270
|
+
for (const stem of stems) {
|
|
271
|
+
if (/\.[cm]?[jt]sx?$/.test(stem) && this.tracked(stem))
|
|
272
|
+
return stem;
|
|
273
|
+
const ext = CODE_EXT.find((x) => this.tracked(stem + x));
|
|
274
|
+
if (ext)
|
|
275
|
+
return stem + ext;
|
|
276
|
+
const index = CODE_EXT.find((x) => this.tracked(`${stem}/index${x}`));
|
|
277
|
+
if (index)
|
|
278
|
+
return `${stem}/index${index}`;
|
|
279
|
+
}
|
|
280
|
+
for (const stem of stems) {
|
|
281
|
+
if (this.tracked(`${stem}.d.ts`))
|
|
282
|
+
return `${stem}.d.ts`;
|
|
283
|
+
if (this.tracked(`${stem}/index.d.ts`))
|
|
284
|
+
return `${stem}/index.d.ts`;
|
|
285
|
+
}
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
async function buildGraph(family, root, sources) {
|
|
290
|
+
switch (family) {
|
|
291
|
+
case 'java': return buildJavaGraph(sources);
|
|
292
|
+
case 'python': return buildPythonGraph(sources, { consoleScripts: consoleScripts(root) });
|
|
293
|
+
case 'go': {
|
|
294
|
+
const modulePath = goModulePath(root);
|
|
295
|
+
return buildGoGraph(sources, modulePath ? { modulePath } : {});
|
|
296
|
+
}
|
|
297
|
+
default: return buildTsCallGraph(sources, { packages: packageManifests(root, sources) });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Every string target of a `package.json` `exports` / `imports` value, every condition (X2). */
|
|
301
|
+
function allTargets(v) {
|
|
302
|
+
if (typeof v === 'string')
|
|
303
|
+
return [v];
|
|
304
|
+
if (Array.isArray(v))
|
|
305
|
+
return v.flatMap(allTargets);
|
|
306
|
+
if (v && typeof v === 'object')
|
|
307
|
+
return Object.values(v).flatMap(allTargets);
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
/** The targets of `key` in an `exports` or `imports` map: the exact key, else every pattern that matches it. */
|
|
311
|
+
function matchMap(map, key) {
|
|
312
|
+
if (key in map)
|
|
313
|
+
return allTargets(map[key]);
|
|
314
|
+
const out = [];
|
|
315
|
+
for (const [k, v] of Object.entries(map)) {
|
|
316
|
+
const star = k.indexOf('*');
|
|
317
|
+
if (star < 0)
|
|
318
|
+
continue;
|
|
319
|
+
const pre = k.slice(0, star);
|
|
320
|
+
const post = k.slice(star + 1);
|
|
321
|
+
if (key.length >= pre.length + post.length && key.startsWith(pre) && key.endsWith(post)) {
|
|
322
|
+
const s = key.slice(pre.length, key.length - post.length);
|
|
323
|
+
out.push(...allTargets(v).map((t) => t.split('*').join(s)));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return out;
|
|
327
|
+
}
|
|
328
|
+
function* walkSyn(root) {
|
|
329
|
+
const stack = [root];
|
|
330
|
+
while (stack.length > 0) {
|
|
331
|
+
const n = stack.pop();
|
|
332
|
+
yield n;
|
|
333
|
+
const kids = n.namedChildren;
|
|
334
|
+
for (let i = kids.length - 1; i >= 0; i--)
|
|
335
|
+
stack.push(kids[i]);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/** A TS/JS string or substitution-free template literal's value. */
|
|
339
|
+
function tsLiteral(n) {
|
|
340
|
+
if (!n)
|
|
341
|
+
return null;
|
|
342
|
+
if (n.type === 'string')
|
|
343
|
+
return n.text.slice(1, -1);
|
|
344
|
+
if (n.type === 'template_string' && !n.namedChildren.some((c) => c.type === 'template_substitution'))
|
|
345
|
+
return n.text.slice(1, -1);
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
/** A Python string's value, unless it interpolates. */
|
|
349
|
+
function pyLiteral(n) {
|
|
350
|
+
if (n.type !== 'string' || n.namedChildren.some((c) => c.type === 'interpolation'))
|
|
351
|
+
return null;
|
|
352
|
+
const m = /^[rRbBuU]{0,2}("""|'''|"|')([\s\S]*)\1$/.exec(n.text);
|
|
353
|
+
return m ? m[2] : null;
|
|
354
|
+
}
|
|
355
|
+
const firstArg = (call) => call.childForFieldName('arguments')?.namedChildren.filter((c) => c.type !== 'comment')[0];
|
|
356
|
+
async function sideOf(name, rootIn, maxFiles, maxDepth, failures) {
|
|
357
|
+
const root = path.resolve(rootIn);
|
|
358
|
+
const { files, cut, kept } = await listTracked(root, maxFiles);
|
|
359
|
+
const byRel = new Map(files.map((f) => [f.rel, f]));
|
|
360
|
+
const has = (rel) => byRel.has(rel);
|
|
361
|
+
const kind = new Map(files.map((f) => [f.rel, kindOf(f)]));
|
|
362
|
+
const skippedDir = (rel) => {
|
|
363
|
+
const segs = rel.split('/');
|
|
364
|
+
return segs.slice(0, -1).includes('node_modules') || (segs.length > 1 && (SKIPPED_ROOT_DIRS.has(segs[0]) || segs[0].startsWith('.')));
|
|
365
|
+
};
|
|
366
|
+
const graphed = new Set(files.filter((f) => kind.get(f.rel) === 'code' && !skippedDir(f.rel) && f.size <= MAX_GRAPH_BYTES).map((f) => f.rel));
|
|
367
|
+
const dirs = new Set();
|
|
368
|
+
for (const f of files)
|
|
369
|
+
for (let d = dirOf(f.rel); d !== '' && !dirs.has(d); d = dirOf(d))
|
|
370
|
+
dirs.add(d);
|
|
371
|
+
const under = (dir) => files.filter((f) => f.rel.startsWith(`${dir}/`)).map((f) => f.rel);
|
|
372
|
+
// Stored bytes (S1): what the batch kept, else the blob read alone.
|
|
373
|
+
const raw = new Map();
|
|
374
|
+
const rawOf = (rel) => {
|
|
375
|
+
if (raw.has(rel))
|
|
376
|
+
return raw.get(rel);
|
|
377
|
+
const f = byRel.get(rel);
|
|
378
|
+
const b = f && f.link === null && f.gitlink === null && f.size <= MAX_PARSE_BYTES ? (kept.get(f.sha) ?? readBlob(root, f.sha)) : null;
|
|
379
|
+
raw.set(rel, b);
|
|
380
|
+
return b;
|
|
381
|
+
};
|
|
382
|
+
const text = new Map();
|
|
383
|
+
const read = (rel) => {
|
|
384
|
+
if (text.has(rel))
|
|
385
|
+
return text.get(rel);
|
|
386
|
+
const t = rawOf(rel)?.toString('utf8') ?? null;
|
|
387
|
+
text.set(rel, t);
|
|
388
|
+
return t;
|
|
389
|
+
};
|
|
390
|
+
const tracked = new TrackedResolver(root, has);
|
|
391
|
+
const fileOrCode = (cand) => (has(cand) ? cand : tracked.resolve(cand));
|
|
392
|
+
// Graphs, with TypeScript's mapped imports rewritten.
|
|
393
|
+
const map = loadImportMap(root, maxDepth);
|
|
394
|
+
const byFamily = new Map();
|
|
395
|
+
/** The text a graph was built on, where it is not the stored text: declarations' positions are in it (F2). */
|
|
396
|
+
const graphText = new Map();
|
|
397
|
+
for (const rel of graphed) {
|
|
398
|
+
const family = familyOf(rel);
|
|
399
|
+
let code = read(rel) ?? '';
|
|
400
|
+
if (family === 'typescript' && !importMapIsEmpty(map)) {
|
|
401
|
+
const rewritten = rewriteImports(rel, code, map, tracked).code;
|
|
402
|
+
if (rewritten !== code)
|
|
403
|
+
graphText.set(rel, rewritten);
|
|
404
|
+
code = rewritten;
|
|
405
|
+
}
|
|
406
|
+
(byFamily.get(family) ?? byFamily.set(family, []).get(family)).push({ path: rel, code });
|
|
407
|
+
}
|
|
408
|
+
const graphs = [];
|
|
409
|
+
const partial = new Set();
|
|
410
|
+
for (const family of FAMILIES) {
|
|
411
|
+
const sources = byFamily.get(family);
|
|
412
|
+
if (!sources)
|
|
413
|
+
continue;
|
|
414
|
+
try {
|
|
415
|
+
const g = await buildGraph(family, root, sources);
|
|
416
|
+
graphs.push(g);
|
|
417
|
+
for (const p of g.partial)
|
|
418
|
+
partial.add(p);
|
|
419
|
+
}
|
|
420
|
+
catch (err) {
|
|
421
|
+
failures.push({ reason: 'graph_failed', side: name, detail: `the ${family} graph could not be built (${err.message})` });
|
|
422
|
+
for (const s of sources)
|
|
423
|
+
partial.add(s.path);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
// JavaScript packages: manifests, repository package names, local dependencies, workspace roots, committed node_modules.
|
|
427
|
+
const pkgJson = new Map();
|
|
428
|
+
for (const f of files) {
|
|
429
|
+
if (path.posix.basename(f.rel) !== 'package.json' || f.rel.split('/').includes('node_modules'))
|
|
430
|
+
continue;
|
|
431
|
+
try {
|
|
432
|
+
pkgJson.set(dirOf(f.rel), parseJsonc(read(f.rel) ?? ''));
|
|
433
|
+
}
|
|
434
|
+
catch { /* unreadable */ }
|
|
435
|
+
}
|
|
436
|
+
const DEP_KINDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
|
|
437
|
+
const repoPackages = new Map();
|
|
438
|
+
const localDeps = new Map();
|
|
439
|
+
for (const [d, pj] of pkgJson) {
|
|
440
|
+
if (typeof pj.name === 'string')
|
|
441
|
+
(repoPackages.get(pj.name) ?? repoPackages.set(pj.name, []).get(pj.name)).push(d);
|
|
442
|
+
for (const k of DEP_KINDS) {
|
|
443
|
+
const deps = pj[k];
|
|
444
|
+
if (!deps || typeof deps !== 'object')
|
|
445
|
+
continue;
|
|
446
|
+
for (const [dep, ver] of Object.entries(deps)) {
|
|
447
|
+
if (typeof ver !== 'string' || !/^(file|link|portal):/.test(ver))
|
|
448
|
+
continue;
|
|
449
|
+
const target = joinIn(d, ver.replace(/^\w+:/, ''));
|
|
450
|
+
if (!target.startsWith('..'))
|
|
451
|
+
(localDeps.get(d) ?? localDeps.set(d, new Map()).get(d)).set(dep, target);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const workspaceRoots = new Set(files.filter((f) => path.posix.basename(f.rel) === 'pnpm-workspace.yaml').map((f) => dirOf(f.rel)));
|
|
456
|
+
for (const [d, pj] of pkgJson)
|
|
457
|
+
if (pj.workspaces)
|
|
458
|
+
workspaceRoots.add(d);
|
|
459
|
+
const upChain = (dir) => {
|
|
460
|
+
const out = [];
|
|
461
|
+
for (let d = dir;; d = dirOf(d)) {
|
|
462
|
+
out.push(d);
|
|
463
|
+
if (d === '' || workspaceRoots.has(d))
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
return out;
|
|
467
|
+
};
|
|
468
|
+
const declaredMemo = new Map();
|
|
469
|
+
const declaredAt = (dir) => {
|
|
470
|
+
const hit = declaredMemo.get(dir);
|
|
471
|
+
if (hit)
|
|
472
|
+
return hit;
|
|
473
|
+
const out = new Set();
|
|
474
|
+
for (const d of upChain(dir)) {
|
|
475
|
+
const pj = pkgJson.get(d);
|
|
476
|
+
if (!pj)
|
|
477
|
+
continue;
|
|
478
|
+
if (typeof pj.name === 'string')
|
|
479
|
+
out.add(pj.name);
|
|
480
|
+
for (const k of DEP_KINDS) {
|
|
481
|
+
const deps = pj[k];
|
|
482
|
+
if (deps && typeof deps === 'object')
|
|
483
|
+
for (const dep of Object.keys(deps))
|
|
484
|
+
out.add(dep);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
declaredMemo.set(dir, out);
|
|
488
|
+
return out;
|
|
489
|
+
};
|
|
490
|
+
const localDepAt = (dir, dep) => {
|
|
491
|
+
for (const d of upChain(dir)) {
|
|
492
|
+
const t = localDeps.get(d)?.get(dep);
|
|
493
|
+
if (t !== undefined)
|
|
494
|
+
return t;
|
|
495
|
+
}
|
|
496
|
+
return null;
|
|
497
|
+
};
|
|
498
|
+
const committed = new Set();
|
|
499
|
+
for (const f of files) {
|
|
500
|
+
const segs = f.rel.split('/');
|
|
501
|
+
for (let i = segs.indexOf('node_modules'); i >= 0 && i < segs.length - 1; i = segs.indexOf('node_modules', i + 1)) {
|
|
502
|
+
const pkg = segs[i + 1].startsWith('@') ? segs.slice(i + 1, i + 3).join('/') : segs[i + 1];
|
|
503
|
+
committed.add([...segs.slice(0, i), 'node_modules', pkg].join('/'));
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const committedAt = (dir, pkg) => {
|
|
507
|
+
for (let d = dir;; d = dirOf(d)) {
|
|
508
|
+
if (committed.has(joinIn(d, `node_modules/${pkg}`)))
|
|
509
|
+
return true;
|
|
510
|
+
if (d === '')
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
const builtins = new Set(builtinModules);
|
|
515
|
+
const pkgOf = (spec) => (spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0]);
|
|
516
|
+
const typesOf = (pkg) => `@types/${pkg.startsWith('@') ? pkg.slice(1).replace('/', '__') : pkg}`;
|
|
517
|
+
const asFile = (spec, p) => (p ? { specifier: spec, path: p, kind: 'file' } : { specifier: spec, path: null, kind: 'missing' });
|
|
518
|
+
const external = (spec) => ({ specifier: spec, path: null, kind: 'package' });
|
|
519
|
+
/** A target inside package `dir`: the file, else its source when it points at built output (`dist/` → `src/`). */
|
|
520
|
+
const BUILT = /(^|\/)(?:dist|build|lib|out)(?:\/(?:esm|cjs|es|mjs|types|module|commonjs|node|browser))?\//;
|
|
521
|
+
const inPackage = (dir, target) => {
|
|
522
|
+
const p = joinIn(dir, target);
|
|
523
|
+
if (p.startsWith('..'))
|
|
524
|
+
return null;
|
|
525
|
+
const hit = fileOrCode(p);
|
|
526
|
+
if (hit)
|
|
527
|
+
return hit;
|
|
528
|
+
const within = dir ? p.slice(dir.length + 1) : p;
|
|
529
|
+
if (!BUILT.test(within))
|
|
530
|
+
return null;
|
|
531
|
+
return tracked.resolve(joinIn(dir, within.replace(BUILT, '$1src/').replace(/\.d\.[cm]?ts$|\.[cm]?jsx?$/, '')));
|
|
532
|
+
};
|
|
533
|
+
const packageTargets = (pj, sub) => {
|
|
534
|
+
const exp = pj.exports;
|
|
535
|
+
if (exp !== undefined && exp !== null) {
|
|
536
|
+
const keyed = typeof exp === 'object' && !Array.isArray(exp) && Object.keys(exp).some((k) => k.startsWith('.'));
|
|
537
|
+
return matchMap(keyed ? exp : { '.': exp }, sub ? `./${sub}` : '.').filter((t) => t.startsWith('./'));
|
|
538
|
+
}
|
|
539
|
+
if (sub)
|
|
540
|
+
return [sub];
|
|
541
|
+
const mains = [pj.source, pj.module, pj.main, typeof pj.browser === 'string' ? pj.browser : undefined, pj.types, pj.typings].filter((x) => typeof x === 'string');
|
|
542
|
+
return mains.length > 0 ? mains : ['index'];
|
|
543
|
+
};
|
|
544
|
+
/** An in-repository package (X1): every target resolves inside the repository, or the import is `missing`. */
|
|
545
|
+
const resolvePackage = (raw, dir, sub) => {
|
|
546
|
+
const pj = pkgJson.get(dir);
|
|
547
|
+
const targets = pj ? packageTargets(pj, sub) : [sub || 'index'];
|
|
548
|
+
if (targets.length === 0)
|
|
549
|
+
return [asFile(raw, null)];
|
|
550
|
+
return targets.map((t) => asFile(raw, inPackage(dir, t)));
|
|
551
|
+
};
|
|
552
|
+
const hashImport = (rel, raw, spec) => {
|
|
553
|
+
for (let d = dirOf(rel);; d = dirOf(d)) {
|
|
554
|
+
const imports = pkgJson.get(d)?.imports;
|
|
555
|
+
if (imports && typeof imports === 'object') {
|
|
556
|
+
const targets = matchMap(imports, spec);
|
|
557
|
+
if (targets.length === 0)
|
|
558
|
+
return [asFile(raw, null)];
|
|
559
|
+
return targets.flatMap((t) => (t.startsWith('./') ? [asFile(raw, inPackage(d, t))] : resolveTs(rel, t)));
|
|
560
|
+
}
|
|
561
|
+
if (d === '')
|
|
562
|
+
return [asFile(raw, null)];
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
function resolveTs(rel, raw) {
|
|
566
|
+
// A query or fragment (`./x.svg?raw`) is not part of the path; a `#imports` specifier starts with one.
|
|
567
|
+
const spec = raw.startsWith('#') ? raw.split('?')[0] : raw.split(/[?#]/)[0];
|
|
568
|
+
if (!spec)
|
|
569
|
+
return [asFile(raw, null)];
|
|
570
|
+
if (spec.startsWith('.') || spec.startsWith('/')) {
|
|
571
|
+
const joined = path.posix.normalize(spec.startsWith('/') ? spec.slice(1) : joinIn(dirOf(rel), spec));
|
|
572
|
+
return [asFile(raw, joined.startsWith('..') ? null : fileOrCode(joined))];
|
|
573
|
+
}
|
|
574
|
+
if (spec.startsWith('#'))
|
|
575
|
+
return hashImport(rel, raw, spec);
|
|
576
|
+
if (spec.startsWith('node:') || builtins.has(spec) || builtins.has(pkgOf(spec)))
|
|
577
|
+
return [external(raw)];
|
|
578
|
+
const pkg = pkgOf(spec);
|
|
579
|
+
const sub = spec.slice(pkg.length + 1);
|
|
580
|
+
const local = localDepAt(dirOf(rel), pkg);
|
|
581
|
+
if (local !== null)
|
|
582
|
+
return resolvePackage(raw, local, sub);
|
|
583
|
+
const inRepo = repoPackages.get(pkg);
|
|
584
|
+
if (inRepo)
|
|
585
|
+
return inRepo.flatMap((d) => resolvePackage(raw, d, sub));
|
|
586
|
+
const mapped = resolveSpecifier(rel, spec, map, tracked);
|
|
587
|
+
if (mapped)
|
|
588
|
+
return [asFile(raw, mapped)];
|
|
589
|
+
if (committedAt(dirOf(rel), pkg))
|
|
590
|
+
return [{ specifier: raw, path: null, kind: 'opaque' }];
|
|
591
|
+
const declared = declaredAt(dirOf(rel));
|
|
592
|
+
return declared.has(pkg) || declared.has(typesOf(pkg)) ? [external(raw)] : [asFile(raw, null)];
|
|
593
|
+
}
|
|
594
|
+
// Python: every module or package directory in the tree, outside virtual environments, is an in-repository name (X4).
|
|
595
|
+
const pyTop = new Map();
|
|
596
|
+
for (const f of files) {
|
|
597
|
+
if (extOf(f.rel) !== '.py' || f.rel.split('/').some((s) => VENV_DIRS.has(s)))
|
|
598
|
+
continue;
|
|
599
|
+
const segs = f.rel.split('/');
|
|
600
|
+
const names = [...segs.slice(0, -1), segs[segs.length - 1].replace(/\.py$/, '')];
|
|
601
|
+
names.forEach((n, i) => (pyTop.get(n) ?? pyTop.set(n, new Set()).get(n)).add(names.slice(0, i).join('/')));
|
|
602
|
+
}
|
|
603
|
+
const pyAt = (r, dotted) => {
|
|
604
|
+
const parts = dotted.split('.');
|
|
605
|
+
const out = [];
|
|
606
|
+
for (let i = 1; i < parts.length; i++) {
|
|
607
|
+
const init = joinIn(r, `${parts.slice(0, i).join('/')}/__init__.py`);
|
|
608
|
+
if (has(init))
|
|
609
|
+
out.push(init);
|
|
610
|
+
}
|
|
611
|
+
const p = joinIn(r, parts.join('/'));
|
|
612
|
+
if (has(`${p}.py`))
|
|
613
|
+
return [...out, `${p}.py`];
|
|
614
|
+
if (has(`${p}/__init__.py`))
|
|
615
|
+
return [...out, `${p}/__init__.py`];
|
|
616
|
+
return dirs.has(p) ? out : null;
|
|
617
|
+
};
|
|
618
|
+
const resolvePyAbsolute = (dotted, imported) => {
|
|
619
|
+
const roots = [...(pyTop.get(dotted.split('.')[0]) ?? [])].sort(byCodePoints);
|
|
620
|
+
if (roots.length === 0)
|
|
621
|
+
return [external(dotted)];
|
|
622
|
+
const hits = [];
|
|
623
|
+
let found = false;
|
|
624
|
+
for (const r of roots) {
|
|
625
|
+
const req = pyAt(r, dotted);
|
|
626
|
+
if (req === null)
|
|
627
|
+
continue;
|
|
628
|
+
found = true;
|
|
629
|
+
hits.push(...req);
|
|
630
|
+
if (imported && imported !== '*')
|
|
631
|
+
hits.push(...(pyAt(r, `${dotted}.${imported}`) ?? []));
|
|
632
|
+
}
|
|
633
|
+
return found ? [...new Set(hits)].map((p) => asFile(dotted, p)) : [asFile(dotted, null)];
|
|
634
|
+
};
|
|
635
|
+
const resolvePy = (rel, from, imported) => {
|
|
636
|
+
const spec = from ?? imported;
|
|
637
|
+
if (!spec.startsWith('.'))
|
|
638
|
+
return resolvePyAbsolute(spec, from ? imported : null);
|
|
639
|
+
const dots = /^\.+/.exec(spec)[0].length;
|
|
640
|
+
let dir = dirOf(rel);
|
|
641
|
+
for (let i = 1; i < dots; i++)
|
|
642
|
+
dir = dirOf(dir);
|
|
643
|
+
const p = joinIn(dir, spec.slice(dots).split('.').filter(Boolean).join('/'));
|
|
644
|
+
const one = (q) => (has(`${q}.py`) ? [`${q}.py`] : has(`${q}/__init__.py`) ? [`${q}/__init__.py`] : dirs.has(q) || q === '' || q === '.' ? [] : null);
|
|
645
|
+
const required = one(p);
|
|
646
|
+
if (required === null)
|
|
647
|
+
return [asFile(spec, null)];
|
|
648
|
+
return [...required, ...(one(joinIn(p, imported)) ?? [])].map((x) => asFile(spec, x));
|
|
649
|
+
};
|
|
650
|
+
// Go: the module path, or vendor/.
|
|
651
|
+
const goModule = goModulePath(root);
|
|
652
|
+
const goDir = (dir) => files.filter((f) => extOf(f.rel) === '.go' && !f.rel.endsWith('_test.go') && dirOf(f.rel) === dir).map((f) => f.rel);
|
|
653
|
+
const resolveGo = (importPath) => {
|
|
654
|
+
const local = goModule && (importPath === goModule || importPath.startsWith(`${goModule}/`)) ? importPath.slice(goModule.length + 1) : null;
|
|
655
|
+
const dir = local ?? (dirs.has(`vendor/${importPath}`) ? `vendor/${importPath}` : null);
|
|
656
|
+
if (dir === null)
|
|
657
|
+
return [external(importPath)];
|
|
658
|
+
const found = goDir(dir);
|
|
659
|
+
return found.length > 0 ? found.map((p) => asFile(importPath, p)) : [asFile(importPath, null)];
|
|
660
|
+
};
|
|
661
|
+
// Java: packages and classes; a package prefix of any JVM or proto package in the tree is in-repository (X4).
|
|
662
|
+
const javaPkg = new Map();
|
|
663
|
+
const javaFiles = new Map();
|
|
664
|
+
const jvmPackages = new Set();
|
|
665
|
+
for (const f of files) {
|
|
666
|
+
const ext = extOf(f.rel);
|
|
667
|
+
if (f.rel.split('/').includes('node_modules'))
|
|
668
|
+
continue;
|
|
669
|
+
if (ext === '.java') {
|
|
670
|
+
const m = /^\s*package\s+([\w.]+)\s*;/m.exec(read(f.rel) ?? '');
|
|
671
|
+
const pkg = m ? m[1] : '';
|
|
672
|
+
javaPkg.set(f.rel, pkg);
|
|
673
|
+
(javaFiles.get(pkg) ?? javaFiles.set(pkg, []).get(pkg)).push(f.rel);
|
|
674
|
+
if (pkg)
|
|
675
|
+
jvmPackages.add(pkg);
|
|
676
|
+
}
|
|
677
|
+
else if (JVM_SOURCE.has(ext)) {
|
|
678
|
+
const m = /^\s*package\s+([\w.]+)/m.exec(read(f.rel) ?? '');
|
|
679
|
+
if (m)
|
|
680
|
+
jvmPackages.add(m[1]);
|
|
681
|
+
}
|
|
682
|
+
else if (ext === '.proto') {
|
|
683
|
+
const t = read(f.rel) ?? '';
|
|
684
|
+
const m = /option\s+java_package\s*=\s*"([\w.]+)"/.exec(t) ?? /^\s*package\s+([\w.]+)\s*;/m.exec(t);
|
|
685
|
+
if (m)
|
|
686
|
+
jvmPackages.add(m[1]);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
const javaClass = new Map([...javaPkg].map(([rel, pkg]) => [`${pkg ? `${pkg}.` : ''}${path.posix.basename(rel, '.java')}`, rel]));
|
|
690
|
+
const jvmInRepo = (pkg) => [...jvmPackages].some((t) => t === pkg || t.startsWith(`${pkg}.`) || pkg.startsWith(`${t}.`));
|
|
691
|
+
const resolveJava = (pkg, cls) => {
|
|
692
|
+
const spec = `${pkg}.${cls}`;
|
|
693
|
+
if (cls === '*') {
|
|
694
|
+
if (javaFiles.has(pkg))
|
|
695
|
+
return javaFiles.get(pkg).map((p) => asFile(spec, p));
|
|
696
|
+
if (javaClass.has(pkg))
|
|
697
|
+
return [asFile(spec, javaClass.get(pkg))];
|
|
698
|
+
return jvmInRepo(pkg) ? [asFile(spec, null)] : [external(spec)];
|
|
699
|
+
}
|
|
700
|
+
const hit = javaClass.get(spec) ?? javaClass.get(pkg);
|
|
701
|
+
if (hit)
|
|
702
|
+
return [asFile(spec, hit)];
|
|
703
|
+
return jvmInRepo(pkg) ? [asFile(spec, null)] : [external(spec)];
|
|
704
|
+
};
|
|
705
|
+
// Build and tool configuration over each file (BUILD_CONFIG), and the jest/vitest manual mocks beside it.
|
|
706
|
+
const namesIn = new Map();
|
|
707
|
+
for (const f of files)
|
|
708
|
+
(namesIn.get(dirOf(f.rel)) ?? namesIn.set(dirOf(f.rel), []).get(dirOf(f.rel))).push(path.posix.basename(f.rel));
|
|
709
|
+
const isConfig = (rel) => {
|
|
710
|
+
const family = familyOf(rel) ?? 'typescript';
|
|
711
|
+
return BUILD_CONFIG.some((r) => r.for.includes(family) && minimatch(path.posix.basename(rel), r.files, { dot: true }));
|
|
712
|
+
};
|
|
713
|
+
const extendsOf = (rel, seen) => {
|
|
714
|
+
let ext;
|
|
715
|
+
try {
|
|
716
|
+
ext = parseJsonc(read(rel) ?? '').extends;
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
return [];
|
|
720
|
+
}
|
|
721
|
+
const out = [];
|
|
722
|
+
for (const e of typeof ext === 'string' ? [ext] : Array.isArray(ext) ? ext : []) {
|
|
723
|
+
if (typeof e !== 'string' || !(e.startsWith('./') || e.startsWith('../')))
|
|
724
|
+
continue; // a package's is pinned by the lockfile
|
|
725
|
+
const p = joinIn(dirOf(rel), e);
|
|
726
|
+
const hit = [p, `${p}.json`].find((c) => !c.startsWith('..') && has(c));
|
|
727
|
+
if (hit && !seen.has(hit)) {
|
|
728
|
+
seen.add(hit);
|
|
729
|
+
out.push(hit, ...extendsOf(hit, seen));
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return out;
|
|
733
|
+
};
|
|
734
|
+
const configMemo = new Map();
|
|
735
|
+
const configOf = (dir, family) => {
|
|
736
|
+
const key = `${family}\u0000${dir}`;
|
|
737
|
+
if (configMemo.has(key))
|
|
738
|
+
return configMemo.get(key);
|
|
739
|
+
const rows = BUILD_CONFIG.filter((r) => r.for.includes(family));
|
|
740
|
+
const here = (namesIn.get(dir) ?? []).filter((n) => rows.some((r) => minimatch(n, r.files, { dot: true }))).sort(byCodePoints).map((n) => joinIn(dir, n));
|
|
741
|
+
const tsconfigs = here.filter((c) => /^(tsconfig[^/]*|jsconfig)\.json$/.test(path.posix.basename(c)));
|
|
742
|
+
const mocks = family === 'typescript' && dirs.has(joinIn(dir, '__mocks__')) ? under(joinIn(dir, '__mocks__')) : [];
|
|
743
|
+
const local = [...here, ...tsconfigs.flatMap((c) => extendsOf(c, new Set())), ...mocks];
|
|
744
|
+
const out = [...new Set(dir === '' ? local : [...local, ...configOf(dirOf(dir), family)])];
|
|
745
|
+
configMemo.set(key, out);
|
|
746
|
+
return out;
|
|
747
|
+
};
|
|
748
|
+
// Imports, unfollowed forms and decorators of graphed code, from circle-ir's parser.
|
|
749
|
+
const imports = new Map();
|
|
750
|
+
const forms = new Map();
|
|
751
|
+
const form = (rel, what) => { (forms.get(rel) ?? forms.set(rel, new Set()).get(rel)).add(what); };
|
|
752
|
+
/** A decorated node's first decorator or directive line, by every position on the node's leading spine (`file:line:column`). */
|
|
753
|
+
const decoStart = new Map();
|
|
754
|
+
const pos = (n) => `${n.startPosition.row + 1}:${n.startPosition.column}`;
|
|
755
|
+
/**
|
|
756
|
+
* The node and its first children on its first line, comments skipped (F1): a declaration starts at one of them
|
|
757
|
+
* (`var s` at `s`, B1). A body is not entered, so a member on the first line of a decorated anonymous class does
|
|
758
|
+
* not take the class's decorators (F3).
|
|
759
|
+
*/
|
|
760
|
+
const decorate = (rel, c, from) => {
|
|
761
|
+
for (let x = c; x && x.startPosition.row === c.startPosition.row; x = x.namedChildren.find((k) => k.type !== 'comment')) {
|
|
762
|
+
if (/(?:^|_)body$|^statement_block$|^block$/.test(x.type))
|
|
763
|
+
break;
|
|
764
|
+
decoStart.set(`${rel}:${pos(x)}`, from);
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
/** Each graphed file's declarations by their first line, with their exact span, as circle-ir gives them. */
|
|
768
|
+
const declSpans = new Map();
|
|
769
|
+
for (const g of graphs) {
|
|
770
|
+
for (const f of g.files) {
|
|
771
|
+
const m = declSpans.get(f.file) ?? declSpans.set(f.file, new Map()).get(f.file);
|
|
772
|
+
for (const d of f.decls)
|
|
773
|
+
(m.get(d.start_line) ?? m.set(d.start_line, []).get(d.start_line)).push({ id: d.id, col: d.start_column, endLine: d.end_line, endCol: d.end_column });
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
/** Declarations a syntax node of the graph's text spans exactly: only these have bytes (fail closed). */
|
|
777
|
+
const matched = new Set();
|
|
778
|
+
/** Class bodies whose members the parser misread (`LINE_BREAK_MODIFIERS`): every declaration in one fails closed. */
|
|
779
|
+
const misread = new Map();
|
|
780
|
+
/** Java declaration nodes by file and declared name. */
|
|
781
|
+
const javaNodes = new Map();
|
|
782
|
+
// Loading by convention (D30): frameworks present, strings that name modules, Spring base packages, test setup files.
|
|
783
|
+
const present = new Set();
|
|
784
|
+
const conventionStrings_ = [];
|
|
785
|
+
const springBases = new Set();
|
|
786
|
+
const conventionFiles = new Map();
|
|
787
|
+
const parseFile = async (rel) => {
|
|
788
|
+
const lang = EXT_LANG[extOf(rel)];
|
|
789
|
+
const code = read(rel);
|
|
790
|
+
if (code === null) {
|
|
791
|
+
imports.set(rel, null);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
let tree;
|
|
795
|
+
try {
|
|
796
|
+
tree = await parse(code, lang);
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
imports.set(rel, null);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
const list = [];
|
|
803
|
+
const family = familyOf(rel);
|
|
804
|
+
for (const imp of extractImports(tree, lang)) {
|
|
805
|
+
if (family === 'typescript') {
|
|
806
|
+
if (imp.from_package)
|
|
807
|
+
list.push(...resolveTs(rel, imp.from_package));
|
|
808
|
+
}
|
|
809
|
+
else if (family === 'python') {
|
|
810
|
+
list.push(...resolvePy(rel, imp.from_package, imp.imported_name));
|
|
811
|
+
const spec = imp.from_package ?? imp.imported_name;
|
|
812
|
+
if (/^django(\.|$)/.test(spec))
|
|
813
|
+
present.add('django');
|
|
814
|
+
if (/^celery(\.|$)/.test(spec))
|
|
815
|
+
present.add('celery');
|
|
816
|
+
}
|
|
817
|
+
else if (family === 'go' && imp.from_package)
|
|
818
|
+
list.push(...resolveGo(imp.from_package));
|
|
819
|
+
else if (family === 'java' && imp.from_package)
|
|
820
|
+
list.push(...resolveJava(imp.from_package, imp.imported_name));
|
|
821
|
+
}
|
|
822
|
+
// A package's other files are in scope without an import (Go, Java).
|
|
823
|
+
if (family === 'go')
|
|
824
|
+
list.push(...goDir(dirOf(rel)).filter((p) => p !== rel).map((p) => asFile('(package)', p)));
|
|
825
|
+
if (family === 'java')
|
|
826
|
+
list.push(...(javaFiles.get(javaPkg.get(rel) ?? '') ?? []).filter((p) => p !== rel).map((p) => asFile('(package)', p)));
|
|
827
|
+
if (family === 'go' && /^\s*\/\/go:embed\s/m.test(code))
|
|
828
|
+
form(rel, '//go:embed');
|
|
829
|
+
const config = isConfig(rel);
|
|
830
|
+
const base = path.posix.basename(rel);
|
|
831
|
+
const conventionStrings = family === 'python' && (base === 'settings.py' || rel.split('/').slice(0, -1).includes('settings')) ? 'django'
|
|
832
|
+
: base === 'conftest.py' ? 'pytest' : null;
|
|
833
|
+
const testRunnerConfig = family === 'typescript' && /^(jest|vitest|vite)\.(config|workspace)\./.test(base);
|
|
834
|
+
const rootNode = tree.rootNode;
|
|
835
|
+
for (const n of walkSyn(rootNode)) {
|
|
836
|
+
if (family === 'typescript') {
|
|
837
|
+
if (n.type === 'import_require_clause') {
|
|
838
|
+
const s = n.namedChildren.find((c) => c.type === 'string');
|
|
839
|
+
if (s)
|
|
840
|
+
list.push(...resolveTs(rel, s.text.slice(1, -1)));
|
|
841
|
+
}
|
|
842
|
+
else if (n.type === 'call_expression') {
|
|
843
|
+
const fn = n.childForFieldName('function');
|
|
844
|
+
const f = fn?.text ?? '';
|
|
845
|
+
if (f === 'require' || fn?.type === 'import') {
|
|
846
|
+
const a = firstArg(n);
|
|
847
|
+
const lit = tsLiteral(a);
|
|
848
|
+
if (lit === null)
|
|
849
|
+
form(rel, `a computed ${f === 'require' ? 'require()' : 'import()'}`);
|
|
850
|
+
else if (a?.type === 'template_string')
|
|
851
|
+
list.push(...resolveTs(rel, lit));
|
|
852
|
+
}
|
|
853
|
+
else if (/^import\.meta\.glob(?:Eager)?$/.test(f))
|
|
854
|
+
form(rel, 'import.meta.glob');
|
|
855
|
+
else if (f === 'require.context')
|
|
856
|
+
form(rel, 'require.context');
|
|
857
|
+
else if (/(^|\.)importScripts$|serviceWorker\.register$/.test(f))
|
|
858
|
+
form(rel, 'a worker script URL');
|
|
859
|
+
}
|
|
860
|
+
else if (n.type === 'new_expression') {
|
|
861
|
+
// A URL alone loads nothing (an asset or a data file is not source, and its change re-runs the closure); a worker loads code.
|
|
862
|
+
const ctor = n.childForFieldName('constructor')?.text;
|
|
863
|
+
if (ctor === 'Worker' || ctor === 'SharedWorker')
|
|
864
|
+
form(rel, 'a worker URL (new Worker)');
|
|
865
|
+
}
|
|
866
|
+
else if (config && n.type === 'string') {
|
|
867
|
+
const hit = followConfigString(rel, tsLiteral(n), list);
|
|
868
|
+
if (hit && testRunnerConfig)
|
|
869
|
+
conventionFiles.set(hit, 'jest/vitest setupFiles');
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
else if (family === 'python') {
|
|
873
|
+
if (n.type === 'call') {
|
|
874
|
+
const f = n.childForFieldName('function')?.text ?? '';
|
|
875
|
+
if (/(^|\.)import_module$/.test(f) || f === '__import__')
|
|
876
|
+
form(rel, 'importlib / __import__');
|
|
877
|
+
else if (/^sys\.path\.(insert|append|extend)$/.test(f) || /(^|\.)addsitedir$/.test(f))
|
|
878
|
+
form(rel, 'a sys.path change');
|
|
879
|
+
else if (/(^|\.)(spec_from_file_location|module_from_spec|run_path|run_module|iter_modules|walk_packages|load_source|load_module|entry_points|load_entry_point)$/.test(f))
|
|
880
|
+
form(rel, `${f} (a loading form the engine does not follow)`);
|
|
881
|
+
if (/(^|\.)(autodiscover_tasks|Celery)$/.test(f)) {
|
|
882
|
+
if (/autodiscover_tasks$/.test(f))
|
|
883
|
+
present.add('celery-autodiscover');
|
|
884
|
+
for (const a of walkSyn(n.childForFieldName('arguments') ?? n)) {
|
|
885
|
+
const v = a.type === 'string' ? pyLiteral(a) : null;
|
|
886
|
+
if (v)
|
|
887
|
+
conventionStrings_.push([rel, v, 'celery']);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
else if ((n.type === 'assignment' || n.type === 'augmented_assignment') && /^sys\.path\b/.test(n.childForFieldName('left')?.text ?? '')) {
|
|
892
|
+
form(rel, 'a sys.path change');
|
|
893
|
+
}
|
|
894
|
+
else if (n.type === 'string') {
|
|
895
|
+
const v = pyLiteral(n);
|
|
896
|
+
if (config)
|
|
897
|
+
followConfigString(rel, v, list);
|
|
898
|
+
if (conventionStrings && v)
|
|
899
|
+
conventionStrings_.push([rel, v, conventionStrings]);
|
|
900
|
+
// `pytest_plugins` in a conftest: the modules it names are followed, so the tests under it hold them.
|
|
901
|
+
if (conventionStrings === 'pytest' && v && DOTTED.test(v) && v.includes('.')) {
|
|
902
|
+
for (const i of resolvePyAbsolute(v, null))
|
|
903
|
+
if (i.kind === 'file')
|
|
904
|
+
list.push(i);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
else if (family === 'java') {
|
|
909
|
+
if (n.type === 'method_invocation') {
|
|
910
|
+
const m = n.childForFieldName('name')?.text;
|
|
911
|
+
const obj = n.childForFieldName('object')?.text ?? '';
|
|
912
|
+
if (m === 'forName' && /(^|\.)Class$/.test(obj))
|
|
913
|
+
form(rel, 'Class.forName');
|
|
914
|
+
else if (m === 'loadClass' || ((m === 'load' || m === 'loadInstalled') && /ServiceLoader$/.test(obj)))
|
|
915
|
+
form(rel, `${m} (reflection)`);
|
|
916
|
+
}
|
|
917
|
+
else if (n.type === 'marker_annotation' || n.type === 'annotation') {
|
|
918
|
+
const a = n.childForFieldName('name')?.text ?? '';
|
|
919
|
+
if (SPRING_SCAN.test(a.split('.').pop()))
|
|
920
|
+
form(rel, `@${a} (Spring component scan)`);
|
|
921
|
+
if (SPRING_APP.test(a.split('.').pop())) {
|
|
922
|
+
springBases.add(javaPkg.get(rel) ?? '');
|
|
923
|
+
for (const m of n.text.matchAll(/"([\w.]+)"/g))
|
|
924
|
+
springBases.add(m[1]);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
else if (family === 'go' && n.type === 'call_expression' && n.childForFieldName('function')?.text === 'plugin.Open') {
|
|
929
|
+
form(rel, 'plugin.Open');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
imports.set(rel, list);
|
|
933
|
+
// Positions come from the text the graph was built on (F2); its lines must be the stored text's, which the
|
|
934
|
+
// declaration's bytes are cut from by line.
|
|
935
|
+
const graphCode = graphText.get(rel);
|
|
936
|
+
let posTree = null;
|
|
937
|
+
let posRoot = rootNode;
|
|
938
|
+
if (graphCode !== undefined) {
|
|
939
|
+
posRoot = null;
|
|
940
|
+
if (graphCode.split('\n').length === code.split('\n').length) {
|
|
941
|
+
try {
|
|
942
|
+
posTree = await parse(graphCode, lang);
|
|
943
|
+
posRoot = posTree.rootNode;
|
|
944
|
+
}
|
|
945
|
+
catch {
|
|
946
|
+
posRoot = null;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (posRoot)
|
|
951
|
+
positions(rel, family, posRoot);
|
|
952
|
+
posTree?.delete?.();
|
|
953
|
+
tree.delete?.();
|
|
954
|
+
};
|
|
955
|
+
/** Decorators, Java declaration nodes, and the declarations a node spans exactly, from one parse of a file. */
|
|
956
|
+
const positions = (rel, family, rootNode) => {
|
|
957
|
+
const spans = declSpans.get(rel);
|
|
958
|
+
for (const n of walkSyn(rootNode)) {
|
|
959
|
+
for (const e of spans?.get(n.startPosition.row + 1) ?? []) {
|
|
960
|
+
if (e.col === n.startPosition.column && e.endLine === n.endPosition.row + 1 && e.endCol === n.endPosition.column)
|
|
961
|
+
matched.add(e.id);
|
|
962
|
+
}
|
|
963
|
+
if (family === 'typescript' && n.type === 'class_body') {
|
|
964
|
+
const kids = n.namedChildren.filter((c) => c.type !== 'comment');
|
|
965
|
+
for (let i = 0; i + 1 < kids.length; i++) {
|
|
966
|
+
const k = kids[i];
|
|
967
|
+
if (k.type !== 'public_field_definition' && k.type !== 'field_definition')
|
|
968
|
+
continue;
|
|
969
|
+
const name = (k.childForFieldName('name') ?? k.childForFieldName('property'))?.text ?? '';
|
|
970
|
+
if (!LINE_BREAK_MODIFIERS.has(name) || k.childForFieldName('type') || k.childForFieldName('value') || k.nextSibling?.type === ';')
|
|
971
|
+
continue;
|
|
972
|
+
if (kids[i + 1].startPosition.row <= k.endPosition.row)
|
|
973
|
+
continue;
|
|
974
|
+
(misread.get(rel) ?? misread.set(rel, []).get(rel)).push({
|
|
975
|
+
from: [n.startPosition.row + 1, n.startPosition.column], to: [n.endPosition.row + 1, n.endPosition.column],
|
|
976
|
+
why: `line ${k.endPosition.row + 1} ends with \`${name}\`, which the parser reads as a field named ${name} where tsc reads a modifier of the next member, so the members of this class body are not known`,
|
|
977
|
+
});
|
|
978
|
+
break;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (family === 'typescript' || family === 'python') {
|
|
983
|
+
// Decorators: from the first to the declaration, comments between them kept (X6).
|
|
984
|
+
const visit = (node) => {
|
|
985
|
+
let pending = null;
|
|
986
|
+
for (const c of node.namedChildren) {
|
|
987
|
+
if (c.type === 'decorator') {
|
|
988
|
+
pending ??= c.startPosition.row + 1;
|
|
989
|
+
continue;
|
|
990
|
+
}
|
|
991
|
+
if (c.type === 'comment' && pending !== null)
|
|
992
|
+
continue;
|
|
993
|
+
if (pending !== null)
|
|
994
|
+
decorate(rel, c, pending);
|
|
995
|
+
pending = null;
|
|
996
|
+
visit(c);
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
visit(rootNode);
|
|
1000
|
+
}
|
|
1001
|
+
else if (family === 'go') {
|
|
1002
|
+
// Compiler directives in the comments right above a declaration (`//go:embed`, `//go:linkname`, cgo's
|
|
1003
|
+
// `//export`) are its decorators: from the first of them (B1, N4). Blank lines and other comments may sit between.
|
|
1004
|
+
const visit = (node) => {
|
|
1005
|
+
let first = null;
|
|
1006
|
+
for (const c of node.namedChildren) {
|
|
1007
|
+
if (c.type === 'comment') {
|
|
1008
|
+
if (/^\/\/(?:go:\S|export\s)/.test(c.text))
|
|
1009
|
+
first ??= c.startPosition.row + 1;
|
|
1010
|
+
continue;
|
|
1011
|
+
}
|
|
1012
|
+
if (first !== null)
|
|
1013
|
+
decorate(rel, c, first);
|
|
1014
|
+
first = null;
|
|
1015
|
+
visit(c);
|
|
1016
|
+
}
|
|
1017
|
+
};
|
|
1018
|
+
visit(rootNode);
|
|
1019
|
+
}
|
|
1020
|
+
else if (family === 'java') {
|
|
1021
|
+
// circle-ir starts a Java field or constant at its declarator, whose first token is its name; its node starts at
|
|
1022
|
+
// its modifiers, annotations included (B1). Each declaration node, with the names it declares and their
|
|
1023
|
+
// positions, for matching a declaration by kind and exact position.
|
|
1024
|
+
const add = (n, kind, names) => {
|
|
1025
|
+
const node = { kind, start: n.startPosition.row + 1, at: pos(n), names, mods: n.namedChildren.find((c) => c.type === 'modifiers')?.text ?? null };
|
|
1026
|
+
for (const [name] of names) {
|
|
1027
|
+
const key = `${rel}\0${name}`;
|
|
1028
|
+
(javaNodes.get(key) ?? javaNodes.set(key, []).get(key)).push(node);
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
const named = (c) => (c ? [[c.text, pos(c)]] : []);
|
|
1032
|
+
for (const n of walkSyn(rootNode)) {
|
|
1033
|
+
const kind = JAVA_DECL_KIND[n.type];
|
|
1034
|
+
if (!kind)
|
|
1035
|
+
continue;
|
|
1036
|
+
if (n.type === 'field_declaration' || n.type === 'constant_declaration') {
|
|
1037
|
+
add(n, kind, n.namedChildren.filter((c) => c.type === 'variable_declarator').flatMap((c) => named(c.childForFieldName('name'))));
|
|
1038
|
+
}
|
|
1039
|
+
else if (n.type === 'constructor_declaration' || n.type === 'compact_constructor_declaration') {
|
|
1040
|
+
add(n, kind, [['constructor', pos(n.childForFieldName('name') ?? n)]]);
|
|
1041
|
+
}
|
|
1042
|
+
else {
|
|
1043
|
+
add(n, kind, named(n.childForFieldName('name')));
|
|
1044
|
+
}
|
|
1045
|
+
if (n.type === 'record_declaration') {
|
|
1046
|
+
for (const p of n.childForFieldName('parameters')?.namedChildren ?? [])
|
|
1047
|
+
if (p.type === 'formal_parameter')
|
|
1048
|
+
add(p, 'field', named(p.childForFieldName('name')));
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
/** A string in build or tool config that names a tracked file (`setupFiles`, a plugin, `requirements/base.txt`) is followed. */
|
|
1054
|
+
function followConfigString(rel, value, list) {
|
|
1055
|
+
if (!value || value.length > 300 || /^[a-z][\w+.-]*:/i.test(value) || !/^\.{0,2}\/|[\w-]\/[\w.-]|\.\w+$/.test(value))
|
|
1056
|
+
return null;
|
|
1057
|
+
for (const c of [joinIn(dirOf(rel), value.replace(/^<rootDir>\//, '').replace(/^\//, '')), path.posix.normalize(value.replace(/^<rootDir>\//, '').replace(/^\//, ''))]) {
|
|
1058
|
+
if (c.startsWith('..'))
|
|
1059
|
+
continue;
|
|
1060
|
+
const hit = has(c) ? c : familyOf(c) || !extOf(c) ? tracked.resolve(c) : null;
|
|
1061
|
+
if (hit && hit !== rel) {
|
|
1062
|
+
list.push(asFile(value, hit));
|
|
1063
|
+
return hit;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
return null;
|
|
1067
|
+
}
|
|
1068
|
+
for (const rel of graphed)
|
|
1069
|
+
await parseFile(rel);
|
|
1070
|
+
for (const g of graphs) {
|
|
1071
|
+
const fileOf = new Map(g.files.flatMap((f) => f.decls.map((d) => [d.id, f.file])));
|
|
1072
|
+
for (const u of g.unresolved) {
|
|
1073
|
+
const f = fileOf.get(u.from);
|
|
1074
|
+
if (u.methodName === '<module>' && f)
|
|
1075
|
+
form(f, 'a computed import or require');
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
// Angular and Nx `fileReplacements`: the build swaps `replace` for `with`, so `replace` imports it (X8).
|
|
1079
|
+
for (const f of files) {
|
|
1080
|
+
if (!['angular.json', 'project.json', 'workspace.json'].includes(path.posix.basename(f.rel)) || f.rel.split('/').includes('node_modules'))
|
|
1081
|
+
continue;
|
|
1082
|
+
let json;
|
|
1083
|
+
try {
|
|
1084
|
+
json = parseJsonc(read(f.rel) ?? '');
|
|
1085
|
+
}
|
|
1086
|
+
catch {
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const visit = (v) => {
|
|
1090
|
+
if (Array.isArray(v)) {
|
|
1091
|
+
v.forEach(visit);
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
if (!v || typeof v !== 'object')
|
|
1095
|
+
return;
|
|
1096
|
+
for (const [k, x] of Object.entries(v)) {
|
|
1097
|
+
if (k === 'fileReplacements' && Array.isArray(x)) {
|
|
1098
|
+
for (const r of x) {
|
|
1099
|
+
const from = typeof r.replace === 'string' ? r.replace : typeof r.src === 'string' ? r.src : null;
|
|
1100
|
+
const to = typeof r.with === 'string' ? r.with : typeof r.replaceWith === 'string' ? r.replaceWith : null;
|
|
1101
|
+
if (!from || !to)
|
|
1102
|
+
continue;
|
|
1103
|
+
const at = (p) => [joinIn(dirOf(f.rel), p), path.posix.normalize(p)].find((c) => has(c)) ?? null;
|
|
1104
|
+
const a = at(from);
|
|
1105
|
+
if (a && imports.has(a))
|
|
1106
|
+
imports.get(a)?.push(asFile(to, at(to)));
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
else
|
|
1110
|
+
visit(x);
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
visit(json);
|
|
1114
|
+
}
|
|
1115
|
+
// Stylesheets: every import form is followed, or the import is `missing` (X5); Sass built-ins are not imports (S7).
|
|
1116
|
+
for (const f of files) {
|
|
1117
|
+
if (!STYLES.has(extOf(f.rel)))
|
|
1118
|
+
continue;
|
|
1119
|
+
const css = (read(f.rel) ?? '').replace(/\/\*[\s\S]*?\*\//g, '');
|
|
1120
|
+
const list = [];
|
|
1121
|
+
const dir = dirOf(f.rel);
|
|
1122
|
+
const resolveStyle = (spec, required) => {
|
|
1123
|
+
if (/^(https?:|data:|\/\/|#|sass:)/.test(spec))
|
|
1124
|
+
return;
|
|
1125
|
+
if (spec.startsWith('~')) {
|
|
1126
|
+
if (required && !declaredAt(dir).has(pkgOf(spec.slice(1))))
|
|
1127
|
+
list.push(asFile(spec, null));
|
|
1128
|
+
return;
|
|
1129
|
+
}
|
|
1130
|
+
const base = path.posix.normalize(spec.startsWith('/') ? spec.slice(1) : joinIn(dir, spec));
|
|
1131
|
+
const stem = joinIn(dirOf(base), `_${path.posix.basename(base)}`);
|
|
1132
|
+
const exts = ['.scss', '.sass', '.css', '.less', '.styl'];
|
|
1133
|
+
const hit = [base, ...exts.flatMap((x) => [`${base}${x}`, `${stem}${x}`, `${base}/index${x}`, `${base}/_index${x}`])].find(has);
|
|
1134
|
+
if (hit)
|
|
1135
|
+
list.push(asFile(spec, hit));
|
|
1136
|
+
else if (!/^\.{0,2}\//.test(spec) && declaredAt(dir).has(pkgOf(spec)))
|
|
1137
|
+
list.push(external(spec));
|
|
1138
|
+
else if (required)
|
|
1139
|
+
list.push(asFile(spec, null));
|
|
1140
|
+
};
|
|
1141
|
+
for (const m of css.matchAll(/@(import|use|forward|require)\b([^;{}]*)/g)) {
|
|
1142
|
+
let params = m[2].trim();
|
|
1143
|
+
if (m[1] === 'import')
|
|
1144
|
+
params = params.replace(/^\([^)]*\)\s*/, ''); // Less options
|
|
1145
|
+
const specs = [...params.matchAll(/url\(\s*(['"]?)([^'")\s]+)\1\s*\)|(['"])((?:(?!\3).)+)\3/g)].map((x) => (x[2] ?? x[4]));
|
|
1146
|
+
if (specs.length === 0) {
|
|
1147
|
+
list.push(asFile(`@${m[1]} ${params}`, null));
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
for (const s of m[1] === 'use' || m[1] === 'forward' ? specs.slice(0, 1) : specs)
|
|
1151
|
+
resolveStyle(s, true);
|
|
1152
|
+
}
|
|
1153
|
+
for (const m of css.matchAll(/\bcomposes\s*:[^;}]*?\bfrom\s+(['"])([^'"]+)\1/g))
|
|
1154
|
+
resolveStyle(m[2], true);
|
|
1155
|
+
for (const m of css.matchAll(/url\(\s*['"]?([^'")\s]+)['"]?\s*\)/g))
|
|
1156
|
+
resolveStyle(m[1], false);
|
|
1157
|
+
imports.set(f.rel, list);
|
|
1158
|
+
}
|
|
1159
|
+
// HTML: its src/href references are followed; a module it names is an app entry; an inline script is a form the engine does not follow.
|
|
1160
|
+
const named = new Set();
|
|
1161
|
+
const namedBy = new Map();
|
|
1162
|
+
for (const f of files) {
|
|
1163
|
+
if (!HTML.has(extOf(f.rel)))
|
|
1164
|
+
continue;
|
|
1165
|
+
const html = (read(f.rel) ?? '').replace(/<!--[\s\S]*?-->/g, '');
|
|
1166
|
+
const list = [];
|
|
1167
|
+
for (const m of html.matchAll(/\b(?:src|href)\s*=\s*["']([^"'#?]+)/g)) {
|
|
1168
|
+
const s = m[1];
|
|
1169
|
+
if (/^(https?:|data:|\/\/|mailto:)/.test(s))
|
|
1170
|
+
continue;
|
|
1171
|
+
const hit = (s.startsWith('/') ? [s.slice(1), joinIn(dirOf(f.rel), `public${s}`), `public${s}`] : [joinIn(dirOf(f.rel), s)]).map((c) => path.posix.normalize(c)).find(has);
|
|
1172
|
+
if (!hit)
|
|
1173
|
+
continue;
|
|
1174
|
+
list.push(asFile(s, hit));
|
|
1175
|
+
if (kind.get(hit) === 'code') {
|
|
1176
|
+
named.add(hit);
|
|
1177
|
+
(namedBy.get(hit) ?? namedBy.set(hit, []).get(hit)).push(f.rel);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
if (/<script\b(?![^>]*\bsrc\s*=)(?![^>]*\btype\s*=\s*["']?(?:application\/(?:ld\+)?json|importmap-json|text\/template))[^>]*>\s*[^<\s]/i.test(html))
|
|
1181
|
+
form(f.rel, 'an inline script');
|
|
1182
|
+
imports.set(f.rel, list);
|
|
1183
|
+
}
|
|
1184
|
+
for (const [d, pj] of pkgJson) {
|
|
1185
|
+
// A built target (`dist/index.js`) names its source, as for an in-repository package (X1).
|
|
1186
|
+
for (const t of [pj.main, pj.module, pj.browser, pj.bin, pj.exports].flatMap(allTargets)) {
|
|
1187
|
+
if (t.includes('*')) {
|
|
1188
|
+
// A subpath pattern (`./dist/specifica/*.js`) names every module under its directory, built or source.
|
|
1189
|
+
const within = dirOf(t.slice(0, t.indexOf('*')).replace(/^\.\//, '') + 'x');
|
|
1190
|
+
for (const dir of new Set([joinIn(d, within), joinIn(d, `${within}/`.replace(BUILT, '$1src/').replace(/\/$/, ''))])) {
|
|
1191
|
+
for (const f of files)
|
|
1192
|
+
if (f.rel.startsWith(`${dir}/`) && kind.get(f.rel) === 'code')
|
|
1193
|
+
named.add(f.rel);
|
|
1194
|
+
}
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
const p = inPackage(d, t);
|
|
1198
|
+
if (p && kind.get(p) === 'code')
|
|
1199
|
+
named.add(p);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
const appEntries = new Set(named);
|
|
1203
|
+
for (const g of graphs)
|
|
1204
|
+
for (const e of g.entries)
|
|
1205
|
+
if (e.kind === 'main' && graphed.has(e.file))
|
|
1206
|
+
appEntries.add(e.file);
|
|
1207
|
+
// Code the graphs leave out but something references: imports from graphed code (tests included), manifests' entry points, HTML.
|
|
1208
|
+
const referenced = new Set();
|
|
1209
|
+
const ungraphedCode = (rel) => !!rel && kind.get(rel) === 'code' && !graphed.has(rel);
|
|
1210
|
+
for (const rel of graphed)
|
|
1211
|
+
for (const i of imports.get(rel) ?? [])
|
|
1212
|
+
if (ungraphedCode(i.path))
|
|
1213
|
+
referenced.add(i.path);
|
|
1214
|
+
for (const p of named)
|
|
1215
|
+
if (ungraphedCode(p))
|
|
1216
|
+
referenced.add(p);
|
|
1217
|
+
// Who imports whom (code, tests aside), for a route's registration chain.
|
|
1218
|
+
const isTest = productScope(root, { env: {} });
|
|
1219
|
+
const importers = new Map();
|
|
1220
|
+
for (const rel of graphed) {
|
|
1221
|
+
if (isTest.classify(rel)?.reason === 'test')
|
|
1222
|
+
continue;
|
|
1223
|
+
for (const i of imports.get(rel) ?? [])
|
|
1224
|
+
if (i.kind === 'file')
|
|
1225
|
+
(importers.get(i.path) ?? importers.set(i.path, []).get(i.path)).push(rel);
|
|
1226
|
+
}
|
|
1227
|
+
// Framework convention roots (D30, CONVENTIONS): a changed file under them is not understood.
|
|
1228
|
+
const convention = new Map();
|
|
1229
|
+
const mark = (rel, fw) => { if (has(rel) && !convention.has(rel))
|
|
1230
|
+
convention.set(rel, fw); };
|
|
1231
|
+
const markGlob = (dir, glob, fw) => {
|
|
1232
|
+
for (const f of files) {
|
|
1233
|
+
if (dir && !f.rel.startsWith(`${dir}/`))
|
|
1234
|
+
continue;
|
|
1235
|
+
if (minimatch(dir ? f.rel.slice(dir.length + 1) : f.rel, glob, { dot: true }))
|
|
1236
|
+
mark(f.rel, fw);
|
|
1237
|
+
}
|
|
1238
|
+
};
|
|
1239
|
+
const JS_PRESENT = {
|
|
1240
|
+
next: (d) => d === 'next',
|
|
1241
|
+
nuxt: (d) => d === 'nuxt',
|
|
1242
|
+
sveltekit: (d) => d === '@sveltejs/kit',
|
|
1243
|
+
remix: (d) => d.startsWith('@remix-run/') || d === '@react-router/dev',
|
|
1244
|
+
astro: (d) => d === 'astro',
|
|
1245
|
+
gatsby: (d) => d === 'gatsby',
|
|
1246
|
+
'expo-router': (d) => d === 'expo-router',
|
|
1247
|
+
'tanstack-router': (d) => d === '@tanstack/router-plugin' || d === '@tanstack/router-vite-plugin' || d === '@tanstack/react-start',
|
|
1248
|
+
storybook: (d) => d === 'storybook' || d.startsWith('@storybook/'),
|
|
1249
|
+
'jest/vitest': (d) => d === 'jest' || d === 'vitest',
|
|
1250
|
+
};
|
|
1251
|
+
for (const [d, pj] of pkgJson) {
|
|
1252
|
+
const deps = DEP_KINDS.flatMap((k) => (pj[k] && typeof pj[k] === 'object' ? Object.keys(pj[k]) : []));
|
|
1253
|
+
for (const c of CONVENTIONS) {
|
|
1254
|
+
const isPresent = JS_PRESENT[c.name];
|
|
1255
|
+
if (!isPresent || !deps.some(isPresent))
|
|
1256
|
+
continue;
|
|
1257
|
+
for (const g of c.roots)
|
|
1258
|
+
if (!g.includes(' '))
|
|
1259
|
+
markGlob(d, g, c.name);
|
|
1260
|
+
}
|
|
1261
|
+
const jest = pj.jest;
|
|
1262
|
+
if (jest && typeof jest === 'object') {
|
|
1263
|
+
for (const k of ['setupFiles', 'setupFilesAfterEnv', 'globalSetup', 'globalTeardown']) {
|
|
1264
|
+
for (const v of allTargets(jest[k])) {
|
|
1265
|
+
const hit = followConfigString(joinIn(d, 'package.json'), v, []);
|
|
1266
|
+
if (hit)
|
|
1267
|
+
mark(hit, 'jest/vitest setupFiles');
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
for (const [f, fw] of conventionFiles)
|
|
1273
|
+
mark(f, fw);
|
|
1274
|
+
const pyNamed = (dotted) => {
|
|
1275
|
+
if (!DOTTED.test(dotted))
|
|
1276
|
+
return [];
|
|
1277
|
+
for (const m of [dotted, dotted.split('.').slice(0, -1).join('.')]) {
|
|
1278
|
+
if (!m)
|
|
1279
|
+
continue;
|
|
1280
|
+
const hits = resolvePyAbsolute(m, null).filter((i) => i.kind === 'file').map((i) => i.path);
|
|
1281
|
+
if (hits.length > 0)
|
|
1282
|
+
return hits;
|
|
1283
|
+
}
|
|
1284
|
+
return [];
|
|
1285
|
+
};
|
|
1286
|
+
const pyFiles = files.filter((f) => extOf(f.rel) === '.py').map((f) => f.rel);
|
|
1287
|
+
if (present.has('django')) {
|
|
1288
|
+
const apps = new Set(pyFiles.filter((f) => path.posix.basename(f) === 'apps.py').map(dirOf));
|
|
1289
|
+
for (const [, v, fw] of conventionStrings_) {
|
|
1290
|
+
if (fw !== 'django')
|
|
1291
|
+
continue;
|
|
1292
|
+
for (const hit of pyNamed(v)) {
|
|
1293
|
+
mark(hit, 'django');
|
|
1294
|
+
if (/(^|\/)(__init__|apps)\.py$/.test(hit))
|
|
1295
|
+
apps.add(dirOf(hit));
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
for (const a of apps)
|
|
1299
|
+
for (const g of DJANGO_APP_MODULES)
|
|
1300
|
+
markGlob(a, g, 'django');
|
|
1301
|
+
}
|
|
1302
|
+
if (present.has('celery')) {
|
|
1303
|
+
for (const f of pyFiles)
|
|
1304
|
+
if (/(^|\/)tasks(\.py$|\/)/.test(f))
|
|
1305
|
+
mark(f, 'celery');
|
|
1306
|
+
for (const [, v, fw] of conventionStrings_)
|
|
1307
|
+
if (fw === 'celery')
|
|
1308
|
+
for (const hit of pyNamed(v))
|
|
1309
|
+
mark(hit, 'celery');
|
|
1310
|
+
}
|
|
1311
|
+
for (const f of pyFiles)
|
|
1312
|
+
if (path.posix.basename(f) === 'conftest.py')
|
|
1313
|
+
mark(f, 'pytest');
|
|
1314
|
+
for (const [, v, fw] of conventionStrings_)
|
|
1315
|
+
if (fw === 'pytest')
|
|
1316
|
+
for (const hit of pyNamed(v))
|
|
1317
|
+
mark(hit, 'pytest');
|
|
1318
|
+
if (springBases.size > 0) {
|
|
1319
|
+
for (const [f, pkg] of javaPkg)
|
|
1320
|
+
if ([...springBases].some((b) => b === '' || pkg === b || pkg.startsWith(`${b}.`)))
|
|
1321
|
+
mark(f, 'spring');
|
|
1322
|
+
}
|
|
1323
|
+
// Declarations' raw bytes, from the first decorator (X6, X9).
|
|
1324
|
+
const starts = new Map();
|
|
1325
|
+
const bytesOf = (rel, from, to) => {
|
|
1326
|
+
const buf = rawOf(rel);
|
|
1327
|
+
if (!buf)
|
|
1328
|
+
return null;
|
|
1329
|
+
let s = starts.get(rel);
|
|
1330
|
+
if (!s) {
|
|
1331
|
+
s = [0];
|
|
1332
|
+
for (let i = 0; i < buf.length; i++)
|
|
1333
|
+
if (buf[i] === 10)
|
|
1334
|
+
s.push(i + 1);
|
|
1335
|
+
starts.set(rel, s);
|
|
1336
|
+
}
|
|
1337
|
+
return buf.subarray(s[from - 1] ?? buf.length, to < s.length ? s[to] : buf.length);
|
|
1338
|
+
};
|
|
1339
|
+
// A declaration's first line: its first decorator or directive, for the decorated node that starts exactly where the
|
|
1340
|
+
// declaration does (TypeScript, Python and Go). For Java, the declaration's own node, by kind and exact position:
|
|
1341
|
+
// the node starts there (a method, a type, a constructor, an annotated enum constant, a record component), or it
|
|
1342
|
+
// declares the declaration's name there (a field's declarator). So a field of several declarators, or one whose
|
|
1343
|
+
// initializer declares a class, a method or a field of the same name, keeps its own modifiers, and only them (B1).
|
|
1344
|
+
const declAt = new Map();
|
|
1345
|
+
const decorators = new Map();
|
|
1346
|
+
const failed = new Map();
|
|
1347
|
+
const notAfter = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] <= b[1]);
|
|
1348
|
+
for (const g of graphs) {
|
|
1349
|
+
for (const f of g.files) {
|
|
1350
|
+
for (const d of f.decls) {
|
|
1351
|
+
// Fail closed: a declaration no syntax node spans exactly has no bytes, never its bare lines; nor one in a class
|
|
1352
|
+
// body whose members the parser misread.
|
|
1353
|
+
if (!matched.has(d.id))
|
|
1354
|
+
continue;
|
|
1355
|
+
const at0 = [d.start_line, d.start_column];
|
|
1356
|
+
const bad = misread.get(f.file)?.find((b) => notAfter(b.from, at0) && notAfter(at0, b.to));
|
|
1357
|
+
if (bad) {
|
|
1358
|
+
failed.set(d.id, bad.why);
|
|
1359
|
+
continue;
|
|
1360
|
+
}
|
|
1361
|
+
const at = `${d.start_line}:${d.start_column}`;
|
|
1362
|
+
let from = decoStart.get(`${f.file}:${at}`) ?? d.start_line;
|
|
1363
|
+
const own = (javaNodes.get(`${f.file}\0${d.name}`) ?? [])
|
|
1364
|
+
.find((x) => x.kind === d.kind && (x.at === at || x.names.some(([nm, p]) => nm === d.name && p === at)));
|
|
1365
|
+
if (own) {
|
|
1366
|
+
from = Math.min(from, own.start);
|
|
1367
|
+
// Annotations and modifiers, even on the declarator's own line, are the declaration's decorators.
|
|
1368
|
+
if (own.mods !== null)
|
|
1369
|
+
decorators.set(d.id, blake3Hex(own.mods));
|
|
1370
|
+
}
|
|
1371
|
+
declAt.set(d.id, { file: f.file, from, start: d.start_line, end: d.end_line });
|
|
1372
|
+
if (!own && from < d.start_line)
|
|
1373
|
+
decorators.set(d.id, blake3Hex(bytesOf(f.file, from, d.start_line - 1) ?? new Uint8Array()));
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
/** A symlink followed hop by hop against the tracked listing, as POSIX resolves a path (B2). */
|
|
1378
|
+
const links = new Map();
|
|
1379
|
+
const resolveLink = (rel) => {
|
|
1380
|
+
if (links.has(rel))
|
|
1381
|
+
return links.get(rel);
|
|
1382
|
+
const first = byRel.get(rel);
|
|
1383
|
+
if (!first || first.link === null)
|
|
1384
|
+
return null;
|
|
1385
|
+
const hops = [];
|
|
1386
|
+
const done = (target, why) => { const r = { hops, target, why }; links.set(rel, r); return r; };
|
|
1387
|
+
const at = [];
|
|
1388
|
+
let rest = rel.split('/');
|
|
1389
|
+
let n = 0;
|
|
1390
|
+
while (rest.length > 0) {
|
|
1391
|
+
const seg = rest.shift();
|
|
1392
|
+
if (seg === '' || seg === '.')
|
|
1393
|
+
continue;
|
|
1394
|
+
if (seg === '..') {
|
|
1395
|
+
if (at.length === 0)
|
|
1396
|
+
return done(null, `${rel} links out of the tree`);
|
|
1397
|
+
at.pop();
|
|
1398
|
+
continue;
|
|
1399
|
+
}
|
|
1400
|
+
const p = [...at, seg].join('/');
|
|
1401
|
+
const f = byRel.get(p);
|
|
1402
|
+
if (f && f.link !== null) {
|
|
1403
|
+
if (++n > MAX_LINK_HOPS)
|
|
1404
|
+
return done(null, `${rel} links in a loop`);
|
|
1405
|
+
if (!hops.includes(p))
|
|
1406
|
+
hops.push(p);
|
|
1407
|
+
if (path.posix.isAbsolute(f.link) || /^[A-Za-z]:[\\/]/.test(f.link))
|
|
1408
|
+
return done(null, `${rel} links out of the tree (${p} → ${f.link})`);
|
|
1409
|
+
rest = [...f.link.split('/'), ...rest];
|
|
1410
|
+
continue;
|
|
1411
|
+
}
|
|
1412
|
+
if (f && rest.length > 0)
|
|
1413
|
+
return done(null, `${rel} links into ${p}, ${f.gitlink !== null ? 'a submodule' : 'a file'}, to a path that is not tracked`);
|
|
1414
|
+
// A part on the way must be a tracked directory (or a tracked link, above): `nothere/../x` is not resolved on its text.
|
|
1415
|
+
if (rest.some((r) => r !== '' && r !== '.') && !dirs.has(p))
|
|
1416
|
+
return done(null, `${rel} links through ${p}, which is not a tracked directory`);
|
|
1417
|
+
at.push(seg);
|
|
1418
|
+
}
|
|
1419
|
+
const target = at.join('/');
|
|
1420
|
+
const f = byRel.get(target);
|
|
1421
|
+
if (f && f.gitlink !== null)
|
|
1422
|
+
return done(null, `${rel} links to ${target}, a submodule`);
|
|
1423
|
+
if (f)
|
|
1424
|
+
return done(target, null);
|
|
1425
|
+
if (target === '' || dirs.has(target))
|
|
1426
|
+
return done(null, `${rel} links to a directory (${target || '.'})`);
|
|
1427
|
+
return done(null, `${rel} links to ${target}, which is not tracked`);
|
|
1428
|
+
};
|
|
1429
|
+
const isConfigName = (rel) => CONFIG_FILES.some((g) => minimatch(path.posix.basename(rel), g, { dot: true }));
|
|
1430
|
+
const understood = (rel) => graphed.has(rel) && !partial.has(rel) && !isConfigName(rel);
|
|
1431
|
+
const notUnderstood = (rel) => {
|
|
1432
|
+
const k = kind.get(rel);
|
|
1433
|
+
if (k === undefined || understood(rel))
|
|
1434
|
+
return null;
|
|
1435
|
+
if (k === 'gitlink')
|
|
1436
|
+
return { reason: 'gitlink', detail: `${rel} is a submodule, whose content the engine does not read` };
|
|
1437
|
+
if (k === 'symlink')
|
|
1438
|
+
return { reason: 'symlink', detail: `${rel} is a symlink, not source` };
|
|
1439
|
+
if (k === 'unsupported')
|
|
1440
|
+
return { reason: 'unsupported_language', detail: `${rel} is code or a template in a language the engine does not fully resolve` };
|
|
1441
|
+
if (k === 'non_code')
|
|
1442
|
+
return { reason: 'not_source', detail: `${rel} is not source (configuration, data, markup, a stylesheet or documentation)` };
|
|
1443
|
+
if (partial.has(rel))
|
|
1444
|
+
return { reason: 'partial_file', detail: `${rel} did not parse completely` };
|
|
1445
|
+
if (graphed.has(rel))
|
|
1446
|
+
return { reason: 'config', detail: `${rel} is configuration by its file pattern (CONFIG_FILES), which D30 never counts as provably outside` };
|
|
1447
|
+
return skippedDir(rel)
|
|
1448
|
+
? { reason: 'skipped_dir', detail: `${rel} is code under a directory the graphs skip` }
|
|
1449
|
+
: { reason: 'skipped_size', detail: `${rel} is code over the size bound, not graphed` };
|
|
1450
|
+
};
|
|
1451
|
+
return {
|
|
1452
|
+
name,
|
|
1453
|
+
graphs,
|
|
1454
|
+
paths: files.map((f) => f.rel),
|
|
1455
|
+
fileHash: (rel) => byRel.get(rel)?.hash ?? null,
|
|
1456
|
+
fileMode: (rel) => byRel.get(rel)?.mode ?? null,
|
|
1457
|
+
fileId: (rel) => { const f = byRel.get(rel); return f ? `${f.mode} ${f.sha}` : null; },
|
|
1458
|
+
fileKind: (rel) => kind.get(rel) ?? null,
|
|
1459
|
+
resolveLink,
|
|
1460
|
+
imports: (rel) => {
|
|
1461
|
+
if (imports.has(rel))
|
|
1462
|
+
return imports.get(rel);
|
|
1463
|
+
return kind.get(rel) === 'non_code' ? [] : null;
|
|
1464
|
+
},
|
|
1465
|
+
forms: (rel) => [...(forms.get(rel) ?? [])].sort(byCodePoints),
|
|
1466
|
+
importers: (rel) => importers.get(rel) ?? [],
|
|
1467
|
+
named,
|
|
1468
|
+
isTest: (rel) => isTest.classify(rel)?.reason === 'test',
|
|
1469
|
+
convention: (rel) => convention.get(rel) ?? null,
|
|
1470
|
+
appEntries,
|
|
1471
|
+
namedBy: (rel) => namedBy.get(rel) ?? [],
|
|
1472
|
+
manifests: (rel) => configOf(dirOf(rel), familyOf(rel) ?? 'typescript'),
|
|
1473
|
+
declText: (id) => {
|
|
1474
|
+
const at = declAt.get(id);
|
|
1475
|
+
return at ? bytesOf(at.file, at.from, at.end) : null;
|
|
1476
|
+
},
|
|
1477
|
+
declProblem: (id) => (declAt.has(id) ? null : failed.get(id) ?? `no syntax node of its file spans the declaration exactly, so where its decorators start is not known`),
|
|
1478
|
+
decorators,
|
|
1479
|
+
partial,
|
|
1480
|
+
understood: (rel) => (byRel.has(rel) ? understood(rel) : null),
|
|
1481
|
+
notUnderstood,
|
|
1482
|
+
referencedUngraphed: [...referenced].sort(byCodePoints),
|
|
1483
|
+
walkCut: cut,
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
/** The change scope of a pull request: base and head as two git checkouts. */
|
|
1487
|
+
export async function changeScope(baseRoot, headRoot, anchors, opts = {}) {
|
|
1488
|
+
checkAnchors(anchors);
|
|
1489
|
+
for (const [label, root] of [['base', baseRoot], ['head', headRoot]]) {
|
|
1490
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory())
|
|
1491
|
+
throw new Error(`${label} root is not a directory: ${root}`);
|
|
1492
|
+
}
|
|
1493
|
+
const maxFiles = opts.walk?.maxFiles ?? CHANGE_SCOPE_WALK.maxFiles;
|
|
1494
|
+
const maxDepth = opts.walk?.maxDepth ?? CHANGE_SCOPE_WALK.maxDepth;
|
|
1495
|
+
const { ensureAnalyzerInitialized, isAnalyzerInitialized } = await import('../utils/analyzer-init.js');
|
|
1496
|
+
if (!isAnalyzerInitialized())
|
|
1497
|
+
await ensureAnalyzerInitialized();
|
|
1498
|
+
const failures = [];
|
|
1499
|
+
const base = await sideOf('base', baseRoot, maxFiles, maxDepth, failures);
|
|
1500
|
+
const head = await sideOf('head', headRoot, maxFiles, maxDepth, failures);
|
|
1501
|
+
return scopeOf(base, head, anchors, failures, { closureReuse: opts.closureReuse ?? closureReuseEnabled() });
|
|
1502
|
+
}
|
|
1503
|
+
//# sourceMappingURL=index.js.map
|