@detiq/crawler 1.1.9 → 1.1.11

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.
Files changed (83) hide show
  1. package/dist/accessibility-auditor.js +54 -74
  2. package/dist/ai-login.js +227 -249
  3. package/dist/auth-token-rotator.js +57 -67
  4. package/dist/auth.js +299 -336
  5. package/dist/browser-extension.js +104 -142
  6. package/dist/captcha-solver.js +98 -125
  7. package/dist/color-contrast.js +77 -89
  8. package/dist/content-chunker.js +126 -126
  9. package/dist/content-dedup.js +54 -71
  10. package/dist/cookie-consent.js +68 -83
  11. package/dist/cookie-jar.js +53 -60
  12. package/dist/crawler.js +4494 -5353
  13. package/dist/custom-js-injector.js +45 -61
  14. package/dist/dark-mode-capture.js +67 -81
  15. package/dist/dead-link-detector.js +47 -55
  16. package/dist/element-hash.js +8 -12
  17. package/dist/email-otp.js +154 -195
  18. package/dist/engine-router.js +87 -98
  19. package/dist/export/bulk-export.js +70 -55
  20. package/dist/export/vector-export.js +77 -105
  21. package/dist/extractors/advanced.js +249 -266
  22. package/dist/extractors/artifact-envelope.js +59 -58
  23. package/dist/failure-analysis-agent.js +37 -33
  24. package/dist/feature-flag-detector.js +51 -66
  25. package/dist/form-detector.js +55 -75
  26. package/dist/frontier.js +76 -101
  27. package/dist/gap-pass.js +68 -89
  28. package/dist/graphql-detector.js +62 -72
  29. package/dist/http-engine.js +282 -330
  30. package/dist/incremental-diff.js +54 -87
  31. package/dist/index.js +67 -28
  32. package/dist/input-fuzzer.js +93 -97
  33. package/dist/interactive-probe.js +715 -827
  34. package/dist/job-queue.js +2151 -2169
  35. package/dist/js-coverage.js +52 -56
  36. package/dist/js-router-detector.js +86 -117
  37. package/dist/language-detector.js +51 -63
  38. package/dist/link-classifier.js +32 -50
  39. package/dist/live-view.js +91 -108
  40. package/dist/locator-extractor.js +151 -187
  41. package/dist/logger.js +9 -7
  42. package/dist/markdown-extract.js +48 -61
  43. package/dist/native-crawler.js +780 -946
  44. package/dist/network-observer.js +135 -156
  45. package/dist/network-throttle.js +29 -40
  46. package/dist/openapi-generator.js +77 -92
  47. package/dist/pdf-extractor.js +72 -90
  48. package/dist/performance-metrics.js +80 -102
  49. package/dist/phash.js +125 -144
  50. package/dist/pii-scrubber.js +65 -68
  51. package/dist/playwright-recorder.js +70 -58
  52. package/dist/policies/crawl-safety.js +31 -34
  53. package/dist/profiles/domain-profile.js +130 -125
  54. package/dist/proxy.js +146 -172
  55. package/dist/rate-limiter.js +58 -65
  56. package/dist/redirect-tracker.js +60 -64
  57. package/dist/redis-frontier.js +116 -136
  58. package/dist/redis-queue.js +157 -144
  59. package/dist/response-cache.js +127 -140
  60. package/dist/responsive-detector.js +42 -46
  61. package/dist/retry-policy.js +46 -50
  62. package/dist/robots-txt.js +69 -83
  63. package/dist/screen-reader.js +45 -70
  64. package/dist/screenshot-masker.js +59 -77
  65. package/dist/seo-checker.js +88 -107
  66. package/dist/session-capture.js +192 -212
  67. package/dist/session-export.js +107 -133
  68. package/dist/sitemap-writer.js +38 -41
  69. package/dist/sitemap.js +141 -202
  70. package/dist/skyvern.js +123 -148
  71. package/dist/sqs-queue.js +42 -42
  72. package/dist/sso-token.js +74 -90
  73. package/dist/stealth/human-behavior.js +156 -173
  74. package/dist/telemetry.js +68 -82
  75. package/dist/test-executor.js +309 -335
  76. package/dist/tls-fingerprint.js +77 -88
  77. package/dist/url-pattern-completer.js +71 -90
  78. package/dist/visual-diff-verdict.js +23 -38
  79. package/dist/webhook-notifier.js +71 -69
  80. package/dist/websocket-detector.js +56 -68
  81. package/dist/worker.js +29 -38
  82. package/package.json +1 -1
  83. package/src/job-queue.ts +136 -0
