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57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// The person's browser makes the lookup. The terms already allow that.
// Nothing here sets a User-Agent. The browser sends its own.
// Wikipedia's API answers a page when the query includes origin=*.

const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i;

function fromCode(c) {
  if (!Number.isFinite(c) || c <= 0 || c > 0x10ffff) return "";
  try { return String.fromCodePoint(c); } catch { return ""; }
}

// Recipe pages store apostrophes as &#8217; and &#x27;. The quote is the page's words.
function decodeEntities(s) {
  return String(s || "")
    .replace(/&amp;/gi, "&")
    .replace(/&#x([0-9a-f]+);/gi, (_, h) => fromCode(parseInt(h, 16)))
    .replace(/&#(\d+);/g, (_, d) => fromCode(Number(d)))
    .replace(/&lt;/gi, "<")
    .replace(/&gt;/gi, ">")
    .replace(/&quot;/gi, '"')
    .replace(/&apos;/gi, "'")
    .replace(/&nbsp;/gi, " ")
    .replace(/&rsquo;|&lsquo;/gi, "'")
    .replace(/&rdquo;|&ldquo;/gi, '"')
    .replace(/&ndash;|&mdash;/gi, "-");
}

function clean(s) {
  return decodeEntities(String(s || "").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
}

function allowedPage(raw) {
  let u;
  try { u = new URL(String(raw)); } catch { return false; }
  if (u.username || u.password) return false;
  if (u.protocol !== "http:" && u.protocol !== "https:") return false;
  const host = u.hostname.toLowerCase().replace(/\.$/, "");
  if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false;
  if (host === "metadata.google.internal") return false;
  if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.includes(":")) {
    if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("127.") || host.startsWith("192.168.")) return false;
    if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)) return false;
    if (/^169\.254\./.test(host)) return false;
    if (host === "::1" || host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) return false;
  }
  return true;
}

export function wikiTitle(raw) {
  let u;
  try { u = new URL(String(raw)); } catch { return ""; }
  const host = u.hostname.toLowerCase().replace(/^www\./, "");
  if (host !== "en.wikipedia.org" || !u.pathname.startsWith("/wiki/")) return "";
  let title = "";
  try { title = decodeURIComponent(u.pathname.slice("/wiki/".length)); } catch { return ""; }
  title = title.replace(/_/g, " ").trim();
  if (!title || title.includes(":")) return "";
  return title;
}

export function formatHits(hits) {
  const list = (hits || []).filter((h) => h && h.title && h.url).slice(0, 5);
  if (!list.length) return "";
  const text = list.map((h, i) => {
    const bit = h.snippet ? "\n" + h.snippet : "";
    return (i + 1) + ". " + h.title + "\n" + h.url + bit;
  }).join("\n\n");
  return text.length > 1800 ? text.slice(0, 1800) : text;
}

export function parseWikiSearch(data) {
  const rows = data && data.query && data.query.search;
  if (!Array.isArray(rows)) return [];
  const hits = [];
  for (const row of rows) {
    const title = clean(row && row.title).slice(0, 160);
    if (!title) continue;
    hits.push({
      title,
      url: "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")),
      snippet: clean(row.snippet).slice(0, 180),
    });
    if (hits.length >= 5) break;
  }
  return hits;
}

export function parseWikiExtract(data) {
  const pages = data && data.query && data.query.pages;
  if (!pages) return "";
  const page = Object.values(pages)[0];
  const extract = page && page.extract;
  if (!extract || page.missing != null) return "";
  const paras = [];
  for (const para of String(extract).split(/\n+/)) {
    const t = clean(para);
    if (!t || CHROME_RE.test(t)) continue;
    if (t.split(/\s+/).length < 6) continue;
    paras.push(t);
  }
  const body = paras.join("\n\n");
  return body.length > 6000 ? body.slice(0, 6000) : body;
}

const NOT_A_PAGE = /(?:wikipedia\.org|wikimedia\.org|wikidata\.org|duckduckgo\.com|web\.archive\.org|archive\.org|doi\.org|dx\.doi\.org|books\.google\.|google\.com\/books|d-nb\.info|id\.loc\.gov)/i;

