@crawlith/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/analysis/analyze.d.ts +70 -0
- package/dist/analysis/analyze.js +436 -0
- package/dist/analysis/content.d.ts +12 -0
- package/dist/analysis/content.js +33 -0
- package/dist/analysis/images.d.ts +6 -0
- package/dist/analysis/images.js +18 -0
- package/dist/analysis/links.d.ts +7 -0
- package/dist/analysis/links.js +30 -0
- package/dist/analysis/scoring.d.ts +9 -0
- package/dist/analysis/scoring.js +42 -0
- package/dist/analysis/seo.d.ts +15 -0
- package/dist/analysis/seo.js +64 -0
- package/dist/analysis/structuredData.d.ts +6 -0
- package/dist/analysis/structuredData.js +51 -0
- package/dist/audit/dns.d.ts +2 -0
- package/dist/audit/dns.js +42 -0
- package/dist/audit/headers.d.ts +2 -0
- package/dist/audit/headers.js +95 -0
- package/dist/audit/index.d.ts +2 -0
- package/dist/audit/index.js +50 -0
- package/dist/audit/scoring.d.ts +14 -0
- package/dist/audit/scoring.js +214 -0
- package/dist/audit/transport.d.ts +6 -0
- package/dist/audit/transport.js +207 -0
- package/dist/audit/types.d.ts +88 -0
- package/dist/audit/types.js +1 -0
- package/dist/core/network/proxyAdapter.d.ts +6 -0
- package/dist/core/network/proxyAdapter.js +19 -0
- package/dist/core/network/rateLimiter.d.ts +6 -0
- package/dist/core/network/rateLimiter.js +31 -0
- package/dist/core/network/redirectController.d.ts +13 -0
- package/dist/core/network/redirectController.js +41 -0
- package/dist/core/network/responseLimiter.d.ts +4 -0
- package/dist/core/network/responseLimiter.js +26 -0
- package/dist/core/network/retryPolicy.d.ts +10 -0
- package/dist/core/network/retryPolicy.js +41 -0
- package/dist/core/scope/domainFilter.d.ts +11 -0
- package/dist/core/scope/domainFilter.js +40 -0
- package/dist/core/scope/scopeManager.d.ts +14 -0
- package/dist/core/scope/scopeManager.js +39 -0
- package/dist/core/scope/subdomainPolicy.d.ts +6 -0
- package/dist/core/scope/subdomainPolicy.js +35 -0
- package/dist/core/security/ipGuard.d.ts +11 -0
- package/dist/core/security/ipGuard.js +84 -0
- package/dist/crawler/crawl.d.ts +22 -0
- package/dist/crawler/crawl.js +336 -0
- package/dist/crawler/extract.d.ts +5 -0
- package/dist/crawler/extract.js +33 -0
- package/dist/crawler/fetcher.d.ts +40 -0
- package/dist/crawler/fetcher.js +161 -0
- package/dist/crawler/metricsRunner.d.ts +1 -0
- package/dist/crawler/metricsRunner.js +108 -0
- package/dist/crawler/normalize.d.ts +7 -0
- package/dist/crawler/normalize.js +88 -0
- package/dist/crawler/parser.d.ts +22 -0
- package/dist/crawler/parser.js +158 -0
- package/dist/crawler/sitemap.d.ts +8 -0
- package/dist/crawler/sitemap.js +70 -0
- package/dist/crawler/trap.d.ts +24 -0
- package/dist/crawler/trap.js +78 -0
- package/dist/db/graphLoader.d.ts +2 -0
- package/dist/db/graphLoader.js +96 -0
- package/dist/db/index.d.ts +4 -0
- package/dist/db/index.js +61 -0
- package/dist/db/repositories/EdgeRepository.d.ts +16 -0
- package/dist/db/repositories/EdgeRepository.js +17 -0
- package/dist/db/repositories/MetricsRepository.d.ts +26 -0
- package/dist/db/repositories/MetricsRepository.js +27 -0
- package/dist/db/repositories/PageRepository.d.ts +47 -0
- package/dist/db/repositories/PageRepository.js +93 -0
- package/dist/db/repositories/SiteRepository.d.ts +15 -0
- package/dist/db/repositories/SiteRepository.js +22 -0
- package/dist/db/repositories/SnapshotRepository.d.ts +22 -0
- package/dist/db/repositories/SnapshotRepository.js +55 -0
- package/dist/db/schema.d.ts +2 -0
- package/dist/db/schema.js +169 -0
- package/dist/diff/compare.d.ts +26 -0
- package/dist/diff/compare.js +64 -0
- package/dist/graph/cluster.d.ts +6 -0
- package/dist/graph/cluster.js +173 -0
- package/dist/graph/duplicate.d.ts +10 -0
- package/dist/graph/duplicate.js +251 -0
- package/dist/graph/graph.d.ts +103 -0
- package/dist/graph/graph.js +106 -0
- package/dist/graph/metrics.d.ts +29 -0
- package/dist/graph/metrics.js +74 -0
- package/dist/graph/pagerank.d.ts +12 -0
- package/dist/graph/pagerank.js +102 -0
- package/dist/graph/simhash.d.ts +17 -0
- package/dist/graph/simhash.js +56 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +30 -0
- package/dist/lock/hashKey.d.ts +1 -0
- package/dist/lock/hashKey.js +44 -0
- package/dist/lock/lockManager.d.ts +7 -0
- package/dist/lock/lockManager.js +112 -0
- package/dist/lock/pidCheck.d.ts +1 -0
- package/dist/lock/pidCheck.js +14 -0
- package/dist/report/html.d.ts +2 -0
- package/dist/report/html.js +223 -0
- package/dist/report/sitegraphExport.d.ts +3 -0
- package/dist/report/sitegraphExport.js +52 -0
- package/dist/report/sitegraph_template.d.ts +1 -0
- package/dist/report/sitegraph_template.js +630 -0
- package/dist/scoring/hits.d.ts +9 -0
- package/dist/scoring/hits.js +111 -0
- package/dist/scoring/orphanSeverity.d.ts +39 -0
- package/dist/scoring/orphanSeverity.js +125 -0
- package/dist/utils/version.d.ts +2 -0
- package/dist/utils/version.js +15 -0
- package/package.json +33 -0
- package/src/analysis/analyze.ts +548 -0
- package/src/analysis/content.ts +62 -0
- package/src/analysis/images.ts +28 -0
- package/src/analysis/links.ts +41 -0
- package/src/analysis/scoring.ts +59 -0
- package/src/analysis/seo.ts +82 -0
- package/src/analysis/structuredData.ts +62 -0
- package/src/audit/dns.ts +49 -0
- package/src/audit/headers.ts +98 -0
- package/src/audit/index.ts +66 -0
- package/src/audit/scoring.ts +232 -0
- package/src/audit/transport.ts +258 -0
- package/src/audit/types.ts +102 -0
- package/src/core/network/proxyAdapter.ts +21 -0
- package/src/core/network/rateLimiter.ts +39 -0
- package/src/core/network/redirectController.ts +47 -0
- package/src/core/network/responseLimiter.ts +34 -0
- package/src/core/network/retryPolicy.ts +57 -0
- package/src/core/scope/domainFilter.ts +45 -0
- package/src/core/scope/scopeManager.ts +52 -0
- package/src/core/scope/subdomainPolicy.ts +39 -0
- package/src/core/security/ipGuard.ts +92 -0
- package/src/crawler/crawl.ts +382 -0
- package/src/crawler/extract.ts +34 -0
- package/src/crawler/fetcher.ts +233 -0
- package/src/crawler/metricsRunner.ts +124 -0
- package/src/crawler/normalize.ts +108 -0
- package/src/crawler/parser.ts +190 -0
- package/src/crawler/sitemap.ts +73 -0
- package/src/crawler/trap.ts +96 -0
- package/src/db/graphLoader.ts +105 -0
- package/src/db/index.ts +70 -0
- package/src/db/repositories/EdgeRepository.ts +29 -0
- package/src/db/repositories/MetricsRepository.ts +49 -0
- package/src/db/repositories/PageRepository.ts +128 -0
- package/src/db/repositories/SiteRepository.ts +32 -0
- package/src/db/repositories/SnapshotRepository.ts +74 -0
- package/src/db/schema.ts +177 -0
- package/src/diff/compare.ts +84 -0
- package/src/graph/cluster.ts +192 -0
- package/src/graph/duplicate.ts +286 -0
- package/src/graph/graph.ts +172 -0
- package/src/graph/metrics.ts +110 -0
- package/src/graph/pagerank.ts +125 -0
- package/src/graph/simhash.ts +61 -0
- package/src/index.ts +30 -0
- package/src/lock/hashKey.ts +51 -0
- package/src/lock/lockManager.ts +124 -0
- package/src/lock/pidCheck.ts +13 -0
- package/src/report/html.ts +227 -0
- package/src/report/sitegraphExport.ts +58 -0
- package/src/report/sitegraph_template.ts +630 -0
- package/src/scoring/hits.ts +131 -0
- package/src/scoring/orphanSeverity.ts +176 -0
- package/src/utils/version.ts +18 -0
- package/tests/__snapshots__/orphanSeverity.test.ts.snap +49 -0
- package/tests/analysis.unit.test.ts +98 -0
- package/tests/analyze.integration.test.ts +98 -0
- package/tests/audit/dns.test.ts +31 -0
- package/tests/audit/headers.test.ts +45 -0
- package/tests/audit/scoring.test.ts +133 -0
- package/tests/audit/security.test.ts +12 -0
- package/tests/audit/transport.test.ts +112 -0
- package/tests/clustering.test.ts +118 -0
- package/tests/crawler.test.ts +358 -0
- package/tests/db.test.ts +159 -0
- package/tests/diff.test.ts +67 -0
- package/tests/duplicate.test.ts +110 -0
- package/tests/fetcher.test.ts +106 -0
- package/tests/fetcher_safety.test.ts +85 -0
- package/tests/fixtures/analyze-crawl.json +26 -0
- package/tests/hits.test.ts +134 -0
- package/tests/html_report.test.ts +58 -0
- package/tests/lock/lockManager.test.ts +138 -0
- package/tests/metrics.test.ts +196 -0
- package/tests/normalize.test.ts +101 -0
- package/tests/orphanSeverity.test.ts +160 -0
- package/tests/pagerank.test.ts +98 -0
- package/tests/parser.test.ts +117 -0
- package/tests/proxy_safety.test.ts +57 -0
- package/tests/redirect_safety.test.ts +73 -0
- package/tests/safety.test.ts +114 -0
- package/tests/scope.test.ts +66 -0
- package/tests/scoring.test.ts +59 -0
- package/tests/sitemap.test.ts +88 -0
- package/tests/soft404.test.ts +41 -0
- package/tests/trap.test.ts +39 -0
- package/tests/visualization_data.test.ts +46 -0
- package/tsconfig.json +11 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import * as dns from 'dns';
|
|
2
|
+
import * as net from 'net';
|
|
3
|
+
import { promisify } from 'util';
|
|
4
|
+
|
|
5
|
+
const resolve4 = promisify(dns.resolve4);
|
|
6
|
+
const resolve6 = promisify(dns.resolve6);
|
|
7
|
+
|
|
8
|
+
export class IPGuard {
|
|
9
|
+
/**
|
|
10
|
+
* Checks if an IP address is internal/private
|
|
11
|
+
*/
|
|
12
|
+
static isInternal(ip: string): boolean {
|
|
13
|
+
if (net.isIPv4(ip)) {
|
|
14
|
+
const parts = ip.split('.').map(Number);
|
|
15
|
+
|
|
16
|
+
// 127.0.0.0/8
|
|
17
|
+
if (parts[0] === 127) return true;
|
|
18
|
+
|
|
19
|
+
// 10.0.0.0/8
|
|
20
|
+
if (parts[0] === 10) return true;
|
|
21
|
+
|
|
22
|
+
// 192.168.0.0/16
|
|
23
|
+
if (parts[0] === 192 && parts[1] === 168) return true;
|
|
24
|
+
|
|
25
|
+
// 172.16.0.0 – 172.31.255.255
|
|
26
|
+
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
|
|
27
|
+
|
|
28
|
+
// 169.254.0.0/16
|
|
29
|
+
if (parts[0] === 169 && parts[1] === 254) return true;
|
|
30
|
+
|
|
31
|
+
// 0.0.0.0/8
|
|
32
|
+
if (parts[0] === 0) return true;
|
|
33
|
+
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (net.isIPv6(ip)) {
|
|
38
|
+
// Normalize IPv6
|
|
39
|
+
const expanded = IPGuard.expandIPv6(ip);
|
|
40
|
+
|
|
41
|
+
// ::1
|
|
42
|
+
if (expanded === '0000:0000:0000:0000:0000:0000:0000:0001') return true;
|
|
43
|
+
|
|
44
|
+
// fc00::/7 (Unique Local Address) -> fc or fd
|
|
45
|
+
const firstWord = parseInt(expanded.split(':')[0], 16);
|
|
46
|
+
if ((firstWord & 0xfe00) === 0xfc00) return true;
|
|
47
|
+
|
|
48
|
+
// fe80::/10 (Link Local)
|
|
49
|
+
if ((firstWord & 0xffc0) === 0xfe80) return true;
|
|
50
|
+
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return true; // Unknown format, block it for safety
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Resolves a hostname and validates all result IPs
|
|
59
|
+
*/
|
|
60
|
+
static async validateHost(host: string): Promise<boolean> {
|
|
61
|
+
if (net.isIP(host)) {
|
|
62
|
+
return !IPGuard.isInternal(host);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const res4 = await resolve4(host).catch(() => [] as string[]);
|
|
67
|
+
const res6 = await resolve6(host).catch(() => [] as string[]);
|
|
68
|
+
const ips = [...res4, ...res6];
|
|
69
|
+
|
|
70
|
+
if (ips.length === 0) return true; // Let the fetcher handle DNS failures
|
|
71
|
+
|
|
72
|
+
return ips.every(ip => !IPGuard.isInternal(ip));
|
|
73
|
+
} catch (_e) {
|
|
74
|
+
// If resolution fails drastically, we block for safety or let fetcher try
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private static expandIPv6(ip: string): string {
|
|
80
|
+
if (ip === '::') return '0000:0000:0000:0000:0000:0000:0000:0000';
|
|
81
|
+
let full = ip;
|
|
82
|
+
if (ip.includes('::')) {
|
|
83
|
+
const parts = ip.split('::');
|
|
84
|
+
const left = parts[0].split(':').filter(x => x !== '');
|
|
85
|
+
const right = parts[1].split(':').filter(x => x !== '');
|
|
86
|
+
const missing = 8 - (left.length + right.length);
|
|
87
|
+
const middle = Array(missing).fill('0000');
|
|
88
|
+
full = [...left, ...middle, ...right].join(':');
|
|
89
|
+
}
|
|
90
|
+
return full.split(':').map(part => part.padStart(4, '0')).join(':');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { request } from 'undici';
|
|
2
|
+
import pLimit from 'p-limit';
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import robotsParser from 'robots-parser';
|
|
5
|
+
import { Graph } from '../graph/graph.js';
|
|
6
|
+
import { Fetcher } from './fetcher.js';
|
|
7
|
+
import { Parser } from './parser.js';
|
|
8
|
+
import { Sitemap } from './sitemap.js';
|
|
9
|
+
import { normalizeUrl } from './normalize.js';
|
|
10
|
+
import { TrapDetector } from './trap.js';
|
|
11
|
+
import { ScopeManager } from '../core/scope/scopeManager.js';
|
|
12
|
+
import { getDb } from '../db/index.js';
|
|
13
|
+
import { SiteRepository } from '../db/repositories/SiteRepository.js';
|
|
14
|
+
import { SnapshotRepository } from '../db/repositories/SnapshotRepository.js';
|
|
15
|
+
import { PageRepository } from '../db/repositories/PageRepository.js';
|
|
16
|
+
import { EdgeRepository } from '../db/repositories/EdgeRepository.js';
|
|
17
|
+
import { MetricsRepository } from '../db/repositories/MetricsRepository.js';
|
|
18
|
+
import { analyzeContent, calculateThinContentScore } from '../analysis/content.js';
|
|
19
|
+
import { analyzeLinks } from '../analysis/links.js';
|
|
20
|
+
|
|
21
|
+
export interface CrawlOptions {
|
|
22
|
+
limit: number;
|
|
23
|
+
depth: number;
|
|
24
|
+
concurrency?: number;
|
|
25
|
+
ignoreRobots?: boolean;
|
|
26
|
+
stripQuery?: boolean;
|
|
27
|
+
previousGraph?: Graph;
|
|
28
|
+
sitemap?: string;
|
|
29
|
+
debug?: boolean;
|
|
30
|
+
detectSoft404?: boolean;
|
|
31
|
+
detectTraps?: boolean;
|
|
32
|
+
rate?: number;
|
|
33
|
+
maxBytes?: number;
|
|
34
|
+
allowedDomains?: string[];
|
|
35
|
+
deniedDomains?: string[];
|
|
36
|
+
includeSubdomains?: boolean;
|
|
37
|
+
proxyUrl?: string;
|
|
38
|
+
maxRedirects?: number;
|
|
39
|
+
userAgent?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface QueueItem {
|
|
43
|
+
url: string;
|
|
44
|
+
depth: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function crawl(startUrl: string, options: CrawlOptions): Promise<number> {
|
|
48
|
+
const visited = new Set<string>();
|
|
49
|
+
const concurrency = Math.min(options.concurrency || 2, 10);
|
|
50
|
+
const limitConcurrency = pLimit(concurrency);
|
|
51
|
+
const trapDetector = new TrapDetector();
|
|
52
|
+
|
|
53
|
+
const db = getDb();
|
|
54
|
+
const siteRepo = new SiteRepository(db);
|
|
55
|
+
const snapshotRepo = new SnapshotRepository(db);
|
|
56
|
+
const pageRepo = new PageRepository(db);
|
|
57
|
+
const edgeRepo = new EdgeRepository(db);
|
|
58
|
+
const metricsRepo = new MetricsRepository(db);
|
|
59
|
+
|
|
60
|
+
const rootUrl = normalizeUrl(startUrl, '', { stripQuery: options.stripQuery });
|
|
61
|
+
if (!rootUrl) throw new Error('Invalid start URL');
|
|
62
|
+
|
|
63
|
+
const urlObj = new URL(rootUrl);
|
|
64
|
+
const domain = urlObj.hostname.replace('www.', '');
|
|
65
|
+
const site = siteRepo.firstOrCreateSite(domain);
|
|
66
|
+
const siteId = site.id;
|
|
67
|
+
|
|
68
|
+
const snapshotId = snapshotRepo.createSnapshot(siteId, options.previousGraph ? 'incremental' : 'full');
|
|
69
|
+
const rootOrigin = urlObj.origin;
|
|
70
|
+
|
|
71
|
+
// DB Helper
|
|
72
|
+
const savePageToDb = (url: string, depth: number, status: number, data: any = {}): number | null => {
|
|
73
|
+
try {
|
|
74
|
+
const existing = pageRepo.getPage(siteId!, url);
|
|
75
|
+
const isSameSnapshot = existing?.last_seen_snapshot_id === snapshotId;
|
|
76
|
+
|
|
77
|
+
return pageRepo.upsertAndGetId({
|
|
78
|
+
site_id: siteId!,
|
|
79
|
+
normalized_url: url,
|
|
80
|
+
depth: isSameSnapshot ? existing.depth : depth,
|
|
81
|
+
http_status: status,
|
|
82
|
+
first_seen_snapshot_id: existing ? existing.first_seen_snapshot_id : snapshotId,
|
|
83
|
+
last_seen_snapshot_id: snapshotId,
|
|
84
|
+
canonical_url: data.canonical !== undefined ? data.canonical : existing?.canonical_url,
|
|
85
|
+
content_hash: data.contentHash !== undefined ? data.contentHash : existing?.content_hash,
|
|
86
|
+
simhash: data.simhash !== undefined ? data.simhash : existing?.simhash,
|
|
87
|
+
etag: data.etag !== undefined ? data.etag : existing?.etag,
|
|
88
|
+
last_modified: data.lastModified !== undefined ? data.lastModified : existing?.last_modified,
|
|
89
|
+
html: data.html !== undefined ? data.html : existing?.html,
|
|
90
|
+
soft404_score: data.soft404Score !== undefined ? data.soft404Score : existing?.soft404_score,
|
|
91
|
+
noindex: data.noindex !== undefined ? (data.noindex ? 1 : 0) : existing?.noindex,
|
|
92
|
+
nofollow: data.nofollow !== undefined ? (data.nofollow ? 1 : 0) : existing?.nofollow,
|
|
93
|
+
security_error: data.securityError !== undefined ? data.securityError : existing?.security_error,
|
|
94
|
+
retries: data.retries !== undefined ? data.retries : existing?.retries
|
|
95
|
+
});
|
|
96
|
+
} catch (e) {
|
|
97
|
+
console.error(`Failed to save page ${url}:`, e);
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const saveEdgeToDb = (sourceUrl: string, targetUrl: string, weight: number = 1.0, rel: string = 'internal') => {
|
|
103
|
+
try {
|
|
104
|
+
const sourceId = pageRepo.getIdByUrl(siteId!, sourceUrl);
|
|
105
|
+
const targetId = pageRepo.getIdByUrl(siteId!, targetUrl);
|
|
106
|
+
if (sourceId && targetId) {
|
|
107
|
+
edgeRepo.insertEdge(snapshotId, sourceId, targetId, weight, rel);
|
|
108
|
+
}
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.error(`Failed to save edge ${sourceUrl} -> ${targetUrl}:`, e);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// Initialize Modules
|
|
115
|
+
const scopeManager = new ScopeManager({
|
|
116
|
+
allowedDomains: options.allowedDomains || [],
|
|
117
|
+
deniedDomains: options.deniedDomains || [],
|
|
118
|
+
includeSubdomains: options.includeSubdomains || false,
|
|
119
|
+
rootUrl: startUrl
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const fetcher = new Fetcher({
|
|
123
|
+
rate: options.rate,
|
|
124
|
+
proxyUrl: options.proxyUrl,
|
|
125
|
+
scopeManager,
|
|
126
|
+
maxRedirects: options.maxRedirects,
|
|
127
|
+
userAgent: options.userAgent
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
const parser = new Parser();
|
|
131
|
+
const sitemapFetcher = new Sitemap();
|
|
132
|
+
|
|
133
|
+
// Handle robots.txt
|
|
134
|
+
let robots: any = null;
|
|
135
|
+
if (!options.ignoreRobots) {
|
|
136
|
+
try {
|
|
137
|
+
const robotsUrl = new URL('/robots.txt', rootOrigin).toString();
|
|
138
|
+
const res = await request(robotsUrl, {
|
|
139
|
+
maxRedirections: 3,
|
|
140
|
+
headers: { 'User-Agent': 'crawlith/1.0' },
|
|
141
|
+
headersTimeout: 5000,
|
|
142
|
+
bodyTimeout: 5000
|
|
143
|
+
});
|
|
144
|
+
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
145
|
+
const txt = await res.body.text();
|
|
146
|
+
robots = (robotsParser as any)(robotsUrl, txt);
|
|
147
|
+
} else {
|
|
148
|
+
await res.body.dump();
|
|
149
|
+
}
|
|
150
|
+
} catch {
|
|
151
|
+
console.warn('Failed to fetch robots.txt, proceeding...');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Queue Setup
|
|
156
|
+
const queue: QueueItem[] = [];
|
|
157
|
+
const uniqueQueue = new Set<string>();
|
|
158
|
+
|
|
159
|
+
const addToQueue = (u: string, d: number) => {
|
|
160
|
+
if (scopeManager.isUrlEligible(u) !== 'allowed') return;
|
|
161
|
+
if (!uniqueQueue.has(u)) {
|
|
162
|
+
uniqueQueue.add(u);
|
|
163
|
+
queue.push({ url: u, depth: d });
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// Seed from Sitemap
|
|
168
|
+
if (options.sitemap) {
|
|
169
|
+
try {
|
|
170
|
+
const sitemapUrl = options.sitemap === 'true' ? new URL('/sitemap.xml', rootOrigin).toString() : options.sitemap;
|
|
171
|
+
if (sitemapUrl.startsWith('http')) {
|
|
172
|
+
console.log(`Fetching sitemap: ${sitemapUrl}`);
|
|
173
|
+
const sitemapUrls = await sitemapFetcher.fetch(sitemapUrl);
|
|
174
|
+
for (const u of sitemapUrls) {
|
|
175
|
+
const normalized = normalizeUrl(u, '', options);
|
|
176
|
+
if (normalized) addToQueue(normalized, 0);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} catch (e) {
|
|
180
|
+
console.warn('Sitemap fetch failed', e);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Seed from startUrl
|
|
185
|
+
addToQueue(rootUrl, 0);
|
|
186
|
+
|
|
187
|
+
let pagesCrawled = 0;
|
|
188
|
+
let active = 0;
|
|
189
|
+
let reachedLimit = false;
|
|
190
|
+
const maxDepthInCrawl = Math.min(options.depth, 10);
|
|
191
|
+
|
|
192
|
+
const shouldEnqueue = (url: string, depth: number) => {
|
|
193
|
+
if (visited.has(url)) return false;
|
|
194
|
+
if (uniqueQueue.has(url)) return false;
|
|
195
|
+
if (depth > maxDepthInCrawl) return false;
|
|
196
|
+
if (scopeManager.isUrlEligible(url) !== 'allowed') return false;
|
|
197
|
+
|
|
198
|
+
if (options.detectTraps) {
|
|
199
|
+
const trap = trapDetector.checkTrap(url, depth);
|
|
200
|
+
if (trap.risk > 0.8) return false;
|
|
201
|
+
}
|
|
202
|
+
return true;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
return new Promise((resolve) => {
|
|
206
|
+
const checkDone = () => {
|
|
207
|
+
if (queue.length === 0 && active === 0) {
|
|
208
|
+
snapshotRepo.updateSnapshotStatus(snapshotId, 'completed', {
|
|
209
|
+
limit_reached: reachedLimit ? 1 : 0
|
|
210
|
+
});
|
|
211
|
+
resolve(snapshotId);
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
return false;
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const next = () => {
|
|
218
|
+
if (checkDone()) return;
|
|
219
|
+
if (pagesCrawled >= options.limit) {
|
|
220
|
+
reachedLimit = true;
|
|
221
|
+
if (active === 0) {
|
|
222
|
+
snapshotRepo.updateSnapshotStatus(snapshotId, 'completed', {
|
|
223
|
+
limit_reached: 1
|
|
224
|
+
});
|
|
225
|
+
resolve(snapshotId);
|
|
226
|
+
}
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
while (queue.length > 0 && active < concurrency && pagesCrawled < options.limit) {
|
|
231
|
+
const item = queue.shift()!;
|
|
232
|
+
if (visited.has(item.url)) continue;
|
|
233
|
+
if (robots && !robots.isAllowed(item.url, 'crawlith')) continue;
|
|
234
|
+
|
|
235
|
+
active++;
|
|
236
|
+
pagesCrawled++;
|
|
237
|
+
visited.add(item.url);
|
|
238
|
+
|
|
239
|
+
limitConcurrency(() => processPage(item)).finally(() => {
|
|
240
|
+
active--;
|
|
241
|
+
next();
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const processPage = async (item: QueueItem) => {
|
|
247
|
+
const { url, depth } = item;
|
|
248
|
+
if (scopeManager.isUrlEligible(url) !== 'allowed') {
|
|
249
|
+
savePageToDb(url, depth, 0, { securityError: 'blocked_by_domain_filter' });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const existingInDb = pageRepo.getPage(siteId!, url);
|
|
254
|
+
savePageToDb(url, depth, 0);
|
|
255
|
+
|
|
256
|
+
try {
|
|
257
|
+
const res = await fetcher.fetch(url, {
|
|
258
|
+
etag: existingInDb?.etag || undefined,
|
|
259
|
+
lastModified: existingInDb?.last_modified || undefined,
|
|
260
|
+
maxBytes: options.maxBytes,
|
|
261
|
+
crawlDelay: robots ? robots.getCrawlDelay('crawlith') : undefined
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
if (options.debug) {
|
|
265
|
+
console.log(`${chalk.gray(`[D:${depth}]`)} ${res.status} ${chalk.blue(url)}`);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (res.status === 304) {
|
|
269
|
+
savePageToDb(url, depth, 304);
|
|
270
|
+
metricsRepo.insertMetrics({
|
|
271
|
+
snapshot_id: snapshotId,
|
|
272
|
+
page_id: existingInDb!.id,
|
|
273
|
+
authority_score: null,
|
|
274
|
+
hub_score: null,
|
|
275
|
+
pagerank: null,
|
|
276
|
+
pagerank_score: null,
|
|
277
|
+
link_role: null,
|
|
278
|
+
crawl_status: 'cached',
|
|
279
|
+
word_count: null,
|
|
280
|
+
thin_content_score: null,
|
|
281
|
+
external_link_ratio: null,
|
|
282
|
+
orphan_score: null,
|
|
283
|
+
duplicate_cluster_id: null,
|
|
284
|
+
duplicate_type: null,
|
|
285
|
+
is_cluster_primary: 0
|
|
286
|
+
});
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const chain = res.redirectChain;
|
|
291
|
+
for (const step of chain) {
|
|
292
|
+
const source = normalizeUrl(step.url, '', options);
|
|
293
|
+
const target = normalizeUrl(step.target, '', options);
|
|
294
|
+
if (source && target) {
|
|
295
|
+
savePageToDb(source, depth, step.status);
|
|
296
|
+
savePageToDb(target, depth, 0);
|
|
297
|
+
saveEdgeToDb(source, target);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const finalUrl = normalizeUrl(res.finalUrl, '', options);
|
|
302
|
+
if (!finalUrl) return;
|
|
303
|
+
|
|
304
|
+
const isStringStatus = typeof res.status === 'string';
|
|
305
|
+
if (isStringStatus || (typeof res.status === 'number' && res.status >= 300)) {
|
|
306
|
+
savePageToDb(finalUrl, depth, typeof res.status === 'number' ? res.status : 0, {
|
|
307
|
+
securityError: isStringStatus ? res.status : undefined,
|
|
308
|
+
retries: res.retries
|
|
309
|
+
});
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (res.status === 200) {
|
|
314
|
+
const contentTypeHeader = res.headers['content-type'];
|
|
315
|
+
const contentType = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : (contentTypeHeader || '');
|
|
316
|
+
if (!contentType || !contentType.toLowerCase().includes('text/html')) {
|
|
317
|
+
savePageToDb(finalUrl, depth, res.status);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
savePageToDb(finalUrl, depth, res.status);
|
|
322
|
+
const parseResult = parser.parse(res.body, finalUrl, res.status);
|
|
323
|
+
|
|
324
|
+
const pageId = savePageToDb(finalUrl, depth, res.status, {
|
|
325
|
+
html: parseResult.html,
|
|
326
|
+
canonical: parseResult.canonical || undefined,
|
|
327
|
+
noindex: parseResult.noindex,
|
|
328
|
+
nofollow: parseResult.nofollow,
|
|
329
|
+
contentHash: parseResult.contentHash,
|
|
330
|
+
simhash: parseResult.simhash,
|
|
331
|
+
soft404Score: parseResult.soft404Score,
|
|
332
|
+
etag: res.etag,
|
|
333
|
+
lastModified: res.lastModified,
|
|
334
|
+
retries: res.retries
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
if (pageId) {
|
|
338
|
+
try {
|
|
339
|
+
const contentAnalysis = analyzeContent(parseResult.html);
|
|
340
|
+
const linkAnalysis = analyzeLinks(parseResult.html, finalUrl, rootOrigin);
|
|
341
|
+
const thinScore = calculateThinContentScore(contentAnalysis, 0);
|
|
342
|
+
|
|
343
|
+
metricsRepo.insertMetrics({
|
|
344
|
+
snapshot_id: snapshotId,
|
|
345
|
+
page_id: pageId,
|
|
346
|
+
authority_score: null,
|
|
347
|
+
hub_score: null,
|
|
348
|
+
pagerank: null,
|
|
349
|
+
pagerank_score: null,
|
|
350
|
+
link_role: null,
|
|
351
|
+
crawl_status: 'fetched',
|
|
352
|
+
word_count: contentAnalysis.wordCount,
|
|
353
|
+
thin_content_score: thinScore,
|
|
354
|
+
external_link_ratio: linkAnalysis.externalRatio,
|
|
355
|
+
orphan_score: null,
|
|
356
|
+
duplicate_cluster_id: null,
|
|
357
|
+
duplicate_type: null,
|
|
358
|
+
is_cluster_primary: 0
|
|
359
|
+
});
|
|
360
|
+
} catch (e) {
|
|
361
|
+
console.error(`Error calculating per-page metrics for ${finalUrl}:`, e);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
for (const linkItem of parseResult.links) {
|
|
366
|
+
const normalizedLink = normalizeUrl(linkItem.url, '', options);
|
|
367
|
+
if (normalizedLink && normalizedLink !== finalUrl) {
|
|
368
|
+
savePageToDb(normalizedLink, depth + 1, 0);
|
|
369
|
+
saveEdgeToDb(finalUrl, normalizedLink, 1.0, 'internal');
|
|
370
|
+
if (shouldEnqueue(normalizedLink, depth + 1)) {
|
|
371
|
+
addToQueue(normalizedLink, depth + 1);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
} catch (e) {
|
|
377
|
+
console.error(`Error processing ${url}:`, e);
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
next();
|
|
381
|
+
});
|
|
382
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as cheerio from 'cheerio';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Extracts all links from an HTML document.
|
|
5
|
+
* Returns absolute URLs.
|
|
6
|
+
*/
|
|
7
|
+
export function extractLinks(html: string, baseUrl: string): string[] {
|
|
8
|
+
try {
|
|
9
|
+
const $ = cheerio.load(html);
|
|
10
|
+
const links = new Set<string>();
|
|
11
|
+
|
|
12
|
+
$('a').each((_, element) => {
|
|
13
|
+
const href = $(element).attr('href');
|
|
14
|
+
if (href) {
|
|
15
|
+
try {
|
|
16
|
+
const absoluteUrl = new URL(href, baseUrl);
|
|
17
|
+
// Only http(s) links
|
|
18
|
+
if (absoluteUrl.protocol === 'http:' || absoluteUrl.protocol === 'https:') {
|
|
19
|
+
// Remove hash fragments immediately as they are irrelevant for crawling
|
|
20
|
+
absoluteUrl.hash = '';
|
|
21
|
+
links.add(absoluteUrl.toString());
|
|
22
|
+
}
|
|
23
|
+
} catch (_e) {
|
|
24
|
+
// Invalid URL, skip
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
return Array.from(links);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
console.error(`Error extracting links from ${baseUrl}:`, e);
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
}
|