All files vault-indexer.ts

99.16% Statements 119/120
91.66% Branches 33/36
100% Functions 16/16
99.09% Lines 110/111

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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398      1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             1x       31x       16x 16x   16x 16x 2x       14x 15x 15x   54x 53x 53x   53x 50x           3x       15x 54x 50x 4x 1x             38x             268x           841x                                                                                                                                                                                                                                                                       841x               60x 60x     60x 60x   60x   60x 3x       60x 60x 60x 60x 2x 2x 2x 3x 3x 3x 3x 3x           60x     60x 60x 60x 60x 63x   63x 3x     60x 2x   58x 58x 1x     60x     60x 60x   60x           3x                                 58x 58x 58x 58x     58x 50x     58x 64x     64x 1x       64x 1x       64x 1x 1x 1x         123x 57x       295x 64x   58x       64x 58x     64x         58x 58x       58x                 489x 220x       269x 1x   268x 1x       267x 534x 520x 519x     267x      
import { Vault, TFile } from 'obsidian';
import { VaultIndexEntry } from './types';
 
const MAX_CONTENT_PREVIEW_LENGTH = 500;
const BATCH_SIZE = 10;
const MAX_TOKENS = 10000;
const TITLE_WEIGHT = 10;
const HEADING_WEIGHT = 5;
const FRONTMATTER_WEIGHT = 8;
const FIRST_PARAGRAPH_WEIGHT = 3;
const BODY_WEIGHT = 1;
const PHRASE_MATCH_BONUS = 2;
const EXACT_WORD_MATCH_BONUS = 1.5;
 
interface TokenizedContent {
  text: string;
  tokens: string[];
  title: string;
  titleTokens: string[];
  headings: string[];
  headingTokens: string[][];
  frontmatter: Record<string, string>;
  frontmatterTokens: string[];
  firstParagraph: string;
  firstParagraphTokens: string[];
}
 
export class VaultIndexer {
  private vault: Vault;
 
  constructor(vault: Vault) {
    this.vault = vault;
  }
 
