@agentproto/collect 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1197 @@
1
+ import { defineConnector } from './chunk-SYTQ6RN6.mjs';
2
+ import { TransportError, textFingerprint, itemIdFromUrl, canonicalUrl } from './chunk-FQLYZIVI.mjs';
3
+ import { z } from 'zod';
4
+ import { parse, defaultTreeAdapter } from 'parse5';
5
+
6
+ /**
7
+ * @agentproto/collect
8
+ * Schemas, ids, URL canonicalisation and text fingerprints for collected public content.
9
+ */
10
+ var MAX_DEPTH = 200;
11
+ var DEFAULT_MAX_NODES = 15e4;
12
+ var DEFAULT_MAX_PARSE_OPS = 3e6;
13
+ var TooComplexError = class extends Error {
14
+ code = "TOO_COMPLEX";
15
+ constructor() {
16
+ super("page is too complex to parse within its work budget");
17
+ this.name = "TooComplexError";
18
+ }
19
+ };
20
+ function budgetedAdapter(limit) {
21
+ let ops = 0;
22
+ const tick = () => {
23
+ if (++ops > limit) throw new TooComplexError();
24
+ };
25
+ const a = defaultTreeAdapter;
26
+ return {
27
+ ...a,
28
+ createElement: (...args) => (tick(), a.createElement(...args)),
29
+ createCommentNode: (...args) => (tick(), a.createCommentNode(...args)),
30
+ appendChild: (...args) => (tick(), a.appendChild(...args)),
31
+ insertBefore: (...args) => (tick(), a.insertBefore(...args)),
32
+ insertText: (...args) => (tick(), a.insertText(...args)),
33
+ insertTextBefore: (...args) => (tick(), a.insertTextBefore(...args)),
34
+ detachNode: (...args) => (tick(), a.detachNode(...args)),
35
+ adoptAttributes: (...args) => (tick(), a.adoptAttributes(...args))
36
+ };
37
+ }
38
+ function parseHtml(html, options = {}) {
39
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
40
+ let document;
41
+ try {
42
+ document = parse(html, { treeAdapter: budgetedAdapter(options.maxOps ?? DEFAULT_MAX_PARSE_OPS) });
43
+ } catch (e) {
44
+ if (e instanceof TooComplexError) return { root: { type: "element", tag: "#root", attrs: {}, children: [] }, capped: true, tooComplex: true };
45
+ throw e;
46
+ }
47
+ const root = { type: "element", tag: "#root", attrs: {}, children: [] };
48
+ let count = 0;
49
+ let capped = false;
50
+ const pending = [];
51
+ const push = (nodes, parent, depth) => {
52
+ for (let i = nodes.length - 1; i >= 0; i--) pending.push({ node: nodes[i], parent, depth });
53
+ };
54
+ push(document.childNodes, root, 0);
55
+ while (pending.length) {
56
+ const { node, parent, depth } = pending.pop();
57
+ if (node.nodeName === "#text") {
58
+ if (++count > maxNodes) {
59
+ capped = true;
60
+ break;
61
+ }
62
+ const value = node.value;
63
+ const last = parent.children[parent.children.length - 1];
64
+ if (last?.type === "text") last.value += value;
65
+ else parent.children.push({ type: "text", value, parent });
66
+ continue;
67
+ }
68
+ if (node.nodeName.startsWith("#")) continue;
69
+ const source = node;
70
+ if (++count > maxNodes) {
71
+ capped = true;
72
+ break;
73
+ }
74
+ const attrs = {};
75
+ for (const a of source.attrs) if (!(a.name in attrs)) attrs[a.name] = a.value;
76
+ const el = { type: "element", tag: source.tagName, attrs, children: [], parent };
77
+ if (depth >= MAX_DEPTH) {
78
+ if (!options.skip?.(el)) push(source.childNodes, parent, depth);
79
+ continue;
80
+ }
81
+ parent.children.push(el);
82
+ if (options.skip?.(el)) continue;
83
+ push(source.childNodes, el, depth + 1);
84
+ }
85
+ return { root, capped };
86
+ }
87
+ function* walk(node) {
88
+ const pending = [node];
89
+ while (pending.length) {
90
+ const cur = pending.pop();
91
+ if (cur.type !== "element") continue;
92
+ yield cur;
93
+ for (let k = cur.children.length - 1; k >= 0; k--) pending.push(cur.children[k]);
94
+ }
95
+ }
96
+ function textOf(node) {
97
+ if (node.type === "text") return node.value;
98
+ if (node.tag === "script" || node.tag === "style") return "";
99
+ let out = "";
100
+ for (const c of node.children) out += textOf(c);
101
+ return out;
102
+ }
103
+ function rawTextOf(node) {
104
+ return node.children.map((c) => c.type === "text" ? c.value : "").join("");
105
+ }
106
+ function collapse(text) {
107
+ return text.replace(/[\s ]+/g, " ").trim();
108
+ }
109
+
110
+ // src/connectors/extract.ts
111
+ var MIN_WORDS = 15;
112
+ var DEFAULT_MAX_CHARS = 2e5;
113
+ var DEFAULT_MAX_INPUT_BYTES = 5 * 1024 * 1024;
114
+ var DEFAULT_MAX_LINKS = 1e3;
115
+ var MAX_URL_LENGTH = 2048;
116
+ var DEFAULT_MAX_LINK_BYTES = 1024 * 1024;
117
+ var NOISE_TAGS = /* @__PURE__ */ new Set([
118
+ "script",
119
+ "style",
120
+ "noscript",
121
+ "template",
122
+ "nav",
123
+ "footer",
124
+ "aside",
125
+ "iframe",
126
+ "svg",
127
+ "button",
128
+ "select",
129
+ "option",
130
+ "dialog",
131
+ "canvas",
132
+ "object",
133
+ "embed",
134
+ "menu",
135
+ "head",
136
+ "textarea",
137
+ "input",
138
+ "label"
139
+ ]);
140
+ var NOISE_ROLES = /* @__PURE__ */ new Set(["navigation", "banner", "complementary", "contentinfo", "search", "dialog", "alert"]);
141
+ var NOISE_WORDS = [
142
+ "comment",
143
+ "comments",
144
+ "comment-list",
145
+ "commentlist",
146
+ "disqus",
147
+ "respond",
148
+ "sidebar",
149
+ "side-bar",
150
+ "nav",
151
+ "navbar",
152
+ "navigation",
153
+ "menu",
154
+ "footer",
155
+ "masthead",
156
+ "banner",
157
+ "cookie",
158
+ "cookies",
159
+ "consent",
160
+ "gdpr",
161
+ "share",
162
+ "sharing",
163
+ "social",
164
+ "related",
165
+ "recommended",
166
+ "advert",
167
+ "advertisement",
168
+ "ad",
169
+ "ads",
170
+ "sponsor",
171
+ "sponsored",
172
+ "promo",
173
+ "popup",
174
+ "modal",
175
+ "newsletter",
176
+ "subscribe",
177
+ "subscription",
178
+ "paywall",
179
+ "regwall",
180
+ "breadcrumb",
181
+ "breadcrumbs",
182
+ "pagination",
183
+ "toolbar",
184
+ "skip-link",
185
+ "tag-list",
186
+ "tags-list",
187
+ "toc",
188
+ "hidden",
189
+ "byline",
190
+ "author",
191
+ "author-name",
192
+ "author-info",
193
+ "author-bio",
194
+ "about-author",
195
+ "dateline",
196
+ "entry-meta",
197
+ "post-meta",
198
+ "article-meta",
199
+ "posted-on",
200
+ "print-only",
201
+ "sr-only",
202
+ "visually-hidden"
203
+ ];
204
+ var NOISE_RE = new RegExp(`(?:^|[\\s_-])(?:${NOISE_WORDS.map((w) => w.replace(/-/g, "[-_]?")).join("|")})(?:$|[\\s_-])`, "i");
205
+ var POSITIVE_RE = /(?:^|[\s_-])(?:article|content|post|body|entry|story|text|main|page|prose|markdown|docs?)(?:$|[\s_-])/i;
206
+ var NEGATIVE_RE = /(?:^|[\s_-])(?:foot|footer|header|widget|meta|tool|extra|outer|hero|teaser|summary|list)(?:$|[\s_-])/i;
207
+ var BLOCK_TAGS = /* @__PURE__ */ new Set([
208
+ "address",
209
+ "article",
210
+ "aside",
211
+ "blockquote",
212
+ "dd",
213
+ "details",
214
+ "div",
215
+ "dl",
216
+ "dt",
217
+ "fieldset",
218
+ "figcaption",
219
+ "figure",
220
+ "footer",
221
+ "h1",
222
+ "h2",
223
+ "h3",
224
+ "h4",
225
+ "h5",
226
+ "h6",
227
+ "header",
228
+ "hr",
229
+ "li",
230
+ "main",
231
+ "nav",
232
+ "ol",
233
+ "p",
234
+ "pre",
235
+ "section",
236
+ "summary",
237
+ "table",
238
+ "tbody",
239
+ "td",
240
+ "tfoot",
241
+ "th",
242
+ "thead",
243
+ "tr",
244
+ "ul"
245
+ ]);
246
+ var CONTAINER_TAGS = /* @__PURE__ */ new Set(["div", "section", "article", "main", "td", "body", "blockquote", "figure"]);
247
+ var MEDIA_TAGS = /* @__PURE__ */ new Set(["img", "video", "picture", "audio"]);
248
+ var idClass = (el) => `${el.attrs.class ?? ""} ${el.attrs.id ?? ""}`;
249
+ function hasAncestor(el, tags) {
250
+ for (let p = el.parent; p; p = p.parent) if (tags.includes(p.tag)) return true;
251
+ return false;
252
+ }
253
+ var FURNITURE_FORM = /search|log-?in|sign-?in|sign-?up|regist|contact|comment|subscri|newsletter/i;
254
+ function isNoise(el) {
255
+ if (NOISE_TAGS.has(el.tag)) return true;
256
+ if (el.tag === "form" && FURNITURE_FORM.test(`${idClass(el)} ${el.attrs.action ?? ""}`)) return true;
257
+ if ("hidden" in el.attrs || el.attrs["aria-hidden"] === "true") return true;
258
+ if (/display\s*:\s*none|visibility\s*:\s*hidden/i.test(el.attrs.style ?? "")) return true;
259
+ if (el.attrs.role && NOISE_ROLES.has(el.attrs.role.toLowerCase())) return true;
260
+ if (el.tag === "header") return !hasAncestor(el, ["article", "main"]);
261
+ if (el.tag === "body" || el.tag === "html" || el.tag === "#root") return false;
262
+ if ((el.tag === "main" || el.tag === "article") && !hasAncestor(el, ["article", "main"])) return false;
263
+ const marks = idClass(el);
264
+ return marks.trim() !== "" && NOISE_RE.test(marks);
265
+ }
266
+ var SKIP_TAGS = /* @__PURE__ */ new Set(["nav", "footer", "aside", "iframe", "svg", "button", "select", "dialog", "canvas", "object", "embed", "menu", "style", "template", "noscript", "textarea"]);
267
+ var KEEP_FOR_META = /* @__PURE__ */ new Set(["byline", "author", "author-name", "author-info", "author-bio", "about-author", "dateline", "entry-meta", "post-meta", "article-meta", "posted-on"]);
268
+ var SKIP_RE = new RegExp(`(?:^|[\\s_-])(?:${NOISE_WORDS.filter((w) => !KEEP_FOR_META.has(w)).map((w) => w.replace(/-/g, "[-_]?")).join("|")})(?:$|[\\s_-])`, "i");
269
+ function skipSubtree(el) {
270
+ if (SKIP_TAGS.has(el.tag)) return true;
271
+ if (el.tag === "form" && FURNITURE_FORM.test(`${idClass(el)} ${el.attrs.action ?? ""}`)) return true;
272
+ if (el.tag === "head" || el.tag === "script" || el.tag === "html" || el.tag === "body" || el.tag === "#root") return false;
273
+ if ("hidden" in el.attrs || el.attrs["aria-hidden"] === "true") return true;
274
+ if (/display\s*:\s*none|visibility\s*:\s*hidden/i.test(el.attrs.style ?? "")) return true;
275
+ if (el.attrs.role && NOISE_ROLES.has(el.attrs.role.toLowerCase())) return true;
276
+ if (el.tag === "header") return !hasAncestor(el, ["article", "main"]);
277
+ if ((el.tag === "main" || el.tag === "article") && !hasAncestor(el, ["article", "main"])) return false;
278
+ const marks = idClass(el);
279
+ return marks.trim() !== "" && SKIP_RE.test(marks);
280
+ }
281
+ function measure(root) {
282
+ const out = /* @__PURE__ */ new Map();
283
+ const visit = (el, inLink) => {
284
+ const m = { text: 0, link: 0 };
285
+ if (el.dead) {
286
+ out.set(el, m);
287
+ return m;
288
+ }
289
+ const link = inLink || el.tag === "a";
290
+ for (const c of el.children) {
291
+ if (c.type === "text") {
292
+ const len = collapse(c.value).length;
293
+ m.text += len;
294
+ if (link) m.link += len;
295
+ } else {
296
+ const cm = visit(c, link);
297
+ m.text += cm.text;
298
+ m.link += cm.link;
299
+ }
300
+ }
301
+ out.set(el, m);
302
+ return m;
303
+ };
304
+ visit(root, false);
305
+ return out;
306
+ }
307
+ var hasBlockChild = (el) => el.children.some((c) => c.type === "element" && BLOCK_TAGS.has(c.tag));
308
+ function baseScore(el) {
309
+ let s = 0;
310
+ switch (el.tag) {
311
+ case "article":
312
+ s += 8;
313
+ break;
314
+ case "main":
315
+ s += 6;
316
+ break;
317
+ case "div":
318
+ case "section":
319
+ s += 2;
320
+ break;
321
+ case "blockquote":
322
+ s -= 2;
323
+ break;
324
+ case "ul":
325
+ case "ol":
326
+ case "li":
327
+ case "form":
328
+ s -= 3;
329
+ break;
330
+ }
331
+ const marks = idClass(el);
332
+ if (NEGATIVE_RE.test(marks)) s -= 10;
333
+ if (POSITIVE_RE.test(marks)) s += 10;
334
+ return s;
335
+ }
336
+ function pickMain(body, metrics) {
337
+ const scores = /* @__PURE__ */ new Map();
338
+ const add = (el, points) => {
339
+ if (!el || el.tag === "#root" || el.tag === "html") return;
340
+ if (!scores.has(el)) scores.set(el, baseScore(el));
341
+ scores.set(el, scores.get(el) + points);
342
+ };
343
+ for (const el of walk(body)) {
344
+ if (el.dead) continue;
345
+ const paragraph = el.tag === "p" || el.tag === "pre" || el.tag === "blockquote" && !hasBlockChild(el) || el.tag === "div" && !hasBlockChild(el);
346
+ if (!paragraph) continue;
347
+ const m = metrics.get(el);
348
+ if (!m || m.text < 25) continue;
349
+ const text = collapse(textOf(el));
350
+ const commas = (text.match(/[,،、,]/g) ?? []).length;
351
+ const points = 1 + commas + Math.min(Math.floor(text.length / 100), 3);
352
+ let level = 0;
353
+ for (let a = el.parent; a; a = a.parent, level++) add(a, points / (level === 0 ? 1 : level === 1 ? 2 : level * 3));
354
+ }
355
+ let top;
356
+ let best = -Infinity;
357
+ for (const [el, raw] of scores) {
358
+ if (!CONTAINER_TAGS.has(el.tag) && el.tag !== "body") continue;
359
+ const m = metrics.get(el);
360
+ const density = m && m.text > 0 ? m.link / m.text : 1;
361
+ const final = raw * (1 - density);
362
+ if (final > best) {
363
+ best = final;
364
+ top = el;
365
+ }
366
+ }
367
+ if (!top) return { top: body };
368
+ const parent = top.parent;
369
+ if (!parent) return { top };
370
+ const members = /* @__PURE__ */ new Set([top]);
371
+ for (const sib of parent.children) {
372
+ if (sib.type !== "element" || sib === top || sib.dead) continue;
373
+ const sm = metrics.get(sib);
374
+ const density = sm && sm.text > 0 ? sm.link / sm.text : 1;
375
+ const sScore = (scores.get(sib) ?? 0) * (1 - density);
376
+ if (sScore >= Math.max(10, best * 0.2) || sib.tag === "p" && (sm?.text ?? 0) > 80 && density < 0.25) members.add(sib);
377
+ }
378
+ return members.size > 1 ? { top: parent, members } : { top };
379
+ }
380
+ function renderBlocks(main, metrics, titleKey, linkOf, maxChars, maxLinks) {
381
+ const blocks = [];
382
+ let cur = "";
383
+ let curLinks = [];
384
+ let curLinkChars = 0;
385
+ let hasMedia = false;
386
+ let total = 0;
387
+ let full = false;
388
+ const guard = Math.max(maxLinks * 8, 5e3);
389
+ let seenCount = 0;
390
+ const seenAny = /* @__PURE__ */ new Set();
391
+ let linkCapped = false;
392
+ const flush = () => {
393
+ const text = cur.replace(/[ \t\r\f\v ]+/g, " ").replace(/ ?\n ?/g, "\n").trim();
394
+ if (text) {
395
+ blocks.push({ text, links: curLinks, linkChars: Math.min(curLinkChars, text.length) });
396
+ total += text.length + 2;
397
+ if (total > maxChars) full = true;
398
+ }
399
+ cur = "";
400
+ curLinks = [];
401
+ curLinkChars = 0;
402
+ };
403
+ const addLink = (href, into) => {
404
+ if (href === void 0) return;
405
+ const link = linkOf(href);
406
+ if (!link) return;
407
+ if (into.includes(link)) return;
408
+ if (!seenAny.has(link)) {
409
+ if (seenCount >= guard) {
410
+ linkCapped = true;
411
+ return;
412
+ }
413
+ seenCount++;
414
+ seenAny.add(link);
415
+ }
416
+ into.push(link);
417
+ };
418
+ const dropped = (el) => {
419
+ if (el.dead) return true;
420
+ const m = metrics.get(el);
421
+ if (!m || m.text === 0) return false;
422
+ const density = m.link / m.text;
423
+ if (["ul", "ol", "div", "section", "table", "dl"].includes(el.tag) && density > 0.5 && (m.text < 400 || el.tag === "ul" || el.tag === "ol")) return true;
424
+ if (el.tag === "p" && density > 0.9 && m.text < 80) return true;
425
+ return false;
426
+ };
427
+ const visit = (node, inLink) => {
428
+ if (full) return;
429
+ if (node.type === "text") {
430
+ const t = node.value.replace(/\s+/g, " ");
431
+ cur += t;
432
+ if (inLink) curLinkChars += t.trim().length;
433
+ return;
434
+ }
435
+ const el = node;
436
+ if (MEDIA_TAGS.has(el.tag)) hasMedia = true;
437
+ if (dropped(el)) return;
438
+ if (el.tag === "br") {
439
+ cur += "\n";
440
+ return;
441
+ }
442
+ if (el.tag === "pre") {
443
+ flush();
444
+ const links = [];
445
+ const linked = { chars: 0 };
446
+ const raw = preText(el, (href) => addLink(href, links), linked, false).trimEnd().replace(/^\n+/, "");
447
+ if (raw.trim()) {
448
+ blocks.push({ text: raw, links, linkChars: Math.min(linked.chars, raw.length) });
449
+ total += raw.length + 2;
450
+ if (total > maxChars) full = true;
451
+ }
452
+ return;
453
+ }
454
+ if (el.tag === "h1" && titleKey && collapse(textOf(el)).toLowerCase() === titleKey) return;
455
+ const block = BLOCK_TAGS.has(el.tag);
456
+ if (block) flush();
457
+ if (el.tag === "li") cur += "- ";
458
+ if (el.tag === "a") addLink(el.attrs.href, curLinks);
459
+ for (const c of el.children) visit(c, inLink || el.tag === "a");
460
+ if (block) flush();
461
+ };
462
+ const roots = main.members ? main.top.children.filter((c) => c.type === "element" && main.members.has(c)) : main.top.children;
463
+ for (const c of roots) visit(c, false);
464
+ flush();
465
+ return { blocks, hasMedia, full, linkCapped };
466
+ }
467
+ function preText(node, onLink, linked, inLink) {
468
+ if (node.type === "text") {
469
+ if (inLink) linked.chars += node.value.trim().length;
470
+ return node.value;
471
+ }
472
+ if (node.dead) return "";
473
+ if (node.tag === "br") return "\n";
474
+ if (node.tag === "a") onLink(node.attrs.href);
475
+ return node.children.map((c) => preText(c, onLink, linked, inLink || node.tag === "a")).join("");
476
+ }
477
+ function countWords(text) {
478
+ const spaced = text.replace(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/gu, " $& ");
479
+ return (spaced.match(/[\p{L}\p{N}][\p{L}\p{N}'’_-]*/gu) ?? []).length;
480
+ }
481
+ var hostKey = (host) => host.toLowerCase().replace(/^www\./, "");
482
+ function safeHost(url) {
483
+ try {
484
+ return new URL(url).hostname;
485
+ } catch {
486
+ return "";
487
+ }
488
+ }
489
+ var dateOrTimestamp = z.union([z.iso.date(), z.iso.datetime({ offset: true })]);
490
+ function validDay(y, m, d) {
491
+ if (y < 1e3 || m < 1 || m > 12 || d < 1) return false;
492
+ return d <= new Date(Date.UTC(y, m, 0)).getUTCDate();
493
+ }
494
+ var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
495
+ function textDateIsReal(v) {
496
+ const monthOf = (name) => MONTHS.indexOf(name.slice(0, 3).toLowerCase()) + 1;
497
+ const dmy = /\b(\d{1,2})(?:st|nd|rd|th)?[\s-]+([A-Za-z]{3,9})\.?,?[\s-]+(\d{4})\b/.exec(v);
498
+ const mdy = /\b([A-Za-z]{3,9})\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(\d{4})\b/.exec(v);
499
+ const ymd = /\b(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})\b/.exec(v);
500
+ const slash = /\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.exec(v);
501
+ const parts = dmy ? [+dmy[1], monthOf(dmy[2]), +dmy[3]] : mdy ? [+mdy[2], monthOf(mdy[1]), +mdy[3]] : ymd ? [+ymd[3], +ymd[2], +ymd[1]] : slash ? [+slash[2], +slash[1], +slash[3]] : void 0;
502
+ if (!parts || !validDay(parts[2], parts[1], parts[0])) return false;
503
+ const time = /\b(\d{1,2}):(\d{2})(?::(\d{2}))?/.exec(v);
504
+ if (time && !(+time[1] <= 23 && +time[2] <= 59 && +(time[3] ?? 0) <= 59)) return false;
505
+ const offset = /\s[+-](\d{2}):?(\d{2})\b/.exec(v);
506
+ return !offset || +offset[1] <= 23 && +offset[2] <= 59;
507
+ }
508
+ function normalizeDate(value) {
509
+ if (!value) return void 0;
510
+ const v = value.trim();
511
+ let out;
512
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v);
513
+ const full = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})?$/i.exec(v);
514
+ if (day) {
515
+ if (validDay(+day[1], +day[2], +day[3])) out = v;
516
+ } else if (full) {
517
+ const [, y, mo, d, h, mi, s, tzRaw] = full;
518
+ let tz = "Z";
519
+ let tzOk = true;
520
+ if (tzRaw && tzRaw.toUpperCase() !== "Z") {
521
+ const t = tzRaw.replace(":", "");
522
+ tz = `${t.slice(0, 3)}:${t.slice(3)}`;
523
+ tzOk = +t.slice(1, 3) <= 23 && +t.slice(3) <= 59;
524
+ }
525
+ if (tzOk && validDay(+y, +mo, +d) && +h <= 23 && +mi <= 59 && +(s ?? 0) <= 59) out = `${y}-${mo}-${d}T${h}:${mi}:${s ?? "00"}${tz}`;
526
+ } else if (/(?:\b(?:GMT|UTC|UT)\b|[+-]\d{2}:?\d{2}\b|\dZ$)/.test(v) && textDateIsReal(v)) {
527
+ const t = Date.parse(v);
528
+ if (!Number.isNaN(t)) out = new Date(t).toISOString().replace(/\.\d{3}Z$/, "Z");
529
+ }
530
+ return out !== void 0 && dateOrTimestamp.safeParse(out).success ? out : void 0;
531
+ }
532
+ function languageOf(value) {
533
+ const m = /^([a-z]{2,3})(?:[-_][a-z0-9]+)*$/i.exec((value ?? "").trim());
534
+ return m ? m[1].toLowerCase() : void 0;
535
+ }
536
+ var asArray = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
537
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
538
+ function readJsonLd(root, normId) {
539
+ const objects = [];
540
+ const byId = /* @__PURE__ */ new Map();
541
+ let count = 0;
542
+ const visit = (v, depth) => {
543
+ if (depth > 10 || count > 5e3 || !v || typeof v !== "object") return;
544
+ if (Array.isArray(v)) return void v.forEach((x) => visit(x, depth + 1));
545
+ const o = v;
546
+ count++;
547
+ objects.push(o);
548
+ const id = o["@id"];
549
+ if (typeof id === "string" && Object.keys(o).length > 1) {
550
+ const key = normId(id);
551
+ const prev = byId.get(key);
552
+ if (!prev || Object.keys(prev).length < Object.keys(o).length) byId.set(key, o);
553
+ }
554
+ for (const value of Object.values(o)) visit(value, depth + 1);
555
+ };
556
+ for (const el of walk(root)) {
557
+ if (el.tag !== "script" || !/ld\+json/i.test(el.attrs.type ?? "")) continue;
558
+ try {
559
+ visit(JSON.parse(rawTextOf(el).trim()), 0);
560
+ } catch {
561
+ }
562
+ }
563
+ return { objects, byId, normId };
564
+ }
565
+ var ARTICLE_TYPE = /(?:^|[:/])(?:News|Blog|Scholarly|Tech|Social|Live)?(?:Article|Posting|Report)$/;
566
+ function hasArticleType(o) {
567
+ return asArray(o["@type"]).some((t) => typeof t === "string" && ARTICLE_TYPE.test(t));
568
+ }
569
+ function deref(ld, v) {
570
+ if (isObject(v)) {
571
+ const keys = Object.keys(v);
572
+ if (keys.length === 1 && keys[0] === "@id" && typeof v["@id"] === "string") return ld.byId.get(ld.normId(v["@id"])) ?? v;
573
+ }
574
+ return v;
575
+ }
576
+ function nameOf(v) {
577
+ if (typeof v === "string") return v;
578
+ if (isObject(v) && typeof v.name === "string") return v.name;
579
+ return void 0;
580
+ }
581
+ function cleanName(raw, fromByline) {
582
+ if (!raw) return void 0;
583
+ let s = collapse(raw).replace(/^(?:\p{L}+\.?\s+\d{1,2},?\s+\d{4}|\d{4}-\d{2}-\d{2}|\d{1,2}\s+\p{L}+\s+\d{4})\s*[·•|–—,-]?\s*/u, "").replace(/^(?:written\s+by|posted\s+by|published\s+by|by|par|von|por)\s*[:\s]\s*/i, "");
584
+ s = s.split(/\s+[|•·–—]\s+|\s+-\s+/)[0];
585
+ if (fromByline) s = s.split(/,|\s+(?:on|le|am)\s+\d|\s+\d/)[0];
586
+ s = s.trim();
587
+ if (/^(?:by|par|von|por)$/i.test(s) || /^\d|\bago\b/i.test(s)) return void 0;
588
+ if (s.length < 2 || s.length > 80 || /https?:|@|[<>{}]/.test(s) || s.split(" ").length > 6) return void 0;
589
+ if (/^(?:admin|administrator|staff|editor|editors|posted|share|follow)$/i.test(s) && fromByline) return void 0;
590
+ return s;
591
+ }
592
+ function authorSlug(name) {
593
+ return name.normalize("NFKD").replace(/\p{M}+/gu, "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "");
594
+ }
595
+ function labelText(node) {
596
+ if (node.type === "text") return node.value;
597
+ if (["button", "svg", "time", "script", "style", "noscript", "form", "select"].includes(node.tag)) return " ";
598
+ return ` ${node.children.map(labelText).join("")} `;
599
+ }
600
+ var isByline = (el) => /(?:^|[\s_-])(?:byline|author|author-name|authorname|writer)(?:$|[\s_-])/i.test(idClass(el)) && !/(?:bio|box|list|avatar|image|photo)/i.test(idClass(el));
601
+ function visibleText(node) {
602
+ if (node.type === "text") return node.value;
603
+ if (node.dead || node.tag === "script" || node.tag === "style") return " ";
604
+ return node.children.map(visibleText).join("");
605
+ }
606
+ function liveScript(el) {
607
+ for (let p = el.parent; p; p = p.parent) {
608
+ if (p.tag === "head" || p.tag === "html" || p.tag === "#root") continue;
609
+ if (isNoise(p) || skipSubtree(p)) return false;
610
+ }
611
+ return true;
612
+ }
613
+ function inFurniture(el) {
614
+ for (let p = el; p; p = p.parent) {
615
+ if (p.tag === "footer" || p.tag === "nav" || p.tag === "aside") return true;
616
+ if (p !== el && /(?:^|[\s_-])(?:comments?|sidebar|related|disqus)(?:$|[\s_-])/i.test(idClass(p))) return true;
617
+ }
618
+ return false;
619
+ }
620
+ var CHALLENGE_TITLE = /just a moment|attention required|are you a (?:robot|human)|verify you are (?:a )?human|checking your browser|security check|access denied/i;
621
+ var CHALLENGE_TEXT = /verify you are (?:a )?human|checking your browser|enable javascript and cookies|complete the (?:security )?check|unusual traffic|are you a robot|prove you(?:'|’)re (?:not a robot|human)/i;
622
+ var CHALLENGE_WIDGET = /(?:^|[\s_-])(?:cf-turnstile|g-recaptcha|h-captcha|hcaptcha|captcha-container|challenge-form|cf-challenge)(?:$|[\s_-])/i;
623
+ var CHALLENGE_SCRIPT = /recaptcha|hcaptcha|turnstile|challenge-platform|captcha-delivery/i;
624
+ function extractArticle(html, pageUrl, options = {}) {
625
+ const maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
626
+ const maxLinks = options.maxLinks ?? DEFAULT_MAX_LINKS;
627
+ const notes = [];
628
+ if (options.inputTruncated) notes.push("input_truncated");
629
+ const { root, capped, tooComplex } = parseHtml(html, {
630
+ maxNodes: options.maxNodes ?? DEFAULT_MAX_NODES,
631
+ maxOps: options.maxParseOps ?? DEFAULT_MAX_PARSE_OPS,
632
+ skip: skipSubtree
633
+ });
634
+ if (tooComplex) {
635
+ notes.push("too_complex");
636
+ const cu = canonicalUrl(pageUrl);
637
+ return { extraction: "empty", text: "", textTruncated: false, wordCount: 0, canonicalUrl: cu, site: hostKey(safeHost(pageUrl)), outboundLinks: [], hasMedia: false, challenge: false, notes };
638
+ }
639
+ if (capped) notes.push("node_cap");
640
+ for (const el of walk(root)) el.dead = (el.parent?.dead ?? false) || isNoise(el);
641
+ const meta = /* @__PURE__ */ new Map();
642
+ const links = [];
643
+ let docLang;
644
+ let titleTag;
645
+ let baseHref;
646
+ let body;
647
+ let widget = false;
648
+ let scriptMarker = false;
649
+ const h1s = [];
650
+ const times = [];
651
+ const authorLinks = [];
652
+ const bylines = [];
653
+ const itempropAuthors = [];
654
+ for (const el of walk(root)) {
655
+ switch (el.tag) {
656
+ case "html":
657
+ docLang ??= el.attrs.lang;
658
+ break;
659
+ case "body":
660
+ body ??= el;
661
+ break;
662
+ case "meta": {
663
+ const key = (el.attrs.property ?? el.attrs.name ?? el.attrs.itemprop ?? el.attrs["http-equiv"] ?? "").toLowerCase();
664
+ const content = el.attrs.content;
665
+ if (key && content !== void 0 && !meta.has(key)) meta.set(key, content);
666
+ break;
667
+ }
668
+ case "link":
669
+ if (el.attrs.rel && el.attrs.href) links.push({ rel: el.attrs.rel.toLowerCase(), href: el.attrs.href });
670
+ break;
671
+ case "base":
672
+ baseHref ??= el.attrs.href;
673
+ break;
674
+ case "title":
675
+ titleTag ??= collapse(textOf(el));
676
+ break;
677
+ case "h1":
678
+ if (!el.dead) h1s.push(collapse(textOf(el)));
679
+ break;
680
+ case "script":
681
+ if (CHALLENGE_SCRIPT.test(el.attrs.src ?? "") && liveScript(el)) scriptMarker = true;
682
+ break;
683
+ case "time":
684
+ if (el.attrs.datetime && !inFurniture(el)) times.push({ value: el.attrs.datetime, inArticle: hasAncestor(el, ["article", "main"]) });
685
+ break;
686
+ }
687
+ if (!el.dead && (CHALLENGE_WIDGET.test(idClass(el)) || "data-sitekey" in el.attrs)) widget = true;
688
+ if (el.tag === "a" && /(?:^|\s)author(?:\s|$)/i.test(el.attrs.rel ?? "")) authorLinks.push({ name: collapse(textOf(el)), href: el.attrs.href });
689
+ if (el.attrs.itemprop?.toLowerCase() === "author" && el.tag !== "meta" && el.tag !== "link") {
690
+ const named = [...walk(el)].find((c) => c.attrs.itemprop?.toLowerCase() === "name");
691
+ itempropAuthors.push(collapse(labelText(named ?? el)));
692
+ } else if (el.tag !== "html" && el.tag !== "body" && isByline(el) && !inFurniture(el)) {
693
+ bylines.push(collapse(labelText(el)));
694
+ }
695
+ }
696
+ let base = pageUrl;
697
+ if (baseHref) {
698
+ if (baseHref.length > MAX_URL_LENGTH) notes.push("base_ignored");
699
+ else {
700
+ try {
701
+ const candidate = new URL(baseHref, pageUrl).href;
702
+ if (candidate.length > MAX_URL_LENGTH) notes.push("base_ignored");
703
+ else base = candidate;
704
+ } catch {
705
+ base = pageUrl;
706
+ }
707
+ }
708
+ }
709
+ let tooLong = false;
710
+ const resolve = (href) => {
711
+ if (href.length > MAX_URL_LENGTH) {
712
+ tooLong = true;
713
+ return void 0;
714
+ }
715
+ try {
716
+ const abs = new URL(href.trim(), base).href;
717
+ if (abs.length > MAX_URL_LENGTH) {
718
+ tooLong = true;
719
+ return void 0;
720
+ }
721
+ return abs;
722
+ } catch {
723
+ return void 0;
724
+ }
725
+ };
726
+ const pageCanonical = canonicalUrl(pageUrl);
727
+ const aliases = new Set((options.canonicalAliases ?? []).map(hostKey));
728
+ const declared = links.find((l) => l.rel.split(/\s+/).includes("canonical"));
729
+ let canonical = pageCanonical;
730
+ if (declared) {
731
+ const abs = resolve(declared.href);
732
+ if (abs && /^https?:/i.test(abs)) {
733
+ const host = hostKey(safeHost(abs));
734
+ if (host === hostKey(safeHost(pageUrl)) || aliases.has(host)) canonical = canonicalUrl(abs);
735
+ }
736
+ }
737
+ const isThisPage = (u) => {
738
+ if (typeof u !== "string" || u.length > MAX_URL_LENGTH) return false;
739
+ try {
740
+ const c = canonicalUrl(new URL(u, base).href);
741
+ return c === pageCanonical || c === canonical;
742
+ } catch {
743
+ return false;
744
+ }
745
+ };
746
+ const normId = (id) => {
747
+ try {
748
+ return new URL(id, base).href;
749
+ } catch {
750
+ return id;
751
+ }
752
+ };
753
+ const ld = readJsonLd(root, normId);
754
+ const typed = ld.objects.filter(hasArticleType);
755
+ const refsOf = (o) => {
756
+ const page = deref(ld, o.mainEntityOfPage);
757
+ return [o.url, o["@id"], typeof page === "string" ? page : isObject(page) ? [page.url, page["@id"]] : []].flat();
758
+ };
759
+ const asArticle = (v) => {
760
+ const d = deref(ld, v);
761
+ return isObject(d) && hasArticleType(d) ? d : void 0;
762
+ };
763
+ const holders = ld.objects.filter((o) => o.mainEntity !== void 0 && [o.url, o["@id"]].some(isThisPage));
764
+ const isPage = (o) => asArray(o["@type"]).some((t) => typeof t === "string" && /(?:^|[:/])\w*Page$/.test(t));
765
+ const explicit = [...holders.filter(isPage), ...holders.filter((o) => !isPage(o))].flatMap((o) => asArray(o.mainEntity).map(asArticle)).find((a) => a !== void 0);
766
+ const viaMainEntity = ld.objects.flatMap((o) => ["mainEntity", "mainEntityOfPage"].flatMap((k) => asArray(o[k]).map(asArticle))).filter((v) => v !== void 0);
767
+ const article = explicit ?? typed.find((o) => refsOf(o).some(isThisPage)) ?? viaMainEntity[0] ?? typed[0];
768
+ const site = collapse(meta.get("og:site_name") ?? "") || hostKey(safeHost(pageUrl));
769
+ let title = collapse(meta.get("og:title") ?? "") || void 0;
770
+ if (!title && titleTag) {
771
+ title = titleTag;
772
+ for (const sep of [" | ", " - ", " \u2013 ", " \u2014 ", " \xB7 ", " :: "]) {
773
+ const at = title.lastIndexOf(sep);
774
+ if (at > 0 && collapse(title.slice(at + sep.length)).toLowerCase() === site.toLowerCase()) {
775
+ title = title.slice(0, at).trim();
776
+ break;
777
+ }
778
+ }
779
+ }
780
+ title ||= h1s.find(Boolean) || void 0;
781
+ const lang = languageOf(docLang) ?? languageOf(meta.get("og:locale")) ?? languageOf(meta.get("content-language")) ?? languageOf(meta.get("language"));
782
+ const bodyEl = body ?? root;
783
+ const visible = collapse(visibleText(bodyEl));
784
+ const challenge = visible.length < 2e3 && (titleTag !== void 0 && CHALLENGE_TITLE.test(titleTag) || CHALLENGE_TEXT.test(visible.slice(0, 1500)) || widget || scriptMarker && visible.length < 200);
785
+ if (challenge) {
786
+ return { extraction: "blocked", ...title ? { title } : {}, text: "", textTruncated: false, wordCount: 0, canonicalUrl: canonical, site, outboundLinks: [], hasMedia: false, challenge: true, notes };
787
+ }
788
+ const metrics = measure(bodyEl);
789
+ const main = pickMain(bodyEl, metrics);
790
+ const titleKey = title?.toLowerCase();
791
+ const linkOf = (href) => {
792
+ const abs = resolve(href);
793
+ if (!abs || !/^https?:/i.test(abs)) return void 0;
794
+ const c = canonicalUrl(abs);
795
+ return c === pageCanonical || c === canonical ? void 0 : c;
796
+ };
797
+ const rendered = renderBlocks(main, metrics, titleKey, linkOf, maxChars, maxLinks);
798
+ const { blocks, hasMedia } = rendered;
799
+ let text = "";
800
+ let kept = 0;
801
+ let truncated = rendered.full || capped || options.inputTruncated === true;
802
+ for (const b of blocks) {
803
+ const next = kept === 0 ? b.text : `${text}
804
+
805
+ ${b.text}`;
806
+ if (next.length > maxChars) {
807
+ truncated = true;
808
+ if (kept === 0) {
809
+ const cut = b.text.slice(0, maxChars);
810
+ const space = cut.lastIndexOf(" ");
811
+ text = (space > maxChars * 0.8 ? cut.slice(0, space) : cut).trimEnd();
812
+ kept = 1;
813
+ }
814
+ break;
815
+ }
816
+ text = next;
817
+ kept++;
818
+ }
819
+ if (rendered.full) notes.push("text_cap");
820
+ const seen = /* @__PURE__ */ new Set();
821
+ const outbound = [];
822
+ let linkCapped = rendered.linkCapped;
823
+ let linkBytes = 0;
824
+ let bytesCapped = false;
825
+ const maxLinkBytes = options.maxLinkBytes ?? DEFAULT_MAX_LINK_BYTES;
826
+ for (const b of blocks.slice(0, kept)) {
827
+ for (const l of b.links) {
828
+ if (seen.has(l)) continue;
829
+ if (linkBytes + l.length > maxLinkBytes) {
830
+ bytesCapped = true;
831
+ continue;
832
+ }
833
+ if (seen.size >= maxLinks) {
834
+ linkCapped = true;
835
+ continue;
836
+ }
837
+ seen.add(l);
838
+ linkBytes += l.length;
839
+ outbound.push(l);
840
+ }
841
+ }
842
+ if (linkCapped) notes.push("link_cap");
843
+ if (bytesCapped) notes.push("link_bytes_cap");
844
+ if (tooLong) notes.push("url_too_long");
845
+ const chosen = asArray(article?.author).map((a) => deref(ld, a));
846
+ const ldAuthor = chosen.map((a) => ({ name: cleanName(nameOf(a), false), url: isObject(a) && typeof a.url === "string" ? a.url : void 0 })).find((a) => a.name);
847
+ let author = ldAuthor?.name;
848
+ for (const cand of [
849
+ cleanName(meta.get("author"), false),
850
+ cleanName(meta.get("article:author"), false),
851
+ cleanName(meta.get("parsely-author"), false),
852
+ cleanName(meta.get("dc.creator"), false),
853
+ cleanName(meta.get("citation_author"), false)
854
+ ]) {
855
+ if (author) break;
856
+ author = cand;
857
+ }
858
+ const pick = (names) => names.map((n) => cleanName(n, true)).find((n) => n !== void 0);
859
+ author ??= pick(authorLinks.map((a) => a.name ?? ""));
860
+ author ??= pick([...itempropAuthors, ...bylines]);
861
+ if (!author) {
862
+ for (const b of blocks.slice(0, 3)) {
863
+ const m = /^(?:by|par|von)\s+(\p{Lu}[\p{L}'’.-]*(?:\s+\p{Lu}[\p{L}'’.-]*){0,3})/u.exec(b.text);
864
+ if (m) {
865
+ author = cleanName(m[1], true);
866
+ if (author) break;
867
+ }
868
+ }
869
+ }
870
+ let authorUrl;
871
+ if (author) {
872
+ const same = (a) => a ? cleanName(a, true)?.toLowerCase() === author.toLowerCase() : false;
873
+ const profile = (ldAuthor?.name === author ? ldAuthor.url : void 0) ?? authorLinks.find((a) => a.href && same(a.name))?.href;
874
+ const abs = profile ? resolve(profile) : void 0;
875
+ if (abs && /^https?:/i.test(abs)) authorUrl = abs;
876
+ }
877
+ const timeCandidates = [...times.filter((t) => t.inArticle), ...times.filter((t) => !t.inArticle)].map((t) => t.value);
878
+ const publishedAt = [
879
+ meta.get("article:published_time"),
880
+ meta.get("og:article:published_time"),
881
+ typeof article?.datePublished === "string" ? article.datePublished : void 0,
882
+ meta.get("datepublished"),
883
+ meta.get("date"),
884
+ meta.get("pubdate"),
885
+ meta.get("publish-date"),
886
+ meta.get("dc.date"),
887
+ meta.get("dc.date.issued"),
888
+ meta.get("parsely-pub-date"),
889
+ meta.get("sailthru.date"),
890
+ ...timeCandidates
891
+ ].map(normalizeDate).find((d) => d !== void 0);
892
+ const free = article?.isAccessibleForFree;
893
+ const paywalled = free === false || typeof free === "string" && free.toLowerCase() === "false" ? true : void 0;
894
+ const wordCount = countWords(text);
895
+ const linkChars = blocks.reduce((n, b) => n + b.linkChars, 0);
896
+ const textChars = blocks.reduce((n, b) => n + b.text.length, 0);
897
+ const editorial = textChars - linkChars >= 80 && linkChars / Math.max(textChars, 1) <= 0.5;
898
+ const extraction = wordCount < MIN_WORDS || !editorial ? "empty" : "ok";
899
+ return {
900
+ extraction,
901
+ ...title ? { title } : {},
902
+ text,
903
+ textTruncated: truncated,
904
+ wordCount,
905
+ ...author ? { author } : {},
906
+ ...authorUrl ? { authorUrl } : {},
907
+ ...publishedAt ? { publishedAt } : {},
908
+ ...lang ? { language: lang } : {},
909
+ canonicalUrl: canonical,
910
+ site,
911
+ outboundLinks: outbound,
912
+ hasMedia,
913
+ ...paywalled ? { paywalled } : {},
914
+ challenge,
915
+ notes
916
+ };
917
+ }
918
+ function tagEnd(text, from) {
919
+ let quote = "";
920
+ for (let i = from; i < text.length; i++) {
921
+ const c = text[i];
922
+ if (quote) {
923
+ if (c === quote) quote = "";
924
+ } else if (c === '"' || c === "'") quote = c;
925
+ else if (c === ">") return i;
926
+ }
927
+ return -1;
928
+ }
929
+ var PRESCAN_BYTES = 8192;
930
+ function supportedLabel(label, fromMeta = true) {
931
+ const l = label?.trim().toLowerCase();
932
+ if (!l) return void 0;
933
+ if (fromMeta && l === "x-user-defined") return "windows-1252";
934
+ try {
935
+ const name = new TextDecoder(l).encoding;
936
+ return fromMeta && (name === "utf-16le" || name === "utf-16be") ? "utf-8" : l;
937
+ } catch {
938
+ return void 0;
939
+ }
940
+ }
941
+ function sniffCharset(bytes) {
942
+ const head = new TextDecoder("latin1").decode(bytes.subarray(0, PRESCAN_BYTES));
943
+ let i = 0;
944
+ while (i < head.length) {
945
+ const lt = head.indexOf("<", i);
946
+ if (lt === -1) return void 0;
947
+ i = lt;
948
+ if (head.startsWith("<!-->", i)) {
949
+ i += 5;
950
+ continue;
951
+ }
952
+ if (head.startsWith("<!--->", i)) {
953
+ i += 6;
954
+ continue;
955
+ }
956
+ if (head.startsWith("<!--", i)) {
957
+ const end2 = head.indexOf("-->", i + 2);
958
+ if (end2 === -1) return void 0;
959
+ i = end2 + 3;
960
+ continue;
961
+ }
962
+ const m = /^<(\/?)([a-zA-Z][^\s/>]*)/.exec(head.slice(i, i + 40));
963
+ if (!m) {
964
+ if (/^<[!/?]/.test(head.slice(i, i + 2))) {
965
+ const end2 = head.indexOf(">", i);
966
+ if (end2 === -1) return void 0;
967
+ i = end2 + 1;
968
+ } else i += 1;
969
+ continue;
970
+ }
971
+ const end = tagEnd(head, i + 1);
972
+ if (end === -1) return void 0;
973
+ const name = m[2].toLowerCase();
974
+ if (!m[1] && name === "meta") {
975
+ const attrs = /* @__PURE__ */ new Map();
976
+ for (const a of head.slice(i + 1 + m[0].length - 1, end).matchAll(/([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
977
+ if (!attrs.has(a[1].toLowerCase())) attrs.set(a[1].toLowerCase(), a[2] ?? a[3] ?? a[4] ?? "");
978
+ }
979
+ const direct = supportedLabel(attrs.get("charset"));
980
+ if (direct) return direct;
981
+ if (attrs.get("http-equiv")?.toLowerCase() === "content-type") {
982
+ const found = supportedLabel(/charset\s*=\s*["']?([\w:.-]+)/i.exec(attrs.get("content") ?? "")?.[1]);
983
+ if (found) return found;
984
+ }
985
+ }
986
+ i = end + 1;
987
+ if (!m[1] && (name === "script" || name === "style" || name === "title" || name === "textarea")) {
988
+ const closer = new RegExp(`</${name}[\\s/>]`, "ig");
989
+ closer.lastIndex = i;
990
+ const close = closer.exec(head);
991
+ if (!close) return void 0;
992
+ i = close.index;
993
+ }
994
+ }
995
+ return void 0;
996
+ }
997
+ function charsetOf(bytes, contentType) {
998
+ if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) return "utf-8";
999
+ if (bytes[0] === 255 && bytes[1] === 254) return "utf-16le";
1000
+ if (bytes[0] === 254 && bytes[1] === 255) return "utf-16be";
1001
+ const header = supportedLabel(contentType ? /charset\s*=\s*["']?([\w:.-]+)/i.exec(contentType)?.[1] : void 0, false);
1002
+ return header ?? sniffCharset(bytes) ?? "utf-8";
1003
+ }
1004
+ function decodeHtml(bytes, contentType) {
1005
+ return new TextDecoder(charsetOf(bytes, contentType)).decode(bytes);
1006
+ }
1007
+
1008
+ // src/connectors/web.ts
1009
+ var WEB_CONNECTOR_ID = "web";
1010
+ function webTask(url, context = {}) {
1011
+ return {
1012
+ id: canonicalUrl(url),
1013
+ kind: "read",
1014
+ params: { url: url.trim(), ...Object.keys(context).length ? { context } : {} }
1015
+ };
1016
+ }
1017
+ var WebExt = z.object({
1018
+ site: z.string(),
1019
+ /** Author name as found on the page. */
1020
+ extractedAuthor: z.string().optional(),
1021
+ extraction: z.enum(["ok", "empty", "not_html", "blocked"]),
1022
+ /** The page says its full text is behind a paywall. */
1023
+ paywalled: z.boolean().optional(),
1024
+ /** Why the result is partial, comma separated: `input_truncated`, `node_cap`, `text_cap`, `link_cap`. */
1025
+ note: z.string().optional()
1026
+ });
1027
+ var isHttpUrl = (s) => /^https?:\/\/\S+$/i.test(s.trim()) && URL.canParse(s.trim());
1028
+ var HTML_TYPE = /^(?:text\/html|application\/xhtml\+xml)\b/i;
1029
+ function headerOf(headers, name) {
1030
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === name) return v;
1031
+ return void 0;
1032
+ }
1033
+ var extOf = (contentType) => !contentType || HTML_TYPE.test(contentType) ? "html" : /^application\/pdf\b/i.test(contentType) ? "pdf" : "bin";
1034
+ var BLOCKED_STATUSES = /* @__PURE__ */ new Set([401, 403, 429]);
1035
+ var web = defineConnector({
1036
+ id: WEB_CONNECTOR_ID,
1037
+ version: "1",
1038
+ transports: ["http", "browser"],
1039
+ access: { level: "none" },
1040
+ capabilities: ["read-by-url"],
1041
+ counters: [],
1042
+ pace: { delayMs: 1e3 },
1043
+ ext: WebExt,
1044
+ plan(_recipe, sources) {
1045
+ const tasks = /* @__PURE__ */ new Map();
1046
+ const add = (task) => {
1047
+ const known = tasks.get(task.id);
1048
+ if (!known) return void tasks.set(task.id, task);
1049
+ const a = known.params?.context;
1050
+ const b = task.params?.context;
1051
+ const aliases = [.../* @__PURE__ */ new Set([...a?.canonicalAliases ?? [], ...b?.canonicalAliases ?? []])];
1052
+ const subjects = [...a?.subjects ?? []];
1053
+ for (const s of b?.subjects ?? []) if (!subjects.some((x) => x.label === s.label && x.provenance === s.provenance)) subjects.push(s);
1054
+ if (!subjects.length && !aliases.length) return;
1055
+ tasks.set(task.id, {
1056
+ ...known,
1057
+ params: { ...known.params, context: { ...b ?? {}, ...a ?? {}, ...subjects.length ? { subjects } : {}, ...aliases.length ? { canonicalAliases: aliases } : {} } }
1058
+ });
1059
+ };
1060
+ for (const source of sources) {
1061
+ const base = { ...source.instance ? { sourceInstance: source.instance } : {}, ...limitsOf(source.options) };
1062
+ const urls = source.options?.urls;
1063
+ for (const u of Array.isArray(urls) ? urls : []) {
1064
+ if (typeof u !== "string" || !u.trim()) continue;
1065
+ add(isHttpUrl(u) ? webTask(u, base) : invalidTask(u));
1066
+ }
1067
+ for (const q of source.queries) {
1068
+ const text = q.text.trim();
1069
+ add(isHttpUrl(text) ? webTask(text, { ...base, query: text, subjects: [{ label: q.subject, provenance: "query" }] }) : invalidTask(text));
1070
+ }
1071
+ }
1072
+ return [...tasks.values()];
1073
+ },
1074
+ async fetch(task, transport) {
1075
+ const url = String(task.params.url ?? "");
1076
+ if (!isHttpUrl(url)) throw new Error(`not an http(s) URL: ${url}`);
1077
+ const context = task.params.context;
1078
+ if (transport.name === "browser") {
1079
+ const page = await transport.browser.open(url);
1080
+ try {
1081
+ const html = await transport.browser.evaluate(page, "document.documentElement.outerHTML");
1082
+ const raw2 = { url: page.url ?? url, ext: "html", bytes: new TextEncoder().encode(String(html ?? "")), httpStatus: 200, contentType: SNAPSHOT_TYPE };
1083
+ assess(raw2, context);
1084
+ return { raws: [raw2] };
1085
+ } finally {
1086
+ await transport.browser.close(page);
1087
+ }
1088
+ }
1089
+ const res = await transport.http.request({
1090
+ url,
1091
+ headers: { accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5" }
1092
+ });
1093
+ const contentType = headerOf(res.headers, "content-type");
1094
+ const raw = { url: res.url, ext: extOf(contentType), bytes: res.body, httpStatus: res.status, ...contentType ? { contentType } : {} };
1095
+ if (res.status >= 200 && res.status < 300 && raw.ext === "html" && res.body.byteLength > 0) assess(raw, context);
1096
+ return { raws: [raw] };
1097
+ },
1098
+ parse(input) {
1099
+ const { raw, task } = input;
1100
+ if (raw.ext !== "html") return {};
1101
+ if (raw.httpStatus !== void 0 && (BLOCKED_STATUSES.has(raw.httpStatus) || raw.httpStatus < 200 || raw.httpStatus >= 300)) return {};
1102
+ const context = task.params?.context;
1103
+ const page = readPage(raw.bytes, raw.contentType, raw.url, context);
1104
+ if (page.extraction !== "ok") return {};
1105
+ return buildItem(page, String(task.params?.url ?? raw.url), context);
1106
+ }
1107
+ });
1108
+ var SNAPSHOT_TYPE = "text/html; charset=utf-8";
1109
+ function limitsOf(options) {
1110
+ const out = {};
1111
+ const aliases = options?.canonicalAliases;
1112
+ if (Array.isArray(aliases)) {
1113
+ const hosts = aliases.filter((h) => typeof h === "string" && h.trim() !== "").map((h) => h.trim().toLowerCase());
1114
+ if (hosts.length) out.canonicalAliases = hosts;
1115
+ }
1116
+ for (const key of ["maxInputBytes", "maxChars"]) {
1117
+ const v = options?.[key];
1118
+ if (typeof v === "number" && Number.isInteger(v) && v > 0) out[key] = v;
1119
+ }
1120
+ return out;
1121
+ }
1122
+ var recent = /* @__PURE__ */ new WeakMap();
1123
+ function readPage(bytes, contentType, url, context) {
1124
+ const key = JSON.stringify([contentType ?? "", url, context ?? null]);
1125
+ const hit = recent.get(bytes);
1126
+ if (hit?.key === key) return hit.page;
1127
+ const page = extract(bytes, contentType, url, context);
1128
+ recent.set(bytes, { key, page });
1129
+ return page;
1130
+ }
1131
+ function extract(bytes, contentType, url, context) {
1132
+ const cap = context?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES;
1133
+ const inputTruncated = bytes.byteLength > cap;
1134
+ const html = decodeHtml(inputTruncated ? bytes.subarray(0, cap) : bytes, contentType);
1135
+ return extractArticle(html, url, {
1136
+ inputTruncated,
1137
+ ...context?.maxChars ? { maxChars: context.maxChars } : {},
1138
+ ...context?.canonicalAliases ? { canonicalAliases: context.canonicalAliases } : {}
1139
+ });
1140
+ }
1141
+ function invalidTask(text) {
1142
+ return { id: `invalid:${text}`, kind: "read", params: { url: text } };
1143
+ }
1144
+ function assess(raw, context) {
1145
+ const page = readPage(raw.bytes, raw.contentType, raw.url, context);
1146
+ if (page.extraction === "ok") return;
1147
+ const cause = page.extraction === "blocked" ? "challenge" : "empty";
1148
+ throw new TransportError(cause, cause === "challenge" ? "verification page" : `no article text in the page${page.notes.length ? ` (${page.notes.join(", ")})` : ""}`, { status: raw.httpStatus, url: raw.url, body: raw.bytes, ext: raw.ext, contentType: raw.contentType });
1149
+ }
1150
+ async function buildItem(page, finalUrl, context) {
1151
+ const domain = new URL(page.canonicalUrl).hostname.replace(/^www\./, "");
1152
+ const slug = page.author ? authorSlug(page.author) : "";
1153
+ const authorRef = slug ? `web:${domain}/${slug}` : void 0;
1154
+ const contentId = await textFingerprint(page.text);
1155
+ const ext = {
1156
+ site: page.site,
1157
+ ...page.author ? { extractedAuthor: page.author } : {},
1158
+ extraction: "ok",
1159
+ ...page.paywalled ? { paywalled: true } : {},
1160
+ ...page.notes.length ? { note: page.notes.join(",") } : {}
1161
+ };
1162
+ const actors = authorRef ? [{ ref: authorRef, displayName: page.author, ...page.authorUrl ? { profileUrl: page.authorUrl } : {}, audience: [] }] : [];
1163
+ return {
1164
+ items: [
1165
+ {
1166
+ id: await itemIdFromUrl(WEB_CONNECTOR_ID, page.canonicalUrl),
1167
+ source: WEB_CONNECTOR_ID,
1168
+ ...context?.sourceInstance ? { sourceInstance: context.sourceInstance } : {},
1169
+ kind: "article",
1170
+ url: finalUrl,
1171
+ canonicalUrl: page.canonicalUrl,
1172
+ ...contentId ? { contentId } : {},
1173
+ subjects: context?.subjects ?? [],
1174
+ ...page.title ? { title: page.title } : {},
1175
+ text: page.text,
1176
+ textTruncated: page.textTruncated,
1177
+ ...page.language ? { language: page.language } : {},
1178
+ wordCount: page.wordCount,
1179
+ format: page.wordCount >= 400 ? "long article" : "short article",
1180
+ ...authorRef ? { authorRef } : {},
1181
+ ...page.publishedAt ? { publishedAt: page.publishedAt } : {},
1182
+ outboundLinks: page.outboundLinks,
1183
+ hasMedia: page.hasMedia,
1184
+ ...context?.query ? { query: context.query } : {},
1185
+ ext
1186
+ }
1187
+ ],
1188
+ actors
1189
+ };
1190
+ }
1191
+
1192
+ // src/connectors/index.ts
1193
+ var shippedConnectors = [web];
1194
+
1195
+ export { DEFAULT_MAX_CHARS, DEFAULT_MAX_INPUT_BYTES, DEFAULT_MAX_LINKS, DEFAULT_MAX_LINK_BYTES, MAX_URL_LENGTH, MIN_WORDS, WEB_CONNECTOR_ID, WebExt, authorSlug, charsetOf, decodeHtml, extractArticle, normalizeDate, shippedConnectors, web, webTask };
1196
+ //# sourceMappingURL=connectors.mjs.map
1197
+ //# sourceMappingURL=connectors.mjs.map