@crawlith/core 0.1.0 → 0.1.1

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 (131) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/analysis/analysis_list.html +35 -0
  3. package/dist/analysis/analysis_page.html +123 -0
  4. package/dist/analysis/analyze.d.ts +17 -3
  5. package/dist/analysis/analyze.js +192 -248
  6. package/dist/analysis/scoring.js +7 -1
  7. package/dist/analysis/templates.d.ts +2 -0
  8. package/dist/analysis/templates.js +7 -0
  9. package/dist/core/security/ipGuard.d.ts +11 -0
  10. package/dist/core/security/ipGuard.js +71 -3
  11. package/dist/crawler/crawl.d.ts +4 -22
  12. package/dist/crawler/crawl.js +4 -335
  13. package/dist/crawler/crawler.d.ts +75 -0
  14. package/dist/crawler/crawler.js +518 -0
  15. package/dist/crawler/extract.d.ts +4 -1
  16. package/dist/crawler/extract.js +7 -2
  17. package/dist/crawler/fetcher.d.ts +1 -0
  18. package/dist/crawler/fetcher.js +20 -5
  19. package/dist/crawler/metricsRunner.d.ts +3 -1
  20. package/dist/crawler/metricsRunner.js +55 -46
  21. package/dist/crawler/sitemap.d.ts +3 -0
  22. package/dist/crawler/sitemap.js +5 -1
  23. package/dist/db/graphLoader.js +32 -3
  24. package/dist/db/index.d.ts +3 -0
  25. package/dist/db/index.js +4 -0
  26. package/dist/db/repositories/EdgeRepository.d.ts +8 -0
  27. package/dist/db/repositories/EdgeRepository.js +13 -0
  28. package/dist/db/repositories/MetricsRepository.d.ts +3 -0
  29. package/dist/db/repositories/MetricsRepository.js +14 -1
  30. package/dist/db/repositories/PageRepository.d.ts +11 -0
  31. package/dist/db/repositories/PageRepository.js +112 -19
  32. package/dist/db/repositories/SiteRepository.d.ts +3 -0
  33. package/dist/db/repositories/SiteRepository.js +9 -0
  34. package/dist/db/repositories/SnapshotRepository.d.ts +2 -0
  35. package/dist/db/repositories/SnapshotRepository.js +23 -2
  36. package/dist/events.d.ts +48 -0
  37. package/dist/events.js +1 -0
  38. package/dist/graph/cluster.js +62 -14
  39. package/dist/graph/duplicate.js +242 -191
  40. package/dist/graph/graph.d.ts +16 -0
  41. package/dist/graph/graph.js +17 -4
  42. package/dist/graph/metrics.js +12 -0
  43. package/dist/graph/pagerank.js +2 -0
  44. package/dist/graph/simhash.d.ts +6 -0
  45. package/dist/graph/simhash.js +14 -0
  46. package/dist/index.d.ts +5 -2
  47. package/dist/index.js +5 -2
  48. package/dist/lock/hashKey.js +1 -1
  49. package/dist/lock/lockManager.d.ts +4 -1
  50. package/dist/lock/lockManager.js +23 -13
  51. package/{src/report/sitegraph_template.ts → dist/report/crawl.html} +330 -81
  52. package/dist/report/crawlExport.d.ts +3 -0
  53. package/dist/report/{sitegraphExport.js → crawlExport.js} +3 -3
  54. package/dist/report/crawl_template.d.ts +1 -0
  55. package/dist/report/crawl_template.js +7 -0
  56. package/dist/report/html.js +15 -216
  57. package/dist/scoring/health.d.ts +50 -0
  58. package/dist/scoring/health.js +170 -0
  59. package/dist/scoring/hits.d.ts +1 -0
  60. package/dist/scoring/hits.js +64 -44
  61. package/dist/scoring/orphanSeverity.d.ts +5 -5
  62. package/package.json +3 -3
  63. package/scripts/copy-assets.js +37 -0
  64. package/src/analysis/analysis_list.html +35 -0
  65. package/src/analysis/analysis_page.html +123 -0
  66. package/src/analysis/analyze.ts +218 -261
  67. package/src/analysis/scoring.ts +8 -1
  68. package/src/analysis/templates.ts +9 -0
  69. package/src/core/security/ipGuard.ts +82 -3
  70. package/src/crawler/crawl.ts +6 -379
  71. package/src/crawler/crawler.ts +601 -0
  72. package/src/crawler/extract.ts +7 -2
  73. package/src/crawler/fetcher.ts +24 -6
  74. package/src/crawler/metricsRunner.ts +60 -47
  75. package/src/crawler/sitemap.ts +4 -1
  76. package/src/db/graphLoader.ts +33 -3
  77. package/src/db/index.ts +5 -0
  78. package/src/db/repositories/EdgeRepository.ts +14 -0
  79. package/src/db/repositories/MetricsRepository.ts +15 -1
  80. package/src/db/repositories/PageRepository.ts +119 -19
  81. package/src/db/repositories/SiteRepository.ts +11 -0
  82. package/src/db/repositories/SnapshotRepository.ts +28 -3
  83. package/src/events.ts +16 -0
  84. package/src/graph/cluster.ts +69 -15
  85. package/src/graph/duplicate.ts +249 -185
  86. package/src/graph/graph.ts +24 -4
  87. package/src/graph/metrics.ts +15 -0
  88. package/src/graph/pagerank.ts +1 -0
  89. package/src/graph/simhash.ts +15 -0
  90. package/src/index.ts +5 -2
  91. package/src/lock/hashKey.ts +1 -1
  92. package/src/lock/lockManager.ts +21 -13
  93. package/{dist/report/sitegraph_template.js → src/report/crawl.html} +330 -81
  94. package/src/report/{sitegraphExport.ts → crawlExport.ts} +3 -3
  95. package/src/report/crawl_template.ts +9 -0
  96. package/src/report/html.ts +17 -217
  97. package/src/scoring/health.ts +241 -0
  98. package/src/scoring/hits.ts +67 -45
  99. package/src/scoring/orphanSeverity.ts +8 -8
  100. package/tests/analysis.unit.test.ts +44 -0
  101. package/tests/analyze.integration.test.ts +88 -53
  102. package/tests/analyze_markdown.test.ts +98 -0
  103. package/tests/audit/audit.test.ts +101 -0
  104. package/tests/audit/scoring.test.ts +25 -25
  105. package/tests/audit/transport.test.ts +0 -1
  106. package/tests/clustering_risk.test.ts +118 -0
  107. package/tests/crawler.test.ts +19 -13
  108. package/tests/db/index.test.ts +134 -0
  109. package/tests/db/repositories.test.ts +115 -0
  110. package/tests/db_repos.test.ts +72 -0
  111. package/tests/duplicate.test.ts +2 -2
  112. package/tests/extract.test.ts +86 -0
  113. package/tests/fetcher.test.ts +5 -1
  114. package/tests/fetcher_safety.test.ts +9 -3
  115. package/tests/graph/graph.test.ts +100 -0
  116. package/tests/graphLoader.test.ts +124 -0
  117. package/tests/html_report.test.ts +52 -51
  118. package/tests/ipGuard.test.ts +73 -0
  119. package/tests/lock/lockManager.test.ts +77 -17
  120. package/tests/normalize.test.ts +6 -19
  121. package/tests/orphanSeverity.test.ts +9 -9
  122. package/tests/redirect_safety.test.ts +5 -1
  123. package/tests/renderAnalysisCsv.test.ts +183 -0
  124. package/tests/safety.test.ts +12 -0
  125. package/tests/scope.test.ts +18 -0
  126. package/tests/scoring.test.ts +25 -24
  127. package/tests/sitemap.test.ts +13 -1
  128. package/tests/ssrf_fix.test.ts +69 -0
  129. package/tests/visualization_data.test.ts +10 -10
  130. package/dist/report/sitegraphExport.d.ts +0 -3
  131. package/dist/report/sitegraph_template.d.ts +0 -1
