| 1 | // Sistema de archivos real vía File System Access API (Chrome/Edge). |
| 2 | // Los handles de carpeta se persisten en IndexedDB; el navegador re-pide |
| 3 | // su propio permiso nativo al volver a usarlos en otra sesión. |
| 4 | import * as db from '../db.js'; |
| 5 | import { require as requirePerm } from '../permissions.js'; |
| 6 | import { t } from '../i18n.js'; |
| 7 | |
| 8 | const MAX_READ = 200_000; // caracteres |
| 9 | |
| 10 | export async function pickFolder() { |
| 11 | await requirePerm('fs', t('pdPickFolder')); |
| 12 | if (!window.showDirectoryPicker) |
| 13 | throw new Error(t('fsNoApi')); |
| 14 | const handle = await window.showDirectoryPicker(); |
| 15 | await db.set('fs', handle.name, handle); |
| 16 | return t('fsAuthorized', { name: handle.name }); |
| 17 | } |
| 18 | |
| 19 | export async function folders() { return db.keys('fs'); } |
| 20 | |
| 21 | export async function root(folder) { |
| 22 | await requirePerm('fs'); |
| 23 | const names = await db.keys('fs'); |
| 24 | if (!names.length) |
| 25 | throw new Error(t('fsNoFolder')); |
| 26 | if (folder && !names.includes(folder)) |
| 27 | throw new Error(t('fsUnknownFolder', { folder, names: names.join(', ') })); |
| 28 | const handle = await db.get('fs', folder || names[0]); |
| 29 | // (los handles OPFS no exponen queryPermission — se consideran concedidos) |
| 30 | const perm = handle.queryPermission ? await handle.queryPermission({ mode: 'readwrite' }) : 'granted'; |
| 31 | if (perm !== 'granted' && |
| 32 | (!handle.requestPermission || await handle.requestPermission({ mode: 'readwrite' }) !== 'granted')) |
| 33 | throw new Error(t('fsDenied')); |
| 34 | return handle; |
| 35 | } |
| 36 | |
| 37 | // Excel → CSV (SheetJS, lazy). Devuelve el CSV de la primera hoja. |
| 38 | export async function xlsxToCsv(file) { |
| 39 | const XLSX = await import('https://cdn.sheetjs.com/xlsx-latest/package/xlsx.mjs'); |
| 40 | const wb = XLSX.read(await file.arrayBuffer(), { type: 'array' }); |
| 41 | const sheet = wb.SheetNames[0]; |
| 42 | return { sheet, csv: XLSX.utils.sheet_to_csv(wb.Sheets[sheet]) }; |
| 43 | } |
| 44 | |
| 45 | // Un modelo pequeño suele pasar el NOMBRE de la carpeta raíz como si fuera una |
| 46 | // subcarpeta: fs.list(path="models") cuando la carpeta autorizada YA es «models». |
| 47 | // Lo perdonamos quitando ese primer segmento redundante. |
| 48 | function stripRootName(path, rootName) { |
| 49 | const parts = (path || '').split('/').filter(Boolean); |
| 50 | if (parts.length && parts[0] === rootName) parts.shift(); |
| 51 | return parts; |
| 52 | } |
| 53 | |
| 54 | // Entra en subcarpetas dando un error que ENSEÑA (qué hay) en vez del críptico |
| 55 | // «could not be found». |
| 56 | async function enterDir(dir, parts) { |
| 57 | for (const p of parts) { |
| 58 | try { dir = await dir.getDirectoryHandle(p); } |
| 59 | catch { |
| 60 | const hay = []; |
| 61 | try { for await (const e of dir.values()) hay.push((e.kind === 'directory' ? '📁 ' : '📄 ') + e.name); } catch {} |
| 62 | throw new Error(t('fsNoSubfolder', { sub: p, dir: dir.name, hay: hay.join(', ') || t('fsEmpty') })); |
| 63 | } |
| 64 | } |
| 65 | return dir; |
| 66 | } |
| 67 | |
| 68 | // Recorre 'a/b/c.txt' → { dir: handle de a/b, name: 'c.txt' } |
| 69 | async function walk(handle, path, { create = false } = {}) { |
| 70 | const parts = stripRootName(path, handle.name); |
| 71 | const name = parts.pop(); |
| 72 | for (const p of parts) handle = await handle.getDirectoryHandle(p, { create }); |
| 73 | return { dir: handle, name }; |
| 74 | } |
| 75 | |
| 76 | export async function list({ path = '', folder } = {}) { |
| 77 | const rootH = await root(folder); |
| 78 | const dir = await enterDir(rootH, stripRootName(path, rootH.name)); |
| 79 | const out = []; |
| 80 | for await (const entry of dir.values()) |
| 81 | out.push(`${entry.kind === 'directory' ? '📁' : '📄'} ${entry.name}`); |
| 82 | return out.length ? out.sort().join('\n') : t('fsEmptyFolder'); |
| 83 | } |
| 84 | |
| 85 | export async function read({ path, folder } = {}) { |
| 86 | if (!path) throw new Error(t('toolMissing', { arg: 'path' })); |
| 87 | const { dir, name } = await walk(await root(folder), path); |
| 88 | const file = await (await dir.getFileHandle(name)).getFile(); |
| 89 | if (/\.xlsx?$/i.test(name)) { // Excel: binario → CSV legible |
| 90 | const { sheet, csv } = await xlsxToCsv(file); |
| 91 | const body = csv.length > MAX_READ ? csv.slice(0, MAX_READ) + '\n' + t('cutMark') : csv; |
| 92 | return t('fsSheetCsv', { name, sheet }) + '\n' + body; |
| 93 | } |
| 94 | const text = await file.text(); |
| 95 | return text.length > MAX_READ |
| 96 | ? text.slice(0, MAX_READ) + '\n' + t('fsCutBytes', { n: file.size }) |
| 97 | : text; |
| 98 | } |
| 99 | |
| 100 | export async function write({ path, content = '', folder } = {}) { |
| 101 | if (!path) throw new Error(t('toolMissing', { arg: 'path' })); |
| 102 | const { dir, name } = await walk(await root(folder), path, { create: true }); |
| 103 | const fh = await dir.getFileHandle(name, { create: true }); |
| 104 | const w = await fh.createWritable(); |
| 105 | await w.write(content); |
| 106 | await w.close(); |
| 107 | return t('fsWritten', { path, n: content.length }); |
| 108 | } |
| 109 | |
| 110 | export const globToRegex = pattern => new RegExp( |
| 111 | '^' + pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$', 'i'); |
| 112 | |
| 113 | // Copia one-shot entre dos carpetas autorizadas (pattern tipo *.txt). |
| 114 | export async function copy({ pattern = '*', from, to } = {}) { |
| 115 | if (!from || !to) throw new Error(t('fsMissingFromTo')); |
| 116 | const src = await root(from), dst = await root(to); |
| 117 | const rx = globToRegex(pattern); |
| 118 | const copied = []; |
| 119 | for await (const entry of src.values()) { |
| 120 | if (entry.kind !== 'file' || !rx.test(entry.name)) continue; |
| 121 | const data = await (await entry.getFile()).arrayBuffer(); |
| 122 | const fh = await dst.getFileHandle(entry.name, { create: true }); |
| 123 | const w = await fh.createWritable(); |
| 124 | await w.write(data); |
| 125 | await w.close(); |
| 126 | copied.push(entry.name); |
| 127 | } |
| 128 | return copied.length |
| 129 | ? t('fsCopied', { n: copied.length, from, to, files: copied.join(', ') }) |
| 130 | : t('fsNothingToCopy', { pattern, from }); |
| 131 | } |