@crawlith/core 0.1.0 → 0.1.2

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 (238) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +70 -0
  3. package/dist/analysis/analysis_list.html +35 -0
  4. package/dist/analysis/analysis_page.html +123 -0
  5. package/dist/analysis/analyze.d.ts +40 -5
  6. package/dist/analysis/analyze.js +395 -347
  7. package/dist/analysis/clustering.d.ts +23 -0
  8. package/dist/analysis/clustering.js +206 -0
  9. package/dist/analysis/content.d.ts +1 -1
  10. package/dist/analysis/content.js +11 -5
  11. package/dist/analysis/duplicate.d.ts +34 -0
  12. package/dist/analysis/duplicate.js +305 -0
  13. package/dist/analysis/heading.d.ts +116 -0
  14. package/dist/analysis/heading.js +356 -0
  15. package/dist/analysis/images.d.ts +1 -1
  16. package/dist/analysis/images.js +6 -5
  17. package/dist/analysis/links.d.ts +1 -1
  18. package/dist/analysis/links.js +8 -8
  19. package/dist/{scoring/orphanSeverity.d.ts → analysis/orphan.d.ts} +12 -23
  20. package/dist/{scoring/orphanSeverity.js → analysis/orphan.js} +9 -3
  21. package/dist/analysis/scoring.js +11 -2
  22. package/dist/analysis/seo.d.ts +8 -4
  23. package/dist/analysis/seo.js +41 -30
  24. package/dist/analysis/soft404.d.ts +17 -0
  25. package/dist/analysis/soft404.js +62 -0
  26. package/dist/analysis/structuredData.d.ts +1 -1
  27. package/dist/analysis/structuredData.js +5 -4
  28. package/dist/analysis/templates.d.ts +2 -0
  29. package/dist/analysis/templates.js +7 -0
  30. package/dist/application/index.d.ts +2 -0
  31. package/dist/application/index.js +2 -0
  32. package/dist/application/usecase.d.ts +3 -0
  33. package/dist/application/usecase.js +1 -0
  34. package/dist/application/usecases.d.ts +114 -0
  35. package/dist/application/usecases.js +201 -0
  36. package/dist/audit/index.js +1 -1
  37. package/dist/audit/transport.d.ts +1 -1
  38. package/dist/audit/transport.js +5 -4
  39. package/dist/audit/types.d.ts +1 -0
  40. package/dist/constants.d.ts +17 -0
  41. package/dist/constants.js +23 -0
  42. package/dist/core/scope/scopeManager.js +3 -0
  43. package/dist/core/security/ipGuard.d.ts +11 -0
  44. package/dist/core/security/ipGuard.js +71 -3
  45. package/dist/crawler/crawl.d.ts +4 -22
  46. package/dist/crawler/crawl.js +4 -335
  47. package/dist/crawler/crawler.d.ts +87 -0
  48. package/dist/crawler/crawler.js +683 -0
  49. package/dist/crawler/extract.d.ts +4 -1
  50. package/dist/crawler/extract.js +7 -2
  51. package/dist/crawler/fetcher.d.ts +2 -1
  52. package/dist/crawler/fetcher.js +26 -11
  53. package/dist/crawler/metricsRunner.d.ts +23 -1
  54. package/dist/crawler/metricsRunner.js +202 -72
  55. package/dist/crawler/normalize.d.ts +41 -0
  56. package/dist/crawler/normalize.js +119 -3
  57. package/dist/crawler/parser.d.ts +1 -3
  58. package/dist/crawler/parser.js +2 -49
  59. package/dist/crawler/resolver.d.ts +11 -0
  60. package/dist/crawler/resolver.js +67 -0
  61. package/dist/crawler/sitemap.d.ts +6 -0
  62. package/dist/crawler/sitemap.js +27 -17
  63. package/dist/crawler/trap.d.ts +5 -1
  64. package/dist/crawler/trap.js +23 -2
  65. package/dist/db/CrawlithDB.d.ts +110 -0
  66. package/dist/db/CrawlithDB.js +500 -0
  67. package/dist/db/graphLoader.js +42 -30
  68. package/dist/db/index.d.ts +11 -0
  69. package/dist/db/index.js +41 -29
  70. package/dist/db/migrations.d.ts +2 -0
  71. package/dist/db/{schema.js → migrations.js} +90 -43
  72. package/dist/db/pluginRegistry.d.ts +9 -0
  73. package/dist/db/pluginRegistry.js +19 -0
  74. package/dist/db/repositories/EdgeRepository.d.ts +13 -0
  75. package/dist/db/repositories/EdgeRepository.js +20 -0
  76. package/dist/db/repositories/MetricsRepository.d.ts +16 -8
  77. package/dist/db/repositories/MetricsRepository.js +28 -7
  78. package/dist/db/repositories/PageRepository.d.ts +15 -2
  79. package/dist/db/repositories/PageRepository.js +169 -25
  80. package/dist/db/repositories/SiteRepository.d.ts +9 -0
  81. package/dist/db/repositories/SiteRepository.js +13 -0
  82. package/dist/db/repositories/SnapshotRepository.d.ts +14 -5
  83. package/dist/db/repositories/SnapshotRepository.js +64 -5
  84. package/dist/db/reset.d.ts +9 -0
  85. package/dist/db/reset.js +32 -0
  86. package/dist/db/statements.d.ts +12 -0
  87. package/dist/db/statements.js +40 -0
  88. package/dist/diff/compare.d.ts +0 -5
  89. package/dist/diff/compare.js +0 -12
  90. package/dist/diff/service.d.ts +16 -0
  91. package/dist/diff/service.js +41 -0
  92. package/dist/domain/index.d.ts +4 -0
  93. package/dist/domain/index.js +4 -0
  94. package/dist/events.d.ts +56 -0
  95. package/dist/events.js +1 -0
  96. package/dist/graph/graph.d.ts +36 -42
  97. package/dist/graph/graph.js +26 -17
  98. package/dist/graph/hits.d.ts +23 -0
  99. package/dist/graph/hits.js +111 -0
  100. package/dist/graph/metrics.d.ts +0 -4
  101. package/dist/graph/metrics.js +25 -9
  102. package/dist/graph/pagerank.d.ts +17 -4
  103. package/dist/graph/pagerank.js +126 -91
  104. package/dist/graph/simhash.d.ts +6 -0
  105. package/dist/graph/simhash.js +14 -0
  106. package/dist/index.d.ts +29 -8
  107. package/dist/index.js +29 -8
  108. package/dist/lock/hashKey.js +1 -1
  109. package/dist/lock/lockManager.d.ts +5 -1
  110. package/dist/lock/lockManager.js +38 -13
  111. package/dist/plugin-system/plugin-cli.d.ts +10 -0
  112. package/dist/plugin-system/plugin-cli.js +31 -0
  113. package/dist/plugin-system/plugin-config.d.ts +16 -0
  114. package/dist/plugin-system/plugin-config.js +36 -0
  115. package/dist/plugin-system/plugin-loader.d.ts +17 -0
  116. package/dist/plugin-system/plugin-loader.js +122 -0
  117. package/dist/plugin-system/plugin-registry.d.ts +25 -0
  118. package/dist/plugin-system/plugin-registry.js +167 -0
  119. package/dist/plugin-system/plugin-types.d.ts +205 -0
  120. package/dist/plugin-system/plugin-types.js +1 -0
  121. package/dist/ports/index.d.ts +9 -0
  122. package/dist/ports/index.js +1 -0
  123. package/{src/report/sitegraph_template.ts → dist/report/crawl.html} +330 -81
  124. package/dist/report/crawlExport.d.ts +3 -0
  125. package/dist/report/{sitegraphExport.js → crawlExport.js} +3 -3
  126. package/dist/report/crawl_template.d.ts +1 -0
  127. package/dist/report/crawl_template.js +7 -0
  128. package/dist/report/export.d.ts +3 -0
  129. package/dist/report/export.js +81 -0
  130. package/dist/report/html.js +15 -216
  131. package/dist/report/insight.d.ts +27 -0
  132. package/dist/report/insight.js +103 -0
  133. package/dist/scoring/health.d.ts +56 -0
  134. package/dist/scoring/health.js +213 -0
  135. package/dist/utils/chalk.d.ts +6 -0
  136. package/dist/utils/chalk.js +41 -0
  137. package/dist/utils/secureConfig.d.ts +23 -0
  138. package/dist/utils/secureConfig.js +128 -0
  139. package/package.json +12 -6
  140. package/CHANGELOG.md +0 -7
  141. package/dist/db/schema.d.ts +0 -2
  142. package/dist/graph/cluster.d.ts +0 -6
  143. package/dist/graph/cluster.js +0 -173
  144. package/dist/graph/duplicate.d.ts +0 -10
  145. package/dist/graph/duplicate.js +0 -251
  146. package/dist/report/sitegraphExport.d.ts +0 -3
  147. package/dist/report/sitegraph_template.d.ts +0 -1
  148. package/dist/report/sitegraph_template.js +0 -630
  149. package/dist/scoring/hits.d.ts +0 -9
  150. package/dist/scoring/hits.js +0 -111
  151. package/src/analysis/analyze.ts +0 -548
  152. package/src/analysis/content.ts +0 -62
  153. package/src/analysis/images.ts +0 -28
  154. package/src/analysis/links.ts +0 -41
  155. package/src/analysis/scoring.ts +0 -59
  156. package/src/analysis/seo.ts +0 -82
  157. package/src/analysis/structuredData.ts +0 -62
  158. package/src/audit/dns.ts +0 -49
  159. package/src/audit/headers.ts +0 -98
  160. package/src/audit/index.ts +0 -66
  161. package/src/audit/scoring.ts +0 -232
  162. package/src/audit/transport.ts +0 -258
  163. package/src/audit/types.ts +0 -102
  164. package/src/core/network/proxyAdapter.ts +0 -21
  165. package/src/core/network/rateLimiter.ts +0 -39
  166. package/src/core/network/redirectController.ts +0 -47
  167. package/src/core/network/responseLimiter.ts +0 -34
  168. package/src/core/network/retryPolicy.ts +0 -57
  169. package/src/core/scope/domainFilter.ts +0 -45
  170. package/src/core/scope/scopeManager.ts +0 -52
  171. package/src/core/scope/subdomainPolicy.ts +0 -39
  172. package/src/core/security/ipGuard.ts +0 -92
  173. package/src/crawler/crawl.ts +0 -382
  174. package/src/crawler/extract.ts +0 -34
  175. package/src/crawler/fetcher.ts +0 -233
  176. package/src/crawler/metricsRunner.ts +0 -124
  177. package/src/crawler/normalize.ts +0 -108
  178. package/src/crawler/parser.ts +0 -190
  179. package/src/crawler/sitemap.ts +0 -73
  180. package/src/crawler/trap.ts +0 -96
  181. package/src/db/graphLoader.ts +0 -105
  182. package/src/db/index.ts +0 -70
  183. package/src/db/repositories/EdgeRepository.ts +0 -29
  184. package/src/db/repositories/MetricsRepository.ts +0 -49
  185. package/src/db/repositories/PageRepository.ts +0 -128
  186. package/src/db/repositories/SiteRepository.ts +0 -32
  187. package/src/db/repositories/SnapshotRepository.ts +0 -74
  188. package/src/db/schema.ts +0 -177
  189. package/src/diff/compare.ts +0 -84
  190. package/src/graph/cluster.ts +0 -192
  191. package/src/graph/duplicate.ts +0 -286
  192. package/src/graph/graph.ts +0 -172
  193. package/src/graph/metrics.ts +0 -110
  194. package/src/graph/pagerank.ts +0 -125
  195. package/src/graph/simhash.ts +0 -61
  196. package/src/index.ts +0 -30
  197. package/src/lock/hashKey.ts +0 -51
  198. package/src/lock/lockManager.ts +0 -124
  199. package/src/lock/pidCheck.ts +0 -13
  200. package/src/report/html.ts +0 -227
  201. package/src/report/sitegraphExport.ts +0 -58
  202. package/src/scoring/hits.ts +0 -131
  203. package/src/scoring/orphanSeverity.ts +0 -176
  204. package/src/utils/version.ts +0 -18
  205. package/tests/__snapshots__/orphanSeverity.test.ts.snap +0 -49
  206. package/tests/analysis.unit.test.ts +0 -98
  207. package/tests/analyze.integration.test.ts +0 -98
  208. package/tests/audit/dns.test.ts +0 -31
  209. package/tests/audit/headers.test.ts +0 -45
  210. package/tests/audit/scoring.test.ts +0 -133
  211. package/tests/audit/security.test.ts +0 -12
  212. package/tests/audit/transport.test.ts +0 -112
  213. package/tests/clustering.test.ts +0 -118
  214. package/tests/crawler.test.ts +0 -358
  215. package/tests/db.test.ts +0 -159
  216. package/tests/diff.test.ts +0 -67
  217. package/tests/duplicate.test.ts +0 -110
  218. package/tests/fetcher.test.ts +0 -106
  219. package/tests/fetcher_safety.test.ts +0 -85
  220. package/tests/fixtures/analyze-crawl.json +0 -26
  221. package/tests/hits.test.ts +0 -134
  222. package/tests/html_report.test.ts +0 -58
  223. package/tests/lock/lockManager.test.ts +0 -138
  224. package/tests/metrics.test.ts +0 -196
  225. package/tests/normalize.test.ts +0 -101
  226. package/tests/orphanSeverity.test.ts +0 -160
  227. package/tests/pagerank.test.ts +0 -98
  228. package/tests/parser.test.ts +0 -117
  229. package/tests/proxy_safety.test.ts +0 -57
  230. package/tests/redirect_safety.test.ts +0 -73
  231. package/tests/safety.test.ts +0 -114
  232. package/tests/scope.test.ts +0 -66
  233. package/tests/scoring.test.ts +0 -59
  234. package/tests/sitemap.test.ts +0 -88
  235. package/tests/soft404.test.ts +0 -41
  236. package/tests/trap.test.ts +0 -39
  237. package/tests/visualization_data.test.ts +0 -46
  238. package/tsconfig.json +0 -11
