All files vault-indexer.ts

92.85% Statements 104/112
80% Branches 36/45
100% Functions 15/15
95.19% Lines 99/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271      2x                                                           67x     67x       33x 2x     31x       31x 31x 31x 31x   31x 50x 38x                 31x 31x 31x   31x 15x 15x   54x 54x 53x 53x 53x 50x           50x 50x 50x       3x   1x       1x         15x 54x   15x     31x       100x                                                     100x     367x       60x 60x 60x     60x 60x 2x 2x 2x 2x 3x 3x 3x 3x 1x 1x   2x 2x 2x                 60x 60x 3x     60x 60x 60x     60x           60x   60x               58x 58x   58x 64x 64x 64x   64x           64x         1x 1x     64x 1x 1x     64x 1x 1x     64x 58x 58x     64x 56x 56x     64x 60x 60x       58x               127x 127x 126x 126x 122x       63x 63x       2x  
// src/vault-indexer.ts
 
import { VaultIndexEntry } from './types';
import { Logger } from './utils';
 
interface Frontmatter {
  title?: string;
  tags?: string;
}
 
interface VaultFile {
  basename: string;
  path: string;
}
 
interface VaultLike {
  getMarkdownFiles(): VaultFile[];
  read(file: VaultFile): Promise<string>;
}
 
interface TokenizedContent {
  tokens: string[];
  headings: string[];
  frontmatter: Frontmatter;
  firstParagraph?: string;
}
 
interface ScoreResult {
  score: number;
  matchedFields: string[];
}
 
class VaultIndexer {
  private vault: VaultLike | null = null;
 
  constructor(vault: VaultLike) {
    this.vault = vault;
  }
 
  async searchVault(query: string, limit: number = 5): Promise<VaultIndexEntry[]> {
    if (!query || !query.trim()) {
      return [];
    }
 
    Iif (!this.vault) {
      throw new Error('Vault-like object not provided to VaultIndexer');
    }
 
    const queryTokens = this.tokenize(query.trim());
    const vault = this.vault;
    const allFiles = vault.getMarkdownFiles();
    const results = await this.processFilesInBatches(vault, allFiles, queryTokens);
 
    return results
      .filter((result): result is NonNullable<typeof result> => result !== null)
      .sort((a, b) => b.score - a.score)
      .slice(0, limit);
  }
 
  private async processFilesInBatches(
    vault: VaultLike,
    files: VaultFile[],
    queryTokens: string[]
  ): Promise<Array<VaultIndexEntry | null>> {
    const batchSize = 10;
    const results: VaultIndexEntry[] = [];
    const seenPaths = new Set<string>();
 
    for (let i = 0; i < files.length; i += batchSize) {
      const batch = files.slice(i, i + batchSize);
      const batchResults = await Promise.all(
        batch.map(async (file) => {
          try {
            const content = await vault.read(file);
            const tokenized = this.tokenizeContent(content);
            const scoreResult = this.calculateWeightedScore(tokenized, queryTokens, file);
            if (scoreResult.score > 0) {
              const entry: VaultIndexEntry = {
                path: file.path,
                title: file.basename.replace(/\.md$/, ''),
                content: content.substring(0, 500),
                score: scoreResult.score,
              };
              if (!seenPaths.has(entry.path)) {
                seenPaths.add(entry.path);
                return entry;
              }
              return null;
            }
            return null;
          } catch (error) {
            Logger.warn(
              `Failed to process ${file.path}: ${error instanceof Error ? error.message : String(error)}`,
              'vault-indexer'
            );
            return null;
          }
        })
      );
 
      const validResults = batchResults.filter(
        (result): result is NonNullable<typeof result> => result !== null
      );
      results.push(...validResults);
    }
 
    return results;
  }
 
  private tokenize(text: string): string[] {
    const stopWords = new Set([
      'the',
      'a',
      'an',
      'and',
      'or',
      'but',
      'is',
      'are',
      'was',
      'were',
      'in',
      'on',
      'at',
      'to',
      'of',
      'for',
      'with',
      'as',
      'by',
      'it',
      'its',
      'that',
      'this',
      'these',
      'those',
    ]);
    return text
      .toLowerCase()
      .split(/\W+/)
      .filter((token) => token.length > 1 && !stopWords.has(token));
  }
 