@@ -1,153 +1,140 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, unlinkSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- export class ResponseCache {
5
- dir;
6
- totalHits = 0;
7
- totalRequests = 0;
8
- constructor(cacheDir) {
9
- this.dir = cacheDir;
10
- if (!existsSync(cacheDir))
11
- mkdirSync(cacheDir, { recursive: true });
1
+ import { createHash } from "node:crypto";
2
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, unlinkSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ class ResponseCache {
5
+ dir;
6
+ totalHits = 0;
7
+ totalRequests = 0;
8
+ constructor(cacheDir) {
9
+ this.dir = cacheDir;
10
+ if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
11
+ }
12
+ key(url) {
13
+ return createHash("sha256").update(url).digest("hex").slice(0, 16);
14
+ }
15
+ path(url) {
16
+ return join(this.dir, `${this.key(url)}.json`);
17
+ }
18
+ get(url) {
19
+ this.totalRequests++;
20
+ try {
21
+ const p = this.path(url);
22
+ if (!existsSync(p)) return null;
23
+ const entry = JSON.parse(readFileSync(p, "utf-8"));
24
+ this.totalHits++;
25
+ return entry;
26
+ } catch {
27
+ return null;
12
28
  }
13
- key(url) {
14
- return createHash('sha256').update(url).digest('hex').slice(0, 16);
29
+ }
30
+ read(url) {
31
+ try {
32
+ const p = this.path(url);
33
+ if (!existsSync(p)) return null;
34
+ return JSON.parse(readFileSync(p, "utf-8"));
35
+ } catch {
36
+ return null;
15
37
  }
16
- path(url) {
17
- return join(this.dir, `${this.key(url)}.json`);
38
+ }
39
+ isFresh(url) {
40
+ const entry = this.read(url);
41
+ if (!entry?.cacheControl) return false;
42
+ const m = /max-age=(\d+)/i.exec(entry.cacheControl);
43
+ if (!m) return false;
44
+ const maxAgeMs = parseInt(m[1], 10) * 1e3;
45
+ return entry.cachedAt + maxAgeMs > Date.now();
46
+ }
47
+ staleIfError(url) {
48
+ const entry = this.read(url);
49
+ if (!entry?.cacheControl) return false;
50
+ const m = /stale-if-error=(\d+)/i.exec(entry.cacheControl);
51
+ if (!m) return false;
52
+ const staleIfErrorMs = parseInt(m[1], 10) * 1e3;
53
+ return entry.cachedAt + staleIfErrorMs >= Date.now();
54
+ }
55
+ set(url, entry) {
56
+ try {
57
+ const full = { ...entry, cachedAt: Date.now(), hitCount: 0 };
58
+ writeFileSync(this.path(url), JSON.stringify(full), "utf-8");
59
+ } catch {
18
60
  }
19
- get(url) {
20
- this.totalRequests++;
21
- try {
22
- const p = this.path(url);
23
- if (!existsSync(p))
24
- return null;
25
- const entry = JSON.parse(readFileSync(p, 'utf-8'));
26
- this.totalHits++;
27
- return entry;
28
- }
29
- catch {
30
- return null;
31
- }
32
- }
33
- read(url) {
34
- try {
35
- const p = this.path(url);
36
- if (!existsSync(p))
37
- return null;
38
- return JSON.parse(readFileSync(p, 'utf-8'));
39
- }
40
- catch {
41
- return null;
42
- }
43
- }
44
- isFresh(url) {
45
- const entry = this.read(url);
46
- if (!entry?.cacheControl)
47
- return false;
48
- const m = /max-age=(\d+)/i.exec(entry.cacheControl);
49
- if (!m)
50
- return false;
51
- const maxAgeMs = parseInt(m[1], 10) * 1000;
52
- return entry.cachedAt + maxAgeMs > Date.now();
53
- }
54
- staleIfError(url) {
55
- const entry = this.read(url);
56
- if (!entry?.cacheControl)
57
- return false;
58
- const m = /stale-if-error=(\d+)/i.exec(entry.cacheControl);
59
- if (!m)
60
- return false;
61
- const staleIfErrorMs = parseInt(m[1], 10) * 1000;
62
- return entry.cachedAt + staleIfErrorMs >= Date.now();
63
- }
64
- set(url, entry) {
65
- try {
66
- const full = { ...entry, cachedAt: Date.now(), hitCount: 0 };
67
- writeFileSync(this.path(url), JSON.stringify(full), 'utf-8');
68
- }
69
- catch { /* non-fatal */ }
70
- }
71
- getValidationHeaders(url) {
72
- const entry = this.get(url);
73
- if (!entry)
74
- return {};
75
- const headers = {};
76
- if (entry.etag)
77
- headers['If-None-Match'] = entry.etag;
78
- if (entry.lastModified)
79
- headers['If-Modified-Since'] = entry.lastModified;
80
- return headers;
81
- }
82
- markHit(url) {
83
- try {
84
- const p = this.path(url);
85
- if (!existsSync(p))
86
- return;
87
- const entry = JSON.parse(readFileSync(p, 'utf-8'));
88
- entry.hitCount++;
89
- writeFileSync(p, JSON.stringify(entry), 'utf-8');
90
- }
91
- catch { /* non-fatal */ }
61
+ }
62
+ getValidationHeaders(url) {
63
+ const entry = this.get(url);
64
+ if (!entry) return {};
65
+ const headers = {};
66
+ if (entry.etag) headers["If-None-Match"] = entry.etag;
67
+ if (entry.lastModified) headers["If-Modified-Since"] = entry.lastModified;
68
+ return headers;
69
+ }
70
+ markHit(url) {
71
+ try {
72
+ const p = this.path(url);
73
+ if (!existsSync(p)) return;
74
+ const entry = JSON.parse(readFileSync(p, "utf-8"));
75
+ entry.hitCount++;
76
+ writeFileSync(p, JSON.stringify(entry), "utf-8");
77
+ } catch {
92
78
  }
93
- invalidate(url) {
94
- try {
95
- const p = this.path(url);
96
- if (existsSync(p))
97
- unlinkSync(p);
98
- }
99
- catch { /* non-fatal */ }
79
+ }
80
+ invalidate(url) {
81
+ try {
82
+ const p = this.path(url);
83
+ if (existsSync(p)) unlinkSync(p);
84
+ } catch {
100
85
  }
101
- clear() {
102
- try {
103
- for (const f of readdirSync(this.dir)) {
104
- if (f.endsWith('.json'))
105
- unlinkSync(join(this.dir, f));
106
- }
107
- }
108
- catch { /* non-fatal */ }
86
+ }
87
+ clear() {
88
+ try {
89
+ for (const f of readdirSync(this.dir)) {
90
+ if (f.endsWith(".json")) unlinkSync(join(this.dir, f));
91
+ }
92
+ } catch {
109
93
  }
110
- stats() {
111
- let entries = 0;
112
- let totalSizeBytes = 0;
94
+ }
95
+ stats() {
96
+ let entries = 0;
97
+ let totalSizeBytes = 0;
98
+ try {
99
+ for (const f of readdirSync(this.dir)) {
100
+ if (!f.endsWith(".json")) continue;
101
+ entries++;
113
102
  try {
114
- for (const f of readdirSync(this.dir)) {
115
- if (!f.endsWith('.json'))
116
- continue;
117
- entries++;
118
- try {
119
- totalSizeBytes += statSync(join(this.dir, f)).size;
120
- }
121
- catch { /* skip */ }
122
- }
103
+ totalSizeBytes += statSync(join(this.dir, f)).size;
104
+ } catch {
123
105
  }
124
- catch { /* non-fatal */ }
125
- return {
126
- entries,
127
- totalSizeBytes,
128
- hitRate: this.totalRequests > 0 ? this.totalHits / this.totalRequests : 0,
129
- totalHits: this.totalHits,
130
- };
106
+ }
107
+ } catch {
131
108
  }
132
- prune(maxAgeMs) {
133
- let deleted = 0;
134
- const cutoff = Date.now() - maxAgeMs;
109
+ return {
110
+ entries,
111
+ totalSizeBytes,
112
+ hitRate: this.totalRequests > 0 ? this.totalHits / this.totalRequests : 0,
113
+ totalHits: this.totalHits
114
+ };
115
+ }
116
+ prune(maxAgeMs) {
117
+ let deleted = 0;
118
+ const cutoff = Date.now() - maxAgeMs;
119
+ try {
120
+ for (const f of readdirSync(this.dir)) {
121
+ if (!f.endsWith(".json")) continue;
135
122
  try {
136
- for (const f of readdirSync(this.dir)) {
137
- if (!f.endsWith('.json'))
138
- continue;
139
- try {
140
- const p = join(this.dir, f);
141
- const entry = JSON.parse(readFileSync(p, 'utf-8'));
142
- if (entry.cachedAt < cutoff) {
143
- unlinkSync(p);
144
- deleted++;
145
- }
146
- }
147
- catch { /* skip */ }
148
- }
123
+ const p = join(this.dir, f);
124
+ const entry = JSON.parse(readFileSync(p, "utf-8"));
125
+ if (entry.cachedAt < cutoff) {
126
+ unlinkSync(p);
127
+ deleted++;
128
+ }
129
+ } catch {
149
130
  }
150
- catch { /* non-fatal */ }
151
- return deleted;
131
+ }
132
+ } catch {
152
133
  }
134
+ return deleted;
135
+ }
153
136
  }
137
+ export {
138
+ ResponseCache
139
+ };
140
+ //# sourceMappingURL=response-cache.js.map
@@ -1,50 +1,46 @@
1
- /**
2
- * Responsive design detector — captures page at multiple breakpoints
3
- * and detects layout differences between desktop and mobile viewports.
4
- *
5
- * Breakpoints: mobile(375), tablet(768), desktop(1280), wide(1920)
6
- * Detects: viewport-specific content visibility, menu collapse state,
7
- * font size changes, hidden/shown elements.
8
- */
9
1
  const BREAKPOINTS = [
10
- { width: 375, height: 812, label: 'mobile' },
11
- { width: 768, height: 1024, label: 'tablet' },
12
- { width: 1280, height: 800, label: 'desktop' },
2
+ { width: 375, height: 812, label: "mobile" },
3
+ { width: 768, height: 1024, label: "tablet" },
4
+ { width: 1280, height: 800, label: "desktop" }
13
5
  ];
14
- export async function detectResponsive(page, url, opts = {}) {
15
- const captures = [];
16
- const issues = [];
17
- for (const bp of BREAKPOINTS) {
18
- try {
19
- await page.setViewportSize({ width: bp.width, height: bp.height });
20
- await page.waitForTimeout(500); // allow CSS reflow
21
- const data = await page.evaluate(() => ({
22
- visibleTextLength: (document.body.innerText ?? '').length,
23
- hasHamburgerMenu: !!(document.querySelector('[class*="hamburger"],[class*="menu-toggle"],[class*="nav-toggle"],[aria-label*="menu"],[aria-label*="Menu"]')),
24
- hiddenElements: Array.from(document.querySelectorAll('*')).filter((el) => window.getComputedStyle(el).display === 'none').length,
25
- scrollHeight: document.body.scrollHeight,
26
- })).catch(() => ({ visibleTextLength: 0, hasHamburgerMenu: false, hiddenElements: 0, scrollHeight: 0 }));
27
- let screenshotBuffer;
28
- if (opts.captureScreenshots) {
29
- screenshotBuffer = await page.screenshot({ type: 'jpeg', quality: 60 }).catch(() => undefined);
30
- }
31
- captures.push({ ...bp, ...data, screenshotBuffer });
32
- }
33
- catch { /* viewport failed — skip */ }
6
+ async function detectResponsive(page, url, opts = {}) {
7
+ const captures = [];
8
+ const issues = [];
9
+ for (const bp of BREAKPOINTS) {
10
+ try {
11
+ await page.setViewportSize({ width: bp.width, height: bp.height });
12
+ await page.waitForTimeout(500);
13
+ const data = await page.evaluate(() => ({
14
+ visibleTextLength: (document.body.innerText ?? "").length,
15
+ hasHamburgerMenu: !!document.querySelector('[class*="hamburger"],[class*="menu-toggle"],[class*="nav-toggle"],[aria-label*="menu"],[aria-label*="Menu"]'),
16
+ hiddenElements: Array.from(document.querySelectorAll("*")).filter(
17
+ (el) => window.getComputedStyle(el).display === "none"
18
+ ).length,
19
+ scrollHeight: document.body.scrollHeight
20
+ })).catch(() => ({ visibleTextLength: 0, hasHamburgerMenu: false, hiddenElements: 0, scrollHeight: 0 }));
21
+ let screenshotBuffer;
22
+ if (opts.captureScreenshots) {
23
+ screenshotBuffer = await page.screenshot({ type: "jpeg", quality: 60 }).catch(() => void 0);
24
+ }
25
+ captures.push({ ...bp, ...data, screenshotBuffer });
26
+ } catch {
34
27
  }
35
- // Restore to desktop
36
- await page.setViewportSize({ width: 1280, height: 800 }).catch(() => { });
37
- const mobile = captures.find(c => c.label === 'mobile');
38
- const desktop = captures.find(c => c.label === 'desktop');
39
- const isResponsive = !!(mobile && desktop && (mobile.hiddenElements !== desktop.hiddenElements ||
40
- mobile.scrollHeight !== desktop.scrollHeight ||
41
- mobile.hasHamburgerMenu));
42
- const hasMobileMenu = captures.some(c => c.label === 'mobile' && c.hasHamburgerMenu);
43
- if (mobile && desktop && mobile.visibleTextLength > desktop.visibleTextLength * 1.3) {
44
- issues.push('Mobile shows significantly more text than desktop — possible responsive issue');
45
- }
46
- if (!isResponsive && captures.length > 1) {
47
- issues.push('Layout appears identical across breakpoints — may not be responsive');
48
- }
49
- return { url, captures, isResponsive, hasMobileMenu, issues };
28
+ }
29
+ await page.setViewportSize({ width: 1280, height: 800 }).catch(() => {
30
+ });
31
+ const mobile = captures.find((c) => c.label === "mobile");
32
+ const desktop = captures.find((c) => c.label === "desktop");
33
+ const isResponsive = !!(mobile && desktop && (mobile.hiddenElements !== desktop.hiddenElements || mobile.scrollHeight !== desktop.scrollHeight || mobile.hasHamburgerMenu));
34
+ const hasMobileMenu = captures.some((c) => c.label === "mobile" && c.hasHamburgerMenu);
35
+ if (mobile && desktop && mobile.visibleTextLength > desktop.visibleTextLength * 1.3) {
36
+ issues.push("Mobile shows significantly more text than desktop \u2014 possible responsive issue");
37
+ }
38
+ if (!isResponsive && captures.length > 1) {
39
+ issues.push("Layout appears identical across breakpoints \u2014 may not be responsive");
40
+ }
41
+ return { url, captures, isResponsive, hasMobileMenu, issues };
50
42
  }
43
+ export {
44
+ detectResponsive
45
+ };
46
+ //# sourceMappingURL=responsive-detector.js.map
@@ -1,58 +1,54 @@
1
- /**
2
- * Retry policy — configurable exponential backoff with jitter.
3
- * Covers: 5xx server errors, network timeouts, ECONNREFUSED, ECONNRESET.
4
- * NOT retried: 4xx client errors (except 429 — handled separately), redirects.
5
- */
6
1
  const DEFAULT_RETRY_STATUSES = [429, 500, 502, 503, 504];
7
2
  function shouldRetry(error, retryOn) {
8
- // Network-level errors
9
- if (error?.code && ['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'EPIPE'].includes(error.code))
10
- return true;
11
- // Playwright navigation timeout
12
- if (error?.message && /timeout|net::ERR_/i.test(error.message))
13
- return true;
14
- // HTTP status errors
15
- if (typeof error?.status === 'number')
16
- return retryOn.includes(error.status);
17
- return false;
3
+ if (error?.code && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE"].includes(error.code)) return true;
4
+ if (error?.message && /timeout|net::ERR_/i.test(error.message)) return true;
5
+ if (typeof error?.status === "number") return retryOn.includes(error.status);
6
+ return false;
18
7
  }
19
8
  function delay(ms) {
20
- return new Promise(r => setTimeout(r, ms));
9
+ return new Promise((r) => setTimeout(r, ms));
21
10
  }
22
- export async function withRetry(fn, opts = {}) {
23
- const { maxRetries = 3, baseDelayMs = 1_000, maxDelayMs = 30_000, jitterMs = 500, retryOn = DEFAULT_RETRY_STATUSES, } = opts;
24
- let lastError;
25
- let totalDelayMs = 0;
26
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
27
- try {
28
- const value = await fn(attempt);
29
- return { value, attempts: attempt + 1, totalDelayMs };
30
- }
31
- catch (err) {
32
- lastError = err;
33
- if (attempt === maxRetries)
34
- break;
35
- if (!shouldRetry(err, retryOn))
36
- throw err; // non-retryable — fail fast
37
- const backoff = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
38
- const jitter = Math.random() * jitterMs;
39
- const waitMs = Math.round(backoff + jitter);
40
- totalDelayMs += waitMs;
41
- await delay(waitMs);
42
- }
11
+ async function withRetry(fn, opts = {}) {
12
+ const {
13
+ maxRetries = 3,
14
+ baseDelayMs = 1e3,
15
+ maxDelayMs = 3e4,
16
+ jitterMs = 500,
17
+ retryOn = DEFAULT_RETRY_STATUSES
18
+ } = opts;
19
+ let lastError;
20
+ let totalDelayMs = 0;
21
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
22
+ try {
23
+ const value = await fn(attempt);
24
+ return { value, attempts: attempt + 1, totalDelayMs };
25
+ } catch (err) {
26
+ lastError = err;
27
+ if (attempt === maxRetries) break;
28
+ if (!shouldRetry(err, retryOn)) throw err;
29
+ const backoff = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
30
+ const jitter = Math.random() * jitterMs;
31
+ const waitMs = Math.round(backoff + jitter);
32
+ totalDelayMs += waitMs;
33
+ await delay(waitMs);
43
34
  }
44
- throw lastError;
35
+ }
36
+ throw lastError;
45
37
  }
46
- /** Wraps fetch() with retry policy */
47
- export async function fetchWithRetry(url, init = {}, retryOpts = {}) {
48
- const result = await withRetry(async () => {
49
- const res = await fetch(url, init);
50
- if (retryOpts.retryOn?.includes(res.status) ?? DEFAULT_RETRY_STATUSES.includes(res.status)) {
51
- const err = new Error(`HTTP ${res.status}`);
52
- err.status = res.status;
53
- throw err;
54
- }
55
- return res;
56
- }, retryOpts);
57
- return result.value;
38
+ async function fetchWithRetry(url, init = {}, retryOpts = {}) {
39
+ const result = await withRetry(async () => {
40
+ const res = await fetch(url, init);
41
+ if (retryOpts.retryOn?.includes(res.status) ?? DEFAULT_RETRY_STATUSES.includes(res.status)) {
42
+ const err = new Error(`HTTP ${res.status}`);
43
+ err.status = res.status;
44
+ throw err;
45
+ }
46
+ return res;
47
+ }, retryOpts);
48
+ return result.value;
58
49
  }
50
+ export {
51
+ fetchWithRetry,
52
+ withRetry
53
+ };
54
+ //# sourceMappingURL=retry-policy.js.map
@@ -1,91 +1,77 @@
1
- /**
2
- * Minimal robots.txt fetcher + parser. No external deps. Caches per origin.
3
- * Implements the subset of robots.txt spec used in practice:
4
- * User-agent, Disallow, Allow — longest match wins (RFC 9309).
5
- */
6
1
  function parseRobots(text) {
7
- const rules = [];
8
- let current = null;
9
- for (const rawLine of text.split('\n')) {
10
- const line = rawLine.split('#')[0].trim();
11
- if (!line) {
12
- current = null;
13
- continue;
14
- }
15
- const colonIdx = line.indexOf(':');
16
- if (colonIdx === -1)
17
- continue;
18
- const key = line.slice(0, colonIdx).trim().toLowerCase();
19
- const value = line.slice(colonIdx + 1).trim();
20
- if (key === 'user-agent') {
21
- // Start new block only when current block already has rules, otherwise
22
- // accumulate multiple User-agent lines into one block.
23
- if (!current || current.disallow.length > 0 || current.allow.length > 0) {
24
- current = { userAgent: value.toLowerCase(), disallow: [], allow: [] };
25
- rules.push(current);
26
- }
27
- else {
28
- current.userAgent = value.toLowerCase();
29
- }
30
- }
31
- else if (key === 'disallow' && current && value) {
32
- current.disallow.push(value);
33
- }
34
- else if (key === 'allow' && current && value) {
35
- current.allow.push(value);
36
- }
2
+ const rules = [];
3
+ let current = null;
4
+ for (const rawLine of text.split("\n")) {
5
+ const line = rawLine.split("#")[0].trim();
6
+ if (!line) {
7
+ current = null;
8
+ continue;
37
9
  }
38
- return rules;
10
+ const colonIdx = line.indexOf(":");
11
+ if (colonIdx === -1) continue;
12
+ const key = line.slice(0, colonIdx).trim().toLowerCase();
13
+ const value = line.slice(colonIdx + 1).trim();
14
+ if (key === "user-agent") {
15
+ if (!current || current.disallow.length > 0 || current.allow.length > 0) {
16
+ current = { userAgent: value.toLowerCase(), disallow: [], allow: [] };
17
+ rules.push(current);
18
+ } else {
19
+ current.userAgent = value.toLowerCase();
20
+ }
21
+ } else if (key === "disallow" && current && value) {
22
+ current.disallow.push(value);
23
+ } else if (key === "allow" && current && value) {
24
+ current.allow.push(value);
25
+ }
26
+ }
27
+ return rules;
39
28
  }
40
29
  function isAllowedByRules(rules, userAgent, pathname) {
41
- const ua = userAgent.toLowerCase();
42
- const exactRules = rules.filter(r => r.userAgent === ua);
43
- const wildcardRules = rules.filter(r => r.userAgent === '*');
44
- const applicable = exactRules.length > 0 ? exactRules : wildcardRules;
45
- if (applicable.length === 0)
46
- return true;
47
- // Collect all matched allow/disallow directives; longest path wins.
48
- const matched = [];
49
- for (const rule of applicable) {
50
- for (const p of rule.allow) {
51
- if (pathname.startsWith(p))
52
- matched.push({ path: p, allow: true });
53
- }
54
- for (const p of rule.disallow) {
55
- if (pathname.startsWith(p))
56
- matched.push({ path: p, allow: false });
57
- }
30
+ const ua = userAgent.toLowerCase();
31
+ const exactRules = rules.filter((r) => r.userAgent === ua);
32
+ const wildcardRules = rules.filter((r) => r.userAgent === "*");
33
+ const applicable = exactRules.length > 0 ? exactRules : wildcardRules;
34
+ if (applicable.length === 0) return true;
35
+ const matched = [];
36
+ for (const rule of applicable) {
37
+ for (const p of rule.allow) {
38
+ if (pathname.startsWith(p)) matched.push({ path: p, allow: true });
39
+ }
40
+ for (const p of rule.disallow) {
41
+ if (pathname.startsWith(p)) matched.push({ path: p, allow: false });
58
42
  }
59
- if (matched.length === 0)
60
- return true;
61
- matched.sort((a, b) => b.path.length - a.path.length);
62
- return matched[0].allow;
43
+ }
44
+ if (matched.length === 0) return true;
45
+ matched.sort((a, b) => b.path.length - a.path.length);
46
+ return matched[0].allow;
63
47
  }
64
- export class RobotsCache {
65
- cache = new Map();
66
- async isAllowed(url, userAgent = 'ZeTa-Crawler') {
67
- let origin;
68
- let pathname;
69
- try {
70
- const u = new URL(url);
71
- origin = u.origin;
72
- pathname = u.pathname || '/';
73
- }
74
- catch {
75
- return true;
76
- }
77
- if (!this.cache.has(origin)) {
78
- try {
79
- const res = await fetch(`${origin}/robots.txt`, {
80
- headers: { 'User-Agent': userAgent },
81
- signal: AbortSignal.timeout(5_000),
82
- });
83
- this.cache.set(origin, res.ok ? parseRobots(await res.text()) : []);
84
- }
85
- catch {
86
- this.cache.set(origin, []); // network error or timeout = no restrictions
87
- }
88
- }
89
- return isAllowedByRules(this.cache.get(origin), userAgent, pathname);
48
+ class RobotsCache {
49
+ cache = /* @__PURE__ */ new Map();
50
+ async isAllowed(url, userAgent = "ZeTa-Crawler") {
51
+ let origin;
52
+ let pathname;
53
+ try {
54
+ const u = new URL(url);
55
+ origin = u.origin;
56
+ pathname = u.pathname || "/";
57
+ } catch {
58
+ return true;
59
+ }
60
+ if (!this.cache.has(origin)) {
61
+ try {
62
+ const res = await fetch(`${origin}/robots.txt`, {
63
+ headers: { "User-Agent": userAgent },
64
+ signal: AbortSignal.timeout(5e3)
65
+ });
66
+ this.cache.set(origin, res.ok ? parseRobots(await res.text()) : []);
67
+ } catch {
68
+ this.cache.set(origin, []);
69
+ }
90
70
  }
71
+ return isAllowedByRules(this.cache.get(origin), userAgent, pathname);
72
+ }
91
73
  }
74
+ export {
75
+ RobotsCache
76
+ };
77
+ //# sourceMappingURL=robots-txt.js.map