export function parseWikiExtlinks(data) {
  const pages = data && data.query && data.query.pages;
  if (!pages) return [];
  const page = Object.values(pages)[0];
  const rows = (page && page.extlinks) || [];
  const hits = [];
  const hosts = new Set();
  for (const row of rows) {
    const url = String((row && (row["*"] || row.url)) || "");
    if (!/^https:\/\//i.test(url) || NOT_A_PAGE.test(url)) continue;
    let host = "";
    try { host = new URL(url).hostname.replace(/^www\./, ""); } catch { continue; }
    if (!host || hosts.has(host)) continue;
    hosts.add(host);
    hits.push({ title: host, url, snippet: "" });
    if (hits.length >= 3) break;
  }
  return hits;
}

function ddgUrl(href) {
  const raw = String(href || "").replace(/&amp;/g, "&");
  const m = /[?&]uddg=([^&]+)/.exec(raw);
  if (!m) return "";
  try { return decodeURIComponent(m[1]); } catch { return ""; }
}

export function parseDdgHtml(html) {
  const hits = [];
  const seen = new Set();
  const re = /<a\b([^>]*\bclass="result__a"[^>]*)>([\s\S]*?)<\/a>/gi;
  let m;
  while ((m = re.exec(String(html || "")))) {
    const href = /href="([^"]+)"/i.exec(m[1]);
    const url = ddgUrl(href && href[1]);
    if (!/^https?:\/\//i.test(url) || seen.has(url) || NOT_A_PAGE.test(url)) continue;
    const title = clean(m[2]).slice(0, 160);
    if (!title) continue;
    seen.add(url);
    hits.push({ title, url, snippet: "" });
    if (hits.length >= 5) break;
  }
  return hits;
}

