rebilder 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1633 +0,0 @@
1
- 'use strict';
2
-
3
- var util = require('util');
4
- var agentReadability = require('@rebilder/agent-readability');
5
- var promises = require('fs/promises');
6
- var path = require('path');
7
- var probe = require('@rebilder/agent-readability/probe');
8
-
9
- // src/args.ts
10
-
11
- // src/exit.ts
12
- var EXIT = {
13
- /** Completed; threshold met, or no threshold set. */
14
- OK: 0,
15
- /** Completed; threshold NOT met. Only ever produced by a real score. */
16
- THRESHOLD: 1,
17
- /** Usage error — unknown flag, bad value, missing argument, unparseable URL. */
18
- USAGE: 2,
19
- /** Probe failed / target unreachable. INFRASTRUCTURE, not a score failure. */
20
- PROBE: 3,
21
- /** Blocked by policy — SSRF guard, robots opt-out, exhausted probe budget. */
22
- POLICY: 4
23
- };
24
- var SEVERITY = [EXIT.USAGE, EXIT.POLICY, EXIT.PROBE, EXIT.THRESHOLD, EXIT.OK];
25
- function worstExit(codes) {
26
- for (const candidate of SEVERITY) {
27
- if (codes.includes(candidate)) return candidate;
28
- }
29
- return EXIT.OK;
30
- }
31
- var UsageError = class extends Error {
32
- constructor(message) {
33
- super(message);
34
- this.name = "UsageError";
35
- }
36
- };
37
-
38
- // src/args.ts
39
- var FORMATS = ["pretty", "json", "markdown", "junit"];
40
- var GRADES = ["A", "B", "C", "D", "F"];
41
- var COMMANDS = ["check", "diff", "init", "badge"];
42
- var OPTIONS = {
43
- format: { type: "string" },
44
- "fail-on": { type: "string" },
45
- out: { type: "string" },
46
- "allow-private": { type: "boolean" },
47
- "allow-http": { type: "boolean" },
48
- concurrency: { type: "string" },
49
- framework: { type: "string" },
50
- help: { type: "boolean", short: "h" },
51
- version: { type: "boolean", short: "v" }
52
- };
53
- function asFormat(value, fallback) {
54
- if (value === void 0) return fallback;
55
- const match = FORMATS.find((format) => format === value);
56
- if (match === void 0) {
57
- throw new UsageError(`--format must be one of ${FORMATS.join(", ")} (received "${value}")`);
58
- }
59
- return match;
60
- }
61
- function asGrade(value) {
62
- if (value === void 0) return null;
63
- const upper = value.toUpperCase();
64
- const match = GRADES.find((grade) => grade === upper);
65
- if (match === void 0) {
66
- throw new UsageError(`--fail-on must be one of ${GRADES.join(", ")} (received "${value}")`);
67
- }
68
- return match;
69
- }
70
- var MAX_CONCURRENCY = 8;
71
- function asConcurrency(value) {
72
- if (value === void 0) return 1;
73
- if (!/^[0-9]+$/.test(value)) {
74
- throw new UsageError(`--concurrency must be a positive integer (received "${value}")`);
75
- }
76
- const parsed = Number.parseInt(value, 10);
77
- if (parsed < 1) throw new UsageError("--concurrency must be at least 1");
78
- if (parsed > MAX_CONCURRENCY) {
79
- throw new UsageError(
80
- `--concurrency is capped at ${MAX_CONCURRENCY}; the probe's politeness limiter allows at most 2 in-flight requests globally in any case`
81
- );
82
- }
83
- return parsed;
84
- }
85
- var LABEL_CHARS = /^[a-z0-9-]+$/;
86
- function isLabel(label) {
87
- if (label.length < 1 || label.length > 63) return false;
88
- if (label.startsWith("-") || label.endsWith("-")) return false;
89
- return LABEL_CHARS.test(label);
90
- }
91
- function isDomain(value) {
92
- if (value.length === 0 || value.length > 253) return false;
93
- const labels = value.split(".");
94
- if (labels.length < 2) return false;
95
- return labels.every(isLabel);
96
- }
97
- function normalizeDomain(input) {
98
- let value = input.trim().toLowerCase();
99
- if (value.includes("://")) {
100
- try {
101
- value = new URL(value).hostname;
102
- } catch {
103
- throw new UsageError(`"${input}" is not a domain`);
104
- }
105
- }
106
- value = value.replace(/\/.*$/, "").replace(/\.$/, "");
107
- if (!isDomain(value)) {
108
- throw new UsageError(
109
- `"${input}" is not a domain. Pass a registrable hostname such as example.com \u2014 not a URL, not a path.`
110
- );
111
- }
112
- return value;
113
- }
114
- function parseCommandLine(argv) {
115
- let parsed;
116
- try {
117
- parsed = util.parseArgs({
118
- args: [...argv],
119
- options: OPTIONS,
120
- allowPositionals: true,
121
- strict: true
122
- });
123
- } catch (error) {
124
- throw new UsageError(error instanceof Error ? error.message : String(error));
125
- }
126
- const { values, positionals } = parsed;
127
- const [first, ...rest] = positionals;
128
- if (values.version === true) return { kind: "version" };
129
- if (values.help === true || first === void 0 || first === "help") {
130
- const topicCandidate = first === "help" ? rest[0] : first;
131
- const topic = COMMANDS.find((name2) => name2 === topicCandidate) ?? null;
132
- if (first === "help" && rest[0] !== void 0 && topic === null) {
133
- throw new UsageError(`unknown command "${rest[0]}". Expected one of ${COMMANDS.join(", ")}.`);
134
- }
135
- return { kind: "help", topic };
136
- }
137
- const name = COMMANDS.find((command) => command === first);
138
- if (name === void 0) {
139
- throw new UsageError(`unknown command "${first}". Expected one of ${COMMANDS.join(", ")}.`);
140
- }
141
- const out = values.out ?? null;
142
- const allowPrivate = values["allow-private"] === true;
143
- const allowHttp = values["allow-http"] === true || allowPrivate;
144
- switch (name) {
145
- case "check": {
146
- if (rest.length === 0) {
147
- throw new UsageError("check needs at least one URL. Usage: rebilder check <url...>");
148
- }
149
- return {
150
- kind: "command",
151
- command: {
152
- name: "check",
153
- urls: rest,
154
- format: asFormat(values.format, "pretty"),
155
- failOn: asGrade(values["fail-on"]),
156
- out,
157
- allowPrivate,
158
- allowHttp,
159
- concurrency: asConcurrency(values.concurrency)
160
- }
161
- };
162
- }
163
- case "diff": {
164
- if (rest.length === 0) throw new UsageError("diff needs a URL. Usage: rebilder diff <url>");
165
- if (rest.length > 1) {
166
- throw new UsageError(
167
- "diff takes exactly one URL. It is a two-representation comparison of a single page; use `check` for a set."
168
- );
169
- }
170
- if (values["fail-on"] !== void 0) {
171
- throw new UsageError(
172
- "--fail-on is not supported by `diff`. diff reports what the two representations contain; it does not grade. Use `rebilder check --fail-on`."
173
- );
174
- }
175
- const url = rest[0];
176
- if (url === void 0) throw new UsageError("diff needs a URL. Usage: rebilder diff <url>");
177
- return {
178
- kind: "command",
179
- command: {
180
- name: "diff",
181
- url,
182
- format: asFormat(values.format, "pretty"),
183
- out,
184
- allowPrivate,
185
- allowHttp
186
- }
187
- };
188
- }
189
- case "init": {
190
- if (rest.length > 0) {
191
- throw new UsageError(
192
- `init takes no positional arguments (received "${rest[0]}"). Use --framework to override detection.`
193
- );
194
- }
195
- return {
196
- kind: "command",
197
- command: {
198
- name: "init",
199
- framework: values.framework ?? null,
200
- out,
201
- format: asFormat(values.format, "pretty")
202
- }
203
- };
204
- }
205
- case "badge": {
206
- if (rest.length === 0) {
207
- throw new UsageError("badge needs a domain. Usage: rebilder badge <domain>");
208
- }
209
- if (rest.length > 1) throw new UsageError("badge takes exactly one domain.");
210
- const domain = rest[0];
211
- if (domain === void 0) throw new UsageError("badge needs a domain.");
212
- return {
213
- kind: "command",
214
- command: {
215
- name: "badge",
216
- domain: normalizeDomain(domain),
217
- format: asFormat(values.format, "pretty"),
218
- out
219
- }
220
- };
221
- }
222
- }
223
- }
224
-
225
- // src/commands/badge.ts
226
- var BADGE_ORIGIN = "https://rebilder.com";
227
- function runBadge(command) {
228
- const { domain } = command;
229
- const svgUrl = `${BADGE_ORIGIN}/badge/${domain}.svg`;
230
- const pageUrl = `${BADGE_ORIGIN}/readable/${domain}`;
231
- const alt = `Agent Readability Score for ${domain}`;
232
- return {
233
- domain,
234
- svgUrl,
235
- pageUrl,
236
- markdown: `[![${alt}](${svgUrl})](${pageUrl})`,
237
- html: `<a href="${pageUrl}"><img src="${svgUrl}" alt="${alt}" height="20"></a>`,
238
- notes: [
239
- "A grade renders only for a verified opted-in domain. Every other domain gets a neutral \u201Cnot rated\u201D badge, served at 200 so it never shows as a broken image.",
240
- "Verify by publishing a DNS TXT record `rebilder-verify=<token>`, or by serving `X-Rebilder-Path` from your origin where we can observe it.",
241
- "The badge is served live from our data: you capture nothing and freeze nothing. It degrades to \u201Cunverified\u201D after 30 days without a successful re-scan.",
242
- "It always names its subject (`example.com \xB7 A \xB7 94 \xB7 Mar 2026`) and it shows the ruleset hash alongside the spec version \u2014 two scores from different rulesets must not render identically.",
243
- "No score ever comes from the query string. Removal from the index is free, self-serve, permanent, and never purchasable.",
244
- "This command makes no network request. It builds the snippet locally, so we never learn which domain you asked about."
245
- ]
246
- };
247
- }
248
- async function runCheck(command, probe) {
249
- return mapWithConcurrency(command.urls, command.concurrency, (url) => probeOne(url, probe));
250
- }
251
- async function probeOne(url, probe) {
252
- const outcome = await probe(url);
253
- if (!outcome.ok) {
254
- return { kind: "rejected", url, rejection: outcome.rejection, detail: outcome.detail };
255
- }
256
- return { kind: "probed", url, result: agentReadability.score(outcome.evidence) };
257
- }
258
- async function mapWithConcurrency(items, concurrency, worker) {
259
- const results = new Array(items.length);
260
- let next = 0;
261
- const lanes = Array.from(
262
- { length: Math.min(Math.max(1, concurrency), items.length) },
263
- async () => {
264
- for (; ; ) {
265
- const index = next++;
266
- if (index >= items.length) return;
267
- const item = items[index];
268
- if (item === void 0) return;
269
- results[index] = await worker(item, index);
270
- }
271
- }
272
- );
273
- await Promise.all(lanes);
274
- return results;
275
- }
276
- var PARITY_CHECK_ID = "machine-representation.substance-parity";
277
- async function runDiff(command, probe) {
278
- const outcome = await probe(command.url);
279
- if (!outcome.ok) {
280
- const report2 = {
281
- kind: "rejected",
282
- url: command.url,
283
- rejection: outcome.rejection,
284
- detail: outcome.detail
285
- };
286
- return { url: command.url, agent: null, browser: null, parity: null, result: null, report: report2 };
287
- }
288
- const result = agentReadability.score(outcome.evidence);
289
- const report = { kind: "probed", url: command.url, result };
290
- return {
291
- url: command.url,
292
- agent: sideOf(outcome.evidence, "agent"),
293
- browser: sideOf(outcome.evidence, "browser"),
294
- parity: parityCheck(result),
295
- result,
296
- report
297
- };
298
- }
299
- function parityCheck(result) {
300
- for (const dimension of result.dimensions) {
301
- for (const check of dimension.checks) {
302
- if (check.id === PARITY_CHECK_ID) return check;
303
- }
304
- }
305
- return null;
306
- }
307
- function sideOf(evidence, role) {
308
- const record = evidence.probes[role];
309
- const accept = record.requestHeaders["accept"] ?? "(none)";
310
- if (!record.result.ok) {
311
- return {
312
- role,
313
- accept,
314
- status: null,
315
- contentType: null,
316
- bytes: null,
317
- approxTokens: null,
318
- truncated: false,
319
- redirects: 0,
320
- error: `${record.result.error}${record.result.detail === void 0 ? "" : `: ${record.result.detail}`}`
321
- };
322
- }
323
- const capture = record.result.capture;
324
- return {
325
- role,
326
- accept,
327
- status: capture.status,
328
- contentType: capture.headers["content-type"]?.[0] ?? null,
329
- bytes: capture.bytes,
330
- approxTokens: approxTokensOf(capture),
331
- truncated: capture.truncated,
332
- redirects: capture.redirects.length,
333
- error: null
334
- };
335
- }
336
- function approxTokensOf(capture) {
337
- const characters = capture.body?.length ?? capture.bytes;
338
- return Math.round(characters / 4);
339
- }
340
-
341
- // src/commands/init.ts
342
- var FRAMEWORKS = ["next", "node", "edge", "shopify"];
343
- var MARKER_FILES = [
344
- {
345
- file: "shopify.app.toml",
346
- framework: "shopify",
347
- reason: "shopify.app.toml in the working directory"
348
- },
349
- { file: "next.config.ts", framework: "next", reason: "next.config.ts in the working directory" },
350
- {
351
- file: "next.config.mjs",
352
- framework: "next",
353
- reason: "next.config.mjs in the working directory"
354
- },
355
- { file: "next.config.js", framework: "next", reason: "next.config.js in the working directory" },
356
- { file: "wrangler.toml", framework: "edge", reason: "wrangler.toml in the working directory" },
357
- { file: "wrangler.jsonc", framework: "edge", reason: "wrangler.jsonc in the working directory" }
358
- ];
359
- var DEPENDENCY_MARKERS = [
360
- { dependency: "@shopify/shopify-app-remix", framework: "shopify" },
361
- { dependency: "@shopify/shopify-api", framework: "shopify" },
362
- { dependency: "next", framework: "next" },
363
- { dependency: "@cloudflare/workers-types", framework: "edge" },
364
- { dependency: "wrangler", framework: "edge" },
365
- { dependency: "hono", framework: "edge" },
366
- { dependency: "express", framework: "node" },
367
- { dependency: "fastify", framework: "node" }
368
- ];
369
- async function detectFramework(runtime) {
370
- for (const marker of MARKER_FILES) {
371
- if (await runtime.readFile(marker.file) !== null) {
372
- return { framework: marker.framework, reason: `detected from ${marker.reason}` };
373
- }
374
- }
375
- const manifest = await runtime.readFile("package.json");
376
- if (manifest !== null) {
377
- let dependencies = {};
378
- try {
379
- const parsed = JSON.parse(manifest);
380
- if (typeof parsed === "object" && parsed !== null) {
381
- const record = parsed;
382
- dependencies = {
383
- ...asRecord(record["dependencies"]),
384
- ...asRecord(record["devDependencies"])
385
- };
386
- }
387
- } catch {
388
- dependencies = {};
389
- }
390
- for (const marker of DEPENDENCY_MARKERS) {
391
- if (marker.dependency in dependencies) {
392
- return {
393
- framework: marker.framework,
394
- reason: `detected from "${marker.dependency}" in package.json`
395
- };
396
- }
397
- }
398
- }
399
- return {
400
- framework: "node",
401
- reason: "no framework marker found \u2014 defaulting to the Node adapter. Pass --framework next|node|edge|shopify to choose."
402
- };
403
- }
404
- function asRecord(value) {
405
- return typeof value === "object" && value !== null ? value : {};
406
- }
407
- async function runInit(command, runtime) {
408
- let framework;
409
- let detection;
410
- if (command.framework !== null) {
411
- const match = FRAMEWORKS.find((name) => name === command.framework);
412
- if (match === void 0) {
413
- throw new UsageError(
414
- `--framework must be one of ${FRAMEWORKS.join(", ")} (received "${command.framework}")`
415
- );
416
- }
417
- framework = match;
418
- detection = "chosen with --framework";
419
- } else {
420
- const detected = await detectFramework(runtime);
421
- framework = detected.framework;
422
- detection = detected.reason;
423
- }
424
- return { ...SCAFFOLDS[framework], framework, detection };
425
- }
426
- var SHARED_NOTES = [
427
- "The resolvers return your source of truth. Every substantive value \u2014 price, stock, hours, policy text \u2014 comes from these fields; the gateway never invents one.",
428
- "The gateway has no concept of a plan, licence, tier or quota, and never will. Free-tier cost control happens at ingest, never at the edge.",
429
- "Run `rebilder check <url>` before and after to see what changed. Content negotiation is D2.1 (10 points) and unlocks D2.3 and D2.4."
430
- ];
431
- var CONFIG_BODY = `import type { GatewayConfig } from '@rebilder/gateway'
432
-
433
- /**
434
- * Wiring to YOUR source of truth. Each resolver takes a URL and returns the
435
- * fields for that page, or null to fall through to your normal HTML.
436
- *
437
- * Resolvers run on the request hot path: p95 < 50ms of compute, and no network
438
- * call except a cache. Anything slower belongs in a build step.
439
- */
440
- export const gatewayConfig: GatewayConfig = {
441
- storeId: 'TODO-your-store-id',
442
- sources: {
443
- // TODO: return your product fields, or null when the URL is not a PDP.
444
- product: async (url) => {
445
- void url
446
- return null
447
- },
448
- // TODO: policies, catalog, document, collection \u2014 add the ones you have.
449
- },
450
- // Optional: emit @rebilder/events RebilderEventV0 into your observation layer.
451
- // onEvent: (event) => { void event },
452
- }
453
- `;
454
- var SCAFFOLDS = {
455
- next: {
456
- suggestedPath: "lib/gateway-config.ts",
457
- language: "ts",
458
- notes: [
459
- "Then add the proxy: `const gateway = createGatewayProxy(gatewayConfig)` in proxy.ts (Next 16) or middleware.ts (Next 15 and earlier), returning `(await gateway(req)) ?? NextResponse.next()`.",
460
- ...SHARED_NOTES
461
- ],
462
- contents: `${CONFIG_BODY}
463
- /* \u2500\u2500 proxy.ts (Next 16) or middleware.ts (Next \u226415) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
464
- //
465
- // import { NextResponse } from 'next/server'
466
- // import { createGatewayProxy } from '@rebilder/gateway/next'
467
- // import { gatewayConfig } from './lib/gateway-config'
468
- //
469
- // const gateway = createGatewayProxy(gatewayConfig)
470
- //
471
- // export default async function proxy(req: Request) {
472
- // return (await gateway(req)) ?? NextResponse.next()
473
- // }
474
- `
475
- },
476
- node: {
477
- suggestedPath: "gateway-config.ts",
478
- language: "ts",
479
- notes: [
480
- "Then mount it before your routes: `app.use(createGatewayMiddleware(gatewayConfig))`.",
481
- ...SHARED_NOTES
482
- ],
483
- contents: `${CONFIG_BODY}
484
- /* \u2500\u2500 Express \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
485
- //
486
- // import express from 'express'
487
- // import { createGatewayMiddleware } from '@rebilder/gateway/node'
488
- // import { gatewayConfig } from './gateway-config'
489
- //
490
- // const app = express()
491
- // app.use(createGatewayMiddleware(gatewayConfig)) // before your routes
492
- `
493
- },
494
- edge: {
495
- suggestedPath: "gateway-config.ts",
496
- language: "ts",
497
- notes: [
498
- "Then export the fetch handler: `export default { fetch: createGatewayFetchHandler(gatewayConfig) }`.",
499
- "On a route-mounted Worker, non-markdown requests pass through to your origin unchanged, so browsers and crawlers keep receiving the canonical HTML.",
500
- ...SHARED_NOTES
501
- ],
502
- contents: `${CONFIG_BODY}
503
- /* \u2500\u2500 worker.ts (Cloudflare Workers, Vercel Edge, Deno Deploy) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
504
- //
505
- // import { createGatewayFetchHandler } from '@rebilder/gateway/edge'
506
- // import { gatewayConfig } from './gateway-config'
507
- //
508
- // export default { fetch: createGatewayFetchHandler(gatewayConfig) }
509
- `
510
- },
511
- shopify: {
512
- suggestedPath: "app/gateway-config.ts",
513
- language: "ts",
514
- notes: [
515
- "Then mount the app-proxy handler and give it your app\u2019s shared secret; requests are signature-verified before anything is rendered.",
516
- ...SHARED_NOTES
517
- ],
518
- contents: `${CONFIG_BODY}
519
- /* \u2500\u2500 Shopify app proxy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
520
- //
521
- // import { createShopifyAppProxyHandler } from '@rebilder/gateway/shopify'
522
- // import { gatewayConfig } from './gateway-config'
523
- //
524
- // export const loader = createShopifyAppProxyHandler(gatewayConfig, {
525
- // sharedSecret: process.env.SHOPIFY_API_SECRET ?? '',
526
- // })
527
- `
528
- }
529
- };
530
-
531
- // src/disclosure.ts
532
- var ARS_NOTICE_LINES = [
533
- "ARS measures format and retrievability. It does not measure whether the",
534
- "facts are true, or whether any assistant cites this page."
535
- ];
536
- var ARS_NOTICE = ARS_NOTICE_LINES.join(" ");
537
- var TELEMETRY_LINES = [
538
- "This CLI ships zero telemetry. It never uploads a scan, a URL, a hostname,",
539
- "or a result. The only requests it makes are to the target you name."
540
- ];
541
-
542
- // src/report.ts
543
- var ORDER = GRADES;
544
- function meetsThreshold(grade, failOn) {
545
- return ORDER.indexOf(grade) <= ORDER.indexOf(failOn);
546
- }
547
- function exitCodeFor(report, failOn) {
548
- if (report.kind === "rejected") {
549
- switch (report.rejection) {
550
- case "invalid-url":
551
- return EXIT.USAGE;
552
- case "policy-rejected":
553
- case "budget-exceeded":
554
- return EXIT.POLICY;
555
- }
556
- }
557
- const { outcome } = report.result;
558
- switch (outcome.kind) {
559
- case "opt-out":
560
- return EXIT.POLICY;
561
- case "unscored":
562
- return outcome.reason === "robots-disallow-scanner" ? EXIT.POLICY : EXIT.PROBE;
563
- case "scored":
564
- if (failOn === null) return EXIT.OK;
565
- return meetsThreshold(outcome.grade, failOn) ? EXIT.OK : EXIT.THRESHOLD;
566
- }
567
- }
568
- var UNSCORED_TEXT = {
569
- "blocked-at-edge": "blocked at the edge (403 or challenge) \u2014 the block is itself the finding",
570
- unreachable: "unreachable",
571
- "non-2xx": "the agent path did not return 2xx",
572
- "too-many-redirects": "too many redirects",
573
- "robots-disallow-scanner": "robots.txt disallows rebilder-ars \u2014 we obeyed it and did not score",
574
- "robots-unavailable": "robots.txt returned a persistent error; a policy we cannot read is not a policy we may assume",
575
- "truncated-evidence": "the response exceeded the 2 MiB body cap and the evidence is incomplete",
576
- "evidence-incomplete": "the evidence bundle is incomplete"
577
- };
578
- var REJECTION_TEXT = {
579
- "invalid-url": "not a URL",
580
- "policy-rejected": "refused by the URL guard",
581
- "budget-exceeded": "the probe budget for this run is spent"
582
- };
583
- function outcomeSummary(report) {
584
- if (report.kind === "rejected") {
585
- return `${REJECTION_TEXT[report.rejection]}: ${report.detail}`;
586
- }
587
- const { outcome } = report.result;
588
- switch (outcome.kind) {
589
- case "scored":
590
- return `${outcome.score}/100 ${outcome.grade}`;
591
- case "opt-out":
592
- return `OPT-OUT \u2014 a deliberate, well-formed robots disallow for the ${outcome.audience} audience. Not a failure and not a grade.`;
593
- case "unscored":
594
- return `UNSCORED \u2014 ${UNSCORED_TEXT[outcome.reason] ?? outcome.reason}${outcome.detail === void 0 ? "" : ` (${outcome.detail})`}`;
595
- }
596
- }
597
- function statusOf(report) {
598
- return report.kind === "rejected" ? "rejected" : report.result.outcome.kind;
599
- }
600
-
601
- // src/format/json.ts
602
- function renderJson(payload, ctx) {
603
- return JSON.stringify(jsonValue(payload, ctx), null, 2) + "\n";
604
- }
605
- function jsonValue(payload, ctx) {
606
- const envelope = {
607
- tool: "rebilder",
608
- toolVersion: ctx.cliVersion,
609
- generatedAt: ctx.generatedAt,
610
- notice: ARS_NOTICE
611
- };
612
- switch (payload.command) {
613
- case "check":
614
- return {
615
- ...envelope,
616
- command: "check",
617
- failOn: payload.failOn,
618
- results: payload.reports.map((report) => ({
619
- url: report.url,
620
- status: statusOf(report),
621
- summary: outcomeSummary(report),
622
- exitCode: exitCodeFor(report, payload.failOn),
623
- ...report.kind === "rejected" ? { rejection: report.rejection, detail: report.detail, result: null } : { rejection: null, detail: null, result: report.result }
624
- }))
625
- };
626
- case "diff":
627
- return {
628
- ...envelope,
629
- command: "diff",
630
- url: payload.diff.url,
631
- status: statusOf(payload.diff.report),
632
- agent: payload.diff.agent,
633
- browser: payload.diff.browser,
634
- substanceParity: payload.diff.parity,
635
- result: payload.diff.result
636
- };
637
- case "init":
638
- return { ...envelope, command: "init", scaffold: payload.scaffold };
639
- case "badge":
640
- return { ...envelope, command: "badge", badge: payload.badge };
641
- }
642
- }
643
-
644
- // src/format/shared.ts
645
- function absent(unicode) {
646
- return unicode ? "\u2014" : "-";
647
- }
648
- function basisLabel(basis) {
649
- return basis === "heuristic" ? "heuristic" : "measured";
650
- }
651
- function bytesText(bytes, truncated, unicode) {
652
- if (bytes === null) return absent(unicode);
653
- const formatted = `${bytes.toLocaleString("en-US")} B`;
654
- if (!truncated) return formatted;
655
- return `${unicode ? "\u2265" : ">="} ${formatted} (truncated at the 2 MiB cap)`;
656
- }
657
- function approxTokens(tokens, unicode) {
658
- if (tokens === null) return absent(unicode);
659
- return `${unicode ? "\u2248" : "~"}${tokens.toLocaleString("en-US")} tokens (est.)`;
660
- }
661
- function percent(numerator, denominator) {
662
- if (denominator === 0) return "0%";
663
- return `${Math.round(numerator * 100 / denominator)}%`;
664
- }
665
- function checkMark(check, unicode) {
666
- if (check.earned >= check.weight) return unicode ? "\u2714" : "+";
667
- if (check.earned > 0) return unicode ? "\u25D0" : "~";
668
- return unicode ? "\u2718" : "x";
669
- }
670
- function shortHash(hash) {
671
- return hash.slice(0, 12);
672
- }
673
- function escapeXml(text2) {
674
- return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "");
675
- }
676
- function escapeCell(text2) {
677
- return text2.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
678
- }
679
-
680
- // src/format/junit.ts
681
- var SUITE_NAME = "rebilder.ars";
682
- function renderJunit(payload, ctx) {
683
- const suites = [];
684
- let tests = 0;
685
- let failures = 0;
686
- let errors = 0;
687
- if (payload.command === "check") {
688
- for (const report of payload.reports) {
689
- const suite = checkSuite(report, payload.failOn, ctx);
690
- suites.push(suite.xml);
691
- tests += suite.tests;
692
- failures += suite.failures;
693
- errors += suite.errors;
694
- }
695
- } else if (payload.command === "diff") {
696
- const suite = checkSuite(payload.diff.report, null, ctx);
697
- suites.push(suite.xml);
698
- tests += suite.tests;
699
- failures += suite.failures;
700
- errors += suite.errors;
701
- } else {
702
- suites.push(
703
- ` <testsuite name="${SUITE_NAME}.${payload.command}" tests="0" failures="0" errors="0"/>`
704
- );
705
- }
706
- return [
707
- '<?xml version="1.0" encoding="UTF-8"?>',
708
- `<testsuites name="${SUITE_NAME}" tests="${tests}" failures="${failures}" errors="${errors}">`,
709
- ...suites,
710
- "</testsuites>",
711
- ""
712
- ].join("\n");
713
- }
714
- function checkSuite(report, failOn, ctx) {
715
- const cases = [];
716
- let tests = 0;
717
- let failures = 0;
718
- let errors = 0;
719
- const properties = [
720
- ` <property name="notice" value="${escapeXml(ARS_NOTICE)}"/>`,
721
- ` <property name="url" value="${escapeXml(report.url)}"/>`,
722
- ` <property name="generatedAt" value="${escapeXml(ctx.generatedAt)}"/>`,
723
- ` <property name="tool" value="rebilder ${escapeXml(ctx.cliVersion)}"/>`
724
- ];
725
- if (report.kind === "probed") {
726
- const { result } = report;
727
- properties.push(
728
- ` <property name="specVersion" value="${escapeXml(result.specVersion)}"/>`,
729
- ` <property name="rulesetHash" value="${escapeXml(result.rulesetHash)}"/>`,
730
- ` <property name="corpusHash" value="${escapeXml(result.corpusHash)}"/>`,
731
- ` <property name="evidenceHash" value="${escapeXml(result.evidenceHash)}"/>`,
732
- ` <property name="measuredWeight" value="${result.measuredWeight}"/>`,
733
- ` <property name="heuristicWeight" value="${result.heuristicWeight}"/>`
734
- );
735
- }
736
- const status = statusOf(report);
737
- if (report.kind === "rejected" || report.result.outcome.kind !== "scored") {
738
- tests += 1;
739
- errors += 1;
740
- cases.push(
741
- [
742
- ` <testcase classname="${escapeXml(report.url)}" name="probe">`,
743
- ` <error type="${escapeXml(status)}" message="${escapeXml(outcomeSummary(report))}"/>`,
744
- " </testcase>"
745
- ].join("\n")
746
- );
747
- } else {
748
- const { result } = report;
749
- for (const dimension of result.dimensions) {
750
- for (const check of dimension.checks) {
751
- tests += 1;
752
- const passed = check.earned >= check.weight;
753
- const name = `${check.id} [${basisLabel(check.basis)}] ${check.earned}/${check.weight}`;
754
- if (passed) {
755
- cases.push(
756
- ` <testcase classname="${escapeXml(report.url)}" name="${escapeXml(name)}"/>`
757
- );
758
- continue;
759
- }
760
- failures += 1;
761
- const detail = [
762
- check.remedy ?? "",
763
- ...check.evidence.map(
764
- (item) => `${item.label}: ${item.value} [${basisLabel(item.basis)}]`
765
- )
766
- ].filter((line) => line.length > 0).join("\n");
767
- cases.push(
768
- [
769
- ` <testcase classname="${escapeXml(report.url)}" name="${escapeXml(name)}">`,
770
- ` <failure type="${escapeXml(check.basis)}" message="${escapeXml(`${check.label} earned ${check.earned} of ${check.weight}`)}">${escapeXml(detail)}</failure>`,
771
- " </testcase>"
772
- ].join("\n")
773
- );
774
- }
775
- }
776
- if (failOn !== null && result.grade !== null) {
777
- tests += 1;
778
- const met = meetsThreshold(result.grade, failOn);
779
- const name = `threshold --fail-on ${failOn}`;
780
- if (met) {
781
- cases.push(` <testcase classname="${escapeXml(report.url)}" name="${escapeXml(name)}"/>`);
782
- } else {
783
- failures += 1;
784
- cases.push(
785
- [
786
- ` <testcase classname="${escapeXml(report.url)}" name="${escapeXml(name)}">`,
787
- ` <failure type="threshold" message="${escapeXml(`graded ${result.grade} (${result.score}/100); the threshold is ${failOn} or better`)}"/>`,
788
- " </testcase>"
789
- ].join("\n")
790
- );
791
- }
792
- }
793
- }
794
- const exitCode = exitCodeFor(report, failOn);
795
- properties.push(` <property name="exitCode" value="${exitCode}"/>`);
796
- if (exitCode === EXIT.PROBE || exitCode === EXIT.POLICY) {
797
- properties.push(
798
- ` <property name="notAScoreFailure" value="${exitCode === EXIT.PROBE ? "probe failure \u2014 infrastructure" : "blocked by policy"}"/>`
799
- );
800
- }
801
- const xml = [
802
- ` <testsuite name="${escapeXml(report.url)}" tests="${tests}" failures="${failures}" errors="${errors}">`,
803
- " <properties>",
804
- ...properties,
805
- " </properties>",
806
- ...cases,
807
- " </testsuite>"
808
- ].join("\n");
809
- return { xml, tests, failures, errors };
810
- }
811
-
812
- // src/format/markdown.ts
813
- function renderMarkdown(payload, ctx) {
814
- switch (payload.command) {
815
- case "check":
816
- return payload.reports.map((report) => checkSection(report)).join("\n---\n\n") + notice();
817
- case "diff":
818
- return diffSection(payload.diff) + notice();
819
- case "init":
820
- return initSection(payload, ctx);
821
- case "badge":
822
- return badgeSection(payload);
823
- }
824
- }
825
- function notice() {
826
- return `
827
- ${ARS_NOTICE_LINES.map((line) => `> ${line}`).join("\n")}
828
- `;
829
- }
830
- function checkSection(report) {
831
- const out = [`## ${escapeCell(report.url)}`, ""];
832
- if (report.kind === "rejected") {
833
- out.push(`**REJECTED** \u2014 ${outcomeSummary(report)}`, "");
834
- return out.join("\n");
835
- }
836
- const { result } = report;
837
- if (statusOf(report) !== "scored") {
838
- out.push(outcomeSummary(report), "");
839
- out.push(policyLine(result), "");
840
- out.push(identityLine(result), "");
841
- return out.join("\n");
842
- }
843
- out.push(
844
- `**${result.grade} \u2014 ${result.bandLabel}** \xB7 ${result.score}/100 \xB7 page kind \`${result.pageKind}\` (${result.pageKindConfidence} confidence, ${basisLabel(result.pageKindBasis)})`,
845
- "",
846
- `${result.measuredWeight} of the 100 points are measured; ${result.heuristicWeight} are heuristic.`,
847
- "",
848
- "| Check | Points | Basis |",
849
- "| --- | ---: | --- |"
850
- );
851
- for (const dimension of result.dimensions) {
852
- out.push(
853
- `| **${escapeCell(dimension.label)}** | **${dimension.earned}/${dimension.weight}** | ${basisLabel(dimension.basis)} |`
854
- );
855
- for (const check of dimension.checks) {
856
- out.push(
857
- `| ${escapeCell(check.label)} | ${check.earned}/${check.weight} | ${basisLabel(check.basis)} |`
858
- );
859
- }
860
- }
861
- out.push("", "### What an agent pays", "");
862
- out.push("| | Bytes | Tokens |", "| --- | --- | --- |");
863
- out.push(
864
- `| HTML | ${bytesText(result.cost.htmlBytes, result.cost.truncated, true)} | ${approxTokens(result.cost.approxHtmlTokens, true)} |`
865
- );
866
- out.push(
867
- `| Negotiated | ${bytesText(result.cost.negotiatedBytes, result.cost.truncated, true)} | ${approxTokens(result.cost.approxNegotiatedTokens, true)} |`
868
- );
869
- if (result.cost.reductionRatio !== null) {
870
- out.push(`| Reduction | ${result.cost.reductionRatio}% | |`);
871
- }
872
- if (result.flags.length > 0) {
873
- out.push("", "### Flags", "");
874
- for (const flag of result.flags) {
875
- out.push(`- \`${flag.id}\` (${flag.severity}, ${basisLabel(flag.basis)}) \u2014 ${flag.message}`);
876
- }
877
- }
878
- if (result.recommendations.length > 0) {
879
- out.push("", "### Fixes, most points first", "");
880
- out.push("| Points | Fix | Effort |", "| ---: | --- | --- |");
881
- for (const recommendation of result.recommendations) {
882
- out.push(
883
- `| +${recommendation.pointsAvailable} | ${escapeCell(recommendation.title)} | ${recommendation.effort} |`
884
- );
885
- }
886
- }
887
- out.push("", policyLine(result), "", identityLine(result), "");
888
- return out.join("\n");
889
- }
890
- function policyLine(result) {
891
- const { policy } = result;
892
- return `Policy: robots.txt ${policy.robotsTxtStatus} \xB7 assistant ${policy.audiences.assistant.decision} \xB7 training ${policy.audiences.training.decision} (neutral) \xB7 sitemap ${policy.sitemapDeclared ? "declared" : "not declared"}`;
893
- }
894
- function identityLine(result) {
895
- return `ARS ${result.specVersion} \xB7 ruleset \`${shortHash(result.rulesetHash)}\` \xB7 corpus \`${shortHash(result.corpusHash)}\` \xB7 evidence \`${shortHash(result.evidenceHash)}\` \xB7 vantage ${result.vantage}`;
896
- }
897
- function diffSection(diff) {
898
- const out = [`## ${escapeCell(diff.url)} \u2014 agent view vs browser view`, ""];
899
- if (diff.report.kind === "rejected") {
900
- out.push(`**REJECTED** \u2014 ${outcomeSummary(diff.report)}`, "");
901
- return out.join("\n");
902
- }
903
- out.push(
904
- "The two requests differ in the `Accept` header and in nothing else \u2014 same User-Agent, same everything.",
905
- "",
906
- "| | Agent | Browser |",
907
- "| --- | --- | --- |",
908
- `| Accept | \`${escapeCell(diff.agent?.accept ?? "\u2014")}\` | \`${escapeCell(diff.browser?.accept ?? "\u2014")}\` |`,
909
- `| Status | ${diff.agent?.status ?? "\u2014"} | ${diff.browser?.status ?? "\u2014"} |`,
910
- `| Content-Type | ${escapeCell(diff.agent?.contentType ?? "\u2014")} | ${escapeCell(diff.browser?.contentType ?? "\u2014")} |`,
911
- `| Bytes | ${bytesText(diff.agent?.bytes ?? null, diff.agent?.truncated ?? false, true)} | ${bytesText(diff.browser?.bytes ?? null, diff.browser?.truncated ?? false, true)} |`,
912
- `| Tokens | ${approxTokens(diff.agent?.approxTokens ?? null, true)} | ${approxTokens(diff.browser?.approxTokens ?? null, true)} |`,
913
- `| Redirects | ${diff.agent?.redirects ?? "\u2014"} | ${diff.browser?.redirects ?? "\u2014"} |`
914
- );
915
- if (diff.parity !== null) {
916
- out.push(
917
- "",
918
- `### Substance parity \u2014 ${diff.parity.earned}/${diff.parity.weight} (${basisLabel(diff.parity.basis)})`,
919
- "",
920
- "Compared on price, currency, availability and title only \u2014 never description or free text.",
921
- ""
922
- );
923
- for (const evidence of diff.parity.evidence) {
924
- out.push(
925
- `- ${escapeCell(evidence.label)}: ${escapeCell(evidence.value)} (${basisLabel(evidence.basis)})`
926
- );
927
- }
928
- }
929
- if (diff.result !== null) out.push("", identityLine(diff.result), "");
930
- return out.join("\n");
931
- }
932
- function initSection(payload, ctx) {
933
- const { scaffold } = payload;
934
- const out = [
935
- `## Rebilder gateway scaffold \u2014 ${scaffold.framework}`,
936
- "",
937
- scaffold.detection,
938
- "",
939
- `Suggested path: \`${scaffold.suggestedPath}\``,
940
- "",
941
- "```" + scaffold.language,
942
- scaffold.contents.trimEnd(),
943
- "```",
944
- ""
945
- ];
946
- for (const note of scaffold.notes) out.push(`- ${note}`);
947
- out.push("", `<!-- generated by rebilder ${ctx.cliVersion} -->`, "");
948
- return out.join("\n");
949
- }
950
- function badgeSection(payload) {
951
- const { badge } = payload;
952
- const out = [
953
- `## Rebilder badge \u2014 ${badge.domain}`,
954
- "",
955
- "```markdown",
956
- badge.markdown,
957
- "```",
958
- "",
959
- "```html",
960
- badge.html,
961
- "```",
962
- ""
963
- ];
964
- for (const note of badge.notes) out.push(`- ${note}`);
965
- out.push("");
966
- return out.join("\n");
967
- }
968
-
969
- // src/term.ts
970
- var MIN_WIDTH = 40;
971
- var MAX_WIDTH = 100;
972
- function detectCapabilities(environment) {
973
- const { env, isTty } = environment;
974
- const noColor = env["NO_COLOR"] !== void 0;
975
- const forceColor = env["FORCE_COLOR"] !== void 0 && env["FORCE_COLOR"] !== "0";
976
- const dumbTerm = env["TERM"] === "dumb";
977
- const color = !noColor && !dumbTerm && (forceColor || isTty);
978
- const locale = `${env["LC_ALL"] ?? ""} ${env["LC_CTYPE"] ?? ""} ${env["LANG"] ?? ""}`;
979
- const unicode = /utf-?8/i.test(locale);
980
- const raw = environment.columns ?? 80;
981
- const width = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, Number.isFinite(raw) ? raw : 80));
982
- return { color, unicode, width };
983
- }
984
- var CODES = {
985
- reset: 0,
986
- bold: 1,
987
- dim: 2,
988
- red: 31,
989
- green: 32,
990
- yellow: 33,
991
- blue: 34,
992
- magenta: 35,
993
- cyan: 36,
994
- gray: 90
995
- };
996
- function createPainter(enabled) {
997
- const paint = (text2, ...styles) => {
998
- if (!enabled || styles.length === 0) return text2;
999
- const open = styles.map((style) => `\x1B[${CODES[style]}m`).join("");
1000
- return `${open}${text2}\x1B[${CODES.reset}m`;
1001
- };
1002
- return Object.assign(paint, { enabled });
1003
- }
1004
- var ANSI_RE = /\u001b\[[0-9;]*m/g;
1005
- function visibleWidth(text2) {
1006
- return [...text2.replace(ANSI_RE, "")].length;
1007
- }
1008
- function padEnd(text2, width) {
1009
- const pad = width - visibleWidth(text2);
1010
- return pad > 0 ? text2 + " ".repeat(pad) : text2;
1011
- }
1012
- function padStart(text2, width) {
1013
- const pad = width - visibleWidth(text2);
1014
- return pad > 0 ? " ".repeat(pad) + text2 : text2;
1015
- }
1016
- function truncate(text2, width, unicode) {
1017
- if (visibleWidth(text2) <= width) return text2;
1018
- const marker = unicode ? "\u2026" : "...";
1019
- const budget = Math.max(0, width - marker.length);
1020
- let out = "";
1021
- let used = 0;
1022
- for (const codePoint of text2) {
1023
- if (used + 1 > budget) break;
1024
- out += codePoint;
1025
- used += 1;
1026
- }
1027
- return out + marker;
1028
- }
1029
- var UNICODE_GLYPHS = {
1030
- horizontal: "\u2500",
1031
- vertical: "\u2502",
1032
- topLeft: "\u250C",
1033
- topRight: "\u2510",
1034
- bottomLeft: "\u2514",
1035
- bottomRight: "\u2518",
1036
- teeLeft: "\u251C",
1037
- teeRight: "\u2524",
1038
- bullet: "\u2022",
1039
- check: "\u2714",
1040
- cross: "\u2718",
1041
- partial: "\u25D0",
1042
- arrow: "\u2192"
1043
- };
1044
- var ASCII_GLYPHS = {
1045
- horizontal: "-",
1046
- vertical: "|",
1047
- topLeft: "+",
1048
- topRight: "+",
1049
- bottomLeft: "+",
1050
- bottomRight: "+",
1051
- teeLeft: "+",
1052
- teeRight: "+",
1053
- bullet: "*",
1054
- // One code point each, matching the Unicode set, so the status column is the
1055
- // same width in both renderings and the table does not need two layouts.
1056
- check: "+",
1057
- cross: "x",
1058
- partial: "~",
1059
- arrow: ">"
1060
- };
1061
- function glyphsFor(unicode) {
1062
- return unicode ? UNICODE_GLYPHS : ASCII_GLYPHS;
1063
- }
1064
-
1065
- // src/format/pretty.ts
1066
- var BASIS_COLUMN = 9;
1067
- var POINTS_COLUMN = 7;
1068
- function renderPretty(payload, caps, _ctx) {
1069
- const pretty = { caps, paint: createPainter(caps.color) };
1070
- switch (payload.command) {
1071
- case "check":
1072
- return joinBlocks(payload.reports.map((report) => checkBlock(report, pretty)));
1073
- case "diff":
1074
- return joinBlocks([diffBlock(payload.diff, pretty)]);
1075
- case "init":
1076
- return joinBlocks([initBlock(payload.scaffold, pretty)]);
1077
- case "badge":
1078
- return joinBlocks([badgeBlock(payload.badge, pretty)]);
1079
- }
1080
- }
1081
- function joinBlocks(blocks) {
1082
- return blocks.map((lines) => lines.map((line) => line.replace(/[ \t]+$/, "")).join("\n")).join("\n\n") + "\n";
1083
- }
1084
- function gradeStyle(grade) {
1085
- if (grade === "A") return "green";
1086
- if (grade === "B") return "cyan";
1087
- if (grade === "C") return "yellow";
1088
- return "red";
1089
- }
1090
- function checkBlock(report, pretty) {
1091
- const { paint, caps } = pretty;
1092
- const glyphs = glyphsFor(caps.unicode);
1093
- const lines = [];
1094
- const width = caps.width;
1095
- lines.push(paint(truncate(report.url, width, caps.unicode), "bold"));
1096
- lines.push(paint(glyphs.horizontal.repeat(Math.min(width, 64)), "gray"));
1097
- if (report.kind === "rejected") {
1098
- lines.push(`${paint("REJECTED", "red", "bold")} ${outcomeSummary(report)}`);
1099
- lines.push(...noticeLines(pretty));
1100
- return lines;
1101
- }
1102
- const { result } = report;
1103
- const status = statusOf(report);
1104
- if (status !== "scored") {
1105
- lines.push(paint(outcomeSummary(report), "yellow"));
1106
- lines.push("");
1107
- lines.push(...policyLines(result, pretty));
1108
- lines.push(...identityLines(result, pretty));
1109
- lines.push(...noticeLines(pretty));
1110
- return lines;
1111
- }
1112
- const grade = result.grade ?? "?";
1113
- const scoreText = `${result.score ?? 0}/100`;
1114
- lines.push(
1115
- `${paint(grade, gradeStyle(grade), "bold")} ${paint(result.bandLabel ?? "", "bold")} ${paint(scoreText, "gray")}`
1116
- );
1117
- lines.push(
1118
- paint(
1119
- `${result.measuredWeight} of the 100 points are measured, ${result.heuristicWeight} heuristic`,
1120
- "gray"
1121
- )
1122
- );
1123
- lines.push(
1124
- paint(
1125
- `page kind: ${result.pageKind} (${result.pageKindConfidence} confidence, ${basisLabel(result.pageKindBasis)})`,
1126
- "gray"
1127
- )
1128
- );
1129
- lines.push("");
1130
- for (const dimension of result.dimensions) {
1131
- lines.push(...dimensionLines(dimension, pretty));
1132
- }
1133
- lines.push("");
1134
- lines.push(...costLines(result, pretty));
1135
- if (result.flags.length > 0) {
1136
- lines.push("");
1137
- lines.push(paint("Flags", "bold"));
1138
- for (const flag of result.flags) {
1139
- const tone = flag.severity === "warn" ? "yellow" : "gray";
1140
- lines.push(
1141
- ` ${glyphs.bullet} ${paint(flag.id, tone)} [${basisLabel(flag.basis)}] ${flag.message}`
1142
- );
1143
- }
1144
- }
1145
- if (result.recommendations.length > 0) {
1146
- lines.push("");
1147
- lines.push(paint("Fixes, most points first", "bold"));
1148
- for (const recommendation of result.recommendations) {
1149
- lines.push(
1150
- ` ${padStart(`+${recommendation.pointsAvailable}`, 4)} ${paint(recommendation.title, "bold")} ${paint(`(${recommendation.effort})`, "gray")}`
1151
- );
1152
- lines.push(
1153
- paint(` ${truncate(recommendation.detail, caps.width - 8, caps.unicode)}`, "gray")
1154
- );
1155
- }
1156
- }
1157
- lines.push("");
1158
- lines.push(...policyLines(result, pretty));
1159
- lines.push(...identityLines(result, pretty));
1160
- lines.push(...noticeLines(pretty));
1161
- return lines;
1162
- }
1163
- function dimensionLines(dimension, pretty) {
1164
- const { paint, caps } = pretty;
1165
- const lines = [];
1166
- const head = `${dimension.label}`;
1167
- const points = `${dimension.earned}/${dimension.weight}`;
1168
- const labelWidth = Math.max(10, caps.width - POINTS_COLUMN - BASIS_COLUMN - 4);
1169
- lines.push(
1170
- `${paint(padEnd(truncate(head, labelWidth, caps.unicode), labelWidth), "bold")} ${padStart(points, POINTS_COLUMN)} ${padEnd(basisLabel(dimension.basis), BASIS_COLUMN)}`
1171
- );
1172
- for (const check of dimension.checks) {
1173
- lines.push(checkLine(check, pretty, labelWidth));
1174
- }
1175
- return lines;
1176
- }
1177
- function checkLine(check, pretty, labelWidth) {
1178
- const { paint, caps } = pretty;
1179
- const mark = checkMark(check, caps.unicode);
1180
- const tone = check.earned >= check.weight ? "green" : check.earned > 0 ? "yellow" : "red";
1181
- const label = ` ${mark} ${check.label}`;
1182
- const points = `${check.earned}/${check.weight}`;
1183
- return `${padEnd(truncate(label, labelWidth, caps.unicode), labelWidth)} ${paint(padStart(points, POINTS_COLUMN), tone)} ${paint(padEnd(basisLabel(check.basis), BASIS_COLUMN), "gray")}`;
1184
- }
1185
- function costLines(result, pretty) {
1186
- const { paint, caps } = pretty;
1187
- const { cost } = result;
1188
- const lines = [paint("What an agent pays", "bold")];
1189
- const html = bytesText(cost.htmlBytes, cost.truncated, caps.unicode);
1190
- const negotiated = bytesText(cost.negotiatedBytes, cost.truncated, caps.unicode);
1191
- const byteColumn = Math.max(visibleWidth(html), visibleWidth(negotiated)) + 3;
1192
- lines.push(
1193
- ` HTML ${padEnd(html, byteColumn)}${approxTokens(cost.approxHtmlTokens, caps.unicode)}`
1194
- );
1195
- lines.push(
1196
- ` Negotiated ${padEnd(negotiated, byteColumn)}${approxTokens(cost.approxNegotiatedTokens, caps.unicode)}`
1197
- );
1198
- if (cost.reductionRatio !== null) {
1199
- lines.push(paint(` Reduction ${cost.reductionRatio}%`, "green"));
1200
- }
1201
- lines.push(
1202
- ` First core fact at byte ${cost.firstCoreFactOffset === null ? absent(caps.unicode) : cost.firstCoreFactOffset.toLocaleString("en-US")}`
1203
- );
1204
- const core = result.factProfile.core;
1205
- const found = result.facts.filter((fact) => core.includes(fact.kind)).length;
1206
- lines.push(
1207
- paint(
1208
- ` Core facts found ${found}/${core.length} (${percent(found, core.length)}) for a ${result.pageKind} page \u2014 heuristic`,
1209
- "gray"
1210
- )
1211
- );
1212
- return lines;
1213
- }
1214
- function policyLines(result, pretty) {
1215
- const { paint } = pretty;
1216
- const { policy } = result;
1217
- const parts = [
1218
- `robots.txt ${policy.robotsTxtStatus}`,
1219
- `assistant ${policy.audiences.assistant.decision}`,
1220
- `training ${policy.audiences.training.decision} (neutral)`,
1221
- `sitemap ${policy.sitemapDeclared ? "declared" : "not declared"}`
1222
- ];
1223
- return [paint(`Policy: ${parts.join(" \xB7 ")}`, "gray")];
1224
- }
1225
- function identityLines(result, pretty) {
1226
- const { paint } = pretty;
1227
- return [
1228
- paint(
1229
- `ARS ${result.specVersion} \xB7 ruleset ${shortHash(result.rulesetHash)} \xB7 corpus ${shortHash(result.corpusHash)} \xB7 evidence ${shortHash(result.evidenceHash)} \xB7 vantage ${result.vantage}`,
1230
- "gray"
1231
- )
1232
- ];
1233
- }
1234
- function noticeLines(pretty) {
1235
- return ["", ...ARS_NOTICE_LINES.map((line) => pretty.paint(line, "gray"))];
1236
- }
1237
- function diffBlock(diff, pretty) {
1238
- const { paint, caps } = pretty;
1239
- const glyphs = glyphsFor(caps.unicode);
1240
- const lines = [
1241
- paint(truncate(diff.url, caps.width, caps.unicode), "bold"),
1242
- paint(glyphs.horizontal.repeat(Math.min(caps.width, 64)), "gray")
1243
- ];
1244
- if (diff.report.kind === "rejected") {
1245
- lines.push(`${paint("REJECTED", "red", "bold")} ${outcomeSummary(diff.report)}`);
1246
- lines.push(...noticeLines(pretty));
1247
- return lines;
1248
- }
1249
- lines.push(
1250
- paint(
1251
- "The two requests differ in the Accept header and in nothing else \u2014 same User-Agent, same everything (\xA73.3).",
1252
- "gray"
1253
- )
1254
- );
1255
- lines.push("");
1256
- const rows = [
1257
- ["", "agent", "browser"],
1258
- [
1259
- "Accept",
1260
- diff.agent?.accept ?? absent(caps.unicode),
1261
- diff.browser?.accept ?? absent(caps.unicode)
1262
- ],
1263
- ["Status", text(diff.agent?.status, caps.unicode), text(diff.browser?.status, caps.unicode)],
1264
- [
1265
- "Content-Type",
1266
- diff.agent?.contentType ?? absent(caps.unicode),
1267
- diff.browser?.contentType ?? absent(caps.unicode)
1268
- ],
1269
- [
1270
- "Bytes",
1271
- bytesText(diff.agent?.bytes ?? null, diff.agent?.truncated ?? false, caps.unicode),
1272
- bytesText(diff.browser?.bytes ?? null, diff.browser?.truncated ?? false, caps.unicode)
1273
- ],
1274
- [
1275
- "Tokens",
1276
- approxTokens(diff.agent?.approxTokens ?? null, caps.unicode),
1277
- approxTokens(diff.browser?.approxTokens ?? null, caps.unicode)
1278
- ],
1279
- [
1280
- "Redirects",
1281
- text(diff.agent?.redirects, caps.unicode),
1282
- text(diff.browser?.redirects, caps.unicode)
1283
- ],
1284
- [
1285
- "Error",
1286
- diff.agent?.error ?? absent(caps.unicode),
1287
- diff.browser?.error ?? absent(caps.unicode)
1288
- ]
1289
- ];
1290
- const labelWidth = Math.max(...rows.map((row) => row[0].length)) + 2;
1291
- const columnWidth = Math.max(12, Math.floor((caps.width - labelWidth - 2) / 2));
1292
- for (const [label, agentCell, browserCell] of rows) {
1293
- lines.push(
1294
- `${paint(padEnd(label, labelWidth), "bold")}${padEnd(truncate(agentCell, columnWidth, caps.unicode), columnWidth + 2)}${truncate(browserCell, columnWidth, caps.unicode)}`
1295
- );
1296
- }
1297
- if (diff.parity !== null) {
1298
- lines.push("");
1299
- lines.push(
1300
- `${paint("Substance parity", "bold")} ${paint(`[${basisLabel(diff.parity.basis)}]`, "gray")} ${diff.parity.earned}/${diff.parity.weight}`
1301
- );
1302
- lines.push(
1303
- paint(
1304
- " Compared on price, currency, availability and title only \u2014 never description or free text (\xA73.8).",
1305
- "gray"
1306
- )
1307
- );
1308
- for (const evidence of diff.parity.evidence) {
1309
- lines.push(
1310
- ` ${glyphs.bullet} ${evidence.label}: ${evidence.value} [${basisLabel(evidence.basis)}]`
1311
- );
1312
- }
1313
- }
1314
- if (diff.result !== null) {
1315
- lines.push("");
1316
- lines.push(paint(`Score: ${outcomeSummary(diff.report)}`, "gray"));
1317
- lines.push(...identityLines(diff.result, pretty));
1318
- }
1319
- lines.push(...noticeLines(pretty));
1320
- return lines;
1321
- }
1322
- function text(value, unicode) {
1323
- return value === void 0 || value === null ? absent(unicode) : String(value);
1324
- }
1325
- function initBlock(scaffold, pretty) {
1326
- const { paint } = pretty;
1327
- const lines = [
1328
- paint(`Detected framework: ${scaffold.framework}`, "bold"),
1329
- paint(` ${scaffold.detection}`, "gray"),
1330
- "",
1331
- paint(`Suggested path: ${scaffold.suggestedPath}`, "gray"),
1332
- "",
1333
- scaffold.contents.trimEnd()
1334
- ];
1335
- if (scaffold.notes.length > 0) {
1336
- lines.push("");
1337
- for (const note of scaffold.notes) lines.push(paint(` ${note}`, "gray"));
1338
- }
1339
- return lines;
1340
- }
1341
- function badgeBlock(badge, pretty) {
1342
- const { paint } = pretty;
1343
- const lines = [
1344
- paint(`Badge for ${badge.domain}`, "bold"),
1345
- "",
1346
- paint("Markdown", "bold"),
1347
- badge.markdown,
1348
- "",
1349
- paint("HTML", "bold"),
1350
- badge.html,
1351
- ""
1352
- ];
1353
- for (const note of badge.notes) lines.push(paint(` ${note}`, "gray"));
1354
- return lines;
1355
- }
1356
-
1357
- // src/format/index.ts
1358
- function render(payload, format, caps, ctx) {
1359
- if (format === "junit" && (payload.command === "init" || payload.command === "badge")) {
1360
- throw new UsageError(
1361
- `--format junit reports observations about a page; \`${payload.command}\` makes none. Use pretty, json or markdown.`
1362
- );
1363
- }
1364
- switch (format) {
1365
- case "pretty":
1366
- return renderPretty(payload, caps);
1367
- case "json":
1368
- return renderJson(payload, ctx);
1369
- case "markdown":
1370
- return renderMarkdown(payload, ctx);
1371
- case "junit":
1372
- return renderJunit(payload, ctx);
1373
- }
1374
- }
1375
-
1376
- // src/help.ts
1377
- var EXIT_TABLE = [
1378
- ` ${EXIT.OK} completed; threshold met, or no threshold set`,
1379
- ` ${EXIT.THRESHOLD} completed; threshold NOT met`,
1380
- ` ${EXIT.USAGE} usage error`,
1381
- ` ${EXIT.PROBE} probe failed / target unreachable \u2014 infrastructure, not a score failure`,
1382
- ` ${EXIT.POLICY} blocked by policy (SSRF guard, robots opt-out, probe budget spent)`
1383
- ];
1384
- var GENERAL = `rebilder \u2014 the Agent Readability Score, from your machine.
1385
-
1386
- USAGE
1387
- rebilder check <url...> [--format ${FORMATS.join("|")}] [--fail-on ${GRADES.join("|")}]
1388
- [--out <file>] [--allow-private] [--allow-http]
1389
- [--concurrency <n>]
1390
- rebilder diff <url> agent view vs browser view
1391
- rebilder init gateway config scaffold for the detected framework
1392
- rebilder badge <domain> embed snippet
1393
-
1394
- rebilder help <command> detail for one command
1395
- rebilder --version
1396
-
1397
- EXIT CODES (a stable contract; never renumbered)
1398
- ${EXIT_TABLE.join("\n")}
1399
-
1400
- The 1-vs-3 split is load-bearing. A flaky network exits 3, never 1: if an
1401
- unreachable host failed your build as a score failure, the check would be
1402
- deleted from CI within a week. --fail-on defaults to nothing, so plain
1403
- \`rebilder check <url>\` reports and exits 0.
1404
-
1405
- ZERO TELEMETRY
1406
- ${TELEMETRY_LINES.map((line) => ` ${line}`).join("\n")}
1407
-
1408
- Spec: https://rebilder.com/spec/ars Crawler policy: https://rebilder.com/bots
1409
- `;
1410
- var CHECK = `rebilder check <url...>
1411
-
1412
- Probes each URL twice \u2014 an agent request and a browser control that differ in
1413
- the Accept header and in nothing else \u2014 plus /robots.txt, /llms.txt and
1414
- /.well-known/ucp per origin. Nothing else is requested. robots.txt is fetched
1415
- first and obeyed.
1416
-
1417
- OPTIONS
1418
- --format ${FORMATS.join("|")} default pretty
1419
- --fail-on ${GRADES.join("|")} default none. "--fail-on C" means C or
1420
- better passes; a worse grade exits 1.
1421
- --out <file> write the same rendering to a file
1422
- --concurrency <n> URLs in flight; default 1, max 8. The
1423
- probe's politeness limiter still allows
1424
- at most 1 request per host and 2 globally.
1425
- --allow-http permit plain http targets
1426
- --allow-private permit private, loopback and link-local
1427
- targets. Routes through a separate,
1428
- import-time-gated entry point; it is opt-in
1429
- per invocation, never a config default, and
1430
- refuses to load in a hosted runtime.
1431
- Implies --allow-http.
1432
-
1433
- A non-graded outcome \u2014 a deliberate robots opt-out, a 403 at the edge, an
1434
- unreachable host \u2014 never produces exit 1. Only a real score compared against a
1435
- threshold you set can do that.
1436
- `;
1437
- var DIFF = `rebilder diff <url>
1438
-
1439
- Shows what the agent request received next to what the browser request
1440
- received: status, content type, decoded bytes, an estimated token count, and
1441
- the D2.4 substance-parity comparison verbatim.
1442
-
1443
- It shows structure and numbers, never an excerpt of the page. --fail-on is not
1444
- supported: diff reports, it does not grade.
1445
-
1446
- OPTIONS
1447
- --format ${FORMATS.join("|")} default pretty
1448
- --out <file> write the same rendering to a file
1449
- --allow-http, --allow-private as \`check\`
1450
- `;
1451
- var INIT = `rebilder init
1452
-
1453
- Writes a @rebilder/gateway config scaffold for the framework it detects in the
1454
- working directory, and prints how it decided. Makes no network request and
1455
- reads nothing outside the working directory.
1456
-
1457
- OPTIONS
1458
- --framework next|node|edge|shopify override detection
1459
- --out <file> write the scaffold to a file
1460
- --format ${FORMATS.join("|")} junit is refused: init makes no observations
1461
-
1462
- The scaffold is a skeleton with TODOs, not a working config. The resolvers
1463
- return YOUR source of truth \u2014 every substantive value comes from those fields,
1464
- and the gateway never invents one.
1465
- `;
1466
- var BADGE = `rebilder badge <domain>
1467
-
1468
- Prints the markdown and HTML embed snippets for a domain's badge. Built
1469
- locally: no network request, so we never learn which domain you asked about.
1470
-
1471
- A grade renders only for a verified opted-in domain; every other domain gets a
1472
- neutral "not rated" badge at 200, not 404. The badge always names its subject,
1473
- is served live, and degrades to "unverified" after 30 days without a
1474
- successful re-scan.
1475
-
1476
- OPTIONS
1477
- --format ${FORMATS.join("|")} junit is refused: badge makes no observations
1478
- --out <file> write the snippet to a file
1479
- `;
1480
- var TOPICS = {
1481
- check: CHECK,
1482
- diff: DIFF,
1483
- init: INIT,
1484
- badge: BADGE
1485
- };
1486
- function helpText(topic) {
1487
- if (topic === null) return GENERAL;
1488
- return TOPICS[topic];
1489
- }
1490
-
1491
- // src/cli.ts
1492
- var CLI_VERSION = "0.2.0";
1493
- async function runCli(argv, runtime) {
1494
- const caps = detectCapabilities({
1495
- env: runtime.env,
1496
- isTty: runtime.isTty,
1497
- columns: runtime.columns
1498
- });
1499
- try {
1500
- const parsed = parseCommandLine(argv);
1501
- if (parsed.kind === "version") {
1502
- runtime.write(`${CLI_VERSION}
1503
- `);
1504
- return EXIT.OK;
1505
- }
1506
- if (parsed.kind === "help") {
1507
- runtime.write(helpText(parsed.topic));
1508
- return EXIT.OK;
1509
- }
1510
- const { command } = parsed;
1511
- const { payload, exitCode } = await execute(command, runtime);
1512
- const ctx = {
1513
- unicode: caps.unicode,
1514
- generatedAt: runtime.now().toISOString(),
1515
- cliVersion: CLI_VERSION
1516
- };
1517
- const rendered = render(payload, command.format, caps, ctx);
1518
- runtime.write(rendered);
1519
- if (command.out !== null) {
1520
- await runtime.writeFile(command.out, rendered);
1521
- }
1522
- return exitCode;
1523
- } catch (error) {
1524
- if (error instanceof UsageError) {
1525
- runtime.writeError(`rebilder: ${error.message}
1526
-
1527
- Run \`rebilder --help\`.
1528
- `);
1529
- return EXIT.USAGE;
1530
- }
1531
- runtime.writeError(`rebilder: ${error instanceof Error ? error.message : String(error)}
1532
- `);
1533
- return EXIT.PROBE;
1534
- }
1535
- }
1536
- async function execute(command, runtime) {
1537
- switch (command.name) {
1538
- case "check": {
1539
- const probe = await buildProbe(runtime, command.urls.length, command);
1540
- const reports = await runCheck(command, probe);
1541
- return {
1542
- payload: { command: "check", reports, failOn: command.failOn },
1543
- exitCode: worstExit(reports.map((report) => exitCodeFor(report, command.failOn)))
1544
- };
1545
- }
1546
- case "diff": {
1547
- const probe = await buildProbe(runtime, 1, command);
1548
- const diff = await runDiff(command, probe);
1549
- return { payload: { command: "diff", diff }, exitCode: exitCodeFor(diff.report, null) };
1550
- }
1551
- case "init": {
1552
- const scaffold = await runInit(command, runtime);
1553
- return { payload: { command: "init", scaffold }, exitCode: EXIT.OK };
1554
- }
1555
- case "badge": {
1556
- return { payload: { command: "badge", badge: runBadge(command) }, exitCode: EXIT.OK };
1557
- }
1558
- }
1559
- }
1560
- function buildProbe(runtime, urlCount, flags) {
1561
- return runtime.probe({
1562
- allowPrivate: flags.allowPrivate,
1563
- allowHttp: flags.allowHttp,
1564
- urlCount
1565
- });
1566
- }
1567
- function budgetFor(urlCount) {
1568
- return Math.max(20, urlCount * 6 + 4);
1569
- }
1570
- function policyFor(setup, base) {
1571
- return { ...base, allowHttp: setup.allowHttp || base.allowHttp };
1572
- }
1573
- var nodeProbeFactory = async (setup) => {
1574
- const limiter = probe.createLimiter({ maxProbesPerRun: budgetFor(setup.urlCount) });
1575
- if (!setup.allowPrivate) {
1576
- const policy2 = policyFor(setup, probe.strictPolicy(limiter));
1577
- return (target) => probe.probeStrict(target, policy2);
1578
- }
1579
- const local = await import('@rebilder/agent-readability/probe/local');
1580
- const policy = policyFor(setup, local.localPolicy(limiter));
1581
- return (target) => local.probeLocal(target, policy);
1582
- };
1583
- function createNodeRuntime() {
1584
- return {
1585
- env: process.env,
1586
- cwd: process.cwd(),
1587
- isTty: process.stdout.isTTY === true,
1588
- columns: process.stdout.columns,
1589
- write: (text2) => process.stdout.write(text2),
1590
- writeError: (text2) => process.stderr.write(text2),
1591
- writeFile: async (path$1, contents) => {
1592
- await promises.writeFile(path.resolve(process.cwd(), path$1), contents, "utf8");
1593
- },
1594
- readFile: async (path$1) => {
1595
- try {
1596
- return await promises.readFile(path.resolve(process.cwd(), path$1), "utf8");
1597
- } catch {
1598
- return null;
1599
- }
1600
- },
1601
- probe: nodeProbeFactory,
1602
- now: () => /* @__PURE__ */ new Date()
1603
- };
1604
- }
1605
-
1606
- exports.ARS_NOTICE = ARS_NOTICE;
1607
- exports.ARS_NOTICE_LINES = ARS_NOTICE_LINES;
1608
- exports.BADGE_ORIGIN = BADGE_ORIGIN;
1609
- exports.CLI_VERSION = CLI_VERSION;
1610
- exports.COMMANDS = COMMANDS;
1611
- exports.EXIT = EXIT;
1612
- exports.FORMATS = FORMATS;
1613
- exports.FRAMEWORKS = FRAMEWORKS;
1614
- exports.GRADES = GRADES;
1615
- exports.TELEMETRY_LINES = TELEMETRY_LINES;
1616
- exports.UsageError = UsageError;
1617
- exports.budgetFor = budgetFor;
1618
- exports.createNodeRuntime = createNodeRuntime;
1619
- exports.detectCapabilities = detectCapabilities;
1620
- exports.detectFramework = detectFramework;
1621
- exports.exitCodeFor = exitCodeFor;
1622
- exports.helpText = helpText;
1623
- exports.meetsThreshold = meetsThreshold;
1624
- exports.nodeProbeFactory = nodeProbeFactory;
1625
- exports.normalizeDomain = normalizeDomain;
1626
- exports.outcomeSummary = outcomeSummary;
1627
- exports.parseCommandLine = parseCommandLine;
1628
- exports.render = render;
1629
- exports.runCli = runCli;
1630
- exports.statusOf = statusOf;
1631
- exports.worstExit = worstExit;
1632
- //# sourceMappingURL=index.cjs.map
1633
- //# sourceMappingURL=index.cjs.map