@@ -1,6 +1,7 @@
1
1
  import * as dns from 'dns';
2
2
  import * as net from 'net';
3
3
  import { promisify } from 'util';
4
+ import { Agent } from 'undici';
4
5
  const resolve4 = promisify(dns.resolve4);
5
6
  const resolve6 = promisify(dns.resolve6);
6
7
  export class IPGuard {
@@ -43,6 +44,14 @@ export class IPGuard {
43
44
  // fe80::/10 (Link Local)
44
45
  if ((firstWord & 0xffc0) === 0xfe80)
45
46
  return true;
47
+ // IPv4-mapped IPv6: ::ffff:0:0/96
48
+ if (expanded.startsWith('0000:0000:0000:0000:0000:ffff:')) {
49
+ const parts = expanded.split(':');
50
+ const p7 = parseInt(parts[6], 16);
51
+ const p8 = parseInt(parts[7], 16);
52
+ const ip4 = `${(p7 >> 8) & 255}.${p7 & 255}.${(p8 >> 8) & 255}.${p8 & 255}`;
53
+ return IPGuard.isInternal(ip4);
54
+ }
46
55
  return false;
47
56
  }
48
57
  return true; // Unknown format, block it for safety
@@ -67,12 +76,71 @@ export class IPGuard {
67
76
  return false;
68
77
  }
69
78
  }