  private tokenizeContent(content: string): TokenizedContent {
    const tokens: string[] = [];
    const headings: string[] = [];
    const frontmatter: Frontmatter = {};
    let firstParagraph: string | undefined;
 
    const frontmatterMatch = content.match(/^---(.*?)---/s);
    if (frontmatterMatch) {
      try {
        const frontmatterContent = frontmatterMatch[1];
        const lines = frontmatterContent.trim().split('\n');
        for (const line of lines) {
          const [key, ...valueParts] = line.split(':');
          Iif (!key) continue;
          const value = valueParts.join(':').trim();
          if (key.trim() === 'title') {
            if (value) {
              frontmatter.title = value;
            }
          } else if (key.trim() === 'tags') {
            if (value) {
              frontmatter.tags = value;
            }
          }
        }
      } catch {
        Logger.warn('Failed to parse frontmatter', 'vault-indexer');
      }
    }
 
    const headingMatches = content.match(/^#{1,6} (.*?)$/gm);
    if (headingMatches) {
      headings.push(...headingMatches.map((h: string) => h.replace(/^#{1,6} /, '')));
    }
 
    const paragraphMatch = content.match(/^([^#]*?)(?=#|\n\n|$)/s);
    if (paragraphMatch) {
      firstParagraph = paragraphMatch[1].trim();
    }
 
    const allText = content
      .replace(/^---.*?---/s, '')
      .replace(/^#.*?$/gm, '')
      .replace(/```.*?```/gs, '')
      .replace(/`.*?`/g, '')
      .replace(/\[.*?\]\(.*?\)/g, '');
    tokens.push(...this.tokenize(allText));
 
    return { tokens, headings, frontmatter, firstParagraph };
  }
 
  private calculateWeightedScore(
    tokenized: TokenizedContent,
    queryTokens: string[],
    file?: VaultFile
  ): ScoreResult {
    let totalScore = 0;
    const matchedTokens: Set<string> = new Set<string>();
 
    for (const queryToken of queryTokens) {
      let tokenScore = 0;
      const stemmed = this.stemToken(queryToken);
      let matched = false;
 
      Iif (
        tokenized.frontmatter?.title &&
        this.exactMatch(tokenized.frontmatter.title, queryToken)
      ) {
        tokenScore += 3;
        matched = true;
      } else if (
        file &&
        file.basename &&
        this.exactMatch(file.basename.replace(/\.md$/, ''), queryToken)
      ) {
        tokenScore += 3;
        matched = true;
      }
 
      if (tokenized.frontmatter?.tags && this.exactMatch(tokenized.frontmatter.tags, queryToken)) {
        tokenScore += 2.5;
        matched = true;
      }
 
      if (tokenized.headings.some((heading: string) => heading.toLowerCase().includes(stemmed))) {
        tokenScore += 5;
        matched = true;
      }
 
      if (tokenized.firstParagraph && tokenized.firstParagraph.toLowerCase().includes(stemmed)) {
        tokenScore += 1.5;
        matched = true;
      }
 
      if (tokenized.tokens.includes(stemmed)) {
        tokenScore += 1;
        matched = true;
      }
 
      if (matched) {
        totalScore += tokenScore;
        matchedTokens.add(queryToken);
      }
    }
 
    return {
      score: totalScore,
      matchedFields: Array.from(matchedTokens),
    };
  }
 
  private stemToken(token: string): string {
    // Improved stemmer that handles edge cases
    Iif (token.length <= 3) return token; // Don't stem very short tokens
    if (token.endsWith('s')) return token.slice(0, -1);
    Iif (token.endsWith('ed') && token.length > 4) return token.slice(0, -2); // Don't stem 3-letter words ending in ed
    if (token.endsWith('ing') && token.length > 5) return token.slice(0, -3); // Don't stem 4-letter words ending in ing
    return token;
  }
 
  private exactMatch(content: string, token: string): boolean {
    const stemmedToken = this.stemToken(token);
    return content.toLowerCase().includes(stemmedToken);
  }
}
 
export { VaultIndexer };