| 1 | // web.fetch y web.search dicen POR QUÉ no pueden, en vez de callarlo. |
| 2 | // |
| 3 | // En producción el servidor no tiene ruta /proxy (nginx contesta 404): los |
| 4 | // sitios sin CORS no se pueden leer y DuckDuckGo tampoco. Antes web.fetch daba |
| 5 | // «HTTP 404» a secas (se lee como «esa página no existe») y web.search tragaba |
| 6 | // los dos fallos y contestaba «Sin resultados», como si no hubiera nada. Ahora: |
| 7 | // 1. sin proxy (404): las dos lo dicen, con la causa; |
| 8 | // 2. el proxy falla (502): se dice que falló el proxy; |
| 9 | // 3. DuckDuckGo pide su verificación anti-bot: es un bloqueo, no una lista vacía; |
| 10 | // 4. con resultados, los da (y «Sin resultados» solo cuando el buscador |
| 11 | // contestó y no encontró nada); |
| 12 | // 5. un sitio con CORS se lee directo, sin pasar por el proxy. |
| 13 | // Todo con page.route: ninguna petición sale a internet. |
| 14 | // |
| 15 | // BASE=http://localhost:8799 node tests/web-honest.mjs |
| 16 | import { chromium } from 'playwright'; |
| 17 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 18 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + String(e).replace(/\n/g, ' ').slice(0, 150) : '')); if (!c) fails++; }; |
| 19 | |
| 20 | const RESULTADOS = `<html><body><table> |
| 21 | <tr><td><a href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fdeveloper.mozilla.org%2Fes%2Fdocs%2FArray%2Fmap&rut=x">Array.prototype.map() - JavaScript | MDN</a></td></tr> |
| 22 | <tr><td>El método map() crea un nuevo array con los resultados.</td></tr> |
| 23 | </table></body></html>`; |
| 24 | const VACIO = '<html><body><table><tr><td>No results.</td></tr></table></body></html>'; |
| 25 | const ANTIBOT = '<html><body><div class="anomaly-modal__title">Unfortunately, bots use DuckDuckGo too.</div></body></html>'; |
| 26 | |
| 27 | const b = await chromium.launch(); |
| 28 | async function escenario(proxy, { directoCORS = false } = {}) { |
| 29 | const ctx = await b.newContext(); |
| 30 | const p = await ctx.newPage(); |
| 31 | const alProxy = []; |
| 32 | // Los sitios de fuera: sin CORS (el fetch directo falla), salvo que se diga. |
| 33 | await p.route(/^https:\/\/(example\.com|html\.duckduckgo\.com|lite\.duckduckgo\.com)\//, r => directoCORS |
| 34 | ? r.fulfill({ status: 200, contentType: 'text/html', headers: { 'access-control-allow-origin': '*' }, body: '<html><body><p>Example Domain directo</p></body></html>' }) |
| 35 | : r.abort('failed')); |
| 36 | await p.route('**/proxy?url=*', r => { alProxy.push(decodeURIComponent(r.request().url().split('url=')[1] || '')); return proxy(r); }); |
| 37 | await p.goto(BASE + '/manifest.json'); |
| 38 | const llama = (que, args) => p.evaluate(async ({ que, args }) => { |
| 39 | const web = await import('/js/tools/web.js'); |
| 40 | try { return { ok: true, out: await (que === 'search' ? web.search(args) : web.fetchUrl(args)) }; } |
| 41 | catch (e) { return { ok: false, out: String(e.message || e) }; } |
| 42 | }, { que, args }); |
| 43 | return { ctx, alProxy, llama }; |
| 44 | } |
| 45 | |
| 46 | // 1 · sin proxy en el servidor (lo de producción hoy) |
| 47 | { |
| 48 | const { ctx, llama } = await escenario(r => r.fulfill({ status: 404, contentType: 'text/html', body: '<h1>404 Not Found</h1>' })); |
| 49 | const f = await llama('fetch', { url: 'https://example.com' }); |
| 50 | ok('1 · web.fetch sin proxy: falla diciendo que el servidor no tiene el proxy', !f.ok && /no tiene el proxy de respaldo/.test(f.out) && /404/.test(f.out), f.out); |
| 51 | ok(' …y que no es que la página no exista', /No es que la página no exista/.test(f.out), f.out); |
| 52 | const s = await llama('search', { query: 'mdn array map' }); |
| 53 | ok('1 · web.search sin proxy: falla con la causa, NO «Sin resultados»', !s.ok && /no tiene el proxy de respaldo/.test(s.out) && !/Sin resultados/.test(s.out), s.out); |
| 54 | await ctx.close(); |
| 55 | } |
| 56 | // 2 · el proxy existe pero falla |
| 57 | { |
| 58 | const { ctx, llama } = await escenario(r => r.fulfill({ status: 502, contentType: 'text/plain', body: 'proxy: timed out' })); |
| 59 | const f = await llama('fetch', { url: 'https://example.com' }); |
| 60 | ok('2 · el proxy falla: se dice que falló el proxy (HTTP 502)', !f.ok && /proxy del servidor \(HTTP 502\)/.test(f.out), f.out); |
| 61 | await ctx.close(); |
| 62 | } |
| 63 | // 3 · DuckDuckGo pide la verificación anti-bot |
| 64 | { |
| 65 | const { ctx, llama } = await escenario(r => r.fulfill({ status: 202, contentType: 'text/html', body: ANTIBOT })); |
| 66 | const s = await llama('search', { query: 'mdn array map' }); |
| 67 | ok('3 · la verificación anti-bot es un bloqueo, no «Sin resultados»', !s.ok && /bloqueó la consulta/.test(s.out) && !/Sin resultados/.test(s.out), s.out); |
| 68 | await ctx.close(); |
| 69 | } |
| 70 | // 4 · con resultados, y vacío de verdad |
| 71 | { |
| 72 | const { ctx, llama } = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: RESULTADOS })); |
| 73 | const s = await llama('search', { query: 'mdn array map' }); |
| 74 | ok('4 · con resultados: los da, con su URL', s.ok && /Resultados para «mdn array map»/.test(s.out) && /developer\.mozilla\.org/.test(s.out), s.out); |
| 75 | await ctx.close(); |
| 76 | const v = await escenario(r => r.fulfill({ status: 200, contentType: 'text/html', body: VACIO })); |
| 77 | const sv = await v.llama('search', { query: 'xyzzy-nada' }); |
| 78 | ok('4 · y «Sin resultados» cuando el buscador contestó y no encontró nada', sv.ok && /Sin resultados para «xyzzy-nada»/.test(sv.out), sv.out); |
| 79 | await v.ctx.close(); |
| 80 | } |
| 81 | // 5 · un sitio con CORS se lee directo |
| 82 | { |
| 83 | const { ctx, alProxy, llama } = await escenario(r => r.fulfill({ status: 404, body: '' }), { directoCORS: true }); |
| 84 | const f = await llama('fetch', { url: 'https://example.com' }); |
| 85 | ok('5 · con CORS se lee directo y el proxy ni se toca', f.ok && /Example Domain directo/.test(f.out) && alProxy.length === 0, `${f.out} · proxy ${alProxy.length}`); |
| 86 | await ctx.close(); |
| 87 | } |
| 88 | |
| 89 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ WEB: si no puede leer o buscar, dice por qué'); |
| 90 | await b.close(); |
| 91 | process.exit(fails ? 1 : 0); |