79
+ /**
80
+ * Custom lookup function for undici that validates the resolved IP.
81
+ * Prevents DNS Rebinding attacks by checking the IP immediately before connection.
82
+ */
83
+ static secureLookup(hostname, options, callback) {
84
+ dns.lookup(hostname, options, (err, address, family) => {
85
+ if (err) {
86
+ return callback(err, address, family);
87
+ }
88
+ const checkIP = (ip) => {
89
+ if (IPGuard.isInternal(ip)) {
90
+ return new Error(`Blocked internal IP: ${ip}`);
91
+ }
92
+ return null;
93
+ };
94
+ if (typeof address === 'string') {
95
+ const error = checkIP(address);
96
+ if (error) {
97
+ // Return a custom error that undici will propagate
98
+ const blockedError = new Error(`Blocked internal IP: ${address}`);
99
+ blockedError.code = 'EBLOCKED';
100
+ return callback(blockedError, address, family);
101
+ }
102
+ }
103
+ else if (Array.isArray(address)) {
104
+ // Handle array of addresses (if options.all is true)
105
+ for (const addr of address) {
106
+ const error = checkIP(addr.address);
107
+ if (error) {
108
+ const blockedError = new Error(`Blocked internal IP: ${addr.address}`);
109
+ blockedError.code = 'EBLOCKED';
110
+ return callback(blockedError, address, family);
111
+ }
112
+ }
113
+ }
114
+ callback(null, address, family);
115
+ });
116
+ }
117
+ /**
118
+ * Returns an undici Agent configured with secure DNS lookup.
119
+ */
120
+ static getSecureDispatcher() {
121
+ return new Agent({
122
+ connect: {
123
+ lookup: IPGuard.secureLookup
124
+ }
125
+ });
126
+ }
70
127
  static expandIPv6(ip) {
71
128
  if (ip === '::')
72
129
  return '0000:0000:0000:0000:0000:0000:0000:0000';
73
- let full = ip;
74
- if (ip.includes('::')) {
75
- const parts = ip.split('::');
130
+ let normalizedIp = ip;
131
+ if (ip.includes('.')) {
132
+ const lastColonIndex = ip.lastIndexOf(':');
133
+ const lastPart = ip.substring(lastColonIndex + 1);
134
+ if (net.isIPv4(lastPart)) {
135
+ const parts = lastPart.split('.').map(Number);
136
+ const hex1 = ((parts[0] << 8) | parts[1]).toString(16);
137
+ const hex2 = ((parts[2] << 8) | parts[3]).toString(16);
138
+ normalizedIp = ip.substring(0, lastColonIndex + 1) + hex1 + ':' + hex2;
139
+ }
140
+ }
141
+ let full = normalizedIp;
142
+ if (normalizedIp.includes('::')) {
143
+ const parts = normalizedIp.split('::');
76
144
  const left = parts[0].split(':').filter(x => x !== '');
77
145
  const right = parts[1].split(':').filter(x => x !== '');
78
146
  const missing = 8 - (left.length + right.length);
@@ -1,22 +1,4 @@
1
- import { Graph } from '../graph/graph.js';
2
- export interface CrawlOptions {
3
- limit: number;
4
- depth: number;
5
- concurrency?: number;
6
- ignoreRobots?: boolean;
7
- stripQuery?: boolean;
8
- previousGraph?: Graph;
9
- sitemap?: string;
10
- debug?: boolean;
11
- detectSoft404?: boolean;
12
- detectTraps?: boolean;
13
- rate?: number;
14
- maxBytes?: number;
15
- allowedDomains?: string[];
16
- deniedDomains?: string[];
17
- includeSubdomains?: boolean;
18
- proxyUrl?: string;
19
- maxRedirects?: number;
20
- userAgent?: string;
21
- }
22
- export declare function crawl(startUrl: string, options: CrawlOptions): Promise<number>;
1
+ import { CrawlOptions } from './crawler.js';
2
+ import { EngineContext } from '../events.js';
3
+ export { CrawlOptions };
4
+ export declare function crawl(startUrl: string, options: CrawlOptions, context?: EngineContext): Promise<number>;
@@ -1,336 +1,5 @@
1
- import { request } from 'undici';
2
- import pLimit from 'p-limit';
3
- import chalk from 'chalk';
4
- import robotsParser from 'robots-parser';
5
- import { Fetcher } from './fetcher.js';
6
- import { Parser } from './parser.js';
7
- import { Sitemap } from './sitemap.js';
8
- import { normalizeUrl } from './normalize.js';
9
- import { TrapDetector } from './trap.js';
10
- import { ScopeManager } from '../core/scope/scopeManager.js';
11
- import { getDb } from '../db/index.js';
12
- import { SiteRepository } from '../db/repositories/SiteRepository.js';
13
- import { SnapshotRepository } from '../db/repositories/SnapshotRepository.js';
14
- import { PageRepository } from '../db/repositories/PageRepository.js';
15
- import { EdgeRepository } from '../db/repositories/EdgeRepository.js';
16
- import { MetricsRepository } from '../db/repositories/MetricsRepository.js';
17
- import { analyzeContent, calculateThinContentScore } from '../analysis/content.js';
18
- import { analyzeLinks } from '../analysis/links.js';
19
- export async function crawl(startUrl, options) {
20
- const visited = new Set();
21
- const concurrency = Math.min(options.concurrency || 2, 10);
22
- const limitConcurrency = pLimit(concurrency);
23
- const trapDetector = new TrapDetector();
24
- const db = getDb();
25
- const siteRepo = new SiteRepository(db);
26
- const snapshotRepo = new SnapshotRepository(db);
27
- const pageRepo = new PageRepository(db);
28
- const edgeRepo = new EdgeRepository(db);
29
- const metricsRepo = new MetricsRepository(db);
30
- const rootUrl = normalizeUrl(startUrl, '', { stripQuery: options.stripQuery });
31
- if (!rootUrl)
32
- throw new Error('Invalid start URL');
33
- const urlObj = new URL(rootUrl);
34
- const domain = urlObj.hostname.replace('www.', '');
35
- const site = siteRepo.firstOrCreateSite(domain);
36
- const siteId = site.id;
37
- const snapshotId = snapshotRepo.createSnapshot(siteId, options.previousGraph ? 'incremental' : 'full');
38
- const rootOrigin = urlObj.origin;
39
- // DB Helper
40
- const savePageToDb = (url, depth, status, data = {}) => {
41
- try {
42
- const existing = pageRepo.getPage(siteId, url);
43
- const isSameSnapshot = existing?.last_seen_snapshot_id === snapshotId;
44
- return pageRepo.upsertAndGetId({
45
- site_id: siteId,
46
- normalized_url: url,
47
- depth: isSameSnapshot ? existing.depth : depth,
48
- http_status: status,
49
- first_seen_snapshot_id: existing ? existing.first_seen_snapshot_id : snapshotId,
50
- last_seen_snapshot_id: snapshotId,
51
- canonical_url: data.canonical !== undefined ? data.canonical : existing?.canonical_url,
52
- content_hash: data.contentHash !== undefined ? data.contentHash : existing?.content_hash,
53
- simhash: data.simhash !== undefined ? data.simhash : existing?.simhash,
54
- etag: data.etag !== undefined ? data.etag : existing?.etag,
55
- last_modified: data.lastModified !== undefined ? data.lastModified : existing?.last_modified,
56
- html: data.html !== undefined ? data.html : existing?.html,
57
- soft404_score: data.soft404Score !== undefined ? data.soft404Score : existing?.soft404_score,
58
- noindex: data.noindex !== undefined ? (data.noindex ? 1 : 0) : existing?.noindex,
59
- nofollow: data.nofollow !== undefined ? (data.nofollow ? 1 : 0) : existing?.nofollow,
60
- security_error: data.securityError !== undefined ? data.securityError : existing?.security_error,
61
- retries: data.retries !== undefined ? data.retries : existing?.retries
62
- });
63
- }
64
- catch (e) {
65
- console.error(`Failed to save page ${url}:`, e);
66
- return null;
67
- }
68
- };
69
- const saveEdgeToDb = (sourceUrl, targetUrl, weight = 1.0, rel = 'internal') => {
70
- try {
71
- const sourceId = pageRepo.getIdByUrl(siteId, sourceUrl);
72
- const targetId = pageRepo.getIdByUrl(siteId, targetUrl);
73
- if (sourceId && targetId) {
74
- edgeRepo.insertEdge(snapshotId, sourceId, targetId, weight, rel);
75
- }
76
- }
77
- catch (e) {
78
- console.error(`Failed to save edge ${sourceUrl} -> ${targetUrl}:`, e);
79
- }
80
- };
81
- // Initialize Modules
82
- const scopeManager = new ScopeManager({
83
- allowedDomains: options.allowedDomains || [],
84
- deniedDomains: options.deniedDomains || [],
85
- includeSubdomains: options.includeSubdomains || false,
86
- rootUrl: startUrl
87
- });
88
- const fetcher = new Fetcher({
89
- rate: options.rate,
90
- proxyUrl: options.proxyUrl,
91
- scopeManager,
92
- maxRedirects: options.maxRedirects,
93
- userAgent: options.userAgent
94
- });
95
- const parser = new Parser();
96
- const sitemapFetcher = new Sitemap();
97
- // Handle robots.txt
98
- let robots = null;
99
- if (!options.ignoreRobots) {
100
- try {
101
- const robotsUrl = new URL('/robots.txt', rootOrigin).toString();
102
- const res = await request(robotsUrl, {
103
- maxRedirections: 3,
104
- headers: { 'User-Agent': 'crawlith/1.0' },
105
- headersTimeout: 5000,
106
- bodyTimeout: 5000
107
- });
108
- if (res.statusCode >= 200 && res.statusCode < 300) {
109
- const txt = await res.body.text();
110
- robots = robotsParser(robotsUrl, txt);
111
- }
112
- else {
113
- await res.body.dump();
114
- }
115
- }
116
- catch {
117
- console.warn('Failed to fetch robots.txt, proceeding...');
118
- }
119
- }
120
- // Queue Setup
121
- const queue = [];
122
- const uniqueQueue = new Set();
123
- const addToQueue = (u, d) => {
124
- if (scopeManager.isUrlEligible(u) !== 'allowed')
125
- return;
126
- if (!uniqueQueue.has(u)) {
127
- uniqueQueue.add(u);
128
- queue.push({ url: u, depth: d });
129
- }
130
- };
131
- // Seed from Sitemap
132
- if (options.sitemap) {
133
- try {
134
- const sitemapUrl = options.sitemap === 'true' ? new URL('/sitemap.xml', rootOrigin).toString() : options.sitemap;
135
- if (sitemapUrl.startsWith('http')) {
136
- console.log(`Fetching sitemap: ${sitemapUrl}`);
137
- const sitemapUrls = await sitemapFetcher.fetch(sitemapUrl);
138
- for (const u of sitemapUrls) {
139
- const normalized = normalizeUrl(u, '', options);
140
- if (normalized)
141
- addToQueue(normalized, 0);
142
- }
143
- }
144
- }
145
- catch (e) {
146
- console.warn('Sitemap fetch failed', e);
147
- }
148
- }
149
- // Seed from startUrl
150
- addToQueue(rootUrl, 0);
151
- let pagesCrawled = 0;
152
- let active = 0;
153
- let reachedLimit = false;
154
- const maxDepthInCrawl = Math.min(options.depth, 10);
155
- const shouldEnqueue = (url, depth) => {
156
- if (visited.has(url))
157
- return false;
158
- if (uniqueQueue.has(url))
159
- return false;
160
- if (depth > maxDepthInCrawl)
161
- return false;
162
- if (scopeManager.isUrlEligible(url) !== 'allowed')
163
- return false;
164
- if (options.detectTraps) {
165
- const trap = trapDetector.checkTrap(url, depth);
166
- if (trap.risk > 0.8)
167
- return false;
168
- }
169
- return true;
170
- };
171
- return new Promise((resolve) => {
172
- const checkDone = () => {
173
- if (queue.length === 0 && active === 0) {
174
- snapshotRepo.updateSnapshotStatus(snapshotId, 'completed', {
175
- limit_reached: reachedLimit ? 1 : 0
176
- });
177
- resolve(snapshotId);
178
- return true;
179
- }
180
- return false;
181
- };
182
- const next = () => {
183
- if (checkDone())
184
- return;
185
- if (pagesCrawled >= options.limit) {
186
- reachedLimit = true;
187
- if (active === 0) {
188
- snapshotRepo.updateSnapshotStatus(snapshotId, 'completed', {
189
- limit_reached: 1
190
- });
191
- resolve(snapshotId);
192
- }
193
- return;
194
- }
195
- while (queue.length > 0 && active < concurrency && pagesCrawled < options.limit) {
196
- const item = queue.shift();
197
- if (visited.has(item.url))
198
- continue;
199
- if (robots && !robots.isAllowed(item.url, 'crawlith'))
200
- continue;
201
- active++;
202
- pagesCrawled++;
203
- visited.add(item.url);
204
- limitConcurrency(() => processPage(item)).finally(() => {
205
- active--;
206
- next();
207
- });
208
- }
209
- };
210
- const processPage = async (item) => {
211
- const { url, depth } = item;
212
- if (scopeManager.isUrlEligible(url) !== 'allowed') {
213
- savePageToDb(url, depth, 0, { securityError: 'blocked_by_domain_filter' });
214
- return;
215
- }
216
- const existingInDb = pageRepo.getPage(siteId, url);
217
- savePageToDb(url, depth, 0);
218
- try {
219
- const res = await fetcher.fetch(url, {
220
- etag: existingInDb?.etag || undefined,
221
- lastModified: existingInDb?.last_modified || undefined,
222
- maxBytes: options.maxBytes,
223
- crawlDelay: robots ? robots.getCrawlDelay('crawlith') : undefined
224
- });
225
- if (options.debug) {
226
- console.log(`${chalk.gray(`[D:${depth}]`)} ${res.status} ${chalk.blue(url)}`);
227
- }
228
- if (res.status === 304) {
229
- savePageToDb(url, depth, 304);
230
- metricsRepo.insertMetrics({
231
- snapshot_id: snapshotId,
232
- page_id: existingInDb.id,
233
- authority_score: null,
234
- hub_score: null,
235
- pagerank: null,
236
- pagerank_score: null,
237
- link_role: null,
238
- crawl_status: 'cached',
239
- word_count: null,
240
- thin_content_score: null,
241
- external_link_ratio: null,
242
- orphan_score: null,
243
- duplicate_cluster_id: null,
244
- duplicate_type: null,
245
- is_cluster_primary: 0
246
- });
247
- return;
248
- }
249
- const chain = res.redirectChain;
250
- for (const step of chain) {
251
- const source = normalizeUrl(step.url, '', options);
252
- const target = normalizeUrl(step.target, '', options);
253
- if (source && target) {
254
- savePageToDb(source, depth, step.status);
255
- savePageToDb(target, depth, 0);
256
- saveEdgeToDb(source, target);
257
- }
258
- }
259
- const finalUrl = normalizeUrl(res.finalUrl, '', options);
260
- if (!finalUrl)
261
- return;
262
- const isStringStatus = typeof res.status === 'string';
263
- if (isStringStatus || (typeof res.status === 'number' && res.status >= 300)) {
264
- savePageToDb(finalUrl, depth, typeof res.status === 'number' ? res.status : 0, {
265
- securityError: isStringStatus ? res.status : undefined,
266
- retries: res.retries
267
- });
268
- return;
269
- }
270
- if (res.status === 200) {
271
- const contentTypeHeader = res.headers['content-type'];
272
- const contentType = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : (contentTypeHeader || '');
273
- if (!contentType || !contentType.toLowerCase().includes('text/html')) {
274
- savePageToDb(finalUrl, depth, res.status);
275
- return;
276
- }
277
- savePageToDb(finalUrl, depth, res.status);
278
- const parseResult = parser.parse(res.body, finalUrl, res.status);
279
- const pageId = savePageToDb(finalUrl, depth, res.status, {
280
- html: parseResult.html,
281
- canonical: parseResult.canonical || undefined,
282
- noindex: parseResult.noindex,
283
- nofollow: parseResult.nofollow,
284
- contentHash: parseResult.contentHash,
285
- simhash: parseResult.simhash,
286
- soft404Score: parseResult.soft404Score,
287
- etag: res.etag,
288
- lastModified: res.lastModified,
289
- retries: res.retries
290
- });
291
- if (pageId) {
292
- try {
293
- const contentAnalysis = analyzeContent(parseResult.html);
294
- const linkAnalysis = analyzeLinks(parseResult.html, finalUrl, rootOrigin);
295
- const thinScore = calculateThinContentScore(contentAnalysis, 0);
296
- metricsRepo.insertMetrics({
297
- snapshot_id: snapshotId,
298
- page_id: pageId,
299
- authority_score: null,
300
- hub_score: null,
301
- pagerank: null,
302
- pagerank_score: null,
303
- link_role: null,
304
- crawl_status: 'fetched',
305
- word_count: contentAnalysis.wordCount,
306
- thin_content_score: thinScore,
307
- external_link_ratio: linkAnalysis.externalRatio,
308
- orphan_score: null,
309
- duplicate_cluster_id: null,
310
- duplicate_type: null,
311
- is_cluster_primary: 0
312
- });
313
- }
314
- catch (e) {
315
- console.error(`Error calculating per-page metrics for ${finalUrl}:`, e);
316
- }
317
- }
318
- for (const linkItem of parseResult.links) {
319
- const normalizedLink = normalizeUrl(linkItem.url, '', options);
320
- if (normalizedLink && normalizedLink !== finalUrl) {
321
- savePageToDb(normalizedLink, depth + 1, 0);
322
- saveEdgeToDb(finalUrl, normalizedLink, 1.0, 'internal');
323
- if (shouldEnqueue(normalizedLink, depth + 1)) {
324
- addToQueue(normalizedLink, depth + 1);
325
- }
326
- }
327
- }
328
- }
329
- }
330
- catch (e) {
331
- console.error(`Error processing ${url}:`, e);
332
- }
333
- };
334
- next();
335
- });
1
+ import { Crawler } from './crawler.js';
2
+ export async function crawl(startUrl, options, context) {
3
+ const crawler = new Crawler(startUrl, options, context);
4
+ return crawler.run();
336
5
  }
@@ -0,0 +1,75 @@
1
+ import { Graph } from '../graph/graph.js';
2
+ import { EngineContext } from '../events.js';
3
+ export interface CrawlOptions {
4
+ limit: number;
5
+ depth: number;
6
+ concurrency?: number;
7
+ ignoreRobots?: boolean;
8
+ stripQuery?: boolean;
9
+ previousGraph?: Graph;
10
+ sitemap?: string;
11
+ debug?: boolean;
12
+ detectSoft404?: boolean;
13
+ detectTraps?: boolean;
14
+ rate?: number;
15
+ maxBytes?: number;
16
+ allowedDomains?: string[];
17
+ deniedDomains?: string[];
18
+ includeSubdomains?: boolean;
19
+ proxyUrl?: string;
20
+ maxRedirects?: number;
21
+ userAgent?: string;
22
+ snapshotType?: 'full' | 'partial' | 'incremental';
23
+ }
24
+ export declare class Crawler {
25
+ private startUrl;
26
+ private options;
27
+ private context;
28
+ private visited;
29
+ private uniqueQueue;
30
+ private queue;
31
+ private active;
32
+ private pagesCrawled;
33
+ private reachedLimit;
34
+ private maxDepthInCrawl;
35
+ private concurrency;
36
+ private limitConcurrency;
37
+ private siteRepo;
38
+ private snapshotRepo;
39
+ private pageRepo;
40
+ private edgeRepo;
41
+ private metricsRepo;
42
+ private siteId;
43
+ private snapshotId;
44
+ private rootOrigin;
45
+ private discoveryDepths;
46
+ private pageBuffer;
47
+ private edgeBuffer;
48
+ private metricsBuffer;
49
+ private scopeManager;
50
+ private fetcher;
51
+ private parser;
52
+ private sitemapFetcher;
53
+ private trapDetector;
54
+ private robots;
55
+ constructor(startUrl: string, options: CrawlOptions, context?: EngineContext);
56
+ initialize(): Promise<void>;
57
+ setupModules(): void;
58
+ fetchRobots(): Promise<void>;
59
+ shouldEnqueue(url: string, depth: number): boolean;
60
+ addToQueue(u: string, d: number): void;
61
+ seedQueue(): Promise<void>;
62
+ private bufferPage;
63
+ private flushPages;
64
+ private bufferEdge;
65
+ private flushEdges;
66
+ private bufferMetrics;
67
+ private flushMetrics;
68
+ flushAll(): Promise<void>;
69
+ private fetchPage;
70
+ private handleCachedResponse;
71
+ private handleRedirects;
72
+ private handleSuccessResponse;
73
+ private processPage;
74
+ run(): Promise<number>;
75
+ }