@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.
@@ -0,0 +1,1318 @@
1
+ import { promises } from 'dns';
2
+ import * as http from 'http';
3
+ import * as https from 'https';
4
+
5
+ // src/probe/ssrf.ts
6
+ var ALLOW_PRIVATE_HOSTS = /* @__PURE__ */ Symbol("rebilder.ars.probe.allow-private-hosts");
7
+ var allowsPrivateHosts = (policy) => policy === ALLOW_PRIVATE_HOSTS;
8
+ var NOT_AN_IP = { family: null, reserved: false, label: "hostname" };
9
+ var IPV4_OCTET = /^(?:0|[1-9]\d{0,2})$/;
10
+ function parseIpv4(text) {
11
+ const parts = text.split(".");
12
+ if (parts.length !== 4) return null;
13
+ const octets = [];
14
+ for (const part of parts) {
15
+ if (!IPV4_OCTET.test(part)) return null;
16
+ const value = Number(part);
17
+ if (!Number.isInteger(value) || value > 255) return null;
18
+ octets.push(value);
19
+ }
20
+ const [a, b, c, d] = octets;
21
+ if (a === void 0 || b === void 0 || c === void 0 || d === void 0) return null;
22
+ return [a, b, c, d];
23
+ }
24
+ function classifyIpv4Octets(octets) {
25
+ const [a, b] = octets;
26
+ const v4 = (label, reserved) => ({
27
+ family: 4,
28
+ reserved,
29
+ label
30
+ });
31
+ if (a === 0) return v4("this-network (0.0.0.0/8)", true);
32
+ if (a === 10) return v4("private (10.0.0.0/8)", true);
33
+ if (a === 100 && b >= 64 && b <= 127) return v4("carrier-grade NAT (100.64.0.0/10)", true);
34
+ if (a === 127) return v4("loopback (127.0.0.0/8)", true);
35
+ if (a === 169 && b === 254) return v4("link-local / cloud metadata (169.254.0.0/16)", true);
36
+ if (a === 172 && b >= 16 && b <= 31) return v4("private (172.16.0.0/12)", true);
37
+ if (a === 192 && b === 0 && octets[2] === 0)
38
+ return v4("IETF protocol assignments (192.0.0.0/24)", true);
39
+ if (a === 192 && b === 168) return v4("private (192.168.0.0/16)", true);
40
+ if (a === 198 && (b === 18 || b === 19)) return v4("benchmarking (198.18.0.0/15)", true);
41
+ if (a >= 224 && a <= 239) return v4("multicast (224.0.0.0/4)", true);
42
+ if (a >= 240) return v4("reserved / broadcast (240.0.0.0/4)", true);
43
+ return v4("public", false);
44
+ }
45
+ function parseIpv6(input) {
46
+ let text = input.trim();
47
+ if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
48
+ const zone = text.indexOf("%");
49
+ if (zone !== -1) text = text.slice(0, zone);
50
+ if (text.length === 0 || !text.includes(":")) return null;
51
+ const lastColon = text.lastIndexOf(":");
52
+ const maybeV4 = text.slice(lastColon + 1);
53
+ if (maybeV4.includes(".")) {
54
+ const quad = parseIpv4(maybeV4);
55
+ if (quad === null) return null;
56
+ const hi = (quad[0] << 8 | quad[1]).toString(16);
57
+ const lo = (quad[2] << 8 | quad[3]).toString(16);
58
+ text = `${text.slice(0, lastColon + 1)}${hi}:${lo}`;
59
+ }
60
+ const doubleColon = text.indexOf("::");
61
+ if (doubleColon !== text.lastIndexOf("::")) return null;
62
+ const toGroups = (segment) => {
63
+ if (segment.length === 0) return [];
64
+ const out = [];
65
+ for (const piece of segment.split(":")) {
66
+ if (piece.length === 0 || piece.length > 4 || !/^[0-9a-fA-F]+$/.test(piece)) return null;
67
+ out.push(Number.parseInt(piece, 16));
68
+ }
69
+ return out;
70
+ };
71
+ if (doubleColon === -1) {
72
+ const only = toGroups(text);
73
+ return only !== null && only.length === 8 ? only : null;
74
+ }
75
+ const head = toGroups(text.slice(0, doubleColon));
76
+ const rest = toGroups(text.slice(doubleColon + 2));
77
+ if (head === null || rest === null) return null;
78
+ const explicit = head.length + rest.length;
79
+ if (explicit > 7) return null;
80
+ const zeros = new Array(8 - explicit).fill(0);
81
+ return [...head, ...zeros, ...rest];
82
+ }
83
+ function classifyIpv6Groups(groups) {
84
+ const v6 = (label, reserved) => ({
85
+ family: 6,
86
+ reserved,
87
+ label
88
+ });
89
+ const g = (index) => groups[index] ?? 0;
90
+ const embeddedV4 = (hi, lo) => [
91
+ hi >> 8 & 255,
92
+ hi & 255,
93
+ lo >> 8 & 255,
94
+ lo & 255
95
+ ];
96
+ const allZeroThrough = (upTo) => groups.slice(0, upTo).every((x) => x === 0);
97
+ if (groups.every((x) => x === 0)) return v6("unspecified (::)", true);
98
+ if (allZeroThrough(7) && g(7) === 1) return v6("loopback (::1)", true);
99
+ if (allZeroThrough(5) && g(5) === 65535) {
100
+ const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
101
+ return v6(`IPv4-mapped \u2192 ${inner.label}`, inner.reserved);
102
+ }
103
+ if (allZeroThrough(6)) {
104
+ const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
105
+ return v6(`IPv4-compatible \u2192 ${inner.label}`, true);
106
+ }
107
+ if (g(0) === 100 && g(1) === 65435 && g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {
108
+ const inner = classifyIpv4Octets(embeddedV4(g(6), g(7)));
109
+ return v6(`NAT64 64:ff9b::/96 \u2192 ${inner.label}`, inner.reserved);
110
+ }
111
+ if (g(0) === 8194) {
112
+ const inner = classifyIpv4Octets(embeddedV4(g(1), g(2)));
113
+ return v6(`6to4 2002::/16 \u2192 ${inner.label}`, inner.reserved);
114
+ }
115
+ if (g(0) === 256 && g(1) === 0 && g(2) === 0 && g(3) === 0)
116
+ return v6("discard-only (100::/64)", true);
117
+ if (g(0) === 8193 && g(1) === 3512) return v6("documentation (2001:db8::/32)", true);
118
+ if ((g(0) & 65024) === 64512) return v6("unique local (fc00::/7)", true);
119
+ if ((g(0) & 65472) === 65152) return v6("link-local (fe80::/10)", true);
120
+ if ((g(0) & 65280) === 65280) return v6("multicast (ff00::/8)", true);
121
+ return v6("public", false);
122
+ }
123
+ function classifyIp(text) {
124
+ const trimmed = text.trim();
125
+ const bare = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
126
+ const quad = parseIpv4(bare);
127
+ if (quad !== null) return classifyIpv4Octets(quad);
128
+ if (bare.includes(":")) {
129
+ const groups = parseIpv6(bare);
130
+ if (groups === null) return { family: 6, reserved: true, label: "unparseable IPv6 literal" };
131
+ return classifyIpv6Groups(groups);
132
+ }
133
+ if (/^[0-9.]+$/.test(bare))
134
+ return { family: 4, reserved: true, label: "unparseable IPv4 literal" };
135
+ return NOT_AN_IP;
136
+ }
137
+ var PRIVATE_SUFFIXES = [".localhost", ".local", ".internal"];
138
+ function guardUrl(input, policy) {
139
+ let url;
140
+ try {
141
+ url = new URL(input.trim());
142
+ } catch {
143
+ return { ok: false, reason: "That does not look like a valid URL." };
144
+ }
145
+ const httpsOnly = !policy.allowHttp;
146
+ if (httpsOnly && url.protocol !== "https:") {
147
+ return { ok: false, reason: "Only https:// URLs can be fetched." };
148
+ }
149
+ if (!httpsOnly && url.protocol !== "https:" && url.protocol !== "http:") {
150
+ return { ok: false, reason: "Only https:// and http:// URLs can be fetched." };
151
+ }
152
+ const defaultPort = url.protocol === "https:" ? "443" : "80";
153
+ if (url.port !== "" && url.port !== defaultPort && !allowsPrivateHosts(policy.hostPolicy)) {
154
+ return {
155
+ ok: false,
156
+ reason: `Non-standard ports cannot be fetched (${url.protocol}// on ${defaultPort} only).`
157
+ };
158
+ }
159
+ if (url.username !== "" || url.password !== "") {
160
+ return { ok: false, reason: "URLs with embedded credentials cannot be fetched." };
161
+ }
162
+ let hostname = url.hostname.toLowerCase();
163
+ if (hostname.endsWith(".") && hostname.length > 1) hostname = hostname.slice(0, -1);
164
+ const permissive = allowsPrivateHosts(policy.hostPolicy);
165
+ if (!permissive && (hostname === "localhost" || hostname.endsWith(".localhost"))) {
166
+ return { ok: false, reason: "localhost cannot be fetched." };
167
+ }
168
+ const classification = classifyIp(hostname);
169
+ if (classification.family === 6) {
170
+ if (!permissive) {
171
+ return { ok: false, reason: "IPv6 literal addresses cannot be fetched \u2014 use a hostname." };
172
+ }
173
+ }
174
+ if (classification.family !== null && classification.reserved && !permissive) {
175
+ return {
176
+ ok: false,
177
+ reason: `Private or reserved IP addresses cannot be fetched (${classification.label}).`
178
+ };
179
+ }
180
+ if (classification.family === null && !permissive) {
181
+ if (PRIVATE_SUFFIXES.some((suffix) => hostname.endsWith(suffix))) {
182
+ return {
183
+ ok: false,
184
+ reason: "Internal hostnames (.local, .internal, .localhost) cannot be fetched."
185
+ };
186
+ }
187
+ if (!hostname.includes(".")) {
188
+ return {
189
+ ok: false,
190
+ reason: "Single-label hostnames cannot be fetched \u2014 they resolve on the local network."
191
+ };
192
+ }
193
+ }
194
+ return { ok: true, url };
195
+ }
196
+ function createDnsResolver() {
197
+ return {
198
+ async resolve(hostname) {
199
+ const records = await promises.lookup(hostname, { all: true, verbatim: true });
200
+ return records.map((record) => ({
201
+ address: record.address,
202
+ family: record.family === 6 ? 6 : 4
203
+ }));
204
+ }
205
+ };
206
+ }
207
+ async function resolveAndValidate(hostname, resolver, hostPolicy) {
208
+ const literal = classifyIp(hostname);
209
+ if (literal.family !== null) {
210
+ if (literal.reserved && !allowsPrivateHosts(hostPolicy)) {
211
+ return {
212
+ ok: false,
213
+ kind: "policy-rejected",
214
+ reason: `target is a reserved address (${literal.label})`
215
+ };
216
+ }
217
+ return {
218
+ ok: true,
219
+ addresses: [{ address: hostname.replace(/^\[|\]$/g, ""), family: literal.family }]
220
+ };
221
+ }
222
+ let addresses;
223
+ try {
224
+ addresses = await resolver.resolve(hostname);
225
+ } catch (error) {
226
+ const detail = error instanceof Error ? error.message : String(error);
227
+ return {
228
+ ok: false,
229
+ kind: "unreachable",
230
+ reason: `DNS lookup failed for ${hostname}: ${detail}`
231
+ };
232
+ }
233
+ if (addresses.length === 0) {
234
+ return { ok: false, kind: "unreachable", reason: `DNS returned no addresses for ${hostname}` };
235
+ }
236
+ if (allowsPrivateHosts(hostPolicy)) return { ok: true, addresses };
237
+ for (const record of addresses) {
238
+ const classification = classifyIp(record.address);
239
+ if (classification.family === null) {
240
+ return {
241
+ ok: false,
242
+ kind: "policy-rejected",
243
+ reason: `DNS returned an unparseable address (${record.address})`
244
+ };
245
+ }
246
+ if (classification.reserved) {
247
+ return {
248
+ ok: false,
249
+ kind: "policy-rejected",
250
+ reason: `${hostname} resolves to a private or reserved address (${record.address}: ${classification.label})`
251
+ };
252
+ }
253
+ }
254
+ return { ok: true, addresses };
255
+ }
256
+ function pinnedLookup(addresses) {
257
+ return (_hostname, options, callback) => {
258
+ if (addresses.length === 0) {
259
+ callback(new Error("rebilder-ars: no pinned address for this connection"), "", 4);
260
+ return;
261
+ }
262
+ if (typeof options === "object" && options !== null && options.all === true) {
263
+ callback(
264
+ null,
265
+ addresses.map((record) => ({ address: record.address, family: record.family }))
266
+ );
267
+ return;
268
+ }
269
+ const first = addresses[0];
270
+ if (first === void 0) {
271
+ callback(new Error("rebilder-ars: no pinned address for this connection"), "", 4);
272
+ return;
273
+ }
274
+ callback(null, first.address, first.family);
275
+ };
276
+ }
277
+ function createPinnedTransport() {
278
+ return (url, init) => new Promise((resolve, reject) => {
279
+ let target;
280
+ try {
281
+ target = new URL(url);
282
+ } catch (error) {
283
+ reject(error instanceof Error ? error : new Error(String(error)));
284
+ return;
285
+ }
286
+ const secure = target.protocol === "https:";
287
+ const client = secure ? https : http;
288
+ const headers = { ...init.headers, host: target.host };
289
+ const request = client.request(
290
+ {
291
+ protocol: target.protocol,
292
+ hostname: target.hostname,
293
+ port: target.port === "" ? secure ? 443 : 80 : Number(target.port),
294
+ path: `${target.pathname}${target.search}`,
295
+ method: "GET",
296
+ headers,
297
+ servername: secure ? target.hostname : void 0,
298
+ lookup: pinnedLookup(init.pinnedAddresses),
299
+ agent: false,
300
+ signal: init.signal
301
+ },
302
+ (response) => {
303
+ const collected = {};
304
+ const raw = response.rawHeaders;
305
+ for (let i = 0; i + 1 < raw.length; i += 2) {
306
+ const name = (raw[i] ?? "").toLowerCase();
307
+ const value = raw[i + 1] ?? "";
308
+ const existing = collected[name];
309
+ if (existing) existing.push(value);
310
+ else collected[name] = [value];
311
+ }
312
+ const body = new ReadableStream({
313
+ start(controller) {
314
+ response.on("data", (chunk) => {
315
+ controller.enqueue(new Uint8Array(chunk));
316
+ if ((controller.desiredSize ?? 1) <= 0) response.pause();
317
+ });
318
+ response.on("end", () => {
319
+ try {
320
+ controller.close();
321
+ } catch {
322
+ }
323
+ });
324
+ response.on("error", (error) => {
325
+ try {
326
+ controller.error(error);
327
+ } catch {
328
+ }
329
+ });
330
+ },
331
+ pull() {
332
+ response.resume();
333
+ },
334
+ cancel() {
335
+ response.destroy();
336
+ request.destroy();
337
+ }
338
+ });
339
+ resolve({ status: response.statusCode ?? 0, headers: collected, body });
340
+ }
341
+ );
342
+ request.on("error", (error) => reject(error));
343
+ request.end();
344
+ });
345
+ }
346
+
347
+ // src/profiles.ts
348
+ var PROFILE_BY_KIND = {
349
+ product: {
350
+ pageKind: "product",
351
+ core: ["title", "price", "currency", "availability"],
352
+ extended: ["brand", "sku", "shipping", "returns", "description"],
353
+ byteReference: 8 * 1024
354
+ },
355
+ collection: {
356
+ pageKind: "collection",
357
+ core: ["title", "item-count", "item-link"],
358
+ extended: ["price", "availability", "description"],
359
+ byteReference: 16 * 1024
360
+ },
361
+ article: {
362
+ pageKind: "article",
363
+ core: ["title", "author", "published"],
364
+ extended: ["updated", "section", "description"],
365
+ byteReference: 40 * 1024
366
+ },
367
+ place: {
368
+ pageKind: "place",
369
+ core: ["org-name", "address", "hours", "phone"],
370
+ extended: ["email", "service-area", "primary-action-url", "description"],
371
+ byteReference: 8 * 1024
372
+ },
373
+ service: {
374
+ pageKind: "service",
375
+ core: ["title", "price", "primary-action-url"],
376
+ extended: ["duration", "eligibility", "service-area", "description", "updated"],
377
+ byteReference: 8 * 1024
378
+ },
379
+ faq: {
380
+ pageKind: "faq",
381
+ core: ["title", "question-answer"],
382
+ extended: ["updated", "description"],
383
+ byteReference: 16 * 1024
384
+ },
385
+ document: {
386
+ pageKind: "document",
387
+ core: ["title", "updated", "authority"],
388
+ extended: ["description", "primary-action-url", "section"],
389
+ byteReference: 24 * 1024
390
+ },
391
+ unknown: {
392
+ pageKind: "unknown",
393
+ core: ["title", "description", "primary-action-url"],
394
+ extended: ["updated", "org-name"],
395
+ byteReference: 16 * 1024
396
+ }
397
+ };
398
+ var PROFILES = Object.freeze(Object.values(PROFILE_BY_KIND));
399
+
400
+ // src/ruleset.ts
401
+ function deepFreeze(value) {
402
+ if (typeof value !== "object" || value === null) return value;
403
+ for (const child of Object.values(value)) deepFreeze(child);
404
+ return Object.freeze(value);
405
+ }
406
+ var WEIGHTS = {
407
+ // D1 Retrievability — 20
408
+ "retrievability.reachable": 8,
409
+ "retrievability.robots-policy": 6,
410
+ "retrievability.render-independence": 6,
411
+ // D2 Machine representation — 20
412
+ "machine-representation.negotiated-response": 10,
413
+ "machine-representation.declared-alternates": 4,
414
+ "machine-representation.vary-accept": 3,
415
+ "machine-representation.substance-parity": 3,
416
+ // D3 Fact coverage — 20
417
+ "fact-coverage.core-facts": 14,
418
+ "fact-coverage.context-cost": 6,
419
+ // D4 Fact position — 10
420
+ "fact-position.first-core-fact-offset": 5,
421
+ "fact-position.front-window": 5,
422
+ // D5 Structured data — 15
423
+ "structured-data.present": 5,
424
+ "structured-data.required-properties": 7,
425
+ "structured-data.text-agreement": 3,
426
+ // D6 Contract & discovery — 15
427
+ "contract-discovery.canonical": 4,
428
+ "contract-discovery.cache-validators": 3,
429
+ "contract-discovery.llms-txt": 2,
430
+ "contract-discovery.sitemap": 2,
431
+ "contract-discovery.machine-endpoint": 4
432
+ };
433
+ var THRESHOLDS = {
434
+ /**
435
+ * D3.1 fact weighting, in quarter-units (§3.6), as
436
+ * `[corroboratedCore, uncorroboratedCore, corroboratedExtended, uncorroboratedExtended]`:
437
+ * coreUnits = 4 × corroborated core + 2 × uncorroborated core
438
+ * extendedUnits = 1 × corroborated extended + 0 × uncorroborated extended
439
+ * "Extended = ¼ credit" is the single definition of extended credit.
440
+ */
441
+ "fact-coverage.fact-units": [4, 2, 1, 0],
442
+ /**
443
+ * D3.1 denominator multiplier: `denominator = 4 × coreSize`, i.e. full credit
444
+ * is every core fact corroborated. `coveragePct` is then
445
+ * `min(100, (100 × (coreUnits + extendedUnits) + denominator / 2) / denominator)`.
446
+ */
447
+ "fact-coverage.core-denominator-multiplier": [4],
448
+ /**
449
+ * D3.1 density band. AT-LEAST over
450
+ * `factsPerKiB100 = (coreFound × 100 + extendedFound × 25) × 1024 / max(1, bytes)`.
451
+ * The `max(1, bytes)` clamp is normative and replaces `max(1, bytes / 1024)`,
452
+ * which let a 200-byte stub top the band. Density saturates at ≥2 facts/KiB so
453
+ * that keyword stuffing is pointless — fixtures `031` and `032` must score
454
+ * identically.
455
+ * Earned = `(14 × coveragePct × densityPct + 5000) / 10000`.
456
+ */
457
+ "fact-coverage.density": [200, 100, 100, 85, 50, 70, 20, 50, 5, 30, 0, 15],
458
+ /**
459
+ * D3.2 context cost, 6 pts. AT-MOST over
460
+ * `ratio = 100 × bytes / byteReference[pageKind]`; above the last threshold, 0.
461
+ */
462
+ "fact-coverage.context-cost": [100, 6, 200, 5, 500, 3, 1500, 1],
463
+ /** D4.1 first-core-fact byte offset, 5 pts. AT-MOST over the offset in bytes; else 0. */
464
+ "fact-position.first-core-fact-offset": [512, 5, 2048, 4, 8192, 2, 32768, 1],
465
+ /**
466
+ * D4.2 front window, 5 pts. AT-LEAST over the percentage of core facts whose
467
+ * offset falls inside the window; below the last threshold, 0.
468
+ */
469
+ "fact-position.front-window": [90, 5, 70, 4, 50, 3, 25, 1],
470
+ /**
471
+ * D4.2 window size: `max(2048, bytes / 5)`, as `[floor, divisor]`. ONE
472
+ * expression, integer division — the `0.2 × bytes` form is deleted, because
473
+ * two implementations rounding a float disagree at the boundary.
474
+ */
475
+ "fact-position.front-window-size": [2048, 5],
476
+ /**
477
+ * Approximate token estimate, as `[bytesPerToken]`. HEURISTIC: decoded UTF-8
478
+ * bytes are the normative measurement and approximate tokens are always
479
+ * rendered with `≈` and an "est." chip. chars/4 is not a token count and the
480
+ * spec says so.
481
+ */
482
+ "cost.approx-bytes-per-token": [4]
483
+ };
484
+ var AUDIENCE_TOKENS = {
485
+ /** User-triggered assistant fetches. THE audience ARS scores. */
486
+ assistant: [
487
+ "ChatGPT-User",
488
+ "Claude-User",
489
+ "Claude-SearchBot",
490
+ "DuckAssistBot",
491
+ "Meta-ExternalFetcher",
492
+ "MistralAI-User",
493
+ "OAI-SearchBot",
494
+ "Perplexity-User"
495
+ ],
496
+ /** Corpus/model-training crawlers. STRICTLY NEUTRAL — never lowers the score. */
497
+ training: [
498
+ "AI2Bot",
499
+ "Applebot-Extended",
500
+ "Bytespider",
501
+ "CCBot",
502
+ "ClaudeBot",
503
+ "Diffbot",
504
+ "FacebookBot",
505
+ "Google-Extended",
506
+ "GPTBot",
507
+ "Meta-ExternalAgent",
508
+ "PanguBot",
509
+ "Timpibot",
510
+ "anthropic-ai",
511
+ "cohere-ai",
512
+ "omgili"
513
+ ],
514
+ /** Classic search indexers. Reported only. */
515
+ search: ["Applebot", "Baiduspider", "Bingbot", "DuckDuckBot", "Googlebot", "Slurp", "YandexBot"]
516
+ };
517
+ var REQUIRED_PROPERTIES = {
518
+ product: ["name", "offers.price", "offers.priceCurrency", "offers.availability"],
519
+ collection: ["name", "numberOfItems", "itemListElement"],
520
+ article: ["headline", "author", "datePublished"],
521
+ place: ["name", "address", "openingHours", "telephone"],
522
+ service: ["name", "offers.price", "offers.priceCurrency", "potentialAction.target"],
523
+ faq: ["name", "mainEntity", "mainEntity.acceptedAnswer"],
524
+ document: ["name", "dateModified", "publisher"],
525
+ unknown: ["name"]
526
+ };
527
+ var ACTION_LEXICON = [
528
+ "add to bag",
529
+ "add to basket",
530
+ "add to cart",
531
+ "apply",
532
+ "apply now",
533
+ "book",
534
+ "book now",
535
+ "buy",
536
+ "buy now",
537
+ "call now",
538
+ "checkout",
539
+ "contact",
540
+ "contact us",
541
+ "donate",
542
+ "download",
543
+ "email us",
544
+ "enroll",
545
+ "get a quote",
546
+ "get quote",
547
+ "get started",
548
+ "join",
549
+ "make an appointment",
550
+ "order",
551
+ "order now",
552
+ "purchase",
553
+ "register",
554
+ "request",
555
+ "request a demo",
556
+ "request a quote",
557
+ "reserve",
558
+ "schedule",
559
+ "sign up",
560
+ "signup",
561
+ "start",
562
+ "start free trial",
563
+ "subscribe"
564
+ ];
565
+ var BANDS = [
566
+ {
567
+ grade: "A",
568
+ min: 90,
569
+ max: 100,
570
+ label: "Agent-native",
571
+ meaning: "Facts are in a machine representation, complete for this page kind, front-loaded, and cheap to fetch."
572
+ },
573
+ {
574
+ grade: "B",
575
+ min: 75,
576
+ max: 89,
577
+ label: "Agent-friendly",
578
+ meaning: "All core facts are present and findable; the agent pays more bytes than it needs, or one signal is missing."
579
+ },
580
+ {
581
+ grade: "C",
582
+ min: 60,
583
+ max: 74,
584
+ label: "Readable with effort",
585
+ meaning: "Core facts are extractable from HTML, at high cost."
586
+ },
587
+ {
588
+ grade: "D",
589
+ min: 40,
590
+ max: 59,
591
+ label: "Partial",
592
+ meaning: "Some core facts for this page kind were not found in the fetched response."
593
+ },
594
+ {
595
+ grade: "F",
596
+ min: 0,
597
+ max: 39,
598
+ label: "Not extractable",
599
+ meaning: "Few or no core facts for this page kind were found in the fetched response."
600
+ }
601
+ ];
602
+ var DEFAULT_RULESET = deepFreeze({
603
+ version: "0.1.0",
604
+ weights: WEIGHTS,
605
+ thresholds: THRESHOLDS,
606
+ audienceTokens: AUDIENCE_TOKENS,
607
+ requiredProperties: REQUIRED_PROPERTIES,
608
+ actionLexicon: ACTION_LEXICON,
609
+ /** 2 MiB decoded. Streamed and aborted at the cap; `await response.text()` is forbidden. */
610
+ maxBodyBytes: 2 * 1024 * 1024,
611
+ /** 3 hops. Every hop re-resolves DNS and re-validates (§5.2). */
612
+ maxRedirects: 3,
613
+ /** 5s per request. See the ADDED note on `ArsRuleset` in ./types. */
614
+ timeoutMs: 5e3,
615
+ profiles: PROFILES,
616
+ bands: BANDS
617
+ });
618
+
619
+ // src/extract.ts
620
+ function utf8Length(text) {
621
+ let bytes = 0;
622
+ for (let i = 0; i < text.length; i++) {
623
+ const code = text.charCodeAt(i);
624
+ if (code < 128) bytes += 1;
625
+ else if (code < 2048) bytes += 2;
626
+ else if (code >= 55296 && code <= 56319) {
627
+ const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0;
628
+ if (next >= 56320 && next <= 57343) {
629
+ bytes += 4;
630
+ i++;
631
+ } else bytes += 3;
632
+ } else bytes += 3;
633
+ }
634
+ return bytes;
635
+ }
636
+ function parseRobots(text) {
637
+ const groups = [];
638
+ const sitemaps = [];
639
+ let malformedLines = 0;
640
+ let orphanRules = 0;
641
+ let current = null;
642
+ let openingGroup = false;
643
+ for (const rawLine of text.split(/\r?\n/)) {
644
+ const withoutComment = rawLine.split("#")[0] ?? "";
645
+ const line = withoutComment.trim();
646
+ if (line.length === 0) continue;
647
+ const colon = line.indexOf(":");
648
+ if (colon <= 0) {
649
+ malformedLines++;
650
+ continue;
651
+ }
652
+ const field = line.slice(0, colon).trim().toLowerCase();
653
+ const value = line.slice(colon + 1).trim();
654
+ if (field === "user-agent") {
655
+ if (current === null || !openingGroup) {
656
+ current = { agents: [], allow: [], disallow: [] };
657
+ groups.push(current);
658
+ openingGroup = true;
659
+ }
660
+ current.agents.push(value.toLowerCase());
661
+ continue;
662
+ }
663
+ if (field === "sitemap") {
664
+ sitemaps.push(value);
665
+ continue;
666
+ }
667
+ if (field === "allow" || field === "disallow") {
668
+ if (current === null) {
669
+ orphanRules++;
670
+ continue;
671
+ }
672
+ openingGroup = false;
673
+ if (field === "allow") current.allow.push(value);
674
+ else current.disallow.push(value);
675
+ continue;
676
+ }
677
+ if (field === "crawl-delay" || field === "host" || field === "clean-param") continue;
678
+ malformedLines++;
679
+ }
680
+ return { groups, sitemaps, malformedLines, orphanRules };
681
+ }
682
+ function pathMatches(pattern, path) {
683
+ if (pattern === "") return false;
684
+ const anchored = pattern.endsWith("$");
685
+ const body = anchored ? pattern.slice(0, -1) : pattern;
686
+ const segments = body.split("*");
687
+ let cursor = 0;
688
+ for (let i = 0; i < segments.length; i++) {
689
+ const segment = segments[i] ?? "";
690
+ if (i === 0) {
691
+ if (!path.startsWith(segment)) return false;
692
+ cursor = segment.length;
693
+ continue;
694
+ }
695
+ if (segment === "") continue;
696
+ const at = path.indexOf(segment, cursor);
697
+ if (at === -1) return false;
698
+ cursor = at + segment.length;
699
+ }
700
+ if (anchored) {
701
+ const last = segments[segments.length - 1] ?? "";
702
+ return segments.length === 1 ? path === body : path.endsWith(last);
703
+ }
704
+ return true;
705
+ }
706
+
707
+ // src/score.ts
708
+ function idiv(numerator, denominator) {
709
+ if (denominator === 0) return 0;
710
+ return (numerator - numerator % denominator) / denominator;
711
+ }
712
+ function deepFreeze2(value) {
713
+ if (typeof value !== "object" || value === null) return value;
714
+ for (const child of Object.values(value)) deepFreeze2(child);
715
+ return Object.freeze(value);
716
+ }
717
+ deepFreeze2({
718
+ /** D1.1, 8 = 4 + 2 + 2. */
719
+ reachable: { status2xx: 4, withinRedirectLimit: 2, noAcceptConditionalRedirect: 2 },
720
+ /** D1.2, 6 = 3 + 1 + 1 + 1. A disallowed assistant audience scores 0 for all four (§3.7). */
721
+ robotsPolicy: { assistantAllowed: 3, parsesClean: 1, noOrphanRules: 1, sitemapDeclared: 1 },
722
+ /**
723
+ * D1.3, 6. AT-LEAST band over `100 × coreFactsInHtml / coreProfileSize`, plus
724
+ * the `<noscript>` floor: a page whose facts are all client-rendered but which
725
+ * ships a non-empty `<noscript>` has told a JS-less caller something, and §3.8
726
+ * says that earns partial credit.
727
+ */
728
+ renderIndependence: {
729
+ band: [100, 6, 75, 5, 50, 3, 25, 1],
730
+ noscriptFloor: 1
731
+ },
732
+ /** D2.1, 10. All-or-nothing: a machine media type AND a body that is not HTML. */
733
+ negotiatedResponse: { full: 10 },
734
+ /** D2.2, 4. All-or-nothing. */
735
+ declaredAlternates: { full: 4 },
736
+ /** D2.3, 3. All-or-nothing, and 0 unless D2.1 > 0. */
737
+ varyAccept: { full: 3 },
738
+ /** D2.4, 3. All-or-nothing, and 0 unless D2.1 > 0 and a browser capture exists. */
739
+ substanceParity: { full: 3 },
740
+ /** D5.1, 5. Structured data present AND parsing; a partly-broken graph scores 3. */
741
+ structuredDataPresent: { clean: 5, partial: 3 },
742
+ /** D5.2, 7 = 2 (a recognised type) + 5 (required-property completeness, scaled). */
743
+ requiredProperties: { recognisedType: 2, completeness: 5 },
744
+ /** D5.3, 3. All-or-nothing. */
745
+ textAgreement: { full: 3 },
746
+ /** D6.1, 4 = 2 + 1 + 1. */
747
+ canonical: { present: 2, absolute: 1, consistentAcrossProbes: 1 },
748
+ /** D6.2, 3 = 2 + 1. */
749
+ cacheValidators: { saneCacheControl: 2, validator: 1 },
750
+ /** D6.3, 2. `present` alone for a file that exists; `specShaped` for one that parses as llms.txt. */
751
+ llmsTxt: { present: 1, specShaped: 2 },
752
+ /** D6.4, 2. All-or-nothing. */
753
+ sitemap: { full: 2 },
754
+ /** D6.5, 4. All-or-nothing over any ONE declared machine endpoint. */
755
+ machineEndpoint: { full: 4 }
756
+ });
757
+ var SHA256_K = [
758
+ 1116352408,
759
+ 1899447441,
760
+ 3049323471,
761
+ 3921009573,
762
+ 961987163,
763
+ 1508970993,
764
+ 2453635748,
765
+ 2870763221,
766
+ 3624381080,
767
+ 310598401,
768
+ 607225278,
769
+ 1426881987,
770
+ 1925078388,
771
+ 2162078206,
772
+ 2614888103,
773
+ 3248222580,
774
+ 3835390401,
775
+ 4022224774,
776
+ 264347078,
777
+ 604807628,
778
+ 770255983,
779
+ 1249150122,
780
+ 1555081692,
781
+ 1996064986,
782
+ 2554220882,
783
+ 2821834349,
784
+ 2952996808,
785
+ 3210313671,
786
+ 3336571891,
787
+ 3584528711,
788
+ 113926993,
789
+ 338241895,
790
+ 666307205,
791
+ 773529912,
792
+ 1294757372,
793
+ 1396182291,
794
+ 1695183700,
795
+ 1986661051,
796
+ 2177026350,
797
+ 2456956037,
798
+ 2730485921,
799
+ 2820302411,
800
+ 3259730800,
801
+ 3345764771,
802
+ 3516065817,
803
+ 3600352804,
804
+ 4094571909,
805
+ 275423344,
806
+ 430227734,
807
+ 506948616,
808
+ 659060556,
809
+ 883997877,
810
+ 958139571,
811
+ 1322822218,
812
+ 1537002063,
813
+ 1747873779,
814
+ 1955562222,
815
+ 2024104815,
816
+ 2227730452,
817
+ 2361852424,
818
+ 2428436474,
819
+ 2756734187,
820
+ 3204031479,
821
+ 3329325298
822
+ ];
823
+ function rotr(value, bits) {
824
+ return (value >>> bits | value << 32 - bits) >>> 0;
825
+ }
826
+ function sha256Hex(message) {
827
+ const bytes = new TextEncoder().encode(message);
828
+ const bitLength = bytes.length * 8;
829
+ const padded = new Uint8Array((idiv(bytes.length + 9 + 63, 64) || 1) * 64);
830
+ padded.set(bytes);
831
+ padded[bytes.length] = 128;
832
+ const view = new DataView(padded.buffer);
833
+ view.setUint32(padded.length - 8, idiv(bitLength, 4294967296), false);
834
+ view.setUint32(padded.length - 4, bitLength >>> 0, false);
835
+ const h = [
836
+ 1779033703,
837
+ 3144134277,
838
+ 1013904242,
839
+ 2773480762,
840
+ 1359893119,
841
+ 2600822924,
842
+ 528734635,
843
+ 1541459225
844
+ ];
845
+ const w = new Uint32Array(64);
846
+ for (let offset = 0; offset < padded.length; offset += 64) {
847
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
848
+ for (let i = 16; i < 64; i++) {
849
+ const a2 = w[i - 15] ?? 0;
850
+ const b2 = w[i - 2] ?? 0;
851
+ const s0 = (rotr(a2, 7) ^ rotr(a2, 18) ^ a2 >>> 3) >>> 0;
852
+ const s1 = (rotr(b2, 17) ^ rotr(b2, 19) ^ b2 >>> 10) >>> 0;
853
+ w[i] = (w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1 >>> 0;
854
+ }
855
+ let [a, b, c, d, e, f, g, hh] = h;
856
+ for (let i = 0; i < 64; i++) {
857
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
858
+ const ch = (e & f ^ ~e & g) >>> 0;
859
+ const temp1 = hh + s1 + ch + (SHA256_K[i] ?? 0) + (w[i] ?? 0) >>> 0;
860
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
861
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
862
+ const temp2 = s0 + maj >>> 0;
863
+ hh = g;
864
+ g = f;
865
+ f = e;
866
+ e = d + temp1 >>> 0;
867
+ d = c;
868
+ c = b;
869
+ b = a;
870
+ a = temp1 + temp2 >>> 0;
871
+ }
872
+ const next = [a, b, c, d, e, f, g, hh];
873
+ for (let i = 0; i < 8; i++) h[i] = (h[i] ?? 0) + (next[i] ?? 0) >>> 0;
874
+ }
875
+ let hex = "";
876
+ for (const word of h) hex += word.toString(16).padStart(8, "0");
877
+ return hex;
878
+ }
879
+ sha256Hex("ars-0.1-corpus-unfrozen");
880
+
881
+ // src/probe/limiter.ts
882
+ var ProbeBudgetExceededError = class extends Error {
883
+ budget;
884
+ constructor(budget) {
885
+ super(
886
+ `rebilder-ars: probe budget exhausted (${budget} requests this run). Raise it explicitly with createLimiter({ maxProbesPerRun }) \u2014 it is a soft cap, not a hard one, and raising it should be a decision someone made on purpose.`
887
+ );
888
+ this.name = "ProbeBudgetExceededError";
889
+ this.budget = budget;
890
+ }
891
+ };
892
+
893
+ // src/probe/index.ts
894
+ var ARS_USER_AGENT = "rebilder-ars/0.1 (+https://rebilder.com/bots)";
895
+ var ARS_ROBOTS_TOKEN = "rebilder-ars";
896
+ var AGENT_ACCEPT = "text/markdown;q=1.0, text/html;q=0.8, text/plain;q=0.5, */*;q=0.1";
897
+ var BROWSER_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
898
+ var ASSET_ACCEPT = "text/plain,*/*;q=0.5";
899
+ var AGENT_IDENTITY = {
900
+ role: "agent",
901
+ userAgent: ARS_USER_AGENT,
902
+ accept: AGENT_ACCEPT
903
+ };
904
+ var BROWSER_IDENTITY = {
905
+ role: "browser",
906
+ userAgent: ARS_USER_AGENT,
907
+ accept: BROWSER_ACCEPT
908
+ };
909
+ var ASSET_IDENTITY = {
910
+ role: "asset",
911
+ userAgent: ARS_USER_AGENT,
912
+ accept: ASSET_ACCEPT
913
+ };
914
+ var DEFAULT_IDENTITIES = Object.freeze([
915
+ AGENT_IDENTITY,
916
+ BROWSER_IDENTITY,
917
+ ASSET_IDENTITY
918
+ ]);
919
+ var IMPERSONATION_TOKENS = [
920
+ "googlebot",
921
+ "bingbot",
922
+ "applebot",
923
+ "baiduspider",
924
+ "yandexbot",
925
+ "duckduckbot",
926
+ "slurp",
927
+ "gptbot",
928
+ "chatgpt",
929
+ "oai-searchbot",
930
+ "claudebot",
931
+ "claude-user",
932
+ "claude-searchbot",
933
+ "anthropic-ai",
934
+ "perplexitybot",
935
+ "perplexity-user",
936
+ "facebookexternalhit",
937
+ "meta-external"
938
+ ];
939
+ function assertIdentities(identities) {
940
+ const byRole = /* @__PURE__ */ new Map();
941
+ for (const identity of identities) byRole.set(identity.role, identity);
942
+ const agent = byRole.get("agent");
943
+ const browser = byRole.get("browser");
944
+ if (agent === void 0 || browser === void 0) {
945
+ return 'the identity set must contain an "agent" and a "browser" entry (\xA73.3)';
946
+ }
947
+ if (agent.userAgent !== browser.userAgent) {
948
+ return "the agent and browser probes must send the SAME User-Agent and differ only in Accept (\xA73.3) \u2014 a UA difference makes the parity check measure our own request instead of the page";
949
+ }
950
+ for (const identity of identities) {
951
+ const ua = identity.userAgent.toLowerCase();
952
+ for (const token of IMPERSONATION_TOKENS) {
953
+ if (ua.includes(token)) {
954
+ return `the User-Agent names another operator's crawler ("${token}"). ARS imitates agent intent, never agent identity (\xA73.3)`;
955
+ }
956
+ }
957
+ }
958
+ return null;
959
+ }
960
+ function strictPolicy(limiter, ruleset = DEFAULT_RULESET) {
961
+ return {
962
+ allowHttp: false,
963
+ maxBodyBytes: ruleset.maxBodyBytes,
964
+ maxRedirects: ruleset.maxRedirects,
965
+ timeoutMs: ruleset.timeoutMs,
966
+ limiter,
967
+ identities: DEFAULT_IDENTITIES
968
+ };
969
+ }
970
+ function charsetOf(headers) {
971
+ const value = headers["content-type"]?.[0];
972
+ if (value === void 0) return "utf-8";
973
+ const match = /;\s*charset\s*=\s*"?([^";\s]+)"?/i.exec(value);
974
+ return match?.[1]?.toLowerCase() ?? "utf-8";
975
+ }
976
+ function createDecoder(charset) {
977
+ try {
978
+ return new TextDecoder(charset, { fatal: false });
979
+ } catch {
980
+ return new TextDecoder("utf-8", { fatal: false });
981
+ }
982
+ }
983
+ function fitPrefix(chunk, budget) {
984
+ let out = "";
985
+ let used = 0;
986
+ for (const codePoint of chunk) {
987
+ const size = utf8Length(codePoint);
988
+ if (used + size > budget) break;
989
+ out += codePoint;
990
+ used += size;
991
+ }
992
+ return out;
993
+ }
994
+ async function readCappedBody(body, charset, maxBytes) {
995
+ if (body === null) return { text: "", bytes: 0, truncated: false };
996
+ const decoder = createDecoder(charset);
997
+ const reader = body.getReader();
998
+ const parts = [];
999
+ const rawCeiling = maxBytes * 4;
1000
+ let bytes = 0;
1001
+ let rawBytes = 0;
1002
+ let truncated = false;
1003
+ try {
1004
+ for (; ; ) {
1005
+ const { done, value } = await reader.read();
1006
+ if (done) break;
1007
+ if (value === void 0) continue;
1008
+ rawBytes += value.byteLength;
1009
+ const chunk = decoder.decode(value, { stream: true });
1010
+ const chunkBytes = utf8Length(chunk);
1011
+ if (bytes + chunkBytes > maxBytes) {
1012
+ const prefix = fitPrefix(chunk, maxBytes - bytes);
1013
+ if (prefix.length > 0) parts.push(prefix);
1014
+ bytes += utf8Length(prefix);
1015
+ truncated = true;
1016
+ break;
1017
+ }
1018
+ parts.push(chunk);
1019
+ bytes += chunkBytes;
1020
+ if (rawBytes >= rawCeiling) {
1021
+ truncated = true;
1022
+ break;
1023
+ }
1024
+ }
1025
+ if (!truncated) {
1026
+ const tail = decoder.decode();
1027
+ if (tail.length > 0) {
1028
+ const tailBytes = utf8Length(tail);
1029
+ if (bytes + tailBytes > maxBytes) {
1030
+ const prefix = fitPrefix(tail, maxBytes - bytes);
1031
+ parts.push(prefix);
1032
+ bytes += utf8Length(prefix);
1033
+ truncated = true;
1034
+ } else {
1035
+ parts.push(tail);
1036
+ bytes += tailBytes;
1037
+ }
1038
+ }
1039
+ }
1040
+ } finally {
1041
+ await reader.cancel().catch(() => void 0);
1042
+ }
1043
+ return { text: parts.join(""), bytes, truncated };
1044
+ }
1045
+ function failed(error, detail) {
1046
+ return { ok: false, error, detail };
1047
+ }
1048
+ function classifyTransportError(error, signal) {
1049
+ const reason = signal.aborted ? signal.reason : void 0;
1050
+ if (reason instanceof Error && reason.name === "TimeoutError") return "timeout";
1051
+ if (error instanceof Error && error.name === "TimeoutError") return "timeout";
1052
+ if (signal.aborted) return "timeout";
1053
+ return "unreachable";
1054
+ }
1055
+ async function fetchWithPolicy(startUrl, headers, context) {
1056
+ const { policy, hostPolicy, transport, resolver } = context;
1057
+ const redirects = [];
1058
+ let current = startUrl;
1059
+ for (let hop = 0; hop < policy.maxRedirects; hop++) {
1060
+ const blocked = hop === 0 ? "policy-rejected" : "blocked-redirect";
1061
+ const guard = guardUrl(current, { allowHttp: policy.allowHttp, hostPolicy });
1062
+ if (!guard.ok) return failed(blocked, guard.reason);
1063
+ const resolved = await resolveAndValidate(guard.url.hostname, resolver, hostPolicy);
1064
+ if (!resolved.ok) {
1065
+ return failed(resolved.kind === "unreachable" ? "unreachable" : blocked, resolved.reason);
1066
+ }
1067
+ const lease = await policy.limiter.acquire(guard.url.hostname);
1068
+ const signal = AbortSignal.timeout(policy.timeoutMs);
1069
+ let response;
1070
+ try {
1071
+ response = await transport(guard.url.toString(), {
1072
+ headers,
1073
+ redirect: "manual",
1074
+ signal,
1075
+ pinnedAddresses: resolved.addresses
1076
+ });
1077
+ } catch (error) {
1078
+ lease.release();
1079
+ const kind = classifyTransportError(error, signal);
1080
+ return failed(
1081
+ kind,
1082
+ kind === "timeout" ? `No response within ${policy.timeoutMs}ms.` : `The URL could not be reached: ${error instanceof Error ? error.message : String(error)}`
1083
+ );
1084
+ }
1085
+ if (response.status >= 300 && response.status < 400) {
1086
+ const location = response.headers["location"]?.[0];
1087
+ if (response.body !== null) await response.body.cancel().catch(() => void 0);
1088
+ lease.release();
1089
+ if (location === void 0 || location.trim() === "") {
1090
+ return failed("non-2xx", `Redirect (${response.status}) without a Location header.`);
1091
+ }
1092
+ let next;
1093
+ try {
1094
+ next = new URL(location, guard.url).toString();
1095
+ } catch {
1096
+ return failed("blocked-redirect", `Redirect to an unparseable Location: ${location}`);
1097
+ }
1098
+ redirects.push({ status: response.status, location: next });
1099
+ current = next;
1100
+ continue;
1101
+ }
1102
+ let decoded;
1103
+ try {
1104
+ decoded = await readCappedBody(
1105
+ response.body,
1106
+ charsetOf(response.headers),
1107
+ policy.maxBodyBytes
1108
+ );
1109
+ } catch (error) {
1110
+ const kind = classifyTransportError(error, signal);
1111
+ return failed(
1112
+ kind,
1113
+ `The response body could not be read: ${error instanceof Error ? error.message : String(error)}`
1114
+ );
1115
+ } finally {
1116
+ lease.release();
1117
+ }
1118
+ const capture = {
1119
+ requestedUrl: startUrl,
1120
+ finalUrl: guard.url.toString(),
1121
+ redirects,
1122
+ status: response.status,
1123
+ headers: response.headers,
1124
+ bytes: decoded.bytes,
1125
+ bodySha256: sha256Hex(decoded.text),
1126
+ body: decoded.text,
1127
+ truncated: decoded.truncated
1128
+ };
1129
+ return { ok: true, capture };
1130
+ }
1131
+ return failed("too-many-redirects", `More than ${policy.maxRedirects - 1} redirects.`);
1132
+ }
1133
+ function scannerDisallows(robotsBody, path) {
1134
+ const robots = parseRobots(robotsBody);
1135
+ for (const group of robots.groups) {
1136
+ if (!group.agents.some((agent) => agent.toLowerCase() === ARS_ROBOTS_TOKEN)) continue;
1137
+ let best = null;
1138
+ for (const value of group.allow) {
1139
+ if (!pathMatches(value, path)) continue;
1140
+ if (best === null || value.length > best.value.length) best = { field: "allow", value };
1141
+ }
1142
+ for (const value of group.disallow) {
1143
+ if (!pathMatches(value, path)) continue;
1144
+ if (best === null || value.length > best.value.length) best = { field: "disallow", value };
1145
+ }
1146
+ if (best !== null && best.field === "disallow") {
1147
+ return `User-agent: ${ARS_ROBOTS_TOKEN} / Disallow: ${best.value}`;
1148
+ }
1149
+ }
1150
+ return null;
1151
+ }
1152
+ function headersFor(identity) {
1153
+ return { accept: identity.accept, "user-agent": identity.userAgent };
1154
+ }
1155
+ function identityFor(policy, role) {
1156
+ const found = policy.identities.find((identity) => identity.role === role);
1157
+ return found ?? policy.identities.find((identity) => identity.role === "agent") ?? AGENT_IDENTITY;
1158
+ }
1159
+ function skipped(headers, detail) {
1160
+ return { requestHeaders: headers, result: { ok: false, error: "policy-rejected", detail } };
1161
+ }
1162
+ async function probeWithHostPolicy(target, policy, hostPolicy, options = {}) {
1163
+ const identityProblem = assertIdentities(policy.identities);
1164
+ if (identityProblem !== null) {
1165
+ return { ok: false, rejection: "policy-rejected", detail: identityProblem };
1166
+ }
1167
+ let parseable = true;
1168
+ try {
1169
+ void new URL(target.trim());
1170
+ } catch {
1171
+ parseable = false;
1172
+ }
1173
+ const guard = guardUrl(target, { allowHttp: policy.allowHttp, hostPolicy });
1174
+ if (!guard.ok) {
1175
+ return {
1176
+ ok: false,
1177
+ rejection: parseable ? "policy-rejected" : "invalid-url",
1178
+ detail: guard.reason
1179
+ };
1180
+ }
1181
+ const context = {
1182
+ policy,
1183
+ hostPolicy,
1184
+ transport: options.transport ?? createPinnedTransport(),
1185
+ resolver: options.resolver ?? createDnsResolver()
1186
+ };
1187
+ const vantage = options.vantage ?? "public";
1188
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
1189
+ const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1190
+ const robotsRetryDelayMs = options.robotsRetryDelayMs ?? 5e3;
1191
+ const url = guard.url;
1192
+ const origin = url.origin;
1193
+ const assetHeaders = headersFor(identityFor(policy, "asset"));
1194
+ const agentHeaders = headersFor(identityFor(policy, "agent"));
1195
+ const browserHeaders = headersFor(identityFor(policy, "browser"));
1196
+ const run = async (href, headers) => {
1197
+ try {
1198
+ return { requestHeaders: headers, result: await fetchWithPolicy(href, headers, context) };
1199
+ } catch (error) {
1200
+ if (error instanceof ProbeBudgetExceededError) throw error;
1201
+ return {
1202
+ requestHeaders: headers,
1203
+ result: {
1204
+ ok: false,
1205
+ error: "unreachable",
1206
+ detail: error instanceof Error ? error.message : String(error)
1207
+ }
1208
+ };
1209
+ }
1210
+ };
1211
+ const evidenceOf = (probes) => ({
1212
+ ok: true,
1213
+ evidence: {
1214
+ evidenceVersion: "0.1.0",
1215
+ target: { url: url.toString(), origin },
1216
+ probes,
1217
+ vantage,
1218
+ capturedAt: now().toISOString()
1219
+ }
1220
+ });
1221
+ try {
1222
+ let robotsTxt = await run(`${origin}/robots.txt`, assetHeaders);
1223
+ const robotsUnavailable = (record) => !record.result.ok || record.result.capture.status >= 500;
1224
+ const worthRetrying = (record) => record.result.ok ? record.result.capture.status >= 500 : record.result.error === "unreachable" || record.result.error === "timeout";
1225
+ if (worthRetrying(robotsTxt)) {
1226
+ await sleep(robotsRetryDelayMs);
1227
+ robotsTxt = await run(`${origin}/robots.txt`, assetHeaders);
1228
+ }
1229
+ if (robotsUnavailable(robotsTxt)) {
1230
+ const detail = "robots.txt returned a persistent error; a policy we could not read is not a policy we may assume";
1231
+ return evidenceOf({
1232
+ agent: skipped(agentHeaders, detail),
1233
+ browser: skipped(browserHeaders, detail),
1234
+ parityConfirm: null,
1235
+ robotsTxt,
1236
+ llmsTxt: null,
1237
+ wellKnownUcp: null
1238
+ });
1239
+ }
1240
+ const robotsBody = robotsTxt.result.ok ? robotsTxt.result.capture.body ?? "" : "";
1241
+ const robotsUsable = robotsTxt.result.ok && robotsTxt.result.capture.status < 400;
1242
+ const disallowedFor = (path) => vantage === "public" && robotsUsable ? scannerDisallows(robotsBody, path) : null;
1243
+ const pageRule = disallowedFor(url.pathname);
1244
+ if (pageRule !== null) {
1245
+ const detail = `robots.txt disallows the ${ARS_ROBOTS_TOKEN} token (${pageRule})`;
1246
+ return evidenceOf({
1247
+ agent: skipped(agentHeaders, detail),
1248
+ browser: skipped(browserHeaders, detail),
1249
+ parityConfirm: null,
1250
+ robotsTxt,
1251
+ llmsTxt: null,
1252
+ wellKnownUcp: null
1253
+ });
1254
+ }
1255
+ const agent = await run(url.toString(), agentHeaders);
1256
+ const browser = await run(url.toString(), browserHeaders);
1257
+ const fetchAsset = async (path) => {
1258
+ const rule = disallowedFor(path);
1259
+ if (rule !== null)
1260
+ return skipped(assetHeaders, `robots.txt disallows ${ARS_ROBOTS_TOKEN} for ${path}`);
1261
+ return run(`${origin}${path}`, assetHeaders);
1262
+ };
1263
+ const llmsTxt = await fetchAsset("/llms.txt");
1264
+ const wellKnownUcp = await fetchAsset("/.well-known/ucp");
1265
+ return evidenceOf({ agent, browser, parityConfirm: null, robotsTxt, llmsTxt, wellKnownUcp });
1266
+ } catch (error) {
1267
+ if (error instanceof ProbeBudgetExceededError) {
1268
+ return { ok: false, rejection: "budget-exceeded", detail: error.message };
1269
+ }
1270
+ throw error;
1271
+ }
1272
+ }
1273
+
1274
+ // src/probe/local.ts
1275
+ var ALLOW_PRIVATE_FLAG = "--allow-private";
1276
+ var HOSTED_RUNTIME_MARKERS = [
1277
+ "VERCEL",
1278
+ "NEXT_RUNTIME",
1279
+ "AWS_LAMBDA_FUNCTION_NAME",
1280
+ "AWS_EXECUTION_ENV",
1281
+ "FUNCTIONS_WORKER_RUNTIME",
1282
+ "K_SERVICE",
1283
+ "CF_PAGES"
1284
+ ];
1285
+ function hostedRuntimeMarker() {
1286
+ for (const key of HOSTED_RUNTIME_MARKERS) {
1287
+ const value = process.env[key];
1288
+ if (typeof value === "string" && value.length > 0) return key;
1289
+ }
1290
+ return null;
1291
+ }
1292
+ function assertLocalModeUnlocked() {
1293
+ const hosted = hostedRuntimeMarker();
1294
+ if (hosted !== null) {
1295
+ throw new Error(
1296
+ `@rebilder/agent-readability/probe/local: refusing to load in a hosted runtime (${hosted} is set). Local mode allows private and loopback targets and must never be reachable from an HTTP transport. Use probeStrict() from "@rebilder/agent-readability/probe".`
1297
+ );
1298
+ }
1299
+ if (!process.argv.includes(ALLOW_PRIVATE_FLAG)) {
1300
+ throw new Error(
1301
+ `@rebilder/agent-readability/probe/local: refusing to load without ${ALLOW_PRIVATE_FLAG}. Private hosts, loopback, link-local and cloud-metadata addresses are reachable through this entry point, so the permission is per invocation and comes from the command line \u2014 not from a config object, not from an environment variable, and never by default.`
1302
+ );
1303
+ }
1304
+ }
1305
+ assertLocalModeUnlocked();
1306
+ function localPolicy(limiter, ruleset = DEFAULT_RULESET) {
1307
+ return { ...strictPolicy(limiter, ruleset), allowHttp: true };
1308
+ }
1309
+ function probeLocal(target, policy, options = {}) {
1310
+ return probeWithHostPolicy(target, policy, ALLOW_PRIVATE_HOSTS, {
1311
+ ...options,
1312
+ vantage: options.vantage ?? "self"
1313
+ });
1314
+ }
1315
+
1316
+ export { ALLOW_PRIVATE_FLAG, localPolicy, probeLocal };
1317
+ //# sourceMappingURL=local.js.map
1318
+ //# sourceMappingURL=local.js.map