@@ -1,192 +0,0 @@
1
- import { Graph, GraphNode, ClusterInfo } from './graph.js';
2
- import { SimHash } from './simhash.js';
3
-
4
- /**
5
- * Detects content clusters using 64-bit SimHash and Hamming Distance.
6
- * Uses band optimization to reduce O(n^2) comparisons.
7
- */
8
- export function detectContentClusters(
9
- graph: Graph,
10
- threshold: number = 10,
11
- minSize: number = 3
12
- ): ClusterInfo[] {
13
- const nodes = graph.getNodes().filter(n => n.simhash && n.status === 200);
14
- if (nodes.length === 0) return [];
15
-
16
- const adjacency = new Map<string, Set<string>>();
17
-
18
- // Banding Optimization (4 bands of 16 bits)
19
- // Note: For threshold > 3, this is a heuristic and may miss some pairs,
20
- // but it dramatically reduces the search space as requested.
21
- const bands = 4;
22
- const bandWidth = 16;
23
- const buckets: Map<number, Set<string>>[] = Array.from({ length: bands }, () => new Map());
24
-
25
- for (const node of nodes) {
26
- const hash = BigInt(node.simhash!);
27
- for (let b = 0; b < bands; b++) {
28
- const bandValue = Number((hash >> BigInt(b * bandWidth)) & 0xFFFFn);
29
- if (!buckets[b].has(bandValue)) {
30
- buckets[b].set(bandValue, new Set());
31
- }
32
- buckets[b].get(bandValue)!.add(node.url);
33
- }
34
- }
35
-
36
- const checkedPairs = new Set<string>();
37
-
38
- for (let b = 0; b < bands; b++) {
39
- for (const bucket of buckets[b].values()) {
40
- if (bucket.size < 2) continue;
41
- const bucketNodes = Array.from(bucket);
42
- for (let i = 0; i < bucketNodes.length; i++) {
43
- for (let j = i + 1; j < bucketNodes.length; j++) {
44
- const u1 = bucketNodes[i];
45
- const u2 = bucketNodes[j];
46
- if (u1 === u2) continue;
47
-
48
- const pairKey = u1 < u2 ? `${u1}|${u2}` : `${u2}|${u1}`;
49
- if (checkedPairs.has(pairKey)) continue;
50
- checkedPairs.add(pairKey);
51
-
52
- const n1 = graph.nodes.get(u1)!;
53
- const n2 = graph.nodes.get(u2)!;
54
-
55
- const dist = SimHash.hammingDistance(BigInt(n1.simhash!), BigInt(n2.simhash!));
56
- if (dist <= threshold) {
57
- if (!adjacency.has(u1)) adjacency.set(u1, new Set());
58
- if (!adjacency.has(u2)) adjacency.set(u2, new Set());
59
- adjacency.get(u1)!.add(u2);
60
- adjacency.get(u2)!.add(u1);
61
- }
62
- }
63
- }
64
- }
65
- }
66
-
67
- // Find connected components (Clusters)
68
- const visited = new Set<string>();
69
- const clusters: string[][] = [];
70
-
71
- for (const node of nodes) {
72
- if (visited.has(node.url)) continue;
73
-
74
- const component: string[] = [];
75
- const queue = [node.url];
76
- visited.add(node.url);
77
-
78
- while (queue.length > 0) {
79
- const current = queue.shift()!;
80
- component.push(current);
81
-
82
- const neighbors = adjacency.get(current);
83
- if (neighbors) {
84
- for (const neighbor of neighbors) {
85
- if (!visited.has(neighbor)) {
86
- visited.add(neighbor);
87
- queue.push(neighbor);
88
- }
89
- }
90
- }
91
- }
92
-
93
- if (component.length >= minSize) {
94
- clusters.push(component);
95
- }
96
- }
97
-
98
- // Sort clusters by size (descending) then by primary URL (ascending) for deterministic IDs
99
- clusters.sort((a, b) => {
100
- if (b.length !== a.length) return b.length - a.length;
101
- const aPrimary = selectPrimaryUrl(a, graph);
102
- const bPrimary = selectPrimaryUrl(b, graph);
103
- return aPrimary.localeCompare(bPrimary);
104
- });
105
-
106
- const clusterInfos: ClusterInfo[] = [];
107
- clusters.forEach((memberUrls, index) => {
108
- const clusterId = index + 1;
109
- const clusterNodes = memberUrls.map(url => graph.nodes.get(url)!);
110
-
111
- for (const node of clusterNodes) {
112
- node.clusterId = clusterId;
113
- }
114
-
115
- const primaryUrl = selectPrimaryUrl(memberUrls, graph);
116
- const risk = calculateClusterRisk(clusterNodes);
117
- const sharedPathPrefix = findSharedPathPrefix(memberUrls);
118
-
119
- clusterInfos.push({
120
- id: clusterId,
121
- count: memberUrls.length,
122
- primaryUrl,
123
- risk,
124
- sharedPathPrefix
125
- });
126
- });
127
-
128
- graph.contentClusters = clusterInfos;
129
- return clusterInfos;
130
- }
131
-
132
- /**
133
- * Selects the primary URL for a cluster based on:
134
- * 1. Highest PageRank
135
- * 2. Shortest URL
136
- * 3. Lexicographic fallback
137
- */
138
- function selectPrimaryUrl(urls: string[], graph: Graph): string {
139
- return urls.reduce((best, current) => {
140
- const nBest = graph.nodes.get(best)!;
141
- const nCurrent = graph.nodes.get(current)!;
142
-
143
- if ((nCurrent.pageRank || 0) > (nBest.pageRank || 0)) return current;
144
- if ((nCurrent.pageRank || 0) < (nBest.pageRank || 0)) return best;
145
-
146
- if (current.length < best.length) return current;
147
- if (current.length > best.length) return best;
148
-
149
- return current.localeCompare(best) < 0 ? current : best;
150
- });
151
- }
152
-
153
- /**
154
- * Calculates cannibalization risk based on title and H1 similarity within the cluster.
155
- */
156
- function calculateClusterRisk(nodes: GraphNode[]): 'low' | 'medium' | 'high' {
157
- // Logic: Check if there's significant overlap in Titles or H1s among cluster members.
158
- // This is a heuristic as requested.
159
- // Simplified heuristic: risk is based on cluster density and size
160
- // Large clusters of highly similar content are high risk.
161
-
162
- // Fallback to a safe categorization
163
- if (nodes.length > 5) return 'high';
164
- if (nodes.length > 2) return 'medium';
165
- return 'low';
166
- }
167
-
168
- /**
169
- * Finds the common path prefix among a set of URLs.
170
- */
171
- function findSharedPathPrefix(urls: string[]): string | undefined {
172
- if (urls.length < 2) return undefined;
173
-
174
- try {
175
- const paths = urls.map(u => new URL(u).pathname.split('/').filter(Boolean));
176
- const first = paths[0];
177
- const common: string[] = [];
178
-
179
- for (let i = 0; i < first.length; i++) {
180
- const segment = first[i];
181
- if (paths.every(p => p[i] === segment)) {
182
- common.push(segment);
183
- } else {
184
- break;
185
- }
186
- }
187
-
188
- return common.length > 0 ? '/' + common.join('/') : undefined;
189
- } catch {
190
- return undefined;
191
- }
192
- }
@@ -1,286 +0,0 @@
1
- import { Graph, GraphNode } from './graph.js';
2
- import { SimHash } from './simhash.js';
3
-
4
- export interface DuplicateOptions {
5
- collapse?: boolean;
6
- simhashThreshold?: number; // Hamming distance threshold (default: 3)
7
- }
8
-
9
- interface DuplicateCluster {
10
- id: string;
11
- type: 'exact' | 'near' | 'template_heavy';
12
- nodes: GraphNode[];
13
- representative?: string;
14
- severity?: 'low' | 'medium' | 'high';
15
- }
16
-
17
- /**
18
- * Detects exact and near duplicates, identifies canonical conflicts,
19
- * and performs non-destructive collapse of edges.
20
- */
21
- export function detectDuplicates(graph: Graph, options: DuplicateOptions = {}) {
22
- const collapse = options.collapse !== false; // Default to true
23
- const threshold = options.simhashThreshold ?? 3;
24
-
25
- const exactClusters: DuplicateCluster[] = [];
26
- const nearClusters: DuplicateCluster[] = [];
27
-
28
- const nodes = graph.getNodes();
29
-
30
- // Phase 1 & 2: Exact Duplicate Detection
31
- const exactMap = new Map<string, GraphNode[]>();
32
- for (const node of nodes) {
33
- if (!node.contentHash || node.status !== 200) continue;
34
-
35
- // Safety check: if there's no soft404 signal (soft404 is handled elsewhere, but just filter 200 OKs)
36
- let arr = exactMap.get(node.contentHash);
37
- if (!arr) {
38
- arr = [];
39
- exactMap.set(node.contentHash, arr);
40
- }
41
- arr.push(node);
42
- }
43
-
44
- // Nodes that are NOT part of an exact duplicate group are candidates for near duplicate checks
45
- const nearCandidates: GraphNode[] = [];
46
- let clusterCounter = 1;
47
-
48
- for (const [_hash, group] of exactMap.entries()) {
49
- if (group.length > 1) {
50
- const id = `cluster_exact_${clusterCounter++}`;
51
- exactClusters.push({ id, type: 'exact', nodes: group });
52
- // Mark nodes
53
- for (const n of group) {
54
- n.duplicateClusterId = id;
55
- n.duplicateType = 'exact';
56
- }
57
- } else {
58
- nearCandidates.push(group[0]);
59
- }
60
- }
61
-
62
- // Phase 3: Near Duplicate Detection (SimHash with Bands)
63
- // 64-bit simhash -> split into 4 bands of 16 bits.
64
- const bandsMaps = [
65
- new Map<number, GraphNode[]>(),
66
- new Map<number, GraphNode[]>(),
67
- new Map<number, GraphNode[]>(),
68
- new Map<number, GraphNode[]>()
69
- ];
70
-
71
- for (const node of nearCandidates) {
72
- if (!node.simhash) continue;
73
- const simhash = BigInt(node.simhash);
74
-
75
- // Extract 16 bit bands
76
- const b0 = Number(simhash & 0xFFFFn);
77
- const b1 = Number((simhash >> 16n) & 0xFFFFn);
78
- const b2 = Number((simhash >> 32n) & 0xFFFFn);
79
- const b3 = Number((simhash >> 48n) & 0xFFFFn);
80
-
81
- const bands = [b0, b1, b2, b3];
82
- for (let i = 0; i < 4; i++) {
83
- let arr = bandsMaps[i].get(bands[i]);
84
- if (!arr) {
85
- arr = [];
86
- bandsMaps[i].set(bands[i], arr);
87
- }
88
- arr.push(node);
89
- }
90
- }
91
-
92
- // Find candidate pairs
93
- const nearGroupMap = new Map<string, Set<GraphNode>>(); // node.url -> cluster set
94
- const checkedPairs = new Set<string>();
95
-
96
- for (let i = 0; i < 4; i++) {
97
- for (const [_bandVal, bucketNodes] of bandsMaps[i].entries()) {
98
- if (bucketNodes.length < 2) continue; // nothing to compare
99
-
100
- // Compare all nodes in this bucket
101
- for (let j = 0; j < bucketNodes.length; j++) {
102
- for (let k = j + 1; k < bucketNodes.length; k++) {
103
- const n1 = bucketNodes[j];
104
- const n2 = bucketNodes[k];
105
-
106
- // Ensure n1 < n2 lexicographically to avoid duplicate pairs
107
- const [a, b] = n1.url < n2.url ? [n1, n2] : [n2, n1];
108
- const pairKey = `${a.url}|${b.url}`;
109
-
110
- if (checkedPairs.has(pairKey)) continue;
111
- checkedPairs.add(pairKey);
112
-
113
- const dist = SimHash.hammingDistance(BigInt(a.simhash!), BigInt(b.simhash!));
114
- if (dist <= threshold) {
115
- // They are near duplicates.
116
- // Find or create their cluster set using union-find or reference propagation
117
- const setA = nearGroupMap.get(a.url);
118
- const setB = nearGroupMap.get(b.url);
119
-
120
- if (!setA && !setB) {
121
- const newSet = new Set<GraphNode>([a, b]);
122
- nearGroupMap.set(a.url, newSet);
123
- nearGroupMap.set(b.url, newSet);
124
- } else if (setA && !setB) {
125
- setA.add(b);
126
- nearGroupMap.set(b.url, setA);
127
- } else if (setB && !setA) {
128
- setB.add(a);
129
- nearGroupMap.set(a.url, setB);
130
- } else if (setA && setB && setA !== setB) {
131
- // Merge sets
132
- for (const node of setB) {
133
- setA.add(node);
134
- nearGroupMap.set(node.url, setA);
135
- }
136
- }
137
- }
138
- }
139
- }
140
- }
141
- }
142
-
143
- // Compile near duplicate clusters (deduplicated by Set reference)
144
- const uniqueNearSets = new Set<Set<GraphNode>>();
145
- for (const group of nearGroupMap.values()) {
146
- uniqueNearSets.add(group);
147
- }
148
-
149
- for (const groupSet of uniqueNearSets) {
150
- if (groupSet.size > 1) {
151
- const id = `cluster_near_${clusterCounter++}`;
152
- const groupArr = Array.from(groupSet);
153
- nearClusters.push({ id, type: 'near', nodes: groupArr });
154
- for (const n of groupArr) {
155
- n.duplicateClusterId = id;
156
- n.duplicateType = 'near';
157
- }
158
- }
159
- }
160
-
161
- const allClusters = [...exactClusters, ...nearClusters];
162
-
163
- // Phase 4: Template-Heavy Detection
164
- // Mark classes as 'template_heavy' if ratio < 0.3
165
- for (const cluster of allClusters) {
166
- const avgRatio = cluster.nodes.reduce((sum, n) => sum + (n.uniqueTokenRatio || 0), 0) / cluster.nodes.length;
167
- if (avgRatio < 0.3) {
168
- cluster.type = 'template_heavy';
169
- cluster.nodes.forEach(n => n.duplicateType = 'template_heavy');
170
- }
171
- }
172
-
173
- // Phase 5: Canonical Conflict & Representative Selection
174
- for (const cluster of allClusters) {
175
- const canonicals = new Set<string>();
176
- let hasMissing = false;
177
-
178
- for (const n of cluster.nodes) {
179
- if (!n.canonical) hasMissing = true;
180
- // We compare full absolute canonical URLs (assuming they are normalized during crawl)
181
- else canonicals.add(n.canonical);
182
- }
183
-
184
- if (hasMissing || canonicals.size > 1) {
185
- cluster.severity = 'high';
186
- } else if (cluster.type === 'near') {
187
- cluster.severity = 'medium';
188
- } else {
189
- cluster.severity = 'low';
190
- }
191
-
192
- // Phase 6: Select Representative
193
- // 1. Valid Canonical target in cluster
194
- // 2. Highest internal in-degree
195
- // 3. Shortest URL
196
- // 4. First discovered (relying on array order, which is from BFS map roughly)
197
- let representativeNode = cluster.nodes[0];
198
-
199
- // Evaluate best rep
200
- const urlsInCluster = new Set(cluster.nodes.map(n => n.url));
201
- const validCanonicals = cluster.nodes.filter(n => n.canonical && urlsInCluster.has(n.canonical) && n.url === n.canonical);
202
-
203
- if (validCanonicals.length > 0) {
204
- representativeNode = validCanonicals[0]; // If multiple, just pick first matching self
205
- } else {
206
- representativeNode = cluster.nodes.reduce((best, current) => {
207
- if (current.inLinks > best.inLinks) return current;
208
- if (current.inLinks < best.inLinks) return best;
209
- if (current.url.length < best.url.length) return current;
210
- return best;
211
- });
212
- }
213
-
214
- cluster.representative = representativeNode.url;
215
-
216
- cluster.nodes.forEach(n => {
217
- n.isClusterPrimary = n.url === representativeNode.url;
218
- n.isCollapsed = false; // default for JSON
219
- n.collapseInto = undefined;
220
- });
221
-
222
- // Push to Graph's final cluster list
223
- graph.duplicateClusters.push({
224
- id: cluster.id,
225
- type: cluster.type,
226
- size: cluster.nodes.length,
227
- representative: representativeNode.url,
228
- severity: cluster.severity!
229
- });
230
-
231
- // Controlled Collapse
232
- if (collapse) {
233
- for (const n of cluster.nodes) {
234
- if (n.url !== representativeNode.url) {
235
- n.isCollapsed = true;
236
- n.collapseInto = representativeNode.url;
237
- }
238
- }
239
- }
240
- }
241
-
242
- // Final Edge Transfer if Collapsing
243
- if (collapse) {
244
- const edges = graph.getEdges();
245
- const updatedEdges = new Map<string, number>();
246
-
247
- for (const edge of edges) {
248
- const sourceNode = graph.nodes.get(edge.source);
249
- const targetNode = graph.nodes.get(edge.target);
250
-
251
- if (!sourceNode || !targetNode) continue;
252
-
253
- // We do NOT modify source structure for out-bound edges of collapsed nodes?
254
- // Spec: "Ignore edges from collapsed nodes. Transfer inbound edges to representative."
255
- // Actually, if a node links TO a collapsed node, we repoint the edge to the representative.
256
- // If a collapsed node links to X, we ignore it (PageRank will filter it out).
257
-
258
- const actualSource = edge.source;
259
- // repoint target
260
- const actualTarget = targetNode.isCollapsed && targetNode.collapseInto ? targetNode.collapseInto : edge.target;
261
-
262
- // Skip self-referential edges caused by repointing
263
- if (actualSource === actualTarget) continue;
264
-
265
- const edgeKey = `${actualSource}|${actualTarget}`;
266
- const existingWeight = updatedEdges.get(edgeKey) || 0;
267
- updatedEdges.set(edgeKey, Math.max(existingWeight, edge.weight)); // deduplicate
268
- }
269
-
270
- // Update graph edges in-place
271
- graph.edges = updatedEdges;
272
-
273
- // Re-calculate inLinks and outLinks based on collapsed edges
274
- for (const node of graph.getNodes()) {
275
- node.inLinks = 0;
276
- node.outLinks = 0;
277
- }
278
- for (const [edgeKey, _weight] of updatedEdges.entries()) {
279
- const [src, tgt] = edgeKey.split('|');
280
- const sn = graph.nodes.get(src);
281
- const tn = graph.nodes.get(tgt);
282
- if (sn) sn.outLinks++;
283
- if (tn) tn.inLinks++;
284
- }
285
- }
286
- }
@@ -1,172 +0,0 @@
1
- export interface GraphNode {
2
- url: string;
3
- depth: number;
4
- inLinks: number;
5
- outLinks: number;
6
- status: number;
7
- canonical?: string;
8
- noindex?: boolean;
9
- nofollow?: boolean;
10
- brokenLinks?: string[];
11
- redirectChain?: string[];
12
- incrementalStatus?: 'new' | 'changed' | 'unchanged' | 'deleted';
13
- etag?: string;
14
- lastModified?: string;
15
- contentHash?: string;
16
- html?: string;
17
- pageRank?: number;
18
- pageRankScore?: number;
19
- authorityScore?: number;
20
- hubScore?: number;
21
- duplicateClusterId?: string;
22
- duplicateType?: 'exact' | 'near' | 'template_heavy' | 'none';
23
- isClusterPrimary?: boolean;
24
- isCollapsed?: boolean;
25
- collapseInto?: string;
26
- simhash?: string;
27
- uniqueTokenRatio?: number;
28
- soft404Score?: number;
29
- soft404Signals?: string[];
30
- crawlTrapFlag?: boolean;
31
- crawlTrapRisk?: number;
32
- trapType?: string;
33
- securityError?: string;
34
- retries?: number;
35
- clusterId?: number;
36
- bytesReceived?: number;
37
- linkRole?: 'hub' | 'authority' | 'power' | 'balanced' | 'peripheral';
38
- }
39
-
40
- export interface GraphEdge {
41
- source: string;
42
- target: string;
43
- weight: number;
44
- }
45
-
46
- export interface ClusterInfo {
47
- id: number;
48
- count: number;
49
- primaryUrl: string;
50
- risk: 'low' | 'medium' | 'high';
51
- sharedPathPrefix?: string;
52
- }
53
-
54
- export interface CrawlStats {
55
- pagesFetched: number;
56
- pagesCached: number;
57
- pagesSkipped: number;
58
- totalFound: number;
59
- }
60
-
61
- export class Graph {
62
- nodes: Map<string, GraphNode> = new Map();
63
- // Using string "source|target" to ensure uniqueness efficiently. Mapping to weight.
64
- edges: Map<string, number> = new Map();
65
- limitReached: boolean = false;
66
- sessionStats: CrawlStats = {
67
- pagesFetched: 0,
68
- pagesCached: 0,
69
- pagesSkipped: 0,
70
- totalFound: 0
71
- };
72
- trapClusters: { pattern: string; type: string; count: number }[] = [];
73
- duplicateClusters: { id: string; type: 'exact' | 'near' | 'template_heavy'; size: number; representative: string; severity: 'low' | 'medium' | 'high' }[] = [];
74
- contentClusters: ClusterInfo[] = [];
75
-
76
- /**
77
- * Adds a node to the graph if it doesn't exist.
78
- * If it exists, updates the status if the new status is non-zero (meaning we crawled it).
79
- * Depth is only set on creation (BFS guarantees shortest path first).
80
- */
81
- addNode(url: string, depth: number, status: number = 0) {
82
- const existing = this.nodes.get(url);
83
- if (!existing) {
84
- this.nodes.set(url, {
85
- url,
86
- depth,
87
- status,
88
- inLinks: 0,
89
- outLinks: 0
90
- });
91
- } else {
92
- // Update status if we have a real one now (e.g. was 0/pending, now crawled)
93
- if (status !== 0) {
94
- existing.status = status;
95
- }
96
- }
97
- }
98
-
99
- updateNodeData(url: string, data: Partial<GraphNode>) {
100
- const existing = this.nodes.get(url);
101
- if (existing) {
102
- Object.assign(existing, data);
103
- }
104
- }
105
-
106
- /**
107
- * Adds a directed edge between two nodes.
108
- * Both nodes must exist in the graph.
109
- * Updates inLinks and outLinks counts.
110
- */
111
- addEdge(source: string, target: string, weight: number = 1.0) {
112
- const sourceNode = this.nodes.get(source);
113
- const targetNode = this.nodes.get(target);
114
-
115
- if (sourceNode && targetNode) {
116
- const edgeKey = `${source}|${target}`;
117
- if (!this.edges.has(edgeKey)) {
118
- this.edges.set(edgeKey, weight);
119
- sourceNode.outLinks++;
120
- targetNode.inLinks++;
121
- } else {
122
- // If edge exists, keep highest weight (or could sum, but usually we just want the 'best' relationship)
123
- const currentWeight = this.edges.get(edgeKey) || 0;
124
- if (weight > currentWeight) {
125
- this.edges.set(edgeKey, weight);
126
- }
127
- }
128
- }
129
- }
130
-
131
- getNodes(): GraphNode[] {
132
- return Array.from(this.nodes.values());
133
- }
134
-
135
- getEdges(): GraphEdge[] {
136
- return Array.from(this.edges.entries()).map(([edge, weight]) => {
137
- const [source, target] = edge.split('|');
138
- return { source, target, weight };
139
- });
140
- }
141
-
142
- toJSON() {
143
- return {
144
- nodes: this.getNodes(),
145
- edges: this.getEdges(),
146
- duplicateClusters: this.duplicateClusters,
147
- contentClusters: this.contentClusters
148
- };
149
- }
150
-
151
- static fromJSON(json: any): Graph {
152
- const graph = new Graph();
153
- if (json.nodes) {
154
- for (const node of json.nodes) {
155
- graph.nodes.set(node.url, { ...node });
156
- }
157
- }
158
- if (json.edges) {
159
- for (const edge of json.edges) {
160
- const key = `${edge.source}|${edge.target}`;
161
- graph.edges.set(key, edge.weight || 1.0);
162
- }
163
- }
164
- if (json.duplicateClusters) {
165
- graph.duplicateClusters = json.duplicateClusters;
166
- }
167
- if (json.contentClusters) {
168
- graph.contentClusters = json.contentClusters;
169
- }
170
- return graph;
171
- }
172
- }