@rebilder/agent-readability 0.4.0 → 0.5.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
@@ -750,10 +750,9 @@ function parseStartTag(html, start) {
750
750
  }
751
751
  return { tag, attrs, selfClosing, end: i };
752
752
  }
753
- function findRawTextEnd(html, from, tag) {
753
+ function findRawTextEnd(lowerHtml, from, tag) {
754
754
  const needle = `</${tag}`;
755
- const lower = html.toLowerCase();
756
- const at = lower.indexOf(needle, from);
755
+ const at = lowerHtml.indexOf(needle, from);
757
756
  return at === -1 ? -1 : at;
758
757
  }
759
758
  function ownExclusion(tag, attrs) {
@@ -817,6 +816,7 @@ function tokenizeHtml(html) {
817
816
  };
818
817
  let i = 0;
819
818
  let textStart = 0;
819
+ let lowerHtml = null;
820
820
  while (i < html.length) {
821
821
  const lt = html.indexOf("<", i);
822
822
  if (lt === -1) break;
@@ -868,7 +868,8 @@ function tokenizeHtml(html) {
868
868
  const isRcdata = RCDATA_ELEMENTS.has(parsed.tag);
869
869
  if (isRawText || isRcdata) {
870
870
  const contentStart = i;
871
- const close = findRawTextEnd(html, contentStart, parsed.tag);
871
+ lowerHtml ??= html.toLowerCase();
872
+ const close = findRawTextEnd(lowerHtml, contentStart, parsed.tag);
872
873
  const contentEnd = close === -1 ? html.length : close;
873
874
  if (contentEnd > contentStart) {
874
875
  const wasTop = stack.length;
@@ -2392,7 +2393,10 @@ function parseRobots(text) {
2392
2393
  else current.disallow.push(value);
2393
2394
  continue;
2394
2395
  }
2395
- if (field === "crawl-delay" || field === "host" || field === "clean-param") continue;
2396
+ if (field === "crawl-delay" || field === "host" || field === "clean-param" || field === "content-signal") {
2397
+ if (field === "content-signal" && current !== null) openingGroup = false;
2398
+ continue;
2399
+ }
2396
2400
  malformedLines++;
2397
2401
  }
2398
2402
  return { groups, sitemaps, malformedLines, orphanRules };
@@ -4942,6 +4946,843 @@ function robotsDisallowsScanner(robotsBody, path) {
4942
4946
  return null;
4943
4947
  }
4944
4948
 
4945
- export { AGENT_ACCEPT, ARS_CORPUS_HASH, ARS_HEURISTIC_WEIGHT, ARS_HEURISTIC_WEIGHT_CEILING, ARS_MEASURED_WEIGHT, ARS_ROBOTS_TOKEN, ARS_SPEC_VERSION, ASSET_ACCEPT, BROWSER_ACCEPT, CHECK_META, DEFAULT_RULESET, DIMENSION_META, PROFILES, SUBPOINTS, bandFor, canonicalJson, classify, declaredMarkdownAlternates, evidenceHash, isMachineCopy, markdownAlternateTarget, minorUnitDigits, parseMoneyText, parseRobots, pathMatches, profileFor, recommend, robotsDisallowsScanner, rulesetHash, score, sha256Hex, utf8Length };
4949
+ // src/site-signals.ts
4950
+ var EDGE_CHALLENGE_VENDOR_LABEL = {
4951
+ cloudflare: "Cloudflare",
4952
+ vercel: "Vercel",
4953
+ datadome: "DataDome",
4954
+ human: "HUMAN"
4955
+ };
4956
+ var BODY_SCAN_CHARS = 256 * 1024;
4957
+ function headerValues(input, name) {
4958
+ const direct = input.headers[name];
4959
+ if (direct !== void 0) return direct.map((value) => value.toLowerCase());
4960
+ const target = name.toLowerCase();
4961
+ const out = [];
4962
+ for (const [key, values] of Object.entries(input.headers)) {
4963
+ if (key.toLowerCase() === target) {
4964
+ for (const value of values) out.push(value.toLowerCase());
4965
+ }
4966
+ }
4967
+ return out;
4968
+ }
4969
+ function hasToken(values, token) {
4970
+ return values.some(
4971
+ (value) => value.split(",").map((part) => part.trim()).includes(token)
4972
+ );
4973
+ }
4974
+ function isRobotsTxtTarget(input) {
4975
+ for (const raw of [input.requestedUrl, input.finalUrl]) {
4976
+ if (typeof raw !== "string" || raw.length === 0) continue;
4977
+ try {
4978
+ if (new URL(raw).pathname.toLowerCase() === "/robots.txt") return true;
4979
+ } catch {
4980
+ const path = (raw.split("#")[0]?.split("?")[0] ?? "").toLowerCase();
4981
+ if (path === "/robots.txt" || path.endsWith("/robots.txt")) return true;
4982
+ }
4983
+ }
4984
+ return false;
4985
+ }
4986
+ function detectEdgeChallenge(input) {
4987
+ const status = input.status;
4988
+ const body = typeof input.body === "string" ? input.body.slice(0, BODY_SCAN_CHARS) : "";
4989
+ const server = headerValues(input, "server");
4990
+ const contentTypes = headerValues(input, "content-type");
4991
+ const isHtmlContent = contentTypes.some(
4992
+ (value) => value.includes("text/html") || value.includes("application/xhtml+xml")
4993
+ );
4994
+ const lowerBodyHead = body.slice(0, 4096).toLowerCase();
4995
+ const isPlainTextWithoutMarkup = contentTypes.some((value) => value.includes("text/plain")) && !lowerBodyHead.includes("<html") && !lowerBodyHead.includes("<script") && !lowerBodyHead.includes("<!doctype html");
4996
+ const isRobotsHtmlChallenge = isRobotsTxtTarget(input) && isHtmlContent;
4997
+ if (hasToken(headerValues(input, "cf-mitigated"), "challenge")) {
4998
+ return { vendor: "cloudflare", signal: "cf-mitigated: challenge", status };
4999
+ }
5000
+ if ((status === 403 || status === 429 || status === 503 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("cloudflare")) && body.includes("/cdn-cgi/challenge-platform/")) {
5001
+ return { vendor: "cloudflare", signal: "Cloudflare challenge page", status };
5002
+ }
5003
+ if (hasToken(headerValues(input, "x-vercel-mitigated"), "challenge")) {
5004
+ return { vendor: "vercel", signal: "x-vercel-mitigated: challenge", status };
5005
+ }
5006
+ if ((status < 200 || status >= 300 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && server.some((value) => value.includes("vercel")) && body.includes("Vercel Security Checkpoint")) {
5007
+ return { vendor: "vercel", signal: "Vercel Security Checkpoint page", status };
5008
+ }
5009
+ if ((status === 401 || status === 403) && headerValues(input, "x-datadome").length > 0) {
5010
+ return { vendor: "datadome", signal: `x-datadome with HTTP ${status}`, status };
5011
+ }
5012
+ if ((status === 403 || status === 429 || isRobotsHtmlChallenge && status === 200) && !isPlainTextWithoutMarkup && body.includes("px-captcha") && body.includes("_pxAppId")) {
5013
+ return { vendor: "human", signal: "HUMAN block page", status };
5014
+ }
5015
+ return null;
5016
+ }
5017
+ var DETAIL_PREFIX = "edge-challenge";
5018
+ var DETAIL_PATTERN = /^edge-challenge; vendor=([a-z]+); status=(\d{3}); signal=(.{1,120})$/;
5019
+ function challengeDetail(challenge) {
5020
+ return `${DETAIL_PREFIX}; vendor=${challenge.vendor}; status=${challenge.status}; signal=${challenge.signal.slice(0, 120)}`;
5021
+ }
5022
+ function parseChallengeDetail(detail) {
5023
+ if (typeof detail !== "string") return null;
5024
+ const match = DETAIL_PATTERN.exec(detail);
5025
+ if (match === null) return null;
5026
+ const vendor = match[1];
5027
+ if (!(vendor in EDGE_CHALLENGE_VENDOR_LABEL)) return null;
5028
+ return { vendor, status: Number(match[2]), signal: match[3] ?? "" };
5029
+ }
5030
+ function edgeChallengeOf(evidence) {
5031
+ if (typeof evidence !== "object" || evidence === null) return null;
5032
+ const agent = evidence.probes?.agent?.result;
5033
+ if (typeof agent !== "object" || agent === null) return null;
5034
+ const result = agent;
5035
+ if (result.ok !== false || result.error !== "challenge") return null;
5036
+ return parseChallengeDetail(result.detail);
5037
+ }
5038
+ function robotsEdgeChallengeOf(evidence) {
5039
+ if (typeof evidence !== "object" || evidence === null) return null;
5040
+ const robots = evidence.probes?.robotsTxt?.result;
5041
+ if (typeof robots !== "object" || robots === null) return null;
5042
+ const result = robots;
5043
+ if (result.ok === false && result.error === "challenge") {
5044
+ return parseChallengeDetail(result.detail);
5045
+ }
5046
+ if (result.ok === true && result.capture !== void 0 && typeof result.capture === "object") {
5047
+ return detectEdgeChallenge(result.capture);
5048
+ }
5049
+ return null;
5050
+ }
5051
+ var CLOUDFLARE_MANAGED_MARKER = "# begin cloudflare managed content";
5052
+ function parseContentSignals(robotsTxt) {
5053
+ let cloudflareManaged = false;
5054
+ const rules = [];
5055
+ let currentAgents = [];
5056
+ let openingGroup = false;
5057
+ for (const rawLine of robotsTxt.split(/\r?\n/)) {
5058
+ const trimmedRaw = rawLine.trim();
5059
+ if (trimmedRaw.toLowerCase().includes(CLOUDFLARE_MANAGED_MARKER)) {
5060
+ cloudflareManaged = true;
5061
+ }
5062
+ const withoutComment = rawLine.split("#")[0] ?? "";
5063
+ const line = withoutComment.trim();
5064
+ if (line.length === 0) continue;
5065
+ const colon = line.indexOf(":");
5066
+ if (colon <= 0) continue;
5067
+ const field = line.slice(0, colon).trim().toLowerCase();
5068
+ const value = line.slice(colon + 1).trim();
5069
+ if (field === "user-agent") {
5070
+ if (!openingGroup) {
5071
+ currentAgents = [];
5072
+ openingGroup = true;
5073
+ }
5074
+ if (value.length > 0) currentAgents.push(value.toLowerCase());
5075
+ continue;
5076
+ }
5077
+ if (field === "allow" || field === "disallow") {
5078
+ openingGroup = false;
5079
+ continue;
5080
+ }
5081
+ if (field === "content-signal") {
5082
+ if (currentAgents.length > 0) openingGroup = false;
5083
+ const parsed = {};
5084
+ for (const part of value.split(",")) {
5085
+ const eq = part.indexOf("=");
5086
+ if (eq <= 0) continue;
5087
+ const key = part.slice(0, eq).trim().toLowerCase();
5088
+ const val = part.slice(eq + 1).trim().toLowerCase();
5089
+ if (key.length > 0 && val.length > 0) {
5090
+ parsed[key] = val;
5091
+ }
5092
+ }
5093
+ rules.push({
5094
+ agents: [...currentAgents],
5095
+ raw: value,
5096
+ signals: parsed
5097
+ });
5098
+ }
5099
+ }
5100
+ let search = null;
5101
+ let aiInput = null;
5102
+ let aiTrain = null;
5103
+ const wildcardRules = rules.filter((rule) => rule.agents.includes("*"));
5104
+ const summarySource = wildcardRules.length > 0 ? wildcardRules : rules.filter((rule) => rule.agents.length === 0);
5105
+ for (const rule of summarySource) {
5106
+ if (rule.signals["search"] !== void 0) search = rule.signals["search"];
5107
+ if (rule.signals["ai-input"] !== void 0) aiInput = rule.signals["ai-input"];
5108
+ if (rule.signals["ai-train"] !== void 0) aiTrain = rule.signals["ai-train"];
5109
+ }
5110
+ return {
5111
+ present: rules.length > 0,
5112
+ cloudflareManaged,
5113
+ rules,
5114
+ summary: { search, aiInput, aiTrain }
5115
+ };
5116
+ }
5117
+ var ROBOTS_DIRECTIVES = /* @__PURE__ */ new Set([
5118
+ "all",
5119
+ "noindex",
5120
+ "nofollow",
5121
+ "none",
5122
+ "noarchive",
5123
+ "nosnippet",
5124
+ "notranslate",
5125
+ "noimageindex",
5126
+ "unavailable_after",
5127
+ "max-snippet",
5128
+ "max-image-preview",
5129
+ "max-video-preview",
5130
+ "indexifembedded",
5131
+ "noai",
5132
+ "noimageai"
5133
+ ]);
5134
+ var AGENT_META_NAMES = new Set(
5135
+ [
5136
+ ...DEFAULT_RULESET.audienceTokens.assistant,
5137
+ ...DEFAULT_RULESET.audienceTokens.training,
5138
+ ...DEFAULT_RULESET.audienceTokens.search,
5139
+ "googlebot",
5140
+ "bingbot"
5141
+ ].map((token) => token.toLowerCase())
5142
+ );
5143
+ function splitRobotTokens(directives) {
5144
+ return directives.toLowerCase().split(",").map((part) => part.trim()).filter((part) => part.length > 0);
5145
+ }
5146
+ function blocksIndexing(directives) {
5147
+ return splitRobotTokens(directives).some((part) => part === "noindex" || part === "none");
5148
+ }
5149
+ function extractRestrictions(directives) {
5150
+ const found = [];
5151
+ for (const part of splitRobotTokens(directives)) {
5152
+ if (part === "nosnippet") found.push("nosnippet");
5153
+ else if (/^max-snippet\s*:\s*0$/.test(part)) found.push("max-snippet:0");
5154
+ else if (part === "noai") found.push("noai");
5155
+ else if (part === "noimageai") found.push("noimageai");
5156
+ }
5157
+ return found;
5158
+ }
5159
+ function parseHeaderRobots(values) {
5160
+ const noindex = [];
5161
+ const restrictions = [];
5162
+ for (const value of values) {
5163
+ const trimmed = value.trim();
5164
+ const prefixed = /^\s*([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(value);
5165
+ const prefix = prefixed?.[1]?.toLowerCase();
5166
+ let agent = "robots";
5167
+ let directiveBody = value;
5168
+ if (prefixed !== null && prefix !== void 0 && !ROBOTS_DIRECTIVES.has(prefix)) {
5169
+ agent = prefix;
5170
+ directiveBody = prefixed[2] ?? "";
5171
+ }
5172
+ if (blocksIndexing(directiveBody)) {
5173
+ noindex.push({ agent, source: "header", value: trimmed });
5174
+ }
5175
+ for (const directive of extractRestrictions(directiveBody)) {
5176
+ restrictions.push({ agent, source: "header", directive, value: trimmed });
5177
+ }
5178
+ }
5179
+ return { noindex, restrictions };
5180
+ }
5181
+ function summarizeCanonicals(canonicals) {
5182
+ let htmlCount = 0;
5183
+ let headerCount = 0;
5184
+ const distinct = /* @__PURE__ */ new Set();
5185
+ for (const entry of canonicals) {
5186
+ if (entry.source === "html") htmlCount++;
5187
+ else headerCount++;
5188
+ distinct.add(entry.url);
5189
+ }
5190
+ return {
5191
+ duplicateCanonical: htmlCount > 1 || headerCount > 1,
5192
+ conflictingCanonical: distinct.size > 1
5193
+ };
5194
+ }
5195
+ function indexSignalsOf(capture) {
5196
+ const parsedHeaders = parseHeaderRobots(headerAll(capture.headers, "x-robots-tag"));
5197
+ const noindex = [...parsedHeaders.noindex];
5198
+ const restrictions = [...parsedHeaders.restrictions];
5199
+ const canonicals = [];
5200
+ let canonical = null;
5201
+ for (const link of parseLinkHeaders(headerAll(capture.headers, "link"))) {
5202
+ if (link.rel.includes("canonical")) {
5203
+ const resolved = absoluteUrl(link.url, capture.finalUrl);
5204
+ if (resolved !== null) {
5205
+ canonicals.push({ source: "header", url: resolved });
5206
+ if (canonical === null) canonical = resolved;
5207
+ }
5208
+ }
5209
+ }
5210
+ const representation = buildRepresentation(capture);
5211
+ const doc = representation?.doc ?? null;
5212
+ if (doc !== null) {
5213
+ for (const meta of doc.metas) {
5214
+ const name = meta.name;
5215
+ if (name === null || meta.content === null) continue;
5216
+ const targetAgent = name === "robots" ? "robots" : AGENT_META_NAMES.has(name) ? name : null;
5217
+ if (targetAgent === null) continue;
5218
+ if (blocksIndexing(meta.content)) {
5219
+ noindex.push({ agent: targetAgent, source: "meta", value: meta.content });
5220
+ }
5221
+ for (const directive of extractRestrictions(meta.content)) {
5222
+ restrictions.push({
5223
+ agent: targetAgent,
5224
+ source: "meta",
5225
+ directive,
5226
+ value: meta.content
5227
+ });
5228
+ }
5229
+ }
5230
+ for (const link of doc.links) {
5231
+ if (link.rel.includes("canonical") && link.href !== null) {
5232
+ const resolved = absoluteUrl(link.href, capture.finalUrl);
5233
+ if (resolved !== null) {
5234
+ canonicals.push({ source: "html", url: resolved });
5235
+ if (canonical === null) canonical = resolved;
5236
+ }
5237
+ }
5238
+ }
5239
+ }
5240
+ const { duplicateCanonical, conflictingCanonical } = summarizeCanonicals(canonicals);
5241
+ return {
5242
+ status: capture.status,
5243
+ finalUrl: capture.finalUrl,
5244
+ redirected: capture.redirects.length > 0,
5245
+ noindex,
5246
+ canonical,
5247
+ restrictions,
5248
+ nosnippet: restrictions.some((r) => r.directive === "nosnippet"),
5249
+ maxSnippetZero: restrictions.some((r) => r.directive === "max-snippet:0"),
5250
+ noai: restrictions.some((r) => r.directive === "noai"),
5251
+ noimageai: restrictions.some((r) => r.directive === "noimageai"),
5252
+ canonicals,
5253
+ duplicateCanonical,
5254
+ conflictingCanonical,
5255
+ payPerCrawl: capture.status === 402
5256
+ };
5257
+ }
5258
+ function pageIndexSignals(evidence) {
5259
+ const browser = evidence.probes.browser.result;
5260
+ const agent = evidence.probes.agent.result;
5261
+ const capture = browser.ok ? browser.capture : agent.ok ? agent.capture : null;
5262
+ if (capture === null) return null;
5263
+ const signals = indexSignalsOf(capture);
5264
+ if (browser.ok && agent.ok) {
5265
+ const agentRobots = parseHeaderRobots(headerAll(agent.capture.headers, "x-robots-tag"));
5266
+ const seenNoindex = new Set(signals.noindex.map((d) => `${d.agent}|${d.source}|${d.value}`));
5267
+ for (const directive of agentRobots.noindex) {
5268
+ const key = `${directive.agent}|${directive.source}|${directive.value}`;
5269
+ if (!seenNoindex.has(key)) {
5270
+ seenNoindex.add(key);
5271
+ signals.noindex.push(directive);
5272
+ }
5273
+ }
5274
+ const seenRestrictions = new Set(
5275
+ signals.restrictions.map((d) => `${d.agent}|${d.source}|${d.directive}|${d.value}`)
5276
+ );
5277
+ for (const directive of agentRobots.restrictions) {
5278
+ const key = `${directive.agent}|${directive.source}|${directive.directive}|${directive.value}`;
5279
+ if (!seenRestrictions.has(key)) {
5280
+ seenRestrictions.add(key);
5281
+ signals.restrictions.push(directive);
5282
+ }
5283
+ }
5284
+ signals.nosnippet = signals.restrictions.some((r) => r.directive === "nosnippet");
5285
+ signals.maxSnippetZero = signals.restrictions.some((r) => r.directive === "max-snippet:0");
5286
+ signals.noai = signals.restrictions.some((r) => r.directive === "noai");
5287
+ signals.noimageai = signals.restrictions.some((r) => r.directive === "noimageai");
5288
+ const seenCanonicals = new Set(signals.canonicals.map((c) => `${c.source}|${c.url}`));
5289
+ let canonicalsAdded = false;
5290
+ for (const link of parseLinkHeaders(headerAll(agent.capture.headers, "link"))) {
5291
+ if (!link.rel.includes("canonical")) continue;
5292
+ const resolved = absoluteUrl(link.url, agent.capture.finalUrl);
5293
+ if (resolved === null) continue;
5294
+ const key = `header|${resolved}`;
5295
+ if (!seenCanonicals.has(key)) {
5296
+ seenCanonicals.add(key);
5297
+ signals.canonicals.push({ source: "header", url: resolved });
5298
+ if (signals.canonical === null) signals.canonical = resolved;
5299
+ canonicalsAdded = true;
5300
+ }
5301
+ }
5302
+ if (canonicalsAdded) {
5303
+ const summary = summarizeCanonicals(signals.canonicals);
5304
+ signals.duplicateCanonical = summary.duplicateCanonical;
5305
+ signals.conflictingCanonical = summary.conflictingCanonical;
5306
+ }
5307
+ if (agent.capture.status === 402) {
5308
+ signals.payPerCrawl = true;
5309
+ }
5310
+ }
5311
+ return signals;
5312
+ }
5313
+ var SPA_MOUNT_ROOT_IDS = /* @__PURE__ */ new Set(["root", "app", "__next", "__nuxt"]);
5314
+ var NOSCRIPT_JS_PATTERNS = [
5315
+ /\benable\s+javascript\b/i,
5316
+ /\bjavascript\s+(?:is\s+required|must\s+be\s+enabled|is\s+disabled)\b/i,
5317
+ /\brequires?\s+javascript\b/i,
5318
+ /\bturn\s+on\s+javascript\b/i,
5319
+ /\bwithout\s+javascript\b/i,
5320
+ /\bdoes\s+not\s+support\s+javascript\b/i,
5321
+ /\bneed\s+javascript\b/i
5322
+ ];
5323
+ function hasAncestorTag(doc, startIndex, tags) {
5324
+ let current = startIndex;
5325
+ for (let hops = 0; hops < 128 && current >= 0; hops++) {
5326
+ const el = doc.elements[current];
5327
+ if (el === void 0) break;
5328
+ if (tags.has(el.tag)) return true;
5329
+ current = el.parent;
5330
+ }
5331
+ return false;
5332
+ }
5333
+ var NON_BODY_TEXT_TAGS = /* @__PURE__ */ new Set(["title", "noscript"]);
5334
+ function detectSpaJsDependency(html) {
5335
+ const doc = tokenizeHtml(html);
5336
+ const emptyMountRoots = [];
5337
+ for (const el of doc.elements) {
5338
+ const id = el.attrs["id"]?.trim().toLowerCase();
5339
+ if (id === void 0 || !SPA_MOUNT_ROOT_IDS.has(id)) continue;
5340
+ const text = elementText(doc, el.index);
5341
+ if (text.length === 0) {
5342
+ const selector = `#${el.attrs["id"]?.trim() ?? id}`;
5343
+ if (!emptyMountRoots.includes(selector)) emptyMountRoots.push(selector);
5344
+ }
5345
+ }
5346
+ let jsRequiredNoscript = false;
5347
+ let noscriptSnippet = null;
5348
+ for (const el of doc.elements) {
5349
+ if (el.tag !== "noscript") continue;
5350
+ const text = elementText(doc, el.index);
5351
+ if (text.length === 0) continue;
5352
+ if (NOSCRIPT_JS_PATTERNS.some((pattern) => pattern.test(text))) {
5353
+ jsRequiredNoscript = true;
5354
+ if (noscriptSnippet === null) noscriptSnippet = text.slice(0, 200);
5355
+ }
5356
+ }
5357
+ const visibleParts = [];
5358
+ for (const node of doc.texts) {
5359
+ if (node.excludedBy !== null) continue;
5360
+ if (hasAncestorTag(doc, node.parent, NON_BODY_TEXT_TAGS)) continue;
5361
+ visibleParts.push(node.text);
5362
+ }
5363
+ const visibleBodyText = visibleParts.join(" ").replace(/\s+/g, " ").trim();
5364
+ const visibleWordCount = visibleBodyText.length === 0 ? 0 : visibleBodyText.split(/\s+/).filter(Boolean).length;
5365
+ const visibleTextBytes = utf8Length(visibleBodyText);
5366
+ let scriptBytes = 0;
5367
+ let externalScriptCount = 0;
5368
+ let hasNextData = false;
5369
+ let hasNextFlight = false;
5370
+ let hydrationPayloadBytes = 0;
5371
+ const nextDataElements = /* @__PURE__ */ new Set();
5372
+ for (const el of doc.elements) {
5373
+ if (el.tag !== "script") continue;
5374
+ const typeAttr = el.attrs["type"]?.trim().toLowerCase() ?? "";
5375
+ if (typeAttr === "application/ld+json") continue;
5376
+ if (typeof el.attrs["src"] === "string" && el.attrs["src"].trim().length > 0) {
5377
+ externalScriptCount++;
5378
+ }
5379
+ if (el.attrs["id"]?.trim().toLowerCase() === "__next_data__") {
5380
+ hasNextData = true;
5381
+ nextDataElements.add(el.index);
5382
+ }
5383
+ }
5384
+ for (const node of doc.texts) {
5385
+ if (node.excludedBy !== "script") continue;
5386
+ scriptBytes += node.bytes;
5387
+ if (nextDataElements.has(node.parent)) {
5388
+ hydrationPayloadBytes += node.bytes;
5389
+ } else if (node.text.includes("__next_f")) {
5390
+ hasNextFlight = true;
5391
+ hydrationPayloadBytes += node.bytes;
5392
+ }
5393
+ }
5394
+ const unrenderedHydrationPayload = (hasNextData || hasNextFlight) && hydrationPayloadBytes >= 1024 && (visibleWordCount < 50 || visibleWordCount < 100 && visibleTextBytes > 0 && hydrationPayloadBytes / visibleTextBytes >= 4);
5395
+ const scriptToTextRatio = visibleTextBytes > 0 ? Number((scriptBytes / visibleTextBytes).toFixed(2)) : scriptBytes > 0 ? null : 0;
5396
+ const lowTextToScriptRatio = visibleWordCount < 40 && (scriptBytes >= 2048 || externalScriptCount >= 2) || visibleWordCount < 80 && visibleTextBytes > 0 && scriptBytes / visibleTextBytes >= 20;
5397
+ const reasons = [];
5398
+ if (emptyMountRoots.length > 0) reasons.push("empty-mount-root");
5399
+ if (jsRequiredNoscript) reasons.push("noscript-js-required");
5400
+ if (unrenderedHydrationPayload) reasons.push("unrendered-next-payload");
5401
+ if (lowTextToScriptRatio) reasons.push("low-text-vs-script");
5402
+ const likelySpaShell = emptyMountRoots.length > 0 && visibleWordCount < 50 || jsRequiredNoscript && visibleWordCount < 80 || unrenderedHydrationPayload || reasons.length >= 2;
5403
+ return {
5404
+ likelySpaShell,
5405
+ reasons,
5406
+ emptyMountRoots,
5407
+ jsRequiredNoscript,
5408
+ noscriptSnippet,
5409
+ hasNextData,
5410
+ hasNextFlight,
5411
+ hydrationPayloadBytes,
5412
+ unrenderedHydrationPayload,
5413
+ visibleWordCount,
5414
+ visibleTextBytes,
5415
+ scriptBytes,
5416
+ externalScriptCount,
5417
+ scriptToTextRatio,
5418
+ lowTextToScriptRatio
5419
+ };
5420
+ }
5421
+ var SAAS_QUOTA_UNITS = [
5422
+ "seats",
5423
+ "users",
5424
+ "projects",
5425
+ "pages",
5426
+ "sites",
5427
+ "requests",
5428
+ "tokens",
5429
+ "credits",
5430
+ "calls",
5431
+ "events",
5432
+ "contacts",
5433
+ "workspaces",
5434
+ "domains",
5435
+ "rows"
5436
+ ];
5437
+ var QUOTA_UNIT_CANONICAL = {
5438
+ seat: "seats",
5439
+ seats: "seats",
5440
+ user: "users",
5441
+ users: "users",
5442
+ project: "projects",
5443
+ projects: "projects",
5444
+ page: "pages",
5445
+ pages: "pages",
5446
+ site: "sites",
5447
+ sites: "sites",
5448
+ request: "requests",
5449
+ requests: "requests",
5450
+ token: "tokens",
5451
+ tokens: "tokens",
5452
+ credit: "credits",
5453
+ credits: "credits",
5454
+ call: "calls",
5455
+ calls: "calls",
5456
+ event: "events",
5457
+ events: "events",
5458
+ contact: "contacts",
5459
+ contacts: "contacts",
5460
+ workspace: "workspaces",
5461
+ workspaces: "workspaces",
5462
+ domain: "domains",
5463
+ domains: "domains",
5464
+ row: "rows",
5465
+ rows: "rows"
5466
+ };
5467
+ var PRICE_TOKEN_PATTERN = /(?:[$€£¥] ?\d[\d,.]*|\b(?:USD|EUR|GBP|CAD|AUD) \d[\d,.]*)/gi;
5468
+ var TIER_CONTAINER_TAGS = /* @__PURE__ */ new Set(["article", "section", "div", "li"]);
5469
+ var TIER_ATTR_HINT = /(?:^|[-_\s])(plan|tier|pricing[-_]?card|price[-_]?card|package)(?:$|[-_\s])/i;
5470
+ var TIER_TEXT_HINT = /\b(?:free|custom pricing|custom|contact sales|enterprise|talk to sales)\b/i;
5471
+ var ICON_CLASS_HINT = /(?:icon|check|tick|cross|dash|minus|yes|no|fa-|lucide|heroicon|badge)/i;
5472
+ var TOGGLE_ELEMENT_TAGS = /* @__PURE__ */ new Set(["button", "input", "label", "select", "div", "span", "fieldset"]);
5473
+ var ANNUAL_PRICE_CONTEXT = /\b(?:billed (?:annually|yearly)|annual billing|per year|annually|yearly)\b|\/(?:yr|year)\b/i;
5474
+ var MONTHLY_PRICE_CONTEXT = /\b(?:billed monthly|monthly billing|per month|monthly)\b|\/(?:mo|month)\b/i;
5475
+ var CADENCE_PATTERNS = [
5476
+ /\/(?:mo|month|yr|year|quarter|week|day|seat|user|member)\b/gi,
5477
+ /\bper (?:month|mo|year|yr|quarter|week|day|hour|seat|user|member|workspace|project|site|domain|request|call|credit|token|contact|unit)\b/gi,
5478
+ /\bbilled (?:annually|yearly|monthly|quarterly)\b/gi,
5479
+ /\bone-time\b/gi
5480
+ ];
5481
+ var QUOTA_MODIFIER_WORDS = /* @__PURE__ */ new Set([
5482
+ "active",
5483
+ "custom",
5484
+ "monthly",
5485
+ "annual",
5486
+ "api",
5487
+ "team",
5488
+ "tracked",
5489
+ "monitored",
5490
+ "included",
5491
+ "free",
5492
+ "extra",
5493
+ "total",
5494
+ "concurrent",
5495
+ "unique"
5496
+ ]);
5497
+ var QUOTA_QUANTITY_TOKEN = /^(?:unlimited|\d[\d,.]*[kmb]?\+?)$/i;
5498
+ var QUOTA_VALUE_CELL = /^(?:unlimited|up to \d[\d,.]*[kmb]?|\d[\d,.]*[kmb]?\+?)$/i;
5499
+ function isAncestorOf(doc, ancestor, descendant) {
5500
+ let current = descendant;
5501
+ for (let hops = 0; hops < 128 && current >= 0; hops++) {
5502
+ if (current === ancestor) return true;
5503
+ current = doc.elements[current]?.parent ?? -1;
5504
+ }
5505
+ return false;
5506
+ }
5507
+ function collectOfferRecords(nodes) {
5508
+ const offers = [];
5509
+ const seen = /* @__PURE__ */ new Set();
5510
+ const visit = (obj, depth) => {
5511
+ if (depth > 8 || obj === null || typeof obj !== "object") return;
5512
+ if (Array.isArray(obj)) {
5513
+ for (const item of obj) visit(item, depth + 1);
5514
+ return;
5515
+ }
5516
+ if (seen.has(obj)) return;
5517
+ seen.add(obj);
5518
+ const rec = obj;
5519
+ const rawType = rec["@type"];
5520
+ const types = typeof rawType === "string" ? [rawType.replace(/^https?:\/\/schema\.org\//, "")] : Array.isArray(rawType) ? rawType.filter((t) => typeof t === "string").map((t) => t.replace(/^https?:\/\/schema\.org\//, "")) : [];
5521
+ if (types.includes("Offer")) offers.push(rec);
5522
+ if (rec["offers"] !== void 0) visit(rec["offers"], depth + 1);
5523
+ };
5524
+ for (const node of nodes) {
5525
+ if (!seen.has(node.value)) {
5526
+ seen.add(node.value);
5527
+ if (node.types.includes("Offer")) offers.push(node.value);
5528
+ }
5529
+ if (node.value["offers"] !== void 0) visit(node.value["offers"], 1);
5530
+ }
5531
+ return offers;
5532
+ }
5533
+ function hasOfferPrice(offer) {
5534
+ if (offer["price"] !== void 0 && offer["price"] !== null && String(offer["price"]).trim() !== "") {
5535
+ return true;
5536
+ }
5537
+ const spec = offer["priceSpecification"];
5538
+ const specs = Array.isArray(spec) ? spec : spec !== void 0 && spec !== null ? [spec] : [];
5539
+ return specs.some((entry) => {
5540
+ if (entry === null || typeof entry !== "object") return false;
5541
+ const record = entry;
5542
+ return record["price"] !== void 0 && String(record["price"]).trim() !== "" || record["minPrice"] !== void 0 && String(record["minPrice"]).trim() !== "";
5543
+ });
5544
+ }
5545
+ function normalizePriceMatch(raw) {
5546
+ return raw.replace(/[.,]+$/, "").replace(/\s+/g, "").toUpperCase();
5547
+ }
5548
+ function directChildrenOfTag(doc, parentIndex, tag) {
5549
+ const out = [];
5550
+ for (const el of doc.elements) {
5551
+ if (el.parent === parentIndex && el.tag === tag) out.push(el);
5552
+ }
5553
+ return out;
5554
+ }
5555
+ function descendantsOf(doc, ancestorIndex) {
5556
+ const out = [];
5557
+ for (let i = ancestorIndex + 1; i < doc.elements.length; i++) {
5558
+ const el = doc.elements[i];
5559
+ if (el === void 0) continue;
5560
+ if (el.depth <= (doc.elements[ancestorIndex]?.depth ?? 0)) break;
5561
+ if (isAncestorOf(doc, ancestorIndex, el.index)) out.push(el);
5562
+ }
5563
+ return out;
5564
+ }
5565
+ function quotaUnitFromLabel(label) {
5566
+ const words = label.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
5567
+ for (const word of words) {
5568
+ const mapped = QUOTA_UNIT_CANONICAL[word];
5569
+ if (mapped !== void 0) return mapped;
5570
+ }
5571
+ return null;
5572
+ }
5573
+ function auditPricingAndLimits(html, jsonLdNodes) {
5574
+ const doc = tokenizeHtml(html);
5575
+ const nodes = jsonLdNodes !== void 0 ? jsonLdNodes : parseJsonLd(doc.jsonLd).nodes;
5576
+ const offerRecords = collectOfferRecords(nodes);
5577
+ const jsonLdOfferCount = offerRecords.length;
5578
+ const jsonLdPricedOfferCount = offerRecords.filter(hasOfferPrice).length;
5579
+ const visibleParts = [];
5580
+ for (const node of doc.texts) {
5581
+ if (node.excludedBy !== null) continue;
5582
+ if (hasAncestorTag(doc, node.parent, NON_BODY_TEXT_TAGS)) continue;
5583
+ visibleParts.push(node.text);
5584
+ }
5585
+ const visibleText = visibleParts.join(" ").replace(/\s+/g, " ").trim();
5586
+ const priceMatches = [];
5587
+ PRICE_TOKEN_PATTERN.lastIndex = 0;
5588
+ let match;
5589
+ while ((match = PRICE_TOKEN_PATTERN.exec(visibleText)) !== null) {
5590
+ priceMatches.push({ raw: match[0], index: match.index });
5591
+ }
5592
+ const visiblePriceCount = priceMatches.length;
5593
+ const distinctVisiblePriceCount = new Set(priceMatches.map((m) => normalizePriceMatch(m.raw))).size;
5594
+ const candidateCards = [];
5595
+ for (const el of doc.elements) {
5596
+ if (!TIER_CONTAINER_TAGS.has(el.tag) || el.excludedBy !== null) continue;
5597
+ const hasDataPlan = el.attrs["data-plan"] !== void 0 || el.attrs["data-tier"] !== void 0 || el.attrs["data-pricing-tier"] !== void 0;
5598
+ const hintStr = `${el.attrs["class"] ?? ""} ${el.attrs["id"] ?? ""}`;
5599
+ if (!hasDataPlan && !TIER_ATTR_HINT.test(hintStr)) continue;
5600
+ const text = elementText(doc, el.index);
5601
+ if (text.length === 0) continue;
5602
+ PRICE_TOKEN_PATTERN.lastIndex = 0;
5603
+ if (PRICE_TOKEN_PATTERN.test(text) || TIER_TEXT_HINT.test(text)) {
5604
+ candidateCards.push(el);
5605
+ }
5606
+ }
5607
+ const leafCards = candidateCards.filter(
5608
+ (card) => !candidateCards.some((other) => other.index !== card.index && isAncestorOf(doc, card.index, other.index))
5609
+ );
5610
+ let iconOnlyCellCount = 0;
5611
+ let pricingTableTierCount = 0;
5612
+ const unitCounts = {};
5613
+ const incrementUnit = (unit) => {
5614
+ unitCounts[unit] = (unitCounts[unit] ?? 0) + 1;
5615
+ };
5616
+ for (const el of doc.elements) {
5617
+ if (el.tag !== "table" || el.excludedBy !== null) continue;
5618
+ const tableDescendants = descendantsOf(doc, el.index);
5619
+ const rows = tableDescendants.filter((child) => child.tag === "tr");
5620
+ if (rows.length === 0) continue;
5621
+ const tableText = elementText(doc, el.index);
5622
+ PRICE_TOKEN_PATTERN.lastIndex = 0;
5623
+ const tableHasPrices = PRICE_TOKEN_PATTERN.test(tableText);
5624
+ for (const row of rows) {
5625
+ const cells = [
5626
+ ...directChildrenOfTag(doc, row.index, "th"),
5627
+ ...directChildrenOfTag(doc, row.index, "td")
5628
+ ].sort((a, b) => a.index - b.index);
5629
+ if (cells.length >= 3 && tableHasPrices) {
5630
+ const thCount = cells.filter((c) => c.tag === "th").length;
5631
+ if (thCount >= 3) {
5632
+ pricingTableTierCount = Math.max(pricingTableTierCount, thCount - 1);
5633
+ }
5634
+ }
5635
+ const firstCell = cells[0];
5636
+ const rowQuotaUnit = firstCell !== void 0 && cells.length >= 2 ? quotaUnitFromLabel(elementText(doc, firstCell.index)) : null;
5637
+ for (let cellIdx = 0; cellIdx < cells.length; cellIdx++) {
5638
+ const cell = cells[cellIdx];
5639
+ if (cell === void 0 || cell.tag !== "td") continue;
5640
+ const cellText = elementText(doc, cell.index);
5641
+ if (cellIdx > 0 && rowQuotaUnit !== null && QUOTA_VALUE_CELL.test(cellText)) {
5642
+ incrementUnit(rowQuotaUnit);
5643
+ }
5644
+ if (cells.length >= 2 && cellText.length === 0) {
5645
+ const cellDescendants = descendantsOf(doc, cell.index);
5646
+ const hasIconOnly = cellDescendants.some((desc) => {
5647
+ if (desc.tag === "svg") return true;
5648
+ if (desc.tag === "img" && (desc.attrs["alt"] ?? "").trim().length === 0) return true;
5649
+ if ((desc.tag === "i" || desc.tag === "span") && ICON_CLASS_HINT.test(desc.attrs["class"] ?? "")) {
5650
+ return true;
5651
+ }
5652
+ return false;
5653
+ });
5654
+ if (hasIconOnly) iconOnlyCellCount++;
5655
+ }
5656
+ }
5657
+ }
5658
+ }
5659
+ const visibleTierCount = Math.max(leafCards.length, pricingTableTierCount, distinctVisiblePriceCount);
5660
+ const iconOnlyFeatureMatrix = iconOnlyCellCount > 0;
5661
+ let hasBillingToggleHint = false;
5662
+ let sawMonthlyControl = false;
5663
+ let sawAnnualControl = false;
5664
+ for (const el of doc.elements) {
5665
+ if (!TOGGLE_ELEMENT_TAGS.has(el.tag) || el.excludedBy !== null) continue;
5666
+ const role = el.attrs["role"]?.toLowerCase() ?? "";
5667
+ const isInteractive = el.tag === "button" || el.tag === "input" || el.tag === "label" || el.tag === "select" || role === "switch" || role === "tab" || role === "tablist" || role === "radiogroup";
5668
+ if (!isInteractive) continue;
5669
+ const labelText = [
5670
+ elementText(doc, el.index),
5671
+ el.attrs["aria-label"] ?? "",
5672
+ el.attrs["name"] ?? "",
5673
+ el.attrs["id"] ?? "",
5674
+ el.attrs["data-billing"] ?? "",
5675
+ el.attrs["data-period"] ?? ""
5676
+ ].join(" ").toLowerCase();
5677
+ const hasMonthly = /\b(?:monthly|month)\b/.test(labelText);
5678
+ const hasAnnual = /\b(?:annual(?:ly)?|yearly|year)\b/.test(labelText);
5679
+ if (hasMonthly && hasAnnual) {
5680
+ hasBillingToggleHint = true;
5681
+ break;
5682
+ }
5683
+ if (hasMonthly) sawMonthlyControl = true;
5684
+ if (hasAnnual) sawAnnualControl = true;
5685
+ }
5686
+ if (sawMonthlyControl && sawAnnualControl) hasBillingToggleHint = true;
5687
+ let monthlyPricePresent = false;
5688
+ let annualPricePresent = false;
5689
+ for (let i = 0; i < priceMatches.length; i++) {
5690
+ const pm = priceMatches[i];
5691
+ if (pm === void 0) continue;
5692
+ const nextPriceIndex = priceMatches[i + 1]?.index ?? visibleText.length;
5693
+ const contextEnd = Math.min(nextPriceIndex, pm.index + 48);
5694
+ const context = visibleText.slice(pm.index, contextEnd);
5695
+ if (ANNUAL_PRICE_CONTEXT.test(context)) {
5696
+ annualPricePresent = true;
5697
+ } else if (MONTHLY_PRICE_CONTEXT.test(context)) {
5698
+ monthlyPricePresent = true;
5699
+ }
5700
+ }
5701
+ const billingToggleSinglePeriodOnly = hasBillingToggleHint && monthlyPricePresent !== annualPricePresent;
5702
+ const billingCadences = [];
5703
+ const seenCadences = /* @__PURE__ */ new Set();
5704
+ for (const pattern of CADENCE_PATTERNS) {
5705
+ pattern.lastIndex = 0;
5706
+ let cadenceMatch;
5707
+ while ((cadenceMatch = pattern.exec(visibleText)) !== null) {
5708
+ const normalized = cadenceMatch[0].replace(/\s+/g, " ").trim().toLowerCase();
5709
+ if (normalized.length > 0 && !seenCadences.has(normalized)) {
5710
+ seenCadences.add(normalized);
5711
+ billingCadences.push(normalized);
5712
+ }
5713
+ }
5714
+ }
5715
+ const words = visibleText.toLowerCase().split(/[^a-z0-9.,+]+/).map((token) => token.replace(/^[.,]+/, "").replace(/[.,]+$/, "")).filter((token) => token.length > 0);
5716
+ for (let i = 0; i + 1 < words.length; i++) {
5717
+ const qty = words[i];
5718
+ if (qty === void 0 || !QUOTA_QUANTITY_TOKEN.test(qty)) continue;
5719
+ const next = words[i + 1];
5720
+ if (next === void 0) continue;
5721
+ const direct = QUOTA_UNIT_CANONICAL[next];
5722
+ if (direct !== void 0) {
5723
+ incrementUnit(direct);
5724
+ i += 1;
5725
+ continue;
5726
+ }
5727
+ if (QUOTA_MODIFIER_WORDS.has(next)) {
5728
+ const after = words[i + 2];
5729
+ const modified = after !== void 0 ? QUOTA_UNIT_CANONICAL[after] : void 0;
5730
+ if (modified !== void 0) {
5731
+ incrementUnit(modified);
5732
+ i += 2;
5733
+ }
5734
+ }
5735
+ }
5736
+ const detectedQuotaUnits = SAAS_QUOTA_UNITS.filter((unit) => (unitCounts[unit] ?? 0) > 0);
5737
+ const featureLimitCount = detectedQuotaUnits.reduce((sum, unit) => sum + (unitCounts[unit] ?? 0), 0);
5738
+ return {
5739
+ jsonLdOfferCount,
5740
+ jsonLdPricedOfferCount,
5741
+ visibleTierCount,
5742
+ visiblePriceCount,
5743
+ iconOnlyFeatureMatrix,
5744
+ iconOnlyCellCount,
5745
+ hasBillingToggleHint,
5746
+ billingToggleSinglePeriodOnly,
5747
+ billingCadences,
5748
+ featureLimitCount,
5749
+ featureLimitUnits: unitCounts,
5750
+ detectedQuotaUnits
5751
+ };
5752
+ }
5753
+ function declaredPageFacts(evidence) {
5754
+ const browser = evidence.probes.browser.result;
5755
+ const agent = evidence.probes.agent.result;
5756
+ const capture = browser.ok ? browser.capture : agent.ok ? agent.capture : null;
5757
+ if (capture === null) return null;
5758
+ const representation = buildRepresentation(capture);
5759
+ if (representation === null) return null;
5760
+ const extract = (kinds, currencyHint) => {
5761
+ const profile = {
5762
+ pageKind: "unknown",
5763
+ core: kinds,
5764
+ extended: [],
5765
+ byteReference: DEFAULT_RULESET.maxBodyBytes
5766
+ };
5767
+ return extractFacts(representation, {
5768
+ profile,
5769
+ ruleset: DEFAULT_RULESET,
5770
+ baseUrl: capture.finalUrl,
5771
+ origin: evidence.target.origin,
5772
+ currencyHint
5773
+ });
5774
+ };
5775
+ const currency = extract(["currency"], void 0).find((fact) => fact.kind === "currency");
5776
+ const facts = extract(["updated", "price"], currency?.normalized);
5777
+ let updated = null;
5778
+ const priceSources = [];
5779
+ for (const fact of facts) {
5780
+ if (fact.kind === "updated" && updated === null) updated = fact.normalized;
5781
+ if (fact.kind === "price" && !priceSources.includes(fact.source)) priceSources.push(fact.source);
5782
+ }
5783
+ return { updated, priceSources };
5784
+ }
5785
+
5786
+ export { AGENT_ACCEPT, ARS_CORPUS_HASH, ARS_HEURISTIC_WEIGHT, ARS_HEURISTIC_WEIGHT_CEILING, ARS_MEASURED_WEIGHT, ARS_ROBOTS_TOKEN, ARS_SPEC_VERSION, ASSET_ACCEPT, BROWSER_ACCEPT, CHECK_META, DEFAULT_RULESET, DIMENSION_META, EDGE_CHALLENGE_VENDOR_LABEL, PROFILES, SAAS_QUOTA_UNITS, SUBPOINTS, auditPricingAndLimits, bandFor, canonicalJson, challengeDetail, classify, decideRobots, declaredMarkdownAlternates, declaredPageFacts, detectEdgeChallenge, detectSpaJsDependency, edgeChallengeOf, evidenceHash, indexSignalsOf, isMachineCopy, markdownAlternateTarget, minorUnitDigits, pageIndexSignals, parseChallengeDetail, parseContentSignals, parseMoneyText, parseRobots, pathMatches, profileFor, recommend, robotsDisallowsScanner, robotsEdgeChallengeOf, rulesetHash, score, sha256Hex, utf8Length };
4946
5787
  //# sourceMappingURL=index.js.map
4947
5788
  //# sourceMappingURL=index.js.map