rebilder 0.4.0 → 0.6.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.js CHANGED
@@ -36,10 +36,12 @@ var UsageError = class extends Error {
36
36
  // src/args.ts
37
37
  var FORMATS = ["pretty", "json", "markdown", "junit"];
38
38
  var GRADES = ["A", "B", "C", "D", "F"];
39
- var COMMANDS = ["check", "diff", "init", "badge"];
39
+ var COMMANDS = ["check", "docs-check", "diff", "init", "badge"];
40
40
  var OPTIONS = {
41
41
  format: { type: "string" },
42
+ json: { type: "boolean" },
42
43
  "fail-on": { type: "string" },
44
+ "fail-on-blocking": { type: "boolean" },
43
45
  out: { type: "string" },
44
46
  "allow-private": { type: "boolean" },
45
47
  "allow-http": { type: "boolean" },
@@ -139,6 +141,15 @@ function parseCommandLine(argv) {
139
141
  const out = values.out ?? null;
140
142
  const allowPrivate = values["allow-private"] === true;
141
143
  const allowHttp = values["allow-http"] === true || allowPrivate;
144
+ if (values["fail-on-blocking"] === true && name !== "docs-check") {
145
+ throw new UsageError(
146
+ `--fail-on-blocking is only supported by \`docs-check\`. Use \`rebilder check --fail-on <grade>\` for ARS grading.`
147
+ );
148
+ }
149
+ if (values.json === true && values.format !== void 0 && values.format !== "json") {
150
+ throw new UsageError(`--json cannot be combined with --format ${values.format}.`);
151
+ }
152
+ const resolvedFormat = values.json === true ? "json" : asFormat(values.format, "pretty");
142
153
  switch (name) {
143
154
  case "check": {
144
155
  if (rest.length === 0) {
@@ -149,7 +160,7 @@ function parseCommandLine(argv) {
149
160
  command: {
150
161
  name: "check",
151
162
  urls: rest,
152
- format: asFormat(values.format, "pretty"),
163
+ format: resolvedFormat,
153
164
  failOn: asGrade(values["fail-on"]),
154
165
  out,
155
166
  allowPrivate,
@@ -158,6 +169,35 @@ function parseCommandLine(argv) {
158
169
  }
159
170
  };
160
171
  }
172
+ case "docs-check": {
173
+ if (rest.length === 0) {
174
+ throw new UsageError("docs-check needs a URL. Usage: rebilder docs-check <url>");
175
+ }
176
+ if (rest.length > 1) {
177
+ throw new UsageError("docs-check takes exactly one URL.");
178
+ }
179
+ if (values["fail-on"] !== void 0) {
180
+ throw new UsageError(
181
+ "--fail-on is not supported by `docs-check`. Use `--fail-on-blocking` to fail when blocking docs findings are present."
182
+ );
183
+ }
184
+ const url = rest[0];
185
+ if (url === void 0) {
186
+ throw new UsageError("docs-check needs a URL. Usage: rebilder docs-check <url>");
187
+ }
188
+ return {
189
+ kind: "command",
190
+ command: {
191
+ name: "docs-check",
192
+ url,
193
+ format: resolvedFormat,
194
+ failOnBlocking: values["fail-on-blocking"] === true,
195
+ out,
196
+ allowPrivate,
197
+ allowHttp
198
+ }
199
+ };
200
+ }
161
201
  case "diff": {
162
202
  if (rest.length === 0) throw new UsageError("diff needs a URL. Usage: rebilder diff <url>");
163
203
  if (rest.length > 1) {
@@ -466,12 +506,26 @@ async function runInit(command, runtime) {
466
506
  }
467
507
  return { ...SCAFFOLDS[framework], framework, detection };
468
508
  }
509
+ var INGEST_ORIGIN = "https://api.rebilder.com";
510
+ var CONSOLE_INSTALL_URL = "https://rebilder.com/console/install";
469
511
  var SHARED_NOTES = [
470
512
  "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.",
471
- "The Apache-2.0 SDK serves without a Rebilder account or subscription. Configure reporting separately.",
513
+ "The Apache-2.0 SDK serves without a Rebilder account or subscription.",
514
+ `Reporting is wired in. Install \`@rebilder/events\`, create a free account, then set REBILDER_STORE_ID and REBILDER_API_KEY from ${CONSOLE_INSTALL_URL}. Without the key, nothing is sent.`,
472
515
  `Run \`rebilder check <url>\` before and after to see what changed. Sending a Markdown copy from the page address is D2.1 (${DEFAULT_RULESET.weights["machine-representation.negotiated-response"] ?? 0} points) and unlocks D2.3 and D2.4.`
473
516
  ];
474
517
  var CONFIG_BODY = `import type { GatewayConfig } from '@rebilder/gateway'
518
+ import { createHttpEventSink } from '@rebilder/events'
519
+
520
+ // Reports agent visits to your Rebilder Console. Free accounts include it.
521
+ // Copy both values from ${CONSOLE_INSTALL_URL} into your environment.
522
+ // Without REBILDER_API_KEY, nothing is sent.
523
+ const env = (name: string): string | undefined =>
524
+ (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.[name]
525
+ const apiKey = env('REBILDER_API_KEY')
526
+
527
+ // Module scope, not per request: the sink batches (20 events, or every 2s).
528
+ const sink = apiKey ? createHttpEventSink({ url: '${INGEST_ORIGIN}', apiKey }) : null
475
529
 
476
530
  /**
477
531
  * Wiring to YOUR source of truth. Each resolver takes a URL and returns the
@@ -481,7 +535,7 @@ var CONFIG_BODY = `import type { GatewayConfig } from '@rebilder/gateway'
481
535
  * call except a cache. Anything slower belongs in a build step.
482
536
  */
483
537
  export const gatewayConfig: GatewayConfig = {
484
- storeId: 'TODO-your-store-id',
538
+ storeId: env('REBILDER_STORE_ID') ?? 'TODO-your-store-id',
485
539
  sources: {
486
540
  // TODO: return your product fields, or null when the URL is not a PDP.
487
541
  product: async (url) => {
@@ -490,8 +544,7 @@ export const gatewayConfig: GatewayConfig = {
490
544
  },
491
545
  // TODO: policies, catalog, document, collection \u2014 add the ones you have.
492
546
  },
493
- // Optional: emit @rebilder/events RebilderEventV0 into your observation layer.
494
- // onEvent: (event) => { void event },
547
+ onEvent: (event) => sink?.emit(event),
495
548
  }
496
549
  `;
497
550
  function scaffold(suggestedPath, mount, notes) {
@@ -565,7 +618,7 @@ import { createShopifyAppProxyHandler } from '@rebilder/gateway/shopify'
565
618
  import { gatewayConfig } from './gateway-config'
566
619
 
567
620
  export const loader = createShopifyAppProxyHandler(gatewayConfig, {
568
- sharedSecret: process.env.SHOPIFY_API_SECRET ?? '',
621
+ sharedSecret: process.env.SHOPIFY_APP_SECRET ?? '',
569
622
  })
570
623
  `,
571
624
  [
@@ -777,6 +830,1492 @@ export default async function middleware(request: Request) {
777
830
  )
778
831
  };
779
832
 
833
+ // src/docs-check.ts
834
+ var DOCS_CHECK_SCOPE = "This check reads the fetched page locally on your machine. It sends no data to Rebilder, does not install packages, and runs no code.";
835
+ function mediaTypeOf(contentType) {
836
+ if (contentType === null) return null;
837
+ return (contentType.split(";")[0] ?? "").trim().toLowerCase() || null;
838
+ }
839
+ function isMarkdownResponse(contentType, body) {
840
+ const type = mediaTypeOf(contentType);
841
+ if (type !== "text/markdown" && type !== "text/x-markdown" && type !== "text/plain") return false;
842
+ if (body === null) return false;
843
+ return !/^\s*(?:<!doctype html|<html\b)/i.test(body.slice(0, 2e3));
844
+ }
845
+ function captureToRep(capture) {
846
+ return {
847
+ status: capture.status,
848
+ contentType: capture.headers["content-type"]?.[0] ?? null,
849
+ body: capture.body ?? null,
850
+ finalUrl: capture.finalUrl
851
+ };
852
+ }
853
+ function recordToRep(record) {
854
+ if (record === null || record === void 0 || !record.result.ok) return null;
855
+ return captureToRep(record.result.capture);
856
+ }
857
+ function is2xx(rep) {
858
+ return rep !== null && rep.status >= 200 && rep.status < 300 && rep.body !== null;
859
+ }
860
+ function factsFromEvidence(evidence) {
861
+ const browser = recordToRep(evidence.probes.browser);
862
+ const agent = recordToRep(evidence.probes.agent);
863
+ const alt = recordToRep(evidence.probes.markdownAlternate);
864
+ let markdown = null;
865
+ if (is2xx(agent) && isMarkdownResponse(agent.contentType, agent.body)) {
866
+ markdown = { source: "negotiated", url: agent.finalUrl, body: agent.body };
867
+ } else if (is2xx(alt) && isMarkdownResponse(alt.contentType, alt.body)) {
868
+ markdown = { source: "alternate", url: alt.finalUrl, body: alt.body };
869
+ }
870
+ const llmsUrl = `${evidence.target.origin}/llms.txt`;
871
+ const llmsRecord = evidence.probes.llmsTxt;
872
+ let llmsTxt = { state: "unavailable", body: null, url: llmsUrl };
873
+ if (llmsRecord !== null && llmsRecord.result.ok) {
874
+ const cap = llmsRecord.result.capture;
875
+ const body = cap.body ?? "";
876
+ const ct = cap.headers["content-type"]?.[0] ?? null;
877
+ const looksHtml = /^\s*(?:<!doctype html|<html\b)/i.test(body.slice(0, 1e3));
878
+ if (cap.status >= 200 && cap.status < 300 && body.trim() !== "" && !looksHtml) {
879
+ llmsTxt = { state: "found", body, url: llmsUrl };
880
+ } else if (cap.status === 404 || cap.status === 410 || looksHtml || mediaTypeOf(ct) === "text/html") {
881
+ llmsTxt = { state: "missing", body: null, url: llmsUrl };
882
+ }
883
+ }
884
+ return {
885
+ url: evidence.target.url,
886
+ browser,
887
+ agent,
888
+ markdown,
889
+ llmsTxt
890
+ };
891
+ }
892
+ function classifyEvidenceStatus(evidence) {
893
+ const agent = evidence.probes.agent.result;
894
+ const browser = evidence.probes.browser.result;
895
+ if (agent.ok || browser.ok) return { status: "ok", detail: null };
896
+ if (agent.error === "policy-rejected" || browser.error === "policy-rejected") {
897
+ const detail2 = agent.error === "policy-rejected" ? agent.detail ?? "Blocked by robots.txt or probe policy." : browser.detail ?? "Blocked by robots.txt or probe policy.";
898
+ return { status: "policy", detail: detail2 };
899
+ }
900
+ const detail = browser.detail ?? agent.detail ?? `Probe failed (${browser.error})`;
901
+ return { status: "unreachable", detail };
902
+ }
903
+ var MAX_CODE_BLOCKS = 80;
904
+ var MAX_BLOCK_CHARS = 2e4;
905
+ var CONTEXT_CHARS = 600;
906
+ var NAMED_ENTITIES = {
907
+ amp: "&",
908
+ lt: "<",
909
+ gt: ">",
910
+ quot: '"',
911
+ apos: "'",
912
+ nbsp: " ",
913
+ hellip: "\u2026",
914
+ mdash: "\u2014",
915
+ ndash: "\u2013",
916
+ rsquo: "\u2019",
917
+ lsquo: "\u2018",
918
+ rdquo: "\u201D",
919
+ ldquo: "\u201C",
920
+ copy: "\xA9"
921
+ };
922
+ function decodeEntities(text2) {
923
+ return text2.replace(/&(#x[0-9a-f]{1,6}|#[0-9]{1,7}|[a-z]{2,8});/gi, (whole, ref) => {
924
+ if (ref[0] === "#") {
925
+ const code = ref[1] === "x" || ref[1] === "X" ? Number.parseInt(ref.slice(2), 16) : Number.parseInt(ref.slice(1), 10);
926
+ if (!Number.isFinite(code) || code <= 0 || code > 1114111) return whole;
927
+ try {
928
+ return String.fromCodePoint(code);
929
+ } catch {
930
+ return whole;
931
+ }
932
+ }
933
+ return NAMED_ENTITIES[ref.toLowerCase()] ?? whole;
934
+ });
935
+ }
936
+ function stripTags(html) {
937
+ return html.replace(/<[^>]*>/g, "");
938
+ }
939
+ function htmlProse(html) {
940
+ const withBreaks = html.replace(/<br\s*\/?>/gi, "\n").replace(
941
+ /<\/?(?:p|div|li|ul|ol|tr|td|th|table|section|article|header|footer|aside|nav|blockquote|dd|dt|dl|figure|figcaption|details|summary)\b[^>]*>/gi,
942
+ "\n"
943
+ );
944
+ return decodeEntities(stripTags(withBreaks)).split("\n").map((line) => line.replace(/[ \t\u00a0]+/g, " ").trim()).filter((line) => line !== "");
945
+ }
946
+ function attrValue(tag, name) {
947
+ const patterns = {
948
+ class: /\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/i,
949
+ "data-language": /\sdata-language\s*=\s*(?:"([^"]*)"|'([^']*)')/i,
950
+ "data-lang": /\sdata-lang\s*=\s*(?:"([^"]*)"|'([^']*)')/i,
951
+ alt: /\salt\s*=\s*(?:"([^"]*)"|'([^']*)')/i,
952
+ src: /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i
953
+ };
954
+ const match = patterns[name].exec(tag);
955
+ if (!match) return null;
956
+ return decodeEntities(match[1] ?? match[2] ?? "");
957
+ }
958
+ var LANG_ALIASES = {
959
+ sh: "shell",
960
+ bash: "shell",
961
+ zsh: "shell",
962
+ shell: "shell",
963
+ shellscript: "shell",
964
+ "shell-session": "console",
965
+ shellsession: "console",
966
+ terminal: "shell",
967
+ console: "console",
968
+ powershell: "powershell",
969
+ ps1: "powershell",
970
+ js: "javascript",
971
+ mjs: "javascript",
972
+ cjs: "javascript",
973
+ javascript: "javascript",
974
+ jsx: "jsx",
975
+ ts: "typescript",
976
+ typescript: "typescript",
977
+ tsx: "tsx",
978
+ py: "python",
979
+ python: "python",
980
+ python3: "python",
981
+ plaintext: "text",
982
+ plain: "text",
983
+ txt: "text",
984
+ text: "text",
985
+ none: "text",
986
+ yml: "yaml",
987
+ dotenv: "env",
988
+ env: "env"
989
+ };
990
+ function normalizeLang(raw) {
991
+ const lang = raw.trim().toLowerCase().replace(/^\{?\.?/, "").replace(/[{}]/g, "").split(/[\s,:{]/)[0];
992
+ if (lang === void 0 || lang === "") return null;
993
+ return LANG_ALIASES[lang] ?? lang;
994
+ }
995
+ function languageFromTag(tag) {
996
+ const data = attrValue(tag, "data-language") ?? attrValue(tag, "data-lang");
997
+ if (data !== null && data.trim() !== "") return normalizeLang(data);
998
+ const classes = attrValue(tag, "class");
999
+ if (classes === null) return null;
1000
+ for (const token of classes.split(/\s+/)) {
1001
+ const match = /^(?:language|lang|highlight-source|highlight)-([a-z0-9+#._-]{1,30})$/i.exec(
1002
+ token
1003
+ );
1004
+ if (match?.[1]) return normalizeLang(match[1]);
1005
+ }
1006
+ return null;
1007
+ }
1008
+ function linkContext(nodes, source) {
1009
+ const blocks = [];
1010
+ let section = null;
1011
+ for (const node of nodes) {
1012
+ if (node.kind === "heading") section = node.text;
1013
+ if (node.kind === "code") {
1014
+ node.block.section = section;
1015
+ blocks.push(node.block);
1016
+ }
1017
+ }
1018
+ for (let i = 0; i < nodes.length; i++) {
1019
+ const node = nodes[i];
1020
+ if (node?.kind !== "code") continue;
1021
+ let before = "";
1022
+ for (let j = i - 1; j >= 0 && before.length < CONTEXT_CHARS; j--) {
1023
+ const prev = nodes[j];
1024
+ if (prev === void 0 || prev.kind === "code") break;
1025
+ if (prev.kind === "text" || prev.kind === "heading") before = `${prev.text}
1026
+ ${before}`;
1027
+ }
1028
+ let after = "";
1029
+ for (let j = i + 1; j < nodes.length && after.length < CONTEXT_CHARS; j++) {
1030
+ const next = nodes[j];
1031
+ if (next === void 0 || next.kind === "code" || next.kind === "heading") break;
1032
+ if (next.kind === "text") after = `${after}${next.text}
1033
+ `;
1034
+ }
1035
+ node.block.before = before.slice(-CONTEXT_CHARS);
1036
+ node.block.after = after.slice(0, CONTEXT_CHARS);
1037
+ }
1038
+ const prose = nodes.flatMap((node) => node.kind === "text" || node.kind === "heading" ? [node.text] : []).join("\n");
1039
+ return { source, nodes, blocks, prose };
1040
+ }
1041
+ function contentRegion(html) {
1042
+ const main = /<main\b[^>]*>([\s\S]*)<\/main>/i.exec(html);
1043
+ if (main?.[1] !== void 0) return main[1];
1044
+ const article = /<article\b[^>]*>([\s\S]*)<\/article>/i.exec(html);
1045
+ if (article?.[1] !== void 0) return article[1];
1046
+ const body = /<body\b[^>]*>([\s\S]*)<\/body>/i.exec(html);
1047
+ return body?.[1] ?? html;
1048
+ }
1049
+ function stripInvisible(html) {
1050
+ return html.replace(/<!--[\s\S]*?-->/g, " ").replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, " ").replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/gi, " ").replace(/<svg\b[^>]*>[\s\S]*?<\/svg\s*>/gi, " ").replace(/<template\b[^>]*>[\s\S]*?<\/template\s*>/gi, " ").replace(/<head\b[^>]*>[\s\S]*?<\/head\s*>/gi, " ");
1051
+ }
1052
+ function parseHtmlDocument(html) {
1053
+ const region = stripInvisible(contentRegion(stripInvisible(html)));
1054
+ const nodes = [];
1055
+ const pattern = /<pre\b[^>]*>[\s\S]*?<\/pre\s*>|<h([1-6])\b[^>]*>[\s\S]*?<\/h\1\s*>|<img\b[^>]*>/gi;
1056
+ let last = 0;
1057
+ let blockIndex = 0;
1058
+ const pushText = (chunk) => {
1059
+ for (const line of htmlProse(chunk)) nodes.push({ kind: "text", text: line });
1060
+ };
1061
+ for (let match = pattern.exec(region); match !== null; match = pattern.exec(region)) {
1062
+ pushText(region.slice(last, match.index));
1063
+ last = match.index + match[0].length;
1064
+ const whole = match[0];
1065
+ if (/^<pre\b/i.test(whole)) {
1066
+ if (blockIndex >= MAX_CODE_BLOCKS) continue;
1067
+ const openPre = /^<pre\b[^>]*>/i.exec(whole)?.[0] ?? "";
1068
+ const openCode = /<code\b[^>]*>/i.exec(whole)?.[0] ?? "";
1069
+ const wrapper = region.slice(Math.max(0, match.index - 300), match.index);
1070
+ const wrapperTags = wrapper.match(/<[a-z][^>]*>/gi) ?? [];
1071
+ const lang = languageFromTag(openPre) ?? languageFromTag(openCode) ?? (wrapperTags.length > 0 ? languageFromTag(wrapperTags[wrapperTags.length - 1] ?? "") : null);
1072
+ const inner = whole.replace(/^<pre\b[^>]*>/i, "").replace(/<\/pre\s*>$/i, "").replace(/<br\s*\/?>/gi, "\n").replace(/<\/div>\s*<div\b[^>]*>/gi, "\n");
1073
+ const codeText = decodeEntities(stripTags(inner)).replace(/\n$/, "").slice(0, MAX_BLOCK_CHARS);
1074
+ nodes.push({
1075
+ kind: "code",
1076
+ block: { index: blockIndex++, lang, code: codeText, section: null, before: "", after: "" }
1077
+ });
1078
+ } else if (/^<h[1-6]\b/i.test(whole)) {
1079
+ const level = Number(match[1] ?? "2");
1080
+ const text2 = decodeEntities(stripTags(whole)).replace(/\s+/g, " ").trim();
1081
+ if (text2 !== "") nodes.push({ kind: "heading", level, text: text2 });
1082
+ } else {
1083
+ nodes.push({
1084
+ kind: "image",
1085
+ alt: (attrValue(whole, "alt") ?? "").trim(),
1086
+ src: (attrValue(whole, "src") ?? "").trim()
1087
+ });
1088
+ }
1089
+ }
1090
+ pushText(region.slice(last));
1091
+ return linkContext(nodes, "html");
1092
+ }
1093
+ function parseMarkdownDocument(markdown) {
1094
+ const nodes = [];
1095
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
1096
+ let i = 0;
1097
+ if (lines[0]?.trim() === "---") {
1098
+ const end = lines.findIndex((line, n) => n > 0 && line.trim() === "---");
1099
+ if (end > 0) i = end + 1;
1100
+ }
1101
+ let blockIndex = 0;
1102
+ while (i < lines.length) {
1103
+ const line = lines[i] ?? "";
1104
+ const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1105
+ if (fence) {
1106
+ const marker = fence[1] ?? "```";
1107
+ const info = (fence[2] ?? "").trim();
1108
+ const body = [];
1109
+ i++;
1110
+ while (i < lines.length) {
1111
+ const candidate = (lines[i] ?? "").trim();
1112
+ const closes = candidate.length >= marker.length && candidate[0] === marker[0] && /^(?:`+|~+)$/.test(candidate);
1113
+ if (closes) break;
1114
+ body.push(lines[i] ?? "");
1115
+ i++;
1116
+ }
1117
+ i++;
1118
+ if (blockIndex < MAX_CODE_BLOCKS) {
1119
+ nodes.push({
1120
+ kind: "code",
1121
+ block: {
1122
+ index: blockIndex++,
1123
+ lang: info === "" ? null : normalizeLang(info),
1124
+ code: body.join("\n").slice(0, MAX_BLOCK_CHARS),
1125
+ section: null,
1126
+ before: "",
1127
+ after: ""
1128
+ }
1129
+ });
1130
+ }
1131
+ continue;
1132
+ }
1133
+ const heading = /^ {0,3}(#{1,6})\s+(.+)$/.exec(line);
1134
+ if (heading) {
1135
+ const text3 = (heading[2] ?? "").replace(/\s+#+\s*$/, "").trim();
1136
+ if (text3 !== "") nodes.push({ kind: "heading", level: heading[1]?.length ?? 2, text: text3 });
1137
+ i++;
1138
+ continue;
1139
+ }
1140
+ const imagePattern = /!\[([^\]]{0,300})\]\(\s*([^)\s]{1,2048})[^)]{0,300}\)/g;
1141
+ let rest = line;
1142
+ for (let image = imagePattern.exec(line); image !== null; image = imagePattern.exec(line)) {
1143
+ nodes.push({ kind: "image", alt: image[1] ?? "", src: image[2] ?? "" });
1144
+ rest = rest.replace(image[0], " ");
1145
+ }
1146
+ const text2 = rest.trim();
1147
+ if (text2 !== "") nodes.push({ kind: "text", text: text2 });
1148
+ i++;
1149
+ }
1150
+ return linkContext(nodes, "markdown");
1151
+ }
1152
+ var SHELL_LANGS = /* @__PURE__ */ new Set(["shell", "console", "powershell", "cmd", "bat"]);
1153
+ var JS_LANGS = /* @__PURE__ */ new Set(["javascript", "typescript", "jsx", "tsx"]);
1154
+ var PY_LANGS = /* @__PURE__ */ new Set(["python"]);
1155
+ var NON_RUNNABLE_LANGS = /* @__PURE__ */ new Set(["text", "output", "log", "console", "diff"]);
1156
+ var MARKUP_LANGS = /* @__PURE__ */ new Set([
1157
+ "html",
1158
+ "xml",
1159
+ "jsx",
1160
+ "tsx",
1161
+ "vue",
1162
+ "svelte",
1163
+ "markup",
1164
+ "astro"
1165
+ ]);
1166
+ var PROGRAM_LANGS = /* @__PURE__ */ new Set([
1167
+ "javascript",
1168
+ "typescript",
1169
+ "jsx",
1170
+ "tsx",
1171
+ "python",
1172
+ "go",
1173
+ "ruby",
1174
+ "rust",
1175
+ "java",
1176
+ "kotlin",
1177
+ "csharp",
1178
+ "cs",
1179
+ "c#",
1180
+ "php",
1181
+ "swift",
1182
+ "dart",
1183
+ "elixir",
1184
+ "scala"
1185
+ ]);
1186
+ var SHELL_START = /^\s*(?:\$|%|>)?\s*(?:npm|npx|pnpm|yarn|bun|pip3?|python3?|uv|poetry|pipenv|curl|wget|git|cd|export|go|cargo|gem|bundle|composer|dotnet|brew|docker|kubectl|mkdir|echo|source)\b/;
1187
+ var PROGRAM_LINE = /^\s*(?:import\s+[\w*{'"]|from\s+[\w.]+\s+import\s|(?:const|let|var)\s+[\w${}\s,]+=\s*require\(|export\s+(?:default|const|function|class)\s|package\s+\w+\s*;?\s*$|#include\s*[<"]|using\s+[\w.]+\s*;)/m;
1188
+ var PROMPT = /^\s*(?:\$|%|PS [^>\n]{0,80}>|[A-Za-z]:\\[^>\n]{0,80}>)\s/;
1189
+ function isShellBlock(block) {
1190
+ if (block.lang !== null) return SHELL_LANGS.has(block.lang);
1191
+ const first = block.code.split("\n").find((line) => line.trim() !== "" && !/^\s*#/.test(line)) ?? "";
1192
+ return SHELL_START.test(first);
1193
+ }
1194
+ function isProgramBlock(block) {
1195
+ if (block.lang !== null) return PROGRAM_LANGS.has(block.lang);
1196
+ return !isShellBlock(block) && PROGRAM_LINE.test(block.code);
1197
+ }
1198
+ function stripPrompt(line) {
1199
+ return line.replace(PROMPT, "");
1200
+ }
1201
+ function promptUse(block) {
1202
+ const lines = block.code.split("\n");
1203
+ const promptLines = lines.filter((line) => PROMPT.test(line));
1204
+ if (promptLines.length === 0) return { promptLines, outputLines: [] };
1205
+ const outputLines = [];
1206
+ let continued = false;
1207
+ for (const line of lines) {
1208
+ const trimmed = line.trim();
1209
+ if (trimmed === "") {
1210
+ continued = false;
1211
+ continue;
1212
+ }
1213
+ if (PROMPT.test(line)) {
1214
+ continued = trimmed.endsWith("\\");
1215
+ continue;
1216
+ }
1217
+ if (continued) {
1218
+ continued = trimmed.endsWith("\\");
1219
+ continue;
1220
+ }
1221
+ if (trimmed.startsWith("#")) continue;
1222
+ outputLines.push(line);
1223
+ }
1224
+ return { promptLines, outputLines };
1225
+ }
1226
+ function elisionLines(block) {
1227
+ if (block.lang !== null && NON_RUNNABLE_LANGS.has(block.lang)) return [];
1228
+ return block.code.split("\n").filter((line) => {
1229
+ const trimmed = line.trim();
1230
+ if (trimmed === "..." || trimmed === "\u2026") return true;
1231
+ if (/^(?:\/\/|#|--|\/\*|<!--)\s*(?:\.\.\.|…)/.test(trimmed)) return true;
1232
+ if (trimmed.includes("\u2026")) return true;
1233
+ return /(?:^|[^\w.])\.\.\.(?![\w$[({'"`.])/.test(line);
1234
+ });
1235
+ }
1236
+ var PLACEHOLDER_PATTERNS = [
1237
+ /\b(?:YOUR|MY)_[A-Z0-9_]{2,40}\b/g,
1238
+ /\b(?:your|my)[-_][a-z0-9][a-z0-9_-]{1,40}\b/g,
1239
+ /\b(?:REPLACE_ME|CHANGE_?ME|INSERT_[A-Z0-9_]{2,40})\b/g,
1240
+ /(?<![\w-])[xX]{3,}(?![\w-])/g
1241
+ ];
1242
+ var ANGLE_PLACEHOLDER = /<([A-Za-z][\w -]{0,30})>/g;
1243
+ var ANGLE_KEYWORDS = /(?:key|token|secret|password|passwd|id|name|project|org|account|value|url|domain|host|region|user|email|your|workspace|tenant)/i;
1244
+ var EXPLAINS_VALUE = /\b(?:replace|substitute|dashboard|settings|console|portal|account page|keys? page|generate|create (?:an?|your|the)|obtain|copy (?:it|your|the)|found (?:in|under|on)|get (?:an?|your)|sign up|you(?:'|’)ll need|retrieve)\b/i;
1245
+ function angleAllowed(block, line, index, length) {
1246
+ const before = line[index - 1];
1247
+ const after = line[index + length];
1248
+ const quoted = (before === '"' || before === "'") && (after === '"' || after === "'");
1249
+ if (quoted) return true;
1250
+ if (block.lang !== null && MARKUP_LANGS.has(block.lang)) return false;
1251
+ if (block.lang === null || isShellBlock(block)) return true;
1252
+ return ["env", "yaml", "toml", "json", "ini", "http", "text", "properties"].includes(block.lang);
1253
+ }
1254
+ function findPlaceholders(blocks) {
1255
+ const seen = /* @__PURE__ */ new Set();
1256
+ const out = [];
1257
+ for (const block of blocks) {
1258
+ const context = `${block.before}
1259
+ ${block.after}`;
1260
+ for (const line of block.code.split("\n")) {
1261
+ const tokens = [];
1262
+ for (const pattern of PLACEHOLDER_PATTERNS) {
1263
+ for (const match of line.matchAll(pattern)) tokens.push(match[0]);
1264
+ }
1265
+ for (const match of line.matchAll(ANGLE_PLACEHOLDER)) {
1266
+ const inner = match[1] ?? "";
1267
+ if (!ANGLE_KEYWORDS.test(inner)) continue;
1268
+ if (!angleAllowed(block, line, match.index ?? 0, match[0].length)) continue;
1269
+ tokens.push(match[0]);
1270
+ }
1271
+ for (const token of tokens) {
1272
+ const key = token.toLowerCase();
1273
+ if (seen.has(key)) continue;
1274
+ seen.add(key);
1275
+ const bare = token.replace(/^<|>$/g, "").toLowerCase();
1276
+ const explained = context.toLowerCase().includes(bare) || EXPLAINS_VALUE.test(context);
1277
+ out.push({ token, block, line: line.trim(), explained });
1278
+ if (out.length >= 20) return out;
1279
+ }
1280
+ }
1281
+ }
1282
+ return out;
1283
+ }
1284
+ var NPM_SEGMENT = /^[a-z0-9][a-z0-9._~-]{0,213}$/;
1285
+ var PYPI_CHARS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
1286
+ function isNpmName(name) {
1287
+ if (name.startsWith("@")) {
1288
+ const slash = name.indexOf("/");
1289
+ if (slash <= 1 || slash !== name.lastIndexOf("/")) return false;
1290
+ const scope = name.slice(1, slash);
1291
+ const pkg = name.slice(slash + 1);
1292
+ return scope.length <= 101 && NPM_SEGMENT.test(scope) && NPM_SEGMENT.test(pkg);
1293
+ }
1294
+ return NPM_SEGMENT.test(name);
1295
+ }
1296
+ function isPypiName(name) {
1297
+ if (name.length === 0 || name.length > 100) return false;
1298
+ if (!PYPI_CHARS.test(name)) return false;
1299
+ return /[A-Za-z0-9]$/.test(name);
1300
+ }
1301
+ function npmSpec(token, line) {
1302
+ const cleaned = token.replace(/^['"]|['"]$/g, "");
1303
+ if (cleaned === "" || /^(?:\.|\/|~|git|https?:|file:|npm:|github:|link:|workspace:)/.test(cleaned)) {
1304
+ return null;
1305
+ }
1306
+ const at = cleaned.startsWith("@") ? cleaned.indexOf("@", 1) : cleaned.indexOf("@");
1307
+ const name = at > 0 ? cleaned.slice(0, at) : cleaned;
1308
+ if (!isNpmName(name)) return null;
1309
+ return { ecosystem: "npm", name, evidence: line };
1310
+ }
1311
+ function pypiSpec(token, line) {
1312
+ const cleaned = token.replace(/^['"]|['"],?$/g, "").trim();
1313
+ if (cleaned === "" || cleaned.includes("/") || cleaned.endsWith(".whl") || cleaned.startsWith(".")) {
1314
+ return null;
1315
+ }
1316
+ const opIndex = cleaned.search(/===|==|~=|>=|<=|!=|>|</);
1317
+ const head = (opIndex >= 0 ? cleaned.slice(0, opIndex) : cleaned).trim();
1318
+ const bracket = head.indexOf("[");
1319
+ const name = (bracket >= 0 ? head.slice(0, bracket) : head).trim();
1320
+ if (!isPypiName(name)) return null;
1321
+ return { ecosystem: "pypi", name, evidence: line };
1322
+ }
1323
+ var MANAGER_RULES = [
1324
+ { manager: "npm", ecosystem: "npm", pattern: /^npm\s+(?:install|i|add)(?=\s|$)/ },
1325
+ { manager: "pnpm", ecosystem: "npm", pattern: /^pnpm\s+(?:add|install|i)(?=\s|$)/ },
1326
+ { manager: "yarn", ecosystem: "npm", pattern: /^yarn\s+(?:global\s+add|add)(?=\s|$)/ },
1327
+ { manager: "bun", ecosystem: "npm", pattern: /^bun\s+(?:add|install|i)(?=\s|$)/ },
1328
+ {
1329
+ manager: "pip",
1330
+ ecosystem: "pypi",
1331
+ pattern: /^(?:python3?\s+-m\s+pip3?|pip3?)\s+install(?=\s|$)/
1332
+ },
1333
+ { manager: "uv", ecosystem: "pypi", pattern: /^uv\s+(?:pip\s+install|add)(?=\s|$)/ },
1334
+ { manager: "poetry", ecosystem: "pypi", pattern: /^poetry\s+add(?=\s|$)/ },
1335
+ { manager: "pipenv", ecosystem: "pypi", pattern: /^pipenv\s+install(?=\s|$)/ },
1336
+ { manager: "go", ecosystem: "other", pattern: /^go\s+(?:get|install)(?=\s|$)/ },
1337
+ { manager: "cargo", ecosystem: "other", pattern: /^cargo\s+(?:add|install)(?=\s|$)/ },
1338
+ { manager: "gem", ecosystem: "other", pattern: /^(?:gem\s+install|bundle\s+add)(?=\s|$)/ },
1339
+ { manager: "composer", ecosystem: "other", pattern: /^composer\s+require(?=\s|$)/ },
1340
+ { manager: "dotnet", ecosystem: "other", pattern: /^dotnet\s+add\s+package(?=\s|$)/ },
1341
+ { manager: "brew", ecosystem: "other", pattern: /^brew\s+install(?=\s|$)/ }
1342
+ ];
1343
+ var ARG_FLAGS = /* @__PURE__ */ new Set([
1344
+ "-r",
1345
+ "--requirement",
1346
+ "-e",
1347
+ "--editable",
1348
+ "-c",
1349
+ "--constraint",
1350
+ "-i",
1351
+ "--index-url",
1352
+ "--extra-index-url",
1353
+ "--registry",
1354
+ "--filter",
1355
+ "-w",
1356
+ "--workspace",
1357
+ "-C",
1358
+ "--cwd"
1359
+ ]);
1360
+ function parseInstallLine(raw) {
1361
+ const line = stripPrompt(raw).trim().replace(/^sudo\s+/, "");
1362
+ for (const rule of MANAGER_RULES) {
1363
+ const head = rule.pattern.exec(line);
1364
+ if (!head) continue;
1365
+ const tail = line.slice(head[0].length).split(/\s(?:&&|\|\||;|\||#)\s?|[;|]/)[0] ?? "";
1366
+ const tokens = tail.split(/\s+/).filter((token) => token !== "" && token !== "\\");
1367
+ const packages = [];
1368
+ for (let n = 0; n < tokens.length; n++) {
1369
+ const token = tokens[n] ?? "";
1370
+ if (token.startsWith("-")) {
1371
+ if (ARG_FLAGS.has(token)) n++;
1372
+ continue;
1373
+ }
1374
+ if (rule.ecosystem === "npm") {
1375
+ const ref = npmSpec(token, line);
1376
+ if (ref) packages.push(ref);
1377
+ } else if (rule.ecosystem === "pypi") {
1378
+ const ref = pypiSpec(token, line);
1379
+ if (ref) packages.push(ref);
1380
+ }
1381
+ }
1382
+ return { manager: rule.manager, ecosystem: rule.ecosystem, line, packages };
1383
+ }
1384
+ return null;
1385
+ }
1386
+ function findInstallCommands(doc) {
1387
+ const out = [];
1388
+ const seen = /* @__PURE__ */ new Set();
1389
+ const add = (command) => {
1390
+ if (command === null || seen.has(command.line) || out.length >= 30) return;
1391
+ seen.add(command.line);
1392
+ out.push(command);
1393
+ };
1394
+ for (const block of doc.blocks) {
1395
+ if (!(isShellBlock(block) || block.lang === null || block.lang === "text")) continue;
1396
+ for (const line of block.code.split("\n")) add(parseInstallLine(line));
1397
+ }
1398
+ for (const node of doc.nodes) {
1399
+ if (node.kind !== "text") continue;
1400
+ const inline = /\b((?:npm|pnpm|yarn|bun|pip3?|python3? -m pip|uv|poetry|pipenv|go|cargo|gem|composer|dotnet|brew)\s+(?:install|i|add|get|require|pip install)\b[^`\n]{0,160})/.exec(
1401
+ node.text
1402
+ );
1403
+ if (inline?.[1]) add(parseInstallLine(inline[1].replace(/[.,)]+$/, "")));
1404
+ }
1405
+ return out;
1406
+ }
1407
+ var NODE_BUILTINS = /* @__PURE__ */ new Set([
1408
+ "assert",
1409
+ "async_hooks",
1410
+ "buffer",
1411
+ "child_process",
1412
+ "cluster",
1413
+ "console",
1414
+ "crypto",
1415
+ "dgram",
1416
+ "dns",
1417
+ "events",
1418
+ "fs",
1419
+ "http",
1420
+ "http2",
1421
+ "https",
1422
+ "module",
1423
+ "net",
1424
+ "os",
1425
+ "path",
1426
+ "perf_hooks",
1427
+ "process",
1428
+ "querystring",
1429
+ "readline",
1430
+ "stream",
1431
+ "string_decoder",
1432
+ "timers",
1433
+ "tls",
1434
+ "url",
1435
+ "util",
1436
+ "v8",
1437
+ "vm",
1438
+ "worker_threads",
1439
+ "zlib"
1440
+ ]);
1441
+ var PY_STDLIB = /* @__PURE__ */ new Set([
1442
+ "__future__",
1443
+ "abc",
1444
+ "argparse",
1445
+ "asyncio",
1446
+ "base64",
1447
+ "collections",
1448
+ "contextlib",
1449
+ "copy",
1450
+ "csv",
1451
+ "dataclasses",
1452
+ "datetime",
1453
+ "decimal",
1454
+ "enum",
1455
+ "functools",
1456
+ "glob",
1457
+ "hashlib",
1458
+ "hmac",
1459
+ "http",
1460
+ "importlib",
1461
+ "io",
1462
+ "itertools",
1463
+ "json",
1464
+ "logging",
1465
+ "math",
1466
+ "os",
1467
+ "pathlib",
1468
+ "pickle",
1469
+ "pprint",
1470
+ "random",
1471
+ "re",
1472
+ "shutil",
1473
+ "signal",
1474
+ "socket",
1475
+ "sqlite3",
1476
+ "ssl",
1477
+ "string",
1478
+ "subprocess",
1479
+ "sys",
1480
+ "tempfile",
1481
+ "textwrap",
1482
+ "threading",
1483
+ "time",
1484
+ "traceback",
1485
+ "typing",
1486
+ "unittest",
1487
+ "urllib",
1488
+ "uuid",
1489
+ "warnings",
1490
+ "xml",
1491
+ "zipfile"
1492
+ ]);
1493
+ function npmPackageOf(specifier) {
1494
+ if (/^(?:\.|\/|node:|#|https?:|~|@\/|bun:|deno:|jsr:|npm:)/.test(specifier)) return null;
1495
+ const parts = specifier.split("/");
1496
+ const name = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? "";
1497
+ if (!isNpmName(name) || NODE_BUILTINS.has(name)) return null;
1498
+ return name;
1499
+ }
1500
+ function findImports(doc) {
1501
+ const out = [];
1502
+ const seen = /* @__PURE__ */ new Set();
1503
+ const add = (ref) => {
1504
+ const key = `${ref.ecosystem}:${ref.name}`;
1505
+ if (seen.has(key)) return;
1506
+ seen.add(key);
1507
+ out.push(ref);
1508
+ };
1509
+ for (const block of doc.blocks) {
1510
+ const lang = block.lang;
1511
+ const js = lang !== null && JS_LANGS.has(lang);
1512
+ const py = lang !== null && PY_LANGS.has(lang);
1513
+ if (!js && !py && lang !== null) continue;
1514
+ for (const line of block.code.split("\n")) {
1515
+ if (js || lang === null) {
1516
+ for (const match of line.matchAll(
1517
+ /\b(?:from|import|require\(|import\()\s*['"]([^'"\s]{1,214})['"]/g
1518
+ )) {
1519
+ const name = npmPackageOf(match[1] ?? "");
1520
+ if (name !== null) add({ ecosystem: "npm", name, line: line.trim() });
1521
+ }
1522
+ }
1523
+ if (py || lang === null) {
1524
+ const fromImport = /^\s*from\s+([A-Za-z_][\w.]{0,100})\s+import\b/.exec(line);
1525
+ const plainImport = /^\s*import\s+([A-Za-z_][\w., ]{0,200})$/.exec(line);
1526
+ const modules = fromImport ? [fromImport[1] ?? ""] : plainImport ? (plainImport[1] ?? "").split(",").map((part) => part.trim().split(/\s+/)[0] ?? "") : [];
1527
+ for (const moduleName of modules) {
1528
+ const top = moduleName.split(".")[0] ?? "";
1529
+ if (top === "" || PY_STDLIB.has(top) || /['"]/.test(line)) continue;
1530
+ if (lang === null && /\bfrom\s+['"]/.test(line)) continue;
1531
+ add({ ecosystem: "pypi", name: top, line: line.trim() });
1532
+ }
1533
+ }
1534
+ }
1535
+ }
1536
+ return out.slice(0, 40);
1537
+ }
1538
+ var PY_IMPORT_ALIASES = {
1539
+ bs4: "beautifulsoup4",
1540
+ PIL: "pillow",
1541
+ yaml: "pyyaml",
1542
+ cv2: "opencv-python",
1543
+ sklearn: "scikit-learn",
1544
+ dotenv: "python-dotenv",
1545
+ dateutil: "python-dateutil",
1546
+ jwt: "pyjwt",
1547
+ magic: "python-magic",
1548
+ OpenSSL: "pyopenssl"
1549
+ };
1550
+ function normalizePy(name) {
1551
+ return name.toLowerCase().replace(/[-_.]+/g, "_");
1552
+ }
1553
+ function installProvides(installed, imported) {
1554
+ if (installed.ecosystem !== imported.ecosystem) return false;
1555
+ if (installed.ecosystem === "npm") return installed.name === imported.name;
1556
+ const dist = normalizePy(installed.name);
1557
+ const importedModule = normalizePy(imported.name);
1558
+ const alias = PY_IMPORT_ALIASES[imported.name];
1559
+ if (alias !== void 0 && normalizePy(alias) === dist) return true;
1560
+ const stripped = dist.replace(/^(?:python|py)_/, "").replace(/_(?:python|py|sdk|client)$/, "");
1561
+ return dist === importedModule || stripped === importedModule || dist.startsWith(`${importedModule}_`) || importedModule.startsWith(`${stripped}_`);
1562
+ }
1563
+ var CREDENTIAL_NAME = /(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|CREDENTIALS|AUTH|API)/;
1564
+ function isCredentialName(name) {
1565
+ return CREDENTIAL_NAME.test(name);
1566
+ }
1567
+ function envNamesReadByCode(blocks) {
1568
+ const names = /* @__PURE__ */ new Set();
1569
+ const readers = [
1570
+ /process\.env\.([A-Z][A-Z0-9_]{1,80})/g,
1571
+ /process\.env\[\s*['"]([A-Z][A-Z0-9_]{1,80})['"]\s*\]/g,
1572
+ /import\.meta\.env\.([A-Z][A-Z0-9_]{1,80})/g,
1573
+ /os\.environ\[\s*['"]([A-Z][A-Z0-9_]{1,80})['"]\s*\]/g,
1574
+ /os\.environ\.get\(\s*['"]([A-Z][A-Z0-9_]{1,80})['"]/g,
1575
+ /os\.getenv\(\s*['"]([A-Z][A-Z0-9_]{1,80})['"]/g,
1576
+ /Deno\.env\.get\(\s*['"]([A-Z][A-Z0-9_]{1,80})['"]/g,
1577
+ /\bENV\[\s*['"]([A-Z][A-Z0-9_]{1,80})['"]\s*\]/g,
1578
+ /os\.Getenv\(\s*"([A-Z][A-Z0-9_]{1,80})"/g,
1579
+ /System\.getenv\(\s*"([A-Z][A-Z0-9_]{1,80})"/g,
1580
+ /Environment\.GetEnvironmentVariable\(\s*"([A-Z][A-Z0-9_]{1,80})"/g
1581
+ ];
1582
+ for (const block of blocks) {
1583
+ for (const reader of readers) {
1584
+ for (const match of block.code.matchAll(reader)) if (match[1]) names.add(match[1]);
1585
+ }
1586
+ if (isShellBlock(block)) {
1587
+ for (const line of block.code.split("\n")) {
1588
+ const trimmed = stripPrompt(line).trim().replace(/^export\s+/, "");
1589
+ if (/^[A-Z][A-Z0-9_]*=/.test(trimmed)) continue;
1590
+ for (const match of line.matchAll(/\$\{?([A-Z][A-Z0-9]*_[A-Z0-9_]{1,80})\}?/g)) {
1591
+ if (match[1]) names.add(match[1]);
1592
+ }
1593
+ }
1594
+ }
1595
+ }
1596
+ return [...names].filter(isCredentialName).slice(0, 20);
1597
+ }
1598
+ function envNamesInSetup(doc) {
1599
+ const names = /* @__PURE__ */ new Set();
1600
+ for (const block of doc.blocks) {
1601
+ const setupBlock = isShellBlock(block) || block.lang === "env" || block.lang === null || block.lang === "text";
1602
+ if (!setupBlock) continue;
1603
+ for (const line of block.code.split("\n")) {
1604
+ const cleaned = stripPrompt(line).trim().replace(/^(?:export\s+|set\s+|\$env:)/, "");
1605
+ const assignment = /^([A-Z][A-Z0-9]*_[A-Z0-9_]{1,80})\s*=/.exec(cleaned);
1606
+ if (assignment?.[1]) names.add(assignment[1]);
1607
+ }
1608
+ }
1609
+ for (const match of doc.prose.matchAll(/\b([A-Z][A-Z0-9]*_[A-Z0-9_]{1,80})\b/g)) {
1610
+ if (match[1]) names.add(match[1]);
1611
+ }
1612
+ return [...names].filter(isCredentialName).slice(0, 20);
1613
+ }
1614
+ var CREDENTIAL_SOURCE = [
1615
+ /\b(?:api[ -]?keys?|tokens?|secrets?|credentials?|access keys?)\b[^.\n]{0,100}\b(?:dashboard|settings|console|portal|account|create|generate|get|obtain|sign up|copy|issued|from)\b/i,
1616
+ /\b(?:dashboard|settings|console|portal|create|generate|get|obtain|copy|sign up)\b[^.\n]{0,100}\b(?:api[ -]?keys?|tokens?|secrets?|credentials?|access keys?)\b/i
1617
+ ];
1618
+ function credentialSourceSentence(prose) {
1619
+ for (const line of prose.split("\n")) {
1620
+ for (const pattern of CREDENTIAL_SOURCE) {
1621
+ if (pattern.exec(line)) return line.length > 240 ? `${line.slice(0, 237)}\u2026` : line;
1622
+ }
1623
+ }
1624
+ return null;
1625
+ }
1626
+ function examplesNeedCredential(blocks, placeholders) {
1627
+ const envName = envNamesReadByCode(blocks)[0];
1628
+ if (envName !== void 0) return envName;
1629
+ const keyPlaceholder = placeholders.find(
1630
+ (use) => /key|token|secret|password|credential/i.test(use.token)
1631
+ );
1632
+ if (keyPlaceholder !== void 0) return keyPlaceholder.token;
1633
+ for (const block of blocks) {
1634
+ const auth = /\b(?:Authorization|X-Api-Key|api[_-]?key|apiKey)\b/i.exec(block.code);
1635
+ if (auth) return auth[0];
1636
+ }
1637
+ return null;
1638
+ }
1639
+ function runnableExample(blocks) {
1640
+ for (const block of blocks) {
1641
+ if (elisionLines(block).length > 0) continue;
1642
+ if (isProgramBlock(block)) {
1643
+ const lines = block.code.split("\n").filter((line) => line.trim() !== "");
1644
+ if (lines.length >= 3 || /\b(?:import|require|from|package|using|use)\b/.test(block.code)) {
1645
+ return block;
1646
+ }
1647
+ }
1648
+ if (isShellBlock(block) && /\bcurl\b[^\n]*https?:\/\//.test(block.code)) return block;
1649
+ }
1650
+ return null;
1651
+ }
1652
+ var VERIFY_TEXT = /\b(?:you should see|expected output|should (?:print|return|output|log|see|respond)|prints?|outputs?|returns?|responds? with|verify|confirm|check that|to test|succeeded|success(?:fully)?|if (?:it|everything) (?:works|worked))\b/i;
1653
+ function verificationSignal(doc, example) {
1654
+ for (const block of doc.blocks) {
1655
+ if (block.lang === "output" || block.lang === "console" || /^(?:output|response|result)\b/i.test(block.section ?? "")) {
1656
+ return `An output block${block.section ? ` under \u201C${block.section}\u201D` : ""}`;
1657
+ }
1658
+ const comment = /(?:\/\/|#)\s*(?:=>|→|output:|prints?:?|returns?:?|expected:?)[^\n]{0,120}/i.exec(block.code);
1659
+ if (comment) return comment[0].trim();
1660
+ }
1661
+ const lines = example === null ? doc.prose.split("\n") : `${example.after}
1662
+ ${doc.prose}`.split("\n");
1663
+ for (const line of lines) {
1664
+ if (VERIFY_TEXT.test(line)) return line.length > 240 ? `${line.slice(0, 237)}\u2026` : line;
1665
+ }
1666
+ return null;
1667
+ }
1668
+ var DATE_TEXT = /\b(?:last (?:updated|modified|edited|reviewed)|updated(?: on)?|modified)\s*:?\s*((?:[A-Z][a-z]{2,8}\.? \d{1,2},? \d{4})|(?:\d{1,2} [A-Z][a-z]{2,8}\.? \d{4})|(?:\d{4}-\d{2}-\d{2})|(?:\d{1,2}\/\d{1,2}\/\d{4}))/i;
1669
+ function statedUpdatedDate(html, markdown) {
1670
+ if (html !== null) {
1671
+ const meta = /<meta\b[^>]*(?:property|name|itemprop)\s*=\s*["'](?:article:modified_time|og:updated_time|last-modified|dateModified|revised)["'][^>]*>/i.exec(
1672
+ html
1673
+ );
1674
+ if (meta) {
1675
+ const content = /\scontent\s*=\s*["']([^"']{4,40})["']/i.exec(meta[0]);
1676
+ if (content?.[1]) return { date: content[1], where: "page metadata" };
1677
+ }
1678
+ const jsonLd = /"dateModified"\s*:\s*"([^"]{4,40})"/.exec(html);
1679
+ if (jsonLd?.[1]) return { date: jsonLd[1], where: "structured data (dateModified)" };
1680
+ }
1681
+ if (markdown !== null && markdown.startsWith("---")) {
1682
+ const front = /^(?:last_?updated|lastUpdated|updated|last_modified|date_modified|modified)\s*:\s*["']?([^"'\n]{4,40})/im.exec(
1683
+ markdown.slice(0, 2e3)
1684
+ );
1685
+ if (front?.[1]) return { date: front[1].trim(), where: "front matter" };
1686
+ }
1687
+ const visible = [
1688
+ html === null ? "" : htmlProse(stripInvisible(html)).join("\n"),
1689
+ markdown ?? ""
1690
+ ].join("\n");
1691
+ const prose = DATE_TEXT.exec(visible);
1692
+ if (prose?.[1]) return { date: prose[1], where: "page text" };
1693
+ if (html !== null) {
1694
+ const time = /<time\b[^>]*\sdatetime\s*=\s*["']([^"']{4,40})["']/i.exec(html);
1695
+ if (time?.[1]) return { date: time[1], where: "a <time> element" };
1696
+ }
1697
+ return null;
1698
+ }
1699
+ function excerpt(text2, maxLines = 4, maxChars = 280) {
1700
+ const lines = text2.split("\n").filter((line) => line.trim() !== "").slice(0, maxLines);
1701
+ const joined = lines.join("\n");
1702
+ return joined.length > maxChars ? `${joined.slice(0, maxChars - 1)}\u2026` : joined;
1703
+ }
1704
+ function comparablePath(href) {
1705
+ try {
1706
+ const url = new URL(href);
1707
+ return `${url.host}${url.pathname.replace(/\/index(?:\.html|\.htm|\.md)?$/, "").replace(/\.(?:md|html?)$/, "").replace(/\/$/, "")}`;
1708
+ } catch {
1709
+ return null;
1710
+ }
1711
+ }
1712
+ function llmsTxtCoverage(body, pageUrl) {
1713
+ const page = comparablePath(pageUrl);
1714
+ if (page === null) return "no-link";
1715
+ const parent = page.includes("/") ? page.slice(0, page.lastIndexOf("/")) : page;
1716
+ let section = false;
1717
+ for (const match of body.matchAll(
1718
+ /\]\(\s*([^)\s]{1,2048})\s*\)|(https?:\/\/[^\s)>\]]{1,2048})/g
1719
+ )) {
1720
+ const raw = match[1] ?? match[2] ?? "";
1721
+ let href;
1722
+ try {
1723
+ href = new URL(raw, pageUrl).href;
1724
+ } catch {
1725
+ continue;
1726
+ }
1727
+ const linked = comparablePath(href);
1728
+ if (linked === null) continue;
1729
+ if (linked === page) return "links-page";
1730
+ if (parent.includes("/") && (linked === parent || linked.startsWith(`${parent}/`))) {
1731
+ section = true;
1732
+ }
1733
+ }
1734
+ return section ? "links-section" : "no-link";
1735
+ }
1736
+ function codeInline(text2) {
1737
+ return `\`${text2.replace(/`/g, "")}\``;
1738
+ }
1739
+ function listWords(items) {
1740
+ if (items.length <= 1) return items.join("");
1741
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
1742
+ }
1743
+ function namedInProse(name, prose) {
1744
+ const hay = prose.toLowerCase();
1745
+ const needle = name.toLowerCase();
1746
+ if (needle === "") return false;
1747
+ const plainWord = /^[a-z]+$/.test(needle);
1748
+ const outside = (ch) => ch === void 0 || !/[\w@/-]/.test(ch);
1749
+ for (let at = hay.indexOf(needle); at !== -1; at = hay.indexOf(needle, at + 1)) {
1750
+ if (!outside(hay[at - 1])) continue;
1751
+ const end = at + needle.length;
1752
+ if (hay.startsWith(".js", end) && outside(hay[end + 3])) return true;
1753
+ if (!outside(hay[end])) continue;
1754
+ if (!plainWord) return true;
1755
+ if (/^\s+(?:v?\d|apps?\b|projects?\b|applications?\b)/.test(hay.slice(end, end + 16))) {
1756
+ return true;
1757
+ }
1758
+ }
1759
+ return false;
1760
+ }
1761
+ function fetchFindings(facts, html, content) {
1762
+ const out = [];
1763
+ const agentType = mediaTypeOf(facts.agent?.contentType ?? null);
1764
+ if (facts.markdown?.source === "negotiated") {
1765
+ out.push({
1766
+ id: "markdown-negotiated",
1767
+ check: "fetch",
1768
+ severity: "passed",
1769
+ title: "Serves Markdown to agents that ask for it",
1770
+ detail: `A request with \`Accept: text/markdown\` received \`${agentType ?? "text/markdown"}\`.`,
1771
+ evidence: [excerpt(facts.markdown.body.replace(/^---\n[\s\S]*?\n---\n/, ""), 3)],
1772
+ fix: null
1773
+ });
1774
+ } else if (facts.markdown?.source === "alternate") {
1775
+ out.push({
1776
+ id: "markdown-alternate",
1777
+ check: "fetch",
1778
+ severity: "passed",
1779
+ title: "Links a Markdown copy of the page",
1780
+ detail: `The page declares a Markdown alternate at ${facts.markdown.url}, and it returned Markdown.`,
1781
+ evidence: [facts.markdown.url],
1782
+ fix: null
1783
+ });
1784
+ } else {
1785
+ out.push({
1786
+ id: "markdown-missing",
1787
+ check: "fetch",
1788
+ severity: "should-fix",
1789
+ title: "No Markdown version of the page",
1790
+ detail: `A request with \`Accept: text/markdown\` received ${agentType === null ? "no content type" : `\`${agentType}\``}, and the page declares no Markdown alternate. Coding agents then read the HTML, navigation and all.`,
1791
+ evidence: [`Content-Type: ${facts.agent?.contentType ?? "not sent"}`],
1792
+ fix: 'Serve `text/markdown` when the Accept header prefers it, or link a copy with `<link rel="alternate" type="text/markdown" href="\u2026">`.'
1793
+ });
1794
+ }
1795
+ const htmlBlocks = html?.blocks.length ?? 0;
1796
+ const contentBlocks = content?.blocks.length ?? 0;
1797
+ if (html !== null && htmlBlocks > 0) {
1798
+ out.push({
1799
+ id: "server-html-has-code",
1800
+ check: "fetch",
1801
+ severity: "passed",
1802
+ title: "Instructions are in the server HTML",
1803
+ detail: `The HTML response contains ${htmlBlocks} code ${htmlBlocks === 1 ? "block" : "blocks"} before any JavaScript runs.`,
1804
+ evidence: [excerpt(html.blocks[0]?.code ?? "", 2)],
1805
+ fix: null
1806
+ });
1807
+ } else if (html !== null && facts.markdown !== null && contentBlocks > 0) {
1808
+ out.push({
1809
+ id: "code-needs-javascript",
1810
+ check: "fetch",
1811
+ severity: "should-fix",
1812
+ title: "Code examples appear only after JavaScript runs",
1813
+ detail: `The Markdown copy has ${contentBlocks} code ${contentBlocks === 1 ? "block" : "blocks"}, but the HTML response has none. Agents that fetch the HTML without running JavaScript see no commands.`,
1814
+ evidence: [`${html.prose.length} characters of text and 0 code blocks in the HTML response`],
1815
+ fix: "Render code examples on the server, or prerender the docs pages."
1816
+ });
1817
+ } else if (html !== null && contentBlocks === 0 && html.prose.length < 400) {
1818
+ out.push({
1819
+ id: "content-needs-javascript",
1820
+ check: "fetch",
1821
+ severity: "blocking",
1822
+ title: "The page content needs JavaScript to appear",
1823
+ detail: `The HTML response holds only ${html.prose.length} characters of text and no code blocks, so an agent that reads the response sees no instructions.`,
1824
+ evidence: [excerpt(html.prose, 3) || "(no visible text)"],
1825
+ fix: "Render the docs on the server or prerender them, and serve a Markdown copy to agents."
1826
+ });
1827
+ }
1828
+ if (facts.llmsTxt.state === "missing") {
1829
+ out.push({
1830
+ id: "llms-txt-missing",
1831
+ check: "fetch",
1832
+ severity: "should-fix",
1833
+ title: "No /llms.txt on this site",
1834
+ detail: `${facts.llmsTxt.url} did not return a file. An llms.txt gives agents a map of the docs, with links to the pages that matter.`,
1835
+ evidence: [facts.llmsTxt.url],
1836
+ fix: "Publish /llms.txt with a link to this page under its section."
1837
+ });
1838
+ } else if (facts.llmsTxt.state === "found" && facts.llmsTxt.body !== null) {
1839
+ const coverage = llmsTxtCoverage(facts.llmsTxt.body, facts.url);
1840
+ if (coverage === "no-link") {
1841
+ out.push({
1842
+ id: "llms-txt-no-link",
1843
+ check: "fetch",
1844
+ severity: "should-fix",
1845
+ title: "/llms.txt does not link this page",
1846
+ detail: "The site has an llms.txt, but no link in it points at this page or its section.",
1847
+ evidence: [facts.llmsTxt.url],
1848
+ fix: `Add a link to ${facts.url} under the matching section of /llms.txt.`
1849
+ });
1850
+ } else {
1851
+ out.push({
1852
+ id: coverage === "links-page" ? "llms-txt-links-page" : "llms-txt-links-section",
1853
+ check: "fetch",
1854
+ severity: "passed",
1855
+ title: coverage === "links-page" ? "/llms.txt links this page" : "/llms.txt links this section",
1856
+ detail: coverage === "links-page" ? "An agent starting from /llms.txt can find this page." : "An agent starting from /llms.txt can find pages next to this one.",
1857
+ evidence: [facts.llmsTxt.url],
1858
+ fix: null
1859
+ });
1860
+ }
1861
+ }
1862
+ return out;
1863
+ }
1864
+ function codeFindings(doc) {
1865
+ const out = [];
1866
+ const blocks = doc.blocks;
1867
+ if (blocks.length === 0) {
1868
+ out.push({
1869
+ id: "no-code",
1870
+ check: "code",
1871
+ severity: "blocking",
1872
+ title: "No code examples on this page",
1873
+ detail: "The page has no code blocks, so an agent has no command or snippet to copy.",
1874
+ evidence: [excerpt(doc.prose, 2) || "(no visible text)"],
1875
+ fix: "Show the install command and a minimal example as code blocks."
1876
+ });
1877
+ return out;
1878
+ }
1879
+ const unlabeled = blocks.filter((block) => block.lang === null);
1880
+ if (unlabeled.length > 0) {
1881
+ out.push({
1882
+ id: "code-unlabeled",
1883
+ check: "code",
1884
+ severity: "should-fix",
1885
+ title: `${unlabeled.length} of ${blocks.length} code ${blocks.length === 1 ? "block" : "blocks"} ${unlabeled.length === 1 ? "has" : "have"} no language label`,
1886
+ detail: "Without a label an agent has to guess which blocks are terminal commands and which are source files.",
1887
+ evidence: unlabeled.slice(0, 3).map((block) => excerpt(block.code, 2)),
1888
+ fix: "Label every block (```bash, ```ts, ```python) and use `text` for output."
1889
+ });
1890
+ } else {
1891
+ out.push({
1892
+ id: "code-labeled",
1893
+ check: "code",
1894
+ severity: "passed",
1895
+ title: "Every code block has a language label",
1896
+ detail: `${blocks.length} code ${blocks.length === 1 ? "block" : "blocks"}, all labeled.`,
1897
+ evidence: [],
1898
+ fix: null
1899
+ });
1900
+ }
1901
+ const prompted = [];
1902
+ for (const block of blocks) {
1903
+ if (!isShellBlock(block)) continue;
1904
+ const use = promptUse(block);
1905
+ if (use.promptLines.length > 0) {
1906
+ prompted.push({ block, prompts: use.promptLines, output: use.outputLines });
1907
+ }
1908
+ }
1909
+ const mixed = prompted.filter((entry) => entry.output.length > 0);
1910
+ if (mixed.length > 0) {
1911
+ out.push({
1912
+ id: "shell-mixes-output",
1913
+ check: "code",
1914
+ severity: "should-fix",
1915
+ title: "Shell examples mix commands with their output",
1916
+ detail: `${mixed.length} terminal ${mixed.length === 1 ? "block puts" : "blocks put"} \`$\`-prompted commands and output lines together. Copied whole, the output lines run as commands.`,
1917
+ evidence: mixed.slice(0, 3).map((entry) => excerpt(entry.block.code, 4)),
1918
+ fix: "Put commands in their own block with no prompt, and show expected output in a separate `text` block."
1919
+ });
1920
+ } else if (prompted.length > 0) {
1921
+ out.push({
1922
+ id: "shell-prompts",
1923
+ check: "code",
1924
+ severity: "should-fix",
1925
+ title: "Shell commands start with a prompt",
1926
+ detail: "Copied as written, `$ npm install` fails with \u201Ccommand not found: $\u201D.",
1927
+ evidence: prompted.slice(0, 3).map((entry) => entry.prompts[0]?.trim() ?? ""),
1928
+ fix: "Remove the `$` prompts from command blocks."
1929
+ });
1930
+ }
1931
+ const placeholders = findPlaceholders(blocks);
1932
+ const unexplained = placeholders.filter((use) => !use.explained);
1933
+ for (const use of unexplained.slice(0, 3)) {
1934
+ out.push({
1935
+ id: "placeholder-unexplained",
1936
+ check: "code",
1937
+ severity: "blocking",
1938
+ title: `Placeholder ${codeInline(use.token)} has no explanation`,
1939
+ detail: `The text around this block does not say what to put in ${codeInline(use.token)} or where that value comes from, so an agent cannot fill it in.`,
1940
+ evidence: [use.line],
1941
+ fix: `Say where ${codeInline(use.token)} comes from next to the block (for example, \u201CCreate a key under Settings \u2192 API keys\u201D), or read it from an environment variable the setup step names.`
1942
+ });
1943
+ }
1944
+ if (placeholders.length > 0 && unexplained.length === 0) {
1945
+ out.push({
1946
+ id: "placeholders-explained",
1947
+ check: "code",
1948
+ severity: "passed",
1949
+ title: "Placeholders are explained",
1950
+ detail: `${listWords(placeholders.slice(0, 4).map((use) => codeInline(use.token)))} ${placeholders.length === 1 ? "is" : "are"} explained next to the code.`,
1951
+ evidence: [],
1952
+ fix: null
1953
+ });
1954
+ }
1955
+ const elided = blocks.map((block) => ({ block, lines: elisionLines(block) })).filter((entry) => entry.lines.length > 0);
1956
+ if (elided.length > 0) {
1957
+ out.push({
1958
+ id: "code-elisions",
1959
+ check: "code",
1960
+ severity: "should-fix",
1961
+ title: "Code meant to be run has \u201C...\u201D gaps",
1962
+ detail: `${elided.length} code ${elided.length === 1 ? "block leaves" : "blocks leave"} out part of the code with \`...\`. An agent copying the block gets code that does not parse or run.`,
1963
+ evidence: elided.slice(0, 3).map((entry) => entry.lines[0]?.trim() ?? ""),
1964
+ fix: "Show the complete snippet, or mark the block as a fragment and link the full example."
1965
+ });
1966
+ }
1967
+ const installHeading = /\b(?:install|installation|set ?up|getting started|quick ?start|configure|configuration|prerequisites?|step \d+)\b/i;
1968
+ let section = null;
1969
+ let sectionHasCode = false;
1970
+ let sectionImages = [];
1971
+ const imageOnly = [];
1972
+ const flush = () => {
1973
+ if (section !== null && installHeading.test(section) && !sectionHasCode && sectionImages.length > 0) {
1974
+ const image = sectionImages[0];
1975
+ imageOnly.push(
1976
+ `\u201C${section}\u201D: ${image?.alt ? `image \u201C${image.alt}\u201D` : `image ${image?.src ?? ""}`}`
1977
+ );
1978
+ }
1979
+ };
1980
+ for (const node of doc.nodes) {
1981
+ if (node.kind === "heading") {
1982
+ flush();
1983
+ section = node.text;
1984
+ sectionHasCode = false;
1985
+ sectionImages = [];
1986
+ } else if (node.kind === "code") sectionHasCode = true;
1987
+ else if (node.kind === "image") sectionImages.push(node);
1988
+ }
1989
+ flush();
1990
+ if (imageOnly.length > 0) {
1991
+ out.push({
1992
+ id: "screenshot-only-step",
1993
+ check: "code",
1994
+ severity: "should-fix",
1995
+ title: "A setup step is shown only as an image",
1996
+ detail: "These setup sections have a screenshot and no command or code. An agent cannot read the step from the image.",
1997
+ evidence: imageOnly.slice(0, 3),
1998
+ fix: "Write the step as text, with the exact command, setting name or value, and keep the screenshot as a supplement."
1999
+ });
2000
+ }
2001
+ return out;
2002
+ }
2003
+ function installFindings(commands, imports, prose) {
2004
+ const out = [];
2005
+ if (commands.length === 0) {
2006
+ const first = imports[0];
2007
+ out.push(
2008
+ first !== void 0 ? {
2009
+ id: "install-missing",
2010
+ check: "install",
2011
+ severity: "blocking",
2012
+ title: `The examples import ${codeInline(first.name)}, but the page never installs it`,
2013
+ detail: "There is no install command on the page, so an agent has to guess the package name and manager.",
2014
+ evidence: [first.line],
2015
+ fix: `Add the install command for each package manager you support, for example ${codeInline(first.ecosystem === "npm" ? `npm install ${first.name}` : `pip install ${first.name}`)}.`
2016
+ } : {
2017
+ id: "install-none",
2018
+ check: "install",
2019
+ severity: "should-fix",
2020
+ title: "No install command on this page",
2021
+ detail: "If this page is where a developer starts, an agent needs the exact install command here.",
2022
+ evidence: [],
2023
+ fix: "Add the install command near the top, in a labeled terminal block."
2024
+ }
2025
+ );
2026
+ return out;
2027
+ }
2028
+ const managers = [...new Set(commands.map((command) => command.manager))];
2029
+ out.push({
2030
+ id: "install-found",
2031
+ check: "install",
2032
+ severity: "passed",
2033
+ title: `Install command for ${listWords(managers)}`,
2034
+ detail: `The page shows ${commands.length === 1 ? "an install command" : `${commands.length} install commands`}.`,
2035
+ evidence: commands.slice(0, 3).map((command) => command.line),
2036
+ fix: null
2037
+ });
2038
+ for (const ecosystem of ["npm", "pypi"]) {
2039
+ const installed = commands.flatMap((command) => command.packages).filter((ref) => ref.ecosystem === ecosystem);
2040
+ const imported = imports.filter((ref) => ref.ecosystem === ecosystem);
2041
+ if (installed.length === 0 || imported.length === 0) continue;
2042
+ const provided = imported.filter((ref) => installed.some((pkg) => installProvides(pkg, ref)));
2043
+ if (provided.length === 0) {
2044
+ const importedRef = imported[0];
2045
+ out.push({
2046
+ id: "install-import-mismatch",
2047
+ check: "install",
2048
+ severity: "blocking",
2049
+ title: "The install command and the import name different packages",
2050
+ detail: `The page installs ${listWords(installed.slice(0, 3).map((ref) => codeInline(ref.name)))} but the example imports ${codeInline(importedRef?.name ?? "")}. An agent following both gets a \u201Cmodule not found\u201D error.`,
2051
+ evidence: [installed[0]?.evidence ?? "", importedRef?.line ?? ""],
2052
+ fix: "Make the install command and the import use the same package name."
2053
+ });
2054
+ continue;
2055
+ }
2056
+ const missing = imported.filter(
2057
+ (ref) => !installed.some((pkg) => installProvides(pkg, ref)) && !namedInProse(ref.name, prose)
2058
+ );
2059
+ if (missing.length > 0) {
2060
+ out.push({
2061
+ id: "import-not-installed",
2062
+ check: "install",
2063
+ severity: "should-fix",
2064
+ title: `The examples import ${listWords(missing.slice(0, 3).map((ref) => codeInline(ref.name)))}, which the install step does not install`,
2065
+ detail: "If the example needs these packages, an agent has to discover that from an error.",
2066
+ evidence: missing.slice(0, 3).map((ref) => ref.line),
2067
+ fix: "Add the packages to the install command, or say that they are already expected in the project."
2068
+ });
2069
+ } else {
2070
+ out.push({
2071
+ id: "install-import-match",
2072
+ check: "install",
2073
+ severity: "passed",
2074
+ title: "Install and import names match",
2075
+ detail: `${listWords(provided.slice(0, 3).map((ref) => codeInline(ref.name)))} ${provided.length === 1 ? "is" : "are"} installed and imported under the same name.`,
2076
+ evidence: [],
2077
+ fix: null
2078
+ });
2079
+ }
2080
+ }
2081
+ return out;
2082
+ }
2083
+ function authFindings(doc) {
2084
+ const out = [];
2085
+ const placeholders = findPlaceholders(doc.blocks);
2086
+ const needs = examplesNeedCredential(doc.blocks, placeholders);
2087
+ if (needs !== null) {
2088
+ const source = credentialSourceSentence(doc.prose);
2089
+ out.push(
2090
+ source === null ? {
2091
+ id: "credential-source-missing",
2092
+ check: "auth",
2093
+ severity: "blocking",
2094
+ title: "The page does not say where the credential comes from",
2095
+ detail: `The examples use ${codeInline(needs)}, but no step says where to create or copy it.`,
2096
+ evidence: [needs],
2097
+ fix: "Add a step before the example: where to create the key (the exact page or command) and which environment variable to put it in."
2098
+ } : {
2099
+ id: "credential-source",
2100
+ check: "auth",
2101
+ severity: "passed",
2102
+ title: "Says where the credential comes from",
2103
+ detail: "The setup text names where to get the credential the examples use.",
2104
+ evidence: [source],
2105
+ fix: null
2106
+ }
2107
+ );
2108
+ }
2109
+ const readByCode = envNamesReadByCode(doc.blocks);
2110
+ const inSetup = envNamesInSetup(doc);
2111
+ if (readByCode.length > 0) {
2112
+ const unset = readByCode.filter((name) => !inSetup.includes(name));
2113
+ const unused = inSetup.filter((name) => !readByCode.includes(name));
2114
+ if (unset.length > 0 && unused.length > 0) {
2115
+ out.push({
2116
+ id: "env-name-mismatch",
2117
+ check: "auth",
2118
+ severity: "blocking",
2119
+ title: `The setup sets ${codeInline(unused[0] ?? "")} but the code reads ${codeInline(unset[0] ?? "")}`,
2120
+ detail: "An agent that follows the setup step exactly ends up with an empty credential in the example.",
2121
+ evidence: [...unused.slice(0, 2), ...unset.slice(0, 2)],
2122
+ fix: "Use one environment variable name in the setup text and in every example."
2123
+ });
2124
+ } else if (unset.length > 0) {
2125
+ out.push({
2126
+ id: "env-name-unexplained",
2127
+ check: "auth",
2128
+ severity: "should-fix",
2129
+ title: `The code reads ${listWords(unset.slice(0, 3).map(codeInline))}, which the setup never mentions`,
2130
+ detail: "Name the variable in the setup step so an agent sets it before running the example.",
2131
+ evidence: unset.slice(0, 3),
2132
+ fix: `Add a setup step such as ${codeInline(`export ${unset[0] ?? "API_KEY"}=\u2026`)} with where the value comes from.`
2133
+ });
2134
+ } else {
2135
+ out.push({
2136
+ id: "env-names-match",
2137
+ check: "auth",
2138
+ severity: "passed",
2139
+ title: "Environment variable names match",
2140
+ detail: `${listWords(readByCode.slice(0, 3).map(codeInline))} ${readByCode.length === 1 ? "is" : "are"} named in the setup and read by the code.`,
2141
+ evidence: [],
2142
+ fix: null
2143
+ });
2144
+ }
2145
+ }
2146
+ const example = runnableExample(doc.blocks);
2147
+ if (example === null) {
2148
+ out.push({
2149
+ id: "runnable-example-missing",
2150
+ check: "auth",
2151
+ severity: "should-fix",
2152
+ title: "No complete example to run",
2153
+ detail: "No code block is a complete program or request: each is either a fragment, has `...` gaps, or is only an install command.",
2154
+ evidence: [],
2155
+ fix: "Add one minimal, complete example that runs as written after the install and setup steps."
2156
+ });
2157
+ } else {
2158
+ out.push({
2159
+ id: "runnable-example",
2160
+ check: "auth",
2161
+ severity: "passed",
2162
+ title: "Has a minimal example to run",
2163
+ detail: `${example.section ? `Under \u201C${example.section}\u201D, a` : "A"} ${example.lang ?? "terminal"} block reads as a complete example.`,
2164
+ evidence: [excerpt(example.code, 3)],
2165
+ fix: null
2166
+ });
2167
+ }
2168
+ const verification = verificationSignal(doc, example);
2169
+ out.push(
2170
+ verification === null ? {
2171
+ id: "verification-missing",
2172
+ check: "auth",
2173
+ severity: "should-fix",
2174
+ title: "No way to confirm the example worked",
2175
+ detail: "The page shows no expected output and no check command, so an agent cannot tell success from a silent failure.",
2176
+ evidence: [],
2177
+ fix: "Show the expected output after the example, or a command that confirms the setup (for example, one that prints the SDK version or a test response)."
2178
+ } : {
2179
+ id: "verification",
2180
+ check: "auth",
2181
+ severity: "passed",
2182
+ title: "States how to confirm it worked",
2183
+ detail: "The page shows expected output or a check.",
2184
+ evidence: [verification],
2185
+ fix: null
2186
+ }
2187
+ );
2188
+ return out;
2189
+ }
2190
+ function freshnessFindings(facts) {
2191
+ const html = facts.browser !== null && facts.browser.body !== null && !isMarkdownResponse(facts.browser.contentType, facts.browser.body) ? facts.browser.body : null;
2192
+ const stated = statedUpdatedDate(html, facts.markdown?.body ?? null);
2193
+ return [
2194
+ stated === null ? {
2195
+ id: "updated-date-missing",
2196
+ check: "freshness",
2197
+ severity: "should-fix",
2198
+ title: "No last-updated date on the page",
2199
+ detail: "A stated date tells an agent, and the developer reviewing its work, how current the instructions are.",
2200
+ evidence: [],
2201
+ fix: "Show a \u201CLast updated\u201D date, and include `dateModified` in the page\u2019s structured data."
2202
+ } : {
2203
+ id: "updated-date",
2204
+ check: "freshness",
2205
+ severity: "passed",
2206
+ title: `States a last-updated date: ${stated.date}`,
2207
+ detail: `Found in ${stated.where}.`,
2208
+ evidence: [stated.date],
2209
+ fix: null
2210
+ }
2211
+ ];
2212
+ }
2213
+ var STEP_ORDER = {
2214
+ fetch: 0,
2215
+ install: 1,
2216
+ code: 2,
2217
+ auth: 3,
2218
+ freshness: 4
2219
+ };
2220
+ var SEVERITY_ORDER = {
2221
+ blocking: 0,
2222
+ "should-fix": 1,
2223
+ passed: 2
2224
+ };
2225
+ function analyzeDocsFacts(facts, checkedAt) {
2226
+ const htmlBody = is2xx(facts.browser) && !isMarkdownResponse(facts.browser.contentType, facts.browser.body) ? facts.browser.body : null;
2227
+ const html = htmlBody === null ? null : parseHtmlDocument(htmlBody);
2228
+ const markdown = facts.markdown === null ? null : parseMarkdownDocument(facts.markdown.body);
2229
+ const content = markdown ?? html;
2230
+ const findings = [];
2231
+ const finalUrl = facts.browser?.finalUrl ?? facts.agent?.finalUrl ?? facts.url;
2232
+ const browserStatus = facts.browser?.status ?? null;
2233
+ if (content === null) {
2234
+ findings.push({
2235
+ id: "page-unreadable",
2236
+ check: "fetch",
2237
+ severity: "blocking",
2238
+ title: browserStatus === null ? "The page could not be fetched" : `The page returned HTTP ${browserStatus}`,
2239
+ detail: browserStatus === null ? "Neither request reached the page, so an agent cannot read it either." : "An agent requesting this address gets an error instead of the instructions.",
2240
+ evidence: [finalUrl],
2241
+ fix: "Make the page publicly reachable at this address with a 200 response."
2242
+ });
2243
+ } else {
2244
+ findings.push(...fetchFindings(facts, html, content));
2245
+ findings.push(...codeFindings(content));
2246
+ const commands = findInstallCommands(content);
2247
+ findings.push(...installFindings(commands, findImports(content), content.prose));
2248
+ findings.push(...authFindings(content));
2249
+ findings.push(...freshnessFindings(facts));
2250
+ }
2251
+ const ordered = findings.map((finding, position) => ({ finding, position })).sort(
2252
+ (a, b) => SEVERITY_ORDER[a.finding.severity] - SEVERITY_ORDER[b.finding.severity] || STEP_ORDER[a.finding.check] - STEP_ORDER[b.finding.check] || a.position - b.position
2253
+ ).map((entry) => ({
2254
+ ...entry.finding,
2255
+ evidence: entry.finding.evidence.filter((item) => item !== "").slice(0, 3)
2256
+ }));
2257
+ const blocking = ordered.filter((finding) => finding.severity === "blocking");
2258
+ const shouldFix = ordered.filter((finding) => finding.severity === "should-fix");
2259
+ const passed = ordered.filter((finding) => finding.severity === "passed");
2260
+ return {
2261
+ url: facts.url,
2262
+ finalUrl,
2263
+ checkedAt: checkedAt.toISOString(),
2264
+ verdict: blocking.length === 0 ? "can-follow" : "likely-stuck",
2265
+ stuckAt: blocking.map((finding) => finding.title),
2266
+ analyzedSource: facts.markdown !== null ? "markdown" : "html",
2267
+ fetch: {
2268
+ browserStatus,
2269
+ agentStatus: facts.agent?.status ?? null,
2270
+ agentContentType: facts.agent?.contentType ?? null,
2271
+ markdown: facts.markdown?.source ?? "none",
2272
+ markdownUrl: facts.markdown?.url ?? null,
2273
+ serverHtmlCodeBlocks: html?.blocks.length ?? 0,
2274
+ llmsTxt: facts.llmsTxt.state === "found" && facts.llmsTxt.body !== null ? llmsTxtCoverage(facts.llmsTxt.body, facts.url) : facts.llmsTxt.state === "found" ? "no-link" : facts.llmsTxt.state
2275
+ },
2276
+ installManagers: content === null ? [] : [...new Set(findInstallCommands(content).map((command) => command.manager))],
2277
+ blocking,
2278
+ shouldFix,
2279
+ passed,
2280
+ findings: ordered,
2281
+ scope: DOCS_CHECK_SCOPE
2282
+ };
2283
+ }
2284
+ function analyzeDocsEvidence(evidence, checkedAt) {
2285
+ return analyzeDocsFacts(factsFromEvidence(evidence), checkedAt);
2286
+ }
2287
+ async function runDocsCheck(command, probe, now) {
2288
+ const outcome = await probe(command.url);
2289
+ if (!outcome.ok) {
2290
+ return {
2291
+ kind: "rejected",
2292
+ url: command.url,
2293
+ failOnBlocking: command.failOnBlocking,
2294
+ rejection: outcome.rejection,
2295
+ detail: outcome.detail
2296
+ };
2297
+ }
2298
+ const { status, detail } = classifyEvidenceStatus(outcome.evidence);
2299
+ const report = analyzeDocsEvidence(outcome.evidence, now);
2300
+ return {
2301
+ kind: "probed",
2302
+ url: command.url,
2303
+ failOnBlocking: command.failOnBlocking,
2304
+ probeStatus: status,
2305
+ probeDetail: detail,
2306
+ report
2307
+ };
2308
+ }
2309
+ function exitCodeForDocsCheck(payload) {
2310
+ if (payload.kind === "rejected") {
2311
+ return payload.rejection === "invalid-url" ? EXIT.USAGE : EXIT.POLICY;
2312
+ }
2313
+ if (payload.probeStatus === "policy") return EXIT.POLICY;
2314
+ if (payload.probeStatus === "unreachable") return EXIT.PROBE;
2315
+ if (payload.failOnBlocking && payload.report.blocking.length > 0) return EXIT.THRESHOLD;
2316
+ return EXIT.OK;
2317
+ }
2318
+
780
2319
  // src/disclosure.ts
781
2320
  var ARS_NOTICE_LINES = [
782
2321
  "ARS measures format and retrievability. It does not measure whether the",
@@ -886,6 +2425,34 @@ function jsonValue(payload, ctx) {
886
2425
  ...report.kind === "rejected" ? { rejection: report.rejection, detail: report.detail, result: null } : { rejection: null, detail: null, result: report.result }
887
2426
  }))
888
2427
  };
2428
+ case "docs-check": {
2429
+ const { docsCheck } = payload;
2430
+ const exitCode = exitCodeForDocsCheck(docsCheck);
2431
+ if (docsCheck.kind === "rejected") {
2432
+ return {
2433
+ ...envelope,
2434
+ command: "docs-check",
2435
+ url: docsCheck.url,
2436
+ failOnBlocking: docsCheck.failOnBlocking,
2437
+ status: "rejected",
2438
+ exitCode,
2439
+ rejection: docsCheck.rejection,
2440
+ detail: docsCheck.detail,
2441
+ report: null
2442
+ };
2443
+ }
2444
+ return {
2445
+ ...envelope,
2446
+ command: "docs-check",
2447
+ url: docsCheck.url,
2448
+ failOnBlocking: docsCheck.failOnBlocking,
2449
+ status: docsCheck.probeStatus,
2450
+ exitCode,
2451
+ rejection: null,
2452
+ detail: docsCheck.probeDetail,
2453
+ report: docsCheck.report
2454
+ };
2455
+ }
889
2456
  case "diff":
890
2457
  return {
891
2458
  ...envelope,
@@ -959,6 +2526,12 @@ function renderJunit(payload, ctx) {
959
2526
  failures += suite.failures;
960
2527
  errors += suite.errors;
961
2528
  }
2529
+ } else if (payload.command === "docs-check") {
2530
+ const suite = docsCheckSuite(payload.docsCheck, ctx);
2531
+ suites.push(suite.xml);
2532
+ tests += suite.tests;
2533
+ failures += suite.failures;
2534
+ errors += suite.errors;
962
2535
  } else if (payload.command === "diff") {
963
2536
  const suite = checkSuite(payload.diff.report, null, ctx);
964
2537
  suites.push(suite.xml);
@@ -978,6 +2551,72 @@ function renderJunit(payload, ctx) {
978
2551
  ""
979
2552
  ].join("\n");
980
2553
  }
2554
+ function docsCheckSuite(payload, ctx) {
2555
+ const cases = [];
2556
+ let tests = 0;
2557
+ let failures = 0;
2558
+ let errors = 0;
2559
+ const exitCode = exitCodeForDocsCheck(payload);
2560
+ const properties = [
2561
+ ` <property name="url" value="${escapeXml(payload.url)}"/>`,
2562
+ ` <property name="generatedAt" value="${escapeXml(ctx.generatedAt)}"/>`,
2563
+ ` <property name="tool" value="rebilder ${escapeXml(ctx.cliVersion)}"/>`,
2564
+ ` <property name="exitCode" value="${exitCode}"/>`
2565
+ ];
2566
+ if (payload.kind === "rejected" || payload.probeStatus !== "ok") {
2567
+ tests = 1;
2568
+ errors = 1;
2569
+ const type = payload.kind === "rejected" ? payload.rejection : payload.probeStatus;
2570
+ const message = payload.kind === "rejected" ? payload.detail : payload.probeDetail ?? "Page could not be probed";
2571
+ cases.push(
2572
+ [
2573
+ ` <testcase classname="${escapeXml(payload.url)}" name="probe">`,
2574
+ ` <error type="${escapeXml(type)}" message="${escapeXml(message)}"/>`,
2575
+ " </testcase>"
2576
+ ].join("\n")
2577
+ );
2578
+ } else {
2579
+ const { report } = payload;
2580
+ properties.push(
2581
+ ` <property name="verdict" value="${escapeXml(report.verdict)}"/>`,
2582
+ ` <property name="analyzedSource" value="${escapeXml(report.analyzedSource)}"/>`
2583
+ );
2584
+ for (const finding of report.findings) {
2585
+ tests += 1;
2586
+ const name = `${finding.check}.${finding.id}`;
2587
+ if (finding.severity === "blocking") {
2588
+ failures += 1;
2589
+ const body = [finding.detail, finding.fix ? `Fix: ${finding.fix}` : ""].filter((part) => part !== "").join("\n");
2590
+ cases.push(
2591
+ [
2592
+ ` <testcase classname="${escapeXml(payload.url)}" name="${escapeXml(name)}">`,
2593
+ ` <failure type="blocking" message="${escapeXml(finding.title)}">${escapeXml(body)}</failure>`,
2594
+ " </testcase>"
2595
+ ].join("\n")
2596
+ );
2597
+ } else if (finding.severity === "should-fix") {
2598
+ cases.push(
2599
+ [
2600
+ ` <testcase classname="${escapeXml(payload.url)}" name="${escapeXml(name)}">`,
2601
+ ` <skipped type="should-fix" message="${escapeXml(finding.title)}"/>`,
2602
+ " </testcase>"
2603
+ ].join("\n")
2604
+ );
2605
+ } else {
2606
+ cases.push(` <testcase classname="${escapeXml(payload.url)}" name="${escapeXml(name)}"/>`);
2607
+ }
2608
+ }
2609
+ }
2610
+ const xml = [
2611
+ ` <testsuite name="${escapeXml(payload.url)}" tests="${tests}" failures="${failures}" errors="${errors}">`,
2612
+ " <properties>",
2613
+ ...properties,
2614
+ " </properties>",
2615
+ ...cases,
2616
+ " </testsuite>"
2617
+ ].join("\n");
2618
+ return { xml, tests, failures, errors };
2619
+ }
981
2620
  function checkSuite(report, failOn, ctx) {
982
2621
  const cases = [];
983
2622
  let tests = 0;
@@ -1111,6 +2750,8 @@ function renderMarkdown(payload, ctx) {
1111
2750
  switch (payload.command) {
1112
2751
  case "check":
1113
2752
  return payload.reports.map((report) => checkSection(report)).join("\n---\n\n") + notice();
2753
+ case "docs-check":
2754
+ return docsCheckSection(payload.docsCheck);
1114
2755
  case "diff":
1115
2756
  return diffSection(payload.diff) + notice();
1116
2757
  case "init":
@@ -1195,6 +2836,45 @@ function policyLine(result) {
1195
2836
  function identityLine(result) {
1196
2837
  return `ARS ${result.specVersion} \xB7 ruleset \`${shortHash(result.rulesetHash)}\` \xB7 corpus \`${shortHash(result.corpusHash)}\` \xB7 evidence \`${shortHash(result.evidenceHash)}\` \xB7 vantage ${result.vantage}`;
1197
2838
  }
2839
+ function docsCheckSection(payload) {
2840
+ const out = [`## ${escapeCell(payload.url)} \u2014 docs check`, ""];
2841
+ if (payload.kind === "rejected") {
2842
+ out.push(`**REJECTED** \u2014 ${payload.rejection}: ${payload.detail}`, "");
2843
+ return out.join("\n");
2844
+ }
2845
+ if (payload.probeStatus !== "ok") {
2846
+ const label = payload.probeStatus === "policy" ? "BLOCKED BY POLICY" : "UNREACHABLE";
2847
+ out.push(`**${label}** \u2014 ${payload.probeDetail ?? ""}`, "");
2848
+ return out.join("\n");
2849
+ }
2850
+ const { report } = payload;
2851
+ const verdict = report.verdict === "can-follow" ? "Can follow" : "Likely stuck";
2852
+ out.push(
2853
+ `**${verdict}** \xB7 ${report.blocking.length} blocking \xB7 ${report.shouldFix.length} should-fix \xB7 ${report.passed.length} passed`,
2854
+ "",
2855
+ "| Check | Value |",
2856
+ "| --- | --- |",
2857
+ `| Analyzed source | \`${report.analyzedSource}\` |`,
2858
+ `| Markdown | \`${report.fetch.markdown}\` |`,
2859
+ `| Server HTML code blocks | ${report.fetch.serverHtmlCodeBlocks} |`,
2860
+ `| /llms.txt | \`${report.fetch.llmsTxt}\` |`,
2861
+ ""
2862
+ );
2863
+ const renderGroup = (title, items) => {
2864
+ if (items.length === 0) return;
2865
+ out.push(`### ${title}`, "");
2866
+ for (const item of items) {
2867
+ out.push(`- **${escapeCell(item.title)}** (\`${item.id}\`) \u2014 ${item.detail}`);
2868
+ if (item.fix !== null) out.push(` - Fix: ${item.fix}`);
2869
+ }
2870
+ out.push("");
2871
+ };
2872
+ renderGroup("Blocking", report.blocking);
2873
+ renderGroup("Should fix", report.shouldFix);
2874
+ renderGroup("Passed", report.passed);
2875
+ out.push(`> ${report.scope}`, "");
2876
+ return out.join("\n");
2877
+ }
1198
2878
  function diffSection(diff) {
1199
2879
  const out = [`## ${escapeCell(diff.url)} \u2014 agent view vs browser view`, ""];
1200
2880
  if (diff.report.kind === "rejected") {
@@ -1374,6 +3054,8 @@ function renderPretty(payload, caps, _ctx) {
1374
3054
  switch (payload.command) {
1375
3055
  case "check":
1376
3056
  return joinBlocks(payload.reports.map((report) => checkBlock(report, pretty)));
3057
+ case "docs-check":
3058
+ return joinBlocks([docsCheckBlock(payload.docsCheck, pretty)]);
1377
3059
  case "diff":
1378
3060
  return joinBlocks([diffBlock(payload.diff, pretty)]);
1379
3061
  case "init":
@@ -1541,6 +3223,52 @@ function identityLines(result, pretty) {
1541
3223
  function noticeLines(pretty) {
1542
3224
  return ["", ...ARS_NOTICE_LINES.map((line) => pretty.paint(line, "gray"))];
1543
3225
  }
3226
+ function docsCheckBlock(payload, pretty) {
3227
+ const { paint, caps } = pretty;
3228
+ const glyphs = glyphsFor(caps.unicode);
3229
+ const lines = [
3230
+ paint(truncate(payload.url, caps.width, caps.unicode), "bold"),
3231
+ paint(glyphs.horizontal.repeat(Math.min(caps.width, 64)), "gray")
3232
+ ];
3233
+ if (payload.kind === "rejected") {
3234
+ lines.push(`${paint("REJECTED", "red", "bold")} ${payload.rejection}: ${payload.detail}`);
3235
+ return lines;
3236
+ }
3237
+ if (payload.probeStatus !== "ok") {
3238
+ const label = payload.probeStatus === "policy" ? "BLOCKED BY POLICY" : "UNREACHABLE";
3239
+ lines.push(`${paint(label, "yellow", "bold")} ${payload.probeDetail ?? ""}`.trimEnd());
3240
+ return lines;
3241
+ }
3242
+ const { report } = payload;
3243
+ const verdictLabel = report.verdict === "can-follow" ? paint("CAN FOLLOW", "green", "bold") : paint("LIKELY STUCK", "red", "bold");
3244
+ lines.push(
3245
+ `${verdictLabel} ${paint(`${report.blocking.length} blocking \xB7 ${report.shouldFix.length} should-fix \xB7 ${report.passed.length} passed`, "gray")}`
3246
+ );
3247
+ lines.push(
3248
+ paint(
3249
+ `source: ${report.analyzedSource} \xB7 markdown: ${report.fetch.markdown} \xB7 /llms.txt: ${report.fetch.llmsTxt} \xB7 server HTML code blocks: ${report.fetch.serverHtmlCodeBlocks}`,
3250
+ "gray"
3251
+ )
3252
+ );
3253
+ const pushGroup = (heading, items, tone, mark) => {
3254
+ if (items.length === 0) return;
3255
+ lines.push("");
3256
+ lines.push(paint(heading, "bold"));
3257
+ for (const item of items) {
3258
+ lines.push(` ${paint(mark, tone)} ${paint(item.title, "bold")} ${paint(`[${item.id}]`, "gray")}`);
3259
+ lines.push(paint(` ${item.detail}`, "gray"));
3260
+ if (item.fix !== null) {
3261
+ lines.push(` Fix: ${item.fix}`);
3262
+ }
3263
+ }
3264
+ };
3265
+ pushGroup("Blocking", report.blocking, "red", caps.unicode ? "\u2718" : "x");
3266
+ pushGroup("Should fix", report.shouldFix, "yellow", caps.unicode ? "\u25D0" : "~");
3267
+ pushGroup("Passed", report.passed, "green", caps.unicode ? "\u2714" : "+");
3268
+ lines.push("");
3269
+ lines.push(paint(report.scope, "gray"));
3270
+ return lines;
3271
+ }
1544
3272
  function diffBlock(diff, pretty) {
1545
3273
  const { paint, caps } = pretty;
1546
3274
  const glyphs = glyphsFor(caps.unicode);
@@ -1697,6 +3425,7 @@ USAGE
1697
3425
  rebilder check <url...> [--format ${FORMATS.join("|")}] [--fail-on ${GRADES.join("|")}]
1698
3426
  [--out <file>] [--allow-private] [--allow-http]
1699
3427
  [--concurrency <n>]
3428
+ rebilder docs-check <url> [--json] [--fail-on-blocking] [--allow-private]
1700
3429
  rebilder diff <url> agent view vs browser view
1701
3430
  rebilder init gateway config scaffold for the detected framework
1702
3431
  rebilder badge <domain> embed snippet
@@ -1800,8 +3529,32 @@ OPTIONS
1800
3529
  --format ${FORMATS.join("|")} junit is refused: badge makes no observations
1801
3530
  --out <file> write the snippet to a file
1802
3531
  `;
3532
+ var DOCS_CHECK = `rebilder docs-check <url>
3533
+
3534
+ Checks whether a coding agent can follow a documentation page without getting
3535
+ stuck: Markdown negotiation, JS-dependent content, /llms.txt coverage, code
3536
+ block language labels, shell prompts, "..." elisions, unexplained placeholders,
3537
+ install-vs-import consistency, credential setup & env-var naming, runnable
3538
+ example, verification signal, and last-updated date.
3539
+
3540
+ Runs locally from your machine with zero telemetry \u2014 nothing is sent to
3541
+ Rebilder, no packages are installed, and no code is executed.
3542
+
3543
+ OPTIONS
3544
+ --format ${FORMATS.join("|")} default pretty
3545
+ --json shorthand for --format json
3546
+ --fail-on-blocking default off. Exit 1 when blocking findings
3547
+ are present (never exits 1 on probe or
3548
+ policy errors).
3549
+ --out <file> write the same rendering to a file
3550
+ --allow-http permit plain http targets
3551
+ --allow-private permit private, loopback and link-local
3552
+ targets (per-invocation opt-in, implies
3553
+ --allow-http)
3554
+ `;
1803
3555
  var TOPICS = {
1804
3556
  check: CHECK,
3557
+ "docs-check": DOCS_CHECK,
1805
3558
  diff: DIFF,
1806
3559
  init: INIT,
1807
3560
  badge: BADGE
@@ -1812,7 +3565,7 @@ function helpText(topic) {
1812
3565
  }
1813
3566
 
1814
3567
  // src/cli.ts
1815
- var CLI_VERSION = "0.4.0";
3568
+ var CLI_VERSION = "0.6.0";
1816
3569
  async function runCli(argv, runtime) {
1817
3570
  const caps = detectCapabilities({
1818
3571
  env: runtime.env,
@@ -1866,6 +3619,14 @@ async function execute(command, runtime) {
1866
3619
  exitCode: worstExit(reports.map((report) => exitCodeFor(report, command.failOn)))
1867
3620
  };
1868
3621
  }
3622
+ case "docs-check": {
3623
+ const probe = await buildProbe(runtime, 1, command);
3624
+ const docsCheck = await runDocsCheck(command, probe, runtime.now());
3625
+ return {
3626
+ payload: { command: "docs-check", docsCheck },
3627
+ exitCode: exitCodeForDocsCheck(docsCheck)
3628
+ };
3629
+ }
1869
3630
  case "diff": {
1870
3631
  const probe = await buildProbe(runtime, 1, command);
1871
3632
  const diff = await runDiff(command, probe);
@@ -1926,6 +3687,6 @@ function createNodeRuntime() {
1926
3687
  };
1927
3688
  }
1928
3689
 
1929
- export { ARS_NOTICE, ARS_NOTICE_LINES, BADGE_ORIGIN, CLI_VERSION, COMMANDS, EXIT, FORMATS, FRAMEWORKS, GRADES, TELEMETRY_LINES, UsageError, budgetFor, createNodeRuntime, detectCapabilities, detectFramework, exitCodeFor, helpText, meetsThreshold, nodeProbeFactory, normalizeDomain, outcomeSummary, parseCommandLine, render, runCli, statusOf, worstExit };
3690
+ export { ARS_NOTICE, ARS_NOTICE_LINES, BADGE_ORIGIN, CLI_VERSION, COMMANDS, DOCS_CHECK_SCOPE, EXIT, FORMATS, FRAMEWORKS, GRADES, TELEMETRY_LINES, UsageError, analyzeDocsEvidence, analyzeDocsFacts, budgetFor, createNodeRuntime, detectCapabilities, detectFramework, exitCodeFor, exitCodeForDocsCheck, factsFromEvidence, helpText, meetsThreshold, nodeProbeFactory, normalizeDomain, outcomeSummary, parseCommandLine, render, runCli, runDocsCheck, statusOf, worstExit };
1930
3691
  //# sourceMappingURL=index.js.map
1931
3692
  //# sourceMappingURL=index.js.map