|
| 1 | +import { readdir, readFile } from "node:fs/promises"; |
| 2 | +import { join, relative } from "node:path"; |
| 3 | + |
| 4 | +interface IndexedDoc { |
| 5 | + filepath: string; |
| 6 | + url: string; |
| 7 | + title: string; |
| 8 | + content: string; |
| 9 | + terms: Map<string, number>; |
| 10 | + termCount: number; |
| 11 | +} |
| 12 | + |
| 13 | +export class DocsIndex { |
| 14 | + private docs: IndexedDoc[] = []; |
| 15 | + private idf: Map<string, number> = new Map(); |
| 16 | + private loaded = false; |
| 17 | + private docsDir: string; |
| 18 | + |
| 19 | + constructor(docsDir: string) { |
| 20 | + this.docsDir = docsDir; |
| 21 | + } |
| 22 | + |
| 23 | + async load(): Promise<void> { |
| 24 | + if (this.loaded) return; |
| 25 | + |
| 26 | + const files = await this.findMarkdownFiles(this.docsDir); |
| 27 | + |
| 28 | + const manifestMap = new Map<string, string>(); |
| 29 | + try { |
| 30 | + const manifestRaw = await readFile(join(this.docsDir, "_manifest.json"), "utf-8"); |
| 31 | + const manifest: Array<{ url: string; filepath: string }> = JSON.parse(manifestRaw); |
| 32 | + for (const entry of manifest) { |
| 33 | + manifestMap.set(entry.filepath, entry.url); |
| 34 | + } |
| 35 | + } catch (_e) { /* manifest may not exist */ } |
| 36 | + |
| 37 | + for (const file of files) { |
| 38 | + if (file.endsWith("_all.md") || file.endsWith("_manifest.json")) continue; |
| 39 | + |
| 40 | + const content = await readFile(file, "utf-8"); |
| 41 | + const title = this.extractTitle(content); |
| 42 | + const terms = this.tokenize(content); |
| 43 | + const termFreq = this.computeTermFrequency(terms); |
| 44 | + const url = manifestMap.get(file) || this.filepathToUrl(file); |
| 45 | + |
| 46 | + this.docs.push({ |
| 47 | + filepath: relative(this.docsDir, file), |
| 48 | + url, |
| 49 | + title, |
| 50 | + content, |
| 51 | + terms: termFreq, |
| 52 | + termCount: terms.length, |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + this.computeIDF(); |
| 57 | + this.loaded = true; |
| 58 | + console.error(`Docs index loaded: ${this.docs.length} documents from ${this.docsDir}`); |
| 59 | + } |
| 60 | + |
| 61 | + search(query: string, maxResults = 5): Array<{ url: string; title: string; snippet: string; score: number; filepath: string }> { |
| 62 | + const queryTerms = this.tokenize(query); |
| 63 | + if (!queryTerms.length) return []; |
| 64 | + |
| 65 | + const scores: Array<{ doc: IndexedDoc; score: number }> = []; |
| 66 | + |
| 67 | + for (const doc of this.docs) { |
| 68 | + let score = 0; |
| 69 | + for (const term of queryTerms) { |
| 70 | + const tf = (doc.terms.get(term) || 0) / Math.max(doc.termCount, 1); |
| 71 | + const idf = this.idf.get(term) || 0; |
| 72 | + score += tf * idf; |
| 73 | + } |
| 74 | + |
| 75 | + const titleBonus = queryTerms.some((t) => doc.title.toLowerCase().includes(t)) ? 2 : 1; |
| 76 | + score *= titleBonus; |
| 77 | + |
| 78 | + if (score > 0) { |
| 79 | + scores.push({ doc, score }); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + scores.sort((a, b) => b.score - a.score); |
| 84 | + |
| 85 | + return scores.slice(0, maxResults).map(({ doc, score }) => ({ |
| 86 | + url: doc.url, |
| 87 | + title: doc.title, |
| 88 | + snippet: this.extractSnippet(doc.content, queryTerms), |
| 89 | + score: Math.round(score * 10000) / 10000, |
| 90 | + filepath: doc.filepath, |
| 91 | + })); |
| 92 | + } |
| 93 | + |
| 94 | + getDocContent(filepath: string): string | null { |
| 95 | + const doc = this.docs.find((d) => d.filepath === filepath); |
| 96 | + return doc?.content ?? null; |
| 97 | + } |
| 98 | + |
| 99 | + get documentCount(): number { |
| 100 | + return this.docs.length; |
| 101 | + } |
| 102 | + |
| 103 | + get isLoaded(): boolean { |
| 104 | + return this.loaded; |
| 105 | + } |
| 106 | + |
| 107 | + private tokenize(text: string): string[] { |
| 108 | + return text |
| 109 | + .toLowerCase() |
| 110 | + .replace(/[^\p{L}\p{N}\s]/gu, " ") |
| 111 | + .split(/\s+/) |
| 112 | + .filter((t) => t.length > 2); |
| 113 | + } |
| 114 | + |
| 115 | + private computeTermFrequency(terms: string[]): Map<string, number> { |
| 116 | + const freq = new Map<string, number>(); |
| 117 | + for (const term of terms) { |
| 118 | + freq.set(term, (freq.get(term) || 0) + 1); |
| 119 | + } |
| 120 | + return freq; |
| 121 | + } |
| 122 | + |
| 123 | + private computeIDF(): void { |
| 124 | + const docFreq = new Map<string, number>(); |
| 125 | + for (const doc of this.docs) { |
| 126 | + for (const term of doc.terms.keys()) { |
| 127 | + docFreq.set(term, (docFreq.get(term) || 0) + 1); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + const n = this.docs.length; |
| 132 | + for (const [term, df] of docFreq) { |
| 133 | + this.idf.set(term, Math.log(1 + n / df)); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + private extractTitle(content: string): string { |
| 138 | + const match = content.match(/^#\s+(.+)$/m); |
| 139 | + return match?.[1]?.trim() || "Untitled"; |
| 140 | + } |
| 141 | + |
| 142 | + private extractSnippet(content: string, queryTerms: string[]): string { |
| 143 | + const lines = content.split("\n").filter((l) => l.trim()); |
| 144 | + const lower = queryTerms.map((t) => t.toLowerCase()); |
| 145 | + |
| 146 | + for (const line of lines) { |
| 147 | + if (lower.some((t) => line.toLowerCase().includes(t))) { |
| 148 | + return line.slice(0, 300); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + return lines.slice(0, 3).join(" ").slice(0, 300); |
| 153 | + } |
| 154 | + |
| 155 | + private async findMarkdownFiles(dir: string): Promise<string[]> { |
| 156 | + const results: string[] = []; |
| 157 | + try { |
| 158 | + const entries = await readdir(dir, { withFileTypes: true }); |
| 159 | + for (const entry of entries) { |
| 160 | + const fullPath = join(dir, entry.name); |
| 161 | + if (entry.isDirectory()) { |
| 162 | + results.push(...(await this.findMarkdownFiles(fullPath))); |
| 163 | + } else if (entry.name.endsWith(".md")) { |
| 164 | + results.push(fullPath); |
| 165 | + } |
| 166 | + } |
| 167 | + } catch (_e) { /* directory may not exist */ } |
| 168 | + return results; |
| 169 | + } |
| 170 | + |
| 171 | + private filepathToUrl(filepath: string): string { |
| 172 | + const rel = relative(this.docsDir, filepath).replace(/\.md$/, ""); |
| 173 | + return `https://dev.magalu.com/docs/${rel}`; |
| 174 | + } |
| 175 | +} |
0 commit comments