@daogee/mdgraph 1.0.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 +25 -0
- package/LICENSE +21 -0
- package/README-ZH.md +203 -0
- package/README.md +203 -0
- package/agent-pack/README.md +26 -0
- package/agent-pack/host-examples.md +71 -0
- package/agent-pack/mcp-config.example.json +14 -0
- package/agent-pack/mdgraph-agent-instructions.md +21 -0
- package/agent-pack/prompts/relationship-trace.md +12 -0
- package/agent-pack/prompts/status-doctor.md +13 -0
- package/agent-pack/prompts/task-start-context.md +15 -0
- package/dist/analysis/doctor-scope.d.ts +8 -0
- package/dist/analysis/doctor-scope.js +109 -0
- package/dist/analysis/doctor.d.ts +148 -0
- package/dist/analysis/doctor.js +919 -0
- package/dist/analysis/status-freshness.d.ts +13 -0
- package/dist/analysis/status-freshness.js +55 -0
- package/dist/benchmark/benchmark.d.ts +118 -0
- package/dist/benchmark/benchmark.js +357 -0
- package/dist/bin/mdgraph.d.ts +2 -0
- package/dist/bin/mdgraph.js +877 -0
- package/dist/bundle/bundle.d.ts +66 -0
- package/dist/bundle/bundle.js +320 -0
- package/dist/config/limits.d.ts +24 -0
- package/dist/config/limits.js +24 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +177 -0
- package/dist/db/connection.d.ts +15 -0
- package/dist/db/connection.js +145 -0
- package/dist/db/repositories.d.ts +159 -0
- package/dist/db/repositories.js +929 -0
- package/dist/db/schema.sql +110 -0
- package/dist/db/sqlite-adapter.d.ts +18 -0
- package/dist/db/sqlite-adapter.js +60 -0
- package/dist/diff/graph-diff.d.ts +41 -0
- package/dist/diff/graph-diff.js +334 -0
- package/dist/evaluation/retrieval-eval.d.ts +115 -0
- package/dist/evaluation/retrieval-eval.js +399 -0
- package/dist/export/diagram.d.ts +11 -0
- package/dist/export/diagram.js +41 -0
- package/dist/export/graphjson.d.ts +89 -0
- package/dist/export/graphjson.js +299 -0
- package/dist/export/markdown-index.d.ts +21 -0
- package/dist/export/markdown-index.js +89 -0
- package/dist/export/source-bridge.d.ts +22 -0
- package/dist/export/source-bridge.js +83 -0
- package/dist/extraction/entity-extractor.d.ts +12 -0
- package/dist/extraction/entity-extractor.js +153 -0
- package/dist/extraction/graph-builder.d.ts +2 -0
- package/dist/extraction/graph-builder.js +168 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +28 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +100 -0
- package/dist/mcp/debug.d.ts +7 -0
- package/dist/mcp/debug.js +41 -0
- package/dist/mcp/server-instructions.d.ts +2 -0
- package/dist/mcp/server-instructions.js +40 -0
- package/dist/mcp/server.d.ts +28 -0
- package/dist/mcp/server.js +232 -0
- package/dist/mcp/tools.d.ts +31 -0
- package/dist/mcp/tools.js +506 -0
- package/dist/mcp/transport.d.ts +50 -0
- package/dist/mcp/transport.js +88 -0
- package/dist/parser/frontmatter.d.ts +10 -0
- package/dist/parser/frontmatter.js +191 -0
- package/dist/parser/links.d.ts +6 -0
- package/dist/parser/links.js +9 -0
- package/dist/parser/markdown-parser.d.ts +2 -0
- package/dist/parser/markdown-parser.js +267 -0
- package/dist/query/context-builder.d.ts +85 -0
- package/dist/query/context-builder.js +413 -0
- package/dist/query/search.d.ts +32 -0
- package/dist/query/search.js +237 -0
- package/dist/query/trace.d.ts +10 -0
- package/dist/query/trace.js +55 -0
- package/dist/reporting/report.d.ts +49 -0
- package/dist/reporting/report.js +143 -0
- package/dist/resolution/link-resolver.d.ts +17 -0
- package/dist/resolution/link-resolver.js +113 -0
- package/dist/scanner/file-scanner.d.ts +4 -0
- package/dist/scanner/file-scanner.js +144 -0
- package/dist/semantic/local-embedding.d.ts +4 -0
- package/dist/semantic/local-embedding.js +30 -0
- package/dist/semantic/status.d.ts +19 -0
- package/dist/semantic/status.js +70 -0
- package/dist/semantic/vector-codec.d.ts +3 -0
- package/dist/semantic/vector-codec.js +35 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +15 -0
- package/dist/utils/bounded-json.d.ts +9 -0
- package/dist/utils/bounded-json.js +57 -0
- package/dist/utils/content-risk.d.ts +5 -0
- package/dist/utils/content-risk.js +20 -0
- package/dist/utils/fts.d.ts +3 -0
- package/dist/utils/fts.js +52 -0
- package/dist/utils/id.d.ts +2 -0
- package/dist/utils/id.js +8 -0
- package/dist/utils/path-safety.d.ts +4 -0
- package/dist/utils/path-safety.js +25 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.js +36 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +11 -0
- package/dist/watcher/file-watcher.d.ts +11 -0
- package/dist/watcher/file-watcher.js +127 -0
- package/docs/EN/Agent_Integration.md +129 -0
- package/docs/EN/Architecture.md +135 -0
- package/docs/EN/Evaluation_Questions.md +68 -0
- package/docs/EN/Output_Contracts.md +274 -0
- package/docs/EN/Public_Contracts.md +88 -0
- package/docs/EN/Public_Contracts_1.0.md +234 -0
- package/docs/EN/Release_Checklist.md +82 -0
- package/docs/ZH/Agent_Integration.md +105 -0
- package/docs/ZH/Architecture.md +124 -0
- package/docs/ZH/Evaluation_Questions.md +66 -0
- package/docs/ZH/Output_Contracts.md +269 -0
- package/docs/ZH/Public_Contracts.md +81 -0
- package/docs/ZH/Public_Contracts_1.0.md +202 -0
- package/docs/ZH/Release_Checklist.md +83 -0
- package/package.json +94 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export function encodeFloat32Vector(vector) {
|
|
2
|
+
const buffer = Buffer.allocUnsafe(vector.length * Float32Array.BYTES_PER_ELEMENT);
|
|
3
|
+
vector.forEach((value, index) => {
|
|
4
|
+
buffer.writeFloatLE(value, index * Float32Array.BYTES_PER_ELEMENT);
|
|
5
|
+
});
|
|
6
|
+
return buffer;
|
|
7
|
+
}
|
|
8
|
+
export function decodeFloat32Vector(value) {
|
|
9
|
+
const bytes = bytesFromBlob(value);
|
|
10
|
+
if (!bytes.length || bytes.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
const result = [];
|
|
14
|
+
for (let offset = 0; offset < bytes.byteLength; offset += Float32Array.BYTES_PER_ELEMENT) {
|
|
15
|
+
result.push(Number(bytes.readFloatLE(offset).toFixed(6)));
|
|
16
|
+
}
|
|
17
|
+
return result;
|
|
18
|
+
}
|
|
19
|
+
export function encodeVectorJsonAsFloat32Blob(value) {
|
|
20
|
+
if (typeof value !== "string" || !value) {
|
|
21
|
+
return encodeFloat32Vector([]);
|
|
22
|
+
}
|
|
23
|
+
const parsed = JSON.parse(value);
|
|
24
|
+
const vector = Array.isArray(parsed) ? parsed.filter((item) => typeof item === "number") : [];
|
|
25
|
+
return encodeFloat32Vector(vector);
|
|
26
|
+
}
|
|
27
|
+
function bytesFromBlob(value) {
|
|
28
|
+
if (Buffer.isBuffer(value)) {
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
if (value instanceof Uint8Array) {
|
|
32
|
+
return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
|
|
33
|
+
}
|
|
34
|
+
return Buffer.alloc(0);
|
|
35
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
export type DocumentKind = "spec" | "design" | "adr" | "api" | "runbook" | "incident" | "meeting" | "guide" | "memory" | "other";
|
|
2
|
+
export type TrustTier = "authored" | "generated" | "validated" | "external" | "untrusted";
|
|
3
|
+
export type SearchQueryMode = "auto" | "keyword" | "semantic";
|
|
4
|
+
export type EntityKind = "symbol" | "api_route" | "error_code" | "config_key" | "file_path" | "command" | "package" | "concept" | "decision";
|
|
5
|
+
export type EdgeKind = "CONTAINS" | "DEFINES" | "REFERENCES" | "DEPENDS_ON" | "LINKS_TO" | "IMPLEMENTS" | "REFERENCES_SOURCE" | "SUPERSEDES" | "DEPRECATED_BY" | "SAME_AS" | "RELATED_TO" | "CONTRADICTS";
|
|
6
|
+
export declare const RESERVED_EDGE_KINDS: readonly ["SAME_AS", "RELATED_TO", "CONTRADICTS"];
|
|
7
|
+
export type Provenance = "frontmatter" | "markdown_link" | "wikilink" | "declared_section" | "heading" | "inline_code" | "code_block" | "regex";
|
|
8
|
+
export interface MDGraphConfig {
|
|
9
|
+
docs: {
|
|
10
|
+
include: string[];
|
|
11
|
+
exclude: string[];
|
|
12
|
+
};
|
|
13
|
+
index: {
|
|
14
|
+
parseMdx: boolean;
|
|
15
|
+
followGitignore: boolean;
|
|
16
|
+
maxFileBytes: number;
|
|
17
|
+
};
|
|
18
|
+
search: {
|
|
19
|
+
defaultLimit: number;
|
|
20
|
+
maxDepth: number;
|
|
21
|
+
maxContextChars: number;
|
|
22
|
+
highFrequencyEntityThreshold: number;
|
|
23
|
+
};
|
|
24
|
+
entities: {
|
|
25
|
+
enabledKinds: EntityKind[];
|
|
26
|
+
stopEntities: string[];
|
|
27
|
+
};
|
|
28
|
+
embedding: {
|
|
29
|
+
enabled: boolean;
|
|
30
|
+
provider: string;
|
|
31
|
+
model: string;
|
|
32
|
+
dimensions: number;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export interface DocumentFrontmatter {
|
|
36
|
+
id?: string;
|
|
37
|
+
title?: string;
|
|
38
|
+
type?: DocumentKind;
|
|
39
|
+
status?: string;
|
|
40
|
+
tags?: string[];
|
|
41
|
+
defines?: string[];
|
|
42
|
+
depends_on?: string[];
|
|
43
|
+
implements?: string[];
|
|
44
|
+
supersedes?: string[];
|
|
45
|
+
deprecated_by?: string[];
|
|
46
|
+
source_refs?: string[];
|
|
47
|
+
trust_tier?: TrustTier;
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
}
|
|
50
|
+
export type FrontmatterDiagnosticCode = "front_matter.invalid_yaml" | "front_matter.not_mapping" | "front_matter.unclosed" | "front_matter.invalid_field";
|
|
51
|
+
export interface FrontmatterDiagnostic {
|
|
52
|
+
code: FrontmatterDiagnosticCode;
|
|
53
|
+
message: string;
|
|
54
|
+
line: number;
|
|
55
|
+
field?: string;
|
|
56
|
+
expected?: string;
|
|
57
|
+
actual?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface MarkdownLink {
|
|
60
|
+
text: string;
|
|
61
|
+
url: string;
|
|
62
|
+
title?: string;
|
|
63
|
+
line: number;
|
|
64
|
+
sectionId?: string;
|
|
65
|
+
}
|
|
66
|
+
export interface WikiLink {
|
|
67
|
+
raw: string;
|
|
68
|
+
target: string;
|
|
69
|
+
anchor?: string;
|
|
70
|
+
alias?: string;
|
|
71
|
+
line: number;
|
|
72
|
+
sectionId?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface CodeSnippet {
|
|
75
|
+
language?: string;
|
|
76
|
+
value: string;
|
|
77
|
+
line: number;
|
|
78
|
+
sectionId?: string;
|
|
79
|
+
}
|
|
80
|
+
export interface ParsedSection {
|
|
81
|
+
id: string;
|
|
82
|
+
anchor: string;
|
|
83
|
+
heading: string;
|
|
84
|
+
level: number;
|
|
85
|
+
startLine: number;
|
|
86
|
+
endLine: number;
|
|
87
|
+
content: string;
|
|
88
|
+
}
|
|
89
|
+
export interface ParsedDocument {
|
|
90
|
+
id: string;
|
|
91
|
+
absolutePath: string;
|
|
92
|
+
relativePath: string;
|
|
93
|
+
title: string;
|
|
94
|
+
hash: string;
|
|
95
|
+
frontmatter: DocumentFrontmatter;
|
|
96
|
+
frontmatterDiagnostics: FrontmatterDiagnostic[];
|
|
97
|
+
body: string;
|
|
98
|
+
sections: ParsedSection[];
|
|
99
|
+
markdownLinks: MarkdownLink[];
|
|
100
|
+
wikiLinks: WikiLink[];
|
|
101
|
+
codeBlocks: CodeSnippet[];
|
|
102
|
+
inlineCode: CodeSnippet[];
|
|
103
|
+
}
|
|
104
|
+
export interface GraphDocument {
|
|
105
|
+
id: string;
|
|
106
|
+
path: string;
|
|
107
|
+
title: string;
|
|
108
|
+
type: DocumentKind;
|
|
109
|
+
status: string;
|
|
110
|
+
hash: string;
|
|
111
|
+
trustTier: TrustTier;
|
|
112
|
+
updatedAt?: string;
|
|
113
|
+
indexedAt: string;
|
|
114
|
+
metadata?: Record<string, unknown>;
|
|
115
|
+
}
|
|
116
|
+
export interface GraphSection extends ParsedSection {
|
|
117
|
+
documentId: string;
|
|
118
|
+
}
|
|
119
|
+
export interface GraphEntity {
|
|
120
|
+
id: string;
|
|
121
|
+
name: string;
|
|
122
|
+
normalizedName: string;
|
|
123
|
+
kind: EntityKind;
|
|
124
|
+
namespace?: string;
|
|
125
|
+
createdAt: string;
|
|
126
|
+
metadata?: Record<string, unknown>;
|
|
127
|
+
}
|
|
128
|
+
export interface SourceRef {
|
|
129
|
+
id: string;
|
|
130
|
+
path: string;
|
|
131
|
+
normalizedPath: string;
|
|
132
|
+
createdAt: string;
|
|
133
|
+
metadata?: Record<string, unknown>;
|
|
134
|
+
}
|
|
135
|
+
export interface GraphEdge {
|
|
136
|
+
id: string;
|
|
137
|
+
fromId: string;
|
|
138
|
+
toId: string;
|
|
139
|
+
kind: EdgeKind;
|
|
140
|
+
weight: number;
|
|
141
|
+
confidence: number;
|
|
142
|
+
provenance: Provenance;
|
|
143
|
+
metadata?: Record<string, unknown>;
|
|
144
|
+
createdAt: string;
|
|
145
|
+
}
|
|
146
|
+
export interface GraphChunk {
|
|
147
|
+
id: string;
|
|
148
|
+
documentId: string;
|
|
149
|
+
sectionId?: string;
|
|
150
|
+
content: string;
|
|
151
|
+
tokenEstimate: number;
|
|
152
|
+
metadata?: Record<string, unknown>;
|
|
153
|
+
}
|
|
154
|
+
export interface ChunkVector {
|
|
155
|
+
chunkId: string;
|
|
156
|
+
provider: string;
|
|
157
|
+
model: string;
|
|
158
|
+
dimensions: number;
|
|
159
|
+
vector: number[];
|
|
160
|
+
createdAt: string;
|
|
161
|
+
}
|
|
162
|
+
export interface SemanticMatchMetadata {
|
|
163
|
+
source: "chunk_vector";
|
|
164
|
+
provider: string;
|
|
165
|
+
model: string;
|
|
166
|
+
confidence: number;
|
|
167
|
+
}
|
|
168
|
+
export interface GraphRecordSet {
|
|
169
|
+
documents: GraphDocument[];
|
|
170
|
+
sections: GraphSection[];
|
|
171
|
+
entities: GraphEntity[];
|
|
172
|
+
sourceRefs: SourceRef[];
|
|
173
|
+
edges: GraphEdge[];
|
|
174
|
+
chunks: GraphChunk[];
|
|
175
|
+
vectors: ChunkVector[];
|
|
176
|
+
}
|
|
177
|
+
export interface SearchResult {
|
|
178
|
+
document: GraphDocument;
|
|
179
|
+
section?: GraphSection;
|
|
180
|
+
score: number;
|
|
181
|
+
reason: string;
|
|
182
|
+
content: string;
|
|
183
|
+
matchedEntities: GraphEntity[];
|
|
184
|
+
semantic?: SemanticMatchMetadata;
|
|
185
|
+
}
|
|
186
|
+
export interface TraceStep {
|
|
187
|
+
fromId: string;
|
|
188
|
+
fromLabel: string;
|
|
189
|
+
edgeFromId: string;
|
|
190
|
+
edgeToId: string;
|
|
191
|
+
edgeKind: EdgeKind;
|
|
192
|
+
toId: string;
|
|
193
|
+
toLabel: string;
|
|
194
|
+
traversalDirection: "forward" | "reverse";
|
|
195
|
+
confidence: number;
|
|
196
|
+
provenance: Provenance;
|
|
197
|
+
}
|
|
198
|
+
export declare const EDGE_WEIGHTS: Record<EdgeKind, number>;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const RESERVED_EDGE_KINDS = ["SAME_AS", "RELATED_TO", "CONTRADICTS"];
|
|
2
|
+
export const EDGE_WEIGHTS = {
|
|
3
|
+
CONTAINS: 5,
|
|
4
|
+
DEFINES: 10,
|
|
5
|
+
REFERENCES: 4,
|
|
6
|
+
DEPENDS_ON: 9,
|
|
7
|
+
LINKS_TO: 7,
|
|
8
|
+
IMPLEMENTS: 8,
|
|
9
|
+
REFERENCES_SOURCE: 6,
|
|
10
|
+
SUPERSEDES: 8,
|
|
11
|
+
DEPRECATED_BY: 8,
|
|
12
|
+
SAME_AS: 7,
|
|
13
|
+
RELATED_TO: 2,
|
|
14
|
+
CONTRADICTS: 6
|
|
15
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface BoundedJsonOptions {
|
|
2
|
+
maxBytes?: number;
|
|
3
|
+
maxDepth?: number;
|
|
4
|
+
maxNodes?: number;
|
|
5
|
+
maxArrayLength?: number;
|
|
6
|
+
}
|
|
7
|
+
export declare function readBoundedJsonFile(filePath: string, label?: string, options?: BoundedJsonOptions): unknown;
|
|
8
|
+
export declare function parseBoundedJsonString(raw: string, label?: string, options?: BoundedJsonOptions): unknown;
|
|
9
|
+
export declare function assertBoundedJsonValue(value: unknown, label?: string, options?: BoundedJsonOptions): void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { JSON_ARTIFACT_LIMITS } from "../config/limits.js";
|
|
3
|
+
export function readBoundedJsonFile(filePath, label = "JSON artifact", options = {}) {
|
|
4
|
+
const limits = jsonLimits(options);
|
|
5
|
+
const size = fs.statSync(filePath).size;
|
|
6
|
+
if (size > limits.maxBytes) {
|
|
7
|
+
throw new Error(`${label} exceeds ${limits.maxBytes} bytes.`);
|
|
8
|
+
}
|
|
9
|
+
return parseBoundedJsonString(fs.readFileSync(filePath, "utf8"), label, options);
|
|
10
|
+
}
|
|
11
|
+
export function parseBoundedJsonString(raw, label = "JSON artifact", options = {}) {
|
|
12
|
+
const limits = jsonLimits(options);
|
|
13
|
+
if (Buffer.byteLength(raw, "utf8") > limits.maxBytes) {
|
|
14
|
+
throw new Error(`${label} exceeds ${limits.maxBytes} bytes.`);
|
|
15
|
+
}
|
|
16
|
+
const parsed = JSON.parse(raw);
|
|
17
|
+
assertBoundedJsonValue(parsed, label, options);
|
|
18
|
+
return parsed;
|
|
19
|
+
}
|
|
20
|
+
export function assertBoundedJsonValue(value, label = "JSON artifact", options = {}) {
|
|
21
|
+
const limits = jsonLimits(options);
|
|
22
|
+
const stack = [{ value, depth: 0 }];
|
|
23
|
+
let nodes = 0;
|
|
24
|
+
while (stack.length) {
|
|
25
|
+
const current = stack.pop();
|
|
26
|
+
nodes += 1;
|
|
27
|
+
if (nodes > limits.maxNodes) {
|
|
28
|
+
throw new Error(`${label} exceeds ${limits.maxNodes} JSON nodes.`);
|
|
29
|
+
}
|
|
30
|
+
if (current.depth > limits.maxDepth) {
|
|
31
|
+
throw new Error(`${label} exceeds JSON depth ${limits.maxDepth}.`);
|
|
32
|
+
}
|
|
33
|
+
if (!current.value || typeof current.value !== "object") {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (Array.isArray(current.value)) {
|
|
37
|
+
if (current.value.length > limits.maxArrayLength) {
|
|
38
|
+
throw new Error(`${label} exceeds array length ${limits.maxArrayLength}.`);
|
|
39
|
+
}
|
|
40
|
+
for (const item of current.value) {
|
|
41
|
+
stack.push({ value: item, depth: current.depth + 1 });
|
|
42
|
+
}
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
for (const item of Object.values(current.value)) {
|
|
46
|
+
stack.push({ value: item, depth: current.depth + 1 });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function jsonLimits(options) {
|
|
51
|
+
return {
|
|
52
|
+
maxBytes: options.maxBytes ?? JSON_ARTIFACT_LIMITS.maxBytes,
|
|
53
|
+
maxDepth: options.maxDepth ?? JSON_ARTIFACT_LIMITS.maxDepth,
|
|
54
|
+
maxNodes: options.maxNodes ?? JSON_ARTIFACT_LIMITS.maxNodes,
|
|
55
|
+
maxArrayLength: options.maxArrayLength ?? JSON_ARTIFACT_LIMITS.maxArrayLength
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function scanContentRiskLines(content) {
|
|
2
|
+
const risks = [];
|
|
3
|
+
const lines = content.split(/\r?\n/);
|
|
4
|
+
lines.forEach((line, index) => {
|
|
5
|
+
const lower = line.toLowerCase();
|
|
6
|
+
if (lower.includes("ignore previous instructions") || lower.includes("system prompt")) {
|
|
7
|
+
risks.push({ line: index + 1, reason: "possible prompt injection text" });
|
|
8
|
+
}
|
|
9
|
+
if (/<\s*(script|iframe)\b/i.test(line)) {
|
|
10
|
+
risks.push({ line: index + 1, reason: "HTML script or iframe" });
|
|
11
|
+
}
|
|
12
|
+
if (/data:text\/html|data:application\/javascript/i.test(line)) {
|
|
13
|
+
risks.push({ line: index + 1, reason: "active data URI" });
|
|
14
|
+
}
|
|
15
|
+
if (/\p{Cf}/u.test(line)) {
|
|
16
|
+
risks.push({ line: index + 1, reason: "hidden Unicode format character" });
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
return risks;
|
|
20
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const cjkRunPattern = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
|
|
2
|
+
export function ftsIndexContent(content) {
|
|
3
|
+
const cjkTokens = cjkNgramTokens(content);
|
|
4
|
+
return cjkTokens.length ? `${content}\n${cjkTokens.join(" ")}` : content;
|
|
5
|
+
}
|
|
6
|
+
export function ftsQueryFor(query) {
|
|
7
|
+
const tokens = ftsQueryTokens(query).slice(0, 24);
|
|
8
|
+
return [...new Set(tokens)].map((token) => `${escapeFtsToken(token)}*`).join(" OR ");
|
|
9
|
+
}
|
|
10
|
+
export function ftsQueryTokens(query) {
|
|
11
|
+
const tokens = [];
|
|
12
|
+
const lexicalTokens = query.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [];
|
|
13
|
+
for (const token of lexicalTokens) {
|
|
14
|
+
const cjkTokens = cjkNgramTokens(token);
|
|
15
|
+
tokens.push(...cjkTokens);
|
|
16
|
+
const nonCjkText = token.replace(cjkRunPattern, " ");
|
|
17
|
+
tokens.push(...nonCjkText
|
|
18
|
+
.match(/[\p{L}\p{N}_]+/gu)
|
|
19
|
+
?.flatMap((part) => part.split("_")) ?? []);
|
|
20
|
+
if (!cjkTokens.length) {
|
|
21
|
+
tokens.push(...token.split("_"));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return tokens
|
|
25
|
+
.map(escapeFtsToken)
|
|
26
|
+
.filter((token) => token.length > 1)
|
|
27
|
+
.filter((token) => !isFtsOperatorToken(token));
|
|
28
|
+
}
|
|
29
|
+
function cjkNgramTokens(content) {
|
|
30
|
+
const tokens = [];
|
|
31
|
+
for (const match of content.matchAll(cjkRunPattern)) {
|
|
32
|
+
tokens.push(...ngrams(Array.from(match[0]), 2));
|
|
33
|
+
tokens.push(...ngrams(Array.from(match[0]), 3));
|
|
34
|
+
}
|
|
35
|
+
return tokens;
|
|
36
|
+
}
|
|
37
|
+
function ngrams(chars, size) {
|
|
38
|
+
if (chars.length < size) {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
const result = [];
|
|
42
|
+
for (let index = 0; index <= chars.length - size; index += 1) {
|
|
43
|
+
result.push(chars.slice(index, index + size).join(""));
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
function isFtsOperatorToken(token) {
|
|
48
|
+
return token === "and" || token === "or" || token === "not" || token === "near";
|
|
49
|
+
}
|
|
50
|
+
function escapeFtsToken(token) {
|
|
51
|
+
return token.replace(/[^\p{L}\p{N}_]/gu, "");
|
|
52
|
+
}
|
package/dist/utils/id.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export function stableId(kind, value) {
|
|
3
|
+
const digest = createHash("sha1").update(`${kind}:${value}`).digest("hex").slice(0, 20);
|
|
4
|
+
return `${kind}:${digest}`;
|
|
5
|
+
}
|
|
6
|
+
export function contentHash(content) {
|
|
7
|
+
return createHash("sha256").update(content).digest("hex");
|
|
8
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function isPathInsideOrEqual(root: string, target: string): boolean;
|
|
2
|
+
export declare function resolveInsideRoot(root: string, target: string): string | undefined;
|
|
3
|
+
export declare function assertInsideRoot(root: string, target: string, label?: string): string;
|
|
4
|
+
export declare function relativePathInsideRoot(root: string, target: string): string | undefined;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { normalizePath } from "./text.js";
|
|
3
|
+
export function isPathInsideOrEqual(root, target) {
|
|
4
|
+
const resolvedRoot = path.resolve(root);
|
|
5
|
+
const resolvedTarget = path.resolve(target);
|
|
6
|
+
const relative = path.relative(resolvedRoot, resolvedTarget);
|
|
7
|
+
return relative === "" || Boolean(relative && !relative.startsWith("..") && !path.isAbsolute(relative));
|
|
8
|
+
}
|
|
9
|
+
export function resolveInsideRoot(root, target) {
|
|
10
|
+
const resolved = path.resolve(root, target);
|
|
11
|
+
return isPathInsideOrEqual(root, resolved) ? resolved : undefined;
|
|
12
|
+
}
|
|
13
|
+
export function assertInsideRoot(root, target, label = "path") {
|
|
14
|
+
const resolved = path.resolve(target);
|
|
15
|
+
if (!isPathInsideOrEqual(root, resolved)) {
|
|
16
|
+
throw new Error(`${label} must stay inside project root: ${target}`);
|
|
17
|
+
}
|
|
18
|
+
return resolved;
|
|
19
|
+
}
|
|
20
|
+
export function relativePathInsideRoot(root, target) {
|
|
21
|
+
if (!isPathInsideOrEqual(root, target)) {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
return normalizePath(path.relative(path.resolve(root), path.resolve(target)));
|
|
25
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function normalizePath(input: string): string;
|
|
2
|
+
export declare function relativeUnixPath(root: string, absolutePath: string): string;
|
|
3
|
+
export declare function normalizeEntityName(name: string): string;
|
|
4
|
+
export declare function slugifyHeading(heading: string): string;
|
|
5
|
+
export declare function estimateTokens(content: string): number;
|
|
6
|
+
export declare function uniqueStrings(values: Iterable<string>): string[];
|
|
7
|
+
export declare function asStringArray(value: unknown): string[];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
export function normalizePath(input) {
|
|
3
|
+
return input.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
4
|
+
}
|
|
5
|
+
export function relativeUnixPath(root, absolutePath) {
|
|
6
|
+
return normalizePath(path.relative(root, absolutePath));
|
|
7
|
+
}
|
|
8
|
+
export function normalizeEntityName(name) {
|
|
9
|
+
return name.trim().replace(/^`|`$/g, "").toLowerCase();
|
|
10
|
+
}
|
|
11
|
+
export function slugifyHeading(heading) {
|
|
12
|
+
const slug = heading
|
|
13
|
+
.trim()
|
|
14
|
+
.toLowerCase()
|
|
15
|
+
.replace(/`/g, "")
|
|
16
|
+
.replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, "")
|
|
17
|
+
.replace(/\s+/g, "-")
|
|
18
|
+
.replace(/-+/g, "-")
|
|
19
|
+
.replace(/^-|-$/g, "");
|
|
20
|
+
return slug || "section";
|
|
21
|
+
}
|
|
22
|
+
export function estimateTokens(content) {
|
|
23
|
+
return Math.max(1, Math.ceil(content.length / 4));
|
|
24
|
+
}
|
|
25
|
+
export function uniqueStrings(values) {
|
|
26
|
+
return [...new Set([...values].map((value) => value.trim()).filter(Boolean))];
|
|
27
|
+
}
|
|
28
|
+
export function asStringArray(value) {
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean);
|
|
31
|
+
}
|
|
32
|
+
if (typeof value === "string" && value.trim()) {
|
|
33
|
+
return [value.trim()];
|
|
34
|
+
}
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function packageVersion(): string;
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
let cachedVersion;
|
|
3
|
+
export function packageVersion() {
|
|
4
|
+
if (cachedVersion) {
|
|
5
|
+
return cachedVersion;
|
|
6
|
+
}
|
|
7
|
+
const packageJsonUrl = new URL("../package.json", import.meta.url);
|
|
8
|
+
const packageJson = JSON.parse(fs.readFileSync(packageJsonUrl, "utf8"));
|
|
9
|
+
cachedVersion = typeof packageJson.version === "string" && packageJson.version ? packageJson.version : "0.0.0";
|
|
10
|
+
return cachedVersion;
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type IndexResult } from "../indexer.js";
|
|
2
|
+
export interface WatchProjectOptions {
|
|
3
|
+
debounceMs?: number;
|
|
4
|
+
semantic?: boolean;
|
|
5
|
+
onIndexed?: (result: IndexResult) => void;
|
|
6
|
+
onError?: (error: Error) => void;
|
|
7
|
+
}
|
|
8
|
+
export interface WatchHandle {
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export declare function watchProject(projectRoot: string, options?: WatchProjectOptions): Promise<WatchHandle>;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import chokidar from "chokidar";
|
|
2
|
+
import { loadConfig } from "../config/load-config.js";
|
|
3
|
+
import { indexProject } from "../indexer.js";
|
|
4
|
+
import { resolveIgnorePatterns } from "../scanner/file-scanner.js";
|
|
5
|
+
export async function watchProject(projectRoot, options = {}) {
|
|
6
|
+
const config = loadConfig(projectRoot);
|
|
7
|
+
const ignored = await resolveIgnorePatterns(projectRoot, config);
|
|
8
|
+
const watchesMdx = config.index.parseMdx;
|
|
9
|
+
const debounceMs = options.debounceMs ?? 250;
|
|
10
|
+
let timer;
|
|
11
|
+
let running = false;
|
|
12
|
+
let queued = false;
|
|
13
|
+
let closed = false;
|
|
14
|
+
let activeIndex;
|
|
15
|
+
const runIndex = async () => {
|
|
16
|
+
if (closed) {
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (running) {
|
|
20
|
+
queued = true;
|
|
21
|
+
await activeIndex;
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
running = true;
|
|
25
|
+
activeIndex = (async () => {
|
|
26
|
+
try {
|
|
27
|
+
const result = await indexProject(projectRoot, { semantic: options.semantic });
|
|
28
|
+
options.onIndexed?.(result);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
notifyError(options.onError, error);
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
running = false;
|
|
35
|
+
activeIndex = undefined;
|
|
36
|
+
if (!closed && queued) {
|
|
37
|
+
queued = false;
|
|
38
|
+
scheduleIndex();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
})();
|
|
42
|
+
await activeIndex;
|
|
43
|
+
};
|
|
44
|
+
const scheduleIndex = () => {
|
|
45
|
+
if (closed) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (timer) {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
}
|
|
51
|
+
timer = setTimeout(() => {
|
|
52
|
+
timer = undefined;
|
|
53
|
+
void runIndex();
|
|
54
|
+
}, debounceMs);
|
|
55
|
+
};
|
|
56
|
+
const scheduleIndexForMarkdown = (filePath) => {
|
|
57
|
+
const lower = filePath.toLowerCase();
|
|
58
|
+
if (lower.endsWith(".md") || (watchesMdx && lower.endsWith(".mdx"))) {
|
|
59
|
+
scheduleIndex();
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const watcher = chokidar.watch(".", {
|
|
63
|
+
cwd: projectRoot,
|
|
64
|
+
ignored,
|
|
65
|
+
ignoreInitial: true,
|
|
66
|
+
persistent: true,
|
|
67
|
+
awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 }
|
|
68
|
+
});
|
|
69
|
+
watcher.on("add", scheduleIndexForMarkdown);
|
|
70
|
+
watcher.on("change", scheduleIndexForMarkdown);
|
|
71
|
+
watcher.on("unlink", scheduleIndexForMarkdown);
|
|
72
|
+
watcher.on("error", (error) => {
|
|
73
|
+
notifyError(options.onError, error);
|
|
74
|
+
});
|
|
75
|
+
try {
|
|
76
|
+
await waitForReady(watcher);
|
|
77
|
+
await runIndex();
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
closed = true;
|
|
81
|
+
await watcher.close();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
close: async () => {
|
|
86
|
+
closed = true;
|
|
87
|
+
if (timer) {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
timer = undefined;
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
if (activeIndex) {
|
|
93
|
+
await activeIndex;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await watcher.close();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function notifyError(onError, error) {
|
|
103
|
+
try {
|
|
104
|
+
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// User callbacks must not break watcher cleanup or future indexing.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function waitForReady(watcher) {
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const cleanup = () => {
|
|
113
|
+
watcher.off("ready", onReady);
|
|
114
|
+
watcher.off("error", onError);
|
|
115
|
+
};
|
|
116
|
+
const onReady = () => {
|
|
117
|
+
cleanup();
|
|
118
|
+
resolve();
|
|
119
|
+
};
|
|
120
|
+
const onError = (error) => {
|
|
121
|
+
cleanup();
|
|
122
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
123
|
+
};
|
|
124
|
+
watcher.once("ready", onReady);
|
|
125
|
+
watcher.once("error", onError);
|
|
126
|
+
});
|
|
127
|
+
}
|