| 1 | // Verifica la caché de modelos por service worker: descarga una vez, se sirve |
| 2 | // desde Cache Storage (incluso OFFLINE) y soporta range requests. Usa un fixture |
| 3 | // .litertlm determinista (byte[i] = i%256) para no bajar los GB reales. |
| 4 | import { chromium } from 'playwright'; |
| 5 | import { writeFileSync, rmSync } from 'node:fs'; |
| 6 | import { fileURLToPath } from 'node:url'; |
| 7 | import { dirname, join } from 'node:path'; |
| 8 | const BASE = process.env.BASE || 'http://localhost:8788'; |
| 9 | const FIX = BASE + '/__test_fixture.litertlm'; |
| 10 | const SIZE = 100000; |
| 11 | let fails = 0; |
| 12 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 13 | |
| 14 | // fixture determinista (byte[i]=i%256) en web/, autolimpiado al terminar |
| 15 | const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); |
| 16 | const FIXPATH = join(WEB, '__test_fixture.litertlm'); |
| 17 | writeFileSync(FIXPATH, Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256))); |
| 18 | const cleanup = () => { try { rmSync(FIXPATH); } catch {} }; |
| 19 | process.on('exit', cleanup); |
| 20 | |
| 21 | const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', '--use-angle=metal'] }); |
| 22 | const ctx = await b.newContext(); |
| 23 | await ctx.addInitScript(() => { try { localStorage.setItem('elffuss.model', 'rules'); } catch {} }); |
| 24 | const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } }); |
| 25 | await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); |
| 26 | |
| 27 | // esperar a que el SW controle la página |
| 28 | const controlled = await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller != null, null, { timeout: 10000 }).then(() => true).catch(() => false); |
| 29 | ok('el service worker controla la página', controlled); |
| 30 | |
| 31 | const fetchInfo = (u, opts) => p.evaluate(async ({ u, opts }) => { |
| 32 | const r = await fetch(u, opts); |
| 33 | const buf = new Uint8Array(await r.arrayBuffer()); |
| 34 | return { status: r.status, len: buf.length, cr: r.headers.get('content-range'), first: [...buf.slice(0, 4)], sample: [...buf.slice(0, 12)] }; |
| 35 | }, { u, opts }); |
| 36 | |
| 37 | // 1) primera descarga (el SW baja el fichero completo y lo cachea) |
| 38 | const r1 = await fetchInfo(FIX); |
| 39 | ok('primera petición devuelve el fichero completo', r1.status === 200 && r1.len === SIZE, `status ${r1.status}, ${r1.len}B`); |
| 40 | |
| 41 | // 2) OFFLINE: si está cacheado, se sigue sirviendo sin red |
| 42 | await ctx.setOffline(true); |
| 43 | const r2 = await fetchInfo(FIX).catch(e => ({ status: 0, err: String(e) })); |
| 44 | ok('OFFLINE se sirve desde la caché (prueba de que quedó cacheado)', r2.status === 200 && r2.len === SIZE, `status ${r2.status}, ${r2.len}B`); |
| 45 | |
| 46 | // 3) range request servido desde el blob cacheado (bytes 10..19) |
| 47 | const r3 = await fetchInfo(FIX, { headers: { Range: 'bytes=10-19' } }); |
| 48 | const expected = Array.from({ length: 10 }, (_, i) => (10 + i) % 256); |
| 49 | ok('range request → 206 con los bytes correctos', r3.status === 206 && r3.len === 10 && JSON.stringify(r3.sample.slice(0, 10)) === JSON.stringify(expected), `status ${r3.status}, cr=${r3.cr}, bytes=${r3.sample}`); |
| 50 | await ctx.setOffline(false); |
| 51 | |
| 52 | // 4) el estimate reporta uso (>0) tras cachear |
| 53 | const est = await p.evaluate(() => navigator.storage.estimate().then(e => ({ usage: e.usage, persisted: null })).catch(() => ({ usage: 0 }))); |
| 54 | ok('storage.estimate refleja el uso cacheado', est.usage > 0, `${(est.usage / 1024 / 1024).toFixed(1)} MB`); |
| 55 | |
| 56 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — descarga 1 vez, persiste y sirve offline + ranges'); |
| 57 | await b.close(); |
| 58 | process.exit(fails ? 1 : 0); |