@denizokcu/haze 1.7.11 → 1.8.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 +56 -0
- package/README.md +142 -102
- package/SECURITY.md +1 -1
- package/assets/graph-grammars/NOTICE.md +21 -0
- package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
- package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.js +4056 -0
- package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
- package/bin/haze.js +47 -19
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +1 -2
- package/dist/cli/chat/ChatHeader.d.ts +6 -0
- package/dist/cli/chat/ChatHeader.js +11 -0
- package/dist/cli/chat/ChatScreen.d.ts +16 -0
- package/dist/cli/chat/ChatScreen.js +399 -0
- package/dist/cli/chat/ChatScreenView.d.ts +68 -0
- package/dist/cli/chat/ChatScreenView.js +47 -0
- package/dist/cli/chat/LiveTail.d.ts +11 -0
- package/dist/cli/chat/LiveTail.js +26 -0
- package/dist/cli/chat/TaskBar.d.ts +3 -2
- package/dist/cli/chat/TaskBar.js +4 -0
- package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
- package/dist/cli/chat/agentTurnRunner.js +177 -0
- package/dist/cli/chat/busyIndicator.js +9 -5
- package/dist/cli/chat/chatMetrics.d.ts +7 -0
- package/dist/cli/chat/chatMetrics.js +15 -1
- package/dist/cli/chat/chatViewModel.d.ts +85 -0
- package/dist/cli/chat/chatViewModel.js +66 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
- package/dist/cli/chat/fileMentionSuggestions.js +4 -21
- package/dist/cli/chat/inputSuggestions.js +1 -0
- package/dist/cli/chat/liveTheme.d.ts +11 -0
- package/dist/cli/chat/liveTheme.js +26 -0
- package/dist/cli/chat/messageFinalize.d.ts +4 -0
- package/dist/cli/chat/messageFinalize.js +8 -0
- package/dist/cli/chat/messages.js +1 -1
- package/dist/cli/chat/pickerOpeners.d.ts +23 -0
- package/dist/cli/chat/pickerOpeners.js +36 -0
- package/dist/cli/chat/promptSessionState.d.ts +11 -0
- package/dist/cli/chat/promptSessionState.js +39 -0
- package/dist/cli/chat/renderMetrics.d.ts +8 -0
- package/dist/cli/chat/renderMetrics.js +14 -0
- package/dist/cli/chat/resizeGuard.d.ts +11 -0
- package/dist/cli/chat/resizeGuard.js +25 -0
- package/dist/cli/chat/screenDeps.d.ts +116 -0
- package/dist/cli/chat/screenDeps.js +1 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
- package/dist/cli/chat/sessionLifecycle.js +6 -2
- package/dist/cli/chat/sessionRecorder.js +4 -1
- package/dist/cli/chat/settingsSelection.d.ts +33 -0
- package/dist/cli/chat/settingsSelection.js +46 -0
- package/dist/cli/chat/skillNotices.d.ts +18 -0
- package/dist/cli/chat/skillNotices.js +26 -0
- package/dist/cli/chat/startupInfo.js +1 -1
- package/dist/cli/chat/startupSequence.d.ts +2 -0
- package/dist/cli/chat/startupSequence.js +6 -0
- package/dist/cli/chat/submitPipeline.d.ts +8 -0
- package/dist/cli/chat/submitPipeline.js +141 -0
- package/dist/cli/chat/terminalControl.js +1 -1
- package/dist/cli/chat/toolSummaries.d.ts +29 -0
- package/dist/cli/chat/toolSummaries.js +268 -0
- package/dist/cli/chat/turnState.d.ts +8 -0
- package/dist/cli/chat/turnState.js +1 -0
- package/dist/cli/chat/userCommandFlow.d.ts +21 -0
- package/dist/cli/chat/userCommandFlow.js +66 -0
- package/dist/cli/chat/userCommandRunner.d.ts +14 -0
- package/dist/cli/chat/userCommandRunner.js +56 -0
- package/dist/cli/chat/wizard/providerHandlers.js +19 -2
- package/dist/cli/chat/wizardTrail.d.ts +22 -0
- package/dist/cli/chat/wizardTrail.js +55 -0
- package/dist/cli/commands/chat.d.ts +1 -13
- package/dist/cli/commands/chat.js +10 -795
- package/dist/cli/commands/commandHelp.js +11 -6
- package/dist/cli/commands/commandSuggest.d.ts +2 -0
- package/dist/cli/commands/commandSuggest.js +35 -0
- package/dist/cli/commands/commands.js +12 -3
- package/dist/cli/commands/formatters.d.ts +1 -23
- package/dist/cli/commands/formatters.js +3 -224
- package/dist/cli/commands/graphCommand.d.ts +2 -0
- package/dist/cli/commands/graphCommand.js +60 -0
- package/dist/cli/commands/initCommand.js +14 -0
- package/dist/cli/commands/modelCommand.js +11 -7
- package/dist/cli/commands/reasoningCommand.js +3 -3
- package/dist/cli/commands/runCommand.js +6 -2
- package/dist/cli/commands/streaming/agentAttempt.js +11 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
- package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
- package/dist/cli/commands/streaming/attemptSetup.js +34 -5
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
- package/dist/cli/commands/streaming/prepareStep.js +1 -0
- package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
- package/dist/cli/commands/streaming/stepProjection.js +54 -0
- package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
- package/dist/cli/commands/streaming/streamLoop.js +34 -23
- package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
- package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
- package/dist/cli/commands/streaming.d.ts +3 -1
- package/dist/cli/commands/streaming.js +5 -0
- package/dist/cli/commands/wizardFlow.d.ts +2 -0
- package/dist/cli/commands/wizardFlow.js +3 -0
- package/dist/cli/index.js +8 -4
- package/dist/cli/terminalTitle.js +9 -3
- package/dist/config/contextFiles.d.ts +2 -5
- package/dist/config/contextFiles.js +1 -1
- package/dist/config/inputHistory.js +2 -2
- package/dist/config/providerAuth.js +2 -2
- package/dist/config/providerModelFacts.js +5 -0
- package/dist/config/providerPresets.js +1 -1
- package/dist/config/settings.d.ts +7 -0
- package/dist/config/settings.js +9 -2
- package/dist/config/updateCheck.js +2 -2
- package/dist/core/agent/compaction.d.ts +1 -0
- package/dist/core/agent/compaction.js +3 -0
- package/dist/core/agent/completionController.d.ts +1 -1
- package/dist/core/agent/contextBudget.d.ts +1 -1
- package/dist/core/agent/goalPolicy.js +8 -2
- package/dist/core/agent/overflow.js +5 -0
- package/dist/core/agent/toolCapabilities.js +14 -0
- package/dist/core/agent/userCommands.d.ts +53 -0
- package/dist/core/agent/userCommands.js +116 -0
- package/dist/core/agent/workState.d.ts +3 -1
- package/dist/core/agent/workState.js +57 -26
- package/dist/core/contextFileTypes.d.ts +12 -0
- package/dist/core/contextFileTypes.js +1 -0
- package/dist/core/graph/analyze.d.ts +61 -0
- package/dist/core/graph/analyze.js +274 -0
- package/dist/core/graph/buildGraph.d.ts +44 -0
- package/dist/core/graph/buildGraph.js +290 -0
- package/dist/core/graph/digest.d.ts +2 -0
- package/dist/core/graph/digest.js +40 -0
- package/dist/core/graph/extract.d.ts +58 -0
- package/dist/core/graph/extract.js +394 -0
- package/dist/core/graph/model.d.ts +63 -0
- package/dist/core/graph/model.js +96 -0
- package/dist/core/graph/query.d.ts +69 -0
- package/dist/core/graph/query.js +391 -0
- package/dist/core/graph/store.d.ts +64 -0
- package/dist/core/graph/store.js +171 -0
- package/dist/core/limits.d.ts +2 -0
- package/dist/core/limits.js +2 -0
- package/dist/core/log/llmLog.js +2 -2
- package/dist/{config → core/persistence}/privateStorage.js +1 -1
- package/dist/core/process/runBoundedProcess.d.ts +7 -4
- package/dist/core/process/runBoundedProcess.js +22 -11
- package/dist/core/safety/redaction.d.ts +2 -0
- package/dist/core/safety/redaction.js +26 -5
- package/dist/core/safety/secretPaths.js +12 -3
- package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
- package/dist/core/safety/untrustedEnvelopes.js +17 -2
- package/dist/core/safety/urlGuard.js +2 -0
- package/dist/core/session/sessionStore.d.ts +8 -1
- package/dist/core/session/sessionStore.js +15 -4
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/types.d.ts +1 -1
- package/dist/core/subagent/executionProfiles.js +4 -4
- package/dist/core/tasks/taskStorage.js +11 -1
- package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +16 -8
- package/dist/llm/hazeTools.d.ts +2 -12426
- package/dist/llm/hazeTools.js +4 -0
- package/dist/llm/lsp/pool.js +1 -1
- package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
- package/dist/llm/lspTools.d.ts +3 -12622
- package/dist/llm/requestContext.d.ts +6 -0
- package/dist/llm/requestContext.js +28 -7
- package/dist/llm/subagentRunner.d.ts +2 -308
- package/dist/llm/systemPrompt.js +17 -7
- package/dist/llm/toolGroups.d.ts +534 -0
- package/dist/llm/toolGroups.js +57 -0
- package/dist/llm/tools/editMatch.d.ts +1 -1
- package/dist/llm/tools/failures.d.ts +1 -1
- package/dist/llm/tools/fetchTool.d.ts +2 -1221
- package/dist/llm/tools/fileToolShared.d.ts +1 -1
- package/dist/llm/tools/fileToolShared.js +1 -1
- package/dist/llm/tools/fileTools.d.ts +2 -7768
- package/dist/llm/tools/fileTools.js +1 -1
- package/dist/llm/tools/gitTools.d.ts +12 -0
- package/dist/llm/tools/gitTools.js +527 -0
- package/dist/llm/tools/graphAdvisory.d.ts +22 -0
- package/dist/llm/tools/graphAdvisory.js +68 -0
- package/dist/llm/tools/graphTools.d.ts +13 -0
- package/dist/llm/tools/graphTools.js +195 -0
- package/dist/llm/tools/processTool.d.ts +2 -1081
- package/dist/llm/tools/readRecovery.d.ts +1 -1
- package/dist/llm/tools/replaceInFiles.d.ts +1 -1
- package/dist/llm/tools/replaceInFiles.js +1 -1
- package/dist/llm/tools/shellTool.d.ts +2 -1513
- package/dist/llm/tools/storedOutputTool.d.ts +2 -355
- package/dist/llm/tools/taskTool.d.ts +2 -489
- package/dist/llm/tools/taskTool.js +4 -1
- package/dist/llm/tools/toolContext.js +29 -11
- package/dist/llm/tools/toolContextState.d.ts +4 -1
- package/dist/llm/tools/toolContextState.js +2 -1
- package/dist/llm/tools/workspaceFile.d.ts +2 -2
- package/dist/llm/tools/workspaceFile.js +10 -5
- package/dist/skills/SkillRegistry.js +1 -1
- package/dist/skills/builder/SkillBuilder.js +1 -1
- package/dist/skills/plugins/installer.js +1 -1
- package/dist/skills/plugins/runtime.js +1 -1
- package/dist/skills/skillTools.js +4 -1
- package/dist/ui/components/MarkdownText.d.ts +14 -0
- package/dist/ui/components/MarkdownText.js +77 -12
- package/dist/ui/components/NativeIndicators.js +5 -1
- package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
- package/dist/ui/components/StreamingMarkdownText.js +39 -11
- package/dist/ui/components/TextInput.d.ts +1 -2
- package/dist/ui/components/TextInput.js +79 -9
- package/dist/ui/components/WizardChoices.d.ts +1 -2
- package/dist/ui/components/useInputSuggestions.d.ts +1 -1
- package/dist/ui/components/useInputSuggestions.js +1 -1
- package/dist/ui/mentionDetection.d.ts +20 -0
- package/dist/ui/mentionDetection.js +24 -0
- package/dist/ui/terminalColors.d.ts +4 -4
- package/dist/ui/terminalColors.js +23 -6
- package/dist/ui/terminalSanitize.js +8 -3
- package/dist/ui/textGeometry.d.ts +2 -0
- package/dist/ui/textGeometry.js +6 -0
- package/dist/ui/themes/registry.js +33 -33
- package/dist/utils/openPath.js +7 -0
- package/package.json +22 -19
- /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
- /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
- /package/dist/{config → core}/paths.d.ts +0 -0
- /package/dist/{config → core}/paths.js +0 -0
- /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
- /package/dist/{llm → core}/toolResultTypes.js +0 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compact structure digest for compaction: a bounded, deterministic excerpt
|
|
3
|
+
* of the code graph (top hub symbols + community directory labels) handed to
|
|
4
|
+
* LLM-written compaction summaries so they reference named structure instead
|
|
5
|
+
* of re-describing it in prose. The graph itself persists across compaction —
|
|
6
|
+
* this only keeps its vocabulary alive in the summarized prefix.
|
|
7
|
+
*/
|
|
8
|
+
import { workspaceRoot } from '../../utils/path.js';
|
|
9
|
+
import { buildGraphIndex } from './model.js';
|
|
10
|
+
import { graphStoreFor, readGraph } from './store.js';
|
|
11
|
+
import { communitySummaries, godNodes } from './analyze.js';
|
|
12
|
+
const DIGEST_MAX_CHARS = 2_000;
|
|
13
|
+
/** Build the digest, or undefined when no graph exists / it cannot be read. Best-effort by contract. */
|
|
14
|
+
export async function buildCodeGraphDigest() {
|
|
15
|
+
try {
|
|
16
|
+
const graph = await readGraph(graphStoreFor(workspaceRoot()));
|
|
17
|
+
if (!graph || graph.nodes.length === 0)
|
|
18
|
+
return undefined;
|
|
19
|
+
const index = buildGraphIndex(graph);
|
|
20
|
+
const lines = [];
|
|
21
|
+
const gods = godNodes(index, 6);
|
|
22
|
+
if (gods.length > 0) {
|
|
23
|
+
lines.push('Hub symbols:');
|
|
24
|
+
for (const god of gods)
|
|
25
|
+
lines.push(`- ${god.label} (${god.kind}, ${god.file})`);
|
|
26
|
+
}
|
|
27
|
+
const communities = communitySummaries(index, 5).filter(community => community.size >= 10);
|
|
28
|
+
if (communities.length > 0) {
|
|
29
|
+
lines.push('Subsystems (communities):');
|
|
30
|
+
for (const community of communities) {
|
|
31
|
+
const members = community.members.slice(0, 3).map(member => member.label).join(', ');
|
|
32
|
+
lines.push(`- [${community.directories.join(', ') || 'misc'}] ${members}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return lines.length > 0 ? lines.slice(0, 20).join('\n').slice(0, DIGEST_MAX_CHARS) : undefined;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type GraphNodeKind } from './model.js';
|
|
2
|
+
export declare const EXTRACTOR_VERSION = 4;
|
|
3
|
+
/** Largest source file parsed; bigger files are reported as skipped instead. */
|
|
4
|
+
export declare const MAX_SOURCE_BYTES: number;
|
|
5
|
+
export declare function isGraphSupportedExtension(extension: string): boolean;
|
|
6
|
+
export interface ExtractedSymbol {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
kind: GraphNodeKind;
|
|
10
|
+
line: number;
|
|
11
|
+
/** Enclosing class name for methods/fields; absent on top-level symbols. */
|
|
12
|
+
owner?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ImportedBinding {
|
|
15
|
+
/** Name exported by the source module. */
|
|
16
|
+
importedName: string;
|
|
17
|
+
/** Local name after aliasing (`as`); equals importedName when not aliased. */
|
|
18
|
+
localName: string;
|
|
19
|
+
}
|
|
20
|
+
export interface FileImport {
|
|
21
|
+
/** Raw module specifier as written (./foo.js, ../bar, pkg). */
|
|
22
|
+
specifier: string;
|
|
23
|
+
line: number;
|
|
24
|
+
kind: 'import' | 'export-from' | 'require';
|
|
25
|
+
defaultImport?: string;
|
|
26
|
+
namespaceImport?: string;
|
|
27
|
+
bindings: ImportedBinding[];
|
|
28
|
+
}
|
|
29
|
+
export interface CallSite {
|
|
30
|
+
/** Called identifier, or property name for `this.method()` member calls. */
|
|
31
|
+
name: string;
|
|
32
|
+
line: number;
|
|
33
|
+
/** True for `this.x()` calls; resolvable only against the enclosing class. */
|
|
34
|
+
thisCall?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface HeritageEntry {
|
|
37
|
+
/** Superclass identifier as written. */
|
|
38
|
+
name: string;
|
|
39
|
+
line: number;
|
|
40
|
+
}
|
|
41
|
+
export interface FileExtraction {
|
|
42
|
+
version: number;
|
|
43
|
+
file: string;
|
|
44
|
+
symbols: ExtractedSymbol[];
|
|
45
|
+
imports: FileImport[];
|
|
46
|
+
calls: CallSite[];
|
|
47
|
+
heritage: HeritageEntry[];
|
|
48
|
+
/** Names exported for other files (declaration name or explicit export list). */
|
|
49
|
+
exports: string[];
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Extract one file's structure. `file` is the workspace-relative path used for
|
|
53
|
+
* node ids; `content` is the UTF-8 source. Throws on parser/grammar problems;
|
|
54
|
+
* syntax errors inside the source degrade gracefully (tree-sitter keeps
|
|
55
|
+
* parsing; partial results are still honest structure).
|
|
56
|
+
*/
|
|
57
|
+
export declare function extractFile(file: string, content: string): Promise<FileExtraction>;
|
|
58
|
+
export declare function contentHash(content: string): string;
|
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic per-file AST extraction via tree-sitter WASM (core runtime and
|
|
3
|
+
* js/ts/tsx/jsx grammars vendored under `assets/graph-grammars/`).
|
|
4
|
+
*
|
|
5
|
+
* Extraction is pure: one source file in, one {@link FileExtraction} out, no
|
|
6
|
+
* workspace access — so results are content-hash cacheable. Cross-file
|
|
7
|
+
* resolution (import targets, call/heritage endpoints) deliberately lives in
|
|
8
|
+
* `buildGraph.ts`, which sees the whole corpus.
|
|
9
|
+
*
|
|
10
|
+
* Bump {@link EXTRACTOR_VERSION} whenever node/edge derivation logic changes;
|
|
11
|
+
* the cache and the persisted graph both key off it.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { createHash } from 'node:crypto';
|
|
17
|
+
import { Language, Parser } from 'web-tree-sitter';
|
|
18
|
+
import { symbolNodeId } from './model.js';
|
|
19
|
+
export const EXTRACTOR_VERSION = 4;
|
|
20
|
+
/** Largest source file parsed; bigger files are reported as skipped instead. */
|
|
21
|
+
export const MAX_SOURCE_BYTES = 1024 * 1024;
|
|
22
|
+
/** The 0.27.x runtime exposes `Language` as a named export with a static `.load()`.
|
|
23
|
+
* 0.23.x attached it as `Parser.Language` post-init — no longer needed. */
|
|
24
|
+
function languageStatic() {
|
|
25
|
+
return Language;
|
|
26
|
+
}
|
|
27
|
+
let grammarsDir;
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the vendored grammar directory. Compiled output and source agree on
|
|
30
|
+
* depth (`<root>/dist/core/graph` and `<root>/src/core/graph` are both three
|
|
31
|
+
* levels below the package root), so one relative walk covers dev, tests, and
|
|
32
|
+
* the published package.
|
|
33
|
+
*/
|
|
34
|
+
function resolveGrammarsDir() {
|
|
35
|
+
if (grammarsDir)
|
|
36
|
+
return grammarsDir;
|
|
37
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
38
|
+
const vendored = path.resolve(here, '../../../assets/graph-grammars');
|
|
39
|
+
grammarsDir = fs.existsSync(path.join(vendored, 'tree-sitter-typescript.wasm'))
|
|
40
|
+
? vendored
|
|
41
|
+
: path.dirname(require.resolve('web-tree-sitter/tree-sitter.wasm'));
|
|
42
|
+
return grammarsDir;
|
|
43
|
+
}
|
|
44
|
+
let parserInit;
|
|
45
|
+
const loadedLanguages = new Map();
|
|
46
|
+
const parsers = new Map();
|
|
47
|
+
const GRAMMAR_BY_EXTENSION = {
|
|
48
|
+
'.ts': 'tree-sitter-typescript.wasm',
|
|
49
|
+
'.mts': 'tree-sitter-typescript.wasm',
|
|
50
|
+
'.cts': 'tree-sitter-typescript.wasm',
|
|
51
|
+
'.tsx': 'tree-sitter-tsx.wasm',
|
|
52
|
+
'.js': 'tree-sitter-javascript.wasm',
|
|
53
|
+
'.jsx': 'tree-sitter-tsx.wasm',
|
|
54
|
+
'.mjs': 'tree-sitter-javascript.wasm',
|
|
55
|
+
'.cjs': 'tree-sitter-javascript.wasm',
|
|
56
|
+
};
|
|
57
|
+
export function isGraphSupportedExtension(extension) {
|
|
58
|
+
return extension in GRAMMAR_BY_EXTENSION;
|
|
59
|
+
}
|
|
60
|
+
async function parserFor(extension) {
|
|
61
|
+
if (!(extension in GRAMMAR_BY_EXTENSION))
|
|
62
|
+
throw new Error(`No graph grammar for ${extension}`);
|
|
63
|
+
let parser = parsers.get(extension);
|
|
64
|
+
if (!parser) {
|
|
65
|
+
parser = (async () => {
|
|
66
|
+
parserInit ??= (async () => {
|
|
67
|
+
const dir = resolveGrammarsDir();
|
|
68
|
+
const coreWasm = path.join(dir, 'web-tree-sitter.wasm');
|
|
69
|
+
await Parser.init(fs.existsSync(coreWasm) ? { locateFile: () => coreWasm } : undefined);
|
|
70
|
+
})();
|
|
71
|
+
await parserInit;
|
|
72
|
+
const grammar = GRAMMAR_BY_EXTENSION[extension];
|
|
73
|
+
const wasmPath = path.join(resolveGrammarsDir(), grammar);
|
|
74
|
+
if (!fs.existsSync(wasmPath))
|
|
75
|
+
throw new Error(`Grammar ${grammar} is not available at ${wasmPath}`);
|
|
76
|
+
let language = loadedLanguages.get(grammar);
|
|
77
|
+
if (!language) {
|
|
78
|
+
language = languageStatic().load(wasmPath);
|
|
79
|
+
loadedLanguages.set(grammar, language);
|
|
80
|
+
}
|
|
81
|
+
const parserInstance = new Parser();
|
|
82
|
+
parserInstance.setLanguage(await language);
|
|
83
|
+
return parserInstance;
|
|
84
|
+
})();
|
|
85
|
+
parsers.set(extension, parser);
|
|
86
|
+
}
|
|
87
|
+
return parser;
|
|
88
|
+
}
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
// Tree walks
|
|
91
|
+
// ---------------------------------------------------------------------------
|
|
92
|
+
const KIND_BY_NODE_TYPE = {
|
|
93
|
+
function_declaration: 'function',
|
|
94
|
+
generator_function_declaration: 'function',
|
|
95
|
+
function_signature: 'function',
|
|
96
|
+
method_definition: 'method',
|
|
97
|
+
method_signature: 'method',
|
|
98
|
+
abstract_method_signature: 'method',
|
|
99
|
+
class_declaration: 'class',
|
|
100
|
+
abstract_class_declaration: 'class',
|
|
101
|
+
interface_declaration: 'type',
|
|
102
|
+
type_alias_declaration: 'type',
|
|
103
|
+
enum_declaration: 'type',
|
|
104
|
+
};
|
|
105
|
+
function identifierText(node) {
|
|
106
|
+
return node && (node.type === 'identifier' || node.type === 'type_identifier') ? node.text : undefined;
|
|
107
|
+
}
|
|
108
|
+
/** Method/property names arrive as `property_identifier`, declarations as identifier/type_identifier. */
|
|
109
|
+
function definitionNameText(node) {
|
|
110
|
+
return node && (node.type === 'identifier' || node.type === 'type_identifier' || node.type === 'property_identifier') ? node.text : undefined;
|
|
111
|
+
}
|
|
112
|
+
function propertyName(nameNode) {
|
|
113
|
+
if (nameNode.type === 'identifier' || nameNode.type === 'property_identifier')
|
|
114
|
+
return nameNode.text;
|
|
115
|
+
if (nameNode.type === 'computed_property_name') {
|
|
116
|
+
const inner = nameNode.namedChildren[0];
|
|
117
|
+
return inner?.text || undefined;
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
/** Best-effort enclosing class name by walking parent links. */
|
|
122
|
+
function enclosingClassName(node) {
|
|
123
|
+
let current = node;
|
|
124
|
+
while (current) {
|
|
125
|
+
if (current.type === 'class_declaration' || current.type === 'abstract_class_declaration' || current.type === 'class_expression') {
|
|
126
|
+
const name = identifierText(current.childForFieldName('name'));
|
|
127
|
+
if (name)
|
|
128
|
+
return name;
|
|
129
|
+
}
|
|
130
|
+
current = current.parent ?? null;
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Declarators whose value is a non-trivial expression become symbols:
|
|
136
|
+
* functions for arrow/function values (callable), fields for object/array/
|
|
137
|
+
* call/new values (`export const hazeTools = {...}` names a real API
|
|
138
|
+
* surface). Primitive literals and plain identifiers stay out.
|
|
139
|
+
*
|
|
140
|
+
* Node wrappers are recreated per access, so the name child is identified by
|
|
141
|
+
* its stable `.id`, never by reference equality.
|
|
142
|
+
*/
|
|
143
|
+
const VALUED_DECLARATOR_TYPES = new Set(['arrow_function', 'function_expression', 'object', 'array', 'new_expression', 'call_expression']);
|
|
144
|
+
function declaratorValueKind(declarator) {
|
|
145
|
+
const name = declarator.childForFieldName('name');
|
|
146
|
+
const nameId = name?.id;
|
|
147
|
+
for (const child of declarator.namedChildren) {
|
|
148
|
+
if (child.id === nameId)
|
|
149
|
+
continue;
|
|
150
|
+
// A type annotation (`const x: SomeType = {...}`) sits between the name
|
|
151
|
+
// and the value; skip it so typed declarators still yield their symbol.
|
|
152
|
+
if (child.type === 'type_annotation')
|
|
153
|
+
continue;
|
|
154
|
+
if (child.type === 'arrow_function' || child.type === 'function_expression')
|
|
155
|
+
return 'function';
|
|
156
|
+
if (VALUED_DECLARATOR_TYPES.has(child.type))
|
|
157
|
+
return 'field';
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
function collectDefinitions(root) {
|
|
163
|
+
const definitions = [];
|
|
164
|
+
const walk = (node, owner) => {
|
|
165
|
+
const type = node.type;
|
|
166
|
+
const mapped = KIND_BY_NODE_TYPE[type];
|
|
167
|
+
if (mapped) {
|
|
168
|
+
const name = definitionNameText(node.childForFieldName('name'));
|
|
169
|
+
if (name) {
|
|
170
|
+
definitions.push({ name, kind: mapped, line: node.startPosition.row + 1, ...(owner ? { owner } : {}) });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else if (type === 'public_field_definition' || type === 'field_definition') {
|
|
174
|
+
const name = propertyName(node.childForFieldName('name') ?? node.namedChildren[0] ?? node);
|
|
175
|
+
if (name)
|
|
176
|
+
definitions.push({ name, kind: 'field', line: node.startPosition.row + 1, owner: owner ?? enclosingClassName(node) ?? undefined });
|
|
177
|
+
}
|
|
178
|
+
else if (type === 'property_signature') {
|
|
179
|
+
// Interface members are real API surface; anonymous type-literal
|
|
180
|
+
// properties inside expressions are noise and stay out.
|
|
181
|
+
if (node.parent?.type === 'object_type' && node.parent.parent?.type === 'interface_declaration') {
|
|
182
|
+
const name = propertyName(node.childForFieldName('name') ?? node.namedChildren[0] ?? node);
|
|
183
|
+
if (name)
|
|
184
|
+
definitions.push({ name, kind: 'field', line: node.startPosition.row + 1, owner: owner ?? enclosingClassName(node) ?? undefined });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else if (type === 'variable_declarator') {
|
|
188
|
+
const name = identifierText(node.childForFieldName('name'));
|
|
189
|
+
const valueKind = name ? declaratorValueKind(node) : undefined;
|
|
190
|
+
if (name && valueKind)
|
|
191
|
+
definitions.push({ name, kind: valueKind, line: node.startPosition.row + 1 });
|
|
192
|
+
}
|
|
193
|
+
const childOwner = type === 'class_declaration' || type === 'abstract_class_declaration'
|
|
194
|
+
? identifierText(node.childForFieldName('name')) ?? owner
|
|
195
|
+
: owner;
|
|
196
|
+
for (const child of node.namedChildren)
|
|
197
|
+
walk(child, childOwner);
|
|
198
|
+
};
|
|
199
|
+
walk(root, undefined);
|
|
200
|
+
return definitions;
|
|
201
|
+
}
|
|
202
|
+
function collectImports(root) {
|
|
203
|
+
const imports = [];
|
|
204
|
+
const specifierOf = (source) => source.text.replace(/^['"]|['"]$/g, '');
|
|
205
|
+
const visit = (node) => {
|
|
206
|
+
if (node.type === 'import_statement') {
|
|
207
|
+
const source = node.childForFieldName('source');
|
|
208
|
+
if (source) {
|
|
209
|
+
const entry = { specifier: specifierOf(source), line: source.startPosition.row + 1, kind: 'import', bindings: [] };
|
|
210
|
+
// The grammar exposes `source` as a field but the clause is a plain named child.
|
|
211
|
+
const clause = node.namedChildren.find(child => child.type === 'import_clause');
|
|
212
|
+
if (clause) {
|
|
213
|
+
for (const part of clause.namedChildren) {
|
|
214
|
+
if (part.type === 'named_imports') {
|
|
215
|
+
for (const spec of part.namedChildren) {
|
|
216
|
+
if (spec.type !== 'import_specifier')
|
|
217
|
+
continue;
|
|
218
|
+
const imported = spec.childForFieldName('name');
|
|
219
|
+
const alias = spec.childForFieldName('alias');
|
|
220
|
+
const importedName = imported ? imported.text : '';
|
|
221
|
+
if (importedName)
|
|
222
|
+
entry.bindings.push({ importedName, localName: alias ? alias.text : importedName });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
else if (part.type === 'identifier') {
|
|
226
|
+
entry.defaultImport = part.text;
|
|
227
|
+
}
|
|
228
|
+
else if (part.type === 'namespace_import') {
|
|
229
|
+
const alias = part.namedChildren.find(child => child.type === 'identifier');
|
|
230
|
+
if (alias)
|
|
231
|
+
entry.namespaceImport = alias.text;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
imports.push(entry);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else if (node.type === 'export_statement') {
|
|
239
|
+
const source = node.childForFieldName('source');
|
|
240
|
+
if (source) {
|
|
241
|
+
const entry = { specifier: specifierOf(source), line: source.startPosition.row + 1, kind: 'export-from', bindings: [] };
|
|
242
|
+
const clause = node.namedChildren.find(child => child.type === 'export_clause');
|
|
243
|
+
if (clause) {
|
|
244
|
+
for (const spec of clause.namedChildren) {
|
|
245
|
+
if (spec.type !== 'export_specifier')
|
|
246
|
+
continue;
|
|
247
|
+
const name = spec.childForFieldName('name');
|
|
248
|
+
const alias = spec.childForFieldName('alias');
|
|
249
|
+
const importedName = name ? name.text : '';
|
|
250
|
+
if (importedName)
|
|
251
|
+
entry.bindings.push({ importedName, localName: alias ? alias.text : importedName });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
imports.push(entry);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
for (const child of node.namedChildren)
|
|
258
|
+
visit(child);
|
|
259
|
+
};
|
|
260
|
+
visit(root);
|
|
261
|
+
return imports;
|
|
262
|
+
}
|
|
263
|
+
function collectCalls(root) {
|
|
264
|
+
const calls = [];
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
const visit = (node) => {
|
|
267
|
+
if (node.type === 'call_expression') {
|
|
268
|
+
const func = node.childForFieldName('function');
|
|
269
|
+
const record = (name, thisCall = false) => {
|
|
270
|
+
const key = `${name}:${node.startPosition.row + 1}:${thisCall}`;
|
|
271
|
+
if (!seen.has(key)) {
|
|
272
|
+
seen.add(key);
|
|
273
|
+
calls.push({ name, line: node.startPosition.row + 1, ...(thisCall ? { thisCall: true } : {}) });
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
if (func?.type === 'identifier') {
|
|
277
|
+
record(func.text);
|
|
278
|
+
}
|
|
279
|
+
else if (func?.type === 'member_expression') {
|
|
280
|
+
const object = func.childForFieldName('object');
|
|
281
|
+
const property = func.childForFieldName('property');
|
|
282
|
+
if (object?.type === 'this' && property?.type === 'property_identifier') {
|
|
283
|
+
record(property.text, true);
|
|
284
|
+
}
|
|
285
|
+
// Other member calls (obj.method()) stay unresolved on purpose:
|
|
286
|
+
// binding receivers to types from AST alone is guesswork, and a wrong
|
|
287
|
+
// calls edge costs more than a missing one.
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
for (const child of node.namedChildren)
|
|
291
|
+
visit(child);
|
|
292
|
+
};
|
|
293
|
+
visit(root);
|
|
294
|
+
return calls;
|
|
295
|
+
}
|
|
296
|
+
function collectHeritage(root) {
|
|
297
|
+
const heritage = [];
|
|
298
|
+
const visit = (node) => {
|
|
299
|
+
if (node.type === 'extends_clause') {
|
|
300
|
+
const value = node.childForFieldName('value');
|
|
301
|
+
// `class A extends B` names B as a type_identifier; `extends expr()` stays out.
|
|
302
|
+
const name = value && (value.type === 'identifier' || value.type === 'type_identifier') ? value.text : undefined;
|
|
303
|
+
if (name)
|
|
304
|
+
heritage.push({ name, line: node.startPosition.row + 1 });
|
|
305
|
+
}
|
|
306
|
+
for (const child of node.namedChildren)
|
|
307
|
+
visit(child);
|
|
308
|
+
};
|
|
309
|
+
visit(root);
|
|
310
|
+
return heritage;
|
|
311
|
+
}
|
|
312
|
+
function collectExports(root, localNames) {
|
|
313
|
+
const exportNames = new Set();
|
|
314
|
+
const visit = (node) => {
|
|
315
|
+
if (node.type === 'export_statement') {
|
|
316
|
+
const declaration = node.childForFieldName('declaration');
|
|
317
|
+
const isDefault = node.text.startsWith('export default');
|
|
318
|
+
if (declaration) {
|
|
319
|
+
const nameNode = declaration.childForFieldName('name') ?? declaration.namedChildren[0];
|
|
320
|
+
const name = identifierText(nameNode) ?? (nameNode ? propertyName(nameNode) : undefined);
|
|
321
|
+
if (name)
|
|
322
|
+
exportNames.add(name);
|
|
323
|
+
if (declaration.type === 'lexical_declaration' || declaration.type === 'variable_declaration') {
|
|
324
|
+
for (const declarator of declaration.namedChildren) {
|
|
325
|
+
const declaratorName = identifierText(declarator.childForFieldName('name'));
|
|
326
|
+
if (declaratorName)
|
|
327
|
+
exportNames.add(declaratorName);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else if (isDefault) {
|
|
332
|
+
const target = node.namedChildren.find(child => child.type === 'identifier');
|
|
333
|
+
if (target)
|
|
334
|
+
exportNames.add(target.text);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
const clause = node.namedChildren.find(child => child.type === 'export_clause');
|
|
338
|
+
if (clause) {
|
|
339
|
+
for (const spec of clause.namedChildren) {
|
|
340
|
+
if (spec.type !== 'export_specifier')
|
|
341
|
+
continue;
|
|
342
|
+
const original = spec.childForFieldName('name');
|
|
343
|
+
// `export { a as default }` also satisfies a default import of a.
|
|
344
|
+
if (original && localNames.has(original.text))
|
|
345
|
+
exportNames.add(original.text);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
for (const child of node.namedChildren)
|
|
351
|
+
visit(child);
|
|
352
|
+
};
|
|
353
|
+
visit(root);
|
|
354
|
+
return [...exportNames];
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Extract one file's structure. `file` is the workspace-relative path used for
|
|
358
|
+
* node ids; `content` is the UTF-8 source. Throws on parser/grammar problems;
|
|
359
|
+
* syntax errors inside the source degrade gracefully (tree-sitter keeps
|
|
360
|
+
* parsing; partial results are still honest structure).
|
|
361
|
+
*/
|
|
362
|
+
export async function extractFile(file, content) {
|
|
363
|
+
const extension = path.extname(file).toLowerCase();
|
|
364
|
+
const parser = await parserFor(extension);
|
|
365
|
+
const treeRaw = parser.parse(content);
|
|
366
|
+
const tree = treeRaw ?? parser.parse('');
|
|
367
|
+
try {
|
|
368
|
+
const root = tree.rootNode;
|
|
369
|
+
const definitions = collectDefinitions(root);
|
|
370
|
+
const taken = new Set([file]);
|
|
371
|
+
const symbols = definitions.map(def => ({
|
|
372
|
+
id: symbolNodeId(file, def.name, def.line, taken),
|
|
373
|
+
name: def.name,
|
|
374
|
+
kind: def.kind,
|
|
375
|
+
line: def.line,
|
|
376
|
+
...(def.owner ? { owner: def.owner } : {}),
|
|
377
|
+
}));
|
|
378
|
+
return {
|
|
379
|
+
version: EXTRACTOR_VERSION,
|
|
380
|
+
file,
|
|
381
|
+
symbols,
|
|
382
|
+
imports: collectImports(root),
|
|
383
|
+
calls: collectCalls(root),
|
|
384
|
+
heritage: collectHeritage(root),
|
|
385
|
+
exports: collectExports(root, new Set(definitions.map(def => def.name))),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
finally {
|
|
389
|
+
tree.delete();
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
export function contentHash(content) {
|
|
393
|
+
return createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 32);
|
|
394
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code-graph data model: the persisted graph JSON shape, the in-memory index
|
|
3
|
+
* built from it, and the workspace-keyed store layout contract shared by
|
|
4
|
+
* extraction, build, and query.
|
|
5
|
+
*
|
|
6
|
+
* Nodes are files and the symbols they define; edges carry a relation and an
|
|
7
|
+
* honest confidence label (`EXTRACTED` for relationships explicit in the
|
|
8
|
+
* source, `INFERRED` for relationships resolved across files). The persisted
|
|
9
|
+
* `schemaVersion` lets future extractors detect incompatible graphs, mirroring
|
|
10
|
+
* the signature-validated sparse indexes used for exact readFile paging.
|
|
11
|
+
*/
|
|
12
|
+
export declare const GRAPH_SCHEMA_VERSION = 1;
|
|
13
|
+
export type GraphNodeKind = 'file' | 'function' | 'class' | 'method' | 'type' | 'field';
|
|
14
|
+
export type GraphEdgeRelation = 'defines' | 'imports' | 'calls' | 'inherits' | 'references';
|
|
15
|
+
/** How trustworthy an edge is; surfaces in tool output so the model can weigh it. */
|
|
16
|
+
export type GraphConfidence = 'EXTRACTED' | 'INFERRED';
|
|
17
|
+
export interface GraphNode {
|
|
18
|
+
/** Deterministic id: the workspace-relative file path for files, `path#name` (plus `@line` on duplicates) for symbols. */
|
|
19
|
+
id: string;
|
|
20
|
+
label: string;
|
|
21
|
+
kind: GraphNodeKind;
|
|
22
|
+
/** Workspace-relative source file. */
|
|
23
|
+
file: string;
|
|
24
|
+
/** 1-based definition line. */
|
|
25
|
+
line: number;
|
|
26
|
+
/** Community id assigned by label propagation; absent before analysis runs. */
|
|
27
|
+
community?: number;
|
|
28
|
+
}
|
|
29
|
+
export interface GraphEdge {
|
|
30
|
+
source: string;
|
|
31
|
+
target: string;
|
|
32
|
+
relation: GraphEdgeRelation;
|
|
33
|
+
confidence: GraphConfidence;
|
|
34
|
+
/** Workspace-relative file where the relationship site lives (the import/call line, not the definition). */
|
|
35
|
+
file?: string;
|
|
36
|
+
/** 1-based line of the relationship site. */
|
|
37
|
+
line?: number;
|
|
38
|
+
}
|
|
39
|
+
/** The persisted graph document written under `~/.haze/graphs/<workspace>/graph.json`. */
|
|
40
|
+
export interface CodeGraph {
|
|
41
|
+
schemaVersion: number;
|
|
42
|
+
extractorVersion: number;
|
|
43
|
+
builtAt: string;
|
|
44
|
+
fileCount: number;
|
|
45
|
+
nodes: GraphNode[];
|
|
46
|
+
edges: GraphEdge[];
|
|
47
|
+
}
|
|
48
|
+
/** Adjacency index over a {@link CodeGraph}; the query/analysis read surface. */
|
|
49
|
+
export interface GraphIndex {
|
|
50
|
+
graph: CodeGraph;
|
|
51
|
+
nodes: Map<string, GraphNode>;
|
|
52
|
+
out: Map<string, GraphEdge[]>;
|
|
53
|
+
in: Map<string, GraphEdge[]>;
|
|
54
|
+
degree: Map<string, number>;
|
|
55
|
+
/** Lowercased symbol label -> node ids (files excluded; symbol lookup only). */
|
|
56
|
+
labels: Map<string, string[]>;
|
|
57
|
+
}
|
|
58
|
+
export declare function buildGraphIndex(graph: CodeGraph): GraphIndex;
|
|
59
|
+
export declare function nodeDegree(index: GraphIndex, id: string): number;
|
|
60
|
+
/** Stable symbol-id construction; `path#name`, disambiguated by line on duplicates. */
|
|
61
|
+
export declare function symbolNodeId(file: string, name: string, line: number, taken: Set<string>): string;
|
|
62
|
+
/** Parse and validate a graph document read from disk. Throws on unknown schema versions. */
|
|
63
|
+
export declare function parseCodeGraph(value: unknown): CodeGraph;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code-graph data model: the persisted graph JSON shape, the in-memory index
|
|
3
|
+
* built from it, and the workspace-keyed store layout contract shared by
|
|
4
|
+
* extraction, build, and query.
|
|
5
|
+
*
|
|
6
|
+
* Nodes are files and the symbols they define; edges carry a relation and an
|
|
7
|
+
* honest confidence label (`EXTRACTED` for relationships explicit in the
|
|
8
|
+
* source, `INFERRED` for relationships resolved across files). The persisted
|
|
9
|
+
* `schemaVersion` lets future extractors detect incompatible graphs, mirroring
|
|
10
|
+
* the signature-validated sparse indexes used for exact readFile paging.
|
|
11
|
+
*/
|
|
12
|
+
export const GRAPH_SCHEMA_VERSION = 1;
|
|
13
|
+
export function buildGraphIndex(graph) {
|
|
14
|
+
const nodes = new Map();
|
|
15
|
+
const out = new Map();
|
|
16
|
+
const inn = new Map();
|
|
17
|
+
const degree = new Map();
|
|
18
|
+
const labels = new Map();
|
|
19
|
+
for (const node of graph.nodes) {
|
|
20
|
+
nodes.set(node.id, node);
|
|
21
|
+
if (node.kind !== 'file') {
|
|
22
|
+
const key = node.label.toLowerCase();
|
|
23
|
+
const bucket = labels.get(key);
|
|
24
|
+
if (bucket)
|
|
25
|
+
bucket.push(node.id);
|
|
26
|
+
else
|
|
27
|
+
labels.set(key, [node.id]);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
for (const edge of graph.edges) {
|
|
31
|
+
if (!nodes.has(edge.source) || !nodes.has(edge.target))
|
|
32
|
+
continue;
|
|
33
|
+
let outBucket = out.get(edge.source);
|
|
34
|
+
if (!outBucket) {
|
|
35
|
+
outBucket = [];
|
|
36
|
+
out.set(edge.source, outBucket);
|
|
37
|
+
}
|
|
38
|
+
outBucket.push(edge);
|
|
39
|
+
let inBucket = inn.get(edge.target);
|
|
40
|
+
if (!inBucket) {
|
|
41
|
+
inBucket = [];
|
|
42
|
+
inn.set(edge.target, inBucket);
|
|
43
|
+
}
|
|
44
|
+
inBucket.push(edge);
|
|
45
|
+
degree.set(edge.source, (degree.get(edge.source) ?? 0) + 1);
|
|
46
|
+
degree.set(edge.target, (degree.get(edge.target) ?? 0) + 1);
|
|
47
|
+
}
|
|
48
|
+
return { graph, nodes, out, in: inn, degree, labels };
|
|
49
|
+
}
|
|
50
|
+
export function nodeDegree(index, id) {
|
|
51
|
+
return index.degree.get(id) ?? 0;
|
|
52
|
+
}
|
|
53
|
+
/** Stable symbol-id construction; `path#name`, disambiguated by line on duplicates. */
|
|
54
|
+
export function symbolNodeId(file, name, line, taken) {
|
|
55
|
+
let id = `${file}#${name}`;
|
|
56
|
+
if (!taken.has(id)) {
|
|
57
|
+
taken.add(id);
|
|
58
|
+
return id;
|
|
59
|
+
}
|
|
60
|
+
id = `${file}#${name}@${line}`;
|
|
61
|
+
// Duplicate names at one line are pathological; keep appending until free.
|
|
62
|
+
let suffix = 0;
|
|
63
|
+
while (taken.has(id)) {
|
|
64
|
+
suffix += 1;
|
|
65
|
+
id = `${file}#${name}@${line}-${suffix}`;
|
|
66
|
+
}
|
|
67
|
+
taken.add(id);
|
|
68
|
+
return id;
|
|
69
|
+
}
|
|
70
|
+
/** Parse and validate a graph document read from disk. Throws on unknown schema versions. */
|
|
71
|
+
export function parseCodeGraph(value) {
|
|
72
|
+
if (typeof value !== 'object' || value == null)
|
|
73
|
+
throw new Error('graph.json is not an object');
|
|
74
|
+
const data = value;
|
|
75
|
+
const schemaVersion = data.schemaVersion;
|
|
76
|
+
if (typeof schemaVersion !== 'number' || schemaVersion > GRAPH_SCHEMA_VERSION) {
|
|
77
|
+
throw new Error(`graph.json schema version ${String(schemaVersion)} is newer than supported ${GRAPH_SCHEMA_VERSION}; rebuild the graph`);
|
|
78
|
+
}
|
|
79
|
+
const nodes = Array.isArray(data.nodes) ? data.nodes : [];
|
|
80
|
+
const edges = Array.isArray(data.edges) ? data.edges : [];
|
|
81
|
+
const validNodes = nodes.filter((node) => typeof node === 'object' && node != null
|
|
82
|
+
&& typeof node.id === 'string'
|
|
83
|
+
&& typeof node.label === 'string'
|
|
84
|
+
&& typeof node.file === 'string');
|
|
85
|
+
const validEdges = edges.filter((edge) => typeof edge === 'object' && edge != null
|
|
86
|
+
&& typeof edge.source === 'string'
|
|
87
|
+
&& typeof edge.target === 'string');
|
|
88
|
+
return {
|
|
89
|
+
schemaVersion: GRAPH_SCHEMA_VERSION,
|
|
90
|
+
extractorVersion: typeof data.extractorVersion === 'number' ? data.extractorVersion : 0,
|
|
91
|
+
builtAt: typeof data.builtAt === 'string' ? data.builtAt : new Date(0).toISOString(),
|
|
92
|
+
fileCount: typeof data.fileCount === 'number' ? data.fileCount : validNodes.filter(node => node.kind === 'file').length,
|
|
93
|
+
nodes: validNodes,
|
|
94
|
+
edges: validEdges,
|
|
95
|
+
};
|
|
96
|
+
}
|