| 1 | // web.fetch y web.search cuando algo falla, y ■ con una descarga en curso. |
| 2 | // Sin red: todo lo de fuera lo contesta la prueba (rutas de Playwright). |
| 3 | // · Sin el proxy de respaldo (/proxy en 404, como estuvo producción semanas), |
| 4 | // web.fetch dice que no hay proxy y no «HTTP 404» a secas, y web.search |
| 5 | // falla diciendo por qué en vez de «Sin resultados». |
| 6 | // · Un 404 del propio sitio es «esa página no existe», haya proxy o no. |
| 7 | // · La verificación anti-bot de DuckDuckGo es un bloqueo, no una lista vacía. |
| 8 | // · Con el buscador contestando de verdad, salen los resultados. |
| 9 | // · ■ (la señal del turno) corta la descarga en curso y no prueba el proxy. |
| 10 | // |
| 11 | // BASE=http://localhost:8743 node tests/web-tools.mjs |
| 12 | import { navegador, contexto, pagina, ok, hasta, fin, BASE } from './ux-comun.mjs'; |
| 13 | |
| 14 | const b = await navegador(); |
| 15 | const estado = { proxy: 404, ddg: 'ok', vistos: [] }; |
| 16 | const DDG_OK = '<html><body><table><tr><td><a href="/l/?uddg=https%3A%2F%2Fejemplo.org%2Fhistoria-del-reloj&rut=x">Historia del reloj</a> Un repaso a la historia del reloj.</td></tr></table></body></html>'; |
| 17 | const DDG_ANOMALIA = '<html><body><form id="challenge-form" action="/anomaly.js"><p>Unfortunately, bots use DuckDuckGo too.</p></form></body></html>'; |
| 18 | const { ctx } = await contexto(b, { |
| 19 | grants: ['web'], |
| 20 | rutas: async (url, route) => { |
| 21 | estado.vistos.push(url); |
| 22 | // Un sitio sin CORS: el fetch directo del navegador falla sin respuesta. |
| 23 | if (url.startsWith('https://sin-cors.ejemplo/')) { await route.abort('failed'); return true; } |
| 24 | // Un sitio que contesta (con CORS) que la página no existe. |
| 25 | if (url.startsWith('https://con-cors.ejemplo/')) { |
| 26 | await route.fulfill({ status: 404, headers: { 'access-control-allow-origin': '*' }, body: 'no existe' }); return true; |
| 27 | } |
| 28 | // Una descarga que no termina nunca (para ■). |
| 29 | if (url.startsWith('https://lento.ejemplo/')) { await new Promise(r => setTimeout(r, 4000)); await route.abort('failed').catch(() => {}); return true; } |
| 30 | // DuckDuckGo directo: sin CORS, como el de verdad. |
| 31 | if (/duckduckgo\.com\//.test(url)) { await route.abort('failed'); return true; } |
| 32 | return false; |
| 33 | }, |
| 34 | }); |
| 35 | // El proxy del servidor, contestado por la prueba: 404 (no existe), la página de |
| 36 | // DuckDuckGo (normal o la de verificación) o el texto de la URL pedida. |
| 37 | const esProxy = u => u.origin === new URL(BASE).origin && u.pathname === '/proxy'; |
| 38 | await ctx.route(esProxy, async route => { |
| 39 | const pedida = decodeURIComponent(new URL(route.request().url()).searchParams.get('url') || ''); |
| 40 | estado.vistos.push('proxy:' + pedida); |
| 41 | if (estado.proxy === 404) return route.fulfill({ status: 404, contentType: 'text/html', body: '<html><body>404 Not Found</body></html>' }); |
| 42 | if (/duckduckgo\.com\//.test(pedida)) return route.fulfill({ status: 200, contentType: 'text/html', body: estado.ddg === 'anomalia' ? DDG_ANOMALIA : DDG_OK }); |
| 43 | return route.fulfill({ status: 200, contentType: 'text/html', body: '<html><body><p>Texto de ' + pedida + '</p></body></html>' }); |
| 44 | }); |
| 45 | const { p, errores } = await pagina(ctx); |
| 46 | |
| 47 | const llamar = (tool, args, pararTrasMs = null) => p.evaluate(async ({ tool, args, pararTrasMs }) => { |
| 48 | const { runTool } = await import('/js/tools/index.js'); |
| 49 | const ctl = new AbortController(); |
| 50 | if (pararTrasMs != null) setTimeout(() => ctl.abort(), pararTrasMs); |
| 51 | const t0 = performance.now(); |
| 52 | try { return { ok: true, res: await runTool(tool, args, { signal: ctl.signal }), rapido: performance.now() - t0 < 2000 }; } |
| 53 | catch (e) { return { ok: false, err: String(e?.message || e), nombre: e?.name || '', rapido: performance.now() - t0 < 2000 }; } |
| 54 | }, { tool, args, pararTrasMs }); |
| 55 | |
| 56 | // ── sin proxy de respaldo ──────────────────────────────────────────────────── |
| 57 | estado.proxy = 404; |
| 58 | const f1 = await llamar('web.fetch', { url: 'https://sin-cors.ejemplo/pagina' }); |
| 59 | ok('sin proxy, web.fetch dice que este servidor no tiene el proxy de respaldo (no «HTTP 404» a secas)', |
| 60 | !f1.ok && /proxy de respaldo/.test(f1.err) && /no dice nada de si la página existe/.test(f1.err) && f1.err !== 'HTTP 404', f1.err); |
| 61 | const s1 = await llamar('web.search', { query: 'historia del reloj' }); |
| 62 | ok('sin proxy, web.search falla diciendo por qué, no «Sin resultados»', !s1.ok && /proxy de respaldo/.test(s1.err), s1.ok ? s1.res : s1.err); |
| 63 | const f2 = await llamar('web.fetch', { url: 'https://con-cors.ejemplo/no-esta' }); |
| 64 | ok('un 404 del propio sitio es «esa página no existe»', !f2.ok && /no existe/.test(f2.err) && !/proxy/.test(f2.err), f2.err); |
| 65 | |
| 66 | // ── con proxy ──────────────────────────────────────────────────────────────── |
| 67 | estado.proxy = 200; estado.ddg = 'anomalia'; |
| 68 | const s2 = await llamar('web.search', { query: 'historia del reloj' }); |
| 69 | ok('la verificación anti-bot de DuckDuckGo es un bloqueo, no una lista vacía', !s2.ok && /bloqueó la consulta/.test(s2.err), s2.ok ? s2.res : s2.err); |
| 70 | estado.ddg = 'ok'; |
| 71 | const s3 = await llamar('web.search', { query: 'historia del reloj' }); |
| 72 | ok('con el buscador contestando, salen los resultados con su enlace', s3.ok && /Resultados para «historia del reloj»/.test(s3.res) && /https:\/\/ejemplo\.org\/historia-del-reloj/.test(s3.res), s3.ok ? s3.res.slice(0, 120) : s3.err); |
| 73 | const f3 = await llamar('web.fetch', { url: 'https://sin-cors.ejemplo/otra' }); |
| 74 | ok('y web.fetch de un sitio sin CORS sale por el proxy', f3.ok && /Texto de https:\/\/sin-cors\.ejemplo\/otra/.test(f3.res), f3.ok ? f3.res.slice(0, 80) : f3.err); |
| 75 | |
| 76 | // ── ■ con una descarga en curso ────────────────────────────────────────────── |
| 77 | estado.vistos = []; |
| 78 | const f4 = await llamar('web.fetch', { url: 'https://lento.ejemplo/pesado' }, 150); |
| 79 | ok('■ corta la descarga en curso: web.fetch acaba al momento con AbortError', !f4.ok && f4.nombre === 'AbortError' && f4.rapido, JSON.stringify(f4)); |
| 80 | ok('…y no prueba el proxy después de parar', !estado.vistos.some(u => u.startsWith('proxy:https://lento.ejemplo')), JSON.stringify(estado.vistos)); |
| 81 | |
| 82 | // ── en inglés, los mismos avisos en inglés ─────────────────────────────────── |
| 83 | { |
| 84 | const { ctx: c2 } = await contexto(b, { locale: 'en-US', grants: ['web'], |
| 85 | rutas: async (url, route) => { if (url.startsWith('https://sin-cors.ejemplo/')) { await route.abort('failed'); return true; } return false; } }); |
| 86 | await c2.route(esProxy, route => route.fulfill({ status: 404, contentType: 'text/html', body: 'nope' })); |
| 87 | const { p: q } = await pagina(c2); |
| 88 | const r = await q.evaluate(async () => { |
| 89 | const { runTool } = await import('/js/tools/index.js'); |
| 90 | try { await runTool('web.fetch', { url: 'https://sin-cors.ejemplo/x' }); return 'sin error'; } catch (e) { return String(e.message); } |
| 91 | }); |
| 92 | ok('en inglés el aviso está en inglés', /no fallback proxy/.test(r) && !/No pude/.test(r), r); |
| 93 | await c2.close(); |
| 94 | } |
| 95 | |
| 96 | ok('sin errores de página', errores.length === 0, errores.slice(0, 3).join(' | ')); |
| 97 | await fin(b, 'WEB: sin proxy o bloqueado se dice por qué, y ■ corta la descarga'); |