@rebilder/agent-readability 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.
- package/LICENSE +204 -0
- package/README.md +183 -0
- package/dist/index.cjs +4543 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +785 -0
- package/dist/index.d.ts +785 -0
- package/dist/index.js +4521 -0
- package/dist/index.js.map +1 -0
- package/dist/probe/index.cjs +1416 -0
- package/dist/probe/index.cjs.map +1 -0
- package/dist/probe/index.d.cts +385 -0
- package/dist/probe/index.d.ts +385 -0
- package/dist/probe/index.js +1373 -0
- package/dist/probe/index.js.map +1 -0
- package/dist/probe/local.cjs +1343 -0
- package/dist/probe/local.cjs.map +1 -0
- package/dist/probe/local.d.cts +67 -0
- package/dist/probe/local.d.ts +67 -0
- package/dist/probe/local.js +1318 -0
- package/dist/probe/local.js.map +1 -0
- package/dist/types-B2FhQ1YC.d.cts +345 -0
- package/dist/types-B2FhQ1YC.d.ts +345 -0
- package/package.json +88 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4521 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var ARS_SPEC_VERSION = "0.1.0";
|
|
3
|
+
|
|
4
|
+
// src/profiles.ts
|
|
5
|
+
var PROFILE_BY_KIND = {
|
|
6
|
+
product: {
|
|
7
|
+
pageKind: "product",
|
|
8
|
+
core: ["title", "price", "currency", "availability"],
|
|
9
|
+
extended: ["brand", "sku", "shipping", "returns", "description"],
|
|
10
|
+
byteReference: 8 * 1024
|
|
11
|
+
},
|
|
12
|
+
collection: {
|
|
13
|
+
pageKind: "collection",
|
|
14
|
+
core: ["title", "item-count", "item-link"],
|
|
15
|
+
extended: ["price", "availability", "description"],
|
|
16
|
+
byteReference: 16 * 1024
|
|
17
|
+
},
|
|
18
|
+
article: {
|
|
19
|
+
pageKind: "article",
|
|
20
|
+
core: ["title", "author", "published"],
|
|
21
|
+
extended: ["updated", "section", "description"],
|
|
22
|
+
byteReference: 40 * 1024
|
|
23
|
+
},
|
|
24
|
+
place: {
|
|
25
|
+
pageKind: "place",
|
|
26
|
+
core: ["org-name", "address", "hours", "phone"],
|
|
27
|
+
extended: ["email", "service-area", "primary-action-url", "description"],
|
|
28
|
+
byteReference: 8 * 1024
|
|
29
|
+
},
|
|
30
|
+
service: {
|
|
31
|
+
pageKind: "service",
|
|
32
|
+
core: ["title", "price", "primary-action-url"],
|
|
33
|
+
extended: ["duration", "eligibility", "service-area", "description", "updated"],
|
|
34
|
+
byteReference: 8 * 1024
|
|
35
|
+
},
|
|
36
|
+
faq: {
|
|
37
|
+
pageKind: "faq",
|
|
38
|
+
core: ["title", "question-answer"],
|
|
39
|
+
extended: ["updated", "description"],
|
|
40
|
+
byteReference: 16 * 1024
|
|
41
|
+
},
|
|
42
|
+
document: {
|
|
43
|
+
pageKind: "document",
|
|
44
|
+
core: ["title", "updated", "authority"],
|
|
45
|
+
extended: ["description", "primary-action-url", "section"],
|
|
46
|
+
byteReference: 24 * 1024
|
|
47
|
+
},
|
|
48
|
+
unknown: {
|
|
49
|
+
pageKind: "unknown",
|
|
50
|
+
core: ["title", "description", "primary-action-url"],
|
|
51
|
+
extended: ["updated", "org-name"],
|
|
52
|
+
byteReference: 16 * 1024
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var PROFILES = Object.freeze(Object.values(PROFILE_BY_KIND));
|
|
56
|
+
function profileFor(pageKind) {
|
|
57
|
+
return PROFILE_BY_KIND[pageKind];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/ruleset.ts
|
|
61
|
+
function deepFreeze(value) {
|
|
62
|
+
if (typeof value !== "object" || value === null) return value;
|
|
63
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
64
|
+
return Object.freeze(value);
|
|
65
|
+
}
|
|
66
|
+
var WEIGHTS = {
|
|
67
|
+
// D1 Retrievability — 20
|
|
68
|
+
"retrievability.reachable": 8,
|
|
69
|
+
"retrievability.robots-policy": 6,
|
|
70
|
+
"retrievability.render-independence": 6,
|
|
71
|
+
// D2 Machine representation — 20
|
|
72
|
+
"machine-representation.negotiated-response": 10,
|
|
73
|
+
"machine-representation.declared-alternates": 4,
|
|
74
|
+
"machine-representation.vary-accept": 3,
|
|
75
|
+
"machine-representation.substance-parity": 3,
|
|
76
|
+
// D3 Fact coverage — 20
|
|
77
|
+
"fact-coverage.core-facts": 14,
|
|
78
|
+
"fact-coverage.context-cost": 6,
|
|
79
|
+
// D4 Fact position — 10
|
|
80
|
+
"fact-position.first-core-fact-offset": 5,
|
|
81
|
+
"fact-position.front-window": 5,
|
|
82
|
+
// D5 Structured data — 15
|
|
83
|
+
"structured-data.present": 5,
|
|
84
|
+
"structured-data.required-properties": 7,
|
|
85
|
+
"structured-data.text-agreement": 3,
|
|
86
|
+
// D6 Contract & discovery — 15
|
|
87
|
+
"contract-discovery.canonical": 4,
|
|
88
|
+
"contract-discovery.cache-validators": 3,
|
|
89
|
+
"contract-discovery.llms-txt": 2,
|
|
90
|
+
"contract-discovery.sitemap": 2,
|
|
91
|
+
"contract-discovery.machine-endpoint": 4
|
|
92
|
+
};
|
|
93
|
+
var CHECK_META = {
|
|
94
|
+
"retrievability.reachable": {
|
|
95
|
+
dimension: "retrievability",
|
|
96
|
+
label: "Reachable on the agent path",
|
|
97
|
+
basis: "measured"
|
|
98
|
+
},
|
|
99
|
+
"retrievability.robots-policy": {
|
|
100
|
+
dimension: "retrievability",
|
|
101
|
+
label: "Robots policy for assistants",
|
|
102
|
+
basis: "measured"
|
|
103
|
+
},
|
|
104
|
+
"retrievability.render-independence": {
|
|
105
|
+
dimension: "retrievability",
|
|
106
|
+
label: "Core facts present without JavaScript",
|
|
107
|
+
basis: "heuristic"
|
|
108
|
+
},
|
|
109
|
+
"machine-representation.negotiated-response": {
|
|
110
|
+
dimension: "machine-representation",
|
|
111
|
+
label: "Machine representation on Accept negotiation",
|
|
112
|
+
basis: "measured"
|
|
113
|
+
},
|
|
114
|
+
"machine-representation.declared-alternates": {
|
|
115
|
+
dimension: "machine-representation",
|
|
116
|
+
label: "Declared alternate representations",
|
|
117
|
+
basis: "measured"
|
|
118
|
+
},
|
|
119
|
+
"machine-representation.vary-accept": {
|
|
120
|
+
dimension: "machine-representation",
|
|
121
|
+
label: "Vary: Accept declared correctly",
|
|
122
|
+
basis: "measured"
|
|
123
|
+
},
|
|
124
|
+
"machine-representation.substance-parity": {
|
|
125
|
+
dimension: "machine-representation",
|
|
126
|
+
label: "Same substance across representations",
|
|
127
|
+
basis: "heuristic"
|
|
128
|
+
},
|
|
129
|
+
"fact-coverage.core-facts": {
|
|
130
|
+
dimension: "fact-coverage",
|
|
131
|
+
label: "Core facts for this page kind",
|
|
132
|
+
basis: "heuristic"
|
|
133
|
+
},
|
|
134
|
+
"fact-coverage.context-cost": {
|
|
135
|
+
dimension: "fact-coverage",
|
|
136
|
+
label: "Context cost relative to this page kind",
|
|
137
|
+
basis: "measured"
|
|
138
|
+
},
|
|
139
|
+
"fact-position.first-core-fact-offset": {
|
|
140
|
+
dimension: "fact-position",
|
|
141
|
+
label: "Byte offset of the first core fact",
|
|
142
|
+
basis: "heuristic"
|
|
143
|
+
},
|
|
144
|
+
"fact-position.front-window": {
|
|
145
|
+
dimension: "fact-position",
|
|
146
|
+
label: "Core facts inside the front window",
|
|
147
|
+
basis: "heuristic"
|
|
148
|
+
},
|
|
149
|
+
"structured-data.present": {
|
|
150
|
+
dimension: "structured-data",
|
|
151
|
+
label: "Structured data present and parsing",
|
|
152
|
+
basis: "measured"
|
|
153
|
+
},
|
|
154
|
+
"structured-data.required-properties": {
|
|
155
|
+
dimension: "structured-data",
|
|
156
|
+
label: "Recognised type with its required properties",
|
|
157
|
+
basis: "measured"
|
|
158
|
+
},
|
|
159
|
+
"structured-data.text-agreement": {
|
|
160
|
+
dimension: "structured-data",
|
|
161
|
+
label: "Structured data agrees with visible text",
|
|
162
|
+
basis: "heuristic"
|
|
163
|
+
},
|
|
164
|
+
"contract-discovery.canonical": {
|
|
165
|
+
dimension: "contract-discovery",
|
|
166
|
+
label: "Canonical URL present and self-consistent",
|
|
167
|
+
basis: "measured"
|
|
168
|
+
},
|
|
169
|
+
"contract-discovery.cache-validators": {
|
|
170
|
+
dimension: "contract-discovery",
|
|
171
|
+
label: "Cache validators",
|
|
172
|
+
basis: "measured"
|
|
173
|
+
},
|
|
174
|
+
"contract-discovery.llms-txt": {
|
|
175
|
+
dimension: "contract-discovery",
|
|
176
|
+
label: "llms.txt present and spec-shaped",
|
|
177
|
+
basis: "measured"
|
|
178
|
+
},
|
|
179
|
+
"contract-discovery.sitemap": {
|
|
180
|
+
dimension: "contract-discovery",
|
|
181
|
+
label: "Sitemap declared in robots.txt",
|
|
182
|
+
basis: "measured"
|
|
183
|
+
},
|
|
184
|
+
"contract-discovery.machine-endpoint": {
|
|
185
|
+
dimension: "contract-discovery",
|
|
186
|
+
label: "Declared machine endpoint",
|
|
187
|
+
basis: "measured"
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
var DIMENSION_META = {
|
|
191
|
+
retrievability: { label: "Retrievability", weight: 20 },
|
|
192
|
+
"machine-representation": { label: "Machine representation", weight: 20 },
|
|
193
|
+
"fact-coverage": { label: "Fact coverage", weight: 20 },
|
|
194
|
+
"fact-position": { label: "Fact position", weight: 10 },
|
|
195
|
+
"structured-data": { label: "Structured data", weight: 15 },
|
|
196
|
+
"contract-discovery": { label: "Contract & discovery", weight: 15 }
|
|
197
|
+
};
|
|
198
|
+
var ARS_MEASURED_WEIGHT = 64;
|
|
199
|
+
var ARS_HEURISTIC_WEIGHT = 36;
|
|
200
|
+
var ARS_HEURISTIC_WEIGHT_CEILING = 40;
|
|
201
|
+
var THRESHOLDS = {
|
|
202
|
+
/**
|
|
203
|
+
* D3.1 fact weighting, in quarter-units (§3.6), as
|
|
204
|
+
* `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:
|
|
205
|
+
* coreUnits = 4 × corroborated core + 2 × uncorroborated core
|
|
206
|
+
* extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended
|
|
207
|
+
* "Extended = ¼ credit" is the single definition of extended credit.
|
|
208
|
+
*/
|
|
209
|
+
"fact-coverage.fact-units": [4, 2, 1, 0],
|
|
210
|
+
/**
|
|
211
|
+
* D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit
|
|
212
|
+
* is every core fact corroborated. `coveragePct` is then
|
|
213
|
+
* `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.
|
|
214
|
+
*/
|
|
215
|
+
"fact-coverage.core-denominator-multiplier": [4],
|
|
216
|
+
/**
|
|
217
|
+
* D3.1 density band. AT-LEAST over
|
|
218
|
+
* `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.
|
|
219
|
+
* The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,
|
|
220
|
+
* which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so
|
|
221
|
+
* that keyword stuffing is pointless — fixtures `031` and `032` must score
|
|
222
|
+
* identically.
|
|
223
|
+
* Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.
|
|
224
|
+
*/
|
|
225
|
+
"fact-coverage.density": [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],
|
|
226
|
+
/**
|
|
227
|
+
* D3.2 context cost, 6 pts. AT-MOST over
|
|
228
|
+
* `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.
|
|
229
|
+
*/
|
|
230
|
+
"fact-coverage.context-cost": [100, 6, 200, 5, 500, 3, 1500, 1],
|
|
231
|
+
/** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */
|
|
232
|
+
"fact-position.first-core-fact-offset": [512, 5, 2048, 4, 8192, 2, 32768, 1],
|
|
233
|
+
/**
|
|
234
|
+
* D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose
|
|
235
|
+
* offset falls inside the window; below the last threshold, 0.
|
|
236
|
+
*/
|
|
237
|
+
"fact-position.front-window": [90, 5, 70, 4, 50, 3, 25, 1],
|
|
238
|
+
/**
|
|
239
|
+
* D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE
|
|
240
|
+
* expression, integer division — the `0.2 × bytes` form is deleted, because
|
|
241
|
+
* two implementations rounding a float disagree at the boundary.
|
|
242
|
+
*/
|
|
243
|
+
"fact-position.front-window-size": [2048, 5],
|
|
244
|
+
/**
|
|
245
|
+
* Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8
|
|
246
|
+
* bytes are the normative measurement and approximate tokens are always
|
|
247
|
+
* rendered with `≈` and an "est." chip. chars/4 is not a token count and the
|
|
248
|
+
* spec says so.
|
|
249
|
+
*/
|
|
250
|
+
"cost.approx-bytes-per-token": [4]
|
|
251
|
+
};
|
|
252
|
+
var AUDIENCE_TOKENS = {
|
|
253
|
+
/** User-triggered assistant fetches. THE audience ARS scores. */
|
|
254
|
+
assistant: [
|
|
255
|
+
"ChatGPT-User",
|
|
256
|
+
"Claude-User",
|
|
257
|
+
"Claude-SearchBot",
|
|
258
|
+
"DuckAssistBot",
|
|
259
|
+
"Meta-ExternalFetcher",
|
|
260
|
+
"MistralAI-User",
|
|
261
|
+
"OAI-SearchBot",
|
|
262
|
+
"Perplexity-User"
|
|
263
|
+
],
|
|
264
|
+
/** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */
|
|
265
|
+
training: [
|
|
266
|
+
"AI2Bot",
|
|
267
|
+
"Applebot-Extended",
|
|
268
|
+
"Bytespider",
|
|
269
|
+
"CCBot",
|
|
270
|
+
"ClaudeBot",
|
|
271
|
+
"Diffbot",
|
|
272
|
+
"FacebookBot",
|
|
273
|
+
"Google-Extended",
|
|
274
|
+
"GPTBot",
|
|
275
|
+
"Meta-ExternalAgent",
|
|
276
|
+
"PanguBot",
|
|
277
|
+
"Timpibot",
|
|
278
|
+
"anthropic-ai",
|
|
279
|
+
"cohere-ai",
|
|
280
|
+
"omgili"
|
|
281
|
+
],
|
|
282
|
+
/** Classic search indexers. Reported only. */
|
|
283
|
+
search: ["Applebot", "Baiduspider", "Bingbot", "DuckDuckBot", "Googlebot", "Slurp", "YandexBot"]
|
|
284
|
+
};
|
|
285
|
+
var REQUIRED_PROPERTIES = {
|
|
286
|
+
product: ["name", "offers.price", "offers.priceCurrency", "offers.availability"],
|
|
287
|
+
collection: ["name", "numberOfItems", "itemListElement"],
|
|
288
|
+
article: ["headline", "author", "datePublished"],
|
|
289
|
+
place: ["name", "address", "openingHours", "telephone"],
|
|
290
|
+
service: ["name", "offers.price", "offers.priceCurrency", "potentialAction.target"],
|
|
291
|
+
faq: ["name", "mainEntity", "mainEntity.acceptedAnswer"],
|
|
292
|
+
document: ["name", "dateModified", "publisher"],
|
|
293
|
+
unknown: ["name"]
|
|
294
|
+
};
|
|
295
|
+
var ACTION_LEXICON = [
|
|
296
|
+
"add to bag",
|
|
297
|
+
"add to basket",
|
|
298
|
+
"add to cart",
|
|
299
|
+
"apply",
|
|
300
|
+
"apply now",
|
|
301
|
+
"book",
|
|
302
|
+
"book now",
|
|
303
|
+
"buy",
|
|
304
|
+
"buy now",
|
|
305
|
+
"call now",
|
|
306
|
+
"checkout",
|
|
307
|
+
"contact",
|
|
308
|
+
"contact us",
|
|
309
|
+
"donate",
|
|
310
|
+
"download",
|
|
311
|
+
"email us",
|
|
312
|
+
"enroll",
|
|
313
|
+
"get a quote",
|
|
314
|
+
"get quote",
|
|
315
|
+
"get started",
|
|
316
|
+
"join",
|
|
317
|
+
"make an appointment",
|
|
318
|
+
"order",
|
|
319
|
+
"order now",
|
|
320
|
+
"purchase",
|
|
321
|
+
"register",
|
|
322
|
+
"request",
|
|
323
|
+
"request a demo",
|
|
324
|
+
"request a quote",
|
|
325
|
+
"reserve",
|
|
326
|
+
"schedule",
|
|
327
|
+
"sign up",
|
|
328
|
+
"signup",
|
|
329
|
+
"start",
|
|
330
|
+
"start free trial",
|
|
331
|
+
"subscribe"
|
|
332
|
+
];
|
|
333
|
+
var BANDS = [
|
|
334
|
+
{
|
|
335
|
+
grade: "A",
|
|
336
|
+
min: 90,
|
|
337
|
+
max: 100,
|
|
338
|
+
label: "Agent-native",
|
|
339
|
+
meaning: "Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch."
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
grade: "B",
|
|
343
|
+
min: 75,
|
|
344
|
+
max: 89,
|
|
345
|
+
label: "Agent-friendly",
|
|
346
|
+
meaning: "All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing."
|
|
347
|
+
},
|
|
348
|
+
{
|
|
349
|
+
grade: "C",
|
|
350
|
+
min: 60,
|
|
351
|
+
max: 74,
|
|
352
|
+
label: "Readable with effort",
|
|
353
|
+
meaning: "Core facts are extractable from HTML, at high cost."
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
grade: "D",
|
|
357
|
+
min: 40,
|
|
358
|
+
max: 59,
|
|
359
|
+
label: "Partial",
|
|
360
|
+
meaning: "Some core facts for this page kind were not found in the fetched response."
|
|
361
|
+
},
|
|
362
|
+
{
|
|
363
|
+
grade: "F",
|
|
364
|
+
min: 0,
|
|
365
|
+
max: 39,
|
|
366
|
+
label: "Not extractable",
|
|
367
|
+
meaning: "Few or no core facts for this page kind were found in the fetched response."
|
|
368
|
+
}
|
|
369
|
+
];
|
|
370
|
+
var DEFAULT_RULESET = deepFreeze({
|
|
371
|
+
version: "0.1.0",
|
|
372
|
+
weights: WEIGHTS,
|
|
373
|
+
thresholds: THRESHOLDS,
|
|
374
|
+
audienceTokens: AUDIENCE_TOKENS,
|
|
375
|
+
requiredProperties: REQUIRED_PROPERTIES,
|
|
376
|
+
actionLexicon: ACTION_LEXICON,
|
|
377
|
+
/** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */
|
|
378
|
+
maxBodyBytes: 2 * 1024 * 1024,
|
|
379
|
+
/** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */
|
|
380
|
+
maxRedirects: 3,
|
|
381
|
+
/** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */
|
|
382
|
+
timeoutMs: 5e3,
|
|
383
|
+
profiles: PROFILES,
|
|
384
|
+
bands: BANDS
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
// src/html.ts
|
|
388
|
+
var Utf8Cursor = class {
|
|
389
|
+
constructor(source) {
|
|
390
|
+
this.source = source;
|
|
391
|
+
}
|
|
392
|
+
source;
|
|
393
|
+
charIndex = 0;
|
|
394
|
+
byteIndex = 0;
|
|
395
|
+
at(target) {
|
|
396
|
+
if (target < this.charIndex) {
|
|
397
|
+
this.charIndex = 0;
|
|
398
|
+
this.byteIndex = 0;
|
|
399
|
+
}
|
|
400
|
+
const limit = Math.min(target, this.source.length);
|
|
401
|
+
while (this.charIndex < limit) {
|
|
402
|
+
const code = this.source.charCodeAt(this.charIndex);
|
|
403
|
+
if (code < 128) {
|
|
404
|
+
this.byteIndex += 1;
|
|
405
|
+
this.charIndex += 1;
|
|
406
|
+
} else if (code < 2048) {
|
|
407
|
+
this.byteIndex += 2;
|
|
408
|
+
this.charIndex += 1;
|
|
409
|
+
} else if (code >= 55296 && code <= 56319) {
|
|
410
|
+
const next = this.charIndex + 1 < this.source.length ? this.source.charCodeAt(this.charIndex + 1) : 0;
|
|
411
|
+
if (next >= 56320 && next <= 57343 && this.charIndex + 1 < limit) {
|
|
412
|
+
this.byteIndex += 4;
|
|
413
|
+
this.charIndex += 2;
|
|
414
|
+
} else {
|
|
415
|
+
this.byteIndex += 3;
|
|
416
|
+
this.charIndex += 1;
|
|
417
|
+
}
|
|
418
|
+
} else {
|
|
419
|
+
this.byteIndex += 3;
|
|
420
|
+
this.charIndex += 1;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return this.byteIndex;
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
var NAMED_ENTITIES = {
|
|
427
|
+
amp: "&",
|
|
428
|
+
lt: "<",
|
|
429
|
+
gt: ">",
|
|
430
|
+
quot: '"',
|
|
431
|
+
apos: "'",
|
|
432
|
+
nbsp: "\xA0",
|
|
433
|
+
ensp: "\u2002",
|
|
434
|
+
emsp: "\u2003",
|
|
435
|
+
thinsp: "\u2009",
|
|
436
|
+
shy: "\xAD",
|
|
437
|
+
zwnj: "\u200C",
|
|
438
|
+
zwj: "\u200D",
|
|
439
|
+
// Currency
|
|
440
|
+
cent: "\xA2",
|
|
441
|
+
pound: "\xA3",
|
|
442
|
+
curren: "\xA4",
|
|
443
|
+
yen: "\xA5",
|
|
444
|
+
euro: "\u20AC",
|
|
445
|
+
dollar: "$",
|
|
446
|
+
// Typography
|
|
447
|
+
ndash: "\u2013",
|
|
448
|
+
mdash: "\u2014",
|
|
449
|
+
hellip: "\u2026",
|
|
450
|
+
lsquo: "\u2018",
|
|
451
|
+
rsquo: "\u2019",
|
|
452
|
+
sbquo: "\u201A",
|
|
453
|
+
ldquo: "\u201C",
|
|
454
|
+
rdquo: "\u201D",
|
|
455
|
+
bdquo: "\u201E",
|
|
456
|
+
laquo: "\xAB",
|
|
457
|
+
raquo: "\xBB",
|
|
458
|
+
lsaquo: "\u2039",
|
|
459
|
+
rsaquo: "\u203A",
|
|
460
|
+
bull: "\u2022",
|
|
461
|
+
middot: "\xB7",
|
|
462
|
+
dagger: "\u2020",
|
|
463
|
+
Dagger: "\u2021",
|
|
464
|
+
prime: "\u2032",
|
|
465
|
+
Prime: "\u2033",
|
|
466
|
+
// Marks and math
|
|
467
|
+
copy: "\xA9",
|
|
468
|
+
reg: "\xAE",
|
|
469
|
+
trade: "\u2122",
|
|
470
|
+
sect: "\xA7",
|
|
471
|
+
para: "\xB6",
|
|
472
|
+
deg: "\xB0",
|
|
473
|
+
plusmn: "\xB1",
|
|
474
|
+
times: "\xD7",
|
|
475
|
+
divide: "\xF7",
|
|
476
|
+
minus: "\u2212",
|
|
477
|
+
permil: "\u2030",
|
|
478
|
+
frac12: "\xBD",
|
|
479
|
+
frac14: "\xBC",
|
|
480
|
+
frac34: "\xBE",
|
|
481
|
+
sup2: "\xB2",
|
|
482
|
+
sup3: "\xB3",
|
|
483
|
+
le: "\u2264",
|
|
484
|
+
ge: "\u2265",
|
|
485
|
+
ne: "\u2260",
|
|
486
|
+
// Directionality (invisible, but they do occupy bytes)
|
|
487
|
+
lrm: "\u200E",
|
|
488
|
+
rlm: "\u200F"
|
|
489
|
+
};
|
|
490
|
+
var C1_REPLACEMENTS = {
|
|
491
|
+
128: 8364,
|
|
492
|
+
130: 8218,
|
|
493
|
+
131: 402,
|
|
494
|
+
132: 8222,
|
|
495
|
+
133: 8230,
|
|
496
|
+
134: 8224,
|
|
497
|
+
135: 8225,
|
|
498
|
+
136: 710,
|
|
499
|
+
137: 8240,
|
|
500
|
+
138: 352,
|
|
501
|
+
139: 8249,
|
|
502
|
+
140: 338,
|
|
503
|
+
142: 381,
|
|
504
|
+
145: 8216,
|
|
505
|
+
146: 8217,
|
|
506
|
+
147: 8220,
|
|
507
|
+
148: 8221,
|
|
508
|
+
149: 8226,
|
|
509
|
+
150: 8211,
|
|
510
|
+
151: 8212,
|
|
511
|
+
152: 732,
|
|
512
|
+
153: 8482,
|
|
513
|
+
154: 353,
|
|
514
|
+
155: 8250,
|
|
515
|
+
156: 339,
|
|
516
|
+
158: 382,
|
|
517
|
+
159: 376
|
|
518
|
+
};
|
|
519
|
+
var ENTITY_RE = /&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z][a-zA-Z0-9]{0,31});/g;
|
|
520
|
+
function codePointToString(raw) {
|
|
521
|
+
const mapped = C1_REPLACEMENTS[raw];
|
|
522
|
+
const code = mapped ?? raw;
|
|
523
|
+
if (code === 0 || code > 1114111 || code >= 55296 && code <= 57343) return "\uFFFD";
|
|
524
|
+
return String.fromCodePoint(code);
|
|
525
|
+
}
|
|
526
|
+
function decodeEntities(text) {
|
|
527
|
+
if (!text.includes("&")) return text;
|
|
528
|
+
return text.replace(ENTITY_RE, (match, body) => {
|
|
529
|
+
if (body.startsWith("#")) {
|
|
530
|
+
const isHex = body[1] === "x" || body[1] === "X";
|
|
531
|
+
const digits = isHex ? body.slice(2) : body.slice(1);
|
|
532
|
+
const value = Number.parseInt(digits, isHex ? 16 : 10);
|
|
533
|
+
return Number.isNaN(value) ? match : codePointToString(value);
|
|
534
|
+
}
|
|
535
|
+
return NAMED_ENTITIES[body] ?? match;
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
var VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
539
|
+
"area",
|
|
540
|
+
"base",
|
|
541
|
+
"br",
|
|
542
|
+
"col",
|
|
543
|
+
"embed",
|
|
544
|
+
"hr",
|
|
545
|
+
"img",
|
|
546
|
+
"input",
|
|
547
|
+
"link",
|
|
548
|
+
"meta",
|
|
549
|
+
"param",
|
|
550
|
+
"source",
|
|
551
|
+
"track",
|
|
552
|
+
"wbr"
|
|
553
|
+
]);
|
|
554
|
+
var RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
|
|
555
|
+
var RCDATA_ELEMENTS = /* @__PURE__ */ new Set(["textarea", "title"]);
|
|
556
|
+
var IMPLIED_END_TAGS = {
|
|
557
|
+
li: ["li"],
|
|
558
|
+
dt: ["dt", "dd"],
|
|
559
|
+
dd: ["dt", "dd"],
|
|
560
|
+
option: ["option"],
|
|
561
|
+
optgroup: ["option", "optgroup"],
|
|
562
|
+
tr: ["td", "th", "tr"],
|
|
563
|
+
td: ["td", "th"],
|
|
564
|
+
th: ["td", "th"],
|
|
565
|
+
tbody: ["td", "th", "tr", "thead", "tbody"],
|
|
566
|
+
tfoot: ["td", "th", "tr", "thead", "tbody"]
|
|
567
|
+
};
|
|
568
|
+
var CLOSES_OPEN_P = /* @__PURE__ */ new Set([
|
|
569
|
+
"address",
|
|
570
|
+
"article",
|
|
571
|
+
"aside",
|
|
572
|
+
"blockquote",
|
|
573
|
+
"details",
|
|
574
|
+
"div",
|
|
575
|
+
"dl",
|
|
576
|
+
"fieldset",
|
|
577
|
+
"figcaption",
|
|
578
|
+
"figure",
|
|
579
|
+
"footer",
|
|
580
|
+
"form",
|
|
581
|
+
"h1",
|
|
582
|
+
"h2",
|
|
583
|
+
"h3",
|
|
584
|
+
"h4",
|
|
585
|
+
"h5",
|
|
586
|
+
"h6",
|
|
587
|
+
"header",
|
|
588
|
+
"hr",
|
|
589
|
+
"main",
|
|
590
|
+
"nav",
|
|
591
|
+
"ol",
|
|
592
|
+
"p",
|
|
593
|
+
"pre",
|
|
594
|
+
"section",
|
|
595
|
+
"table",
|
|
596
|
+
"ul"
|
|
597
|
+
]);
|
|
598
|
+
var MAX_DEPTH = 256;
|
|
599
|
+
function isAsciiAlpha(ch) {
|
|
600
|
+
if (ch === void 0) return false;
|
|
601
|
+
return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
|
|
602
|
+
}
|
|
603
|
+
function isHtmlSpace(ch) {
|
|
604
|
+
return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f";
|
|
605
|
+
}
|
|
606
|
+
var DISPLAY_NONE_RE = /(^|;)display:none(!important)?(;|$)/;
|
|
607
|
+
function hasInlineDisplayNone(style) {
|
|
608
|
+
if (style === void 0) return false;
|
|
609
|
+
return DISPLAY_NONE_RE.test(style.toLowerCase().replace(/\s+/g, ""));
|
|
610
|
+
}
|
|
611
|
+
function attr(element, name) {
|
|
612
|
+
return element.attrs[name] ?? null;
|
|
613
|
+
}
|
|
614
|
+
function parseStartTag(html, start) {
|
|
615
|
+
let i = start + 1;
|
|
616
|
+
const nameStart = i;
|
|
617
|
+
while (i < html.length) {
|
|
618
|
+
const ch = html[i] ?? "";
|
|
619
|
+
if (isHtmlSpace(ch) || ch === "/" || ch === ">") break;
|
|
620
|
+
i++;
|
|
621
|
+
}
|
|
622
|
+
const tag = html.slice(nameStart, i).toLowerCase();
|
|
623
|
+
const attrs = {};
|
|
624
|
+
let selfClosing = false;
|
|
625
|
+
while (i < html.length) {
|
|
626
|
+
while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
|
|
627
|
+
if (i >= html.length) break;
|
|
628
|
+
const ch = html[i] ?? "";
|
|
629
|
+
if (ch === ">") {
|
|
630
|
+
i++;
|
|
631
|
+
return { tag, attrs, selfClosing, end: i };
|
|
632
|
+
}
|
|
633
|
+
if (ch === "/") {
|
|
634
|
+
selfClosing = true;
|
|
635
|
+
i++;
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
const attrNameStart = i;
|
|
639
|
+
while (i < html.length) {
|
|
640
|
+
const c = html[i] ?? "";
|
|
641
|
+
if (isHtmlSpace(c) || c === "=" || c === ">" || c === "/") break;
|
|
642
|
+
i++;
|
|
643
|
+
}
|
|
644
|
+
if (i === attrNameStart) {
|
|
645
|
+
i++;
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
const attrName = html.slice(attrNameStart, i).toLowerCase();
|
|
649
|
+
let value = "";
|
|
650
|
+
while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
|
|
651
|
+
if (html[i] === "=") {
|
|
652
|
+
i++;
|
|
653
|
+
while (i < html.length && isHtmlSpace(html[i] ?? "")) i++;
|
|
654
|
+
const quote = html[i];
|
|
655
|
+
if (quote === '"' || quote === "'") {
|
|
656
|
+
i++;
|
|
657
|
+
const valueStart = i;
|
|
658
|
+
const close = html.indexOf(quote, i);
|
|
659
|
+
if (close === -1) {
|
|
660
|
+
value = html.slice(valueStart);
|
|
661
|
+
i = html.length;
|
|
662
|
+
} else {
|
|
663
|
+
value = html.slice(valueStart, close);
|
|
664
|
+
i = close + 1;
|
|
665
|
+
}
|
|
666
|
+
} else {
|
|
667
|
+
const valueStart = i;
|
|
668
|
+
while (i < html.length) {
|
|
669
|
+
const c = html[i] ?? "";
|
|
670
|
+
if (isHtmlSpace(c) || c === ">") break;
|
|
671
|
+
i++;
|
|
672
|
+
}
|
|
673
|
+
value = html.slice(valueStart, i);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
if (!(attrName in attrs)) attrs[attrName] = decodeEntities(value);
|
|
677
|
+
}
|
|
678
|
+
return { tag, attrs, selfClosing, end: i };
|
|
679
|
+
}
|
|
680
|
+
function findRawTextEnd(html, from, tag) {
|
|
681
|
+
const needle = `</${tag}`;
|
|
682
|
+
const lower = html.toLowerCase();
|
|
683
|
+
const at = lower.indexOf(needle, from);
|
|
684
|
+
return at === -1 ? -1 : at;
|
|
685
|
+
}
|
|
686
|
+
function ownExclusion(tag, attrs) {
|
|
687
|
+
if (tag === "script") {
|
|
688
|
+
const type = (attrs["type"] ?? "").toLowerCase().split(";")[0]?.trim() ?? "";
|
|
689
|
+
return type === "application/ld+json" ? "script-ld-json" : "script";
|
|
690
|
+
}
|
|
691
|
+
if (tag === "style") return "style";
|
|
692
|
+
if (tag === "template") return "template";
|
|
693
|
+
if ("hidden" in attrs) return "hidden-attribute";
|
|
694
|
+
if (hasInlineDisplayNone(attrs["style"])) return "inline-display-none";
|
|
695
|
+
return null;
|
|
696
|
+
}
|
|
697
|
+
function tokenizeHtml(html) {
|
|
698
|
+
const elements = [];
|
|
699
|
+
const texts = [];
|
|
700
|
+
const jsonLd = [];
|
|
701
|
+
const metas = [];
|
|
702
|
+
const links = [];
|
|
703
|
+
const stack = [];
|
|
704
|
+
const cursor = new Utf8Cursor(html);
|
|
705
|
+
const topIndex = () => stack[stack.length - 1] ?? -1;
|
|
706
|
+
const exclusionAt = (elementIndex) => elementIndex >= 0 ? elements[elementIndex]?.excludedBy ?? null : null;
|
|
707
|
+
const emitText = (from, to, decode, override) => {
|
|
708
|
+
if (to <= from) return;
|
|
709
|
+
const raw = html.slice(from, to);
|
|
710
|
+
const parent = topIndex();
|
|
711
|
+
const offset = cursor.at(from);
|
|
712
|
+
texts.push({
|
|
713
|
+
text: decode ? decodeEntities(raw) : raw,
|
|
714
|
+
offset,
|
|
715
|
+
bytes: cursor.at(to) - offset,
|
|
716
|
+
parent,
|
|
717
|
+
excludedBy: override ?? exclusionAt(parent)
|
|
718
|
+
});
|
|
719
|
+
};
|
|
720
|
+
const popTo = (tag) => {
|
|
721
|
+
for (let depth = stack.length - 1; depth >= 0; depth--) {
|
|
722
|
+
const candidate = stack[depth];
|
|
723
|
+
if (candidate === void 0) continue;
|
|
724
|
+
if (elements[candidate]?.tag === tag) {
|
|
725
|
+
stack.length = depth;
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
const applyImpliedEndTags = (tag) => {
|
|
731
|
+
const closes = IMPLIED_END_TAGS[tag];
|
|
732
|
+
if (closes !== void 0) {
|
|
733
|
+
while (stack.length > 0) {
|
|
734
|
+
const top = stack[stack.length - 1];
|
|
735
|
+
const openTag = top === void 0 ? void 0 : elements[top]?.tag;
|
|
736
|
+
if (openTag === void 0 || !closes.includes(openTag)) break;
|
|
737
|
+
stack.pop();
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (CLOSES_OPEN_P.has(tag)) {
|
|
741
|
+
const top = stack[stack.length - 1];
|
|
742
|
+
if (top !== void 0 && elements[top]?.tag === "p") stack.pop();
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
let i = 0;
|
|
746
|
+
let textStart = 0;
|
|
747
|
+
while (i < html.length) {
|
|
748
|
+
const lt = html.indexOf("<", i);
|
|
749
|
+
if (lt === -1) break;
|
|
750
|
+
const next = html[lt + 1];
|
|
751
|
+
if (next !== "!" && next !== "/" && !isAsciiAlpha(next)) {
|
|
752
|
+
i = lt + 1;
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
emitText(textStart, lt, true);
|
|
756
|
+
if (next === "!") {
|
|
757
|
+
if (html.startsWith("<!--", lt)) {
|
|
758
|
+
const close = html.indexOf("-->", lt + 4);
|
|
759
|
+
i = close === -1 ? html.length : close + 3;
|
|
760
|
+
} else {
|
|
761
|
+
const close = html.indexOf(">", lt + 2);
|
|
762
|
+
i = close === -1 ? html.length : close + 1;
|
|
763
|
+
}
|
|
764
|
+
textStart = i;
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
if (next === "/") {
|
|
768
|
+
const close = html.indexOf(">", lt + 2);
|
|
769
|
+
const end = close === -1 ? html.length : close + 1;
|
|
770
|
+
const rawName = html.slice(lt + 2, close === -1 ? html.length : close).trim();
|
|
771
|
+
const tag = rawName.toLowerCase();
|
|
772
|
+
if (tag.length > 0) popTo(tag);
|
|
773
|
+
i = end;
|
|
774
|
+
textStart = i;
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
const parsed = parseStartTag(html, lt);
|
|
778
|
+
applyImpliedEndTags(parsed.tag);
|
|
779
|
+
const parent = topIndex();
|
|
780
|
+
const own = ownExclusion(parsed.tag, parsed.attrs);
|
|
781
|
+
const element = {
|
|
782
|
+
index: elements.length,
|
|
783
|
+
tag: parsed.tag,
|
|
784
|
+
attrs: parsed.attrs,
|
|
785
|
+
offset: cursor.at(lt),
|
|
786
|
+
parent,
|
|
787
|
+
depth: stack.length,
|
|
788
|
+
excludedBy: exclusionAt(parent) ?? own
|
|
789
|
+
};
|
|
790
|
+
elements.push(element);
|
|
791
|
+
collectMetaOrLink(element, metas, links);
|
|
792
|
+
i = parsed.end;
|
|
793
|
+
const isVoid = VOID_ELEMENTS.has(parsed.tag);
|
|
794
|
+
const isRawText = RAW_TEXT_ELEMENTS.has(parsed.tag);
|
|
795
|
+
const isRcdata = RCDATA_ELEMENTS.has(parsed.tag);
|
|
796
|
+
if (isRawText || isRcdata) {
|
|
797
|
+
const contentStart = i;
|
|
798
|
+
const close = findRawTextEnd(html, contentStart, parsed.tag);
|
|
799
|
+
const contentEnd = close === -1 ? html.length : close;
|
|
800
|
+
if (contentEnd > contentStart) {
|
|
801
|
+
const wasTop = stack.length;
|
|
802
|
+
stack.push(element.index);
|
|
803
|
+
emitText(contentStart, contentEnd, isRcdata, element.excludedBy ?? own ?? void 0);
|
|
804
|
+
stack.length = wasTop;
|
|
805
|
+
if (own === "script-ld-json") {
|
|
806
|
+
jsonLd.push({
|
|
807
|
+
text: html.slice(contentStart, contentEnd),
|
|
808
|
+
offset: cursor.at(contentStart),
|
|
809
|
+
element: element.index
|
|
810
|
+
});
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (close === -1) {
|
|
814
|
+
i = html.length;
|
|
815
|
+
} else {
|
|
816
|
+
const gt = html.indexOf(">", close);
|
|
817
|
+
i = gt === -1 ? html.length : gt + 1;
|
|
818
|
+
}
|
|
819
|
+
textStart = i;
|
|
820
|
+
continue;
|
|
821
|
+
}
|
|
822
|
+
if (!isVoid && !parsed.selfClosing && stack.length < MAX_DEPTH) stack.push(element.index);
|
|
823
|
+
textStart = i;
|
|
824
|
+
}
|
|
825
|
+
emitText(textStart, html.length, true);
|
|
826
|
+
return {
|
|
827
|
+
elements,
|
|
828
|
+
texts,
|
|
829
|
+
jsonLd,
|
|
830
|
+
metas,
|
|
831
|
+
links,
|
|
832
|
+
bytes: cursor.at(html.length)
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
function collectMetaOrLink(element, metas, links) {
|
|
836
|
+
const lower = (value) => value === void 0 ? null : value.toLowerCase();
|
|
837
|
+
if (element.tag === "meta") {
|
|
838
|
+
metas.push({
|
|
839
|
+
name: lower(element.attrs["name"]),
|
|
840
|
+
property: lower(element.attrs["property"]),
|
|
841
|
+
httpEquiv: lower(element.attrs["http-equiv"]),
|
|
842
|
+
itemprop: lower(element.attrs["itemprop"]),
|
|
843
|
+
charset: lower(element.attrs["charset"]),
|
|
844
|
+
content: element.attrs["content"] ?? null,
|
|
845
|
+
element: element.index,
|
|
846
|
+
offset: element.offset
|
|
847
|
+
});
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
if (element.tag === "link") {
|
|
851
|
+
const rawRel = element.attrs["rel"] ?? "";
|
|
852
|
+
const rel = [];
|
|
853
|
+
for (const token of rawRel.toLowerCase().split(/\s+/)) {
|
|
854
|
+
if (token.length > 0 && !rel.includes(token)) rel.push(token);
|
|
855
|
+
}
|
|
856
|
+
links.push({
|
|
857
|
+
rel,
|
|
858
|
+
href: element.attrs["href"] ?? null,
|
|
859
|
+
type: lower(element.attrs["type"]),
|
|
860
|
+
hreflang: lower(element.attrs["hreflang"]),
|
|
861
|
+
title: element.attrs["title"] ?? null,
|
|
862
|
+
element: element.index,
|
|
863
|
+
offset: element.offset
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
function joinText(parts) {
|
|
868
|
+
return parts.join(" ").replace(/\s+/g, " ").trim();
|
|
869
|
+
}
|
|
870
|
+
function countedText(doc) {
|
|
871
|
+
const parts = [];
|
|
872
|
+
for (const node of doc.texts) {
|
|
873
|
+
if (node.excludedBy === null) parts.push(node.text);
|
|
874
|
+
}
|
|
875
|
+
return joinText(parts);
|
|
876
|
+
}
|
|
877
|
+
function elementText(doc, elementIndex, includeExcluded = false) {
|
|
878
|
+
const parts = [];
|
|
879
|
+
for (const node of doc.texts) {
|
|
880
|
+
if (!includeExcluded && node.excludedBy !== null) continue;
|
|
881
|
+
if (isSelfOrDescendant(doc, node.parent, elementIndex)) parts.push(node.text);
|
|
882
|
+
}
|
|
883
|
+
return joinText(parts);
|
|
884
|
+
}
|
|
885
|
+
function isSelfOrDescendant(doc, from, ancestor) {
|
|
886
|
+
let current = from;
|
|
887
|
+
for (let hops = 0; hops <= MAX_DEPTH + 1 && current >= 0; hops++) {
|
|
888
|
+
if (current === ancestor) return true;
|
|
889
|
+
current = doc.elements[current]?.parent ?? -1;
|
|
890
|
+
}
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
// src/parse-money.ts
|
|
895
|
+
var ISO_4217 = new Set(
|
|
896
|
+
"AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VED VES VND VUV WST XAF XAG XAU XCD XCG XDR XOF XPD XPF XPT YER ZAR ZMW ZWG".split(" ")
|
|
897
|
+
);
|
|
898
|
+
var ZERO_DECIMAL = /* @__PURE__ */ new Set([
|
|
899
|
+
"BIF",
|
|
900
|
+
"CLP",
|
|
901
|
+
"DJF",
|
|
902
|
+
"GNF",
|
|
903
|
+
"ISK",
|
|
904
|
+
"JPY",
|
|
905
|
+
"KMF",
|
|
906
|
+
"KRW",
|
|
907
|
+
"MGA",
|
|
908
|
+
"PYG",
|
|
909
|
+
"RWF",
|
|
910
|
+
"UGX",
|
|
911
|
+
"VND",
|
|
912
|
+
"VUV",
|
|
913
|
+
"XAF",
|
|
914
|
+
"XOF",
|
|
915
|
+
"XPF"
|
|
916
|
+
]);
|
|
917
|
+
var THREE_DECIMAL = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
|
|
918
|
+
function minorUnitDigits(code) {
|
|
919
|
+
const upper = code.toUpperCase();
|
|
920
|
+
if (ZERO_DECIMAL.has(upper)) return 0;
|
|
921
|
+
if (THREE_DECIMAL.has(upper)) return 3;
|
|
922
|
+
return 2;
|
|
923
|
+
}
|
|
924
|
+
var SYMBOLS = {
|
|
925
|
+
US$: { fallback: "USD", alternatives: [] },
|
|
926
|
+
CA$: { fallback: "CAD", alternatives: [] },
|
|
927
|
+
C$: { fallback: "CAD", alternatives: [] },
|
|
928
|
+
AU$: { fallback: "AUD", alternatives: [] },
|
|
929
|
+
A$: { fallback: "AUD", alternatives: [] },
|
|
930
|
+
NZ$: { fallback: "NZD", alternatives: [] },
|
|
931
|
+
HK$: { fallback: "HKD", alternatives: [] },
|
|
932
|
+
NT$: { fallback: "TWD", alternatives: [] },
|
|
933
|
+
S$: { fallback: "SGD", alternatives: [] },
|
|
934
|
+
R$: { fallback: "BRL", alternatives: [] },
|
|
935
|
+
MX$: { fallback: "MXN", alternatives: [] },
|
|
936
|
+
$: {
|
|
937
|
+
fallback: "USD",
|
|
938
|
+
alternatives: [
|
|
939
|
+
"USD",
|
|
940
|
+
"CAD",
|
|
941
|
+
"AUD",
|
|
942
|
+
"NZD",
|
|
943
|
+
"SGD",
|
|
944
|
+
"HKD",
|
|
945
|
+
"MXN",
|
|
946
|
+
"TWD",
|
|
947
|
+
"BRL",
|
|
948
|
+
"ARS",
|
|
949
|
+
"CLP",
|
|
950
|
+
"COP",
|
|
951
|
+
"UYU"
|
|
952
|
+
]
|
|
953
|
+
},
|
|
954
|
+
"\xA5": { fallback: "JPY", alternatives: ["JPY", "CNY"] },
|
|
955
|
+
kr: { fallback: null, alternatives: ["SEK", "NOK", "DKK", "ISK"] },
|
|
956
|
+
"\u20AC": { fallback: "EUR", alternatives: [] },
|
|
957
|
+
"\xA3": { fallback: "GBP", alternatives: [] },
|
|
958
|
+
"\u20B9": { fallback: "INR", alternatives: [] },
|
|
959
|
+
"\u20A9": { fallback: "KRW", alternatives: [] },
|
|
960
|
+
"\u20BD": { fallback: "RUB", alternatives: [] },
|
|
961
|
+
"\u20BA": { fallback: "TRY", alternatives: [] },
|
|
962
|
+
"\u20AA": { fallback: "ILS", alternatives: [] },
|
|
963
|
+
"\u20AB": { fallback: "VND", alternatives: [] },
|
|
964
|
+
"\u20B1": { fallback: "PHP", alternatives: [] },
|
|
965
|
+
"\u20B4": { fallback: "UAH", alternatives: [] },
|
|
966
|
+
"\u20A6": { fallback: "NGN", alternatives: [] },
|
|
967
|
+
"\u20A1": { fallback: "CRC", alternatives: [] },
|
|
968
|
+
"\u20B8": { fallback: "KZT", alternatives: [] },
|
|
969
|
+
"\u20BE": { fallback: "GEL", alternatives: [] },
|
|
970
|
+
"\u0E3F": { fallback: "THB", alternatives: [] },
|
|
971
|
+
z\u0142: { fallback: "PLN", alternatives: [] },
|
|
972
|
+
K\u010D: { fallback: "CZK", alternatives: [] }
|
|
973
|
+
};
|
|
974
|
+
var SYMBOLS_BY_LENGTH = Object.keys(SYMBOLS).sort((a, b) => b.length - a.length);
|
|
975
|
+
var PREFIX_QUALIFIERS = [
|
|
976
|
+
"starting from",
|
|
977
|
+
"starting at",
|
|
978
|
+
"prices from",
|
|
979
|
+
"priced from",
|
|
980
|
+
"as little as",
|
|
981
|
+
"as much as",
|
|
982
|
+
"as low as",
|
|
983
|
+
"starts at",
|
|
984
|
+
"up to",
|
|
985
|
+
"from"
|
|
986
|
+
];
|
|
987
|
+
var SUFFIX_QUALIFIERS = ["and above", "or more", "or less", "and up", "+"];
|
|
988
|
+
var RANGE_DASHES = ["\u2014", "\u2013", "\u2010", "-"];
|
|
989
|
+
var SPACE_RE = /[\t\n\r\f\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]/g;
|
|
990
|
+
var GROUP_SPACERS = [" ", "'", "\u2019"];
|
|
991
|
+
var MAX_INPUT_LENGTH = 256;
|
|
992
|
+
var MAX_SIGNIFICANT_DIGITS = 15;
|
|
993
|
+
var NUMBER_RUN_RE = /\d[\d.,'’ ]*/g;
|
|
994
|
+
function isGroupedInteger(parts) {
|
|
995
|
+
if (parts.length < 2) return false;
|
|
996
|
+
const first = parts[0] ?? "";
|
|
997
|
+
if (first.length < 1 || first.length > 3 || first.startsWith("0")) return false;
|
|
998
|
+
for (let i = 1; i < parts.length; i++) {
|
|
999
|
+
if ((parts[i] ?? "").length !== 3) return false;
|
|
1000
|
+
}
|
|
1001
|
+
return true;
|
|
1002
|
+
}
|
|
1003
|
+
function stripGroupSpacers(token) {
|
|
1004
|
+
if (!GROUP_SPACERS.some((c) => token.includes(c))) return token;
|
|
1005
|
+
let head = token;
|
|
1006
|
+
let tail = "";
|
|
1007
|
+
const lastDot = token.lastIndexOf(".");
|
|
1008
|
+
const lastComma = token.lastIndexOf(",");
|
|
1009
|
+
const lastSep = Math.max(lastDot, lastComma);
|
|
1010
|
+
if (lastSep > 0) {
|
|
1011
|
+
const after = token.slice(lastSep + 1);
|
|
1012
|
+
const afterIsDigits = after.length > 0 && !/\D/.test(after);
|
|
1013
|
+
if (afterIsDigits) {
|
|
1014
|
+
head = token.slice(0, lastSep);
|
|
1015
|
+
tail = token.slice(lastSep);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const parts = [];
|
|
1019
|
+
let current = "";
|
|
1020
|
+
for (const ch of head) {
|
|
1021
|
+
if (GROUP_SPACERS.includes(ch)) {
|
|
1022
|
+
parts.push(current);
|
|
1023
|
+
current = "";
|
|
1024
|
+
} else if (ch >= "0" && ch <= "9") {
|
|
1025
|
+
current += ch;
|
|
1026
|
+
} else {
|
|
1027
|
+
return null;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
parts.push(current);
|
|
1031
|
+
if (!isGroupedInteger(parts)) return null;
|
|
1032
|
+
return parts.join("") + tail;
|
|
1033
|
+
}
|
|
1034
|
+
function splitMajorFraction(token, minorDigits) {
|
|
1035
|
+
const dots = token.split(".").length - 1;
|
|
1036
|
+
const commas = token.split(",").length - 1;
|
|
1037
|
+
if (dots === 0 && commas === 0) return { major: token, fraction: "" };
|
|
1038
|
+
if (dots > 0 && commas > 0) {
|
|
1039
|
+
const decimal = token.lastIndexOf(".") > token.lastIndexOf(",") ? "." : ",";
|
|
1040
|
+
const group = decimal === "." ? "," : ".";
|
|
1041
|
+
const decimalAt = token.lastIndexOf(decimal);
|
|
1042
|
+
const head = token.slice(0, decimalAt);
|
|
1043
|
+
const fraction = token.slice(decimalAt + 1);
|
|
1044
|
+
if (fraction.length === 0 || head.includes(decimal)) return null;
|
|
1045
|
+
if (!isGroupedInteger(head.split(group))) return null;
|
|
1046
|
+
return { major: head.split(group).join(""), fraction };
|
|
1047
|
+
}
|
|
1048
|
+
const separator = dots > 0 ? "." : ",";
|
|
1049
|
+
const count = dots > 0 ? dots : commas;
|
|
1050
|
+
const parts = token.split(separator);
|
|
1051
|
+
if (count > 1) {
|
|
1052
|
+
return isGroupedInteger(parts) ? { major: parts.join(""), fraction: "" } : null;
|
|
1053
|
+
}
|
|
1054
|
+
const left = parts[0] ?? "";
|
|
1055
|
+
const right = parts[1] ?? "";
|
|
1056
|
+
if (left.length === 0 || right.length === 0) return null;
|
|
1057
|
+
if (right.length === 3 && isGroupedInteger(parts)) {
|
|
1058
|
+
if (minorDigits === 3) return null;
|
|
1059
|
+
return { major: left + right, fraction: "" };
|
|
1060
|
+
}
|
|
1061
|
+
return { major: left, fraction: right };
|
|
1062
|
+
}
|
|
1063
|
+
function toMinorUnits(major, fraction, minorDigits) {
|
|
1064
|
+
let frac = fraction;
|
|
1065
|
+
if (frac.length > minorDigits) {
|
|
1066
|
+
const extra = frac.slice(minorDigits);
|
|
1067
|
+
if (/[^0]/.test(extra)) return null;
|
|
1068
|
+
frac = frac.slice(0, minorDigits);
|
|
1069
|
+
}
|
|
1070
|
+
frac = frac.padEnd(minorDigits, "0");
|
|
1071
|
+
const digits = (major + frac).replace(/^0+(?=\d)/, "");
|
|
1072
|
+
if (digits.length > MAX_SIGNIFICANT_DIGITS) return null;
|
|
1073
|
+
const value = Number.parseInt(digits, 10);
|
|
1074
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
1075
|
+
}
|
|
1076
|
+
function adjacentIsoCode(ctx) {
|
|
1077
|
+
const beforeMatch = /([A-Z]{3})\s?$/.exec(ctx.before);
|
|
1078
|
+
const afterMatch = /^\s?([A-Z]{3})(?![A-Za-z])/.exec(ctx.after);
|
|
1079
|
+
const codes = [];
|
|
1080
|
+
for (const match of [beforeMatch, afterMatch]) {
|
|
1081
|
+
const code = match?.[1];
|
|
1082
|
+
if (code !== void 0 && ISO_4217.has(code) && !codes.includes(code)) codes.push(code);
|
|
1083
|
+
}
|
|
1084
|
+
if (codes.length > 1) return false;
|
|
1085
|
+
return codes[0] ?? null;
|
|
1086
|
+
}
|
|
1087
|
+
function stripTrailingSign(text) {
|
|
1088
|
+
const trimmed = text.trimEnd();
|
|
1089
|
+
return /[-−]$/.test(trimmed) ? trimmed.slice(0, -1).trimEnd() : trimmed;
|
|
1090
|
+
}
|
|
1091
|
+
function adjacentSymbol(ctx) {
|
|
1092
|
+
const before = stripTrailingSign(ctx.before);
|
|
1093
|
+
const after = ctx.after.trimStart();
|
|
1094
|
+
const found = [];
|
|
1095
|
+
for (const symbol of SYMBOLS_BY_LENGTH) {
|
|
1096
|
+
if (before.endsWith(symbol) && !found.some((s) => s.endsWith(symbol))) found.push(symbol);
|
|
1097
|
+
}
|
|
1098
|
+
for (const symbol of SYMBOLS_BY_LENGTH) {
|
|
1099
|
+
if (after.startsWith(symbol) && !found.some((s) => s.startsWith(symbol))) found.push(symbol);
|
|
1100
|
+
}
|
|
1101
|
+
if (found.length > 1) return false;
|
|
1102
|
+
return found[0] ?? null;
|
|
1103
|
+
}
|
|
1104
|
+
function resolveSymbol(symbol, hint) {
|
|
1105
|
+
const entry = SYMBOLS[symbol];
|
|
1106
|
+
if (entry === void 0) return null;
|
|
1107
|
+
if (hint !== void 0) {
|
|
1108
|
+
const upper = hint.toUpperCase();
|
|
1109
|
+
if (upper === entry.fallback || entry.alternatives.includes(upper)) return upper;
|
|
1110
|
+
}
|
|
1111
|
+
return entry.fallback;
|
|
1112
|
+
}
|
|
1113
|
+
function normalizeSpaces(text) {
|
|
1114
|
+
return text.replace(SPACE_RE, " ").replace(/ {2,}/g, " ").trim();
|
|
1115
|
+
}
|
|
1116
|
+
function stripQualifiers(text) {
|
|
1117
|
+
let out = text;
|
|
1118
|
+
let qualified = false;
|
|
1119
|
+
const lower = out.toLowerCase();
|
|
1120
|
+
for (const phrase of PREFIX_QUALIFIERS) {
|
|
1121
|
+
if (!lower.startsWith(phrase)) continue;
|
|
1122
|
+
const next = out.charAt(phrase.length);
|
|
1123
|
+
if (next !== "" && /[a-z]/i.test(next)) continue;
|
|
1124
|
+
out = out.slice(phrase.length).trim();
|
|
1125
|
+
qualified = true;
|
|
1126
|
+
break;
|
|
1127
|
+
}
|
|
1128
|
+
const lowerEnd = out.toLowerCase();
|
|
1129
|
+
for (const phrase of SUFFIX_QUALIFIERS) {
|
|
1130
|
+
if (!lowerEnd.endsWith(phrase)) continue;
|
|
1131
|
+
const prev = out.charAt(out.length - phrase.length - 1);
|
|
1132
|
+
if (/[a-z]/i.test(prev)) continue;
|
|
1133
|
+
out = out.slice(0, out.length - phrase.length).trim();
|
|
1134
|
+
qualified = true;
|
|
1135
|
+
break;
|
|
1136
|
+
}
|
|
1137
|
+
return { text: out, qualified };
|
|
1138
|
+
}
|
|
1139
|
+
function splitRange(text) {
|
|
1140
|
+
let separatorIndex = -1;
|
|
1141
|
+
let separatorLength = 0;
|
|
1142
|
+
let count = 0;
|
|
1143
|
+
for (const dash of RANGE_DASHES) {
|
|
1144
|
+
let at = text.indexOf(dash);
|
|
1145
|
+
while (at !== -1) {
|
|
1146
|
+
count++;
|
|
1147
|
+
if (count === 1) {
|
|
1148
|
+
separatorIndex = at;
|
|
1149
|
+
separatorLength = dash.length;
|
|
1150
|
+
}
|
|
1151
|
+
at = text.indexOf(dash, at + dash.length);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
if (count === 0) {
|
|
1155
|
+
const word = / to /i.exec(text);
|
|
1156
|
+
if (word === null) return null;
|
|
1157
|
+
separatorIndex = word.index;
|
|
1158
|
+
separatorLength = word[0].length;
|
|
1159
|
+
} else if (count > 1) {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1162
|
+
const left = text.slice(0, separatorIndex).trim();
|
|
1163
|
+
const right = text.slice(separatorIndex + separatorLength).trim();
|
|
1164
|
+
if (!/\d/.test(left) || !/\d/.test(right)) return null;
|
|
1165
|
+
return [left, right];
|
|
1166
|
+
}
|
|
1167
|
+
function parseOperand(text, hints) {
|
|
1168
|
+
if (text.includes("%")) return null;
|
|
1169
|
+
NUMBER_RUN_RE.lastIndex = 0;
|
|
1170
|
+
const runs = [];
|
|
1171
|
+
let match;
|
|
1172
|
+
while ((match = NUMBER_RUN_RE.exec(text)) !== null) {
|
|
1173
|
+
let value = match[0];
|
|
1174
|
+
while (value.length > 0 && !/\d$/.test(value)) value = value.slice(0, -1);
|
|
1175
|
+
runs.push({ value, start: match.index, end: match.index + value.length });
|
|
1176
|
+
if (runs.length > 1) return null;
|
|
1177
|
+
}
|
|
1178
|
+
const run = runs[0];
|
|
1179
|
+
if (run === void 0) return null;
|
|
1180
|
+
const ctx = { before: text.slice(0, run.start), after: text.slice(run.end) };
|
|
1181
|
+
const isoCode = adjacentIsoCode(ctx);
|
|
1182
|
+
if (isoCode === false) return null;
|
|
1183
|
+
const symbol = adjacentSymbol(ctx);
|
|
1184
|
+
if (symbol === false) return null;
|
|
1185
|
+
let currency;
|
|
1186
|
+
if (isoCode !== null && symbol !== null) {
|
|
1187
|
+
const fromSymbol = resolveSymbol(symbol, isoCode);
|
|
1188
|
+
if (fromSymbol !== isoCode) return null;
|
|
1189
|
+
currency = isoCode;
|
|
1190
|
+
} else if (isoCode !== null) {
|
|
1191
|
+
currency = isoCode;
|
|
1192
|
+
} else if (symbol !== null) {
|
|
1193
|
+
currency = resolveSymbol(symbol, hints?.currency);
|
|
1194
|
+
} else {
|
|
1195
|
+
const hint = hints?.currency?.toUpperCase();
|
|
1196
|
+
if (hint === void 0 || !ISO_4217.has(hint)) return null;
|
|
1197
|
+
if (/[A-Za-z]/.test(ctx.before + ctx.after)) return null;
|
|
1198
|
+
currency = hint;
|
|
1199
|
+
}
|
|
1200
|
+
if (currency === null || !ISO_4217.has(currency)) return null;
|
|
1201
|
+
const negative = /[-−]\s?$/.test(stripTrailingSymbol(ctx.before));
|
|
1202
|
+
const spaced = stripGroupSpacers(run.value);
|
|
1203
|
+
if (spaced === null) return null;
|
|
1204
|
+
const split = splitMajorFraction(spaced, minorUnitDigits(currency));
|
|
1205
|
+
if (split === null) return null;
|
|
1206
|
+
const magnitude = toMinorUnits(split.major, split.fraction, minorUnitDigits(currency));
|
|
1207
|
+
if (magnitude === null) return null;
|
|
1208
|
+
return { amount: negative ? -magnitude : magnitude, currency };
|
|
1209
|
+
}
|
|
1210
|
+
function stripTrailingSymbol(before) {
|
|
1211
|
+
const trimmed = before.trimEnd();
|
|
1212
|
+
for (const symbol of SYMBOLS_BY_LENGTH) {
|
|
1213
|
+
if (trimmed.endsWith(symbol)) return trimmed.slice(0, trimmed.length - symbol.length);
|
|
1214
|
+
}
|
|
1215
|
+
return trimmed;
|
|
1216
|
+
}
|
|
1217
|
+
function parseMoneyText(text, hints) {
|
|
1218
|
+
if (typeof text !== "string" || text.length === 0 || text.length > MAX_INPUT_LENGTH) return null;
|
|
1219
|
+
const normalized = normalizeSpaces(text);
|
|
1220
|
+
if (!/\d/.test(normalized)) return null;
|
|
1221
|
+
const prepared = stripQualifiers(normalized);
|
|
1222
|
+
const range = splitRange(prepared.text);
|
|
1223
|
+
if (range === null) {
|
|
1224
|
+
const single = parseOperand(prepared.text, hints);
|
|
1225
|
+
return single === null ? null : { ...single, qualified: prepared.qualified };
|
|
1226
|
+
}
|
|
1227
|
+
const [leftText, rightText] = range;
|
|
1228
|
+
let left = parseOperand(leftText, hints);
|
|
1229
|
+
const right = parseOperand(rightText, left === null ? hints : { currency: left.currency });
|
|
1230
|
+
if (left === null && right !== null) left = parseOperand(leftText, { currency: right.currency });
|
|
1231
|
+
if (left !== null && right !== null) {
|
|
1232
|
+
if (left.currency !== right.currency) return null;
|
|
1233
|
+
const lower = right.amount < left.amount ? right : left;
|
|
1234
|
+
return { ...lower, qualified: true };
|
|
1235
|
+
}
|
|
1236
|
+
const only = left ?? right;
|
|
1237
|
+
return only === null ? null : { ...only, qualified: true };
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
// src/extract.ts
|
|
1241
|
+
function utf8Length(text) {
|
|
1242
|
+
let bytes = 0;
|
|
1243
|
+
for (let i = 0; i < text.length; i++) {
|
|
1244
|
+
const code = text.charCodeAt(i);
|
|
1245
|
+
if (code < 128) bytes += 1;
|
|
1246
|
+
else if (code < 2048) bytes += 2;
|
|
1247
|
+
else if (code >= 55296 && code <= 56319) {
|
|
1248
|
+
const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
|
|
1249
|
+
if (next >= 56320 && next <= 57343) {
|
|
1250
|
+
bytes += 4;
|
|
1251
|
+
i++;
|
|
1252
|
+
} else bytes += 3;
|
|
1253
|
+
} else bytes += 3;
|
|
1254
|
+
}
|
|
1255
|
+
return bytes;
|
|
1256
|
+
}
|
|
1257
|
+
var SCHEMA_PREFIX = /^https?:\/\/schema\.org\//;
|
|
1258
|
+
function stripSchemaPrefix(type) {
|
|
1259
|
+
return type.replace(SCHEMA_PREFIX, "");
|
|
1260
|
+
}
|
|
1261
|
+
function typesOf(value) {
|
|
1262
|
+
const raw = value["@type"];
|
|
1263
|
+
if (typeof raw === "string") return [stripSchemaPrefix(raw)];
|
|
1264
|
+
if (Array.isArray(raw)) {
|
|
1265
|
+
const out = [];
|
|
1266
|
+
for (const entry of raw) if (typeof entry === "string") out.push(stripSchemaPrefix(entry));
|
|
1267
|
+
return out;
|
|
1268
|
+
}
|
|
1269
|
+
return [];
|
|
1270
|
+
}
|
|
1271
|
+
var JSON_LD_MAX_DEPTH = 12;
|
|
1272
|
+
function collectNodes(value, offset, depth, out, seen) {
|
|
1273
|
+
if (depth > JSON_LD_MAX_DEPTH || value === null || typeof value !== "object") return;
|
|
1274
|
+
if (seen.has(value)) return;
|
|
1275
|
+
seen.add(value);
|
|
1276
|
+
if (Array.isArray(value)) {
|
|
1277
|
+
for (const entry of value) collectNodes(entry, offset, depth + 1, out, seen);
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
const record = value;
|
|
1281
|
+
const types = typesOf(record);
|
|
1282
|
+
if (types.length > 0) out.push({ types, value: record, offset });
|
|
1283
|
+
for (const [key, child] of Object.entries(record)) {
|
|
1284
|
+
if (key === "@context") continue;
|
|
1285
|
+
collectNodes(child, offset, depth + 1, out, seen);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
function parseJsonLd(blocks) {
|
|
1289
|
+
const nodes = [];
|
|
1290
|
+
let parsed = 0;
|
|
1291
|
+
for (const block of blocks) {
|
|
1292
|
+
let value;
|
|
1293
|
+
try {
|
|
1294
|
+
value = JSON.parse(block.text);
|
|
1295
|
+
} catch {
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
parsed++;
|
|
1299
|
+
collectNodes(value, block.offset, 0, nodes, /* @__PURE__ */ new Set());
|
|
1300
|
+
}
|
|
1301
|
+
return { nodes, blocks: blocks.length, parsed };
|
|
1302
|
+
}
|
|
1303
|
+
function readPath(node, path) {
|
|
1304
|
+
const segments = path.split(".");
|
|
1305
|
+
let frontier = [node.value];
|
|
1306
|
+
for (const segment of segments) {
|
|
1307
|
+
const next = [];
|
|
1308
|
+
for (const current of frontier) {
|
|
1309
|
+
if (current === null || typeof current !== "object") continue;
|
|
1310
|
+
if (Array.isArray(current)) {
|
|
1311
|
+
for (const entry of current) {
|
|
1312
|
+
if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
|
|
1313
|
+
const child2 = entry[segment];
|
|
1314
|
+
if (child2 !== void 0) next.push(child2);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
const child = current[segment];
|
|
1320
|
+
if (child !== void 0) next.push(child);
|
|
1321
|
+
}
|
|
1322
|
+
frontier = next;
|
|
1323
|
+
if (frontier.length === 0) return null;
|
|
1324
|
+
}
|
|
1325
|
+
for (const found of frontier) {
|
|
1326
|
+
const scalar = scalarOf(found);
|
|
1327
|
+
if (scalar !== null) return scalar;
|
|
1328
|
+
}
|
|
1329
|
+
return null;
|
|
1330
|
+
}
|
|
1331
|
+
function scalarOf(value) {
|
|
1332
|
+
if (typeof value === "string") return value.trim().length > 0 ? value.trim() : null;
|
|
1333
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
1334
|
+
if (typeof value === "boolean") return String(value);
|
|
1335
|
+
if (Array.isArray(value)) {
|
|
1336
|
+
for (const entry of value) {
|
|
1337
|
+
const scalar = scalarOf(entry);
|
|
1338
|
+
if (scalar !== null) return scalar;
|
|
1339
|
+
}
|
|
1340
|
+
return null;
|
|
1341
|
+
}
|
|
1342
|
+
if (value !== null && typeof value === "object") {
|
|
1343
|
+
const record = value;
|
|
1344
|
+
for (const key of ["name", "value", "@id", "url", "headline"]) {
|
|
1345
|
+
const scalar = scalarOf(record[key]);
|
|
1346
|
+
if (scalar !== null) return scalar;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
return null;
|
|
1350
|
+
}
|
|
1351
|
+
function hasPath(node, path) {
|
|
1352
|
+
return readPath(node, path) !== null;
|
|
1353
|
+
}
|
|
1354
|
+
function header(headers, name) {
|
|
1355
|
+
const values = headers[name];
|
|
1356
|
+
return values !== void 0 && values.length > 0 ? values[0] ?? null : null;
|
|
1357
|
+
}
|
|
1358
|
+
function headerAll(headers, name) {
|
|
1359
|
+
return headers[name] ?? [];
|
|
1360
|
+
}
|
|
1361
|
+
function mediaType(contentType) {
|
|
1362
|
+
if (contentType === null) return null;
|
|
1363
|
+
const semi = contentType.indexOf(";");
|
|
1364
|
+
const value = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
|
|
1365
|
+
return value.length > 0 ? value : null;
|
|
1366
|
+
}
|
|
1367
|
+
function classifyMediaType(type) {
|
|
1368
|
+
if (type === null) return "other";
|
|
1369
|
+
if (type === "text/html" || type === "application/xhtml+xml") return "html";
|
|
1370
|
+
if (type === "text/markdown" || type === "text/x-markdown") return "markdown";
|
|
1371
|
+
if (type === "text/plain") return "text";
|
|
1372
|
+
if (type === "application/json" || type === "application/ld+json" || type.endsWith("+json")) {
|
|
1373
|
+
return "json";
|
|
1374
|
+
}
|
|
1375
|
+
return "other";
|
|
1376
|
+
}
|
|
1377
|
+
function bodyLooksLikeHtml(body) {
|
|
1378
|
+
const head = body.slice(0, 1024).trimStart().toLowerCase();
|
|
1379
|
+
return head.startsWith("<!doctype html") || head.startsWith("<html") || head.startsWith("<?xml") ? true : head.includes("<html") || head.includes("<head>") || head.includes("<body");
|
|
1380
|
+
}
|
|
1381
|
+
function buildRepresentation(capture) {
|
|
1382
|
+
if (typeof capture.body !== "string") return null;
|
|
1383
|
+
const contentType = mediaType(header(capture.headers, "content-type"));
|
|
1384
|
+
const declared = classifyMediaType(contentType);
|
|
1385
|
+
const looksLikeHtml = bodyLooksLikeHtml(capture.body);
|
|
1386
|
+
const doc = declared === "html" || looksLikeHtml ? tokenizeHtml(capture.body) : null;
|
|
1387
|
+
const jsonLd = doc !== null ? parseJsonLd(doc.jsonLd.map((block) => ({ text: block.text, offset: block.offset }))) : declared === "json" ? parseJsonLd([{ text: capture.body, offset: 0 }]) : { nodes: [], blocks: 0, parsed: 0 };
|
|
1388
|
+
return {
|
|
1389
|
+
kind: declared,
|
|
1390
|
+
contentType,
|
|
1391
|
+
body: capture.body,
|
|
1392
|
+
bytes: capture.bytes,
|
|
1393
|
+
doc,
|
|
1394
|
+
jsonLd,
|
|
1395
|
+
text: doc !== null ? countedText(doc) : capture.body,
|
|
1396
|
+
looksLikeHtml,
|
|
1397
|
+
truncated: capture.truncated,
|
|
1398
|
+
finalUrl: capture.finalUrl,
|
|
1399
|
+
headers: capture.headers
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
var SOURCE_ORDER = [
|
|
1403
|
+
"json-ld",
|
|
1404
|
+
"microdata",
|
|
1405
|
+
"meta",
|
|
1406
|
+
"html-text",
|
|
1407
|
+
"negotiated"
|
|
1408
|
+
];
|
|
1409
|
+
var PRESENCE_FACTS = /* @__PURE__ */ new Set([
|
|
1410
|
+
"shipping",
|
|
1411
|
+
"returns",
|
|
1412
|
+
"hours",
|
|
1413
|
+
"service-area",
|
|
1414
|
+
"eligibility",
|
|
1415
|
+
"question-answer",
|
|
1416
|
+
"item-link"
|
|
1417
|
+
]);
|
|
1418
|
+
var DECLARED = "declared";
|
|
1419
|
+
function mergeFacts(primary, corroborating) {
|
|
1420
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
1421
|
+
for (const fact of primary) {
|
|
1422
|
+
const list = byKind.get(fact.kind);
|
|
1423
|
+
if (list === void 0) byKind.set(fact.kind, [fact]);
|
|
1424
|
+
else list.push(fact);
|
|
1425
|
+
}
|
|
1426
|
+
const merged = [];
|
|
1427
|
+
for (const [kind, observations] of byKind) {
|
|
1428
|
+
const representative = observations.reduce(
|
|
1429
|
+
(best, candidate) => betterObservation(best, candidate)
|
|
1430
|
+
);
|
|
1431
|
+
const sources = [];
|
|
1432
|
+
for (const fact of [...observations, ...corroborating]) {
|
|
1433
|
+
if (fact.kind !== kind) continue;
|
|
1434
|
+
if (fact.normalized !== representative.normalized) continue;
|
|
1435
|
+
if (!sources.includes(fact.source)) sources.push(fact.source);
|
|
1436
|
+
}
|
|
1437
|
+
merged.push({
|
|
1438
|
+
kind,
|
|
1439
|
+
normalized: representative.normalized,
|
|
1440
|
+
source: representative.source,
|
|
1441
|
+
offset: representative.offset,
|
|
1442
|
+
corroborated: sources.length >= 2,
|
|
1443
|
+
qualified: representative.qualified,
|
|
1444
|
+
sources
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
merged.sort((a, b) => a.offset === b.offset ? cmp(a.kind, b.kind) : a.offset - b.offset);
|
|
1448
|
+
return merged;
|
|
1449
|
+
}
|
|
1450
|
+
function betterObservation(a, b) {
|
|
1451
|
+
if (a.offset !== b.offset) return a.offset < b.offset ? a : b;
|
|
1452
|
+
const rank = SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source);
|
|
1453
|
+
if (rank !== 0) return rank < 0 ? a : b;
|
|
1454
|
+
return cmp(a.normalized, b.normalized) <= 0 ? a : b;
|
|
1455
|
+
}
|
|
1456
|
+
function cmp(a, b) {
|
|
1457
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1458
|
+
}
|
|
1459
|
+
var TITLE_SEPARATORS = [" | ", " \u2014 ", " \u2013 ", " \xB7 ", " :: ", " \xBB "];
|
|
1460
|
+
function normalizeTitle(text) {
|
|
1461
|
+
const collapsed = text.replace(/\s+/g, " ").trim();
|
|
1462
|
+
let cut = collapsed;
|
|
1463
|
+
for (const separator of TITLE_SEPARATORS) {
|
|
1464
|
+
const at = cut.indexOf(separator);
|
|
1465
|
+
if (at > 0) cut = cut.slice(0, at);
|
|
1466
|
+
}
|
|
1467
|
+
return cut.trim().toLowerCase();
|
|
1468
|
+
}
|
|
1469
|
+
var MAX_NORMALIZED_TEXT = 200;
|
|
1470
|
+
function normalizeText(text) {
|
|
1471
|
+
return text.replace(/\s+/g, " ").trim().toLowerCase().slice(0, MAX_NORMALIZED_TEXT);
|
|
1472
|
+
}
|
|
1473
|
+
function normalizeMoney(amount, currency) {
|
|
1474
|
+
return `${currency} ${amount}`;
|
|
1475
|
+
}
|
|
1476
|
+
function normalizeDate(text) {
|
|
1477
|
+
const trimmed = text.trim();
|
|
1478
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(trimmed);
|
|
1479
|
+
if (iso !== null) return `${iso[1]}-${iso[2]}-${iso[3]}`;
|
|
1480
|
+
const slashes = /^(\d{4})\/(\d{2})\/(\d{2})/.exec(trimmed);
|
|
1481
|
+
if (slashes !== null) return `${slashes[1]}-${slashes[2]}-${slashes[3]}`;
|
|
1482
|
+
const named = /^(\d{1,2}) ([A-Za-z]{3,9}) (\d{4})$/.exec(trimmed);
|
|
1483
|
+
if (named !== null) {
|
|
1484
|
+
const month = MONTHS.indexOf((named[2] ?? "").slice(0, 3).toLowerCase());
|
|
1485
|
+
if (month >= 0) return `${named[3]}-${pad2(month + 1)}-${pad2(Number(named[1]))}`;
|
|
1486
|
+
}
|
|
1487
|
+
const american = /^([A-Za-z]{3,9}) (\d{1,2}), (\d{4})$/.exec(trimmed);
|
|
1488
|
+
if (american !== null) {
|
|
1489
|
+
const month = MONTHS.indexOf((american[1] ?? "").slice(0, 3).toLowerCase());
|
|
1490
|
+
if (month >= 0) return `${american[3]}-${pad2(month + 1)}-${pad2(Number(american[2]))}`;
|
|
1491
|
+
}
|
|
1492
|
+
return null;
|
|
1493
|
+
}
|
|
1494
|
+
var MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
|
|
1495
|
+
function pad2(value) {
|
|
1496
|
+
return value < 10 ? `0${value}` : String(value);
|
|
1497
|
+
}
|
|
1498
|
+
var AVAILABILITY_TOKENS = [
|
|
1499
|
+
["limitedavailability", "limited"],
|
|
1500
|
+
["onlineonly", "instock"],
|
|
1501
|
+
["instoreonly", "instock"],
|
|
1502
|
+
["presale", "preorder"],
|
|
1503
|
+
["preorder", "preorder"],
|
|
1504
|
+
["backorder", "backorder"],
|
|
1505
|
+
["discontinued", "discontinued"],
|
|
1506
|
+
["soldout", "outofstock"],
|
|
1507
|
+
["outofstock", "outofstock"],
|
|
1508
|
+
["instock", "instock"]
|
|
1509
|
+
];
|
|
1510
|
+
var AVAILABILITY_PHRASES = [
|
|
1511
|
+
["limited availability", "limited"],
|
|
1512
|
+
["limited stock", "limited"],
|
|
1513
|
+
["currently unavailable", "outofstock"],
|
|
1514
|
+
["temporarily unavailable", "outofstock"],
|
|
1515
|
+
["out of stock", "outofstock"],
|
|
1516
|
+
["discontinued", "discontinued"],
|
|
1517
|
+
["back order", "backorder"],
|
|
1518
|
+
["backorder", "backorder"],
|
|
1519
|
+
["pre-order", "preorder"],
|
|
1520
|
+
["preorder", "preorder"],
|
|
1521
|
+
["sold out", "outofstock"],
|
|
1522
|
+
["in stock", "instock"],
|
|
1523
|
+
["available now", "instock"]
|
|
1524
|
+
];
|
|
1525
|
+
function normalizeAvailability(value) {
|
|
1526
|
+
const squashed = value.toLowerCase().replace(/[^a-z]/g, "");
|
|
1527
|
+
for (const [needle, token] of AVAILABILITY_TOKENS) {
|
|
1528
|
+
if (squashed.endsWith(needle) || squashed === needle) return token;
|
|
1529
|
+
}
|
|
1530
|
+
return null;
|
|
1531
|
+
}
|
|
1532
|
+
var NO_PUBLISHED_PRICE = [
|
|
1533
|
+
"price on request",
|
|
1534
|
+
"pricing on request",
|
|
1535
|
+
"price on application",
|
|
1536
|
+
"contact us for pricing",
|
|
1537
|
+
"contact for pricing",
|
|
1538
|
+
"contact us for a quote",
|
|
1539
|
+
"no published price",
|
|
1540
|
+
"pricing available on request"
|
|
1541
|
+
];
|
|
1542
|
+
var UNPRICED = "unpriced";
|
|
1543
|
+
function normalizePhone(value) {
|
|
1544
|
+
const trimmed = value.trim();
|
|
1545
|
+
const plus = trimmed.startsWith("+") || trimmed.startsWith("tel:+");
|
|
1546
|
+
const digits = trimmed.replace(/\D/g, "");
|
|
1547
|
+
if (digits.length < 7 || digits.length > 15) return null;
|
|
1548
|
+
return plus ? `+${digits}` : digits;
|
|
1549
|
+
}
|
|
1550
|
+
var CURRENCY_SYMBOLS = "$\u20AC\xA3\xA5\u20B9\u20A9\u20AA\u20AB\u20B4\u20A6\u20B1\u0E3F\u20BA";
|
|
1551
|
+
var DIGITS = "0123456789";
|
|
1552
|
+
var MONEY_SEPARATORS = ".,'\u2019 \xA0\u202F";
|
|
1553
|
+
var MONEY_PREFIX_QUALIFIERS = [
|
|
1554
|
+
"starting from",
|
|
1555
|
+
"starting at",
|
|
1556
|
+
"prices from",
|
|
1557
|
+
"priced from",
|
|
1558
|
+
"as little as",
|
|
1559
|
+
"as low as",
|
|
1560
|
+
"starts at",
|
|
1561
|
+
"from"
|
|
1562
|
+
];
|
|
1563
|
+
var RANGE_JOINERS = ["\u2014", "\u2013", "-", " to "];
|
|
1564
|
+
function findMoneyPhrases(text) {
|
|
1565
|
+
const found = [];
|
|
1566
|
+
const limit = Math.min(text.length, MAX_SCAN_CHARS);
|
|
1567
|
+
let i = 0;
|
|
1568
|
+
while (i < limit) {
|
|
1569
|
+
const spanEnd = readMoneySpan(text, i, limit);
|
|
1570
|
+
if (spanEnd === null) {
|
|
1571
|
+
i++;
|
|
1572
|
+
continue;
|
|
1573
|
+
}
|
|
1574
|
+
let start = i;
|
|
1575
|
+
let end = spanEnd;
|
|
1576
|
+
const before = text.slice(Math.max(0, start - 20), start).toLowerCase();
|
|
1577
|
+
for (const qualifier of MONEY_PREFIX_QUALIFIERS) {
|
|
1578
|
+
if (before.trimEnd().endsWith(qualifier)) {
|
|
1579
|
+
start = Math.max(0, start - (before.length - before.trimEnd().length) - qualifier.length);
|
|
1580
|
+
break;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
for (const joiner of RANGE_JOINERS) {
|
|
1584
|
+
const after = text.slice(end, end + joiner.length + 2);
|
|
1585
|
+
const at = after.indexOf(joiner);
|
|
1586
|
+
if (at === -1 || at > 1) continue;
|
|
1587
|
+
const secondStart = end + at + joiner.length;
|
|
1588
|
+
const secondEnd = readMoneySpan(text, skipSpaces(text, secondStart, limit), limit);
|
|
1589
|
+
if (secondEnd !== null) end = secondEnd;
|
|
1590
|
+
break;
|
|
1591
|
+
}
|
|
1592
|
+
found.push({ phrase: text.slice(start, end), index: start });
|
|
1593
|
+
i = end;
|
|
1594
|
+
}
|
|
1595
|
+
return found;
|
|
1596
|
+
}
|
|
1597
|
+
var MAX_SCAN_CHARS = 4e5;
|
|
1598
|
+
function skipSpaces(text, from, limit) {
|
|
1599
|
+
let i = from;
|
|
1600
|
+
while (i < limit && text.charAt(i) === " ") i++;
|
|
1601
|
+
return i;
|
|
1602
|
+
}
|
|
1603
|
+
function readMoneySpan(text, from, limit) {
|
|
1604
|
+
const char = text.charAt(from);
|
|
1605
|
+
if (CURRENCY_SYMBOLS.includes(char) && char !== "") {
|
|
1606
|
+
let i = from + 1;
|
|
1607
|
+
if (text.charAt(i) === " ") i++;
|
|
1608
|
+
if (!DIGITS.includes(text.charAt(i))) return null;
|
|
1609
|
+
return readNumberRun(text, i, limit);
|
|
1610
|
+
}
|
|
1611
|
+
if (DIGITS.includes(char)) {
|
|
1612
|
+
const previous = from > 0 ? text.charAt(from - 1) : "";
|
|
1613
|
+
if (DIGITS.includes(previous) || MONEY_SEPARATORS.includes(previous)) return null;
|
|
1614
|
+
const end = readNumberRun(text, from, limit);
|
|
1615
|
+
let i = end;
|
|
1616
|
+
if (text.charAt(i) === " ") i++;
|
|
1617
|
+
const symbol = text.charAt(i);
|
|
1618
|
+
if (CURRENCY_SYMBOLS.includes(symbol) && symbol !== "") return i + 1;
|
|
1619
|
+
const code = text.slice(i, i + 3);
|
|
1620
|
+
if (/^[A-Z]{3}$/.test(code) && !/[A-Za-z]/.test(text.charAt(i + 3))) return i + 3;
|
|
1621
|
+
return null;
|
|
1622
|
+
}
|
|
1623
|
+
if (/[A-Z]/.test(char) && from + 3 <= limit) {
|
|
1624
|
+
const code = text.slice(from, from + 3);
|
|
1625
|
+
if (!/^[A-Z]{3}$/.test(code)) return null;
|
|
1626
|
+
if (from > 0 && /[A-Za-z]/.test(text.charAt(from - 1))) return null;
|
|
1627
|
+
let i = from + 3;
|
|
1628
|
+
if (text.charAt(i) === " ") i++;
|
|
1629
|
+
if (!DIGITS.includes(text.charAt(i))) return null;
|
|
1630
|
+
return readNumberRun(text, i, limit);
|
|
1631
|
+
}
|
|
1632
|
+
return null;
|
|
1633
|
+
}
|
|
1634
|
+
function readNumberRun(text, from, limit) {
|
|
1635
|
+
let i = from;
|
|
1636
|
+
let end = from;
|
|
1637
|
+
while (i < limit) {
|
|
1638
|
+
const char = text.charAt(i);
|
|
1639
|
+
if (DIGITS.includes(char)) {
|
|
1640
|
+
i++;
|
|
1641
|
+
end = i;
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
if (MONEY_SEPARATORS.includes(char) && char !== "") {
|
|
1645
|
+
i++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
break;
|
|
1649
|
+
}
|
|
1650
|
+
return end;
|
|
1651
|
+
}
|
|
1652
|
+
var LABEL_LEXICON = [
|
|
1653
|
+
["price", "price"],
|
|
1654
|
+
["cost", "price"],
|
|
1655
|
+
["currency", "currency"],
|
|
1656
|
+
["availability", "availability"],
|
|
1657
|
+
["stock", "availability"],
|
|
1658
|
+
["brand", "brand"],
|
|
1659
|
+
["manufacturer", "brand"],
|
|
1660
|
+
["sku", "sku"],
|
|
1661
|
+
["item number", "sku"],
|
|
1662
|
+
["product code", "sku"],
|
|
1663
|
+
["mpn", "sku"],
|
|
1664
|
+
["shipping", "shipping"],
|
|
1665
|
+
["delivery", "shipping"],
|
|
1666
|
+
["returns", "returns"],
|
|
1667
|
+
["return policy", "returns"],
|
|
1668
|
+
["refunds", "returns"],
|
|
1669
|
+
["description", "description"],
|
|
1670
|
+
["summary", "description"],
|
|
1671
|
+
["updated", "updated"],
|
|
1672
|
+
["last updated", "updated"],
|
|
1673
|
+
["modified", "updated"],
|
|
1674
|
+
["published", "published"],
|
|
1675
|
+
["date published", "published"],
|
|
1676
|
+
["author", "author"],
|
|
1677
|
+
["written by", "author"],
|
|
1678
|
+
["publisher", "authority"],
|
|
1679
|
+
["organization", "org-name"],
|
|
1680
|
+
["organisation", "org-name"],
|
|
1681
|
+
["company", "org-name"],
|
|
1682
|
+
["business", "org-name"],
|
|
1683
|
+
["address", "address"],
|
|
1684
|
+
["location", "address"],
|
|
1685
|
+
["phone", "phone"],
|
|
1686
|
+
["telephone", "phone"],
|
|
1687
|
+
["tel", "phone"],
|
|
1688
|
+
["email", "email"],
|
|
1689
|
+
["e-mail", "email"],
|
|
1690
|
+
["hours", "hours"],
|
|
1691
|
+
["opening hours", "hours"],
|
|
1692
|
+
["duration", "duration"],
|
|
1693
|
+
["length", "duration"],
|
|
1694
|
+
["eligibility", "eligibility"],
|
|
1695
|
+
["requirements", "eligibility"],
|
|
1696
|
+
["section", "section"],
|
|
1697
|
+
["category", "section"],
|
|
1698
|
+
["topic", "section"],
|
|
1699
|
+
["service area", "service-area"],
|
|
1700
|
+
["areas served", "service-area"],
|
|
1701
|
+
["items", "item-count"],
|
|
1702
|
+
["item count", "item-count"]
|
|
1703
|
+
];
|
|
1704
|
+
function normalizeLabel(raw) {
|
|
1705
|
+
return raw.replace(/^[\s>*\-+#]+/, "").replace(/[*_`]/g, "").trim().toLowerCase();
|
|
1706
|
+
}
|
|
1707
|
+
function readLabelledLines(text) {
|
|
1708
|
+
const out = [];
|
|
1709
|
+
let cursor = 0;
|
|
1710
|
+
for (const line of text.split("\n")) {
|
|
1711
|
+
const lineStart = cursor;
|
|
1712
|
+
cursor += line.length + 1;
|
|
1713
|
+
const colon = line.indexOf(":");
|
|
1714
|
+
if (colon === -1 || colon > MAX_LABEL_CHARS) continue;
|
|
1715
|
+
const label = normalizeLabel(line.slice(0, colon));
|
|
1716
|
+
if (label.length === 0) continue;
|
|
1717
|
+
const value = line.slice(colon + 1).replace(/^[\s*_`]+/, "").trim();
|
|
1718
|
+
if (value.length === 0) continue;
|
|
1719
|
+
for (const [needle, kind] of LABEL_LEXICON) {
|
|
1720
|
+
if (label !== needle) continue;
|
|
1721
|
+
out.push({ kind, value, index: lineStart + colon + 1 });
|
|
1722
|
+
break;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
return out;
|
|
1726
|
+
}
|
|
1727
|
+
var MAX_LABEL_CHARS = 32;
|
|
1728
|
+
function wanted(profile) {
|
|
1729
|
+
return /* @__PURE__ */ new Set([...profile.core, ...profile.extended]);
|
|
1730
|
+
}
|
|
1731
|
+
function extractFacts(representation, context) {
|
|
1732
|
+
const facts = [];
|
|
1733
|
+
const want = wanted(context.profile);
|
|
1734
|
+
const push = (fact) => {
|
|
1735
|
+
if (want.has(fact.kind)) facts.push(fact);
|
|
1736
|
+
};
|
|
1737
|
+
for (const node of representation.jsonLd.nodes) extractFromJsonLd(node, context, push);
|
|
1738
|
+
if (representation.doc !== null) {
|
|
1739
|
+
extractFromHtml(representation.doc, context, push);
|
|
1740
|
+
} else {
|
|
1741
|
+
extractFromPlainText(representation, context, push);
|
|
1742
|
+
}
|
|
1743
|
+
return facts;
|
|
1744
|
+
}
|
|
1745
|
+
var JSON_LD_PATHS = [
|
|
1746
|
+
["title", ["name", "headline"]],
|
|
1747
|
+
["description", ["description", "abstract"]],
|
|
1748
|
+
["price", ["offers.price", "offers.lowPrice", "offers.priceSpecification.price", "price"]],
|
|
1749
|
+
["currency", ["offers.priceCurrency", "offers.priceSpecification.priceCurrency", "priceCurrency"]],
|
|
1750
|
+
["availability", ["offers.availability", "availability"]],
|
|
1751
|
+
["brand", ["brand"]],
|
|
1752
|
+
["sku", ["sku", "mpn", "gtin13", "gtin"]],
|
|
1753
|
+
["shipping", ["offers.shippingDetails", "shippingDetails"]],
|
|
1754
|
+
["returns", ["offers.hasMerchantReturnPolicy", "hasMerchantReturnPolicy"]],
|
|
1755
|
+
["org-name", ["name"]],
|
|
1756
|
+
["address", ["address"]],
|
|
1757
|
+
["hours", ["openingHours", "openingHoursSpecification"]],
|
|
1758
|
+
["phone", ["telephone", "contactPoint.telephone"]],
|
|
1759
|
+
["email", ["email", "contactPoint.email"]],
|
|
1760
|
+
["service-area", ["areaServed", "serviceArea"]],
|
|
1761
|
+
["author", ["author"]],
|
|
1762
|
+
["authority", ["publisher", "author"]],
|
|
1763
|
+
["section", ["articleSection", "genre"]],
|
|
1764
|
+
["published", ["datePublished", "dateCreated"]],
|
|
1765
|
+
["updated", ["dateModified"]],
|
|
1766
|
+
["duration", ["duration", "timeRequired"]],
|
|
1767
|
+
["eligibility", ["eligibleCustomerType", "audience"]],
|
|
1768
|
+
["primary-action-url", ["potentialAction.target", "potentialAction.url"]],
|
|
1769
|
+
["question-answer", ["mainEntity.acceptedAnswer"]],
|
|
1770
|
+
["item-count", ["numberOfItems"]],
|
|
1771
|
+
["item-link", ["itemListElement.url", "itemListElement.item"]]
|
|
1772
|
+
];
|
|
1773
|
+
var ORG_TYPES = /* @__PURE__ */ new Set([
|
|
1774
|
+
"Organization",
|
|
1775
|
+
"LocalBusiness",
|
|
1776
|
+
"Store",
|
|
1777
|
+
"Restaurant",
|
|
1778
|
+
"Corporation",
|
|
1779
|
+
"NGO",
|
|
1780
|
+
"GovernmentOrganization",
|
|
1781
|
+
"EducationalOrganization",
|
|
1782
|
+
"MedicalBusiness",
|
|
1783
|
+
"ProfessionalService",
|
|
1784
|
+
"FoodEstablishment",
|
|
1785
|
+
"LodgingBusiness",
|
|
1786
|
+
"AutomotiveBusiness",
|
|
1787
|
+
"HealthAndBeautyBusiness",
|
|
1788
|
+
"SportsActivityLocation",
|
|
1789
|
+
"Place"
|
|
1790
|
+
]);
|
|
1791
|
+
function extractFromJsonLd(node, context, push) {
|
|
1792
|
+
const isOrg = node.types.some((type) => ORG_TYPES.has(type));
|
|
1793
|
+
for (const [kind, paths] of JSON_LD_PATHS) {
|
|
1794
|
+
if (kind === "title" && isOrg) continue;
|
|
1795
|
+
if (kind === "org-name" && !isOrg) continue;
|
|
1796
|
+
for (const path of paths) {
|
|
1797
|
+
const raw = readPath(node, path);
|
|
1798
|
+
if (raw === null) continue;
|
|
1799
|
+
const normalized = normalizeFactValue(kind, raw, context);
|
|
1800
|
+
if (normalized === null) continue;
|
|
1801
|
+
push({ kind, normalized: normalized.value, source: "json-ld", offset: node.offset, qualified: normalized.qualified });
|
|
1802
|
+
break;
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
function normalizeFactValue(kind, raw, context) {
|
|
1807
|
+
if (PRESENCE_FACTS.has(kind)) return { value: DECLARED, qualified: false };
|
|
1808
|
+
switch (kind) {
|
|
1809
|
+
case "title":
|
|
1810
|
+
return raw.trim().length === 0 ? null : { value: normalizeTitle(raw), qualified: false };
|
|
1811
|
+
case "price": {
|
|
1812
|
+
const lowered = raw.trim().toLowerCase();
|
|
1813
|
+
if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {
|
|
1814
|
+
return { value: UNPRICED, qualified: false };
|
|
1815
|
+
}
|
|
1816
|
+
const money = parseMoneyText(raw, { currency: context.currencyHint });
|
|
1817
|
+
return money === null ? null : { value: normalizeMoney(money.amount, money.currency), qualified: money.qualified };
|
|
1818
|
+
}
|
|
1819
|
+
case "currency": {
|
|
1820
|
+
const code = raw.trim().toUpperCase();
|
|
1821
|
+
return /^[A-Z]{3}$/.test(code) ? { value: code, qualified: false } : null;
|
|
1822
|
+
}
|
|
1823
|
+
case "availability": {
|
|
1824
|
+
const token = normalizeAvailability(raw);
|
|
1825
|
+
return token === null ? null : { value: token, qualified: false };
|
|
1826
|
+
}
|
|
1827
|
+
case "phone": {
|
|
1828
|
+
const phone = normalizePhone(raw);
|
|
1829
|
+
return phone === null ? null : { value: phone, qualified: false };
|
|
1830
|
+
}
|
|
1831
|
+
case "email": {
|
|
1832
|
+
const email = raw.trim().replace(/^mailto:/i, "").toLowerCase();
|
|
1833
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? { value: email, qualified: false } : null;
|
|
1834
|
+
}
|
|
1835
|
+
case "published":
|
|
1836
|
+
case "updated": {
|
|
1837
|
+
const date = normalizeDate(raw);
|
|
1838
|
+
return date === null ? null : { value: date, qualified: false };
|
|
1839
|
+
}
|
|
1840
|
+
case "duration": {
|
|
1841
|
+
const minutes = normalizeDuration(raw);
|
|
1842
|
+
return minutes === null ? null : { value: minutes, qualified: false };
|
|
1843
|
+
}
|
|
1844
|
+
case "item-count": {
|
|
1845
|
+
const count = Number.parseInt(raw.replace(/[^0-9]/g, ""), 10);
|
|
1846
|
+
return Number.isFinite(count) && count > 0 ? { value: String(count), qualified: false } : null;
|
|
1847
|
+
}
|
|
1848
|
+
case "primary-action-url": {
|
|
1849
|
+
const absolute = absoluteUrl(raw, context.baseUrl);
|
|
1850
|
+
return absolute === null ? null : { value: absolute, qualified: false };
|
|
1851
|
+
}
|
|
1852
|
+
default:
|
|
1853
|
+
return raw.trim().length === 0 ? null : { value: normalizeText(raw), qualified: false };
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
function normalizeDuration(raw) {
|
|
1857
|
+
const iso = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?$/.exec(raw.trim().toUpperCase());
|
|
1858
|
+
if (iso !== null && (iso[1] ?? iso[2] ?? iso[3]) !== void 0) {
|
|
1859
|
+
const minutes = Number(iso[1] ?? 0) * 1440 + Number(iso[2] ?? 0) * 60 + Number(iso[3] ?? 0);
|
|
1860
|
+
return minutes > 0 ? String(minutes) : null;
|
|
1861
|
+
}
|
|
1862
|
+
const spoken = /^(\d{1,4})\s?(min|mins|minute|minutes|h|hr|hrs|hour|hours)\b/i.exec(raw.trim());
|
|
1863
|
+
if (spoken !== null) {
|
|
1864
|
+
const amount = Number(spoken[1]);
|
|
1865
|
+
const unit = (spoken[2] ?? "").toLowerCase();
|
|
1866
|
+
const minutes = unit.startsWith("h") ? amount * 60 : amount;
|
|
1867
|
+
return minutes > 0 ? String(minutes) : null;
|
|
1868
|
+
}
|
|
1869
|
+
return null;
|
|
1870
|
+
}
|
|
1871
|
+
function absoluteUrl(href, base) {
|
|
1872
|
+
try {
|
|
1873
|
+
return new URL(href, base).toString();
|
|
1874
|
+
} catch {
|
|
1875
|
+
return null;
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
var META_LEXICON = [
|
|
1879
|
+
["og:title", "title"],
|
|
1880
|
+
["twitter:title", "title"],
|
|
1881
|
+
["description", "description"],
|
|
1882
|
+
["og:description", "description"],
|
|
1883
|
+
["twitter:description", "description"],
|
|
1884
|
+
["og:price:amount", "price"],
|
|
1885
|
+
["product:price:amount", "price"],
|
|
1886
|
+
["og:price:currency", "currency"],
|
|
1887
|
+
["product:price:currency", "currency"],
|
|
1888
|
+
["og:availability", "availability"],
|
|
1889
|
+
["product:availability", "availability"],
|
|
1890
|
+
["product:brand", "brand"],
|
|
1891
|
+
["og:site_name", "org-name"],
|
|
1892
|
+
["author", "author"],
|
|
1893
|
+
["article:author", "author"],
|
|
1894
|
+
["article:published_time", "published"],
|
|
1895
|
+
["article:modified_time", "updated"],
|
|
1896
|
+
["article:section", "section"]
|
|
1897
|
+
];
|
|
1898
|
+
var ITEMPROP_LEXICON = [
|
|
1899
|
+
["name", "title"],
|
|
1900
|
+
["price", "price"],
|
|
1901
|
+
["pricecurrency", "currency"],
|
|
1902
|
+
["availability", "availability"],
|
|
1903
|
+
["brand", "brand"],
|
|
1904
|
+
["sku", "sku"],
|
|
1905
|
+
["description", "description"],
|
|
1906
|
+
["telephone", "phone"],
|
|
1907
|
+
["email", "email"],
|
|
1908
|
+
["address", "address"],
|
|
1909
|
+
["openinghours", "hours"],
|
|
1910
|
+
["author", "author"],
|
|
1911
|
+
["datepublished", "published"],
|
|
1912
|
+
["datemodified", "updated"],
|
|
1913
|
+
["articlesection", "section"]
|
|
1914
|
+
];
|
|
1915
|
+
function extractFromHtml(doc, context, push) {
|
|
1916
|
+
for (const element of doc.elements) {
|
|
1917
|
+
if (element.tag !== "title") continue;
|
|
1918
|
+
const text = elementText(doc, element.index);
|
|
1919
|
+
const normalized = normalizeFactValue("title", text, context);
|
|
1920
|
+
if (normalized !== null) {
|
|
1921
|
+
push({ kind: "title", normalized: normalized.value, source: "html-text", offset: element.offset, qualified: false });
|
|
1922
|
+
}
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
for (const element of doc.elements) {
|
|
1926
|
+
if (element.tag !== "h1" || element.excludedBy !== null) continue;
|
|
1927
|
+
const normalized = normalizeFactValue("title", elementText(doc, element.index), context);
|
|
1928
|
+
if (normalized !== null) {
|
|
1929
|
+
push({ kind: "title", normalized: normalized.value, source: "html-text", offset: element.offset, qualified: false });
|
|
1930
|
+
}
|
|
1931
|
+
break;
|
|
1932
|
+
}
|
|
1933
|
+
for (const meta of doc.metas) {
|
|
1934
|
+
if (meta.content === null) continue;
|
|
1935
|
+
const key = meta.property ?? meta.name;
|
|
1936
|
+
if (key === null) continue;
|
|
1937
|
+
for (const [needle, kind] of META_LEXICON) {
|
|
1938
|
+
if (key !== needle) continue;
|
|
1939
|
+
const normalized = normalizeFactValue(kind, meta.content, context);
|
|
1940
|
+
if (normalized !== null) {
|
|
1941
|
+
push({ kind, normalized: normalized.value, source: "meta", offset: meta.offset, qualified: normalized.qualified });
|
|
1942
|
+
}
|
|
1943
|
+
break;
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
for (const element of doc.elements) {
|
|
1947
|
+
const itemprop = attr(element, "itemprop");
|
|
1948
|
+
if (itemprop === null) continue;
|
|
1949
|
+
const key = itemprop.toLowerCase();
|
|
1950
|
+
for (const [needle, kind] of ITEMPROP_LEXICON) {
|
|
1951
|
+
if (key !== needle) continue;
|
|
1952
|
+
const raw = attr(element, "content") ?? attr(element, "datetime") ?? attr(element, "href") ?? elementText(doc, element.index);
|
|
1953
|
+
const normalized = normalizeFactValue(kind, raw, context);
|
|
1954
|
+
if (normalized !== null) {
|
|
1955
|
+
push({ kind, normalized: normalized.value, source: "microdata", offset: element.offset, qualified: normalized.qualified });
|
|
1956
|
+
}
|
|
1957
|
+
break;
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
extractVisibleText(doc, context, push);
|
|
1961
|
+
extractLinks(doc, context, push);
|
|
1962
|
+
extractStructures(doc, context, push);
|
|
1963
|
+
}
|
|
1964
|
+
function extractVisibleText(doc, context, push) {
|
|
1965
|
+
for (const node of doc.texts) {
|
|
1966
|
+
if (node.excludedBy !== null) continue;
|
|
1967
|
+
const text = node.text;
|
|
1968
|
+
if (text.trim().length === 0) continue;
|
|
1969
|
+
for (const money of findMoneyPhrases(text)) {
|
|
1970
|
+
const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint });
|
|
1971
|
+
if (parsed === null) continue;
|
|
1972
|
+
push({
|
|
1973
|
+
kind: "price",
|
|
1974
|
+
normalized: normalizeMoney(parsed.amount, parsed.currency),
|
|
1975
|
+
source: "html-text",
|
|
1976
|
+
offset: node.offset,
|
|
1977
|
+
qualified: parsed.qualified
|
|
1978
|
+
});
|
|
1979
|
+
push({
|
|
1980
|
+
kind: "currency",
|
|
1981
|
+
normalized: parsed.currency,
|
|
1982
|
+
source: "html-text",
|
|
1983
|
+
offset: node.offset,
|
|
1984
|
+
qualified: false
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
const lowered = text.toLowerCase();
|
|
1988
|
+
if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {
|
|
1989
|
+
push({ kind: "price", normalized: UNPRICED, source: "html-text", offset: node.offset, qualified: false });
|
|
1990
|
+
}
|
|
1991
|
+
for (const [phrase, token] of AVAILABILITY_PHRASES) {
|
|
1992
|
+
if (!lowered.includes(phrase)) continue;
|
|
1993
|
+
push({ kind: "availability", normalized: token, source: "html-text", offset: node.offset, qualified: false });
|
|
1994
|
+
break;
|
|
1995
|
+
}
|
|
1996
|
+
for (const [kind, marker] of TEXT_PRESENCE_MARKERS) {
|
|
1997
|
+
if (!marker.some((phrase) => lowered.includes(phrase))) continue;
|
|
1998
|
+
push({ kind, normalized: DECLARED, source: "html-text", offset: node.offset, qualified: false });
|
|
1999
|
+
}
|
|
2000
|
+
const sku = /\bsku[:\s]+([A-Za-z0-9][A-Za-z0-9._-]{2,31})\b/i.exec(text);
|
|
2001
|
+
if (sku !== null && sku[1] !== void 0) {
|
|
2002
|
+
push({ kind: "sku", normalized: normalizeText(sku[1]), source: "html-text", offset: node.offset, qualified: false });
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
for (const labelled of readLabelledLines(countedText(doc))) {
|
|
2006
|
+
const normalized = normalizeFactValue(labelled.kind, labelled.value, context);
|
|
2007
|
+
if (normalized === null) continue;
|
|
2008
|
+
push({
|
|
2009
|
+
kind: labelled.kind,
|
|
2010
|
+
normalized: normalized.value,
|
|
2011
|
+
source: "html-text",
|
|
2012
|
+
offset: firstTextOffset(doc),
|
|
2013
|
+
qualified: normalized.qualified
|
|
2014
|
+
});
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
var TEXT_PRESENCE_MARKERS = [
|
|
2018
|
+
["shipping", ["free shipping", "shipping", "ships in", "delivery", "ships free"]],
|
|
2019
|
+
["returns", ["return policy", "returns", "money-back", "money back", "refund"]],
|
|
2020
|
+
["service-area", ["areas served", "service area", "we serve", "serving"]],
|
|
2021
|
+
["eligibility", ["eligibility", "who can apply", "you must be", "requirements"]]
|
|
2022
|
+
];
|
|
2023
|
+
function firstTextOffset(doc) {
|
|
2024
|
+
for (const node of doc.texts) {
|
|
2025
|
+
if (node.excludedBy === null && node.text.trim().length > 0) return node.offset;
|
|
2026
|
+
}
|
|
2027
|
+
return 0;
|
|
2028
|
+
}
|
|
2029
|
+
var ACTION_MAX_TEXT_CHARS = 64;
|
|
2030
|
+
function extractLinks(doc, context, push) {
|
|
2031
|
+
const lexicon = context.ruleset.actionLexicon;
|
|
2032
|
+
for (const element of doc.elements) {
|
|
2033
|
+
if (element.excludedBy !== null) continue;
|
|
2034
|
+
if (element.tag === "a") {
|
|
2035
|
+
const href = attr(element, "href");
|
|
2036
|
+
if (href === null) continue;
|
|
2037
|
+
if (href.toLowerCase().startsWith("tel:")) {
|
|
2038
|
+
const phone = normalizePhone(href.slice(4));
|
|
2039
|
+
if (phone !== null) {
|
|
2040
|
+
push({ kind: "phone", normalized: phone, source: "html-text", offset: element.offset, qualified: false });
|
|
2041
|
+
}
|
|
2042
|
+
continue;
|
|
2043
|
+
}
|
|
2044
|
+
if (href.toLowerCase().startsWith("mailto:")) {
|
|
2045
|
+
const normalized = normalizeFactValue("email", href, context);
|
|
2046
|
+
if (normalized !== null) {
|
|
2047
|
+
push({ kind: "email", normalized: normalized.value, source: "html-text", offset: element.offset, qualified: false });
|
|
2048
|
+
}
|
|
2049
|
+
continue;
|
|
2050
|
+
}
|
|
2051
|
+
const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS);
|
|
2052
|
+
if (!matchesLexicon(text, lexicon)) continue;
|
|
2053
|
+
const absolute = absoluteUrl(href, context.baseUrl);
|
|
2054
|
+
if (absolute === null) continue;
|
|
2055
|
+
push({ kind: "primary-action-url", normalized: absolute, source: "html-text", offset: element.offset, qualified: false });
|
|
2056
|
+
continue;
|
|
2057
|
+
}
|
|
2058
|
+
if (element.tag === "form") {
|
|
2059
|
+
const action = attr(element, "action");
|
|
2060
|
+
if (action === null) continue;
|
|
2061
|
+
const text = elementText(doc, element.index).slice(0, ACTION_MAX_TEXT_CHARS);
|
|
2062
|
+
if (!matchesLexicon(text, lexicon)) continue;
|
|
2063
|
+
const absolute = absoluteUrl(action, context.baseUrl);
|
|
2064
|
+
if (absolute === null) continue;
|
|
2065
|
+
push({ kind: "primary-action-url", normalized: absolute, source: "html-text", offset: element.offset, qualified: false });
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
const items = largestRepeatedLinkBlock(doc, context.origin);
|
|
2069
|
+
if (items.count > 0) {
|
|
2070
|
+
push({ kind: "item-count", normalized: String(items.count), source: "html-text", offset: items.offset, qualified: false });
|
|
2071
|
+
if (items.sameOrigin) {
|
|
2072
|
+
push({ kind: "item-link", normalized: DECLARED, source: "html-text", offset: items.offset, qualified: false });
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
function matchesLexicon(text, lexicon) {
|
|
2077
|
+
const normalized = text.replace(/\s+/g, " ").trim().toLowerCase();
|
|
2078
|
+
if (normalized.length === 0) return false;
|
|
2079
|
+
for (const phrase of lexicon) {
|
|
2080
|
+
if (normalized === phrase) return true;
|
|
2081
|
+
if (normalized.startsWith(`${phrase} `)) return true;
|
|
2082
|
+
}
|
|
2083
|
+
return false;
|
|
2084
|
+
}
|
|
2085
|
+
function largestRepeatedLinkBlock(doc, origin) {
|
|
2086
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2087
|
+
for (const element of doc.elements) {
|
|
2088
|
+
if (element.tag !== "a" || element.excludedBy !== null) continue;
|
|
2089
|
+
const href = attr(element, "href");
|
|
2090
|
+
if (href === null || href.startsWith("#")) continue;
|
|
2091
|
+
const parent = element.parent >= 0 ? doc.elements[element.parent] : void 0;
|
|
2092
|
+
const container = parent !== void 0 && parent.parent >= 0 ? parent.parent : element.parent;
|
|
2093
|
+
if (container < 0) continue;
|
|
2094
|
+
if (isInsideChrome(doc, container)) continue;
|
|
2095
|
+
const absolute = absoluteUrl(href, origin);
|
|
2096
|
+
if (absolute === null) continue;
|
|
2097
|
+
const group = groups.get(container) ?? {
|
|
2098
|
+
hrefs: /* @__PURE__ */ new Set(),
|
|
2099
|
+
sameOrigin: 0,
|
|
2100
|
+
offset: doc.elements[container]?.offset ?? 0
|
|
2101
|
+
};
|
|
2102
|
+
if (!group.hrefs.has(absolute)) {
|
|
2103
|
+
group.hrefs.add(absolute);
|
|
2104
|
+
if (absolute.startsWith(origin)) group.sameOrigin++;
|
|
2105
|
+
}
|
|
2106
|
+
groups.set(container, group);
|
|
2107
|
+
}
|
|
2108
|
+
let best = { count: 0, offset: 0, sameOrigin: false };
|
|
2109
|
+
for (const [, group] of groups) {
|
|
2110
|
+
if (group.hrefs.size <= best.count) continue;
|
|
2111
|
+
best = {
|
|
2112
|
+
count: group.hrefs.size,
|
|
2113
|
+
offset: group.offset,
|
|
2114
|
+
sameOrigin: group.sameOrigin * 2 >= group.hrefs.size
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
return best.count >= MIN_REPEATED_ITEMS ? best : { count: 0, offset: 0, sameOrigin: false };
|
|
2118
|
+
}
|
|
2119
|
+
var MIN_REPEATED_ITEMS = 3;
|
|
2120
|
+
var CHROME_TAGS = /* @__PURE__ */ new Set(["nav", "header", "footer"]);
|
|
2121
|
+
function isInsideChrome(doc, from) {
|
|
2122
|
+
let current = from;
|
|
2123
|
+
for (let hops = 0; hops < 64 && current >= 0; hops++) {
|
|
2124
|
+
const element = doc.elements[current];
|
|
2125
|
+
if (element === void 0) return false;
|
|
2126
|
+
if (CHROME_TAGS.has(element.tag)) return true;
|
|
2127
|
+
if (element.attrs["role"] === "navigation" || element.attrs["role"] === "banner") return true;
|
|
2128
|
+
current = element.parent;
|
|
2129
|
+
}
|
|
2130
|
+
return false;
|
|
2131
|
+
}
|
|
2132
|
+
var DAY_NAMES = [
|
|
2133
|
+
"monday",
|
|
2134
|
+
"tuesday",
|
|
2135
|
+
"wednesday",
|
|
2136
|
+
"thursday",
|
|
2137
|
+
"friday",
|
|
2138
|
+
"saturday",
|
|
2139
|
+
"sunday",
|
|
2140
|
+
"mon",
|
|
2141
|
+
"tue",
|
|
2142
|
+
"wed",
|
|
2143
|
+
"thu",
|
|
2144
|
+
"fri",
|
|
2145
|
+
"sat",
|
|
2146
|
+
"sun"
|
|
2147
|
+
];
|
|
2148
|
+
function hasOpeningHoursShape(text) {
|
|
2149
|
+
const lowered = text.toLowerCase();
|
|
2150
|
+
for (const day of DAY_NAMES) {
|
|
2151
|
+
let at = lowered.indexOf(day);
|
|
2152
|
+
while (at !== -1) {
|
|
2153
|
+
const window = lowered.slice(at, at + 40);
|
|
2154
|
+
if (/\d{1,2}[:.]\d{2}/.test(window) || /\d{1,2}\s?(am|pm)/.test(window)) return true;
|
|
2155
|
+
at = lowered.indexOf(day, at + day.length);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
return false;
|
|
2159
|
+
}
|
|
2160
|
+
function extractStructures(doc, context, push) {
|
|
2161
|
+
for (const node of doc.texts) {
|
|
2162
|
+
if (node.excludedBy !== null) continue;
|
|
2163
|
+
if (!hasOpeningHoursShape(node.text)) continue;
|
|
2164
|
+
push({ kind: "hours", normalized: DECLARED, source: "html-text", offset: node.offset, qualified: false });
|
|
2165
|
+
break;
|
|
2166
|
+
}
|
|
2167
|
+
for (const element of doc.elements) {
|
|
2168
|
+
if (element.excludedBy !== null) continue;
|
|
2169
|
+
if (element.tag === "address") {
|
|
2170
|
+
const normalized = normalizeFactValue("address", elementText(doc, element.index), context);
|
|
2171
|
+
if (normalized !== null) {
|
|
2172
|
+
push({ kind: "address", normalized: normalized.value, source: "html-text", offset: element.offset, qualified: false });
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
const qa = firstQuestionAnswer(doc);
|
|
2177
|
+
if (qa !== null) {
|
|
2178
|
+
push({ kind: "question-answer", normalized: DECLARED, source: "html-text", offset: qa, qualified: false });
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
var HEADING_TAGS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
|
|
2182
|
+
function firstQuestionAnswer(doc) {
|
|
2183
|
+
let sawDt = false;
|
|
2184
|
+
let pendingQuestionHeading = false;
|
|
2185
|
+
for (const element of doc.elements) {
|
|
2186
|
+
if (element.excludedBy !== null) continue;
|
|
2187
|
+
if (element.tag === "dt") {
|
|
2188
|
+
sawDt = true;
|
|
2189
|
+
continue;
|
|
2190
|
+
}
|
|
2191
|
+
if (element.tag === "dd" && sawDt) return element.offset;
|
|
2192
|
+
if (element.tag === "details") {
|
|
2193
|
+
for (const child of doc.elements) {
|
|
2194
|
+
if (child.parent === element.index && child.tag === "summary") return element.offset;
|
|
2195
|
+
}
|
|
2196
|
+
continue;
|
|
2197
|
+
}
|
|
2198
|
+
if (HEADING_TAGS.has(element.tag)) {
|
|
2199
|
+
pendingQuestionHeading = elementText(doc, element.index).trim().endsWith("?");
|
|
2200
|
+
continue;
|
|
2201
|
+
}
|
|
2202
|
+
if (element.tag === "p" && pendingQuestionHeading) return element.offset;
|
|
2203
|
+
}
|
|
2204
|
+
return null;
|
|
2205
|
+
}
|
|
2206
|
+
var MARKDOWN_LINK_RE = /\[([^\]\n]{1,120})\]\(([^)\s]{1,500})\)/g;
|
|
2207
|
+
function extractFromPlainText(representation, context, push) {
|
|
2208
|
+
const body = representation.body;
|
|
2209
|
+
const offsetOf = (index) => utf8Length(body.slice(0, index));
|
|
2210
|
+
const heading = /^#{1,6}[ \t]+(.+)$/m.exec(body);
|
|
2211
|
+
if (heading !== null && heading[1] !== void 0) {
|
|
2212
|
+
const linked = /^\[([^\]]+)\]\([^)]*\)\s*$/.exec(heading[1].trim());
|
|
2213
|
+
const raw = linked !== null && linked[1] !== void 0 ? linked[1] : heading[1];
|
|
2214
|
+
const normalized = normalizeFactValue("title", raw, context);
|
|
2215
|
+
if (normalized !== null) {
|
|
2216
|
+
push({ kind: "title", normalized: normalized.value, source: "negotiated", offset: offsetOf(heading.index), qualified: false });
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
for (const labelled of readLabelledLines(body)) {
|
|
2220
|
+
const normalized = normalizeFactValue(labelled.kind, labelled.value, context);
|
|
2221
|
+
if (normalized === null) continue;
|
|
2222
|
+
push({ kind: labelled.kind, normalized: normalized.value, source: "negotiated", offset: offsetOf(labelled.index), qualified: normalized.qualified });
|
|
2223
|
+
if (labelled.kind === "price" && normalized.value !== UNPRICED) {
|
|
2224
|
+
const code = normalized.value.slice(0, 3);
|
|
2225
|
+
push({ kind: "currency", normalized: code, source: "negotiated", offset: offsetOf(labelled.index), qualified: false });
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
for (const money of findMoneyPhrases(body)) {
|
|
2229
|
+
const parsed = parseMoneyText(money.phrase, { currency: context.currencyHint });
|
|
2230
|
+
if (parsed === null) continue;
|
|
2231
|
+
push({ kind: "price", normalized: normalizeMoney(parsed.amount, parsed.currency), source: "negotiated", offset: offsetOf(money.index), qualified: parsed.qualified });
|
|
2232
|
+
push({ kind: "currency", normalized: parsed.currency, source: "negotiated", offset: offsetOf(money.index), qualified: false });
|
|
2233
|
+
}
|
|
2234
|
+
const lowered = body.toLowerCase();
|
|
2235
|
+
if (NO_PUBLISHED_PRICE.some((phrase) => lowered.includes(phrase))) {
|
|
2236
|
+
push({ kind: "price", normalized: UNPRICED, source: "negotiated", offset: 0, qualified: false });
|
|
2237
|
+
}
|
|
2238
|
+
for (const [phrase, token] of AVAILABILITY_PHRASES) {
|
|
2239
|
+
const at = lowered.indexOf(phrase);
|
|
2240
|
+
if (at === -1) continue;
|
|
2241
|
+
push({ kind: "availability", normalized: token, source: "negotiated", offset: offsetOf(at), qualified: false });
|
|
2242
|
+
break;
|
|
2243
|
+
}
|
|
2244
|
+
for (const [kind, markers] of TEXT_PRESENCE_MARKERS) {
|
|
2245
|
+
for (const phrase of markers) {
|
|
2246
|
+
const at = lowered.indexOf(phrase);
|
|
2247
|
+
if (at === -1) continue;
|
|
2248
|
+
push({ kind, normalized: DECLARED, source: "negotiated", offset: offsetOf(at), qualified: false });
|
|
2249
|
+
break;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
if (hasOpeningHoursShape(body)) {
|
|
2253
|
+
push({ kind: "hours", normalized: DECLARED, source: "negotiated", offset: 0, qualified: false });
|
|
2254
|
+
}
|
|
2255
|
+
const itemLinks = /* @__PURE__ */ new Set();
|
|
2256
|
+
let firstItemOffset = 0;
|
|
2257
|
+
let match;
|
|
2258
|
+
MARKDOWN_LINK_RE.lastIndex = 0;
|
|
2259
|
+
while ((match = MARKDOWN_LINK_RE.exec(body)) !== null) {
|
|
2260
|
+
const text = match[1] ?? "";
|
|
2261
|
+
const href = match[2] ?? "";
|
|
2262
|
+
const absolute = absoluteUrl(href, context.baseUrl);
|
|
2263
|
+
if (absolute === null) continue;
|
|
2264
|
+
if (matchesLexicon(text, context.ruleset.actionLexicon)) {
|
|
2265
|
+
push({ kind: "primary-action-url", normalized: absolute, source: "negotiated", offset: offsetOf(match.index), qualified: false });
|
|
2266
|
+
}
|
|
2267
|
+
if (absolute.startsWith(context.origin) && !itemLinks.has(absolute)) {
|
|
2268
|
+
if (itemLinks.size === 0) firstItemOffset = offsetOf(match.index);
|
|
2269
|
+
itemLinks.add(absolute);
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
if (itemLinks.size >= MIN_REPEATED_ITEMS) {
|
|
2273
|
+
push({ kind: "item-count", normalized: String(itemLinks.size), source: "negotiated", offset: firstItemOffset, qualified: false });
|
|
2274
|
+
push({ kind: "item-link", normalized: DECLARED, source: "negotiated", offset: firstItemOffset, qualified: false });
|
|
2275
|
+
}
|
|
2276
|
+
const question = /^#{1,6}[ \t]+.*\?[ \t]*$/m.exec(body);
|
|
2277
|
+
if (question !== null) {
|
|
2278
|
+
push({ kind: "question-answer", normalized: DECLARED, source: "negotiated", offset: offsetOf(question.index), qualified: false });
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
function parseRobots(text) {
|
|
2282
|
+
const groups = [];
|
|
2283
|
+
const sitemaps = [];
|
|
2284
|
+
let malformedLines = 0;
|
|
2285
|
+
let orphanRules = 0;
|
|
2286
|
+
let current = null;
|
|
2287
|
+
let openingGroup = false;
|
|
2288
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
2289
|
+
const withoutComment = rawLine.split("#")[0] ?? "";
|
|
2290
|
+
const line = withoutComment.trim();
|
|
2291
|
+
if (line.length === 0) continue;
|
|
2292
|
+
const colon = line.indexOf(":");
|
|
2293
|
+
if (colon <= 0) {
|
|
2294
|
+
malformedLines++;
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
const field = line.slice(0, colon).trim().toLowerCase();
|
|
2298
|
+
const value = line.slice(colon + 1).trim();
|
|
2299
|
+
if (field === "user-agent") {
|
|
2300
|
+
if (current === null || !openingGroup) {
|
|
2301
|
+
current = { agents: [], allow: [], disallow: [] };
|
|
2302
|
+
groups.push(current);
|
|
2303
|
+
openingGroup = true;
|
|
2304
|
+
}
|
|
2305
|
+
current.agents.push(value.toLowerCase());
|
|
2306
|
+
continue;
|
|
2307
|
+
}
|
|
2308
|
+
if (field === "sitemap") {
|
|
2309
|
+
sitemaps.push(value);
|
|
2310
|
+
continue;
|
|
2311
|
+
}
|
|
2312
|
+
if (field === "allow" || field === "disallow") {
|
|
2313
|
+
if (current === null) {
|
|
2314
|
+
orphanRules++;
|
|
2315
|
+
continue;
|
|
2316
|
+
}
|
|
2317
|
+
openingGroup = false;
|
|
2318
|
+
if (field === "allow") current.allow.push(value);
|
|
2319
|
+
else current.disallow.push(value);
|
|
2320
|
+
continue;
|
|
2321
|
+
}
|
|
2322
|
+
if (field === "crawl-delay" || field === "host" || field === "clean-param") continue;
|
|
2323
|
+
malformedLines++;
|
|
2324
|
+
}
|
|
2325
|
+
return { groups, sitemaps, malformedLines, orphanRules };
|
|
2326
|
+
}
|
|
2327
|
+
function decideRobots(robots, tokens, path) {
|
|
2328
|
+
let bestGroup = null;
|
|
2329
|
+
let bestAgent = null;
|
|
2330
|
+
let bestSpecificity = -1;
|
|
2331
|
+
for (const group of robots.groups) {
|
|
2332
|
+
for (const agent of group.agents) {
|
|
2333
|
+
const specificity = agent === "*" ? 0 : matchesToken(agent, tokens) ? agent.length : -1;
|
|
2334
|
+
if (specificity > bestSpecificity) {
|
|
2335
|
+
bestSpecificity = specificity;
|
|
2336
|
+
bestGroup = group;
|
|
2337
|
+
bestAgent = agent;
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
if (bestGroup === null || bestAgent === null) {
|
|
2342
|
+
return { decision: "unspecified", matchedGroup: null, matchedRule: null };
|
|
2343
|
+
}
|
|
2344
|
+
let bestRule = null;
|
|
2345
|
+
for (const value of bestGroup.allow) {
|
|
2346
|
+
if (!pathMatches(value, path)) continue;
|
|
2347
|
+
if (bestRule === null || value.length > bestRule.value.length) {
|
|
2348
|
+
bestRule = { field: "allow", value };
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
for (const value of bestGroup.disallow) {
|
|
2352
|
+
if (!pathMatches(value, path)) continue;
|
|
2353
|
+
if (bestRule === null || value.length > bestRule.value.length) {
|
|
2354
|
+
bestRule = { field: "disallow", value };
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
if (bestRule === null) {
|
|
2358
|
+
return { decision: "allow", matchedGroup: bestAgent, matchedRule: null };
|
|
2359
|
+
}
|
|
2360
|
+
return {
|
|
2361
|
+
decision: bestRule.field === "allow" ? "allow" : "disallow",
|
|
2362
|
+
matchedGroup: bestAgent,
|
|
2363
|
+
matchedRule: `${bestRule.field === "allow" ? "Allow" : "Disallow"}: ${bestRule.value}`
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
function matchesToken(agent, tokens) {
|
|
2367
|
+
const lowered = agent.toLowerCase();
|
|
2368
|
+
return tokens.some((token) => token.toLowerCase() === lowered);
|
|
2369
|
+
}
|
|
2370
|
+
function pathMatches(pattern, path) {
|
|
2371
|
+
if (pattern === "") return false;
|
|
2372
|
+
const anchored = pattern.endsWith("$");
|
|
2373
|
+
const body = anchored ? pattern.slice(0, -1) : pattern;
|
|
2374
|
+
const segments = body.split("*");
|
|
2375
|
+
let cursor = 0;
|
|
2376
|
+
for (let i = 0; i < segments.length; i++) {
|
|
2377
|
+
const segment = segments[i] ?? "";
|
|
2378
|
+
if (i === 0) {
|
|
2379
|
+
if (!path.startsWith(segment)) return false;
|
|
2380
|
+
cursor = segment.length;
|
|
2381
|
+
continue;
|
|
2382
|
+
}
|
|
2383
|
+
if (segment === "") continue;
|
|
2384
|
+
const at = path.indexOf(segment, cursor);
|
|
2385
|
+
if (at === -1) return false;
|
|
2386
|
+
cursor = at + segment.length;
|
|
2387
|
+
}
|
|
2388
|
+
if (anchored) {
|
|
2389
|
+
const last = segments[segments.length - 1] ?? "";
|
|
2390
|
+
return segments.length === 1 ? path === body : path.endsWith(last);
|
|
2391
|
+
}
|
|
2392
|
+
return true;
|
|
2393
|
+
}
|
|
2394
|
+
function buildPolicyReport(robots, status, ruleset, path) {
|
|
2395
|
+
const empty = { decision: "unspecified", matchedGroup: null, matchedRule: null };
|
|
2396
|
+
const audiences = {
|
|
2397
|
+
assistant: empty,
|
|
2398
|
+
training: empty,
|
|
2399
|
+
search: empty
|
|
2400
|
+
};
|
|
2401
|
+
if (robots !== null) {
|
|
2402
|
+
for (const audience of ["assistant", "training", "search"]) {
|
|
2403
|
+
audiences[audience] = decideRobots(robots, ruleset.audienceTokens[audience], path);
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
return {
|
|
2407
|
+
robotsTxtStatus: status,
|
|
2408
|
+
audiences,
|
|
2409
|
+
// A deliberate opt-out requires a group that NAMES an assistant token.
|
|
2410
|
+
// Consent has to be specific: a blanket `User-agent: *` disallow is the
|
|
2411
|
+
// accidental case (§3.7) and is scored, not excused.
|
|
2412
|
+
deliberateOptOut: robots !== null && audiences.assistant.decision === "disallow" && audiences.assistant.matchedGroup !== "*" && robots.malformedLines === 0 && robots.orphanRules === 0,
|
|
2413
|
+
trainingOptOut: audiences.training.decision === "disallow",
|
|
2414
|
+
sitemapDeclared: robots !== null && robots.sitemaps.length > 0
|
|
2415
|
+
};
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
// src/classify.ts
|
|
2419
|
+
function pass1Signals(representation, targetUrl) {
|
|
2420
|
+
const jsonLdTypes = [];
|
|
2421
|
+
let hasTelephone = false;
|
|
2422
|
+
for (const node of representation.jsonLd.nodes) {
|
|
2423
|
+
for (const type of node.types) jsonLdTypes.push(type);
|
|
2424
|
+
if (typeof node.value["telephone"] === "string") hasTelephone = true;
|
|
2425
|
+
}
|
|
2426
|
+
const microdataTypes = [];
|
|
2427
|
+
const rdfaTypes = [];
|
|
2428
|
+
if (representation.doc !== null) {
|
|
2429
|
+
for (const element of representation.doc.elements) {
|
|
2430
|
+
const itemtype = attr(element, "itemtype");
|
|
2431
|
+
if (itemtype !== null) {
|
|
2432
|
+
for (const token of itemtype.split(/\s+/)) {
|
|
2433
|
+
const segment = token.split("/").pop();
|
|
2434
|
+
if (segment !== void 0 && segment.length > 0) microdataTypes.push(segment);
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
const typeOf = attr(element, "typeof");
|
|
2438
|
+
if (typeOf !== null) {
|
|
2439
|
+
for (const token of typeOf.split(/\s+/)) {
|
|
2440
|
+
const segment = token.split(/[/:]/).pop();
|
|
2441
|
+
if (segment !== void 0 && segment.length > 0) rdfaTypes.push(segment);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
if (element.tag === "a") {
|
|
2445
|
+
const href = attr(element, "href");
|
|
2446
|
+
if (href !== null && href.toLowerCase().startsWith("tel:")) hasTelephone = true;
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
let ogType = null;
|
|
2451
|
+
if (representation.doc !== null) {
|
|
2452
|
+
for (const meta of representation.doc.metas) {
|
|
2453
|
+
if (meta.property === "og:type" && meta.content !== null) {
|
|
2454
|
+
ogType = meta.content.trim().toLowerCase();
|
|
2455
|
+
break;
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
const text = representation.text;
|
|
2460
|
+
let hasCurrencyToken = false;
|
|
2461
|
+
for (const money of findMoneyPhrases(text)) {
|
|
2462
|
+
if (parseMoneyText(money.phrase) !== null) {
|
|
2463
|
+
hasCurrencyToken = true;
|
|
2464
|
+
break;
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
if (!hasTelephone) hasTelephone = /\btel:\+?[0-9()\-. ]{7,}/.test(text);
|
|
2468
|
+
return {
|
|
2469
|
+
jsonLdTypes,
|
|
2470
|
+
microdataTypes,
|
|
2471
|
+
rdfaTypes,
|
|
2472
|
+
ogType,
|
|
2473
|
+
pathSegments: pathSegmentsOf(targetUrl),
|
|
2474
|
+
hasCurrencyToken,
|
|
2475
|
+
hasOpeningHours: hasOpeningHoursShape(text),
|
|
2476
|
+
hasTelephone
|
|
2477
|
+
};
|
|
2478
|
+
}
|
|
2479
|
+
function pathSegmentsOf(url) {
|
|
2480
|
+
const absolute = absoluteUrl(url, "https://invalid.example/");
|
|
2481
|
+
if (absolute === null) return [];
|
|
2482
|
+
try {
|
|
2483
|
+
return new URL(absolute).pathname.toLowerCase().split("/").filter((segment) => segment.length > 0);
|
|
2484
|
+
} catch {
|
|
2485
|
+
return [];
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
var TYPE_TO_KIND = {
|
|
2489
|
+
// product
|
|
2490
|
+
Product: "product",
|
|
2491
|
+
ProductGroup: "product",
|
|
2492
|
+
ProductModel: "product",
|
|
2493
|
+
IndividualProduct: "product",
|
|
2494
|
+
SomeProducts: "product",
|
|
2495
|
+
Vehicle: "product",
|
|
2496
|
+
Car: "product",
|
|
2497
|
+
Book: "product",
|
|
2498
|
+
SoftwareApplication: "product",
|
|
2499
|
+
MobileApplication: "product",
|
|
2500
|
+
WebApplication: "product",
|
|
2501
|
+
// collection
|
|
2502
|
+
CollectionPage: "collection",
|
|
2503
|
+
ItemList: "collection",
|
|
2504
|
+
OfferCatalog: "collection",
|
|
2505
|
+
SearchResultsPage: "collection",
|
|
2506
|
+
// article
|
|
2507
|
+
Article: "article",
|
|
2508
|
+
NewsArticle: "article",
|
|
2509
|
+
BlogPosting: "article",
|
|
2510
|
+
TechArticle: "article",
|
|
2511
|
+
ScholarlyArticle: "article",
|
|
2512
|
+
ReportageNewsArticle: "article",
|
|
2513
|
+
LiveBlogPosting: "article",
|
|
2514
|
+
Blog: "article",
|
|
2515
|
+
// place
|
|
2516
|
+
Place: "place",
|
|
2517
|
+
LocalBusiness: "place",
|
|
2518
|
+
Store: "place",
|
|
2519
|
+
Restaurant: "place",
|
|
2520
|
+
Hotel: "place",
|
|
2521
|
+
LodgingBusiness: "place",
|
|
2522
|
+
FoodEstablishment: "place",
|
|
2523
|
+
CafeOrCoffeeShop: "place",
|
|
2524
|
+
MedicalBusiness: "place",
|
|
2525
|
+
MedicalClinic: "place",
|
|
2526
|
+
Dentist: "place",
|
|
2527
|
+
ProfessionalService: "place",
|
|
2528
|
+
AutomotiveBusiness: "place",
|
|
2529
|
+
HealthAndBeautyBusiness: "place",
|
|
2530
|
+
HairSalon: "place",
|
|
2531
|
+
SportsActivityLocation: "place",
|
|
2532
|
+
ExerciseGym: "place",
|
|
2533
|
+
// service
|
|
2534
|
+
Service: "service",
|
|
2535
|
+
GovernmentService: "service",
|
|
2536
|
+
FinancialProduct: "service",
|
|
2537
|
+
LoanOrCredit: "service",
|
|
2538
|
+
InsuranceAgency: "service",
|
|
2539
|
+
Course: "service",
|
|
2540
|
+
Event: "service",
|
|
2541
|
+
BusinessEvent: "service",
|
|
2542
|
+
EducationEvent: "service",
|
|
2543
|
+
// faq
|
|
2544
|
+
FAQPage: "faq",
|
|
2545
|
+
QAPage: "faq",
|
|
2546
|
+
// document
|
|
2547
|
+
Dataset: "document",
|
|
2548
|
+
DataCatalog: "document",
|
|
2549
|
+
DigitalDocument: "document",
|
|
2550
|
+
TextDigitalDocument: "document",
|
|
2551
|
+
APIReference: "document",
|
|
2552
|
+
WebAPI: "document",
|
|
2553
|
+
Legislation: "document",
|
|
2554
|
+
HowTo: "document",
|
|
2555
|
+
Report: "document",
|
|
2556
|
+
Manuscript: "document"
|
|
2557
|
+
};
|
|
2558
|
+
var RECOGNISED_ONLY = /* @__PURE__ */ new Set([
|
|
2559
|
+
"Thing",
|
|
2560
|
+
"WebPage",
|
|
2561
|
+
"WebSite",
|
|
2562
|
+
"AboutPage",
|
|
2563
|
+
"ContactPage",
|
|
2564
|
+
"ProfilePage",
|
|
2565
|
+
"ItemPage",
|
|
2566
|
+
"Organization",
|
|
2567
|
+
"Corporation",
|
|
2568
|
+
"NGO",
|
|
2569
|
+
"GovernmentOrganization",
|
|
2570
|
+
"EducationalOrganization",
|
|
2571
|
+
"Person",
|
|
2572
|
+
"BreadcrumbList",
|
|
2573
|
+
"Offer",
|
|
2574
|
+
"AggregateOffer",
|
|
2575
|
+
"PostalAddress",
|
|
2576
|
+
"ImageObject",
|
|
2577
|
+
"VideoObject",
|
|
2578
|
+
"SiteNavigationElement",
|
|
2579
|
+
"Brand",
|
|
2580
|
+
"Review",
|
|
2581
|
+
"AggregateRating",
|
|
2582
|
+
"Question",
|
|
2583
|
+
"Answer",
|
|
2584
|
+
"MerchantReturnPolicy",
|
|
2585
|
+
"OfferShippingDetails",
|
|
2586
|
+
"SearchAction",
|
|
2587
|
+
"ReadAction",
|
|
2588
|
+
"OrderAction"
|
|
2589
|
+
]);
|
|
2590
|
+
function isRecognisedType(type) {
|
|
2591
|
+
return TYPE_TO_KIND[type] !== void 0 || RECOGNISED_ONLY.has(type);
|
|
2592
|
+
}
|
|
2593
|
+
function kindForType(type) {
|
|
2594
|
+
return TYPE_TO_KIND[type] ?? null;
|
|
2595
|
+
}
|
|
2596
|
+
function nodeForKind(nodes, kind) {
|
|
2597
|
+
for (const node of nodes) {
|
|
2598
|
+
for (const type of node.types) {
|
|
2599
|
+
if (kindForType(type) === kind) return node;
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
return null;
|
|
2603
|
+
}
|
|
2604
|
+
var OG_TYPE_TO_KIND = {
|
|
2605
|
+
product: "product",
|
|
2606
|
+
"product.group": "product",
|
|
2607
|
+
"product.item": "product",
|
|
2608
|
+
"og:product": "product",
|
|
2609
|
+
article: "article",
|
|
2610
|
+
"article:published_time": "article",
|
|
2611
|
+
blog: "article",
|
|
2612
|
+
book: "product",
|
|
2613
|
+
place: "place",
|
|
2614
|
+
business: "place",
|
|
2615
|
+
"business.business": "place",
|
|
2616
|
+
restaurant: "place",
|
|
2617
|
+
"restaurant.restaurant": "place",
|
|
2618
|
+
profile: "unknown",
|
|
2619
|
+
website: "unknown"
|
|
2620
|
+
};
|
|
2621
|
+
var PATH_PATTERNS = [
|
|
2622
|
+
["product", ["products", "product", "p", "item", "items", "dp", "sku", "buy"]],
|
|
2623
|
+
["collection", ["collections", "collection", "category", "categories", "catalog", "c", "shop"]],
|
|
2624
|
+
["article", ["blog", "blogs", "news", "article", "articles", "post", "posts", "stories"]],
|
|
2625
|
+
["place", ["locations", "location", "stores", "store-locator", "branches", "find-us", "visit"]],
|
|
2626
|
+
["service", ["services", "service", "book", "booking", "appointments", "pricing", "plans"]],
|
|
2627
|
+
["faq", ["faq", "faqs", "questions", "help"]],
|
|
2628
|
+
["document", ["docs", "documentation", "reference", "guide", "guides", "manual", "api", "policies", "legal", "terms", "privacy"]]
|
|
2629
|
+
];
|
|
2630
|
+
function classify(signals) {
|
|
2631
|
+
const hasRecognisedType = signals.jsonLdTypes.some(isRecognisedType) || signals.microdataTypes.some(isRecognisedType) || signals.rdfaTypes.some(isRecognisedType);
|
|
2632
|
+
const fromJsonLd = firstMappedType(signals.jsonLdTypes);
|
|
2633
|
+
if (fromJsonLd !== null) {
|
|
2634
|
+
return {
|
|
2635
|
+
pageKind: fromJsonLd.kind,
|
|
2636
|
+
confidence: "high",
|
|
2637
|
+
signal: `json-ld @type ${fromJsonLd.type}`,
|
|
2638
|
+
hasRecognisedType
|
|
2639
|
+
};
|
|
2640
|
+
}
|
|
2641
|
+
const fromMicrodata = firstMappedType(signals.microdataTypes);
|
|
2642
|
+
if (fromMicrodata !== null) {
|
|
2643
|
+
return {
|
|
2644
|
+
pageKind: fromMicrodata.kind,
|
|
2645
|
+
confidence: "high",
|
|
2646
|
+
signal: `microdata itemtype ${fromMicrodata.type}`,
|
|
2647
|
+
hasRecognisedType
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
const fromRdfa = firstMappedType(signals.rdfaTypes);
|
|
2651
|
+
if (fromRdfa !== null) {
|
|
2652
|
+
return {
|
|
2653
|
+
pageKind: fromRdfa.kind,
|
|
2654
|
+
confidence: "high",
|
|
2655
|
+
signal: `rdfa typeof ${fromRdfa.type}`,
|
|
2656
|
+
hasRecognisedType
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
if (signals.ogType !== null) {
|
|
2660
|
+
const kind = OG_TYPE_TO_KIND[signals.ogType];
|
|
2661
|
+
if (kind !== void 0 && kind !== "unknown") {
|
|
2662
|
+
return {
|
|
2663
|
+
pageKind: kind,
|
|
2664
|
+
confidence: "medium",
|
|
2665
|
+
signal: `og:type ${signals.ogType}`,
|
|
2666
|
+
hasRecognisedType
|
|
2667
|
+
};
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
for (const [kind, patterns] of PATH_PATTERNS) {
|
|
2671
|
+
for (const segment of signals.pathSegments) {
|
|
2672
|
+
if (!patterns.includes(segment)) continue;
|
|
2673
|
+
return {
|
|
2674
|
+
pageKind: kind,
|
|
2675
|
+
confidence: "medium",
|
|
2676
|
+
signal: `url path segment /${segment}/`,
|
|
2677
|
+
hasRecognisedType
|
|
2678
|
+
};
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
if (signals.hasOpeningHours && signals.hasTelephone) {
|
|
2682
|
+
return {
|
|
2683
|
+
pageKind: "place",
|
|
2684
|
+
confidence: "medium",
|
|
2685
|
+
signal: "opening-hours shape and telephone present",
|
|
2686
|
+
hasRecognisedType
|
|
2687
|
+
};
|
|
2688
|
+
}
|
|
2689
|
+
return {
|
|
2690
|
+
pageKind: "unknown",
|
|
2691
|
+
confidence: "low",
|
|
2692
|
+
signal: signals.hasCurrencyToken ? "currency token only \u2014 below medium confidence, not classified" : "no classifying signal",
|
|
2693
|
+
hasRecognisedType
|
|
2694
|
+
};
|
|
2695
|
+
}
|
|
2696
|
+
function firstMappedType(types) {
|
|
2697
|
+
const mapped = [];
|
|
2698
|
+
for (const type of types) {
|
|
2699
|
+
const kind = kindForType(type);
|
|
2700
|
+
if (kind !== null) mapped.push({ type, kind });
|
|
2701
|
+
}
|
|
2702
|
+
if (mapped.length === 0) return null;
|
|
2703
|
+
const first = mapped[0];
|
|
2704
|
+
if (first === void 0) return null;
|
|
2705
|
+
let winner = first;
|
|
2706
|
+
for (const candidate of mapped) {
|
|
2707
|
+
if (candidate.kind !== first.kind) break;
|
|
2708
|
+
if (candidate.type < winner.type) winner = candidate;
|
|
2709
|
+
}
|
|
2710
|
+
return winner;
|
|
2711
|
+
}
|
|
2712
|
+
|
|
2713
|
+
// src/recommend.ts
|
|
2714
|
+
var NO_UNLOCKS = () => [];
|
|
2715
|
+
var TEMPLATES = [
|
|
2716
|
+
{
|
|
2717
|
+
id: "fix-robots-policy",
|
|
2718
|
+
title: "Let assistant crawlers fetch this page",
|
|
2719
|
+
effort: "config",
|
|
2720
|
+
detail: "robots.txt currently blocks or ambiguously blocks the crawlers that fetch pages on a user's behalf. Name them in their own group and allow them. Blocking model-training crawlers is a separate decision and costs nothing in ARS.",
|
|
2721
|
+
checks: ["retrievability.robots-policy"],
|
|
2722
|
+
unlocks: NO_UNLOCKS
|
|
2723
|
+
},
|
|
2724
|
+
{
|
|
2725
|
+
id: "render-without-javascript",
|
|
2726
|
+
title: "Put the core facts in the HTML the server sends",
|
|
2727
|
+
effort: "engineering",
|
|
2728
|
+
detail: "The facts for this page kind were not all present in the served HTML. Agents do not execute JavaScript: server-render the core facts, or ship them in a <noscript> block or structured data.",
|
|
2729
|
+
checks: ["retrievability.render-independence"],
|
|
2730
|
+
unlocks: NO_UNLOCKS
|
|
2731
|
+
},
|
|
2732
|
+
{
|
|
2733
|
+
id: "serve-machine-representation",
|
|
2734
|
+
title: "Serve a machine representation on Accept negotiation",
|
|
2735
|
+
effort: "config",
|
|
2736
|
+
detail: "Return Markdown, plain text or JSON with a matching Content-Type when the request asks for one, and keep the same URL. This is the single largest recoverable block in ARS, and it is also what makes Vary: Accept and the substance-parity check scoreable at all.",
|
|
2737
|
+
checks: ["machine-representation.negotiated-response"],
|
|
2738
|
+
unlocks: (state) => earnedOf(state, "machine-representation.negotiated-response") === 0 ? ["machine-representation.vary-accept", "machine-representation.substance-parity"] : []
|
|
2739
|
+
},
|
|
2740
|
+
{
|
|
2741
|
+
id: "declare-alternates",
|
|
2742
|
+
title: "Declare the alternate representation",
|
|
2743
|
+
effort: "config",
|
|
2744
|
+
detail: 'Add `Link: <\u2026>; rel="alternate"; type="text/markdown"` or a typed `<link rel="alternate">`. An endpoint an agent cannot find is an endpoint that does not exist.',
|
|
2745
|
+
checks: ["machine-representation.declared-alternates"],
|
|
2746
|
+
unlocks: NO_UNLOCKS
|
|
2747
|
+
},
|
|
2748
|
+
{
|
|
2749
|
+
id: "declare-vary-accept",
|
|
2750
|
+
title: "Send Vary: Accept",
|
|
2751
|
+
effort: "config",
|
|
2752
|
+
detail: "A URL that returns different representations by Accept must say so, or a shared cache will hand the Markdown to a browser and the HTML to an agent.",
|
|
2753
|
+
checks: ["machine-representation.vary-accept"],
|
|
2754
|
+
unlocks: NO_UNLOCKS
|
|
2755
|
+
},
|
|
2756
|
+
{
|
|
2757
|
+
id: "resolve-substance-divergence",
|
|
2758
|
+
title: "Make both representations state the same values",
|
|
2759
|
+
effort: "engineering",
|
|
2760
|
+
detail: "The two representations reported different values for a core fact. Render both from one source of truth. ARS reports what each one said and does not assert which is correct.",
|
|
2761
|
+
checks: ["machine-representation.substance-parity"],
|
|
2762
|
+
unlocks: NO_UNLOCKS
|
|
2763
|
+
},
|
|
2764
|
+
{
|
|
2765
|
+
id: "add-core-facts",
|
|
2766
|
+
title: "State the missing core facts for this page kind",
|
|
2767
|
+
effort: "template",
|
|
2768
|
+
detail: "Coverage is scored against the fact set this kind of page is expected to carry, and only against that set \u2014 adding facts outside it earns nothing. A fact stated in two places (structured data and visible text) counts double.",
|
|
2769
|
+
checks: ["fact-coverage.core-facts"],
|
|
2770
|
+
unlocks: (state) => (
|
|
2771
|
+
// Position can only be scored once something is there to position. While
|
|
2772
|
+
// no core fact exists, D4's points are reachable through this and nothing
|
|
2773
|
+
// else; once one exists, "front-load the core facts" owns them.
|
|
2774
|
+
earnedOf(state, "fact-position.first-core-fact-offset") === 0 && earnedOf(state, "fact-position.front-window") === 0 ? ["fact-position.first-core-fact-offset", "fact-position.front-window"] : []
|
|
2775
|
+
)
|
|
2776
|
+
},
|
|
2777
|
+
{
|
|
2778
|
+
id: "reduce-page-weight",
|
|
2779
|
+
title: "Cut the bytes an agent has to read",
|
|
2780
|
+
effort: "engineering",
|
|
2781
|
+
detail: "Context cost is scored against what a page of this kind reasonably costs, not an absolute budget. The cheapest fix is usually to serve a machine representation rather than to shrink the HTML.",
|
|
2782
|
+
checks: ["fact-coverage.context-cost"],
|
|
2783
|
+
unlocks: NO_UNLOCKS
|
|
2784
|
+
},
|
|
2785
|
+
{
|
|
2786
|
+
id: "front-load-core-facts",
|
|
2787
|
+
title: "Move the core facts to the front",
|
|
2788
|
+
effort: "template",
|
|
2789
|
+
detail: "A caller that reads the first few kilobytes should already have the facts. Everything after the front window costs a full read of the document.",
|
|
2790
|
+
checks: ["fact-position.first-core-fact-offset", "fact-position.front-window"],
|
|
2791
|
+
unlocks: NO_UNLOCKS
|
|
2792
|
+
},
|
|
2793
|
+
{
|
|
2794
|
+
id: "add-structured-data",
|
|
2795
|
+
title: "Add JSON-LD for this page",
|
|
2796
|
+
effort: "template",
|
|
2797
|
+
detail: 'Declare a schema.org type in a JSON-LD block. Choosing no type does not avoid the check: an unrecognised page is still scored against "any recognised type present".',
|
|
2798
|
+
checks: ["structured-data.present"],
|
|
2799
|
+
unlocks: (state) => earnedOf(state, "structured-data.present") === 0 ? ["structured-data.required-properties", "structured-data.text-agreement"] : []
|
|
2800
|
+
},
|
|
2801
|
+
{
|
|
2802
|
+
id: "complete-required-properties",
|
|
2803
|
+
title: "Complete the required properties for this page kind",
|
|
2804
|
+
effort: "template",
|
|
2805
|
+
detail: 'The required-property table is published per page kind in the spec. It is not "schema.org validity" \u2014 schema.org defines no required properties \u2014 and it does not change without an ARS release.',
|
|
2806
|
+
checks: ["structured-data.required-properties"],
|
|
2807
|
+
unlocks: NO_UNLOCKS
|
|
2808
|
+
},
|
|
2809
|
+
{
|
|
2810
|
+
id: "align-structured-data-with-text",
|
|
2811
|
+
title: "Make the structured data agree with the page",
|
|
2812
|
+
effort: "template",
|
|
2813
|
+
detail: "The JSON-LD and the visible page reported different values for a core fact. Generate both from the same source so they cannot drift.",
|
|
2814
|
+
checks: ["structured-data.text-agreement"],
|
|
2815
|
+
unlocks: NO_UNLOCKS
|
|
2816
|
+
},
|
|
2817
|
+
{
|
|
2818
|
+
id: "declare-canonical",
|
|
2819
|
+
title: "Declare one canonical URL, in both representations",
|
|
2820
|
+
effort: "config",
|
|
2821
|
+
detail: 'Add an absolute `<link rel="canonical">` to the HTML and a `Link: <\u2026>; rel="canonical"` header to the machine representation, pointing at the same URL. A representation with no canonical cannot be attributed to a page.',
|
|
2822
|
+
checks: ["contract-discovery.canonical"],
|
|
2823
|
+
unlocks: NO_UNLOCKS
|
|
2824
|
+
},
|
|
2825
|
+
{
|
|
2826
|
+
id: "add-cache-validators",
|
|
2827
|
+
title: "Add cache headers an agent can act on",
|
|
2828
|
+
effort: "config",
|
|
2829
|
+
detail: "Send a Cache-Control a cache can use plus an ETag or Last-Modified. Repeat fetches are most of agent traffic, and a response with no validator has to be re-read in full every time.",
|
|
2830
|
+
checks: ["contract-discovery.cache-validators"],
|
|
2831
|
+
unlocks: NO_UNLOCKS
|
|
2832
|
+
},
|
|
2833
|
+
{
|
|
2834
|
+
id: "publish-llms-txt",
|
|
2835
|
+
title: "Publish /llms.txt",
|
|
2836
|
+
effort: "config",
|
|
2837
|
+
detail: "An H1 title, a short summary, and links to the pages that matter. It is worth 2 points of 100, deliberately: content negotiation is the mechanism that measurably improves retrieval, and we have observed no citation lift from llms.txt alone.",
|
|
2838
|
+
checks: ["contract-discovery.llms-txt"],
|
|
2839
|
+
unlocks: NO_UNLOCKS
|
|
2840
|
+
},
|
|
2841
|
+
{
|
|
2842
|
+
id: "declare-sitemap",
|
|
2843
|
+
title: "Declare a sitemap in robots.txt",
|
|
2844
|
+
effort: "config",
|
|
2845
|
+
detail: "Add a `Sitemap:` line. It is the one place an agent looks to find the rest of the site.",
|
|
2846
|
+
checks: ["contract-discovery.sitemap"],
|
|
2847
|
+
unlocks: NO_UNLOCKS
|
|
2848
|
+
},
|
|
2849
|
+
{
|
|
2850
|
+
id: "declare-machine-endpoint",
|
|
2851
|
+
title: "Declare a machine endpoint",
|
|
2852
|
+
effort: "engineering",
|
|
2853
|
+
detail: "A feed, an OpenAPI document, /.well-known/ucp \u2014 anything an agent can call \u2014 declared with a `Link` header or a `<link>`. ARS probes /robots.txt, /llms.txt and /.well-known/ucp and guesses at no other path.",
|
|
2854
|
+
checks: ["contract-discovery.machine-endpoint"],
|
|
2855
|
+
unlocks: NO_UNLOCKS
|
|
2856
|
+
}
|
|
2857
|
+
];
|
|
2858
|
+
var EFFORT_ORDER = ["config", "template", "engineering"];
|
|
2859
|
+
function earnedOf(state, id) {
|
|
2860
|
+
return state.get(id)?.earned ?? 0;
|
|
2861
|
+
}
|
|
2862
|
+
function gapOf(state, id) {
|
|
2863
|
+
const check = state.get(id);
|
|
2864
|
+
return check === void 0 ? 0 : Math.max(0, check.weight - check.earned);
|
|
2865
|
+
}
|
|
2866
|
+
function recommend(input) {
|
|
2867
|
+
if (input.score === null) return [];
|
|
2868
|
+
const state = /* @__PURE__ */ new Map();
|
|
2869
|
+
const dimensionOf = /* @__PURE__ */ new Map();
|
|
2870
|
+
for (const dimension of input.dimensions) {
|
|
2871
|
+
for (const check of dimension.checks) {
|
|
2872
|
+
state.set(check.id, check);
|
|
2873
|
+
dimensionOf.set(check.id, dimension);
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
const ranked = TEMPLATES.map((template, index) => {
|
|
2877
|
+
const own = template.checks.reduce((sum, id) => sum + gapOf(state, id), 0);
|
|
2878
|
+
const unlocked = own > 0 ? template.unlocks(state) : [];
|
|
2879
|
+
const ids = [...template.checks, ...unlocked];
|
|
2880
|
+
const raw = own + unlocked.reduce((sum, id) => sum + gapOf(state, id), 0);
|
|
2881
|
+
return { template, ids, raw, index };
|
|
2882
|
+
}).filter((entry) => entry.raw > 0).sort((a, b) => {
|
|
2883
|
+
if (a.raw !== b.raw) return b.raw - a.raw;
|
|
2884
|
+
const effort = EFFORT_ORDER.indexOf(a.template.effort) - EFFORT_ORDER.indexOf(b.template.effort);
|
|
2885
|
+
return effort !== 0 ? effort : a.index - b.index;
|
|
2886
|
+
});
|
|
2887
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
2888
|
+
const spent = /* @__PURE__ */ new Map();
|
|
2889
|
+
const out = [];
|
|
2890
|
+
for (const entry of ranked) {
|
|
2891
|
+
let points = 0;
|
|
2892
|
+
const closes = [];
|
|
2893
|
+
const opens = [];
|
|
2894
|
+
for (const id of entry.ids) {
|
|
2895
|
+
if (claimed.has(id)) continue;
|
|
2896
|
+
const dimension = dimensionOf.get(id);
|
|
2897
|
+
if (dimension === void 0) continue;
|
|
2898
|
+
const remaining = Math.max(
|
|
2899
|
+
0,
|
|
2900
|
+
dimension.weight - dimension.earned - (spent.get(dimension.id) ?? 0)
|
|
2901
|
+
);
|
|
2902
|
+
const value = Math.min(gapOf(state, id), remaining);
|
|
2903
|
+
if (value <= 0) continue;
|
|
2904
|
+
points += value;
|
|
2905
|
+
spent.set(dimension.id, (spent.get(dimension.id) ?? 0) + value);
|
|
2906
|
+
claimed.add(id);
|
|
2907
|
+
if (entry.template.checks.includes(id)) closes.push(id);
|
|
2908
|
+
else opens.push(id);
|
|
2909
|
+
}
|
|
2910
|
+
if (points <= 0) continue;
|
|
2911
|
+
out.push({
|
|
2912
|
+
id: entry.template.id,
|
|
2913
|
+
title: entry.template.title,
|
|
2914
|
+
pointsAvailable: points,
|
|
2915
|
+
effort: entry.template.effort,
|
|
2916
|
+
detail: entry.template.detail,
|
|
2917
|
+
checks: closes,
|
|
2918
|
+
unlocks: opens
|
|
2919
|
+
});
|
|
2920
|
+
}
|
|
2921
|
+
return out;
|
|
2922
|
+
}
|
|
2923
|
+
|
|
2924
|
+
// src/score.ts
|
|
2925
|
+
function idiv(numerator, denominator) {
|
|
2926
|
+
if (denominator === 0) return 0;
|
|
2927
|
+
return (numerator - numerator % denominator) / denominator;
|
|
2928
|
+
}
|
|
2929
|
+
function divRoundHalfUp(numerator, denominator) {
|
|
2930
|
+
if (denominator === 0) return 0;
|
|
2931
|
+
return idiv(numerator + idiv(denominator, 2), denominator);
|
|
2932
|
+
}
|
|
2933
|
+
function atLeast(pairs, input) {
|
|
2934
|
+
if (pairs === void 0) return 0;
|
|
2935
|
+
for (let i = 0; i + 1 < pairs.length; i += 2) {
|
|
2936
|
+
const threshold = pairs[i];
|
|
2937
|
+
const value = pairs[i + 1];
|
|
2938
|
+
if (threshold === void 0 || value === void 0) return 0;
|
|
2939
|
+
if (input >= threshold) return value;
|
|
2940
|
+
}
|
|
2941
|
+
return 0;
|
|
2942
|
+
}
|
|
2943
|
+
function atMost(pairs, input) {
|
|
2944
|
+
if (pairs === void 0) return 0;
|
|
2945
|
+
for (let i = 0; i + 1 < pairs.length; i += 2) {
|
|
2946
|
+
const threshold = pairs[i];
|
|
2947
|
+
const value = pairs[i + 1];
|
|
2948
|
+
if (threshold === void 0 || value === void 0) return 0;
|
|
2949
|
+
if (input <= threshold) return value;
|
|
2950
|
+
}
|
|
2951
|
+
return 0;
|
|
2952
|
+
}
|
|
2953
|
+
function deepFreeze2(value) {
|
|
2954
|
+
if (typeof value !== "object" || value === null) return value;
|
|
2955
|
+
for (const child of Object.values(value)) deepFreeze2(child);
|
|
2956
|
+
return Object.freeze(value);
|
|
2957
|
+
}
|
|
2958
|
+
var SUBPOINTS = deepFreeze2({
|
|
2959
|
+
/** D1.1, 8 = 4 + 2 + 2. */
|
|
2960
|
+
reachable: { status2xx: 4, withinRedirectLimit: 2, noAcceptConditionalRedirect: 2 },
|
|
2961
|
+
/** D1.2, 6 = 3 + 1 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */
|
|
2962
|
+
robotsPolicy: { assistantAllowed: 3, parsesClean: 1, noOrphanRules: 1, sitemapDeclared: 1 },
|
|
2963
|
+
/**
|
|
2964
|
+
* D1.3, 6. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus
|
|
2965
|
+
* the `<noscript>` floor: a page whose facts are all client-rendered but which
|
|
2966
|
+
* ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8
|
|
2967
|
+
* says that earns partial credit.
|
|
2968
|
+
*/
|
|
2969
|
+
renderIndependence: {
|
|
2970
|
+
band: [100, 6, 75, 5, 50, 3, 25, 1],
|
|
2971
|
+
noscriptFloor: 1
|
|
2972
|
+
},
|
|
2973
|
+
/** D2.1, 10. All-or-nothing: a machine media type AND a body that is not HTML. */
|
|
2974
|
+
negotiatedResponse: { full: 10 },
|
|
2975
|
+
/** D2.2, 4. All-or-nothing. */
|
|
2976
|
+
declaredAlternates: { full: 4 },
|
|
2977
|
+
/** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
|
|
2978
|
+
varyAccept: { full: 3 },
|
|
2979
|
+
/** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */
|
|
2980
|
+
substanceParity: { full: 3 },
|
|
2981
|
+
/** D5.1, 5. Structured data present AND parsing; a partly-broken graph scores 3. */
|
|
2982
|
+
structuredDataPresent: { clean: 5, partial: 3 },
|
|
2983
|
+
/** D5.2, 7 = 2 (a recognised type) + 5 (required-property completeness, scaled). */
|
|
2984
|
+
requiredProperties: { recognisedType: 2, completeness: 5 },
|
|
2985
|
+
/** D5.3, 3. All-or-nothing. */
|
|
2986
|
+
textAgreement: { full: 3 },
|
|
2987
|
+
/** D6.1, 4 = 2 + 1 + 1. */
|
|
2988
|
+
canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },
|
|
2989
|
+
/** D6.2, 3 = 2 + 1. */
|
|
2990
|
+
cacheValidators: { saneCacheControl: 2, validator: 1 },
|
|
2991
|
+
/** D6.3, 2. `present` alone for a file that exists; `specShaped` for one that parses as llms.txt. */
|
|
2992
|
+
llmsTxt: { present: 1, specShaped: 2 },
|
|
2993
|
+
/** D6.4, 2. All-or-nothing. */
|
|
2994
|
+
sitemap: { full: 2 },
|
|
2995
|
+
/** D6.5, 4. All-or-nothing over any ONE declared machine endpoint. */
|
|
2996
|
+
machineEndpoint: { full: 4 }
|
|
2997
|
+
});
|
|
2998
|
+
var SHA256_K = [
|
|
2999
|
+
1116352408,
|
|
3000
|
+
1899447441,
|
|
3001
|
+
3049323471,
|
|
3002
|
+
3921009573,
|
|
3003
|
+
961987163,
|
|
3004
|
+
1508970993,
|
|
3005
|
+
2453635748,
|
|
3006
|
+
2870763221,
|
|
3007
|
+
3624381080,
|
|
3008
|
+
310598401,
|
|
3009
|
+
607225278,
|
|
3010
|
+
1426881987,
|
|
3011
|
+
1925078388,
|
|
3012
|
+
2162078206,
|
|
3013
|
+
2614888103,
|
|
3014
|
+
3248222580,
|
|
3015
|
+
3835390401,
|
|
3016
|
+
4022224774,
|
|
3017
|
+
264347078,
|
|
3018
|
+
604807628,
|
|
3019
|
+
770255983,
|
|
3020
|
+
1249150122,
|
|
3021
|
+
1555081692,
|
|
3022
|
+
1996064986,
|
|
3023
|
+
2554220882,
|
|
3024
|
+
2821834349,
|
|
3025
|
+
2952996808,
|
|
3026
|
+
3210313671,
|
|
3027
|
+
3336571891,
|
|
3028
|
+
3584528711,
|
|
3029
|
+
113926993,
|
|
3030
|
+
338241895,
|
|
3031
|
+
666307205,
|
|
3032
|
+
773529912,
|
|
3033
|
+
1294757372,
|
|
3034
|
+
1396182291,
|
|
3035
|
+
1695183700,
|
|
3036
|
+
1986661051,
|
|
3037
|
+
2177026350,
|
|
3038
|
+
2456956037,
|
|
3039
|
+
2730485921,
|
|
3040
|
+
2820302411,
|
|
3041
|
+
3259730800,
|
|
3042
|
+
3345764771,
|
|
3043
|
+
3516065817,
|
|
3044
|
+
3600352804,
|
|
3045
|
+
4094571909,
|
|
3046
|
+
275423344,
|
|
3047
|
+
430227734,
|
|
3048
|
+
506948616,
|
|
3049
|
+
659060556,
|
|
3050
|
+
883997877,
|
|
3051
|
+
958139571,
|
|
3052
|
+
1322822218,
|
|
3053
|
+
1537002063,
|
|
3054
|
+
1747873779,
|
|
3055
|
+
1955562222,
|
|
3056
|
+
2024104815,
|
|
3057
|
+
2227730452,
|
|
3058
|
+
2361852424,
|
|
3059
|
+
2428436474,
|
|
3060
|
+
2756734187,
|
|
3061
|
+
3204031479,
|
|
3062
|
+
3329325298
|
|
3063
|
+
];
|
|
3064
|
+
function rotr(value, bits) {
|
|
3065
|
+
return (value >>> bits | value << 32 - bits) >>> 0;
|
|
3066
|
+
}
|
|
3067
|
+
function sha256Hex(message) {
|
|
3068
|
+
const bytes = new TextEncoder().encode(message);
|
|
3069
|
+
const bitLength = bytes.length * 8;
|
|
3070
|
+
const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64);
|
|
3071
|
+
padded.set(bytes);
|
|
3072
|
+
padded[bytes.length] = 128;
|
|
3073
|
+
const view = new DataView(padded.buffer);
|
|
3074
|
+
view.setUint32(padded.length - 8, idiv(bitLength, 4294967296), false);
|
|
3075
|
+
view.setUint32(padded.length - 4, bitLength >>> 0, false);
|
|
3076
|
+
const h = [
|
|
3077
|
+
1779033703,
|
|
3078
|
+
3144134277,
|
|
3079
|
+
1013904242,
|
|
3080
|
+
2773480762,
|
|
3081
|
+
1359893119,
|
|
3082
|
+
2600822924,
|
|
3083
|
+
528734635,
|
|
3084
|
+
1541459225
|
|
3085
|
+
];
|
|
3086
|
+
const w = new Uint32Array(64);
|
|
3087
|
+
for (let offset = 0; offset < padded.length; offset += 64) {
|
|
3088
|
+
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
|
|
3089
|
+
for (let i = 16; i < 64; i++) {
|
|
3090
|
+
const a2 = w[i - 15] ?? 0;
|
|
3091
|
+
const b2 = w[i - 2] ?? 0;
|
|
3092
|
+
const s0 = (rotr(a2, 7) ^ rotr(a2, 18) ^ a2 >>> 3) >>> 0;
|
|
3093
|
+
const s1 = (rotr(b2, 17) ^ rotr(b2, 19) ^ b2 >>> 10) >>> 0;
|
|
3094
|
+
w[i] = (w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1 >>> 0;
|
|
3095
|
+
}
|
|
3096
|
+
let [a, b, c, d, e, f, g, hh] = h;
|
|
3097
|
+
for (let i = 0; i < 64; i++) {
|
|
3098
|
+
const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
|
|
3099
|
+
const ch = (e & f ^ ~e & g) >>> 0;
|
|
3100
|
+
const temp1 = hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0) >>> 0;
|
|
3101
|
+
const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
|
|
3102
|
+
const maj = (a & b ^ a & c ^ b & c) >>> 0;
|
|
3103
|
+
const temp2 = s0 + maj >>> 0;
|
|
3104
|
+
hh = g;
|
|
3105
|
+
g = f;
|
|
3106
|
+
f = e;
|
|
3107
|
+
e = d + temp1 >>> 0;
|
|
3108
|
+
d = c;
|
|
3109
|
+
c = b;
|
|
3110
|
+
b = a;
|
|
3111
|
+
a = temp1 + temp2 >>> 0;
|
|
3112
|
+
}
|
|
3113
|
+
const next = [a, b, c, d, e, f, g, hh];
|
|
3114
|
+
for (let i = 0; i < 8; i++) h[i] = (h[i] ?? 0) + (next[i] ?? 0) >>> 0;
|
|
3115
|
+
}
|
|
3116
|
+
let hex = "";
|
|
3117
|
+
for (const word of h) hex += word.toString(16).padStart(8, "0");
|
|
3118
|
+
return hex;
|
|
3119
|
+
}
|
|
3120
|
+
function canonicalJson(value) {
|
|
3121
|
+
if (value === null) return "null";
|
|
3122
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
3123
|
+
if (typeof value === "number") return Number.isFinite(value) ? JSON.stringify(value) : "null";
|
|
3124
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
3125
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
3126
|
+
if (typeof value === "object") {
|
|
3127
|
+
const record = value;
|
|
3128
|
+
const keys = Object.keys(record).filter((key) => record[key] !== void 0);
|
|
3129
|
+
keys.sort();
|
|
3130
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
|
|
3131
|
+
}
|
|
3132
|
+
return "null";
|
|
3133
|
+
}
|
|
3134
|
+
function rulesetHash(ruleset) {
|
|
3135
|
+
return sha256Hex(canonicalJson(ruleset));
|
|
3136
|
+
}
|
|
3137
|
+
var VOLATILE_HEADERS = /* @__PURE__ */ new Set([
|
|
3138
|
+
"date",
|
|
3139
|
+
"age",
|
|
3140
|
+
"set-cookie",
|
|
3141
|
+
"x-request-id",
|
|
3142
|
+
"cf-ray",
|
|
3143
|
+
"report-to"
|
|
3144
|
+
]);
|
|
3145
|
+
function stableHeaders(headers) {
|
|
3146
|
+
const out = {};
|
|
3147
|
+
for (const [name, values] of Object.entries(headers)) {
|
|
3148
|
+
if (VOLATILE_HEADERS.has(name.toLowerCase())) continue;
|
|
3149
|
+
out[name.toLowerCase()] = values;
|
|
3150
|
+
}
|
|
3151
|
+
return out;
|
|
3152
|
+
}
|
|
3153
|
+
function evidenceHash(evidence) {
|
|
3154
|
+
const redactProbe = (probe) => {
|
|
3155
|
+
if (probe === null) return null;
|
|
3156
|
+
if (!probe.result.ok) return { requestHeaders: probe.requestHeaders, result: probe.result };
|
|
3157
|
+
const capture = probe.result.capture;
|
|
3158
|
+
return {
|
|
3159
|
+
requestHeaders: probe.requestHeaders,
|
|
3160
|
+
result: {
|
|
3161
|
+
ok: true,
|
|
3162
|
+
capture: { ...capture, headers: stableHeaders(capture.headers) }
|
|
3163
|
+
}
|
|
3164
|
+
};
|
|
3165
|
+
};
|
|
3166
|
+
return sha256Hex(
|
|
3167
|
+
canonicalJson({
|
|
3168
|
+
evidenceVersion: evidence.evidenceVersion,
|
|
3169
|
+
target: evidence.target,
|
|
3170
|
+
vantage: evidence.vantage,
|
|
3171
|
+
probes: {
|
|
3172
|
+
agent: redactProbe(evidence.probes.agent),
|
|
3173
|
+
browser: redactProbe(evidence.probes.browser),
|
|
3174
|
+
parityConfirm: redactProbe(evidence.probes.parityConfirm),
|
|
3175
|
+
robotsTxt: redactProbe(evidence.probes.robotsTxt),
|
|
3176
|
+
llmsTxt: redactProbe(evidence.probes.llmsTxt),
|
|
3177
|
+
wellKnownUcp: redactProbe(evidence.probes.wellKnownUcp)
|
|
3178
|
+
}
|
|
3179
|
+
})
|
|
3180
|
+
);
|
|
3181
|
+
}
|
|
3182
|
+
var ARS_CORPUS_HASH = sha256Hex("ars-0.1-corpus-unfrozen");
|
|
3183
|
+
function parseLinkHeaders(values) {
|
|
3184
|
+
const out = [];
|
|
3185
|
+
for (const value of values) {
|
|
3186
|
+
for (const entry of splitLinkEntries(value)) {
|
|
3187
|
+
const open = entry.indexOf("<");
|
|
3188
|
+
const close = entry.indexOf(">", open + 1);
|
|
3189
|
+
if (open === -1 || close === -1) continue;
|
|
3190
|
+
const url = entry.slice(open + 1, close).trim();
|
|
3191
|
+
if (url.length === 0) continue;
|
|
3192
|
+
let rel = [];
|
|
3193
|
+
let type = null;
|
|
3194
|
+
for (const param of entry.slice(close + 1).split(";")) {
|
|
3195
|
+
const equals = param.indexOf("=");
|
|
3196
|
+
if (equals === -1) continue;
|
|
3197
|
+
const name = param.slice(0, equals).trim().toLowerCase();
|
|
3198
|
+
const raw = param.slice(equals + 1).trim();
|
|
3199
|
+
const unquoted = raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw;
|
|
3200
|
+
if (name === "rel")
|
|
3201
|
+
rel = unquoted.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
|
|
3202
|
+
else if (name === "type") type = unquoted.trim().toLowerCase();
|
|
3203
|
+
}
|
|
3204
|
+
out.push({ url, rel, type });
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
return out;
|
|
3208
|
+
}
|
|
3209
|
+
function splitLinkEntries(value) {
|
|
3210
|
+
const entries = [];
|
|
3211
|
+
let depth = 0;
|
|
3212
|
+
let quoted = false;
|
|
3213
|
+
let start = 0;
|
|
3214
|
+
for (let i = 0; i < value.length; i++) {
|
|
3215
|
+
const char = value.charAt(i);
|
|
3216
|
+
if (quoted) {
|
|
3217
|
+
if (char === '"') quoted = false;
|
|
3218
|
+
continue;
|
|
3219
|
+
}
|
|
3220
|
+
if (char === '"') quoted = true;
|
|
3221
|
+
else if (char === "<") depth++;
|
|
3222
|
+
else if (char === ">") depth = depth > 0 ? depth - 1 : 0;
|
|
3223
|
+
else if (char === "," && depth === 0) {
|
|
3224
|
+
entries.push(value.slice(start, i));
|
|
3225
|
+
start = i + 1;
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
entries.push(value.slice(start));
|
|
3229
|
+
return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
|
|
3230
|
+
}
|
|
3231
|
+
function headerTokens(value) {
|
|
3232
|
+
if (value === null) return [];
|
|
3233
|
+
return value.toLowerCase().split(/[,\s]+/).map((token) => token.trim()).filter((token) => token.length > 0);
|
|
3234
|
+
}
|
|
3235
|
+
var YES = "yes";
|
|
3236
|
+
var NO = "no";
|
|
3237
|
+
var yesNo = (value) => value ? YES : NO;
|
|
3238
|
+
function measured(label, value) {
|
|
3239
|
+
return { label, value, basis: "measured" };
|
|
3240
|
+
}
|
|
3241
|
+
function heuristic(label, value) {
|
|
3242
|
+
return { label, value, basis: "heuristic" };
|
|
3243
|
+
}
|
|
3244
|
+
function checkReachable(context) {
|
|
3245
|
+
const { agentCapture, browserCapture, ruleset } = context;
|
|
3246
|
+
const split = SUBPOINTS.reachable;
|
|
3247
|
+
const status2xx = agentCapture.status >= 200 && agentCapture.status < 300;
|
|
3248
|
+
const hops = agentCapture.redirects.length;
|
|
3249
|
+
const withinLimit = hops <= ruleset.maxRedirects;
|
|
3250
|
+
const sameFinalUrl = browserCapture !== null && browserCapture.finalUrl === agentCapture.finalUrl;
|
|
3251
|
+
const earned = (status2xx ? split.status2xx : 0) + (withinLimit ? split.withinRedirectLimit : 0) + (sameFinalUrl ? split.noAcceptConditionalRedirect : 0);
|
|
3252
|
+
const evidence = [
|
|
3253
|
+
measured("HTTP status on the agent path", String(agentCapture.status)),
|
|
3254
|
+
measured("Redirect hops", `${hops} (limit ${ruleset.maxRedirects})`),
|
|
3255
|
+
measured(
|
|
3256
|
+
"Both probes resolved to the same URL",
|
|
3257
|
+
browserCapture === null ? "not comparable \u2014 no browser-control capture in this bundle" : yesNo(sameFinalUrl)
|
|
3258
|
+
)
|
|
3259
|
+
];
|
|
3260
|
+
return sameFinalUrl ? { earned, evidence } : {
|
|
3261
|
+
earned,
|
|
3262
|
+
evidence,
|
|
3263
|
+
remedy: "Serve the same URL to both Accept headers. An Accept-conditional redirect sends the agent somewhere the browser never goes, and caches key on the URL."
|
|
3264
|
+
};
|
|
3265
|
+
}
|
|
3266
|
+
function checkRobotsPolicy(context) {
|
|
3267
|
+
const { policy, robots } = context;
|
|
3268
|
+
const split = SUBPOINTS.robotsPolicy;
|
|
3269
|
+
const decision = policy.audiences.assistant;
|
|
3270
|
+
const parsesClean = robots === null || robots.malformedLines === 0;
|
|
3271
|
+
const noOrphanRules = robots === null || robots.orphanRules === 0;
|
|
3272
|
+
const evidence = [
|
|
3273
|
+
measured("robots.txt", policy.robotsTxtStatus),
|
|
3274
|
+
measured(
|
|
3275
|
+
"Assistant audience",
|
|
3276
|
+
decision.matchedGroup === null ? `${decision.decision} (no matching group)` : `${decision.decision} via User-agent: ${decision.matchedGroup}${decision.matchedRule === null ? "" : ` / ${decision.matchedRule}`}`
|
|
3277
|
+
),
|
|
3278
|
+
measured("Malformed lines", robots === null ? "n/a" : String(robots.malformedLines)),
|
|
3279
|
+
measured(
|
|
3280
|
+
"Rules before any User-agent line",
|
|
3281
|
+
robots === null ? "n/a" : String(robots.orphanRules)
|
|
3282
|
+
),
|
|
3283
|
+
measured("Sitemap: declared", yesNo(policy.sitemapDeclared)),
|
|
3284
|
+
measured(
|
|
3285
|
+
"Training-crawler policy (never scored)",
|
|
3286
|
+
policy.trainingOptOut ? "blocked \u2014 neutral, no effect on this score" : "allowed"
|
|
3287
|
+
)
|
|
3288
|
+
];
|
|
3289
|
+
if (decision.decision === "disallow") {
|
|
3290
|
+
context.flags.push({
|
|
3291
|
+
id: "robots-contradiction",
|
|
3292
|
+
severity: "warn",
|
|
3293
|
+
basis: "measured",
|
|
3294
|
+
message: "robots.txt disallows assistant crawlers through a group that does not name one, so it reads as a blanket rule rather than a deliberate choice. Assistant traffic is blocked as a side effect.",
|
|
3295
|
+
evidence: [evidence[1] ?? measured("Assistant audience", decision.decision)]
|
|
3296
|
+
});
|
|
3297
|
+
return {
|
|
3298
|
+
earned: 0,
|
|
3299
|
+
evidence,
|
|
3300
|
+
remedy: "Name the assistant crawlers you mean to allow or block in their own robots.txt group. A blanket disallow blocks assistant fetches that users triggered on purpose."
|
|
3301
|
+
};
|
|
3302
|
+
}
|
|
3303
|
+
const earned = split.assistantAllowed + (parsesClean ? split.parsesClean : 0) + (noOrphanRules ? split.noOrphanRules : 0) + (policy.sitemapDeclared ? split.sitemapDeclared : 0);
|
|
3304
|
+
return {
|
|
3305
|
+
earned,
|
|
3306
|
+
evidence,
|
|
3307
|
+
remedy: policy.sitemapDeclared ? void 0 : "Add a `Sitemap:` line to robots.txt. It is the one place an agent looks to find the rest of the site."
|
|
3308
|
+
};
|
|
3309
|
+
}
|
|
3310
|
+
function checkRenderIndependence(context) {
|
|
3311
|
+
const { structural, structuralFacts, profile } = context;
|
|
3312
|
+
const split = SUBPOINTS.renderIndependence;
|
|
3313
|
+
const coreSize = profile.core.length;
|
|
3314
|
+
if (structural === null || structural.doc === null) {
|
|
3315
|
+
return {
|
|
3316
|
+
earned: 0,
|
|
3317
|
+
evidence: [heuristic("HTML representation", "none in this bundle \u2014 not evaluated")]
|
|
3318
|
+
};
|
|
3319
|
+
}
|
|
3320
|
+
const found = /* @__PURE__ */ new Set();
|
|
3321
|
+
for (const fact of structuralFacts) if (profile.core.includes(fact.kind)) found.add(fact.kind);
|
|
3322
|
+
const ratio = coreSize === 0 ? 0 : idiv(100 * found.size, coreSize);
|
|
3323
|
+
let noscriptText = "";
|
|
3324
|
+
for (const element of structural.doc.elements) {
|
|
3325
|
+
if (element.tag !== "noscript") continue;
|
|
3326
|
+
noscriptText = elementText(structural.doc, element.index).trim();
|
|
3327
|
+
if (noscriptText.length > 0) break;
|
|
3328
|
+
}
|
|
3329
|
+
const hasNoscript = noscriptText.length > 0;
|
|
3330
|
+
const banded = atLeast(split.band, ratio);
|
|
3331
|
+
const earned = Math.max(banded, hasNoscript ? split.noscriptFloor : 0);
|
|
3332
|
+
const full = atLeast(split.band, 100);
|
|
3333
|
+
if (ratio < 50) {
|
|
3334
|
+
context.flags.push({
|
|
3335
|
+
id: "render-dependent",
|
|
3336
|
+
severity: "info",
|
|
3337
|
+
basis: "heuristic",
|
|
3338
|
+
message: `${found.size} of ${coreSize} core facts for this page kind were present in the HTML without running JavaScript. A caller that does not execute scripts sees the rest as missing.`,
|
|
3339
|
+
evidence: [heuristic("Core facts in the served HTML", `${found.size}/${coreSize}`)]
|
|
3340
|
+
});
|
|
3341
|
+
}
|
|
3342
|
+
return {
|
|
3343
|
+
earned,
|
|
3344
|
+
evidence: [
|
|
3345
|
+
heuristic("Core facts present without JavaScript", `${found.size}/${coreSize}`),
|
|
3346
|
+
heuristic("<noscript> fallback with content", yesNo(hasNoscript)),
|
|
3347
|
+
heuristic(
|
|
3348
|
+
"Basis",
|
|
3349
|
+
"inferred \u2014 ARS never executes JavaScript, so this measures the served HTML, not what a browser would render"
|
|
3350
|
+
)
|
|
3351
|
+
],
|
|
3352
|
+
remedy: earned === full ? void 0 : "Render the core facts for this page kind into the HTML the server sends. Agents do not run your JavaScript."
|
|
3353
|
+
};
|
|
3354
|
+
}
|
|
3355
|
+
var MACHINE_KINDS = /* @__PURE__ */ new Set(["markdown", "text", "json"]);
|
|
3356
|
+
function checkNegotiatedResponse(context) {
|
|
3357
|
+
const { agent } = context;
|
|
3358
|
+
const typeIsMachine = MACHINE_KINDS.has(agent.kind);
|
|
3359
|
+
const bodyIsHtml = agent.looksLikeHtml;
|
|
3360
|
+
const earned = typeIsMachine && !bodyIsHtml ? SUBPOINTS.negotiatedResponse.full : 0;
|
|
3361
|
+
return {
|
|
3362
|
+
earned,
|
|
3363
|
+
evidence: [
|
|
3364
|
+
measured("Content-Type on the agent probe", agent.contentType ?? "absent"),
|
|
3365
|
+
measured("Body is HTML", yesNo(bodyIsHtml)),
|
|
3366
|
+
measured(
|
|
3367
|
+
"Request Accept header",
|
|
3368
|
+
context.evidence.probes.agent.requestHeaders["accept"] ?? context.evidence.probes.agent.requestHeaders["Accept"] ?? "not recorded"
|
|
3369
|
+
)
|
|
3370
|
+
],
|
|
3371
|
+
remedy: earned > 0 ? void 0 : typeIsMachine ? "The response declared a machine media type but the body is HTML. Send the representation the Content-Type promises." : "Return a machine representation \u2014 Markdown, plain text or JSON \u2014 when the request Accept header asks for one, with a matching Content-Type."
|
|
3372
|
+
};
|
|
3373
|
+
}
|
|
3374
|
+
function checkDeclaredAlternates(context) {
|
|
3375
|
+
const { agentCapture, browserCapture, structural } = context;
|
|
3376
|
+
const links = parseLinkHeaders([
|
|
3377
|
+
...headerAll(agentCapture.headers, "link"),
|
|
3378
|
+
...browserCapture === null ? [] : headerAll(browserCapture.headers, "link")
|
|
3379
|
+
]);
|
|
3380
|
+
const headerAlternates = links.filter(
|
|
3381
|
+
(link) => link.rel.includes("alternate") && link.type !== null
|
|
3382
|
+
);
|
|
3383
|
+
const documentAlternates = [];
|
|
3384
|
+
if (structural !== null && structural.doc !== null) {
|
|
3385
|
+
for (const link of structural.doc.links) {
|
|
3386
|
+
if (!link.rel.includes("alternate")) continue;
|
|
3387
|
+
if (link.type === null || link.href === null) continue;
|
|
3388
|
+
documentAlternates.push(`${link.type} \u2192 ${link.href}`);
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
const total = headerAlternates.length + documentAlternates.length;
|
|
3392
|
+
return {
|
|
3393
|
+
earned: total > 0 ? SUBPOINTS.declaredAlternates.full : 0,
|
|
3394
|
+
evidence: [
|
|
3395
|
+
measured(
|
|
3396
|
+
'Link: rel="alternate" (typed)',
|
|
3397
|
+
headerAlternates.length === 0 ? "none" : headerAlternates.map((link) => `${link.type ?? "?"} \u2192 ${link.url}`).join(", ")
|
|
3398
|
+
),
|
|
3399
|
+
measured(
|
|
3400
|
+
'<link rel="alternate"> (typed)',
|
|
3401
|
+
documentAlternates.length === 0 ? "none" : documentAlternates.join(", ")
|
|
3402
|
+
)
|
|
3403
|
+
],
|
|
3404
|
+
remedy: total > 0 ? void 0 : 'Declare the machine representation: `Link: <\u2026>; rel="alternate"; type="text/markdown"` or a `<link rel="alternate">` in the HTML. An endpoint an agent cannot find is an endpoint that does not exist.'
|
|
3405
|
+
};
|
|
3406
|
+
}
|
|
3407
|
+
function checkVaryAccept(context, negotiated) {
|
|
3408
|
+
const { agentCapture, browserCapture } = context;
|
|
3409
|
+
const agentVary = headerTokens(header(agentCapture.headers, "vary"));
|
|
3410
|
+
const browserVary = browserCapture === null ? [] : headerTokens(header(browserCapture.headers, "vary"));
|
|
3411
|
+
const declared = agentVary.includes("accept") || browserVary.includes("accept");
|
|
3412
|
+
const evidence = [
|
|
3413
|
+
measured("Vary on the agent response", header(agentCapture.headers, "vary") ?? "absent"),
|
|
3414
|
+
measured(
|
|
3415
|
+
"Vary on the browser response",
|
|
3416
|
+
browserCapture === null ? "no browser capture" : header(browserCapture.headers, "vary") ?? "absent"
|
|
3417
|
+
)
|
|
3418
|
+
];
|
|
3419
|
+
if (negotiated === 0) {
|
|
3420
|
+
return {
|
|
3421
|
+
earned: 0,
|
|
3422
|
+
evidence: [
|
|
3423
|
+
...evidence,
|
|
3424
|
+
measured(
|
|
3425
|
+
"Scored",
|
|
3426
|
+
"no \u2014 this check is 0 unless a machine representation was served (D2.1)"
|
|
3427
|
+
)
|
|
3428
|
+
]
|
|
3429
|
+
};
|
|
3430
|
+
}
|
|
3431
|
+
if (!declared) {
|
|
3432
|
+
context.flags.push({
|
|
3433
|
+
id: "vary-missing",
|
|
3434
|
+
severity: "warn",
|
|
3435
|
+
basis: "measured",
|
|
3436
|
+
message: "The same URL returns different representations by Accept but does not send `Vary: Accept`. A shared cache can serve the Markdown to a browser, or the HTML to an agent.",
|
|
3437
|
+
evidence
|
|
3438
|
+
});
|
|
3439
|
+
}
|
|
3440
|
+
return {
|
|
3441
|
+
earned: declared ? SUBPOINTS.varyAccept.full : 0,
|
|
3442
|
+
evidence,
|
|
3443
|
+
remedy: declared ? void 0 : "Send `Vary: Accept` on every response from a URL that negotiates on Accept."
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3446
|
+
var PARITY_KINDS = ["price", "currency", "availability", "title"];
|
|
3447
|
+
function factView(facts) {
|
|
3448
|
+
const best = /* @__PURE__ */ new Map();
|
|
3449
|
+
const observed = /* @__PURE__ */ new Map();
|
|
3450
|
+
for (const fact of facts) {
|
|
3451
|
+
if (fact.qualified) continue;
|
|
3452
|
+
const seen = observed.get(fact.kind);
|
|
3453
|
+
if (seen === void 0) observed.set(fact.kind, /* @__PURE__ */ new Set([fact.normalized]));
|
|
3454
|
+
else seen.add(fact.normalized);
|
|
3455
|
+
const current = best.get(fact.kind);
|
|
3456
|
+
if (current === void 0) {
|
|
3457
|
+
best.set(fact.kind, fact);
|
|
3458
|
+
continue;
|
|
3459
|
+
}
|
|
3460
|
+
if (fact.offset < current.offset) best.set(fact.kind, fact);
|
|
3461
|
+
else if (fact.offset === current.offset && fact.normalized < current.normalized)
|
|
3462
|
+
best.set(fact.kind, fact);
|
|
3463
|
+
}
|
|
3464
|
+
const representative = /* @__PURE__ */ new Map();
|
|
3465
|
+
for (const [kind, fact] of best) representative.set(kind, fact.normalized);
|
|
3466
|
+
return { representative, observed };
|
|
3467
|
+
}
|
|
3468
|
+
function divergentKinds(left, right, kinds) {
|
|
3469
|
+
const compared = [];
|
|
3470
|
+
const divergent = [];
|
|
3471
|
+
for (const kind of kinds) {
|
|
3472
|
+
const claim = left.representative.get(kind);
|
|
3473
|
+
const stated = right.observed.get(kind);
|
|
3474
|
+
if (claim === void 0 || stated === void 0 || stated.size === 0) continue;
|
|
3475
|
+
compared.push(kind);
|
|
3476
|
+
if (!stated.has(claim)) {
|
|
3477
|
+
divergent.push({ kind, left: claim, right: [...stated].sort().join(" | ") });
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
return { compared, divergent };
|
|
3481
|
+
}
|
|
3482
|
+
function checkSubstanceParity(context, negotiated) {
|
|
3483
|
+
const { agentFacts, browserFacts, browser, evidence: bundle } = context;
|
|
3484
|
+
if (negotiated === 0 || browser === null) {
|
|
3485
|
+
return {
|
|
3486
|
+
earned: 0,
|
|
3487
|
+
evidence: [
|
|
3488
|
+
heuristic(
|
|
3489
|
+
"Comparable",
|
|
3490
|
+
negotiated === 0 ? "no \u2014 there is one representation, so there is nothing to compare (this is the designed 84-point ceiling for a page with no content negotiation)" : "no \u2014 no browser-control capture in this bundle"
|
|
3491
|
+
)
|
|
3492
|
+
]
|
|
3493
|
+
};
|
|
3494
|
+
}
|
|
3495
|
+
const agentValues = factView(agentFacts);
|
|
3496
|
+
const browserValues = factView(browserFacts);
|
|
3497
|
+
const { compared, divergent } = divergentKinds(agentValues, browserValues, PARITY_KINDS);
|
|
3498
|
+
const evidenceLines = [
|
|
3499
|
+
heuristic(
|
|
3500
|
+
"Compared facts",
|
|
3501
|
+
compared.length === 0 ? "none present in both representations" : compared.join(", ")
|
|
3502
|
+
),
|
|
3503
|
+
heuristic(
|
|
3504
|
+
"Values",
|
|
3505
|
+
divergent.length === 0 ? "agree" : divergent.map((entry) => `${entry.kind}: agent ${entry.left} / HTML ${entry.right}`).join("; ")
|
|
3506
|
+
)
|
|
3507
|
+
];
|
|
3508
|
+
if (compared.length === 0) {
|
|
3509
|
+
return {
|
|
3510
|
+
earned: 0,
|
|
3511
|
+
evidence: [
|
|
3512
|
+
...evidenceLines,
|
|
3513
|
+
heuristic(
|
|
3514
|
+
"Scored",
|
|
3515
|
+
"no \u2014 a comparison needs at least one comparable fact in both representations"
|
|
3516
|
+
)
|
|
3517
|
+
],
|
|
3518
|
+
remedy: "State the same core facts in both representations. ARS could not compare them, so it could not award the parity points."
|
|
3519
|
+
};
|
|
3520
|
+
}
|
|
3521
|
+
if (divergent.length === 0)
|
|
3522
|
+
return { earned: SUBPOINTS.substanceParity.full, evidence: evidenceLines };
|
|
3523
|
+
const confirm = bundle.probes.parityConfirm;
|
|
3524
|
+
const confirmCapture = confirm !== null && confirm.result.ok ? confirm.result.capture : null;
|
|
3525
|
+
const confirmRep = confirmCapture === null ? null : buildRepresentation(confirmCapture);
|
|
3526
|
+
if (confirmRep === null) {
|
|
3527
|
+
return {
|
|
3528
|
+
earned: 0,
|
|
3529
|
+
evidence: [
|
|
3530
|
+
...evidenceLines,
|
|
3531
|
+
heuristic("Confirming probe", "absent \u2014 divergence observed once and NOT flagged")
|
|
3532
|
+
],
|
|
3533
|
+
remedy: "The two representations reported different values for a core fact. ARS did not flag it, because a single observation cannot distinguish a divergence from an inventory change."
|
|
3534
|
+
};
|
|
3535
|
+
}
|
|
3536
|
+
const confirmFacts = extractFacts(confirmRep, {
|
|
3537
|
+
profile: context.profile,
|
|
3538
|
+
ruleset: context.ruleset,
|
|
3539
|
+
baseUrl: confirmRep.finalUrl,
|
|
3540
|
+
origin: bundle.target.origin,
|
|
3541
|
+
currencyHint: currencyHintOf(context.structural, context.agent)
|
|
3542
|
+
});
|
|
3543
|
+
const confirmValues = factView(confirmFacts);
|
|
3544
|
+
const reproduced = divergentKinds(
|
|
3545
|
+
confirmValues,
|
|
3546
|
+
browserValues,
|
|
3547
|
+
divergent.map((entry) => entry.kind)
|
|
3548
|
+
);
|
|
3549
|
+
if (reproduced.divergent.length === 0) {
|
|
3550
|
+
return {
|
|
3551
|
+
earned: SUBPOINTS.substanceParity.full,
|
|
3552
|
+
evidence: [
|
|
3553
|
+
...evidenceLines,
|
|
3554
|
+
heuristic(
|
|
3555
|
+
"Confirming probe",
|
|
3556
|
+
"the difference did not reproduce \u2014 treated as a value that changed between requests"
|
|
3557
|
+
)
|
|
3558
|
+
]
|
|
3559
|
+
};
|
|
3560
|
+
}
|
|
3561
|
+
context.flags.push({
|
|
3562
|
+
id: "substance-divergence",
|
|
3563
|
+
severity: "warn",
|
|
3564
|
+
basis: "heuristic",
|
|
3565
|
+
message: reproduced.divergent.map(
|
|
3566
|
+
(entry) => `The agent representation reported ${entry.kind} ${entry.left}; the HTML representation reported ${entry.right} at capture time, on two captures taken apart.`
|
|
3567
|
+
).join(" "),
|
|
3568
|
+
evidence: evidenceLines
|
|
3569
|
+
});
|
|
3570
|
+
return {
|
|
3571
|
+
earned: 0,
|
|
3572
|
+
evidence: [...evidenceLines, heuristic("Confirming probe", "the difference reproduced")],
|
|
3573
|
+
remedy: "Serve the same values in both representations. ARS reports what each one said; it does not assert which is correct."
|
|
3574
|
+
};
|
|
3575
|
+
}
|
|
3576
|
+
function coverageMath(context) {
|
|
3577
|
+
const { facts, profile, ruleset, agent } = context;
|
|
3578
|
+
const units = ruleset.thresholds["fact-coverage.fact-units"] ?? [];
|
|
3579
|
+
const coreCorroboratedUnit = units[0] ?? 0;
|
|
3580
|
+
const coreUnit = units[1] ?? 0;
|
|
3581
|
+
const extendedCorroboratedUnit = units[2] ?? 0;
|
|
3582
|
+
const extendedUnit = units[3] ?? 0;
|
|
3583
|
+
const denominatorMultiplier = ruleset.thresholds["fact-coverage.core-denominator-multiplier"]?.[0] ?? 0;
|
|
3584
|
+
let coreUnits = 0;
|
|
3585
|
+
let extendedUnits = 0;
|
|
3586
|
+
let coreFound = 0;
|
|
3587
|
+
let extendedFound = 0;
|
|
3588
|
+
for (const fact of facts) {
|
|
3589
|
+
if (profile.core.includes(fact.kind)) {
|
|
3590
|
+
coreFound++;
|
|
3591
|
+
coreUnits += fact.corroborated ? coreCorroboratedUnit : coreUnit;
|
|
3592
|
+
} else if (profile.extended.includes(fact.kind)) {
|
|
3593
|
+
extendedFound++;
|
|
3594
|
+
extendedUnits += fact.corroborated ? extendedCorroboratedUnit : extendedUnit;
|
|
3595
|
+
}
|
|
3596
|
+
}
|
|
3597
|
+
const denominator = denominatorMultiplier * profile.core.length;
|
|
3598
|
+
const coveragePct = denominator === 0 ? 0 : Math.min(100, divRoundHalfUp(100 * (coreUnits + extendedUnits), denominator));
|
|
3599
|
+
const factsPerKiB100 = idiv(
|
|
3600
|
+
(coreFound * 100 + extendedFound * 25) * 1024,
|
|
3601
|
+
Math.max(1, agent.bytes)
|
|
3602
|
+
);
|
|
3603
|
+
const densityPct = atLeast(ruleset.thresholds["fact-coverage.density"], factsPerKiB100);
|
|
3604
|
+
return { coreFound, extendedFound, coveragePct, densityPct, factsPerKiB100 };
|
|
3605
|
+
}
|
|
3606
|
+
function checkCoreFacts(context, math) {
|
|
3607
|
+
const weight = weightOf(context.ruleset, "fact-coverage.core-facts");
|
|
3608
|
+
const earned = idiv(weight * math.coveragePct * math.densityPct + 5e3, 1e4);
|
|
3609
|
+
const missing = context.profile.core.filter(
|
|
3610
|
+
(kind) => !context.facts.some((fact) => fact.kind === kind)
|
|
3611
|
+
);
|
|
3612
|
+
return {
|
|
3613
|
+
earned,
|
|
3614
|
+
evidence: [
|
|
3615
|
+
heuristic(
|
|
3616
|
+
"Core facts found",
|
|
3617
|
+
`${math.coreFound}/${context.profile.core.length}${missing.length === 0 ? "" : ` \u2014 missing ${missing.join(", ")}`}`
|
|
3618
|
+
),
|
|
3619
|
+
heuristic("Extended facts found", `${math.extendedFound}/${context.profile.extended.length}`),
|
|
3620
|
+
heuristic("Coverage", `${math.coveragePct}%`),
|
|
3621
|
+
heuristic(
|
|
3622
|
+
"Density band",
|
|
3623
|
+
`${math.densityPct}% (${math.factsPerKiB100} hundredths of a fact per KiB)`
|
|
3624
|
+
),
|
|
3625
|
+
measured("Bytes the agent received", String(context.agent.bytes))
|
|
3626
|
+
],
|
|
3627
|
+
remedy: missing.length === 0 ? void 0 : `State ${missing.join(", ")} in the representation the agent receives. A fact only the HTML carries is a fact the caller never saw.`
|
|
3628
|
+
};
|
|
3629
|
+
}
|
|
3630
|
+
function checkContextCost(context) {
|
|
3631
|
+
const table = context.ruleset.thresholds["fact-coverage.context-cost"];
|
|
3632
|
+
const reference = context.profile.byteReference;
|
|
3633
|
+
const ratio = reference === 0 ? 0 : idiv(100 * context.agent.bytes, reference);
|
|
3634
|
+
const earned = atMost(table, ratio);
|
|
3635
|
+
const full = atMost(table, 0);
|
|
3636
|
+
return {
|
|
3637
|
+
earned,
|
|
3638
|
+
evidence: [
|
|
3639
|
+
measured(
|
|
3640
|
+
"Bytes the agent received",
|
|
3641
|
+
`${context.agent.bytes}${context.agent.truncated ? " (truncated at the cap)" : ""}`
|
|
3642
|
+
),
|
|
3643
|
+
measured("Byte reference for this page kind", `${reference} (${context.profile.pageKind})`),
|
|
3644
|
+
measured("Ratio", `${ratio}% of the reference`)
|
|
3645
|
+
],
|
|
3646
|
+
remedy: earned === full ? void 0 : "Serve a representation sized to the facts. The reference is what a page of this kind reasonably costs, not an absolute budget."
|
|
3647
|
+
};
|
|
3648
|
+
}
|
|
3649
|
+
function coreOffsets(context) {
|
|
3650
|
+
const offsets = [];
|
|
3651
|
+
for (const fact of context.facts)
|
|
3652
|
+
if (context.profile.core.includes(fact.kind)) offsets.push(fact.offset);
|
|
3653
|
+
return offsets.sort((a, b) => a - b);
|
|
3654
|
+
}
|
|
3655
|
+
function checkFirstCoreFactOffset(context, offsets) {
|
|
3656
|
+
const first = offsets[0];
|
|
3657
|
+
if (first === void 0) {
|
|
3658
|
+
return {
|
|
3659
|
+
earned: 0,
|
|
3660
|
+
evidence: [heuristic("First core fact", "none found \u2014 nothing to position")]
|
|
3661
|
+
};
|
|
3662
|
+
}
|
|
3663
|
+
return {
|
|
3664
|
+
earned: atMost(context.ruleset.thresholds["fact-position.first-core-fact-offset"], first),
|
|
3665
|
+
evidence: [
|
|
3666
|
+
measured("Byte offset of the first core fact", String(first)),
|
|
3667
|
+
heuristic(
|
|
3668
|
+
"Which fact",
|
|
3669
|
+
context.facts.find((fact) => fact.offset === first)?.kind ?? "unknown"
|
|
3670
|
+
)
|
|
3671
|
+
],
|
|
3672
|
+
remedy: first <= 512 ? void 0 : "Move the core facts to the top of the representation. A caller that stops reading early stops before them."
|
|
3673
|
+
};
|
|
3674
|
+
}
|
|
3675
|
+
function checkFrontWindow(context, offsets) {
|
|
3676
|
+
const windowRule = context.ruleset.thresholds["fact-position.front-window-size"] ?? [];
|
|
3677
|
+
const floor = windowRule[0] ?? 0;
|
|
3678
|
+
const divisor = windowRule[1] ?? 1;
|
|
3679
|
+
const size = Math.max(floor, idiv(context.agent.bytes, divisor));
|
|
3680
|
+
if (offsets.length === 0) {
|
|
3681
|
+
return {
|
|
3682
|
+
earned: 0,
|
|
3683
|
+
evidence: [
|
|
3684
|
+
measured("Front window", `${size} bytes`),
|
|
3685
|
+
heuristic("Core facts inside it", "none found \u2014 nothing to position")
|
|
3686
|
+
]
|
|
3687
|
+
};
|
|
3688
|
+
}
|
|
3689
|
+
const inside = offsets.filter((offset) => offset < size).length;
|
|
3690
|
+
const pct = idiv(100 * inside, offsets.length);
|
|
3691
|
+
return {
|
|
3692
|
+
earned: atLeast(context.ruleset.thresholds["fact-position.front-window"], pct),
|
|
3693
|
+
evidence: [
|
|
3694
|
+
measured("Front window", `${size} bytes (max(${floor}, bytes/${divisor}))`),
|
|
3695
|
+
heuristic("Core facts inside it", `${inside}/${offsets.length} found (${pct}%)`),
|
|
3696
|
+
heuristic("Core facts in this page kind", String(context.profile.core.length))
|
|
3697
|
+
],
|
|
3698
|
+
remedy: pct >= 90 ? void 0 : "Front-load the core facts. Everything after the window costs the caller a full read."
|
|
3699
|
+
};
|
|
3700
|
+
}
|
|
3701
|
+
function checkStructuredDataPresent(context) {
|
|
3702
|
+
const { structural } = context;
|
|
3703
|
+
const split = SUBPOINTS.structuredDataPresent;
|
|
3704
|
+
if (structural === null) {
|
|
3705
|
+
return {
|
|
3706
|
+
earned: 0,
|
|
3707
|
+
evidence: [measured("HTML representation", "none in this bundle \u2014 not evaluated")]
|
|
3708
|
+
};
|
|
3709
|
+
}
|
|
3710
|
+
const { blocks, parsed } = structural.jsonLd;
|
|
3711
|
+
let microdata = 0;
|
|
3712
|
+
let rdfa = 0;
|
|
3713
|
+
if (structural.doc !== null) {
|
|
3714
|
+
for (const element of structural.doc.elements) {
|
|
3715
|
+
if (attr(element, "itemtype") !== null) microdata++;
|
|
3716
|
+
if (attr(element, "typeof") !== null) rdfa++;
|
|
3717
|
+
}
|
|
3718
|
+
}
|
|
3719
|
+
const jsonLdScore = blocks === 0 ? null : parsed === blocks ? split.clean : parsed > 0 ? split.partial : 0;
|
|
3720
|
+
const otherScore = microdata > 0 || rdfa > 0 ? split.clean : null;
|
|
3721
|
+
const earned = Math.max(jsonLdScore ?? 0, otherScore ?? 0);
|
|
3722
|
+
return {
|
|
3723
|
+
earned,
|
|
3724
|
+
evidence: [
|
|
3725
|
+
measured("JSON-LD blocks", `${parsed} of ${blocks} parsed`),
|
|
3726
|
+
measured("Microdata itemtype scopes", String(microdata)),
|
|
3727
|
+
measured("RDFa typeof scopes", String(rdfa))
|
|
3728
|
+
],
|
|
3729
|
+
remedy: earned === split.clean ? void 0 : blocks > parsed ? "One or more JSON-LD blocks did not parse. A block that does not parse is not structured data." : "Add JSON-LD for this page. It is the one machine representation every consumer already reads."
|
|
3730
|
+
};
|
|
3731
|
+
}
|
|
3732
|
+
function scoredNode(context) {
|
|
3733
|
+
const nodes = context.structural?.jsonLd.nodes ?? [];
|
|
3734
|
+
const forKind = nodeForKind(nodes, context.profile.pageKind);
|
|
3735
|
+
if (forKind !== null) return forKind;
|
|
3736
|
+
for (const node of nodes) if (node.types.some(isRecognisedType)) return node;
|
|
3737
|
+
return null;
|
|
3738
|
+
}
|
|
3739
|
+
function checkRequiredProperties(context) {
|
|
3740
|
+
const split = SUBPOINTS.requiredProperties;
|
|
3741
|
+
const required = context.ruleset.requiredProperties[context.profile.pageKind] ?? [];
|
|
3742
|
+
const node = scoredNode(context);
|
|
3743
|
+
if (node === null) {
|
|
3744
|
+
return {
|
|
3745
|
+
earned: 0,
|
|
3746
|
+
evidence: [
|
|
3747
|
+
measured("Recognised schema.org type", "none"),
|
|
3748
|
+
measured("Required properties for this page kind", required.join(", ") || "none"),
|
|
3749
|
+
measured(
|
|
3750
|
+
"Scope",
|
|
3751
|
+
"JSON-LD only in 0.1 \u2014 microdata satisfies D5.1 but is not walked for required properties"
|
|
3752
|
+
)
|
|
3753
|
+
],
|
|
3754
|
+
remedy: 'Declare a schema.org type in JSON-LD. Choosing no type does not avoid this check \u2014 an unrecognised page still scores against "any recognised type present".'
|
|
3755
|
+
};
|
|
3756
|
+
}
|
|
3757
|
+
const satisfied = required.filter((path) => hasPath(node, path));
|
|
3758
|
+
const missing = required.filter((path) => !hasPath(node, path));
|
|
3759
|
+
const completeness = required.length === 0 ? split.completeness : divRoundHalfUp(split.completeness * satisfied.length, required.length);
|
|
3760
|
+
return {
|
|
3761
|
+
earned: split.recognisedType + completeness,
|
|
3762
|
+
evidence: [
|
|
3763
|
+
measured("Scored node @type", node.types.join(", ")),
|
|
3764
|
+
measured(
|
|
3765
|
+
"Required properties",
|
|
3766
|
+
`${satisfied.length}/${required.length}${missing.length === 0 ? "" : ` \u2014 missing ${missing.join(", ")}`}`
|
|
3767
|
+
),
|
|
3768
|
+
measured("Table", `ruleset.requiredProperties.${context.profile.pageKind}`)
|
|
3769
|
+
],
|
|
3770
|
+
remedy: missing.length === 0 ? void 0 : `Add ${missing.join(", ")} to the ${node.types[0] ?? "top-level"} node.`
|
|
3771
|
+
};
|
|
3772
|
+
}
|
|
3773
|
+
function checkTextAgreement(context) {
|
|
3774
|
+
const { structuralFacts } = context;
|
|
3775
|
+
const fromJsonLd = factView(structuralFacts.filter((fact) => fact.source === "json-ld"));
|
|
3776
|
+
const fromPage = factView(structuralFacts.filter((fact) => fact.source !== "json-ld"));
|
|
3777
|
+
const { compared, divergent } = divergentKinds(fromJsonLd, fromPage, PARITY_KINDS);
|
|
3778
|
+
const evidenceLines = [
|
|
3779
|
+
heuristic(
|
|
3780
|
+
"Compared facts",
|
|
3781
|
+
compared.length === 0 ? "none stated both in structured data and on the page" : compared.join(", ")
|
|
3782
|
+
),
|
|
3783
|
+
heuristic(
|
|
3784
|
+
"Values",
|
|
3785
|
+
divergent.length === 0 ? "agree" : divergent.map((entry) => `${entry.kind}: structured data ${entry.left} / page ${entry.right}`).join("; ")
|
|
3786
|
+
)
|
|
3787
|
+
];
|
|
3788
|
+
if (compared.length === 0) {
|
|
3789
|
+
return {
|
|
3790
|
+
earned: 0,
|
|
3791
|
+
evidence: [...evidenceLines, heuristic("Scored", "no \u2014 nothing was comparable")],
|
|
3792
|
+
remedy: "State the core facts in both the structured data and the visible page, so the two can be checked against each other."
|
|
3793
|
+
};
|
|
3794
|
+
}
|
|
3795
|
+
if (divergent.length > 0) {
|
|
3796
|
+
context.flags.push({
|
|
3797
|
+
id: "structured-data-divergence",
|
|
3798
|
+
severity: "warn",
|
|
3799
|
+
basis: "heuristic",
|
|
3800
|
+
message: divergent.map(
|
|
3801
|
+
(entry) => `The structured data reported ${entry.kind} ${entry.left}; the visible page reported ${entry.right}.`
|
|
3802
|
+
).join(" "),
|
|
3803
|
+
evidence: evidenceLines
|
|
3804
|
+
});
|
|
3805
|
+
return {
|
|
3806
|
+
earned: 0,
|
|
3807
|
+
evidence: evidenceLines,
|
|
3808
|
+
remedy: "Generate the structured data from the same source as the rendered page, so the two cannot drift."
|
|
3809
|
+
};
|
|
3810
|
+
}
|
|
3811
|
+
return { earned: SUBPOINTS.textAgreement.full, evidence: evidenceLines };
|
|
3812
|
+
}
|
|
3813
|
+
function canonicalOf(capture, representation) {
|
|
3814
|
+
if (capture !== null) {
|
|
3815
|
+
for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
|
|
3816
|
+
if (link.rel.includes("canonical")) return link.url;
|
|
3817
|
+
}
|
|
3818
|
+
}
|
|
3819
|
+
if (representation !== null && representation.doc !== null) {
|
|
3820
|
+
for (const link of representation.doc.links) {
|
|
3821
|
+
if (link.rel.includes("canonical") && link.href !== null) return link.href;
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
return null;
|
|
3825
|
+
}
|
|
3826
|
+
function checkCanonical(context) {
|
|
3827
|
+
const split = SUBPOINTS.canonical;
|
|
3828
|
+
const htmlCanonical = canonicalOf(context.browserCapture, context.browser) ?? canonicalOf(context.agentCapture, context.agent);
|
|
3829
|
+
const agentCanonical = canonicalOf(context.agentCapture, context.agent);
|
|
3830
|
+
const present = htmlCanonical !== null;
|
|
3831
|
+
const absolute = htmlCanonical !== null && /^https?:\/\//i.test(htmlCanonical);
|
|
3832
|
+
const consistent = htmlCanonical !== null && agentCanonical !== null && agentCanonical === htmlCanonical;
|
|
3833
|
+
if (htmlCanonical !== null && agentCanonical !== null && agentCanonical !== htmlCanonical) {
|
|
3834
|
+
context.flags.push({
|
|
3835
|
+
id: "canonical-mismatch",
|
|
3836
|
+
severity: "warn",
|
|
3837
|
+
basis: "measured",
|
|
3838
|
+
message: `The two representations of this URL declare different canonicals: ${agentCanonical} and ${htmlCanonical}.`,
|
|
3839
|
+
evidence: [
|
|
3840
|
+
measured("Agent probe canonical", agentCanonical),
|
|
3841
|
+
measured("HTML canonical", htmlCanonical)
|
|
3842
|
+
]
|
|
3843
|
+
});
|
|
3844
|
+
}
|
|
3845
|
+
return {
|
|
3846
|
+
earned: (present ? split.present : 0) + (absolute ? split.absolute : 0) + (consistent ? split.consistentAcrossProbes : 0),
|
|
3847
|
+
evidence: [
|
|
3848
|
+
measured("Canonical (HTML)", htmlCanonical ?? "absent"),
|
|
3849
|
+
measured("Canonical (agent representation)", agentCanonical ?? "absent"),
|
|
3850
|
+
measured("Absolute", yesNo(absolute)),
|
|
3851
|
+
measured("Same across both probes", yesNo(consistent))
|
|
3852
|
+
],
|
|
3853
|
+
remedy: consistent ? void 0 : agentCanonical === null ? 'Declare the canonical on the machine representation too \u2014 `Link: <https://\u2026>; rel="canonical"`. A representation with no canonical cannot be attributed to a page.' : "Declare one canonical URL and use it in both representations."
|
|
3854
|
+
};
|
|
3855
|
+
}
|
|
3856
|
+
function checkCacheValidators(context) {
|
|
3857
|
+
const split = SUBPOINTS.cacheValidators;
|
|
3858
|
+
const cacheControl = header(context.agentCapture.headers, "cache-control");
|
|
3859
|
+
const directives = headerTokens(cacheControl);
|
|
3860
|
+
const noStore = directives.includes("no-store");
|
|
3861
|
+
const maxAge = directives.some((token) => {
|
|
3862
|
+
const match = /^(?:max-age|s-maxage)=(\d{1,10})$/.exec(token);
|
|
3863
|
+
return match !== null && Number(match[1]) > 0;
|
|
3864
|
+
});
|
|
3865
|
+
const noCache = directives.includes("no-cache") || directives.includes("must-revalidate");
|
|
3866
|
+
const etag = header(context.agentCapture.headers, "etag");
|
|
3867
|
+
const lastModified = header(context.agentCapture.headers, "last-modified");
|
|
3868
|
+
const validator = etag !== null || lastModified !== null;
|
|
3869
|
+
const sane = cacheControl !== null && !noStore && (maxAge || noCache && validator);
|
|
3870
|
+
return {
|
|
3871
|
+
earned: (sane ? split.saneCacheControl : 0) + (validator ? split.validator : 0),
|
|
3872
|
+
evidence: [
|
|
3873
|
+
measured("Cache-Control", cacheControl ?? "absent"),
|
|
3874
|
+
measured("ETag", etag ?? "absent"),
|
|
3875
|
+
measured("Last-Modified", lastModified ?? "absent")
|
|
3876
|
+
],
|
|
3877
|
+
remedy: sane && validator ? void 0 : "Send a `Cache-Control` a cache can act on, plus an `ETag` or `Last-Modified`. Repeat fetches are most of agent traffic."
|
|
3878
|
+
};
|
|
3879
|
+
}
|
|
3880
|
+
function bodyOf(probe) {
|
|
3881
|
+
if (probe === null || !probe.result.ok) return null;
|
|
3882
|
+
const capture = probe.result.capture;
|
|
3883
|
+
if (capture.status < 200 || capture.status >= 300) return null;
|
|
3884
|
+
return typeof capture.body === "string" ? capture.body : null;
|
|
3885
|
+
}
|
|
3886
|
+
var MARKDOWN_LINK = /\[[^\]\n]{1,200}\]\(([^)\s]{1,500})\)/g;
|
|
3887
|
+
function checkLlmsTxt(context) {
|
|
3888
|
+
const split = SUBPOINTS.llmsTxt;
|
|
3889
|
+
const body = bodyOf(context.evidence.probes.llmsTxt);
|
|
3890
|
+
if (body === null || body.trim().length === 0) {
|
|
3891
|
+
return {
|
|
3892
|
+
earned: 0,
|
|
3893
|
+
evidence: [measured("/llms.txt", body === null ? "absent or non-2xx" : "empty")],
|
|
3894
|
+
remedy: "Publish /llms.txt: an H1 title, a short summary, and links to the pages that matter. It is worth 2 points of 100, deliberately."
|
|
3895
|
+
};
|
|
3896
|
+
}
|
|
3897
|
+
const hasTitle = /^#\s+\S/m.test(body);
|
|
3898
|
+
MARKDOWN_LINK.lastIndex = 0;
|
|
3899
|
+
const hasLinks = MARKDOWN_LINK.test(body);
|
|
3900
|
+
const specShaped = hasTitle && hasLinks;
|
|
3901
|
+
return {
|
|
3902
|
+
earned: specShaped ? split.specShaped : split.present,
|
|
3903
|
+
evidence: [
|
|
3904
|
+
measured("/llms.txt", `${body.length} characters`),
|
|
3905
|
+
measured("H1 title", yesNo(hasTitle)),
|
|
3906
|
+
measured("Markdown links", yesNo(hasLinks))
|
|
3907
|
+
],
|
|
3908
|
+
remedy: specShaped ? void 0 : "Give /llms.txt an H1 title and at least one Markdown link."
|
|
3909
|
+
};
|
|
3910
|
+
}
|
|
3911
|
+
function checkSitemap(context) {
|
|
3912
|
+
return {
|
|
3913
|
+
earned: context.policy.sitemapDeclared ? SUBPOINTS.sitemap.full : 0,
|
|
3914
|
+
evidence: [
|
|
3915
|
+
measured("Sitemap: in robots.txt", yesNo(context.policy.sitemapDeclared)),
|
|
3916
|
+
measured(
|
|
3917
|
+
"Sitemaps declared",
|
|
3918
|
+
context.robots === null ? "n/a" : context.robots.sitemaps.join(", ") || "none"
|
|
3919
|
+
)
|
|
3920
|
+
],
|
|
3921
|
+
remedy: context.policy.sitemapDeclared ? void 0 : "Declare `Sitemap:` in robots.txt."
|
|
3922
|
+
};
|
|
3923
|
+
}
|
|
3924
|
+
var ENDPOINT_TYPES = [
|
|
3925
|
+
"application/rss+xml",
|
|
3926
|
+
"application/atom+xml",
|
|
3927
|
+
"application/feed+json",
|
|
3928
|
+
"application/json",
|
|
3929
|
+
"application/ld+json",
|
|
3930
|
+
"application/vnd.api+json",
|
|
3931
|
+
"application/schema+json",
|
|
3932
|
+
"application/graphql",
|
|
3933
|
+
"application/openapi+json",
|
|
3934
|
+
"application/yaml",
|
|
3935
|
+
"text/calendar"
|
|
3936
|
+
];
|
|
3937
|
+
var ENDPOINT_RELS = [
|
|
3938
|
+
"service-desc",
|
|
3939
|
+
"service-doc",
|
|
3940
|
+
"api",
|
|
3941
|
+
"describedby",
|
|
3942
|
+
"ucp",
|
|
3943
|
+
"mcp"
|
|
3944
|
+
];
|
|
3945
|
+
var ENDPOINT_PATH_MARKERS = [
|
|
3946
|
+
"/api",
|
|
3947
|
+
"/mcp",
|
|
3948
|
+
"/graphql",
|
|
3949
|
+
"/openapi",
|
|
3950
|
+
"/.well-known/",
|
|
3951
|
+
".json",
|
|
3952
|
+
".ics",
|
|
3953
|
+
".rss",
|
|
3954
|
+
".atom"
|
|
3955
|
+
];
|
|
3956
|
+
function checkMachineEndpoint(context) {
|
|
3957
|
+
const declarations = [];
|
|
3958
|
+
const links = parseLinkHeaders([
|
|
3959
|
+
...headerAll(context.agentCapture.headers, "link"),
|
|
3960
|
+
...context.browserCapture === null ? [] : headerAll(context.browserCapture.headers, "link")
|
|
3961
|
+
]);
|
|
3962
|
+
for (const link of links) {
|
|
3963
|
+
if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))
|
|
3964
|
+
declarations.push(`Link rel=${link.rel.join(" ")} \u2192 ${link.url}`);
|
|
3965
|
+
else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))
|
|
3966
|
+
declarations.push(`Link type=${link.type} \u2192 ${link.url}`);
|
|
3967
|
+
}
|
|
3968
|
+
if (context.structural !== null && context.structural.doc !== null) {
|
|
3969
|
+
for (const link of context.structural.doc.links) {
|
|
3970
|
+
if (link.href === null) continue;
|
|
3971
|
+
if (link.rel.some((rel) => ENDPOINT_RELS.includes(rel)))
|
|
3972
|
+
declarations.push(`<link rel="${link.rel.join(" ")}"> \u2192 ${link.href}`);
|
|
3973
|
+
else if (link.type !== null && ENDPOINT_TYPES.includes(link.type))
|
|
3974
|
+
declarations.push(`<link type="${link.type}"> \u2192 ${link.href}`);
|
|
3975
|
+
}
|
|
3976
|
+
}
|
|
3977
|
+
const llms = bodyOf(context.evidence.probes.llmsTxt);
|
|
3978
|
+
if (llms !== null) {
|
|
3979
|
+
MARKDOWN_LINK.lastIndex = 0;
|
|
3980
|
+
let match;
|
|
3981
|
+
while ((match = MARKDOWN_LINK.exec(llms)) !== null) {
|
|
3982
|
+
const url = (match[1] ?? "").toLowerCase();
|
|
3983
|
+
if (ENDPOINT_PATH_MARKERS.some((marker) => url.includes(marker)))
|
|
3984
|
+
declarations.push(`llms.txt \u2192 ${match?.[1] ?? url}`);
|
|
3985
|
+
}
|
|
3986
|
+
}
|
|
3987
|
+
const ucp = bodyOf(context.evidence.probes.wellKnownUcp);
|
|
3988
|
+
if (ucp !== null && ucp.trim().length > 0) declarations.push("/.well-known/ucp");
|
|
3989
|
+
return {
|
|
3990
|
+
earned: declarations.length > 0 ? SUBPOINTS.machineEndpoint.full : 0,
|
|
3991
|
+
evidence: [
|
|
3992
|
+
measured(
|
|
3993
|
+
"Declared machine endpoints",
|
|
3994
|
+
declarations.length === 0 ? "none" : declarations.join("; ")
|
|
3995
|
+
),
|
|
3996
|
+
measured("Probed paths", "/robots.txt, /llms.txt, /.well-known/ucp \u2014 ARS probes no others")
|
|
3997
|
+
],
|
|
3998
|
+
remedy: declarations.length > 0 ? void 0 : "Declare one machine endpoint \u2014 a feed, an OpenAPI document, /.well-known/ucp \u2014 with a `Link` header or a `<link>`. ARS does not guess at paths."
|
|
3999
|
+
};
|
|
4000
|
+
}
|
|
4001
|
+
function weightOf(ruleset, id) {
|
|
4002
|
+
return ruleset.weights[id] ?? 0;
|
|
4003
|
+
}
|
|
4004
|
+
function buildCheck(ruleset, id, outcome) {
|
|
4005
|
+
const meta = CHECK_META[id];
|
|
4006
|
+
const weight = weightOf(ruleset, id);
|
|
4007
|
+
const earned = Math.max(0, Math.min(weight, outcome.earned));
|
|
4008
|
+
const check = {
|
|
4009
|
+
id,
|
|
4010
|
+
label: meta.label,
|
|
4011
|
+
basis: meta.basis,
|
|
4012
|
+
weight,
|
|
4013
|
+
earned,
|
|
4014
|
+
evidence: outcome.evidence
|
|
4015
|
+
};
|
|
4016
|
+
return outcome.remedy === void 0 || earned === weight ? check : { ...check, remedy: outcome.remedy };
|
|
4017
|
+
}
|
|
4018
|
+
var DIMENSION_ORDER = [
|
|
4019
|
+
"retrievability",
|
|
4020
|
+
"machine-representation",
|
|
4021
|
+
"fact-coverage",
|
|
4022
|
+
"fact-position",
|
|
4023
|
+
"structured-data",
|
|
4024
|
+
"contract-discovery"
|
|
4025
|
+
];
|
|
4026
|
+
function buildDimensions(checks) {
|
|
4027
|
+
return DIMENSION_ORDER.map((id) => {
|
|
4028
|
+
const own = checks.filter((check) => CHECK_META[check.id].dimension === id);
|
|
4029
|
+
return {
|
|
4030
|
+
id,
|
|
4031
|
+
label: DIMENSION_META[id].label,
|
|
4032
|
+
weight: DIMENSION_META[id].weight,
|
|
4033
|
+
earned: own.reduce((sum, check) => sum + check.earned, 0),
|
|
4034
|
+
basis: own.some((check) => check.basis === "heuristic") ? "heuristic" : "measured",
|
|
4035
|
+
checks: own
|
|
4036
|
+
};
|
|
4037
|
+
});
|
|
4038
|
+
}
|
|
4039
|
+
var FLAG_ORDER = [
|
|
4040
|
+
"substance-divergence",
|
|
4041
|
+
"structured-data-divergence",
|
|
4042
|
+
"robots-contradiction",
|
|
4043
|
+
"paywalled",
|
|
4044
|
+
"render-dependent",
|
|
4045
|
+
"scanner-blocked",
|
|
4046
|
+
"training-opt-out",
|
|
4047
|
+
"assistant-opt-out",
|
|
4048
|
+
"vary-missing",
|
|
4049
|
+
"canonical-mismatch",
|
|
4050
|
+
"body-truncated",
|
|
4051
|
+
"vantage-variance"
|
|
4052
|
+
];
|
|
4053
|
+
function sortFlags(flags) {
|
|
4054
|
+
return [...flags].sort((a, b) => FLAG_ORDER.indexOf(a.id) - FLAG_ORDER.indexOf(b.id));
|
|
4055
|
+
}
|
|
4056
|
+
function bandFor(score2, ruleset = DEFAULT_RULESET) {
|
|
4057
|
+
for (const band of ruleset.bands) if (score2 >= band.min && score2 <= band.max) return band;
|
|
4058
|
+
return null;
|
|
4059
|
+
}
|
|
4060
|
+
function captureOf(probe) {
|
|
4061
|
+
return probe !== null && probe.result.ok ? probe.result.capture : null;
|
|
4062
|
+
}
|
|
4063
|
+
function currencyHintOf(structural, agent) {
|
|
4064
|
+
for (const representation of [structural, agent]) {
|
|
4065
|
+
if (representation === null) continue;
|
|
4066
|
+
for (const node of representation.jsonLd.nodes) {
|
|
4067
|
+
for (const path of ["offers.priceCurrency", "priceCurrency"]) {
|
|
4068
|
+
const raw = readPath(node, path);
|
|
4069
|
+
if (raw !== null && /^[A-Za-z]{3}$/.test(raw.trim())) return raw.trim().toUpperCase();
|
|
4070
|
+
}
|
|
4071
|
+
}
|
|
4072
|
+
if (representation.doc === null) continue;
|
|
4073
|
+
for (const meta of representation.doc.metas) {
|
|
4074
|
+
const key = meta.property ?? meta.name;
|
|
4075
|
+
if (key !== "og:price:currency" && key !== "product:price:currency") continue;
|
|
4076
|
+
const value = meta.content;
|
|
4077
|
+
if (value !== null && /^[A-Za-z]{3}$/.test(value.trim())) return value.trim().toUpperCase();
|
|
4078
|
+
}
|
|
4079
|
+
}
|
|
4080
|
+
return void 0;
|
|
4081
|
+
}
|
|
4082
|
+
function pathOf(url, fallback) {
|
|
4083
|
+
try {
|
|
4084
|
+
return new URL(url).pathname;
|
|
4085
|
+
} catch {
|
|
4086
|
+
return fallback;
|
|
4087
|
+
}
|
|
4088
|
+
}
|
|
4089
|
+
function readRobots(probe) {
|
|
4090
|
+
if (probe === null) return { status: "missing", robots: null };
|
|
4091
|
+
if (!probe.result.ok) return { status: "error", robots: null };
|
|
4092
|
+
const capture = probe.result.capture;
|
|
4093
|
+
if (capture.status >= 500) return { status: "error", robots: null };
|
|
4094
|
+
if (capture.status >= 400) return { status: "missing", robots: null };
|
|
4095
|
+
const body = typeof capture.body === "string" ? capture.body : null;
|
|
4096
|
+
if (body === null) return { status: "missing", robots: null };
|
|
4097
|
+
const robots = parseRobots(body);
|
|
4098
|
+
const empty = robots.groups.length === 0 && robots.sitemaps.length === 0;
|
|
4099
|
+
return { status: empty && robots.malformedLines > 0 ? "unparseable" : "ok", robots };
|
|
4100
|
+
}
|
|
4101
|
+
function detectPaywall(context) {
|
|
4102
|
+
if (context.agentCapture.status === 402) return "HTTP 402";
|
|
4103
|
+
if (header(context.agentCapture.headers, "www-authenticate") !== null) return "WWW-Authenticate";
|
|
4104
|
+
for (const node of context.structural?.jsonLd.nodes ?? []) {
|
|
4105
|
+
const value = node.value["isAccessibleForFree"];
|
|
4106
|
+
if (value === false || value === "False" || value === "false")
|
|
4107
|
+
return "isAccessibleForFree: false";
|
|
4108
|
+
}
|
|
4109
|
+
return null;
|
|
4110
|
+
}
|
|
4111
|
+
function nonGrade(evidence, ruleset, outcome, reason, policy, flags) {
|
|
4112
|
+
const agentCapture = captureOf(evidence.probes.agent);
|
|
4113
|
+
const browserCapture = captureOf(evidence.probes.browser);
|
|
4114
|
+
const checks = Object.keys(CHECK_META).map(
|
|
4115
|
+
(id) => buildCheck(ruleset, id, {
|
|
4116
|
+
earned: 0,
|
|
4117
|
+
evidence: [{ label: "Not evaluated", value: reason, basis: CHECK_META[id].basis }]
|
|
4118
|
+
})
|
|
4119
|
+
);
|
|
4120
|
+
const htmlBytes = browserCapture?.bytes ?? agentCapture?.bytes ?? 0;
|
|
4121
|
+
const perToken = ruleset.thresholds["cost.approx-bytes-per-token"]?.[0] ?? 4;
|
|
4122
|
+
return {
|
|
4123
|
+
spec: "ars",
|
|
4124
|
+
specVersion: ARS_SPEC_VERSION,
|
|
4125
|
+
rulesetHash: rulesetHash(ruleset),
|
|
4126
|
+
corpusHash: ARS_CORPUS_HASH,
|
|
4127
|
+
evidenceHash: evidenceHash(evidence),
|
|
4128
|
+
vantage: evidence.vantage,
|
|
4129
|
+
target: {
|
|
4130
|
+
url: evidence.target.url,
|
|
4131
|
+
finalUrl: agentCapture?.finalUrl ?? evidence.target.url,
|
|
4132
|
+
origin: evidence.target.origin
|
|
4133
|
+
},
|
|
4134
|
+
outcome,
|
|
4135
|
+
score: null,
|
|
4136
|
+
grade: null,
|
|
4137
|
+
bandLabel: null,
|
|
4138
|
+
pageKind: "unknown",
|
|
4139
|
+
pageKindBasis: "heuristic",
|
|
4140
|
+
pageKindConfidence: "low",
|
|
4141
|
+
factProfile: profileFor("unknown"),
|
|
4142
|
+
facts: [],
|
|
4143
|
+
dimensions: buildDimensions(checks),
|
|
4144
|
+
flags: sortFlags(flags),
|
|
4145
|
+
policy,
|
|
4146
|
+
cost: {
|
|
4147
|
+
htmlBytes,
|
|
4148
|
+
negotiatedBytes: null,
|
|
4149
|
+
approxHtmlTokens: idiv(htmlBytes, perToken),
|
|
4150
|
+
approxNegotiatedTokens: null,
|
|
4151
|
+
reductionRatio: null,
|
|
4152
|
+
firstCoreFactOffset: null,
|
|
4153
|
+
truncated: (agentCapture?.truncated ?? false) || (browserCapture?.truncated ?? false)
|
|
4154
|
+
},
|
|
4155
|
+
recommendations: [],
|
|
4156
|
+
measuredWeight: measuredWeightOf(ruleset),
|
|
4157
|
+
heuristicWeight: heuristicWeightOf(ruleset)
|
|
4158
|
+
};
|
|
4159
|
+
}
|
|
4160
|
+
function measuredWeightOf(ruleset) {
|
|
4161
|
+
let total = 0;
|
|
4162
|
+
for (const id of Object.keys(CHECK_META)) {
|
|
4163
|
+
if (CHECK_META[id].basis === "measured") total += weightOf(ruleset, id);
|
|
4164
|
+
}
|
|
4165
|
+
return total;
|
|
4166
|
+
}
|
|
4167
|
+
function heuristicWeightOf(ruleset) {
|
|
4168
|
+
let total = 0;
|
|
4169
|
+
for (const id of Object.keys(CHECK_META)) {
|
|
4170
|
+
if (CHECK_META[id].basis === "heuristic") total += weightOf(ruleset, id);
|
|
4171
|
+
}
|
|
4172
|
+
return total;
|
|
4173
|
+
}
|
|
4174
|
+
function unscoredReasonFor(error) {
|
|
4175
|
+
switch (error) {
|
|
4176
|
+
case "challenge":
|
|
4177
|
+
return { reason: "blocked-at-edge", detail: "challenge" };
|
|
4178
|
+
case "non-2xx":
|
|
4179
|
+
return { reason: "non-2xx" };
|
|
4180
|
+
case "too-many-redirects":
|
|
4181
|
+
return { reason: "too-many-redirects" };
|
|
4182
|
+
case "timeout":
|
|
4183
|
+
return { reason: "unreachable", detail: "timeout" };
|
|
4184
|
+
case "blocked-redirect":
|
|
4185
|
+
return { reason: "unreachable", detail: "blocked-redirect" };
|
|
4186
|
+
case "policy-rejected":
|
|
4187
|
+
return { reason: "unreachable", detail: "policy-rejected" };
|
|
4188
|
+
default:
|
|
4189
|
+
return { reason: "unreachable" };
|
|
4190
|
+
}
|
|
4191
|
+
}
|
|
4192
|
+
function score(evidence, ruleset = DEFAULT_RULESET) {
|
|
4193
|
+
const flags = [];
|
|
4194
|
+
const targetPath = pathOf(evidence.target.url, "/");
|
|
4195
|
+
const { status: robotsStatus, robots } = readRobots(evidence.probes.robotsTxt);
|
|
4196
|
+
const policy = buildPolicyReport(robots, robotsStatus, ruleset, targetPath);
|
|
4197
|
+
if (policy.trainingOptOut) {
|
|
4198
|
+
flags.push({
|
|
4199
|
+
id: "training-opt-out",
|
|
4200
|
+
severity: "info",
|
|
4201
|
+
basis: "measured",
|
|
4202
|
+
message: "This site blocks model-training crawlers while allowing assistant fetches. That is neutral in ARS: it never lowers the score.",
|
|
4203
|
+
evidence: [
|
|
4204
|
+
measured("Training audience", policy.audiences.training.matchedRule ?? "disallowed"),
|
|
4205
|
+
measured("Effect on this score", "none")
|
|
4206
|
+
]
|
|
4207
|
+
});
|
|
4208
|
+
}
|
|
4209
|
+
if (evidence.vantage === "public" && robots !== null) {
|
|
4210
|
+
const scannerDecision = decideScannerToken(robots, targetPath);
|
|
4211
|
+
if (scannerDecision) {
|
|
4212
|
+
flags.push({
|
|
4213
|
+
id: "scanner-blocked",
|
|
4214
|
+
severity: "info",
|
|
4215
|
+
basis: "measured",
|
|
4216
|
+
message: "robots.txt disallows the rebilder-ars scanner. We obeyed it and did not score this page.",
|
|
4217
|
+
evidence: [measured("Matched rule", scannerDecision)]
|
|
4218
|
+
});
|
|
4219
|
+
return nonGrade(
|
|
4220
|
+
evidence,
|
|
4221
|
+
ruleset,
|
|
4222
|
+
{ kind: "unscored", reason: "robots-disallow-scanner" },
|
|
4223
|
+
"robots.txt disallows the rebilder-ars token",
|
|
4224
|
+
policy,
|
|
4225
|
+
flags
|
|
4226
|
+
);
|
|
4227
|
+
}
|
|
4228
|
+
}
|
|
4229
|
+
if (robotsStatus === "error") {
|
|
4230
|
+
return nonGrade(
|
|
4231
|
+
evidence,
|
|
4232
|
+
ruleset,
|
|
4233
|
+
{ kind: "unscored", reason: "robots-unavailable" },
|
|
4234
|
+
"robots.txt returned a persistent error",
|
|
4235
|
+
policy,
|
|
4236
|
+
flags
|
|
4237
|
+
);
|
|
4238
|
+
}
|
|
4239
|
+
if (policy.deliberateOptOut) {
|
|
4240
|
+
flags.push({
|
|
4241
|
+
id: "assistant-opt-out",
|
|
4242
|
+
severity: "info",
|
|
4243
|
+
basis: "measured",
|
|
4244
|
+
message: "This site names assistant crawlers in robots.txt and disallows them. ARS records the choice and does not grade the page.",
|
|
4245
|
+
evidence: [
|
|
4246
|
+
measured("Matched group", policy.audiences.assistant.matchedGroup ?? "(named group)"),
|
|
4247
|
+
measured("Matched rule", policy.audiences.assistant.matchedRule ?? "Disallow")
|
|
4248
|
+
]
|
|
4249
|
+
});
|
|
4250
|
+
return nonGrade(
|
|
4251
|
+
evidence,
|
|
4252
|
+
ruleset,
|
|
4253
|
+
{ kind: "opt-out", audience: "assistant", wellFormed: true },
|
|
4254
|
+
"the site opted out of assistant crawling",
|
|
4255
|
+
policy,
|
|
4256
|
+
flags
|
|
4257
|
+
);
|
|
4258
|
+
}
|
|
4259
|
+
const agentProbe = evidence.probes.agent;
|
|
4260
|
+
if (!agentProbe.result.ok) {
|
|
4261
|
+
const { reason, detail } = unscoredReasonFor(agentProbe.result.error);
|
|
4262
|
+
if (reason === "blocked-at-edge") {
|
|
4263
|
+
flags.push({
|
|
4264
|
+
id: "scanner-blocked",
|
|
4265
|
+
severity: "warn",
|
|
4266
|
+
basis: "measured",
|
|
4267
|
+
message: "The origin answered the agent probe with a challenge or a block. ARS reports the evidence and does not grade the page.",
|
|
4268
|
+
evidence: [measured("Probe error", agentProbe.result.error)]
|
|
4269
|
+
});
|
|
4270
|
+
}
|
|
4271
|
+
const outcome = detail === void 0 ? { kind: "unscored", reason } : { kind: "unscored", reason, detail };
|
|
4272
|
+
return nonGrade(
|
|
4273
|
+
evidence,
|
|
4274
|
+
ruleset,
|
|
4275
|
+
outcome,
|
|
4276
|
+
`the agent probe failed: ${agentProbe.result.error}`,
|
|
4277
|
+
policy,
|
|
4278
|
+
flags
|
|
4279
|
+
);
|
|
4280
|
+
}
|
|
4281
|
+
const agentCapture = agentProbe.result.capture;
|
|
4282
|
+
if (agentCapture.status === 403 || agentCapture.status === 401 || agentCapture.status === 429) {
|
|
4283
|
+
flags.push({
|
|
4284
|
+
id: "scanner-blocked",
|
|
4285
|
+
severity: "warn",
|
|
4286
|
+
basis: "measured",
|
|
4287
|
+
message: `The origin answered the agent probe with HTTP ${agentCapture.status}. ARS reports the evidence and does not grade the page.`,
|
|
4288
|
+
evidence: [measured("HTTP status", String(agentCapture.status))]
|
|
4289
|
+
});
|
|
4290
|
+
return nonGrade(
|
|
4291
|
+
evidence,
|
|
4292
|
+
ruleset,
|
|
4293
|
+
{ kind: "unscored", reason: "blocked-at-edge", detail: `HTTP ${agentCapture.status}` },
|
|
4294
|
+
`the origin answered with HTTP ${agentCapture.status}`,
|
|
4295
|
+
policy,
|
|
4296
|
+
flags
|
|
4297
|
+
);
|
|
4298
|
+
}
|
|
4299
|
+
if (agentCapture.status < 200 || agentCapture.status >= 300) {
|
|
4300
|
+
return nonGrade(
|
|
4301
|
+
evidence,
|
|
4302
|
+
ruleset,
|
|
4303
|
+
{ kind: "unscored", reason: "non-2xx", detail: `HTTP ${agentCapture.status}` },
|
|
4304
|
+
`the origin answered with HTTP ${agentCapture.status}`,
|
|
4305
|
+
policy,
|
|
4306
|
+
flags
|
|
4307
|
+
);
|
|
4308
|
+
}
|
|
4309
|
+
if (agentCapture.redirects.length > ruleset.maxRedirects) {
|
|
4310
|
+
return nonGrade(
|
|
4311
|
+
evidence,
|
|
4312
|
+
ruleset,
|
|
4313
|
+
{
|
|
4314
|
+
kind: "unscored",
|
|
4315
|
+
reason: "too-many-redirects",
|
|
4316
|
+
detail: `${agentCapture.redirects.length} hops`
|
|
4317
|
+
},
|
|
4318
|
+
`the agent path took ${agentCapture.redirects.length} redirect hops`,
|
|
4319
|
+
policy,
|
|
4320
|
+
flags
|
|
4321
|
+
);
|
|
4322
|
+
}
|
|
4323
|
+
const browserCapture = captureOf(evidence.probes.browser);
|
|
4324
|
+
if (agentCapture.truncated || (browserCapture?.truncated ?? false)) {
|
|
4325
|
+
flags.push({
|
|
4326
|
+
id: "body-truncated",
|
|
4327
|
+
severity: "warn",
|
|
4328
|
+
basis: "measured",
|
|
4329
|
+
message: `A response exceeded the ${ruleset.maxBodyBytes}-byte body cap and was truncated. The fact set and the byte count would both be wrong, so the page is not scored.`,
|
|
4330
|
+
evidence: [
|
|
4331
|
+
measured("Body cap", `${ruleset.maxBodyBytes} bytes`),
|
|
4332
|
+
measured("Bytes read", `\u2265 ${agentCapture.bytes}`)
|
|
4333
|
+
]
|
|
4334
|
+
});
|
|
4335
|
+
return nonGrade(
|
|
4336
|
+
evidence,
|
|
4337
|
+
ruleset,
|
|
4338
|
+
{ kind: "unscored", reason: "truncated-evidence" },
|
|
4339
|
+
"the response exceeded the body cap and was truncated",
|
|
4340
|
+
policy,
|
|
4341
|
+
flags
|
|
4342
|
+
);
|
|
4343
|
+
}
|
|
4344
|
+
const agent = buildRepresentation(agentCapture);
|
|
4345
|
+
if (agent === null) {
|
|
4346
|
+
return nonGrade(
|
|
4347
|
+
evidence,
|
|
4348
|
+
ruleset,
|
|
4349
|
+
{
|
|
4350
|
+
kind: "unscored",
|
|
4351
|
+
reason: "evidence-incomplete",
|
|
4352
|
+
detail: "the bundle carries no response body"
|
|
4353
|
+
},
|
|
4354
|
+
"the evidence bundle carries hashes but no body, so it cannot be re-scored",
|
|
4355
|
+
policy,
|
|
4356
|
+
flags
|
|
4357
|
+
);
|
|
4358
|
+
}
|
|
4359
|
+
const browser = browserCapture === null ? null : buildRepresentation(browserCapture);
|
|
4360
|
+
const structural = browser !== null && browser.doc !== null ? browser : agent.doc !== null ? agent : browser;
|
|
4361
|
+
const classification = classify(pass1Signals(structural ?? agent, evidence.target.url));
|
|
4362
|
+
const profile = profileFor(classification.pageKind);
|
|
4363
|
+
const currencyHint = currencyHintOf(structural, agent);
|
|
4364
|
+
const extractContext = {
|
|
4365
|
+
profile,
|
|
4366
|
+
ruleset,
|
|
4367
|
+
baseUrl: agentCapture.finalUrl,
|
|
4368
|
+
origin: evidence.target.origin,
|
|
4369
|
+
currencyHint
|
|
4370
|
+
};
|
|
4371
|
+
const agentFacts = extractFacts(agent, extractContext);
|
|
4372
|
+
const browserFacts = browser === null || browser === agent ? [] : extractFacts(browser, { ...extractContext, baseUrl: browser.finalUrl });
|
|
4373
|
+
const structuralFacts = structural === agent ? agentFacts : structural === browser ? browserFacts : [];
|
|
4374
|
+
const facts = mergeFacts(agentFacts, structuralFacts);
|
|
4375
|
+
const context = {
|
|
4376
|
+
evidence,
|
|
4377
|
+
ruleset,
|
|
4378
|
+
agentCapture,
|
|
4379
|
+
browserCapture,
|
|
4380
|
+
agent,
|
|
4381
|
+
browser,
|
|
4382
|
+
structural,
|
|
4383
|
+
profile,
|
|
4384
|
+
facts,
|
|
4385
|
+
agentFacts,
|
|
4386
|
+
browserFacts,
|
|
4387
|
+
structuralFacts,
|
|
4388
|
+
policy,
|
|
4389
|
+
robots,
|
|
4390
|
+
flags
|
|
4391
|
+
};
|
|
4392
|
+
const paywall = detectPaywall(context);
|
|
4393
|
+
if (paywall !== null) {
|
|
4394
|
+
flags.push({
|
|
4395
|
+
id: "paywalled",
|
|
4396
|
+
severity: "info",
|
|
4397
|
+
basis: "measured",
|
|
4398
|
+
message: `This page declares a paywall (${paywall}). ARS scores the portion it was served and does not attempt to reach the gated part.`,
|
|
4399
|
+
evidence: [measured("Paywall signal", paywall)]
|
|
4400
|
+
});
|
|
4401
|
+
}
|
|
4402
|
+
const math = coverageMath(context);
|
|
4403
|
+
const offsets = coreOffsets(context);
|
|
4404
|
+
const negotiated = checkNegotiatedResponse(context);
|
|
4405
|
+
const checks = [
|
|
4406
|
+
buildCheck(ruleset, "retrievability.reachable", checkReachable(context)),
|
|
4407
|
+
buildCheck(ruleset, "retrievability.robots-policy", checkRobotsPolicy(context)),
|
|
4408
|
+
buildCheck(ruleset, "retrievability.render-independence", checkRenderIndependence(context)),
|
|
4409
|
+
buildCheck(ruleset, "machine-representation.negotiated-response", negotiated),
|
|
4410
|
+
buildCheck(
|
|
4411
|
+
ruleset,
|
|
4412
|
+
"machine-representation.declared-alternates",
|
|
4413
|
+
checkDeclaredAlternates(context)
|
|
4414
|
+
),
|
|
4415
|
+
buildCheck(
|
|
4416
|
+
ruleset,
|
|
4417
|
+
"machine-representation.vary-accept",
|
|
4418
|
+
checkVaryAccept(context, negotiated.earned)
|
|
4419
|
+
),
|
|
4420
|
+
buildCheck(
|
|
4421
|
+
ruleset,
|
|
4422
|
+
"machine-representation.substance-parity",
|
|
4423
|
+
checkSubstanceParity(context, negotiated.earned)
|
|
4424
|
+
),
|
|
4425
|
+
buildCheck(ruleset, "fact-coverage.core-facts", checkCoreFacts(context, math)),
|
|
4426
|
+
buildCheck(ruleset, "fact-coverage.context-cost", checkContextCost(context)),
|
|
4427
|
+
buildCheck(
|
|
4428
|
+
ruleset,
|
|
4429
|
+
"fact-position.first-core-fact-offset",
|
|
4430
|
+
checkFirstCoreFactOffset(context, offsets)
|
|
4431
|
+
),
|
|
4432
|
+
buildCheck(ruleset, "fact-position.front-window", checkFrontWindow(context, offsets)),
|
|
4433
|
+
buildCheck(ruleset, "structured-data.present", checkStructuredDataPresent(context)),
|
|
4434
|
+
buildCheck(ruleset, "structured-data.required-properties", checkRequiredProperties(context)),
|
|
4435
|
+
buildCheck(ruleset, "structured-data.text-agreement", checkTextAgreement(context)),
|
|
4436
|
+
buildCheck(ruleset, "contract-discovery.canonical", checkCanonical(context)),
|
|
4437
|
+
buildCheck(ruleset, "contract-discovery.cache-validators", checkCacheValidators(context)),
|
|
4438
|
+
buildCheck(ruleset, "contract-discovery.llms-txt", checkLlmsTxt(context)),
|
|
4439
|
+
buildCheck(ruleset, "contract-discovery.sitemap", checkSitemap(context)),
|
|
4440
|
+
buildCheck(ruleset, "contract-discovery.machine-endpoint", checkMachineEndpoint(context))
|
|
4441
|
+
];
|
|
4442
|
+
const dimensions = buildDimensions(checks);
|
|
4443
|
+
const total = dimensions.reduce((sum, dimension) => sum + dimension.earned, 0);
|
|
4444
|
+
const band = bandFor(total, ruleset);
|
|
4445
|
+
const grade = band?.grade ?? "F";
|
|
4446
|
+
const perToken = ruleset.thresholds["cost.approx-bytes-per-token"]?.[0] ?? 4;
|
|
4447
|
+
const htmlBytes = structural?.bytes ?? agent.bytes;
|
|
4448
|
+
const negotiatedBytes = negotiated.earned > 0 ? agent.bytes : null;
|
|
4449
|
+
const cost = {
|
|
4450
|
+
htmlBytes,
|
|
4451
|
+
negotiatedBytes,
|
|
4452
|
+
approxHtmlTokens: idiv(htmlBytes, perToken),
|
|
4453
|
+
approxNegotiatedTokens: negotiatedBytes === null ? null : idiv(negotiatedBytes, perToken),
|
|
4454
|
+
// Integer PERCENT of HTML bytes the machine representation eliminates:
|
|
4455
|
+
// 94 means "94% fewer bytes". §3.9 types this as a number and does not fix
|
|
4456
|
+
// its unit; a multiple (`4.2×`) would be a float, and this is the same
|
|
4457
|
+
// information with no rounding for two implementations to disagree about.
|
|
4458
|
+
reductionRatio: negotiatedBytes === null || htmlBytes === 0 ? null : Math.max(0, 100 - idiv(100 * negotiatedBytes, htmlBytes)),
|
|
4459
|
+
firstCoreFactOffset: offsets[0] ?? null,
|
|
4460
|
+
truncated: agent.truncated || (browser?.truncated ?? false)
|
|
4461
|
+
};
|
|
4462
|
+
const published = facts.map((fact) => ({
|
|
4463
|
+
kind: fact.kind,
|
|
4464
|
+
normalized: fact.normalized,
|
|
4465
|
+
source: fact.source,
|
|
4466
|
+
offset: fact.offset,
|
|
4467
|
+
corroborated: fact.corroborated
|
|
4468
|
+
}));
|
|
4469
|
+
return {
|
|
4470
|
+
spec: "ars",
|
|
4471
|
+
specVersion: ARS_SPEC_VERSION,
|
|
4472
|
+
rulesetHash: rulesetHash(ruleset),
|
|
4473
|
+
corpusHash: ARS_CORPUS_HASH,
|
|
4474
|
+
evidenceHash: evidenceHash(evidence),
|
|
4475
|
+
vantage: evidence.vantage,
|
|
4476
|
+
target: {
|
|
4477
|
+
url: evidence.target.url,
|
|
4478
|
+
finalUrl: agentCapture.finalUrl,
|
|
4479
|
+
origin: evidence.target.origin
|
|
4480
|
+
},
|
|
4481
|
+
outcome: { kind: "scored", grade, score: total },
|
|
4482
|
+
score: total,
|
|
4483
|
+
grade,
|
|
4484
|
+
bandLabel: band?.label ?? null,
|
|
4485
|
+
pageKind: classification.pageKind,
|
|
4486
|
+
pageKindBasis: "heuristic",
|
|
4487
|
+
pageKindConfidence: classification.confidence,
|
|
4488
|
+
factProfile: profile,
|
|
4489
|
+
facts: published,
|
|
4490
|
+
dimensions,
|
|
4491
|
+
flags: sortFlags(flags),
|
|
4492
|
+
policy,
|
|
4493
|
+
cost,
|
|
4494
|
+
recommendations: recommend({ dimensions, score: total }),
|
|
4495
|
+
measuredWeight: measuredWeightOf(ruleset),
|
|
4496
|
+
heuristicWeight: heuristicWeightOf(ruleset)
|
|
4497
|
+
};
|
|
4498
|
+
}
|
|
4499
|
+
var SCANNER_TOKEN = "rebilder-ars";
|
|
4500
|
+
function decideScannerToken(robots, path) {
|
|
4501
|
+
for (const group of robots.groups) {
|
|
4502
|
+
if (!group.agents.some((agent) => agent === SCANNER_TOKEN)) continue;
|
|
4503
|
+
let best = null;
|
|
4504
|
+
for (const value of group.allow) {
|
|
4505
|
+
if (!pathMatches(value, path)) continue;
|
|
4506
|
+
if (best === null || value.length > best.value.length) best = { field: "allow", value };
|
|
4507
|
+
}
|
|
4508
|
+
for (const value of group.disallow) {
|
|
4509
|
+
if (!pathMatches(value, path)) continue;
|
|
4510
|
+
if (best === null || value.length > best.value.length) best = { field: "disallow", value };
|
|
4511
|
+
}
|
|
4512
|
+
if (best !== null && best.field === "disallow") {
|
|
4513
|
+
return `User-agent: ${SCANNER_TOKEN} / Disallow: ${best.value}`;
|
|
4514
|
+
}
|
|
4515
|
+
}
|
|
4516
|
+
return null;
|
|
4517
|
+
}
|
|
4518
|
+
|
|
4519
|
+
export { ARS_CORPUS_HASH, ARS_HEURISTIC_WEIGHT, ARS_HEURISTIC_WEIGHT_CEILING, ARS_MEASURED_WEIGHT, ARS_SPEC_VERSION, CHECK_META, DEFAULT_RULESET, DIMENSION_META, PROFILES, SUBPOINTS, bandFor, canonicalJson, classify, evidenceHash, minorUnitDigits, parseMoneyText, profileFor, recommend, rulesetHash, score, sha256Hex };
|
|
4520
|
+
//# sourceMappingURL=index.js.map
|
|
4521
|
+
//# sourceMappingURL=index.js.map
|