| 1 | // Escáner en navegador con la File System Access API (Chrome/Edge). |
| 2 | // Produce el mismo formato compacto que scan.mjs: |
| 3 | // dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes, ignorado?] |
| 4 | // |
| 5 | // El escaneo del árbol es completo y sin límite; el análisis de contenidos |
| 6 | // (modo Blast) se devuelve como `runAnalysis`, una pasada perezosa por lotes |
| 7 | // que se ejecuta con la ciudad ya cargada, prioriza los ficheros clave y |
| 8 | // persiste cada lote, de modo que una ejecución interrumpida continúa donde |
| 9 | // se quedó. |
| 10 | import { IgnoreStack, IGNORE_FILES } from './ignore.js'; |
| 11 | import { isCodeownersFile, isPackageMeta, parseCodeowners, parsePackageMeta } from './ownership.js'; |
| 12 | import { parseGitIndex, gitStatusOf, readHeadCommit } from './gitIndex.js'; |
| 13 | import { isAnalyzable, extractRefs, resolveAll } from './codeLinks.js'; |
| 14 | import { stripCommentsAndStrings, extractDefs, extractTokens, buildSymbolLinks, isIndexable, INDEX_VERSION } from './codeIndex.js'; |
| 15 | import { |
| 16 | loadAnalysisCache, saveAnalysisCache, |
| 17 | loadSnapshot, latestSnapshot, saveSnapshotChunk, pruneSnapshots, |
| 18 | loadSavedHandle, saveHandle, |
| 19 | } from './analysisCache.js'; |
| 20 | import { priorityScore } from './filePriority.js'; |
| 21 | |
| 22 | const SKIP = new Set(['node_modules', '.DS_Store']); |
| 23 | // presupuesto del análisis de código (modo Blast): solo la lectura de |
| 24 | // contenidos tiene tope, y se gasta por orden de prioridad |
| 25 | const ANALYZE_MAX_FILES = 20000; |
| 26 | const ANALYZE_MAX_BYTES = 48 * 1024 * 1024; |
| 27 | // tamaño de lote: tras cada lote se escribe un checkpoint (caché de ficheros |
| 28 | // + chunk de snapshot del commit), de modo que un análisis interrumpido |
| 29 | // continúa desde el último punto de control |
| 30 | const BATCH_FILES = 1500; |
| 31 | const BATCH_BYTES = 8 * 1024 * 1024; |
| 32 | // el refresco de enlaces (resolveAll + buildSymbolLinks sobre lo acumulado) |
| 33 | // es caro y síncrono: se hace cada REFRESH_FILES analizados, no por lote |
| 34 | const REFRESH_FILES = 6000; |
| 35 | // cesión periódica del hilo dentro del lote para no congelar el render |
| 36 | const YIELD_EVERY = 100; |
| 37 | |
| 38 | export function canPickFolder() { |
| 39 | return typeof window.showDirectoryPicker === 'function'; |
| 40 | } |
| 41 | |
| 42 | // pide el permiso de lectura dentro del gesto de usuario: en carpetas grandes |
| 43 | // el primer acceso diferido retrasaba el prompt varios segundos |
| 44 | async function ensureReadPermission(handle) { |
| 45 | if (await handle.queryPermission?.({ mode: 'read' }) === 'granted') return true; |
| 46 | return (await handle.requestPermission?.({ mode: 'read' })) === 'granted'; |
| 47 | } |
| 48 | |
| 49 | export async function pickAndScanFolder(onProgress) { |
| 50 | const handle = await window.showDirectoryPicker(); |
| 51 | if (!await ensureReadPermission(handle)) throw Object.assign(new Error('permiso denegado'), { name: 'AbortError' }); |
| 52 | saveHandle(handle); // para poder reabrir sin picker la próxima vez |
| 53 | return scanHandle(handle, onProgress); |
| 54 | } |
| 55 | |
| 56 | // nombre de la última carpeta abierta (o null), para el botón "Reabrir" |
| 57 | export async function savedFolderName() { |
| 58 | const h = await loadSavedHandle(); |
| 59 | return h?.name ?? null; |
| 60 | } |
| 61 | |
| 62 | export async function reopenLastFolder(onProgress) { |
| 63 | const handle = await loadSavedHandle(); |
| 64 | if (!handle) return null; |
| 65 | if (!await ensureReadPermission(handle)) return null; |
| 66 | return scanHandle(handle, onProgress); |
| 67 | } |
| 68 | |
| 69 | async function scanHandle(handle, onProgress) { |
| 70 | let count = 0; |
| 71 | const stack = new IgnoreStack(); |
| 72 | const ownerRules = []; |
| 73 | const refsMap = {}, fileRels = [], dirRels = []; |
| 74 | const defsMap = {}, tokensMap = {}; |
| 75 | // candidatos a análisis: se recogen durante el paseo y se leen después, |
| 76 | // por lotes y ordenados por prioridad (ver filePriority.js) |
| 77 | const candidates = []; |
| 78 | // rel → { size, entry } pendiente de consolidar en el snapshot del commit; |
| 79 | // se vacía en cada checkpoint (cada chunk escribe solo el delta) |
| 80 | let pendingUsed = {}; |
| 81 | // la caché se carga en paralelo con el índice git y el commit de HEAD |
| 82 | const cachePromise = loadAnalysisCache(); |
| 83 | const newCacheEntries = new Map(); |
| 84 | let cacheHits = 0, snapHits = 0; |
| 85 | |
| 86 | // estado git aproximado: parsea .git/index (sin binario git en el navegador) |
| 87 | let gitIndex = null, headCommit = null; |
| 88 | try { |
| 89 | const gh = await handle.getDirectoryHandle('.git'); |
| 90 | const fh = await gh.getFileHandle('index'); |
| 91 | gitIndex = parseGitIndex(await (await fh.getFile()).arrayBuffer()); |
| 92 | headCommit = await readHeadCommit(gh); |
| 93 | } catch { /* sin .git */ } |
| 94 | const gitMap = gitIndex ? {} : null; |
| 95 | |
| 96 | // capas de reutilización: caché por mtime + snapshots por commit. El |
| 97 | // snapshot del commit actual vale tal cual (aunque el mtime haya cambiado |
| 98 | // por un checkout o re-clone); el de otro commit solo para ficheros |
| 99 | // trackeados cuyo tamaño coincide con el índice git. |
| 100 | const analysisCache = await cachePromise; |
| 101 | const snap = headCommit ? await loadSnapshot(headCommit) : null; |
| 102 | const donor = gitIndex ? await latestSnapshot(headCommit) : null; |
| 103 | |
| 104 | function applyEntry(rel, size, entry, consolidate = true) { |
| 105 | if (entry.specs?.length) refsMap[rel] = entry.specs; |
| 106 | if (entry.defs?.length) defsMap[rel] = entry.defs; |
| 107 | if (entry.tokens?.length) tokensMap[rel] = entry.tokens; |
| 108 | // lo que ya vive en el snapshot del commit actual no se reescribe |
| 109 | if (consolidate) pendingUsed[rel] = { size, entry }; |
| 110 | } |
| 111 | |
| 112 | function snapshotEntry(rel, size) { |
| 113 | const s = snap?.files[rel]; |
| 114 | if (s && s.size === size) return { entry: s.entry, fromCurrent: true }; |
| 115 | const d = donor?.files[rel]; |
| 116 | if (d && d.size === size && gitIndex?.get(rel)?.size === size) { |
| 117 | return { entry: d.entry, fromCurrent: false }; |
| 118 | } |
| 119 | return null; |
| 120 | } |
| 121 | |
| 122 | async function walk(h, rel, forced) { |
| 123 | const dirs = [], files = []; |
| 124 | for await (const e of h.values()) { |
| 125 | (e.kind === 'directory' ? dirs : files).push(e); |
| 126 | } |
| 127 | dirs.sort((a, b) => a.name.localeCompare(b.name)); |
| 128 | files.sort((a, b) => a.name.localeCompare(b.name)); |
| 129 | |
| 130 | let pushed = 0; |
| 131 | for (const f of files) { |
| 132 | const isIgn = IGNORE_FILES.includes(f.name); |
| 133 | const isOwn = !rel.includes('.git') && (isCodeownersFile(f.name) || isPackageMeta(f.name)); |
| 134 | if (!isIgn && !isOwn) continue; |
| 135 | try { |
| 136 | const txt = await (await f.getFile()).text(); |
| 137 | if (isIgn) { stack.push(rel, txt.split('\n')); pushed++; } |
| 138 | if (isOwn) { |
| 139 | if (isCodeownersFile(f.name)) ownerRules.push(...parseCodeowners(txt)); |
| 140 | else { |
| 141 | const rule = parsePackageMeta(txt, rel); |
| 142 | if (rule) ownerRules.push(rule); |
| 143 | } |
| 144 | } |
| 145 | } catch { /* ignorar */ } |
| 146 | } |
| 147 | |
| 148 | const outFiles = [], outDirs = []; |
| 149 | for (const f of files) { |
| 150 | const childRel = rel ? `${rel}/${f.name}` : f.name; |
| 151 | let file = null, size = 0; |
| 152 | try { file = await f.getFile(); size = file.size; } catch { /* ignorar */ } |
| 153 | const ign = forced || stack.ignored(childRel, false); |
| 154 | outFiles.push(ign ? [f.name, size, 1] : [f.name, size]); |
| 155 | fileRels.push(childRel); |
| 156 | count++; |
| 157 | if (count % 200 === 0) onProgress?.(`${count} ficheros`); |
| 158 | if (!file || childRel.startsWith('.git/')) continue; |
| 159 | // estado git aproximado (limpio → sin entrada) |
| 160 | if (gitMap && !ign) { |
| 161 | const st = gitStatusOf(gitIndex, childRel, size, file.lastModified); |
| 162 | if (st) gitMap[childRel] = [st, 0, 0]; |
| 163 | } |
| 164 | // relaciones de código + índice de símbolos (con caché y presupuesto) |
| 165 | const wantRefs = isAnalyzable(f.name, size); |
| 166 | const wantIndex = isIndexable(f.name, size); |
| 167 | if (wantRefs || wantIndex) { |
| 168 | const key = `v${INDEX_VERSION}|${childRel}|${size}|${file.lastModified}`; |
| 169 | const hit = analysisCache.get(key); |
| 170 | const se = hit ? { entry: hit, fromCurrent: false } : snapshotEntry(childRel, size); |
| 171 | if (se) { |
| 172 | hit ? cacheHits++ : snapHits++; |
| 173 | // lo recuperado del snapshot se reescribe con la clave mtime actual |
| 174 | // para que el próximo escaneo acierte por la vía rápida |
| 175 | newCacheEntries.set(key, se.entry); |
| 176 | applyEntry(childRel, size, se.entry, !se.fromCurrent); |
| 177 | } else { |
| 178 | candidates.push({ |
| 179 | file, key, rel: childRel, name: f.name, size, wantRefs, wantIndex, |
| 180 | score: priorityScore(childRel, f.name, size), |
| 181 | }); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | for (const d of dirs) { |
| 186 | if (SKIP.has(d.name)) continue; |
| 187 | const childRel = rel ? `${rel}/${d.name}` : d.name; |
| 188 | if (childRel === '.git/objects') continue; // ruido binario sin interés |
| 189 | const ign = forced || stack.ignored(childRel, true); |
| 190 | dirRels.push(childRel); |
| 191 | outDirs.push(await walk(d, childRel, ign)); |
| 192 | } |
| 193 | while (pushed--) stack.pop(); |
| 194 | return [h.name, outDirs, outFiles]; |
| 195 | } |
| 196 | |
| 197 | const tree = await walk(handle, '', false); |
| 198 | // lo recuperado de caché/snapshot se persiste ya: el primer meta queda |
| 199 | // consolidado aunque el análisis perezoso no llegue a ejecutarse |
| 200 | await saveAnalysisCache(newCacheEntries); |
| 201 | newCacheEntries.clear(); |
| 202 | // la caché en memoria ya no se consulta más: liberarla antes del análisis |
| 203 | // (en repos grandes puede ocupar cientos de MB) |
| 204 | analysisCache.clear(); |
| 205 | console.info(`[fsScan] ${count} ficheros · caché: ${cacheHits} hits, snapshot: ${snapHits} · pendientes de análisis: ${candidates.length}`); |
| 206 | |
| 207 | const buildMeta = () => ({ |
| 208 | links: resolveAll(refsMap, fileRels, dirRels), |
| 209 | codeIndex: { version: INDEX_VERSION, defs: defsMap, symLinks: buildSymbolLinks(defsMap, tokensMap) }, |
| 210 | }); |
| 211 | |
| 212 | // ── análisis perezoso por lotes (se lanza con la ciudad ya cargada) ────── |
| 213 | candidates.sort((a, b) => b.score - a.score); |
| 214 | const total = Math.min(candidates.length, ANALYZE_MAX_FILES); |
| 215 | |
| 216 | async function runAnalysis({ onBatch, onProgress: onTick, isCancelled } = {}) { |
| 217 | let analyzed = 0, analyzedBytes = 0, batchBytes = 0; |
| 218 | let checkpoints = 0, lastRefresh = 0; |
| 219 | |
| 220 | // checkpoint: persiste la caché del lote y el chunk de snapshot (delta); |
| 221 | // si la pestaña muere aquí en adelante, la próxima ejecución parte de esto |
| 222 | async function checkpoint() { |
| 223 | await saveAnalysisCache(newCacheEntries); |
| 224 | newCacheEntries.clear(); |
| 225 | if (headCommit) await saveSnapshotChunk(headCommit, pendingUsed); |
| 226 | pendingUsed = {}; |
| 227 | batchBytes = 0; |
| 228 | checkpoints++; |
| 229 | onTick?.(`análisis ${analyzed}/${total} · checkpoint ${checkpoints}`); |
| 230 | } |
| 231 | |
| 232 | for (const c of candidates) { |
| 233 | if (analyzed >= ANALYZE_MAX_FILES || analyzedBytes >= ANALYZE_MAX_BYTES) break; |
| 234 | if (isCancelled?.()) break; |
| 235 | try { |
| 236 | analyzed++; |
| 237 | analyzedBytes += c.size; |
| 238 | batchBytes += c.size; |
| 239 | const text = await c.file.text(); |
| 240 | const entry = {}; |
| 241 | if (c.wantRefs) { |
| 242 | const specs = extractRefs(c.name, text); |
| 243 | if (specs.length) entry.specs = specs; |
| 244 | } |
| 245 | if (c.wantIndex) { |
| 246 | const clean = stripCommentsAndStrings(text, c.name); |
| 247 | const defs = extractDefs(c.name, clean); |
| 248 | const tokens = [...extractTokens(clean)]; |
| 249 | if (defs.length) entry.defs = defs; |
| 250 | if (tokens.length) entry.tokens = tokens; |
| 251 | } |
| 252 | applyEntry(c.rel, c.size, entry); |
| 253 | newCacheEntries.set(c.key, entry); |
| 254 | } catch { /* ignorar */ } |
| 255 | // ceder el hilo con regularidad: el render no se congela dentro del lote |
| 256 | if (analyzed % YIELD_EVERY === 0) await new Promise(r => setTimeout(r, 0)); |
| 257 | if (newCacheEntries.size >= BATCH_FILES || batchBytes >= BATCH_BYTES) { |
| 258 | await checkpoint(); |
| 259 | // el refresco de enlaces es lo caro: solo cada REFRESH_FILES, no por lote |
| 260 | if (analyzed - lastRefresh >= REFRESH_FILES) { |
| 261 | lastRefresh = analyzed; |
| 262 | onBatch?.(buildMeta()); |
| 263 | await new Promise(r => setTimeout(r, 0)); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | await checkpoint(); |
| 268 | if (headCommit) await pruneSnapshots(headCommit); |
| 269 | if (analyzed) onBatch?.(buildMeta()); |
| 270 | console.info(`[fsScan] análisis perezoso: ${analyzed}/${total} ficheros · ${checkpoints} checkpoints`); |
| 271 | return { analyzed, total }; |
| 272 | } |
| 273 | |
| 274 | return { |
| 275 | tree, |
| 276 | meta: { |
| 277 | git: gitMap, // aproximado desde .git/index (sin +/− líneas) |
| 278 | owners: ownerRules, |
| 279 | ...buildMeta(), // enlaces ya consolidados desde caché/snapshot |
| 280 | }, |
| 281 | pending: total, |
| 282 | runAnalysis, |
| 283 | }; |
| 284 | } |