export function parseDdgInstant(data) {
  const hits = [];
  const seen = new Set();
  function add(title, url, snippet) {
    const u = String(url || "");
    const name = clean(title).slice(0, 160);
    if (!name || !/^https?:\/\//i.test(u) || seen.has(u) || NOT_A_PAGE.test(u)) return;
    seen.add(u);
    hits.push({ title: name, url: u, snippet: clean(snippet).slice(0, 180) });
  }
  if (data && data.AbstractURL) add(data.Heading || data.AbstractURL, data.AbstractURL, data.AbstractText);
  const walk = (list) => {
    for (const item of list || []) {
      if (item && Array.isArray(item.Topics)) walk(item.Topics);
      else if (item) add(item.Text, item.FirstURL, "");
    }
  };
  walk(data && data.RelatedTopics);
  return hits.slice(0, 5);
}

export function articleFromHTML(html) {
  const raw = String(html || "")
    .replace(/<script[\s\S]*?<\/script>/gi, " ")
    .replace(/<style[\s\S]*?<\/style>/gi, " ")
    .replace(/<(?:nav|header|footer|aside|form)\b[\s\S]*?<\/(?:nav|header|footer|aside|form)>/gi, " ");
  const blocks = [];
  const re = /<(p|li)\b[^>]*>([\s\S]*?)<\/\1>/gi;
  let m;
  while ((m = re.exec(raw))) {
    const t = clean(m[2]);
    if (!t || CHROME_RE.test(t)) continue;
    const words = t.split(/\s+/).length;
    const li = m[1].toLowerCase() === "li";
    if (li ? words < 6 : words < 12 || !/[.!?]/.test(t)) continue;
    blocks.push(li ? "- " + t : t);
    if (blocks.length >= 40) break;
  }
  const body = blocks.join("\n\n");
  if (!body || body.split(/\s+/).length < 12) return "";
  return body.length > 6000 ? body.slice(0, 6000) : body;
}

// The local frame (frame.html on this origin) runs offscreen_script.js.
// method "fetch" is called with args[0]: { url, headers, request }.
// The handler JSON.parses the body. The frame returns a page as {"text": page}.
const OFFSCREEN_MAGIC = 91556947316803;
let testFrame = null;
let frameWait = null;

export function setLocalFrame(win) {
  testFrame = win || null;
  frameWait = null;
}

function canFrame(fetchImpl) {
  if (testFrame) return true;
  return (!fetchImpl || fetchImpl === globalThis.fetch) && typeof document !== "undefined" && !!document.getElementById("local-frame");
}

export function localFrameWindow() {
  if (testFrame) return Promise.resolve(testFrame);
  if (typeof document === "undefined") return Promise.resolve(null);
  const frame = document.getElementById("local-frame");
  if (!frame) return Promise.resolve(null);
  let win = null;
  try { win = frame.contentWindow; } catch { win = null; }
  if (win && typeof win.frameFetch === "function") return Promise.resolve(win);
  if (frameWait) return frameWait;
  frameWait = new Promise((resolve) => {
    const timer = setTimeout(() => resolve(null), 4000);
    const done = () => {
      clearTimeout(timer);
      let ready = null;
      try { ready = frame.contentWindow; } catch { ready = null; }
      resolve(ready && typeof ready.frameFetch === "function" ? ready : null);
    };
    frame.addEventListener("load", done, { once: true });
  });
  return frameWait;
}

export function offscreenBody(raw) {
  const s = typeof raw === "string" ? raw : "";
  if (!s) return "";
  try {
    const j = JSON.parse(s);
    if (j && typeof j === "object" && !Array.isArray(j) && typeof j.text === "string" && Object.keys(j).length === 1) return j.text;
  } catch { /* the handler already returned the body */ }
  return s;
}

function headerObject(src) {
  const headers = {};
  if (!src) return headers;
  if (typeof src.forEach === "function") {
    src.forEach((v, k) => { headers[k] = String(v); });
  } else {
    for (const [k, v] of Object.entries(src)) headers[k] = String(v);
  }
  for (const key of Object.keys(headers)) {
    const low = key.toLowerCase();
    if (low === "user-agent" || low === "cookie" || low === "authorization") delete headers[key];
  }
  return headers;
}

export function offscreenMessage(url, init) {
  const headers = headerObject(init && init.headers);
  if (!headers.Accept && !headers.accept) headers.Accept = "text/html,application/json";
  const request = {
    method: (init && init.method) || "GET",
    credentials: "omit",
    cache: "no-store",
  };
  if (init && init.body != null) request.body = typeof init.body === "string" ? init.body : String(init.body);
  return {
    magic: OFFSCREEN_MAGIC,
    host: "*",
    method: "fetch",
    args: [{ url, headers, request }],
  };
}

export async function offscreenRead(url, init) {
  const win = await localFrameWindow();
  if (!win || typeof win.frameFetch !== "function") return null;
  let href = "";
  try {
    const base = typeof location !== "undefined" && location.href ? location.href : "https://ai.encryptid.systems/";
    href = new URL(String(url), base).href;
  } catch { return null; }
  if (!/^https:\/\//i.test(href)) return null;
  const reply = await win.frameFetch(offscreenMessage(href, init));
  const result = reply && reply.result;
  if (!result || result.ok === false && !result.text) return null;
  return {
    ok: !!result.ok,
    status: Number(result.status) || 0,
    headers: result.headers && typeof result.headers === "object" ? result.headers : {},
    text: offscreenBody(result.text),
  };
}

function asResponse(got) {
  if (!got) {
    return { ok: false, status: 0, headers: { get() { return ""; } }, text: async () => "", json: async () => null };
  }
  const text = got.text || "";
  const table = got.headers || {};
  return {
    ok: !!got.ok && got.status >= 200 && got.status < 300,
    status: got.status,
    headers: {
      get(name) {
        const want = String(name || "").toLowerCase();
        for (const [k, v] of Object.entries(table)) {
          if (String(k).toLowerCase() === want) return String(v);
        }
        return "";
      },
    },
    text: async () => text,
    json: async () => JSON.parse(text),
  };
}

// duck.ai and Gemini run in the local frame. The frame's script does the fetch.
export function pageFetch(fetchImpl) {
  const base = fetchImpl || globalThis.fetch;
  if (base !== globalThis.fetch) return base;
  return async (input, init) => {
    const url = typeof input === "string" ? input : (input && input.url) || "";
    const got = await offscreenRead(url, init);
    if (got && (got.text || got.ok)) return asResponse(got);
    try { return await base(input, init); } catch { return asResponse(null); }
  };
}

// The site search is the same origin. It is used when the browser cannot read the page.
async function serverLookup(path, params, fetchImpl) {
  const f = fetchImpl || fetch;
  const u = new URL(path, "http://champ.local");
  for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
  try {
    const r = await f(u.pathname + u.search, { headers: { Accept: "application/json" }, cache: "no-store" });
    if (!r || !r.ok || typeof r.json !== "function") return "";
    const j = await r.json();
    if (!j || j.ok === false || typeof j.output !== "string") return "";
    return j.output;
  } catch {
    return "";
  }
}

async function browserJSON(url, fetchImpl) {
  const f = fetchImpl || fetch;
  const r = await f(url, { headers: { Accept: "application/json" }, cache: "no-store" });
  if (!r || !r.ok || typeof r.json !== "function") return null;
  return r.json();
}

// The host did not send a CORS header, so this origin reads the page and hands the text back.
async function originRead(url, init) {
  if (typeof location === "undefined" || !location.origin) return null;
  let href = "";
  try { href = new URL(String(url), location.href).href; } catch { return null; }
  if (!/^https:\/\//i.test(href)) return null;
  try {
    const r = await fetch(location.origin + "/api/read", {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json" },
      cache: "no-store",
      body: JSON.stringify({
        url: href,
        method: (init && init.method) || "GET",
        headers: headerObject(init && init.headers),
        body: init && init.body != null ? String(init.body) : "",
      }),
    });
    if (!r.ok || typeof r.json !== "function") return null;
    const j = await r.json();
    if (!j || typeof j.text !== "string") return null;
    return j;
  } catch {
    return null;
  }
}

async function browserText(url, fetchImpl) {
  const f = fetchImpl || fetch;
  try {
    const r = await f(url, { headers: { Accept: "text/html,application/json" }, cache: "no-store" });
    if (r && r.ok && typeof r.text === "function") return await r.text();
  } catch { /* this page cannot read the host */ }
  if (f === globalThis.fetch) {
    const got = await originRead(url);
    if (got && got.status >= 200 && got.status < 300 && got.text) return got.text;
  }
  return "";
}

export async function browserSearch(source, q, fetchImpl) {
  const query = clean(q).slice(0, 200);
  if (!query) return "";
  const kind = String(source || "").trim().toLowerCase();
  try {
    if (kind === "wiki" || kind === "wikipedia") {
      const url = "https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&origin=*&srlimit=5&srnamespace=0&srprop=snippet&srsearch=" + encodeURIComponent(query);
      const found = parseWikiSearch(await browserJSON(url, fetchImpl));
      return formatHits(found.slice(0, 1));
    }
    if (kind === "duckduckgo" || kind === "ddg") {
      const htmlURL = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query);
      let htmlHits = parseDdgHtml(await browserText(htmlURL, fetchImpl));
      if (!htmlHits.length && canFrame(fetchImpl)) {
        const got = await offscreenRead(htmlURL);
        if (got && got.ok) htmlHits = parseDdgHtml(got.text);
      }
      if (htmlHits.length) return formatHits(htmlHits);
      const url = "https://api.duckduckgo.com/?q=" + encodeURIComponent(query) + "&format=json&no_html=1&no_redirect=1&skip_disambig=1";
      const instant = formatHits(parseDdgInstant(await browserJSON(url, fetchImpl)));
      if (instant) return instant;
      // This host already searches when the browser cannot read the results page.
      return serverLookup("/api/ext/search", { q: query, source: "duckduckgo" }, fetchImpl);
    }
  } catch {
    return "";
  }
  return "";
}

export async function browserGather(raw, fetchImpl) {
  const title = wikiTitle(raw);
  try {
    if (title) {
      const url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&explaintext=1&exsectionformat=plain&redirects=1&format=json&origin=*&titles=" + encodeURIComponent(title);
      const text = parseWikiExtract(await browserJSON(url, fetchImpl));
      return { output: text, exit_code: text ? 0 : 1 };
    }
    if (!allowedPage(raw)) return { output: "That address is not available.", exit_code: 1 };
    let text = articleFromHTML(await browserText(raw, fetchImpl));
    if (!text && canFrame(fetchImpl)) {
      const got = await offscreenRead(raw);
      if (got && got.text) text = articleFromHTML(got.text);
    }
    if (!text) text = await serverLookup("/api/ext/gather", { url: raw }, fetchImpl);
    return { output: text, exit_code: text ? 0 : 1 };
  } catch {
    return { output: "", exit_code: 1 };
  }
}