Spaces:
Running
Running
Read pages in the browser: libcurl.js relays with UA ladder, Reddit via Arctic Shift, Wikipedia API, raw-HTML search
Browse filesWaterfall: direct fetch -> libcurl.js (WISP relays; Safari UA, then facebookexternalhit/Slackbot/Twitterbot on 202/401/403/405/429 or bot-check pages; relay hopping) -> Jina (X-No-Cache) -> defuddle -> Wayback. Search: DuckDuckGo and Bing raw HTML via libcurl.js, then the previous readers. Reddit threads/subreddits from the Arctic Shift archive. Control characters stripped from displayed page text; visualViewport fit for phone keyboards. libcurl.js 0.7.5 (LGPL-3.0) from jsDelivr with SRI.
Files changed (5)
- index.html+4-1
- main.js+6-1
- net.jsAdded+131
- reddit.jsAdded+64
- tools.js+48-4
45 unmodified lines46474849495051525354555657585945 unmodified lines The terminal is a small safe runner written in JavaScript for <code>head tail rg grep sed wc sort uniq cut tr nl</code>; there is no shell. Private and local addresses are refused, as are huggingface.co pages (as upstream blocks them). Each filter pipeline is limited to 5 seconds.</p> <p><b>One addition.</b> The system prompt is Ai2's, plus one line giving today's date (the model does not know it and otherwise searches for old news). Add <code>?date=0</code> to the address to remove it.</p> <p><b>Honest limits.</b> A 4-bit-class model on a free search stack is not the paper's setup: results can be thinner than the reported benchmarks, the free services rate-limit (about 20 page reads a minute, so steps can pause), and answers can be wrong. Check the sources it cites. The model runs on your device; your search queries and the URLs it opens are sent to DuckDuckGo/Brave and Jina (anonymously, from your browser).</p> The model runs on your device; your search queries and the URLs it opens are sent to DuckDuckGo/Bing and, when a site cannot be read directly, through a public relay server (libcurl.js, which keeps the page content private from the relay) or Jina Reader. Reddit threads come from the Arctic Shift archive.</p> <p id="store"></p> <button id="wipe" type="button">Delete downloaded model</button> </details></main><!-- libcurl.js 0.7.5 (c) ading2210, LGPL-3.0-or-later, https://github.com/ading2210/libcurl.js : libcurl compiled to WebAssembly, loaded unmodified from the jsDelivr CDN (pinned version, integrity hash). It reads web pages through public WISP relays when the browser cannot read a site directly. --><script defer src="https://cdn.jsdelivr.net/npm/libcurl.js@0.7.5/libcurl_full.js" integrity="sha384-3tdG8O0pBzLL/H5gcrzmrzTwUw8EXM6vr2qszHS0OBDWH6jFWCEVlK/QZREme5D8" crossorigin="anonymous"></script><script type="module" src="main.js"></script></body></html>43 unmodified lines44454647484950512 unmodified lines5455565557585960143 unmodified lines20420520620720820943 unmodified lines})().catch((e) => { enginePromise = null; throw e; }));
// ---------------------------------------------------------------- transcript// Page text comes from untrusted sites: shown only through textContent, with control characters stripped.const safe = (t) => String(t).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '');function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }
function stepCard(n) {2 unmodified lines d.open = true; d.append(s); ui.trail.prepend(d); // newest on top, open while it works; older steps stay collapsed below return { d, set(tool, arg) { s.children[1].textContent = tool; s.children[2].textContent = arg || ''; }, think(text) { let t = d.querySelector('.think'); if (!t) { t = el('div', 'think'); d.append(t); } t.textContent = text; t.scrollTop = t.scrollHeight; }, result(text) { d.querySelector('pre')?.remove(); d.append(el('pre', '', text)); d.classList.remove('live'); } }; result(text) { d.querySelector('pre')?.remove(); d.append(el('pre', '', safe(text))); d.classList.remove('live'); } }; // (the card is closed by the research loop once its tool result is in)}
143 unmodified linesui.wipe.addEventListener('click', async () => { try { const root = await navigator.storage.getDirectory(); for await (const [name] of root.entries()) await root.removeEntry(name, { recursive: true }); } catch { /* nothing cached */ } enginePromise = null; ui.store.textContent = 'Deleted. The model downloads again next time.'; });storage();window.__dr = { loadEngine, research }; // test hook
// Inside a Space the page sits in an iframe: on phones the soft keyboard changes the visual viewport but not 100vh, hiding the text box.if (window.visualViewport) { const fit = () => { document.body.style.height = visualViewport.height + 'px'; }; visualViewport.addEventListener('resize', fit); fit(); }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131// Network layer for the page-reading and search tools. Order, cheapest and most private first:// 1. direct fetch() the visitor's own (residential) IP; works only when the site sends CORS headers (APIs, Wikipedia, ...)// 2. libcurl.js libcurl compiled to WebAssembly: it speaks TLS itself and tunnels TCP over a public WISP relay (a WebSocket// proxy), so it needs no CORS permission, returns the raw HTML and may set any header, User-Agent included.// Traffic then leaves from the relay's IP, which is why it only runs when step 1 failed. The TLS handshake// is inside the WebAssembly, so a relay sees which host is contacted, not the content.// (Jina Reader, defuddle.md and the Wayback Machine are tried by tools.js when both of these fail.)// The retry policy follows sharp-search (github.com/Belluxx/sharp-search, MIT): Safari-like request first; on 202/401/403/405/429 or a// bot-check page, retry as the link-preview crawlers many sites let through; keep whichever answer has the most text.
export const SAFARI_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15';export const BOT_UAS = ['facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)', 'Slackbot-LinkExpanding 1.0 (+https://api.slack.com/robots)', 'Twitterbot/1.0'];const REFUSALS = new Set([202, 401, 403, 405, 429]);export const CHALLENGE = /(id="anubis_version"|anubis_challenge|making sure you(?:'|')re not a bot|_incapsula_resource|ak_bmsc|attention required! \| cloudflare|cf-browser-verification|just a moment\.\.\.|challenge-platform|captcha-delivery\.com|px-captcha)/i;
// Public WISP relays (volunteer-run). Shuffled once per visit so no single relay takes everyone's traffic.const RELAYS = ['wss://wisp.mercurywork.shop/', 'wss://anura.pro/', 'wss://fern.best/', 'wss://wisp.terbiumon.top/wisp/', 'wss://tomp.app/wisp', 'wss://nebulaservices.org/wisp/', 'wss://relay.widgetry.org/', 'wss://linuxontab-net.fly.dev/wisp'].sort(() => Math.random() - 0.5);let relayAt = 0;const relay = () => RELAYS[relayAt % RELAYS.length];function hopRelay() { // a different relay is a different exit IP relayAt++; try { lc().set_websocket(relay()); return true; } catch { return false; }}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));const aborted = (signal) => { if (signal?.aborted) throw new DOMException('Stopped', 'AbortError'); };const withTimeout = (signal, ms) => { // AbortSignal.any is not in every browser yet const c = new AbortController(), t = setTimeout(() => c.abort(), ms), on = () => c.abort(); signal?.addEventListener('abort', on, { once: true }); return { signal: c.signal, done: () => { clearTimeout(t); signal?.removeEventListener('abort', on); } };};
// ------------------------------------------------------------------------------------------ libcurl.js loaderlet curlReady = null, curlDead = false;const lc = () => (typeof libcurl !== 'undefined' ? libcurl : null); // libcurl.js declares a top-level `const libcurl`: it is a global binding, not a window propertyexport function ensureLibcurl() { // the <script> tag in index.html may finish before or after we ask: handle both, with a timeout if (curlDead) return Promise.reject(new Error('libcurl.js unavailable')); return (curlReady ||= (async () => { const limit = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(what)), ms))]); await limit(new Promise((res) => { if (lc()) return res(); const iv = setInterval(() => { if (lc()) { clearInterval(iv); res(); } }, 100); }), 12000, 'libcurl.js did not load (blocked CDN?)'); await limit(lc().load_wasm('libcurl.wasm'), 12000, 'libcurl.js wasm did not start'); lc().set_websocket(relay()); })().catch((e) => { curlDead = true; throw e; }));}
// ------------------------------------------------------------------------------------------ fetchingconst visibleLen = (t) => t.replace(/<(script|style)[\s\S]*?<\/\1>/gi, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().length;const bad = (status, text) => REFUSALS.has(status) || status >= 500 || CHALLENGE.test(text.slice(0, 6000));
async function direct(url, signal, ms = 8000) { const t = withTimeout(signal, ms); try { const r = await fetch(url, { signal: t.signal, headers: { Accept: 'text/html,application/json,*/*;q=0.8' } }); return { status: r.status, text: await r.text(), how: 'direct' }; } finally { t.done(); }}async function viaCurl(url, ua, signal, ms = 20000) { const t = withTimeout(signal, ms); try { const r = await lc().fetch(url, { signal: t.signal, headers: { 'User-Agent': ua, Accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.9' } }); return { status: r.status, text: await r.text(), how: 'libcurl', ua: ua.split(/[\/ ]/)[0] }; } finally { t.done(); }}
// Returns { status, text, how, tried } for the best answer found, or { status: 0, text: '', tried } when every route failed.export async function rawFetch(url, { signal, direct: tryDirect = true, deadline = 75000 } = {}) { const tried = [], t0 = Date.now(), over = () => Date.now() - t0 > deadline; const stopped = (e) => { if (e?.name === 'AbortError' && signal?.aborted) throw e; }; if (tryDirect) { try { const r = await direct(url, signal); tried.push(`direct HTTP ${r.status}`); if (r.status < 400 && r.text.trim() && !CHALLENGE.test(r.text.slice(0, 6000))) return { ...r, tried }; } catch (e) { stopped(e); tried.push('direct blocked by CORS'); } } try { await ensureLibcurl(); } catch (e) { tried.push(String(e.message || e)); return { status: 0, text: '', tried }; } let best = null, hops = 0, i = 0; const ladder = [SAFARI_UA, ...BOT_UAS]; while (i < ladder.length && !over()) { aborted(signal); const ua = ladder[i]; let r; try { r = await viaCurl(url, ua, signal); } catch (e) { // relay down or TLS refused: another relay, same user agent stopped(e); tried.push(`libcurl ${ua.split(/[\/ ]/)[0]}: ${String(e?.message || e).slice(0, 40)}`); if (hops++ < 3 && hopRelay()) continue; i++; continue; } tried.push(`libcurl ${r.ua} HTTP ${r.status}`); if (r.status >= 500 && hops++ < 3 && hopRelay()) continue; const ok = r.status < 400 && r.text.trim() && !CHALLENGE.test(r.text.slice(0, 6000)); if (ok && (!best || visibleLen(r.text) > visibleLen(best.text))) best = r; if (ok && visibleLen(r.text) >= 500) break; // real content: done. Sparse page: a crawler user agent may be served the full text, keep trying if (bad(r.status, r.text) && i === ladder.length - 1 && hops++ < 3 && hopRelay()) { i = 0; continue; } // all user agents refused: new exit IP, start over i++; } return best ? { ...best, tried } : { status: 0, text: '', tried };}
// ------------------------------------------------------------------------------------------ HTML -> markdownconst SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'SVG', 'IFRAME', 'TEMPLATE', 'NAV', 'FOOTER', 'ASIDE', 'FORM', 'BUTTON', 'SELECT', 'HEAD', 'DIALOG']);const BLOCK = new Set(['P', 'DIV', 'SECTION', 'ARTICLE', 'MAIN', 'HEADER', 'UL', 'OL', 'LI', 'TABLE', 'TR', 'BLOCKQUOTE', 'PRE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'FIGURE', 'DL', 'DT', 'DD', 'HR', 'BR']);function abs(href, base) { try { const u = new URL(href, base); return /^https?:$/.test(u.protocol) ? u.href : ''; } catch { return ''; } }
export function htmlToMarkdown(html, base) { const doc = new DOMParser().parseFromString(html, 'text/html'); const title = (doc.querySelector('title')?.textContent || '').replace(/\s+/g, ' ').trim(); const roots = [...doc.querySelectorAll('main, article, [role=main]')].sort((a, b) => b.textContent.length - a.textContent.length); const root = roots[0] && roots[0].textContent.trim().length > 600 ? roots[0] : doc.body; let out = ''; const walk = (n, ctx = {}) => { if (n.nodeType === 3) { out += ctx.pre ? n.nodeValue : n.nodeValue.replace(/\s+/g, ' '); return; } if (n.nodeType !== 1 || SKIP.has(n.tagName.toUpperCase()) || n.hasAttribute('hidden') || n.getAttribute('aria-hidden') === 'true') return; const t = n.tagName.toUpperCase(); if (t === 'A') { const href = abs(n.getAttribute('href') || '', base), label = n.textContent.replace(/\s+/g, ' ').trim(); if (!label) return; if (href && !href.startsWith('javascript:') && !(n.getAttribute('href') || '').startsWith('#')) out += `[${label}](${href})`; else out += label; return; } if (/^H[1-6]$/.test(t)) { out += `\n\n${'#'.repeat(+t[1])} `; n.childNodes.forEach((c) => walk(c, ctx)); out += '\n\n'; return; } if (t === 'LI') { out += '\n- '; n.childNodes.forEach((c) => walk(c, ctx)); return; } if (t === 'PRE') { out += '\n\n```\n'; n.childNodes.forEach((c) => walk(c, { ...ctx, pre: true })); out += '\n```\n\n'; return; } if (t === 'TD' || t === 'TH') { n.childNodes.forEach((c) => walk(c, ctx)); out += ' | '; return; } if (t === 'BLOCKQUOTE') { out += '\n\n> '; n.childNodes.forEach((c) => walk(c, ctx)); out += '\n\n'; return; } if (t === 'IMG') { const alt = (n.getAttribute('alt') || '').trim(); if (alt.length > 3) out += `[image: ${alt}]`; return; } const block = BLOCK.has(t); if (block) out += t === 'BR' ? '\n' : '\n'; n.childNodes.forEach((c) => walk(c, ctx)); if (block && t !== 'BR') out += '\n'; }; walk(root); const body = out.replace(/[ \t]+\n/g, '\n').replace(/\n[ \t]+/g, '\n').replace(/ {2,}/g, ' ').replace(/\n{3,}/g, '\n\n').trim(); return (title ? `Title: ${title}\n\nURL Source: ${base}\n\nMarkdown Content:\n` : `URL Source: ${base}\n\nMarkdown Content:\n`) + body;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364// Reddit threads and subreddit listings from Arctic Shift (arctic-shift.photon-reddit.com), a public archive of Reddit that is// key-less and sends CORS headers, so the visitor's own browser can read it directly. Reddit itself blocks datacenter IPs, readers// and anonymous API access (its logged-out RSS ended in November 2026). The archive lags live Reddit by minutes to hours, so very// fresh threads can show fewer comments and older scores; the output says so.const API = 'https://arctic-shift.photon-reddit.com/api';const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export function redditTarget(url) { let u; try { u = new URL(url); } catch { return null; } if (!/(^|\.)reddit\.com$/.test(u.hostname) && u.hostname !== 'redd.it') return null; const t = u.pathname.match(/^\/r\/([^/]+)\/comments\/([a-z0-9]+)/i); if (t) return { kind: 'thread', sub: t[1], id: t[2].toLowerCase() }; if (u.hostname === 'redd.it') { const m = u.pathname.match(/^\/([a-z0-9]+)/i); if (m) return { kind: 'thread', sub: '', id: m[1].toLowerCase() }; } const s = u.pathname.match(/^\/r\/([^/]+)\/?(?:hot|new|top|rising|best)?\/?$/i); if (s) return { kind: 'sub', sub: s[1] }; return null;}
async function api(path, signal) { for (let attempt = 0; attempt < 3; attempt++) { if (signal?.aborted) throw new DOMException('Stopped', 'AbortError'); const r = await fetch(API + path, { signal }); if (r.status === 429) { await sleep(Math.min(20, Math.max(2, +r.headers.get('x-ratelimit-reset') || 5)) * 1000); continue; } // the API tells us how long to wait if (!r.ok) throw new Error(`archive HTTP ${r.status}`); return (await r.json()).data; } throw new Error('archive rate limit');}
const when = (s) => (s ? new Date(s * 1000).toISOString().slice(0, 10) : '');const oneLine = (s) => String(s || '').replace(/\s+/g, ' ').trim();const NOTE = '(From the Arctic Shift archive of Reddit; it can lag live Reddit, so recent comments and scores may be missing.)';
function comments(list, depth, out) { for (const n of list || []) { if (n.kind !== 't1') continue; const c = n.data; out.push(`${' '.repeat(depth)}- u/${c.author} (${c.score ?? '?'}): ${oneLine(c.body)}`); const kids = c.replies?.data?.children; if (kids && depth < 8) comments(kids, depth + 1, out); }}
export async function redditArchive(url, signal) { const t = redditTarget(url); if (!t) return ''; if (t.kind === 'thread') { const posts = await api(`/posts/ids?ids=${t.id}`, signal); const p = posts?.[0]; if (!p) return ''; await sleep(1200); // the archive's rate limit is tight: space the two calls let tree = []; try { tree = await api(`/comments/tree?link_id=t3_${t.id}&limit=200`, signal) || []; } catch (e) { if (e.name === 'AbortError') throw e; } const lines = []; comments(tree, 0, lines); return [`Title: ${p.title}`, `URL Source: ${url}`, '', 'Markdown Content:', `# ${p.title}`, `r/${p.subreddit} · u/${p.author} · ${when(p.created_utc)} · score ${p.score} · ${p.num_comments} comments`, NOTE, '', oneLine(p.selftext) || (p.url && !/reddit\.com/.test(p.url) ? `Link: ${p.url}` : ''), '', `## Comments (${lines.length} shown)`, ...(lines.length ? lines : ['(no comments in the archive yet)'])].join('\n'); } const posts = await api(`/posts/search?subreddit=${encodeURIComponent(t.sub)}&sort=desc&limit=25&fields=id,title,score,num_comments,created_utc,author,url`, signal); if (!posts?.length) return ''; return [`Title: r/${t.sub} (newest posts)`, `URL Source: ${url}`, '', 'Markdown Content:', `# r/${t.sub}: newest posts`, NOTE, '', ...posts.map((p) => `- ${p.title} (${when(p.created_utc)}, score ${p.score}, ${p.num_comments} comments) https://www.reddit.com/r/${t.sub}/comments/${p.id}/`)].join('\n');}6 unmodified lines789101112131446 unmodified lines6162636263646465666768697071727374757677787980818283848581 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002011582022032042056 unmodified lines// (both CORS-enabled APIs) as fallbacks. No backend, no keys.
import { pyJson } from './agent.js';import { rawFetch, htmlToMarkdown } from './net.js';import { redditTarget, redditArchive } from './reddit.js';
export const MAX_OUTPUT = 10_000; // the model is told terminal output is capped at 10,000 charactersconst READER = 'https://r.jina.ai/';46 unmodified lines try { const r = await fn(); tried.push(`${name} HTTP ${r.status}`); if (r.status < 400 && usable(r.text)) text = r.text; } catch (e) { if (e?.name === 'AbortError' && outer?.aborted) throw e; tried.push(`${name} ${e?.name === 'AbortError' ? 'timeout' : 'unreachable'}`); } }; await attempt('reader', () => getText(url, { reader: true, timeout: 45000 })); // 1. Jina Reader: renders JavaScript, strips boilerplate await attempt('defuddle', () => getText('https://defuddle.md/' + url, { timeout: 30000 })); // 2. defuddle.md: another free, CORS-enabled reader; fetches from other IPs than Jina (reads some sites Jina refuses) await attempt('direct', async () => { const r = await getText(url, { timeout: 15000 }); return { ...r, text: r.status < 400 ? htmlToText(r.text) : '' }; }); // 3. the page itself, when its server allows cross-origin reads if (redditTarget(url)) { // 0. Reddit blocks readers and datacenters: its public archive (CORS-enabled) first try { const t = await redditArchive(url, outer); if (t) { text = t; tried.push('reddit archive'); } else tried.push('reddit archive empty'); } catch (e) { if (e?.name === 'AbortError' && outer?.aborted) throw e; tried.push('reddit archive unreachable'); } } const wiki = url.match(/^https?:\/\/([a-z-]+\.wikipedia\.org)\/wiki\/([^?#]+)/i); // 0b. Wikipedia: its CORS-enabled API, straight from the visitor's browser if (!text && wiki) { try { const r = await getText(`https://${wiki[1]}/w/api.php?action=parse&page=${encodeURIComponent(decodeURIComponent(wiki[2]))}&prop=text&format=json&formatversion=2&redirects=1&origin=*`, { timeout: 20000 }); const html = JSON.parse(r.text)?.parse?.text; if (html) { const md = htmlToMarkdown(html, url); if (usable(md)) { text = md; tried.push('wikipedia api'); } } } catch (e) { if (e?.name === 'AbortError' && outer?.aborted) throw e; tried.push('wikipedia api failed'); } } if (!text) { // 1. the page itself: direct, else raw HTML through libcurl.js (net.js) const target = redditTarget(url) ? url.replace(/^(https?:\/\/)(?:www\.)?reddit\.com/, '$1old.reddit.com') : url; // old.reddit renders the thread on the server const r = await rawFetch(target, { signal: outer }); tried.push(...r.tried.slice(-3)); if (r.text && !r.text.startsWith('%PDF')) { const md = /<(html|head|body)[\s>]/i.test(r.text.slice(0, 3000)) ? htmlToMarkdown(r.text, target) : r.text; if (usable(md)) text = md; } } await attempt('reader', () => getText(url, { reader: true, timeout: 45000, headers: { 'X-No-Cache': 'true' } })); // 2. Jina Reader: renders JavaScript, reads PDFs await attempt('defuddle', () => getText('https://defuddle.md/' + url, { timeout: 30000 })); // 3. defuddle.md: another free, CORS-enabled reader on other IPs if (!text) try { // 4. newest Wayback Machine snapshot (CORS-enabled API), raw copy first, then through defuddle const av = await getText(`https://archive.org/wayback/available?url=${encodeURIComponent(url)}`, { timeout: 15000 }); const snap = JSON.parse(av.text)?.archived_snapshots?.closest?.url?.replace(/^http:/, 'https:');81 unmodified lines if (r.status >= 400) throw new Error(`ddg ${r.status}`); return parseDdg(r.text);}// Raw result pages fetched with libcurl.js (net.js): real URLs straight from the HTML, no reader in between.export function parseDdgHtml(html) { const d = new DOMParser().parseFromString(html, 'text/html'); return [...d.querySelectorAll('.result')].filter((e) => !e.classList.contains('result--ad')).map((e) => { const a = e.querySelector('a.result__a'); let href = a?.getAttribute('href') || ''; const m = href.match(/[?&]uddg=([^&]+)/); if (m) href = decodeURIComponent(m[1]); if (href.startsWith('//')) href = 'https:' + href; return { title: (a?.textContent || '').trim(), body: (e.querySelector('.result__snippet')?.textContent || '').trim(), href }; }).filter((r) => /^https?:\/\//.test(r.href) && !r.href.includes('duckduckgo.com/y.js'));}function bingUrl(h) { // Bing wraps results as /ck/a?...&u=a1<base64url of the real URL> try { const u = new URL(h, 'https://www.bing.com').searchParams.get('u'); if (u && u.startsWith('a1')) { const b = u.slice(2).replace(/-/g, '+').replace(/_/g, '/'); return decodeURIComponent(escape(atob(b + '='.repeat((4 - b.length % 4) % 4)))); } } catch { /* plain link */ } return h;}export function parseBing(html) { const d = new DOMParser().parseFromString(html, 'text/html'); return [...d.querySelectorAll('li.b_algo')].map((e) => { const a = e.querySelector('h2 a'); return { title: (a?.textContent || '').trim(), body: (e.querySelector('.b_caption p, .b_lineclamp2, .b_lineclamp3')?.textContent || '').trim(), href: bingUrl(a?.getAttribute('href') || '') }; }).filter((r) => /^https?:\/\//.test(r.href));}async function rawEngine(url, parse) { const r = await rawFetch(url, { signal: outer, direct: false }); if (!r.text) throw new Error('no answer'); return parse(r.text);}export async function search(query) { query = (query || '').trim(); const n = 10; if (!query) return 'Error: query is empty.'; const key = query.toLowerCase(); let rows = searchCache.get(key), repeat = !!rows; if (!rows) { rows = []; for (const f of [() => ddgSearch(query), () => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) { for (const f of [() => rawEngine(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`, parseDdgHtml), () => rawEngine(`https://www.bing.com/search?q=${encodeURIComponent(query)}`, parseBing), () => ddgSearch(query), () => braveSearch(query), () => wikipedia(query, n), () => openalex(query, n)]) { try { rows = (await f()).filter((r) => r.href && !blocked(r.href)); } catch (e) { if (e?.name === 'AbortError') throw e; } if (rows.length) break; }index.html+4-1
main.js+6-1
net.jsAdded+131
reddit.jsAdded+64
tools.js+48-4