@astratra/web-search 0.0.0-stage → 1.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.
package/src/dates.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Les dates de publication, telles que les moteurs les donnent : ISO
3
+ * (`2026-11-02T08:00:00Z`), relatives (« 3 days ago », « il y a 2 heures »),
4
+ * ou écrites (« Sep 2, 2026 », « 2 sept. 2026 »). Rendues en ISO (UTC), ou
5
+ * null quand on ne sait pas : une date devinée serait pire que pas de date.
6
+ */
7
+
8
+ const MONTHS = {
9
+ jan: 0, january: 0, janv: 0, janvier: 0,
10
+ feb: 1, february: 1, fev: 1, fevr: 1, fevrier: 1,
11
+ mar: 2, march: 2, mars: 2,
12
+ apr: 3, april: 3, avr: 3, avril: 3,
13
+ may: 4, mai: 4,
14
+ jun: 5, june: 5, juin: 5,
15
+ jul: 6, july: 6, juil: 6, juillet: 6,
16
+ aug: 7, august: 7, aout: 7,
17
+ sep: 8, sept: 8, september: 8, septembre: 8,
18
+ oct: 9, october: 9, octobre: 9,
19
+ nov: 10, november: 10, novembre: 10,
20
+ dec: 11, december: 11, decembre: 11
21
+ };
22
+
23
+ const UNITS = {
24
+ minute: 60_000, minutes: 60_000, min: 60_000, mins: 60_000,
25
+ hour: 3_600_000, hours: 3_600_000, heure: 3_600_000, heures: 3_600_000, h: 3_600_000,
26
+ day: 86_400_000, days: 86_400_000, jour: 86_400_000, jours: 86_400_000,
27
+ week: 604_800_000, weeks: 604_800_000, semaine: 604_800_000, semaines: 604_800_000,
28
+ month: 2_592_000_000, months: 2_592_000_000, mois: 2_592_000_000,
29
+ year: 31_536_000_000, years: 31_536_000_000, an: 31_536_000_000, ans: 31_536_000_000, annee: 31_536_000_000, annees: 31_536_000_000
30
+ };
31
+
32
+ const fold = (text) => text.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
33
+
34
+ function valid(year, month, day) {
35
+ const date = new Date(Date.UTC(year, month, day));
36
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month && date.getUTCDate() === day ? date : null;
37
+ }
38
+
39
+ /**
40
+ * @param {unknown} value
41
+ * @param {{ now?: number }} [options] l'horloge, pour les dates relatives.
42
+ * @returns {string|null} une date ISO 8601 en UTC
43
+ */
44
+ function parseDate(value, { now = Date.now() } = {}) {
45
+ if (value === null || value === undefined || value === '') return null;
46
+ if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null;
47
+ const text = fold(String(value).trim());
48
+ if (!text || text.length > 80) return null;
49
+
50
+ if (/^\d{4}-\d{2}-\d{2}([t ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(z|[+-]\d{2}:?\d{2})?)?$/.test(text)) {
51
+ const [year, month, day] = text.slice(0, 10).split('-').map(Number);
52
+ if (!valid(year, month - 1, day)) return null;
53
+ /* Une heure sans fuseau est lue en UTC (ce que les moteurs envoient), jamais à l'heure de la machine. */
54
+ const stamp = text.length === 10 ? `${text}T00:00:00Z` : text.toUpperCase().replace(' ', 'T');
55
+ const date = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(stamp) ? stamp : `${stamp}Z`);
56
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
57
+ }
58
+
59
+ const relative = text.match(/^(?:il y a\s+)?(\d+|an?|une?)\s+([a-z]+)\.?(?:\s+ago)?$/);
60
+ if (relative && (text.includes('ago') || text.startsWith('il y a'))) {
61
+ const amount = /^\d+$/.test(relative[1]) ? Number(relative[1]) : 1;
62
+ const unit = UNITS[relative[2]];
63
+ if (unit && amount < 10_000) return new Date(now - amount * unit).toISOString();
64
+ return null;
65
+ }
66
+ if (text === 'yesterday' || text === 'hier') return new Date(now - 86_400_000).toISOString();
67
+ if (text === 'today' || text === "aujourd'hui") return new Date(now).toISOString();
68
+
69
+ // « Sep 2, 2026 », « September 2 2026 »
70
+ let match = text.match(/^([a-z]+)\.?\s+(\d{1,2}),?\s+(\d{4})$/);
71
+ if (match && MONTHS[match[1]] !== undefined) {
72
+ const date = valid(Number(match[3]), MONTHS[match[1]], Number(match[2]));
73
+ return date ? date.toISOString() : null;
74
+ }
75
+ // « 2 sept. 2026 », « 2 September 2026 », « 1er mars 2026 »
76
+ match = text.match(/^(\d{1,2})(?:er)?\s+([a-z]+)\.?\s+(\d{4})$/);
77
+ if (match && MONTHS[match[2]] !== undefined) {
78
+ const date = valid(Number(match[3]), MONTHS[match[2]], Number(match[1]));
79
+ return date ? date.toISOString() : null;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ /** L'âge en jours d'une date ISO, ou null. */
85
+ function ageInDays(iso, now = Date.now()) {
86
+ if (!iso) return null;
87
+ const time = Date.parse(iso);
88
+ return Number.isFinite(time) ? Math.max(0, (now - time) / 86_400_000) : null;
89
+ }
90
+
91
+ module.exports = { parseDate, ageInDays };
package/src/errors.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Les erreurs du paquet : un code stable, un message court, jamais de clé.
3
+ *
4
+ * Le message d'une erreur part parfois vers un modèle ou un journal : il ne
5
+ * porte que le code, le fournisseur et le statut HTTP. Une clé passée par
6
+ * l'appelant est aussi retirée de tout texte venu d'ailleurs (`redact`).
7
+ */
8
+
9
+ const CODES = Object.freeze({
10
+ BAD_REQUEST: 'WEB_SEARCH_BAD_REQUEST',
11
+ NO_PROVIDER: 'WEB_SEARCH_NO_PROVIDER',
12
+ ALL_FAILED: 'WEB_SEARCH_ALL_FAILED',
13
+ PROVIDER_FAILED: 'WEB_SEARCH_PROVIDER_FAILED',
14
+ QUOTA: 'WEB_SEARCH_QUOTA',
15
+ BLOCKED_URL: 'WEB_READ_BLOCKED_URL',
16
+ BLOCKED_ADDRESS: 'WEB_READ_BLOCKED_ADDRESS',
17
+ TOO_MANY_REDIRECTS: 'WEB_READ_TOO_MANY_REDIRECTS',
18
+ TOO_LARGE: 'WEB_READ_TOO_LARGE',
19
+ TIMEOUT: 'WEB_READ_TIMEOUT',
20
+ BAD_STATUS: 'WEB_READ_BAD_STATUS',
21
+ UNSUPPORTED_TYPE: 'WEB_READ_UNSUPPORTED_TYPE',
22
+ READ_FAILED: 'WEB_READ_FAILED'
23
+ });
24
+
25
+ class WebSearchError extends Error {
26
+ /**
27
+ * @param {string} code
28
+ * @param {string} message
29
+ * @param {{ provider?: string, status?: number, retryable?: boolean, quota?: boolean }} [details]
30
+ */
31
+ constructor(code, message, details = {}) {
32
+ super(message);
33
+ this.name = 'WebSearchError';
34
+ this.code = code;
35
+ if (details.provider) this.provider = details.provider;
36
+ if (details.status !== undefined) this.status = details.status;
37
+ this.retryable = Boolean(details.retryable);
38
+ this.quota = Boolean(details.quota);
39
+ }
40
+ }
41
+
42
+ /** Retire chaque secret d'un texte (au moins 4 caractères, pour ne pas effacer n'importe quoi). */
43
+ function redact(text, secrets = []) {
44
+ let out = String(text ?? '');
45
+ for (const secret of secrets) {
46
+ if (typeof secret === 'string' && secret.length >= 4) out = out.split(secret).join('[redacted]');
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /**
52
+ * L'échec d'un fournisseur, classé pour le repli :
53
+ * - 429, 5xx, réseau, délai : `retryable` (un nouvel essai a une chance) ;
54
+ * - 402, 429 répété, quota : `quota` (passer au suivant, le laisser reposer) ;
55
+ * - autre 4xx : ni l'un ni l'autre (la requête elle-même est refusée par ce moteur).
56
+ */
57
+ function providerFailure(provider, { status, cause, secrets } = {}) {
58
+ const retryable = status === undefined || status === 408 || status === 429 || status >= 500;
59
+ const quota = status === 402 || status === 429;
60
+ const reason = status !== undefined ? `answered ${status}` : `unreachable (${redact(cause?.name === 'TimeoutError' || cause?.name === 'AbortError' ? 'timeout' : cause?.message || 'network', secrets).slice(0, 120)})`;
61
+ return new WebSearchError(CODES.PROVIDER_FAILED, `${provider} ${reason}`, { provider, status, retryable, quota });
62
+ }
63
+
64
+ module.exports = { CODES, WebSearchError, redact, providerFailure };
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Une petite batterie d'évaluation : des questions types et des critères
3
+ * qu'une machine vérifie, pour comparer l'outil à une recherche brute.
4
+ *
5
+ * Critères vérifiés sur chaque cas :
6
+ * - `noMixing` : le titre et l'extrait de chaque entrée sont exactement ceux
7
+ * que le moteur nommé par `snippetFrom` a donnés pour CETTE page ;
8
+ * - `noDuplicates` : pas deux entrées pour la même page canonique ;
9
+ * - `passagesVerified` : chaque passage cité est, mot pour mot, à sa position
10
+ * dans le texte de sa page (`readText` donne ce texte) ;
11
+ * - et, selon le cas : `expectedDomain` (le bon site dans les `within`
12
+ * premiers), `recentFirst` (la page la plus récente en tête parmi les
13
+ * premières datées), `forbiddenDomains` (aucun de ces sites).
14
+ */
15
+
16
+ const { canonicalUrl, inSite, normalizeSite } = require('./url');
17
+ const { verifyPassage } = require('./passages');
18
+
19
+ /** Enveloppe des fournisseurs pour garder ce que chacun a rendu, page par page. */
20
+ function recordProviders(providers) {
21
+ const seen = new Map();
22
+ const wrapped = providers.map((provider) => ({
23
+ ...provider,
24
+ async search(request, context) {
25
+ const answer = await provider.search(request, context);
26
+ for (const hit of answer?.hits || []) {
27
+ const key = `${provider.id} ${canonicalUrl(hit.url)}`;
28
+ if (!seen.has(key)) seen.set(key, []);
29
+ seen.get(key).push(hit);
30
+ }
31
+ return answer;
32
+ }
33
+ }));
34
+ return {
35
+ providers: wrapped,
36
+ /** Ce que ce moteur a rendu pour cette page (toutes les fois). */
37
+ hitsFor: (providerId, url) => seen.get(`${providerId} ${canonicalUrl(url)}`) || []
38
+ };
39
+ }
40
+
41
+ /**
42
+ * Une recherche brute, pour comparer : un seul moteur, ses résultats tels quels
43
+ * (ni dédoublonnage, ni filtre revérifié, ni fraîcheur).
44
+ */
45
+ async function rawSearch(provider, request) {
46
+ const answer = await provider.search({ sites: [], excludeSites: [], lang: null, country: null, freshness: null, limit: 8, ...request }, {});
47
+ return {
48
+ query: request.query,
49
+ results: (answer?.hits || []).slice(0, request.limit || 8).map((hit, index) => ({
50
+ id: `S${index + 1}`, title: hit.title, url: hit.url, canonicalUrl: canonicalUrl(hit.url) || hit.url,
51
+ domain: (() => { try { return new URL(hit.url).hostname.replace(/^www\./, ''); } catch (_error) { return null; } })(),
52
+ publishedAt: hit.publishedAt || null, snippet: hit.snippet, snippetFrom: provider.id
53
+ }))
54
+ };
55
+ }
56
+
57
+ function checkCase(found, expect = {}, { recorder, pageTexts }) {
58
+ const results = found.results || [];
59
+ const checks = {};
60
+ if (recorder) {
61
+ checks.noMixing = results.every((result) => recorder.hitsFor(result.snippetFrom, result.url)
62
+ .some((hit) => hit.title === result.title && (hit.snippet || '') === (result.snippet || '')));
63
+ }
64
+ const canonicals = results.map((result) => result.canonicalUrl);
65
+ checks.noDuplicates = new Set(canonicals).size === canonicals.length;
66
+ const passages = results.flatMap((result) => (result.page?.status === 'read' ? result.page.passages.map((passage) => ({ url: result.url, passage })) : []));
67
+ if (passages.length) checks.passagesVerified = passages.every(({ url, passage }) => pageTexts.has(url) && verifyPassage(pageTexts.get(url), passage));
68
+ if (expect.expectedDomain) {
69
+ const site = normalizeSite(expect.expectedDomain);
70
+ const within = expect.within || 3;
71
+ checks.expectedDomain = results.slice(0, within).some((result) => inSite(result.domain, site));
72
+ }
73
+ if (expect.recentFirst) {
74
+ const dated = results.slice(0, expect.within || 3).filter((result) => result.publishedAt);
75
+ checks.recentFirst = dated.length > 0 && results[0].publishedAt !== null
76
+ && dated.every((result) => Date.parse(results[0].publishedAt) >= Date.parse(result.publishedAt));
77
+ }
78
+ if (expect.forbiddenDomains) {
79
+ const forbidden = expect.forbiddenDomains.map(normalizeSite);
80
+ checks.forbiddenDomains = results.every((result) => !forbidden.some((site) => inSite(result.domain, site)));
81
+ }
82
+ return checks;
83
+ }
84
+
85
+ /**
86
+ * @param {object} options
87
+ * @param {{ id: string, input: object, expect?: object }[]} options.cases
88
+ * @param {Function} options.search (input) => Promise<résultat de ws.search>
89
+ * @param {object} [options.recorder] recordProviders(…) : active le critère noMixing.
90
+ * @param {Function} [options.readText] async (url) => texte de la page, pour revérifier les passages.
91
+ * @returns {Promise<{ cases: object[], summary: { cases: number, passed: number, checks: Record<string, { passed: number, total: number }> } }>}
92
+ */
93
+ async function runEvaluation({ cases, search, recorder, readText }) {
94
+ const out = [];
95
+ const totals = {};
96
+ for (const testCase of cases) {
97
+ let found;
98
+ try {
99
+ found = await search(testCase.input);
100
+ } catch (error) {
101
+ out.push({ id: testCase.id, passed: false, error: error.code || 'error', checks: {} });
102
+ continue;
103
+ }
104
+ const pageTexts = new Map();
105
+ if (typeof readText === 'function') {
106
+ for (const result of found.results || []) {
107
+ if (result.page?.status !== 'read') continue;
108
+ try {
109
+ pageTexts.set(result.url, await readText(result.url));
110
+ } catch (_error) {
111
+ /* une page illisible au second passage fait échouer la vérification */
112
+ }
113
+ }
114
+ }
115
+ const checks = checkCase(found, testCase.expect, { recorder, pageTexts });
116
+ for (const [name, ok] of Object.entries(checks)) {
117
+ totals[name] = totals[name] || { passed: 0, total: 0 };
118
+ totals[name].total += 1;
119
+ if (ok) totals[name].passed += 1;
120
+ }
121
+ out.push({ id: testCase.id, passed: Object.values(checks).every(Boolean), checks, results: (found.results || []).map((result) => ({ id: result.id, domain: result.domain, url: result.url, publishedAt: result.publishedAt })) });
122
+ }
123
+ return { cases: out, summary: { cases: out.length, passed: out.filter((entry) => entry.passed).length, checks: totals } };
124
+ }
125
+
126
+ module.exports = { runEvaluation, recordProviders, rawSearch, checkCase };
package/src/extract.js ADDED
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Le texte principal d'une page HTML, et ce qu'elle dit d'elle-même (titre,
3
+ * langue, adresse canonique, date de publication), sans aucune dépendance.
4
+ *
5
+ * Prudent plutôt que malin : scripts, styles, cadres et commentaires partent
6
+ * d'abord ; puis la zone principale est choisie (<article> le plus long,
7
+ * <main>, role="main", sinon <body>), débarrassée de la navigation, des pieds
8
+ * de page, des encarts et de ce que leurs classes désignent comme accessoire
9
+ * (cookies, partage, publicités, commentaires…). Les blocs deviennent des
10
+ * retours à la ligne. Le texte rendu est celui dans lequel les passages cités
11
+ * sont repérés : une position renvoie toujours à ce texte-là.
12
+ *
13
+ * Le HTML est découpé une seule fois, en temps linéaire (indexOf, aucune
14
+ * expression régulière qui revienne en arrière) : une page piégée de 2 Mo
15
+ * (« <a <a <a … » sans fin de balise) se lit aussi vite qu'une page normale et
16
+ * ne bloque jamais le processus.
17
+ *
18
+ * Un extracteur meilleur (Readability…) se branche par l'option `extract` de
19
+ * createWebSearch ; il doit rendre au moins `{ text }`.
20
+ */
21
+
22
+ const { decodeEntities, plainText } = require('./text');
23
+ const { parseDate } = require('./dates');
24
+
25
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
26
+ /* Leur contenu est du texte brut jusqu'à la balise de fin (pas de balises dedans). */
27
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title', 'noscript', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext']);
28
+ /* Jamais du texte à lire. */
29
+ const DROP_ALWAYS = new Set(['script', 'style', 'noscript', 'template', 'svg', 'math', 'iframe', 'object', 'canvas', 'video', 'audio', 'select', 'textarea', 'head', 'title']);
30
+ const BOILERPLATE_TAGS = new Set(['nav', 'footer', 'aside', 'menu', 'dialog', 'form']);
31
+ const BOILERPLATE_HINT = /(^|[\s_-])(cookie|consent|gdpr|newsletter|subscribe|share|sharing|social|related|recommend|comment|comments|advert|advertisement|ads?|promo|sponsor|breadcrumbs?|sidebar|menu|navbar|nav|footer|masthead|banner|popup|modal|signup|paywall)([\s_-]|$)/i;
32
+ const BLOCK_TAGS = new Set(['p', 'div', 'section', 'article', 'main', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'blockquote', 'pre', 'figure', 'figcaption', 'address', 'details', 'summary', 'hr', 'br']);
33
+ const MAX_TAG_ATTRIBUTES = 8_192;
34
+
35
+ /**
36
+ * Découpe le HTML en jetons, en une passe : texte, balise (ouvrante ou fermante)
37
+ * ou contenu brut (script, style…). Les commentaires et déclarations disparaissent ;
38
+ * une balise jamais fermée (pas de « > ») arrête la lecture là.
39
+ */
40
+ function tokenize(html) {
41
+ const tokens = [];
42
+ const n = html.length;
43
+ let i = 0;
44
+ while (i < n) {
45
+ const lt = html.indexOf('<', i);
46
+ if (lt === -1) {
47
+ tokens.push({ type: 'text', start: i, end: n });
48
+ break;
49
+ }
50
+ if (lt > i) tokens.push({ type: 'text', start: i, end: lt });
51
+ if (html.startsWith('<!--', lt)) {
52
+ const close = html.indexOf('-->', lt + 4);
53
+ if (close === -1) break;
54
+ i = close + 3;
55
+ continue;
56
+ }
57
+ const next = html.charCodeAt(lt + 1);
58
+ const isLetter = (code) => (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
59
+ const closing = next === 47; // '/'
60
+ if (next === 33 || next === 63) { // '<!' ou '<?'
61
+ const gt = html.indexOf('>', lt + 2);
62
+ if (gt === -1) break;
63
+ i = gt + 1;
64
+ continue;
65
+ }
66
+ if (!isLetter(closing ? html.charCodeAt(lt + 2) : next)) {
67
+ tokens.push({ type: 'text', start: lt, end: lt + 1 });
68
+ i = lt + 1;
69
+ continue;
70
+ }
71
+ const gt = html.indexOf('>', lt + 1);
72
+ if (gt === -1) break;
73
+ const head = html.slice(lt + (closing ? 2 : 1), Math.min(gt, lt + 80));
74
+ const name = (/^[a-zA-Z][\w-]*/.exec(head) || [''])[0].toLowerCase();
75
+ const raw = html.slice(lt, Math.min(gt + 1, lt + MAX_TAG_ATTRIBUTES));
76
+ const selfClosing = html.charCodeAt(gt - 1) === 47;
77
+ tokens.push({ type: 'tag', name, closing, selfClosing, raw, start: lt, end: gt + 1 });
78
+ i = gt + 1;
79
+ if (!closing && !selfClosing && RAW_TEXT.has(name)) {
80
+ const finder = new RegExp(`</${name}[\\s/>]`, 'gi');
81
+ finder.lastIndex = i;
82
+ const found = finder.exec(html);
83
+ const stop = found ? found.index : n;
84
+ tokens.push({ type: 'raw', name, start: i, end: stop });
85
+ if (!found) break;
86
+ const gtClose = html.indexOf('>', stop);
87
+ tokens.push({ type: 'tag', name, closing: true, selfClosing: false, raw: '', start: stop, end: gtClose === -1 ? n : gtClose + 1 });
88
+ if (gtClose === -1) break;
89
+ i = gtClose + 1;
90
+ }
91
+ }
92
+ return tokens;
93
+ }
94
+
95
+ function attribute(tag, name) {
96
+ const match = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag);
97
+ return match ? decodeEntities(match[2] ?? match[3] ?? match[4] ?? '') : null;
98
+ }
99
+
100
+ const opens = (token) => token.type === 'tag' && !token.closing && !token.selfClosing && !VOID.has(token.name);
101
+
102
+ /** Les jetons sans les éléments que `drop(name, rawTag)` désigne, contenu compris. */
103
+ function dropTokens(tokens, drop) {
104
+ const out = [];
105
+ let skipping = null;
106
+ let depth = 0;
107
+ for (const token of tokens) {
108
+ if (skipping) {
109
+ if (token.type === 'tag' && token.name === skipping && !token.selfClosing && !VOID.has(token.name)) depth += token.closing ? -1 : 1;
110
+ if (depth === 0) skipping = null;
111
+ continue;
112
+ }
113
+ if (opens(token) && drop(token.name, token.raw)) {
114
+ skipping = token.name;
115
+ depth = 1;
116
+ continue;
117
+ }
118
+ out.push(token);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** Le contenu (en jetons) de chaque élément de premier niveau que `test` désigne. */
124
+ function elementsIn(tokens, test) {
125
+ const found = [];
126
+ let open = null;
127
+ let depth = 0;
128
+ let start = 0;
129
+ tokens.forEach((token, index) => {
130
+ if (token.type !== 'tag' || token.selfClosing || VOID.has(token.name)) return;
131
+ if (open) {
132
+ if (token.name === open) depth += token.closing ? -1 : 1;
133
+ if (depth === 0) {
134
+ found.push(tokens.slice(start, index));
135
+ open = null;
136
+ }
137
+ } else if (!token.closing && test(token.name, token.raw)) {
138
+ open = token.name;
139
+ depth = 1;
140
+ start = index + 1;
141
+ }
142
+ });
143
+ if (open) found.push(tokens.slice(start));
144
+ return found;
145
+ }
146
+
147
+ function isBoilerplate(name, tag) {
148
+ if (BOILERPLATE_TAGS.has(name)) return true;
149
+ if (name === 'header' && !/\bclass\s*=\s*["'][^"']*(entry|article|post)-?header/i.test(tag)) return true;
150
+ const role = attribute(tag, 'role');
151
+ if (role && /^(navigation|banner|contentinfo|complementary|search|dialog|alert)$/i.test(role)) return true;
152
+ if (/\s(hidden|aria-hidden\s*=\s*["']?true)/i.test(tag)) return true;
153
+ const hint = `${attribute(tag, 'class') || ''} ${attribute(tag, 'id') || ''}`;
154
+ return BOILERPLATE_HINT.test(hint);
155
+ }
156
+
157
+ /** Jetons → texte : blocs en lignes, entités décodées, espaces resserrés ligne par ligne. */
158
+ function textOf(html, tokens) {
159
+ let out = '';
160
+ for (const token of tokens) {
161
+ if (token.type === 'text') out += html.slice(token.start, token.end);
162
+ else if (token.type === 'tag') {
163
+ if (token.name === 'li' && !token.closing) out += '\n- ';
164
+ else if (BLOCK_TAGS.has(token.name)) out += '\n';
165
+ else if (token.closing && (token.name === 'td' || token.name === 'th')) out += ' ';
166
+ }
167
+ }
168
+ return decodeEntities(out)
169
+ // eslint-disable-next-line no-control-regex -- les caractères de contrôle sont justement ceux qu'on retire
170
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
171
+ .split('\n')
172
+ .map((line) => line.replace(/[ \t\u00a0\u2000-\u200b\u3000]+/g, ' ').trim())
173
+ .filter((line) => line !== '-')
174
+ .join('\n')
175
+ .replace(/\n{3,}/g, '\n\n')
176
+ .trim();
177
+ }
178
+
179
+ /** Le HTML sans les éléments que `drop(name, rawTag)` désigne (balises et contenu). */
180
+ function removeElements(html, drop) {
181
+ const source = String(html ?? '');
182
+ return dropTokens(tokenize(source), drop).map((token) => source.slice(token.start, token.end)).join('');
183
+ }
184
+
185
+ /** HTML → texte lisible (sans choisir de zone principale). */
186
+ function toText(html) {
187
+ const source = String(html ?? '');
188
+ return textOf(source, dropTokens(tokenize(source), (name) => DROP_ALWAYS.has(name)));
189
+ }
190
+
191
+ /**
192
+ * @param {string} html
193
+ * @param {{ url?: string, now?: number }} [options]
194
+ * @returns {{ title: string, text: string, lang: string|null, canonical: string|null, publishedAt: string|null,
195
+ * modifiedAt: string|null, description: string|null, siteName: string|null }}
196
+ */
197
+ function extractPage(html, { url, now } = {}) {
198
+ const source = String(html ?? '');
199
+ const tokens = tokenize(source);
200
+
201
+ const meta = new Map();
202
+ let canonical = null;
203
+ let lang = null;
204
+ let titleText = '';
205
+ let timeValue = null;
206
+ const ld = { published: null, modified: null, headline: null };
207
+ const visit = (node, depth) => {
208
+ if (!node || typeof node !== 'object' || depth > 6) return;
209
+ if (Array.isArray(node)) return node.forEach((child) => visit(child, depth + 1));
210
+ if (!ld.published && typeof node.datePublished === 'string') ld.published = node.datePublished;
211
+ if (!ld.modified && typeof node.dateModified === 'string') ld.modified = node.dateModified;
212
+ if (!ld.headline && typeof node.headline === 'string') ld.headline = node.headline;
213
+ if (node['@graph']) visit(node['@graph'], depth + 1);
214
+ };
215
+ tokens.forEach((token, index) => {
216
+ if (token.type === 'tag' && !token.closing) {
217
+ if (token.name === 'meta') {
218
+ const key = (attribute(token.raw, 'property') || attribute(token.raw, 'name') || attribute(token.raw, 'itemprop') || '').toLowerCase();
219
+ const content = attribute(token.raw, 'content');
220
+ if (key && content && !meta.has(key)) meta.set(key, content.trim());
221
+ } else if (token.name === 'link' && !canonical && /\brel\s*=\s*["']?canonical\b/i.test(token.raw)) {
222
+ const href = attribute(token.raw, 'href');
223
+ try {
224
+ canonical = href ? new URL(href, url).href : null;
225
+ } catch (_error) {
226
+ canonical = null;
227
+ }
228
+ } else if (token.name === 'html' && !lang) {
229
+ lang = attribute(token.raw, 'lang');
230
+ } else if (token.name === 'time' && !timeValue) {
231
+ timeValue = attribute(token.raw, 'datetime');
232
+ }
233
+ } else if (token.type === 'raw') {
234
+ const opening = tokens[index - 1];
235
+ const body = source.slice(token.start, token.end);
236
+ if (token.name === 'title' && !titleText) titleText = body;
237
+ if (token.name === 'script' && opening && /application\/ld\+json/i.test(opening.raw) && body.length < 500_000) {
238
+ try {
239
+ visit(JSON.parse(body.trim()), 0);
240
+ } catch (_error) {
241
+ /* un bloc illisible ne dit rien */
242
+ }
243
+ }
244
+ }
245
+ });
246
+
247
+ const title = plainText(meta.get('og:title') || ld.headline || titleText || '');
248
+ const published = meta.get('article:published_time') || ld.published || meta.get('datepublished') || meta.get('date')
249
+ || meta.get('dc.date') || meta.get('dc.date.issued') || meta.get('pubdate') || meta.get('publish-date') || timeValue;
250
+ const modified = meta.get('article:modified_time') || ld.modified || meta.get('datemodified') || null;
251
+
252
+ const cleaned = dropTokens(tokens, (name) => DROP_ALWAYS.has(name));
253
+ const [inBody] = elementsIn(cleaned, (name) => name === 'body');
254
+ const body = inBody || cleaned;
255
+ const regions = [
256
+ ...elementsIn(body, (name) => name === 'article'),
257
+ ...elementsIn(body, (name) => name === 'main'),
258
+ ...elementsIn(body, (_name, raw) => /^main$/i.test(attribute(raw, 'role') || ''))
259
+ ].map((part) => textOf(source, dropTokens(part, isBoilerplate)));
260
+ const whole = textOf(source, dropTokens(body, isBoilerplate));
261
+ const best = regions.sort((a, b) => b.length - a.length)[0] || '';
262
+ /* Une zone principale trop maigre (un <article> d'aperçu) ne vaut pas le corps entier. */
263
+ const text = best.length >= 200 || best.length >= whole.length * 0.5 ? best : whole;
264
+
265
+ return {
266
+ title,
267
+ text,
268
+ lang: lang ? String(lang).trim().slice(0, 35) : (meta.get('og:locale') || null),
269
+ canonical,
270
+ publishedAt: parseDate(published, { now }),
271
+ modifiedAt: parseDate(modified, { now }),
272
+ description: meta.get('og:description') || meta.get('description') || null,
273
+ siteName: meta.get('og:site_name') || null
274
+ };
275
+ }
276
+
277
+ module.exports = { extractPage, removeElements, toText };
package/src/format.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Ce que le modèle lit : les règles de citation HORS du cadre, les pages
3
+ * DANS le cadre des données non fiables (frameUntrusted de @astratra/ai/guards).
4
+ *
5
+ * Chaque source a son identifiant ([S1], [S2]…), son adresse exacte, son site
6
+ * et sa date ; son extrait et ses passages sont sous elle et sous elle seule.
7
+ * Un texte de page qui donnerait des ordres reste du texte entre deux marques
8
+ * qu'il ne peut pas refermer.
9
+ */
10
+
11
+ const { frameUntrusted } = require('@astratra/ai/guards');
12
+ const { clip } = require('./text');
13
+
14
+ const RULES = [
15
+ 'Each source below is ONE page of ONE site. Cite the id of the source of every fact, like [S1].',
16
+ 'Never attribute the words of one source to another, and never merge two sources into one claim without citing both.',
17
+ 'Passages marked "verbatim" are exact quotes of that page; a snippet is the search engine\'s excerpt of that page.',
18
+ 'If the sources do not answer the question, say so instead of guessing.'
19
+ ].join('\n');
20
+
21
+ /* En dessous, les règles et le cadre ne tiendraient pas. */
22
+ const MIN_CHARS = 1_000;
23
+
24
+ /**
25
+ * Un passage : « verbatim » seulement s'il est rendu tel quel (JSON garde les
26
+ * retours à la ligne) ; trop long, il est dit raccourci, sans le mot verbatim.
27
+ */
28
+ function quoted(passage, max, where) {
29
+ const place = `characters ${passage.start}-${passage.end}${where}`;
30
+ if (passage.text.length <= max) return `verbatim (${place}): ${JSON.stringify(passage.text)}`;
31
+ return `shortened excerpt (${place}, cut at ${max} characters, not verbatim): ${JSON.stringify(clip(passage.text, max))}`;
32
+ }
33
+
34
+ /* Une ligne d'en-tête ne garde ni retour à la ligne ni marque de cadre. */
35
+ const line = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();
36
+
37
+ /**
38
+ * @param {object} found le résultat de ws.search
39
+ * @param {{ maxChars?: number, snippetChars?: number, passageChars?: number }} [options]
40
+ * @returns {string}
41
+ */
42
+ function formatForModel(found, { maxChars: asked = 12_000, snippetChars = 400, passageChars = 600 } = {}) {
43
+ const maxChars = Math.max(MIN_CHARS, asked);
44
+ const results = Array.isArray(found?.results) ? found.results : [];
45
+ const header = `Web search for "${clip(line(found?.query), 200)}" (${line(found?.searchedAt || '').slice(0, 10)}): ${results.length} source${results.length === 1 ? '' : 's'}.`;
46
+ if (!results.length) return `${header}\nNo page was found. Say that the web search found nothing; do not invent sources.`;
47
+ const room = maxChars - header.length - RULES.length - frameUntrusted('', { source: 'web_search' }).length - 2;
48
+ const blocks = [];
49
+ let used = 0;
50
+ for (const result of results) {
51
+ const lines = [`[${result.id}] ${line(result.title)}`, `url: ${result.url}`, `site: ${result.domain}`];
52
+ if (result.publishedAt) lines.push(`published: ${result.publishedAt.slice(0, 10)}${result.dateSource === 'page' ? ' (from the page)' : ''}`);
53
+ else lines.push('published: unknown');
54
+ if (result.snippet) lines.push(`snippet: ${clip(line(result.snippet), snippetChars)}`);
55
+ for (const extra of (result.extraSnippets || []).slice(0, 2)) lines.push(`snippet: ${clip(line(extra), snippetChars)}`);
56
+ if (result.page?.status === 'read') {
57
+ for (const passage of result.page.passages || []) {
58
+ lines.push(quoted(passage, passageChars, ' of the page'));
59
+ }
60
+ } else if (result.page?.status === 'other_site') {
61
+ lines.push('page: redirected to another site, not read');
62
+ } else if (result.page?.status === 'failed') {
63
+ lines.push('page: could not be read');
64
+ }
65
+ const separator = blocks.length ? 2 : 0;
66
+ let block = lines.join('\n');
67
+ if (used + separator + block.length > room) {
68
+ if (blocks.length) break;
69
+ block = clip(block, Math.max(0, room));
70
+ }
71
+ blocks.push(block);
72
+ used += separator + block.length;
73
+ }
74
+ return `${header}\n${RULES}\n${frameUntrusted(blocks.join('\n\n'), { source: 'web_search' })}`;
75
+ }
76
+
77
+ /**
78
+ * Une page lue (ws.read), pour le modèle.
79
+ * @param {object} page
80
+ * @param {{ maxChars?: number }} [options]
81
+ */
82
+ function formatPageForModel(page, { maxChars: asked = 8_000 } = {}) {
83
+ const maxChars = Math.max(MIN_CHARS, asked);
84
+ const lines = [`url: ${page.finalUrl}`, `site: ${page.domain}`, `title: ${line(page.title)}`, `published: ${page.publishedAt ? page.publishedAt.slice(0, 10) : 'unknown'}`];
85
+ if (!page.sameSite) lines.push(`note: the address redirected to another site (${page.domain}); this text belongs to that site.`);
86
+ for (const quote of page.quotes || []) {
87
+ lines.push(quote.found
88
+ ? `quote found (characters ${quote.start}-${quote.end}): ${JSON.stringify(quote.text)}`
89
+ : `quote NOT found on this page: "${line(quote.quote)}"`);
90
+ }
91
+ for (const passage of page.passages || []) {
92
+ lines.push(quoted(passage, 1_000, ''));
93
+ }
94
+ const rules = 'This is the text of ONE page. Cite it by its url. A quote marked NOT found must not be presented as said by this page.';
95
+ let head = lines.join('\n');
96
+ const overhead = rules.length + 1 + frameUntrusted('', { source: 'web_page' }).length + '\n\ntext:\n'.length;
97
+ if (overhead + head.length > maxChars) head = clip(head, Math.max(0, maxChars - overhead));
98
+ const body = `${head}\n\ntext:\n${clip(page.text, Math.max(0, maxChars - overhead - head.length))}`;
99
+ return `${rules}\n${frameUntrusted(body, { source: 'web_page' })}`;
100
+ }
101
+
102
+ module.exports = { formatForModel, formatPageForModel, CITATION_RULES: RULES };