  async searchVault(query: string, limit: number = 5): Promise<VaultIndexEntry[]> {
    const files = this.vault.getMarkdownFiles();
    const results: VaultIndexEntry[] = [];
 
    const queryTokens = this.tokenize(query);
    if (queryTokens.length === 0) {
      return [];
    }
 
    // Process files in batches with concurrency limit
    for (let i = 0; i < files.length; i += BATCH_SIZE) {
      const batch = files.slice(i, i + BATCH_SIZE);
      const batchResults = await Promise.allSettled(
        batch.map(async (file) => {
          const fullContent = await this.vault.read(file);
          const tokenized = this.tokenizeContent(fullContent, file);
          const score = this.calculateWeightedScore(tokenized, query, queryTokens);
 
          if (score > 0) {
            return {
              title: file.basename,
              content: fullContent.substring(0, MAX_CONTENT_PREVIEW_LENGTH),
              score,
            } as VaultIndexEntry;
          }
          return null;
        })
      );
 
      for (const result of batchResults) {
        if (result.status === 'fulfilled' && result.value !== null) {
          results.push(result.value);
        } else if (result.status === 'rejected') {
          console.warn(
            `[VaultIndexer] Failed to read file: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
          );
        }
      }
    }
 
    return results.sort((a, b) => b.score - a.score).slice(0, limit);
  }
 
  /**
   * Tokenize a string into lowercase words, filtering out stop words and very short tokens
   */
  private tokenize(text: string): string[] {
    return text
      .toLowerCase()
      .replace(/[^\w\s]/g, ' ')
      .split(/\s+/)
      .filter((token) => {
        // Filter out common stop words and very short tokens
        const stopWords = new Set([
          'a',
          'an',
          'the',
          'and',
          'or',
          'but',
          'in',
          'on',
          'at',
          'to',
          'for',
          'of',
          'with',
          'by',
          'is',
          'are',
          'was',
          'were',
          'be',
          'been',
          'have',
          'has',
          'had',
          'do',
          'does',
          'did',
          'will',
          'would',
          'could',
          'should',
          'may',
          'might',
          'must',
          'shall',
          'can',
          'need',
          'dare',
          'ought',
          'used',
          'it',
          'its',
          'this',
          'that',
          'these',
          'those',
          'i',
          'you',
          'he',
          'she',
          'we',
          'they',
          'me',
          'him',
          'her',
          'us',
          'them',
          'my',
          'your',
          'his',
          'our',
          'their',
          'mine',
          'yours',
          'hers',
          'ours',
          'theirs',
          'what',
          'which',
          'who',
          'whom',
          'whose',
          'where',
          'when',
          'why',
          'how',
          'not',
          'no',
          'nor',
          'so',
          'if',
          'then',
          'than',
          'too',
          'very',
          'just',
          'about',
          'above',
          'after',
          'again',
          'all',
          'am',
          'any',
          'as',
          'because',
          'before',
          'being',
          'below',
          'between',
          'both',
          'during',
          'each',
          'few',
          'further',
          'get',
          'got',
          'here',
          'into',
          'more',
          'most',
          'much',
          'myself',
          'nothing',
          'only',
          'other',
          'out',
          'over',
          'own',
          'same',
          'some',
          'such',
          'there',
          'through',
          'under',
          'until',
          'up',
          'while',
          'why',
          'yes',
          'also',
          'from',
        ]);
        return token.length > 1 && !stopWords.has(token);
      });
  }
 
  /**
   * Tokenize markdown content into structured components
   */
  private tokenizeContent(content: string, file: TFile): TokenizedContent {
    const title = file.basename;
    const titleTokens = this.tokenize(title);
 
    // Extract headings
    const headingRegex = /^(#{1,6})\s+(.+)$/gm;
    const headings: string[] = [];
    let match: RegExpExecArray | null;
    const headingRegexState = /^(#{1,6})\s+(.+)$/gm;
 
    while ((match = headingRegexState.exec(content)) !== null) {
      headings.push(match[2]);
    }
 
    // Extract frontmatter (YAML between --- markers)
    const frontmatter: Record<string, string> = {};
    const frontmatterRegex = /^---\n([\s\S]*?)\n---/;
    const frontmatterMatch = frontmatterRegex.exec(content);
    if (frontmatterMatch) {
      const frontmatterContent = frontmatterMatch[1];
      const lines = frontmatterContent.split('\n');
      for (const line of lines) {
        const colonIndex = line.indexOf(':');
        if (colonIndex > 0) {
          const key = line.substring(0, colonIndex).trim();
          const value = line.substring(colonIndex + 1).trim();
          frontmatter[key] = value;
        }
      }
    }
 
    // Get frontmatter tokens from values
    const frontmatterTokens = this.tokenize(Object.values(frontmatter).join(' '));
 
    // Extract first paragraph (non-empty lines after frontmatter, stop at paragraph break)
    const cleanContent = content.replace(/^---\n[\s\S]*?\n---/, '').trim();
    const lines = cleanContent.split('\n');
    let firstParagraph = '';
    for (const line of lines) {
      const trimmed = line.trim();
      // Stop at empty line (paragraph break)
      if (!trimmed) {
        break;
      }
      // Skip headings
      if (trimmed.startsWith('#')) {
        continue;
      }
      firstParagraph += trimmed + ' ';
      if (firstParagraph.length > 200) {
        break;
      }
    }
    const firstParagraphTokens = this.tokenize(firstParagraph);
 
    // Get body tokens (limit to prevent memory issues with huge files)
    const bodyText = cleanContent.substring(0, MAX_TOKENS);
    const tokens = this.tokenize(bodyText);
 
    return {
      text: bodyText,
      tokens,
      title,
      titleTokens,
      headings,
      headingTokens: headings.map((h) => this.tokenize(h)),
      frontmatter,
      frontmatterTokens,
      firstParagraph,
      firstParagraphTokens,
    };
  }
 
  /**
   * Calculate a weighted score based on where query tokens appear
   * Uses a combination of position weighting, exact matching, and phrase matching
   */
  private calculateWeightedScore(
    tokenized: TokenizedContent,
    query: string,
    queryTokens: string[]
  ): number {
    let score = 0;
    const queryLower = query.toLowerCase();
    const contentLower = tokenized.text.toLowerCase();
    const contentWithBoundaries = '\\b' + contentLower + '\\b';
 
    // Check for exact phrase match (bonus)
    if (queryLower.length > 0 && contentLower.includes(queryLower)) {
      score += PHRASE_MATCH_BONUS * queryTokens.length;
    }
 
    for (const queryToken of queryTokens) {
      let tokenScore = 0;
 
      // Title match (highest priority)
      if (tokenized.titleTokens.some((t) => this.exactMatch(t, queryToken))) {
        tokenScore += TITLE_WEIGHT;
      }
 
      // Frontmatter match (high priority - often contains tags/categories)
      if (tokenized.frontmatterTokens.some((t) => this.exactMatch(t, queryToken))) {
        tokenScore += FRONTMATTER_WEIGHT;
      }
 
      // Heading match (high priority)
      for (const headingTokens of tokenized.headingTokens) {
        if (headingTokens.some((t) => this.exactMatch(t, queryToken))) {
          tokenScore += HEADING_WEIGHT;
          break; // Only count once per query token
        }
      }
 
      // First paragraph match (medium priority - likely contains topic summary)
      if (tokenized.firstParagraphTokens.some((t) => this.exactMatch(t, queryToken))) {
        tokenScore += FIRST_PARAGRAPH_WEIGHT;
      }
 
      // Body match (lowest priority)
      const bodyMatchCount = tokenized.tokens.filter((t) => this.exactMatch(t, queryToken)).length;
      if (bodyMatchCount > 0) {
        // Use logarithmic scaling to prevent very frequent words from dominating
        tokenScore += BODY_WEIGHT * Math.log(1 + bodyMatchCount);
      }
 
      // Exact word boundary bonus
      if (new RegExp(`\\b${queryToken}\\b`).test(contentLower)) {
        tokenScore *= EXACT_WORD_MATCH_BONUS;
      }
 
      score += tokenScore;
    }
 
    // Normalize by document length to prevent bias toward longer documents
    // Use a gentle normalization: divide by log of token count + 1
    const lengthNorm = Math.log(1 + tokenized.tokens.length / 100);
    Iif (lengthNorm > 1) {
      score /= lengthNorm;
    }
 
    return score;
  }
 
  /**
   * Check for exact or stemmed word match
   * Handles plurals and common suffixes
   */
  private exactMatch(textToken: string, queryToken: string): boolean {
    // Exact match
    if (textToken === queryToken) {
      return true;
    }
 
    // Handle plurals
    if (queryToken.endsWith('s') && textToken === queryToken.slice(0, -1)) {
      return true;
    }
    if (textToken.endsWith('s') && textToken.slice(0, -1) === queryToken) {
      return true;
    }
 
    // Handle -ed and -ing suffixes (simple stemmer)
    const stem = (word: string): string => {
      if (word.endsWith('ing')) return word.slice(0, -3);
      if (word.endsWith('ed')) return word.slice(0, -2);
      return word;
    };
 
    return stem(textToken) === stem(queryToken);
  }
}