| 1 | import { fdir } from "fdir"; |
| 2 | import { AsyncFzf, FzfResultItem } from "fzf"; |
| 3 | |
| 4 | import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; |
| 5 | import { logger } from "../util/logger.js"; |
| 6 | |
| 7 | import { BaseService } from "./BaseService.js"; |
| 8 | import { serviceContainer } from "./ServiceContainer.js"; |
| 9 | |
| 10 | export interface FileItem { |
| 11 | path: string; |
| 12 | displayName: string; |
| 13 | positions?: Set<number>; |
| 14 | } |
| 15 | |
| 16 | export interface FileIndexServiceState { |
| 17 | files: FileItem[]; |
| 18 | isIndexing: boolean; |
| 19 | error: string | null; |
| 20 | } |
| 21 | |
| 22 | export class FileIndexService extends BaseService<FileIndexServiceState> { |
| 23 | private fzf: AsyncFzf<FileItem[]> | null = null; |
| 24 | |
| 25 | // Helper to check if a file should be included based on FILE_PATTERNS |
| 26 | private shouldIncludeFile(filePath: string): boolean { |
| 27 | const fileName = filePath.split("/").pop()?.toLowerCase() || ""; |
| 28 | const ext = fileName.split(".").pop(); |
| 29 | |
| 30 | // Check if file matches any of the original FILE_PATTERNS |
| 31 | const supportedExtensions = [ |
| 32 | "ts", |
| 33 | "tsx", |
| 34 | "js", |
| 35 | "jsx", |
| 36 | "py", |
| 37 | "java", |
| 38 | "cpp", |
| 39 | "c", |
| 40 | "h", |
| 41 | "hpp", |
| 42 | "cs", |
| 43 | "go", |
| 44 | "rs", |
| 45 | "rb", |
| 46 | "php", |
| 47 | "swift", |
| 48 | "kt", |
| 49 | "scala", |
| 50 | "md", |
| 51 | "json", |
| 52 | "yaml", |
| 53 | "yml", |
| 54 | "xml", |
| 55 | "html", |
| 56 | "css", |
| 57 | "scss", |
| 58 | "sass", |
| 59 | "less", |
| 60 | "sql", |
| 61 | "sh", |
| 62 | "dockerfile", |
| 63 | "makefile", |
| 64 | "cmake", |
| 65 | "gradle", |
| 66 | "toml", |
| 67 | "ini", |
| 68 | "env", |
| 69 | "txt", |
| 70 | "log", |
| 71 | ]; |
| 72 | |
| 73 | // Check extension match |
| 74 | if (ext && supportedExtensions.includes(ext)) { |
| 75 | return true; |
| 76 | } |
| 77 | |
| 78 | // Check special file patterns |
| 79 | if ( |
| 80 | fileName.startsWith("readme") || |
| 81 | fileName.startsWith("license") || |
| 82 | fileName.startsWith("changelog") || |
| 83 | fileName === "package.json" || |
| 84 | fileName === "cargo.toml" || |
| 85 | fileName === "pyproject.toml" || |
| 86 | fileName === "composer.json" || |
| 87 | fileName === "gemfile" || |
| 88 | fileName === ".gitignore" || |
| 89 | fileName.startsWith(".env") |
| 90 | ) { |
| 91 | return true; |
| 92 | } |
| 93 | |
| 94 | return false; |
| 95 | } |
| 96 | |
| 97 | constructor() { |
| 98 | super("FileIndexService", { |
| 99 | files: [], |
| 100 | isIndexing: false, |
| 101 | error: null, |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | async doInitialize(): Promise<FileIndexServiceState> { |
| 106 | await this.performFullIndex(); |
| 107 | return this.getState(); |
| 108 | } |
| 109 | |
| 110 | async cleanup(): Promise<void> { |
| 111 | // No cleanup needed - no file watchers or subscriptions |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Override setState to also notify the ServiceContainer |
| 116 | */ |
| 117 | protected setState(newState: Partial<FileIndexServiceState>): void { |
| 118 | super.setState(newState); |
| 119 | |
| 120 | // Also notify the ServiceContainer so UI components get updated |
| 121 | const currentState = this.getState(); |
| 122 | serviceContainer.set("fileIndex", currentState); |
| 123 | } |
| 124 | |
| 125 | private async performFullIndex( |
| 126 | bypassTimeout: boolean = false, |
| 127 | ): Promise<void> { |
| 128 | this.setState({ isIndexing: true, error: null }); |
| 129 | |
| 130 | try { |
| 131 | const currentDir = process.cwd(); |
| 132 | logger.debug(`Starting file index in directory: ${currentDir}`); |
| 133 | |
| 134 | // Create file indexing promise |
| 135 | const fileIndexPromise = new fdir() |
| 136 | .withFullPaths() |
| 137 | .withRelativePaths() |
| 138 | .filter((path) => { |
| 139 | // Use the helper function that implements original FILE_PATTERNS logic |
| 140 | return this.shouldIncludeFile(path); |
| 141 | }) |
| 142 | .exclude((dirName) => { |
| 143 | // Exclude directories based on FILE_IGNORE_PATTERNS |
| 144 | for (const pattern of FILE_IGNORE_PATTERNS) { |
| 145 | if (pattern.startsWith("**/") && pattern.endsWith("/**")) { |
| 146 | const excludeDirName = pattern.slice(3, -3); |
| 147 | if (dirName === excludeDirName) { |
| 148 | return true; |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | return false; |
| 153 | }) |
| 154 | .crawl(currentDir) |
| 155 | .withPromise(); |
| 156 | |
| 157 | let allFiles: string[]; |
| 158 | |
| 159 | if (bypassTimeout) { |
| 160 | // Manual refresh - wait for completion regardless of time |
| 161 | allFiles = await fileIndexPromise; |
| 162 | } else { |
| 163 | // Automatic indexing - race against 1-second timeout |
| 164 | const timeoutPromise = new Promise<"timeout">((resolve) => { |
| 165 | setTimeout(() => { |
| 166 | resolve("timeout"); |
| 167 | }, 1000); |
| 168 | }); |
| 169 | |
| 170 | const result = await Promise.race([fileIndexPromise, timeoutPromise]); |
| 171 | |
| 172 | if (result === "timeout") { |
| 173 | this.setState({ |
| 174 | files: [], |
| 175 | isIndexing: false, |
| 176 | error: "directory-too-large", |
| 177 | }); |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | allFiles = result as string[]; |
| 182 | } |
| 183 | |
| 184 | const fileItems = allFiles.map((path) => ({ |
| 185 | path, |
| 186 | displayName: path, |
| 187 | })); |
| 188 | |
| 189 | this.rebuildFzf(fileItems); |
| 190 | this.setState({ files: fileItems, isIndexing: false }); |
| 191 | |
| 192 | logger.debug(`Indexed ${fileItems.length} files`); |
| 193 | } catch (error) { |
| 194 | const errorMessage = |
| 195 | error instanceof Error ? error.message : String(error); |
| 196 | logger.error("Error performing full file index:", error); |
| 197 | this.setState({ isIndexing: false, error: errorMessage }); |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | private rebuildFzf(files: FileItem[]): void { |
| 202 | this.fzf = new AsyncFzf(files, { |
| 203 | selector: (item: FileItem) => item.path, |
| 204 | casing: "case-insensitive", |
| 205 | }); |
| 206 | } |
| 207 | |
| 208 | // Public API methods |
| 209 | public getFiles(): FileItem[] { |
| 210 | return this.getState().files; |
| 211 | } |
| 212 | |
| 213 | public isIndexing(): boolean { |
| 214 | return this.getState().isIndexing; |
| 215 | } |
| 216 | |
| 217 | public getError(): string | null { |
| 218 | return this.getState().error; |
| 219 | } |
| 220 | |
| 221 | public async refreshIndex(bypassTimeout: boolean = false): Promise<void> { |
| 222 | await this.performFullIndex(bypassTimeout); |
| 223 | } |
| 224 | |
| 225 | public async filterFiles( |
| 226 | filterText: string, |
| 227 | limit: number = 10, |
| 228 | ): Promise<FileItem[]> { |
| 229 | const files = this.getFiles(); |
| 230 | |
| 231 | if (filterText.length === 0) { |
| 232 | // Show files sorted alphabetically when no filter |
| 233 | return [...files] |
| 234 | .sort((a, b) => { |
| 235 | const aFileName = a.path.split("/").pop() || a.path; |
| 236 | const bFileName = b.path.split("/").pop() || b.path; |
| 237 | return aFileName.localeCompare(bFileName); |
| 238 | }) |
| 239 | .slice(0, limit); |
| 240 | } |
| 241 | |
| 242 | // Use fzf for fuzzy search |
| 243 | if (!this.fzf) { |
| 244 | this.rebuildFzf(files); |
| 245 | } |
| 246 | |
| 247 | const results = await this.fzf!.find(filterText); |
| 248 | return results.slice(0, limit).map((entry: FzfResultItem<FileItem>) => ({ |
| 249 | path: entry.item.path, |
| 250 | displayName: entry.item.displayName, |
| 251 | positions: entry.positions, |
| 252 | })); |
| 253 | } |
| 254 | } |