@cobola/dsh-geo 0.0.0-stage → 0.3.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/.github/workflows/publish.yml +65 -0
- package/CHANGELOG.md +27 -0
- package/CONTRIBUTING.md +86 -0
- package/LICENSE +176 -0
- package/NOTICE +14 -0
- package/README.md +228 -2
- package/SECURITY.md +46 -0
- package/bin/dsh-geo.js +381 -0
- package/client.js +707 -0
- package/cordis.patch.yml +4 -0
- package/docs/.nojekyll +0 -0
- package/docs/CI.md +118 -0
- package/docs/GOOGLE.md +57 -0
- package/docs/NPM-TRUSTED-PUBLISHING.md +69 -0
- package/docs/PROFILES.md +51 -0
- package/docs/RULES.md +108 -0
- package/docs/icons/geo.svg +8 -0
- package/docs/index.json +41 -0
- package/icon.svg +8 -0
- package/index.js +381 -0
- package/lib/audit.js +62 -0
- package/lib/fetch.js +650 -0
- package/lib/html.js +651 -0
- package/lib/platforms/bing.js +95 -0
- package/lib/platforms/index.js +70 -0
- package/lib/profiles.js +62 -0
- package/lib/report.js +404 -0
- package/lib/robots.js +209 -0
- package/lib/rules.js +939 -0
- package/lib/scan.js +604 -0
- package/lib/score.js +145 -0
- package/lib/store.js +283 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/html.js
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tolerant, dependency-free HTML extraction for GEO audits.
|
|
3
|
+
*
|
|
4
|
+
* The audit never *renders* a page: it looks at exactly what a crawler that
|
|
5
|
+
* does not run JavaScript receives. A full HTML5 tree builder is unnecessary
|
|
6
|
+
* for that job, but the extractor still needs to be predictable, so this
|
|
7
|
+
* module implements a small tokenizer (with raw-text elements, void elements,
|
|
8
|
+
* and implicit paragraph/list closure) and derives a flat fact sheet from it.
|
|
9
|
+
*
|
|
10
|
+
* Everything here is pure: same input -> same output, no clock, no network.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const VOID_ELEMENTS = new Set([
|
|
14
|
+
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta',
|
|
15
|
+
'param', 'source', 'track', 'wbr',
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const RAW_TEXT_ELEMENTS = new Set(['script', 'style', 'title', 'textarea']);
|
|
19
|
+
|
|
20
|
+
/** Elements that start a new visual line; used to avoid gluing words together. */
|
|
21
|
+
const BLOCK_ELEMENTS = new Set([
|
|
22
|
+
'address', 'article', 'aside', 'blockquote', 'br', 'dd', 'div', 'dl', 'dt',
|
|
23
|
+
'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4',
|
|
24
|
+
'h5', 'h6', 'header', 'hr', 'li', 'main', 'nav', 'ol', 'p', 'pre', 'section',
|
|
25
|
+
'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul',
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/** Block-level start tags that close an open <p>, per the HTML parser rules. */
|
|
29
|
+
const CLOSES_PARAGRAPH = new Set([
|
|
30
|
+
'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
|
|
31
|
+
'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
|
|
32
|
+
'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table',
|
|
33
|
+
'ul',
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
const IMPLICIT_CLOSE = {
|
|
37
|
+
li: new Set(['li']),
|
|
38
|
+
dt: new Set(['dt', 'dd']),
|
|
39
|
+
dd: new Set(['dt', 'dd']),
|
|
40
|
+
option: new Set(['option']),
|
|
41
|
+
tr: new Set(['tr']),
|
|
42
|
+
th: new Set(['th', 'td']),
|
|
43
|
+
td: new Set(['th', 'td', 'tr']),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const HEADING_LEVEL = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 };
|
|
47
|
+
|
|
48
|
+
const SKIP_FOR_TEXT = new Set(['script', 'style', 'template']);
|
|
49
|
+
|
|
50
|
+
const MAX_ELEMENT_DEPTH = 256;
|
|
51
|
+
const OPEN_TAG = /<([a-zA-Z][\w:-]*)/y;
|
|
52
|
+
const CLOSE_TAG = /<\/([a-zA-Z][\w:-]*)\s*>/y;
|
|
53
|
+
const ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
54
|
+
const NAMED_ENTITIES = {
|
|
55
|
+
amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
|
|
56
|
+
copy: '\u00a9', reg: '\u00ae', hellip: '\u2026', mdash: '\u2014',
|
|
57
|
+
ndash: '\u2013', laquo: '\u00ab', raquo: '\u00bb', middot: '\u00b7',
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const QUESTION_START = /^(?:how|what|why|when|where|who|which|can|should|do|does|is|are|will)\b|^(?:如何|为何|为什么|怎么|怎样|什么|哪些|哪个|是否|能否)/i;
|
|
61
|
+
const AUTHORITY_HOSTS = [
|
|
62
|
+
'w3.org', 'whatwg.org', 'schema.org', 'wikipedia.org', 'mozilla.org',
|
|
63
|
+
'developer.mozilla.org', 'developers.google.com', 'web.dev', 'nist.gov',
|
|
64
|
+
'ietf.org', 'rfc-editor.org', 'arxiv.org', 'nature.com', 'science.org',
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
function decodeEntities(value) {
|
|
68
|
+
if (!value || value.indexOf('&') === -1) return value ?? '';
|
|
69
|
+
return value.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, body) => {
|
|
70
|
+
if (body[0] === '#') {
|
|
71
|
+
const code = body[1] === 'x' || body[1] === 'X'
|
|
72
|
+
? Number.parseInt(body.slice(2), 16)
|
|
73
|
+
: Number.parseInt(body.slice(1), 10);
|
|
74
|
+
if (!Number.isFinite(code) || code <= 0 || code > 0x10ffff) return match;
|
|
75
|
+
try {
|
|
76
|
+
return String.fromCodePoint(code);
|
|
77
|
+
} catch {
|
|
78
|
+
return match;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const named = NAMED_ENTITIES[body.toLowerCase()];
|
|
82
|
+
return named === undefined ? match : named;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function collapseWhitespace(value) {
|
|
87
|
+
return String(value ?? '').replace(/[\s\u00a0\u3000]+/g, ' ').trim();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function parseAttributes(source) {
|
|
91
|
+
const attrs = {};
|
|
92
|
+
ATTRIBUTE.lastIndex = 0;
|
|
93
|
+
let match = ATTRIBUTE.exec(source);
|
|
94
|
+
while (match) {
|
|
95
|
+
const name = match[1].toLowerCase();
|
|
96
|
+
const value = match[2] ?? match[3] ?? match[4] ?? '';
|
|
97
|
+
if (!(name in attrs)) attrs[name] = decodeEntities(value).trim();
|
|
98
|
+
match = ATTRIBUTE.exec(source);
|
|
99
|
+
}
|
|
100
|
+
return attrs;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function createNode(tag, attrs, text) {
|
|
104
|
+
return {
|
|
105
|
+
tag,
|
|
106
|
+
attrs: attrs ?? {},
|
|
107
|
+
text: text,
|
|
108
|
+
children: [],
|
|
109
|
+
parent: null,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Parse an HTML string into a tolerant tree.
|
|
115
|
+
* @param {string} source
|
|
116
|
+
* @returns {{tag: string, attrs: object, children: object[], parent: null}}
|
|
117
|
+
*/
|
|
118
|
+
export function parseHtml(source) {
|
|
119
|
+
const html = String(source ?? '');
|
|
120
|
+
const root = createNode('#document', {});
|
|
121
|
+
const stack = [root];
|
|
122
|
+
let index = 0;
|
|
123
|
+
|
|
124
|
+
const current = () => stack[stack.length - 1];
|
|
125
|
+
|
|
126
|
+
const append = (node) => {
|
|
127
|
+
node.parent = current();
|
|
128
|
+
current().children.push(node);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const appendText = (text) => {
|
|
132
|
+
if (!text) return;
|
|
133
|
+
append(createNode('#text', {}, text));
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const popOpenParagraph = () => {
|
|
137
|
+
if (current().tag === 'p') stack.pop();
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const closeForStartTag = (tag) => {
|
|
141
|
+
if (tag === 'p' || CLOSES_PARAGRAPH.has(tag)) popOpenParagraph();
|
|
142
|
+
const closes = IMPLICIT_CLOSE[tag];
|
|
143
|
+
if (closes && closes.has(current().tag)) stack.pop();
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
while (index < html.length) {
|
|
147
|
+
const nextLt = html.indexOf('<', index);
|
|
148
|
+
if (nextLt === -1) {
|
|
149
|
+
appendText(html.slice(index));
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
if (nextLt > index) appendText(html.slice(index, nextLt));
|
|
153
|
+
index = nextLt;
|
|
154
|
+
|
|
155
|
+
if (html.startsWith('<!--', index)) {
|
|
156
|
+
const end = html.indexOf('-->', index + 4);
|
|
157
|
+
index = end === -1 ? html.length : end + 3;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (html.startsWith('<!', index) || html.startsWith('<?', index)) {
|
|
161
|
+
const end = html.indexOf('>', index);
|
|
162
|
+
index = end === -1 ? html.length : end + 1;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
CLOSE_TAG.lastIndex = index;
|
|
167
|
+
const closeMatch = CLOSE_TAG.exec(html);
|
|
168
|
+
if (closeMatch) {
|
|
169
|
+
const tag = closeMatch[1].toLowerCase();
|
|
170
|
+
for (let depth = stack.length - 1; depth > 0; depth -= 1) {
|
|
171
|
+
if (stack[depth].tag === tag) {
|
|
172
|
+
stack.length = depth;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
index += closeMatch[0].length;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
OPEN_TAG.lastIndex = index;
|
|
181
|
+
const openMatch = OPEN_TAG.exec(html);
|
|
182
|
+
if (!openMatch) {
|
|
183
|
+
appendText('<');
|
|
184
|
+
index += 1;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const tag = openMatch[1].toLowerCase();
|
|
189
|
+
let cursor = OPEN_TAG.lastIndex;
|
|
190
|
+
let quote = null;
|
|
191
|
+
while (cursor < html.length) {
|
|
192
|
+
const char = html[cursor];
|
|
193
|
+
if (quote) {
|
|
194
|
+
if (char === quote) quote = null;
|
|
195
|
+
} else if (char === '"' || char === "'") {
|
|
196
|
+
quote = char;
|
|
197
|
+
} else if (char === '>') {
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
cursor += 1;
|
|
201
|
+
}
|
|
202
|
+
if (cursor >= html.length) {
|
|
203
|
+
// Unterminated tag: treat the remainder as text.
|
|
204
|
+
appendText(html.slice(index));
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const inner = html.slice(OPEN_TAG.lastIndex, cursor);
|
|
209
|
+
const attrs = parseAttributes(inner);
|
|
210
|
+
const selfClosing = /\/\s*$/.test(inner);
|
|
211
|
+
index = cursor + 1;
|
|
212
|
+
|
|
213
|
+
closeForStartTag(tag);
|
|
214
|
+
const node = createNode(tag, attrs);
|
|
215
|
+
append(node);
|
|
216
|
+
|
|
217
|
+
if (RAW_TEXT_ELEMENTS.has(tag) && !selfClosing) {
|
|
218
|
+
// Case-insensitive search without copying the document per raw element:
|
|
219
|
+
// a page full of <style> tags must stay linear, not quadratic.
|
|
220
|
+
const closing = new RegExp(`</${tag}(?=[\\s/>])`, 'ig');
|
|
221
|
+
closing.lastIndex = index;
|
|
222
|
+
const match = closing.exec(html);
|
|
223
|
+
const closeAt = match ? match.index : -1;
|
|
224
|
+
const rawEnd = closeAt === -1 ? html.length : closeAt;
|
|
225
|
+
if (rawEnd > index) node.children.push(createNode('#text', {}, html.slice(index, rawEnd)));
|
|
226
|
+
if (closeAt === -1) {
|
|
227
|
+
index = html.length;
|
|
228
|
+
} else {
|
|
229
|
+
const after = html.indexOf('>', closeAt);
|
|
230
|
+
index = after === -1 ? html.length : after + 1;
|
|
231
|
+
}
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (!VOID_ELEMENTS.has(tag) && !selfClosing && stack.length - 1 < MAX_ELEMENT_DEPTH) {
|
|
236
|
+
stack.push(node);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return root;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function walk(node, visit) {
|
|
244
|
+
visit(node);
|
|
245
|
+
for (const child of node.children) walk(child, visit);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function findFirst(node, predicate) {
|
|
249
|
+
if (predicate(node)) return node;
|
|
250
|
+
for (const child of node.children) {
|
|
251
|
+
const found = findFirst(child, predicate);
|
|
252
|
+
if (found) return found;
|
|
253
|
+
}
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function collectText(node, out) {
|
|
258
|
+
if (node.tag === '#text') {
|
|
259
|
+
out.push(node.text);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (SKIP_FOR_TEXT.has(node.tag)) return;
|
|
263
|
+
const block = BLOCK_ELEMENTS.has(node.tag);
|
|
264
|
+
if (block) out.push(' ');
|
|
265
|
+
for (const child of node.children) collectText(child, out);
|
|
266
|
+
if (block) out.push(' ');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function textOf(node) {
|
|
270
|
+
if (!node) return '';
|
|
271
|
+
const out = [];
|
|
272
|
+
collectText(node, out);
|
|
273
|
+
return collapseWhitespace(decodeEntities(out.join('')));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function attribute(node, name) {
|
|
277
|
+
return node.attrs?.[name] ?? null;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function hasAncestor(node, tag) {
|
|
281
|
+
let cursor = node.parent;
|
|
282
|
+
while (cursor) {
|
|
283
|
+
if (cursor.tag === tag) return true;
|
|
284
|
+
cursor = cursor.parent;
|
|
285
|
+
}
|
|
286
|
+
return false;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function tokens(value) {
|
|
290
|
+
return (value ?? '').toLowerCase().split(/\s+/).filter(Boolean);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function resolveUrl(href, base) {
|
|
294
|
+
try {
|
|
295
|
+
const url = new URL(href, base);
|
|
296
|
+
url.hash = '';
|
|
297
|
+
return url.href;
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function isWebUrl(value) {
|
|
304
|
+
return typeof value === 'string' && /^https?:\/\//i.test(value);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function flattenJsonLd(value, out = []) {
|
|
308
|
+
if (!value || typeof value !== 'object') return out;
|
|
309
|
+
if (Array.isArray(value)) {
|
|
310
|
+
for (const entry of value) flattenJsonLd(entry, out);
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
out.push(value);
|
|
314
|
+
if (Array.isArray(value['@graph'])) flattenJsonLd(value['@graph'], out);
|
|
315
|
+
for (const key of ['mainEntity', 'itemListElement', 'hasPart']) {
|
|
316
|
+
if (value[key]) flattenJsonLd(value[key], out);
|
|
317
|
+
}
|
|
318
|
+
return out;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function jsonLdTypes(value) {
|
|
322
|
+
const type = value?.['@type'];
|
|
323
|
+
if (typeof type === 'string') return [type];
|
|
324
|
+
if (Array.isArray(type)) return type.filter((entry) => typeof entry === 'string');
|
|
325
|
+
return [];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function collectJsonLd(nodes) {
|
|
329
|
+
const blocks = [];
|
|
330
|
+
for (const node of nodes) {
|
|
331
|
+
if (node.tag !== 'script') continue;
|
|
332
|
+
const type = (attribute(node, 'type') ?? '').toLowerCase();
|
|
333
|
+
if (!type.includes('ld+json')) continue;
|
|
334
|
+
const raw = node.children.map((child) => child.text ?? '').join('');
|
|
335
|
+
const block = { ok: false, raw: raw.trim(), types: [], entities: [], error: null };
|
|
336
|
+
try {
|
|
337
|
+
const parsed = JSON.parse(raw);
|
|
338
|
+
const entities = flattenJsonLd(parsed);
|
|
339
|
+
block.ok = true;
|
|
340
|
+
block.entities = entities;
|
|
341
|
+
block.types = [...new Set(entities.flatMap(jsonLdTypes))];
|
|
342
|
+
const context = Array.isArray(parsed) ? parsed[0]?.['@context'] : parsed?.['@context'];
|
|
343
|
+
block.context = typeof context === 'string' ? context : null;
|
|
344
|
+
} catch (error) {
|
|
345
|
+
block.error = collapseWhitespace(error?.message ?? String(error)).slice(0, 160);
|
|
346
|
+
}
|
|
347
|
+
blocks.push(block);
|
|
348
|
+
}
|
|
349
|
+
return blocks;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function countWords(text) {
|
|
353
|
+
const cjk = (String(text).match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]/g) ?? []).length;
|
|
354
|
+
const latin = String(text).replace(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af]/g, ' ').split(/\s+/).filter(Boolean).length;
|
|
355
|
+
return cjk + latin;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function countNumericFacts(text) {
|
|
359
|
+
const pattern = /(?<![\w.])\d+(?:[.,]\d+)?\s?(?:%|%|percent|倍|万|亿|千|个|次|分钟|秒|小时|天|周|个月|年|ms|毫秒|s|sec|seconds|min|minutes|hours|days|weeks|months|years|users|customers|stars?|points?|x)(?![\w])/gi;
|
|
360
|
+
return (text.match(pattern) ?? []).length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Extract the fact sheet the scoring rubric runs on.
|
|
365
|
+
*
|
|
366
|
+
* @param {string} html Raw response body.
|
|
367
|
+
* @param {string} pageUrl Absolute URL the body was served from.
|
|
368
|
+
* @returns {object} Flat, JSON-serialisable facts.
|
|
369
|
+
*/
|
|
370
|
+
export function analyzeHtml(html, pageUrl) {
|
|
371
|
+
const doc = parseHtml(html);
|
|
372
|
+
const nodes = [];
|
|
373
|
+
walk(doc, (node) => {
|
|
374
|
+
if (node.tag !== '#text' && node.tag !== '#document') nodes.push(node);
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
const head = findFirst(doc, (node) => node.tag === 'head');
|
|
378
|
+
const body = findFirst(doc, (node) => node.tag === 'body');
|
|
379
|
+
const page = new URL(pageUrl);
|
|
380
|
+
const origin = page.origin;
|
|
381
|
+
|
|
382
|
+
// <base href> changes how every relative URL on the page resolves.
|
|
383
|
+
const baseNode = nodes.find((node) => node.tag === 'base' && attribute(node, 'href'));
|
|
384
|
+
let baseUrl = pageUrl;
|
|
385
|
+
if (baseNode) {
|
|
386
|
+
try {
|
|
387
|
+
baseUrl = new URL(attribute(baseNode, 'href'), pageUrl).href;
|
|
388
|
+
} catch {
|
|
389
|
+
baseUrl = pageUrl;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const metas = nodes.filter((node) => node.tag === 'meta');
|
|
394
|
+
const meta = {};
|
|
395
|
+
for (const node of metas) {
|
|
396
|
+
const key = (attribute(node, 'name') ?? attribute(node, 'property') ?? attribute(node, 'http-equiv') ?? '').toLowerCase();
|
|
397
|
+
const content = attribute(node, 'content');
|
|
398
|
+
if (key && content !== null && !(key in meta)) meta[key] = collapseWhitespace(content);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const links = [];
|
|
402
|
+
for (const node of nodes) {
|
|
403
|
+
if (node.tag !== 'a') continue;
|
|
404
|
+
const href = attribute(node, 'href');
|
|
405
|
+
if (!href) continue;
|
|
406
|
+
const resolved = resolveUrl(href, baseUrl);
|
|
407
|
+
const anchorText = textOf(node);
|
|
408
|
+
links.push({
|
|
409
|
+
href: (resolved ?? href).slice(0, 2048),
|
|
410
|
+
text: anchorText.slice(0, 200),
|
|
411
|
+
rel: tokens(attribute(node, 'rel')),
|
|
412
|
+
internal: resolved ? new URL(resolved).origin === origin : false,
|
|
413
|
+
external: resolved ? new URL(resolved).origin !== origin : false,
|
|
414
|
+
hashOnly: href.startsWith('#'),
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const images = [];
|
|
419
|
+
for (const node of nodes) {
|
|
420
|
+
if (node.tag !== 'img') continue;
|
|
421
|
+
const src = attribute(node, 'src');
|
|
422
|
+
if (!src && !attribute(node, 'srcset')) continue;
|
|
423
|
+
const alt = attribute(node, 'alt');
|
|
424
|
+
images.push({
|
|
425
|
+
src: (resolveUrl(src ?? '', baseUrl) ?? src ?? '').slice(0, 2048),
|
|
426
|
+
alt,
|
|
427
|
+
hasAlt: typeof alt === 'string',
|
|
428
|
+
decorative: attribute(node, 'role') === 'presentation' || alt === '',
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const headings = [];
|
|
433
|
+
let lastHeading = null;
|
|
434
|
+
const paragraphs = [];
|
|
435
|
+
const snippetCandidates = [];
|
|
436
|
+
const headingIds = [];
|
|
437
|
+
let pendingHeading = null;
|
|
438
|
+
for (const node of nodes) {
|
|
439
|
+
const level = HEADING_LEVEL[node.tag];
|
|
440
|
+
if (level) {
|
|
441
|
+
// Fallback copy inside <noscript> is not page structure.
|
|
442
|
+
if (hasAncestor(node, 'noscript')) continue;
|
|
443
|
+
const headingText = textOf(node);
|
|
444
|
+
const id = attribute(node, 'id');
|
|
445
|
+
headings.push({ level, text: headingText.slice(0, 300), id });
|
|
446
|
+
if (id) headingIds.push(id);
|
|
447
|
+
lastHeading = level;
|
|
448
|
+
pendingHeading = headingText;
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (node.tag === 'p') {
|
|
452
|
+
if (hasAncestor(node, 'noscript')) continue;
|
|
453
|
+
const text = textOf(node);
|
|
454
|
+
if (!text) continue;
|
|
455
|
+
const words = countWords(text);
|
|
456
|
+
paragraphs.push({ text: text.slice(0, 1000), words, afterHeading: lastHeading });
|
|
457
|
+
if (pendingHeading !== null && words >= 30 && words <= 140) {
|
|
458
|
+
snippetCandidates.push({ heading: pendingHeading.slice(0, 200), words });
|
|
459
|
+
}
|
|
460
|
+
pendingHeading = null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const bodyText = textOf(body ?? doc);
|
|
465
|
+
const contentRoot = findFirst(doc, (node) => node.tag === 'article')
|
|
466
|
+
?? findFirst(doc, (node) => node.tag === 'main')
|
|
467
|
+
?? body
|
|
468
|
+
?? doc;
|
|
469
|
+
const contentText = textOf(contentRoot);
|
|
470
|
+
const noscriptText = nodes
|
|
471
|
+
.filter((node) => node.tag === 'noscript')
|
|
472
|
+
.map((node) => textOf(node))
|
|
473
|
+
.join(' ')
|
|
474
|
+
.trim();
|
|
475
|
+
|
|
476
|
+
const jsonLd = collectJsonLd(nodes);
|
|
477
|
+
const jsonLdEntities = jsonLd.flatMap((block) => block.entities);
|
|
478
|
+
|
|
479
|
+
const htmlLang = collapseWhitespace(attribute(findFirst(doc, (node) => node.tag === 'html') ?? {}, 'lang') ?? '');
|
|
480
|
+
const titleNode = findFirst(doc, (node) => node.tag === 'title');
|
|
481
|
+
const title = textOf(titleNode);
|
|
482
|
+
|
|
483
|
+
const canonicalNode = nodes.find((node) => node.tag === 'link' && tokens(attribute(node, 'rel')).includes('canonical'));
|
|
484
|
+
const canonicalRaw = canonicalNode ? attribute(canonicalNode, 'href') : null;
|
|
485
|
+
const canonical = canonicalRaw ? resolveUrl(canonicalRaw, baseUrl) : null;
|
|
486
|
+
|
|
487
|
+
const alternateLinks = [];
|
|
488
|
+
const relMe = [];
|
|
489
|
+
for (const node of nodes) {
|
|
490
|
+
if (node.tag !== 'link') continue;
|
|
491
|
+
const rel = tokens(attribute(node, 'rel'));
|
|
492
|
+
const href = attribute(node, 'href');
|
|
493
|
+
if (href && (rel.includes('alternate') || rel.includes('me') || rel.includes('sitemap'))) {
|
|
494
|
+
alternateLinks.push({
|
|
495
|
+
rel,
|
|
496
|
+
type: (attribute(node, 'type') ?? '').toLowerCase(),
|
|
497
|
+
href: (resolveUrl(href, baseUrl) ?? href).slice(0, 2048),
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
if (rel.includes('me') && href) relMe.push((resolveUrl(href, baseUrl) ?? href).slice(0, 2048));
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const times = [];
|
|
504
|
+
for (const node of nodes) {
|
|
505
|
+
if (node.tag !== 'time') continue;
|
|
506
|
+
const datetime = attribute(node, 'datetime');
|
|
507
|
+
if (datetime) times.push({ datetime, text: textOf(node).slice(0, 80) });
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const bylineNodes = nodes.filter((node) => {
|
|
511
|
+
const marker = `${attribute(node, 'class') ?? ''} ${attribute(node, 'id') ?? ''} ${attribute(node, 'rel') ?? ''}`.toLowerCase();
|
|
512
|
+
return /author|byline|writer|作者/.test(marker);
|
|
513
|
+
});
|
|
514
|
+
const bylines = bylineNodes.map((node) => textOf(node)).filter((text) => text.length > 0 && text.length <= 160);
|
|
515
|
+
|
|
516
|
+
const orgEntities = jsonLdEntities.filter((entity) => {
|
|
517
|
+
const types = jsonLdTypes(entity).map((type) => type.toLowerCase());
|
|
518
|
+
return types.some((type) => ['organization', 'corporation', 'localbusiness', 'ngo', 'person', 'onlinebusiness'].includes(type));
|
|
519
|
+
});
|
|
520
|
+
const articleEntities = jsonLdEntities.filter((entity) => {
|
|
521
|
+
const types = jsonLdTypes(entity).map((type) => type.toLowerCase());
|
|
522
|
+
return types.some((type) => ['article', 'newsarticle', 'blogposting', 'techarticle', 'scholarlyarticle', 'report'].includes(type));
|
|
523
|
+
});
|
|
524
|
+
const faqEntities = jsonLdEntities.filter((entity) => {
|
|
525
|
+
const types = jsonLdTypes(entity).map((type) => type.toLowerCase());
|
|
526
|
+
return types.some((type) => ['faqpage', 'qapage', 'howto'].includes(type));
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
const sameAs = [];
|
|
530
|
+
const dateValues = [];
|
|
531
|
+
const authorNames = [];
|
|
532
|
+
for (const entity of jsonLdEntities) {
|
|
533
|
+
if (Array.isArray(entity.sameAs)) {
|
|
534
|
+
for (const value of entity.sameAs) if (typeof value === 'string') sameAs.push(value);
|
|
535
|
+
}
|
|
536
|
+
for (const key of ['datePublished', 'dateModified', 'dateCreated']) {
|
|
537
|
+
if (typeof entity[key] === 'string') dateValues.push({ key, value: entity[key] });
|
|
538
|
+
}
|
|
539
|
+
const author = entity.author;
|
|
540
|
+
const authorList = Array.isArray(author) ? author : author ? [author] : [];
|
|
541
|
+
for (const person of authorList) {
|
|
542
|
+
if (typeof person === 'string') authorNames.push(person);
|
|
543
|
+
else if (person && typeof person.name === 'string') authorNames.push(person.name);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
for (const key of ['article:published_time', 'article:modified_time', 'date', 'pubdate']) {
|
|
547
|
+
if (meta[key]) dateValues.push({ key, value: meta[key] });
|
|
548
|
+
}
|
|
549
|
+
for (const time of times) dateValues.push({ key: 'time', value: time.datetime });
|
|
550
|
+
|
|
551
|
+
const outboundAuthoritative = links.filter((link) => {
|
|
552
|
+
if (!link.external || !isWebUrl(link.href)) return false;
|
|
553
|
+
const host = new URL(link.href).hostname.toLowerCase();
|
|
554
|
+
return AUTHORITY_HOSTS.some((authority) => host === authority || host.endsWith(`.${authority}`)) || host.endsWith('.gov') || host.endsWith('.edu');
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
const questionHeadings = headings.filter((heading) => QUESTION_START.test(heading.text) || /[??]$/.test(heading.text));
|
|
558
|
+
|
|
559
|
+
const scriptTexts = nodes.filter((node) => node.tag === 'script').map((node) => node.children.map((child) => child.text ?? '').join(''));
|
|
560
|
+
const scriptBytes = scriptTexts.reduce((sum, text) => sum + text.length, 0);
|
|
561
|
+
const externalScripts = nodes.filter((node) => node.tag === 'script' && attribute(node, 'src'));
|
|
562
|
+
|
|
563
|
+
const counts = {
|
|
564
|
+
tables: nodes.filter((node) => node.tag === 'table').length,
|
|
565
|
+
lists: nodes.filter((node) => node.tag === 'ul' || node.tag === 'ol').length,
|
|
566
|
+
blockquotes: nodes.filter((node) => node.tag === 'blockquote').length,
|
|
567
|
+
definitionLists: nodes.filter((node) => node.tag === 'dl').length,
|
|
568
|
+
figures: nodes.filter((node) => node.tag === 'figure').length,
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
const hasFaqCopy = /(常见问题|frequently asked questions|FAQ)/i.test(bodyText);
|
|
572
|
+
const hasTldr = /(tl;?dr|key takeaways|快速摘要|要点速览|摘要)/i.test(bodyText);
|
|
573
|
+
const hasSummaryBlock = nodes.some((node) => {
|
|
574
|
+
if (node.tag === '#text') return false;
|
|
575
|
+
const marker = `${attribute(node, 'class') ?? ''} ${attribute(node, 'id') ?? ''}`;
|
|
576
|
+
return /(?:summary|tldr|takeaway|abstract|lede|摘要|要点|概览)/i.test(marker) && textOf(node).length >= 80;
|
|
577
|
+
});
|
|
578
|
+
const contactLinks = links.filter((link) => /^(?:mailto:|tel:)/i.test(link.href));
|
|
579
|
+
|
|
580
|
+
const hasSection = (tag) => nodes.some((node) => node.tag === tag);
|
|
581
|
+
|
|
582
|
+
return {
|
|
583
|
+
url: pageUrl,
|
|
584
|
+
origin,
|
|
585
|
+
path: page.pathname,
|
|
586
|
+
title,
|
|
587
|
+
titleLength: [...title].length,
|
|
588
|
+
meta,
|
|
589
|
+
description: meta.description ?? '',
|
|
590
|
+
lang: htmlLang,
|
|
591
|
+
canonical,
|
|
592
|
+
canonicalRaw,
|
|
593
|
+
robotsMeta: (meta.robots ?? '').toLowerCase(),
|
|
594
|
+
metaViewport: meta.viewport ?? null,
|
|
595
|
+
charset: (nodes.find((node) => node.tag === 'meta' && attribute(node, 'charset'))?.attrs.charset ?? null),
|
|
596
|
+
headings,
|
|
597
|
+
headingIds,
|
|
598
|
+
h1Count: headings.filter((heading) => heading.level === 1).length,
|
|
599
|
+
paragraphs,
|
|
600
|
+
snippetCandidates,
|
|
601
|
+
links,
|
|
602
|
+
internalLinks: links.filter((link) => link.internal && !link.hashOnly),
|
|
603
|
+
externalLinks: links.filter((link) => link.external),
|
|
604
|
+
outboundAuthoritative,
|
|
605
|
+
images,
|
|
606
|
+
text: bodyText,
|
|
607
|
+
contentText,
|
|
608
|
+
textLength: bodyText.length,
|
|
609
|
+
contentLength: contentText.length,
|
|
610
|
+
noscriptText,
|
|
611
|
+
hasMain: hasSection('main'),
|
|
612
|
+
hasArticle: hasSection('article'),
|
|
613
|
+
hasNav: hasSection('nav'),
|
|
614
|
+
hasFooter: hasSection('footer'),
|
|
615
|
+
counts,
|
|
616
|
+
hasFaqCopy,
|
|
617
|
+
hasTldr,
|
|
618
|
+
hasSummaryBlock,
|
|
619
|
+
contactLinks,
|
|
620
|
+
jsonLd,
|
|
621
|
+
jsonLdTypes: [...new Set(jsonLd.flatMap((block) => block.types))].sort(),
|
|
622
|
+
jsonLdValid: jsonLd.length > 0 && jsonLd.every((block) => block.ok),
|
|
623
|
+
orgEntities,
|
|
624
|
+
articleEntities,
|
|
625
|
+
faqEntities,
|
|
626
|
+
sameAs: [...new Set(sameAs)],
|
|
627
|
+
dateValues,
|
|
628
|
+
authorNames: [...new Set(authorNames)],
|
|
629
|
+
metasAuthor: meta.author ?? null,
|
|
630
|
+
bylines: [...new Set(bylines)],
|
|
631
|
+
alternateLinks,
|
|
632
|
+
relMe: [...new Set(relMe)],
|
|
633
|
+
times,
|
|
634
|
+
scriptBytes,
|
|
635
|
+
externalScriptCount: externalScripts.length,
|
|
636
|
+
scriptCount: scriptTexts.length,
|
|
637
|
+
numericFacts: countNumericFacts(contentText),
|
|
638
|
+
dataNosnippetCount: nodes.filter((node) => node.attrs && 'data-nosnippet' in node.attrs).length,
|
|
639
|
+
metaBingbot: (meta.bingbot ?? '').toLowerCase(),
|
|
640
|
+
questionHeadings,
|
|
641
|
+
snippetBlockCount: snippetCandidates.length,
|
|
642
|
+
// A shell has scripts but no readable structure at all. This is a
|
|
643
|
+
// diagnostic; rules score the actual text length and heading structure.
|
|
644
|
+
jsShell: bodyText.length < 600
|
|
645
|
+
&& headings.length === 0
|
|
646
|
+
&& paragraphs.length === 0
|
|
647
|
+
&& (scriptTexts.length > 0 || externalScripts.length > 0),
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
export { textOf, walk, findFirst, decodeEntities, flattenJsonLd, jsonLdTypes, countWords };
|